Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobac6f739e5cf9e0474a689b5c8674aa4c4fbe2b16
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite)
266 (const :tag "ebnf2ps" ebnf2ps))
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-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
888 "Matches first line of a hidden block.
889 Group 1 contains drawer's name.")
891 (defconst org-repeat-re
892 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
893 "Regular expression for specifying repeated events.
894 After a match, group 1 contains the repeat expression.")
896 (defgroup org-structure nil
897 "Options concerning the general structure of Org-mode files."
898 :tag "Org Structure"
899 :group 'org)
901 (defgroup org-reveal-location nil
902 "Options about how to make context of a location visible."
903 :tag "Org Reveal Location"
904 :group 'org-structure)
906 (defconst org-context-choice
907 '(choice
908 (const :tag "Always" t)
909 (const :tag "Never" nil)
910 (repeat :greedy t :tag "Individual contexts"
911 (cons
912 (choice :tag "Context"
913 (const agenda)
914 (const org-goto)
915 (const occur-tree)
916 (const tags-tree)
917 (const link-search)
918 (const mark-goto)
919 (const bookmark-jump)
920 (const isearch)
921 (const default))
922 (boolean))))
923 "Contexts for the reveal options.")
925 (defcustom org-show-hierarchy-above '((default . t))
926 "Non-nil means show full hierarchy when revealing a location.
927 Org-mode often shows locations in an org-mode file which might have
928 been invisible before. When this is set, the hierarchy of headings
929 above the exposed location is shown.
930 Turning this off for example for sparse trees makes them very compact.
931 Instead of t, this can also be an alist specifying this option for different
932 contexts. Valid contexts are
933 agenda when exposing an entry from the agenda
934 org-goto when using the command `org-goto' on key C-c C-j
935 occur-tree when using the command `org-occur' on key C-c /
936 tags-tree when constructing a sparse tree based on tags matches
937 link-search when exposing search matches associated with a link
938 mark-goto when exposing the jump goal of a mark
939 bookmark-jump when exposing a bookmark location
940 isearch when exiting from an incremental search
941 default default for all contexts not set explicitly"
942 :group 'org-reveal-location
943 :type org-context-choice)
945 (defcustom org-show-following-heading '((default . nil))
946 "Non-nil means show following heading when revealing a location.
947 Org-mode often shows locations in an org-mode file which might have
948 been invisible before. When this is set, the heading following the
949 match is shown.
950 Turning this off for example for sparse trees makes them very compact,
951 but makes it harder to edit the location of the match. In such a case,
952 use the command \\[org-reveal] to show more context.
953 Instead of t, this can also be an alist specifying this option for different
954 contexts. See `org-show-hierarchy-above' for valid contexts."
955 :group 'org-reveal-location
956 :type org-context-choice)
958 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
959 "Non-nil means show all sibling heading when revealing a location.
960 Org-mode often shows locations in an org-mode file which might have
961 been invisible before. When this is set, the sibling of the current entry
962 heading are all made visible. If `org-show-hierarchy-above' is t,
963 the same happens on each level of the hierarchy above the current entry.
965 By default this is on for the isearch context, off for all other contexts.
966 Turning this off for example for sparse trees makes them very compact,
967 but makes it harder to edit the location of the match. In such a case,
968 use the command \\[org-reveal] to show more context.
969 Instead of t, this can also be an alist specifying this option for different
970 contexts. See `org-show-hierarchy-above' for valid contexts."
971 :group 'org-reveal-location
972 :type org-context-choice
973 :version "24.4"
974 :package-version '(Org . "8.0"))
976 (defcustom org-show-entry-below '((default . nil))
977 "Non-nil means show the entry below a headline when revealing a location.
978 Org-mode often shows locations in an org-mode file which might have
979 been invisible before. When this is set, the text below the headline that is
980 exposed is also shown.
982 By default this is off for all contexts.
983 Instead of t, this can also be an alist specifying this option for different
984 contexts. See `org-show-hierarchy-above' for valid contexts."
985 :group 'org-reveal-location
986 :type org-context-choice)
988 (defcustom org-indirect-buffer-display 'other-window
989 "How should indirect tree buffers be displayed?
990 This applies to indirect buffers created with the commands
991 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
992 Valid values are:
993 current-window Display in the current window
994 other-window Just display in another window.
995 dedicated-frame Create one new frame, and re-use it each time.
996 new-frame Make a new frame each time. Note that in this case
997 previously-made indirect buffers are kept, and you need to
998 kill these buffers yourself."
999 :group 'org-structure
1000 :group 'org-agenda-windows
1001 :type '(choice
1002 (const :tag "In current window" current-window)
1003 (const :tag "In current frame, other window" other-window)
1004 (const :tag "Each time a new frame" new-frame)
1005 (const :tag "One dedicated frame" dedicated-frame)))
1007 (defcustom org-use-speed-commands nil
1008 "Non-nil means activate single letter commands at beginning of a headline.
1009 This may also be a function to test for appropriate locations where speed
1010 commands should be active."
1011 :group 'org-structure
1012 :type '(choice
1013 (const :tag "Never" nil)
1014 (const :tag "At beginning of headline stars" t)
1015 (function)))
1017 (defcustom org-speed-commands-user nil
1018 "Alist of additional speed commands.
1019 This list will be checked before `org-speed-commands-default'
1020 when the variable `org-use-speed-commands' is non-nil
1021 and when the cursor is at the beginning of a headline.
1022 The car if each entry is a string with a single letter, which must
1023 be assigned to `self-insert-command' in the global map.
1024 The cdr is either a command to be called interactively, a function
1025 to be called, or a form to be evaluated.
1026 An entry that is just a list with a single string will be interpreted
1027 as a descriptive headline that will be added when listing the speed
1028 commands in the Help buffer using the `?' speed command."
1029 :group 'org-structure
1030 :type '(repeat :value ("k" . ignore)
1031 (choice :value ("k" . ignore)
1032 (list :tag "Descriptive Headline" (string :tag "Headline"))
1033 (cons :tag "Letter and Command"
1034 (string :tag "Command letter")
1035 (choice
1036 (function)
1037 (sexp))))))
1039 (defcustom org-bookmark-names-plist
1040 '(:last-capture "org-capture-last-stored"
1041 :last-refile "org-refile-last-stored"
1042 :last-capture-marker "org-capture-last-stored-marker")
1043 "Names for bookmarks automatically set by some Org commands.
1044 This can provide strings as names for a number of bookmakrs Org sets
1045 automatically. The following keys are currently implemented:
1046 :last-capture
1047 :last-capture-marker
1048 :last-refile
1049 When a key does not show up in the property list, the corresponding bookmark
1050 is not set."
1051 :group 'org-structure
1052 :type 'plist)
1054 (defgroup org-cycle nil
1055 "Options concerning visibility cycling in Org-mode."
1056 :tag "Org Cycle"
1057 :group 'org-structure)
1059 (defcustom org-cycle-skip-children-state-if-no-children t
1060 "Non-nil means skip CHILDREN state in entries that don't have any."
1061 :group 'org-cycle
1062 :type 'boolean)
1064 (defcustom org-cycle-max-level nil
1065 "Maximum level which should still be subject to visibility cycling.
1066 Levels higher than this will, for cycling, be treated as text, not a headline.
1067 When `org-odd-levels-only' is set, a value of N in this variable actually
1068 means 2N-1 stars as the limiting headline.
1069 When nil, cycle all levels.
1070 Note that the limiting level of cycling is also influenced by
1071 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1072 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1073 than its value."
1074 :group 'org-cycle
1075 :type '(choice
1076 (const :tag "No limit" nil)
1077 (integer :tag "Maximum level")))
1079 (defcustom org-hide-block-startup nil
1080 "Non-nil means entering Org-mode will fold all blocks.
1081 This can also be set in on a per-file basis with
1083 #+STARTUP: hideblocks
1084 #+STARTUP: showblocks"
1085 :group 'org-startup
1086 :group 'org-cycle
1087 :type 'boolean)
1089 (defcustom org-cycle-global-at-bob nil
1090 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1091 This makes it possible to do global cycling without having to use S-TAB or
1092 \\[universal-argument] TAB. For this special case to work, the first line
1093 of the buffer must not be a headline -- it may be empty or some other text.
1094 When used in this way, `org-cycle-hook' is disabled temporarily to make
1095 sure the cursor stays at the beginning of the buffer. When this option is
1096 nil, don't do anything special at the beginning of the buffer."
1097 :group 'org-cycle
1098 :type 'boolean)
1100 (defcustom org-cycle-level-after-item/entry-creation t
1101 "Non-nil means cycle entry level or item indentation in new empty entries.
1103 When the cursor is at the end of an empty headline, i.e., with only stars
1104 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1105 and then all possible ancestor states, before returning to the original state.
1106 This makes data entry extremely fast: M-RET to create a new headline,
1107 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1109 When the cursor is at the end of an empty plain list item, one TAB will
1110 make it a subitem, two or more tabs will back up to make this an item
1111 higher up in the item hierarchy."
1112 :group 'org-cycle
1113 :type 'boolean)
1115 (defcustom org-cycle-emulate-tab t
1116 "Where should `org-cycle' emulate TAB.
1117 nil Never
1118 white Only in completely white lines
1119 whitestart Only at the beginning of lines, before the first non-white char
1120 t Everywhere except in headlines
1121 exc-hl-bol Everywhere except at the start of a headline
1122 If TAB is used in a place where it does not emulate TAB, the current subtree
1123 visibility is cycled."
1124 :group 'org-cycle
1125 :type '(choice (const :tag "Never" nil)
1126 (const :tag "Only in completely white lines" white)
1127 (const :tag "Before first char in a line" whitestart)
1128 (const :tag "Everywhere except in headlines" t)
1129 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1131 (defcustom org-cycle-separator-lines 2
1132 "Number of empty lines needed to keep an empty line between collapsed trees.
1133 If you leave an empty line between the end of a subtree and the following
1134 headline, this empty line is hidden when the subtree is folded.
1135 Org-mode will leave (exactly) one empty line visible if the number of
1136 empty lines is equal or larger to the number given in this variable.
1137 So the default 2 means at least 2 empty lines after the end of a subtree
1138 are needed to produce free space between a collapsed subtree and the
1139 following headline.
1141 If the number is negative, and the number of empty lines is at least -N,
1142 all empty lines are shown.
1144 Special case: when 0, never leave empty lines in collapsed view."
1145 :group 'org-cycle
1146 :type 'integer)
1147 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1149 (defcustom org-pre-cycle-hook nil
1150 "Hook that is run before visibility cycling is happening.
1151 The function(s) in this hook must accept a single argument which indicates
1152 the new state that will be set right after running this hook. The
1153 argument is a symbol. Before a global state change, it can have the values
1154 `overview', `content', or `all'. Before a local state change, it can have
1155 the values `folded', `children', or `subtree'."
1156 :group 'org-cycle
1157 :type 'hook)
1159 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1160 org-cycle-hide-drawers
1161 org-cycle-hide-inline-tasks
1162 org-cycle-show-empty-lines
1163 org-optimize-window-after-visibility-change)
1164 "Hook that is run after `org-cycle' has changed the buffer visibility.
1165 The function(s) in this hook must accept a single argument which indicates
1166 the new state that was set by the most recent `org-cycle' command. The
1167 argument is a symbol. After a global state change, it can have the values
1168 `overview', `contents', or `all'. After a local state change, it can have
1169 the values `folded', `children', or `subtree'."
1170 :group 'org-cycle
1171 :type 'hook)
1173 (defgroup org-edit-structure nil
1174 "Options concerning structure editing in Org-mode."
1175 :tag "Org Edit Structure"
1176 :group 'org-structure)
1178 (defcustom org-odd-levels-only nil
1179 "Non-nil means skip even levels and only use odd levels for the outline.
1180 This has the effect that two stars are being added/taken away in
1181 promotion/demotion commands. It also influences how levels are
1182 handled by the exporters.
1183 Changing it requires restart of `font-lock-mode' to become effective
1184 for fontification also in regions already fontified.
1185 You may also set this on a per-file basis by adding one of the following
1186 lines to the buffer:
1188 #+STARTUP: odd
1189 #+STARTUP: oddeven"
1190 :group 'org-edit-structure
1191 :group 'org-appearance
1192 :type 'boolean)
1194 (defcustom org-adapt-indentation t
1195 "Non-nil means adapt indentation to outline node level.
1197 When this variable is set, Org assumes that you write outlines by
1198 indenting text in each node to align with the headline (after the stars).
1199 The following issues are influenced by this variable:
1201 - When this is set and the *entire* text in an entry is indented, the
1202 indentation is increased by one space in a demotion command, and
1203 decreased by one in a promotion command. If any line in the entry
1204 body starts with text at column 0, indentation is not changed at all.
1206 - Property drawers and planning information is inserted indented when
1207 this variable s set. When nil, they will not be indented.
1209 - TAB indents a line relative to context. The lines below a headline
1210 will be indented when this variable is set.
1212 Note that this is all about true indentation, by adding and removing
1213 space characters. See also `org-indent.el' which does level-dependent
1214 indentation in a virtual way, i.e. at display time in Emacs."
1215 :group 'org-edit-structure
1216 :type 'boolean)
1218 (defcustom org-special-ctrl-a/e nil
1219 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1221 When t, `C-a' will bring back the cursor to the beginning of the
1222 headline text, i.e. after the stars and after a possible TODO
1223 keyword. In an item, this will be the position after bullet and
1224 check-box, if any. When the cursor is already at that position,
1225 another `C-a' will bring it to the beginning of the line.
1227 `C-e' will jump to the end of the headline, ignoring the presence
1228 of tags in the headline. A second `C-e' will then jump to the
1229 true end of the line, after any tags. This also means that, when
1230 this variable is non-nil, `C-e' also will never jump beyond the
1231 end of the heading of a folded section, i.e. not after the
1232 ellipses.
1234 When set to the symbol `reversed', the first `C-a' or `C-e' works
1235 normally, going to the true line boundary first. Only a directly
1236 following, identical keypress will bring the cursor to the
1237 special positions.
1239 This may also be a cons cell where the behavior for `C-a' and
1240 `C-e' is set separately."
1241 :group 'org-edit-structure
1242 :type '(choice
1243 (const :tag "off" nil)
1244 (const :tag "on: after stars/bullet and before tags first" t)
1245 (const :tag "reversed: true line boundary first" reversed)
1246 (cons :tag "Set C-a and C-e separately"
1247 (choice :tag "Special C-a"
1248 (const :tag "off" nil)
1249 (const :tag "on: after stars/bullet first" t)
1250 (const :tag "reversed: before stars/bullet first" reversed))
1251 (choice :tag "Special C-e"
1252 (const :tag "off" nil)
1253 (const :tag "on: before tags first" t)
1254 (const :tag "reversed: after tags first" reversed)))))
1255 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1257 (defcustom org-special-ctrl-k nil
1258 "Non-nil means `C-k' will behave specially in headlines.
1259 When nil, `C-k' will call the default `kill-line' command.
1260 When t, the following will happen while the cursor is in the headline:
1262 - When the cursor is at the beginning of a headline, kill the entire
1263 line and possible the folded subtree below the line.
1264 - When in the middle of the headline text, kill the headline up to the tags.
1265 - When after the headline text, kill the tags."
1266 :group 'org-edit-structure
1267 :type 'boolean)
1269 (defcustom org-ctrl-k-protect-subtree nil
1270 "Non-nil means, do not delete a hidden subtree with C-k.
1271 When set to the symbol `error', simply throw an error when C-k is
1272 used to kill (part-of) a headline that has hidden text behind it.
1273 Any other non-nil value will result in a query to the user, if it is
1274 OK to kill that hidden subtree. When nil, kill without remorse."
1275 :group 'org-edit-structure
1276 :version "24.1"
1277 :type '(choice
1278 (const :tag "Do not protect hidden subtrees" nil)
1279 (const :tag "Protect hidden subtrees with a security query" t)
1280 (const :tag "Never kill a hidden subtree with C-k" error)))
1282 (defcustom org-special-ctrl-o t
1283 "Non-nil means, make `C-o' insert a row in tables."
1284 :group 'org-edit-structure
1285 :type 'boolean)
1287 (defcustom org-catch-invisible-edits nil
1288 "Check if in invisible region before inserting or deleting a character.
1289 Valid values are:
1291 nil Do not check, so just do invisible edits.
1292 error Throw an error and do nothing.
1293 show Make point visible, and do the requested edit.
1294 show-and-error Make point visible, then throw an error and abort the edit.
1295 smart Make point visible, and do insertion/deletion if it is
1296 adjacent to visible text and the change feels predictable.
1297 Never delete a previously invisible character or add in the
1298 middle or right after an invisible region. Basically, this
1299 allows insertion and backward-delete right before ellipses.
1300 FIXME: maybe in this case we should not even show?"
1301 :group 'org-edit-structure
1302 :version "24.1"
1303 :type '(choice
1304 (const :tag "Do not check" nil)
1305 (const :tag "Throw error when trying to edit" error)
1306 (const :tag "Unhide, but do not do the edit" show-and-error)
1307 (const :tag "Show invisible part and do the edit" show)
1308 (const :tag "Be smart and do the right thing" smart)))
1310 (defcustom org-yank-folded-subtrees t
1311 "Non-nil means when yanking subtrees, fold them.
1312 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1313 it starts with a heading and all other headings in it are either children
1314 or siblings, then fold all the subtrees. However, do this only if no
1315 text after the yank would be swallowed into a folded tree by this action."
1316 :group 'org-edit-structure
1317 :type 'boolean)
1319 (defcustom org-yank-adjusted-subtrees nil
1320 "Non-nil means when yanking subtrees, adjust the level.
1321 With this setting, `org-paste-subtree' is used to insert the subtree, see
1322 this function for details."
1323 :group 'org-edit-structure
1324 :type 'boolean)
1326 (defcustom org-M-RET-may-split-line '((default . t))
1327 "Non-nil means M-RET will split the line at the cursor position.
1328 When nil, it will go to the end of the line before making a
1329 new line.
1330 You may also set this option in a different way for different
1331 contexts. Valid contexts are:
1333 headline when creating a new headline
1334 item when creating a new item
1335 table in a table field
1336 default the value to be used for all contexts not explicitly
1337 customized"
1338 :group 'org-structure
1339 :group 'org-table
1340 :type '(choice
1341 (const :tag "Always" t)
1342 (const :tag "Never" nil)
1343 (repeat :greedy t :tag "Individual contexts"
1344 (cons
1345 (choice :tag "Context"
1346 (const headline)
1347 (const item)
1348 (const table)
1349 (const default))
1350 (boolean)))))
1353 (defcustom org-insert-heading-respect-content nil
1354 "Non-nil means insert new headings after the current subtree.
1355 When nil, the new heading is created directly after the current line.
1356 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1357 this variable on for the duration of the command."
1358 :group 'org-structure
1359 :type 'boolean)
1361 (defcustom org-blank-before-new-entry '((heading . auto)
1362 (plain-list-item . auto))
1363 "Should `org-insert-heading' leave a blank line before new heading/item?
1364 The value is an alist, with `heading' and `plain-list-item' as CAR,
1365 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1366 which case Org will look at the surrounding headings/items and try to
1367 make an intelligent decision whether to insert a blank line or not.
1369 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1370 the setting here is ignored and no empty line is inserted to avoid breaking
1371 the list structure."
1372 :group 'org-edit-structure
1373 :type '(list
1374 (cons (const heading)
1375 (choice (const :tag "Never" nil)
1376 (const :tag "Always" t)
1377 (const :tag "Auto" auto)))
1378 (cons (const plain-list-item)
1379 (choice (const :tag "Never" nil)
1380 (const :tag "Always" t)
1381 (const :tag "Auto" auto)))))
1383 (defcustom org-insert-heading-hook nil
1384 "Hook being run after inserting a new heading."
1385 :group 'org-edit-structure
1386 :type 'hook)
1388 (defcustom org-enable-fixed-width-editor t
1389 "Non-nil means lines starting with \":\" are treated as fixed-width.
1390 This currently only means they are never auto-wrapped.
1391 When nil, such lines will be treated like ordinary lines.
1392 See also the QUOTE keyword."
1393 :group 'org-edit-structure
1394 :type 'boolean)
1396 (defcustom org-goto-auto-isearch t
1397 "Non-nil means typing characters in `org-goto' starts incremental search.
1398 When nil, you can use these keybindings to navigate the buffer:
1400 q Quit the org-goto interface
1401 n Go to the next visible heading
1402 p Go to the previous visible heading
1403 f Go one heading forward on same level
1404 b Go one heading backward on same level
1405 u Go one heading up"
1406 :group 'org-edit-structure
1407 :type 'boolean)
1409 (defgroup org-sparse-trees nil
1410 "Options concerning sparse trees in Org-mode."
1411 :tag "Org Sparse Trees"
1412 :group 'org-structure)
1414 (defcustom org-highlight-sparse-tree-matches t
1415 "Non-nil means highlight all matches that define a sparse tree.
1416 The highlights will automatically disappear the next time the buffer is
1417 changed by an edit command."
1418 :group 'org-sparse-trees
1419 :type 'boolean)
1421 (defcustom org-remove-highlights-with-change t
1422 "Non-nil means any change to the buffer will remove temporary highlights.
1423 Such highlights are created by `org-occur' and `org-clock-display'.
1424 When nil, `C-c C-c needs to be used to get rid of the highlights.
1425 The highlights created by `org-preview-latex-fragment' always need
1426 `C-c C-c' to be removed."
1427 :group 'org-sparse-trees
1428 :group 'org-time
1429 :type 'boolean)
1432 (defcustom org-occur-hook '(org-first-headline-recenter)
1433 "Hook that is run after `org-occur' has constructed a sparse tree.
1434 This can be used to recenter the window to show as much of the structure
1435 as possible."
1436 :group 'org-sparse-trees
1437 :type 'hook)
1439 (defgroup org-imenu-and-speedbar nil
1440 "Options concerning imenu and speedbar in Org-mode."
1441 :tag "Org Imenu and Speedbar"
1442 :group 'org-structure)
1444 (defcustom org-imenu-depth 2
1445 "The maximum level for Imenu access to Org-mode headlines.
1446 This also applied for speedbar access."
1447 :group 'org-imenu-and-speedbar
1448 :type 'integer)
1450 (defgroup org-table nil
1451 "Options concerning tables in Org-mode."
1452 :tag "Org Table"
1453 :group 'org)
1455 (defcustom org-enable-table-editor 'optimized
1456 "Non-nil means lines starting with \"|\" are handled by the table editor.
1457 When nil, such lines will be treated like ordinary lines.
1459 When equal to the symbol `optimized', the table editor will be optimized to
1460 do the following:
1461 - Automatic overwrite mode in front of whitespace in table fields.
1462 This makes the structure of the table stay in tact as long as the edited
1463 field does not exceed the column width.
1464 - Minimize the number of realigns. Normally, the table is aligned each time
1465 TAB or RET are pressed to move to another field. With optimization this
1466 happens only if changes to a field might have changed the column width.
1467 Optimization requires replacing the functions `self-insert-command',
1468 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1469 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1470 very good at guessing when a re-align will be necessary, but you can always
1471 force one with \\[org-ctrl-c-ctrl-c].
1473 If you would like to use the optimized version in Org-mode, but the
1474 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1476 This variable can be used to turn on and off the table editor during a session,
1477 but in order to toggle optimization, a restart is required.
1479 See also the variable `org-table-auto-blank-field'."
1480 :group 'org-table
1481 :type '(choice
1482 (const :tag "off" nil)
1483 (const :tag "on" t)
1484 (const :tag "on, optimized" optimized)))
1486 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1487 (version<= emacs-version "24.1"))
1488 "Non-nil means cluster self-insert commands for undo when possible.
1489 If this is set, then, like in the Emacs command loop, 20 consecutive
1490 characters will be undone together.
1491 This is configurable, because there is some impact on typing performance."
1492 :group 'org-table
1493 :type 'boolean)
1495 (defcustom org-table-tab-recognizes-table.el t
1496 "Non-nil means TAB will automatically notice a table.el table.
1497 When it sees such a table, it moves point into it and - if necessary -
1498 calls `table-recognize-table'."
1499 :group 'org-table-editing
1500 :type 'boolean)
1502 (defgroup org-link nil
1503 "Options concerning links in Org-mode."
1504 :tag "Org Link"
1505 :group 'org)
1507 (defvar org-link-abbrev-alist-local nil
1508 "Buffer-local version of `org-link-abbrev-alist', which see.
1509 The value of this is taken from the #+LINK lines.")
1510 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1512 (defcustom org-link-abbrev-alist nil
1513 "Alist of link abbreviations.
1514 The car of each element is a string, to be replaced at the start of a link.
1515 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1516 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1518 [[linkkey:tag][description]]
1520 The 'linkkey' must be a word word, starting with a letter, followed
1521 by letters, numbers, '-' or '_'.
1523 If REPLACE is a string, the tag will simply be appended to create the link.
1524 If the string contains \"%s\", the tag will be inserted there. If the string
1525 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1526 at that point (see the function `url-hexify-string'). If the string contains
1527 the specifier \"%(my-function)\", then the custom function `my-function' will
1528 be invoked: this function takes the tag as its only argument and must return
1529 a string.
1531 REPLACE may also be a function that will be called with the tag as the
1532 only argument to create the link, which should be returned as a string.
1534 See the manual for examples."
1535 :group 'org-link
1536 :type '(repeat
1537 (cons
1538 (string :tag "Protocol")
1539 (choice
1540 (string :tag "Format")
1541 (function)))))
1543 (defcustom org-descriptive-links t
1544 "Non-nil means Org will display descriptive links.
1545 E.g. [[http://orgmode.org][Org website]] will be displayed as
1546 \"Org Website\", hiding the link itself and just displaying its
1547 description. When set to `nil', Org will display the full links
1548 literally.
1550 You can interactively set the value of this variable by calling
1551 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1552 :group 'org-link
1553 :type 'boolean)
1555 (defcustom org-link-file-path-type 'adaptive
1556 "How the path name in file links should be stored.
1557 Valid values are:
1559 relative Relative to the current directory, i.e. the directory of the file
1560 into which the link is being inserted.
1561 absolute Absolute path, if possible with ~ for home directory.
1562 noabbrev Absolute path, no abbreviation of home directory.
1563 adaptive Use relative path for files in the current directory and sub-
1564 directories of it. For other files, use an absolute path."
1565 :group 'org-link
1566 :type '(choice
1567 (const relative)
1568 (const absolute)
1569 (const noabbrev)
1570 (const adaptive)))
1572 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1573 "Types of links that should be activated in Org-mode files.
1574 This is a list of symbols, each leading to the activation of a certain link
1575 type. In principle, it does not hurt to turn on most link types - there may
1576 be a small gain when turning off unused link types. The types are:
1578 bracket The recommended [[link][description]] or [[link]] links with hiding.
1579 angle Links in angular brackets that may contain whitespace like
1580 <bbdb:Carsten Dominik>.
1581 plain Plain links in normal text, no whitespace, like http://google.com.
1582 radio Text that is matched by a radio target, see manual for details.
1583 tag Tag settings in a headline (link to tag search).
1584 date Time stamps (link to calendar).
1585 footnote Footnote labels.
1587 Changing this variable requires a restart of Emacs to become effective."
1588 :group 'org-link
1589 :type '(set :greedy t
1590 (const :tag "Double bracket links" bracket)
1591 (const :tag "Angular bracket links" angle)
1592 (const :tag "Plain text links" plain)
1593 (const :tag "Radio target matches" radio)
1594 (const :tag "Tags" tag)
1595 (const :tag "Timestamps" date)
1596 (const :tag "Footnotes" footnote)))
1598 (defcustom org-make-link-description-function nil
1599 "Function to use for generating link descriptions from links.
1600 When nil, the link location will be used. This function must take
1601 two parameters: the first one is the link, the second one is the
1602 description generated by `org-insert-link'. The function should
1603 return the description to use."
1604 :group 'org-link
1605 :type '(choice (const nil) (function)))
1607 (defgroup org-link-store nil
1608 "Options concerning storing links in Org-mode."
1609 :tag "Org Store Link"
1610 :group 'org-link)
1612 (defcustom org-url-hexify-p t
1613 "When non-nil, hexify URL when creating a link."
1614 :type 'boolean
1615 :version "24.3"
1616 :group 'org-link-store)
1618 (defcustom org-email-link-description-format "Email %c: %.30s"
1619 "Format of the description part of a link to an email or usenet message.
1620 The following %-escapes will be replaced by corresponding information:
1622 %F full \"From\" field
1623 %f name, taken from \"From\" field, address if no name
1624 %T full \"To\" field
1625 %t first name in \"To\" field, address if no name
1626 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1627 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1628 %s subject
1629 %d date
1630 %m message-id.
1632 You may use normal field width specification between the % and the letter.
1633 This is for example useful to limit the length of the subject.
1635 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1636 :group 'org-link-store
1637 :type 'string)
1639 (defcustom org-from-is-user-regexp
1640 (let (r1 r2)
1641 (when (and user-mail-address (not (string= user-mail-address "")))
1642 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1643 (when (and user-full-name (not (string= user-full-name "")))
1644 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1645 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1646 "Regexp matched against the \"From:\" header of an email or usenet message.
1647 It should match if the message is from the user him/herself."
1648 :group 'org-link-store
1649 :type 'regexp)
1651 (defcustom org-context-in-file-links t
1652 "Non-nil means file links from `org-store-link' contain context.
1653 A search string will be added to the file name with :: as separator and
1654 used to find the context when the link is activated by the command
1655 `org-open-at-point'. When this option is t, the entire active region
1656 will be placed in the search string of the file link. If set to a
1657 positive integer, only the first n lines of context will be stored.
1659 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1660 negates this setting for the duration of the command."
1661 :group 'org-link-store
1662 :type '(choice boolean integer))
1664 (defcustom org-keep-stored-link-after-insertion nil
1665 "Non-nil means keep link in list for entire session.
1667 The command `org-store-link' adds a link pointing to the current
1668 location to an internal list. These links accumulate during a session.
1669 The command `org-insert-link' can be used to insert links into any
1670 Org-mode file (offering completion for all stored links). When this
1671 option is nil, every link which has been inserted once using \\[org-insert-link]
1672 will be removed from the list, to make completing the unused links
1673 more efficient."
1674 :group 'org-link-store
1675 :type 'boolean)
1677 (defgroup org-link-follow nil
1678 "Options concerning following links in Org-mode."
1679 :tag "Org Follow Link"
1680 :group 'org-link)
1682 (defcustom org-link-translation-function nil
1683 "Function to translate links with different syntax to Org syntax.
1684 This can be used to translate links created for example by the Planner
1685 or emacs-wiki packages to Org syntax.
1686 The function must accept two parameters, a TYPE containing the link
1687 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1688 which is everything after the link protocol. It should return a cons
1689 with possibly modified values of type and path.
1690 Org contains a function for this, so if you set this variable to
1691 `org-translate-link-from-planner', you should be able follow many
1692 links created by planner."
1693 :group 'org-link-follow
1694 :type '(choice (const nil) (function)))
1696 (defcustom org-follow-link-hook nil
1697 "Hook that is run after a link has been followed."
1698 :group 'org-link-follow
1699 :type 'hook)
1701 (defcustom org-tab-follows-link nil
1702 "Non-nil means on links TAB will follow the link.
1703 Needs to be set before org.el is loaded.
1704 This really should not be used, it does not make sense, and the
1705 implementation is bad."
1706 :group 'org-link-follow
1707 :type 'boolean)
1709 (defcustom org-return-follows-link nil
1710 "Non-nil means on links RET will follow the link.
1711 In tables, the special behavior of RET has precedence."
1712 :group 'org-link-follow
1713 :type 'boolean)
1715 (defcustom org-mouse-1-follows-link
1716 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1717 "Non-nil means mouse-1 on a link will follow the link.
1718 A longer mouse click will still set point. Does not work on XEmacs.
1719 Needs to be set before org.el is loaded."
1720 :group 'org-link-follow
1721 :type 'boolean)
1723 (defcustom org-mark-ring-length 4
1724 "Number of different positions to be recorded in the ring.
1725 Changing this requires a restart of Emacs to work correctly."
1726 :group 'org-link-follow
1727 :type 'integer)
1729 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1730 "Non-nil means internal links in Org files must exactly match a headline.
1731 When nil, the link search tries to match a phrase with all words
1732 in the search text."
1733 :group 'org-link-follow
1734 :version "24.1"
1735 :type '(choice
1736 (const :tag "Use fuzzy text search" nil)
1737 (const :tag "Match only exact headline" t)
1738 (const :tag "Match exact headline or query to create it"
1739 query-to-create)))
1741 (defcustom org-link-frame-setup
1742 '((vm . vm-visit-folder-other-frame)
1743 (vm-imap . vm-visit-imap-folder-other-frame)
1744 (gnus . org-gnus-no-new-news)
1745 (file . find-file-other-window)
1746 (wl . wl-other-frame))
1747 "Setup the frame configuration for following links.
1748 When following a link with Emacs, it may often be useful to display
1749 this link in another window or frame. This variable can be used to
1750 set this up for the different types of links.
1751 For VM, use any of
1752 `vm-visit-folder'
1753 `vm-visit-folder-other-window'
1754 `vm-visit-folder-other-frame'
1755 For Gnus, use any of
1756 `gnus'
1757 `gnus-other-frame'
1758 `org-gnus-no-new-news'
1759 For FILE, use any of
1760 `find-file'
1761 `find-file-other-window'
1762 `find-file-other-frame'
1763 For Wanderlust use any of
1764 `wl'
1765 `wl-other-frame'
1766 For the calendar, use the variable `calendar-setup'.
1767 For BBDB, it is currently only possible to display the matches in
1768 another window."
1769 :group 'org-link-follow
1770 :type '(list
1771 (cons (const vm)
1772 (choice
1773 (const vm-visit-folder)
1774 (const vm-visit-folder-other-window)
1775 (const vm-visit-folder-other-frame)))
1776 (cons (const vm-imap)
1777 (choice
1778 (const vm-visit-imap-folder)
1779 (const vm-visit-imap-folder-other-window)
1780 (const vm-visit-imap-folder-other-frame)))
1781 (cons (const gnus)
1782 (choice
1783 (const gnus)
1784 (const gnus-other-frame)
1785 (const org-gnus-no-new-news)))
1786 (cons (const file)
1787 (choice
1788 (const find-file)
1789 (const find-file-other-window)
1790 (const find-file-other-frame)))
1791 (cons (const wl)
1792 (choice
1793 (const wl)
1794 (const wl-other-frame)))))
1796 (defcustom org-display-internal-link-with-indirect-buffer nil
1797 "Non-nil means use indirect buffer to display infile links.
1798 Activating internal links (from one location in a file to another location
1799 in the same file) normally just jumps to the location. When the link is
1800 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1801 is displayed in
1802 another window. When this option is set, the other window actually displays
1803 an indirect buffer clone of the current buffer, to avoid any visibility
1804 changes to the current buffer."
1805 :group 'org-link-follow
1806 :type 'boolean)
1808 (defcustom org-open-non-existing-files nil
1809 "Non-nil means `org-open-file' will open non-existing files.
1810 When nil, an error will be generated.
1811 This variable applies only to external applications because they
1812 might choke on non-existing files. If the link is to a file that
1813 will be opened in Emacs, the variable is ignored."
1814 :group 'org-link-follow
1815 :type 'boolean)
1817 (defcustom org-open-directory-means-index-dot-org nil
1818 "Non-nil means a link to a directory really means to index.org.
1819 When nil, following a directory link will run dired or open a finder/explorer
1820 window on that directory."
1821 :group 'org-link-follow
1822 :type 'boolean)
1824 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1825 "Function and arguments to call for following mailto links.
1826 This is a list with the first element being a Lisp function, and the
1827 remaining elements being arguments to the function. In string arguments,
1828 %a will be replaced by the address, and %s will be replaced by the subject
1829 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1830 :group 'org-link-follow
1831 :type '(choice
1832 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1833 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1834 (const :tag "message-mail" (message-mail "%a" "%s"))
1835 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1837 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1838 "Non-nil means ask for confirmation before executing shell links.
1839 Shell links can be dangerous: just think about a link
1841 [[shell:rm -rf ~/*][Google Search]]
1843 This link would show up in your Org-mode document as \"Google Search\",
1844 but really it would remove your entire home directory.
1845 Therefore we advise against setting this variable to nil.
1846 Just change it to `y-or-n-p' if you want to confirm with a
1847 single keystroke rather than having to type \"yes\"."
1848 :group 'org-link-follow
1849 :type '(choice
1850 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1851 (const :tag "with y-or-n (faster)" y-or-n-p)
1852 (const :tag "no confirmation (dangerous)" nil)))
1853 (put 'org-confirm-shell-link-function
1854 'safe-local-variable
1855 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1857 (defcustom org-confirm-shell-link-not-regexp ""
1858 "A regexp to skip confirmation for shell links."
1859 :group 'org-link-follow
1860 :version "24.1"
1861 :type 'regexp)
1863 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1864 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1865 Elisp links can be dangerous: just think about a link
1867 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1869 This link would show up in your Org-mode document as \"Google Search\",
1870 but really it would remove your entire home directory.
1871 Therefore we advise against setting this variable to nil.
1872 Just change it to `y-or-n-p' if you want to confirm with a
1873 single keystroke rather than having to type \"yes\"."
1874 :group 'org-link-follow
1875 :type '(choice
1876 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1877 (const :tag "with y-or-n (faster)" y-or-n-p)
1878 (const :tag "no confirmation (dangerous)" nil)))
1879 (put 'org-confirm-shell-link-function
1880 'safe-local-variable
1881 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1883 (defcustom org-confirm-elisp-link-not-regexp ""
1884 "A regexp to skip confirmation for Elisp links."
1885 :group 'org-link-follow
1886 :version "24.1"
1887 :type 'regexp)
1889 (defconst org-file-apps-defaults-gnu
1890 '((remote . emacs)
1891 (system . mailcap)
1892 (t . mailcap))
1893 "Default file applications on a UNIX or GNU/Linux system.
1894 See `org-file-apps'.")
1896 (defconst org-file-apps-defaults-macosx
1897 '((remote . emacs)
1898 (t . "open %s")
1899 (system . "open %s")
1900 ("ps.gz" . "gv %s")
1901 ("eps.gz" . "gv %s")
1902 ("dvi" . "xdvi %s")
1903 ("fig" . "xfig %s"))
1904 "Default file applications on a MacOS X system.
1905 The system \"open\" is known as a default, but we use X11 applications
1906 for some files for which the OS does not have a good default.
1907 See `org-file-apps'.")
1909 (defconst org-file-apps-defaults-windowsnt
1910 (list
1911 '(remote . emacs)
1912 (cons t
1913 (list (if (featurep 'xemacs)
1914 'mswindows-shell-execute
1915 'w32-shell-execute)
1916 "open" 'file))
1917 (cons 'system
1918 (list (if (featurep 'xemacs)
1919 'mswindows-shell-execute
1920 'w32-shell-execute)
1921 "open" 'file)))
1922 "Default file applications on a Windows NT system.
1923 The system \"open\" is used for most files.
1924 See `org-file-apps'.")
1926 (defcustom org-file-apps
1927 '((auto-mode . emacs)
1928 ("\\.mm\\'" . default)
1929 ("\\.x?html?\\'" . default)
1930 ("\\.pdf\\'" . default))
1931 "External applications for opening `file:path' items in a document.
1932 Org-mode uses system defaults for different file types, but
1933 you can use this variable to set the application for a given file
1934 extension. The entries in this list are cons cells where the car identifies
1935 files and the cdr the corresponding command. Possible values for the
1936 file identifier are
1937 \"string\" A string as a file identifier can be interpreted in different
1938 ways, depending on its contents:
1940 - Alphanumeric characters only:
1941 Match links with this file extension.
1942 Example: (\"pdf\" . \"evince %s\")
1943 to open PDFs with evince.
1945 - Regular expression: Match links where the
1946 filename matches the regexp. If you want to
1947 use groups here, use shy groups.
1949 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1950 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1951 to open *.html and *.xhtml with firefox.
1953 - Regular expression which contains (non-shy) groups:
1954 Match links where the whole link, including \"::\", and
1955 anything after that, matches the regexp.
1956 In a custom command string, %1, %2, etc. are replaced with
1957 the parts of the link that were matched by the groups.
1958 For backwards compatibility, if a command string is given
1959 that does not use any of the group matches, this case is
1960 handled identically to the second one (i.e. match against
1961 file name only).
1962 In a custom lisp form, you can access the group matches with
1963 (match-string n link).
1965 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1966 to open [[file:document.pdf::5]] with evince at page 5.
1968 `directory' Matches a directory
1969 `remote' Matches a remote file, accessible through tramp or efs.
1970 Remote files most likely should be visited through Emacs
1971 because external applications cannot handle such paths.
1972 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1973 so all files Emacs knows how to handle. Using this with
1974 command `emacs' will open most files in Emacs. Beware that this
1975 will also open html files inside Emacs, unless you add
1976 (\"html\" . default) to the list as well.
1977 t Default for files not matched by any of the other options.
1978 `system' The system command to open files, like `open' on Windows
1979 and Mac OS X, and mailcap under GNU/Linux. This is the command
1980 that will be selected if you call `C-c C-o' with a double
1981 \\[universal-argument] \\[universal-argument] prefix.
1983 Possible values for the command are:
1984 `emacs' The file will be visited by the current Emacs process.
1985 `default' Use the default application for this file type, which is the
1986 association for t in the list, most likely in the system-specific
1987 part.
1988 This can be used to overrule an unwanted setting in the
1989 system-specific variable.
1990 `system' Use the system command for opening files, like \"open\".
1991 This command is specified by the entry whose car is `system'.
1992 Most likely, the system-specific version of this variable
1993 does define this command, but you can overrule/replace it
1994 here.
1995 string A command to be executed by a shell; %s will be replaced
1996 by the path to the file.
1997 sexp A Lisp form which will be evaluated. The file path will
1998 be available in the Lisp variable `file'.
1999 For more examples, see the system specific constants
2000 `org-file-apps-defaults-macosx'
2001 `org-file-apps-defaults-windowsnt'
2002 `org-file-apps-defaults-gnu'."
2003 :group 'org-link-follow
2004 :type '(repeat
2005 (cons (choice :value ""
2006 (string :tag "Extension")
2007 (const :tag "System command to open files" system)
2008 (const :tag "Default for unrecognized files" t)
2009 (const :tag "Remote file" remote)
2010 (const :tag "Links to a directory" directory)
2011 (const :tag "Any files that have Emacs modes"
2012 auto-mode))
2013 (choice :value ""
2014 (const :tag "Visit with Emacs" emacs)
2015 (const :tag "Use default" default)
2016 (const :tag "Use the system command" system)
2017 (string :tag "Command")
2018 (sexp :tag "Lisp form")))))
2020 (defcustom org-doi-server-url "http://dx.doi.org/"
2021 "The URL of the DOI server."
2022 :type 'string
2023 :version "24.3"
2024 :group 'org-link-follow)
2026 (defgroup org-refile nil
2027 "Options concerning refiling entries in Org-mode."
2028 :tag "Org Refile"
2029 :group 'org)
2031 (defcustom org-directory "~/org"
2032 "Directory with org files.
2033 This is just a default location to look for Org files. There is no need
2034 at all to put your files into this directory. It is only used in the
2035 following situations:
2037 1. When a capture template specifies a target file that is not an
2038 absolute path. The path will then be interpreted relative to
2039 `org-directory'
2040 2. When a capture note is filed away in an interactive way (when exiting the
2041 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2042 with `org-directory' as the default path."
2043 :group 'org-refile
2044 :group 'org-remember
2045 :group 'org-capture
2046 :type 'directory)
2048 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2049 "Default target for storing notes.
2050 Used as a fall back file for org-remember.el and org-capture.el, for
2051 templates that do not specify a target file."
2052 :group 'org-refile
2053 :group 'org-remember
2054 :group 'org-capture
2055 :type '(choice
2056 (const :tag "Default from remember-data-file" nil)
2057 file))
2059 (defcustom org-goto-interface 'outline
2060 "The default interface to be used for `org-goto'.
2061 Allowed values are:
2062 outline The interface shows an outline of the relevant file
2063 and the correct heading is found by moving through
2064 the outline or by searching with incremental search.
2065 outline-path-completion Headlines in the current buffer are offered via
2066 completion. This is the interface also used by
2067 the refile command."
2068 :group 'org-refile
2069 :type '(choice
2070 (const :tag "Outline" outline)
2071 (const :tag "Outline-path-completion" outline-path-completion)))
2073 (defcustom org-goto-max-level 5
2074 "Maximum target level when running `org-goto' with refile interface."
2075 :group 'org-refile
2076 :type 'integer)
2078 (defcustom org-reverse-note-order nil
2079 "Non-nil means store new notes at the beginning of a file or entry.
2080 When nil, new notes will be filed to the end of a file or entry.
2081 This can also be a list with cons cells of regular expressions that
2082 are matched against file names, and values."
2083 :group 'org-remember
2084 :group 'org-capture
2085 :group 'org-refile
2086 :type '(choice
2087 (const :tag "Reverse always" t)
2088 (const :tag "Reverse never" nil)
2089 (repeat :tag "By file name regexp"
2090 (cons regexp boolean))))
2092 (defcustom org-log-refile nil
2093 "Information to record when a task is refiled.
2095 Possible values are:
2097 nil Don't add anything
2098 time Add a time stamp to the task
2099 note Prompt for a note and add it with template `org-log-note-headings'
2101 This option can also be set with on a per-file-basis with
2103 #+STARTUP: nologrefile
2104 #+STARTUP: logrefile
2105 #+STARTUP: lognoterefile
2107 You can have local logging settings for a subtree by setting the LOGGING
2108 property to one or more of these keywords.
2110 When bulk-refiling from the agenda, the value `note' is forbidden and
2111 will temporarily be changed to `time'."
2112 :group 'org-refile
2113 :group 'org-progress
2114 :version "24.1"
2115 :type '(choice
2116 (const :tag "No logging" nil)
2117 (const :tag "Record timestamp" time)
2118 (const :tag "Record timestamp with note." note)))
2120 (defcustom org-refile-targets nil
2121 "Targets for refiling entries with \\[org-refile].
2122 This is a list of cons cells. Each cell contains:
2123 - a specification of the files to be considered, either a list of files,
2124 or a symbol whose function or variable value will be used to retrieve
2125 a file name or a list of file names. If you use `org-agenda-files' for
2126 that, all agenda files will be scanned for targets. Nil means consider
2127 headings in the current buffer.
2128 - A specification of how to find candidate refile targets. This may be
2129 any of:
2130 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2131 This tag has to be present in all target headlines, inheritance will
2132 not be considered.
2133 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2134 todo keyword.
2135 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2136 headlines that are refiling targets.
2137 - a cons cell (:level . N). Any headline of level N is considered a target.
2138 Note that, when `org-odd-levels-only' is set, level corresponds to
2139 order in hierarchy, not to the number of stars.
2140 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2141 Note that, when `org-odd-levels-only' is set, level corresponds to
2142 order in hierarchy, not to the number of stars.
2144 Each element of this list generates a set of possible targets.
2145 The union of these sets is presented (with completion) to
2146 the user by `org-refile'.
2148 You can set the variable `org-refile-target-verify-function' to a function
2149 to verify each headline found by the simple criteria above.
2151 When this variable is nil, all top-level headlines in the current buffer
2152 are used, equivalent to the value `((nil . (:level . 1))'."
2153 :group 'org-refile
2154 :type '(repeat
2155 (cons
2156 (choice :value org-agenda-files
2157 (const :tag "All agenda files" org-agenda-files)
2158 (const :tag "Current buffer" nil)
2159 (function) (variable) (file))
2160 (choice :tag "Identify target headline by"
2161 (cons :tag "Specific tag" (const :value :tag) (string))
2162 (cons :tag "TODO keyword" (const :value :todo) (string))
2163 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2164 (cons :tag "Level number" (const :value :level) (integer))
2165 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2167 (defcustom org-refile-target-verify-function nil
2168 "Function to verify if the headline at point should be a refile target.
2169 The function will be called without arguments, with point at the
2170 beginning of the headline. It should return t and leave point
2171 where it is if the headline is a valid target for refiling.
2173 If the target should not be selected, the function must return nil.
2174 In addition to this, it may move point to a place from where the search
2175 should be continued. For example, the function may decide that the entire
2176 subtree of the current entry should be excluded and move point to the end
2177 of the subtree."
2178 :group 'org-refile
2179 :type '(choice
2180 (const nil)
2181 (function)))
2183 (defcustom org-refile-use-cache nil
2184 "Non-nil means cache refile targets to speed up the process.
2185 The cache for a particular file will be updated automatically when
2186 the buffer has been killed, or when any of the marker used for flagging
2187 refile targets no longer points at a live buffer.
2188 If you have added new entries to a buffer that might themselves be targets,
2189 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2190 find that easier, `C-u C-u C-u C-c C-w'."
2191 :group 'org-refile
2192 :version "24.1"
2193 :type 'boolean)
2195 (defcustom org-refile-use-outline-path nil
2196 "Non-nil means provide refile targets as paths.
2197 So a level 3 headline will be available as level1/level2/level3.
2199 When the value is `file', also include the file name (without directory)
2200 into the path. In this case, you can also stop the completion after
2201 the file name, to get entries inserted as top level in the file.
2203 When `full-file-path', include the full file path."
2204 :group 'org-refile
2205 :type '(choice
2206 (const :tag "Not" nil)
2207 (const :tag "Yes" t)
2208 (const :tag "Start with file name" file)
2209 (const :tag "Start with full file path" full-file-path)))
2211 (defcustom org-outline-path-complete-in-steps t
2212 "Non-nil means complete the outline path in hierarchical steps.
2213 When Org-mode uses the refile interface to select an outline path
2214 \(see variable `org-refile-use-outline-path'), the completion of
2215 the path can be done is a single go, or if can be done in steps down
2216 the headline hierarchy. Going in steps is probably the best if you
2217 do not use a special completion package like `ido' or `icicles'.
2218 However, when using these packages, going in one step can be very
2219 fast, while still showing the whole path to the entry."
2220 :group 'org-refile
2221 :type 'boolean)
2223 (defcustom org-refile-allow-creating-parent-nodes nil
2224 "Non-nil means allow to create new nodes as refile targets.
2225 New nodes are then created by adding \"/new node name\" to the completion
2226 of an existing node. When the value of this variable is `confirm',
2227 new node creation must be confirmed by the user (recommended)
2228 When nil, the completion must match an existing entry.
2230 Note that, if the new heading is not seen by the criteria
2231 listed in `org-refile-targets', multiple instances of the same
2232 heading would be created by trying again to file under the new
2233 heading."
2234 :group 'org-refile
2235 :type '(choice
2236 (const :tag "Never" nil)
2237 (const :tag "Always" t)
2238 (const :tag "Prompt for confirmation" confirm)))
2240 (defcustom org-refile-active-region-within-subtree nil
2241 "Non-nil means also refile active region within a subtree.
2243 By default `org-refile' doesn't allow refiling regions if they
2244 don't contain a set of subtrees, but it might be convenient to
2245 do so sometimes: in that case, the first line of the region is
2246 converted to a headline before refiling."
2247 :group 'org-refile
2248 :version "24.1"
2249 :type 'boolean)
2251 (defgroup org-todo nil
2252 "Options concerning TODO items in Org-mode."
2253 :tag "Org TODO"
2254 :group 'org)
2256 (defgroup org-progress nil
2257 "Options concerning Progress logging in Org-mode."
2258 :tag "Org Progress"
2259 :group 'org-time)
2261 (defvar org-todo-interpretation-widgets
2262 '((:tag "Sequence (cycling hits every state)" sequence)
2263 (:tag "Type (cycling directly to DONE)" type))
2264 "The available interpretation symbols for customizing `org-todo-keywords'.
2265 Interested libraries should add to this list.")
2267 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2268 "List of TODO entry keyword sequences and their interpretation.
2269 \\<org-mode-map>This is a list of sequences.
2271 Each sequence starts with a symbol, either `sequence' or `type',
2272 indicating if the keywords should be interpreted as a sequence of
2273 action steps, or as different types of TODO items. The first
2274 keywords are states requiring action - these states will select a headline
2275 for inclusion into the global TODO list Org-mode produces. If one of
2276 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2277 signify that no further action is necessary. If \"|\" is not found,
2278 the last keyword is treated as the only DONE state of the sequence.
2280 The command \\[org-todo] cycles an entry through these states, and one
2281 additional state where no keyword is present. For details about this
2282 cycling, see the manual.
2284 TODO keywords and interpretation can also be set on a per-file basis with
2285 the special #+SEQ_TODO and #+TYP_TODO lines.
2287 Each keyword can optionally specify a character for fast state selection
2288 \(in combination with the variable `org-use-fast-todo-selection')
2289 and specifiers for state change logging, using the same syntax that
2290 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2291 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2292 indicates to record a time stamp each time this state is selected.
2294 Each keyword may also specify if a timestamp or a note should be
2295 recorded when entering or leaving the state, by adding additional
2296 characters in the parenthesis after the keyword. This looks like this:
2297 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2298 record only the time of the state change. With X and Y being either
2299 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2300 Y when leaving the state if and only if the *target* state does not
2301 define X. You may omit any of the fast-selection key or X or /Y,
2302 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2304 For backward compatibility, this variable may also be just a list
2305 of keywords. In this case the interpretation (sequence or type) will be
2306 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2307 :group 'org-todo
2308 :group 'org-keywords
2309 :type '(choice
2310 (repeat :tag "Old syntax, just keywords"
2311 (string :tag "Keyword"))
2312 (repeat :tag "New syntax"
2313 (cons
2314 (choice
2315 :tag "Interpretation"
2316 ;;Quick and dirty way to see
2317 ;;`org-todo-interpretations'. This takes the
2318 ;;place of item arguments
2319 :convert-widget
2320 (lambda (widget)
2321 (widget-put widget
2322 :args (mapcar
2323 #'(lambda (x)
2324 (widget-convert
2325 (cons 'const x)))
2326 org-todo-interpretation-widgets))
2327 widget))
2328 (repeat
2329 (string :tag "Keyword"))))))
2331 (defvar org-todo-keywords-1 nil
2332 "All TODO and DONE keywords active in a buffer.")
2333 (make-variable-buffer-local 'org-todo-keywords-1)
2334 (defvar org-todo-keywords-for-agenda nil)
2335 (defvar org-done-keywords-for-agenda nil)
2336 (defvar org-todo-keyword-alist-for-agenda nil)
2337 (defvar org-tag-alist-for-agenda nil
2338 "Alist of all tags from all agenda files.")
2339 (defvar org-tag-groups-alist-for-agenda nil
2340 "Alist of all groups tags from all current agenda files.")
2341 (defvar org-tag-groups-alist nil)
2342 (make-variable-buffer-local 'org-tag-groups-alist)
2343 (defvar org-agenda-contributing-files nil)
2344 (defvar org-not-done-keywords nil)
2345 (make-variable-buffer-local 'org-not-done-keywords)
2346 (defvar org-done-keywords nil)
2347 (make-variable-buffer-local 'org-done-keywords)
2348 (defvar org-todo-heads nil)
2349 (make-variable-buffer-local 'org-todo-heads)
2350 (defvar org-todo-sets nil)
2351 (make-variable-buffer-local 'org-todo-sets)
2352 (defvar org-todo-log-states nil)
2353 (make-variable-buffer-local 'org-todo-log-states)
2354 (defvar org-todo-kwd-alist nil)
2355 (make-variable-buffer-local 'org-todo-kwd-alist)
2356 (defvar org-todo-key-alist nil)
2357 (make-variable-buffer-local 'org-todo-key-alist)
2358 (defvar org-todo-key-trigger nil)
2359 (make-variable-buffer-local 'org-todo-key-trigger)
2361 (defcustom org-todo-interpretation 'sequence
2362 "Controls how TODO keywords are interpreted.
2363 This variable is in principle obsolete and is only used for
2364 backward compatibility, if the interpretation of todo keywords is
2365 not given already in `org-todo-keywords'. See that variable for
2366 more information."
2367 :group 'org-todo
2368 :group 'org-keywords
2369 :type '(choice (const sequence)
2370 (const type)))
2372 (defcustom org-use-fast-todo-selection t
2373 "Non-nil means use the fast todo selection scheme with C-c C-t.
2374 This variable describes if and under what circumstances the cycling
2375 mechanism for TODO keywords will be replaced by a single-key, direct
2376 selection scheme.
2378 When nil, fast selection is never used.
2380 When the symbol `prefix', it will be used when `org-todo' is called
2381 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2382 `C-u t' in an agenda buffer.
2384 When t, fast selection is used by default. In this case, the prefix
2385 argument forces cycling instead.
2387 In all cases, the special interface is only used if access keys have
2388 actually been assigned by the user, i.e. if keywords in the configuration
2389 are followed by a letter in parenthesis, like TODO(t)."
2390 :group 'org-todo
2391 :type '(choice
2392 (const :tag "Never" nil)
2393 (const :tag "By default" t)
2394 (const :tag "Only with C-u C-c C-t" prefix)))
2396 (defcustom org-provide-todo-statistics t
2397 "Non-nil means update todo statistics after insert and toggle.
2398 ALL-HEADLINES means update todo statistics by including headlines
2399 with no TODO keyword as well, counting them as not done.
2400 A list of TODO keywords means the same, but skip keywords that are
2401 not in this list.
2403 When this is set, todo statistics is updated in the parent of the
2404 current entry each time a todo state is changed."
2405 :group 'org-todo
2406 :type '(choice
2407 (const :tag "Yes, only for TODO entries" t)
2408 (const :tag "Yes, including all entries" 'all-headlines)
2409 (repeat :tag "Yes, for TODOs in this list"
2410 (string :tag "TODO keyword"))
2411 (other :tag "No TODO statistics" nil)))
2413 (defcustom org-hierarchical-todo-statistics t
2414 "Non-nil means TODO statistics covers just direct children.
2415 When nil, all entries in the subtree are considered.
2416 This has only an effect if `org-provide-todo-statistics' is set.
2417 To set this to nil for only a single subtree, use a COOKIE_DATA
2418 property and include the word \"recursive\" into the value."
2419 :group 'org-todo
2420 :type 'boolean)
2422 (defcustom org-after-todo-state-change-hook nil
2423 "Hook which is run after the state of a TODO item was changed.
2424 The new state (a string with a TODO keyword, or nil) is available in the
2425 Lisp variable `org-state'."
2426 :group 'org-todo
2427 :type 'hook)
2429 (defvar org-blocker-hook nil
2430 "Hook for functions that are allowed to block a state change.
2432 Functions in this hook should not modify the buffer.
2433 Each function gets as its single argument a property list,
2434 see `org-trigger-hook' for more information about this list.
2436 If any of the functions in this hook returns nil, the state change
2437 is blocked.")
2439 (defvar org-trigger-hook nil
2440 "Hook for functions that are triggered by a state change.
2442 Each function gets as its single argument a property list with at
2443 least the following elements:
2445 (:type type-of-change :position pos-at-entry-start
2446 :from old-state :to new-state)
2448 Depending on the type, more properties may be present.
2450 This mechanism is currently implemented for:
2452 TODO state changes
2453 ------------------
2454 :type todo-state-change
2455 :from previous state (keyword as a string), or nil, or a symbol
2456 'todo' or 'done', to indicate the general type of state.
2457 :to new state, like in :from")
2459 (defcustom org-enforce-todo-dependencies nil
2460 "Non-nil means undone TODO entries will block switching the parent to DONE.
2461 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2462 be blocked if any prior sibling is not yet done.
2463 Finally, if the parent is blocked because of ordered siblings of its own,
2464 the child will also be blocked."
2465 :set (lambda (var val)
2466 (set var val)
2467 (if val
2468 (add-hook 'org-blocker-hook
2469 'org-block-todo-from-children-or-siblings-or-parent)
2470 (remove-hook 'org-blocker-hook
2471 'org-block-todo-from-children-or-siblings-or-parent)))
2472 :group 'org-todo
2473 :type 'boolean)
2475 (defcustom org-enforce-todo-checkbox-dependencies nil
2476 "Non-nil means unchecked boxes will block switching the parent to DONE.
2477 When this is nil, checkboxes have no influence on switching TODO states.
2478 When non-nil, you first need to check off all check boxes before the TODO
2479 entry can be switched to DONE.
2480 This variable needs to be set before org.el is loaded, and you need to
2481 restart Emacs after a change to make the change effective. The only way
2482 to change is while Emacs is running is through the customize interface."
2483 :set (lambda (var val)
2484 (set var val)
2485 (if val
2486 (add-hook 'org-blocker-hook
2487 'org-block-todo-from-checkboxes)
2488 (remove-hook 'org-blocker-hook
2489 'org-block-todo-from-checkboxes)))
2490 :group 'org-todo
2491 :type 'boolean)
2493 (defcustom org-treat-insert-todo-heading-as-state-change nil
2494 "Non-nil means inserting a TODO heading is treated as state change.
2495 So when the command \\[org-insert-todo-heading] is used, state change
2496 logging will apply if appropriate. When nil, the new TODO item will
2497 be inserted directly, and no logging will take place."
2498 :group 'org-todo
2499 :type 'boolean)
2501 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2502 "Non-nil means switching TODO states with S-cursor counts as state change.
2503 This is the default behavior. However, setting this to nil allows a
2504 convenient way to select a TODO state and bypass any logging associated
2505 with that."
2506 :group 'org-todo
2507 :type 'boolean)
2509 (defcustom org-todo-state-tags-triggers nil
2510 "Tag changes that should be triggered by TODO state changes.
2511 This is a list. Each entry is
2513 (state-change (tag . flag) .......)
2515 State-change can be a string with a state, and empty string to indicate the
2516 state that has no TODO keyword, or it can be one of the symbols `todo'
2517 or `done', meaning any not-done or done state, respectively."
2518 :group 'org-todo
2519 :group 'org-tags
2520 :type '(repeat
2521 (cons (choice :tag "When changing to"
2522 (const :tag "Not-done state" todo)
2523 (const :tag "Done state" done)
2524 (string :tag "State"))
2525 (repeat
2526 (cons :tag "Tag action"
2527 (string :tag "Tag")
2528 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2530 (defcustom org-log-done nil
2531 "Information to record when a task moves to the DONE state.
2533 Possible values are:
2535 nil Don't add anything, just change the keyword
2536 time Add a time stamp to the task
2537 note Prompt for a note and add it with template `org-log-note-headings'
2539 This option can also be set with on a per-file-basis with
2541 #+STARTUP: nologdone
2542 #+STARTUP: logdone
2543 #+STARTUP: lognotedone
2545 You can have local logging settings for a subtree by setting the LOGGING
2546 property to one or more of these keywords."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type '(choice
2550 (const :tag "No logging" nil)
2551 (const :tag "Record CLOSED timestamp" time)
2552 (const :tag "Record CLOSED timestamp with note." note)))
2554 ;; Normalize old uses of org-log-done.
2555 (cond
2556 ((eq org-log-done t) (setq org-log-done 'time))
2557 ((and (listp org-log-done) (memq 'done org-log-done))
2558 (setq org-log-done 'note)))
2560 (defcustom org-log-reschedule nil
2561 "Information to record when the scheduling date of a tasks is modified.
2563 Possible values are:
2565 nil Don't add anything, just change the date
2566 time Add a time stamp to the task
2567 note Prompt for a note and add it with template `org-log-note-headings'
2569 This option can also be set with on a per-file-basis with
2571 #+STARTUP: nologreschedule
2572 #+STARTUP: logreschedule
2573 #+STARTUP: lognotereschedule"
2574 :group 'org-todo
2575 :group 'org-progress
2576 :type '(choice
2577 (const :tag "No logging" nil)
2578 (const :tag "Record timestamp" time)
2579 (const :tag "Record timestamp with note." note)))
2581 (defcustom org-log-redeadline nil
2582 "Information to record when the deadline date of a tasks is modified.
2584 Possible values are:
2586 nil Don't add anything, just change the date
2587 time Add a time stamp to the task
2588 note Prompt for a note and add it with template `org-log-note-headings'
2590 This option can also be set with on a per-file-basis with
2592 #+STARTUP: nologredeadline
2593 #+STARTUP: logredeadline
2594 #+STARTUP: lognoteredeadline
2596 You can have local logging settings for a subtree by setting the LOGGING
2597 property to one or more of these keywords."
2598 :group 'org-todo
2599 :group 'org-progress
2600 :type '(choice
2601 (const :tag "No logging" nil)
2602 (const :tag "Record timestamp" time)
2603 (const :tag "Record timestamp with note." note)))
2605 (defcustom org-log-note-clock-out nil
2606 "Non-nil means record a note when clocking out of an item.
2607 This can also be configured on a per-file basis by adding one of
2608 the following lines anywhere in the buffer:
2610 #+STARTUP: lognoteclock-out
2611 #+STARTUP: nolognoteclock-out"
2612 :group 'org-todo
2613 :group 'org-progress
2614 :type 'boolean)
2616 (defcustom org-log-done-with-time t
2617 "Non-nil means the CLOSED time stamp will contain date and time.
2618 When nil, only the date will be recorded."
2619 :group 'org-progress
2620 :type 'boolean)
2622 (defcustom org-log-note-headings
2623 '((done . "CLOSING NOTE %t")
2624 (state . "State %-12s from %-12S %t")
2625 (note . "Note taken on %t")
2626 (reschedule . "Rescheduled from %S on %t")
2627 (delschedule . "Not scheduled, was %S on %t")
2628 (redeadline . "New deadline from %S on %t")
2629 (deldeadline . "Removed deadline, was %S on %t")
2630 (refile . "Refiled on %t")
2631 (clock-out . ""))
2632 "Headings for notes added to entries.
2633 The value is an alist, with the car being a symbol indicating the note
2634 context, and the cdr is the heading to be used. The heading may also be the
2635 empty string.
2636 %t in the heading will be replaced by a time stamp.
2637 %T will be an active time stamp instead the default inactive one
2638 %d will be replaced by a short-format time stamp.
2639 %D will be replaced by an active short-format time stamp.
2640 %s will be replaced by the new TODO state, in double quotes.
2641 %S will be replaced by the old TODO state, in double quotes.
2642 %u will be replaced by the user name.
2643 %U will be replaced by the full user name.
2645 In fact, it is not a good idea to change the `state' entry, because
2646 agenda log mode depends on the format of these entries."
2647 :group 'org-todo
2648 :group 'org-progress
2649 :type '(list :greedy t
2650 (cons (const :tag "Heading when closing an item" done) string)
2651 (cons (const :tag
2652 "Heading when changing todo state (todo sequence only)"
2653 state) string)
2654 (cons (const :tag "Heading when just taking a note" note) string)
2655 (cons (const :tag "Heading when clocking out" clock-out) string)
2656 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2657 (cons (const :tag "Heading when rescheduling" reschedule) string)
2658 (cons (const :tag "Heading when changing deadline" redeadline) string)
2659 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2660 (cons (const :tag "Heading when refiling" refile) string)))
2662 (unless (assq 'note org-log-note-headings)
2663 (push '(note . "%t") org-log-note-headings))
2665 (defcustom org-log-into-drawer nil
2666 "Non-nil means insert state change notes and time stamps into a drawer.
2667 When nil, state changes notes will be inserted after the headline and
2668 any scheduling and clock lines, but not inside a drawer.
2670 The value of this variable should be the name of the drawer to use.
2671 LOGBOOK is proposed as the default drawer for this purpose, you can
2672 also set this to a string to define the drawer of your choice.
2674 A value of t is also allowed, representing \"LOGBOOK\".
2676 A value of t or nil can also be set with on a per-file-basis with
2678 #+STARTUP: logdrawer
2679 #+STARTUP: nologdrawer
2681 If this variable is set, `org-log-state-notes-insert-after-drawers'
2682 will be ignored.
2684 You can set the property LOG_INTO_DRAWER to overrule this setting for
2685 a subtree."
2686 :group 'org-todo
2687 :group 'org-progress
2688 :type '(choice
2689 (const :tag "Not into a drawer" nil)
2690 (const :tag "LOGBOOK" t)
2691 (string :tag "Other")))
2693 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2695 (defun org-log-into-drawer ()
2696 "Return the value of `org-log-into-drawer', but let properties overrule.
2697 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2698 used instead of the default value."
2699 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2700 (cond
2701 ((not p) org-log-into-drawer)
2702 ((equal p "nil") nil)
2703 ((equal p "t") "LOGBOOK")
2704 (t p))))
2706 (defcustom org-log-state-notes-insert-after-drawers nil
2707 "Non-nil means insert state change notes after any drawers in entry.
2708 Only the drawers that *immediately* follow the headline and the
2709 deadline/scheduled line are skipped.
2710 When nil, insert notes right after the heading and perhaps the line
2711 with deadline/scheduling if present.
2713 This variable will have no effect if `org-log-into-drawer' is
2714 set."
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type 'boolean)
2719 (defcustom org-log-states-order-reversed t
2720 "Non-nil means the latest state note will be directly after heading.
2721 When nil, the state change notes will be ordered according to time.
2723 This option can also be set with on a per-file-basis with
2725 #+STARTUP: logstatesreversed
2726 #+STARTUP: nologstatesreversed"
2727 :group 'org-todo
2728 :group 'org-progress
2729 :type 'boolean)
2731 (defcustom org-todo-repeat-to-state nil
2732 "The TODO state to which a repeater should return the repeating task.
2733 By default this is the first task in a TODO sequence, or the previous state
2734 in a TODO_TYP set. But you can specify another task here.
2735 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2736 :group 'org-todo
2737 :version "24.1"
2738 :type '(choice (const :tag "Head of sequence" nil)
2739 (string :tag "Specific state")))
2741 (defcustom org-log-repeat 'time
2742 "Non-nil means record moving through the DONE state when triggering repeat.
2743 An auto-repeating task is immediately switched back to TODO when
2744 marked DONE. If you are not logging state changes (by adding \"@\"
2745 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2746 record a closing note, there will be no record of the task moving
2747 through DONE. This variable forces taking a note anyway.
2749 nil Don't force a record
2750 time Record a time stamp
2751 note Prompt for a note and add it with template `org-log-note-headings'
2753 This option can also be set with on a per-file-basis with
2755 #+STARTUP: nologrepeat
2756 #+STARTUP: logrepeat
2757 #+STARTUP: lognoterepeat
2759 You can have local logging settings for a subtree by setting the LOGGING
2760 property to one or more of these keywords."
2761 :group 'org-todo
2762 :group 'org-progress
2763 :type '(choice
2764 (const :tag "Don't force a record" nil)
2765 (const :tag "Force recording the DONE state" time)
2766 (const :tag "Force recording a note with the DONE state" note)))
2769 (defgroup org-priorities nil
2770 "Priorities in Org-mode."
2771 :tag "Org Priorities"
2772 :group 'org-todo)
2774 (defcustom org-enable-priority-commands t
2775 "Non-nil means priority commands are active.
2776 When nil, these commands will be disabled, so that you never accidentally
2777 set a priority."
2778 :group 'org-priorities
2779 :type 'boolean)
2781 (defcustom org-highest-priority ?A
2782 "The highest priority of TODO items. A character like ?A, ?B etc.
2783 Must have a smaller ASCII number than `org-lowest-priority'."
2784 :group 'org-priorities
2785 :type 'character)
2787 (defcustom org-lowest-priority ?C
2788 "The lowest priority of TODO items. A character like ?A, ?B etc.
2789 Must have a larger ASCII number than `org-highest-priority'."
2790 :group 'org-priorities
2791 :type 'character)
2793 (defcustom org-default-priority ?B
2794 "The default priority of TODO items.
2795 This is the priority an item gets if no explicit priority is given.
2796 When starting to cycle on an empty priority the first step in the cycle
2797 depends on `org-priority-start-cycle-with-default'. The resulting first
2798 step priority must not exceed the range from `org-highest-priority' to
2799 `org-lowest-priority' which means that `org-default-priority' has to be
2800 in this range exclusive or inclusive the range boundaries. Else the
2801 first step refuses to set the default and the second will fall back
2802 to (depending on the command used) the highest or lowest priority."
2803 :group 'org-priorities
2804 :type 'character)
2806 (defcustom org-priority-start-cycle-with-default t
2807 "Non-nil means start with default priority when starting to cycle.
2808 When this is nil, the first step in the cycle will be (depending on the
2809 command used) one higher or lower than the default priority.
2810 See also `org-default-priority'."
2811 :group 'org-priorities
2812 :type 'boolean)
2814 (defcustom org-get-priority-function nil
2815 "Function to extract the priority from a string.
2816 The string is normally the headline. If this is nil Org computes the
2817 priority from the priority cookie like [#A] in the headline. It returns
2818 an integer, increasing by 1000 for each priority level.
2819 The user can set a different function here, which should take a string
2820 as an argument and return the numeric priority."
2821 :group 'org-priorities
2822 :version "24.1"
2823 :type '(choice
2824 (const nil)
2825 (function)))
2827 (defgroup org-time nil
2828 "Options concerning time stamps and deadlines in Org-mode."
2829 :tag "Org Time"
2830 :group 'org)
2832 (defcustom org-insert-labeled-timestamps-at-point nil
2833 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2834 When nil, these labeled time stamps are forces into the second line of an
2835 entry, just after the headline. When scheduling from the global TODO list,
2836 the time stamp will always be forced into the second line."
2837 :group 'org-time
2838 :type 'boolean)
2840 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2841 "Formats for `format-time-string' which are used for time stamps.
2842 It is not recommended to change this constant.")
2844 (defcustom org-time-stamp-rounding-minutes '(0 5)
2845 "Number of minutes to round time stamps to.
2846 These are two values, the first applies when first creating a time stamp.
2847 The second applies when changing it with the commands `S-up' and `S-down'.
2848 When changing the time stamp, this means that it will change in steps
2849 of N minutes, as given by the second value.
2851 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2852 numbers should be factors of 60, so for example 5, 10, 15.
2854 When this is larger than 1, you can still force an exact time stamp by using
2855 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2856 and by using a prefix arg to `S-up/down' to specify the exact number
2857 of minutes to shift."
2858 :group 'org-time
2859 :get #'(lambda (var) ; Make sure both elements are there
2860 (if (integerp (default-value var))
2861 (list (default-value var) 5)
2862 (default-value var)))
2863 :type '(list
2864 (integer :tag "when inserting times")
2865 (integer :tag "when modifying times")))
2867 ;; Normalize old customizations of this variable.
2868 (when (integerp org-time-stamp-rounding-minutes)
2869 (setq org-time-stamp-rounding-minutes
2870 (list org-time-stamp-rounding-minutes
2871 org-time-stamp-rounding-minutes)))
2873 (defcustom org-display-custom-times nil
2874 "Non-nil means overlay custom formats over all time stamps.
2875 The formats are defined through the variable `org-time-stamp-custom-formats'.
2876 To turn this on on a per-file basis, insert anywhere in the file:
2877 #+STARTUP: customtime"
2878 :group 'org-time
2879 :set 'set-default
2880 :type 'sexp)
2881 (make-variable-buffer-local 'org-display-custom-times)
2883 (defcustom org-time-stamp-custom-formats
2884 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2885 "Custom formats for time stamps. See `format-time-string' for the syntax.
2886 These are overlaid over the default ISO format if the variable
2887 `org-display-custom-times' is set. Time like %H:%M should be at the
2888 end of the second format. The custom formats are also honored by export
2889 commands, if custom time display is turned on at the time of export."
2890 :group 'org-time
2891 :type 'sexp)
2893 (defun org-time-stamp-format (&optional long inactive)
2894 "Get the right format for a time string."
2895 (let ((f (if long (cdr org-time-stamp-formats)
2896 (car org-time-stamp-formats))))
2897 (if inactive
2898 (concat "[" (substring f 1 -1) "]")
2899 f)))
2901 (defcustom org-time-clocksum-format
2902 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2903 "The format string used when creating CLOCKSUM lines.
2904 This is also used when Org mode generates a time duration.
2906 The value can be a single format string containing two
2907 %-sequences, which will be filled with the number of hours and
2908 minutes in that order.
2910 Alternatively, the value can be a plist associating any of the
2911 keys :years, :months, :weeks, :days, :hours or :minutes with
2912 format strings. The time duration is formatted using only the
2913 time components that are needed and concatenating the results.
2914 If a time unit in absent, it falls back to the next smallest
2915 unit.
2917 The keys :require-years, :require-months, :require-days,
2918 :require-weeks, :require-hours, :require-minutes are also
2919 meaningful. A non-nil value for these keys indicates that the
2920 corresponding time component should always be included, even if
2921 its value is 0.
2924 For example,
2926 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2927 :require-minutes t)
2929 means durations longer than a day will be expressed in days,
2930 hours and minutes, and durations less than a day will always be
2931 expressed in hours and minutes (even for durations less than an
2932 hour).
2934 The value
2936 \(:days \"%dd\" :minutes \"%dm\")
2938 means durations longer than a day will be expressed in days and
2939 minutes, and durations less than a day will be expressed entirely
2940 in minutes (even for durations longer than an hour)."
2941 :group 'org-time
2942 :group 'org-clock
2943 :version "24.4"
2944 :package-version '(Org . "8.0")
2945 :type '(choice (string :tag "Format string")
2946 (set :tag "Plist"
2947 (group :inline t (const :tag "Years" :years)
2948 (string :tag "Format string"))
2949 (group :inline t
2950 (const :tag "Always show years" :require-years)
2951 (const t))
2952 (group :inline t (const :tag "Months" :months)
2953 (string :tag "Format string"))
2954 (group :inline t
2955 (const :tag "Always show months" :require-months)
2956 (const t))
2957 (group :inline t (const :tag "Weeks" :weeks)
2958 (string :tag "Format string"))
2959 (group :inline t
2960 (const :tag "Always show weeks" :require-weeks)
2961 (const t))
2962 (group :inline t (const :tag "Days" :days)
2963 (string :tag "Format string"))
2964 (group :inline t
2965 (const :tag "Always show days" :require-days)
2966 (const t))
2967 (group :inline t (const :tag "Hours" :hours)
2968 (string :tag "Format string"))
2969 (group :inline t
2970 (const :tag "Always show hours" :require-hours)
2971 (const t))
2972 (group :inline t (const :tag "Minutes" :minutes)
2973 (string :tag "Format string"))
2974 (group :inline t
2975 (const :tag "Always show minutes" :require-minutes)
2976 (const t)))))
2978 (defcustom org-time-clocksum-use-fractional nil
2979 "When non-nil, \\[org-clock-display] uses fractional times.
2980 See `org-time-clocksum-format' for more on time clock formats."
2981 :group 'org-time
2982 :group 'org-clock
2983 :version "24.3"
2984 :type 'boolean)
2986 (defcustom org-time-clocksum-use-effort-durations nil
2987 "When non-nil, \\[org-clock-display] uses effort durations.
2988 E.g. by default, one day is considered to be a 8 hours effort,
2989 so a task that has been clocked for 16 hours will be displayed
2990 as during 2 days in the clock display or in the clocktable.
2992 See `org-effort-durations' on how to set effort durations
2993 and `org-time-clocksum-format' for more on time clock formats."
2994 :group 'org-time
2995 :group 'org-clock
2996 :version "24.4"
2997 :package-version '(Org . "8.0")
2998 :type 'boolean)
3000 (defcustom org-time-clocksum-fractional-format "%.2f"
3001 "The format string used when creating CLOCKSUM lines,
3002 or when Org mode generates a time duration, if
3003 `org-time-clocksum-use-fractional' is enabled.
3005 The value can be a single format string containing one
3006 %-sequence, which will be filled with the number of hours as
3007 a float.
3009 Alternatively, the value can be a plist associating any of the
3010 keys :years, :months, :weeks, :days, :hours or :minutes with
3011 a format string. The time duration is formatted using the
3012 largest time unit which gives a non-zero integer part. If all
3013 specified formats have zero integer part, the smallest time unit
3014 is used."
3015 :group 'org-time
3016 :type '(choice (string :tag "Format string")
3017 (set (group :inline t (const :tag "Years" :years)
3018 (string :tag "Format string"))
3019 (group :inline t (const :tag "Months" :months)
3020 (string :tag "Format string"))
3021 (group :inline t (const :tag "Weeks" :weeks)
3022 (string :tag "Format string"))
3023 (group :inline t (const :tag "Days" :days)
3024 (string :tag "Format string"))
3025 (group :inline t (const :tag "Hours" :hours)
3026 (string :tag "Format string"))
3027 (group :inline t (const :tag "Minutes" :minutes)
3028 (string :tag "Format string")))))
3030 (defcustom org-deadline-warning-days 14
3031 "Number of days before expiration during which a deadline becomes active.
3032 This variable governs the display in sparse trees and in the agenda.
3033 When 0 or negative, it means use this number (the absolute value of it)
3034 even if a deadline has a different individual lead time specified.
3036 Custom commands can set this variable in the options section."
3037 :group 'org-time
3038 :group 'org-agenda-daily/weekly
3039 :type 'integer)
3041 (defcustom org-scheduled-delay-days 0
3042 "Number of days before a scheduled item becomes active.
3043 This variable governs the display in sparse trees and in the agenda.
3044 The default value (i.e. 0) means: don't delay scheduled item.
3045 When negative, it means use this number (the absolute value of it)
3046 even if a scheduled item has a different individual delay time
3047 specified.
3049 Custom commands can set this variable in the options section."
3050 :group 'org-time
3051 :group 'org-agenda-daily/weekly
3052 :version "24.4"
3053 :package-version '(Org . "8.0")
3054 :type 'integer)
3056 (defcustom org-read-date-prefer-future t
3057 "Non-nil means assume future for incomplete date input from user.
3058 This affects the following situations:
3059 1. The user gives a month but not a year.
3060 For example, if it is April and you enter \"feb 2\", this will be read
3061 as Feb 2, *next* year. \"May 5\", however, will be this year.
3062 2. The user gives a day, but no month.
3063 For example, if today is the 15th, and you enter \"3\", Org-mode will
3064 read this as the third of *next* month. However, if you enter \"17\",
3065 it will be considered as *this* month.
3067 If you set this variable to the symbol `time', then also the following
3068 will work:
3070 3. If the user gives a time.
3071 If the time is before now, it will be interpreted as tomorrow.
3073 Currently none of this works for ISO week specifications.
3075 When this option is nil, the current day, month and year will always be
3076 used as defaults.
3078 See also `org-agenda-jump-prefer-future'."
3079 :group 'org-time
3080 :type '(choice
3081 (const :tag "Never" nil)
3082 (const :tag "Check month and day" t)
3083 (const :tag "Check month, day, and time" time)))
3085 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3086 "Should the agenda jump command prefer the future for incomplete dates?
3087 The default is to do the same as configured in `org-read-date-prefer-future'.
3088 But you can also set a deviating value here.
3089 This may t or nil, or the symbol `org-read-date-prefer-future'."
3090 :group 'org-agenda
3091 :group 'org-time
3092 :version "24.1"
3093 :type '(choice
3094 (const :tag "Use org-read-date-prefer-future"
3095 org-read-date-prefer-future)
3096 (const :tag "Never" nil)
3097 (const :tag "Always" t)))
3099 (defcustom org-read-date-force-compatible-dates t
3100 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3102 Depending on the system Emacs is running on, certain dates cannot
3103 be represented with the type used internally to represent time.
3104 Dates between 1970-1-1 and 2038-1-1 can always be represented
3105 correctly. Some systems allow for earlier dates, some for later,
3106 some for both. One way to find out it to insert any date into an
3107 Org buffer, putting the cursor on the year and hitting S-up and
3108 S-down to test the range.
3110 When this variable is set to t, the date/time prompt will not let
3111 you specify dates outside the 1970-2037 range, so it is certain that
3112 these dates will work in whatever version of Emacs you are
3113 running, and also that you can move a file from one Emacs implementation
3114 to another. WHenever Org is forcing the year for you, it will display
3115 a message and beep.
3117 When this variable is nil, Org will check if the date is
3118 representable in the specific Emacs implementation you are using.
3119 If not, it will force a year, usually the current year, and beep
3120 to remind you. Currently this setting is not recommended because
3121 the likelihood that you will open your Org files in an Emacs that
3122 has limited date range is not negligible.
3124 A workaround for this problem is to use diary sexp dates for time
3125 stamps outside of this range."
3126 :group 'org-time
3127 :version "24.1"
3128 :type 'boolean)
3130 (defcustom org-read-date-display-live t
3131 "Non-nil means display current interpretation of date prompt live.
3132 This display will be in an overlay, in the minibuffer."
3133 :group 'org-time
3134 :type 'boolean)
3136 (defcustom org-read-date-popup-calendar t
3137 "Non-nil means pop up a calendar when prompting for a date.
3138 In the calendar, the date can be selected with mouse-1. However, the
3139 minibuffer will also be active, and you can simply enter the date as well.
3140 When nil, only the minibuffer will be available."
3141 :group 'org-time
3142 :type 'boolean)
3143 (org-defvaralias 'org-popup-calendar-for-date-prompt
3144 'org-read-date-popup-calendar)
3146 (make-obsolete-variable
3147 'org-read-date-minibuffer-setup-hook
3148 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3149 (defcustom org-read-date-minibuffer-setup-hook nil
3150 "Hook to be used to set up keys for the date/time interface.
3151 Add key definitions to `minibuffer-local-map', which will be a
3152 temporary copy.
3154 WARNING: This option is obsolete, you should use
3155 `org-read-date-minibuffer-local-map' to set up keys."
3156 :group 'org-time
3157 :type 'hook)
3159 (defcustom org-extend-today-until 0
3160 "The hour when your day really ends. Must be an integer.
3161 This has influence for the following applications:
3162 - When switching the agenda to \"today\". It it is still earlier than
3163 the time given here, the day recognized as TODAY is actually yesterday.
3164 - When a date is read from the user and it is still before the time given
3165 here, the current date and time will be assumed to be yesterday, 23:59.
3166 Also, timestamps inserted in capture templates follow this rule.
3168 IMPORTANT: This is a feature whose implementation is and likely will
3169 remain incomplete. Really, it is only here because past midnight seems to
3170 be the favorite working time of John Wiegley :-)"
3171 :group 'org-time
3172 :type 'integer)
3174 (defcustom org-use-effective-time nil
3175 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3176 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3177 \"effective time\" of any timestamps between midnight and 8am will be
3178 23:59 of the previous day."
3179 :group 'org-time
3180 :version "24.1"
3181 :type 'boolean)
3183 (defcustom org-use-last-clock-out-time-as-effective-time nil
3184 "When non-nil, use the last clock out time for `org-todo'.
3185 Note that this option has precedence over the combined use of
3186 `org-use-effective-time' and `org-extend-today-until'."
3187 :group 'org-time
3188 :version "24.4"
3189 :package-version '(Org . "8.0")
3190 :type 'boolean)
3192 (defcustom org-edit-timestamp-down-means-later nil
3193 "Non-nil means S-down will increase the time in a time stamp.
3194 When nil, S-up will increase."
3195 :group 'org-time
3196 :type 'boolean)
3198 (defcustom org-calendar-follow-timestamp-change t
3199 "Non-nil means make the calendar window follow timestamp changes.
3200 When a timestamp is modified and the calendar window is visible, it will be
3201 moved to the new date."
3202 :group 'org-time
3203 :type 'boolean)
3205 (defgroup org-tags nil
3206 "Options concerning tags in Org-mode."
3207 :tag "Org Tags"
3208 :group 'org)
3210 (defcustom org-tag-alist nil
3211 "List of tags allowed in Org-mode files.
3212 When this list is nil, Org-mode will base TAG input on what is already in the
3213 buffer.
3214 The value of this variable is an alist, the car of each entry must be a
3215 keyword as a string, the cdr may be a character that is used to select
3216 that tag through the fast-tag-selection interface.
3217 See the manual for details."
3218 :group 'org-tags
3219 :type '(repeat
3220 (choice
3221 (cons (string :tag "Tag name")
3222 (character :tag "Access char"))
3223 (list :tag "Start radio group"
3224 (const :startgroup)
3225 (option (string :tag "Group description")))
3226 (list :tag "Group tags delimiter"
3227 (const :grouptags))
3228 (list :tag "End radio group"
3229 (const :endgroup)
3230 (option (string :tag "Group description")))
3231 (const :tag "New line" (:newline)))))
3233 (defcustom org-tag-persistent-alist nil
3234 "List of tags that will always appear in all Org-mode files.
3235 This is in addition to any in buffer settings or customizations
3236 of `org-tag-alist'.
3237 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3238 The value of this variable is an alist, the car of each entry must be a
3239 keyword as a string, the cdr may be a character that is used to select
3240 that tag through the fast-tag-selection interface.
3241 See the manual for details.
3242 To disable these tags on a per-file basis, insert anywhere in the file:
3243 #+STARTUP: noptag"
3244 :group 'org-tags
3245 :type '(repeat
3246 (choice
3247 (cons (string :tag "Tag name")
3248 (character :tag "Access char"))
3249 (const :tag "Start radio group" (:startgroup))
3250 (const :tag "Group tags delimiter" (:grouptags))
3251 (const :tag "End radio group" (:endgroup))
3252 (const :tag "New line" (:newline)))))
3254 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3255 "If non-nil, always offer completion for all tags of all agenda files.
3256 Instead of customizing this variable directly, you might want to
3257 set it locally for capture buffers, because there no list of
3258 tags in that file can be created dynamically (there are none).
3260 (add-hook 'org-capture-mode-hook
3261 (lambda ()
3262 (set (make-local-variable
3263 'org-complete-tags-always-offer-all-agenda-tags)
3264 t)))"
3265 :group 'org-tags
3266 :version "24.1"
3267 :type 'boolean)
3269 (defvar org-file-tags nil
3270 "List of tags that can be inherited by all entries in the file.
3271 The tags will be inherited if the variable `org-use-tag-inheritance'
3272 says they should be.
3273 This variable is populated from #+FILETAGS lines.")
3275 (defcustom org-use-fast-tag-selection 'auto
3276 "Non-nil means use fast tag selection scheme.
3277 This is a special interface to select and deselect tags with single keys.
3278 When nil, fast selection is never used.
3279 When the symbol `auto', fast selection is used if and only if selection
3280 characters for tags have been configured, either through the variable
3281 `org-tag-alist' or through a #+TAGS line in the buffer.
3282 When t, fast selection is always used and selection keys are assigned
3283 automatically if necessary."
3284 :group 'org-tags
3285 :type '(choice
3286 (const :tag "Always" t)
3287 (const :tag "Never" nil)
3288 (const :tag "When selection characters are configured" auto)))
3290 (defcustom org-fast-tag-selection-single-key nil
3291 "Non-nil means fast tag selection exits after first change.
3292 When nil, you have to press RET to exit it.
3293 During fast tag selection, you can toggle this flag with `C-c'.
3294 This variable can also have the value `expert'. In this case, the window
3295 displaying the tags menu is not even shown, until you press C-c again."
3296 :group 'org-tags
3297 :type '(choice
3298 (const :tag "No" nil)
3299 (const :tag "Yes" t)
3300 (const :tag "Expert" expert)))
3302 (defvar org-fast-tag-selection-include-todo nil
3303 "Non-nil means fast tags selection interface will also offer TODO states.
3304 This is an undocumented feature, you should not rely on it.")
3306 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3307 "The column to which tags should be indented in a headline.
3308 If this number is positive, it specifies the column. If it is negative,
3309 it means that the tags should be flushright to that column. For example,
3310 -80 works well for a normal 80 character screen.
3311 When 0, place tags directly after headline text, with only one space in
3312 between."
3313 :group 'org-tags
3314 :type 'integer)
3316 (defcustom org-auto-align-tags t
3317 "Non-nil keeps tags aligned when modifying headlines.
3318 Some operations (i.e. demoting) change the length of a headline and
3319 therefore shift the tags around. With this option turned on, after
3320 each such operation the tags are again aligned to `org-tags-column'."
3321 :group 'org-tags
3322 :type 'boolean)
3324 (defcustom org-use-tag-inheritance t
3325 "Non-nil means tags in levels apply also for sublevels.
3326 When nil, only the tags directly given in a specific line apply there.
3327 This may also be a list of tags that should be inherited, or a regexp that
3328 matches tags that should be inherited. Additional control is possible
3329 with the variable `org-tags-exclude-from-inheritance' which gives an
3330 explicit list of tags to be excluded from inheritance, even if the value of
3331 `org-use-tag-inheritance' would select it for inheritance.
3333 If this option is t, a match early-on in a tree can lead to a large
3334 number of matches in the subtree when constructing the agenda or creating
3335 a sparse tree. If you only want to see the first match in a tree during
3336 a search, check out the variable `org-tags-match-list-sublevels'."
3337 :group 'org-tags
3338 :type '(choice
3339 (const :tag "Not" nil)
3340 (const :tag "Always" t)
3341 (repeat :tag "Specific tags" (string :tag "Tag"))
3342 (regexp :tag "Tags matched by regexp")))
3344 (defcustom org-tags-exclude-from-inheritance nil
3345 "List of tags that should never be inherited.
3346 This is a way to exclude a few tags from inheritance. For way to do
3347 the opposite, to actively allow inheritance for selected tags,
3348 see the variable `org-use-tag-inheritance'."
3349 :group 'org-tags
3350 :type '(repeat (string :tag "Tag")))
3352 (defun org-tag-inherit-p (tag)
3353 "Check if TAG is one that should be inherited."
3354 (cond
3355 ((member tag org-tags-exclude-from-inheritance) nil)
3356 ((eq org-use-tag-inheritance t) t)
3357 ((not org-use-tag-inheritance) nil)
3358 ((stringp org-use-tag-inheritance)
3359 (string-match org-use-tag-inheritance tag))
3360 ((listp org-use-tag-inheritance)
3361 (member tag org-use-tag-inheritance))
3362 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3364 (defcustom org-tags-match-list-sublevels t
3365 "Non-nil means list also sublevels of headlines matching a search.
3366 This variable applies to tags/property searches, and also to stuck
3367 projects because this search is based on a tags match as well.
3369 When set to the symbol `indented', sublevels are indented with
3370 leading dots.
3372 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3373 the sublevels of a headline matching a tag search often also match
3374 the same search. Listing all of them can create very long lists.
3375 Setting this variable to nil causes subtrees of a match to be skipped.
3377 This variable is semi-obsolete and probably should always be true. It
3378 is better to limit inheritance to certain tags using the variables
3379 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3380 :group 'org-tags
3381 :type '(choice
3382 (const :tag "No, don't list them" nil)
3383 (const :tag "Yes, do list them" t)
3384 (const :tag "List them, indented with leading dots" indented)))
3386 (defcustom org-tags-sort-function nil
3387 "When set, tags are sorted using this function as a comparator."
3388 :group 'org-tags
3389 :type '(choice
3390 (const :tag "No sorting" nil)
3391 (const :tag "Alphabetical" string<)
3392 (const :tag "Reverse alphabetical" string>)
3393 (function :tag "Custom function" nil)))
3395 (defvar org-tags-history nil
3396 "History of minibuffer reads for tags.")
3397 (defvar org-last-tags-completion-table nil
3398 "The last used completion table for tags.")
3399 (defvar org-after-tags-change-hook nil
3400 "Hook that is run after the tags in a line have changed.")
3402 (defgroup org-properties nil
3403 "Options concerning properties in Org-mode."
3404 :tag "Org Properties"
3405 :group 'org)
3407 (defcustom org-property-format "%-10s %s"
3408 "How property key/value pairs should be formatted by `indent-line'.
3409 When `indent-line' hits a property definition, it will format the line
3410 according to this format, mainly to make sure that the values are
3411 lined-up with respect to each other."
3412 :group 'org-properties
3413 :type 'string)
3415 (defcustom org-properties-postprocess-alist nil
3416 "Alist of properties and functions to adjust inserted values.
3417 Elements of this alist must be of the form
3419 ([string] [function])
3421 where [string] must be a property name and [function] must be a
3422 lambda expression: this lambda expression must take one argument,
3423 the value to adjust, and return the new value as a string.
3425 For example, this element will allow the property \"Remaining\"
3426 to be updated wrt the relation between the \"Effort\" property
3427 and the clock summary:
3429 ((\"Remaining\" (lambda(value)
3430 (let ((clocksum (org-clock-sum-current-item))
3431 (effort (org-duration-string-to-minutes
3432 (org-entry-get (point) \"Effort\"))))
3433 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3434 :group 'org-properties
3435 :version "24.1"
3436 :type '(alist :key-type (string :tag "Property")
3437 :value-type (function :tag "Function")))
3439 (defcustom org-use-property-inheritance nil
3440 "Non-nil means properties apply also for sublevels.
3442 This setting is chiefly used during property searches. Turning it on can
3443 cause significant overhead when doing a search, which is why it is not
3444 on by default.
3446 When nil, only the properties directly given in the current entry count.
3447 When t, every property is inherited. The value may also be a list of
3448 properties that should have inheritance, or a regular expression matching
3449 properties that should be inherited.
3451 However, note that some special properties use inheritance under special
3452 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3453 and the properties ending in \"_ALL\" when they are used as descriptor
3454 for valid values of a property.
3456 Note for programmers:
3457 When querying an entry with `org-entry-get', you can control if inheritance
3458 should be used. By default, `org-entry-get' looks only at the local
3459 properties. You can request inheritance by setting the inherit argument
3460 to t (to force inheritance) or to `selective' (to respect the setting
3461 in this variable)."
3462 :group 'org-properties
3463 :type '(choice
3464 (const :tag "Not" nil)
3465 (const :tag "Always" t)
3466 (repeat :tag "Specific properties" (string :tag "Property"))
3467 (regexp :tag "Properties matched by regexp")))
3469 (defun org-property-inherit-p (property)
3470 "Check if PROPERTY is one that should be inherited."
3471 (cond
3472 ((eq org-use-property-inheritance t) t)
3473 ((not org-use-property-inheritance) nil)
3474 ((stringp org-use-property-inheritance)
3475 (string-match org-use-property-inheritance property))
3476 ((listp org-use-property-inheritance)
3477 (member property org-use-property-inheritance))
3478 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3480 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3481 "The default column format, if no other format has been defined.
3482 This variable can be set on the per-file basis by inserting a line
3484 #+COLUMNS: %25ITEM ....."
3485 :group 'org-properties
3486 :type 'string)
3488 (defcustom org-columns-ellipses ".."
3489 "The ellipses to be used when a field in column view is truncated.
3490 When this is the empty string, as many characters as possible are shown,
3491 but then there will be no visual indication that the field has been truncated.
3492 When this is a string of length N, the last N characters of a truncated
3493 field are replaced by this string. If the column is narrower than the
3494 ellipses string, only part of the ellipses string will be shown."
3495 :group 'org-properties
3496 :type 'string)
3498 (defcustom org-columns-modify-value-for-display-function nil
3499 "Function that modifies values for display in column view.
3500 For example, it can be used to cut out a certain part from a time stamp.
3501 The function must take 2 arguments:
3503 column-title The title of the column (*not* the property name)
3504 value The value that should be modified.
3506 The function should return the value that should be displayed,
3507 or nil if the normal value should be used."
3508 :group 'org-properties
3509 :type '(choice (const nil) (function)))
3511 (defcustom org-effort-property "Effort"
3512 "The property that is being used to keep track of effort estimates.
3513 Effort estimates given in this property need to have the format H:MM."
3514 :group 'org-properties
3515 :group 'org-progress
3516 :type '(string :tag "Property"))
3518 (defconst org-global-properties-fixed
3519 '(("VISIBILITY_ALL" . "folded children content all")
3520 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3521 "List of property/value pairs that can be inherited by any entry.
3523 These are fixed values, for the preset properties. The user variable
3524 that can be used to add to this list is `org-global-properties'.
3526 The entries in this list are cons cells where the car is a property
3527 name and cdr is a string with the value. If the value represents
3528 multiple items like an \"_ALL\" property, separate the items by
3529 spaces.")
3531 (defcustom org-global-properties nil
3532 "List of property/value pairs that can be inherited by any entry.
3534 This list will be combined with the constant `org-global-properties-fixed'.
3536 The entries in this list are cons cells where the car is a property
3537 name and cdr is a string with the value.
3539 You can set buffer-local values for the same purpose in the variable
3540 `org-file-properties' this by adding lines like
3542 #+PROPERTY: NAME VALUE"
3543 :group 'org-properties
3544 :type '(repeat
3545 (cons (string :tag "Property")
3546 (string :tag "Value"))))
3548 (defvar org-file-properties nil
3549 "List of property/value pairs that can be inherited by any entry.
3550 Valid for the current buffer.
3551 This variable is populated from #+PROPERTY lines.")
3552 (make-variable-buffer-local 'org-file-properties)
3554 (defgroup org-agenda nil
3555 "Options concerning agenda views in Org-mode."
3556 :tag "Org Agenda"
3557 :group 'org)
3559 (defvar org-category nil
3560 "Variable used by org files to set a category for agenda display.
3561 Such files should use a file variable to set it, for example
3563 # -*- mode: org; org-category: \"ELisp\"
3565 or contain a special line
3567 #+CATEGORY: ELisp
3569 If the file does not specify a category, then file's base name
3570 is used instead.")
3571 (make-variable-buffer-local 'org-category)
3572 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3574 (defcustom org-agenda-files nil
3575 "The files to be used for agenda display.
3576 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3577 \\[org-remove-file]. You can also use customize to edit the list.
3579 If an entry is a directory, all files in that directory that are matched by
3580 `org-agenda-file-regexp' will be part of the file list.
3582 If the value of the variable is not a list but a single file name, then
3583 the list of agenda files is actually stored and maintained in that file, one
3584 agenda file per line. In this file paths can be given relative to
3585 `org-directory'. Tilde expansion and environment variable substitution
3586 are also made."
3587 :group 'org-agenda
3588 :type '(choice
3589 (repeat :tag "List of files and directories" file)
3590 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3592 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3593 "Regular expression to match files for `org-agenda-files'.
3594 If any element in the list in that variable contains a directory instead
3595 of a normal file, all files in that directory that are matched by this
3596 regular expression will be included."
3597 :group 'org-agenda
3598 :type 'regexp)
3600 (defcustom org-agenda-text-search-extra-files nil
3601 "List of extra files to be searched by text search commands.
3602 These files will be searched in addition to the agenda files by the
3603 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3604 Note that these files will only be searched for text search commands,
3605 not for the other agenda views like todo lists, tag searches or the weekly
3606 agenda. This variable is intended to list notes and possibly archive files
3607 that should also be searched by these two commands.
3608 In fact, if the first element in the list is the symbol `agenda-archives',
3609 then all archive files of all agenda files will be added to the search
3610 scope."
3611 :group 'org-agenda
3612 :type '(set :greedy t
3613 (const :tag "Agenda Archives" agenda-archives)
3614 (repeat :inline t (file))))
3616 (org-defvaralias 'org-agenda-multi-occur-extra-files
3617 'org-agenda-text-search-extra-files)
3619 (defcustom org-agenda-skip-unavailable-files nil
3620 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3621 A nil value means to remove them, after a query, from the list."
3622 :group 'org-agenda
3623 :type 'boolean)
3625 (defcustom org-calendar-to-agenda-key [?c]
3626 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3627 The command `org-calendar-goto-agenda' will be bound to this key. The
3628 default is the character `c' because then `c' can be used to switch back and
3629 forth between agenda and calendar."
3630 :group 'org-agenda
3631 :type 'sexp)
3633 (defcustom org-calendar-insert-diary-entry-key [?i]
3634 "The key to be installed in `calendar-mode-map' for adding diary entries.
3635 This option is irrelevant until `org-agenda-diary-file' has been configured
3636 to point to an Org-mode file. When that is the case, the command
3637 `org-agenda-diary-entry' will be bound to the key given here, by default
3638 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3639 if you want to continue doing this, you need to change this to a different
3640 key."
3641 :group 'org-agenda
3642 :type 'sexp)
3644 (defcustom org-agenda-diary-file 'diary-file
3645 "File to which to add new entries with the `i' key in agenda and calendar.
3646 When this is the symbol `diary-file', the functionality in the Emacs
3647 calendar will be used to add entries to the `diary-file'. But when this
3648 points to a file, `org-agenda-diary-entry' will be used instead."
3649 :group 'org-agenda
3650 :type '(choice
3651 (const :tag "The standard Emacs diary file" diary-file)
3652 (file :tag "Special Org file diary entries")))
3654 (eval-after-load "calendar"
3655 '(progn
3656 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3657 'org-calendar-goto-agenda)
3658 (add-hook 'calendar-mode-hook
3659 (lambda ()
3660 (unless (eq org-agenda-diary-file 'diary-file)
3661 (define-key calendar-mode-map
3662 org-calendar-insert-diary-entry-key
3663 'org-agenda-diary-entry))))))
3665 (defgroup org-latex nil
3666 "Options for embedding LaTeX code into Org-mode."
3667 :tag "Org LaTeX"
3668 :group 'org)
3670 (defcustom org-format-latex-options
3671 '(:foreground default :background default :scale 1.0
3672 :html-foreground "Black" :html-background "Transparent"
3673 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3674 "Options for creating images from LaTeX fragments.
3675 This is a property list with the following properties:
3676 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3677 `default' means use the foreground of the default face.
3678 `auto' means use the foreground from the text face.
3679 :background the background color, or \"Transparent\".
3680 `default' means use the background of the default face.
3681 `auto' means use the background from the text face.
3682 :scale a scaling factor for the size of the images, to get more pixels
3683 :html-foreground, :html-background, :html-scale
3684 the same numbers for HTML export.
3685 :matchers a list indicating which matchers should be used to
3686 find LaTeX fragments. Valid members of this list are:
3687 \"begin\" find environments
3688 \"$1\" find single characters surrounded by $.$
3689 \"$\" find math expressions surrounded by $...$
3690 \"$$\" find math expressions surrounded by $$....$$
3691 \"\\(\" find math expressions surrounded by \\(...\\)
3692 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3693 :group 'org-latex
3694 :type 'plist)
3696 (defcustom org-format-latex-signal-error t
3697 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3698 When nil, just push out a message."
3699 :group 'org-latex
3700 :version "24.1"
3701 :type 'boolean)
3703 (defcustom org-latex-to-mathml-jar-file nil
3704 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3705 Use this to specify additional executable file say a jar file.
3707 When using MathToWeb as the converter, specify the full-path to
3708 your mathtoweb.jar file."
3709 :group 'org-latex
3710 :version "24.1"
3711 :type '(choice
3712 (const :tag "None" nil)
3713 (file :tag "JAR file" :must-match t)))
3715 (defcustom org-latex-to-mathml-convert-command nil
3716 "Command to convert LaTeX fragments to MathML.
3717 Replace format-specifiers in the command as noted below and use
3718 `shell-command' to convert LaTeX to MathML.
3719 %j: Executable file in fully expanded form as specified by
3720 `org-latex-to-mathml-jar-file'.
3721 %I: Input LaTeX file in fully expanded form
3722 %o: Output MathML file
3723 This command is used by `org-create-math-formula'.
3725 When using MathToWeb as the converter, set this to
3726 \"java -jar %j -unicode -force -df %o %I\"."
3727 :group 'org-latex
3728 :version "24.1"
3729 :type '(choice
3730 (const :tag "None" nil)
3731 (string :tag "\nShell command")))
3733 (defcustom org-latex-create-formula-image-program 'dvipng
3734 "Program to convert LaTeX fragments with.
3736 dvipng Process the LaTeX fragments to dvi file, then convert
3737 dvi files to png files using dvipng.
3738 This will also include processing of non-math environments.
3739 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3740 to convert pdf files to png files"
3741 :group 'org-latex
3742 :version "24.1"
3743 :type '(choice
3744 (const :tag "dvipng" dvipng)
3745 (const :tag "imagemagick" imagemagick)))
3747 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3748 "Path to store latex preview images.
3749 A relative path here creates many directories relative to the
3750 processed org files paths. An absolute path puts all preview
3751 images at the same place."
3752 :group 'org-latex
3753 :version "24.3"
3754 :type 'string)
3756 (defun org-format-latex-mathml-available-p ()
3757 "Return t if `org-latex-to-mathml-convert-command' is usable."
3758 (save-match-data
3759 (when (and (boundp 'org-latex-to-mathml-convert-command)
3760 org-latex-to-mathml-convert-command)
3761 (let ((executable (car (split-string
3762 org-latex-to-mathml-convert-command))))
3763 (when (executable-find executable)
3764 (if (string-match
3765 "%j" org-latex-to-mathml-convert-command)
3766 (file-readable-p org-latex-to-mathml-jar-file)
3767 t))))))
3769 (defcustom org-format-latex-header "\\documentclass{article}
3770 \\usepackage[usenames]{color}
3771 \[PACKAGES]
3772 \[DEFAULT-PACKAGES]
3773 \\pagestyle{empty} % do not remove
3774 % The settings below are copied from fullpage.sty
3775 \\setlength{\\textwidth}{\\paperwidth}
3776 \\addtolength{\\textwidth}{-3cm}
3777 \\setlength{\\oddsidemargin}{1.5cm}
3778 \\addtolength{\\oddsidemargin}{-2.54cm}
3779 \\setlength{\\evensidemargin}{\\oddsidemargin}
3780 \\setlength{\\textheight}{\\paperheight}
3781 \\addtolength{\\textheight}{-\\headheight}
3782 \\addtolength{\\textheight}{-\\headsep}
3783 \\addtolength{\\textheight}{-\\footskip}
3784 \\addtolength{\\textheight}{-3cm}
3785 \\setlength{\\topmargin}{1.5cm}
3786 \\addtolength{\\topmargin}{-2.54cm}"
3787 "The document header used for processing LaTeX fragments.
3788 It is imperative that this header make sure that no page number
3789 appears on the page. The package defined in the variables
3790 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3791 will either replace the placeholder \"[PACKAGES]\" in this
3792 header, or they will be appended."
3793 :group 'org-latex
3794 :type 'string)
3796 (defun org-set-packages-alist (var val)
3797 "Set the packages alist and make sure it has 3 elements per entry."
3798 (set var (mapcar (lambda (x)
3799 (if (and (consp x) (= (length x) 2))
3800 (list (car x) (nth 1 x) t)
3802 val)))
3804 (defun org-get-packages-alist (var)
3805 "Get the packages alist and make sure it has 3 elements per entry."
3806 (mapcar (lambda (x)
3807 (if (and (consp x) (= (length x) 2))
3808 (list (car x) (nth 1 x) t)
3810 (default-value var)))
3812 (defcustom org-latex-default-packages-alist
3813 '(("AUTO" "inputenc" t)
3814 ("T1" "fontenc" t)
3815 ("" "fixltx2e" nil)
3816 ("" "graphicx" t)
3817 ("" "longtable" nil)
3818 ("" "float" nil)
3819 ("" "wrapfig" nil)
3820 ("" "rotating" nil)
3821 ("normalem" "ulem" t)
3822 ("" "amsmath" t)
3823 ("" "textcomp" t)
3824 ("" "marvosym" t)
3825 ("" "wasysym" t)
3826 ("" "amssymb" t)
3827 ("" "hyperref" nil)
3828 "\\tolerance=1000")
3829 "Alist of default packages to be inserted in the header.
3831 Change this only if one of the packages here causes an
3832 incompatibility with another package you are using.
3834 The packages in this list are needed by one part or another of
3835 Org mode to function properly:
3837 - inputenc, fontenc: for basic font and character selection
3838 - fixltx2e: Important patches of LaTeX itself
3839 - graphicx: for including images
3840 - longtable: For multipage tables
3841 - float, wrapfig: for figure placement
3842 - rotating: for sideways figures and tables
3843 - ulem: for underline and strike-through
3844 - amsmath: for subscript and superscript and math environments
3845 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3846 for interpreting the entities in `org-entities'. You can skip
3847 some of these packages if you don't use any of their symbols.
3848 - hyperref: for cross references
3850 Therefore you should not modify this variable unless you know
3851 what you are doing. The one reason to change it anyway is that
3852 you might be loading some other package that conflicts with one
3853 of the default packages. Each cell is of the format
3854 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3855 the package also needs to be included when compiling LaTeX
3856 snippets into images for inclusion into non-LaTeX output."
3857 :group 'org-latex
3858 :group 'org-export-latex
3859 :set 'org-set-packages-alist
3860 :get 'org-get-packages-alist
3861 :version "24.1"
3862 :type '(repeat
3863 (choice
3864 (list :tag "options/package pair"
3865 (string :tag "options")
3866 (string :tag "package")
3867 (boolean :tag "Snippet"))
3868 (string :tag "A line of LaTeX"))))
3870 (defcustom org-latex-packages-alist nil
3871 "Alist of packages to be inserted in every LaTeX header.
3873 These will be inserted after `org-latex-default-packages-alist'.
3874 Each cell is of the format:
3876 \(\"options\" \"package\" snippet-flag)
3878 SNIPPET-FLAG, when t, indicates that this package is also needed
3879 when turning LaTeX snippets into images for inclusion into
3880 non-LaTeX output.
3882 Make sure that you only list packages here which:
3884 - you want in every file
3885 - do not conflict with the setup in `org-format-latex-header'.
3886 - do not conflict with the default packages in
3887 `org-latex-default-packages-alist'."
3888 :group 'org-latex
3889 :group 'org-export-latex
3890 :set 'org-set-packages-alist
3891 :get 'org-get-packages-alist
3892 :type '(repeat
3893 (choice
3894 (list :tag "options/package pair"
3895 (string :tag "options")
3896 (string :tag "package")
3897 (boolean :tag "Snippet"))
3898 (string :tag "A line of LaTeX"))))
3900 (defgroup org-appearance nil
3901 "Settings for Org-mode appearance."
3902 :tag "Org Appearance"
3903 :group 'org)
3905 (defcustom org-level-color-stars-only nil
3906 "Non-nil means fontify only the stars in each headline.
3907 When nil, the entire headline is fontified.
3908 Changing it requires restart of `font-lock-mode' to become effective
3909 also in regions already fontified."
3910 :group 'org-appearance
3911 :type 'boolean)
3913 (defcustom org-hide-leading-stars nil
3914 "Non-nil means hide the first N-1 stars in a headline.
3915 This works by using the face `org-hide' for these stars. This
3916 face is white for a light background, and black for a dark
3917 background. You may have to customize the face `org-hide' to
3918 make this work.
3919 Changing it requires restart of `font-lock-mode' to become effective
3920 also in regions already fontified.
3921 You may also set this on a per-file basis by adding one of the following
3922 lines to the buffer:
3924 #+STARTUP: hidestars
3925 #+STARTUP: showstars"
3926 :group 'org-appearance
3927 :type 'boolean)
3929 (defcustom org-hidden-keywords nil
3930 "List of symbols corresponding to keywords to be hidden the org buffer.
3931 For example, a value '(title) for this list will make the document's title
3932 appear in the buffer without the initial #+TITLE: keyword."
3933 :group 'org-appearance
3934 :version "24.1"
3935 :type '(set (const :tag "#+AUTHOR" author)
3936 (const :tag "#+DATE" date)
3937 (const :tag "#+EMAIL" email)
3938 (const :tag "#+TITLE" title)))
3940 (defcustom org-custom-properties nil
3941 "List of properties (as strings) with a special meaning.
3942 The default use of these custom properties is to let the user
3943 hide them with `org-toggle-custom-properties-visibility'."
3944 :group 'org-properties
3945 :group 'org-appearance
3946 :version "24.3"
3947 :type '(repeat (string :tag "Property Name")))
3949 (defcustom org-fontify-done-headline nil
3950 "Non-nil means change the face of a headline if it is marked DONE.
3951 Normally, only the TODO/DONE keyword indicates the state of a headline.
3952 When this is non-nil, the headline after the keyword is set to the
3953 `org-headline-done' as an additional indication."
3954 :group 'org-appearance
3955 :type 'boolean)
3957 (defcustom org-fontify-emphasized-text t
3958 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3959 Changing this variable requires a restart of Emacs to take effect."
3960 :group 'org-appearance
3961 :type 'boolean)
3963 (defcustom org-fontify-whole-heading-line nil
3964 "Non-nil means fontify the whole line for headings.
3965 This is useful when setting a background color for the
3966 org-level-* faces."
3967 :group 'org-appearance
3968 :type 'boolean)
3970 (defcustom org-highlight-latex-and-related nil
3971 "Non-nil means highlight LaTeX related syntax in the buffer.
3972 When non nil, the value should be a list containing any of the
3973 following symbols:
3974 `latex' Highlight LaTeX snippets and environments.
3975 `script' Highlight subscript and superscript.
3976 `entities' Highlight entities."
3977 :group 'org-appearance
3978 :version "24.4"
3979 :package-version '(Org . "8.0")
3980 :type '(choice
3981 (const :tag "No highlighting" nil)
3982 (set :greedy t :tag "Highlight"
3983 (const :tag "LaTeX snippets and environments" latex)
3984 (const :tag "Subscript and superscript" script)
3985 (const :tag "Entities" entities))))
3987 (defcustom org-hide-emphasis-markers nil
3988 "Non-nil mean font-lock should hide the emphasis marker characters."
3989 :group 'org-appearance
3990 :type 'boolean)
3992 (defcustom org-pretty-entities nil
3993 "Non-nil means show entities as UTF8 characters.
3994 When nil, the \\name form remains in the buffer."
3995 :group 'org-appearance
3996 :version "24.1"
3997 :type 'boolean)
3999 (defcustom org-pretty-entities-include-sub-superscripts t
4000 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4001 :group 'org-appearance
4002 :version "24.1"
4003 :type 'boolean)
4005 (defvar org-emph-re nil
4006 "Regular expression for matching emphasis.
4007 After a match, the match groups contain these elements:
4008 0 The match of the full regular expression, including the characters
4009 before and after the proper match
4010 1 The character before the proper match, or empty at beginning of line
4011 2 The proper match, including the leading and trailing markers
4012 3 The leading marker like * or /, indicating the type of highlighting
4013 4 The text between the emphasis markers, not including the markers
4014 5 The character after the match, empty at the end of a line")
4015 (defvar org-verbatim-re nil
4016 "Regular expression for matching verbatim text.")
4017 (defvar org-emphasis-regexp-components) ; defined just below
4018 (defvar org-emphasis-alist) ; defined just below
4019 (defun org-set-emph-re (var val)
4020 "Set variable and compute the emphasis regular expression."
4021 (set var val)
4022 (when (and (boundp 'org-emphasis-alist)
4023 (boundp 'org-emphasis-regexp-components)
4024 org-emphasis-alist org-emphasis-regexp-components)
4025 (let* ((e org-emphasis-regexp-components)
4026 (pre (car e))
4027 (post (nth 1 e))
4028 (border (nth 2 e))
4029 (body (nth 3 e))
4030 (nl (nth 4 e))
4031 (body1 (concat body "*?"))
4032 (markers (mapconcat 'car org-emphasis-alist ""))
4033 (vmarkers (mapconcat
4034 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4035 org-emphasis-alist "")))
4036 ;; make sure special characters appear at the right position in the class
4037 (if (string-match "\\^" markers)
4038 (setq markers (concat (replace-match "" t t markers) "^")))
4039 (if (string-match "-" markers)
4040 (setq markers (concat (replace-match "" t t markers) "-")))
4041 (if (string-match "\\^" vmarkers)
4042 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4043 (if (string-match "-" vmarkers)
4044 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4045 (if (> nl 0)
4046 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4047 (int-to-string nl) "\\}")))
4048 ;; Make the regexp
4049 (setq org-emph-re
4050 (concat "\\([" pre "]\\|^\\)"
4051 "\\("
4052 "\\([" markers "]\\)"
4053 "\\("
4054 "[^" border "]\\|"
4055 "[^" border "]"
4056 body1
4057 "[^" border "]"
4058 "\\)"
4059 "\\3\\)"
4060 "\\([" post "]\\|$\\)"))
4061 (setq org-verbatim-re
4062 (concat "\\([" pre "]\\|^\\)"
4063 "\\("
4064 "\\([" vmarkers "]\\)"
4065 "\\("
4066 "[^" border "]\\|"
4067 "[^" border "]"
4068 body1
4069 "[^" border "]"
4070 "\\)"
4071 "\\3\\)"
4072 "\\([" post "]\\|$\\)")))))
4074 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4075 ;; set this option proved cumbersome. See this message/thread:
4076 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4077 (defvar org-emphasis-regexp-components
4078 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4079 "Components used to build the regular expression for emphasis.
4080 This is a list with five entries. Terminology: In an emphasis string
4081 like \" *strong word* \", we call the initial space PREMATCH, the final
4082 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4083 and \"trong wor\" is the body. The different components in this variable
4084 specify what is allowed/forbidden in each part:
4086 pre Chars allowed as prematch. Beginning of line will be allowed too.
4087 post Chars allowed as postmatch. End of line will be allowed too.
4088 border The chars *forbidden* as border characters.
4089 body-regexp A regexp like \".\" to match a body character. Don't use
4090 non-shy groups here, and don't allow newline here.
4091 newline The maximum number of newlines allowed in an emphasis exp.
4093 You need to reload Org or to restart Emacs after customizing this.")
4095 (defcustom org-emphasis-alist
4096 `(("*" bold)
4097 ("/" italic)
4098 ("_" underline)
4099 ("=" org-code verbatim)
4100 ("~" org-verbatim verbatim)
4101 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4102 "Alist of characters and faces to emphasize text.
4103 Text starting and ending with a special character will be emphasized,
4104 for example *bold*, _underlined_ and /italic/. This variable sets the
4105 marker characters and the face to be used by font-lock for highlighting
4106 in Org-mode Emacs buffers.
4108 You need to reload Org or to restart Emacs after customizing this."
4109 :group 'org-appearance
4110 :set 'org-set-emph-re
4111 :version "24.4"
4112 :package-version '(Org . "8.0")
4113 :type '(repeat
4114 (list
4115 (string :tag "Marker character")
4116 (choice
4117 (face :tag "Font-lock-face")
4118 (plist :tag "Face property list"))
4119 (option (const verbatim)))))
4121 (defvar org-protecting-blocks
4122 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4123 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4124 This is needed for font-lock setup.")
4126 ;;; Miscellaneous options
4128 (defgroup org-completion nil
4129 "Completion in Org-mode."
4130 :tag "Org Completion"
4131 :group 'org)
4133 (defcustom org-completion-use-ido nil
4134 "Non-nil means use ido completion wherever possible.
4135 Note that `ido-mode' must be active for this variable to be relevant.
4136 If you decide to turn this variable on, you might well want to turn off
4137 `org-outline-path-complete-in-steps'.
4138 See also `org-completion-use-iswitchb'."
4139 :group 'org-completion
4140 :type 'boolean)
4142 (defcustom org-completion-use-iswitchb nil
4143 "Non-nil means use iswitchb completion wherever possible.
4144 Note that `iswitchb-mode' must be active for this variable to be relevant.
4145 If you decide to turn this variable on, you might well want to turn off
4146 `org-outline-path-complete-in-steps'.
4147 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4148 :group 'org-completion
4149 :type 'boolean)
4151 (defcustom org-completion-fallback-command 'hippie-expand
4152 "The expansion command called by \\[pcomplete] in normal context.
4153 Normal means, no org-mode-specific context."
4154 :group 'org-completion
4155 :type 'function)
4157 ;;; Functions and variables from their packages
4158 ;; Declared here to avoid compiler warnings
4160 ;; XEmacs only
4161 (defvar outline-mode-menu-heading)
4162 (defvar outline-mode-menu-show)
4163 (defvar outline-mode-menu-hide)
4164 (defvar zmacs-regions) ; XEmacs regions
4166 ;; Emacs only
4167 (defvar mark-active)
4169 ;; Various packages
4170 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4171 (declare-function calendar-forward-day "cal-move" (arg))
4172 (declare-function calendar-goto-date "cal-move" (date))
4173 (declare-function calendar-goto-today "cal-move" ())
4174 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4175 (defvar calc-embedded-close-formula)
4176 (defvar calc-embedded-open-formula)
4177 (declare-function cdlatex-tab "ext:cdlatex" ())
4178 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4179 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4180 (defvar font-lock-unfontify-region-function)
4181 (declare-function iswitchb-read-buffer "iswitchb"
4182 (prompt &optional default require-match start matches-set))
4183 (defvar iswitchb-temp-buflist)
4184 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4185 (defvar org-agenda-tags-todo-honor-ignore-options)
4186 (declare-function org-agenda-skip "org-agenda" ())
4187 (declare-function
4188 org-agenda-format-item "org-agenda"
4189 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4190 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4191 (declare-function org-agenda-change-all-lines "org-agenda"
4192 (newhead hdmarker &optional fixface just-this))
4193 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4194 (declare-function org-agenda-maybe-redo "org-agenda" ())
4195 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4196 (beg end))
4197 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4198 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4199 "org-agenda" (&optional end))
4200 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4201 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4202 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4203 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4204 (declare-function org-indent-mode "org-indent" (&optional arg))
4205 (declare-function parse-time-string "parse-time" (string))
4206 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4207 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4208 (defvar remember-data-file)
4209 (defvar texmathp-why)
4210 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4211 (declare-function table--at-cell-p "table" (position &optional object at-column))
4213 (defvar org-latex-regexps)
4215 ;;; Autoload and prepare some org modules
4217 ;; Some table stuff that needs to be defined here, because it is used
4218 ;; by the functions setting up org-mode or checking for table context.
4220 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4221 "Detect an org-type or table-type table.")
4222 (defconst org-table-line-regexp "^[ \t]*|"
4223 "Detect an org-type table line.")
4224 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4225 "Detect an org-type table line.")
4226 (defconst org-table-hline-regexp "^[ \t]*|-"
4227 "Detect an org-type table hline.")
4228 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4229 "Detect a table-type table hline.")
4230 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4231 "Detect the first line outside a table when searching from within it.
4232 This works for both table types.")
4234 ;; Autoload the functions in org-table.el that are needed by functions here.
4236 (eval-and-compile
4237 (org-autoload "org-table"
4238 '(org-table-begin org-table-blank-field org-table-end)))
4240 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4241 "Detect a #+TBLFM line.")
4243 ;;;###autoload
4244 (defun turn-on-orgtbl ()
4245 "Unconditionally turn on `orgtbl-mode'."
4246 (require 'org-table)
4247 (orgtbl-mode 1))
4249 (defun org-at-table-p (&optional table-type)
4250 "Return t if the cursor is inside an org-type table.
4251 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4252 (if org-enable-table-editor
4253 (save-excursion
4254 (beginning-of-line 1)
4255 (looking-at (if table-type org-table-any-line-regexp
4256 org-table-line-regexp)))
4257 nil))
4258 (defsubst org-table-p () (org-at-table-p))
4260 (defun org-at-table.el-p ()
4261 "Return t if and only if we are at a table.el table."
4262 (and (org-at-table-p 'any)
4263 (save-excursion
4264 (goto-char (org-table-begin 'any))
4265 (looking-at org-table1-hline-regexp))))
4267 (defun org-table-recognize-table.el ()
4268 "If there is a table.el table nearby, recognize it and move into it."
4269 (if org-table-tab-recognizes-table.el
4270 (if (org-at-table.el-p)
4271 (progn
4272 (beginning-of-line 1)
4273 (if (looking-at org-table-dataline-regexp)
4275 (if (looking-at org-table1-hline-regexp)
4276 (progn
4277 (beginning-of-line 2)
4278 (if (looking-at org-table-any-border-regexp)
4279 (beginning-of-line -1)))))
4280 (if (re-search-forward "|" (org-table-end t) t)
4281 (progn
4282 (require 'table)
4283 (if (table--at-cell-p (point))
4285 (message "recognizing table.el table...")
4286 (table-recognize-table)
4287 (message "recognizing table.el table...done")))
4288 (error "This should not happen"))
4290 nil)
4291 nil))
4293 (defun org-at-table-hline-p ()
4294 "Return t if the cursor is inside a hline in a table."
4295 (if org-enable-table-editor
4296 (save-excursion
4297 (beginning-of-line 1)
4298 (looking-at org-table-hline-regexp))
4299 nil))
4301 (defun org-table-map-tables (function &optional quietly)
4302 "Apply FUNCTION to the start of all tables in the buffer."
4303 (save-excursion
4304 (save-restriction
4305 (widen)
4306 (goto-char (point-min))
4307 (while (re-search-forward org-table-any-line-regexp nil t)
4308 (unless quietly
4309 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4310 (beginning-of-line 1)
4311 (when (and (looking-at org-table-line-regexp)
4312 ;; Exclude tables in src/example/verbatim/clocktable blocks
4313 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4314 (save-excursion (funcall function))
4315 (or (looking-at org-table-line-regexp)
4316 (forward-char 1)))
4317 (re-search-forward org-table-any-border-regexp nil 1))))
4318 (unless quietly (message "Mapping tables: done")))
4320 ;; Declare and autoload functions from org-agenda.el
4322 (eval-and-compile
4323 (org-autoload "org-agenda"
4324 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4326 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4327 (declare-function org-clock-update-mode-line "org-clock" ())
4328 (declare-function org-resolve-clocks "org-clock"
4329 (&optional also-non-dangling-p prompt last-valid))
4331 (defun org-at-TBLFM-p (&optional pos)
4332 "Return t when point (or POS) is in #+TBLFM line."
4333 (save-excursion
4334 (let ((pos pos)))
4335 (goto-char (or pos (point)))
4336 (beginning-of-line 1)
4337 (looking-at org-TBLFM-regexp)))
4339 (defvar org-clock-start-time)
4340 (defvar org-clock-marker (make-marker)
4341 "Marker recording the last clock-in.")
4342 (defvar org-clock-hd-marker (make-marker)
4343 "Marker recording the last clock-in, but the headline position.")
4344 (defvar org-clock-heading ""
4345 "The heading of the current clock entry.")
4346 (defun org-clock-is-active ()
4347 "Return the buffer where the clock is currently running.
4348 Return nil if no clock is running."
4349 (marker-buffer org-clock-marker))
4351 (eval-and-compile
4352 (org-autoload "org-clock" '(org-clock-remove-overlays
4353 org-clock-update-time-maybe
4354 org-clocktable-shift)))
4356 (defun org-check-running-clock ()
4357 "Check if the current buffer contains the running clock.
4358 If yes, offer to stop it and to save the buffer with the changes."
4359 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4360 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4361 (buffer-name))))
4362 (org-clock-out)
4363 (when (y-or-n-p "Save changed buffer?")
4364 (save-buffer))))
4366 (defun org-clocktable-try-shift (dir n)
4367 "Check if this line starts a clock table, if yes, shift the time block."
4368 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4369 (org-clocktable-shift dir n)))
4371 ;;;###autoload
4372 (defun org-clock-persistence-insinuate ()
4373 "Set up hooks for clock persistence."
4374 (require 'org-clock)
4375 (add-hook 'org-mode-hook 'org-clock-load)
4376 (add-hook 'kill-emacs-hook 'org-clock-save))
4378 ;; Define the variable already here, to make sure we have it.
4379 (defvar org-indent-mode nil
4380 "Non-nil if Org-Indent mode is enabled.
4381 Use the command `org-indent-mode' to change this variable.")
4383 ;; Autoload archiving code
4384 ;; The stuff that is needed for cycling and tags has to be defined here.
4386 (defgroup org-archive nil
4387 "Options concerning archiving in Org-mode."
4388 :tag "Org Archive"
4389 :group 'org-structure)
4391 (defcustom org-archive-location "%s_archive::"
4392 "The location where subtrees should be archived.
4394 The value of this variable is a string, consisting of two parts,
4395 separated by a double-colon. The first part is a filename and
4396 the second part is a headline.
4398 When the filename is omitted, archiving happens in the same file.
4399 %s in the filename will be replaced by the current file
4400 name (without the directory part). Archiving to a different file
4401 is useful to keep archived entries from contributing to the
4402 Org-mode Agenda.
4404 The archived entries will be filed as subtrees of the specified
4405 headline. When the headline is omitted, the subtrees are simply
4406 filed away at the end of the file, as top-level entries. Also in
4407 the heading you can use %s to represent the file name, this can be
4408 useful when using the same archive for a number of different files.
4410 Here are a few examples:
4411 \"%s_archive::\"
4412 If the current file is Projects.org, archive in file
4413 Projects.org_archive, as top-level trees. This is the default.
4415 \"::* Archived Tasks\"
4416 Archive in the current file, under the top-level headline
4417 \"* Archived Tasks\".
4419 \"~/org/archive.org::\"
4420 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4422 \"~/org/archive.org::* From %s\"
4423 Archive in file ~/org/archive.org (absolute path), under headlines
4424 \"From FILENAME\" where file name is the current file name.
4426 \"~/org/datetree.org::datetree/* Finished Tasks\"
4427 The \"datetree/\" string is special, signifying to archive
4428 items to the datetree. Items are placed in either the CLOSED
4429 date of the item, or the current date if there is no CLOSED date.
4430 The heading will be a subentry to the current date. There doesn't
4431 need to be a heading, but there always needs to be a slash after
4432 datetree. For example, to store archived items directly in the
4433 datetree, use \"~/org/datetree.org::datetree/\".
4435 \"basement::** Finished Tasks\"
4436 Archive in file ./basement (relative path), as level 3 trees
4437 below the level 2 heading \"** Finished Tasks\".
4439 You may set this option on a per-file basis by adding to the buffer a
4440 line like
4442 #+ARCHIVE: basement::** Finished Tasks
4444 You may also define it locally for a subtree by setting an ARCHIVE property
4445 in the entry. If such a property is found in an entry, or anywhere up
4446 the hierarchy, it will be used."
4447 :group 'org-archive
4448 :type 'string)
4450 (defcustom org-archive-tag "ARCHIVE"
4451 "The tag that marks a subtree as archived.
4452 An archived subtree does not open during visibility cycling, and does
4453 not contribute to the agenda listings.
4454 After changing this, font-lock must be restarted in the relevant buffers to
4455 get the proper fontification."
4456 :group 'org-archive
4457 :group 'org-keywords
4458 :type 'string)
4460 (defcustom org-agenda-skip-archived-trees t
4461 "Non-nil means the agenda will skip any items located in archived trees.
4462 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4463 variable is no longer recommended, you should leave it at the value t.
4464 Instead, use the key `v' to cycle the archives-mode in the agenda."
4465 :group 'org-archive
4466 :group 'org-agenda-skip
4467 :type 'boolean)
4469 (defcustom org-columns-skip-archived-trees t
4470 "Non-nil means ignore archived trees when creating column view."
4471 :group 'org-archive
4472 :group 'org-properties
4473 :type 'boolean)
4475 (defcustom org-cycle-open-archived-trees nil
4476 "Non-nil means `org-cycle' will open archived trees.
4477 An archived tree is a tree marked with the tag ARCHIVE.
4478 When nil, archived trees will stay folded. You can still open them with
4479 normal outline commands like `show-all', but not with the cycling commands."
4480 :group 'org-archive
4481 :group 'org-cycle
4482 :type 'boolean)
4484 (defcustom org-sparse-tree-open-archived-trees nil
4485 "Non-nil means sparse tree construction shows matches in archived trees.
4486 When nil, matches in these trees are highlighted, but the trees are kept in
4487 collapsed state."
4488 :group 'org-archive
4489 :group 'org-sparse-trees
4490 :type 'boolean)
4492 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4493 "The default date type when building a sparse tree.
4494 When this is nil, a date is a scheduled or a deadline timestamp.
4495 Otherwise, these types are allowed:
4497 all: all timestamps
4498 active: only active timestamps (<...>)
4499 inactive: only inactive timestamps (<...)
4500 scheduled: only scheduled timestamps
4501 deadline: only deadline timestamps"
4502 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4503 (const :tag "All timestamps" all)
4504 (const :tag "Only active timestamps" active)
4505 (const :tag "Only inactive timestamps" inactive)
4506 (const :tag "Only scheduled timestamps" scheduled)
4507 (const :tag "Only deadline timestamps" deadline)
4508 (const :tag "Only closed timestamps" closed))
4509 :version "24.3"
4510 :group 'org-sparse-trees)
4512 (defun org-cycle-hide-archived-subtrees (state)
4513 "Re-hide all archived subtrees after a visibility state change."
4514 (when (and (not org-cycle-open-archived-trees)
4515 (not (memq state '(overview folded))))
4516 (save-excursion
4517 (let* ((globalp (memq state '(contents all)))
4518 (beg (if globalp (point-min) (point)))
4519 (end (if globalp (point-max) (org-end-of-subtree t))))
4520 (org-hide-archived-subtrees beg end)
4521 (goto-char beg)
4522 (if (looking-at (concat ".*:" org-archive-tag ":"))
4523 (message "%s" (substitute-command-keys
4524 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4526 (defun org-force-cycle-archived ()
4527 "Cycle subtree even if it is archived."
4528 (interactive)
4529 (setq this-command 'org-cycle)
4530 (let ((org-cycle-open-archived-trees t))
4531 (call-interactively 'org-cycle)))
4533 (defun org-hide-archived-subtrees (beg end)
4534 "Re-hide all archived subtrees after a visibility state change."
4535 (save-excursion
4536 (let* ((re (concat ":" org-archive-tag ":")))
4537 (goto-char beg)
4538 (while (re-search-forward re end t)
4539 (when (org-at-heading-p)
4540 (org-flag-subtree t)
4541 (org-end-of-subtree t))))))
4543 (declare-function outline-end-of-heading "outline" ())
4544 (declare-function outline-flag-region "outline" (from to flag))
4545 (defun org-flag-subtree (flag)
4546 (save-excursion
4547 (org-back-to-heading t)
4548 (outline-end-of-heading)
4549 (outline-flag-region (point)
4550 (progn (org-end-of-subtree t) (point))
4551 flag)))
4553 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4555 (eval-and-compile
4556 (org-autoload "org-archive"
4557 '(org-add-archive-files)))
4559 ;; Autoload Column View Code
4561 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4562 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4563 (declare-function org-columns-compute "org-colview" (property))
4565 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4566 '(org-columns-number-to-string
4567 org-columns-get-format-and-top-level
4568 org-columns-compute
4569 org-columns-remove-overlays))
4571 ;; Autoload ID code
4573 (declare-function org-id-store-link "org-id")
4574 (declare-function org-id-locations-load "org-id")
4575 (declare-function org-id-locations-save "org-id")
4576 (defvar org-id-track-globally)
4577 (org-autoload "org-id"
4578 '(org-id-new
4579 org-id-copy
4580 org-id-get-with-outline-path-completion
4581 org-id-get-with-outline-drilling))
4583 ;;; Variables for pre-computed regular expressions, all buffer local
4585 (defvar org-todo-regexp nil
4586 "Matches any of the TODO state keywords.")
4587 (make-variable-buffer-local 'org-todo-regexp)
4588 (defvar org-not-done-regexp nil
4589 "Matches any of the TODO state keywords except the last one.")
4590 (make-variable-buffer-local 'org-not-done-regexp)
4591 (defvar org-not-done-heading-regexp nil
4592 "Matches a TODO headline that is not done.")
4593 (make-variable-buffer-local 'org-not-done-regexp)
4594 (defvar org-todo-line-regexp nil
4595 "Matches a headline and puts TODO state into group 2 if present.")
4596 (make-variable-buffer-local 'org-todo-line-regexp)
4597 (defvar org-complex-heading-regexp nil
4598 "Matches a headline and puts everything into groups:
4599 group 1: the stars
4600 group 2: The todo keyword, maybe
4601 group 3: Priority cookie
4602 group 4: True headline
4603 group 5: Tags")
4604 (make-variable-buffer-local 'org-complex-heading-regexp)
4605 (defvar org-complex-heading-regexp-format nil
4606 "Printf format to make regexp to match an exact headline.
4607 This regexp will match the headline of any node which has the
4608 exact headline text that is put into the format, but may have any
4609 TODO state, priority and tags.")
4610 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4611 (defvar org-todo-line-tags-regexp nil
4612 "Matches a headline and puts TODO state into group 2 if present.
4613 Also put tags into group 4 if tags are present.")
4614 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4615 (defvar org-ds-keyword-length 12
4616 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4617 (make-variable-buffer-local 'org-ds-keyword-length)
4618 (defvar org-deadline-regexp nil
4619 "Matches the DEADLINE keyword.")
4620 (make-variable-buffer-local 'org-deadline-regexp)
4621 (defvar org-deadline-time-regexp nil
4622 "Matches the DEADLINE keyword together with a time stamp.")
4623 (make-variable-buffer-local 'org-deadline-time-regexp)
4624 (defvar org-deadline-time-hour-regexp nil
4625 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4626 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4627 (defvar org-deadline-line-regexp nil
4628 "Matches the DEADLINE keyword and the rest of the line.")
4629 (make-variable-buffer-local 'org-deadline-line-regexp)
4630 (defvar org-scheduled-regexp nil
4631 "Matches the SCHEDULED keyword.")
4632 (make-variable-buffer-local 'org-scheduled-regexp)
4633 (defvar org-scheduled-time-regexp nil
4634 "Matches the SCHEDULED keyword together with a time stamp.")
4635 (make-variable-buffer-local 'org-scheduled-time-regexp)
4636 (defvar org-scheduled-time-hour-regexp nil
4637 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4638 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4639 (defvar org-closed-time-regexp nil
4640 "Matches the CLOSED keyword together with a time stamp.")
4641 (make-variable-buffer-local 'org-closed-time-regexp)
4643 (defvar org-keyword-time-regexp nil
4644 "Matches any of the 4 keywords, together with the time stamp.")
4645 (make-variable-buffer-local 'org-keyword-time-regexp)
4646 (defvar org-keyword-time-not-clock-regexp nil
4647 "Matches any of the 3 keywords, together with the time stamp.")
4648 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4649 (defvar org-maybe-keyword-time-regexp nil
4650 "Matches a timestamp, possibly preceded by a keyword.")
4651 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4652 (defvar org-all-time-keywords nil
4653 "List of time keywords.")
4654 (make-variable-buffer-local 'org-all-time-keywords)
4656 (defconst org-plain-time-of-day-regexp
4657 (concat
4658 "\\(\\<[012]?[0-9]"
4659 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4660 "\\(--?"
4661 "\\(\\<[012]?[0-9]"
4662 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4663 "\\)?")
4664 "Regular expression to match a plain time or time range.
4665 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4666 groups carry important information:
4667 0 the full match
4668 1 the first time, range or not
4669 8 the second time, if it is a range.")
4671 (defconst org-plain-time-extension-regexp
4672 (concat
4673 "\\(\\<[012]?[0-9]"
4674 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4675 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4676 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4677 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4678 groups carry important information:
4679 0 the full match
4680 7 hours of duration
4681 9 minutes of duration")
4683 (defconst org-stamp-time-of-day-regexp
4684 (concat
4685 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4686 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4687 "\\(--?"
4688 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4689 "Regular expression to match a timestamp time or time range.
4690 After a match, the following groups carry important information:
4691 0 the full match
4692 1 date plus weekday, for back referencing to make sure both times are on the same day
4693 2 the first time, range or not
4694 4 the second time, if it is a range.")
4696 (defconst org-startup-options
4697 '(("fold" org-startup-folded t)
4698 ("overview" org-startup-folded t)
4699 ("nofold" org-startup-folded nil)
4700 ("showall" org-startup-folded nil)
4701 ("showeverything" org-startup-folded showeverything)
4702 ("content" org-startup-folded content)
4703 ("indent" org-startup-indented t)
4704 ("noindent" org-startup-indented nil)
4705 ("hidestars" org-hide-leading-stars t)
4706 ("showstars" org-hide-leading-stars nil)
4707 ("odd" org-odd-levels-only t)
4708 ("oddeven" org-odd-levels-only nil)
4709 ("align" org-startup-align-all-tables t)
4710 ("noalign" org-startup-align-all-tables nil)
4711 ("inlineimages" org-startup-with-inline-images t)
4712 ("noinlineimages" org-startup-with-inline-images nil)
4713 ("latexpreview" org-startup-with-latex-preview t)
4714 ("nolatexpreview" org-startup-with-latex-preview nil)
4715 ("customtime" org-display-custom-times t)
4716 ("logdone" org-log-done time)
4717 ("lognotedone" org-log-done note)
4718 ("nologdone" org-log-done nil)
4719 ("lognoteclock-out" org-log-note-clock-out t)
4720 ("nolognoteclock-out" org-log-note-clock-out nil)
4721 ("logrepeat" org-log-repeat state)
4722 ("lognoterepeat" org-log-repeat note)
4723 ("logdrawer" org-log-into-drawer t)
4724 ("nologdrawer" org-log-into-drawer nil)
4725 ("logstatesreversed" org-log-states-order-reversed t)
4726 ("nologstatesreversed" org-log-states-order-reversed nil)
4727 ("nologrepeat" org-log-repeat nil)
4728 ("logreschedule" org-log-reschedule time)
4729 ("lognotereschedule" org-log-reschedule note)
4730 ("nologreschedule" org-log-reschedule nil)
4731 ("logredeadline" org-log-redeadline time)
4732 ("lognoteredeadline" org-log-redeadline note)
4733 ("nologredeadline" org-log-redeadline nil)
4734 ("logrefile" org-log-refile time)
4735 ("lognoterefile" org-log-refile note)
4736 ("nologrefile" org-log-refile nil)
4737 ("fninline" org-footnote-define-inline t)
4738 ("nofninline" org-footnote-define-inline nil)
4739 ("fnlocal" org-footnote-section nil)
4740 ("fnauto" org-footnote-auto-label t)
4741 ("fnprompt" org-footnote-auto-label nil)
4742 ("fnconfirm" org-footnote-auto-label confirm)
4743 ("fnplain" org-footnote-auto-label plain)
4744 ("fnadjust" org-footnote-auto-adjust t)
4745 ("nofnadjust" org-footnote-auto-adjust nil)
4746 ("constcgs" constants-unit-system cgs)
4747 ("constSI" constants-unit-system SI)
4748 ("noptag" org-tag-persistent-alist nil)
4749 ("hideblocks" org-hide-block-startup t)
4750 ("nohideblocks" org-hide-block-startup nil)
4751 ("beamer" org-startup-with-beamer-mode t)
4752 ("entitiespretty" org-pretty-entities t)
4753 ("entitiesplain" org-pretty-entities nil))
4754 "Variable associated with STARTUP options for org-mode.
4755 Each element is a list of three items: the startup options (as written
4756 in the #+STARTUP line), the corresponding variable, and the value to set
4757 this variable to if the option is found. An optional forth element PUSH
4758 means to push this value onto the list in the variable.")
4760 (defun org-update-property-plist (key val props)
4761 "Update PROPS with KEY and VAL."
4762 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4763 (key (if appending (substring key 0 (- (length key) 1)) key))
4764 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4765 (previous (cdr (assoc key props))))
4766 (if appending
4767 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4768 (cons (cons key val) remainder))))
4770 (defconst org-block-regexp
4771 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4772 "Regular expression for hiding blocks.")
4773 (defconst org-heading-keyword-regexp-format
4774 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4775 "Printf format for a regexp matching a headline with some keyword.
4776 This regexp will match the headline of any node which has the
4777 exact keyword that is put into the format. The keyword isn't in
4778 any group by default, but the stars and the body are.")
4779 (defconst org-heading-keyword-maybe-regexp-format
4780 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4781 "Printf format for a regexp matching a headline, possibly with some keyword.
4782 This regexp can match any headline with the specified keyword, or
4783 without a keyword. The keyword isn't in any group by default,
4784 but the stars and the body are.")
4786 (defcustom org-group-tags t
4787 "When non-nil (the default), use group tags.
4788 This can be turned on/off through `org-toggle-tags-groups'."
4789 :group 'org-tags
4790 :group 'org-startup
4791 :type 'boolean)
4793 (defun org-toggle-tags-groups ()
4794 "Toggle support for group tags.
4795 Support for group tags is controlled by the option
4796 `org-group-tags', which is non-nil by default."
4797 (interactive)
4798 (setq org-group-tags (not org-group-tags))
4799 (cond ((and (derived-mode-p 'org-agenda-mode)
4800 org-group-tags)
4801 (org-agenda-redo))
4802 ((derived-mode-p 'org-mode)
4803 (let ((org-inhibit-startup t)) (org-mode))))
4804 (message "Groups tags support has been turned %s"
4805 (if org-group-tags "on" "off")))
4807 (defun org-set-regexps-and-options-for-tags ()
4808 "Precompute variables used for tags."
4809 (when (derived-mode-p 'org-mode)
4810 (org-set-local 'org-file-tags nil)
4811 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4812 (splitre "[ \t]+")
4813 (start 0)
4814 tags ftags key value)
4815 (save-excursion
4816 (save-restriction
4817 (widen)
4818 (goto-char (point-min))
4819 (while (re-search-forward re nil t)
4820 (setq key (upcase (org-match-string-no-properties 1))
4821 value (org-match-string-no-properties 2))
4822 (if (stringp value) (setq value (org-trim value)))
4823 (cond
4824 ((equal key "TAGS")
4825 (setq tags (append tags (if tags '("\\n") nil)
4826 (org-split-string value splitre))))
4827 ((equal key "FILETAGS")
4828 (when (string-match "\\S-" value)
4829 (setq ftags
4830 (append
4831 ftags
4832 (apply 'append
4833 (mapcar (lambda (x) (org-split-string x ":"))
4834 (org-split-string value)))))))))))
4835 ;; Process the file tags.
4836 (and ftags (org-set-local 'org-file-tags
4837 (mapcar 'org-add-prop-inherited ftags)))
4838 (org-set-local 'org-tag-groups-alist nil)
4839 ;; Process the tags.
4840 (when (and (not tags) org-tag-alist)
4841 (setq tags
4842 (mapcar
4843 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4844 ((eq (car tg) :endgroup) "}")
4845 ((eq (car tg) :grouptags) ":")
4846 ((eq (car tg) :newline) "\n")
4847 (t (concat (car tg)
4848 (if (characterp (cdr tg))
4849 (format "(%s)" (char-to-string (cdr tg))) "")))))
4850 org-tag-alist)))
4851 (let (e tgs g)
4852 (while (setq e (pop tags))
4853 (cond
4854 ((equal e "{")
4855 (progn (push '(:startgroup) tgs)
4856 (when (equal (nth 1 tags) ":")
4857 (push (list (replace-regexp-in-string
4858 "(.+)$" "" (nth 0 tags)))
4859 org-tag-groups-alist)
4860 (setq g 0))))
4861 ((equal e ":") (push '(:grouptags) tgs))
4862 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4863 ((equal e "\\n") (push '(:newline) tgs))
4864 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4865 (push (cons (match-string 1 e)
4866 (string-to-char (match-string 2 e))) tgs)
4867 (if (and g (> g 0))
4868 (setcar org-tag-groups-alist
4869 (append (car org-tag-groups-alist)
4870 (list (match-string 1 e)))))
4871 (if g (setq g (1+ g))))
4872 (t (push (list e) tgs)
4873 (if (and g (> g 0))
4874 (setcar org-tag-groups-alist
4875 (append (car org-tag-groups-alist) (list e))))
4876 (if g (setq g (1+ g))))))
4877 (org-set-local 'org-tag-alist nil)
4878 (while (setq e (pop tgs))
4879 (or (and (stringp (car e))
4880 (assoc (car e) org-tag-alist))
4881 (push e org-tag-alist)))
4882 ;; Return a list with tag variables
4883 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4885 (defvar org-ota nil)
4886 (defun org-set-regexps-and-options ()
4887 "Precompute regular expressions used in the current buffer."
4888 (when (derived-mode-p 'org-mode)
4889 (org-set-local 'org-todo-kwd-alist nil)
4890 (org-set-local 'org-todo-key-alist nil)
4891 (org-set-local 'org-todo-key-trigger nil)
4892 (org-set-local 'org-todo-keywords-1 nil)
4893 (org-set-local 'org-done-keywords nil)
4894 (org-set-local 'org-todo-heads nil)
4895 (org-set-local 'org-todo-sets nil)
4896 (org-set-local 'org-todo-log-states nil)
4897 (org-set-local 'org-file-properties nil)
4898 (let ((re (org-make-options-regexp
4899 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4900 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4901 "SETUPFILE" "OPTIONS")
4902 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4903 (splitre "[ \t]+")
4904 (scripts org-use-sub-superscripts)
4905 kwds kws0 kwsa key log value cat arch const links hw dws
4906 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4907 (start 0))
4908 (save-excursion
4909 (save-restriction
4910 (widen)
4911 (goto-char (point-min))
4912 (while
4913 (or (and
4914 ext-setup-or-nil
4915 (not org-ota)
4916 (let (ret)
4917 (with-temp-buffer
4918 (insert ext-setup-or-nil)
4919 (let ((major-mode 'org-mode) org-ota)
4920 (setq ret (save-match-data
4921 (org-set-regexps-and-options-for-tags)))))
4922 ;; Append setupfile tags to existing tags
4923 (setq org-ota t)
4924 (setq org-file-tags
4925 (delq nil (append org-file-tags (nth 0 ret)))
4926 org-tag-alist
4927 (delq nil (append org-tag-alist (nth 1 ret)))
4928 org-tag-groups-alist
4929 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4930 (and ext-setup-or-nil
4931 (string-match re ext-setup-or-nil start)
4932 (setq start (match-end 0)))
4933 (and (setq ext-setup-or-nil nil start 0)
4934 (re-search-forward re nil t)))
4935 (setq key (upcase (match-string 1 ext-setup-or-nil))
4936 value (org-match-string-no-properties 2 ext-setup-or-nil))
4937 (if (stringp value) (setq value (org-trim value)))
4938 (cond
4939 ((equal key "CATEGORY")
4940 (setq cat value))
4941 ((member key '("SEQ_TODO" "TODO"))
4942 (push (cons 'sequence (org-split-string value splitre)) kwds))
4943 ((equal key "TYP_TODO")
4944 (push (cons 'type (org-split-string value splitre)) kwds))
4945 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4946 ;; general TODO-like setup
4947 (push (cons (intern (downcase (match-string 1 key)))
4948 (org-split-string value splitre)) kwds))
4949 ((equal key "COLUMNS")
4950 (org-set-local 'org-columns-default-format value))
4951 ((equal key "LINK")
4952 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4953 (push (cons (match-string 1 value)
4954 (org-trim (match-string 2 value)))
4955 links)))
4956 ((equal key "PRIORITIES")
4957 (setq prio (org-split-string value " +")))
4958 ((equal key "PROPERTY")
4959 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4960 (setq props (org-update-property-plist (match-string 1 value)
4961 (match-string 2 value)
4962 props))))
4963 ((equal key "CONSTANTS")
4964 (org-table-set-constants))
4965 ((equal key "STARTUP")
4966 (let ((opts (org-split-string value splitre))
4967 l var val)
4968 (while (setq l (pop opts))
4969 (when (setq l (assoc l org-startup-options))
4970 (setq var (nth 1 l) val (nth 2 l))
4971 (if (not (nth 3 l))
4972 (set (make-local-variable var) val)
4973 (if (not (listp (symbol-value var)))
4974 (set (make-local-variable var) nil))
4975 (set (make-local-variable var) (symbol-value var))
4976 (add-to-list var val))))))
4977 ((equal key "ARCHIVE")
4978 (setq arch value)
4979 (remove-text-properties 0 (length arch)
4980 '(face t fontified t) arch))
4981 ((equal key "OPTIONS")
4982 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4983 (setq scripts (read (match-string 2 value)))))
4984 ((and (equal key "SETUPFILE")
4985 ;; Prevent checking in Gnus messages
4986 (not buffer-read-only))
4987 (setq setup-contents (org-file-contents
4988 (expand-file-name
4989 (org-remove-double-quotes value))
4990 'noerror))
4991 (if (not ext-setup-or-nil)
4992 (setq ext-setup-or-nil setup-contents start 0)
4993 (setq ext-setup-or-nil
4994 (concat (substring ext-setup-or-nil 0 start)
4995 "\n" setup-contents "\n"
4996 (substring ext-setup-or-nil start)))))))
4997 ;; search for property blocks
4998 (goto-char (point-min))
4999 (while (re-search-forward org-block-regexp nil t)
5000 (when (equal "PROPERTY" (upcase (match-string 1)))
5001 (setq value (replace-regexp-in-string
5002 "[\n\r]" " " (match-string 4)))
5003 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5004 (setq props (org-update-property-plist (match-string 1 value)
5005 (match-string 2 value)
5006 props)))))))
5007 (org-set-local 'org-use-sub-superscripts scripts)
5008 (when cat
5009 (org-set-local 'org-category (intern cat))
5010 (push (cons "CATEGORY" cat) props))
5011 (when prio
5012 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5013 (setq prio (mapcar 'string-to-char prio))
5014 (org-set-local 'org-highest-priority (nth 0 prio))
5015 (org-set-local 'org-lowest-priority (nth 1 prio))
5016 (org-set-local 'org-default-priority (nth 2 prio)))
5017 (and props (org-set-local 'org-file-properties (nreverse props)))
5018 (and arch (org-set-local 'org-archive-location arch))
5019 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5020 ;; Process the TODO keywords
5021 (unless kwds
5022 ;; Use the global values as if they had been given locally.
5023 (setq kwds (default-value 'org-todo-keywords))
5024 (if (stringp (car kwds))
5025 (setq kwds (list (cons org-todo-interpretation
5026 (default-value 'org-todo-keywords)))))
5027 (setq kwds (reverse kwds)))
5028 (setq kwds (nreverse kwds))
5029 (let (inter kws kw)
5030 (while (setq kws (pop kwds))
5031 (let ((kws (or
5032 (run-hook-with-args-until-success
5033 'org-todo-setup-filter-hook kws)
5034 kws)))
5035 (setq inter (pop kws) sep (member "|" kws)
5036 kws0 (delete "|" (copy-sequence kws))
5037 kwsa nil
5038 kws1 (mapcar
5039 (lambda (x)
5040 ;; 1 2
5041 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5042 (progn
5043 (setq kw (match-string 1 x)
5044 key (and (match-end 2) (match-string 2 x))
5045 log (org-extract-log-state-settings x))
5046 (push (cons kw (and key (string-to-char key))) kwsa)
5047 (and log (push log org-todo-log-states))
5049 (error "Invalid TODO keyword %s" x)))
5050 kws0)
5051 kwsa (if kwsa (append '((:startgroup))
5052 (nreverse kwsa)
5053 '((:endgroup))))
5054 hw (car kws1)
5055 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5056 tail (list inter hw (car dws) (org-last dws))))
5057 (add-to-list 'org-todo-heads hw 'append)
5058 (push kws1 org-todo-sets)
5059 (setq org-done-keywords (append org-done-keywords dws nil))
5060 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5061 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5062 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5063 (setq org-todo-sets (nreverse org-todo-sets)
5064 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5065 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5066 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5067 ;; Compute the regular expressions and other local variables.
5068 ;; Using `org-outline-regexp-bol' would complicate them much,
5069 ;; because of the fixed white space at the end of that string.
5070 (if (not org-done-keywords)
5071 (setq org-done-keywords (and org-todo-keywords-1
5072 (list (org-last org-todo-keywords-1)))))
5073 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5074 (length org-scheduled-string)
5075 (length org-clock-string)
5076 (length org-closed-string)))
5077 org-not-done-keywords
5078 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5079 org-todo-regexp
5080 (concat "\\("
5081 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5082 "\\)")
5083 org-not-done-regexp
5084 (concat "\\("
5085 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5086 "\\)")
5087 org-not-done-heading-regexp
5088 (format org-heading-keyword-regexp-format org-not-done-regexp)
5089 org-todo-line-regexp
5090 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5091 org-complex-heading-regexp
5092 (concat "^\\(\\*+\\)"
5093 "\\(?: +" org-todo-regexp "\\)?"
5094 "\\(?: +\\(\\[#.\\]\\)\\)?"
5095 "\\(?: +\\(.*?\\)\\)??"
5096 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5097 "[ \t]*$")
5098 org-complex-heading-regexp-format
5099 (concat "^\\(\\*+\\)"
5100 "\\(?: +" org-todo-regexp "\\)?"
5101 "\\(?: +\\(\\[#.\\]\\)\\)?"
5102 "\\(?: +"
5103 ;; Stats cookies can be stuck to body.
5104 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5105 "\\(%s\\)"
5106 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5107 "\\)"
5108 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5109 "[ \t]*$")
5110 org-todo-line-tags-regexp
5111 (concat "^\\(\\*+\\)"
5112 "\\(?: +" org-todo-regexp "\\)?"
5113 "\\(?: +\\(.*?\\)\\)??"
5114 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5115 "[ \t]*$")
5116 org-deadline-regexp (concat "\\<" org-deadline-string)
5117 org-deadline-time-regexp
5118 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5119 org-deadline-time-hour-regexp
5120 (concat "\\<" org-deadline-string
5121 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5122 org-deadline-line-regexp
5123 (concat "\\<\\(" org-deadline-string "\\).*")
5124 org-scheduled-regexp
5125 (concat "\\<" org-scheduled-string)
5126 org-scheduled-time-regexp
5127 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5128 org-scheduled-time-hour-regexp
5129 (concat "\\<" org-scheduled-string
5130 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5131 org-closed-time-regexp
5132 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5133 org-keyword-time-regexp
5134 (concat "\\<\\(" org-scheduled-string
5135 "\\|" org-deadline-string
5136 "\\|" org-closed-string
5137 "\\|" org-clock-string "\\)"
5138 " *[[<]\\([^]>]+\\)[]>]")
5139 org-keyword-time-not-clock-regexp
5140 (concat "\\<\\(" org-scheduled-string
5141 "\\|" org-deadline-string
5142 "\\|" org-closed-string
5143 "\\)"
5144 " *[[<]\\([^]>]+\\)[]>]")
5145 org-maybe-keyword-time-regexp
5146 (concat "\\(\\<\\(" org-scheduled-string
5147 "\\|" org-deadline-string
5148 "\\|" org-closed-string
5149 "\\|" org-clock-string "\\)\\)?"
5150 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5151 org-all-time-keywords
5152 (mapcar (lambda (w) (substring w 0 -1))
5153 (list org-scheduled-string org-deadline-string
5154 org-clock-string org-closed-string)))
5155 (setq org-ota nil)
5156 (org-compute-latex-and-related-regexp))))
5158 (defun org-file-contents (file &optional noerror)
5159 "Return the contents of FILE, as a string."
5160 (if (or (not file)
5161 (not (file-readable-p file)))
5162 (if noerror
5163 (message "Cannot read file \"%s\"" file)
5164 (error "Cannot read file \"%s\"" file))
5165 (with-temp-buffer
5166 (insert-file-contents file)
5167 (buffer-string))))
5169 (defun org-extract-log-state-settings (x)
5170 "Extract the log state setting from a TODO keyword string.
5171 This will extract info from a string like \"WAIT(w@/!)\"."
5172 (let (kw key log1 log2)
5173 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5174 (setq kw (match-string 1 x)
5175 key (and (match-end 2) (match-string 2 x))
5176 log1 (and (match-end 3) (match-string 3 x))
5177 log2 (and (match-end 4) (match-string 4 x)))
5178 (and (or log1 log2)
5179 (list kw
5180 (and log1 (if (equal log1 "!") 'time 'note))
5181 (and log2 (if (equal log2 "!") 'time 'note)))))))
5183 (defun org-remove-keyword-keys (list)
5184 "Remove a pair of parenthesis at the end of each string in LIST."
5185 (mapcar (lambda (x)
5186 (if (string-match "(.*)$" x)
5187 (substring x 0 (match-beginning 0))
5189 list))
5191 (defun org-assign-fast-keys (alist)
5192 "Assign fast keys to a keyword-key alist.
5193 Respect keys that are already there."
5194 (let (new e (alt ?0))
5195 (while (setq e (pop alist))
5196 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5197 (cdr e)) ;; Key already assigned.
5198 (push e new)
5199 (let ((clist (string-to-list (downcase (car e))))
5200 (used (append new alist)))
5201 (when (= (car clist) ?@)
5202 (pop clist))
5203 (while (and clist (rassoc (car clist) used))
5204 (pop clist))
5205 (unless clist
5206 (while (rassoc alt used)
5207 (incf alt)))
5208 (push (cons (car e) (or (car clist) alt)) new))))
5209 (nreverse new)))
5211 ;;; Some variables used in various places
5213 (defvar org-window-configuration nil
5214 "Used in various places to store a window configuration.")
5215 (defvar org-selected-window nil
5216 "Used in various places to store a window configuration.")
5217 (defvar org-finish-function nil
5218 "Function to be called when `C-c C-c' is used.
5219 This is for getting out of special buffers like capture.")
5222 ;; FIXME: Occasionally check by commenting these, to make sure
5223 ;; no other functions uses these, forgetting to let-bind them.
5224 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5225 (defvar org-last-state)
5226 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5228 ;; Defined somewhere in this file, but used before definition.
5229 (defvar org-entities) ;; defined in org-entities.el
5230 (defvar org-struct-menu)
5231 (defvar org-org-menu)
5232 (defvar org-tbl-menu)
5234 ;;;; Define the Org-mode
5236 ;; We use a before-change function to check if a table might need
5237 ;; an update.
5238 (defvar org-table-may-need-update t
5239 "Indicates that a table might need an update.
5240 This variable is set by `org-before-change-function'.
5241 `org-table-align' sets it back to nil.")
5242 (defun org-before-change-function (beg end)
5243 "Every change indicates that a table might need an update."
5244 (setq org-table-may-need-update t))
5245 (defvar org-mode-map)
5246 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5247 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5248 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5249 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5250 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5251 (defvar org-table-buffer-is-an nil)
5253 (defvar bidi-paragraph-direction)
5254 (defvar buffer-face-mode-face)
5256 (require 'outline)
5257 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5258 (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"))
5259 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5261 ;; Other stuff we need.
5262 (require 'time-date)
5263 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5264 (require 'easymenu)
5265 (require 'overlay)
5267 ;; (require 'org-macs) moved higher up in the file before it is first used
5268 (require 'org-entities)
5269 ;; (require 'org-compat) moved higher up in the file before it is first used
5270 (require 'org-faces)
5271 (require 'org-list)
5272 (require 'org-pcomplete)
5273 (require 'org-src)
5274 (require 'org-footnote)
5275 (require 'org-macro)
5277 ;; babel
5278 (require 'ob)
5280 ;;;###autoload
5281 (define-derived-mode org-mode outline-mode "Org"
5282 "Outline-based notes management and organizer, alias
5283 \"Carsten's outline-mode for keeping track of everything.\"
5285 Org-mode develops organizational tasks around a NOTES file which
5286 contains information about projects as plain text. Org-mode is
5287 implemented on top of outline-mode, which is ideal to keep the content
5288 of large files well structured. It supports ToDo items, deadlines and
5289 time stamps, which magically appear in the diary listing of the Emacs
5290 calendar. Tables are easily created with a built-in table editor.
5291 Plain text URL-like links connect to websites, emails (VM), Usenet
5292 messages (Gnus), BBDB entries, and any files related to the project.
5293 For printing and sharing of notes, an Org-mode file (or a part of it)
5294 can be exported as a structured ASCII or HTML file.
5296 The following commands are available:
5298 \\{org-mode-map}"
5300 ;; Get rid of Outline menus, they are not needed
5301 ;; Need to do this here because define-derived-mode sets up
5302 ;; the keymap so late. Still, it is a waste to call this each time
5303 ;; we switch another buffer into org-mode.
5304 (if (featurep 'xemacs)
5305 (when (boundp 'outline-mode-menu-heading)
5306 ;; Assume this is Greg's port, it uses easymenu
5307 (easy-menu-remove outline-mode-menu-heading)
5308 (easy-menu-remove outline-mode-menu-show)
5309 (easy-menu-remove outline-mode-menu-hide))
5310 (define-key org-mode-map [menu-bar headings] 'undefined)
5311 (define-key org-mode-map [menu-bar hide] 'undefined)
5312 (define-key org-mode-map [menu-bar show] 'undefined))
5314 (org-load-modules-maybe)
5315 (easy-menu-add org-org-menu)
5316 (easy-menu-add org-tbl-menu)
5317 (org-install-agenda-files-menu)
5318 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5319 (add-to-invisibility-spec '(org-cwidth))
5320 (add-to-invisibility-spec '(org-hide-block . t))
5321 (when (featurep 'xemacs)
5322 (org-set-local 'line-move-ignore-invisible t))
5323 (org-set-local 'outline-regexp org-outline-regexp)
5324 (org-set-local 'outline-level 'org-outline-level)
5325 (setq bidi-paragraph-direction 'left-to-right)
5326 (when (and org-ellipsis
5327 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5328 (fboundp 'make-glyph-code))
5329 (unless org-display-table
5330 (setq org-display-table (make-display-table)))
5331 (set-display-table-slot
5332 org-display-table 4
5333 (vconcat (mapcar
5334 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5335 org-ellipsis)))
5336 (if (stringp org-ellipsis) org-ellipsis "..."))))
5337 (setq buffer-display-table org-display-table))
5338 (org-set-regexps-and-options-for-tags)
5339 (org-set-regexps-and-options)
5340 (org-set-font-lock-defaults)
5341 (when (and org-tag-faces (not org-tags-special-faces-re))
5342 ;; tag faces set outside customize.... force initialization.
5343 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5344 ;; Calc embedded
5345 (org-set-local 'calc-embedded-open-mode "# ")
5346 ;; Modify a few syntax entries
5347 (modify-syntax-entry ?@ "w")
5348 (modify-syntax-entry ?\" "\"")
5349 (if org-startup-truncated (setq truncate-lines t))
5350 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5351 (org-set-local 'font-lock-unfontify-region-function
5352 'org-unfontify-region)
5353 ;; Activate before-change-function
5354 (org-set-local 'org-table-may-need-update t)
5355 (org-add-hook 'before-change-functions 'org-before-change-function nil
5356 'local)
5357 ;; Check for running clock before killing a buffer
5358 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5359 ;; Initialize macros templates.
5360 (org-macro-initialize-templates)
5361 ;; Initialize radio targets.
5362 (org-update-radio-target-regexp)
5363 ;; Indentation.
5364 (org-set-local 'indent-line-function 'org-indent-line)
5365 (org-set-local 'indent-region-function 'org-indent-region)
5366 ;; Filling and auto-filling.
5367 (org-setup-filling)
5368 ;; Comments.
5369 (org-setup-comments-handling)
5370 ;; Beginning/end of defun
5371 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5372 (org-set-local 'end-of-defun-function 'org-forward-element)
5373 ;; Next error for sparse trees
5374 (org-set-local 'next-error-function 'org-occur-next-match)
5375 ;; Make sure dependence stuff works reliably, even for users who set it
5376 ;; too late :-(
5377 (if org-enforce-todo-dependencies
5378 (add-hook 'org-blocker-hook
5379 'org-block-todo-from-children-or-siblings-or-parent)
5380 (remove-hook 'org-blocker-hook
5381 'org-block-todo-from-children-or-siblings-or-parent))
5382 (if org-enforce-todo-checkbox-dependencies
5383 (add-hook 'org-blocker-hook
5384 'org-block-todo-from-checkboxes)
5385 (remove-hook 'org-blocker-hook
5386 'org-block-todo-from-checkboxes))
5388 ;; Align options lines
5389 (org-set-local
5390 'align-mode-rules-list
5391 '((org-in-buffer-settings
5392 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5393 (modes . '(org-mode)))))
5395 ;; Imenu
5396 (org-set-local 'imenu-create-index-function
5397 'org-imenu-get-tree)
5399 ;; Make isearch reveal context
5400 (if (or (featurep 'xemacs)
5401 (not (boundp 'outline-isearch-open-invisible-function)))
5402 ;; Emacs 21 and XEmacs make use of the hook
5403 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5404 ;; Emacs 22 deals with this through a special variable
5405 (org-set-local 'outline-isearch-open-invisible-function
5406 (lambda (&rest ignore) (org-show-context 'isearch)))
5407 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5409 ;; Setup the pcomplete hooks
5410 (set (make-local-variable 'pcomplete-command-completion-function)
5411 'org-pcomplete-initial)
5412 (set (make-local-variable 'pcomplete-command-name-function)
5413 'org-command-at-point)
5414 (set (make-local-variable 'pcomplete-default-completion-function)
5415 'ignore)
5416 (set (make-local-variable 'pcomplete-parse-arguments-function)
5417 'org-parse-arguments)
5418 (set (make-local-variable 'pcomplete-termination-string) "")
5419 (when (>= emacs-major-version 23)
5420 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5422 ;; If empty file that did not turn on org-mode automatically, make it to.
5423 (if (and org-insert-mode-line-in-empty-file
5424 (org-called-interactively-p 'any)
5425 (= (point-min) (point-max)))
5426 (insert "# -*- mode: org -*-\n\n"))
5427 (unless org-inhibit-startup
5428 (org-unmodified
5429 (and org-startup-with-beamer-mode (org-beamer-mode))
5430 (when org-startup-align-all-tables
5431 (org-table-map-tables 'org-table-align 'quietly))
5432 (when org-startup-with-inline-images
5433 (org-display-inline-images))
5434 (when org-startup-with-latex-preview
5435 (org-preview-latex-fragment))
5436 (unless org-inhibit-startup-visibility-stuff
5437 (org-set-startup-visibility))))
5438 ;; Try to set org-hide correctly
5439 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5441 ;; Update `customize-package-emacs-version-alist'
5442 (add-to-list 'customize-package-emacs-version-alist
5443 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5444 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5445 ("8.0" . "24.4")))
5447 (defvar org-mode-transpose-word-syntax-table
5448 (let ((st (make-syntax-table)))
5449 (mapc (lambda(c) (modify-syntax-entry
5450 (string-to-char (car c)) "w p" st))
5451 org-emphasis-alist)
5452 st))
5454 (when (fboundp 'abbrev-table-put)
5455 (abbrev-table-put org-mode-abbrev-table
5456 :parents (list text-mode-abbrev-table)))
5458 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5460 (defsubst org-fix-ellipsis-at-bol ()
5461 (save-excursion (goto-char (window-start)) (recenter 0)))
5463 (defun org-find-invisible-foreground ()
5464 (let ((candidates (remove
5465 "unspecified-bg"
5466 (nconc
5467 (list (face-background 'default)
5468 (face-background 'org-default))
5469 (mapcar
5470 (lambda (alist)
5471 (when (boundp alist)
5472 (cdr (assoc 'background-color (symbol-value alist)))))
5473 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5474 (list (face-foreground 'org-hide))))))
5475 (car (remove nil candidates))))
5477 (defun org-current-time (&optional rounding-minutes past)
5478 "Current time, possibly rounded to ROUNDING-MINUTES.
5479 When ROUNDING-MINUTES is not an integer, fall back on the car of
5480 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5481 the rounding returns a past time."
5482 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5483 (car org-time-stamp-rounding-minutes)))
5484 (time (decode-time)) res)
5485 (if (< r 1)
5486 (current-time)
5487 (setq res
5488 (apply 'encode-time
5489 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5490 (nthcdr 2 time))))
5491 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5492 (seconds-to-time (- (org-float-time res) (* r 60)))
5493 res))))
5495 (defun org-today ()
5496 "Return today date, considering `org-extend-today-until'."
5497 (time-to-days
5498 (time-subtract (current-time)
5499 (list 0 (* 3600 org-extend-today-until) 0))))
5501 ;;;; Font-Lock stuff, including the activators
5503 (defvar org-mouse-map (make-sparse-keymap))
5504 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5505 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5506 (when org-mouse-1-follows-link
5507 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5508 (when org-tab-follows-link
5509 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5510 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5512 (require 'font-lock)
5514 (defconst org-non-link-chars "]\t\n\r<>")
5515 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5516 "shell" "elisp" "doi" "message"))
5517 (defvar org-link-types-re nil
5518 "Matches a link that has a url-like prefix like \"http:\"")
5519 (defvar org-link-re-with-space nil
5520 "Matches a link with spaces, optional angular brackets around it.")
5521 (defvar org-link-re-with-space2 nil
5522 "Matches a link with spaces, optional angular brackets around it.")
5523 (defvar org-link-re-with-space3 nil
5524 "Matches a link with spaces, only for internal part in bracket links.")
5525 (defvar org-angle-link-re nil
5526 "Matches link with angular brackets, spaces are allowed.")
5527 (defvar org-plain-link-re nil
5528 "Matches plain link, without spaces.")
5529 (defvar org-bracket-link-regexp nil
5530 "Matches a link in double brackets.")
5531 (defvar org-bracket-link-analytic-regexp nil
5532 "Regular expression used to analyze links.
5533 Here is what the match groups contain after a match:
5534 1: http:
5535 2: http
5536 3: path
5537 4: [desc]
5538 5: desc")
5539 (defvar org-bracket-link-analytic-regexp++ nil
5540 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5541 (defvar org-any-link-re nil
5542 "Regular expression matching any link.")
5544 (defconst org-match-sexp-depth 3
5545 "Number of stacked braces for sub/superscript matching.")
5547 (defun org-create-multibrace-regexp (left right n)
5548 "Create a regular expression which will match a balanced sexp.
5549 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5550 as single character strings.
5551 The regexp returned will match the entire expression including the
5552 delimiters. It will also define a single group which contains the
5553 match except for the outermost delimiters. The maximum depth of
5554 stacked delimiters is N. Escaping delimiters is not possible."
5555 (let* ((nothing (concat "[^" left right "]*?"))
5556 (or "\\|")
5557 (re nothing)
5558 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5559 (while (> n 1)
5560 (setq n (1- n)
5561 re (concat re or next)
5562 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5563 (concat left "\\(" re "\\)" right)))
5565 (defvar org-match-substring-regexp
5566 (concat
5567 "\\(\\S-\\)\\([_^]\\)\\("
5568 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5569 "\\|"
5570 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5571 "\\|"
5572 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5573 "The regular expression matching a sub- or superscript.")
5575 (defvar org-match-substring-with-braces-regexp
5576 (concat
5577 "\\(\\S-\\)\\([_^]\\)\\("
5578 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5579 "\\)")
5580 "The regular expression matching a sub- or superscript, forcing braces.")
5582 (defun org-make-link-regexps ()
5583 "Update the link regular expressions.
5584 This should be called after the variable `org-link-types' has changed."
5585 (setq org-link-types-re
5586 (concat
5587 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5588 org-link-re-with-space
5589 (concat
5590 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5591 "\\([^" org-non-link-chars " ]"
5592 "[^" org-non-link-chars "]*"
5593 "[^" org-non-link-chars " ]\\)>?")
5594 org-link-re-with-space2
5595 (concat
5596 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5597 "\\([^" org-non-link-chars " ]"
5598 "[^\t\n\r]*"
5599 "[^" org-non-link-chars " ]\\)>?")
5600 org-link-re-with-space3
5601 (concat
5602 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5603 "\\([^" org-non-link-chars " ]"
5604 "[^\t\n\r]*\\)")
5605 org-angle-link-re
5606 (concat
5607 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5608 "\\([^" org-non-link-chars " ]"
5609 "[^" org-non-link-chars "]*"
5610 "\\)>")
5611 org-plain-link-re
5612 (concat
5613 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5614 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5615 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5616 org-bracket-link-regexp
5617 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5618 org-bracket-link-analytic-regexp
5619 (concat
5620 "\\[\\["
5621 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5622 "\\([^]]+\\)"
5623 "\\]"
5624 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5625 "\\]")
5626 org-bracket-link-analytic-regexp++
5627 (concat
5628 "\\[\\["
5629 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5630 "\\([^]]+\\)"
5631 "\\]"
5632 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5633 "\\]")
5634 org-any-link-re
5635 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5636 org-angle-link-re "\\)\\|\\("
5637 org-plain-link-re "\\)")))
5639 (org-make-link-regexps)
5641 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5642 "Regular expression for fast time stamp matching.")
5643 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5644 "Regular expression for fast time stamp matching.")
5645 (defconst org-ts-regexp0
5646 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5647 "Regular expression matching time strings for analysis.
5648 This one does not require the space after the date, so it can be used
5649 on a string that terminates immediately after the date.")
5650 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5651 "Regular expression matching time strings for analysis.")
5652 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5653 "Regular expression matching time stamps, with groups.")
5654 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5655 "Regular expression matching time stamps (also [..]), with groups.")
5656 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5657 "Regular expression matching a time stamp range.")
5658 (defconst org-tr-regexp-both
5659 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5660 "Regular expression matching a time stamp range.")
5661 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5662 org-ts-regexp "\\)?")
5663 "Regular expression matching a time stamp or time stamp range.")
5664 (defconst org-tsr-regexp-both
5665 (concat org-ts-regexp-both "\\(--?-?"
5666 org-ts-regexp-both "\\)?")
5667 "Regular expression matching a time stamp or time stamp range.
5668 The time stamps may be either active or inactive.")
5670 (defvar org-emph-face nil)
5672 (defun org-do-emphasis-faces (limit)
5673 "Run through the buffer and add overlays to emphasized strings."
5674 (let (rtn a)
5675 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5676 (if (not (= (char-after (match-beginning 3))
5677 (char-after (match-beginning 4))))
5678 (progn
5679 (setq rtn t)
5680 (setq a (assoc (match-string 3) org-emphasis-alist))
5681 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5682 'face
5683 (nth 1 a))
5684 (and (nth 4 a)
5685 (org-remove-flyspell-overlays-in
5686 (match-beginning 0) (match-end 0)))
5687 (add-text-properties (match-beginning 2) (match-end 2)
5688 '(font-lock-multiline t org-emphasis t))
5689 (when org-hide-emphasis-markers
5690 (add-text-properties (match-end 4) (match-beginning 5)
5691 '(invisible org-link))
5692 (add-text-properties (match-beginning 3) (match-end 3)
5693 '(invisible org-link)))))
5694 (backward-char 1))
5695 rtn))
5697 (defun org-emphasize (&optional char)
5698 "Insert or change an emphasis, i.e. a font like bold or italic.
5699 If there is an active region, change that region to a new emphasis.
5700 If there is no region, just insert the marker characters and position
5701 the cursor between them.
5702 CHAR should be the marker character. If it is a space, it means to
5703 remove the emphasis of the selected region.
5704 If CHAR is not given (for example in an interactive call) it will be
5705 prompted for."
5706 (interactive)
5707 (let ((erc org-emphasis-regexp-components)
5708 (prompt "")
5709 (string "") beg end move c s)
5710 (if (org-region-active-p)
5711 (setq beg (region-beginning) end (region-end)
5712 string (buffer-substring beg end))
5713 (setq move t))
5715 (unless char
5716 (message "Emphasis marker or tag: [%s]"
5717 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5718 (setq char (read-char-exclusive)))
5719 (if (equal char ?\ )
5720 (setq s "" move nil)
5721 (unless (assoc (char-to-string char) org-emphasis-alist)
5722 (user-error "No such emphasis marker: \"%c\"" char))
5723 (setq s (char-to-string char)))
5724 (while (and (> (length string) 1)
5725 (equal (substring string 0 1) (substring string -1))
5726 (assoc (substring string 0 1) org-emphasis-alist))
5727 (setq string (substring string 1 -1)))
5728 (setq string (concat s string s))
5729 (if beg (delete-region beg end))
5730 (unless (or (bolp)
5731 (string-match (concat "[" (nth 0 erc) "\n]")
5732 (char-to-string (char-before (point)))))
5733 (insert " "))
5734 (unless (or (eobp)
5735 (string-match (concat "[" (nth 1 erc) "\n]")
5736 (char-to-string (char-after (point)))))
5737 (insert " ") (backward-char 1))
5738 (insert string)
5739 (and move (backward-char 1))))
5741 (defconst org-nonsticky-props
5742 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5744 (defsubst org-rear-nonsticky-at (pos)
5745 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5747 (defun org-activate-plain-links (limit)
5748 "Run through the buffer and add overlays to links."
5749 (let (f hl)
5750 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5751 (not (org-in-src-block-p)))
5752 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5753 (setq f (get-text-property (match-beginning 0) 'face))
5754 (setq hl (org-match-string-no-properties 0))
5755 (if (or (eq f 'org-tag)
5756 (and (listp f) (memq 'org-tag f)))
5758 (add-text-properties (match-beginning 0) (match-end 0)
5759 (list 'mouse-face 'highlight
5760 'face 'org-link
5761 'htmlize-link `(:uri ,hl)
5762 'keymap org-mouse-map))
5763 (org-rear-nonsticky-at (match-end 0)))
5764 t)))
5766 (defun org-activate-code (limit)
5767 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5768 (progn
5769 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5770 (remove-text-properties (match-beginning 0) (match-end 0)
5771 '(display t invisible t intangible t))
5772 t)))
5774 (defcustom org-src-fontify-natively nil
5775 "When non-nil, fontify code in code blocks."
5776 :type 'boolean
5777 :version "24.1"
5778 :group 'org-appearance
5779 :group 'org-babel)
5781 (defcustom org-allow-promoting-top-level-subtree nil
5782 "When non-nil, allow promoting a top level subtree.
5783 The leading star of the top level headline will be replaced
5784 by a #."
5785 :type 'boolean
5786 :version "24.1"
5787 :group 'org-appearance)
5789 (defun org-fontify-meta-lines-and-blocks (limit)
5790 (condition-case nil
5791 (org-fontify-meta-lines-and-blocks-1 limit)
5792 (error (message "org-mode fontification error"))))
5794 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5795 "Fontify #+ lines and blocks."
5796 (let ((case-fold-search t))
5797 (if (re-search-forward
5798 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5799 limit t)
5800 (let ((beg (match-beginning 0))
5801 (block-start (match-end 0))
5802 (block-end nil)
5803 (lang (match-string 7))
5804 (beg1 (line-beginning-position 2))
5805 (dc1 (downcase (match-string 2)))
5806 (dc3 (downcase (match-string 3)))
5807 end end1 quoting block-type ovl)
5808 (cond
5809 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5810 ;; a single line of backend-specific content
5811 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5812 (remove-text-properties (match-beginning 0) (match-end 0)
5813 '(display t invisible t intangible t))
5814 (add-text-properties (match-beginning 1) (match-end 3)
5815 '(font-lock-fontified t face org-meta-line))
5816 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5817 '(font-lock-fontified t face org-block))
5818 ; for backend-specific code
5820 ((and (match-end 4) (equal dc3 "+begin"))
5821 ;; Truly a block
5822 (setq block-type (downcase (match-string 5))
5823 quoting (member block-type org-protecting-blocks))
5824 (when (re-search-forward
5825 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5826 nil t) ;; on purpose, we look further than LIMIT
5827 (setq end (min (point-max) (match-end 0))
5828 end1 (min (point-max) (1- (match-beginning 0))))
5829 (setq block-end (match-beginning 0))
5830 (when quoting
5831 (remove-text-properties beg end
5832 '(display t invisible t intangible t)))
5833 (add-text-properties
5834 beg end
5835 '(font-lock-fontified t font-lock-multiline t))
5836 (add-text-properties beg beg1 '(face org-meta-line))
5837 (add-text-properties end1 (min (point-max) (1+ end))
5838 '(face org-meta-line)) ; for end_src
5839 (cond
5840 ((and lang (not (string= lang "")) org-src-fontify-natively)
5841 (org-src-font-lock-fontify-block lang block-start block-end)
5842 ;; remove old background overlays
5843 (mapc (lambda (ov)
5844 (if (eq (overlay-get ov 'face) 'org-block-background)
5845 (delete-overlay ov)))
5846 (overlays-at (/ (+ beg1 block-end) 2)))
5847 ;; add a background overlay
5848 (setq ovl (make-overlay beg1 block-end))
5849 (overlay-put ovl 'face 'org-block-background)
5850 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5851 (quoting
5852 (add-text-properties beg1 (min (point-max) (1+ end1))
5853 '(face org-block))) ; end of source block
5854 ((not org-fontify-quote-and-verse-blocks))
5855 ((string= block-type "quote")
5856 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5857 ((string= block-type "verse")
5858 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5859 (add-text-properties beg beg1 '(face org-block-begin-line))
5860 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5861 '(face org-block-end-line))
5863 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5864 (add-text-properties
5865 beg (match-end 3)
5866 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5867 '(font-lock-fontified t invisible t)
5868 '(font-lock-fontified t face org-document-info-keyword)))
5869 (add-text-properties
5870 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5871 (if (string-equal dc1 "+title:")
5872 '(font-lock-fontified t face org-document-title)
5873 '(font-lock-fontified t face org-document-info))))
5874 ((or (equal dc1 "+results")
5875 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5876 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5877 "+call:" "+header:" "+headers:" "+name:"))
5878 (and (match-end 4) (equal dc3 "+attr")))
5879 (add-text-properties
5880 beg (match-end 0)
5881 '(font-lock-fontified t face org-meta-line))
5883 ((member dc3 '(" " ""))
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face font-lock-comment-face)))
5887 ((not (member (char-after beg) '(?\ ?\t)))
5888 ;; just any other in-buffer setting, but not indented
5889 (add-text-properties
5890 beg (match-end 0)
5891 '(font-lock-fontified t face org-meta-line))
5893 (t nil))))))
5895 (defun org-activate-angle-links (limit)
5896 "Run through the buffer and add overlays to links."
5897 (if (and (re-search-forward org-angle-link-re limit t)
5898 (not (org-in-src-block-p)))
5899 (progn
5900 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5901 (add-text-properties (match-beginning 0) (match-end 0)
5902 (list 'mouse-face 'highlight
5903 'keymap org-mouse-map))
5904 (org-rear-nonsticky-at (match-end 0))
5905 t)))
5907 (defun org-activate-footnote-links (limit)
5908 "Run through the buffer and add overlays to footnotes."
5909 (let ((fn (org-footnote-next-reference-or-definition limit)))
5910 (when fn
5911 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5912 (org-remove-flyspell-overlays-in beg end)
5913 (add-text-properties beg end
5914 (list 'mouse-face 'highlight
5915 'keymap org-mouse-map
5916 'help-echo
5917 (if (= (point-at-bol) beg)
5918 "Footnote definition"
5919 "Footnote reference")
5920 'font-lock-fontified t
5921 'font-lock-multiline t
5922 'face 'org-footnote))))))
5924 (defun org-activate-bracket-links (limit)
5925 "Run through the buffer and add overlays to bracketed links."
5926 (if (and (re-search-forward org-bracket-link-regexp limit t)
5927 (not (org-in-src-block-p)))
5928 (let* ((hl (org-match-string-no-properties 1))
5929 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5930 (ip (org-maybe-intangible
5931 (list 'invisible 'org-link
5932 'keymap org-mouse-map 'mouse-face 'highlight
5933 'font-lock-multiline t 'help-echo help
5934 'htmlize-link `(:uri ,hl))))
5935 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5936 'font-lock-multiline t 'help-echo help
5937 'htmlize-link `(:uri ,hl))))
5938 ;; We need to remove the invisible property here. Table narrowing
5939 ;; may have made some of this invisible.
5940 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5941 (remove-text-properties (match-beginning 0) (match-end 0)
5942 '(invisible nil))
5943 (if (match-end 3)
5944 (progn
5945 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5946 (org-rear-nonsticky-at (match-beginning 3))
5947 (add-text-properties (match-beginning 3) (match-end 3) vp)
5948 (org-rear-nonsticky-at (match-end 3))
5949 (add-text-properties (match-end 3) (match-end 0) ip)
5950 (org-rear-nonsticky-at (match-end 0)))
5951 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5952 (org-rear-nonsticky-at (match-beginning 1))
5953 (add-text-properties (match-beginning 1) (match-end 1) vp)
5954 (org-rear-nonsticky-at (match-end 1))
5955 (add-text-properties (match-end 1) (match-end 0) ip)
5956 (org-rear-nonsticky-at (match-end 0)))
5957 t)))
5959 (defun org-activate-dates (limit)
5960 "Run through the buffer and add overlays to dates."
5961 (if (and (re-search-forward org-tsr-regexp-both limit t)
5962 (not (equal (char-before (match-beginning 0)) 91)))
5963 (progn
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (add-text-properties (match-beginning 0) (match-end 0)
5966 (list 'mouse-face 'highlight
5967 'keymap org-mouse-map))
5968 (org-rear-nonsticky-at (match-end 0))
5969 (when org-display-custom-times
5970 (if (match-end 3)
5971 (org-display-custom-time (match-beginning 3) (match-end 3)))
5972 (org-display-custom-time (match-beginning 1) (match-end 1)))
5973 t)))
5975 (defvar org-target-link-regexp nil
5976 "Regular expression matching radio targets in plain text.")
5977 (make-variable-buffer-local 'org-target-link-regexp)
5978 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5979 "Regular expression matching a link target.")
5980 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5981 "Regular expression matching a radio target.")
5982 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5983 "Regular expression matching any target.")
5985 (defun org-activate-target-links (limit)
5986 "Run through the buffer and add overlays to target matches."
5987 (when org-target-link-regexp
5988 (let ((case-fold-search t))
5989 (if (re-search-forward org-target-link-regexp limit t)
5990 (progn
5991 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (add-text-properties (match-beginning 0) (match-end 0)
5993 (list 'mouse-face 'highlight
5994 'keymap org-mouse-map
5995 'help-echo "Radio target link"
5996 'org-linked-text t))
5997 (org-rear-nonsticky-at (match-end 0))
5998 t)))))
6000 (defun org-update-radio-target-regexp ()
6001 "Find all radio targets in this file and update the regular expression."
6002 (interactive)
6003 (when (memq 'radio org-activate-links)
6004 (setq org-target-link-regexp
6005 (org-make-target-link-regexp (org-all-targets 'radio)))
6006 (org-restart-font-lock)))
6008 (defun org-hide-wide-columns (limit)
6009 (let (s e)
6010 (setq s (text-property-any (point) (or limit (point-max))
6011 'org-cwidth t))
6012 (when s
6013 (setq e (next-single-property-change s 'org-cwidth))
6014 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6015 (goto-char e)
6016 t)))
6018 (defvar org-latex-and-related-regexp nil
6019 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6020 (defvar org-match-substring-regexp)
6021 (defvar org-match-substring-with-braces-regexp)
6023 (defun org-compute-latex-and-related-regexp ()
6024 "Compute regular expression for LaTeX, entities and sub/superscript.
6025 Result depends on variable `org-highlight-latex-and-related'."
6026 (org-set-local
6027 'org-latex-and-related-regexp
6028 (let* ((re-sub
6029 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6030 ((eq org-use-sub-superscripts '{})
6031 (list org-match-substring-with-braces-regexp))
6032 (org-use-sub-superscripts (list org-match-substring-regexp))))
6033 (re-latex
6034 (when (memq 'latex org-highlight-latex-and-related)
6035 (let ((matchers (plist-get org-format-latex-options :matchers)))
6036 (delq nil
6037 (mapcar (lambda (x)
6038 (and (member (car x) matchers) (nth 1 x)))
6039 org-latex-regexps)))))
6040 (re-entities
6041 (when (memq 'entities org-highlight-latex-and-related)
6042 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6043 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6045 (defun org-do-latex-and-related (limit)
6046 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6047 LIMIT bounds the search for syntax to highlight. Stop at first
6048 highlighted object, if any. Return t if some highlighting was
6049 done, nil otherwise."
6050 (when (org-string-nw-p org-latex-and-related-regexp)
6051 (catch 'found
6052 (while (re-search-forward org-latex-and-related-regexp limit t)
6053 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6054 'face))
6055 '(org-code org-verbatim underline))
6056 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6057 '(?_ ?^))
6059 0)))
6060 (font-lock-prepend-text-property
6061 (+ offset (match-beginning 0)) (match-end 0)
6062 'face 'org-latex-and-related)
6063 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6064 '(font-lock-multiline t)))
6065 (throw 'found t)))
6066 nil)))
6068 (defun org-restart-font-lock ()
6069 "Restart `font-lock-mode', to force refontification."
6070 (when (and (boundp 'font-lock-mode) font-lock-mode)
6071 (font-lock-mode -1)
6072 (font-lock-mode 1)))
6074 (defun org-all-targets (&optional radio)
6075 "Return a list of all targets in this file.
6076 When optional argument RADIO is non-nil, only find radio
6077 targets."
6078 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6079 (save-excursion
6080 (goto-char (point-min))
6081 (while (re-search-forward re nil t)
6082 ;; Make sure point is really within the object.
6083 (backward-char)
6084 (let ((obj (org-element-context)))
6085 (when (memq (org-element-type obj) '(radio-target target))
6086 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6087 rtn)))
6089 (defun org-make-target-link-regexp (targets)
6090 "Make regular expression matching all strings in TARGETS.
6091 The regular expression finds the targets also if there is a line break
6092 between words."
6093 (and targets
6094 (concat
6095 "\\<\\("
6096 (mapconcat
6097 (lambda (x)
6098 (setq x (regexp-quote x))
6099 (while (string-match " +" x)
6100 (setq x (replace-match "\\s-+" t t x)))
6102 targets
6103 "\\|")
6104 "\\)\\>")))
6106 (defun org-activate-tags (limit)
6107 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6108 (progn
6109 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6110 (add-text-properties (match-beginning 1) (match-end 1)
6111 (list 'mouse-face 'highlight
6112 'keymap org-mouse-map))
6113 (org-rear-nonsticky-at (match-end 1))
6114 t)))
6116 (defun org-outline-level ()
6117 "Compute the outline level of the heading at point.
6118 If this is called at a normal headline, the level is the number of stars.
6119 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6120 (save-excursion
6121 (if (not (condition-case nil
6122 (org-back-to-heading t)
6123 (error nil)))
6125 (looking-at org-outline-regexp)
6126 (1- (- (match-end 0) (match-beginning 0))))))
6128 (defvar org-font-lock-keywords nil)
6130 (defsubst org-re-property (property &optional literal)
6131 "Return a regexp matching a PROPERTY line.
6132 Match group 3 will be set to the value if it exists."
6133 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6134 (if literal property (regexp-quote property))
6135 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6137 (defconst org-property-re
6138 (org-re-property ".*?" 'literal)
6139 "Regular expression matching a property line.
6140 There are four matching groups:
6141 1: :PROPKEY: including the leading and trailing colon,
6142 2: PROPKEY without the leading and trailing colon,
6143 3: PROPVAL without leading or trailing spaces,
6144 4: the indentation of the current line,
6145 5: trailing whitespace.")
6147 (defvar org-font-lock-hook nil
6148 "Functions to be called for special font lock stuff.")
6150 (defvar org-font-lock-set-keywords-hook nil
6151 "Functions that can manipulate `org-font-lock-extra-keywords'.
6152 This is called after `org-font-lock-extra-keywords' is defined, but before
6153 it is installed to be used by font lock. This can be useful if something
6154 needs to be inserted at a specific position in the font-lock sequence.")
6156 (defun org-font-lock-hook (limit)
6157 "Run `org-font-lock-hook' within LIMIT."
6158 (run-hook-with-args 'org-font-lock-hook limit))
6160 (defun org-set-font-lock-defaults ()
6161 "Set font lock defaults for the current buffer."
6162 (let* ((em org-fontify-emphasized-text)
6163 (lk org-activate-links)
6164 (org-font-lock-extra-keywords
6165 (list
6166 ;; Call the hook
6167 '(org-font-lock-hook)
6168 ;; Headlines
6169 `(,(if org-fontify-whole-heading-line
6170 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6171 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6172 (1 (org-get-level-face 1))
6173 (2 (org-get-level-face 2))
6174 (3 (org-get-level-face 3)))
6175 ;; Table lines
6176 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6177 (1 'org-table t))
6178 ;; Table internals
6179 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6180 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6181 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6182 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6183 ;; Drawers
6184 (list org-drawer-regexp '(0 'org-special-keyword t))
6185 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6186 ;; Properties
6187 (list org-property-re
6188 '(1 'org-special-keyword t)
6189 '(3 'org-property-value t))
6190 ;; Links
6191 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6192 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6193 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6194 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6195 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6196 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6197 (if (memq 'footnote lk) '(org-activate-footnote-links))
6198 ;; Targets.
6199 (list org-any-target-regexp '(0 'org-target t))
6200 ;; Diary sexps.
6201 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6202 ;; Macro
6203 '("{{{.+}}}" (0 'org-macro t))
6204 '(org-hide-wide-columns (0 nil append))
6205 ;; TODO keyword
6206 (list (format org-heading-keyword-regexp-format
6207 org-todo-regexp)
6208 '(2 (org-get-todo-face 2) t))
6209 ;; DONE
6210 (if org-fontify-done-headline
6211 (list (format org-heading-keyword-regexp-format
6212 (concat
6213 "\\(?:"
6214 (mapconcat 'regexp-quote org-done-keywords "\\|")
6215 "\\)"))
6216 '(2 'org-headline-done t))
6217 nil)
6218 ;; Priorities
6219 '(org-font-lock-add-priority-faces)
6220 ;; Tags
6221 '(org-font-lock-add-tag-faces)
6222 ;; Tags groups
6223 (if (and org-group-tags org-tag-groups-alist)
6224 (list (concat org-outline-regexp-bol ".+\\(:"
6225 (regexp-opt (mapcar 'car org-tag-groups-alist))
6226 ":\\).*$")
6227 '(1 'org-tag-group prepend)))
6228 ;; Special keywords
6229 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6230 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6231 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6232 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6233 ;; Emphasis
6234 (if em
6235 (if (featurep 'xemacs)
6236 '(org-do-emphasis-faces (0 nil append))
6237 '(org-do-emphasis-faces)))
6238 ;; Checkboxes
6239 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6240 1 'org-checkbox prepend)
6241 (if (cdr (assq 'checkbox org-list-automatic-rules))
6242 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6243 (0 (org-get-checkbox-statistics-face) t)))
6244 ;; Description list items
6245 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6246 1 'org-list-dt prepend)
6247 ;; ARCHIVEd headings
6248 (list (concat
6249 org-outline-regexp-bol
6250 "\\(.*:" org-archive-tag ":.*\\)")
6251 '(1 'org-archived prepend))
6252 ;; Specials
6253 '(org-do-latex-and-related)
6254 '(org-fontify-entities)
6255 '(org-raise-scripts)
6256 ;; Code
6257 '(org-activate-code (1 'org-code t))
6258 ;; COMMENT
6259 (list (format org-heading-keyword-regexp-format
6260 (concat "\\("
6261 org-comment-string "\\|" org-quote-string
6262 "\\)"))
6263 '(2 'org-special-keyword t))
6264 ;; Blocks and meta lines
6265 '(org-fontify-meta-lines-and-blocks))))
6266 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6267 (run-hooks 'org-font-lock-set-keywords-hook)
6268 ;; Now set the full font-lock-keywords
6269 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6270 (org-set-local 'font-lock-defaults
6271 '(org-font-lock-keywords t nil nil backward-paragraph))
6272 (kill-local-variable 'font-lock-keywords) nil))
6274 (defun org-toggle-pretty-entities ()
6275 "Toggle the composition display of entities as UTF8 characters."
6276 (interactive)
6277 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6278 (org-restart-font-lock)
6279 (if org-pretty-entities
6280 (message "Entities are now displayed as UTF8 characters")
6281 (save-restriction
6282 (widen)
6283 (org-decompose-region (point-min) (point-max))
6284 (message "Entities are now displayed as plain text"))))
6286 (defvar org-custom-properties-overlays nil
6287 "List of overlays used for custom properties.")
6288 (make-variable-buffer-local 'org-custom-properties-overlays)
6290 (defun org-toggle-custom-properties-visibility ()
6291 "Display or hide properties in `org-custom-properties'."
6292 (interactive)
6293 (if org-custom-properties-overlays
6294 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6295 (setq org-custom-properties-overlays nil))
6296 (unless (not org-custom-properties)
6297 (save-excursion
6298 (save-restriction
6299 (widen)
6300 (goto-char (point-min))
6301 (while (re-search-forward org-property-re nil t)
6302 (mapc (lambda(p)
6303 (when (equal p (substring (match-string 1) 1 -1))
6304 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6305 (overlay-put o 'invisible t)
6306 (overlay-put o 'org-custom-property t)
6307 (push o org-custom-properties-overlays))))
6308 org-custom-properties)))))))
6310 (defun org-fontify-entities (limit)
6311 "Find an entity to fontify."
6312 (let (ee)
6313 (when org-pretty-entities
6314 (catch 'match
6315 (while (re-search-forward
6316 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6317 limit t)
6318 (if (and (not (org-in-indented-comment-line))
6319 (setq ee (org-entity-get (match-string 1)))
6320 (= (length (nth 6 ee)) 1))
6321 (let*
6322 ((end (if (equal (match-string 2) "{}")
6323 (match-end 2)
6324 (match-end 1))))
6325 (add-text-properties
6326 (match-beginning 0) end
6327 (list 'font-lock-fontified t))
6328 (compose-region (match-beginning 0) end
6329 (nth 6 ee) nil)
6330 (backward-char 1)
6331 (throw 'match t))))
6332 nil))))
6334 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6335 "Fontify string S like in Org-mode."
6336 (with-temp-buffer
6337 (insert s)
6338 (let ((org-odd-levels-only odd-levels))
6339 (org-mode)
6340 (font-lock-fontify-buffer)
6341 (buffer-string))))
6343 (defvar org-m nil)
6344 (defvar org-l nil)
6345 (defvar org-f nil)
6346 (defun org-get-level-face (n)
6347 "Get the right face for match N in font-lock matching of headlines."
6348 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6349 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6350 (if org-cycle-level-faces
6351 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6352 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6353 (cond
6354 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6355 ((eq n 2) org-f)
6356 (t (if org-level-color-stars-only nil org-f))))
6359 (defun org-get-todo-face (kwd)
6360 "Get the right face for a TODO keyword KWD.
6361 If KWD is a number, get the corresponding match group."
6362 (if (numberp kwd) (setq kwd (match-string kwd)))
6363 (or (org-face-from-face-or-color
6364 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6365 (and (member kwd org-done-keywords) 'org-done)
6366 'org-todo))
6368 (defun org-face-from-face-or-color (context inherit face-or-color)
6369 "Create a face list that inherits INHERIT, but sets the foreground color.
6370 When FACE-OR-COLOR is not a string, just return it."
6371 (if (stringp face-or-color)
6372 (list :inherit inherit
6373 (cdr (assoc context org-faces-easy-properties))
6374 face-or-color)
6375 face-or-color))
6377 (defun org-font-lock-add-tag-faces (limit)
6378 "Add the special tag faces."
6379 (when (and org-tag-faces org-tags-special-faces-re)
6380 (while (re-search-forward org-tags-special-faces-re limit t)
6381 (add-text-properties (match-beginning 1) (match-end 1)
6382 (list 'face (org-get-tag-face 1)
6383 'font-lock-fontified t))
6384 (backward-char 1))))
6386 (defun org-font-lock-add-priority-faces (limit)
6387 "Add the special priority faces."
6388 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6389 (when (save-match-data (org-at-heading-p))
6390 (add-text-properties
6391 (match-beginning 0) (match-end 0)
6392 (list 'face (or (org-face-from-face-or-color
6393 'priority 'org-priority
6394 (cdr (assoc (char-after (match-beginning 1))
6395 org-priority-faces)))
6396 'org-priority)
6397 'font-lock-fontified t)))))
6399 (defun org-get-tag-face (kwd)
6400 "Get the right face for a TODO keyword KWD.
6401 If KWD is a number, get the corresponding match group."
6402 (if (numberp kwd) (setq kwd (match-string kwd)))
6403 (or (org-face-from-face-or-color
6404 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6405 'org-tag))
6407 (defun org-unfontify-region (beg end &optional maybe_loudly)
6408 "Remove fontification and activation overlays from links."
6409 (font-lock-default-unfontify-region beg end)
6410 (let* ((buffer-undo-list t)
6411 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6412 (inhibit-modification-hooks t)
6413 deactivate-mark buffer-file-name buffer-file-truename)
6414 (org-decompose-region beg end)
6415 (remove-text-properties beg end
6416 '(mouse-face t keymap t org-linked-text t
6417 invisible t intangible t
6418 org-no-flyspell t org-emphasis t))
6419 (org-remove-font-lock-display-properties beg end)))
6421 (defconst org-script-display '(((raise -0.3) (height 0.7))
6422 ((raise 0.3) (height 0.7))
6423 ((raise -0.5))
6424 ((raise 0.5)))
6425 "Display properties for showing superscripts and subscripts.")
6427 (defun org-remove-font-lock-display-properties (beg end)
6428 "Remove specific display properties that have been added by font lock.
6429 The will remove the raise properties that are used to show superscripts
6430 and subscripts."
6431 (let (next prop)
6432 (while (< beg end)
6433 (setq next (next-single-property-change beg 'display nil end)
6434 prop (get-text-property beg 'display))
6435 (if (member prop org-script-display)
6436 (put-text-property beg next 'display nil))
6437 (setq beg next))))
6439 (defun org-raise-scripts (limit)
6440 "Add raise properties to sub/superscripts."
6441 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6442 (if (re-search-forward
6443 (if (eq org-use-sub-superscripts t)
6444 org-match-substring-regexp
6445 org-match-substring-with-braces-regexp)
6446 limit t)
6447 (let* ((pos (point)) table-p comment-p
6448 (mpos (match-beginning 3))
6449 (emph-p (get-text-property mpos 'org-emphasis))
6450 (link-p (get-text-property mpos 'mouse-face))
6451 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6452 (goto-char (point-at-bol))
6453 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6454 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6455 (goto-char pos)
6456 ;; Handle a_b^c
6457 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6458 (if (or comment-p emph-p link-p keyw-p)
6460 (put-text-property (match-beginning 3) (match-end 0)
6461 'display
6462 (if (equal (char-after (match-beginning 2)) ?^)
6463 (nth (if table-p 3 1) org-script-display)
6464 (nth (if table-p 2 0) org-script-display)))
6465 (add-text-properties (match-beginning 2) (match-end 2)
6466 (list 'invisible t
6467 'org-dwidth t 'org-dwidth-n 1))
6468 (if (and (eq (char-after (match-beginning 3)) ?{)
6469 (eq (char-before (match-end 3)) ?}))
6470 (progn
6471 (add-text-properties
6472 (match-beginning 3) (1+ (match-beginning 3))
6473 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6474 (add-text-properties
6475 (1- (match-end 3)) (match-end 3)
6476 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6477 t)))))
6479 ;;;; Visibility cycling, including org-goto and indirect buffer
6481 ;;; Cycling
6483 (defvar org-cycle-global-status nil)
6484 (make-variable-buffer-local 'org-cycle-global-status)
6485 (put 'org-cycle-global-status 'org-state t)
6486 (defvar org-cycle-subtree-status nil)
6487 (make-variable-buffer-local 'org-cycle-subtree-status)
6488 (put 'org-cycle-subtree-status 'org-state t)
6490 (defvar org-inlinetask-min-level)
6492 (defun org-unlogged-message (&rest args)
6493 "Display a message, but avoid logging it in the *Messages* buffer."
6494 (let ((message-log-max nil))
6495 (apply 'message args)))
6497 ;;;###autoload
6498 (defun org-cycle (&optional arg)
6499 "TAB-action and visibility cycling for Org-mode.
6501 This is the command invoked in Org-mode by the TAB key. Its main purpose
6502 is outline visibility cycling, but it also invokes other actions
6503 in special contexts.
6505 - When this function is called with a prefix argument, rotate the entire
6506 buffer through 3 states (global cycling)
6507 1. OVERVIEW: Show only top-level headlines.
6508 2. CONTENTS: Show all headlines of all levels, but no body text.
6509 3. SHOW ALL: Show everything.
6510 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6511 determined by the variable `org-startup-folded', and by any VISIBILITY
6512 properties in the buffer.
6513 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6514 including any drawers.
6516 - When inside a table, re-align the table and move to the next field.
6518 - When point is at the beginning of a headline, rotate the subtree started
6519 by this line through 3 different states (local cycling)
6520 1. FOLDED: Only the main headline is shown.
6521 2. CHILDREN: The main headline and the direct children are shown.
6522 From this state, you can move to one of the children
6523 and zoom in further.
6524 3. SUBTREE: Show the entire subtree, including body text.
6525 If there is no subtree, switch directly from CHILDREN to FOLDED.
6527 - When point is at the beginning of an empty headline and the variable
6528 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6529 of the headline by demoting and promoting it to likely levels. This
6530 speeds up creation document structure by pressing TAB once or several
6531 times right after creating a new headline.
6533 - When there is a numeric prefix, go up to a heading with level ARG, do
6534 a `show-subtree' and return to the previous cursor position. If ARG
6535 is negative, go up that many levels.
6537 - When point is not at the beginning of a headline, execute the global
6538 binding for TAB, which is re-indenting the line. See the option
6539 `org-cycle-emulate-tab' for details.
6541 - Special case: if point is at the beginning of the buffer and there is
6542 no headline in line 1, this function will act as if called with prefix arg
6543 (C-u TAB, same as S-TAB) also when called without prefix arg.
6544 But only if also the variable `org-cycle-global-at-bob' is t."
6545 (interactive "P")
6546 (org-load-modules-maybe)
6547 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6548 (and org-cycle-level-after-item/entry-creation
6549 (or (org-cycle-level)
6550 (org-cycle-item-indentation))))
6551 (let* ((limit-level
6552 (or org-cycle-max-level
6553 (and (boundp 'org-inlinetask-min-level)
6554 org-inlinetask-min-level
6555 (1- org-inlinetask-min-level))))
6556 (nstars (and limit-level
6557 (if org-odd-levels-only
6558 (and limit-level (1- (* limit-level 2)))
6559 limit-level)))
6560 (org-outline-regexp
6561 (if (not (derived-mode-p 'org-mode))
6562 outline-regexp
6563 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6564 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6565 (not (looking-at org-outline-regexp))))
6566 (org-cycle-hook
6567 (if bob-special
6568 (delq 'org-optimize-window-after-visibility-change
6569 (copy-sequence org-cycle-hook))
6570 org-cycle-hook))
6571 (pos (point)))
6573 (if (or bob-special (equal arg '(4)))
6574 ;; special case: use global cycling
6575 (setq arg t))
6577 (cond
6579 ((equal arg '(16))
6580 (setq last-command 'dummy)
6581 (org-set-startup-visibility)
6582 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6584 ((equal arg '(64))
6585 (show-all)
6586 (org-unlogged-message "Entire buffer visible, including drawers"))
6588 ;; Table: enter it or move to the next field.
6589 ((org-at-table-p 'any)
6590 (if (org-at-table.el-p)
6591 (message "Use C-c ' to edit table.el tables")
6592 (if arg (org-table-edit-field t)
6593 (org-table-justify-field-maybe)
6594 (call-interactively 'org-table-next-field))))
6596 ((run-hook-with-args-until-success
6597 'org-tab-after-check-for-table-hook))
6599 ;; Global cycling: delegate to `org-cycle-internal-global'.
6600 ((eq arg t) (org-cycle-internal-global))
6602 ;; Drawers: delegate to `org-flag-drawer'.
6603 ((save-excursion
6604 (beginning-of-line 1)
6605 (looking-at org-drawer-regexp))
6606 (org-flag-drawer ; toggle block visibility
6607 (not (get-char-property (match-end 0) 'invisible))))
6609 ;; Show-subtree, ARG levels up from here.
6610 ((integerp arg)
6611 (save-excursion
6612 (org-back-to-heading)
6613 (outline-up-heading (if (< arg 0) (- arg)
6614 (- (funcall outline-level) arg)))
6615 (org-show-subtree)))
6617 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6618 ((and (featurep 'org-inlinetask)
6619 (org-inlinetask-at-task-p)
6620 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6621 (org-inlinetask-toggle-visibility))
6623 ((org-try-cdlatex-tab))
6625 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6626 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6627 (save-excursion (beginning-of-line 1)
6628 (looking-at org-outline-regexp)))
6629 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6630 (org-cycle-internal-local))
6632 ;; From there: TAB emulation and template completion.
6633 (buffer-read-only (org-back-to-heading))
6635 ((run-hook-with-args-until-success
6636 'org-tab-after-check-for-cycling-hook))
6638 ((org-try-structure-completion))
6640 ((run-hook-with-args-until-success
6641 'org-tab-before-tab-emulation-hook))
6643 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6644 (or (not (bolp))
6645 (not (looking-at org-outline-regexp))))
6646 (call-interactively (global-key-binding "\t")))
6648 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6649 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6650 (or (and (eq org-cycle-emulate-tab 'white)
6651 (= (match-end 0) (point-at-eol)))
6652 (and (eq org-cycle-emulate-tab 'whitestart)
6653 (>= (match-end 0) pos))))
6655 (eq org-cycle-emulate-tab t))
6656 (call-interactively (global-key-binding "\t")))
6658 (t (save-excursion
6659 (org-back-to-heading)
6660 (org-cycle)))))))
6662 (defun org-cycle-internal-global ()
6663 "Do the global cycling action."
6664 ;; Hack to avoid display of messages for .org attachments in Gnus
6665 (let ((ga (string-match "\\*fontification" (buffer-name))))
6666 (cond
6667 ((and (eq last-command this-command)
6668 (eq org-cycle-global-status 'overview))
6669 ;; We just created the overview - now do table of contents
6670 ;; This can be slow in very large buffers, so indicate action
6671 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6672 (unless ga (org-unlogged-message "CONTENTS..."))
6673 (org-content)
6674 (unless ga (org-unlogged-message "CONTENTS...done"))
6675 (setq org-cycle-global-status 'contents)
6676 (run-hook-with-args 'org-cycle-hook 'contents))
6678 ((and (eq last-command this-command)
6679 (eq org-cycle-global-status 'contents))
6680 ;; We just showed the table of contents - now show everything
6681 (run-hook-with-args 'org-pre-cycle-hook 'all)
6682 (show-all)
6683 (unless ga (org-unlogged-message "SHOW ALL"))
6684 (setq org-cycle-global-status 'all)
6685 (run-hook-with-args 'org-cycle-hook 'all))
6688 ;; Default action: go to overview
6689 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6690 (org-overview)
6691 (unless ga (org-unlogged-message "OVERVIEW"))
6692 (setq org-cycle-global-status 'overview)
6693 (run-hook-with-args 'org-cycle-hook 'overview)))))
6695 (defun org-cycle-internal-local ()
6696 "Do the local cycling action."
6697 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6698 ;; First, determine end of headline (EOH), end of subtree or item
6699 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6700 (save-excursion
6701 (if (org-at-item-p)
6702 (progn
6703 (beginning-of-line)
6704 (setq struct (org-list-struct))
6705 (setq eoh (point-at-eol))
6706 (setq eos (org-list-get-item-end-before-blank (point) struct))
6707 (setq has-children (org-list-has-child-p (point) struct)))
6708 (org-back-to-heading)
6709 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6710 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6711 (setq has-children
6712 (or (save-excursion
6713 (let ((level (funcall outline-level)))
6714 (outline-next-heading)
6715 (and (org-at-heading-p t)
6716 (> (funcall outline-level) level))))
6717 (save-excursion
6718 (org-list-search-forward (org-item-beginning-re) eos t)))))
6719 ;; Determine end invisible part of buffer (EOL)
6720 (beginning-of-line 2)
6721 ;; XEmacs doesn't have `next-single-char-property-change'
6722 (if (featurep 'xemacs)
6723 (while (and (not (eobp)) ;; this is like `next-line'
6724 (get-char-property (1- (point)) 'invisible))
6725 (beginning-of-line 2))
6726 (while (and (not (eobp)) ;; this is like `next-line'
6727 (get-char-property (1- (point)) 'invisible))
6728 (goto-char (next-single-char-property-change (point) 'invisible))
6729 (and (eolp) (beginning-of-line 2))))
6730 (setq eol (point)))
6731 ;; Find out what to do next and set `this-command'
6732 (cond
6733 ((= eos eoh)
6734 ;; Nothing is hidden behind this heading
6735 (unless (org-before-first-heading-p)
6736 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6737 (org-unlogged-message "EMPTY ENTRY")
6738 (setq org-cycle-subtree-status nil)
6739 (save-excursion
6740 (goto-char eos)
6741 (outline-next-heading)
6742 (if (outline-invisible-p) (org-flag-heading nil))))
6743 ((and (or (>= eol eos)
6744 (not (string-match "\\S-" (buffer-substring eol eos))))
6745 (or has-children
6746 (not (setq children-skipped
6747 org-cycle-skip-children-state-if-no-children))))
6748 ;; Entire subtree is hidden in one line: children view
6749 (unless (org-before-first-heading-p)
6750 (run-hook-with-args 'org-pre-cycle-hook 'children))
6751 (if (org-at-item-p)
6752 (org-list-set-item-visibility (point-at-bol) struct 'children)
6753 (org-show-entry)
6754 (org-with-limited-levels (show-children))
6755 ;; FIXME: This slows down the func way too much.
6756 ;; How keep drawers hidden in subtree anyway?
6757 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6758 ;; (org-cycle-hide-drawers 'subtree))
6760 ;; Fold every list in subtree to top-level items.
6761 (when (eq org-cycle-include-plain-lists 'integrate)
6762 (save-excursion
6763 (org-back-to-heading)
6764 (while (org-list-search-forward (org-item-beginning-re) eos t)
6765 (beginning-of-line 1)
6766 (let* ((struct (org-list-struct))
6767 (prevs (org-list-prevs-alist struct))
6768 (end (org-list-get-bottom-point struct)))
6769 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6770 (org-list-get-all-items (point) struct prevs))
6771 (goto-char (if (< end eos) end eos)))))))
6772 (org-unlogged-message "CHILDREN")
6773 (save-excursion
6774 (goto-char eos)
6775 (outline-next-heading)
6776 (if (outline-invisible-p) (org-flag-heading nil)))
6777 (setq org-cycle-subtree-status 'children)
6778 (unless (org-before-first-heading-p)
6779 (run-hook-with-args 'org-cycle-hook 'children)))
6780 ((or children-skipped
6781 (and (eq last-command this-command)
6782 (eq org-cycle-subtree-status 'children)))
6783 ;; We just showed the children, or no children are there,
6784 ;; now show everything.
6785 (unless (org-before-first-heading-p)
6786 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6787 (outline-flag-region eoh eos nil)
6788 (org-unlogged-message
6789 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6790 (setq org-cycle-subtree-status 'subtree)
6791 (unless (org-before-first-heading-p)
6792 (run-hook-with-args 'org-cycle-hook 'subtree)))
6794 ;; Default action: hide the subtree.
6795 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6796 (outline-flag-region eoh eos t)
6797 (org-unlogged-message "FOLDED")
6798 (setq org-cycle-subtree-status 'folded)
6799 (unless (org-before-first-heading-p)
6800 (run-hook-with-args 'org-cycle-hook 'folded))))))
6802 ;;;###autoload
6803 (defun org-global-cycle (&optional arg)
6804 "Cycle the global visibility. For details see `org-cycle'.
6805 With \\[universal-argument] prefix arg, switch to startup visibility.
6806 With a numeric prefix, show all headlines up to that level."
6807 (interactive "P")
6808 (let ((org-cycle-include-plain-lists
6809 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6810 (cond
6811 ((integerp arg)
6812 (show-all)
6813 (hide-sublevels arg)
6814 (setq org-cycle-global-status 'contents))
6815 ((equal arg '(4))
6816 (org-set-startup-visibility)
6817 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6819 (org-cycle '(4))))))
6821 (defun org-set-startup-visibility ()
6822 "Set the visibility required by startup options and properties."
6823 (cond
6824 ((eq org-startup-folded t)
6825 (org-cycle '(4)))
6826 ((eq org-startup-folded 'content)
6827 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6828 (org-cycle '(4)) (org-cycle '(4)))))
6829 (unless (eq org-startup-folded 'showeverything)
6830 (if org-hide-block-startup (org-hide-block-all))
6831 (org-set-visibility-according-to-property 'no-cleanup)
6832 (org-cycle-hide-archived-subtrees 'all)
6833 (org-cycle-hide-drawers 'all)
6834 (org-cycle-show-empty-lines t)))
6836 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6837 "Switch subtree visibilities according to :VISIBILITY: property."
6838 (interactive)
6839 (let (org-show-entry-below state)
6840 (save-excursion
6841 (goto-char (point-min))
6842 (while (re-search-forward
6843 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6844 nil t)
6845 (setq state (match-string 1))
6846 (save-excursion
6847 (org-back-to-heading t)
6848 (hide-subtree)
6849 (org-reveal)
6850 (cond
6851 ((equal state '("fold" "folded"))
6852 (hide-subtree))
6853 ((equal state "children")
6854 (org-show-hidden-entry)
6855 (show-children))
6856 ((equal state "content")
6857 (save-excursion
6858 (save-restriction
6859 (org-narrow-to-subtree)
6860 (org-content))))
6861 ((member state '("all" "showall"))
6862 (show-subtree)))))
6863 (unless no-cleanup
6864 (org-cycle-hide-archived-subtrees 'all)
6865 (org-cycle-hide-drawers 'all)
6866 (org-cycle-show-empty-lines 'all)))))
6868 ;; This function uses outline-regexp instead of the more fundamental
6869 ;; org-outline-regexp so that org-cycle-global works outside of Org
6870 ;; buffers, where outline-regexp is needed.
6871 (defun org-overview ()
6872 "Switch to overview mode, showing only top-level headlines.
6873 Really, this shows all headlines with level equal or greater than the level
6874 of the first headline in the buffer. This is important, because if the
6875 first headline is not level one, then (hide-sublevels 1) gives confusing
6876 results."
6877 (interactive)
6878 (let ((pos (point))
6879 (level (save-excursion
6880 (goto-char (point-min))
6881 (if (re-search-forward (concat "^" outline-regexp) nil t)
6882 (progn
6883 (goto-char (match-beginning 0))
6884 (funcall outline-level))))))
6885 (and level (hide-sublevels level))
6886 (recenter '(4))
6887 (goto-char pos)))
6889 (defun org-content (&optional arg)
6890 "Show all headlines in the buffer, like a table of contents.
6891 With numerical argument N, show content up to level N."
6892 (interactive "P")
6893 (save-excursion
6894 ;; Visit all headings and show their offspring
6895 (and (integerp arg) (org-overview))
6896 (goto-char (point-max))
6897 (catch 'exit
6898 (while (and (progn (condition-case nil
6899 (outline-previous-visible-heading 1)
6900 (error (goto-char (point-min))))
6902 (looking-at org-outline-regexp))
6903 (if (integerp arg)
6904 (show-children (1- arg))
6905 (show-branches))
6906 (if (bobp) (throw 'exit nil))))))
6909 (defun org-optimize-window-after-visibility-change (state)
6910 "Adjust the window after a change in outline visibility.
6911 This function is the default value of the hook `org-cycle-hook'."
6912 (when (get-buffer-window (current-buffer))
6913 (cond
6914 ((eq state 'content) nil)
6915 ((eq state 'all) nil)
6916 ((eq state 'folded) nil)
6917 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6918 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6920 (defun org-remove-empty-overlays-at (pos)
6921 "Remove outline overlays that do not contain non-white stuff."
6922 (mapc
6923 (lambda (o)
6924 (and (eq 'outline (overlay-get o 'invisible))
6925 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6926 (overlay-end o))))
6927 (delete-overlay o)))
6928 (overlays-at pos)))
6930 (defun org-clean-visibility-after-subtree-move ()
6931 "Fix visibility issues after moving a subtree."
6932 ;; First, find a reasonable region to look at:
6933 ;; Start two siblings above, end three below
6934 (let* ((beg (save-excursion
6935 (and (org-get-last-sibling)
6936 (org-get-last-sibling))
6937 (point)))
6938 (end (save-excursion
6939 (and (org-get-next-sibling)
6940 (org-get-next-sibling)
6941 (org-get-next-sibling))
6942 (if (org-at-heading-p)
6943 (point-at-eol)
6944 (point))))
6945 (level (looking-at "\\*+"))
6946 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6947 (save-excursion
6948 (save-restriction
6949 (narrow-to-region beg end)
6950 (when re
6951 ;; Properly fold already folded siblings
6952 (goto-char (point-min))
6953 (while (re-search-forward re nil t)
6954 (if (and (not (outline-invisible-p))
6955 (save-excursion
6956 (goto-char (point-at-eol)) (outline-invisible-p)))
6957 (hide-entry))))
6958 (org-cycle-show-empty-lines 'overview)
6959 (org-cycle-hide-drawers 'overview)))))
6961 (defun org-cycle-show-empty-lines (state)
6962 "Show empty lines above all visible headlines.
6963 The region to be covered depends on STATE when called through
6964 `org-cycle-hook'. Lisp program can use t for STATE to get the
6965 entire buffer covered. Note that an empty line is only shown if there
6966 are at least `org-cycle-separator-lines' empty lines before the headline."
6967 (when (not (= org-cycle-separator-lines 0))
6968 (save-excursion
6969 (let* ((n (abs org-cycle-separator-lines))
6970 (re (cond
6971 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6972 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6973 (t (let ((ns (number-to-string (- n 2))))
6974 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6975 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6976 beg end b e)
6977 (cond
6978 ((memq state '(overview contents t))
6979 (setq beg (point-min) end (point-max)))
6980 ((memq state '(children folded))
6981 (setq beg (point) end (progn (org-end-of-subtree t t)
6982 (beginning-of-line 2)
6983 (point)))))
6984 (when beg
6985 (goto-char beg)
6986 (while (re-search-forward re end t)
6987 (unless (get-char-property (match-end 1) 'invisible)
6988 (setq e (match-end 1))
6989 (if (< org-cycle-separator-lines 0)
6990 (setq b (save-excursion
6991 (goto-char (match-beginning 0))
6992 (org-back-over-empty-lines)
6993 (if (save-excursion
6994 (goto-char (max (point-min) (1- (point))))
6995 (org-at-heading-p))
6996 (1- (point))
6997 (point))))
6998 (setq b (match-beginning 1)))
6999 (outline-flag-region b e nil)))))))
7000 ;; Never hide empty lines at the end of the file.
7001 (save-excursion
7002 (goto-char (point-max))
7003 (outline-previous-heading)
7004 (outline-end-of-heading)
7005 (if (and (looking-at "[ \t\n]+")
7006 (= (match-end 0) (point-max)))
7007 (outline-flag-region (point) (match-end 0) nil))))
7009 (defun org-show-empty-lines-in-parent ()
7010 "Move to the parent and re-show empty lines before visible headlines."
7011 (save-excursion
7012 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7013 (org-cycle-show-empty-lines context))))
7015 (defun org-files-list ()
7016 "Return `org-agenda-files' list, plus all open org-mode files.
7017 This is useful for operations that need to scan all of a user's
7018 open and agenda-wise Org files."
7019 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7020 (dolist (buf (buffer-list))
7021 (with-current-buffer buf
7022 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7023 (let ((file (expand-file-name (buffer-file-name))))
7024 (unless (member file files)
7025 (push file files))))))
7026 files))
7028 (defsubst org-entry-beginning-position ()
7029 "Return the beginning position of the current entry."
7030 (save-excursion (outline-back-to-heading t) (point)))
7032 (defsubst org-entry-end-position ()
7033 "Return the end position of the current entry."
7034 (save-excursion (outline-next-heading) (point)))
7036 (defun org-cycle-hide-drawers (state &optional exceptions)
7037 "Re-hide all drawers after a visibility state change.
7038 When non-nil, optional argument EXCEPTIONS is a list of strings
7039 specifying which drawers should not be hidden."
7040 (when (and (derived-mode-p 'org-mode)
7041 (not (memq state '(overview folded contents))))
7042 (save-excursion
7043 (let* ((globalp (memq state '(contents all)))
7044 (beg (if globalp (point-min) (point)))
7045 (end (if globalp (point-max)
7046 (if (eq state 'children)
7047 (save-excursion (outline-next-heading) (point))
7048 (org-end-of-subtree t)))))
7049 (goto-char beg)
7050 (while (re-search-forward org-drawer-regexp end t)
7051 (unless (member-ignore-case (match-string 1) exceptions)
7052 (org-flag-drawer t)))))))
7054 (defun org-cycle-hide-inline-tasks (state)
7055 "Re-hide inline task when switching to 'contents visibility state."
7056 (when (and (eq state 'contents)
7057 (boundp 'org-inlinetask-min-level)
7058 org-inlinetask-min-level)
7059 (hide-sublevels (1- org-inlinetask-min-level))))
7061 (defun org-flag-drawer (flag &optional element)
7062 "When FLAG is non-nil, hide the drawer we are at.
7063 Otherwise make it visible. When optional argument ELEMENT is
7064 a parsed drawer, as returned by `org-element-at-point', hide or
7065 show that drawer instead."
7066 (let ((drawer (or element (org-element-at-point))))
7067 (when (memq (org-element-type drawer) '(drawer property-drawer))
7068 (save-excursion
7069 (goto-char (org-element-property :post-affiliated drawer))
7070 (outline-flag-region
7071 (line-end-position)
7072 (progn (goto-char (org-element-property :end drawer))
7073 (skip-chars-backward " \r\t\n")
7074 (line-end-position))
7075 flag)))))
7077 (defun org-subtree-end-visible-p ()
7078 "Is the end of the current subtree visible?"
7079 (pos-visible-in-window-p
7080 (save-excursion (org-end-of-subtree t) (point))))
7082 (defun org-first-headline-recenter (&optional N)
7083 "Move cursor to the first headline and recenter the headline.
7084 Optional argument N means put the headline into the Nth line of the window."
7085 (goto-char (point-min))
7086 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7087 (beginning-of-line)
7088 (recenter (prefix-numeric-value N))))
7090 ;;; Saving and restoring visibility
7092 (defun org-outline-overlay-data (&optional use-markers)
7093 "Return a list of the locations of all outline overlays.
7094 These are overlays with the `invisible' property value `outline'.
7095 The return value is a list of cons cells, with start and stop
7096 positions for each overlay.
7097 If USE-MARKERS is set, return the positions as markers."
7098 (let (beg end)
7099 (save-excursion
7100 (save-restriction
7101 (widen)
7102 (delq nil
7103 (mapcar (lambda (o)
7104 (when (eq (overlay-get o 'invisible) 'outline)
7105 (setq beg (overlay-start o)
7106 end (overlay-end o))
7107 (and beg end (> end beg)
7108 (if use-markers
7109 (cons (move-marker (make-marker) beg)
7110 (move-marker (make-marker) end))
7111 (cons beg end)))))
7112 (overlays-in (point-min) (point-max))))))))
7114 (defun org-set-outline-overlay-data (data)
7115 "Create visibility overlays for all positions in DATA.
7116 DATA should have been made by `org-outline-overlay-data'."
7117 (let (o)
7118 (save-excursion
7119 (save-restriction
7120 (widen)
7121 (show-all)
7122 (mapc (lambda (c)
7123 (outline-flag-region (car c) (cdr c) t))
7124 data)))))
7126 ;;; Folding of blocks
7128 (defvar org-hide-block-overlays nil
7129 "Overlays hiding blocks.")
7130 (make-variable-buffer-local 'org-hide-block-overlays)
7132 (defun org-block-map (function &optional start end)
7133 "Call FUNCTION at the head of all source blocks in the current buffer.
7134 Optional arguments START and END can be used to limit the range."
7135 (let ((start (or start (point-min)))
7136 (end (or end (point-max))))
7137 (save-excursion
7138 (goto-char start)
7139 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7140 (save-excursion
7141 (save-match-data
7142 (goto-char (match-beginning 0))
7143 (funcall function)))))))
7145 (defun org-hide-block-toggle-all ()
7146 "Toggle the visibility of all blocks in the current buffer."
7147 (org-block-map #'org-hide-block-toggle))
7149 (defun org-hide-block-all ()
7150 "Fold all blocks in the current buffer."
7151 (interactive)
7152 (org-show-block-all)
7153 (org-block-map #'org-hide-block-toggle-maybe))
7155 (defun org-show-block-all ()
7156 "Unfold all blocks in the current buffer."
7157 (interactive)
7158 (mapc 'delete-overlay org-hide-block-overlays)
7159 (setq org-hide-block-overlays nil))
7161 (defun org-hide-block-toggle-maybe ()
7162 "Toggle visibility of block at point."
7163 (interactive)
7164 (let ((case-fold-search t))
7165 (if (save-excursion
7166 (beginning-of-line 1)
7167 (looking-at org-block-regexp))
7168 (progn (org-hide-block-toggle)
7169 t) ;; to signal that we took action
7170 nil))) ;; to signal that we did not
7172 (defun org-hide-block-toggle (&optional force)
7173 "Toggle the visibility of the current block."
7174 (interactive)
7175 (save-excursion
7176 (beginning-of-line)
7177 (if (re-search-forward org-block-regexp nil t)
7178 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7179 (end (match-end 0)) ;; end of entire body
7181 (if (memq t (mapcar (lambda (overlay)
7182 (eq (overlay-get overlay 'invisible)
7183 'org-hide-block))
7184 (overlays-at start)))
7185 (if (or (not force) (eq force 'off))
7186 (mapc (lambda (ov)
7187 (when (member ov org-hide-block-overlays)
7188 (setq org-hide-block-overlays
7189 (delq ov org-hide-block-overlays)))
7190 (when (eq (overlay-get ov 'invisible)
7191 'org-hide-block)
7192 (delete-overlay ov)))
7193 (overlays-at start)))
7194 (setq ov (make-overlay start end))
7195 (overlay-put ov 'invisible 'org-hide-block)
7196 ;; make the block accessible to isearch
7197 (overlay-put
7198 ov 'isearch-open-invisible
7199 (lambda (ov)
7200 (when (member ov org-hide-block-overlays)
7201 (setq org-hide-block-overlays
7202 (delq ov org-hide-block-overlays)))
7203 (when (eq (overlay-get ov 'invisible)
7204 'org-hide-block)
7205 (delete-overlay ov))))
7206 (push ov org-hide-block-overlays)))
7207 (user-error "Not looking at a source block"))))
7209 ;; org-tab-after-check-for-cycling-hook
7210 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7211 ;; Remove overlays when changing major mode
7212 (add-hook 'org-mode-hook
7213 (lambda () (org-add-hook 'change-major-mode-hook
7214 'org-show-block-all 'append 'local)))
7216 ;;; Org-goto
7218 (defvar org-goto-window-configuration nil)
7219 (defvar org-goto-marker nil)
7220 (defvar org-goto-map)
7221 (defun org-goto-map ()
7222 "Set the keymap `org-goto'."
7223 (setq org-goto-map
7224 (let ((map (make-sparse-keymap)))
7225 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7226 mouse-drag-region universal-argument org-occur))
7227 cmd)
7228 (while (setq cmd (pop cmds))
7229 (substitute-key-definition cmd cmd map global-map)))
7230 (suppress-keymap map)
7231 (org-defkey map "\C-m" 'org-goto-ret)
7232 (org-defkey map [(return)] 'org-goto-ret)
7233 (org-defkey map [(left)] 'org-goto-left)
7234 (org-defkey map [(right)] 'org-goto-right)
7235 (org-defkey map [(control ?g)] 'org-goto-quit)
7236 (org-defkey map "\C-i" 'org-cycle)
7237 (org-defkey map [(tab)] 'org-cycle)
7238 (org-defkey map [(down)] 'outline-next-visible-heading)
7239 (org-defkey map [(up)] 'outline-previous-visible-heading)
7240 (if org-goto-auto-isearch
7241 (if (fboundp 'define-key-after)
7242 (define-key-after map [t] 'org-goto-local-auto-isearch)
7243 nil)
7244 (org-defkey map "q" 'org-goto-quit)
7245 (org-defkey map "n" 'outline-next-visible-heading)
7246 (org-defkey map "p" 'outline-previous-visible-heading)
7247 (org-defkey map "f" 'outline-forward-same-level)
7248 (org-defkey map "b" 'outline-backward-same-level)
7249 (org-defkey map "u" 'outline-up-heading))
7250 (org-defkey map "/" 'org-occur)
7251 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7252 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7253 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7254 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7255 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7256 map)))
7258 (defconst org-goto-help
7259 "Browse buffer copy, to find location or copy text.%s
7260 RET=jump to location C-g=quit and return to previous location
7261 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7263 (defvar org-goto-start-pos) ; dynamically scoped parameter
7265 (defun org-goto (&optional alternative-interface)
7266 "Look up a different location in the current file, keeping current visibility.
7268 When you want look-up or go to a different location in a
7269 document, the fastest way is often to fold the entire buffer and
7270 then dive into the tree. This method has the disadvantage, that
7271 the previous location will be folded, which may not be what you
7272 want.
7274 This command works around this by showing a copy of the current
7275 buffer in an indirect buffer, in overview mode. You can dive
7276 into the tree in that copy, use org-occur and incremental search
7277 to find a location. When pressing RET or `Q', the command
7278 returns to the original buffer in which the visibility is still
7279 unchanged. After RET it will also jump to the location selected
7280 in the indirect buffer and expose the headline hierarchy above.
7282 With a prefix argument, use the alternative interface: e.g. if
7283 `org-goto-interface' is 'outline use 'outline-path-completion."
7284 (interactive "P")
7285 (org-goto-map)
7286 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7287 (org-refile-use-outline-path t)
7288 (org-refile-target-verify-function nil)
7289 (interface
7290 (if (not alternative-interface)
7291 org-goto-interface
7292 (if (eq org-goto-interface 'outline)
7293 'outline-path-completion
7294 'outline)))
7295 (org-goto-start-pos (point))
7296 (selected-point
7297 (if (eq interface 'outline)
7298 (car (org-get-location (current-buffer) org-goto-help))
7299 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7300 (org-refile-check-position pa)
7301 (nth 3 pa)))))
7302 (if selected-point
7303 (progn
7304 (org-mark-ring-push org-goto-start-pos)
7305 (goto-char selected-point)
7306 (if (or (outline-invisible-p) (org-invisible-p2))
7307 (org-show-context 'org-goto)))
7308 (message "Quit"))))
7310 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7311 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7312 (defvar org-goto-local-auto-isearch-map) ; defined below
7314 (defun org-get-location (buf help)
7315 "Let the user select a location in the Org-mode buffer BUF.
7316 This function uses a recursive edit. It returns the selected position
7317 or nil."
7318 (org-no-popups
7319 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7320 (isearch-hide-immediately nil)
7321 (isearch-search-fun-function
7322 (lambda () 'org-goto-local-search-headings))
7323 (org-goto-selected-point org-goto-exit-command))
7324 (save-excursion
7325 (save-window-excursion
7326 (delete-other-windows)
7327 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7328 (org-pop-to-buffer-same-window
7329 (condition-case nil
7330 (make-indirect-buffer (current-buffer) "*org-goto*")
7331 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7332 (with-output-to-temp-buffer "*Org Help*"
7333 (princ (format help (if org-goto-auto-isearch
7334 " Just type for auto-isearch."
7335 " n/p/f/b/u to navigate, q to quit."))))
7336 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7337 (setq buffer-read-only nil)
7338 (let ((org-startup-truncated t)
7339 (org-startup-folded nil)
7340 (org-startup-align-all-tables nil))
7341 (org-mode)
7342 (org-overview))
7343 (setq buffer-read-only t)
7344 (if (and (boundp 'org-goto-start-pos)
7345 (integer-or-marker-p org-goto-start-pos))
7346 (let ((org-show-hierarchy-above t)
7347 (org-show-siblings t)
7348 (org-show-following-heading t))
7349 (goto-char org-goto-start-pos)
7350 (and (outline-invisible-p) (org-show-context)))
7351 (goto-char (point-min)))
7352 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7353 (message "Select location and press RET")
7354 (use-local-map org-goto-map)
7355 (recursive-edit)))
7356 (kill-buffer "*org-goto*")
7357 (cons org-goto-selected-point org-goto-exit-command))))
7359 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7360 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7361 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7362 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7364 (defun org-goto-local-search-headings (string bound noerror)
7365 "Search and make sure that any matches are in headlines."
7366 (catch 'return
7367 (while (if isearch-forward
7368 (search-forward string bound noerror)
7369 (search-backward string bound noerror))
7370 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7371 (and (member :headline context)
7372 (not (member :tags context))))
7373 (throw 'return (point))))))
7375 (defun org-goto-local-auto-isearch ()
7376 "Start isearch."
7377 (interactive)
7378 (goto-char (point-min))
7379 (let ((keys (this-command-keys)))
7380 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7381 (isearch-mode t)
7382 (isearch-process-search-char (string-to-char keys)))))
7384 (defun org-goto-ret (&optional arg)
7385 "Finish `org-goto' by going to the new location."
7386 (interactive "P")
7387 (setq org-goto-selected-point (point)
7388 org-goto-exit-command 'return)
7389 (throw 'exit nil))
7391 (defun org-goto-left ()
7392 "Finish `org-goto' by going to the new location."
7393 (interactive)
7394 (if (org-at-heading-p)
7395 (progn
7396 (beginning-of-line 1)
7397 (setq org-goto-selected-point (point)
7398 org-goto-exit-command 'left)
7399 (throw 'exit nil))
7400 (user-error "Not on a heading")))
7402 (defun org-goto-right ()
7403 "Finish `org-goto' by going to the new location."
7404 (interactive)
7405 (if (org-at-heading-p)
7406 (progn
7407 (setq org-goto-selected-point (point)
7408 org-goto-exit-command 'right)
7409 (throw 'exit nil))
7410 (user-error "Not on a heading")))
7412 (defun org-goto-quit ()
7413 "Finish `org-goto' without cursor motion."
7414 (interactive)
7415 (setq org-goto-selected-point nil)
7416 (setq org-goto-exit-command 'quit)
7417 (throw 'exit nil))
7419 ;;; Indirect buffer display of subtrees
7421 (defvar org-indirect-dedicated-frame nil
7422 "This is the frame being used for indirect tree display.")
7423 (defvar org-last-indirect-buffer nil)
7425 (defun org-tree-to-indirect-buffer (&optional arg)
7426 "Create indirect buffer and narrow it to current subtree.
7427 With a numerical prefix ARG, go up to this level and then take that tree.
7428 If ARG is negative, go up that many levels.
7430 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7431 indirect buffer previously made with this command, to avoid proliferation of
7432 indirect buffers. However, when you call the command with a \
7433 \\[universal-argument] prefix, or
7434 when `org-indirect-buffer-display' is `new-frame', the last buffer
7435 is kept so that you can work with several indirect buffers at the same time.
7436 If `org-indirect-buffer-display' is `dedicated-frame', the \
7437 \\[universal-argument] prefix also
7438 requests that a new frame be made for the new buffer, so that the dedicated
7439 frame is not changed."
7440 (interactive "P")
7441 (let ((cbuf (current-buffer))
7442 (cwin (selected-window))
7443 (pos (point))
7444 beg end level heading ibuf)
7445 (save-excursion
7446 (org-back-to-heading t)
7447 (when (numberp arg)
7448 (setq level (org-outline-level))
7449 (if (< arg 0) (setq arg (+ level arg)))
7450 (while (> (setq level (org-outline-level)) arg)
7451 (org-up-heading-safe)))
7452 (setq beg (point)
7453 heading (org-get-heading))
7454 (org-end-of-subtree t t)
7455 (if (org-at-heading-p) (backward-char 1))
7456 (setq end (point)))
7457 (if (and (buffer-live-p org-last-indirect-buffer)
7458 (not (eq org-indirect-buffer-display 'new-frame))
7459 (not arg))
7460 (kill-buffer org-last-indirect-buffer))
7461 (setq ibuf (org-get-indirect-buffer cbuf)
7462 org-last-indirect-buffer ibuf)
7463 (cond
7464 ((or (eq org-indirect-buffer-display 'new-frame)
7465 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7466 (select-frame (make-frame))
7467 (delete-other-windows)
7468 (org-pop-to-buffer-same-window ibuf)
7469 (org-set-frame-title heading))
7470 ((eq org-indirect-buffer-display 'dedicated-frame)
7471 (raise-frame
7472 (select-frame (or (and org-indirect-dedicated-frame
7473 (frame-live-p org-indirect-dedicated-frame)
7474 org-indirect-dedicated-frame)
7475 (setq org-indirect-dedicated-frame (make-frame)))))
7476 (delete-other-windows)
7477 (org-pop-to-buffer-same-window ibuf)
7478 (org-set-frame-title (concat "Indirect: " heading)))
7479 ((eq org-indirect-buffer-display 'current-window)
7480 (org-pop-to-buffer-same-window ibuf))
7481 ((eq org-indirect-buffer-display 'other-window)
7482 (pop-to-buffer ibuf))
7483 (t (error "Invalid value")))
7484 (if (featurep 'xemacs)
7485 (save-excursion (org-mode) (turn-on-font-lock)))
7486 (narrow-to-region beg end)
7487 (show-all)
7488 (goto-char pos)
7489 (run-hook-with-args 'org-cycle-hook 'all)
7490 (and (window-live-p cwin) (select-window cwin))))
7492 (defun org-get-indirect-buffer (&optional buffer)
7493 (setq buffer (or buffer (current-buffer)))
7494 (let ((n 1) (base (buffer-name buffer)) bname)
7495 (while (buffer-live-p
7496 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7497 (setq n (1+ n)))
7498 (condition-case nil
7499 (make-indirect-buffer buffer bname 'clone)
7500 (error (make-indirect-buffer buffer bname)))))
7502 (defun org-set-frame-title (title)
7503 "Set the title of the current frame to the string TITLE."
7504 ;; FIXME: how to name a single frame in XEmacs???
7505 (unless (featurep 'xemacs)
7506 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7508 ;;;; Structure editing
7510 ;;; Inserting headlines
7512 (defun org-previous-line-empty-p (&optional next)
7513 "Is the previous line a blank line?
7514 When NEXT is non-nil, check the next line instead."
7515 (save-excursion
7516 (and (not (bobp))
7517 (or (beginning-of-line (if next 2 0)) t)
7518 (save-match-data
7519 (looking-at "[ \t]*$")))))
7521 (defun org-insert-heading (&optional arg invisible-ok)
7522 "Insert a new heading or item with same depth at point.
7523 If point is in a plain list and ARG is nil, create a new list item.
7524 With one universal prefix argument, insert a heading even in lists.
7525 With two universal prefix arguments, insert the heading at the end
7526 of the parent subtree.
7528 If point is at the beginning of a headline, insert a sibling before
7529 the current headline. If point is not at the beginning, split the line
7530 and create a new headline with the text in the current line after point
7531 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7533 If point is at the beginning of a normal line, turn this line into
7534 a heading.
7536 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7537 This is important for non-interactive uses of the command."
7538 (interactive "P")
7539 (if (org-called-interactively-p 'any) (org-reveal))
7540 (let ((itemp (org-in-item-p))
7541 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7542 (respect-content (or org-insert-heading-respect-content
7543 (equal arg '(16))))
7544 (initial-content "")
7545 (adjust-empty-lines t))
7547 (cond
7549 ((or (= (buffer-size) 0)
7550 (and (not (save-excursion
7551 (and (ignore-errors (org-back-to-heading invisible-ok))
7552 (org-at-heading-p))))
7553 (or arg (not itemp))))
7554 ;; At beginning of buffer or so high up that only a heading
7555 ;; makes sense.
7556 (insert
7557 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7558 (if (org-in-src-block-p) ",* " "* "))
7559 (run-hooks 'org-insert-heading-hook))
7561 ((and itemp (not (equal arg '(4))))
7562 ;; Insert an item
7563 (org-insert-item))
7566 ;; Insert a heading
7567 (save-restriction
7568 (widen)
7569 (let* ((level nil)
7570 (on-heading (org-at-heading-p))
7571 (empty-line-p (if on-heading
7572 (org-previous-line-empty-p)
7573 ;; We will decide later
7574 nil))
7575 ;; Get a level string to fall back on
7576 (fix-level
7577 (save-excursion
7578 (org-back-to-heading t)
7579 (if (org-previous-line-empty-p) (setq empty-line-p t))
7580 (looking-at org-outline-regexp)
7581 (make-string (1- (length (match-string 0))) ?*)))
7582 (stars
7583 (save-excursion
7584 (condition-case nil
7585 (progn
7586 (org-back-to-heading invisible-ok)
7587 (when (and (not on-heading)
7588 (featurep 'org-inlinetask)
7589 (integerp org-inlinetask-min-level)
7590 (>= (length (match-string 0))
7591 org-inlinetask-min-level))
7592 ;; Find a heading level before the inline task
7593 (while (and (setq level (org-up-heading-safe))
7594 (>= level org-inlinetask-min-level)))
7595 (if (org-at-heading-p)
7596 (org-back-to-heading invisible-ok)
7597 (error "This should not happen")))
7598 (unless (and (save-excursion
7599 (save-match-data
7600 (org-backward-heading-same-level
7601 1 invisible-ok))
7602 (= (point) (match-beginning 0)))
7603 (not (org-previous-line-empty-p t)))
7604 (setq empty-line-p (or empty-line-p
7605 (org-previous-line-empty-p))))
7606 (match-string 0))
7607 (error (or fix-level "* ")))))
7608 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7609 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7610 pos hide-previous previous-pos)
7612 ;; If we insert after content, move there and clean up whitespace
7613 (when respect-content
7614 (org-end-of-subtree nil t)
7615 (skip-chars-backward " \r\n")
7616 (and (looking-at "[ \t]+") (replace-match ""))
7617 (unless (eobp) (forward-char 1))
7618 (when (looking-at "^\\*")
7619 (unless (bobp) (backward-char 1))
7620 (insert "\n")))
7622 ;; If we are splitting, grab the text that should be moved to the new headline
7623 (when may-split
7624 (if (org-on-heading-p)
7625 ;; This is a heading, we split intelligently (keeping tags)
7626 (let ((pos (point)))
7627 (goto-char (point-at-bol))
7628 (unless (looking-at org-complex-heading-regexp)
7629 (error "This should not happen"))
7630 (when (and (match-beginning 4)
7631 (> pos (match-beginning 4))
7632 (< pos (match-end 4)))
7633 (setq initial-content (buffer-substring pos (match-end 4)))
7634 (goto-char pos)
7635 (delete-region (point) (match-end 4))
7636 (if (looking-at "[ \t]*$")
7637 (replace-match "")
7638 (insert (make-string (length initial-content) ?\ )))
7639 (setq initial-content (org-trim initial-content)))
7640 (goto-char pos))
7641 ;; a normal line
7642 (unless (bolp)
7643 (setq initial-content (buffer-substring (point) (point-at-eol)))
7644 (delete-region (point) (point-at-eol))
7645 (setq initial-content (org-trim initial-content)))))
7647 ;; If we are at the beginning of the line, insert before it. Else after
7648 (cond
7649 ((and (bolp) (looking-at "[ \t]*$")))
7650 ((and (bolp) (not (looking-at "[ \t]*$")))
7651 (open-line 1))
7653 (goto-char (point-at-eol))
7654 (insert "\n")))
7656 ;; Insert the new heading
7657 (insert stars)
7658 (just-one-space)
7659 (insert initial-content)
7660 (when adjust-empty-lines
7661 (if (or (not blank)
7662 (and blank (not (org-previous-line-empty-p))))
7663 (org-N-empty-lines-before-current (if blank 1 0))))
7664 (run-hooks 'org-insert-heading-hook)))))))
7666 (defun org-N-empty-lines-before-current (N)
7667 "Make the number of empty lines before current exactly N.
7668 So this will delete or add empty lines."
7669 (save-excursion
7670 (goto-char (point-at-bol))
7671 (if (looking-back "\\s-+" nil 'greedy)
7672 (replace-match ""))
7673 (or (bobp) (insert "\n"))
7674 (while (> N 0)
7675 (insert "\n")
7676 (setq N (1- N)))))
7678 (defun org-get-heading (&optional no-tags no-todo)
7679 "Return the heading of the current entry, without the stars.
7680 When NO-TAGS is non-nil, don't include tags.
7681 When NO-TODO is non-nil, don't include TODO keywords."
7682 (save-excursion
7683 (org-back-to-heading t)
7684 (cond
7685 ((and no-tags no-todo)
7686 (looking-at org-complex-heading-regexp)
7687 (match-string 4))
7688 (no-tags
7689 (looking-at (concat org-outline-regexp
7690 "\\(.*?\\)"
7691 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7692 (match-string 1))
7693 (no-todo
7694 (looking-at org-todo-line-regexp)
7695 (match-string 3))
7696 (t (looking-at org-heading-regexp)
7697 (match-string 2)))))
7699 (defvar orgstruct-mode) ; defined below
7701 (defun org-heading-components ()
7702 "Return the components of the current heading.
7703 This is a list with the following elements:
7704 - the level as an integer
7705 - the reduced level, different if `org-odd-levels-only' is set.
7706 - the TODO keyword, or nil
7707 - the priority character, like ?A, or nil if no priority is given
7708 - the headline text itself, or the tags string if no headline text
7709 - the tags string, or nil."
7710 (save-excursion
7711 (org-back-to-heading t)
7712 (if (let (case-fold-search)
7713 (looking-at
7714 (if orgstruct-mode
7715 org-heading-regexp
7716 org-complex-heading-regexp)))
7717 (if orgstruct-mode
7718 (list (length (match-string 1))
7719 (org-reduced-level (length (match-string 1)))
7722 (match-string 2)
7723 nil)
7724 (list (length (match-string 1))
7725 (org-reduced-level (length (match-string 1)))
7726 (org-match-string-no-properties 2)
7727 (and (match-end 3) (aref (match-string 3) 2))
7728 (org-match-string-no-properties 4)
7729 (org-match-string-no-properties 5))))))
7731 (defun org-get-entry ()
7732 "Get the entry text, after heading, entire subtree."
7733 (save-excursion
7734 (org-back-to-heading t)
7735 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7737 (defun org-insert-heading-after-current ()
7738 "Insert a new heading with same level as current, after current subtree."
7739 (interactive)
7740 (org-back-to-heading)
7741 (org-insert-heading)
7742 (org-move-subtree-down)
7743 (end-of-line 1))
7745 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7746 "Insert heading with `org-insert-heading-respect-content' set to t."
7747 (interactive "P")
7748 (let ((org-insert-heading-respect-content t))
7749 (org-insert-heading '(4) invisible-ok)))
7751 (defun org-insert-todo-heading-respect-content (&optional force-state)
7752 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7753 (interactive "P")
7754 (let ((org-insert-heading-respect-content t))
7755 (org-insert-todo-heading force-state '(4))))
7757 (defun org-insert-todo-heading (arg &optional force-heading)
7758 "Insert a new heading with the same level and TODO state as current heading.
7759 If the heading has no TODO state, or if the state is DONE, use the first
7760 state (TODO by default). Also one prefix arg, force first state. With two
7761 prefix args, force inserting at the end of the parent subtree."
7762 (interactive "P")
7763 (when (or force-heading (not (org-insert-item 'checkbox)))
7764 (org-insert-heading (or (and (equal arg '(16)) '(16))
7765 force-heading))
7766 (save-excursion
7767 (org-back-to-heading)
7768 (outline-previous-heading)
7769 (looking-at org-todo-line-regexp))
7770 (let*
7771 ((new-mark-x
7772 (if (or arg
7773 (not (match-beginning 2))
7774 (member (match-string 2) org-done-keywords))
7775 (car org-todo-keywords-1)
7776 (match-string 2)))
7777 (new-mark
7779 (run-hook-with-args-until-success
7780 'org-todo-get-default-hook new-mark-x nil)
7781 new-mark-x)))
7782 (beginning-of-line 1)
7783 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7784 (if org-treat-insert-todo-heading-as-state-change
7785 (org-todo new-mark)
7786 (insert new-mark " "))))
7787 (when org-provide-todo-statistics
7788 (org-update-parent-todo-statistics))))
7790 (defun org-insert-subheading (arg)
7791 "Insert a new subheading and demote it.
7792 Works for outline headings and for plain lists alike."
7793 (interactive "P")
7794 (org-insert-heading arg)
7795 (cond
7796 ((org-at-heading-p) (org-do-demote))
7797 ((org-at-item-p) (org-indent-item))))
7799 (defun org-insert-todo-subheading (arg)
7800 "Insert a new subheading with TODO keyword or checkbox and demote it.
7801 Works for outline headings and for plain lists alike."
7802 (interactive "P")
7803 (org-insert-todo-heading arg)
7804 (cond
7805 ((org-at-heading-p) (org-do-demote))
7806 ((org-at-item-p) (org-indent-item))))
7808 ;;; Promotion and Demotion
7810 (defvar org-after-demote-entry-hook nil
7811 "Hook run after an entry has been demoted.
7812 The cursor will be at the beginning of the entry.
7813 When a subtree is being demoted, the hook will be called for each node.")
7815 (defvar org-after-promote-entry-hook nil
7816 "Hook run after an entry has been promoted.
7817 The cursor will be at the beginning of the entry.
7818 When a subtree is being promoted, the hook will be called for each node.")
7820 (defun org-promote-subtree ()
7821 "Promote the entire subtree.
7822 See also `org-promote'."
7823 (interactive)
7824 (save-excursion
7825 (org-with-limited-levels (org-map-tree 'org-promote)))
7826 (org-fix-position-after-promote))
7828 (defun org-demote-subtree ()
7829 "Demote the entire subtree. See `org-demote'.
7830 See also `org-promote'."
7831 (interactive)
7832 (save-excursion
7833 (org-with-limited-levels (org-map-tree 'org-demote)))
7834 (org-fix-position-after-promote))
7837 (defun org-do-promote ()
7838 "Promote the current heading higher up the tree.
7839 If the region is active in `transient-mark-mode', promote all headings
7840 in the region."
7841 (interactive)
7842 (save-excursion
7843 (if (org-region-active-p)
7844 (org-map-region 'org-promote (region-beginning) (region-end))
7845 (org-promote)))
7846 (org-fix-position-after-promote))
7848 (defun org-do-demote ()
7849 "Demote the current heading lower down the tree.
7850 If the region is active in `transient-mark-mode', demote all headings
7851 in the region."
7852 (interactive)
7853 (save-excursion
7854 (if (org-region-active-p)
7855 (org-map-region 'org-demote (region-beginning) (region-end))
7856 (org-demote)))
7857 (org-fix-position-after-promote))
7859 (defun org-fix-position-after-promote ()
7860 "Make sure that after pro/demotion cursor position is right."
7861 (let ((pos (point)))
7862 (when (save-excursion
7863 (beginning-of-line 1)
7864 (looking-at org-todo-line-regexp)
7865 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7866 (cond ((eobp) (insert " "))
7867 ((eolp) (insert " "))
7868 ((equal (char-after) ?\ ) (forward-char 1))))))
7870 (defun org-current-level ()
7871 "Return the level of the current entry, or nil if before the first headline.
7872 The level is the number of stars at the beginning of the headline."
7873 (save-excursion
7874 (org-with-limited-levels
7875 (if (ignore-errors (org-back-to-heading t))
7876 (funcall outline-level)))))
7878 (defun org-get-previous-line-level ()
7879 "Return the outline depth of the last headline before the current line.
7880 Returns 0 for the first headline in the buffer, and nil if before the
7881 first headline."
7882 (let ((current-level (org-current-level))
7883 (prev-level (when (> (line-number-at-pos) 1)
7884 (save-excursion
7885 (beginning-of-line 0)
7886 (org-current-level)))))
7887 (cond ((null current-level) nil) ; Before first headline
7888 ((null prev-level) 0) ; At first headline
7889 (prev-level))))
7891 (defun org-reduced-level (l)
7892 "Compute the effective level of a heading.
7893 This takes into account the setting of `org-odd-levels-only'."
7894 (cond
7895 ((zerop l) 0)
7896 (org-odd-levels-only (1+ (floor (/ l 2))))
7897 (t l)))
7899 (defun org-level-increment ()
7900 "Return the number of stars that will be added or removed at a
7901 time to headlines when structure editing, based on the value of
7902 `org-odd-levels-only'."
7903 (if org-odd-levels-only 2 1))
7905 (defun org-get-valid-level (level &optional change)
7906 "Rectify a level change under the influence of `org-odd-levels-only'
7907 LEVEL is a current level, CHANGE is by how much the level should be
7908 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7909 even level numbers will become the next higher odd number."
7910 (if org-odd-levels-only
7911 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7912 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7913 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7914 (max 1 (+ level (or change 0)))))
7916 (if (boundp 'define-obsolete-function-alias)
7917 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7918 (define-obsolete-function-alias 'org-get-legal-level
7919 'org-get-valid-level)
7920 (define-obsolete-function-alias 'org-get-legal-level
7921 'org-get-valid-level "23.1")))
7923 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7924 ;; ̀org-with-limited-levels'
7925 (defun org-promote ()
7926 "Promote the current heading higher up the tree.
7927 If the region is active in `transient-mark-mode', promote all headings
7928 in the region."
7929 (org-back-to-heading t)
7930 (let* ((level (save-match-data (funcall outline-level)))
7931 (after-change-functions (remove 'flyspell-after-change-function
7932 after-change-functions))
7933 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7934 (diff (abs (- level (length up-head) -1))))
7935 (cond ((and (= level 1) org-called-with-limited-levels
7936 org-allow-promoting-top-level-subtree)
7937 (replace-match "# " nil t))
7938 ((= level 1)
7939 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7940 (t (replace-match up-head nil t)))
7941 ;; Fixup tag positioning
7942 (unless (= level 1)
7943 (and org-auto-align-tags (org-set-tags nil t))
7944 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7945 (run-hooks 'org-after-promote-entry-hook)))
7947 (defun org-demote ()
7948 "Demote the current heading lower down the tree.
7949 If the region is active in `transient-mark-mode', demote all headings
7950 in the region."
7951 (org-back-to-heading t)
7952 (let* ((level (save-match-data (funcall outline-level)))
7953 (after-change-functions (remove 'flyspell-after-change-function
7954 after-change-functions))
7955 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7956 (diff (abs (- level (length down-head) -1))))
7957 (replace-match down-head nil t)
7958 ;; Fixup tag positioning
7959 (and org-auto-align-tags (org-set-tags nil t))
7960 (if org-adapt-indentation (org-fixup-indentation diff))
7961 (run-hooks 'org-after-demote-entry-hook)))
7963 (defun org-cycle-level ()
7964 "Cycle the level of an empty headline through possible states.
7965 This goes first to child, then to parent, level, then up the hierarchy.
7966 After top level, it switches back to sibling level."
7967 (interactive)
7968 (let ((org-adapt-indentation nil))
7969 (when (org-point-at-end-of-empty-headline)
7970 (setq this-command 'org-cycle-level) ; Only needed for caching
7971 (let ((cur-level (org-current-level))
7972 (prev-level (org-get-previous-line-level)))
7973 (cond
7974 ;; If first headline in file, promote to top-level.
7975 ((= prev-level 0)
7976 (loop repeat (/ (- cur-level 1) (org-level-increment))
7977 do (org-do-promote)))
7978 ;; If same level as prev, demote one.
7979 ((= prev-level cur-level)
7980 (org-do-demote))
7981 ;; If parent is top-level, promote to top level if not already.
7982 ((= prev-level 1)
7983 (loop repeat (/ (- cur-level 1) (org-level-increment))
7984 do (org-do-promote)))
7985 ;; If top-level, return to prev-level.
7986 ((= cur-level 1)
7987 (loop repeat (/ (- prev-level 1) (org-level-increment))
7988 do (org-do-demote)))
7989 ;; If less than prev-level, promote one.
7990 ((< cur-level prev-level)
7991 (org-do-promote))
7992 ;; If deeper than prev-level, promote until higher than
7993 ;; prev-level.
7994 ((> cur-level prev-level)
7995 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7996 do (org-do-promote))))
7997 t))))
7999 (defun org-map-tree (fun)
8000 "Call FUN for every heading underneath the current one."
8001 (org-back-to-heading)
8002 (let ((level (funcall outline-level)))
8003 (save-excursion
8004 (funcall fun)
8005 (while (and (progn
8006 (outline-next-heading)
8007 (> (funcall outline-level) level))
8008 (not (eobp)))
8009 (funcall fun)))))
8011 (defun org-map-region (fun beg end)
8012 "Call FUN for every heading between BEG and END."
8013 (let ((org-ignore-region t))
8014 (save-excursion
8015 (setq end (copy-marker end))
8016 (goto-char beg)
8017 (if (and (re-search-forward org-outline-regexp-bol nil t)
8018 (< (point) end))
8019 (funcall fun))
8020 (while (and (progn
8021 (outline-next-heading)
8022 (< (point) end))
8023 (not (eobp)))
8024 (funcall fun)))))
8026 (defvar org-property-end-re) ; silence byte-compiler
8027 (defun org-fixup-indentation (diff)
8028 "Change the indentation in the current entry by DIFF.
8029 However, if any line in the current entry has no indentation, or if it
8030 would end up with no indentation after the change, nothing at all is done."
8031 (save-excursion
8032 (let ((end (save-excursion (outline-next-heading)
8033 (point-marker)))
8034 (prohibit (if (> diff 0)
8035 "^\\S-"
8036 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8037 col)
8038 (unless (save-excursion (end-of-line 1)
8039 (re-search-forward prohibit end t))
8040 (while (and (< (point) end)
8041 (re-search-forward "^[ \t]+" end t))
8042 (goto-char (match-end 0))
8043 (setq col (current-column))
8044 (if (< diff 0) (replace-match ""))
8045 (org-indent-to-column (+ diff col))))
8046 (move-marker end nil))))
8048 (defun org-convert-to-odd-levels ()
8049 "Convert an org-mode file with all levels allowed to one with odd levels.
8050 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8051 level 5 etc."
8052 (interactive)
8053 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8054 (let ((outline-level 'org-outline-level)
8055 (org-odd-levels-only nil) n)
8056 (save-excursion
8057 (goto-char (point-min))
8058 (while (re-search-forward "^\\*\\*+ " nil t)
8059 (setq n (- (length (match-string 0)) 2))
8060 (while (>= (setq n (1- n)) 0)
8061 (org-demote))
8062 (end-of-line 1))))))
8064 (defun org-convert-to-oddeven-levels ()
8065 "Convert an org-mode file with only odd levels to one with odd/even levels.
8066 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8067 file contains a section with an even level, conversion would
8068 destroy the structure of the file. An error is signaled in this
8069 case."
8070 (interactive)
8071 (goto-char (point-min))
8072 ;; First check if there are no even levels
8073 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8074 (org-show-context t)
8075 (error "Not all levels are odd in this file. Conversion not possible"))
8076 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8077 (let ((outline-regexp org-outline-regexp)
8078 (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 (/ (1- (length (match-string 0))) 2))
8084 (while (>= (setq n (1- n)) 0)
8085 (org-promote))
8086 (end-of-line 1))))))
8088 (defun org-tr-level (n)
8089 "Make N odd if required."
8090 (if org-odd-levels-only (1+ (/ n 2)) n))
8092 ;;; Vertical tree motion, cutting and pasting of subtrees
8094 (defun org-move-subtree-up (&optional arg)
8095 "Move the current subtree up past ARG headlines of the same level."
8096 (interactive "p")
8097 (org-move-subtree-down (- (prefix-numeric-value arg))))
8099 (defun org-move-subtree-down (&optional arg)
8100 "Move the current subtree down past ARG headlines of the same level."
8101 (interactive "p")
8102 (setq arg (prefix-numeric-value arg))
8103 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8104 'org-get-last-sibling))
8105 (ins-point (make-marker))
8106 (cnt (abs arg))
8107 (col (current-column))
8108 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8109 ;; Select the tree
8110 (org-back-to-heading)
8111 (setq beg0 (point))
8112 (save-excursion
8113 (setq ne-beg (org-back-over-empty-lines))
8114 (setq beg (point)))
8115 (save-match-data
8116 (save-excursion (outline-end-of-heading)
8117 (setq folded (outline-invisible-p)))
8118 (outline-end-of-subtree))
8119 (outline-next-heading)
8120 (setq ne-end (org-back-over-empty-lines))
8121 (setq end (point))
8122 (goto-char beg0)
8123 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8124 ;; include less whitespace
8125 (save-excursion
8126 (goto-char beg)
8127 (forward-line (- ne-beg ne-end))
8128 (setq beg (point))))
8129 ;; Find insertion point, with error handling
8130 (while (> cnt 0)
8131 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8132 (progn (goto-char beg0)
8133 (user-error "Cannot move past superior level or buffer limit")))
8134 (setq cnt (1- cnt)))
8135 (if (> arg 0)
8136 ;; Moving forward - still need to move over subtree
8137 (progn (org-end-of-subtree t t)
8138 (save-excursion
8139 (org-back-over-empty-lines)
8140 (or (bolp) (newline)))))
8141 (setq ne-ins (org-back-over-empty-lines))
8142 (move-marker ins-point (point))
8143 (setq txt (buffer-substring beg end))
8144 (org-save-markers-in-region beg end)
8145 (delete-region beg end)
8146 (org-remove-empty-overlays-at beg)
8147 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8148 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8149 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8150 (let ((bbb (point)))
8151 (insert-before-markers txt)
8152 (org-reinstall-markers-in-region bbb)
8153 (move-marker ins-point bbb))
8154 (or (bolp) (insert "\n"))
8155 (setq ins-end (point))
8156 (goto-char ins-point)
8157 (org-skip-whitespace)
8158 (when (and (< arg 0)
8159 (org-first-sibling-p)
8160 (> ne-ins ne-beg))
8161 ;; Move whitespace back to beginning
8162 (save-excursion
8163 (goto-char ins-end)
8164 (let ((kill-whole-line t))
8165 (kill-line (- ne-ins ne-beg)) (point)))
8166 (insert (make-string (- ne-ins ne-beg) ?\n)))
8167 (move-marker ins-point nil)
8168 (if folded
8169 (hide-subtree)
8170 (org-show-entry)
8171 (show-children)
8172 (org-cycle-hide-drawers 'children))
8173 (org-clean-visibility-after-subtree-move)
8174 ;; move back to the initial column we were at
8175 (move-to-column col)))
8177 (defvar org-subtree-clip ""
8178 "Clipboard for cut and paste of subtrees.
8179 This is actually only a copy of the kill, because we use the normal kill
8180 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8182 (defvar org-subtree-clip-folded nil
8183 "Was the last copied subtree folded?
8184 This is used to fold the tree back after pasting.")
8186 (defun org-cut-subtree (&optional n)
8187 "Cut the current subtree into the clipboard.
8188 With prefix arg N, cut this many sequential subtrees.
8189 This is a short-hand for marking the subtree and then cutting it."
8190 (interactive "p")
8191 (org-copy-subtree n 'cut))
8193 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8194 "Copy the current subtree it in the clipboard.
8195 With prefix arg N, copy this many sequential subtrees.
8196 This is a short-hand for marking the subtree and then copying it.
8197 If CUT is non-nil, actually cut the subtree.
8198 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8199 of some markers in the region, even if CUT is non-nil. This is
8200 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8201 (interactive "p")
8202 (let (beg end folded (beg0 (point)))
8203 (if (org-called-interactively-p 'any)
8204 (org-back-to-heading nil) ; take what looks like a subtree
8205 (org-back-to-heading t)) ; take what is really there
8206 (setq beg (point))
8207 (skip-chars-forward " \t\r\n")
8208 (save-match-data
8209 (if nosubtrees
8210 (outline-next-heading)
8211 (save-excursion (outline-end-of-heading)
8212 (setq folded (outline-invisible-p)))
8213 (condition-case nil
8214 (org-forward-heading-same-level (1- n) t)
8215 (error nil))
8216 (org-end-of-subtree t t)))
8217 (setq end (point))
8218 (goto-char beg0)
8219 (when (> end beg)
8220 (setq org-subtree-clip-folded folded)
8221 (when (or cut force-store-markers)
8222 (org-save-markers-in-region beg end))
8223 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8224 (setq org-subtree-clip (current-kill 0))
8225 (message "%s: Subtree(s) with %d characters"
8226 (if cut "Cut" "Copied")
8227 (length org-subtree-clip)))))
8229 (defun org-paste-subtree (&optional level tree for-yank)
8230 "Paste the clipboard as a subtree, with modification of headline level.
8231 The entire subtree is promoted or demoted in order to match a new headline
8232 level.
8234 If the cursor is at the beginning of a headline, the same level as
8235 that headline is used to paste the tree.
8237 If not, the new level is derived from the *visible* headings
8238 before and after the insertion point, and taken to be the inferior headline
8239 level of the two. So if the previous visible heading is level 3 and the
8240 next is level 4 (or vice versa), level 4 will be used for insertion.
8241 This makes sure that the subtree remains an independent subtree and does
8242 not swallow low level entries.
8244 You can also force a different level, either by using a numeric prefix
8245 argument, or by inserting the heading marker by hand. For example, if the
8246 cursor is after \"*****\", then the tree will be shifted to level 5.
8248 If optional TREE is given, use this text instead of the kill ring.
8250 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8251 move back over whitespace before inserting, and move point to the end of
8252 the inserted text when done."
8253 (interactive "P")
8254 (setq tree (or tree (and kill-ring (current-kill 0))))
8255 (unless (org-kill-is-subtree-p tree)
8256 (user-error "%s"
8257 (substitute-command-keys
8258 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8259 (org-with-limited-levels
8260 (let* ((visp (not (outline-invisible-p)))
8261 (txt tree)
8262 (^re_ "\\(\\*+\\)[ \t]*")
8263 (old-level (if (string-match org-outline-regexp-bol txt)
8264 (- (match-end 0) (match-beginning 0) 1)
8265 -1))
8266 (force-level (cond (level (prefix-numeric-value level))
8267 ((and (looking-at "[ \t]*$")
8268 (string-match
8269 "^\\*+$" (buffer-substring
8270 (point-at-bol) (point))))
8271 (- (match-end 1) (match-beginning 1)))
8272 ((and (bolp)
8273 (looking-at org-outline-regexp))
8274 (- (match-end 0) (point) 1))))
8275 (previous-level (save-excursion
8276 (condition-case nil
8277 (progn
8278 (outline-previous-visible-heading 1)
8279 (if (looking-at ^re_)
8280 (- (match-end 0) (match-beginning 0) 1)
8282 (error 1))))
8283 (next-level (save-excursion
8284 (condition-case nil
8285 (progn
8286 (or (looking-at org-outline-regexp)
8287 (outline-next-visible-heading 1))
8288 (if (looking-at ^re_)
8289 (- (match-end 0) (match-beginning 0) 1)
8291 (error 1))))
8292 (new-level (or force-level (max previous-level next-level)))
8293 (shift (if (or (= old-level -1)
8294 (= new-level -1)
8295 (= old-level new-level))
8297 (- new-level old-level)))
8298 (delta (if (> shift 0) -1 1))
8299 (func (if (> shift 0) 'org-demote 'org-promote))
8300 (org-odd-levels-only nil)
8301 beg end newend)
8302 ;; Remove the forced level indicator
8303 (if force-level
8304 (delete-region (point-at-bol) (point)))
8305 ;; Paste
8306 (beginning-of-line (if (bolp) 1 2))
8307 (setq beg (point))
8308 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8309 (insert-before-markers txt)
8310 (unless (string-match "\n\\'" txt) (insert "\n"))
8311 (setq newend (point))
8312 (org-reinstall-markers-in-region beg)
8313 (setq end (point))
8314 (goto-char beg)
8315 (skip-chars-forward " \t\n\r")
8316 (setq beg (point))
8317 (if (and (outline-invisible-p) visp)
8318 (save-excursion (outline-show-heading)))
8319 ;; Shift if necessary
8320 (unless (= shift 0)
8321 (save-restriction
8322 (narrow-to-region beg end)
8323 (while (not (= shift 0))
8324 (org-map-region func (point-min) (point-max))
8325 (setq shift (+ delta shift)))
8326 (goto-char (point-min))
8327 (setq newend (point-max))))
8328 (when (or (org-called-interactively-p 'interactive) for-yank)
8329 (message "Clipboard pasted as level %d subtree" new-level))
8330 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8331 kill-ring
8332 (eq org-subtree-clip (current-kill 0))
8333 org-subtree-clip-folded)
8334 ;; The tree was folded before it was killed/copied
8335 (hide-subtree))
8336 (and for-yank (goto-char newend)))))
8338 (defun org-kill-is-subtree-p (&optional txt)
8339 "Check if the current kill is an outline subtree, or a set of trees.
8340 Returns nil if kill does not start with a headline, or if the first
8341 headline level is not the largest headline level in the tree.
8342 So this will actually accept several entries of equal levels as well,
8343 which is OK for `org-paste-subtree'.
8344 If optional TXT is given, check this string instead of the current kill."
8345 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8346 (re (org-get-limited-outline-regexp))
8347 (^re (concat "^" re))
8348 (start-level (and kill
8349 (string-match
8350 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8351 kill)
8352 (- (match-end 2) (match-beginning 2) 1)))
8353 (start (1+ (or (match-beginning 2) -1))))
8354 (if (not start-level)
8355 (progn
8356 nil) ;; does not even start with a heading
8357 (catch 'exit
8358 (while (setq start (string-match ^re kill (1+ start)))
8359 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8360 (throw 'exit nil)))
8361 t))))
8363 (defvar org-markers-to-move nil
8364 "Markers that should be moved with a cut-and-paste operation.
8365 Those markers are stored together with their positions relative to
8366 the start of the region.")
8368 (defun org-save-markers-in-region (beg end)
8369 "Check markers in region.
8370 If these markers are between BEG and END, record their position relative
8371 to BEG, so that after moving the block of text, we can put the markers back
8372 into place.
8373 This function gets called just before an entry or tree gets cut from the
8374 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8375 called immediately, to move the markers with the entries."
8376 (setq org-markers-to-move nil)
8377 (when (featurep 'org-clock)
8378 (org-clock-save-markers-for-cut-and-paste beg end))
8379 (when (featurep 'org-agenda)
8380 (org-agenda-save-markers-for-cut-and-paste beg end)))
8382 (defun org-check-and-save-marker (marker beg end)
8383 "Check if MARKER is between BEG and END.
8384 If yes, remember the marker and the distance to BEG."
8385 (when (and (marker-buffer marker)
8386 (equal (marker-buffer marker) (current-buffer)))
8387 (if (and (>= marker beg) (< marker end))
8388 (push (cons marker (- marker beg)) org-markers-to-move))))
8390 (defun org-reinstall-markers-in-region (beg)
8391 "Move all remembered markers to their position relative to BEG."
8392 (mapc (lambda (x)
8393 (move-marker (car x) (+ beg (cdr x))))
8394 org-markers-to-move)
8395 (setq org-markers-to-move nil))
8397 (defun org-narrow-to-subtree ()
8398 "Narrow buffer to the current subtree."
8399 (interactive)
8400 (save-excursion
8401 (save-match-data
8402 (org-with-limited-levels
8403 (narrow-to-region
8404 (progn (org-back-to-heading t) (point))
8405 (progn (org-end-of-subtree t t)
8406 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8407 (point)))))))
8409 (defun org-narrow-to-block ()
8410 "Narrow buffer to the current block."
8411 (interactive)
8412 (let* ((case-fold-search t)
8413 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8414 "^[ \t]*#\\+end_.*")))
8415 (if blockp
8416 (narrow-to-region (car blockp) (cdr blockp))
8417 (user-error "Not in a block"))))
8419 (eval-when-compile
8420 (defvar org-property-drawer-re))
8422 (defvar org-property-start-re) ;; defined below
8423 (defun org-clone-subtree-with-time-shift (n &optional shift)
8424 "Clone the task (subtree) at point N times.
8425 The clones will be inserted as siblings.
8427 In interactive use, the user will be prompted for the number of
8428 clones to be produced. If the entry has a timestamp, the user
8429 will also be prompted for a time shift, which may be a repeater
8430 as used in time stamps, for example `+3d'. To disable this,
8431 you can call the function with a universal prefix argument.
8433 When a valid repeater is given and the entry contains any time
8434 stamps, the clones will become a sequence in time, with time
8435 stamps in the subtree shifted for each clone produced. If SHIFT
8436 is nil or the empty string, time stamps will be left alone. The
8437 ID property of the original subtree is removed.
8439 If the original subtree did contain time stamps with a repeater,
8440 the following will happen:
8441 - the repeater will be removed in each clone
8442 - an additional clone will be produced, with the current, unshifted
8443 date(s) in the entry.
8444 - the original entry will be placed *after* all the clones, with
8445 repeater intact.
8446 - the start days in the repeater in the original entry will be shifted
8447 to past the last clone.
8448 In this way you can spell out a number of instances of a repeating task,
8449 and still retain the repeater to cover future instances of the task."
8450 (interactive "nNumber of clones to produce: ")
8451 (let ((shift
8452 (or shift
8453 (if (and (not (equal current-prefix-arg '(4)))
8454 (save-excursion
8455 (re-search-forward org-ts-regexp-both
8456 (save-excursion
8457 (org-end-of-subtree t)
8458 (point)) t)))
8459 (read-from-minibuffer
8460 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8461 ""))) ;; No time shift
8462 (n-no-remove -1)
8463 (drawer-re org-drawer-regexp)
8464 beg end template task idprop
8465 shift-n shift-what doshift nmin nmax)
8466 (if (not (and (integerp n) (> n 0)))
8467 (error "Invalid number of replications %s" n))
8468 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8469 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8470 shift)))
8471 (error "Invalid shift specification %s" shift))
8472 (when doshift
8473 (setq shift-n (string-to-number (match-string 1 shift))
8474 shift-what (cdr (assoc (match-string 2 shift)
8475 '(("d" . day) ("w" . week)
8476 ("m" . month) ("y" . year))))))
8477 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8478 (setq nmin 1 nmax n)
8479 (org-back-to-heading t)
8480 (setq beg (point))
8481 (setq idprop (org-entry-get nil "ID"))
8482 (org-end-of-subtree t t)
8483 (or (bolp) (insert "\n"))
8484 (setq end (point))
8485 (setq template (buffer-substring beg end))
8486 (when (and doshift
8487 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8488 (delete-region beg end)
8489 (setq end beg)
8490 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8491 (goto-char end)
8492 (loop for n from nmin to nmax do
8493 ;; prepare clone
8494 (with-temp-buffer
8495 (insert template)
8496 (org-mode)
8497 (goto-char (point-min))
8498 (org-show-subtree)
8499 (and idprop (if org-clone-delete-id
8500 (org-entry-delete nil "ID")
8501 (org-id-get-create t)))
8502 (unless (= n 0)
8503 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8504 (kill-whole-line))
8505 (goto-char (point-min))
8506 (while (re-search-forward drawer-re nil t)
8507 (org-remove-empty-drawer-at (point))))
8508 (goto-char (point-min))
8509 (when doshift
8510 (while (re-search-forward org-ts-regexp-both nil t)
8511 (org-timestamp-change (* n shift-n) shift-what))
8512 (unless (= n n-no-remove)
8513 (goto-char (point-min))
8514 (while (re-search-forward org-ts-regexp nil t)
8515 (save-excursion
8516 (goto-char (match-beginning 0))
8517 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8518 (delete-region (match-beginning 1) (match-end 1)))))))
8519 (setq task (buffer-string)))
8520 (insert task))
8521 (goto-char beg)))
8523 ;;; Outline Sorting
8525 (defun org-sort (with-case)
8526 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8527 Optional argument WITH-CASE means sort case-sensitively."
8528 (interactive "P")
8529 (cond
8530 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8531 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8533 (org-call-with-arg 'org-sort-entries with-case))))
8535 (defun org-sort-remove-invisible (s)
8536 "Remove invisible links from string S."
8537 (remove-text-properties 0 (length s) org-rm-props s)
8538 (while (string-match org-bracket-link-regexp s)
8539 (setq s (replace-match (if (match-end 2)
8540 (match-string 3 s)
8541 (match-string 1 s)) t t s)))
8542 (let ((st (format " %s " s)))
8543 (while (string-match org-emph-re st)
8544 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8545 (setq s (substring st 1 -1)))
8548 (defvar org-priority-regexp) ; defined later in the file
8550 (defvar org-after-sorting-entries-or-items-hook nil
8551 "Hook that is run after a bunch of entries or items have been sorted.
8552 When children are sorted, the cursor is in the parent line when this
8553 hook gets called. When a region or a plain list is sorted, the cursor
8554 will be in the first entry of the sorted region/list.")
8556 (defun org-sort-entries
8557 (&optional with-case sorting-type getkey-func compare-func property)
8558 "Sort entries on a certain level of an outline tree.
8559 If there is an active region, the entries in the region are sorted.
8560 Else, if the cursor is before the first entry, sort the top-level items.
8561 Else, the children of the entry at point are sorted.
8563 Sorting can be alphabetically, numerically, by date/time as given by
8564 a time stamp, by a property, by priority order, or by a custom function.
8566 The command prompts for the sorting type unless it has been given to the
8567 function through the SORTING-TYPE argument, which needs to be a character,
8568 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8569 precise meaning of each character:
8571 n Numerically, by converting the beginning of the entry/item to a number.
8572 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8573 o By order of TODO keywords.
8574 t By date/time, either the first active time stamp in the entry, or, if
8575 none exist, by the first inactive one.
8576 s By the scheduled date/time.
8577 d By deadline date/time.
8578 c By creation time, which is assumed to be the first inactive time stamp
8579 at the beginning of a line.
8580 p By priority according to the cookie.
8581 r By the value of a property.
8583 Capital letters will reverse the sort order.
8585 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8586 called with point at the beginning of the record. It must return either
8587 a string or a number that should serve as the sorting key for that record.
8589 Comparing entries ignores case by default. However, with an optional argument
8590 WITH-CASE, the sorting considers case as well.
8592 Sorting is done against the visible part of the headlines, it ignores hidden
8593 links."
8594 (interactive "P")
8595 (let ((case-func (if with-case 'identity 'downcase))
8596 (cmstr
8597 ;; The clock marker is lost when using `sort-subr', let's
8598 ;; store the clocking string.
8599 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8600 (save-excursion
8601 (goto-char org-clock-marker)
8602 (looking-back "^.*") (match-string-no-properties 0))))
8603 start beg end stars re re2
8604 txt what tmp)
8605 ;; Find beginning and end of region to sort
8606 (cond
8607 ((org-region-active-p)
8608 ;; we will sort the region
8609 (setq end (region-end)
8610 what "region")
8611 (goto-char (region-beginning))
8612 (if (not (org-at-heading-p)) (outline-next-heading))
8613 (setq start (point)))
8614 ((or (org-at-heading-p)
8615 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8616 ;; we will sort the children of the current headline
8617 (org-back-to-heading)
8618 (setq start (point)
8619 end (progn (org-end-of-subtree t t)
8620 (or (bolp) (insert "\n"))
8621 (org-back-over-empty-lines)
8622 (point))
8623 what "children")
8624 (goto-char start)
8625 (show-subtree)
8626 (outline-next-heading))
8628 ;; we will sort the top-level entries in this file
8629 (goto-char (point-min))
8630 (or (org-at-heading-p) (outline-next-heading))
8631 (setq start (point))
8632 (goto-char (point-max))
8633 (beginning-of-line 1)
8634 (when (looking-at ".*?\\S-")
8635 ;; File ends in a non-white line
8636 (end-of-line 1)
8637 (insert "\n"))
8638 (setq end (point-max))
8639 (setq what "top-level")
8640 (goto-char start)
8641 (show-all)))
8643 (setq beg (point))
8644 (if (>= beg end) (user-error "Nothing to sort"))
8646 (looking-at "\\(\\*+\\)")
8647 (setq stars (match-string 1)
8648 re (concat "^" (regexp-quote stars) " +")
8649 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8650 txt (buffer-substring beg end))
8651 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8652 (if (and (not (equal stars "*")) (string-match re2 txt))
8653 (user-error "Region to sort contains a level above the first entry"))
8655 (unless sorting-type
8656 (message
8657 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8658 [t]ime [s]cheduled [d]eadline [c]reated
8659 A/N/P/R/O/F/T/S/D/C means reversed:"
8660 what)
8661 (setq sorting-type (read-char-exclusive))
8663 (unless getkey-func
8664 (and (= (downcase sorting-type) ?f)
8665 (setq getkey-func
8666 (org-icompleting-read "Sort using function: "
8667 obarray 'fboundp t nil nil))
8668 (setq getkey-func (intern getkey-func))))
8670 (and (= (downcase sorting-type) ?r)
8671 (not property)
8672 (setq property
8673 (org-icompleting-read "Property: "
8674 (mapcar 'list (org-buffer-property-keys t))
8675 nil t))))
8677 (message "Sorting entries...")
8679 (save-restriction
8680 (narrow-to-region start end)
8681 (let ((dcst (downcase sorting-type))
8682 (case-fold-search nil)
8683 (now (current-time)))
8684 (sort-subr
8685 (/= dcst sorting-type)
8686 ;; This function moves to the beginning character of the "record" to
8687 ;; be sorted.
8688 (lambda nil
8689 (if (re-search-forward re nil t)
8690 (goto-char (match-beginning 0))
8691 (goto-char (point-max))))
8692 ;; This function moves to the last character of the "record" being
8693 ;; sorted.
8694 (lambda nil
8695 (save-match-data
8696 (condition-case nil
8697 (outline-forward-same-level 1)
8698 (error
8699 (goto-char (point-max))))))
8700 ;; This function returns the value that gets sorted against.
8701 (lambda nil
8702 (cond
8703 ((= dcst ?n)
8704 (if (looking-at org-complex-heading-regexp)
8705 (string-to-number (org-sort-remove-invisible (match-string 4)))
8706 nil))
8707 ((= dcst ?a)
8708 (if (looking-at org-complex-heading-regexp)
8709 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8710 nil))
8711 ((= dcst ?t)
8712 (let ((end (save-excursion (outline-next-heading) (point))))
8713 (if (or (re-search-forward org-ts-regexp end t)
8714 (re-search-forward org-ts-regexp-both end t))
8715 (org-time-string-to-seconds (match-string 0))
8716 (org-float-time now))))
8717 ((= dcst ?c)
8718 (let ((end (save-excursion (outline-next-heading) (point))))
8719 (if (re-search-forward
8720 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8721 end t)
8722 (org-time-string-to-seconds (match-string 0))
8723 (org-float-time now))))
8724 ((= dcst ?s)
8725 (let ((end (save-excursion (outline-next-heading) (point))))
8726 (if (re-search-forward org-scheduled-time-regexp end t)
8727 (org-time-string-to-seconds (match-string 1))
8728 (org-float-time now))))
8729 ((= dcst ?d)
8730 (let ((end (save-excursion (outline-next-heading) (point))))
8731 (if (re-search-forward org-deadline-time-regexp end t)
8732 (org-time-string-to-seconds (match-string 1))
8733 (org-float-time now))))
8734 ((= dcst ?p)
8735 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8736 (string-to-char (match-string 2))
8737 org-default-priority))
8738 ((= dcst ?r)
8739 (or (org-entry-get nil property) ""))
8740 ((= dcst ?o)
8741 (if (looking-at org-complex-heading-regexp)
8742 (- 9999 (length (member (match-string 2)
8743 org-todo-keywords-1)))))
8744 ((= dcst ?f)
8745 (if getkey-func
8746 (progn
8747 (setq tmp (funcall getkey-func))
8748 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8749 tmp)
8750 (error "Invalid key function `%s'" getkey-func)))
8751 (t (error "Invalid sorting type `%c'" sorting-type))))
8753 (cond
8754 ((= dcst ?a) 'string<)
8755 ((= dcst ?f) compare-func)
8756 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8757 (run-hooks 'org-after-sorting-entries-or-items-hook)
8758 ;; Reset the clock marker if needed
8759 (when cmstr
8760 (save-excursion
8761 (goto-char start)
8762 (search-forward cmstr nil t)
8763 (move-marker org-clock-marker (point))))
8764 (message "Sorting entries...done")))
8766 (defun org-do-sort (table what &optional with-case sorting-type)
8767 "Sort TABLE of WHAT according to SORTING-TYPE.
8768 The user will be prompted for the SORTING-TYPE if the call to this
8769 function does not specify it. WHAT is only for the prompt, to indicate
8770 what is being sorted. The sorting key will be extracted from
8771 the car of the elements of the table.
8772 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8773 (unless sorting-type
8774 (message
8775 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8776 what)
8777 (setq sorting-type (read-char-exclusive)))
8778 (let ((dcst (downcase sorting-type))
8779 extractfun comparefun)
8780 ;; Define the appropriate functions
8781 (cond
8782 ((= dcst ?n)
8783 (setq extractfun 'string-to-number
8784 comparefun (if (= dcst sorting-type) '< '>)))
8785 ((= dcst ?a)
8786 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8787 (lambda(x) (downcase (org-sort-remove-invisible x))))
8788 comparefun (if (= dcst sorting-type)
8789 'string<
8790 (lambda (a b) (and (not (string< a b))
8791 (not (string= a b)))))))
8792 ((= dcst ?t)
8793 (setq extractfun
8794 (lambda (x)
8795 (if (or (string-match org-ts-regexp x)
8796 (string-match org-ts-regexp-both x))
8797 (org-float-time
8798 (org-time-string-to-time (match-string 0 x)))
8800 comparefun (if (= dcst sorting-type) '< '>)))
8801 (t (error "Invalid sorting type `%c'" sorting-type)))
8803 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8804 table)
8805 (lambda (a b) (funcall comparefun (car a) (car b))))))
8808 ;;; The orgstruct minor mode
8810 ;; Define a minor mode which can be used in other modes in order to
8811 ;; integrate the org-mode structure editing commands.
8813 ;; This is really a hack, because the org-mode structure commands use
8814 ;; keys which normally belong to the major mode. Here is how it
8815 ;; works: The minor mode defines all the keys necessary to operate the
8816 ;; structure commands, but wraps the commands into a function which
8817 ;; tests if the cursor is currently at a headline or a plain list
8818 ;; item. If that is the case, the structure command is used,
8819 ;; temporarily setting many Org-mode variables like regular
8820 ;; expressions for filling etc. However, when any of those keys is
8821 ;; used at a different location, function uses `key-binding' to look
8822 ;; up if the key has an associated command in another currently active
8823 ;; keymap (minor modes, major mode, global), and executes that
8824 ;; command. There might be problems if any of the keys is otherwise
8825 ;; used as a prefix key.
8827 (defcustom orgstruct-heading-prefix-regexp nil
8828 "Regexp that matches the custom prefix of Org headlines in
8829 orgstruct(++)-mode."
8830 :group 'org
8831 :version "24.4"
8832 :package-version '(Org . "8.0")
8833 :type 'string)
8834 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8836 (defcustom orgstruct-setup-hook nil
8837 "Hook run after orgstruct-mode-map is filled."
8838 :group 'org
8839 :version "24.4"
8840 :package-version '(Org . "8.0")
8841 :type 'hook)
8843 (defvar orgstruct-initialized nil)
8845 (defvar org-local-vars nil
8846 "List of local variables, for use by `orgstruct-mode'.")
8848 ;;;###autoload
8849 (define-minor-mode orgstruct-mode
8850 "Toggle the minor mode `orgstruct-mode'.
8851 This mode is for using Org-mode structure commands in other
8852 modes. The following keys behave as if Org-mode were active, if
8853 the cursor is on a headline, or on a plain list item (both as
8854 defined by Org-mode)."
8855 nil " OrgStruct" (make-sparse-keymap)
8856 (funcall (if orgstruct-mode
8857 'add-to-invisibility-spec
8858 'remove-from-invisibility-spec)
8859 '(outline . t))
8860 (when orgstruct-mode
8861 (org-load-modules-maybe)
8862 (unless orgstruct-initialized
8863 (orgstruct-setup)
8864 (setq orgstruct-initialized t))))
8866 ;;;###autoload
8867 (defun turn-on-orgstruct ()
8868 "Unconditionally turn on `orgstruct-mode'."
8869 (orgstruct-mode 1))
8871 (defvar org-fb-vars nil)
8872 (make-variable-buffer-local 'org-fb-vars)
8873 (defun orgstruct++-mode (&optional arg)
8874 "Toggle `orgstruct-mode', the enhanced version of it.
8875 In addition to setting orgstruct-mode, this also exports all
8876 indentation and autofilling variables from org-mode into the
8877 buffer. It will also recognize item context in multiline items."
8878 (interactive "P")
8879 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8880 (if (< arg 1)
8881 (progn (orgstruct-mode -1)
8882 (mapc (lambda(v)
8883 (org-set-local (car v)
8884 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8885 org-fb-vars))
8886 (orgstruct-mode 1)
8887 (setq org-fb-vars nil)
8888 (unless org-local-vars
8889 (setq org-local-vars (org-get-local-variables)))
8890 (let (var val)
8891 (mapc
8892 (lambda (x)
8893 (when (string-match
8894 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8895 (symbol-name (car x)))
8896 (setq var (car x) val (nth 1 x))
8897 (push (list var `(quote ,(eval var))) org-fb-vars)
8898 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8899 org-local-vars)
8900 (org-set-local 'orgstruct-is-++ t))))
8902 (defvar orgstruct-is-++ nil
8903 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8904 (make-variable-buffer-local 'orgstruct-is-++)
8906 ;;;###autoload
8907 (defun turn-on-orgstruct++ ()
8908 "Unconditionally turn on `orgstruct++-mode'."
8909 (orgstruct++-mode 1))
8911 (defun orgstruct-error ()
8912 "Error when there is no default binding for a structure key."
8913 (interactive)
8914 (funcall (if (fboundp 'user-error)
8915 'user-error
8916 'error)
8917 "This key has no function outside structure elements"))
8919 (defun orgstruct-setup ()
8920 "Setup orgstruct keymap."
8921 (dolist (cell '((org-demote . t)
8922 (org-metaleft . t)
8923 (org-metaright . t)
8924 (org-promote . t)
8925 (org-shiftmetaleft . t)
8926 (org-shiftmetaright . t)
8927 org-backward-element
8928 org-backward-heading-same-level
8929 org-ctrl-c-ret
8930 org-ctrl-c-minus
8931 org-ctrl-c-star
8932 org-cycle
8933 org-forward-heading-same-level
8934 org-insert-heading
8935 org-insert-heading-respect-content
8936 org-kill-note-or-show-branches
8937 org-mark-subtree
8938 org-meta-return
8939 org-metadown
8940 org-metaup
8941 org-narrow-to-subtree
8942 org-promote-subtree
8943 org-reveal
8944 org-shiftdown
8945 org-shiftleft
8946 org-shiftmetadown
8947 org-shiftmetaup
8948 org-shiftright
8949 org-shifttab
8950 org-shifttab
8951 org-shiftup
8952 org-show-subtree
8953 org-sort
8954 org-up-element
8955 outline-demote
8956 outline-next-visible-heading
8957 outline-previous-visible-heading
8958 outline-promote
8959 outline-up-heading
8960 show-children))
8961 (let ((f (or (car-safe cell) cell))
8962 (disable-when-heading-prefix (cdr-safe cell)))
8963 (when (fboundp f)
8964 (let ((new-bindings))
8965 (dolist (binding (nconc (where-is-internal f org-mode-map)
8966 (where-is-internal f outline-mode-map)))
8967 (push binding new-bindings)
8968 ;; TODO use local-function-key-map
8969 (dolist (rep '(("<tab>" . "TAB")
8970 ("<return>" . "RET")
8971 ("<escape>" . "ESC")
8972 ("<delete>" . "DEL")))
8973 (setq binding (read-kbd-macro
8974 (let ((case-fold-search))
8975 (replace-regexp-in-string
8976 (regexp-quote (cdr rep))
8977 (car rep)
8978 (key-description binding)))))
8979 (pushnew binding new-bindings :test 'equal)))
8980 (dolist (binding new-bindings)
8981 (let ((key (lookup-key orgstruct-mode-map binding)))
8982 (when (or (not key) (numberp key))
8983 (condition-case nil
8984 (org-defkey orgstruct-mode-map
8985 binding
8986 (orgstruct-make-binding f binding disable-when-heading-prefix))
8987 (error nil)))))))))
8988 (run-hooks 'orgstruct-setup-hook))
8990 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8991 "Create a function for binding in the structure minor mode.
8992 FUN is the command to call inside a table. KEY is the key that
8993 should be checked in for a command to execute outside of tables.
8994 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8995 if `orgstruct-heading-prefix-regexp' is non-nil."
8996 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8997 (let ((nname name)
8998 (i 0))
8999 (while (fboundp (intern nname))
9000 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9001 (setq name (intern nname)))
9002 (eval
9003 (let ((bindings '((org-heading-regexp
9004 (concat "^"
9005 orgstruct-heading-prefix-regexp
9006 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9007 (org-outline-regexp
9008 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9009 (org-outline-regexp-bol
9010 (concat "^" org-outline-regexp))
9011 (outline-regexp org-outline-regexp)
9012 (outline-heading-end-regexp "\n")
9013 (outline-level 'org-outline-level)
9014 (outline-heading-alist))))
9015 `(defun ,name (arg)
9016 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9017 "Outside of structure, run the binding of `"
9018 (key-description key) "'."
9019 (when disable-when-heading-prefix
9020 (concat
9021 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9022 "back to the default binding due to limitations of Org's implementation of\n"
9023 "`" (symbol-name fun) "'.")))
9024 (interactive "p")
9025 (let* ((disable
9026 ,(when disable-when-heading-prefix
9027 '(and orgstruct-heading-prefix-regexp
9028 (not (string= orgstruct-heading-prefix-regexp "")))))
9029 (fallback
9030 (or disable
9031 (not
9032 (let* ,bindings
9033 (org-context-p 'headline 'item
9034 ,(when (memq fun
9035 '(org-insert-heading
9036 org-insert-heading-respect-content
9037 org-meta-return))
9038 '(when orgstruct-is-++
9039 'item-body))))))))
9040 (if fallback
9041 (let* ((orgstruct-mode)
9042 (binding
9043 (loop with key = ,key
9044 for rep in
9045 '(nil
9046 ("<\\([^>]*\\)tab>" . "\\1TAB")
9047 ("<\\([^>]*\\)return>" . "\\1RET")
9048 ("<\\([^>]*\\)escape>" . "\\1ESC")
9049 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9051 (when rep
9052 (setq key (read-kbd-macro
9053 (let ((case-fold-search))
9054 (replace-regexp-in-string
9055 (car rep)
9056 (cdr rep)
9057 (key-description key))))))
9058 thereis (key-binding key))))
9059 (if (keymapp binding)
9060 (set-temporary-overlay-map binding)
9061 (let ((func (or binding
9062 (unless disable
9063 'orgstruct-error))))
9064 (when func
9065 (call-interactively func)))))
9066 (org-run-like-in-org-mode
9067 (lambda ()
9068 (interactive)
9069 (let* ,bindings
9070 (call-interactively ',fun)))))))))
9071 name))
9073 (defun org-contextualize-keys (alist contexts)
9074 "Return valid elements in ALIST depending on CONTEXTS.
9076 `org-agenda-custom-commands' or `org-capture-templates' are the
9077 values used for ALIST, and `org-agenda-custom-commands-contexts'
9078 or `org-capture-templates-contexts' are the associated contexts
9079 definitions."
9080 (let ((contexts
9081 ;; normalize contexts
9082 (mapcar
9083 (lambda(c) (cond ((listp (cadr c))
9084 (list (car c) (car c) (cadr c)))
9085 ((string= "" (cadr c))
9086 (list (car c) (car c) (caddr c)))
9087 (t c))) contexts))
9088 (a alist) c r s)
9089 ;; loop over all commands or templates
9090 (while (setq c (pop a))
9091 (let (vrules repl)
9092 (cond
9093 ((not (assoc (car c) contexts))
9094 (push c r))
9095 ((and (assoc (car c) contexts)
9096 (setq vrules (org-contextualize-validate-key
9097 (car c) contexts)))
9098 (mapc (lambda (vr)
9099 (when (not (equal (car vr) (cadr vr)))
9100 (setq repl vr))) vrules)
9101 (if (not repl) (push c r)
9102 (push (cadr repl) s)
9103 (push
9104 (cons (car c)
9105 (cdr (or (assoc (cadr repl) alist)
9106 (error "Undefined key `%s' as contextual replacement for `%s'"
9107 (cadr repl) (car c)))))
9108 r))))))
9109 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9110 (delq
9112 (delete-dups
9113 (mapcar (lambda (x)
9114 (let ((tpl (car x)))
9115 (when (not (delq
9117 (mapcar (lambda(y)
9118 (equal y tpl)) s))) x)))
9119 (reverse r))))))
9121 (defun org-contextualize-validate-key (key contexts)
9122 "Check CONTEXTS for agenda or capture KEY."
9123 (let (r rr res)
9124 (while (setq r (pop contexts))
9125 (mapc
9126 (lambda (rr)
9127 (when
9128 (and (equal key (car r))
9129 (if (functionp rr) (funcall rr)
9130 (or (and (eq (car rr) 'in-file)
9131 (buffer-file-name)
9132 (string-match (cdr rr) (buffer-file-name)))
9133 (and (eq (car rr) 'in-mode)
9134 (string-match (cdr rr) (symbol-name major-mode)))
9135 (and (eq (car rr) 'in-buffer)
9136 (string-match (cdr rr) (buffer-name)))
9137 (when (and (eq (car rr) 'not-in-file)
9138 (buffer-file-name))
9139 (not (string-match (cdr rr) (buffer-file-name))))
9140 (when (eq (car rr) 'not-in-mode)
9141 (not (string-match (cdr rr) (symbol-name major-mode))))
9142 (when (eq (car rr) 'not-in-buffer)
9143 (not (string-match (cdr rr) (buffer-name)))))))
9144 (push r res)))
9145 (car (last r))))
9146 (delete-dups (delq nil res))))
9148 (defun org-context-p (&rest contexts)
9149 "Check if local context is any of CONTEXTS.
9150 Possible values in the list of contexts are `table', `headline', and `item'."
9151 (let ((pos (point)))
9152 (goto-char (point-at-bol))
9153 (prog1 (or (and (memq 'table contexts)
9154 (looking-at "[ \t]*|"))
9155 (and (memq 'headline contexts)
9156 (looking-at org-outline-regexp))
9157 (and (memq 'item contexts)
9158 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9159 (and (memq 'item-body contexts)
9160 (org-in-item-p)))
9161 (goto-char pos))))
9163 (defun org-get-local-variables ()
9164 "Return a list of all local variables in an Org mode buffer."
9165 (let (varlist)
9166 (with-current-buffer (get-buffer-create "*Org tmp*")
9167 (erase-buffer)
9168 (org-mode)
9169 (setq varlist (buffer-local-variables)))
9170 (kill-buffer "*Org tmp*")
9171 (delq nil
9172 (mapcar
9173 (lambda (x)
9174 (setq x
9175 (if (symbolp x)
9176 (list x)
9177 (list (car x) (cdr x))))
9178 (if (and (not (get (car x) 'org-state))
9179 (string-match
9180 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9181 (symbol-name (car x))))
9182 x nil))
9183 varlist))))
9185 (defun org-clone-local-variables (from-buffer &optional regexp)
9186 "Clone local variables from FROM-BUFFER.
9187 Optional argument REGEXP selects variables to clone."
9188 (mapc
9189 (lambda (pair)
9190 (and (symbolp (car pair))
9191 (or (null regexp)
9192 (string-match regexp (symbol-name (car pair))))
9193 (set (make-local-variable (car pair))
9194 (cdr pair))))
9195 (buffer-local-variables from-buffer)))
9197 ;;;###autoload
9198 (defun org-run-like-in-org-mode (cmd)
9199 "Run a command, pretending that the current buffer is in Org-mode.
9200 This will temporarily bind local variables that are typically bound in
9201 Org-mode to the values they have in Org-mode, and then interactively
9202 call CMD."
9203 (org-load-modules-maybe)
9204 (unless org-local-vars
9205 (setq org-local-vars (org-get-local-variables)))
9206 (let (binds)
9207 (dolist (var org-local-vars)
9208 (when (or (not (boundp (car var)))
9209 (eq (symbol-value (car var))
9210 (default-value (car var))))
9211 (push (list (car var) `(quote ,(cadr var))) binds)))
9212 (eval `(let ,binds
9213 (call-interactively (quote ,cmd))))))
9215 ;;;; Archiving
9217 (defun org-get-category (&optional pos force-refresh)
9218 "Get the category applying to position POS."
9219 (save-match-data
9220 (if force-refresh (org-refresh-category-properties))
9221 (let ((pos (or pos (point))))
9222 (or (get-text-property pos 'org-category)
9223 (progn (org-refresh-category-properties)
9224 (get-text-property pos 'org-category))))))
9226 (defun org-refresh-category-properties ()
9227 "Refresh category text properties in the buffer."
9228 (let ((case-fold-search t)
9229 (inhibit-read-only t)
9230 (def-cat (cond
9231 ((null org-category)
9232 (if buffer-file-name
9233 (file-name-sans-extension
9234 (file-name-nondirectory buffer-file-name))
9235 "???"))
9236 ((symbolp org-category) (symbol-name org-category))
9237 (t org-category)))
9238 beg end cat pos optionp)
9239 (org-with-silent-modifications
9240 (save-excursion
9241 (save-restriction
9242 (widen)
9243 (goto-char (point-min))
9244 (put-text-property (point) (point-max) 'org-category def-cat)
9245 (while (re-search-forward
9246 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9247 (setq pos (match-end 0)
9248 optionp (equal (char-after (match-beginning 0)) ?#)
9249 cat (org-trim (match-string 2)))
9250 (if optionp
9251 (setq beg (point-at-bol) end (point-max))
9252 (org-back-to-heading t)
9253 (setq beg (point) end (org-end-of-subtree t t)))
9254 (put-text-property beg end 'org-category cat)
9255 (put-text-property beg end 'org-category-position beg)
9256 (goto-char pos)))))))
9258 (defun org-refresh-properties (dprop tprop)
9259 "Refresh buffer text properties.
9260 DPROP is the drawer property and TPROP is the corresponding text
9261 property to set."
9262 (let ((case-fold-search t)
9263 (inhibit-read-only t) p)
9264 (org-with-silent-modifications
9265 (save-excursion
9266 (save-restriction
9267 (widen)
9268 (goto-char (point-min))
9269 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9270 (setq p (org-match-string-no-properties 1))
9271 (save-excursion
9272 (org-back-to-heading t)
9273 (put-text-property
9274 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9277 ;;;; Link Stuff
9279 ;;; Link abbreviations
9281 (defun org-link-expand-abbrev (link)
9282 "Apply replacements as defined in `org-link-abbrev-alist'."
9283 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9284 (let* ((key (match-string 1 link))
9285 (as (or (assoc key org-link-abbrev-alist-local)
9286 (assoc key org-link-abbrev-alist)))
9287 (tag (and (match-end 2) (match-string 3 link)))
9288 rpl)
9289 (if (not as)
9290 link
9291 (setq rpl (cdr as))
9292 (cond
9293 ((symbolp rpl) (funcall rpl tag))
9294 ((string-match "%(\\([^)]+\\))" rpl)
9295 (replace-match
9296 (save-match-data
9297 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9298 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9299 ((string-match "%h" rpl)
9300 (replace-match (url-hexify-string (or tag "")) t t rpl))
9301 (t (concat rpl tag)))))
9302 link))
9304 ;;; Storing and inserting links
9306 (defvar org-insert-link-history nil
9307 "Minibuffer history for links inserted with `org-insert-link'.")
9309 (defvar org-stored-links nil
9310 "Contains the links stored with `org-store-link'.")
9312 (defvar org-store-link-plist nil
9313 "Plist with info about the most recently link created with `org-store-link'.")
9315 (defvar org-link-protocols nil
9316 "Link protocols added to Org-mode using `org-add-link-type'.")
9318 (defvar org-store-link-functions nil
9319 "List of functions that are called to create and store a link.
9320 Each function will be called in turn until one returns a non-nil
9321 value. Each function should check if it is responsible for creating
9322 this link (for example by looking at the major mode).
9323 If not, it must exit and return nil.
9324 If yes, it should return a non-nil value after a calling
9325 `org-store-link-props' with a list of properties and values.
9326 Special properties are:
9328 :type The link prefix, like \"http\". This must be given.
9329 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9330 This is obligatory as well.
9331 :description Optional default description for the second pair
9332 of brackets in an Org-mode link. The user can still change
9333 this when inserting this link into an Org-mode buffer.
9335 In addition to these, any additional properties can be specified
9336 and then used in capture templates.")
9338 (defun org-add-link-type (type &optional follow export)
9339 "Add TYPE to the list of `org-link-types'.
9340 Re-compute all regular expressions depending on `org-link-types'
9342 FOLLOW and EXPORT are two functions.
9344 FOLLOW should take the link path as the single argument and do whatever
9345 is necessary to follow the link, for example find a file or display
9346 a mail message.
9348 EXPORT should format the link path for export to one of the export formats.
9349 It should be a function accepting three arguments:
9351 path the path of the link, the text after the prefix (like \"http:\")
9352 desc the description of the link, if any, or a description added by
9353 org-export-normalize-links if there is none
9354 format the export format, a symbol like `html' or `latex' or `ascii'..
9356 The function may use the FORMAT information to return different values
9357 depending on the format. The return value will be put literally into
9358 the exported file. If the return value is nil, this means Org should
9359 do what it normally does with links which do not have EXPORT defined.
9361 Org-mode has a built-in default for exporting links. If you are happy with
9362 this default, there is no need to define an export function for the link
9363 type. For a simple example of an export function, see `org-bbdb.el'."
9364 (add-to-list 'org-link-types type t)
9365 (org-make-link-regexps)
9366 (if (assoc type org-link-protocols)
9367 (setcdr (assoc type org-link-protocols) (list follow export))
9368 (push (list type follow export) org-link-protocols)))
9370 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9371 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9373 ;;;###autoload
9374 (defun org-store-link (arg)
9375 "\\<org-mode-map>Store an org-link to the current location.
9376 This link is added to `org-stored-links' and can later be inserted
9377 into an org-buffer with \\[org-insert-link].
9379 For some link types, a prefix arg is interpreted.
9380 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9381 For file links, arg negates `org-context-in-file-links'.
9383 A double prefix arg force skipping storing functions that are not
9384 part of Org's core.
9386 A triple prefix arg force storing a link for each line in the
9387 active region."
9388 (interactive "P")
9389 (org-load-modules-maybe)
9390 (if (and (equal arg '(64)) (org-region-active-p))
9391 (save-excursion
9392 (let ((end (region-end)))
9393 (goto-char (region-beginning))
9394 (set-mark (point))
9395 (while (< (point-at-eol) end)
9396 (move-end-of-line 1) (activate-mark)
9397 (let (current-prefix-arg)
9398 (call-interactively 'org-store-link))
9399 (move-beginning-of-line 2)
9400 (set-mark (point)))))
9401 (org-with-limited-levels
9402 (setq org-store-link-plist nil)
9403 (let (link cpltxt desc description search
9404 txt custom-id agenda-link sfuns sfunsn)
9405 (cond
9407 ;; Store a link using an external link type
9408 ((and (not (equal arg '(16)))
9409 (setq sfuns
9410 (delq
9411 nil (mapcar (lambda (f)
9412 (let (fs) (if (funcall f) (push f fs))))
9413 org-store-link-functions))
9414 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9415 (or (and (cdr sfuns)
9416 (funcall (intern
9417 (completing-read
9418 "Which function for creating the link? "
9419 sfunsn t (car sfunsn)))))
9420 (funcall (caar sfuns)))
9421 (setq link (plist-get org-store-link-plist :link)
9422 desc (or (plist-get org-store-link-plist
9423 :description) link))))
9425 ;; Store a link from a source code buffer
9426 ((org-src-edit-buffer-p)
9427 (let (label gc)
9428 (while (or (not label)
9429 (save-excursion
9430 (save-restriction
9431 (widen)
9432 (goto-char (point-min))
9433 (re-search-forward
9434 (regexp-quote (format org-coderef-label-format label))
9435 nil t))))
9436 (when label (message "Label exists already") (sit-for 2))
9437 (setq label (read-string "Code line label: " label)))
9438 (end-of-line 1)
9439 (setq link (format org-coderef-label-format label))
9440 (setq gc (- 79 (length link)))
9441 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9442 (insert link)
9443 (setq link (concat "(" label ")") desc nil)))
9445 ;; We are in the agenda, link to referenced location
9446 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9447 (let ((m (or (get-text-property (point) 'org-hd-marker)
9448 (get-text-property (point) 'org-marker))))
9449 (when m
9450 (org-with-point-at m
9451 (setq agenda-link
9452 (if (org-called-interactively-p 'any)
9453 (call-interactively 'org-store-link)
9454 (org-store-link nil)))))))
9456 ((eq major-mode 'calendar-mode)
9457 (let ((cd (calendar-cursor-to-date)))
9458 (setq link
9459 (format-time-string
9460 (car org-time-stamp-formats)
9461 (apply 'encode-time
9462 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9463 nil nil nil))))
9464 (org-store-link-props :type "calendar" :date cd)))
9466 ((eq major-mode 'help-mode)
9467 (setq link (concat "help:" (save-excursion
9468 (goto-char (point-min))
9469 (looking-at "^[^ ]+")
9470 (match-string 0))))
9471 (org-store-link-props :type "help"))
9473 ((eq major-mode 'w3-mode)
9474 (setq cpltxt (if (and (buffer-name)
9475 (not (string-match "Untitled" (buffer-name))))
9476 (buffer-name)
9477 (url-view-url t))
9478 link (url-view-url t))
9479 (org-store-link-props :type "w3" :url (url-view-url t)))
9481 ((eq major-mode 'image-mode)
9482 (setq cpltxt (concat "file:"
9483 (abbreviate-file-name buffer-file-name))
9484 link cpltxt)
9485 (org-store-link-props :type "image" :file buffer-file-name))
9487 ;; In dired, store a link to the file of the current line
9488 ((eq major-mode 'dired-mode)
9489 (let ((file (dired-get-filename nil t)))
9490 (setq file (if file
9491 (abbreviate-file-name
9492 (expand-file-name (dired-get-filename nil t)))
9493 ;; otherwise, no file so use current directory.
9494 default-directory))
9495 (setq cpltxt (concat "file:" file)
9496 link cpltxt)))
9498 ((setq search (run-hook-with-args-until-success
9499 'org-create-file-search-functions))
9500 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9501 "::" search))
9502 (setq cpltxt (or description link)))
9504 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9505 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9506 (cond
9507 ;; Store a link using the target at point
9508 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9509 (setq cpltxt
9510 (concat "file:"
9511 (abbreviate-file-name
9512 (buffer-file-name (buffer-base-buffer)))
9513 "::" (match-string 1))
9514 link cpltxt))
9515 ((and (featurep 'org-id)
9516 (or (eq org-id-link-to-org-use-id t)
9517 (and (org-called-interactively-p 'any)
9518 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9519 (and (eq org-id-link-to-org-use-id
9520 'create-if-interactive-and-no-custom-id)
9521 (not custom-id))))
9522 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9523 ;; Store a link using the ID at point
9524 (setq link (condition-case nil
9525 (prog1 (org-id-store-link)
9526 (setq desc (plist-get org-store-link-plist
9527 :description)))
9528 (error
9529 ;; Probably before first headline, link only to file
9530 (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer))))))))
9534 ;; Just link to current headline
9535 (setq cpltxt (concat "file:"
9536 (abbreviate-file-name
9537 (buffer-file-name (buffer-base-buffer)))))
9538 ;; Add a context search string
9539 (when (org-xor org-context-in-file-links arg)
9540 (let* ((ee (org-element-at-point))
9541 (et (org-element-type ee))
9542 (ev (plist-get (cadr ee) :value))
9543 (ek (plist-get (cadr ee) :key))
9544 (eok (and (stringp ek) (string-match "name" ek))))
9545 (setq txt (cond
9546 ((org-at-heading-p) nil)
9547 ((and (eq et 'keyword) eok) ev)
9548 ((org-region-active-p)
9549 (buffer-substring (region-beginning) (region-end)))))
9550 (when (or (null txt) (string-match "\\S-" txt))
9551 (setq cpltxt
9552 (concat cpltxt "::"
9553 (condition-case nil
9554 (org-make-org-heading-search-string txt)
9555 (error "")))
9556 desc (or (and (eq et 'keyword) eok ev)
9557 (nth 4 (ignore-errors (org-heading-components)))
9558 "NONE")))))
9559 (if (string-match "::\\'" cpltxt)
9560 (setq cpltxt (substring cpltxt 0 -2)))
9561 (setq link cpltxt))))
9563 ((buffer-file-name (buffer-base-buffer))
9564 ;; Just link to this file here.
9565 (setq cpltxt (concat "file:"
9566 (abbreviate-file-name
9567 (buffer-file-name (buffer-base-buffer)))))
9568 ;; Add a context string.
9569 (when (org-xor org-context-in-file-links arg)
9570 (setq txt (if (org-region-active-p)
9571 (buffer-substring (region-beginning) (region-end))
9572 (buffer-substring (point-at-bol) (point-at-eol))))
9573 ;; Only use search option if there is some text.
9574 (when (string-match "\\S-" txt)
9575 (setq cpltxt
9576 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9577 desc "NONE")))
9578 (setq link cpltxt))
9580 ((org-called-interactively-p 'interactive)
9581 (user-error "No method for storing a link from this buffer"))
9583 (t (setq link nil)))
9585 ;; We're done setting link and desc, clean up
9586 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9587 (setq link (or link cpltxt)
9588 desc (or desc cpltxt))
9589 (cond ((equal desc "NONE") (setq desc nil))
9590 ((string-match org-bracket-link-analytic-regexp desc)
9591 (let ((d0 (match-string 3 desc))
9592 (p0 (match-string 5 desc)))
9593 (setq desc
9594 (replace-regexp-in-string
9595 org-bracket-link-regexp
9596 (concat (or p0 d0)
9597 (if (equal (length (match-string 0 desc))
9598 (length desc)) "*" "")) desc)))))
9600 ;; Return the link
9601 (if (not (and (or (org-called-interactively-p 'any)
9602 executing-kbd-macro) link))
9603 (or agenda-link (and link (org-make-link-string link desc)))
9604 (push (list link desc) org-stored-links)
9605 (message "Stored: %s" (or desc link))
9606 (when custom-id
9607 (setq link (concat "file:" (abbreviate-file-name
9608 (buffer-file-name)) "::#" custom-id))
9609 (push (list link desc) org-stored-links)))))))
9611 (defun org-store-link-props (&rest plist)
9612 "Store link properties, extract names and addresses."
9613 (let (x adr)
9614 (when (setq x (plist-get plist :from))
9615 (setq adr (mail-extract-address-components x))
9616 (setq plist (plist-put plist :fromname (car adr)))
9617 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9618 (when (setq x (plist-get plist :to))
9619 (setq adr (mail-extract-address-components x))
9620 (setq plist (plist-put plist :toname (car adr)))
9621 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9622 (let ((from (plist-get plist :from))
9623 (to (plist-get plist :to)))
9624 (when (and from to org-from-is-user-regexp)
9625 (setq plist
9626 (plist-put plist :fromto
9627 (if (string-match org-from-is-user-regexp from)
9628 (concat "to %t")
9629 (concat "from %f"))))))
9630 (setq org-store-link-plist plist))
9632 (defun org-add-link-props (&rest plist)
9633 "Add these properties to the link property list."
9634 (let (key value)
9635 (while plist
9636 (setq key (pop plist) value (pop plist))
9637 (setq org-store-link-plist
9638 (plist-put org-store-link-plist key value)))))
9640 (defun org-email-link-description (&optional fmt)
9641 "Return the description part of an email link.
9642 This takes information from `org-store-link-plist' and formats it
9643 according to FMT (default from `org-email-link-description-format')."
9644 (setq fmt (or fmt org-email-link-description-format))
9645 (let* ((p org-store-link-plist)
9646 (to (plist-get p :toaddress))
9647 (from (plist-get p :fromaddress))
9648 (table
9649 (list
9650 (cons "%c" (plist-get p :fromto))
9651 (cons "%F" (plist-get p :from))
9652 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9653 (cons "%T" (plist-get p :to))
9654 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9655 (cons "%s" (plist-get p :subject))
9656 (cons "%d" (plist-get p :date))
9657 (cons "%m" (plist-get p :message-id)))))
9658 (when (string-match "%c" fmt)
9659 ;; Check if the user wrote this message
9660 (if (and org-from-is-user-regexp from to
9661 (save-match-data (string-match org-from-is-user-regexp from)))
9662 (setq fmt (replace-match "to %t" t t fmt))
9663 (setq fmt (replace-match "from %f" t t fmt))))
9664 (org-replace-escapes fmt table)))
9666 (defun org-make-org-heading-search-string (&optional string)
9667 "Make search string for the current headline or STRING."
9668 (let ((s (or string
9669 (and (derived-mode-p 'org-mode)
9670 (save-excursion
9671 (org-back-to-heading t)
9672 (org-element-property :raw-value (org-element-at-point))))))
9673 (lines org-context-in-file-links))
9674 (or string (setq s (concat "*" s))) ; Add * for headlines
9675 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9676 (when (and string (integerp lines) (> lines 0))
9677 (let ((slines (org-split-string s "\n")))
9678 (when (< lines (length slines))
9679 (setq s (mapconcat
9680 'identity
9681 (reverse (nthcdr (- (length slines) lines)
9682 (reverse slines))) "\n")))))
9683 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9685 (defun org-make-link-string (link &optional description)
9686 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9687 (unless (string-match "\\S-" link)
9688 (error "Empty link"))
9689 (when (and description
9690 (stringp description)
9691 (not (string-match "\\S-" description)))
9692 (setq description nil))
9693 (when (stringp description)
9694 ;; Remove brackets from the description, they are fatal.
9695 (while (string-match "\\[" description)
9696 (setq description (replace-match "{" t t description)))
9697 (while (string-match "\\]" description)
9698 (setq description (replace-match "}" t t description))))
9699 (when (equal link description)
9700 ;; No description needed, it is identical
9701 (setq description nil))
9702 (when (and (not description)
9703 (not (string-match (org-image-file-name-regexp) link))
9704 (not (equal link (org-link-escape link))))
9705 (setq description (org-extract-attributes link)))
9706 (setq link
9707 (cond ((string-match (org-image-file-name-regexp) link) link)
9708 ((string-match org-link-types-re link)
9709 (concat (match-string 1 link)
9710 (org-link-escape (substring link (match-end 1)))))
9711 (t (org-link-escape link))))
9712 (concat "[[" link "]"
9713 (if description (concat "[" description "]") "")
9714 "]"))
9716 (defconst org-link-escape-chars
9717 ;;%20 %2B %3B %3D %5B %5D
9718 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9719 "List of characters that should be escaped in link.
9720 This is the list that is used for internal purposes.")
9722 (defconst org-link-escape-chars-browser
9723 ;;%20 %22
9724 '(?\ ?\")
9725 "List of escapes for characters that are problematic in links.
9726 This is the list that is used before handing over to the browser.")
9728 (defun org-link-escape (text &optional table merge)
9729 "Return percent escaped representation of TEXT.
9730 TEXT is a string with the text to escape.
9731 Optional argument TABLE is a list with characters that should be
9732 escaped. When nil, `org-link-escape-chars' is used.
9733 If optional argument MERGE is set, merge TABLE into
9734 `org-link-escape-chars'."
9735 (cond
9736 ((and table merge)
9737 (mapc (lambda (defchr)
9738 (unless (member defchr table)
9739 (setq table (cons defchr table)))) org-link-escape-chars))
9740 ((null table)
9741 (setq table org-link-escape-chars)))
9742 (mapconcat
9743 (lambda (char)
9744 (if (or (member char table)
9745 (and (or (< char 32) (= char ?\%) (> char 126))
9746 org-url-hexify-p))
9747 (mapconcat (lambda (sequence-element)
9748 (format "%%%.2X" sequence-element))
9749 (or (encode-coding-char char 'utf-8)
9750 (error "Unable to percent escape character: %s"
9751 (char-to-string char))) "")
9752 (char-to-string char))) text ""))
9754 (defun org-link-escape-browser (text)
9755 (if (org-string-match-p
9756 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9757 text)
9758 (org-link-escape text org-link-escape-chars-browser)
9759 text))
9761 (defun org-link-unescape (str)
9762 "Unhex hexified Unicode strings as returned from the JavaScript function
9763 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9764 (unless (and (null str) (string= "" str))
9765 (let ((pos 0) (case-fold-search t) unhexed)
9766 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9767 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9768 (setq str (replace-match unhexed t t str))
9769 (setq pos (+ pos (length unhexed))))))
9770 str)
9772 (defun org-link-unescape-compound (hex)
9773 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9774 Note: this function also decodes single byte encodings like
9775 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9776 (save-match-data
9777 (let* ((bytes (cdr (split-string hex "%")))
9778 (ret "")
9779 (eat 0)
9780 (sum 0))
9781 (while bytes
9782 (let* ((val (string-to-number (pop bytes) 16))
9783 (shift-xor
9784 (if (= 0 eat)
9785 (cond
9786 ((>= val 252) (cons 6 252))
9787 ((>= val 248) (cons 5 248))
9788 ((>= val 240) (cons 4 240))
9789 ((>= val 224) (cons 3 224))
9790 ((>= val 192) (cons 2 192))
9791 (t (cons 0 0)))
9792 (cons 6 128))))
9793 (if (>= val 192) (setq eat (car shift-xor)))
9794 (setq val (logxor val (cdr shift-xor)))
9795 (setq sum (+ (lsh sum (car shift-xor)) val))
9796 (if (> eat 0) (setq eat (- eat 1)))
9797 (cond
9798 ((= 0 eat) ;multi byte
9799 (setq ret (concat ret (org-char-to-string sum)))
9800 (setq sum 0))
9801 ((not bytes) ; single byte(s)
9802 (setq ret (org-link-unescape-single-byte-sequence hex))))
9803 )) ;; end (while bytes
9804 ret )))
9806 (defun org-link-unescape-single-byte-sequence (hex)
9807 "Unhexify hex-encoded single byte character sequences."
9808 (mapconcat (lambda (byte)
9809 (char-to-string (string-to-number byte 16)))
9810 (cdr (split-string hex "%")) ""))
9812 (defun org-xor (a b)
9813 "Exclusive or."
9814 (if a (not b) b))
9816 (defun org-fixup-message-id-for-http (s)
9817 "Replace special characters in a message id, so it can be used in an http query."
9818 (when (string-match "%" s)
9819 (setq s (mapconcat (lambda (c)
9820 (if (eq c ?%)
9821 "%25"
9822 (char-to-string c)))
9823 s "")))
9824 (while (string-match "<" s)
9825 (setq s (replace-match "%3C" t t s)))
9826 (while (string-match ">" s)
9827 (setq s (replace-match "%3E" t t s)))
9828 (while (string-match "@" s)
9829 (setq s (replace-match "%40" t t s)))
9832 (defun org-link-prettify (link)
9833 "Return a human-readable representation of LINK.
9834 The car of LINK must be a raw link the cdr of LINK must be either
9835 a link description or nil."
9836 (let ((desc (or (cadr link) "<no description>")))
9837 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9838 "<" (car link) ">")))
9840 ;;;###autoload
9841 (defun org-insert-link-global ()
9842 "Insert a link like Org-mode does.
9843 This command can be called in any mode to insert a link in Org-mode syntax."
9844 (interactive)
9845 (org-load-modules-maybe)
9846 (org-run-like-in-org-mode 'org-insert-link))
9848 (defun org-insert-all-links (&optional keep)
9849 "Insert all links in `org-stored-links'."
9850 (interactive "P")
9851 (let ((links (copy-sequence org-stored-links)) l)
9852 (while (setq l (if keep (pop links) (pop org-stored-links)))
9853 (insert "- ")
9854 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9855 (insert "\n"))))
9857 (defun org-link-fontify-links-to-this-file ()
9858 "Fontify links to the current file in `org-stored-links'."
9859 (let ((f (buffer-file-name)) a b)
9860 (setq a (mapcar (lambda(l)
9861 (let ((ll (car l)))
9862 (when (and (string-match "^file:\\(.+\\)::" ll)
9863 (equal f (expand-file-name (match-string 1 ll))))
9864 ll)))
9865 org-stored-links))
9866 (when (featurep 'org-id)
9867 (setq b (mapcar (lambda(l)
9868 (let ((ll (car l)))
9869 (when (and (string-match "^id:\\(.+\\)$" ll)
9870 (equal f (expand-file-name
9871 (or (org-id-find-id-file
9872 (match-string 1 ll)) ""))))
9873 ll)))
9874 org-stored-links)))
9875 (mapcar (lambda(l)
9876 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9877 (delq nil (append a b)))))
9879 (defvar org-link-links-in-this-file nil)
9880 (defun org-insert-link (&optional complete-file link-location default-description)
9881 "Insert a link. At the prompt, enter the link.
9883 Completion can be used to insert any of the link protocol prefixes like
9884 http or ftp in use.
9886 The history can be used to select a link previously stored with
9887 `org-store-link'. When the empty string is entered (i.e. if you just
9888 press RET at the prompt), the link defaults to the most recently
9889 stored link. As SPC triggers completion in the minibuffer, you need to
9890 use M-SPC or C-q SPC to force the insertion of a space character.
9892 You will also be prompted for a description, and if one is given, it will
9893 be displayed in the buffer instead of the link.
9895 If there is already a link at point, this command will allow you to edit link
9896 and description parts.
9898 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9899 be selected using completion. The path to the file will be relative to the
9900 current directory if the file is in the current directory or a subdirectory.
9901 Otherwise, the link will be the absolute path as completed in the minibuffer
9902 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9903 option `org-link-file-path-type'.
9905 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9906 the current directory or below.
9908 With three \\[universal-argument] prefixes, negate the meaning of
9909 `org-keep-stored-link-after-insertion'.
9911 If `org-make-link-description-function' is non-nil, this function will be
9912 called with the link target, and the result will be the default
9913 link description.
9915 If the LINK-LOCATION parameter is non-nil, this value will be
9916 used as the link location instead of reading one interactively.
9918 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9919 be used as the default description."
9920 (interactive "P")
9921 (let* ((wcf (current-window-configuration))
9922 (origbuf (current-buffer))
9923 (region (if (org-region-active-p)
9924 (buffer-substring (region-beginning) (region-end))))
9925 (remove (and region (list (region-beginning) (region-end))))
9926 (desc region)
9927 tmphist ; byte-compile incorrectly complains about this
9928 (link link-location)
9929 (abbrevs org-link-abbrev-alist-local)
9930 entry file all-prefixes auto-desc)
9931 (cond
9932 (link-location) ; specified by arg, just use it.
9933 ((org-in-regexp org-bracket-link-regexp 1)
9934 ;; We do have a link at point, and we are going to edit it.
9935 (setq remove (list (match-beginning 0) (match-end 0)))
9936 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9937 (setq link (read-string "Link: "
9938 (org-link-unescape
9939 (org-match-string-no-properties 1)))))
9940 ((or (org-in-regexp org-angle-link-re)
9941 (org-in-regexp org-plain-link-re))
9942 ;; Convert to bracket link
9943 (setq remove (list (match-beginning 0) (match-end 0))
9944 link (read-string "Link: "
9945 (org-remove-angle-brackets (match-string 0)))))
9946 ((member complete-file '((4) (16)))
9947 ;; Completing read for file names.
9948 (setq link (org-file-complete-link complete-file)))
9950 ;; Read link, with completion for stored links.
9951 (org-link-fontify-links-to-this-file)
9952 (org-switch-to-buffer-other-window "*Org Links*")
9953 (with-current-buffer "*Org Links*"
9954 (erase-buffer)
9955 (insert "Insert a link.
9956 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9957 (when org-stored-links
9958 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9959 (insert (mapconcat 'org-link-prettify
9960 (reverse org-stored-links) "\n")))
9961 (goto-char (point-min)))
9962 (let ((cw (selected-window)))
9963 (select-window (get-buffer-window "*Org Links*" 'visible))
9964 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9965 (unless (pos-visible-in-window-p (point-max))
9966 (org-fit-window-to-buffer))
9967 (and (window-live-p cw) (select-window cw)))
9968 ;; Fake a link history, containing the stored links.
9969 (setq tmphist (append (mapcar 'car org-stored-links)
9970 org-insert-link-history))
9971 (setq all-prefixes (append (mapcar 'car abbrevs)
9972 (mapcar 'car org-link-abbrev-alist)
9973 org-link-types))
9974 (unwind-protect
9975 (progn
9976 (setq link
9977 (org-completing-read
9978 "Link: "
9979 (append
9980 (mapcar (lambda (x) (concat x ":"))
9981 all-prefixes)
9982 (mapcar 'car org-stored-links))
9983 nil nil nil
9984 'tmphist
9985 (caar org-stored-links)))
9986 (if (not (string-match "\\S-" link))
9987 (user-error "No link selected"))
9988 (mapc (lambda(l)
9989 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9990 org-stored-links)
9991 (if (or (member link all-prefixes)
9992 (and (equal ":" (substring link -1))
9993 (member (substring link 0 -1) all-prefixes)
9994 (setq link (substring link 0 -1))))
9995 (setq link (with-current-buffer origbuf
9996 (org-link-try-special-completion link)))))
9997 (set-window-configuration wcf)
9998 (kill-buffer "*Org Links*"))
9999 (setq entry (assoc link org-stored-links))
10000 (or entry (push link org-insert-link-history))
10001 (setq desc (or desc (nth 1 entry)))))
10003 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10004 (not org-keep-stored-link-after-insertion))
10005 (setq org-stored-links (delq (assoc link org-stored-links)
10006 org-stored-links)))
10008 (if (string-match org-plain-link-re link)
10009 ;; URL-like link, normalize the use of angular brackets.
10010 (setq link (org-remove-angle-brackets link)))
10012 ;; Check if we are linking to the current file with a search
10013 ;; option If yes, simplify the link by using only the search
10014 ;; option.
10015 (when (and buffer-file-name
10016 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10017 (let* ((path (match-string 1 link))
10018 (case-fold-search nil)
10019 (search (match-string 2 link)))
10020 (save-match-data
10021 (if (equal (file-truename buffer-file-name) (file-truename path))
10022 ;; We are linking to this same file, with a search option
10023 (setq link search)))))
10025 ;; Check if we can/should use a relative path. If yes, simplify the link
10026 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10027 (let* ((type (match-string 1 link))
10028 (path (match-string 2 link))
10029 (origpath path)
10030 (case-fold-search nil))
10031 (cond
10032 ((or (eq org-link-file-path-type 'absolute)
10033 (equal complete-file '(16)))
10034 (setq path (abbreviate-file-name (expand-file-name path))))
10035 ((eq org-link-file-path-type 'noabbrev)
10036 (setq path (expand-file-name path)))
10037 ((eq org-link-file-path-type 'relative)
10038 (setq path (file-relative-name path)))
10040 (save-match-data
10041 (if (string-match (concat "^" (regexp-quote
10042 (expand-file-name
10043 (file-name-as-directory
10044 default-directory))))
10045 (expand-file-name path))
10046 ;; We are linking a file with relative path name.
10047 (setq path (substring (expand-file-name path)
10048 (match-end 0)))
10049 (setq path (abbreviate-file-name (expand-file-name path)))))))
10050 (setq link (concat type path))
10051 (if (equal desc origpath)
10052 (setq desc path))))
10054 (if org-make-link-description-function
10055 (setq desc
10056 (or (condition-case nil
10057 (funcall org-make-link-description-function link desc)
10058 (error (progn (message "Can't get link description from `%s'"
10059 (symbol-name org-make-link-description-function))
10060 (sit-for 2) nil)))
10061 (read-string "Description: " default-description)))
10062 (if default-description (setq desc default-description)
10063 (setq desc (or (and auto-desc desc)
10064 (read-string "Description: " desc)))))
10066 (unless (string-match "\\S-" desc) (setq desc nil))
10067 (if remove (apply 'delete-region remove))
10068 (insert (org-make-link-string link desc))))
10070 (defun org-link-try-special-completion (type)
10071 "If there is completion support for link type TYPE, offer it."
10072 (let ((fun (intern (concat "org-" type "-complete-link"))))
10073 (if (functionp fun)
10074 (funcall fun)
10075 (read-string "Link (no completion support): " (concat type ":")))))
10077 (defun org-file-complete-link (&optional arg)
10078 "Create a file link using completion."
10079 (let (file link)
10080 (setq file (org-iread-file-name "File: "))
10081 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10082 (pwd1 (file-name-as-directory (abbreviate-file-name
10083 (expand-file-name ".")))))
10084 (cond
10085 ((equal arg '(16))
10086 (setq link (concat
10087 "file:"
10088 (abbreviate-file-name (expand-file-name file)))))
10089 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10090 (setq link (concat "file:" (match-string 1 file))))
10091 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10092 (expand-file-name file))
10093 (setq link (concat
10094 "file:" (match-string 1 (expand-file-name file)))))
10095 (t (setq link (concat "file:" file)))))
10096 link))
10098 (defun org-iread-file-name (&rest args)
10099 "Read-file-name using `ido-mode' speedup if available.
10100 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10101 See `read-file-name' for a description of parameters."
10102 (org-without-partial-completion
10103 (if (and org-completion-use-ido
10104 (fboundp 'ido-read-file-name)
10105 (boundp 'ido-mode) ido-mode
10106 (listp (second args)))
10107 (let ((ido-enter-matching-directory nil))
10108 (apply 'ido-read-file-name args))
10109 (apply 'read-file-name args))))
10111 (defun org-completing-read (&rest args)
10112 "Completing-read with SPACE being a normal character."
10113 (let ((enable-recursive-minibuffers t)
10114 (minibuffer-local-completion-map
10115 (copy-keymap minibuffer-local-completion-map)))
10116 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10117 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10118 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10119 (apply 'org-icompleting-read args)))
10121 (defun org-completing-read-no-i (&rest args)
10122 (let (org-completion-use-ido org-completion-use-iswitchb)
10123 (apply 'org-completing-read args)))
10125 (defun org-iswitchb-completing-read (prompt choices &rest args)
10126 "Use iswitch as a completing-read replacement to choose from choices.
10127 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10128 from."
10129 (let* ((iswitchb-use-virtual-buffers nil)
10130 (iswitchb-make-buflist-hook
10131 (lambda ()
10132 (setq iswitchb-temp-buflist choices))))
10133 (iswitchb-read-buffer prompt)))
10135 (defun org-icompleting-read (&rest args)
10136 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10137 (org-without-partial-completion
10138 (if (and org-completion-use-ido
10139 (fboundp 'ido-completing-read)
10140 (boundp 'ido-mode) ido-mode
10141 (listp (second args)))
10142 (let ((ido-enter-matching-directory nil))
10143 (apply 'ido-completing-read (concat (car args))
10144 (if (consp (car (nth 1 args)))
10145 (mapcar 'car (nth 1 args))
10146 (nth 1 args))
10147 (cddr args)))
10148 (if (and org-completion-use-iswitchb
10149 (boundp 'iswitchb-mode) iswitchb-mode
10150 (listp (second args)))
10151 (apply 'org-iswitchb-completing-read (concat (car args))
10152 (if (consp (car (nth 1 args)))
10153 (mapcar 'car (nth 1 args))
10154 (nth 1 args))
10155 (cddr args))
10156 (apply 'completing-read args)))))
10158 (defun org-extract-attributes (s)
10159 "Extract the attributes cookie from a string and set as text property."
10160 (let (a attr (start 0) key value)
10161 (save-match-data
10162 (when (string-match "{{\\([^}]+\\)}}$" s)
10163 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10164 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10165 (setq key (match-string 1 a) value (match-string 2 a)
10166 start (match-end 0)
10167 attr (plist-put attr (intern key) value))))
10168 (org-add-props s nil 'org-attr attr))
10171 ;;; Opening/following a link
10173 (defvar org-link-search-failed nil)
10175 (defvar org-open-link-functions nil
10176 "Hook for functions finding a plain text link.
10177 These functions must take a single argument, the link content.
10178 They will be called for links that look like [[link text][description]]
10179 when LINK TEXT does not have a protocol like \"http:\" and does not look
10180 like a filename (e.g. \"./blue.png\").
10182 These functions will be called *before* Org attempts to resolve the
10183 link by doing text searches in the current buffer - so if you want a
10184 link \"[[target]]\" to still find \"<<target>>\", your function should
10185 handle this as a special case.
10187 When the function does handle the link, it must return a non-nil value.
10188 If it decides that it is not responsible for this link, it must return
10189 nil to indicate that that Org-mode can continue with other options
10190 like exact and fuzzy text search.")
10192 (defun org-next-link (&optional search-backward)
10193 "Move forward to the next link.
10194 If the link is in hidden text, expose it."
10195 (interactive "P")
10196 (when (and org-link-search-failed (eq this-command last-command))
10197 (goto-char (point-min))
10198 (message "Link search wrapped back to beginning of buffer"))
10199 (setq org-link-search-failed nil)
10200 (let* ((pos (point))
10201 (ct (org-context))
10202 (a (assoc :link ct))
10203 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10204 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10205 ((looking-at org-any-link-re)
10206 ;; Don't stay stuck at link without an org-link face
10207 (forward-char (if search-backward -1 1))))
10208 (if (funcall srch-fun org-any-link-re nil t)
10209 (progn
10210 (goto-char (match-beginning 0))
10211 (if (outline-invisible-p) (org-show-context)))
10212 (goto-char pos)
10213 (setq org-link-search-failed t)
10214 (message "No further link found"))))
10216 (defun org-previous-link ()
10217 "Move backward to the previous link.
10218 If the link is in hidden text, expose it."
10219 (interactive)
10220 (funcall 'org-next-link t))
10222 (defun org-translate-link (s)
10223 "Translate a link string if a translation function has been defined."
10224 (if (and org-link-translation-function
10225 (fboundp org-link-translation-function)
10226 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10227 (progn
10228 (setq s (funcall org-link-translation-function
10229 (match-string 1 s) (match-string 2 s)))
10230 (concat (car s) ":" (cdr s)))
10233 (defun org-translate-link-from-planner (type path)
10234 "Translate a link from Emacs Planner syntax so that Org can follow it.
10235 This is still an experimental function, your mileage may vary."
10236 (cond
10237 ((member type '("http" "https" "news" "ftp"))
10238 ;; standard Internet links are the same.
10239 nil)
10240 ((and (equal type "irc") (string-match "^//" path))
10241 ;; Planner has two / at the beginning of an irc link, we have 1.
10242 ;; We should have zero, actually....
10243 (setq path (substring path 1)))
10244 ((and (equal type "lisp") (string-match "^/" path))
10245 ;; Planner has a slash, we do not.
10246 (setq type "elisp" path (substring path 1)))
10247 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10248 ;; A typical message link. Planner has the id after the final slash,
10249 ;; we separate it with a hash mark
10250 (setq path (concat (match-string 1 path) "#"
10251 (org-remove-angle-brackets (match-string 2 path))))))
10252 (cons type path))
10254 (defun org-find-file-at-mouse (ev)
10255 "Open file link or URL at mouse."
10256 (interactive "e")
10257 (mouse-set-point ev)
10258 (org-open-at-point 'in-emacs))
10260 (defun org-open-at-mouse (ev)
10261 "Open file link or URL at mouse.
10262 See the docstring of `org-open-file' for details."
10263 (interactive "e")
10264 (mouse-set-point ev)
10265 (if (eq major-mode 'org-agenda-mode)
10266 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10267 (org-open-at-point))
10269 (defvar org-window-config-before-follow-link nil
10270 "The window configuration before following a link.
10271 This is saved in case the need arises to restore it.")
10273 (defvar org-open-link-marker (make-marker)
10274 "Marker pointing to the location where `org-open-at-point; was called.")
10276 ;;;###autoload
10277 (defun org-open-at-point-global ()
10278 "Follow a link like Org-mode does.
10279 This command can be called in any mode to follow a link that has
10280 Org-mode syntax."
10281 (interactive)
10282 (org-run-like-in-org-mode 'org-open-at-point))
10284 ;;;###autoload
10285 (defun org-open-link-from-string (s &optional arg reference-buffer)
10286 "Open a link in the string S, as if it was in Org-mode."
10287 (interactive "sLink: \nP")
10288 (let ((reference-buffer (or reference-buffer (current-buffer))))
10289 (with-temp-buffer
10290 (let ((org-inhibit-startup (not reference-buffer)))
10291 (org-mode)
10292 (insert s)
10293 (goto-char (point-min))
10294 (when reference-buffer
10295 (setq org-link-abbrev-alist-local
10296 (with-current-buffer reference-buffer
10297 org-link-abbrev-alist-local)))
10298 (org-open-at-point arg reference-buffer)))))
10300 (defvar org-open-at-point-functions nil
10301 "Hook that is run when following a link at point.
10303 Functions in this hook must return t if they identify and follow
10304 a link at point. If they don't find anything interesting at point,
10305 they must return nil.")
10307 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10308 (defun org-open-at-point (&optional arg reference-buffer)
10309 "Open link at or after point.
10310 If there is no link at point, this function will search forward up to
10311 the end of the current line.
10312 Normally, files will be opened by an appropriate application. If the
10313 optional prefix argument ARG is non-nil, Emacs will visit the file.
10314 With a double prefix argument, try to open outside of Emacs, in the
10315 application the system uses for this file type."
10316 (interactive "P")
10317 ;; if in a code block, then open the block's results
10318 (unless (call-interactively #'org-babel-open-src-block-result)
10319 (org-load-modules-maybe)
10320 (move-marker org-open-link-marker (point))
10321 (setq org-window-config-before-follow-link (current-window-configuration))
10322 (org-remove-occur-highlights nil nil t)
10323 (cond
10324 ((and (org-at-heading-p)
10325 (not (org-at-timestamp-p t))
10326 (not (org-in-regexp
10327 (concat org-plain-link-re "\\|"
10328 org-bracket-link-regexp "\\|"
10329 org-angle-link-re "\\|"
10330 "[ \t]:[^ \t\n]+:[ \t]*$")))
10331 (not (get-text-property (point) 'org-linked-text)))
10332 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10333 (lk0 (car lkall))
10334 (lk (if (stringp lk0) (list lk0) lk0))
10335 (lkend (cdr lkall)))
10336 (mapcar (lambda(l)
10337 (search-forward l nil lkend)
10338 (goto-char (match-beginning 0))
10339 (org-open-at-point))
10340 lk))
10341 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10342 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10343 ((and (org-at-timestamp-p t)
10344 (not (org-in-regexp org-bracket-link-regexp)))
10345 (org-follow-timestamp-link))
10346 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10347 (not (org-in-regexp org-any-link-re)))
10348 (org-footnote-action))
10350 (let (type path link line search (pos (point)))
10351 (catch 'match
10352 (save-excursion
10353 (skip-chars-forward "^]\n\r")
10354 (when (org-in-regexp org-bracket-link-regexp 1)
10355 (setq link (org-extract-attributes
10356 (org-link-unescape (org-match-string-no-properties 1))))
10357 (while (string-match " *\n *" link)
10358 (setq link (replace-match " " t t link)))
10359 (setq link (org-link-expand-abbrev link))
10360 (cond
10361 ((or (file-name-absolute-p link)
10362 (string-match "^\\.\\.?/" link))
10363 (setq type "file" path link))
10364 ((string-match org-link-re-with-space3 link)
10365 (setq type (match-string 1 link) path (match-string 2 link)))
10366 ((string-match "^help:+\\(.+\\)" link)
10367 (setq type "help" path (match-string 1 link)))
10368 (t (setq type "thisfile" path link)))
10369 (throw 'match t)))
10371 (when (get-text-property (point) 'org-linked-text)
10372 (setq type "thisfile"
10373 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10374 (1+ (point)) (point))
10375 path (buffer-substring
10376 (or (previous-single-property-change pos 'org-linked-text)
10377 (point-min))
10378 (or (next-single-property-change pos 'org-linked-text)
10379 (point-max)))
10380 ;; Ensure we will search for a <<<radio>>> link, not
10381 ;; a simple reference like <<ref>>
10382 path (concat "<" path))
10383 (throw 'match t))
10385 (save-excursion
10386 (when (or (org-in-regexp org-angle-link-re)
10387 (let ((match (org-in-regexp org-plain-link-re)))
10388 ;; Check a plain link is not within a bracket link
10389 (and match
10390 (save-excursion
10391 (progn
10392 (goto-char (car match))
10393 (not (org-in-regexp org-bracket-link-regexp))))))
10394 (let ((line_ending (save-excursion (end-of-line) (point))))
10395 ;; We are in a line before a plain or bracket link
10396 (or (re-search-forward org-plain-link-re line_ending t)
10397 (re-search-forward org-bracket-link-regexp line_ending t))))
10398 (setq type (match-string 1)
10399 path (org-link-unescape (match-string 2)))
10400 (throw 'match t)))
10401 (save-excursion
10402 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10403 (setq type "tags"
10404 path (match-string 1))
10405 (while (string-match ":" path)
10406 (setq path (replace-match "+" t t path)))
10407 (throw 'match t)))
10408 (when (org-in-regexp "<\\([^><\n]+\\)>")
10409 (setq type "tree-match"
10410 path (match-string 1))
10411 (throw 'match t)))
10412 (unless path
10413 (user-error "No link found"))
10415 ;; switch back to reference buffer
10416 ;; needed when if called in a temporary buffer through
10417 ;; org-open-link-from-string
10418 (with-current-buffer (or reference-buffer (current-buffer))
10420 ;; Remove any trailing spaces in path
10421 (if (string-match " +\\'" path)
10422 (setq path (replace-match "" t t path)))
10423 (if (and org-link-translation-function
10424 (fboundp org-link-translation-function))
10425 ;; Check if we need to translate the link
10426 (let ((tmp (funcall org-link-translation-function type path)))
10427 (setq type (car tmp) path (cdr tmp))))
10429 (cond
10431 ((assoc type org-link-protocols)
10432 (funcall (nth 1 (assoc type org-link-protocols)) path))
10434 ((equal type "help")
10435 (let ((f-or-v (intern path)))
10436 (cond ((fboundp f-or-v)
10437 (describe-function f-or-v))
10438 ((boundp f-or-v)
10439 (describe-variable f-or-v))
10440 (t (error "Not a known function or variable")))))
10442 ((equal type "mailto")
10443 (let ((cmd (car org-link-mailto-program))
10444 (args (cdr org-link-mailto-program)) args1
10445 (address path) (subject "") a)
10446 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10447 (setq address (match-string 1 path)
10448 subject (org-link-escape (match-string 2 path))))
10449 (while args
10450 (cond
10451 ((not (stringp (car args))) (push (pop args) args1))
10452 (t (setq a (pop args))
10453 (if (string-match "%a" a)
10454 (setq a (replace-match address t t a)))
10455 (if (string-match "%s" a)
10456 (setq a (replace-match subject t t a)))
10457 (push a args1))))
10458 (apply cmd (nreverse args1))))
10460 ((member type '("http" "https" "ftp" "news"))
10461 (browse-url (concat type ":" (org-link-escape-browser path))))
10463 ((string= type "doi")
10464 (browse-url (concat org-doi-server-url
10465 (org-link-escape-browser path))))
10467 ((member type '("message"))
10468 (browse-url (concat type ":" path)))
10470 ((string= type "tags")
10471 (org-tags-view arg path))
10473 ((string= type "tree-match")
10474 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10476 ((string= type "file")
10477 (if (string-match "::\\([0-9]+\\)\\'" path)
10478 (setq line (string-to-number (match-string 1 path))
10479 path (substring path 0 (match-beginning 0)))
10480 (if (string-match "::\\(.+\\)\\'" path)
10481 (setq search (match-string 1 path)
10482 path (substring path 0 (match-beginning 0)))))
10483 (if (string-match "[*?{]" (file-name-nondirectory path))
10484 (dired path)
10485 (org-open-file path arg line search)))
10487 ((string= type "shell")
10488 (let ((buf (generate-new-buffer "*Org Shell Output"))
10489 (cmd path))
10490 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10491 (string-match org-confirm-shell-link-not-regexp cmd))
10492 (not org-confirm-shell-link-function)
10493 (funcall org-confirm-shell-link-function
10494 (format "Execute \"%s\" in shell? "
10495 (org-add-props cmd nil
10496 'face 'org-warning))))
10497 (progn
10498 (message "Executing %s" cmd)
10499 (shell-command cmd buf)
10500 (if (featurep 'midnight)
10501 (setq clean-buffer-list-kill-buffer-names
10502 (cons buf clean-buffer-list-kill-buffer-names))))
10503 (error "Abort"))))
10505 ((string= type "elisp")
10506 (let ((cmd path))
10507 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10508 (string-match org-confirm-elisp-link-not-regexp cmd))
10509 (not org-confirm-elisp-link-function)
10510 (funcall org-confirm-elisp-link-function
10511 (format "Execute \"%s\" as elisp? "
10512 (org-add-props cmd nil
10513 'face 'org-warning))))
10514 (message "%s => %s" cmd
10515 (if (equal (string-to-char cmd) ?\()
10516 (eval (read cmd))
10517 (call-interactively (read cmd))))
10518 (error "Abort"))))
10520 ((and (string= type "thisfile")
10521 (or (run-hook-with-args-until-success
10522 'org-open-link-functions path)
10523 (and link
10524 (string-match "^id:" link)
10525 (or (featurep 'org-id) (require 'org-id))
10526 (progn
10527 (funcall (nth 1 (assoc "id" org-link-protocols))
10528 (substring path 3))
10529 t)))))
10531 ((string= type "thisfile")
10532 (if arg
10533 (switch-to-buffer-other-window
10534 (org-get-buffer-for-internal-link (current-buffer)))
10535 (org-mark-ring-push))
10536 (let ((cmd `(org-link-search
10537 ,path
10538 ,(cond ((equal arg '(4)) ''occur)
10539 ((equal arg '(16)) ''org-occur))
10540 ,pos)))
10541 (condition-case nil (let ((org-link-search-inhibit-query t))
10542 (eval cmd))
10543 (error (progn (widen) (eval cmd))))))
10545 (t (browse-url-at-point)))))))
10546 (move-marker org-open-link-marker nil)
10547 (run-hook-with-args 'org-follow-link-hook)))
10549 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10550 "Offer links in the current entry and return the selected link.
10551 If there is only one link, return it.
10552 If NTH is an integer, return the NTH link found.
10553 If ZERO is a string, check also this string for a link, and if
10554 there is one, return it."
10555 (with-current-buffer buffer
10556 (save-excursion
10557 (save-restriction
10558 (widen)
10559 (goto-char marker)
10560 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10561 "\\(" org-angle-link-re "\\)\\|"
10562 "\\(" org-plain-link-re "\\)"))
10563 (cnt ?0)
10564 (in-emacs (if (integerp nth) nil nth))
10565 have-zero end links link c)
10566 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10567 (push (match-string 0 zero) links)
10568 (setq cnt (1- cnt) have-zero t))
10569 (save-excursion
10570 (org-back-to-heading t)
10571 (setq end (save-excursion (outline-next-heading) (point)))
10572 (while (re-search-forward re end t)
10573 (push (match-string 0) links))
10574 (setq links (org-uniquify (reverse links))))
10575 (cond
10576 ((null links)
10577 (message "No links"))
10578 ((equal (length links) 1)
10579 (setq link (car links)))
10580 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10581 (setq link (nth (if have-zero nth (1- nth)) links)))
10582 (t ; we have to select a link
10583 (save-excursion
10584 (save-window-excursion
10585 (delete-other-windows)
10586 (with-output-to-temp-buffer "*Select Link*"
10587 (mapc (lambda (l)
10588 (if (not (string-match org-bracket-link-regexp l))
10589 (princ (format "[%c] %s\n" (incf cnt)
10590 (org-remove-angle-brackets l)))
10591 (if (match-end 3)
10592 (princ (format "[%c] %s (%s)\n" (incf cnt)
10593 (match-string 3 l) (match-string 1 l)))
10594 (princ (format "[%c] %s\n" (incf cnt)
10595 (match-string 1 l))))))
10596 links))
10597 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10598 (message "Select link to open, RET to open all:")
10599 (setq c (read-char-exclusive))
10600 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10601 (when (equal c ?q) (error "Abort"))
10602 (if (equal c ?\C-m)
10603 (setq link links)
10604 (setq nth (- c ?0))
10605 (if have-zero (setq nth (1+ nth)))
10606 (unless (and (integerp nth) (>= (length links) nth))
10607 (user-error "Invalid link selection"))
10608 (setq link (nth (1- nth) links)))))
10609 (cons link end))))))
10611 ;; Add special file links that specify the way of opening
10613 (org-add-link-type "file+sys" 'org-open-file-with-system)
10614 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10615 (defun org-open-file-with-system (path)
10616 "Open file at PATH using the system way of opening it."
10617 (org-open-file path 'system))
10618 (defun org-open-file-with-emacs (path)
10619 "Open file at PATH in Emacs."
10620 (org-open-file path 'emacs))
10623 ;;; File search
10625 (defvar org-create-file-search-functions nil
10626 "List of functions to construct the right search string for a file link.
10627 These functions are called in turn with point at the location to
10628 which the link should point.
10630 A function in the hook should first test if it would like to
10631 handle this file type, for example by checking the `major-mode'
10632 or the file extension. If it decides not to handle this file, it
10633 should just return nil to give other functions a chance. If it
10634 does handle the file, it must return the search string to be used
10635 when following the link. The search string will be part of the
10636 file link, given after a double colon, and `org-open-at-point'
10637 will automatically search for it. If special measures must be
10638 taken to make the search successful, another function should be
10639 added to the companion hook `org-execute-file-search-functions',
10640 which see.
10642 A function in this hook may also use `setq' to set the variable
10643 `description' to provide a suggestion for the descriptive text to
10644 be used for this link when it gets inserted into an Org-mode
10645 buffer with \\[org-insert-link].")
10647 (defvar org-execute-file-search-functions nil
10648 "List of functions to execute a file search triggered by a link.
10650 Functions added to this hook must accept a single argument, the
10651 search string that was part of the file link, the part after the
10652 double colon. The function must first check if it would like to
10653 handle this search, for example by checking the `major-mode' or
10654 the file extension. If it decides not to handle this search, it
10655 should just return nil to give other functions a chance. If it
10656 does handle the search, it must return a non-nil value to keep
10657 other functions from trying.
10659 Each function can access the current prefix argument through the
10660 variable `current-prefix-arg'. Note that a single prefix is used
10661 to force opening a link in Emacs, so it may be good to only use a
10662 numeric or double prefix to guide the search function.
10664 In case this is needed, a function in this hook can also restore
10665 the window configuration before `org-open-at-point' was called using:
10667 (set-window-configuration org-window-config-before-follow-link)")
10669 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10670 (defun org-link-search (s &optional type avoid-pos stealth)
10671 "Search for a link search option.
10672 If S is surrounded by forward slashes, it is interpreted as a
10673 regular expression. In org-mode files, this will create an `org-occur'
10674 sparse tree. In ordinary files, `occur' will be used to list matches.
10675 If the current buffer is in `dired-mode', grep will be used to search
10676 in all files. If AVOID-POS is given, ignore matches near that position.
10678 When optional argument STEALTH is non-nil, do not modify
10679 visibility around point, thus ignoring
10680 `org-show-hierarchy-above', `org-show-following-heading' and
10681 `org-show-siblings' variables."
10682 (let ((case-fold-search t)
10683 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10684 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10685 (append '(("") (" ") ("\t") ("\n"))
10686 org-emphasis-alist)
10687 "\\|") "\\)"))
10688 (pos (point))
10689 (pre nil) (post nil)
10690 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10691 (cond
10692 ;; First check if there are any special search functions
10693 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10694 ;; Now try the builtin stuff
10695 ((and (equal (string-to-char s0) ?#)
10696 (> (length s0) 1)
10697 (save-excursion
10698 (goto-char (point-min))
10699 (and
10700 (re-search-forward
10701 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10702 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10703 (setq type 'dedicated
10704 pos (match-beginning 0))))
10705 ;; There is an exact target for this
10706 (goto-char pos)
10707 (org-back-to-heading t)))
10708 ((save-excursion
10709 (goto-char (point-min))
10710 (and
10711 (re-search-forward
10712 (concat "<<" (regexp-quote s0) ">>") nil t)
10713 (setq type 'dedicated
10714 pos (match-beginning 0))))
10715 ;; There is an exact target for this
10716 (goto-char pos))
10717 ((save-excursion
10718 (goto-char (point-min))
10719 (and
10720 (re-search-forward
10721 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10722 (setq type 'dedicated pos (match-beginning 0))))
10723 ;; Found an element with a matching #+name affiliated keyword.
10724 (goto-char pos))
10725 ((and (string-match "^(\\(.*\\))$" s0)
10726 (save-excursion
10727 (goto-char (point-min))
10728 (and
10729 (re-search-forward
10730 (concat "[^[]" (regexp-quote
10731 (format org-coderef-label-format
10732 (match-string 1 s0))))
10733 nil t)
10734 (setq type 'dedicated
10735 pos (1+ (match-beginning 0))))))
10736 ;; There is a coderef target for this
10737 (goto-char pos))
10738 ((string-match "^/\\(.*\\)/$" s)
10739 ;; A regular expression
10740 (cond
10741 ((derived-mode-p 'org-mode)
10742 (org-occur (match-string 1 s)))
10743 (t (org-do-occur (match-string 1 s)))))
10744 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10745 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10746 (goto-char (point-min))
10747 (cond
10748 ((let (case-fold-search)
10749 (re-search-forward (format org-complex-heading-regexp-format
10750 (regexp-quote s))
10751 nil t))
10752 ;; OK, found a match
10753 (setq type 'dedicated)
10754 (goto-char (match-beginning 0)))
10755 ((and (not org-link-search-inhibit-query)
10756 (eq org-link-search-must-match-exact-headline 'query-to-create)
10757 (y-or-n-p "No match - create this as a new heading? "))
10758 (goto-char (point-max))
10759 (or (bolp) (newline))
10760 (insert "* " s "\n")
10761 (beginning-of-line 0))
10763 (goto-char pos)
10764 (error "No match"))))
10766 ;; A normal search string
10767 (when (equal (string-to-char s) ?*)
10768 ;; Anchor on headlines, post may include tags.
10769 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10770 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10771 s (substring s 1)))
10772 (remove-text-properties
10773 0 (length s)
10774 '(face nil mouse-face nil keymap nil fontified nil) s)
10775 ;; Make a series of regular expressions to find a match
10776 (setq words (org-split-string s "[ \n\r\t]+")
10778 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10779 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10780 "\\)" markers)
10781 re2a_ (concat "\\(" (mapconcat 'downcase words
10782 "[ \t\r\n]+") "\\)[ \t\r\n]")
10783 re2a (concat "[ \t\r\n]" re2a_)
10784 re4_ (concat "\\(" (mapconcat 'downcase words
10785 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10786 re4 (concat "[^a-zA-Z_]" re4_)
10788 re1 (concat pre re2 post)
10789 re3 (concat pre (if pre re4_ re4) post)
10790 re5 (concat pre ".*" re4)
10791 re2 (concat pre re2)
10792 re2a (concat pre (if pre re2a_ re2a))
10793 re4 (concat pre (if pre re4_ re4))
10794 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10795 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10796 re5 "\\)"))
10797 (cond
10798 ((eq type 'org-occur) (org-occur reall))
10799 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10800 (t (goto-char (point-min))
10801 (setq type 'fuzzy)
10802 (if (or (and (org-search-not-self 1 re0 nil t)
10803 (setq type 'dedicated))
10804 (org-search-not-self 1 re1 nil t)
10805 (org-search-not-self 1 re2 nil t)
10806 (org-search-not-self 1 re2a nil t)
10807 (org-search-not-self 1 re3 nil t)
10808 (org-search-not-self 1 re4 nil t)
10809 (org-search-not-self 1 re5 nil t))
10810 (goto-char (match-beginning 1))
10811 (goto-char pos)
10812 (error "No match"))))))
10813 (and (derived-mode-p 'org-mode)
10814 (not stealth)
10815 (org-show-context 'link-search))
10816 type))
10818 (defun org-search-not-self (group &rest args)
10819 "Execute `re-search-forward', but only accept matches that do not
10820 enclose the position of `org-open-link-marker'."
10821 (let ((m org-open-link-marker))
10822 (catch 'exit
10823 (while (apply 're-search-forward args)
10824 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10825 (goto-char (match-end group))
10826 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10827 (> (match-beginning 0) (marker-position m))
10828 (< (match-end 0) (marker-position m)))
10829 (save-match-data
10830 (or (not (org-in-regexp
10831 org-bracket-link-analytic-regexp 1))
10832 (not (match-end 4)) ; no description
10833 (and (<= (match-beginning 4) (point))
10834 (>= (match-end 4) (point))))))
10835 (throw 'exit (point))))))))
10837 (defun org-get-buffer-for-internal-link (buffer)
10838 "Return a buffer to be used for displaying the link target of internal links."
10839 (cond
10840 ((not org-display-internal-link-with-indirect-buffer)
10841 buffer)
10842 ((string-match "(Clone)$" (buffer-name buffer))
10843 (message "Buffer is already a clone, not making another one")
10844 ;; we also do not modify visibility in this case
10845 buffer)
10846 (t ; make a new indirect buffer for displaying the link
10847 (let* ((bn (buffer-name buffer))
10848 (ibn (concat bn "(Clone)"))
10849 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10850 (with-current-buffer ib (org-overview))
10851 ib))))
10853 (defun org-do-occur (regexp &optional cleanup)
10854 "Call the Emacs command `occur'.
10855 If CLEANUP is non-nil, remove the printout of the regular expression
10856 in the *Occur* buffer. This is useful if the regex is long and not useful
10857 to read."
10858 (occur regexp)
10859 (when cleanup
10860 (let ((cwin (selected-window)) win beg end)
10861 (when (setq win (get-buffer-window "*Occur*"))
10862 (select-window win))
10863 (goto-char (point-min))
10864 (when (re-search-forward "match[a-z]+" nil t)
10865 (setq beg (match-end 0))
10866 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10867 (setq end (1- (match-beginning 0)))))
10868 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10869 (goto-char (point-min))
10870 (select-window cwin))))
10872 ;;; The mark ring for links jumps
10874 (defvar org-mark-ring nil
10875 "Mark ring for positions before jumps in Org-mode.")
10876 (defvar org-mark-ring-last-goto nil
10877 "Last position in the mark ring used to go back.")
10878 ;; Fill and close the ring
10879 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10880 (loop for i from 1 to org-mark-ring-length do
10881 (push (make-marker) org-mark-ring))
10882 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10883 org-mark-ring)
10885 (defun org-mark-ring-push (&optional pos buffer)
10886 "Put the current position or POS into the mark ring and rotate it."
10887 (interactive)
10888 (setq pos (or pos (point)))
10889 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10890 (move-marker (car org-mark-ring)
10891 (or pos (point))
10892 (or buffer (current-buffer)))
10893 (message "%s"
10894 (substitute-command-keys
10895 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10897 (defun org-mark-ring-goto (&optional n)
10898 "Jump to the previous position in the mark ring.
10899 With prefix arg N, jump back that many stored positions. When
10900 called several times in succession, walk through the entire ring.
10901 Org-mode commands jumping to a different position in the current file,
10902 or to another Org-mode file, automatically push the old position
10903 onto the ring."
10904 (interactive "p")
10905 (let (p m)
10906 (if (eq last-command this-command)
10907 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10908 (setq p org-mark-ring))
10909 (setq org-mark-ring-last-goto p)
10910 (setq m (car p))
10911 (org-pop-to-buffer-same-window (marker-buffer m))
10912 (goto-char m)
10913 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10915 (defun org-remove-angle-brackets (s)
10916 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10917 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10919 (defun org-add-angle-brackets (s)
10920 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10921 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10923 (defun org-remove-double-quotes (s)
10924 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10925 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10928 ;;; Following specific links
10930 (defun org-follow-timestamp-link ()
10931 "Open an agenda view for the time-stamp date/range at point."
10932 (cond
10933 ((org-at-date-range-p t)
10934 (let ((org-agenda-start-on-weekday)
10935 (t1 (match-string 1))
10936 (t2 (match-string 2)) tt1 tt2)
10937 (setq tt1 (time-to-days (org-time-string-to-time t1))
10938 tt2 (time-to-days (org-time-string-to-time t2)))
10939 (let ((org-agenda-buffer-tmp-name
10940 (format "*Org Agenda(a:%s)"
10941 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10942 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10943 ((org-at-timestamp-p t)
10944 (let ((org-agenda-buffer-tmp-name
10945 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10946 (org-agenda-list nil (time-to-days (org-time-string-to-time
10947 (substring (match-string 1) 0 10)))
10948 1)))
10949 (t (error "This should not happen"))))
10952 ;;; Following file links
10953 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10954 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10955 (declare-function mailcap-mime-info
10956 "mailcap" (string &optional request no-decode))
10957 (defvar org-wait nil)
10958 (defun org-open-file (path &optional in-emacs line search)
10959 "Open the file at PATH.
10960 First, this expands any special file name abbreviations. Then the
10961 configuration variable `org-file-apps' is checked if it contains an
10962 entry for this file type, and if yes, the corresponding command is launched.
10964 If no application is found, Emacs simply visits the file.
10966 With optional prefix argument IN-EMACS, Emacs will visit the file.
10967 With a double \\[universal-argument] \\[universal-argument] \
10968 prefix arg, Org tries to avoid opening in Emacs
10969 and to use an external application to visit the file.
10971 Optional LINE specifies a line to go to, optional SEARCH a string
10972 to search for. If LINE or SEARCH is given, the file will be
10973 opened in Emacs, unless an entry from org-file-apps that makes
10974 use of groups in a regexp matches.
10976 If you want to change the way frames are used when following a
10977 link, please customize `org-link-frame-setup'.
10979 If the file does not exist, an error is thrown."
10980 (let* ((file (if (equal path "")
10981 buffer-file-name
10982 (substitute-in-file-name (expand-file-name path))))
10983 (file-apps (append org-file-apps (org-default-apps)))
10984 (apps (org-remove-if
10985 'org-file-apps-entry-match-against-dlink-p file-apps))
10986 (apps-dlink (org-remove-if-not
10987 'org-file-apps-entry-match-against-dlink-p file-apps))
10988 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10989 (dirp (if remp nil (file-directory-p file)))
10990 (file (if (and dirp org-open-directory-means-index-dot-org)
10991 (concat (file-name-as-directory file) "index.org")
10992 file))
10993 (a-m-a-p (assq 'auto-mode apps))
10994 (dfile (downcase file))
10995 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10996 (link (cond ((and (eq line nil)
10997 (eq search nil))
10998 file)
10999 (line
11000 (concat file "::" (number-to-string line)))
11001 (search
11002 (concat file "::" search))))
11003 (dlink (downcase link))
11004 (old-buffer (current-buffer))
11005 (old-pos (point))
11006 (old-mode major-mode)
11007 ext cmd link-match-data)
11008 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11009 (setq ext (match-string 1 dfile))
11010 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11011 (setq ext (match-string 1 dfile))))
11012 (cond
11013 ((member in-emacs '((16) system))
11014 (setq cmd (cdr (assoc 'system apps))))
11015 (in-emacs (setq cmd 'emacs))
11017 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11018 (and dirp (cdr (assoc 'directory apps)))
11019 ; first, try matching against apps-dlink
11020 ; if we get a match here, store the match data for later
11021 (let ((match (assoc-default dlink apps-dlink
11022 'string-match)))
11023 (if match
11024 (progn (setq link-match-data (match-data))
11025 match)
11026 (progn (setq in-emacs (or in-emacs line search))
11027 nil))) ; if we have no match in apps-dlink,
11028 ; always open the file in emacs if line or search
11029 ; is given (for backwards compatibility)
11030 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11031 'string-match)
11032 (cdr (assoc ext apps))
11033 (cdr (assoc t apps))))))
11034 (when (eq cmd 'system)
11035 (setq cmd (cdr (assoc 'system apps))))
11036 (when (eq cmd 'default)
11037 (setq cmd (cdr (assoc t apps))))
11038 (when (eq cmd 'mailcap)
11039 (require 'mailcap)
11040 (mailcap-parse-mailcaps)
11041 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11042 (command (mailcap-mime-info mime-type)))
11043 (if (stringp command)
11044 (setq cmd command)
11045 (setq cmd 'emacs))))
11046 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11047 (not (file-exists-p file))
11048 (not org-open-non-existing-files))
11049 (user-error "No such file: %s" file))
11050 (cond
11051 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11052 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11053 (while (string-match "['\"]%s['\"]" cmd)
11054 (setq cmd (replace-match "%s" t t cmd)))
11055 (while (string-match "%s" cmd)
11056 (setq cmd (replace-match
11057 (save-match-data
11058 (shell-quote-argument
11059 (convert-standard-filename file)))
11060 t t cmd)))
11062 ;; Replace "%1", "%2" etc. in command with group matches from regex
11063 (save-match-data
11064 (let ((match-index 1)
11065 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11066 (set-match-data link-match-data)
11067 (while (<= match-index number-of-groups)
11068 (let ((regex (concat "%" (number-to-string match-index)))
11069 (replace-with (match-string match-index dlink)))
11070 (while (string-match regex cmd)
11071 (setq cmd (replace-match replace-with t t cmd))))
11072 (setq match-index (+ match-index 1)))))
11074 (save-window-excursion
11075 (message "Running %s...done" cmd)
11076 (start-process-shell-command cmd nil cmd)
11077 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11078 ((or (stringp cmd)
11079 (eq cmd 'emacs))
11080 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11081 (widen)
11082 (if line (org-goto-line line)
11083 (if search (org-link-search search))))
11084 ((consp cmd)
11085 (let ((file (convert-standard-filename file)))
11086 (save-match-data
11087 (set-match-data link-match-data)
11088 (eval cmd))))
11089 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11090 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11091 (or (not (equal old-buffer (current-buffer)))
11092 (not (equal old-pos (point))))
11093 (org-mark-ring-push old-pos old-buffer))))
11095 (defun org-file-apps-entry-match-against-dlink-p (entry)
11096 "This function returns non-nil if `entry' uses a regular
11097 expression which should be matched against the whole link by
11098 org-open-file.
11100 It assumes that is the case when the entry uses a regular
11101 expression which has at least one grouping construct and the
11102 action is either a lisp form or a command string containing
11103 '%1', i.e. using at least one subexpression match as a
11104 parameter."
11105 (let ((selector (car entry))
11106 (action (cdr entry)))
11107 (if (stringp selector)
11108 (and (> (regexp-opt-depth selector) 0)
11109 (or (and (stringp action)
11110 (string-match "%[0-9]" action))
11111 (consp action)))
11112 nil)))
11114 (defun org-default-apps ()
11115 "Return the default applications for this operating system."
11116 (cond
11117 ((eq system-type 'darwin)
11118 org-file-apps-defaults-macosx)
11119 ((eq system-type 'windows-nt)
11120 org-file-apps-defaults-windowsnt)
11121 (t org-file-apps-defaults-gnu)))
11123 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11124 "Convert extensions to regular expressions in the cars of LIST.
11125 Also, weed out any non-string entries, because the return value is used
11126 only for regexp matching.
11127 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11128 point to the symbol `emacs', indicating that the file should
11129 be opened in Emacs."
11130 (append
11131 (delq nil
11132 (mapcar (lambda (x)
11133 (if (not (stringp (car x)))
11135 (if (string-match "\\W" (car x))
11137 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11138 list))
11139 (if add-auto-mode
11140 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11142 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11143 (defun org-file-remote-p (file)
11144 "Test whether FILE specifies a location on a remote system.
11145 Return non-nil if the location is indeed remote.
11147 For example, the filename \"/user@host:/foo\" specifies a location
11148 on the system \"/user@host:\"."
11149 (cond ((fboundp 'file-remote-p)
11150 (file-remote-p file))
11151 ((fboundp 'tramp-handle-file-remote-p)
11152 (tramp-handle-file-remote-p file))
11153 ((and (boundp 'ange-ftp-name-format)
11154 (string-match (car ange-ftp-name-format) file))
11155 t)))
11158 ;;;; Refiling
11160 (defun org-get-org-file ()
11161 "Read a filename, with default directory `org-directory'."
11162 (let ((default (or org-default-notes-file remember-data-file)))
11163 (read-file-name (format "File name [%s]: " default)
11164 (file-name-as-directory org-directory)
11165 default)))
11167 (defun org-notes-order-reversed-p ()
11168 "Check if the current file should receive notes in reversed order."
11169 (cond
11170 ((not org-reverse-note-order) nil)
11171 ((eq t org-reverse-note-order) t)
11172 ((not (listp org-reverse-note-order)) nil)
11173 (t (catch 'exit
11174 (let ((all org-reverse-note-order)
11175 entry)
11176 (while (setq entry (pop all))
11177 (if (string-match (car entry) buffer-file-name)
11178 (throw 'exit (cdr entry))))
11179 nil)))))
11181 (defvar org-refile-target-table nil
11182 "The list of refile targets, created by `org-refile'.")
11184 (defvar org-agenda-new-buffers nil
11185 "Buffers created to visit agenda files.")
11187 (defvar org-refile-cache nil
11188 "Cache for refile targets.")
11190 (defvar org-refile-markers nil
11191 "All the markers used for caching refile locations.")
11193 (defun org-refile-marker (pos)
11194 "Get a new refile marker, but only if caching is in use."
11195 (if (not org-refile-use-cache)
11197 (let ((m (make-marker)))
11198 (move-marker m pos)
11199 (push m org-refile-markers)
11200 m)))
11202 (defun org-refile-cache-clear ()
11203 "Clear the refile cache and disable all the markers."
11204 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11205 (setq org-refile-markers nil)
11206 (setq org-refile-cache nil)
11207 (message "Refile cache has been cleared"))
11209 (defun org-refile-cache-check-set (set)
11210 "Check if all the markers in the cache still have live buffers."
11211 (let (marker)
11212 (catch 'exit
11213 (while (and set (setq marker (nth 3 (pop set))))
11214 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11215 (when (and marker (null (marker-buffer marker)))
11216 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11217 (sit-for 3)
11218 (throw 'exit nil)))
11219 t)))
11221 (defun org-refile-cache-put (set &rest identifiers)
11222 "Push the refile targets SET into the cache, under IDENTIFIERS."
11223 (let* ((key (sha1 (prin1-to-string identifiers)))
11224 (entry (assoc key org-refile-cache)))
11225 (if entry
11226 (setcdr entry set)
11227 (push (cons key set) org-refile-cache))))
11229 (defun org-refile-cache-get (&rest identifiers)
11230 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11231 (cond
11232 ((not org-refile-cache) nil)
11233 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11235 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11236 org-refile-cache))))
11237 (and set (org-refile-cache-check-set set) set)))))
11239 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11240 "Produce a table with refile targets."
11241 (let ((case-fold-search nil)
11242 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11243 (entries (or org-refile-targets '((nil . (:level . 1)))))
11244 targets tgs txt re files f desc descre fast-path-p level pos0)
11245 (message "Getting targets...")
11246 (with-current-buffer (or default-buffer (current-buffer))
11247 (while (setq entry (pop entries))
11248 (setq files (car entry) desc (cdr entry))
11249 (setq fast-path-p nil)
11250 (cond
11251 ((null files) (setq files (list (current-buffer))))
11252 ((eq files 'org-agenda-files)
11253 (setq files (org-agenda-files 'unrestricted)))
11254 ((and (symbolp files) (fboundp files))
11255 (setq files (funcall files)))
11256 ((and (symbolp files) (boundp files))
11257 (setq files (symbol-value files))))
11258 (if (stringp files) (setq files (list files)))
11259 (cond
11260 ((eq (car desc) :tag)
11261 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11262 ((eq (car desc) :todo)
11263 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11264 ((eq (car desc) :regexp)
11265 (setq descre (cdr desc)))
11266 ((eq (car desc) :level)
11267 (setq descre (concat "^\\*\\{" (number-to-string
11268 (if org-odd-levels-only
11269 (1- (* 2 (cdr desc)))
11270 (cdr desc)))
11271 "\\}[ \t]")))
11272 ((eq (car desc) :maxlevel)
11273 (setq fast-path-p t)
11274 (setq descre (concat "^\\*\\{1," (number-to-string
11275 (if org-odd-levels-only
11276 (1- (* 2 (cdr desc)))
11277 (cdr desc)))
11278 "\\}[ \t]")))
11279 (t (error "Bad refiling target description %s" desc)))
11280 (while (setq f (pop files))
11281 (with-current-buffer
11282 (if (bufferp f) f (org-get-agenda-file-buffer f))
11284 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11285 (progn
11286 (if (bufferp f) (setq f (buffer-file-name
11287 (buffer-base-buffer f))))
11288 (setq f (and f (expand-file-name f)))
11289 (if (eq org-refile-use-outline-path 'file)
11290 (push (list (file-name-nondirectory f) f nil nil) tgs))
11291 (save-excursion
11292 (save-restriction
11293 (widen)
11294 (goto-char (point-min))
11295 (while (re-search-forward descre nil t)
11296 (goto-char (setq pos0 (point-at-bol)))
11297 (catch 'next
11298 (when org-refile-target-verify-function
11299 (save-match-data
11300 (or (funcall org-refile-target-verify-function)
11301 (throw 'next t))))
11302 (when (and (looking-at org-complex-heading-regexp)
11303 (not (member (match-string 4) excluded-entries))
11304 (match-string 4))
11305 (setq level (org-reduced-level
11306 (- (match-end 1) (match-beginning 1)))
11307 txt (org-link-display-format (match-string 4))
11308 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11309 re (format org-complex-heading-regexp-format
11310 (regexp-quote (match-string 4))))
11311 (when org-refile-use-outline-path
11312 (setq txt (mapconcat
11313 'org-protect-slash
11314 (append
11315 (if (eq org-refile-use-outline-path
11316 'file)
11317 (list (file-name-nondirectory
11318 (buffer-file-name
11319 (buffer-base-buffer))))
11320 (if (eq org-refile-use-outline-path
11321 'full-file-path)
11322 (list (buffer-file-name
11323 (buffer-base-buffer)))))
11324 (org-get-outline-path fast-path-p
11325 level txt)
11326 (list txt))
11327 "/")))
11328 (push (list txt f re (org-refile-marker (point)))
11329 tgs)))
11330 (when (= (point) pos0)
11331 ;; verification function has not moved point
11332 (goto-char (point-at-eol))))))))
11333 (when org-refile-use-cache
11334 (org-refile-cache-put tgs (buffer-file-name) descre))
11335 (setq targets (append tgs targets))))))
11336 (message "Getting targets...done")
11337 (nreverse targets)))
11339 (defun org-protect-slash (s)
11340 (while (string-match "/" s)
11341 (setq s (replace-match "\\" t t s)))
11344 (defvar org-olpa (make-vector 20 nil))
11346 (defun org-get-outline-path (&optional fastp level heading)
11347 "Return the outline path to the current entry, as a list.
11349 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11350 routine which makes outline path derivations for an entire file,
11351 avoiding backtracing. Refile target collection makes use of that."
11352 (if fastp
11353 (progn
11354 (if (> level 19)
11355 (error "Outline path failure, more than 19 levels"))
11356 (loop for i from level upto 19 do
11357 (aset org-olpa i nil))
11358 (prog1
11359 (delq nil (append org-olpa nil))
11360 (aset org-olpa level heading)))
11361 (let (rtn case-fold-search)
11362 (save-excursion
11363 (save-restriction
11364 (widen)
11365 (while (org-up-heading-safe)
11366 (when (looking-at org-complex-heading-regexp)
11367 (push (org-trim
11368 (replace-regexp-in-string
11369 ;; Remove statistical/checkboxes cookies
11370 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11371 (org-match-string-no-properties 4)))
11372 rtn)))
11373 rtn)))))
11375 (defun org-format-outline-path (path &optional width prefix separator)
11376 "Format the outline path PATH for display.
11377 WIDTH is the maximum number of characters that is available.
11378 PREFIX is a prefix to be included in the returned string,
11379 such as the file name.
11380 SEPARATOR is inserted between the different parts of the path,
11381 the default is \"/\"."
11382 (setq width (or width 79))
11383 (if prefix (setq width (- width (length prefix))))
11384 (if (not path)
11385 (or prefix "")
11386 (let* ((nsteps (length path))
11387 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11388 (maxwidth (if (<= total-width width)
11389 10000 ;; everything fits
11390 ;; we need to shorten the level headings
11391 (/ (- width nsteps) nsteps)))
11392 (org-odd-levels-only nil)
11393 (n 0)
11394 (total (1+ (length prefix))))
11395 (setq maxwidth (max maxwidth 10))
11396 (concat prefix
11397 (if prefix (or separator "/"))
11398 (mapconcat
11399 (lambda (h)
11400 (setq n (1+ n))
11401 (if (and (= n nsteps) (< maxwidth 10000))
11402 (setq maxwidth (- total-width total)))
11403 (if (< (length h) maxwidth)
11404 (progn (setq total (+ total (length h) 1)) h)
11405 (setq h (substring h 0 (- maxwidth 2))
11406 total (+ total maxwidth 1))
11407 (if (string-match "[ \t]+\\'" h)
11408 (setq h (substring h 0 (match-beginning 0))))
11409 (setq h (concat h "..")))
11410 (org-add-props h nil 'face
11411 (nth (% (1- n) org-n-level-faces)
11412 org-level-faces))
11414 path (or separator "/"))))))
11416 (defun org-display-outline-path (&optional file current separator just-return-string)
11417 "Display the current outline path in the echo area.
11419 If FILE is non-nil, prepend the output with the file name.
11420 If CURRENT is non-nil, append the current heading to the output.
11421 SEPARATOR is passed through to `org-format-outline-path'. It separates
11422 the different parts of the path and defaults to \"/\".
11423 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11424 (interactive "P")
11425 (let* (case-fold-search
11426 (bfn (buffer-file-name (buffer-base-buffer)))
11427 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11428 res)
11429 (if current (setq path (append path
11430 (save-excursion
11431 (org-back-to-heading t)
11432 (if (looking-at org-complex-heading-regexp)
11433 (list (match-string 4)))))))
11434 (setq res
11435 (org-format-outline-path
11436 path
11437 (1- (frame-width))
11438 (and file bfn (concat (file-name-nondirectory bfn) separator))
11439 separator))
11440 (if just-return-string
11441 (org-no-properties res)
11442 (org-unlogged-message "%s" res))))
11444 (defvar org-refile-history nil
11445 "History for refiling operations.")
11447 (defvar org-after-refile-insert-hook nil
11448 "Hook run after `org-refile' has inserted its stuff at the new location.
11449 Note that this is still *before* the stuff will be removed from
11450 the *old* location.")
11452 (defvar org-capture-last-stored-marker)
11453 (defvar org-refile-keep nil
11454 "Non-nil means `org-refile' will copy instead of refile.")
11456 (defun org-copy ()
11457 "Like `org-refile', but copy."
11458 (interactive)
11459 (let ((org-refile-keep t))
11460 (funcall 'org-refile nil nil nil "Copy")))
11462 (defun org-refile (&optional goto default-buffer rfloc msg)
11463 "Move the entry or entries at point to another heading.
11464 The list of target headings is compiled using the information in
11465 `org-refile-targets', which see.
11467 At the target location, the entry is filed as a subitem of the target
11468 heading. Depending on `org-reverse-note-order', the new subitem will
11469 either be the first or the last subitem.
11471 If there is an active region, all entries in that region will be moved.
11472 However, the region must fulfill the requirement that the first heading
11473 is the first one sets the top-level of the moved text - at most siblings
11474 below it are allowed.
11476 With prefix arg GOTO, the command will only visit the target location
11477 and not actually move anything.
11479 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11480 go to the location where the last refiling operation has put the subtree.
11482 With a numeric prefix argument of `2', refile to the running clock.
11484 With a numeric prefix argument of `3', emulate `org-refile-keep'
11485 being set to `t' and copy to the target location, don't move it.
11486 Beware that keeping refiled entries may result in duplicated ID
11487 properties.
11489 RFLOC can be a refile location obtained in a different way.
11491 MSG is a string to replace \"Refile\" in the default prompt with
11492 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11494 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11496 If you are using target caching (see `org-refile-use-cache'),
11497 you have to clear the target cache in order to find new targets.
11498 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11499 prefix argument (`C-u C-u C-u C-c C-w')."
11501 (interactive "P")
11502 (if (member goto '(0 (64)))
11503 (org-refile-cache-clear)
11504 (let* ((actionmsg (or msg "Refile"))
11505 (cbuf (current-buffer))
11506 (regionp (org-region-active-p))
11507 (region-start (and regionp (region-beginning)))
11508 (region-end (and regionp (region-end)))
11509 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11510 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11511 pos it nbuf file re level reversed)
11512 (setq last-command nil)
11513 (when regionp
11514 (goto-char region-start)
11515 (or (bolp) (goto-char (point-at-bol)))
11516 (setq region-start (point))
11517 (unless (or (org-kill-is-subtree-p
11518 (buffer-substring region-start region-end))
11519 (prog1 org-refile-active-region-within-subtree
11520 (let ((s (point-at-eol)))
11521 (org-toggle-heading)
11522 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11523 (user-error "The region is not a (sequence of) subtree(s)")))
11524 (if (equal goto '(16))
11525 (org-refile-goto-last-stored)
11526 (when (or
11527 (and (equal goto 2)
11528 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11529 (prog1
11530 (setq it (list (or org-clock-heading "running clock")
11531 (buffer-file-name
11532 (marker-buffer org-clock-hd-marker))
11534 (marker-position org-clock-hd-marker)))
11535 (setq goto nil)))
11536 (setq it (or rfloc
11537 (let (heading-text)
11538 (save-excursion
11539 (unless goto
11540 (org-back-to-heading t)
11541 (setq heading-text
11542 (nth 4 (org-heading-components))))
11544 (org-refile-get-location
11545 (cond (goto "Goto")
11546 (regionp (concat actionmsg " region to"))
11547 (t (concat actionmsg " subtree \""
11548 heading-text "\" to")))
11549 default-buffer
11550 (and (not (equal '(4) goto))
11551 org-refile-allow-creating-parent-nodes)
11552 goto))))))
11553 (setq file (nth 1 it)
11554 re (nth 2 it)
11555 pos (nth 3 it))
11556 (if (and (not goto)
11558 (equal (buffer-file-name) file)
11559 (if regionp
11560 (and (>= pos region-start)
11561 (<= pos region-end))
11562 (and (>= pos (point))
11563 (< pos (save-excursion
11564 (org-end-of-subtree t t))))))
11565 (error "Cannot refile to position inside the tree or region"))
11567 (setq nbuf (or (find-buffer-visiting file)
11568 (find-file-noselect file)))
11569 (if (and goto (not (equal goto 3)))
11570 (progn
11571 (org-pop-to-buffer-same-window nbuf)
11572 (goto-char pos)
11573 (org-show-context 'org-goto))
11574 (if regionp
11575 (progn
11576 (org-kill-new (buffer-substring region-start region-end))
11577 (org-save-markers-in-region region-start region-end))
11578 (org-copy-subtree 1 nil t))
11579 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11580 (find-file-noselect file)))
11581 (setq reversed (org-notes-order-reversed-p))
11582 (save-excursion
11583 (save-restriction
11584 (widen)
11585 (if pos
11586 (progn
11587 (goto-char pos)
11588 (looking-at org-outline-regexp)
11589 (setq level (org-get-valid-level (funcall outline-level) 1))
11590 (goto-char
11591 (if reversed
11592 (or (outline-next-heading) (point-max))
11593 (or (save-excursion (org-get-next-sibling))
11594 (org-end-of-subtree t t)
11595 (point-max)))))
11596 (setq level 1)
11597 (if (not reversed)
11598 (goto-char (point-max))
11599 (goto-char (point-min))
11600 (or (outline-next-heading) (goto-char (point-max)))))
11601 (if (not (bolp)) (newline))
11602 (org-paste-subtree level)
11603 (when org-log-refile
11604 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11605 (unless (eq org-log-refile 'note)
11606 (save-excursion (org-add-log-note))))
11607 (and org-auto-align-tags
11608 (let ((org-loop-over-headlines-in-active-region nil))
11609 (org-set-tags nil t)))
11610 (let ((bookmark-name (plist-get org-bookmark-names-plist
11611 :last-refile)))
11612 (when bookmark-name
11613 (with-demoted-errors
11614 (bookmark-set bookmark-name))))
11615 ;; If we are refiling for capture, make sure that the
11616 ;; last-capture pointers point here
11617 (when (org-bound-and-true-p org-refile-for-capture)
11618 (let ((bookmark-name (plist-get org-bookmark-names-plist
11619 :last-capture-marker)))
11620 (when bookmark-name
11621 (with-demoted-errors
11622 (bookmark-set bookmark-name))))
11623 (move-marker org-capture-last-stored-marker (point)))
11624 (if (fboundp 'deactivate-mark) (deactivate-mark))
11625 (run-hooks 'org-after-refile-insert-hook))))
11626 (unless org-refile-keep
11627 (if regionp
11628 (delete-region (point) (+ (point) (- region-end region-start)))
11629 (delete-region
11630 (and (org-back-to-heading t) (point))
11631 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11632 (when (featurep 'org-inlinetask)
11633 (org-inlinetask-remove-END-maybe))
11634 (setq org-markers-to-move nil)
11635 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11637 (defun org-refile-goto-last-stored ()
11638 "Go to the location where the last refile was stored."
11639 (interactive)
11640 (bookmark-jump "org-refile-last-stored")
11641 (message "This is the location of the last refile"))
11643 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11644 no-exclude)
11645 "Prompt the user for a refile location, using PROMPT.
11646 PROMPT should not be suffixed with a colon and a space, because
11647 this function appends the default value from
11648 `org-refile-history' automatically, if that is not empty.
11649 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11650 this is used for the GOTO interface."
11651 (let ((org-refile-targets org-refile-targets)
11652 (org-refile-use-outline-path org-refile-use-outline-path)
11653 excluded-entries)
11654 (when (and (derived-mode-p 'org-mode)
11655 (not org-refile-use-cache)
11656 (not no-exclude))
11657 (org-map-tree
11658 (lambda()
11659 (setq excluded-entries
11660 (append excluded-entries (list (org-get-heading t t)))))))
11661 (setq org-refile-target-table
11662 (org-refile-get-targets default-buffer excluded-entries)))
11663 (unless org-refile-target-table
11664 (user-error "No refile targets"))
11665 (let* ((cbuf (current-buffer))
11666 (partial-completion-mode nil)
11667 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11668 (cfunc (if (and org-refile-use-outline-path
11669 org-outline-path-complete-in-steps)
11670 'org-olpath-completing-read
11671 'org-icompleting-read))
11672 (extra (if org-refile-use-outline-path "/" ""))
11673 (cbnex (concat (buffer-name) extra))
11674 (filename (and cfn (expand-file-name cfn)))
11675 (tbl (mapcar
11676 (lambda (x)
11677 (if (and (not (member org-refile-use-outline-path
11678 '(file full-file-path)))
11679 (not (equal filename (nth 1 x))))
11680 (cons (concat (car x) extra " ("
11681 (file-name-nondirectory (nth 1 x)) ")")
11682 (cdr x))
11683 (cons (concat (car x) extra) (cdr x))))
11684 org-refile-target-table))
11685 (completion-ignore-case t)
11686 cdef
11687 (prompt (concat prompt
11688 (or (and (car org-refile-history)
11689 (concat " (default " (car org-refile-history) ")"))
11690 (and (assoc cbnex tbl) (setq cdef cbnex)
11691 (concat " (default " cbnex ")"))) ": "))
11692 pa answ parent-target child parent old-hist)
11693 (setq old-hist org-refile-history)
11694 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11695 nil 'org-refile-history (or cdef (car org-refile-history))))
11696 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11697 (org-refile-check-position pa)
11698 (if pa
11699 (progn
11700 (when (or (not org-refile-history)
11701 (not (eq old-hist org-refile-history))
11702 (not (equal (car pa) (car org-refile-history))))
11703 (setq org-refile-history
11704 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11705 org-refile-history
11706 (cdr org-refile-history))))
11707 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11708 (pop org-refile-history)))
11710 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11711 (progn
11712 (setq parent (match-string 1 answ)
11713 child (match-string 2 answ))
11714 (setq parent-target (or (assoc parent tbl)
11715 (assoc (concat parent "/") tbl)))
11716 (when (and parent-target
11717 (or (eq new-nodes t)
11718 (and (eq new-nodes 'confirm)
11719 (y-or-n-p (format "Create new node \"%s\"? "
11720 child)))))
11721 (org-refile-new-child parent-target child)))
11722 (user-error "Invalid target location")))))
11724 (declare-function org-string-nw-p "org-macs" (s))
11725 (defun org-refile-check-position (refile-pointer)
11726 "Check if the refile pointer matches the headline to which it points."
11727 (let* ((file (nth 1 refile-pointer))
11728 (re (nth 2 refile-pointer))
11729 (pos (nth 3 refile-pointer))
11730 buffer)
11731 (if (and (not (markerp pos)) (not file))
11732 (user-error "Please save the buffer to a file before refiling")
11733 (when (org-string-nw-p re)
11734 (setq buffer (if (markerp pos)
11735 (marker-buffer pos)
11736 (or (find-buffer-visiting file)
11737 (find-file-noselect file))))
11738 (with-current-buffer buffer
11739 (save-excursion
11740 (save-restriction
11741 (widen)
11742 (goto-char pos)
11743 (beginning-of-line 1)
11744 (unless (org-looking-at-p re)
11745 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11747 (defun org-refile-new-child (parent-target child)
11748 "Use refile target PARENT-TARGET to add new CHILD below it."
11749 (unless parent-target
11750 (error "Cannot find parent for new node"))
11751 (let ((file (nth 1 parent-target))
11752 (pos (nth 3 parent-target))
11753 level)
11754 (with-current-buffer (or (find-buffer-visiting file)
11755 (find-file-noselect file))
11756 (save-excursion
11757 (save-restriction
11758 (widen)
11759 (if pos
11760 (goto-char pos)
11761 (goto-char (point-max))
11762 (if (not (bolp)) (newline)))
11763 (when (looking-at org-outline-regexp)
11764 (setq level (funcall outline-level))
11765 (org-end-of-subtree t t))
11766 (org-back-over-empty-lines)
11767 (insert "\n" (make-string
11768 (if pos (org-get-valid-level level 1) 1) ?*)
11769 " " child "\n")
11770 (beginning-of-line 0)
11771 (list (concat (car parent-target) "/" child) file "" (point)))))))
11773 (defun org-olpath-completing-read (prompt collection &rest args)
11774 "Read an outline path like a file name."
11775 (let ((thetable collection)
11776 (org-completion-use-ido nil) ; does not work with ido.
11777 (org-completion-use-iswitchb nil)) ; or iswitchb
11778 (apply
11779 'org-icompleting-read prompt
11780 (lambda (string predicate &optional flag)
11781 (let (rtn r f (l (length string)))
11782 (cond
11783 ((eq flag nil)
11784 ;; try completion
11785 (try-completion string thetable))
11786 ((eq flag t)
11787 ;; all-completions
11788 (setq rtn (all-completions string thetable predicate))
11789 (mapcar
11790 (lambda (x)
11791 (setq r (substring x l))
11792 (if (string-match " ([^)]*)$" x)
11793 (setq f (match-string 0 x))
11794 (setq f ""))
11795 (if (string-match "/" r)
11796 (concat string (substring r 0 (match-end 0)) f)
11798 rtn))
11799 ((eq flag 'lambda)
11800 ;; exact match?
11801 (assoc string thetable)))))
11802 args)))
11804 ;;;; Dynamic blocks
11806 (defun org-find-dblock (name)
11807 "Find the first dynamic block with name NAME in the buffer.
11808 If not found, stay at current position and return nil."
11809 (let ((case-fold-search t) pos)
11810 (save-excursion
11811 (goto-char (point-min))
11812 (setq pos (and (re-search-forward
11813 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11814 (match-beginning 0))))
11815 (if pos (goto-char pos))
11816 pos))
11818 (defconst org-dblock-start-re
11819 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11820 "Matches the start line of a dynamic block, with parameters.")
11822 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11823 "Matches the end of a dynamic block.")
11825 (defun org-create-dblock (plist)
11826 "Create a dynamic block section, with parameters taken from PLIST.
11827 PLIST must contain a :name entry which is used as name of the block."
11828 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11829 (end-of-line 1)
11830 (newline))
11831 (let ((col (current-column))
11832 (name (plist-get plist :name)))
11833 (insert "#+BEGIN: " name)
11834 (while plist
11835 (if (eq (car plist) :name)
11836 (setq plist (cddr plist))
11837 (insert " " (prin1-to-string (pop plist)))))
11838 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11839 (beginning-of-line -2)))
11841 (defun org-prepare-dblock ()
11842 "Prepare dynamic block for refresh.
11843 This empties the block, puts the cursor at the insert position and returns
11844 the property list including an extra property :name with the block name."
11845 (unless (looking-at org-dblock-start-re)
11846 (user-error "Not at a dynamic block"))
11847 (let* ((begdel (1+ (match-end 0)))
11848 (name (org-no-properties (match-string 1)))
11849 (params (append (list :name name)
11850 (read (concat "(" (match-string 3) ")")))))
11851 (save-excursion
11852 (beginning-of-line 1)
11853 (skip-chars-forward " \t")
11854 (setq params (plist-put params :indentation-column (current-column))))
11855 (unless (re-search-forward org-dblock-end-re nil t)
11856 (error "Dynamic block not terminated"))
11857 (setq params
11858 (append params
11859 (list :content (buffer-substring
11860 begdel (match-beginning 0)))))
11861 (delete-region begdel (match-beginning 0))
11862 (goto-char begdel)
11863 (open-line 1)
11864 params))
11866 (defun org-map-dblocks (&optional command)
11867 "Apply COMMAND to all dynamic blocks in the current buffer.
11868 If COMMAND is not given, use `org-update-dblock'."
11869 (let ((cmd (or command 'org-update-dblock)))
11870 (save-excursion
11871 (goto-char (point-min))
11872 (while (re-search-forward org-dblock-start-re nil t)
11873 (goto-char (match-beginning 0))
11874 (save-excursion
11875 (condition-case nil
11876 (funcall cmd)
11877 (error (message "Error during update of dynamic block"))))
11878 (unless (re-search-forward org-dblock-end-re nil t)
11879 (error "Dynamic block not terminated"))))))
11881 (defun org-dblock-update (&optional arg)
11882 "User command for updating dynamic blocks.
11883 Update the dynamic block at point. With prefix ARG, update all dynamic
11884 blocks in the buffer."
11885 (interactive "P")
11886 (if arg
11887 (org-update-all-dblocks)
11888 (or (looking-at org-dblock-start-re)
11889 (org-beginning-of-dblock))
11890 (org-update-dblock)))
11892 (defun org-update-dblock ()
11893 "Update the dynamic block at point.
11894 This means to empty the block, parse for parameters and then call
11895 the correct writing function."
11896 (interactive)
11897 (save-window-excursion
11898 (let* ((pos (point))
11899 (line (org-current-line))
11900 (params (org-prepare-dblock))
11901 (name (plist-get params :name))
11902 (indent (plist-get params :indentation-column))
11903 (cmd (intern (concat "org-dblock-write:" name))))
11904 (message "Updating dynamic block `%s' at line %d..." name line)
11905 (funcall cmd params)
11906 (message "Updating dynamic block `%s' at line %d...done" name line)
11907 (goto-char pos)
11908 (when (and indent (> indent 0))
11909 (setq indent (make-string indent ?\ ))
11910 (save-excursion
11911 (org-beginning-of-dblock)
11912 (forward-line 1)
11913 (while (not (looking-at org-dblock-end-re))
11914 (insert indent)
11915 (beginning-of-line 2))
11916 (when (looking-at org-dblock-end-re)
11917 (and (looking-at "[ \t]+")
11918 (replace-match ""))
11919 (insert indent)))))))
11921 (defun org-beginning-of-dblock ()
11922 "Find the beginning of the dynamic block at point.
11923 Error if there is no such block at point."
11924 (let ((pos (point))
11925 beg)
11926 (end-of-line 1)
11927 (if (and (re-search-backward org-dblock-start-re nil t)
11928 (setq beg (match-beginning 0))
11929 (re-search-forward org-dblock-end-re nil t)
11930 (> (match-end 0) pos))
11931 (goto-char beg)
11932 (goto-char pos)
11933 (error "Not in a dynamic block"))))
11935 (defun org-update-all-dblocks ()
11936 "Update all dynamic blocks in the buffer.
11937 This function can be used in a hook."
11938 (interactive)
11939 (when (derived-mode-p 'org-mode)
11940 (org-map-dblocks 'org-update-dblock)))
11943 ;;;; Completion
11945 (declare-function org-export-backend-name "org-export" (cl-x))
11946 (declare-function org-export-backend-options "org-export" (cl-x))
11947 (defun org-get-export-keywords ()
11948 "Return a list of all currently understood export keywords.
11949 Export keywords include options, block names, attributes and
11950 keywords relative to each registered export back-end."
11951 (let (keywords)
11952 (dolist (backend
11953 (org-bound-and-true-p org-export--registered-backends)
11954 (delq nil keywords))
11955 ;; Back-end name (for keywords, like #+LATEX:)
11956 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11957 (dolist (option-entry (org-export-backend-options backend))
11958 ;; Back-end options.
11959 (push (nth 1 option-entry) keywords)))))
11961 (defconst org-options-keywords
11962 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11963 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11964 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11965 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11966 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11968 (defcustom org-structure-template-alist
11969 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11970 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11971 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11972 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11973 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11974 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11975 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11976 "<literal style=\"latex\">\n?\n</literal>")
11977 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11978 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11979 "<literal style=\"html\">\n?\n</literal>")
11980 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11981 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11982 ("A" "#+ASCII: " "")
11983 ("i" "#+INDEX: ?" "#+INDEX: ?")
11984 ("I" "#+INCLUDE: %file ?"
11985 "<include file=%file markup=\"?\">"))
11986 "Structure completion elements.
11987 This is a list of abbreviation keys and values. The value gets inserted
11988 if you type `<' followed by the key and then press the completion key,
11989 usually `M-TAB'. %file will be replaced by a file name after prompting
11990 for the file using completion. The cursor will be placed at the position
11991 of the `?` in the template.
11992 There are two templates for each key, the first uses the original Org syntax,
11993 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11994 the default when the /org-mtags.el/ module has been loaded. See also the
11995 variable `org-mtags-prefer-muse-templates'."
11996 :group 'org-completion
11997 :type '(repeat
11998 (list
11999 (string :tag "Key")
12000 (string :tag "Template")
12001 (string :tag "Muse Template"))))
12003 (defun org-try-structure-completion ()
12004 "Try to complete a structure template before point.
12005 This looks for strings like \"<e\" on an otherwise empty line and
12006 expands them."
12007 (let ((l (buffer-substring (point-at-bol) (point)))
12009 (when (and (looking-at "[ \t]*$")
12010 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12011 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12012 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12013 (match-beginning 1)) a)
12014 t)))
12016 (defun org-complete-expand-structure-template (start cell)
12017 "Expand a structure template."
12018 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12019 (rpl (nth (if musep 2 1) cell))
12020 (ind ""))
12021 (delete-region start (point))
12022 (when (string-match "\\`#\\+" rpl)
12023 (cond
12024 ((bolp))
12025 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12026 (setq ind (buffer-substring (point-at-bol) (point))))
12027 (t (newline))))
12028 (setq start (point))
12029 (if (string-match "%file" rpl)
12030 (setq rpl (replace-match
12031 (concat
12032 "\""
12033 (save-match-data
12034 (abbreviate-file-name (read-file-name "Include file: ")))
12035 "\"")
12036 t t rpl)))
12037 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12038 (concat "\n" ind)))
12039 (insert rpl)
12040 (if (re-search-backward "\\?" start t) (delete-char 1))))
12042 ;;;; TODO, DEADLINE, Comments
12044 (defun org-toggle-comment ()
12045 "Change the COMMENT state of an entry."
12046 (interactive)
12047 (save-excursion
12048 (org-back-to-heading)
12049 (let (case-fold-search)
12050 (cond
12051 ((looking-at (format org-heading-keyword-regexp-format
12052 org-comment-string))
12053 (goto-char (match-end 1))
12054 (looking-at (concat " +" org-comment-string))
12055 (replace-match "" t t)
12056 (when (eolp) (insert " ")))
12057 ((looking-at org-outline-regexp)
12058 (goto-char (match-end 0))
12059 (insert org-comment-string " "))))))
12061 (defvar org-last-todo-state-is-todo nil
12062 "This is non-nil when the last TODO state change led to a TODO state.
12063 If the last change removed the TODO tag or switched to DONE, then
12064 this is nil.")
12066 (defvar org-setting-tags nil) ; dynamically skipped
12068 (defvar org-todo-setup-filter-hook nil
12069 "Hook for functions that pre-filter todo specs.
12070 Each function takes a todo spec and returns either nil or the spec
12071 transformed into canonical form." )
12073 (defvar org-todo-get-default-hook nil
12074 "Hook for functions that get a default item for todo.
12075 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12076 nil or a string to be used for the todo mark." )
12078 (defvar org-agenda-headline-snapshot-before-repeat)
12080 (defun org-current-effective-time ()
12081 "Return current time adjusted for `org-extend-today-until' variable."
12082 (let* ((ct (org-current-time))
12083 (dct (decode-time ct))
12084 (ct1
12085 (cond
12086 (org-use-last-clock-out-time-as-effective-time
12087 (or (org-clock-get-last-clock-out-time) ct))
12088 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12089 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12090 (t ct))))
12091 ct1))
12093 (defun org-todo-yesterday (&optional arg)
12094 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12095 (interactive "P")
12096 (if (eq major-mode 'org-agenda-mode)
12097 (apply 'org-agenda-todo-yesterday arg)
12098 (let* ((hour (third (decode-time
12099 (org-current-time))))
12100 (org-extend-today-until (1+ hour)))
12101 (org-todo arg))))
12103 (defvar org-block-entry-blocking ""
12104 "First entry preventing the TODO state change.")
12106 (defun org-todo (&optional arg)
12107 "Change the TODO state of an item.
12108 The state of an item is given by a keyword at the start of the heading,
12109 like
12110 *** TODO Write paper
12111 *** DONE Call mom
12113 The different keywords are specified in the variable `org-todo-keywords'.
12114 By default the available states are \"TODO\" and \"DONE\".
12115 So for this example: when the item starts with TODO, it is changed to DONE.
12116 When it starts with DONE, the DONE is removed. And when neither TODO nor
12117 DONE are present, add TODO at the beginning of the heading.
12119 With \\[universal-argument] prefix arg, use completion to determine the new \
12120 state.
12121 With numeric prefix arg, switch to that state.
12122 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12123 keywords (nextset).
12124 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12125 With a numeric prefix arg of 0, inhibit note taking for the change.
12127 For calling through lisp, arg is also interpreted in the following way:
12128 'none -> empty state
12129 \"\"(empty string) -> switch to empty state
12130 'done -> switch to DONE
12131 'nextset -> switch to the next set of keywords
12132 'previousset -> switch to the previous set of keywords
12133 \"WAITING\" -> switch to the specified keyword, but only if it
12134 really is a member of `org-todo-keywords'."
12135 (interactive "P")
12136 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12137 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12138 'region-start-level 'region))
12139 org-loop-over-headlines-in-active-region)
12140 (org-map-entries
12141 `(org-todo ,arg)
12142 org-loop-over-headlines-in-active-region
12143 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12144 (if (equal arg '(16)) (setq arg 'nextset))
12145 (let ((org-blocker-hook org-blocker-hook)
12146 commentp
12147 case-fold-search)
12148 (when (equal arg '(64))
12149 (setq arg nil org-blocker-hook nil))
12150 (when (and org-blocker-hook
12151 (or org-inhibit-blocking
12152 (org-entry-get nil "NOBLOCKING")))
12153 (setq org-blocker-hook nil))
12154 (save-excursion
12155 (catch 'exit
12156 (org-back-to-heading t)
12157 (when (looking-at (concat "^\\*+ " org-comment-string))
12158 (org-toggle-comment)
12159 (setq commentp t))
12160 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12161 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12162 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12163 (let* ((match-data (match-data))
12164 (startpos (point-at-bol))
12165 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12166 (org-log-done org-log-done)
12167 (org-log-repeat org-log-repeat)
12168 (org-todo-log-states org-todo-log-states)
12169 (org-inhibit-logging
12170 (if (equal arg 0)
12171 (progn (setq arg nil) 'note) org-inhibit-logging))
12172 (this (match-string 1))
12173 (hl-pos (match-beginning 0))
12174 (head (org-get-todo-sequence-head this))
12175 (ass (assoc head org-todo-kwd-alist))
12176 (interpret (nth 1 ass))
12177 (done-word (nth 3 ass))
12178 (final-done-word (nth 4 ass))
12179 (org-last-state (or this ""))
12180 (completion-ignore-case t)
12181 (member (member this org-todo-keywords-1))
12182 (tail (cdr member))
12183 (org-state (cond
12184 ((and org-todo-key-trigger
12185 (or (and (equal arg '(4))
12186 (eq org-use-fast-todo-selection 'prefix))
12187 (and (not arg) org-use-fast-todo-selection
12188 (not (eq org-use-fast-todo-selection
12189 'prefix)))))
12190 ;; Use fast selection
12191 (org-fast-todo-selection))
12192 ((and (equal arg '(4))
12193 (or (not org-use-fast-todo-selection)
12194 (not org-todo-key-trigger)))
12195 ;; Read a state with completion
12196 (org-icompleting-read
12197 "State: " (mapcar 'list org-todo-keywords-1)
12198 nil t))
12199 ((eq arg 'right)
12200 (if this
12201 (if tail (car tail) nil)
12202 (car org-todo-keywords-1)))
12203 ((eq arg 'left)
12204 (if (equal member org-todo-keywords-1)
12206 (if this
12207 (nth (- (length org-todo-keywords-1)
12208 (length tail) 2)
12209 org-todo-keywords-1)
12210 (org-last org-todo-keywords-1))))
12211 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12212 (setq arg nil))) ; hack to fall back to cycling
12213 (arg
12214 ;; user or caller requests a specific state
12215 (cond
12216 ((equal arg "") nil)
12217 ((eq arg 'none) nil)
12218 ((eq arg 'done) (or done-word (car org-done-keywords)))
12219 ((eq arg 'nextset)
12220 (or (car (cdr (member head org-todo-heads)))
12221 (car org-todo-heads)))
12222 ((eq arg 'previousset)
12223 (let ((org-todo-heads (reverse org-todo-heads)))
12224 (or (car (cdr (member head org-todo-heads)))
12225 (car org-todo-heads))))
12226 ((car (member arg org-todo-keywords-1)))
12227 ((stringp arg)
12228 (user-error "State `%s' not valid in this file" arg))
12229 ((nth (1- (prefix-numeric-value arg))
12230 org-todo-keywords-1))))
12231 ((null member) (or head (car org-todo-keywords-1)))
12232 ((equal this final-done-word) nil) ;; -> make empty
12233 ((null tail) nil) ;; -> first entry
12234 ((memq interpret '(type priority))
12235 (if (eq this-command last-command)
12236 (car tail)
12237 (if (> (length tail) 0)
12238 (or done-word (car org-done-keywords))
12239 nil)))
12241 (car tail))))
12242 (org-state (or
12243 (run-hook-with-args-until-success
12244 'org-todo-get-default-hook org-state org-last-state)
12245 org-state))
12246 (next (if org-state (concat " " org-state " ") " "))
12247 (change-plist (list :type 'todo-state-change :from this :to org-state
12248 :position startpos))
12249 dolog now-done-p)
12250 (when org-blocker-hook
12251 (setq org-last-todo-state-is-todo
12252 (not (member this org-done-keywords)))
12253 (unless (save-excursion
12254 (save-match-data
12255 (org-with-wide-buffer
12256 (run-hook-with-args-until-failure
12257 'org-blocker-hook change-plist))))
12258 (if (org-called-interactively-p 'interactive)
12259 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12260 this org-state org-block-entry-blocking)
12261 ;; fail silently
12262 (message "TODO state change from %s to %s blocked (by \"%s\")"
12263 this org-state org-block-entry-blocking)
12264 (throw 'exit nil))))
12265 (store-match-data match-data)
12266 (replace-match next t t)
12267 (unless (pos-visible-in-window-p hl-pos)
12268 (message "TODO state changed to %s" (org-trim next)))
12269 (unless head
12270 (setq head (org-get-todo-sequence-head org-state)
12271 ass (assoc head org-todo-kwd-alist)
12272 interpret (nth 1 ass)
12273 done-word (nth 3 ass)
12274 final-done-word (nth 4 ass)))
12275 (when (memq arg '(nextset previousset))
12276 (message "Keyword-Set %d/%d: %s"
12277 (- (length org-todo-sets) -1
12278 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12279 (length org-todo-sets)
12280 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12281 (setq org-last-todo-state-is-todo
12282 (not (member org-state org-done-keywords)))
12283 (setq now-done-p (and (member org-state org-done-keywords)
12284 (not (member this org-done-keywords))))
12285 (and logging (org-local-logging logging))
12286 (when (and (or org-todo-log-states org-log-done)
12287 (not (eq org-inhibit-logging t))
12288 (not (memq arg '(nextset previousset))))
12289 ;; we need to look at recording a time and note
12290 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12291 (nth 2 (assoc this org-todo-log-states))))
12292 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12293 (setq dolog 'time))
12294 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12295 (and org-state
12296 (member org-state org-not-done-keywords)
12297 (not (member this org-not-done-keywords))))
12298 ;; This is now a todo state and was not one before
12299 ;; If there was a CLOSED time stamp, get rid of it.
12300 (org-add-planning-info nil nil 'closed))
12301 (when (and now-done-p org-log-done)
12302 ;; It is now done, and it was not done before
12303 (org-add-planning-info 'closed (org-current-effective-time))
12304 (if (and (not dolog) (eq 'note org-log-done))
12305 (org-add-log-setup 'done org-state this 'findpos 'note)))
12306 (when (and org-state dolog)
12307 ;; This is a non-nil state, and we need to log it
12308 (org-add-log-setup 'state org-state this 'findpos dolog)))
12309 ;; Fixup tag positioning
12310 (org-todo-trigger-tag-changes org-state)
12311 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12312 (when org-provide-todo-statistics
12313 (org-update-parent-todo-statistics))
12314 (run-hooks 'org-after-todo-state-change-hook)
12315 (if (and arg (not (member org-state org-done-keywords)))
12316 (setq head (org-get-todo-sequence-head org-state)))
12317 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12318 ;; Do we need to trigger a repeat?
12319 (when now-done-p
12320 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12321 ;; This is for the agenda, take a snapshot of the headline.
12322 (save-match-data
12323 (setq org-agenda-headline-snapshot-before-repeat
12324 (org-get-heading))))
12325 (org-auto-repeat-maybe org-state))
12326 ;; Fixup cursor location if close to the keyword
12327 (if (and (outline-on-heading-p)
12328 (not (bolp))
12329 (save-excursion (beginning-of-line 1)
12330 (looking-at org-todo-line-regexp))
12331 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12332 (progn
12333 (goto-char (or (match-end 2) (match-end 1)))
12334 (and (looking-at " ") (just-one-space))))
12335 (when org-trigger-hook
12336 (save-excursion
12337 (run-hook-with-args 'org-trigger-hook change-plist)))
12338 (when commentp (org-toggle-comment))))))))
12340 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12341 "Block turning an entry into a TODO, using the hierarchy.
12342 This checks whether the current task should be blocked from state
12343 changes. Such blocking occurs when:
12345 1. The task has children which are not all in a completed state.
12347 2. A task has a parent with the property :ORDERED:, and there
12348 are siblings prior to the current task with incomplete
12349 status.
12351 3. The parent of the task is blocked because it has siblings that should
12352 be done first, or is child of a block grandparent TODO entry."
12354 (if (not org-enforce-todo-dependencies)
12355 t ; if locally turned off don't block
12356 (catch 'dont-block
12357 ;; If this is not a todo state change, or if this entry is already DONE,
12358 ;; do not block
12359 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12360 (member (plist-get change-plist :from)
12361 (cons 'done org-done-keywords))
12362 (member (plist-get change-plist :to)
12363 (cons 'todo org-not-done-keywords))
12364 (not (plist-get change-plist :to)))
12365 (throw 'dont-block t))
12366 ;; If this task has children, and any are undone, it's blocked
12367 (save-excursion
12368 (org-back-to-heading t)
12369 (let ((this-level (funcall outline-level)))
12370 (outline-next-heading)
12371 (let ((child-level (funcall outline-level)))
12372 (while (and (not (eobp))
12373 (> child-level this-level))
12374 ;; this todo has children, check whether they are all
12375 ;; completed
12376 (if (and (not (org-entry-is-done-p))
12377 (org-entry-is-todo-p))
12378 (progn (setq org-block-entry-blocking (org-get-heading))
12379 (throw 'dont-block nil)))
12380 (outline-next-heading)
12381 (setq child-level (funcall outline-level))))))
12382 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12383 ;; any previous siblings are undone, it's blocked
12384 (save-excursion
12385 (org-back-to-heading t)
12386 (let* ((pos (point))
12387 (parent-pos (and (org-up-heading-safe) (point))))
12388 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12389 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12390 (forward-line 1)
12391 (re-search-forward org-not-done-heading-regexp pos t))
12392 (setq org-block-entry-blocking (match-string 0))
12393 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12394 ;; Search further up the hierarchy, to see if an ancestor is blocked
12395 (while t
12396 (goto-char parent-pos)
12397 (if (not (looking-at org-not-done-heading-regexp))
12398 (throw 'dont-block t)) ; do not block, parent is not a TODO
12399 (setq pos (point))
12400 (setq parent-pos (and (org-up-heading-safe) (point)))
12401 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12402 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12403 (forward-line 1)
12404 (re-search-forward org-not-done-heading-regexp pos t)
12405 (setq org-block-entry-blocking (org-get-heading)))
12406 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12408 (defcustom org-track-ordered-property-with-tag nil
12409 "Should the ORDERED property also be shown as a tag?
12410 The ORDERED property decides if an entry should require subtasks to be
12411 completed in sequence. Since a property is not very visible, setting
12412 this option means that toggling the ORDERED property with the command
12413 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12414 not relevant for the behavior, but it makes things more visible.
12416 Note that toggling the tag with tags commands will not change the property
12417 and therefore not influence behavior!
12419 This can be t, meaning the tag ORDERED should be used, It can also be a
12420 string to select a different tag for this task."
12421 :group 'org-todo
12422 :type '(choice
12423 (const :tag "No tracking" nil)
12424 (const :tag "Track with ORDERED tag" t)
12425 (string :tag "Use other tag")))
12427 (defun org-toggle-ordered-property ()
12428 "Toggle the ORDERED property of the current entry.
12429 For better visibility, you can track the value of this property with a tag.
12430 See variable `org-track-ordered-property-with-tag'."
12431 (interactive)
12432 (let* ((t1 org-track-ordered-property-with-tag)
12433 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12434 (save-excursion
12435 (org-back-to-heading)
12436 (if (org-entry-get nil "ORDERED")
12437 (progn
12438 (org-delete-property "ORDERED")
12439 (and tag (org-toggle-tag tag 'off))
12440 (message "Subtasks can be completed in arbitrary order"))
12441 (org-entry-put nil "ORDERED" "t")
12442 (and tag (org-toggle-tag tag 'on))
12443 (message "Subtasks must be completed in sequence")))))
12445 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12446 (defun org-block-todo-from-checkboxes (change-plist)
12447 "Block turning an entry into a TODO, using checkboxes.
12448 This checks whether the current task should be blocked from state
12449 changes because there are unchecked boxes in this entry."
12450 (if (not org-enforce-todo-checkbox-dependencies)
12451 t ; if locally turned off don't block
12452 (catch 'dont-block
12453 ;; If this is not a todo state change, or if this entry is already DONE,
12454 ;; do not block
12455 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12456 (member (plist-get change-plist :from)
12457 (cons 'done org-done-keywords))
12458 (member (plist-get change-plist :to)
12459 (cons 'todo org-not-done-keywords))
12460 (not (plist-get change-plist :to)))
12461 (throw 'dont-block t))
12462 ;; If this task has checkboxes that are not checked, it's blocked
12463 (save-excursion
12464 (org-back-to-heading t)
12465 (let ((beg (point)) end)
12466 (outline-next-heading)
12467 (setq end (point))
12468 (goto-char beg)
12469 (if (org-list-search-forward
12470 (concat (org-item-beginning-re)
12471 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12472 "\\[[- ]\\]")
12473 end t)
12474 (progn
12475 (if (boundp 'org-blocked-by-checkboxes)
12476 (setq org-blocked-by-checkboxes t))
12477 (throw 'dont-block nil)))))
12478 t))) ; do not block
12480 (defun org-entry-blocked-p ()
12481 "Is the current entry blocked?"
12482 (org-with-silent-modifications
12483 (if (org-entry-get nil "NOBLOCKING")
12484 nil ;; Never block this entry
12485 (not (run-hook-with-args-until-failure
12486 'org-blocker-hook
12487 (list :type 'todo-state-change
12488 :position (point)
12489 :from 'todo
12490 :to 'done))))))
12492 (defun org-update-statistics-cookies (all)
12493 "Update the statistics cookie, either from TODO or from checkboxes.
12494 This should be called with the cursor in a line with a statistics cookie."
12495 (interactive "P")
12496 (if all
12497 (progn
12498 (org-update-checkbox-count 'all)
12499 (org-map-entries 'org-update-parent-todo-statistics))
12500 (if (not (org-at-heading-p))
12501 (org-update-checkbox-count)
12502 (let ((pos (point-marker))
12503 end l1 l2)
12504 (ignore-errors (org-back-to-heading t))
12505 (if (not (org-at-heading-p))
12506 (org-update-checkbox-count)
12507 (setq l1 (org-outline-level))
12508 (setq end (save-excursion
12509 (outline-next-heading)
12510 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12511 (point)))
12512 (if (and (save-excursion
12513 (re-search-forward
12514 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12515 (not (save-excursion (re-search-forward
12516 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12517 (org-update-checkbox-count)
12518 (if (and l2 (> l2 l1))
12519 (progn
12520 (goto-char end)
12521 (org-update-parent-todo-statistics))
12522 (goto-char pos)
12523 (beginning-of-line 1)
12524 (while (re-search-forward
12525 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12526 (point-at-eol) t)
12527 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12528 (goto-char pos)
12529 (move-marker pos nil)))))
12531 (defvar org-entry-property-inherited-from) ;; defined below
12532 (defun org-update-parent-todo-statistics ()
12533 "Update any statistics cookie in the parent of the current headline.
12534 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12535 the entire subtree and this will travel up the hierarchy and update
12536 statistics everywhere."
12537 (let* ((prop (save-excursion (org-up-heading-safe)
12538 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12539 (recursive (or (not org-hierarchical-todo-statistics)
12540 (and prop (string-match "\\<recursive\\>" prop))))
12541 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12543 (first t)
12544 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12545 level ltoggle l1 new ndel
12546 (cnt-all 0) (cnt-done 0) is-percent kwd
12547 checkbox-beg ov ovs ove cookie-present)
12548 (catch 'exit
12549 (save-excursion
12550 (beginning-of-line 1)
12551 (setq ltoggle (funcall outline-level))
12552 ;; Three situations are to consider:
12554 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12555 ;; to the top-level ancestor on the headline;
12557 ;; 2. If parent has "recursive" property, repeat up to the
12558 ;; headline setting that property, taking inheritance into
12559 ;; account;
12561 ;; 3. Else, move up to direct parent and proceed only once.
12562 (while (and (setq level (org-up-heading-safe))
12563 (or recursive first)
12564 (>= (point) lim))
12565 (setq first nil cookie-present nil)
12566 (unless (and level
12567 (not (string-match
12568 "\\<checkbox\\>"
12569 (downcase (or (org-entry-get nil "COOKIE_DATA")
12570 "")))))
12571 (throw 'exit nil))
12572 (while (re-search-forward box-re (point-at-eol) t)
12573 (setq cnt-all 0 cnt-done 0 cookie-present t)
12574 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12575 (save-match-data
12576 (unless (outline-next-heading) (throw 'exit nil))
12577 (while (and (looking-at org-complex-heading-regexp)
12578 (> (setq l1 (length (match-string 1))) level))
12579 (setq kwd (and (or recursive (= l1 ltoggle))
12580 (match-string 2)))
12581 (if (or (eq org-provide-todo-statistics 'all-headlines)
12582 (and (listp org-provide-todo-statistics)
12583 (or (member kwd org-provide-todo-statistics)
12584 (member kwd org-done-keywords))))
12585 (setq cnt-all (1+ cnt-all))
12586 (if (eq org-provide-todo-statistics t)
12587 (and kwd (setq cnt-all (1+ cnt-all)))))
12588 (and (member kwd org-done-keywords)
12589 (setq cnt-done (1+ cnt-done)))
12590 (outline-next-heading)))
12591 (setq new
12592 (if is-percent
12593 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12594 (format "[%d/%d]" cnt-done cnt-all))
12595 ndel (- (match-end 0) checkbox-beg))
12596 ;; handle overlays when updating cookie from column view
12597 (when (setq ov (car (overlays-at checkbox-beg)))
12598 (setq ovs (overlay-start ov) ove (overlay-end ov))
12599 (delete-overlay ov))
12600 (goto-char checkbox-beg)
12601 (insert new)
12602 (delete-region (point) (+ (point) ndel))
12603 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12604 (when ov (move-overlay ov ovs ove)))
12605 (when cookie-present
12606 (run-hook-with-args 'org-after-todo-statistics-hook
12607 cnt-done (- cnt-all cnt-done))))))
12608 (run-hooks 'org-todo-statistics-hook)))
12610 (defvar org-after-todo-statistics-hook nil
12611 "Hook that is called after a TODO statistics cookie has been updated.
12612 Each function is called with two arguments: the number of not-done entries
12613 and the number of done entries.
12615 For example, the following function, when added to this hook, will switch
12616 an entry to DONE when all children are done, and back to TODO when new
12617 entries are set to a TODO status. Note that this hook is only called
12618 when there is a statistics cookie in the headline!
12620 (defun org-summary-todo (n-done n-not-done)
12621 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12622 (let (org-log-done org-log-states) ; turn off logging
12623 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12626 (defvar org-todo-statistics-hook nil
12627 "Hook that is run whenever Org thinks TODO statistics should be updated.
12628 This hook runs even if there is no statistics cookie present, in which case
12629 `org-after-todo-statistics-hook' would not run.")
12631 (defun org-todo-trigger-tag-changes (state)
12632 "Apply the changes defined in `org-todo-state-tags-triggers'."
12633 (let ((l org-todo-state-tags-triggers)
12634 changes)
12635 (when (or (not state) (equal state ""))
12636 (setq changes (append changes (cdr (assoc "" l)))))
12637 (when (and (stringp state) (> (length state) 0))
12638 (setq changes (append changes (cdr (assoc state l)))))
12639 (when (member state org-not-done-keywords)
12640 (setq changes (append changes (cdr (assoc 'todo l)))))
12641 (when (member state org-done-keywords)
12642 (setq changes (append changes (cdr (assoc 'done l)))))
12643 (dolist (c changes)
12644 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12646 (defun org-local-logging (value)
12647 "Get logging settings from a property VALUE."
12648 (let* (words w a)
12649 ;; directly set the variables, they are already local.
12650 (setq org-log-done nil
12651 org-log-repeat nil
12652 org-todo-log-states nil)
12653 (setq words (org-split-string value))
12654 (while (setq w (pop words))
12655 (cond
12656 ((setq a (assoc w org-startup-options))
12657 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12658 (set (nth 1 a) (nth 2 a))))
12659 ((setq a (org-extract-log-state-settings w))
12660 (and (member (car a) org-todo-keywords-1)
12661 (push a org-todo-log-states)))))))
12663 (defun org-get-todo-sequence-head (kwd)
12664 "Return the head of the TODO sequence to which KWD belongs.
12665 If KWD is not set, check if there is a text property remembering the
12666 right sequence."
12667 (let (p)
12668 (cond
12669 ((not kwd)
12670 (or (get-text-property (point-at-bol) 'org-todo-head)
12671 (progn
12672 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12673 nil (point-at-eol)))
12674 (get-text-property p 'org-todo-head))))
12675 ((not (member kwd org-todo-keywords-1))
12676 (car org-todo-keywords-1))
12677 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12679 (defun org-fast-todo-selection ()
12680 "Fast TODO keyword selection with single keys.
12681 Returns the new TODO keyword, or nil if no state change should occur."
12682 (let* ((fulltable org-todo-key-alist)
12683 (done-keywords org-done-keywords) ;; needed for the faces.
12684 (maxlen (apply 'max (mapcar
12685 (lambda (x)
12686 (if (stringp (car x)) (string-width (car x)) 0))
12687 fulltable)))
12688 (expert nil)
12689 (fwidth (+ maxlen 3 1 3))
12690 (ncol (/ (- (window-width) 4) fwidth))
12691 tg cnt e c tbl
12692 groups ingroup)
12693 (save-excursion
12694 (save-window-excursion
12695 (if expert
12696 (set-buffer (get-buffer-create " *Org todo*"))
12697 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12698 (erase-buffer)
12699 (org-set-local 'org-done-keywords done-keywords)
12700 (setq tbl fulltable cnt 0)
12701 (while (setq e (pop tbl))
12702 (cond
12703 ((equal e '(:startgroup))
12704 (push '() groups) (setq ingroup t)
12705 (when (not (= cnt 0))
12706 (setq cnt 0)
12707 (insert "\n"))
12708 (insert "{ "))
12709 ((equal e '(:endgroup))
12710 (setq ingroup nil cnt 0)
12711 (insert "}\n"))
12712 ((equal e '(:newline))
12713 (when (not (= cnt 0))
12714 (setq cnt 0)
12715 (insert "\n")
12716 (setq e (car tbl))
12717 (while (equal (car tbl) '(:newline))
12718 (insert "\n")
12719 (setq tbl (cdr tbl)))))
12721 (setq tg (car e) c (cdr e))
12722 (if ingroup (push tg (car groups)))
12723 (setq tg (org-add-props tg nil 'face
12724 (org-get-todo-face tg)))
12725 (if (and (= cnt 0) (not ingroup)) (insert " "))
12726 (insert "[" c "] " tg (make-string
12727 (- fwidth 4 (length tg)) ?\ ))
12728 (when (= (setq cnt (1+ cnt)) ncol)
12729 (insert "\n")
12730 (if ingroup (insert " "))
12731 (setq cnt 0)))))
12732 (insert "\n")
12733 (goto-char (point-min))
12734 (if (not expert) (org-fit-window-to-buffer))
12735 (message "[a-z..]:Set [SPC]:clear")
12736 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12737 (cond
12738 ((or (= c ?\C-g)
12739 (and (= c ?q) (not (rassoc c fulltable))))
12740 (setq quit-flag t))
12741 ((= c ?\ ) nil)
12742 ((setq e (rassoc c fulltable) tg (car e))
12744 (t (setq quit-flag t)))))))
12746 (defun org-entry-is-todo-p ()
12747 (member (org-get-todo-state) org-not-done-keywords))
12749 (defun org-entry-is-done-p ()
12750 (member (org-get-todo-state) org-done-keywords))
12752 (defun org-get-todo-state ()
12753 "Return the TODO keyword of the current subtree."
12754 (save-excursion
12755 (org-back-to-heading t)
12756 (and (looking-at org-todo-line-regexp)
12757 (match-end 2)
12758 (match-string 2))))
12760 (defun org-at-date-range-p (&optional inactive-ok)
12761 "Is the cursor inside a date range?"
12762 (interactive)
12763 (save-excursion
12764 (catch 'exit
12765 (let ((pos (point)))
12766 (skip-chars-backward "^[<\r\n")
12767 (skip-chars-backward "<[")
12768 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12769 (>= (match-end 0) pos)
12770 (throw 'exit t))
12771 (skip-chars-backward "^<[\r\n")
12772 (skip-chars-backward "<[")
12773 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12774 (>= (match-end 0) pos)
12775 (throw 'exit t)))
12776 nil)))
12778 (defun org-get-repeat (&optional tagline)
12779 "Check if there is a deadline/schedule with repeater in this entry."
12780 (save-match-data
12781 (save-excursion
12782 (org-back-to-heading t)
12783 (and (re-search-forward (if tagline
12784 (concat tagline "\\s-*" org-repeat-re)
12785 org-repeat-re)
12786 (org-entry-end-position) t)
12787 (match-string-no-properties 1)))))
12789 (defvar org-last-changed-timestamp)
12790 (defvar org-last-inserted-timestamp)
12791 (defvar org-log-post-message)
12792 (defvar org-log-note-purpose)
12793 (defvar org-log-note-how)
12794 (defvar org-log-note-extra)
12795 (defun org-auto-repeat-maybe (done-word)
12796 "Check if the current headline contains a repeated deadline/schedule.
12797 If yes, set TODO state back to what it was and change the base date
12798 of repeating deadline/scheduled time stamps to new date.
12799 This function is run automatically after each state change to a DONE state."
12800 ;; last-state is dynamically scoped into this function
12801 (let* ((repeat (org-get-repeat))
12802 (aa (assoc org-last-state org-todo-kwd-alist))
12803 (interpret (nth 1 aa))
12804 (head (nth 2 aa))
12805 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12806 (msg "Entry repeats: ")
12807 (org-log-done nil)
12808 (org-todo-log-states nil)
12809 re type n what ts time to-state)
12810 (when repeat
12811 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12812 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12813 org-todo-repeat-to-state))
12814 (unless (and to-state (member to-state org-todo-keywords-1))
12815 (setq to-state (if (eq interpret 'type) org-last-state head)))
12816 (org-todo to-state)
12817 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12818 (org-entry-put nil "LAST_REPEAT" (format-time-string
12819 (org-time-stamp-format t t))))
12820 (when org-log-repeat
12821 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12822 (memq 'org-add-log-note post-command-hook))
12823 ;; OK, we are already setup for some record
12824 (if (eq org-log-repeat 'note)
12825 ;; make sure we take a note, not only a time stamp
12826 (setq org-log-note-how 'note))
12827 ;; Set up for taking a record
12828 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12829 org-last-state
12830 'findpos org-log-repeat)))
12831 (org-back-to-heading t)
12832 (org-add-planning-info nil nil 'closed)
12833 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12834 org-deadline-time-regexp "\\)\\|\\("
12835 org-ts-regexp "\\)"))
12836 (while (re-search-forward
12837 re (save-excursion (outline-next-heading) (point)) t)
12838 (setq type (if (match-end 1) org-scheduled-string
12839 (if (match-end 3) org-deadline-string "Plain:"))
12840 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12841 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12842 (setq n (string-to-number (match-string 2 ts))
12843 what (match-string 3 ts))
12844 (if (equal what "w") (setq n (* n 7) what "d"))
12845 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12846 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12847 ;; Preparation, see if we need to modify the start date for the change
12848 (when (match-end 1)
12849 (setq time (save-match-data (org-time-string-to-time ts)))
12850 (cond
12851 ((equal (match-string 1 ts) ".")
12852 ;; Shift starting date to today
12853 (org-timestamp-change
12854 (- (org-today) (time-to-days time))
12855 'day))
12856 ((equal (match-string 1 ts) "+")
12857 (let ((nshiftmax 10) (nshift 0))
12858 (while (or (= nshift 0)
12859 (<= (time-to-days time)
12860 (time-to-days (current-time))))
12861 (when (= (incf nshift) nshiftmax)
12862 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12863 (error "Abort")))
12864 (org-timestamp-change n (cdr (assoc what whata)))
12865 (org-at-timestamp-p t)
12866 (setq ts (match-string 1))
12867 (setq time (save-match-data (org-time-string-to-time ts)))))
12868 (org-timestamp-change (- n) (cdr (assoc what whata)))
12869 ;; rematch, so that we have everything in place for the real shift
12870 (org-at-timestamp-p t)
12871 (setq ts (match-string 1))
12872 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12873 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12874 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12875 (setq org-log-post-message msg)
12876 (message "%s" msg))))
12878 (defun org-show-todo-tree (arg)
12879 "Make a compact tree which shows all headlines marked with TODO.
12880 The tree will show the lines where the regexp matches, and all higher
12881 headlines above the match.
12882 With a \\[universal-argument] prefix, prompt for a regexp to match.
12883 With a numeric prefix N, construct a sparse tree for the Nth element
12884 of `org-todo-keywords-1'."
12885 (interactive "P")
12886 (let ((case-fold-search nil)
12887 (kwd-re
12888 (cond ((null arg) org-not-done-regexp)
12889 ((equal arg '(4))
12890 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12891 (mapcar 'list org-todo-keywords-1))))
12892 (concat "\\("
12893 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12894 "\\)\\>")))
12895 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12896 (regexp-quote (nth (1- (prefix-numeric-value arg))
12897 org-todo-keywords-1)))
12898 (t (user-error "Invalid prefix argument: %s" arg)))))
12899 (message "%d TODO entries found"
12900 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12902 (defun org-deadline (arg &optional time)
12903 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12904 With one universal prefix argument, remove any deadline from the item.
12905 With two universal prefix arguments, prompt for a warning delay.
12906 With argument TIME, set the deadline at the corresponding date. TIME
12907 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12908 (interactive "P")
12909 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12910 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12911 'region-start-level 'region))
12912 org-loop-over-headlines-in-active-region)
12913 (org-map-entries
12914 `(org-deadline ',arg ,time)
12915 org-loop-over-headlines-in-active-region
12916 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12917 (let* ((old-date (org-entry-get nil "DEADLINE"))
12918 (old-date-time (if old-date (org-time-string-to-time old-date)))
12919 (repeater (and old-date
12920 (string-match
12921 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12922 old-date)
12923 (match-string 1 old-date))))
12924 (cond
12925 ((equal arg '(4))
12926 (when (and old-date org-log-redeadline)
12927 (org-add-log-setup 'deldeadline nil old-date 'findpos
12928 org-log-redeadline))
12929 (org-remove-timestamp-with-keyword org-deadline-string)
12930 (message "Item no longer has a deadline."))
12931 ((equal arg '(16))
12932 (save-excursion
12933 (if (re-search-forward
12934 org-deadline-time-regexp
12935 (save-excursion (outline-next-heading) (point)) t)
12936 (let* ((rpl0 (match-string 1))
12937 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12938 (replace-match
12939 (concat org-deadline-string
12940 " <" rpl
12941 (format " -%dd"
12942 (abs
12943 (- (time-to-days
12944 (save-match-data
12945 (org-read-date nil t nil "Warn starting from" old-date-time)))
12946 (time-to-days old-date-time))))
12947 ">") t t))
12948 (user-error "No deadline information to update"))))
12950 (org-add-planning-info 'deadline time 'closed)
12951 (when (and old-date org-log-redeadline
12952 (not (equal old-date
12953 (substring org-last-inserted-timestamp 1 -1))))
12954 (org-add-log-setup 'redeadline nil old-date 'findpos
12955 org-log-redeadline))
12956 (when repeater
12957 (save-excursion
12958 (org-back-to-heading t)
12959 (when (re-search-forward (concat org-deadline-string " "
12960 org-last-inserted-timestamp)
12961 (save-excursion
12962 (outline-next-heading) (point)) t)
12963 (goto-char (1- (match-end 0)))
12964 (insert " " repeater)
12965 (setq org-last-inserted-timestamp
12966 (concat (substring org-last-inserted-timestamp 0 -1)
12967 " " repeater
12968 (substring org-last-inserted-timestamp -1))))))
12969 (message "Deadline on %s" org-last-inserted-timestamp))))))
12971 (defun org-schedule (arg &optional time)
12972 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12973 With one universal prefix argument, remove any scheduling date from the item.
12974 With two universal prefix arguments, prompt for a delay cookie.
12975 With argument TIME, scheduled at the corresponding date. TIME can
12976 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12977 (interactive "P")
12978 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12979 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12980 'region-start-level 'region))
12981 org-loop-over-headlines-in-active-region)
12982 (org-map-entries
12983 `(org-schedule ',arg ,time)
12984 org-loop-over-headlines-in-active-region
12985 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12986 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12987 (old-date-time (if old-date (org-time-string-to-time old-date)))
12988 (repeater (and old-date
12989 (string-match
12990 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12991 old-date)
12992 (match-string 1 old-date))))
12993 (cond
12994 ((equal arg '(4))
12995 (progn
12996 (when (and old-date org-log-reschedule)
12997 (org-add-log-setup 'delschedule nil old-date 'findpos
12998 org-log-reschedule))
12999 (org-remove-timestamp-with-keyword org-scheduled-string)
13000 (message "Item is no longer scheduled.")))
13001 ((equal arg '(16))
13002 (save-excursion
13003 (if (re-search-forward
13004 org-scheduled-time-regexp
13005 (save-excursion (outline-next-heading) (point)) t)
13006 (let* ((rpl0 (match-string 1))
13007 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13008 (replace-match
13009 (concat org-scheduled-string
13010 " <" rpl
13011 (format " -%dd"
13012 (abs
13013 (- (time-to-days
13014 (save-match-data
13015 (org-read-date nil t nil "Delay until" old-date-time)))
13016 (time-to-days old-date-time))))
13017 ">") t t))
13018 (user-error "No scheduled information to update"))))
13020 (org-add-planning-info 'scheduled time 'closed)
13021 (when (and old-date org-log-reschedule
13022 (not (equal old-date
13023 (substring org-last-inserted-timestamp 1 -1))))
13024 (org-add-log-setup 'reschedule nil old-date 'findpos
13025 org-log-reschedule))
13026 (when repeater
13027 (save-excursion
13028 (org-back-to-heading t)
13029 (when (re-search-forward (concat org-scheduled-string " "
13030 org-last-inserted-timestamp)
13031 (save-excursion
13032 (outline-next-heading) (point)) t)
13033 (goto-char (1- (match-end 0)))
13034 (insert " " repeater)
13035 (setq org-last-inserted-timestamp
13036 (concat (substring org-last-inserted-timestamp 0 -1)
13037 " " repeater
13038 (substring org-last-inserted-timestamp -1))))))
13039 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13041 (defun org-get-scheduled-time (pom &optional inherit)
13042 "Get the scheduled time as a time tuple, of a format suitable
13043 for calling org-schedule with, or if there is no scheduling,
13044 returns nil."
13045 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13046 (when time
13047 (apply 'encode-time (org-parse-time-string time)))))
13049 (defun org-get-deadline-time (pom &optional inherit)
13050 "Get the deadline as a time tuple, of a format suitable for
13051 calling org-deadline with, or if there is no scheduling, returns
13052 nil."
13053 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13054 (when time
13055 (apply 'encode-time (org-parse-time-string time)))))
13057 (defun org-remove-timestamp-with-keyword (keyword)
13058 "Remove all time stamps with KEYWORD in the current entry."
13059 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13060 beg)
13061 (save-excursion
13062 (org-back-to-heading t)
13063 (setq beg (point))
13064 (outline-next-heading)
13065 (while (re-search-backward re beg t)
13066 (replace-match "")
13067 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13068 (equal (char-before) ?\ ))
13069 (backward-delete-char 1)
13070 (if (string-match "^[ \t]*$" (buffer-substring
13071 (point-at-bol) (point-at-eol)))
13072 (delete-region (point-at-bol)
13073 (min (point-max) (1+ (point-at-eol))))))))))
13075 (defun org-add-planning-info (what &optional time &rest remove)
13076 "Insert new timestamp with keyword in the line directly after the headline.
13077 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13078 If non is given, the user is prompted for a date.
13079 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13080 be removed."
13081 (interactive)
13082 (let (org-time-was-given org-end-time-was-given ts
13083 end default-time default-input)
13085 (catch 'exit
13086 (when (and (memq what '(scheduled deadline))
13087 (or (not time)
13088 (and (stringp time)
13089 (string-match "^[-+]+[0-9]" time))))
13090 ;; Try to get a default date/time from existing timestamp
13091 (save-excursion
13092 (org-back-to-heading t)
13093 (setq end (save-excursion (outline-next-heading) (point)))
13094 (when (re-search-forward (if (eq what 'scheduled)
13095 org-scheduled-time-regexp
13096 org-deadline-time-regexp)
13097 end t)
13098 (setq ts (match-string 1)
13099 default-time
13100 (apply 'encode-time (org-parse-time-string ts))
13101 default-input (and ts (org-get-compact-tod ts))))))
13102 (when what
13103 (setq time
13104 (if (stringp time)
13105 ;; This is a string (relative or absolute), set proper date
13106 (apply 'encode-time
13107 (org-read-date-analyze
13108 time default-time (decode-time default-time)))
13109 ;; If necessary, get the time from the user
13110 (or time (org-read-date nil 'to-time nil nil
13111 default-time default-input)))))
13113 (when (and org-insert-labeled-timestamps-at-point
13114 (member what '(scheduled deadline)))
13115 (insert
13116 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13117 (org-insert-time-stamp time org-time-was-given
13118 nil nil nil (list org-end-time-was-given))
13119 (setq what nil))
13120 (save-excursion
13121 (save-restriction
13122 (let (col list elt ts buffer-invisibility-spec)
13123 (org-back-to-heading t)
13124 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13125 (goto-char (match-end 1))
13126 (setq col (current-column))
13127 (goto-char (match-end 0))
13128 (if (eobp) (insert "\n") (forward-char 1))
13129 (when (and (not what)
13130 (not (looking-at
13131 (concat "[ \t]*"
13132 org-keyword-time-not-clock-regexp))))
13133 ;; Nothing to add, nothing to remove...... :-)
13134 (throw 'exit nil))
13135 (if (and (not (looking-at org-outline-regexp))
13136 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13137 "[^\r\n]*"))
13138 (not (equal (match-string 1) org-clock-string)))
13139 (narrow-to-region (match-beginning 0) (match-end 0))
13140 (insert-before-markers "\n")
13141 (backward-char 1)
13142 (narrow-to-region (point) (point))
13143 (and org-adapt-indentation (org-indent-to-column col)))
13144 ;; Check if we have to remove something.
13145 (setq list (cons what remove))
13146 (while list
13147 (setq elt (pop list))
13148 (when (or (and (eq elt 'scheduled)
13149 (re-search-forward org-scheduled-time-regexp nil t))
13150 (and (eq elt 'deadline)
13151 (re-search-forward org-deadline-time-regexp nil t))
13152 (and (eq elt 'closed)
13153 (re-search-forward org-closed-time-regexp nil t)))
13154 (replace-match "")
13155 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13156 (and (looking-at "[ \t]+") (replace-match ""))
13157 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13158 (when what
13159 (insert
13160 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13161 (cond ((eq what 'scheduled) org-scheduled-string)
13162 ((eq what 'deadline) org-deadline-string)
13163 ((eq what 'closed) org-closed-string))
13164 " ")
13165 (setq ts (org-insert-time-stamp
13166 time
13167 (or org-time-was-given
13168 (and (eq what 'closed) org-log-done-with-time))
13169 (eq what 'closed)
13170 nil nil (list org-end-time-was-given)))
13171 (insert
13172 (if (not (or (bolp) (eq (char-before) ?\ )
13173 (memq (char-after) '(32 10))
13174 (eobp))) " " ""))
13175 (end-of-line 1))
13176 (goto-char (point-min))
13177 (widen)
13178 (if (and (looking-at "[ \t]*\n")
13179 (equal (char-before) ?\n))
13180 (delete-region (1- (point)) (point-at-eol)))
13181 ts))))))
13183 (defvar org-log-note-marker (make-marker))
13184 (defvar org-log-note-purpose nil)
13185 (defvar org-log-note-state nil)
13186 (defvar org-log-note-previous-state nil)
13187 (defvar org-log-note-how nil)
13188 (defvar org-log-note-extra nil)
13189 (defvar org-log-note-window-configuration nil)
13190 (defvar org-log-note-return-to (make-marker))
13191 (defvar org-log-note-effective-time nil
13192 "Remembered current time so that dynamically scoped
13193 `org-extend-today-until' affects tha timestamps in state change
13194 log")
13196 (defvar org-log-post-message nil
13197 "Message to be displayed after a log note has been stored.
13198 The auto-repeater uses this.")
13200 (defun org-add-note ()
13201 "Add a note to the current entry.
13202 This is done in the same way as adding a state change note."
13203 (interactive)
13204 (org-add-log-setup 'note nil nil 'findpos nil))
13206 (defvar org-property-end-re)
13207 (defun org-add-log-setup (&optional purpose state prev-state
13208 findpos how extra)
13209 "Set up the post command hook to take a note.
13210 If this is about to TODO state change, the new state is expected in STATE.
13211 When FINDPOS is non-nil, find the correct position for the note in
13212 the current entry. If not, assume that it can be inserted at point.
13213 HOW is an indicator what kind of note should be created.
13214 EXTRA is additional text that will be inserted into the notes buffer."
13215 (let* ((org-log-into-drawer (org-log-into-drawer))
13216 (drawer (cond ((stringp org-log-into-drawer)
13217 org-log-into-drawer)
13218 (org-log-into-drawer "LOGBOOK"))))
13219 (save-restriction
13220 (save-excursion
13221 (when findpos
13222 (org-back-to-heading t)
13223 (narrow-to-region (point) (save-excursion
13224 (outline-next-heading) (point)))
13225 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13226 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13227 "[^\r\n]*\\)?"))
13228 (goto-char (match-end 0))
13229 (cond
13230 (drawer
13231 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13232 nil t)
13233 (progn
13234 (goto-char (match-end 0))
13235 (or org-log-states-order-reversed
13236 (and (re-search-forward org-property-end-re nil t)
13237 (goto-char (1- (match-beginning 0))))))
13238 (insert "\n:" drawer ":\n:END:")
13239 (beginning-of-line 0)
13240 (org-indent-line)
13241 (beginning-of-line 2)
13242 (org-indent-line)
13243 (end-of-line 0)))
13244 ((and org-log-state-notes-insert-after-drawers
13245 (save-excursion
13246 (forward-line) (looking-at org-drawer-regexp)))
13247 (forward-line)
13248 (while (looking-at org-drawer-regexp)
13249 (goto-char (match-end 0))
13250 (re-search-forward org-property-end-re (point-max) t)
13251 (forward-line))
13252 (forward-line -1)))
13253 (unless org-log-states-order-reversed
13254 (and (= (char-after) ?\n) (forward-char 1))
13255 (org-skip-over-state-notes)
13256 (skip-chars-backward " \t\n\r")))
13257 (move-marker org-log-note-marker (point))
13258 (setq org-log-note-purpose purpose
13259 org-log-note-state state
13260 org-log-note-previous-state prev-state
13261 org-log-note-how how
13262 org-log-note-extra extra
13263 org-log-note-effective-time (org-current-effective-time))
13264 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13266 (defun org-skip-over-state-notes ()
13267 "Skip past the list of State notes in an entry."
13268 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13269 (when (ignore-errors (goto-char (org-in-item-p)))
13270 (let* ((struct (org-list-struct))
13271 (prevs (org-list-prevs-alist struct)))
13272 (while (looking-at "[ \t]*- State")
13273 (goto-char (or (org-list-get-next-item (point) struct prevs)
13274 (org-list-get-item-end (point) struct)))))))
13276 (defun org-add-log-note (&optional purpose)
13277 "Pop up a window for taking a note, and add this note later at point."
13278 (remove-hook 'post-command-hook 'org-add-log-note)
13279 (setq org-log-note-window-configuration (current-window-configuration))
13280 (delete-other-windows)
13281 (move-marker org-log-note-return-to (point))
13282 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13283 (goto-char org-log-note-marker)
13284 (org-switch-to-buffer-other-window "*Org Note*")
13285 (erase-buffer)
13286 (if (memq org-log-note-how '(time state))
13287 (let (current-prefix-arg) (org-store-log-note))
13288 (let ((org-inhibit-startup t)) (org-mode))
13289 (insert (format "# Insert note for %s.
13290 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13291 (cond
13292 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13293 ((eq org-log-note-purpose 'done) "closed todo item")
13294 ((eq org-log-note-purpose 'state)
13295 (format "state change from \"%s\" to \"%s\""
13296 (or org-log-note-previous-state "")
13297 (or org-log-note-state "")))
13298 ((eq org-log-note-purpose 'reschedule)
13299 "rescheduling")
13300 ((eq org-log-note-purpose 'delschedule)
13301 "no longer scheduled")
13302 ((eq org-log-note-purpose 'redeadline)
13303 "changing deadline")
13304 ((eq org-log-note-purpose 'deldeadline)
13305 "removing deadline")
13306 ((eq org-log-note-purpose 'refile)
13307 "refiling")
13308 ((eq org-log-note-purpose 'note)
13309 "this entry")
13310 (t (error "This should not happen")))))
13311 (if org-log-note-extra (insert org-log-note-extra))
13312 (org-set-local 'org-finish-function 'org-store-log-note)
13313 (run-hooks 'org-log-buffer-setup-hook)))
13315 (defvar org-note-abort nil) ; dynamically scoped
13316 (defun org-store-log-note ()
13317 "Finish taking a log note, and insert it to where it belongs."
13318 (let ((txt (buffer-string)))
13319 (kill-buffer (current-buffer))
13320 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13321 lines ind bul)
13322 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13323 (setq txt (replace-match "" t t txt)))
13324 (if (string-match "\\s-+\\'" txt)
13325 (setq txt (replace-match "" t t txt)))
13326 (setq lines (org-split-string txt "\n"))
13327 (when (and note (string-match "\\S-" note))
13328 (setq note
13329 (org-replace-escapes
13330 note
13331 (list (cons "%u" (user-login-name))
13332 (cons "%U" user-full-name)
13333 (cons "%t" (format-time-string
13334 (org-time-stamp-format 'long 'inactive)
13335 org-log-note-effective-time))
13336 (cons "%T" (format-time-string
13337 (org-time-stamp-format 'long nil)
13338 org-log-note-effective-time))
13339 (cons "%d" (format-time-string
13340 (org-time-stamp-format nil 'inactive)
13341 org-log-note-effective-time))
13342 (cons "%D" (format-time-string
13343 (org-time-stamp-format nil nil)
13344 org-log-note-effective-time))
13345 (cons "%s" (if org-log-note-state
13346 (concat "\"" org-log-note-state "\"")
13347 ""))
13348 (cons "%S" (if org-log-note-previous-state
13349 (concat "\"" org-log-note-previous-state "\"")
13350 "\"\"")))))
13351 (if lines (setq note (concat note " \\\\")))
13352 (push note lines))
13353 (when (or current-prefix-arg org-note-abort)
13354 (when org-log-into-drawer
13355 (org-remove-empty-drawer-at org-log-note-marker))
13356 (setq lines nil))
13357 (when lines
13358 (with-current-buffer (marker-buffer org-log-note-marker)
13359 (save-excursion
13360 (goto-char org-log-note-marker)
13361 (move-marker org-log-note-marker nil)
13362 (end-of-line 1)
13363 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13364 (setq ind (save-excursion
13365 (if (ignore-errors (goto-char (org-in-item-p)))
13366 (let ((struct (org-list-struct)))
13367 (org-list-get-ind
13368 (org-list-get-top-point struct) struct))
13369 (skip-chars-backward " \r\t\n")
13370 (cond
13371 ((and (org-at-heading-p)
13372 org-adapt-indentation)
13373 (1+ (org-current-level)))
13374 ((org-at-heading-p) 0)
13375 (t (org-get-indentation))))))
13376 (setq bul (org-list-bullet-string "-"))
13377 (org-indent-line-to ind)
13378 (insert bul (pop lines))
13379 (let ((ind-body (+ (length bul) ind)))
13380 (while lines
13381 (insert "\n")
13382 (org-indent-line-to ind-body)
13383 (insert (pop lines))))
13384 (message "Note stored")
13385 (org-back-to-heading t)
13386 (org-cycle-hide-drawers 'children))
13387 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13388 ;; from within `org-add-log-note' because `buffer-undo-list'
13389 ;; is then modified outside of `org-with-remote-undo'.
13390 (when (eq this-command 'org-agenda-todo)
13391 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13392 ;; Don't add undo information when called from `org-agenda-todo'
13393 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13394 (set-window-configuration org-log-note-window-configuration)
13395 (with-current-buffer (marker-buffer org-log-note-return-to)
13396 (goto-char org-log-note-return-to))
13397 (move-marker org-log-note-return-to nil)
13398 (and org-log-post-message (message "%s" org-log-post-message))))
13400 (defun org-remove-empty-drawer-at (pos)
13401 "Remove an empty drawer at position POS.
13402 POS may also be a marker."
13403 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13404 (org-with-wide-buffer
13405 (goto-char pos)
13406 (let ((drawer (org-element-at-point)))
13407 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13408 (not (org-element-property :contents-begin drawer)))
13409 (delete-region (org-element-property :begin drawer)
13410 (progn (goto-char (org-element-property :end drawer))
13411 (skip-chars-backward " \r\t\n")
13412 (forward-line)
13413 (point))))))))
13415 (defvar org-ts-type nil)
13416 (defun org-sparse-tree (&optional arg type)
13417 "Create a sparse tree, prompt for the details.
13418 This command can create sparse trees. You first need to select the type
13419 of match used to create the tree:
13421 t Show all TODO entries.
13422 T Show entries with a specific TODO keyword.
13423 m Show entries selected by a tags/property match.
13424 p Enter a property name and its value (both with completion on existing
13425 names/values) and show entries with that property.
13426 r Show entries matching a regular expression (`/' can be used as well).
13427 b Show deadlines and scheduled items before a date.
13428 a Show deadlines and scheduled items after a date.
13429 d Show deadlines due within `org-deadline-warning-days'.
13430 D Show deadlines and scheduled items between a date range."
13431 (interactive "P")
13432 (let (ans kwd value ts-type)
13433 (setq type (or type org-sparse-tree-default-date-type))
13434 (setq org-ts-type type)
13435 (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"
13436 (cond ((eq type 'all) "all timestamps")
13437 ((eq type 'scheduled) "only scheduled")
13438 ((eq type 'deadline) "only deadline")
13439 ((eq type 'active) "only active timestamps")
13440 ((eq type 'inactive) "only inactive timestamps")
13441 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13442 ((eq type 'closed) "with a closed time-stamp")
13443 (t "scheduled/deadline")))
13444 (setq ans (read-char-exclusive))
13445 (cond
13446 ((equal ans ?c)
13447 (org-sparse-tree
13448 arg (cadr (member type '(scheduled-or-deadline
13449 all scheduled deadline active inactive closed)))))
13450 ((equal ans ?d)
13451 (call-interactively 'org-check-deadlines))
13452 ((equal ans ?b)
13453 (call-interactively 'org-check-before-date))
13454 ((equal ans ?a)
13455 (call-interactively 'org-check-after-date))
13456 ((equal ans ?D)
13457 (call-interactively 'org-check-dates-range))
13458 ((equal ans ?t)
13459 (call-interactively 'org-show-todo-tree))
13460 ((equal ans ?T)
13461 (org-show-todo-tree '(4)))
13462 ((member ans '(?T ?m))
13463 (call-interactively 'org-match-sparse-tree))
13464 ((member ans '(?p ?P))
13465 (setq kwd (org-icompleting-read "Property: "
13466 (mapcar 'list (org-buffer-property-keys))))
13467 (setq value (org-icompleting-read "Value: "
13468 (mapcar 'list (org-property-values kwd))))
13469 (unless (string-match "\\`{.*}\\'" value)
13470 (setq value (concat "\"" value "\"")))
13471 (org-match-sparse-tree arg (concat kwd "=" value)))
13472 ((member ans '(?r ?R ?/))
13473 (call-interactively 'org-occur))
13474 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13476 (defvar org-occur-highlights nil
13477 "List of overlays used for occur matches.")
13478 (make-variable-buffer-local 'org-occur-highlights)
13479 (defvar org-occur-parameters nil
13480 "Parameters of the active org-occur calls.
13481 This is a list, each call to org-occur pushes as cons cell,
13482 containing the regular expression and the callback, onto the list.
13483 The list can contain several entries if `org-occur' has been called
13484 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13485 will only contain one set of parameters. When the highlights are
13486 removed (for example with `C-c C-c', or with the next edit (depending
13487 on `org-remove-highlights-with-change'), this variable is emptied
13488 as well.")
13489 (make-variable-buffer-local 'org-occur-parameters)
13491 (defun org-occur (regexp &optional keep-previous callback)
13492 "Make a compact tree which shows all matches of REGEXP.
13493 The tree will show the lines where the regexp matches, and all higher
13494 headlines above the match. It will also show the heading after the match,
13495 to make sure editing the matching entry is easy.
13496 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13497 call to `org-occur' will be kept, to allow stacking of calls to this
13498 command.
13499 If CALLBACK is non-nil, it is a function which is called to confirm
13500 that the match should indeed be shown."
13501 (interactive "sRegexp: \nP")
13502 (when (equal regexp "")
13503 (user-error "Regexp cannot be empty"))
13504 (unless keep-previous
13505 (org-remove-occur-highlights nil nil t))
13506 (push (cons regexp callback) org-occur-parameters)
13507 (let ((cnt 0))
13508 (save-excursion
13509 (goto-char (point-min))
13510 (if (or (not keep-previous) ; do not want to keep
13511 (not org-occur-highlights)) ; no previous matches
13512 ;; hide everything
13513 (org-overview))
13514 (while (re-search-forward regexp nil t)
13515 (when (or (not callback)
13516 (save-match-data (funcall callback)))
13517 (setq cnt (1+ cnt))
13518 (when org-highlight-sparse-tree-matches
13519 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13520 (org-show-context 'occur-tree))))
13521 (when org-remove-highlights-with-change
13522 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13523 nil 'local))
13524 (unless org-sparse-tree-open-archived-trees
13525 (org-hide-archived-subtrees (point-min) (point-max)))
13526 (run-hooks 'org-occur-hook)
13527 (if (org-called-interactively-p 'interactive)
13528 (message "%d match(es) for regexp %s" cnt regexp))
13529 cnt))
13531 (defun org-occur-next-match (&optional n reset)
13532 "Function for `next-error-function' to find sparse tree matches.
13533 N is the number of matches to move, when negative move backwards.
13534 RESET is entirely ignored - this function always goes back to the
13535 starting point when no match is found."
13536 (let* ((limit (if (< n 0) (point-min) (point-max)))
13537 (search-func (if (< n 0)
13538 'previous-single-char-property-change
13539 'next-single-char-property-change))
13540 (n (abs n))
13541 (pos (point))
13543 (catch 'exit
13544 (while (setq p1 (funcall search-func (point) 'org-type))
13545 (when (equal p1 limit)
13546 (goto-char pos)
13547 (error "No more matches"))
13548 (when (equal (get-char-property p1 'org-type) 'org-occur)
13549 (setq n (1- n))
13550 (when (= n 0)
13551 (goto-char p1)
13552 (throw 'exit (point))))
13553 (goto-char p1))
13554 (goto-char p1)
13555 (error "No more matches"))))
13557 (defun org-show-context (&optional key)
13558 "Make sure point and context are visible.
13559 How much context is shown depends upon the variables
13560 `org-show-hierarchy-above', `org-show-following-heading',
13561 `org-show-entry-below' and `org-show-siblings'."
13562 (let ((heading-p (org-at-heading-p t))
13563 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13564 (following-p (org-get-alist-option org-show-following-heading key))
13565 (entry-p (org-get-alist-option org-show-entry-below key))
13566 (siblings-p (org-get-alist-option org-show-siblings key)))
13567 ;; Show heading or entry text
13568 (if (and heading-p (not entry-p))
13569 (org-flag-heading nil) ; only show the heading
13570 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13571 (org-show-hidden-entry))) ; show entire entry
13572 (when following-p
13573 ;; Show next sibling, or heading below text
13574 (save-excursion
13575 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13576 (org-flag-heading nil))))
13577 (when siblings-p (org-show-siblings))
13578 (when hierarchy-p
13579 ;; show all higher headings, possibly with siblings
13580 (save-excursion
13581 (while (and (condition-case nil
13582 (progn (org-up-heading-all 1) t)
13583 (error nil))
13584 (not (bobp)))
13585 (org-flag-heading nil)
13586 (when siblings-p (org-show-siblings)))))
13587 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13589 (defvar org-reveal-start-hook nil
13590 "Hook run before revealing a location.")
13592 (defun org-reveal (&optional siblings)
13593 "Show current entry, hierarchy above it, and the following headline.
13594 This can be used to show a consistent set of context around locations
13595 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13596 not t for the search context.
13598 With optional argument SIBLINGS, on each level of the hierarchy all
13599 siblings are shown. This repairs the tree structure to what it would
13600 look like when opened with hierarchical calls to `org-cycle'.
13601 With double optional argument \\[universal-argument] \\[universal-argument], \
13602 go to the parent and show the
13603 entire tree."
13604 (interactive "P")
13605 (run-hooks 'org-reveal-start-hook)
13606 (let ((org-show-hierarchy-above t)
13607 (org-show-following-heading t)
13608 (org-show-siblings (if siblings t org-show-siblings)))
13609 (org-show-context nil))
13610 (when (equal siblings '(16))
13611 (save-excursion
13612 (when (org-up-heading-safe)
13613 (org-show-subtree)
13614 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13616 (defun org-highlight-new-match (beg end)
13617 "Highlight from BEG to END and mark the highlight is an occur headline."
13618 (let ((ov (make-overlay beg end)))
13619 (overlay-put ov 'face 'secondary-selection)
13620 (overlay-put ov 'org-type 'org-occur)
13621 (push ov org-occur-highlights)))
13623 (defun org-remove-occur-highlights (&optional beg end noremove)
13624 "Remove the occur highlights from the buffer.
13625 BEG and END are ignored. If NOREMOVE is nil, remove this function
13626 from the `before-change-functions' in the current buffer."
13627 (interactive)
13628 (unless org-inhibit-highlight-removal
13629 (mapc 'delete-overlay org-occur-highlights)
13630 (setq org-occur-highlights nil)
13631 (setq org-occur-parameters nil)
13632 (unless noremove
13633 (remove-hook 'before-change-functions
13634 'org-remove-occur-highlights 'local))))
13636 ;;;; Priorities
13638 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13639 "Regular expression matching the priority indicator.")
13641 (defvar org-remove-priority-next-time nil)
13643 (defun org-priority-up ()
13644 "Increase the priority of the current item."
13645 (interactive)
13646 (org-priority 'up))
13648 (defun org-priority-down ()
13649 "Decrease the priority of the current item."
13650 (interactive)
13651 (org-priority 'down))
13653 (defun org-priority (&optional action show)
13654 "Change the priority of an item.
13655 ACTION can be `set', `up', `down', or a character."
13656 (interactive "P")
13657 (if (equal action '(4))
13658 (org-show-priority)
13659 (unless org-enable-priority-commands
13660 (user-error "Priority commands are disabled"))
13661 (setq action (or action 'set))
13662 (let (current new news have remove)
13663 (save-excursion
13664 (org-back-to-heading t)
13665 (if (looking-at org-priority-regexp)
13666 (setq current (string-to-char (match-string 2))
13667 have t))
13668 (cond
13669 ((eq action 'remove)
13670 (setq remove t new ?\ ))
13671 ((or (eq action 'set)
13672 (if (featurep 'xemacs) (characterp action) (integerp action)))
13673 (if (not (eq action 'set))
13674 (setq new action)
13675 (message "Priority %c-%c, SPC to remove: "
13676 org-highest-priority org-lowest-priority)
13677 (save-match-data
13678 (setq new (read-char-exclusive))))
13679 (if (and (= (upcase org-highest-priority) org-highest-priority)
13680 (= (upcase org-lowest-priority) org-lowest-priority))
13681 (setq new (upcase new)))
13682 (cond ((equal new ?\ ) (setq remove t))
13683 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13684 (user-error "Priority must be between `%c' and `%c'"
13685 org-highest-priority org-lowest-priority))))
13686 ((eq action 'up)
13687 (setq new (if have
13688 (1- current) ; normal cycling
13689 ;; last priority was empty
13690 (if (eq last-command this-command)
13691 org-lowest-priority ; wrap around empty to lowest
13692 ;; default
13693 (if org-priority-start-cycle-with-default
13694 org-default-priority
13695 (1- org-default-priority))))))
13696 ((eq action 'down)
13697 (setq new (if have
13698 (1+ current) ; normal cycling
13699 ;; last priority was empty
13700 (if (eq last-command this-command)
13701 org-highest-priority ; wrap around empty to highest
13702 ;; default
13703 (if org-priority-start-cycle-with-default
13704 org-default-priority
13705 (1+ org-default-priority))))))
13706 (t (user-error "Invalid action")))
13707 (if (or (< (upcase new) org-highest-priority)
13708 (> (upcase new) org-lowest-priority))
13709 (if (and (memq action '(up down))
13710 (not have) (not (eq last-command this-command)))
13711 ;; `new' is from default priority
13712 (error
13713 "The default can not be set, see `org-default-priority' why")
13714 ;; normal cycling: `new' is beyond highest/lowest priority
13715 ;; and is wrapped around to the empty priority
13716 (setq remove t)))
13717 (setq news (format "%c" new))
13718 (if have
13719 (if remove
13720 (replace-match "" t t nil 1)
13721 (replace-match news t t nil 2))
13722 (if remove
13723 (user-error "No priority cookie found in line")
13724 (let ((case-fold-search nil))
13725 (looking-at org-todo-line-regexp))
13726 (if (match-end 2)
13727 (progn
13728 (goto-char (match-end 2))
13729 (insert " [#" news "]"))
13730 (goto-char (match-beginning 3))
13731 (insert "[#" news "] "))))
13732 (org-preserve-lc (org-set-tags nil 'align)))
13733 (if remove
13734 (message "Priority removed")
13735 (message "Priority of current item set to %s" news)))))
13737 (defun org-show-priority ()
13738 "Show the priority of the current item.
13739 This priority is composed of the main priority given with the [#A] cookies,
13740 and by additional input from the age of a schedules or deadline entry."
13741 (interactive)
13742 (let ((pri (if (eq major-mode 'org-agenda-mode)
13743 (org-get-at-bol 'priority)
13744 (save-excursion
13745 (save-match-data
13746 (beginning-of-line)
13747 (and (looking-at org-heading-regexp)
13748 (org-get-priority (match-string 0))))))))
13749 (message "Priority is %d" (if pri pri -1000))))
13751 (defun org-get-priority (s)
13752 "Find priority cookie and return priority."
13753 (save-match-data
13754 (if (functionp org-get-priority-function)
13755 (funcall org-get-priority-function)
13756 (if (not (string-match org-priority-regexp s))
13757 (* 1000 (- org-lowest-priority org-default-priority))
13758 (* 1000 (- org-lowest-priority
13759 (string-to-char (match-string 2 s))))))))
13761 ;;;; Tags
13763 (defvar org-agenda-archives-mode)
13764 (defvar org-map-continue-from nil
13765 "Position from where mapping should continue.
13766 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13768 (defvar org-scanner-tags nil
13769 "The current tag list while the tags scanner is running.")
13770 (defvar org-trust-scanner-tags nil
13771 "Should `org-get-tags-at' use the tags for the scanner.
13772 This is for internal dynamical scoping only.
13773 When this is non-nil, the function `org-get-tags-at' will return the value
13774 of `org-scanner-tags' instead of building the list by itself. This
13775 can lead to large speed-ups when the tags scanner is used in a file with
13776 many entries, and when the list of tags is retrieved, for example to
13777 obtain a list of properties. Building the tags list for each entry in such
13778 a file becomes an N^2 operation - but with this variable set, it scales
13779 as N.")
13781 (defun org-scan-tags (action matcher todo-only &optional start-level)
13782 "Sca headline tags with inheritance and produce output ACTION.
13784 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13785 or `agenda' to produce an entry list for an agenda view. It can also be
13786 a Lisp form or a function that should be called at each matched headline, in
13787 this case the return value is a list of all return values from these calls.
13789 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13790 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13791 only lines with a not-done TODO keyword are included in the output.
13792 This should be the same variable that was scoped into
13793 and set by `org-make-tags-matcher' when it constructed MATCHER.
13795 START-LEVEL can be a string with asterisks, reducing the scope to
13796 headlines matching this string."
13797 (require 'org-agenda)
13798 (let* ((re (concat "^"
13799 (if start-level
13800 ;; Get the correct level to match
13801 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13802 org-outline-regexp)
13803 " *\\(\\<\\("
13804 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13805 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13806 (props (list 'face 'default
13807 'done-face 'org-agenda-done
13808 'undone-face 'default
13809 'mouse-face 'highlight
13810 'org-not-done-regexp org-not-done-regexp
13811 'org-todo-regexp org-todo-regexp
13812 'org-complex-heading-regexp org-complex-heading-regexp
13813 'help-echo
13814 (format "mouse-2 or RET jump to org file %s"
13815 (abbreviate-file-name
13816 (or (buffer-file-name (buffer-base-buffer))
13817 (buffer-name (buffer-base-buffer)))))))
13818 (org-map-continue-from nil)
13819 lspos tags tags-list
13820 (tags-alist (list (cons 0 org-file-tags)))
13821 (llast 0) rtn rtn1 level category i txt
13822 todo marker entry priority)
13823 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13824 (setq action (list 'lambda nil action)))
13825 (save-excursion
13826 (goto-char (point-min))
13827 (when (eq action 'sparse-tree)
13828 (org-overview)
13829 (org-remove-occur-highlights))
13830 (while (let (case-fold-search)
13831 (re-search-forward re nil t))
13832 (setq org-map-continue-from nil)
13833 (catch :skip
13834 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13835 tags (if (match-end 4) (org-match-string-no-properties 4)))
13836 (goto-char (setq lspos (match-beginning 0)))
13837 (setq level (org-reduced-level (org-outline-level))
13838 category (org-get-category))
13839 (setq i llast llast level)
13840 ;; remove tag lists from same and sublevels
13841 (while (>= i level)
13842 (when (setq entry (assoc i tags-alist))
13843 (setq tags-alist (delete entry tags-alist)))
13844 (setq i (1- i)))
13845 ;; add the next tags
13846 (when tags
13847 (setq tags (org-split-string tags ":")
13848 tags-alist
13849 (cons (cons level tags) tags-alist)))
13850 ;; compile tags for current headline
13851 (setq tags-list
13852 (if org-use-tag-inheritance
13853 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13854 tags)
13855 org-scanner-tags tags-list)
13856 (when org-use-tag-inheritance
13857 (setcdr (car tags-alist)
13858 (mapcar (lambda (x)
13859 (setq x (copy-sequence x))
13860 (org-add-prop-inherited x))
13861 (cdar tags-alist))))
13862 (when (and tags org-use-tag-inheritance
13863 (or (not (eq t org-use-tag-inheritance))
13864 org-tags-exclude-from-inheritance))
13865 ;; selective inheritance, remove uninherited ones
13866 (setcdr (car tags-alist)
13867 (org-remove-uninherited-tags (cdar tags-alist))))
13868 (when (and
13870 ;; eval matcher only when the todo condition is OK
13871 (and (or (not todo-only) (member todo org-not-done-keywords))
13872 (let ((case-fold-search t) (org-trust-scanner-tags t))
13873 (eval matcher)))
13875 ;; Call the skipper, but return t if it does not skip,
13876 ;; so that the `and' form continues evaluating
13877 (progn
13878 (unless (eq action 'sparse-tree) (org-agenda-skip))
13881 ;; Check if timestamps are deselecting this entry
13882 (or (not todo-only)
13883 (and (member todo org-not-done-keywords)
13884 (or (not org-agenda-tags-todo-honor-ignore-options)
13885 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13887 ;; select this headline
13888 (cond
13889 ((eq action 'sparse-tree)
13890 (and org-highlight-sparse-tree-matches
13891 (org-get-heading) (match-end 0)
13892 (org-highlight-new-match
13893 (match-beginning 1) (match-end 1)))
13894 (org-show-context 'tags-tree))
13895 ((eq action 'agenda)
13896 (setq txt (org-agenda-format-item
13898 (concat
13899 (if (eq org-tags-match-list-sublevels 'indented)
13900 (make-string (1- level) ?.) "")
13901 (org-get-heading))
13902 level category
13903 tags-list)
13904 priority (org-get-priority txt))
13905 (goto-char lspos)
13906 (setq marker (org-agenda-new-marker))
13907 (org-add-props txt props
13908 'org-marker marker 'org-hd-marker marker 'org-category category
13909 'todo-state todo
13910 'priority priority 'type "tagsmatch")
13911 (push txt rtn))
13912 ((functionp action)
13913 (setq org-map-continue-from nil)
13914 (save-excursion
13915 (setq rtn1 (funcall action))
13916 (push rtn1 rtn)))
13917 (t (user-error "Invalid action")))
13919 ;; if we are to skip sublevels, jump to end of subtree
13920 (unless org-tags-match-list-sublevels
13921 (org-end-of-subtree t)
13922 (backward-char 1))))
13923 ;; Get the correct position from where to continue
13924 (if org-map-continue-from
13925 (goto-char org-map-continue-from)
13926 (and (= (point) lspos) (end-of-line 1)))))
13927 (when (and (eq action 'sparse-tree)
13928 (not org-sparse-tree-open-archived-trees))
13929 (org-hide-archived-subtrees (point-min) (point-max)))
13930 (nreverse rtn)))
13932 (defun org-remove-uninherited-tags (tags)
13933 "Remove all tags that are not inherited from the list TAGS."
13934 (cond
13935 ((eq org-use-tag-inheritance t)
13936 (if org-tags-exclude-from-inheritance
13937 (org-delete-all org-tags-exclude-from-inheritance tags)
13938 tags))
13939 ((not org-use-tag-inheritance) nil)
13940 ((stringp org-use-tag-inheritance)
13941 (delq nil (mapcar
13942 (lambda (x)
13943 (if (and (string-match org-use-tag-inheritance x)
13944 (not (member x org-tags-exclude-from-inheritance)))
13945 x nil))
13946 tags)))
13947 ((listp org-use-tag-inheritance)
13948 (delq nil (mapcar
13949 (lambda (x)
13950 (if (member x org-use-tag-inheritance) x nil))
13951 tags)))))
13953 (defun org-match-sparse-tree (&optional todo-only match)
13954 "Create a sparse tree according to tags string MATCH.
13955 MATCH can contain positive and negative selection of tags, like
13956 \"+WORK+URGENT-WITHBOSS\".
13957 If optional argument TODO-ONLY is non-nil, only select lines that are
13958 also TODO lines."
13959 (interactive "P")
13960 (org-agenda-prepare-buffers (list (current-buffer)))
13961 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13963 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13965 (defvar org-cached-props nil)
13966 (defun org-cached-entry-get (pom property)
13967 (if (or (eq t org-use-property-inheritance)
13968 (and (stringp org-use-property-inheritance)
13969 (string-match org-use-property-inheritance property))
13970 (and (listp org-use-property-inheritance)
13971 (member property org-use-property-inheritance)))
13972 ;; Caching is not possible, check it directly
13973 (org-entry-get pom property 'inherit)
13974 ;; Get all properties, so that we can do complicated checks easily
13975 (cdr (assoc property (or org-cached-props
13976 (setq org-cached-props
13977 (org-entry-properties pom)))))))
13979 (defun org-global-tags-completion-table (&optional files)
13980 "Return the list of all tags in all agenda buffer/files.
13981 Optional FILES argument is a list of files which can be used
13982 instead of the agenda files."
13983 (save-excursion
13984 (org-uniquify
13985 (delq nil
13986 (apply 'append
13987 (mapcar
13988 (lambda (file)
13989 (set-buffer (find-file-noselect file))
13990 (append (org-get-buffer-tags)
13991 (mapcar (lambda (x) (if (stringp (car-safe x))
13992 (list (car-safe x)) nil))
13993 org-tag-alist)))
13994 (if (and files (car files))
13995 files
13996 (org-agenda-files))))))))
13998 (defun org-make-tags-matcher (match)
13999 "Create the TAGS/TODO matcher form for the selection string MATCH.
14001 The variable `todo-only' is scoped dynamically into this function.
14002 It will be set to t if the matcher restricts matching to TODO entries,
14003 otherwise will not be touched.
14005 Returns a cons of the selection string MATCH and the constructed
14006 lisp form implementing the matcher. The matcher is to be evaluated
14007 at an Org entry, with point on the headline, and returns t if the
14008 entry matches the selection string MATCH. The returned lisp form
14009 references two variables with information about the entry, which
14010 must be bound around the form's evaluation: todo, the TODO keyword
14011 at the entry (or nil of none); and tags-list, the list of all tags
14012 at the entry including inherited ones. Additionally, the category
14013 of the entry (if any) must be specified as the text property
14014 'org-category on the headline.
14016 See also `org-scan-tags'.
14018 (declare (special todo-only))
14019 (unless (boundp 'todo-only)
14020 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14021 (unless match
14022 ;; Get a new match request, with completion against the global
14023 ;; tags table and the local tags in current buffer
14024 (let ((org-last-tags-completion-table
14025 (org-uniquify
14026 (delq nil (append (org-get-buffer-tags)
14027 (org-global-tags-completion-table))))))
14028 (setq match (org-completing-read-no-i
14029 "Match: " 'org-tags-completion-function nil nil nil
14030 'org-tags-history))))
14032 ;; Parse the string and create a lisp form
14033 (let ((match0 match)
14034 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14035 minus tag mm
14036 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14037 orterms term orlist re-p str-p level-p level-op time-p
14038 prop-p pn pv po gv rest (start 0) (ss 0))
14039 ;; Expand group tags
14040 (setq match (org-tags-expand match))
14042 ;; Check if there is a TODO part of this match, which would be the
14043 ;; part after a "/". TO make sure that this slash is not part of
14044 ;; a property value to be matched against, we also check that there
14045 ;; is no " after that slash.
14046 ;; First, find the last slash
14047 (while (string-match "/+" match ss)
14048 (setq start (match-beginning 0) ss (match-end 0)))
14049 (if (and (string-match "/+" match start)
14050 (not (save-match-data (string-match "\"" match start))))
14051 ;; match contains also a todo-matching request
14052 (progn
14053 (setq tagsmatch (substring match 0 (match-beginning 0))
14054 todomatch (substring match (match-end 0)))
14055 (if (string-match "^!" todomatch)
14056 (setq todo-only t todomatch (substring todomatch 1)))
14057 (if (string-match "^\\s-*$" todomatch)
14058 (setq todomatch nil)))
14059 ;; only matching tags
14060 (setq tagsmatch match todomatch nil))
14062 ;; Make the tags matcher
14063 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14064 (setq tagsmatcher t)
14065 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14066 (while (setq term (pop orterms))
14067 (while (and (equal (substring term -1) "\\") orterms)
14068 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14069 (while (string-match re term)
14070 (setq rest (substring term (match-end 0))
14071 minus (and (match-end 1)
14072 (equal (match-string 1 term) "-"))
14073 tag (save-match-data (replace-regexp-in-string
14074 "\\\\-" "-"
14075 (match-string 2 term)))
14076 re-p (equal (string-to-char tag) ?{)
14077 level-p (match-end 4)
14078 prop-p (match-end 5)
14079 mm (cond
14080 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14081 (level-p
14082 (setq level-op (org-op-to-function (match-string 3 term)))
14083 `(,level-op level ,(string-to-number
14084 (match-string 4 term))))
14085 (prop-p
14086 (setq pn (match-string 5 term)
14087 po (match-string 6 term)
14088 pv (match-string 7 term)
14089 re-p (equal (string-to-char pv) ?{)
14090 str-p (equal (string-to-char pv) ?\")
14091 time-p (save-match-data
14092 (string-match "^\"[[<].*[]>]\"$" pv))
14093 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14094 (if time-p (setq pv (org-matcher-time pv)))
14095 (setq po (org-op-to-function po (if time-p 'time str-p)))
14096 (cond
14097 ((equal pn "CATEGORY")
14098 (setq gv '(get-text-property (point) 'org-category)))
14099 ((equal pn "TODO")
14100 (setq gv 'todo))
14102 (setq gv `(org-cached-entry-get nil ,pn))))
14103 (if re-p
14104 (if (eq po 'org<>)
14105 `(not (string-match ,pv (or ,gv "")))
14106 `(string-match ,pv (or ,gv "")))
14107 (if str-p
14108 `(,po (or ,gv "") ,pv)
14109 `(,po (string-to-number (or ,gv ""))
14110 ,(string-to-number pv) ))))
14111 (t `(member ,tag tags-list)))
14112 mm (if minus (list 'not mm) mm)
14113 term rest)
14114 (push mm tagsmatcher))
14115 (push (if (> (length tagsmatcher) 1)
14116 (cons 'and tagsmatcher)
14117 (car tagsmatcher))
14118 orlist)
14119 (setq tagsmatcher nil))
14120 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14121 (setq tagsmatcher
14122 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14123 ;; Make the todo matcher
14124 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14125 (setq todomatcher t)
14126 (setq orterms (org-split-string todomatch "|") orlist nil)
14127 (while (setq term (pop orterms))
14128 (while (string-match re term)
14129 (setq minus (and (match-end 1)
14130 (equal (match-string 1 term) "-"))
14131 kwd (match-string 2 term)
14132 re-p (equal (string-to-char kwd) ?{)
14133 term (substring term (match-end 0))
14134 mm (if re-p
14135 `(string-match ,(substring kwd 1 -1) todo)
14136 (list 'equal 'todo kwd))
14137 mm (if minus (list 'not mm) mm))
14138 (push mm todomatcher))
14139 (push (if (> (length todomatcher) 1)
14140 (cons 'and todomatcher)
14141 (car todomatcher))
14142 orlist)
14143 (setq todomatcher nil))
14144 (setq todomatcher (if (> (length orlist) 1)
14145 (cons 'or orlist) (car orlist))))
14147 ;; Return the string and lisp forms of the matcher
14148 (setq matcher (if todomatcher
14149 (list 'and tagsmatcher todomatcher)
14150 tagsmatcher))
14151 (when todo-only
14152 (setq matcher (list 'and '(member todo org-not-done-keywords)
14153 matcher)))
14154 (cons match0 matcher)))
14156 (defun org-tags-expand (match &optional single-as-list downcased)
14157 "Expand group tags in MATCH.
14159 This replaces every group tag in MATCH with a regexp tag search.
14160 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14161 will be replaced like this:
14163 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14164 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14165 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14167 Replacing by a regexp preserves the structure of the match.
14168 E.g., this expansion
14170 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14172 will match anything tagged with \"Lab\" and \"Home\", or tagged
14173 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14175 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14176 assumed to be a single group tag, and the function will return
14177 the list of tags in this group.
14179 When DOWNCASE is non-nil, expand downcased TAGS."
14180 (if org-group-tags
14181 (let* ((case-fold-search t)
14182 (stable org-mode-syntax-table)
14183 (tal (or org-tag-groups-alist-for-agenda
14184 org-tag-groups-alist))
14185 (tal (if downcased
14186 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14187 (tml (mapcar 'car tal))
14188 (rtnmatch match) rpl)
14189 ;; @ and _ are allowed as word-components in tags
14190 (modify-syntax-entry ?@ "w" stable)
14191 (modify-syntax-entry ?_ "w" stable)
14192 (while (and tml
14193 (with-syntax-table stable
14194 (string-match
14195 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14196 (regexp-opt tml) "\\>\\)") rtnmatch)))
14197 (let* ((dir (match-string 1 rtnmatch))
14198 (tag (match-string 2 rtnmatch))
14199 (tag (if downcased (downcase tag) tag)))
14200 (setq tml (delete tag tml))
14201 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14202 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14203 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14204 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14205 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14206 (if single-as-list
14207 (or (reverse rpl) (list rtnmatch))
14208 rtnmatch))
14209 (if single-as-list (list (if downcased (downcase match) match))
14210 match)))
14212 (defun org-op-to-function (op &optional stringp)
14213 "Turn an operator into the appropriate function."
14214 (setq op
14215 (cond
14216 ((equal op "<" ) '(< string< org-time<))
14217 ((equal op ">" ) '(> org-string> org-time>))
14218 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14219 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14220 ((member op '("=" "==")) '(= string= org-time=))
14221 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14222 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14224 (defun org<> (a b) (not (= a b)))
14225 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14226 (defun org-string>= (a b) (not (string< a b)))
14227 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14228 (defun org-string<> (a b) (not (string= a b)))
14229 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14230 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14231 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14232 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14233 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14234 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14235 (defun org-2ft (s)
14236 "Convert S to a floating point time.
14237 If S is already a number, just return it. If it is a string, parse
14238 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14239 (cond
14240 ((numberp s) s)
14241 ((stringp s)
14242 (condition-case nil
14243 (float-time (apply 'encode-time (org-parse-time-string s)))
14244 (error 0.)))
14245 (t 0.)))
14247 (defun org-time-today ()
14248 "Time in seconds today at 0:00.
14249 Returns the float number of seconds since the beginning of the
14250 epoch to the beginning of today (00:00)."
14251 (float-time (apply 'encode-time
14252 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14254 (defun org-matcher-time (s)
14255 "Interpret a time comparison value."
14256 (save-match-data
14257 (cond
14258 ((string= s "<now>") (float-time))
14259 ((string= s "<today>") (org-time-today))
14260 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14261 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14262 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14263 (+ (org-time-today)
14264 (* (string-to-number (match-string 1 s))
14265 (cdr (assoc (match-string 2 s)
14266 '(("d" . 86400.0) ("w" . 604800.0)
14267 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14268 (t (org-2ft s)))))
14270 (defun org-match-any-p (re list)
14271 "Does re match any element of list?"
14272 (setq list (mapcar (lambda (x) (string-match re x)) list))
14273 (delq nil list))
14275 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14276 (defvar org-tags-overlay (make-overlay 1 1))
14277 (org-detach-overlay org-tags-overlay)
14279 (defun org-get-local-tags-at (&optional pos)
14280 "Get a list of tags defined in the current headline."
14281 (org-get-tags-at pos 'local))
14283 (defun org-get-local-tags ()
14284 "Get a list of tags defined in the current headline."
14285 (org-get-tags-at nil 'local))
14287 (defun org-get-tags-at (&optional pos local)
14288 "Get a list of all headline tags applicable at POS.
14289 POS defaults to point. If tags are inherited, the list contains
14290 the targets in the same sequence as the headlines appear, i.e.
14291 the tags of the current headline come last.
14292 When LOCAL is non-nil, only return tags from the current headline,
14293 ignore inherited ones."
14294 (interactive)
14295 (if (and org-trust-scanner-tags
14296 (or (not pos) (equal pos (point)))
14297 (not local))
14298 org-scanner-tags
14299 (let (tags ltags lastpos parent)
14300 (save-excursion
14301 (save-restriction
14302 (widen)
14303 (goto-char (or pos (point)))
14304 (save-match-data
14305 (catch 'done
14306 (condition-case nil
14307 (progn
14308 (org-back-to-heading t)
14309 (while (not (equal lastpos (point)))
14310 (setq lastpos (point))
14311 (when (looking-at
14312 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14313 (setq ltags (org-split-string
14314 (org-match-string-no-properties 1) ":"))
14315 (when parent
14316 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14317 (setq tags (append
14318 (if parent
14319 (org-remove-uninherited-tags ltags)
14320 ltags)
14321 tags)))
14322 (or org-use-tag-inheritance (throw 'done t))
14323 (if local (throw 'done t))
14324 (or (org-up-heading-safe) (error nil))
14325 (setq parent t)))
14326 (error nil)))))
14327 (if local
14328 tags
14329 (reverse (delete-dups
14330 (reverse (append
14331 (org-remove-uninherited-tags
14332 org-file-tags) tags)))))))))
14334 (defun org-add-prop-inherited (s)
14335 (add-text-properties 0 (length s) '(inherited t) s)
14338 (defun org-toggle-tag (tag &optional onoff)
14339 "Toggle the tag TAG for the current line.
14340 If ONOFF is `on' or `off', don't toggle but set to this state."
14341 (let (res current)
14342 (save-excursion
14343 (org-back-to-heading t)
14344 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14345 (point-at-eol) t)
14346 (progn
14347 (setq current (match-string 1))
14348 (replace-match ""))
14349 (setq current ""))
14350 (setq current (nreverse (org-split-string current ":")))
14351 (cond
14352 ((eq onoff 'on)
14353 (setq res t)
14354 (or (member tag current) (push tag current)))
14355 ((eq onoff 'off)
14356 (or (not (member tag current)) (setq current (delete tag current))))
14357 (t (if (member tag current)
14358 (setq current (delete tag current))
14359 (setq res t)
14360 (push tag current))))
14361 (end-of-line 1)
14362 (if current
14363 (progn
14364 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14365 (org-set-tags nil t))
14366 (delete-horizontal-space))
14367 (run-hooks 'org-after-tags-change-hook))
14368 res))
14370 (defun org-align-tags-here (to-col)
14371 ;; Assumes that this is a headline
14372 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14373 (beginning-of-line 1)
14374 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14375 (< pos (match-beginning 2)))
14376 (progn
14377 (setq tags-l (- (match-end 2) (match-beginning 2)))
14378 (goto-char (match-beginning 1))
14379 (insert " ")
14380 (delete-region (point) (1+ (match-beginning 2)))
14381 (setq ncol (max (current-column)
14382 (1+ col)
14383 (if (> to-col 0)
14384 to-col
14385 (- (abs to-col) tags-l))))
14386 (setq p (point))
14387 (insert (make-string (- ncol (current-column)) ?\ ))
14388 (setq ncol (current-column))
14389 (when indent-tabs-mode (tabify p (point-at-eol)))
14390 (org-move-to-column (min ncol col) t))
14391 (goto-char pos))))
14393 (defun org-set-tags-command (&optional arg just-align)
14394 "Call the set-tags command for the current entry."
14395 (interactive "P")
14396 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14397 (org-set-tags arg just-align)
14398 (save-excursion
14399 (unless (and (org-region-active-p)
14400 org-loop-over-headlines-in-active-region)
14401 (org-back-to-heading t))
14402 (org-set-tags arg just-align))))
14404 (defun org-set-tags-to (data)
14405 "Set the tags of the current entry to DATA, replacing the current tags.
14406 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14407 If DATA is nil or the empty string, any tags will be removed."
14408 (interactive "sTags: ")
14409 (setq data
14410 (cond
14411 ((eq data nil) "")
14412 ((equal data "") "")
14413 ((stringp data)
14414 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14415 ":"))
14416 ((listp data)
14417 (concat ":" (mapconcat 'identity data ":") ":"))))
14418 (when data
14419 (save-excursion
14420 (org-back-to-heading t)
14421 (when (looking-at org-complex-heading-regexp)
14422 (if (match-end 5)
14423 (progn
14424 (goto-char (match-beginning 5))
14425 (insert data)
14426 (delete-region (point) (point-at-eol))
14427 (org-set-tags nil 'align))
14428 (goto-char (point-at-eol))
14429 (insert " " data)
14430 (org-set-tags nil 'align)))
14431 (beginning-of-line 1)
14432 (if (looking-at ".*?\\([ \t]+\\)$")
14433 (delete-region (match-beginning 1) (match-end 1))))))
14435 (defun org-align-all-tags ()
14436 "Align the tags i all headings."
14437 (interactive)
14438 (save-excursion
14439 (or (ignore-errors (org-back-to-heading t))
14440 (outline-next-heading))
14441 (if (org-at-heading-p)
14442 (org-set-tags t)
14443 (message "No headings"))))
14445 (defvar org-indent-indentation-per-level)
14446 (defun org-set-tags (&optional arg just-align)
14447 "Set the tags for the current headline.
14448 With prefix ARG, realign all tags in headings in the current buffer."
14449 (interactive "P")
14450 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14451 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14452 'region-start-level 'region))
14453 org-loop-over-headlines-in-active-region)
14454 (org-map-entries
14455 ;; We don't use ARG and JUST-ALIGN here these args are not
14456 ;; useful when looping over headlines
14457 `(org-set-tags)
14458 org-loop-over-headlines-in-active-region
14459 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14460 (let* ((re org-outline-regexp-bol)
14461 (current (unless arg (org-get-tags-string)))
14462 (col (current-column))
14463 (org-setting-tags t)
14464 table current-tags inherited-tags ; computed below when needed
14465 tags p0 c0 c1 rpl di tc level)
14466 (if arg
14467 (save-excursion
14468 (goto-char (point-min))
14469 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14470 (while (re-search-forward re nil t)
14471 (org-set-tags nil t)
14472 (end-of-line 1)))
14473 (message "All tags realigned to column %d" org-tags-column))
14474 (if just-align
14475 (setq tags current)
14476 ;; Get a new set of tags from the user
14477 (save-excursion
14478 (setq table (append org-tag-persistent-alist
14479 (or org-tag-alist (org-get-buffer-tags))
14480 (and
14481 org-complete-tags-always-offer-all-agenda-tags
14482 (org-global-tags-completion-table
14483 (org-agenda-files))))
14484 org-last-tags-completion-table table
14485 current-tags (org-split-string current ":")
14486 inherited-tags (nreverse
14487 (nthcdr (length current-tags)
14488 (nreverse (org-get-tags-at))))
14489 tags
14490 (if (or (eq t org-use-fast-tag-selection)
14491 (and org-use-fast-tag-selection
14492 (delq nil (mapcar 'cdr table))))
14493 (org-fast-tag-selection
14494 current-tags inherited-tags table
14495 (if org-fast-tag-selection-include-todo
14496 org-todo-key-alist))
14497 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14498 (org-trim
14499 (org-icompleting-read "Tags: "
14500 'org-tags-completion-function
14501 nil nil current 'org-tags-history))))))
14502 (while (string-match "[-+&]+" tags)
14503 ;; No boolean logic, just a list
14504 (setq tags (replace-match ":" t t tags))))
14506 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14508 (if org-tags-sort-function
14509 (setq tags (mapconcat 'identity
14510 (sort (org-split-string
14511 tags (org-re "[^[:alnum:]_@#%]+"))
14512 org-tags-sort-function) ":")))
14514 (if (string-match "\\`[\t ]*\\'" tags)
14515 (setq tags "")
14516 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14517 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14519 ;; Insert new tags at the correct column
14520 (beginning-of-line 1)
14521 (setq level (or (and (looking-at org-outline-regexp)
14522 (- (match-end 0) (point) 1))
14524 (cond
14525 ((and (equal current "") (equal tags "")))
14526 ((re-search-forward
14527 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14528 (point-at-eol) t)
14529 (if (equal tags "")
14530 (setq rpl "")
14531 (goto-char (match-beginning 0))
14532 (setq c0 (current-column)
14533 ;; compute offset for the case of org-indent-mode active
14534 di (if org-indent-mode
14535 (* (1- org-indent-indentation-per-level) (1- level))
14537 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14538 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14539 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14540 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14541 (replace-match rpl t t)
14542 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14543 tags)
14544 (t (error "Tags alignment failed")))
14545 (org-move-to-column col)
14546 (unless just-align
14547 (run-hooks 'org-after-tags-change-hook))))))
14549 (defun org-change-tag-in-region (beg end tag off)
14550 "Add or remove TAG for each entry in the region.
14551 This works in the agenda, and also in an org-mode buffer."
14552 (interactive
14553 (list (region-beginning) (region-end)
14554 (let ((org-last-tags-completion-table
14555 (if (derived-mode-p 'org-mode)
14556 (org-uniquify
14557 (delq nil (append (org-get-buffer-tags)
14558 (org-global-tags-completion-table))))
14559 (org-global-tags-completion-table))))
14560 (org-icompleting-read
14561 "Tag: " 'org-tags-completion-function nil nil nil
14562 'org-tags-history))
14563 (progn
14564 (message "[s]et or [r]emove? ")
14565 (equal (read-char-exclusive) ?r))))
14566 (if (fboundp 'deactivate-mark) (deactivate-mark))
14567 (let ((agendap (equal major-mode 'org-agenda-mode))
14568 l1 l2 m buf pos newhead (cnt 0))
14569 (goto-char end)
14570 (setq l2 (1- (org-current-line)))
14571 (goto-char beg)
14572 (setq l1 (org-current-line))
14573 (loop for l from l1 to l2 do
14574 (org-goto-line l)
14575 (setq m (get-text-property (point) 'org-hd-marker))
14576 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14577 (and agendap m))
14578 (setq buf (if agendap (marker-buffer m) (current-buffer))
14579 pos (if agendap m (point)))
14580 (with-current-buffer buf
14581 (save-excursion
14582 (save-restriction
14583 (goto-char pos)
14584 (setq cnt (1+ cnt))
14585 (org-toggle-tag tag (if off 'off 'on))
14586 (setq newhead (org-get-heading)))))
14587 (and agendap (org-agenda-change-all-lines newhead m))))
14588 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14590 (defun org-tags-completion-function (string predicate &optional flag)
14591 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14592 (confirm (lambda (x) (stringp (car x)))))
14593 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14594 (setq s1 (match-string 1 string)
14595 s2 (match-string 2 string))
14596 (setq s1 "" s2 string))
14597 (cond
14598 ((eq flag nil)
14599 ;; try completion
14600 (setq rtn (try-completion s2 ctable confirm))
14601 (if (stringp rtn)
14602 (setq rtn
14603 (concat s1 s2 (substring rtn (length s2))
14604 (if (and org-add-colon-after-tag-completion
14605 (assoc rtn ctable))
14606 ":" ""))))
14607 rtn)
14608 ((eq flag t)
14609 ;; all-completions
14610 (all-completions s2 ctable confirm))
14611 ((eq flag 'lambda)
14612 ;; exact match?
14613 (assoc s2 ctable)))))
14615 (defun org-fast-tag-insert (kwd tags face &optional end)
14616 "Insert KDW, and the TAGS, the latter with face FACE.
14617 Also insert END."
14618 (insert (format "%-12s" (concat kwd ":"))
14619 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14620 (or end "")))
14622 (defun org-fast-tag-show-exit (flag)
14623 (save-excursion
14624 (org-goto-line 3)
14625 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14626 (replace-match ""))
14627 (when flag
14628 (end-of-line 1)
14629 (org-move-to-column (- (window-width) 19) t)
14630 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14632 (defun org-set-current-tags-overlay (current prefix)
14633 "Add an overlay to CURRENT tag with PREFIX."
14634 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14635 (if (featurep 'xemacs)
14636 (org-overlay-display org-tags-overlay (concat prefix s)
14637 'secondary-selection)
14638 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14639 (org-overlay-display org-tags-overlay (concat prefix s)))))
14641 (defvar org-last-tag-selection-key nil)
14642 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14643 "Fast tag selection with single keys.
14644 CURRENT is the current list of tags in the headline, INHERITED is the
14645 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14646 possibly with grouping information. TODO-TABLE is a similar table with
14647 TODO keywords, should these have keys assigned to them.
14648 If the keys are nil, a-z are automatically assigned.
14649 Returns the new tags string, or nil to not change the current settings."
14650 (let* ((fulltable (append table todo-table))
14651 (maxlen (apply 'max (mapcar
14652 (lambda (x)
14653 (if (stringp (car x)) (string-width (car x)) 0))
14654 fulltable)))
14655 (buf (current-buffer))
14656 (expert (eq org-fast-tag-selection-single-key 'expert))
14657 (buffer-tags nil)
14658 (fwidth (+ maxlen 3 1 3))
14659 (ncol (/ (- (window-width) 4) fwidth))
14660 (i-face 'org-done)
14661 (c-face 'org-todo)
14662 tg cnt e c char c1 c2 ntable tbl rtn
14663 ov-start ov-end ov-prefix
14664 (exit-after-next org-fast-tag-selection-single-key)
14665 (done-keywords org-done-keywords)
14666 groups ingroup)
14667 (save-excursion
14668 (beginning-of-line 1)
14669 (if (looking-at
14670 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14671 (setq ov-start (match-beginning 1)
14672 ov-end (match-end 1)
14673 ov-prefix "")
14674 (setq ov-start (1- (point-at-eol))
14675 ov-end (1+ ov-start))
14676 (skip-chars-forward "^\n\r")
14677 (setq ov-prefix
14678 (concat
14679 (buffer-substring (1- (point)) (point))
14680 (if (> (current-column) org-tags-column)
14682 (make-string (- org-tags-column (current-column)) ?\ ))))))
14683 (move-overlay org-tags-overlay ov-start ov-end)
14684 (save-window-excursion
14685 (if expert
14686 (set-buffer (get-buffer-create " *Org tags*"))
14687 (delete-other-windows)
14688 (split-window-vertically)
14689 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14690 (erase-buffer)
14691 (org-set-local 'org-done-keywords done-keywords)
14692 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14693 (org-fast-tag-insert "Current" current c-face "\n\n")
14694 (org-fast-tag-show-exit exit-after-next)
14695 (org-set-current-tags-overlay current ov-prefix)
14696 (setq tbl fulltable char ?a cnt 0)
14697 (while (setq e (pop tbl))
14698 (cond
14699 ((equal (car e) :startgroup)
14700 (push '() groups) (setq ingroup t)
14701 (when (not (= cnt 0))
14702 (setq cnt 0)
14703 (insert "\n"))
14704 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14705 ((equal (car e) :endgroup)
14706 (setq ingroup nil cnt 0)
14707 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14708 ((equal e '(:newline))
14709 (when (not (= cnt 0))
14710 (setq cnt 0)
14711 (insert "\n")
14712 (setq e (car tbl))
14713 (while (equal (car tbl) '(:newline))
14714 (insert "\n")
14715 (setq tbl (cdr tbl)))))
14716 ((equal e '(:grouptags)) nil)
14718 (setq tg (copy-sequence (car e)) c2 nil)
14719 (if (cdr e)
14720 (setq c (cdr e))
14721 ;; automatically assign a character.
14722 (setq c1 (string-to-char
14723 (downcase (substring
14724 tg (if (= (string-to-char tg) ?@) 1 0)))))
14725 (if (or (rassoc c1 ntable) (rassoc c1 table))
14726 (while (or (rassoc char ntable) (rassoc char table))
14727 (setq char (1+ char)))
14728 (setq c2 c1))
14729 (setq c (or c2 char)))
14730 (if ingroup (push tg (car groups)))
14731 (setq tg (org-add-props tg nil 'face
14732 (cond
14733 ((not (assoc tg table))
14734 (org-get-todo-face tg))
14735 ((member tg current) c-face)
14736 ((member tg inherited) i-face))))
14737 (if (equal (caar tbl) :grouptags)
14738 (org-add-props tg nil 'face 'org-tag-group))
14739 (if (and (= cnt 0) (not ingroup)) (insert " "))
14740 (insert "[" c "] " tg (make-string
14741 (- fwidth 4 (length tg)) ?\ ))
14742 (push (cons tg c) ntable)
14743 (when (= (setq cnt (1+ cnt)) ncol)
14744 (insert "\n")
14745 (if ingroup (insert " "))
14746 (setq cnt 0)))))
14747 (setq ntable (nreverse ntable))
14748 (insert "\n")
14749 (goto-char (point-min))
14750 (if (not expert) (org-fit-window-to-buffer))
14751 (setq rtn
14752 (catch 'exit
14753 (while t
14754 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14755 (if (not groups) "no " "")
14756 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14757 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14758 (setq org-last-tag-selection-key c)
14759 (cond
14760 ((= c ?\r) (throw 'exit t))
14761 ((= c ?!)
14762 (setq groups (not groups))
14763 (goto-char (point-min))
14764 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14765 ((= c ?\C-c)
14766 (if (not expert)
14767 (org-fast-tag-show-exit
14768 (setq exit-after-next (not exit-after-next)))
14769 (setq expert nil)
14770 (delete-other-windows)
14771 (set-window-buffer (split-window-vertically) " *Org tags*")
14772 (org-switch-to-buffer-other-window " *Org tags*")
14773 (org-fit-window-to-buffer)))
14774 ((or (= c ?\C-g)
14775 (and (= c ?q) (not (rassoc c ntable))))
14776 (org-detach-overlay org-tags-overlay)
14777 (setq quit-flag t))
14778 ((= c ?\ )
14779 (setq current nil)
14780 (if exit-after-next (setq exit-after-next 'now)))
14781 ((= c ?\t)
14782 (condition-case nil
14783 (setq tg (org-icompleting-read
14784 "Tag: "
14785 (or buffer-tags
14786 (with-current-buffer buf
14787 (org-get-buffer-tags)))))
14788 (quit (setq tg "")))
14789 (when (string-match "\\S-" tg)
14790 (add-to-list 'buffer-tags (list tg))
14791 (if (member tg current)
14792 (setq current (delete tg current))
14793 (push tg current)))
14794 (if exit-after-next (setq exit-after-next 'now)))
14795 ((setq e (rassoc c todo-table) tg (car e))
14796 (with-current-buffer buf
14797 (save-excursion (org-todo tg)))
14798 (if exit-after-next (setq exit-after-next 'now)))
14799 ((setq e (rassoc c ntable) tg (car e))
14800 (if (member tg current)
14801 (setq current (delete tg current))
14802 (loop for g in groups do
14803 (if (member tg g)
14804 (mapc (lambda (x)
14805 (setq current (delete x current)))
14806 g)))
14807 (push tg current))
14808 (if exit-after-next (setq exit-after-next 'now))))
14810 ;; Create a sorted list
14811 (setq current
14812 (sort current
14813 (lambda (a b)
14814 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14815 (if (eq exit-after-next 'now) (throw 'exit t))
14816 (goto-char (point-min))
14817 (beginning-of-line 2)
14818 (delete-region (point) (point-at-eol))
14819 (org-fast-tag-insert "Current" current c-face)
14820 (org-set-current-tags-overlay current ov-prefix)
14821 (while (re-search-forward
14822 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14823 (setq tg (match-string 1))
14824 (add-text-properties
14825 (match-beginning 1) (match-end 1)
14826 (list 'face
14827 (cond
14828 ((member tg current) c-face)
14829 ((member tg inherited) i-face)
14830 (t (get-text-property (match-beginning 1) 'face))))))
14831 (goto-char (point-min)))))
14832 (org-detach-overlay org-tags-overlay)
14833 (if rtn
14834 (mapconcat 'identity current ":")
14835 nil))))
14837 (defun org-get-tags-string ()
14838 "Get the TAGS string in the current headline."
14839 (unless (org-at-heading-p t)
14840 (user-error "Not on a heading"))
14841 (save-excursion
14842 (beginning-of-line 1)
14843 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14844 (org-match-string-no-properties 1)
14845 "")))
14847 (defun org-get-tags ()
14848 "Get the list of tags specified in the current headline."
14849 (org-split-string (org-get-tags-string) ":"))
14851 (defun org-get-buffer-tags ()
14852 "Get a table of all tags used in the buffer, for completion."
14853 (let (tags)
14854 (save-excursion
14855 (goto-char (point-min))
14856 (while (re-search-forward
14857 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14858 (when (equal (char-after (point-at-bol 0)) ?*)
14859 (mapc (lambda (x) (add-to-list 'tags x))
14860 (org-split-string (org-match-string-no-properties 1) ":")))))
14861 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14862 (mapcar 'list tags)))
14864 ;;;; The mapping API
14866 (defun org-map-entries (func &optional match scope &rest skip)
14867 "Call FUNC at each headline selected by MATCH in SCOPE.
14869 FUNC is a function or a lisp form. The function will be called without
14870 arguments, with the cursor positioned at the beginning of the headline.
14871 The return values of all calls to the function will be collected and
14872 returned as a list.
14874 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14875 does not need to preserve point. After evaluation, the cursor will be
14876 moved to the end of the line (presumably of the headline of the
14877 processed entry) and search continues from there. Under some
14878 circumstances, this may not produce the wanted results. For example,
14879 if you have removed (e.g. archived) the current (sub)tree it could
14880 mean that the next entry will be skipped entirely. In such cases, you
14881 can specify the position from where search should continue by making
14882 FUNC set the variable `org-map-continue-from' to the desired buffer
14883 position.
14885 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14886 Only headlines that are matched by this query will be considered during
14887 the iteration. When MATCH is nil or t, all headlines will be
14888 visited by the iteration.
14890 SCOPE determines the scope of this command. It can be any of:
14892 nil The current buffer, respecting the restriction if any
14893 tree The subtree started with the entry at point
14894 region The entries within the active region, if any
14895 region-start-level
14896 The entries within the active region, but only those at
14897 the same level than the first one.
14898 file The current buffer, without restriction
14899 file-with-archives
14900 The current buffer, and any archives associated with it
14901 agenda All agenda files
14902 agenda-with-archives
14903 All agenda files with any archive files associated with them
14904 \(file1 file2 ...)
14905 If this is a list, all files in the list will be scanned
14907 The remaining args are treated as settings for the skipping facilities of
14908 the scanner. The following items can be given here:
14910 archive skip trees with the archive tag
14911 comment skip trees with the COMMENT keyword
14912 function or Emacs Lisp form:
14913 will be used as value for `org-agenda-skip-function', so
14914 whenever the function returns a position, FUNC will not be
14915 called for that entry and search will continue from the
14916 position returned
14918 If your function needs to retrieve the tags including inherited tags
14919 at the *current* entry, you can use the value of the variable
14920 `org-scanner-tags' which will be much faster than getting the value
14921 with `org-get-tags-at'. If your function gets properties with
14922 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14923 to t around the call to `org-entry-properties' to get the same speedup.
14924 Note that if your function moves around to retrieve tags and properties at
14925 a *different* entry, you cannot use these techniques."
14926 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14927 (not (org-region-active-p)))
14928 (let* ((org-agenda-archives-mode nil) ; just to make sure
14929 (org-agenda-skip-archived-trees (memq 'archive skip))
14930 (org-agenda-skip-comment-trees (memq 'comment skip))
14931 (org-agenda-skip-function
14932 (car (org-delete-all '(comment archive) skip)))
14933 (org-tags-match-list-sublevels t)
14934 (start-level (eq scope 'region-start-level))
14935 matcher file res
14936 org-todo-keywords-for-agenda
14937 org-done-keywords-for-agenda
14938 org-todo-keyword-alist-for-agenda
14939 org-tag-alist-for-agenda
14940 todo-only)
14942 (cond
14943 ((eq match t) (setq matcher t))
14944 ((eq match nil) (setq matcher t))
14945 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14947 (save-window-excursion
14948 (save-restriction
14949 (cond ((eq scope 'tree)
14950 (org-back-to-heading t)
14951 (org-narrow-to-subtree)
14952 (setq scope nil))
14953 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14954 (org-region-active-p))
14955 ;; If needed, set start-level to a string like "2"
14956 (when start-level
14957 (save-excursion
14958 (goto-char (region-beginning))
14959 (unless (org-at-heading-p) (outline-next-heading))
14960 (setq start-level (org-current-level))))
14961 (narrow-to-region (region-beginning)
14962 (save-excursion
14963 (goto-char (region-end))
14964 (unless (and (bolp) (org-at-heading-p))
14965 (outline-next-heading))
14966 (point)))
14967 (setq scope nil)))
14969 (if (not scope)
14970 (progn
14971 (org-agenda-prepare-buffers
14972 (list (buffer-file-name (current-buffer))))
14973 (setq res (org-scan-tags func matcher todo-only start-level)))
14974 ;; Get the right scope
14975 (cond
14976 ((and scope (listp scope) (symbolp (car scope)))
14977 (setq scope (eval scope)))
14978 ((eq scope 'agenda)
14979 (setq scope (org-agenda-files t)))
14980 ((eq scope 'agenda-with-archives)
14981 (setq scope (org-agenda-files t))
14982 (setq scope (org-add-archive-files scope)))
14983 ((eq scope 'file)
14984 (setq scope (list (buffer-file-name))))
14985 ((eq scope 'file-with-archives)
14986 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14987 (org-agenda-prepare-buffers scope)
14988 (while (setq file (pop scope))
14989 (with-current-buffer (org-find-base-buffer-visiting file)
14990 (save-excursion
14991 (save-restriction
14992 (widen)
14993 (goto-char (point-min))
14994 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14995 res)))
14997 ;;;; Properties
14999 ;;; Setting and retrieving properties
15001 (defconst org-special-properties
15002 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15003 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15004 "The special properties valid in Org-mode.
15006 These are properties that are not defined in the property drawer,
15007 but in some other way.")
15009 (defconst org-default-properties
15010 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15011 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15012 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15013 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15014 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15015 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15016 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15017 "Some properties that are used by Org-mode for various purposes.
15018 Being in this list makes sure that they are offered for completion.")
15020 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15021 "Regular expression matching the first line of a property drawer.")
15023 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15024 "Regular expression matching the last line of a property drawer.")
15026 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15027 "Regular expression matching the first line of a property drawer.")
15029 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15030 "Regular expression matching the first line of a property drawer.")
15032 (defconst org-property-drawer-re
15033 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
15034 org-property-end-re "\\)\n?")
15035 "Matches an entire property drawer.")
15037 (defconst org-clock-drawer-re
15038 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
15039 org-property-end-re "\\)\n?")
15040 "Matches an entire clock drawer.")
15042 (defun org-property-action ()
15043 "Do an action on properties."
15044 (interactive)
15045 (let (c)
15046 (org-at-property-p)
15047 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15048 (setq c (read-char-exclusive))
15049 (cond
15050 ((equal c ?s)
15051 (call-interactively 'org-set-property))
15052 ((equal c ?d)
15053 (call-interactively 'org-delete-property))
15054 ((equal c ?D)
15055 (call-interactively 'org-delete-property-globally))
15056 ((equal c ?c)
15057 (call-interactively 'org-compute-property-at-point))
15058 (t (user-error "No such property action %c" c)))))
15060 (defun org-inc-effort ()
15061 "Increment the value of the effort property in the current entry."
15062 (interactive)
15063 (org-set-effort nil t))
15065 (defvar org-clock-effort) ;; Defined in org-clock.el
15066 (defvar org-clock-current-task) ;; Defined in org-clock.el
15067 (defun org-set-effort (&optional value increment)
15068 "Set the effort property of the current entry.
15069 With numerical prefix arg, use the nth allowed value, 0 stands for the
15070 10th allowed value.
15072 When INCREMENT is non-nil, set the property to the next allowed value."
15073 (interactive "P")
15074 (if (equal value 0) (setq value 10))
15075 (let* ((completion-ignore-case t)
15076 (prop org-effort-property)
15077 (cur (org-entry-get nil prop))
15078 (allowed (org-property-get-allowed-values nil prop 'table))
15079 (existing (mapcar 'list (org-property-values prop)))
15080 (heading (nth 4 (org-heading-components)))
15082 (val (cond
15083 ((stringp value) value)
15084 ((and allowed (integerp value))
15085 (or (car (nth (1- value) allowed))
15086 (car (org-last allowed))))
15087 ((and allowed increment)
15088 (or (caadr (member (list cur) allowed))
15089 (user-error "Allowed effort values are not set")))
15090 (allowed
15091 (message "Select 1-9,0, [RET%s]: %s"
15092 (if cur (concat "=" cur) "")
15093 (mapconcat 'car allowed " "))
15094 (setq rpl (read-char-exclusive))
15095 (if (equal rpl ?\r)
15097 (setq rpl (- rpl ?0))
15098 (if (equal rpl 0) (setq rpl 10))
15099 (if (and (> rpl 0) (<= rpl (length allowed)))
15100 (car (nth (1- rpl) allowed))
15101 (org-completing-read "Effort: " allowed nil))))
15103 (let (org-completion-use-ido org-completion-use-iswitchb)
15104 (org-completing-read
15105 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15106 (concat "[" cur "]") "")
15107 ": ")
15108 existing nil nil "" nil cur))))))
15109 (unless (equal (org-entry-get nil prop) val)
15110 (org-entry-put nil prop val))
15111 (save-excursion
15112 (org-back-to-heading t)
15113 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15114 (when (string= heading org-clock-current-task)
15115 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15116 (org-clock-update-mode-line))
15117 (message "%s is now %s" prop val)))
15119 (defun org-at-property-p ()
15120 "Is cursor inside a property drawer?"
15121 (save-excursion
15122 (when (equal 'node-property (car (org-element-at-point)))
15123 (beginning-of-line 1)
15124 (looking-at org-property-re))))
15126 (defun org-get-property-block (&optional beg end force)
15127 "Return the (beg . end) range of the body of the property drawer.
15128 BEG and END are the beginning and end of the current subtree, or of
15129 the part before the first headline. If they are not given, they will
15130 be found. If the drawer does not exist and FORCE is non-nil, create
15131 the drawer."
15132 (catch 'exit
15133 (save-excursion
15134 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15135 (progn (org-back-to-heading t) (point))))
15136 (end (or end (and (not (outline-next-heading)) (point-max))
15137 (point))))
15138 (goto-char beg)
15139 (if (re-search-forward org-property-start-re end t)
15140 (setq beg (1+ (match-end 0)))
15141 (if force
15142 (save-excursion
15143 (org-insert-property-drawer)
15144 (setq end (progn (outline-next-heading) (point))))
15145 (throw 'exit nil))
15146 (goto-char beg)
15147 (if (re-search-forward org-property-start-re end t)
15148 (setq beg (1+ (match-end 0)))))
15149 (if (re-search-forward org-property-end-re end t)
15150 (setq end (match-beginning 0))
15151 (or force (throw 'exit nil))
15152 (goto-char beg)
15153 (setq end beg)
15154 (org-indent-line)
15155 (insert ":END:\n"))
15156 (cons beg end)))))
15158 (defun org-entry-properties (&optional pom which specific)
15159 "Get all properties of the entry at point-or-marker POM.
15160 This includes the TODO keyword, the tags, time strings for deadline,
15161 scheduled, and clocking, and any additional properties defined in the
15162 entry. The return value is an alist, keys may occur multiple times
15163 if the property key was used several times.
15164 POM may also be nil, in which case the current entry is used.
15165 If WHICH is nil or `all', get all properties. If WHICH is
15166 `special' or `standard', only get that subclass. If WHICH
15167 is a string only get exactly this property. SPECIFIC can be a string, the
15168 specific property we are interested in. Specifying it can speed
15169 things up because then unnecessary parsing is avoided."
15170 (setq which (or which 'all))
15171 (org-with-point-at pom
15172 (let ((clockstr (substring org-clock-string 0 -1))
15173 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15174 (case-fold-search nil)
15175 beg end range props sum-props key key1 value string clocksum clocksumt)
15176 (save-excursion
15177 (when (condition-case nil
15178 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15179 (error nil))
15180 (setq beg (point))
15181 (setq sum-props (get-text-property (point) 'org-summaries))
15182 (setq clocksum (get-text-property (point) :org-clock-minutes)
15183 clocksumt (get-text-property (point) :org-clock-minutes-today))
15184 (outline-next-heading)
15185 (setq end (point))
15186 (when (memq which '(all special))
15187 ;; Get the special properties, like TODO and tags
15188 (goto-char beg)
15189 (when (and (or (not specific) (string= specific "TODO"))
15190 (looking-at org-todo-line-regexp) (match-end 2))
15191 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15192 (when (and (or (not specific) (string= specific "PRIORITY"))
15193 (looking-at org-priority-regexp))
15194 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15195 (when (or (not specific) (string= specific "FILE"))
15196 (push (cons "FILE" buffer-file-name) props))
15197 (when (and (or (not specific) (string= specific "TAGS"))
15198 (setq value (org-get-tags-string))
15199 (string-match "\\S-" value))
15200 (push (cons "TAGS" value) props))
15201 (when (and (or (not specific) (string= specific "ALLTAGS"))
15202 (setq value (org-get-tags-at)))
15203 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15204 ":"))
15205 props))
15206 (when (or (not specific) (string= specific "BLOCKED"))
15207 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15208 (when (or (not specific)
15209 (member specific
15210 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15211 "TIMESTAMP" "TIMESTAMP_IA")))
15212 (catch 'match
15213 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15214 (setq key (if (match-end 1)
15215 (substring (org-match-string-no-properties 1)
15216 0 -1))
15217 string (if (equal key clockstr)
15218 (org-trim
15219 (buffer-substring-no-properties
15220 (match-beginning 3) (goto-char
15221 (point-at-eol))))
15222 (substring (org-match-string-no-properties 3)
15223 1 -1)))
15224 ;; Get the correct property name from the key. This is
15225 ;; necessary if the user has configured time keywords.
15226 (setq key1 (concat key ":"))
15227 (cond
15228 ((not key)
15229 (setq key
15230 (if (= (char-after (match-beginning 3)) ?\[)
15231 "TIMESTAMP_IA" "TIMESTAMP")))
15232 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15233 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15234 ((equal key1 org-closed-string) (setq key "CLOSED"))
15235 ((equal key1 org-clock-string) (setq key "CLOCK")))
15236 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15237 (progn
15238 (push (cons key string) props)
15239 ;; no need to search further if match is found
15240 (throw 'match t))
15241 (when (or (equal key "CLOCK") (not (assoc key props)))
15242 (push (cons key string) props)))))))
15244 (when (memq which '(all standard))
15245 ;; Get the standard properties, like :PROP: ...
15246 (setq range (org-get-property-block beg end))
15247 (when range
15248 (goto-char (car range))
15249 (while (re-search-forward org-property-re
15250 (cdr range) t)
15251 (setq key (org-match-string-no-properties 2)
15252 value (org-trim (or (org-match-string-no-properties 3) "")))
15253 (unless (member key excluded)
15254 (push (cons key (or value "")) props)))))
15255 (if clocksum
15256 (push (cons "CLOCKSUM"
15257 (org-columns-number-to-string (/ (float clocksum) 60.)
15258 'add_times))
15259 props))
15260 (if clocksumt
15261 (push (cons "CLOCKSUM_T"
15262 (org-columns-number-to-string (/ (float clocksumt) 60.)
15263 'add_times))
15264 props))
15265 (unless (assoc "CATEGORY" props)
15266 (push (cons "CATEGORY" (org-get-category)) props))
15267 (append sum-props (nreverse props)))))))
15269 (defun org-entry-get (pom property &optional inherit literal-nil)
15270 "Get value of PROPERTY for entry or content at point-or-marker POM.
15271 If INHERIT is non-nil and the entry does not have the property,
15272 then also check higher levels of the hierarchy.
15273 If INHERIT is the symbol `selective', use inheritance only if the setting
15274 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15275 If the property is present but empty, the return value is the empty string.
15276 If the property is not present at all, nil is returned.
15278 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15279 do not interpret it as the list atom nil. This is used for inheritance
15280 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15281 (org-with-point-at pom
15282 (if (and inherit (if (eq inherit 'selective)
15283 (org-property-inherit-p property)
15285 (org-entry-get-with-inheritance property literal-nil)
15286 (if (member property org-special-properties)
15287 ;; We need a special property. Use `org-entry-properties' to
15288 ;; retrieve it, but specify the wanted property
15289 (cdr (assoc property (org-entry-properties nil 'special property)))
15290 (let ((range (org-get-property-block)))
15291 (when (and range (not (eq (car range) (cdr range))))
15292 (let* ((props (list (or (assoc property org-file-properties)
15293 (assoc property org-global-properties)
15294 (assoc property org-global-properties-fixed))))
15295 (ap (lambda (key)
15296 (when (re-search-forward
15297 (org-re-property key) (cdr range) t)
15298 (setq props
15299 (org-update-property-plist
15301 (if (match-end 3)
15302 (org-match-string-no-properties 3) "")
15303 props)))))
15304 val)
15305 (goto-char (car range))
15306 (funcall ap property)
15307 (goto-char (car range))
15308 (while (funcall ap (concat property "+")))
15309 (setq val (cdr (assoc property props)))
15310 (when val (if literal-nil val (org-not-nil val))))))))))
15312 (defun org-property-or-variable-value (var &optional inherit)
15313 "Check if there is a property fixing the value of VAR.
15314 If yes, return this value. If not, return the current value of the variable."
15315 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15316 (if (and prop (stringp prop) (string-match "\\S-" prop))
15317 (read prop)
15318 (symbol-value var))))
15320 (defun org-entry-delete (pom property)
15321 "Delete the property PROPERTY from entry at point-or-marker POM."
15322 (unless (member property org-special-properties)
15323 (org-with-point-at pom
15324 (let ((range (org-get-property-block)))
15325 (if (and range
15326 (goto-char (car range))
15327 (re-search-forward
15328 (org-re-property property)
15329 (cdr range) t))
15330 (progn
15331 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15332 (org-remove-empty-drawer-at (car range))
15334 nil)))))
15336 ;; Multi-values properties are properties that contain multiple values
15337 ;; These values are assumed to be single words, separated by whitespace.
15338 (defun org-entry-add-to-multivalued-property (pom property value)
15339 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15340 (let* ((old (org-entry-get pom property))
15341 (values (and old (org-split-string old "[ \t]"))))
15342 (setq value (org-entry-protect-space value))
15343 (unless (member value values)
15344 (setq values (append values (list value)))
15345 (org-entry-put pom property
15346 (mapconcat 'identity values " ")))))
15348 (defun org-entry-remove-from-multivalued-property (pom property value)
15349 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15350 (let* ((old (org-entry-get pom property))
15351 (values (and old (org-split-string old "[ \t]"))))
15352 (setq value (org-entry-protect-space value))
15353 (when (member value values)
15354 (setq values (delete value values))
15355 (org-entry-put pom property
15356 (mapconcat 'identity values " ")))))
15358 (defun org-entry-member-in-multivalued-property (pom property value)
15359 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15360 (let* ((old (org-entry-get pom property))
15361 (values (and old (org-split-string old "[ \t]"))))
15362 (setq value (org-entry-protect-space value))
15363 (member value values)))
15365 (defun org-entry-get-multivalued-property (pom property)
15366 "Return a list of values in a multivalued property."
15367 (let* ((value (org-entry-get pom property))
15368 (values (and value (org-split-string value "[ \t]"))))
15369 (mapcar 'org-entry-restore-space values)))
15371 (defun org-entry-put-multivalued-property (pom property &rest values)
15372 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15373 VALUES should be a list of strings. Spaces will be protected."
15374 (org-entry-put pom property
15375 (mapconcat 'org-entry-protect-space values " "))
15376 (let* ((value (org-entry-get pom property))
15377 (values (and value (org-split-string value "[ \t]"))))
15378 (mapcar 'org-entry-restore-space values)))
15380 (defun org-entry-protect-space (s)
15381 "Protect spaces and newline in string S."
15382 (while (string-match " " s)
15383 (setq s (replace-match "%20" t t s)))
15384 (while (string-match "\n" s)
15385 (setq s (replace-match "%0A" t t s)))
15388 (defun org-entry-restore-space (s)
15389 "Restore spaces and newline in string S."
15390 (while (string-match "%20" s)
15391 (setq s (replace-match " " t t s)))
15392 (while (string-match "%0A" s)
15393 (setq s (replace-match "\n" t t s)))
15396 (defvar org-entry-property-inherited-from (make-marker)
15397 "Marker pointing to the entry from where a property was inherited.
15398 Each call to `org-entry-get-with-inheritance' will set this marker to the
15399 location of the entry where the inheritance search matched. If there was
15400 no match, the marker will point nowhere.
15401 Note that also `org-entry-get' calls this function, if the INHERIT flag
15402 is set.")
15404 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15405 "Get PROPERTY of entry or content at point, search higher levels if needed.
15406 The search will stop at the first ancestor which has the property defined.
15407 If the value found is \"nil\", return nil to show that the property
15408 should be considered as undefined (this is the meaning of nil here).
15409 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15410 (move-marker org-entry-property-inherited-from nil)
15411 (let (tmp)
15412 (save-excursion
15413 (save-restriction
15414 (widen)
15415 (catch 'ex
15416 (while t
15417 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15418 (or (ignore-errors (org-back-to-heading t))
15419 (goto-char (point-min)))
15420 (move-marker org-entry-property-inherited-from (point))
15421 (throw 'ex tmp))
15422 (or (ignore-errors (org-up-heading-safe))
15423 (throw 'ex nil))))))
15424 (setq tmp (or tmp
15425 (cdr (assoc property org-file-properties))
15426 (cdr (assoc property org-global-properties))
15427 (cdr (assoc property org-global-properties-fixed))))
15428 (if literal-nil tmp (org-not-nil tmp))))
15430 (defvar org-property-changed-functions nil
15431 "Hook called when the value of a property has changed.
15432 Each hook function should accept two arguments, the name of the property
15433 and the new value.")
15435 (defun org-entry-put (pom property value)
15436 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15437 (org-with-point-at pom
15438 (org-back-to-heading t)
15439 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15440 range)
15441 (cond
15442 ((equal property "TODO")
15443 (when (and (stringp value) (string-match "\\S-" value)
15444 (not (member value org-todo-keywords-1)))
15445 (user-error "\"%s\" is not a valid TODO state" value))
15446 (if (or (not value)
15447 (not (string-match "\\S-" value)))
15448 (setq value 'none))
15449 (org-todo value)
15450 (org-set-tags nil 'align))
15451 ((equal property "PRIORITY")
15452 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15453 (string-to-char value) ?\ ))
15454 (org-set-tags nil 'align))
15455 ((equal property "CLOCKSUM")
15456 (if (not (re-search-forward
15457 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15458 (error "Cannot find a clock log")
15459 (goto-char (- (match-end 1) 2))
15460 (cond
15461 ((eq value 'earlier) (org-timestamp-down))
15462 ((eq value 'later) (org-timestamp-up)))
15463 (org-clock-sum-current-item)))
15464 ((equal property "SCHEDULED")
15465 (if (re-search-forward org-scheduled-time-regexp end t)
15466 (cond
15467 ((eq value 'earlier) (org-timestamp-change -1 'day))
15468 ((eq value 'later) (org-timestamp-change 1 'day))
15469 (t (call-interactively 'org-schedule)))
15470 (call-interactively 'org-schedule)))
15471 ((equal property "DEADLINE")
15472 (if (re-search-forward org-deadline-time-regexp end t)
15473 (cond
15474 ((eq value 'earlier) (org-timestamp-change -1 'day))
15475 ((eq value 'later) (org-timestamp-change 1 'day))
15476 (t (call-interactively 'org-deadline)))
15477 (call-interactively 'org-deadline)))
15478 ((member property org-special-properties)
15479 (error "The %s property can not yet be set with `org-entry-put'"
15480 property))
15481 (t ; a non-special property
15482 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15483 (setq range (org-get-property-block beg end 'force))
15484 (goto-char (car range))
15485 (if (re-search-forward
15486 (org-re-property property) (cdr range) t)
15487 (progn
15488 (delete-region (match-beginning 0) (match-end 0))
15489 (goto-char (match-beginning 0)))
15490 (goto-char (cdr range))
15491 (insert "\n")
15492 (backward-char 1)
15493 (org-indent-line))
15494 (insert ":" property ":")
15495 (and value (insert " " value))
15496 (org-indent-line)))))
15497 (run-hook-with-args 'org-property-changed-functions property value)))
15499 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15500 "Get all property keys in the current buffer.
15501 With INCLUDE-SPECIALS, also list the special properties that reflect things
15502 like tags and TODO state.
15503 With INCLUDE-DEFAULTS, also include properties that has special meaning
15504 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15505 and others.
15506 With INCLUDE-COLUMNS, also include property names given in COLUMN
15507 formats in the current buffer."
15508 (let (rtn range cfmt s p)
15509 (save-excursion
15510 (save-restriction
15511 (widen)
15512 (goto-char (point-min))
15513 (while (re-search-forward org-property-start-re nil t)
15514 (setq range (org-get-property-block))
15515 (goto-char (car range))
15516 (while (re-search-forward org-property-re
15517 (cdr range) t)
15518 (add-to-list 'rtn (org-match-string-no-properties 2)))
15519 (outline-next-heading))))
15521 (when include-specials
15522 (setq rtn (append org-special-properties rtn)))
15524 (when include-defaults
15525 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15526 (add-to-list 'rtn org-effort-property))
15528 (when include-columns
15529 (save-excursion
15530 (save-restriction
15531 (widen)
15532 (goto-char (point-min))
15533 (while (re-search-forward
15534 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15535 nil t)
15536 (setq cfmt (match-string 2) s 0)
15537 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15538 cfmt s)
15539 (setq s (match-end 0)
15540 p (match-string 1 cfmt))
15541 (unless (or (equal p "ITEM")
15542 (member p org-special-properties))
15543 (add-to-list 'rtn (match-string 1 cfmt))))))))
15545 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15547 (defun org-property-values (key)
15548 "Return a list of all values of property KEY in the current buffer."
15549 (save-excursion
15550 (save-restriction
15551 (widen)
15552 (goto-char (point-min))
15553 (let ((re (org-re-property key))
15554 values)
15555 (while (re-search-forward re nil t)
15556 (add-to-list 'values (org-trim (match-string 3))))
15557 (delete "" values)))))
15559 (defun org-insert-property-drawer ()
15560 "Insert a property drawer into the current entry."
15561 (org-back-to-heading t)
15562 (looking-at org-outline-regexp)
15563 (let ((indent (if org-adapt-indentation
15564 (- (match-end 0) (match-beginning 0))
15566 (beg (point))
15567 (re (concat "^[ \t]*" org-keyword-time-regexp))
15568 end hiddenp)
15569 (outline-next-heading)
15570 (setq end (point))
15571 (goto-char beg)
15572 (while (re-search-forward re end t))
15573 (setq hiddenp (outline-invisible-p))
15574 (end-of-line 1)
15575 (and (equal (char-after) ?\n) (forward-char 1))
15576 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15577 (if (member (match-string 1) '("CLOCK:" ":END:"))
15578 ;; just skip this line
15579 (beginning-of-line 2)
15580 ;; Drawer start, find the end
15581 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15582 (beginning-of-line 1)))
15583 (org-skip-over-state-notes)
15584 (skip-chars-backward " \t\n\r")
15585 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15586 (forward-char 1))
15587 (goto-char (point-at-eol))
15588 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15589 (beginning-of-line 0)
15590 (org-indent-to-column indent)
15591 (beginning-of-line 2)
15592 (org-indent-to-column indent)
15593 (beginning-of-line 0)
15594 (if hiddenp
15595 (save-excursion
15596 (org-back-to-heading t)
15597 (hide-entry))
15598 (org-flag-drawer t))))
15600 (defun org-insert-drawer (&optional arg drawer)
15601 "Insert a drawer at point.
15603 Optional argument DRAWER, when non-nil, is a string representing
15604 drawer's name. Otherwise, the user is prompted for a name.
15606 If a region is active, insert the drawer around that region
15607 instead.
15609 Point is left between drawer's boundaries."
15610 (interactive "P")
15611 (let* ((drawer (if arg "PROPERTIES"
15612 (or drawer (read-from-minibuffer "Drawer: ")))))
15613 (cond
15614 ;; With C-u, fall back on `org-insert-property-drawer'
15615 (arg (org-insert-property-drawer))
15617 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15618 (user-error "Invalid drawer name"))
15619 ;; With an active region, insert a drawer at point.
15620 ((not (org-region-active-p))
15621 (progn
15622 (unless (bolp) (insert "\n"))
15623 (insert (format ":%s:\n\n:END:\n" drawer))
15624 (forward-line -2)))
15625 ;; Otherwise, insert the drawer at point
15627 (let ((rbeg (region-beginning))
15628 (rend (copy-marker (region-end))))
15629 (unwind-protect
15630 (progn
15631 (goto-char rbeg)
15632 (beginning-of-line)
15633 (when (save-excursion
15634 (re-search-forward org-outline-regexp-bol rend t))
15635 (user-error "Drawers cannot contain headlines"))
15636 ;; Position point at the beginning of the first
15637 ;; non-blank line in region. Insert drawer's opening
15638 ;; there, then indent it.
15639 (org-skip-whitespace)
15640 (beginning-of-line)
15641 (insert ":" drawer ":\n")
15642 (forward-line -1)
15643 (indent-for-tab-command)
15644 ;; Move point to the beginning of the first blank line
15645 ;; after the last non-blank line in region. Insert
15646 ;; drawer's closing, then indent it.
15647 (goto-char rend)
15648 (skip-chars-backward " \r\t\n")
15649 (insert "\n:END:")
15650 (deactivate-mark t)
15651 (indent-for-tab-command)
15652 (unless (eolp) (insert "\n")))
15653 ;; Clear marker, whatever the outcome of insertion is.
15654 (set-marker rend nil)))))))
15656 (defvar org-property-set-functions-alist nil
15657 "Property set function alist.
15658 Each entry should have the following format:
15660 (PROPERTY . READ-FUNCTION)
15662 The read function will be called with the same argument as
15663 `org-completing-read'.")
15665 (defun org-set-property-function (property)
15666 "Get the function that should be used to set PROPERTY.
15667 This is computed according to `org-property-set-functions-alist'."
15668 (or (cdr (assoc property org-property-set-functions-alist))
15669 'org-completing-read))
15671 (defun org-read-property-value (property)
15672 "Read PROPERTY value from user."
15673 (let* ((completion-ignore-case t)
15674 (allowed (org-property-get-allowed-values nil property 'table))
15675 (cur (org-entry-get nil property))
15676 (prompt (concat property " value"
15677 (if (and cur (string-match "\\S-" cur))
15678 (concat " [" cur "]") "") ": "))
15679 (set-function (org-set-property-function property))
15680 (val (if allowed
15681 (funcall set-function prompt allowed nil
15682 (not (get-text-property 0 'org-unrestricted
15683 (caar allowed))))
15684 (let (org-completion-use-ido org-completion-use-iswitchb)
15685 (funcall set-function prompt
15686 (mapcar 'list (org-property-values property))
15687 nil nil "" nil cur)))))
15688 (if (equal val "")
15690 val)))
15692 (defvar org-last-set-property nil)
15693 (defvar org-last-set-property-value nil)
15694 (defun org-read-property-name ()
15695 "Read a property name."
15696 (let* ((completion-ignore-case t)
15697 (keys (org-buffer-property-keys nil t t))
15698 (default-prop (or (save-excursion
15699 (save-match-data
15700 (beginning-of-line)
15701 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15702 (null (string= (match-string 1) "END"))
15703 (match-string 1))))
15704 org-last-set-property))
15705 (property (org-icompleting-read
15706 (concat "Property"
15707 (if default-prop (concat " [" default-prop "]") "")
15708 ": ")
15709 (mapcar 'list keys)
15710 nil nil nil nil
15711 default-prop)))
15712 (if (member property keys)
15713 property
15714 (or (cdr (assoc (downcase property)
15715 (mapcar (lambda (x) (cons (downcase x) x))
15716 keys)))
15717 property))))
15719 (defun org-set-property-and-value (use-last)
15720 "Allow to set [PROPERTY]: [value] direction from prompt.
15721 When use-default, don't even ask, just use the last
15722 \"[PROPERTY]: [value]\" string from the history."
15723 (interactive "P")
15724 (let* ((completion-ignore-case t)
15725 (pv (or (and use-last org-last-set-property-value)
15726 (org-completing-read
15727 "Enter a \"[Property]: [value]\" pair: "
15728 nil nil nil nil nil
15729 org-last-set-property-value)))
15730 prop val)
15731 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15732 (setq prop (match-string 1 pv)
15733 val (match-string 2 pv))
15734 (org-set-property prop val))))
15736 (defun org-set-property (property value)
15737 "In the current entry, set PROPERTY to VALUE.
15738 When called interactively, this will prompt for a property name, offering
15739 completion on existing and default properties. And then it will prompt
15740 for a value, offering completion either on allowed values (via an inherited
15741 xxx_ALL property) or on existing values in other instances of this property
15742 in the current file."
15743 (interactive (list nil nil))
15744 (let* ((property (or property (org-read-property-name)))
15745 (value (or value (org-read-property-value property)))
15746 (fn (cdr (assoc property org-properties-postprocess-alist))))
15747 (setq org-last-set-property property)
15748 (setq org-last-set-property-value (concat property ": " value))
15749 ;; Possibly postprocess the inserted value:
15750 (when fn (setq value (funcall fn value)))
15751 (unless (equal (org-entry-get nil property) value)
15752 (org-entry-put nil property value))))
15754 (defun org-delete-property (property)
15755 "In the current entry, delete PROPERTY."
15756 (interactive
15757 (let* ((completion-ignore-case t)
15758 (prop (org-icompleting-read "Property: "
15759 (org-entry-properties nil 'standard))))
15760 (list prop)))
15761 (message "Property %s %s" property
15762 (if (org-entry-delete nil property)
15763 "deleted"
15764 "was not present in the entry")))
15766 (defun org-delete-property-globally (property)
15767 "Remove PROPERTY globally, from all entries."
15768 (interactive
15769 (let* ((completion-ignore-case t)
15770 (prop (org-icompleting-read
15771 "Globally remove property: "
15772 (mapcar 'list (org-buffer-property-keys)))))
15773 (list prop)))
15774 (save-excursion
15775 (save-restriction
15776 (widen)
15777 (goto-char (point-min))
15778 (let ((cnt 0))
15779 (while (re-search-forward
15780 (org-re-property property)
15781 nil t)
15782 (setq cnt (1+ cnt))
15783 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15784 (message "Property \"%s\" removed from %d entries" property cnt)))))
15786 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15788 (defun org-compute-property-at-point ()
15789 "Compute the property at point.
15790 This looks for an enclosing column format, extracts the operator and
15791 then applies it to the property in the column format's scope."
15792 (interactive)
15793 (unless (org-at-property-p)
15794 (user-error "Not at a property"))
15795 (let ((prop (org-match-string-no-properties 2)))
15796 (org-columns-get-format-and-top-level)
15797 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15798 (user-error "No operator defined for property %s" prop))
15799 (org-columns-compute prop)))
15801 (defvar org-property-allowed-value-functions nil
15802 "Hook for functions supplying allowed values for a specific property.
15803 The functions must take a single argument, the name of the property, and
15804 return a flat list of allowed values. If \":ETC\" is one of
15805 the values, this means that these values are intended as defaults for
15806 completion, but that other values should be allowed too.
15807 The functions must return nil if they are not responsible for this
15808 property.")
15810 (defun org-property-get-allowed-values (pom property &optional table)
15811 "Get allowed values for the property PROPERTY.
15812 When TABLE is non-nil, return an alist that can directly be used for
15813 completion."
15814 (let (vals)
15815 (cond
15816 ((equal property "TODO")
15817 (setq vals (org-with-point-at pom
15818 (append org-todo-keywords-1 '("")))))
15819 ((equal property "PRIORITY")
15820 (let ((n org-lowest-priority))
15821 (while (>= n org-highest-priority)
15822 (push (char-to-string n) vals)
15823 (setq n (1- n)))))
15824 ((member property org-special-properties))
15825 ((setq vals (run-hook-with-args-until-success
15826 'org-property-allowed-value-functions property)))
15828 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15829 (when (and vals (string-match "\\S-" vals))
15830 (setq vals (car (read-from-string (concat "(" vals ")"))))
15831 (setq vals (mapcar (lambda (x)
15832 (cond ((stringp x) x)
15833 ((numberp x) (number-to-string x))
15834 ((symbolp x) (symbol-name x))
15835 (t "???")))
15836 vals)))))
15837 (when (member ":ETC" vals)
15838 (setq vals (remove ":ETC" vals))
15839 (org-add-props (car vals) '(org-unrestricted t)))
15840 (if table (mapcar 'list vals) vals)))
15842 (defun org-property-previous-allowed-value (&optional previous)
15843 "Switch to the next allowed value for this property."
15844 (interactive)
15845 (org-property-next-allowed-value t))
15847 (defun org-property-next-allowed-value (&optional previous)
15848 "Switch to the next allowed value for this property."
15849 (interactive)
15850 (unless (org-at-property-p)
15851 (user-error "Not at a property"))
15852 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15853 (key (match-string 2))
15854 (value (match-string 3))
15855 (allowed (or (org-property-get-allowed-values (point) key)
15856 (and (member value '("[ ]" "[-]" "[X]"))
15857 '("[ ]" "[X]"))))
15858 (heading (save-match-data (nth 4 (org-heading-components))))
15859 nval)
15860 (unless allowed
15861 (user-error "Allowed values for this property have not been defined"))
15862 (if previous (setq allowed (reverse allowed)))
15863 (if (member value allowed)
15864 (setq nval (car (cdr (member value allowed)))))
15865 (setq nval (or nval (car allowed)))
15866 (if (equal nval value)
15867 (user-error "Only one allowed value for this property"))
15868 (org-at-property-p)
15869 (replace-match (concat " :" key ": " nval) t t)
15870 (org-indent-line)
15871 (beginning-of-line 1)
15872 (skip-chars-forward " \t")
15873 (when (equal prop org-effort-property)
15874 (save-excursion
15875 (org-back-to-heading t)
15876 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15877 (when (string= org-clock-current-task heading)
15878 (setq org-clock-effort nval)
15879 (org-clock-update-mode-line)))
15880 (run-hook-with-args 'org-property-changed-functions key nval)))
15882 (defun org-find-olp (path &optional this-buffer)
15883 "Return a marker pointing to the entry at outline path OLP.
15884 If anything goes wrong, throw an error.
15885 You can wrap this call to catch the error like this:
15887 (condition-case msg
15888 (org-mobile-locate-entry (match-string 4))
15889 (error (nth 1 msg)))
15891 The return value will then be either a string with the error message,
15892 or a marker if everything is OK.
15894 If THIS-BUFFER is set, the outline path does not contain a file,
15895 only headings."
15896 (let* ((file (if this-buffer buffer-file-name (pop path)))
15897 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15898 (level 1)
15899 (lmin 1)
15900 (lmax 1)
15901 limit re end found pos heading cnt flevel)
15902 (unless buffer (error "File not found :%s" file))
15903 (with-current-buffer buffer
15904 (save-excursion
15905 (save-restriction
15906 (widen)
15907 (setq limit (point-max))
15908 (goto-char (point-min))
15909 (while (setq heading (pop path))
15910 (setq re (format org-complex-heading-regexp-format
15911 (regexp-quote heading)))
15912 (setq cnt 0 pos (point))
15913 (while (re-search-forward re end t)
15914 (setq level (- (match-end 1) (match-beginning 1)))
15915 (if (and (>= level lmin) (<= level lmax))
15916 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15917 (when (= cnt 0) (error "Heading not found on level %d: %s"
15918 lmax heading))
15919 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15920 lmax heading))
15921 (goto-char found)
15922 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15923 (setq end (save-excursion (org-end-of-subtree t t))))
15924 (when (org-at-heading-p)
15925 (point-marker)))))))
15927 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15928 "Find node HEADING in BUFFER.
15929 Return a marker to the heading if it was found, or nil if not.
15930 If POS-ONLY is set, return just the position instead of a marker.
15932 The heading text must match exact, but it may have a TODO keyword,
15933 a priority cookie and tags in the standard locations."
15934 (with-current-buffer (or buffer (current-buffer))
15935 (save-excursion
15936 (save-restriction
15937 (widen)
15938 (goto-char (point-min))
15939 (let (case-fold-search)
15940 (if (re-search-forward
15941 (format org-complex-heading-regexp-format
15942 (regexp-quote heading)) nil t)
15943 (if pos-only
15944 (match-beginning 0)
15945 (move-marker (make-marker) (match-beginning 0)))))))))
15947 (defun org-find-exact-heading-in-directory (heading &optional dir)
15948 "Find Org node headline HEADING in all .org files in directory DIR.
15949 When the target headline is found, return a marker to this location."
15950 (let ((files (directory-files (or dir default-directory)
15951 nil "\\`[^.#].*\\.org\\'"))
15952 file visiting m buffer)
15953 (catch 'found
15954 (while (setq file (pop files))
15955 (message "trying %s" file)
15956 (setq visiting (org-find-base-buffer-visiting file))
15957 (setq buffer (or visiting (find-file-noselect file)))
15958 (setq m (org-find-exact-headline-in-buffer
15959 heading buffer))
15960 (when (and (not m) (not visiting)) (kill-buffer buffer))
15961 (and m (throw 'found m))))))
15963 (defun org-find-entry-with-id (ident)
15964 "Locate the entry that contains the ID property with exact value IDENT.
15965 IDENT can be a string, a symbol or a number, this function will search for
15966 the string representation of it.
15967 Return the position where this entry starts, or nil if there is no such entry."
15968 (interactive "sID: ")
15969 (let ((id (cond
15970 ((stringp ident) ident)
15971 ((symbol-name ident) (symbol-name ident))
15972 ((numberp ident) (number-to-string ident))
15973 (t (error "IDENT %s must be a string, symbol or number" ident))))
15974 (case-fold-search nil))
15975 (save-excursion
15976 (save-restriction
15977 (widen)
15978 (goto-char (point-min))
15979 (when (re-search-forward
15980 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15981 nil t)
15982 (org-back-to-heading t)
15983 (point))))))
15985 ;;;; Timestamps
15987 (defvar org-last-changed-timestamp nil)
15988 (defvar org-last-inserted-timestamp nil
15989 "The last time stamp inserted with `org-insert-time-stamp'.")
15990 (defvar org-time-was-given) ; dynamically scoped parameter
15991 (defvar org-end-time-was-given) ; dynamically scoped parameter
15992 (defvar org-ts-what) ; dynamically scoped parameter
15994 (defun org-time-stamp (arg &optional inactive)
15995 "Prompt for a date/time and insert a time stamp.
15996 If the user specifies a time like HH:MM or if this command is
15997 called with at least one prefix argument, the time stamp contains
15998 the date and the time. Otherwise, only the date is be included.
16000 All parts of a date not specified by the user is filled in from
16001 the current date/time. So if you just press return without
16002 typing anything, the time stamp will represent the current
16003 date/time.
16005 If there is already a timestamp at the cursor, it will be
16006 modified.
16008 With two universal prefix arguments, insert an active timestamp
16009 with the current time without prompting the user.
16011 When called from lisp, the timestamp is inactive if INACTIVE is
16012 non-nil."
16013 (interactive "P")
16014 (let* ((ts nil)
16015 (default-time
16016 ;; Default time is either today, or, when entering a range,
16017 ;; the range start.
16018 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16019 (save-excursion
16020 (re-search-backward
16021 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16022 (- (point) 20) t)))
16023 (apply 'encode-time (org-parse-time-string (match-string 1)))
16024 (current-time)))
16025 (default-input (and ts (org-get-compact-tod ts)))
16026 (repeater (save-excursion
16027 (save-match-data
16028 (beginning-of-line)
16029 (when (re-search-forward
16030 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16031 (save-excursion (progn (end-of-line) (point))) t)
16032 (match-string 0)))))
16033 org-time-was-given org-end-time-was-given time)
16034 (cond
16035 ((and (org-at-timestamp-p t)
16036 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16037 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16038 (insert "--")
16039 (setq time (let ((this-command this-command))
16040 (org-read-date arg 'totime nil nil
16041 default-time default-input inactive)))
16042 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16043 ((org-at-timestamp-p t)
16044 (setq time (let ((this-command this-command))
16045 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16046 (when (org-at-timestamp-p t) ; just to get the match data
16047 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16048 (replace-match "")
16049 (setq org-last-changed-timestamp
16050 (org-insert-time-stamp
16051 time (or org-time-was-given arg)
16052 inactive nil nil (list org-end-time-was-given)))
16053 (when repeater (goto-char (1- (point))) (insert " " repeater)
16054 (setq org-last-changed-timestamp
16055 (concat (substring org-last-inserted-timestamp 0 -1)
16056 " " repeater ">"))))
16057 (message "Timestamp updated"))
16058 ((equal arg '(16))
16059 (org-insert-time-stamp (current-time) t inactive))
16061 (setq time (let ((this-command this-command))
16062 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16063 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16064 nil nil (list org-end-time-was-given))))))
16066 ;; FIXME: can we use this for something else, like computing time differences?
16067 (defun org-get-compact-tod (s)
16068 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16069 (let* ((t1 (match-string 1 s))
16070 (h1 (string-to-number (match-string 2 s)))
16071 (m1 (string-to-number (match-string 3 s)))
16072 (t2 (and (match-end 4) (match-string 5 s)))
16073 (h2 (and t2 (string-to-number (match-string 6 s))))
16074 (m2 (and t2 (string-to-number (match-string 7 s))))
16075 dh dm)
16076 (if (not t2)
16078 (setq dh (- h2 h1) dm (- m2 m1))
16079 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16080 (concat t1 "+" (number-to-string dh)
16081 (and (/= 0 dm) (format ":%02d" dm)))))))
16083 (defun org-time-stamp-inactive (&optional arg)
16084 "Insert an inactive time stamp.
16085 An inactive time stamp is enclosed in square brackets instead of angle
16086 brackets. It is inactive in the sense that it does not trigger agenda entries,
16087 does not link to the calendar and cannot be changed with the S-cursor keys.
16088 So these are more for recording a certain time/date."
16089 (interactive "P")
16090 (org-time-stamp arg 'inactive))
16092 (defvar org-date-ovl (make-overlay 1 1))
16093 (overlay-put org-date-ovl 'face 'org-date-selected)
16094 (org-detach-overlay org-date-ovl)
16096 (defvar org-ans1) ; dynamically scoped parameter
16097 (defvar org-ans2) ; dynamically scoped parameter
16099 (defvar org-plain-time-of-day-regexp) ; defined below
16101 (defvar org-overriding-default-time nil) ; dynamically scoped
16102 (defvar org-read-date-overlay nil)
16103 (defvar org-dcst nil) ; dynamically scoped
16104 (defvar org-read-date-history nil)
16105 (defvar org-read-date-final-answer nil)
16106 (defvar org-read-date-analyze-futurep nil)
16107 (defvar org-read-date-analyze-forced-year nil)
16108 (defvar org-read-date-inactive)
16110 (defvar org-read-date-minibuffer-local-map
16111 (let* ((org-replace-disputed-keys nil)
16112 (map (make-sparse-keymap)))
16113 (set-keymap-parent map minibuffer-local-map)
16114 (org-defkey map (kbd ".")
16115 (lambda () (interactive)
16116 ;; Are we at the beginning of the prompt?
16117 (if (looking-back "^[^:]+: ")
16118 (org-eval-in-calendar '(calendar-goto-today))
16119 (insert "."))))
16120 (org-defkey map (kbd "C-.")
16121 (lambda () (interactive)
16122 (org-eval-in-calendar '(calendar-goto-today))))
16123 (org-defkey map [(meta shift left)]
16124 (lambda () (interactive)
16125 (org-eval-in-calendar '(calendar-backward-month 1))))
16126 (org-defkey map [(meta shift right)]
16127 (lambda () (interactive)
16128 (org-eval-in-calendar '(calendar-forward-month 1))))
16129 (org-defkey map [(meta shift up)]
16130 (lambda () (interactive)
16131 (org-eval-in-calendar '(calendar-backward-year 1))))
16132 (org-defkey map [(meta shift down)]
16133 (lambda () (interactive)
16134 (org-eval-in-calendar '(calendar-forward-year 1))))
16135 (org-defkey map [?\e (shift left)]
16136 (lambda () (interactive)
16137 (org-eval-in-calendar '(calendar-backward-month 1))))
16138 (org-defkey map [?\e (shift right)]
16139 (lambda () (interactive)
16140 (org-eval-in-calendar '(calendar-forward-month 1))))
16141 (org-defkey map [?\e (shift up)]
16142 (lambda () (interactive)
16143 (org-eval-in-calendar '(calendar-backward-year 1))))
16144 (org-defkey map [?\e (shift down)]
16145 (lambda () (interactive)
16146 (org-eval-in-calendar '(calendar-forward-year 1))))
16147 (org-defkey map [(shift up)]
16148 (lambda () (interactive)
16149 (org-eval-in-calendar '(calendar-backward-week 1))))
16150 (org-defkey map [(shift down)]
16151 (lambda () (interactive)
16152 (org-eval-in-calendar '(calendar-forward-week 1))))
16153 (org-defkey map [(shift left)]
16154 (lambda () (interactive)
16155 (org-eval-in-calendar '(calendar-backward-day 1))))
16156 (org-defkey map [(shift right)]
16157 (lambda () (interactive)
16158 (org-eval-in-calendar '(calendar-forward-day 1))))
16159 (org-defkey map "!"
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(diary-view-entries))
16162 (message "")))
16163 (org-defkey map ">"
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(scroll-calendar-left 1))))
16166 (org-defkey map "<"
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(scroll-calendar-right 1))))
16169 (org-defkey map "\C-v"
16170 (lambda () (interactive)
16171 (org-eval-in-calendar
16172 '(calendar-scroll-left-three-months 1))))
16173 (org-defkey map "\M-v"
16174 (lambda () (interactive)
16175 (org-eval-in-calendar
16176 '(calendar-scroll-right-three-months 1))))
16177 map)
16178 "Keymap for minibuffer commands when using `org-read-date'.")
16180 (defun org-read-date (&optional org-with-time to-time from-string prompt
16181 default-time default-input inactive)
16182 "Read a date, possibly a time, and make things smooth for the user.
16183 The prompt will suggest to enter an ISO date, but you can also enter anything
16184 which will at least partially be understood by `parse-time-string'.
16185 Unrecognized parts of the date will default to the current day, month, year,
16186 hour and minute. If this command is called to replace a timestamp at point,
16187 or to enter the second timestamp of a range, the default time is taken
16188 from the existing stamp. Furthermore, the command prefers the future,
16189 so if you are giving a date where the year is not given, and the day-month
16190 combination is already past in the current year, it will assume you
16191 mean next year. For details, see the manual. A few examples:
16193 3-2-5 --> 2003-02-05
16194 feb 15 --> currentyear-02-15
16195 2/15 --> currentyear-02-15
16196 sep 12 9 --> 2009-09-12
16197 12:45 --> today 12:45
16198 22 sept 0:34 --> currentyear-09-22 0:34
16199 12 --> currentyear-currentmonth-12
16200 Fri --> nearest Friday after today
16201 -Tue --> last Tuesday
16202 etc.
16204 Furthermore you can specify a relative date by giving, as the *first* thing
16205 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16206 change in days weeks, months, years.
16207 With a single plus or minus, the date is relative to today. With a double
16208 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16209 +4d --> four days from today
16210 +4 --> same as above
16211 +2w --> two weeks from today
16212 ++5 --> five days from default date
16214 The function understands only English month and weekday abbreviations.
16216 While prompting, a calendar is popped up - you can also select the
16217 date with the mouse (button 1). The calendar shows a period of three
16218 months. To scroll it to other months, use the keys `>' and `<'.
16219 If you don't like the calendar, turn it off with
16220 \(setq org-read-date-popup-calendar nil)
16222 With optional argument TO-TIME, the date will immediately be converted
16223 to an internal time.
16224 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16225 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16226 still enter a time, and this function will inform the calling routine
16227 about this change. The calling routine may then choose to change the
16228 format used to insert the time stamp into the buffer to include the time.
16229 With optional argument FROM-STRING, read from this string instead from
16230 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16231 the time/date that is used for everything that is not specified by the
16232 user."
16233 (require 'parse-time)
16234 (let* ((org-time-stamp-rounding-minutes
16235 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16236 (org-dcst org-display-custom-times)
16237 (ct (org-current-time))
16238 (org-def (or org-overriding-default-time default-time ct))
16239 (org-defdecode (decode-time org-def))
16240 (dummy (progn
16241 (when (< (nth 2 org-defdecode) org-extend-today-until)
16242 (setcar (nthcdr 2 org-defdecode) -1)
16243 (setcar (nthcdr 1 org-defdecode) 59)
16244 (setq org-def (apply 'encode-time org-defdecode)
16245 org-defdecode (decode-time org-def)))))
16246 (mouse-autoselect-window nil) ; Don't let the mouse jump
16247 (calendar-frame-setup nil)
16248 (calendar-setup nil)
16249 (calendar-move-hook nil)
16250 (calendar-view-diary-initially-flag nil)
16251 (calendar-view-holidays-initially-flag nil)
16252 (timestr (format-time-string
16253 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16254 (prompt (concat (if prompt (concat prompt " ") "")
16255 (format "Date+time [%s]: " timestr)))
16256 ans (org-ans0 "") org-ans1 org-ans2 final)
16258 (cond
16259 (from-string (setq ans from-string))
16260 (org-read-date-popup-calendar
16261 (save-excursion
16262 (save-window-excursion
16263 (calendar)
16264 (org-eval-in-calendar '(setq cursor-type nil) t)
16265 (unwind-protect
16266 (progn
16267 (calendar-forward-day (- (time-to-days org-def)
16268 (calendar-absolute-from-gregorian
16269 (calendar-current-date))))
16270 (org-eval-in-calendar nil t)
16271 (let* ((old-map (current-local-map))
16272 (map (copy-keymap calendar-mode-map))
16273 (minibuffer-local-map
16274 (copy-keymap org-read-date-minibuffer-local-map)))
16275 (org-defkey map (kbd "RET") 'org-calendar-select)
16276 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16277 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16278 (unwind-protect
16279 (progn
16280 (use-local-map map)
16281 (setq org-read-date-inactive inactive)
16282 (add-hook 'post-command-hook 'org-read-date-display)
16283 (setq org-ans0 (read-string prompt default-input
16284 'org-read-date-history nil))
16285 ;; org-ans0: from prompt
16286 ;; org-ans1: from mouse click
16287 ;; org-ans2: from calendar motion
16288 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16289 (remove-hook 'post-command-hook 'org-read-date-display)
16290 (use-local-map old-map)
16291 (when org-read-date-overlay
16292 (delete-overlay org-read-date-overlay)
16293 (setq org-read-date-overlay nil)))))
16294 (bury-buffer "*Calendar*")))))
16296 (t ; Naked prompt only
16297 (unwind-protect
16298 (setq ans (read-string prompt default-input
16299 'org-read-date-history timestr))
16300 (when org-read-date-overlay
16301 (delete-overlay org-read-date-overlay)
16302 (setq org-read-date-overlay nil)))))
16304 (setq final (org-read-date-analyze ans org-def org-defdecode))
16306 (when org-read-date-analyze-forced-year
16307 (message "Year was forced into %s"
16308 (if org-read-date-force-compatible-dates
16309 "compatible range (1970-2037)"
16310 "range representable on this machine"))
16311 (ding))
16313 ;; One round trip to get rid of 34th of August and stuff like that....
16314 (setq final (decode-time (apply 'encode-time final)))
16316 (setq org-read-date-final-answer ans)
16318 (if to-time
16319 (apply 'encode-time final)
16320 (if (and (boundp 'org-time-was-given) org-time-was-given)
16321 (format "%04d-%02d-%02d %02d:%02d"
16322 (nth 5 final) (nth 4 final) (nth 3 final)
16323 (nth 2 final) (nth 1 final))
16324 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16326 (defvar org-def)
16327 (defvar org-defdecode)
16328 (defvar org-with-time)
16329 (defun org-read-date-display ()
16330 "Display the current date prompt interpretation in the minibuffer."
16331 (when org-read-date-display-live
16332 (when org-read-date-overlay
16333 (delete-overlay org-read-date-overlay))
16334 (when (minibufferp (current-buffer))
16335 (save-excursion
16336 (end-of-line 1)
16337 (while (not (equal (buffer-substring
16338 (max (point-min) (- (point) 4)) (point))
16339 " "))
16340 (insert " ")))
16341 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16342 " " (or org-ans1 org-ans2)))
16343 (org-end-time-was-given nil)
16344 (f (org-read-date-analyze ans org-def org-defdecode))
16345 (fmts (if org-dcst
16346 org-time-stamp-custom-formats
16347 org-time-stamp-formats))
16348 (fmt (if (or org-with-time
16349 (and (boundp 'org-time-was-given) org-time-was-given))
16350 (cdr fmts)
16351 (car fmts)))
16352 (txt (format-time-string fmt (apply 'encode-time f)))
16353 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16354 (txt (concat "=> " txt)))
16355 (when (and org-end-time-was-given
16356 (string-match org-plain-time-of-day-regexp txt))
16357 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16358 org-end-time-was-given
16359 (substring txt (match-end 0)))))
16360 (when org-read-date-analyze-futurep
16361 (setq txt (concat txt " (=>F)")))
16362 (setq org-read-date-overlay
16363 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16364 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16366 (defun org-read-date-analyze (ans org-def org-defdecode)
16367 "Analyze the combined answer of the date prompt."
16368 ;; FIXME: cleanup and comment
16369 (let ((nowdecode (decode-time (current-time)))
16370 delta deltan deltaw deltadef year month day
16371 hour minute second wday pm h2 m2 tl wday1
16372 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16373 (setq org-read-date-analyze-futurep nil
16374 org-read-date-analyze-forced-year nil)
16375 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16376 (setq ans "+0"))
16378 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16379 (setq ans (replace-match "" t t ans)
16380 deltan (car delta)
16381 deltaw (nth 1 delta)
16382 deltadef (nth 2 delta)))
16384 ;; Check if there is an iso week date in there. If yes, store the
16385 ;; info and postpone interpreting it until the rest of the parsing
16386 ;; is done.
16387 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16388 (setq iso-year (if (match-end 1)
16389 (org-small-year-to-year
16390 (string-to-number (match-string 1 ans))))
16391 iso-weekday (if (match-end 3)
16392 (string-to-number (match-string 3 ans)))
16393 iso-week (string-to-number (match-string 2 ans)))
16394 (setq ans (replace-match "" t t ans)))
16396 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16397 (when (string-match
16398 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16399 (setq year (if (match-end 2)
16400 (string-to-number (match-string 2 ans))
16401 (progn (setq kill-year t)
16402 (string-to-number (format-time-string "%Y"))))
16403 month (string-to-number (match-string 3 ans))
16404 day (string-to-number (match-string 4 ans)))
16405 (if (< year 100) (setq year (+ 2000 year)))
16406 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16407 t nil ans)))
16409 ;; Help matching dotted european dates
16410 (when (string-match
16411 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16412 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16413 (setq kill-year t)
16414 (string-to-number (format-time-string "%Y")))
16415 day (string-to-number (match-string 1 ans))
16416 month (string-to-number (match-string 2 ans))
16417 ans (replace-match (format "%04d-%02d-%02d" year month day)
16418 t nil ans)))
16420 ;; Help matching american dates, like 5/30 or 5/30/7
16421 (when (string-match
16422 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16423 (setq year (if (match-end 4)
16424 (string-to-number (match-string 4 ans))
16425 (progn (setq kill-year t)
16426 (string-to-number (format-time-string "%Y"))))
16427 month (string-to-number (match-string 1 ans))
16428 day (string-to-number (match-string 2 ans)))
16429 (if (< year 100) (setq year (+ 2000 year)))
16430 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16431 t nil ans)))
16432 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16433 ;; If there is a time with am/pm, and *no* time without it, we convert
16434 ;; so that matching will be successful.
16435 (loop for i from 1 to 2 do ; twice, for end time as well
16436 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16437 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16438 (setq hour (string-to-number (match-string 1 ans))
16439 minute (if (match-end 3)
16440 (string-to-number (match-string 3 ans))
16442 pm (equal ?p
16443 (string-to-char (downcase (match-string 4 ans)))))
16444 (if (and (= hour 12) (not pm))
16445 (setq hour 0)
16446 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16447 (setq ans (replace-match (format "%02d:%02d" hour minute)
16448 t t ans))))
16450 ;; Check if a time range is given as a duration
16451 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16452 (setq hour (string-to-number (match-string 1 ans))
16453 h2 (+ hour (string-to-number (match-string 3 ans)))
16454 minute (string-to-number (match-string 2 ans))
16455 m2 (+ minute (if (match-end 5) (string-to-number
16456 (match-string 5 ans))0)))
16457 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16458 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16459 t t ans)))
16461 ;; Check if there is a time range
16462 (when (boundp 'org-end-time-was-given)
16463 (setq org-time-was-given nil)
16464 (when (and (string-match org-plain-time-of-day-regexp ans)
16465 (match-end 8))
16466 (setq org-end-time-was-given (match-string 8 ans))
16467 (setq ans (concat (substring ans 0 (match-beginning 7))
16468 (substring ans (match-end 7))))))
16470 (setq tl (parse-time-string ans)
16471 day (or (nth 3 tl) (nth 3 org-defdecode))
16472 month (or (nth 4 tl)
16473 (if (and org-read-date-prefer-future
16474 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16475 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16476 (nth 4 org-defdecode)))
16477 year (or (and (not kill-year) (nth 5 tl))
16478 (if (and org-read-date-prefer-future
16479 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16480 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16481 (nth 5 org-defdecode)))
16482 hour (or (nth 2 tl) (nth 2 org-defdecode))
16483 minute (or (nth 1 tl) (nth 1 org-defdecode))
16484 second (or (nth 0 tl) 0)
16485 wday (nth 6 tl))
16487 (when (and (eq org-read-date-prefer-future 'time)
16488 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16489 (equal day (nth 3 nowdecode))
16490 (equal month (nth 4 nowdecode))
16491 (equal year (nth 5 nowdecode))
16492 (nth 2 tl)
16493 (or (< (nth 2 tl) (nth 2 nowdecode))
16494 (and (= (nth 2 tl) (nth 2 nowdecode))
16495 (nth 1 tl)
16496 (< (nth 1 tl) (nth 1 nowdecode)))))
16497 (setq day (1+ day)
16498 futurep t))
16500 ;; Special date definitions below
16501 (cond
16502 (iso-week
16503 ;; There was an iso week
16504 (require 'cal-iso)
16505 (setq futurep nil)
16506 (setq year (or iso-year year)
16507 day (or iso-weekday wday 1)
16508 wday nil ; to make sure that the trigger below does not match
16509 iso-date (calendar-gregorian-from-absolute
16510 (calendar-absolute-from-iso
16511 (list iso-week day year))))
16512 ; FIXME: Should we also push ISO weeks into the future?
16513 ; (when (and org-read-date-prefer-future
16514 ; (not iso-year)
16515 ; (< (calendar-absolute-from-gregorian iso-date)
16516 ; (time-to-days (current-time))))
16517 ; (setq year (1+ year)
16518 ; iso-date (calendar-gregorian-from-absolute
16519 ; (calendar-absolute-from-iso
16520 ; (list iso-week day year)))))
16521 (setq month (car iso-date)
16522 year (nth 2 iso-date)
16523 day (nth 1 iso-date)))
16524 (deltan
16525 (setq futurep nil)
16526 (unless deltadef
16527 (let ((now (decode-time (current-time))))
16528 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16529 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16530 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16531 ((equal deltaw "m") (setq month (+ month deltan)))
16532 ((equal deltaw "y") (setq year (+ year deltan)))))
16533 ((and wday (not (nth 3 tl)))
16534 ;; Weekday was given, but no day, so pick that day in the week
16535 ;; on or after the derived date.
16536 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16537 (unless (equal wday wday1)
16538 (setq day (+ day (% (- wday wday1 -7) 7))))))
16539 (if (and (boundp 'org-time-was-given)
16540 (nth 2 tl))
16541 (setq org-time-was-given t))
16542 (if (< year 100) (setq year (+ 2000 year)))
16543 ;; Check of the date is representable
16544 (if org-read-date-force-compatible-dates
16545 (progn
16546 (if (< year 1970)
16547 (setq year 1970 org-read-date-analyze-forced-year t))
16548 (if (> year 2037)
16549 (setq year 2037 org-read-date-analyze-forced-year t)))
16550 (condition-case nil
16551 (ignore (encode-time second minute hour day month year))
16552 (error
16553 (setq year (nth 5 org-defdecode))
16554 (setq org-read-date-analyze-forced-year t))))
16555 (setq org-read-date-analyze-futurep futurep)
16556 (list second minute hour day month year)))
16558 (defvar parse-time-weekdays)
16559 (defun org-read-date-get-relative (s today default)
16560 "Check string S for special relative date string.
16561 TODAY and DEFAULT are internal times, for today and for a default.
16562 Return shift list (N what def-flag)
16563 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16564 N is the number of WHATs to shift.
16565 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16566 the DEFAULT date rather than TODAY."
16567 (require 'parse-time)
16568 (when (and
16569 (string-match
16570 (concat
16571 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16572 "\\([0-9]+\\)?"
16573 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16574 "\\([ \t]\\|$\\)") s)
16575 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16576 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16577 (string-to-char (substring (match-string 1 s) -1))
16578 ?+))
16579 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16580 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16581 (what (if (match-end 3) (match-string 3 s) "d"))
16582 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16583 (date (if rel default today))
16584 (wday (nth 6 (decode-time date)))
16585 delta)
16586 (if wday1
16587 (progn
16588 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16589 (if (= delta 0) (setq delta 7))
16590 (if (= dir ?-)
16591 (progn
16592 (setq delta (- delta 7))
16593 (if (= delta 0) (setq delta -7))))
16594 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16595 (list delta "d" rel))
16596 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16598 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16599 "Turn a user-specified date into the internal representation.
16600 The internal representation needed by the calendar is (month day year).
16601 This is a wrapper to handle the brain-dead convention in calendar that
16602 user function argument order change dependent on argument order."
16603 (if (boundp 'calendar-date-style)
16604 (cond
16605 ((eq calendar-date-style 'american)
16606 (list arg1 arg2 arg3))
16607 ((eq calendar-date-style 'european)
16608 (list arg2 arg1 arg3))
16609 ((eq calendar-date-style 'iso)
16610 (list arg2 arg3 arg1)))
16611 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16612 (if (org-bound-and-true-p european-calendar-style)
16613 (list arg2 arg1 arg3)
16614 (list arg1 arg2 arg3)))))
16616 (defun org-eval-in-calendar (form &optional keepdate)
16617 "Eval FORM in the calendar window and return to current window.
16618 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16619 otherwise stick to the current value of `org-ans2'."
16620 (let ((sf (selected-frame))
16621 (sw (selected-window)))
16622 (select-window (get-buffer-window "*Calendar*" t))
16623 (eval form)
16624 (when (and (not keepdate) (calendar-cursor-to-date))
16625 (let* ((date (calendar-cursor-to-date))
16626 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16627 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16628 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16629 (select-window sw)
16630 (org-select-frame-set-input-focus sf)))
16632 (defun org-calendar-select ()
16633 "Return to `org-read-date' with the date currently selected.
16634 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16635 (interactive)
16636 (when (calendar-cursor-to-date)
16637 (let* ((date (calendar-cursor-to-date))
16638 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16639 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16640 (if (active-minibuffer-window) (exit-minibuffer))))
16642 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16643 "Insert a date stamp for the date given by the internal TIME.
16644 WITH-HM means use the stamp format that includes the time of the day.
16645 INACTIVE means use square brackets instead of angular ones, so that the
16646 stamp will not contribute to the agenda.
16647 PRE and POST are optional strings to be inserted before and after the
16648 stamp.
16649 The command returns the inserted time stamp."
16650 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16651 stamp)
16652 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16653 (insert-before-markers (or pre ""))
16654 (when (listp extra)
16655 (setq extra (car extra))
16656 (if (and (stringp extra)
16657 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16658 (setq extra (format "-%02d:%02d"
16659 (string-to-number (match-string 1 extra))
16660 (string-to-number (match-string 2 extra))))
16661 (setq extra nil)))
16662 (when extra
16663 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16664 (insert-before-markers (setq stamp (format-time-string fmt time)))
16665 (insert-before-markers (or post ""))
16666 (setq org-last-inserted-timestamp stamp)))
16668 (defun org-toggle-time-stamp-overlays ()
16669 "Toggle the use of custom time stamp formats."
16670 (interactive)
16671 (setq org-display-custom-times (not org-display-custom-times))
16672 (unless org-display-custom-times
16673 (let ((p (point-min)) (bmp (buffer-modified-p)))
16674 (while (setq p (next-single-property-change p 'display))
16675 (if (and (get-text-property p 'display)
16676 (eq (get-text-property p 'face) 'org-date))
16677 (remove-text-properties
16678 p (setq p (next-single-property-change p 'display))
16679 '(display t))))
16680 (set-buffer-modified-p bmp)))
16681 (if (featurep 'xemacs)
16682 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16683 (org-restart-font-lock)
16684 (setq org-table-may-need-update t)
16685 (if org-display-custom-times
16686 (message "Time stamps are overlaid with custom format")
16687 (message "Time stamp overlays removed")))
16689 (defun org-display-custom-time (beg end)
16690 "Overlay modified time stamp format over timestamp between BEG and END."
16691 (let* ((ts (buffer-substring beg end))
16692 t1 w1 with-hm tf time str w2 (off 0))
16693 (save-match-data
16694 (setq t1 (org-parse-time-string ts t))
16695 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16696 (setq off (- (match-end 0) (match-beginning 0)))))
16697 (setq end (- end off))
16698 (setq w1 (- end beg)
16699 with-hm (and (nth 1 t1) (nth 2 t1))
16700 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16701 time (org-fix-decoded-time t1)
16702 str (org-add-props
16703 (format-time-string
16704 (substring tf 1 -1) (apply 'encode-time time))
16705 nil 'mouse-face 'highlight)
16706 w2 (length str))
16707 (if (not (= w2 w1))
16708 (add-text-properties (1+ beg) (+ 2 beg)
16709 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16710 (if (featurep 'xemacs)
16711 (progn
16712 (put-text-property beg end 'invisible t)
16713 (put-text-property beg end 'end-glyph (make-glyph str)))
16714 (put-text-property beg end 'display str))))
16716 (defun org-translate-time (string)
16717 "Translate all timestamps in STRING to custom format.
16718 But do this only if the variable `org-display-custom-times' is set."
16719 (when org-display-custom-times
16720 (save-match-data
16721 (let* ((start 0)
16722 (re org-ts-regexp-both)
16723 t1 with-hm inactive tf time str beg end)
16724 (while (setq start (string-match re string start))
16725 (setq beg (match-beginning 0)
16726 end (match-end 0)
16727 t1 (save-match-data
16728 (org-parse-time-string (substring string beg end) t))
16729 with-hm (and (nth 1 t1) (nth 2 t1))
16730 inactive (equal (substring string beg (1+ beg)) "[")
16731 tf (funcall (if with-hm 'cdr 'car)
16732 org-time-stamp-custom-formats)
16733 time (org-fix-decoded-time t1)
16734 str (format-time-string
16735 (concat
16736 (if inactive "[" "<") (substring tf 1 -1)
16737 (if inactive "]" ">"))
16738 (apply 'encode-time time))
16739 string (replace-match str t t string)
16740 start (+ start (length str)))))))
16741 string)
16743 (defun org-fix-decoded-time (time)
16744 "Set 0 instead of nil for the first 6 elements of time.
16745 Don't touch the rest."
16746 (let ((n 0))
16747 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16749 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16751 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16752 "Difference between TIMESTAMP-STRING and now in days.
16753 If SECONDS is non-nil, return the difference in seconds."
16754 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16755 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16756 (funcall fdiff (current-time)))))
16758 (defun org-deadline-close (timestamp-string &optional ndays)
16759 "Is the time in TIMESTAMP-STRING close to the current date?"
16760 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16761 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16762 (not (org-entry-is-done-p))))
16764 (defun org-get-wdays (ts &optional delay zero-delay)
16765 "Get the deadline lead time appropriate for timestring TS.
16766 When DELAY is non-nil, get the delay time for scheduled items
16767 instead of the deadline lead time. When ZERO-DELAY is non-nil
16768 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16769 don't try to find the delay cookie in the scheduled timestamp."
16770 (let ((tv (if delay org-scheduled-delay-days
16771 org-deadline-warning-days)))
16772 (cond
16773 ((or (and delay (< tv 0))
16774 (and delay zero-delay (<= tv 0))
16775 (and (not delay) (<= tv 0)))
16776 ;; Enforce this value no matter what
16777 (- tv))
16778 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16779 ;; lead time is specified.
16780 (floor (* (string-to-number (match-string 1 ts))
16781 (cdr (assoc (match-string 2 ts)
16782 '(("d" . 1) ("w" . 7)
16783 ("m" . 30.4) ("y" . 365.25)
16784 ("h" . 0.041667)))))))
16785 ;; go for the default.
16786 (t tv))))
16788 (defun org-calendar-select-mouse (ev)
16789 "Return to `org-read-date' with the date currently selected.
16790 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16791 (interactive "e")
16792 (mouse-set-point ev)
16793 (when (calendar-cursor-to-date)
16794 (let* ((date (calendar-cursor-to-date))
16795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16796 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16797 (if (active-minibuffer-window) (exit-minibuffer))))
16799 (defun org-check-deadlines (ndays)
16800 "Check if there are any deadlines due or past due.
16801 A deadline is considered due if it happens within `org-deadline-warning-days'
16802 days from today's date. If the deadline appears in an entry marked DONE,
16803 it is not shown. The prefix arg NDAYS can be used to test that many
16804 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16805 (interactive "P")
16806 (let* ((org-warn-days
16807 (cond
16808 ((equal ndays '(4)) 100000)
16809 (ndays (prefix-numeric-value ndays))
16810 (t (abs org-deadline-warning-days))))
16811 (case-fold-search nil)
16812 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16813 (callback
16814 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16816 (message "%d deadlines past-due or due within %d days"
16817 (org-occur regexp nil callback)
16818 org-warn-days)))
16820 (defsubst org-re-timestamp (type)
16821 "Return a regexp for timestamp TYPE.
16822 Allowed values for TYPE are:
16824 all: all timestamps
16825 active: only active timestamps (<...>)
16826 inactive: only inactive timestamps ([...])
16827 scheduled: only scheduled timestamps
16828 deadline: only deadline timestamps
16829 closed: only closed time-stamps
16831 When TYPE is nil, fall back on returning a regexp that matches
16832 both scheduled and deadline timestamps."
16833 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16834 ((eq type 'active) org-ts-regexp)
16835 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16836 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16837 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16838 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16839 ((eq type 'scheduled-or-deadline)
16840 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16842 (defun org-check-before-date (date)
16843 "Check if there are deadlines or scheduled entries before DATE."
16844 (interactive (list (org-read-date)))
16845 (let ((case-fold-search nil)
16846 (regexp (org-re-timestamp org-ts-type))
16847 (callback
16848 (lambda () (time-less-p
16849 (org-time-string-to-time (match-string 1))
16850 (org-time-string-to-time date)))))
16851 (message "%d entries before %s"
16852 (org-occur regexp nil callback) date)))
16854 (defun org-check-after-date (date)
16855 "Check if there are deadlines or scheduled entries after DATE."
16856 (interactive (list (org-read-date)))
16857 (let ((case-fold-search nil)
16858 (regexp (org-re-timestamp org-ts-type))
16859 (callback
16860 (lambda () (not
16861 (time-less-p
16862 (org-time-string-to-time (match-string 1))
16863 (org-time-string-to-time date))))))
16864 (message "%d entries after %s"
16865 (org-occur regexp nil callback) date)))
16867 (defun org-check-dates-range (start-date end-date)
16868 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16869 (interactive (list (org-read-date nil nil nil "Range starts")
16870 (org-read-date nil nil nil "Range end")))
16871 (let ((case-fold-search nil)
16872 (regexp (org-re-timestamp org-ts-type))
16873 (callback
16874 (lambda ()
16875 (let ((match (match-string 1)))
16876 (and
16877 (not (time-less-p
16878 (org-time-string-to-time match)
16879 (org-time-string-to-time start-date)))
16880 (time-less-p
16881 (org-time-string-to-time match)
16882 (org-time-string-to-time end-date)))))))
16883 (message "%d entries between %s and %s"
16884 (org-occur regexp nil callback) start-date end-date)))
16886 (defun org-evaluate-time-range (&optional to-buffer)
16887 "Evaluate a time range by computing the difference between start and end.
16888 Normally the result is just printed in the echo area, but with prefix arg
16889 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16890 If the time range is actually in a table, the result is inserted into the
16891 next column.
16892 For time difference computation, a year is assumed to be exactly 365
16893 days in order to avoid rounding problems."
16894 (interactive "P")
16896 (org-clock-update-time-maybe)
16897 (save-excursion
16898 (unless (org-at-date-range-p t)
16899 (goto-char (point-at-bol))
16900 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16901 (if (not (org-at-date-range-p t))
16902 (user-error "Not at a time-stamp range, and none found in current line")))
16903 (let* ((ts1 (match-string 1))
16904 (ts2 (match-string 2))
16905 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16906 (match-end (match-end 0))
16907 (time1 (org-time-string-to-time ts1))
16908 (time2 (org-time-string-to-time ts2))
16909 (t1 (org-float-time time1))
16910 (t2 (org-float-time time2))
16911 (diff (abs (- t2 t1)))
16912 (negative (< (- t2 t1) 0))
16913 ;; (ys (floor (* 365 24 60 60)))
16914 (ds (* 24 60 60))
16915 (hs (* 60 60))
16916 (fy "%dy %dd %02d:%02d")
16917 (fy1 "%dy %dd")
16918 (fd "%dd %02d:%02d")
16919 (fd1 "%dd")
16920 (fh "%02d:%02d")
16921 y d h m align)
16922 (if havetime
16923 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16925 d (floor (/ diff ds)) diff (mod diff ds)
16926 h (floor (/ diff hs)) diff (mod diff hs)
16927 m (floor (/ diff 60)))
16928 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16930 d (floor (+ (/ diff ds) 0.5))
16931 h 0 m 0))
16932 (if (not to-buffer)
16933 (message "%s" (org-make-tdiff-string y d h m))
16934 (if (org-at-table-p)
16935 (progn
16936 (goto-char match-end)
16937 (setq align t)
16938 (and (looking-at " *|") (goto-char (match-end 0))))
16939 (goto-char match-end))
16940 (if (looking-at
16941 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16942 (replace-match ""))
16943 (if negative (insert " -"))
16944 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16945 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16946 (insert " " (format fh h m))))
16947 (if align (org-table-align))
16948 (message "Time difference inserted")))))
16950 (defun org-make-tdiff-string (y d h m)
16951 (let ((fmt "")
16952 (l nil))
16953 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16954 l (push y l)))
16955 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16956 l (push d l)))
16957 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16958 l (push h l)))
16959 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16960 l (push m l)))
16961 (apply 'format fmt (nreverse l))))
16963 (defun org-time-string-to-time (s &optional buffer pos)
16964 "Convert a timestamp string into internal time."
16965 (condition-case errdata
16966 (apply 'encode-time (org-parse-time-string s))
16967 (error (error "Bad timestamp `%s'%s\nError was: %s"
16968 s (if (not (and buffer pos))
16970 (format " at %d in buffer `%s'" pos buffer))
16971 (cdr errdata)))))
16973 (defun org-time-string-to-seconds (s)
16974 "Convert a timestamp string to a number of seconds."
16975 (org-float-time (org-time-string-to-time s)))
16977 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16978 "Convert a time stamp to an absolute day number.
16979 If there is a specifier for a cyclic time stamp, get the closest
16980 date to DAYNR.
16981 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16982 The variable `date' is bound by the calendar when this is called."
16983 (cond
16984 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16985 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16986 daynr
16987 (+ daynr 1000)))
16988 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16989 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16990 (time-to-days (current-time))) (match-string 0 s)
16991 prefer show-all))
16992 (t (time-to-days
16993 (condition-case errdata
16994 (apply 'encode-time (org-parse-time-string s))
16995 (error (error "Bad timestamp `%s'%s\nError was: %s"
16996 s (if (not (and buffer pos))
16998 (format " at %d in buffer `%s'" pos buffer))
16999 (cdr errdata))))))))
17001 (defun org-days-to-iso-week (days)
17002 "Return the iso week number."
17003 (require 'cal-iso)
17004 (car (calendar-iso-from-absolute days)))
17006 (defun org-small-year-to-year (year)
17007 "Convert 2-digit years into 4-digit years.
17008 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17009 The year 2000 cannot be abbreviated. Any year larger than 99
17010 is returned unchanged."
17011 (if (< year 38)
17012 (setq year (+ 2000 year))
17013 (if (< year 100)
17014 (setq year (+ 1900 year))))
17015 year)
17017 (defun org-time-from-absolute (d)
17018 "Return the time corresponding to date D.
17019 D may be an absolute day number, or a calendar-type list (month day year)."
17020 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17021 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17023 (defun org-calendar-holiday ()
17024 "List of holidays, for Diary display in Org-mode."
17025 (require 'holidays)
17026 (let ((hl (funcall
17027 (if (fboundp 'calendar-check-holidays)
17028 'calendar-check-holidays 'check-calendar-holidays) date)))
17029 (if hl (mapconcat 'identity hl "; "))))
17031 (defun org-diary-sexp-entry (sexp entry date)
17032 "Process a SEXP diary ENTRY for DATE."
17033 (require 'diary-lib)
17034 (let ((result (if calendar-debug-sexp
17035 (let ((stack-trace-on-error t))
17036 (eval (car (read-from-string sexp))))
17037 (condition-case nil
17038 (eval (car (read-from-string sexp)))
17039 (error
17040 (beep)
17041 (message "Bad sexp at line %d in %s: %s"
17042 (org-current-line)
17043 (buffer-file-name) sexp)
17044 (sleep-for 2))))))
17045 (cond ((stringp result) (split-string result "; "))
17046 ((and (consp result)
17047 (not (consp (cdr result)))
17048 (stringp (cdr result))) (cdr result))
17049 ((and (consp result)
17050 (stringp (car result))) result)
17051 (result entry))))
17053 (defun org-diary-to-ical-string (frombuf)
17054 "Get iCalendar entries from diary entries in buffer FROMBUF.
17055 This uses the icalendar.el library."
17056 (let* ((tmpdir (if (featurep 'xemacs)
17057 (temp-directory)
17058 temporary-file-directory))
17059 (tmpfile (make-temp-name
17060 (expand-file-name "orgics" tmpdir)))
17061 buf rtn b e)
17062 (with-current-buffer frombuf
17063 (icalendar-export-region (point-min) (point-max) tmpfile)
17064 (setq buf (find-buffer-visiting tmpfile))
17065 (set-buffer buf)
17066 (goto-char (point-min))
17067 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17068 (setq b (match-beginning 0)))
17069 (goto-char (point-max))
17070 (if (re-search-backward "^END:VEVENT" nil t)
17071 (setq e (match-end 0)))
17072 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17073 (kill-buffer buf)
17074 (delete-file tmpfile)
17075 rtn))
17077 (defun org-closest-date (start current change prefer show-all)
17078 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17079 When PREFER is `past', return a date that is either CURRENT or past.
17080 When PREFER is `future', return a date that is either CURRENT or future.
17081 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17082 ;; Make the proper lists from the dates
17083 (catch 'exit
17084 (let ((a1 '(("h" . hour)
17085 ("d" . day)
17086 ("w" . week)
17087 ("m" . month)
17088 ("y" . year)))
17089 (shour (nth 2 (org-parse-time-string start)))
17090 dn dw sday cday n1 n2 n0
17091 d m y y1 y2 date1 date2 nmonths nm ny m2)
17093 (setq start (org-date-to-gregorian start)
17094 current (org-date-to-gregorian
17095 (if show-all
17096 current
17097 (time-to-days (current-time))))
17098 sday (calendar-absolute-from-gregorian start)
17099 cday (calendar-absolute-from-gregorian current))
17101 (if (<= cday sday) (throw 'exit sday))
17103 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17104 (setq dn (string-to-number (match-string 1 change))
17105 dw (cdr (assoc (match-string 2 change) a1)))
17106 (user-error "Invalid change specifier: %s" change))
17107 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17108 (cond
17109 ((eq dw 'hour)
17110 (let ((missing-hours
17111 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17112 dn)))
17113 (setq n1 (if (zerop missing-hours) cday
17114 (- cday (1+ (floor (/ missing-hours 24)))))
17115 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17116 ((eq dw 'day)
17117 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17118 n2 (+ n1 dn)))
17119 ((eq dw 'year)
17120 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17121 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17122 (setq date1 (list m d y1)
17123 n1 (calendar-absolute-from-gregorian date1)
17124 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17125 n2 (calendar-absolute-from-gregorian date2)))
17126 ((eq dw 'month)
17127 ;; approx number of month between the two dates
17128 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17129 ;; How often does dn fit in there?
17130 (setq d (nth 1 start) m (car start) y (nth 2 start)
17131 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17132 m (+ m nm)
17133 ny (floor (/ m 12))
17134 y (+ y ny)
17135 m (- m (* ny 12)))
17136 (while (> m 12) (setq m (- m 12) y (1+ y)))
17137 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17138 (setq m2 (+ m dn) y2 y)
17139 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17140 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17141 (while (<= n2 cday)
17142 (setq n1 n2 m m2 y y2)
17143 (setq m2 (+ m dn) y2 y)
17144 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17145 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17146 ;; Make sure n1 is the earlier date
17147 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17148 (if show-all
17149 (cond
17150 ((eq prefer 'past) (if (= cday n2) n2 n1))
17151 ((eq prefer 'future) (if (= cday n1) n1 n2))
17152 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17153 (cond
17154 ((eq prefer 'past) (if (= cday n2) n2 n1))
17155 ((eq prefer 'future) (if (= cday n1) n1 n2))
17156 (t (if (= cday n1) n1 n2)))))))
17158 (defun org-date-to-gregorian (date)
17159 "Turn any specification of DATE into a Gregorian date for the calendar."
17160 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17161 ((and (listp date) (= (length date) 3)) date)
17162 ((stringp date)
17163 (setq date (org-parse-time-string date))
17164 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17165 ((listp date)
17166 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17168 (defun org-parse-time-string (s &optional nodefault)
17169 "Parse the standard Org-mode time string.
17170 This should be a lot faster than the normal `parse-time-string'.
17171 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17172 hour and minute fields will be nil if not given."
17173 (cond ((string-match org-ts-regexp0 s)
17174 (list 0
17175 (if (or (match-beginning 8) (not nodefault))
17176 (string-to-number (or (match-string 8 s) "0")))
17177 (if (or (match-beginning 7) (not nodefault))
17178 (string-to-number (or (match-string 7 s) "0")))
17179 (string-to-number (match-string 4 s))
17180 (string-to-number (match-string 3 s))
17181 (string-to-number (match-string 2 s))
17182 nil nil nil))
17183 ((string-match "^<[^>]+>$" s)
17184 (decode-time (seconds-to-time (org-matcher-time s))))
17185 (t (error "Not a standard Org-mode time string: %s" s))))
17187 (defun org-timestamp-up (&optional arg)
17188 "Increase the date item at the cursor by one.
17189 If the cursor is on the year, change the year. If it is on the month,
17190 the day or the time, change that.
17191 With prefix ARG, change by that many units."
17192 (interactive "p")
17193 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17195 (defun org-timestamp-down (&optional arg)
17196 "Decrease the date item at the cursor by one.
17197 If the cursor is on the year, change the year. If it is on the month,
17198 the day or the time, change that.
17199 With prefix ARG, change by that many units."
17200 (interactive "p")
17201 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17203 (defun org-timestamp-up-day (&optional arg)
17204 "Increase the date in the time stamp by one day.
17205 With prefix ARG, change that many days."
17206 (interactive "p")
17207 (if (and (not (org-at-timestamp-p t))
17208 (org-at-heading-p))
17209 (org-todo 'up)
17210 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17212 (defun org-timestamp-down-day (&optional arg)
17213 "Decrease the date in the time stamp by one day.
17214 With prefix ARG, change that many days."
17215 (interactive "p")
17216 (if (and (not (org-at-timestamp-p t))
17217 (org-at-heading-p))
17218 (org-todo 'down)
17219 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17221 (defun org-at-timestamp-p (&optional inactive-ok)
17222 "Determine if the cursor is in or at a timestamp."
17223 (interactive)
17224 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17225 (pos (point))
17226 (ans (or (looking-at tsr)
17227 (save-excursion
17228 (skip-chars-backward "^[<\n\r\t")
17229 (if (> (point) (point-min)) (backward-char 1))
17230 (and (looking-at tsr)
17231 (> (- (match-end 0) pos) -1))))))
17232 (and ans
17233 (boundp 'org-ts-what)
17234 (setq org-ts-what
17235 (cond
17236 ((= pos (match-beginning 0)) 'bracket)
17237 ;; Point is considered to be "on the bracket" whether
17238 ;; it's really on it or right after it.
17239 ((= pos (1- (match-end 0))) 'bracket)
17240 ((= pos (match-end 0)) 'after)
17241 ((org-pos-in-match-range pos 2) 'year)
17242 ((org-pos-in-match-range pos 3) 'month)
17243 ((org-pos-in-match-range pos 7) 'hour)
17244 ((org-pos-in-match-range pos 8) 'minute)
17245 ((or (org-pos-in-match-range pos 4)
17246 (org-pos-in-match-range pos 5)) 'day)
17247 ((and (> pos (or (match-end 8) (match-end 5)))
17248 (< pos (match-end 0)))
17249 (- pos (or (match-end 8) (match-end 5))))
17250 (t 'day))))
17251 ans))
17253 (defun org-toggle-timestamp-type ()
17254 "Toggle the type (<active> or [inactive]) of a time stamp."
17255 (interactive)
17256 (when (org-at-timestamp-p t)
17257 (let ((beg (match-beginning 0)) (end (match-end 0))
17258 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17259 (save-excursion
17260 (goto-char beg)
17261 (while (re-search-forward "[][<>]" end t)
17262 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17263 t t)))
17264 (message "Timestamp is now %sactive"
17265 (if (equal (char-after beg) ?<) "" "in")))))
17267 (defun org-at-clock-log-p nil
17268 "Is the cursor on the clock log line?"
17269 (save-excursion
17270 (move-beginning-of-line 1)
17271 (looking-at "^[ \t]*CLOCK:")))
17273 (defvar org-clock-history) ; defined in org-clock.el
17274 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17275 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17276 "Change the date in the time stamp at point.
17277 The date will be changed by N times WHAT. WHAT can be `day', `month',
17278 `year', `minute', `second'. If WHAT is not given, the cursor position
17279 in the timestamp determines what will be changed.
17280 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17281 (let ((origin (point)) origin-cat
17282 with-hm inactive
17283 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17284 org-ts-what
17285 extra rem
17286 ts time time0 fixnext clrgx)
17287 (if (not (org-at-timestamp-p t))
17288 (user-error "Not at a timestamp"))
17289 (if (and (not what) (eq org-ts-what 'bracket))
17290 (org-toggle-timestamp-type)
17291 ;; Point isn't on brackets. Remember the part of the time-stamp
17292 ;; the point was in. Indeed, size of time-stamps may change,
17293 ;; but point must be kept in the same category nonetheless.
17294 (setq origin-cat org-ts-what)
17295 (if (and (not what) (not (eq org-ts-what 'day))
17296 org-display-custom-times
17297 (get-text-property (point) 'display)
17298 (not (get-text-property (1- (point)) 'display)))
17299 (setq org-ts-what 'day))
17300 (setq org-ts-what (or what org-ts-what)
17301 inactive (= (char-after (match-beginning 0)) ?\[)
17302 ts (match-string 0))
17303 (replace-match "")
17304 (when (string-match
17305 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17307 (setq extra (match-string 1 ts))
17308 (if suppress-tmp-delay
17309 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17310 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17311 (setq with-hm t))
17312 (setq time0 (org-parse-time-string ts))
17313 (when (and updown
17314 (eq org-ts-what 'minute)
17315 (not current-prefix-arg))
17316 ;; This looks like s-up and s-down. Change by one rounding step.
17317 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17318 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17319 (setcar (cdr time0) (+ (nth 1 time0)
17320 (if (> n 0) (- rem) (- dm rem))))))
17321 (setq time
17322 (encode-time (or (car time0) 0)
17323 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17324 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17325 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17326 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17327 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17328 (nthcdr 6 time0)))
17329 (when (and (member org-ts-what '(hour minute))
17330 extra
17331 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17332 (setq extra (org-modify-ts-extra
17333 extra
17334 (if (eq org-ts-what 'hour) 2 5)
17335 n dm)))
17336 (when (integerp org-ts-what)
17337 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17338 (if (eq what 'calendar)
17339 (let ((cal-date (org-get-date-from-calendar)))
17340 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17341 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17342 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17343 (setcar time0 (or (car time0) 0))
17344 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17345 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17346 (setq time (apply 'encode-time time0))))
17347 ;; Insert the new time-stamp, and ensure point stays in the same
17348 ;; category as before (i.e. not after the last position in that
17349 ;; category).
17350 (let ((pos (point)))
17351 ;; Stay before inserted string. `save-excursion' is of no use.
17352 (setq org-last-changed-timestamp
17353 (org-insert-time-stamp time with-hm inactive nil nil extra))
17354 (goto-char pos))
17355 (save-match-data
17356 (looking-at org-ts-regexp3)
17357 (goto-char (cond
17358 ;; `day' category ends before `hour' if any, or at
17359 ;; the end of the day name.
17360 ((eq origin-cat 'day)
17361 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17362 ((eq origin-cat 'hour) (min (match-end 7) origin))
17363 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17364 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17365 ;; `year' and `month' have both fixed size: point
17366 ;; couldn't have moved into another part.
17367 (t origin))))
17368 ;; Update clock if on a CLOCK line.
17369 (org-clock-update-time-maybe)
17370 ;; Maybe adjust the closest clock in `org-clock-history'
17371 (when org-clock-adjust-closest
17372 (if (not (and (org-at-clock-log-p)
17373 (< 1 (length (delq nil (mapcar 'marker-position
17374 org-clock-history))))))
17375 (message "No clock to adjust")
17376 (cond ((save-excursion ; fix previous clock?
17377 (re-search-backward org-ts-regexp0 nil t)
17378 (org-looking-back (concat org-clock-string " \\[")))
17379 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17380 ((save-excursion ; fix next clock?
17381 (re-search-backward org-ts-regexp0 nil t)
17382 (looking-at (concat org-ts-regexp0 "\\] =>")))
17383 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17384 (save-window-excursion
17385 ;; Find closest clock to point, adjust the previous/next one in history
17386 (let* ((p (save-excursion (org-back-to-heading t)))
17387 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17388 (clfixnth
17389 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17390 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17391 (if (not clfixpos)
17392 (message "No clock to adjust")
17393 (save-excursion
17394 (org-goto-marker-or-bmk clfixpos)
17395 (org-show-subtree)
17396 (when (re-search-forward clrgx nil t)
17397 (goto-char (match-beginning 1))
17398 (let (org-clock-adjust-closest)
17399 (org-timestamp-change n org-ts-what updown))
17400 (message "Clock adjusted in %s for heading: %s"
17401 (file-name-nondirectory (buffer-file-name))
17402 (org-get-heading t t)))))))))
17403 ;; Try to recenter the calendar window, if any.
17404 (if (and org-calendar-follow-timestamp-change
17405 (get-buffer-window "*Calendar*" t)
17406 (memq org-ts-what '(day month year)))
17407 (org-recenter-calendar (time-to-days time))))))
17409 (defun org-modify-ts-extra (s pos n dm)
17410 "Change the different parts of the lead-time and repeat fields in timestamp."
17411 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17412 ng h m new rem)
17413 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17414 (cond
17415 ((or (org-pos-in-match-range pos 2)
17416 (org-pos-in-match-range pos 3))
17417 (setq m (string-to-number (match-string 3 s))
17418 h (string-to-number (match-string 2 s)))
17419 (if (org-pos-in-match-range pos 2)
17420 (setq h (+ h n))
17421 (setq n (* dm (org-no-warnings (signum n))))
17422 (when (not (= 0 (setq rem (% m dm))))
17423 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17424 (setq m (+ m n)))
17425 (if (< m 0) (setq m (+ m 60) h (1- h)))
17426 (if (> m 59) (setq m (- m 60) h (1+ h)))
17427 (setq h (min 24 (max 0 h)))
17428 (setq ng 1 new (format "-%02d:%02d" h m)))
17429 ((org-pos-in-match-range pos 6)
17430 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17431 ((org-pos-in-match-range pos 5)
17432 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17434 ((org-pos-in-match-range pos 9)
17435 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17436 ((org-pos-in-match-range pos 8)
17437 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17439 (when ng
17440 (setq s (concat
17441 (substring s 0 (match-beginning ng))
17443 (substring s (match-end ng))))))
17446 (defun org-recenter-calendar (date)
17447 "If the calendar is visible, recenter it to DATE."
17448 (let ((cwin (get-buffer-window "*Calendar*" t)))
17449 (when cwin
17450 (let ((calendar-move-hook nil))
17451 (with-selected-window cwin
17452 (calendar-goto-date (if (listp date) date
17453 (calendar-gregorian-from-absolute date))))))))
17455 (defun org-goto-calendar (&optional arg)
17456 "Go to the Emacs calendar at the current date.
17457 If there is a time stamp in the current line, go to that date.
17458 A prefix ARG can be used to force the current date."
17459 (interactive "P")
17460 (let ((tsr org-ts-regexp) diff
17461 (calendar-move-hook nil)
17462 (calendar-view-holidays-initially-flag nil)
17463 (calendar-view-diary-initially-flag nil))
17464 (if (or (org-at-timestamp-p)
17465 (save-excursion
17466 (beginning-of-line 1)
17467 (looking-at (concat ".*" tsr))))
17468 (let ((d1 (time-to-days (current-time)))
17469 (d2 (time-to-days
17470 (org-time-string-to-time (match-string 1)))))
17471 (setq diff (- d2 d1))))
17472 (calendar)
17473 (calendar-goto-today)
17474 (if (and diff (not arg)) (calendar-forward-day diff))))
17476 (defun org-get-date-from-calendar ()
17477 "Return a list (month day year) of date at point in calendar."
17478 (with-current-buffer "*Calendar*"
17479 (save-match-data
17480 (calendar-cursor-to-date))))
17482 (defun org-date-from-calendar ()
17483 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17484 If there is already a time stamp at the cursor position, update it."
17485 (interactive)
17486 (if (org-at-timestamp-p t)
17487 (org-timestamp-change 0 'calendar)
17488 (let ((cal-date (org-get-date-from-calendar)))
17489 (org-insert-time-stamp
17490 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17492 (defcustom org-effort-durations
17493 `(("h" . 60)
17494 ("d" . ,(* 60 8))
17495 ("w" . ,(* 60 8 5))
17496 ("m" . ,(* 60 8 5 4))
17497 ("y" . ,(* 60 8 5 40)))
17498 "Conversion factor to minutes for an effort modifier.
17500 Each entry has the form (MODIFIER . MINUTES).
17502 In an effort string, a number followed by MODIFIER is multiplied
17503 by the specified number of MINUTES to obtain an effort in
17504 minutes.
17506 For example, if the value of this variable is ((\"hours\" . 60)), then an
17507 effort string \"2hours\" is equivalent to 120 minutes."
17508 :group 'org-agenda
17509 :version "24.1"
17510 :type '(alist :key-type (string :tag "Modifier")
17511 :value-type (number :tag "Minutes")))
17513 (defun org-minutes-to-clocksum-string (m)
17514 "Format number of minutes as a clocksum string.
17515 The format is determined by `org-time-clocksum-format',
17516 `org-time-clocksum-use-fractional' and
17517 `org-time-clocksum-fractional-format' and
17518 `org-time-clocksum-use-effort-durations'."
17519 (let ((clocksum "")
17520 (m (round m)) ; Don't allow fractions of minutes
17521 h d w mo y fmt n)
17522 (setq h (if org-time-clocksum-use-effort-durations
17523 (cdr (assoc "h" org-effort-durations)) 60)
17524 d (if org-time-clocksum-use-effort-durations
17525 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17526 w (if org-time-clocksum-use-effort-durations
17527 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17528 mo (if org-time-clocksum-use-effort-durations
17529 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17530 y (if org-time-clocksum-use-effort-durations
17531 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17532 ;; fractional format
17533 (if org-time-clocksum-use-fractional
17534 (cond
17535 ;; single format string
17536 ((stringp org-time-clocksum-fractional-format)
17537 (format org-time-clocksum-fractional-format (/ m (float h))))
17538 ;; choice of fractional formats for different time units
17539 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17540 (> (/ (truncate m) (* y d h)) 0))
17541 (format fmt (/ m (* y d (float h)))))
17542 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17543 (> (/ (truncate m) (* mo d h)) 0))
17544 (format fmt (/ m (* mo d (float h)))))
17545 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17546 (> (/ (truncate m) (* w d h)) 0))
17547 (format fmt (/ m (* w d (float h)))))
17548 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17549 (> (/ (truncate m) (* d h)) 0))
17550 (format fmt (/ m (* d (float h)))))
17551 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17552 (> (/ (truncate m) h) 0))
17553 (format fmt (/ m (float h))))
17554 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17555 (format fmt m))
17556 ;; fall back to smallest time unit with a format
17557 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17558 (format fmt (/ m (float h))))
17559 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17560 (format fmt (/ m (* d (float h)))))
17561 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17562 (format fmt (/ m (* w d (float h)))))
17563 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17564 (format fmt (/ m (* mo d (float h)))))
17565 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17566 (format fmt (/ m (* y d (float h))))))
17567 ;; standard (non-fractional) format, with single format string
17568 (if (stringp org-time-clocksum-format)
17569 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17570 ;; separate formats components
17571 (and (setq fmt (plist-get org-time-clocksum-format :years))
17572 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17573 (plist-get org-time-clocksum-format :require-years))
17574 (setq clocksum (concat clocksum (format fmt n))
17575 m (- m (* n y d h))))
17576 (and (setq fmt (plist-get org-time-clocksum-format :months))
17577 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17578 (plist-get org-time-clocksum-format :require-months))
17579 (setq clocksum (concat clocksum (format fmt n))
17580 m (- m (* n mo d h))))
17581 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17582 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17583 (plist-get org-time-clocksum-format :require-weeks))
17584 (setq clocksum (concat clocksum (format fmt n))
17585 m (- m (* n w d h))))
17586 (and (setq fmt (plist-get org-time-clocksum-format :days))
17587 (or (> (setq n (/ (truncate m) (* d h))) 0)
17588 (plist-get org-time-clocksum-format :require-days))
17589 (setq clocksum (concat clocksum (format fmt n))
17590 m (- m (* n d h))))
17591 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17592 (or (> (setq n (/ (truncate m) h)) 0)
17593 (plist-get org-time-clocksum-format :require-hours))
17594 (setq clocksum (concat clocksum (format fmt n))
17595 m (- m (* n h))))
17596 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17597 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17598 (setq clocksum (concat clocksum (format fmt m))))
17599 ;; return formatted time duration
17600 clocksum))))
17602 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17603 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17604 "Org mode version 8.0")
17606 (defun org-hours-to-clocksum-string (n)
17607 (org-minutes-to-clocksum-string (* n 60)))
17609 (defun org-hh:mm-string-to-minutes (s)
17610 "Convert a string H:MM to a number of minutes.
17611 If the string is just a number, interpret it as minutes.
17612 In fact, the first hh:mm or number in the string will be taken,
17613 there can be extra stuff in the string.
17614 If no number is found, the return value is 0."
17615 (cond
17616 ((integerp s) s)
17617 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17618 (+ (* (string-to-number (match-string 1 s)) 60)
17619 (string-to-number (match-string 2 s))))
17620 ((string-match "\\([0-9]+\\)" s)
17621 (string-to-number (match-string 1 s)))
17622 (t 0)))
17624 (defcustom org-image-actual-width t
17625 "Should we use the actual width of images when inlining them?
17627 When set to `t', always use the image width.
17629 When set to a number, use imagemagick (when available) to set
17630 the image's width to this value.
17632 When set to a number in a list, try to get the width from any
17633 #+ATTR.* keyword if it matches a width specification like
17635 #+ATTR_HTML: :width 300px
17637 and fall back on that number if none is found.
17639 When set to nil, try to get the width from an #+ATTR.* keyword
17640 and fall back on the original width if none is found.
17642 This requires Emacs >= 24.1, build with imagemagick support."
17643 :group 'org-appearance
17644 :version "24.4"
17645 :package-version '(Org . "8.0")
17646 :type '(choice
17647 (const :tag "Use the image width" t)
17648 (integer :tag "Use a number of pixels")
17649 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17650 (const :tag "Use #+ATTR* or don't resize" nil)))
17652 (defcustom org-agenda-inhibit-startup nil
17653 "Inhibit startup when preparing agenda buffers.
17654 When this variable is `t' (the default), the initialization of
17655 the Org agenda buffers is inhibited: e.g. the visibility state
17656 is not set, the tables are not re-aligned, etc."
17657 :type 'boolean
17658 :version "24.3"
17659 :group 'org-agenda)
17661 (defcustom org-agenda-ignore-drawer-properties nil
17662 "Avoid updating text properties when building the agenda.
17663 Properties are used to prepare buffers for effort estimates, appointments,
17664 and subtree-local categories.
17665 If you don't use these in the agenda, you can add them to this list and
17666 agenda building will be a bit faster.
17667 The value is a list, with zero or more of the symbols `effort', `appt',
17668 or `category'."
17669 :type '(set :greedy t
17670 (const effort)
17671 (const appt)
17672 (const category))
17673 :version "24.3"
17674 :group 'org-agenda)
17676 (defun org-duration-string-to-minutes (s &optional output-to-string)
17677 "Convert a duration string S to minutes.
17679 A bare number is interpreted as minutes, modifiers can be set by
17680 customizing `org-effort-durations' (which see).
17682 Entries containing a colon are interpreted as H:MM by
17683 `org-hh:mm-string-to-minutes'."
17684 (let ((result 0)
17685 (re (concat "\\([0-9.]+\\) *\\("
17686 (regexp-opt (mapcar 'car org-effort-durations))
17687 "\\)")))
17688 (while (string-match re s)
17689 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17690 (string-to-number (match-string 1 s))))
17691 (setq s (replace-match "" nil t s)))
17692 (setq result (floor result))
17693 (incf result (org-hh:mm-string-to-minutes s))
17694 (if output-to-string (number-to-string result) result)))
17696 ;;;; Files
17698 (defun org-save-all-org-buffers ()
17699 "Save all Org-mode buffers without user confirmation."
17700 (interactive)
17701 (message "Saving all Org-mode buffers...")
17702 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17703 (when (featurep 'org-id) (org-id-locations-save))
17704 (message "Saving all Org-mode buffers... done"))
17706 (defun org-revert-all-org-buffers ()
17707 "Revert all Org-mode buffers.
17708 Prompt for confirmation when there are unsaved changes.
17709 Be sure you know what you are doing before letting this function
17710 overwrite your changes.
17712 This function is useful in a setup where one tracks org files
17713 with a version control system, to revert on one machine after pulling
17714 changes from another. I believe the procedure must be like this:
17716 1. M-x org-save-all-org-buffers
17717 2. Pull changes from the other machine, resolve conflicts
17718 3. M-x org-revert-all-org-buffers"
17719 (interactive)
17720 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17721 (user-error "Abort"))
17722 (save-excursion
17723 (save-window-excursion
17724 (mapc
17725 (lambda (b)
17726 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17727 (with-current-buffer b buffer-file-name))
17728 (org-pop-to-buffer-same-window b)
17729 (revert-buffer t 'no-confirm)))
17730 (buffer-list))
17731 (when (and (featurep 'org-id) org-id-track-globally)
17732 (org-id-locations-load)))))
17734 ;;;; Agenda files
17736 ;;;###autoload
17737 (defun org-switchb (&optional arg)
17738 "Switch between Org buffers.
17739 With one prefix argument, restrict available buffers to files.
17740 With two prefix arguments, restrict available buffers to agenda files.
17742 Defaults to `iswitchb' for buffer name completion.
17743 Set `org-completion-use-ido' to make it use ido instead."
17744 (interactive "P")
17745 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17746 ((equal arg '(16)) (org-buffer-list 'agenda))
17747 (t (org-buffer-list))))
17748 (org-completion-use-iswitchb org-completion-use-iswitchb)
17749 (org-completion-use-ido org-completion-use-ido))
17750 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17751 (setq org-completion-use-iswitchb t))
17752 (org-pop-to-buffer-same-window
17753 (org-icompleting-read "Org buffer: "
17754 (mapcar 'list (mapcar 'buffer-name blist))
17755 nil t))))
17757 ;;; Define some older names previously used for this functionality
17758 ;;;###autoload
17759 (defalias 'org-ido-switchb 'org-switchb)
17760 ;;;###autoload
17761 (defalias 'org-iswitchb 'org-switchb)
17763 (defun org-buffer-list (&optional predicate exclude-tmp)
17764 "Return a list of Org buffers.
17765 PREDICATE can be `export', `files' or `agenda'.
17767 export restrict the list to Export buffers.
17768 files restrict the list to buffers visiting Org files.
17769 agenda restrict the list to buffers visiting agenda files.
17771 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17772 (let* ((bfn nil)
17773 (agenda-files (and (eq predicate 'agenda)
17774 (mapcar 'file-truename (org-agenda-files t))))
17775 (filter
17776 (cond
17777 ((eq predicate 'files)
17778 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17779 ((eq predicate 'export)
17780 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17781 ((eq predicate 'agenda)
17782 (lambda (b)
17783 (with-current-buffer b
17784 (and (derived-mode-p 'org-mode)
17785 (setq bfn (buffer-file-name b))
17786 (member (file-truename bfn) agenda-files)))))
17787 (t (lambda (b) (with-current-buffer b
17788 (or (derived-mode-p 'org-mode)
17789 (string-match "\*Org .*Export"
17790 (buffer-name b)))))))))
17791 (delq nil
17792 (mapcar
17793 (lambda(b)
17794 (if (and (funcall filter b)
17795 (or (not exclude-tmp)
17796 (not (string-match "tmp" (buffer-name b)))))
17798 nil))
17799 (buffer-list)))))
17801 (defun org-agenda-files (&optional unrestricted archives)
17802 "Get the list of agenda files.
17803 Optional UNRESTRICTED means return the full list even if a restriction
17804 is currently in place.
17805 When ARCHIVES is t, include all archive files that are really being
17806 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17807 `org-agenda-archives-mode' is t."
17808 (let ((files
17809 (cond
17810 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17811 ((stringp org-agenda-files) (org-read-agenda-file-list))
17812 ((listp org-agenda-files) org-agenda-files)
17813 (t (error "Invalid value of `org-agenda-files'")))))
17814 (setq files (apply 'append
17815 (mapcar (lambda (f)
17816 (if (file-directory-p f)
17817 (directory-files
17818 f t org-agenda-file-regexp)
17819 (list f)))
17820 files)))
17821 (when org-agenda-skip-unavailable-files
17822 (setq files (delq nil
17823 (mapcar (function
17824 (lambda (file)
17825 (and (file-readable-p file) file)))
17826 files))))
17827 (when (or (eq archives t)
17828 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17829 (setq files (org-add-archive-files files)))
17830 files))
17832 (defun org-agenda-file-p (&optional file)
17833 "Return non-nil, if FILE is an agenda file.
17834 If FILE is omitted, use the file associated with the current
17835 buffer."
17836 (member (or file (buffer-file-name))
17837 (org-agenda-files t)))
17839 (defun org-edit-agenda-file-list ()
17840 "Edit the list of agenda files.
17841 Depending on setup, this either uses customize to edit the variable
17842 `org-agenda-files', or it visits the file that is holding the list. In the
17843 latter case, the buffer is set up in a way that saving it automatically kills
17844 the buffer and restores the previous window configuration."
17845 (interactive)
17846 (if (stringp org-agenda-files)
17847 (let ((cw (current-window-configuration)))
17848 (find-file org-agenda-files)
17849 (org-set-local 'org-window-configuration cw)
17850 (org-add-hook 'after-save-hook
17851 (lambda ()
17852 (set-window-configuration
17853 (prog1 org-window-configuration
17854 (kill-buffer (current-buffer))))
17855 (org-install-agenda-files-menu)
17856 (message "New agenda file list installed"))
17857 nil 'local)
17858 (message "%s" (substitute-command-keys
17859 "Edit list and finish with \\[save-buffer]")))
17860 (customize-variable 'org-agenda-files)))
17862 (defun org-store-new-agenda-file-list (list)
17863 "Set new value for the agenda file list and save it correctly."
17864 (if (stringp org-agenda-files)
17865 (let ((fe (org-read-agenda-file-list t)) b u)
17866 (while (setq b (find-buffer-visiting org-agenda-files))
17867 (kill-buffer b))
17868 (with-temp-file org-agenda-files
17869 (insert
17870 (mapconcat
17871 (lambda (f) ;; Keep un-expanded entries.
17872 (if (setq u (assoc f fe))
17873 (cdr u)
17875 list "\n")
17876 "\n")))
17877 (let ((org-mode-hook nil) (org-inhibit-startup t)
17878 (org-insert-mode-line-in-empty-file nil))
17879 (setq org-agenda-files list)
17880 (customize-save-variable 'org-agenda-files org-agenda-files))))
17882 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17883 "Read the list of agenda files from a file.
17884 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17885 filenames, used by `org-store-new-agenda-file-list' to write back
17886 un-expanded file names."
17887 (when (file-directory-p org-agenda-files)
17888 (error "`org-agenda-files' cannot be a single directory"))
17889 (when (stringp org-agenda-files)
17890 (with-temp-buffer
17891 (insert-file-contents org-agenda-files)
17892 (mapcar
17893 (lambda (f)
17894 (let ((e (expand-file-name (substitute-in-file-name f)
17895 org-directory)))
17896 (if pair-with-expansion
17897 (cons e f)
17898 e)))
17899 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17901 ;;;###autoload
17902 (defun org-cycle-agenda-files ()
17903 "Cycle through the files in `org-agenda-files'.
17904 If the current buffer visits an agenda file, find the next one in the list.
17905 If the current buffer does not, find the first agenda file."
17906 (interactive)
17907 (let* ((fs (org-agenda-files t))
17908 (files (append fs (list (car fs))))
17909 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17910 file)
17911 (unless files (user-error "No agenda files"))
17912 (catch 'exit
17913 (while (setq file (pop files))
17914 (if (equal (file-truename file) tcf)
17915 (when (car files)
17916 (find-file (car files))
17917 (throw 'exit t))))
17918 (find-file (car fs)))
17919 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17921 (defun org-agenda-file-to-front (&optional to-end)
17922 "Move/add the current file to the top of the agenda file list.
17923 If the file is not present in the list, it is added to the front. If it is
17924 present, it is moved there. With optional argument TO-END, add/move to the
17925 end of the list."
17926 (interactive "P")
17927 (let ((org-agenda-skip-unavailable-files nil)
17928 (file-alist (mapcar (lambda (x)
17929 (cons (file-truename x) x))
17930 (org-agenda-files t)))
17931 (ctf (file-truename
17932 (or buffer-file-name
17933 (user-error "Please save the current buffer to a file"))))
17934 x had)
17935 (setq x (assoc ctf file-alist) had x)
17937 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17938 (if to-end
17939 (setq file-alist (append (delq x file-alist) (list x)))
17940 (setq file-alist (cons x (delq x file-alist))))
17941 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17942 (org-install-agenda-files-menu)
17943 (message "File %s to %s of agenda file list"
17944 (if had "moved" "added") (if to-end "end" "front"))))
17946 (defun org-remove-file (&optional file)
17947 "Remove current file from the list of files in variable `org-agenda-files'.
17948 These are the files which are being checked for agenda entries.
17949 Optional argument FILE means use this file instead of the current."
17950 (interactive)
17951 (let* ((org-agenda-skip-unavailable-files nil)
17952 (file (or file buffer-file-name
17953 (user-error "Current buffer does not visit a file")))
17954 (true-file (file-truename file))
17955 (afile (abbreviate-file-name file))
17956 (files (delq nil (mapcar
17957 (lambda (x)
17958 (if (equal true-file
17959 (file-truename x))
17960 nil x))
17961 (org-agenda-files t)))))
17962 (if (not (= (length files) (length (org-agenda-files t))))
17963 (progn
17964 (org-store-new-agenda-file-list files)
17965 (org-install-agenda-files-menu)
17966 (message "Removed file: %s" afile))
17967 (message "File was not in list: %s (not removed)" afile))))
17969 (defun org-file-menu-entry (file)
17970 (vector file (list 'find-file file) t))
17972 (defun org-check-agenda-file (file)
17973 "Make sure FILE exists. If not, ask user what to do."
17974 (when (not (file-exists-p file))
17975 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17976 (abbreviate-file-name file))
17977 (let ((r (downcase (read-char-exclusive))))
17978 (cond
17979 ((equal r ?r)
17980 (org-remove-file file)
17981 (throw 'nextfile t))
17982 (t (error "Abort"))))))
17984 (defun org-get-agenda-file-buffer (file)
17985 "Get a buffer visiting FILE. If the buffer needs to be created, add
17986 it to the list of buffers which might be released later."
17987 (let ((buf (org-find-base-buffer-visiting file)))
17988 (if buf
17989 buf ; just return it
17990 ;; Make a new buffer and remember it
17991 (setq buf (find-file-noselect file))
17992 (if buf (push buf org-agenda-new-buffers))
17993 buf)))
17995 (defun org-release-buffers (blist)
17996 "Release all buffers in list, asking the user for confirmation when needed.
17997 When a buffer is unmodified, it is just killed. When modified, it is saved
17998 \(if the user agrees) and then killed."
17999 (let (buf file)
18000 (while (setq buf (pop blist))
18001 (setq file (buffer-file-name buf))
18002 (when (and (buffer-modified-p buf)
18003 file
18004 (y-or-n-p (format "Save file %s? " file)))
18005 (with-current-buffer buf (save-buffer)))
18006 (kill-buffer buf))))
18008 (defun org-agenda-prepare-buffers (files)
18009 "Create buffers for all agenda files, protect archived trees and comments."
18010 (interactive)
18011 (let ((pa '(:org-archived t))
18012 (pc '(:org-comment t))
18013 (pall '(:org-archived t :org-comment t))
18014 (inhibit-read-only t)
18015 (org-inhibit-startup org-agenda-inhibit-startup)
18016 (rea (concat ":" org-archive-tag ":"))
18017 file re)
18018 (setq org-tag-alist-for-agenda nil
18019 org-tag-groups-alist-for-agenda nil)
18020 (save-excursion
18021 (save-restriction
18022 (while (setq file (pop files))
18023 (catch 'nextfile
18024 (if (bufferp file)
18025 (set-buffer file)
18026 (org-check-agenda-file file)
18027 (set-buffer (org-get-agenda-file-buffer file)))
18028 (widen)
18029 (org-set-regexps-and-options-for-tags)
18030 (goto-char (point-min))
18031 (let ((case-fold-search t))
18032 (when (search-forward "#+setupfile" nil t)
18033 ;; Don't set all regexps and options systematically as
18034 ;; this is only run for setting agenda tags from setup
18035 ;; file
18036 (org-set-regexps-and-options)))
18037 (or (memq 'category org-agenda-ignore-drawer-properties)
18038 (org-refresh-category-properties))
18039 (or (memq 'effort org-agenda-ignore-drawer-properties)
18040 (org-refresh-properties org-effort-property 'org-effort))
18041 (or (memq 'appt org-agenda-ignore-drawer-properties)
18042 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18043 (setq org-todo-keywords-for-agenda
18044 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18045 (setq org-done-keywords-for-agenda
18046 (append org-done-keywords-for-agenda org-done-keywords))
18047 (setq org-todo-keyword-alist-for-agenda
18048 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18049 (setq org-tag-alist-for-agenda
18050 (org-uniquify
18051 (append org-tag-alist-for-agenda
18052 org-tag-alist
18053 org-tag-persistent-alist)))
18054 (if org-group-tags
18055 (setq org-tag-groups-alist-for-agenda
18056 (org-uniquify-alist
18057 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18058 (org-with-silent-modifications
18059 (save-excursion
18060 (remove-text-properties (point-min) (point-max) pall)
18061 (when org-agenda-skip-archived-trees
18062 (goto-char (point-min))
18063 (while (re-search-forward rea nil t)
18064 (if (org-at-heading-p t)
18065 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18066 (goto-char (point-min))
18067 (setq re (format org-heading-keyword-regexp-format
18068 org-comment-string))
18069 (while (re-search-forward re nil t)
18070 (add-text-properties
18071 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18072 (setq org-todo-keywords-for-agenda
18073 (org-uniquify org-todo-keywords-for-agenda))
18074 (setq org-todo-keyword-alist-for-agenda
18075 (org-uniquify org-todo-keyword-alist-for-agenda))))
18078 ;;;; CDLaTeX minor mode
18080 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18081 "Keymap for the minor `org-cdlatex-mode'.")
18083 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18084 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18085 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18086 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18087 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18089 (defvar org-cdlatex-texmathp-advice-is-done nil
18090 "Flag remembering if we have applied the advice to texmathp already.")
18092 (define-minor-mode org-cdlatex-mode
18093 "Toggle the minor `org-cdlatex-mode'.
18094 This mode supports entering LaTeX environment and math in LaTeX fragments
18095 in Org-mode.
18096 \\{org-cdlatex-mode-map}"
18097 nil " OCDL" nil
18098 (when org-cdlatex-mode
18099 (require 'cdlatex)
18100 (run-hooks 'cdlatex-mode-hook)
18101 (cdlatex-compute-tables))
18102 (unless org-cdlatex-texmathp-advice-is-done
18103 (setq org-cdlatex-texmathp-advice-is-done t)
18104 (defadvice texmathp (around org-math-always-on activate)
18105 "Always return t in org-mode buffers.
18106 This is because we want to insert math symbols without dollars even outside
18107 the LaTeX math segments. If Orgmode thinks that point is actually inside
18108 an embedded LaTeX fragment, let texmathp do its job.
18109 \\[org-cdlatex-mode-map]"
18110 (interactive)
18111 (let (p)
18112 (cond
18113 ((not (derived-mode-p 'org-mode)) ad-do-it)
18114 ((eq this-command 'cdlatex-math-symbol)
18115 (setq ad-return-value t
18116 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18118 (let ((p (org-inside-LaTeX-fragment-p)))
18119 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18120 (setq ad-return-value t
18121 texmathp-why '("Org-mode embedded math" . 0))
18122 (if p ad-do-it)))))))))
18124 (defun turn-on-org-cdlatex ()
18125 "Unconditionally turn on `org-cdlatex-mode'."
18126 (org-cdlatex-mode 1))
18128 (defun org-try-cdlatex-tab ()
18129 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18130 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18131 - inside a LaTeX fragment, or
18132 - after the first word in a line, where an abbreviation expansion could
18133 insert a LaTeX environment."
18134 (when org-cdlatex-mode
18135 (cond
18136 ;; Before any word on the line: No expansion possible.
18137 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18138 ;; Just after first word on the line: Expand it. Make sure it
18139 ;; cannot happen on headlines, though.
18140 ((save-excursion
18141 (skip-chars-backward "a-zA-Z0-9*")
18142 (skip-chars-backward " \t")
18143 (and (bolp) (not (org-at-heading-p))))
18144 (cdlatex-tab) t)
18145 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18147 (defun org-cdlatex-underscore-caret (&optional arg)
18148 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18149 Revert to the normal definition outside of these fragments."
18150 (interactive "P")
18151 (if (org-inside-LaTeX-fragment-p)
18152 (call-interactively 'cdlatex-sub-superscript)
18153 (let (org-cdlatex-mode)
18154 (call-interactively (key-binding (vector last-input-event))))))
18156 (defun org-cdlatex-math-modify (&optional arg)
18157 "Execute `cdlatex-math-modify' in LaTeX fragments.
18158 Revert to the normal definition outside of these fragments."
18159 (interactive "P")
18160 (if (org-inside-LaTeX-fragment-p)
18161 (call-interactively 'cdlatex-math-modify)
18162 (let (org-cdlatex-mode)
18163 (call-interactively (key-binding (vector last-input-event))))))
18167 ;;;; LaTeX fragments
18169 (defvar org-latex-regexps
18170 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18171 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18172 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18173 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18174 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18175 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18176 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18177 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18178 "Regular expressions for matching embedded LaTeX.")
18180 (defun org-inside-LaTeX-fragment-p ()
18181 "Test if point is inside a LaTeX fragment.
18182 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18183 sequence appearing also before point.
18184 Even though the matchers for math are configurable, this function assumes
18185 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18186 delimiters are skipped when they have been removed by customization.
18187 The return value is nil, or a cons cell with the delimiter and the
18188 position of this delimiter.
18190 This function does a reasonably good job, but can locally be fooled by
18191 for example currency specifications. For example it will assume being in
18192 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18193 fragments that are properly closed, but during editing, we have to live
18194 with the uncertainty caused by missing closing delimiters. This function
18195 looks only before point, not after."
18196 (catch 'exit
18197 (let ((pos (point))
18198 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18199 (lim (progn
18200 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18201 (point)))
18202 dd-on str (start 0) m re)
18203 (goto-char pos)
18204 (when dodollar
18205 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18206 re (nth 1 (assoc "$" org-latex-regexps)))
18207 (while (string-match re str start)
18208 (cond
18209 ((= (match-end 0) (length str))
18210 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18211 ((= (match-end 0) (- (length str) 5))
18212 (throw 'exit nil))
18213 (t (setq start (match-end 0))))))
18214 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18215 (goto-char pos)
18216 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18217 (and (match-beginning 2) (throw 'exit nil))
18218 ;; count $$
18219 (while (re-search-backward "\\$\\$" lim t)
18220 (setq dd-on (not dd-on)))
18221 (goto-char pos)
18222 (if dd-on (cons "$$" m))))))
18224 (defun org-inside-latex-macro-p ()
18225 "Is point inside a LaTeX macro or its arguments?"
18226 (save-match-data
18227 (org-in-regexp
18228 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18230 (defvar org-latex-fragment-image-overlays nil
18231 "List of overlays carrying the images of latex fragments.")
18232 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18234 (defun org-remove-latex-fragment-image-overlays ()
18235 "Remove all overlays with LaTeX fragment images in current buffer."
18236 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18237 (setq org-latex-fragment-image-overlays nil))
18239 (defun org-preview-latex-fragment (&optional subtree)
18240 "Preview the LaTeX fragment at point, or all locally or globally.
18241 If the cursor is in a LaTeX fragment, create the image and overlay
18242 it over the source code. If there is no fragment at point, display
18243 all fragments in the current text, from one headline to the next. With
18244 prefix SUBTREE, display all fragments in the current subtree. With a
18245 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18246 the cursor is before the first headline,
18247 display all fragments in the buffer.
18248 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18249 (interactive "P")
18250 (unless buffer-file-name
18251 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18252 (when (display-graphic-p)
18253 (org-remove-latex-fragment-image-overlays)
18254 (save-excursion
18255 (save-restriction
18256 (let (beg end at msg)
18257 (cond
18258 ((or (equal subtree '(16))
18259 (not (save-excursion
18260 (re-search-backward org-outline-regexp-bol nil t))))
18261 (setq beg (point-min) end (point-max)
18262 msg "Creating images for buffer...%s"))
18263 ((equal subtree '(4))
18264 (org-back-to-heading)
18265 (setq beg (point) end (org-end-of-subtree t)
18266 msg "Creating images for subtree...%s"))
18268 (if (setq at (org-inside-LaTeX-fragment-p))
18269 (goto-char (max (point-min) (- (cdr at) 2)))
18270 (org-back-to-heading))
18271 (setq beg (point) end (progn (outline-next-heading) (point))
18272 msg (if at "Creating image...%s"
18273 "Creating images for entry...%s"))))
18274 (message msg "")
18275 (narrow-to-region beg end)
18276 (goto-char beg)
18277 (org-format-latex
18278 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18279 (file-name-nondirectory
18280 buffer-file-name)))
18281 default-directory 'overlays msg at 'forbuffer
18282 org-latex-create-formula-image-program)
18283 (message msg "done. Use `C-c C-c' to remove images."))))))
18285 (defun org-format-latex (prefix &optional dir overlays msg at
18286 forbuffer processing-type)
18287 "Replace LaTeX fragments with links to an image, and produce images.
18288 Some of the options can be changed using the variable
18289 `org-format-latex-options'."
18290 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18291 (let* ((prefixnodir (file-name-nondirectory prefix))
18292 (absprefix (expand-file-name prefix dir))
18293 (todir (file-name-directory absprefix))
18294 (opt org-format-latex-options)
18295 (optnew org-format-latex-options)
18296 (matchers (plist-get opt :matchers))
18297 (re-list org-latex-regexps)
18298 (cnt 0) txt hash link beg end re e checkdir
18299 string
18300 m n block-type block linkfile movefile ov)
18301 ;; Check the different regular expressions
18302 (while (setq e (pop re-list))
18303 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18304 block (if block-type "\n\n" ""))
18305 (when (member m matchers)
18306 (goto-char (point-min))
18307 (while (re-search-forward re nil t)
18308 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18309 (or (not overlays)
18310 (not (eq (get-char-property (match-beginning n)
18311 'org-overlay-type)
18312 'org-latex-overlay))))
18313 (cond
18314 ((eq processing-type 'verbatim))
18315 ((eq processing-type 'mathjax)
18316 ;; Prepare for MathJax processing.
18317 (setq string (match-string n))
18318 (when (member m '("$" "$1"))
18319 (save-excursion
18320 (delete-region (match-beginning n) (match-end n))
18321 (goto-char (match-beginning n))
18322 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18323 ((or (eq processing-type 'dvipng)
18324 (eq processing-type 'imagemagick))
18325 ;; Process to an image.
18326 (setq txt (match-string n)
18327 beg (match-beginning n) end (match-end n)
18328 cnt (1+ cnt))
18329 (let ((face (face-at-point))
18330 (fg (plist-get opt :foreground))
18331 (bg (plist-get opt :background))
18332 ;; Ensure full list is printed.
18333 print-length print-level)
18334 (when forbuffer
18335 ;; Get the colors from the face at point.
18336 (goto-char beg)
18337 (when (eq fg 'auto)
18338 (setq fg (face-attribute face :foreground nil 'default)))
18339 (when (eq bg 'auto)
18340 (setq bg (face-attribute face :background nil 'default)))
18341 (setq optnew (copy-sequence opt))
18342 (plist-put optnew :foreground fg)
18343 (plist-put optnew :background bg))
18344 (setq hash (sha1 (prin1-to-string
18345 (list org-format-latex-header
18346 org-latex-default-packages-alist
18347 org-latex-packages-alist
18348 org-format-latex-options
18349 forbuffer txt fg bg)))
18350 linkfile (format "%s_%s.png" prefix hash)
18351 movefile (format "%s_%s.png" absprefix hash)))
18352 (setq link (concat block "[[file:" linkfile "]]" block))
18353 (if msg (message msg cnt))
18354 (goto-char beg)
18355 (unless checkdir ; Ensure the directory exists.
18356 (setq checkdir t)
18357 (or (file-directory-p todir) (make-directory todir t)))
18358 (unless (file-exists-p movefile)
18359 (org-create-formula-image
18360 txt movefile optnew forbuffer processing-type))
18361 (if overlays
18362 (progn
18363 (mapc (lambda (o)
18364 (if (eq (overlay-get o 'org-overlay-type)
18365 'org-latex-overlay)
18366 (delete-overlay o)))
18367 (overlays-in beg end))
18368 (setq ov (make-overlay beg end))
18369 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18370 (if (featurep 'xemacs)
18371 (progn
18372 (overlay-put ov 'invisible t)
18373 (overlay-put
18374 ov 'end-glyph
18375 (make-glyph (vector 'png :file movefile))))
18376 (overlay-put
18377 ov 'display
18378 (list 'image :type 'png :file movefile :ascent 'center)))
18379 (push ov org-latex-fragment-image-overlays)
18380 (goto-char end))
18381 (delete-region beg end)
18382 (insert (org-add-props link
18383 (list 'org-latex-src
18384 (replace-regexp-in-string
18385 "\"" "" txt)
18386 'org-latex-src-embed-type
18387 (if block-type 'paragraph 'character))))))
18388 ((eq processing-type 'mathml)
18389 ;; Process to MathML
18390 (unless (save-match-data (org-format-latex-mathml-available-p))
18391 (user-error "LaTeX to MathML converter not configured"))
18392 (setq txt (match-string n)
18393 beg (match-beginning n) end (match-end n)
18394 cnt (1+ cnt))
18395 (if msg (message msg cnt))
18396 (goto-char beg)
18397 (delete-region beg end)
18398 (insert (org-format-latex-as-mathml
18399 txt block-type prefix dir)))
18401 (error "Unknown conversion type %s for LaTeX fragments"
18402 processing-type)))))))))
18404 (defun org-create-math-formula (latex-frag &optional mathml-file)
18405 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18406 Use `org-latex-to-mathml-convert-command'. If the conversion is
18407 sucessful, return the portion between \"<math...> </math>\"
18408 elements otherwise return nil. When MATHML-FILE is specified,
18409 write the results in to that file. When invoked as an
18410 interactive command, prompt for LATEX-FRAG, with initial value
18411 set to the current active region and echo the results for user
18412 inspection."
18413 (interactive (list (let ((frag (when (org-region-active-p)
18414 (buffer-substring-no-properties
18415 (region-beginning) (region-end)))))
18416 (read-string "LaTeX Fragment: " frag nil frag))))
18417 (unless latex-frag (error "Invalid LaTeX fragment"))
18418 (let* ((tmp-in-file (file-relative-name
18419 (make-temp-name (expand-file-name "ltxmathml-in"))))
18420 (ignore (write-region latex-frag nil tmp-in-file))
18421 (tmp-out-file (file-relative-name
18422 (make-temp-name (expand-file-name "ltxmathml-out"))))
18423 (cmd (format-spec
18424 org-latex-to-mathml-convert-command
18425 `((?j . ,(shell-quote-argument
18426 (expand-file-name org-latex-to-mathml-jar-file)))
18427 (?I . ,(shell-quote-argument tmp-in-file))
18428 (?o . ,(shell-quote-argument tmp-out-file)))))
18429 mathml shell-command-output)
18430 (when (org-called-interactively-p 'any)
18431 (unless (org-format-latex-mathml-available-p)
18432 (user-error "LaTeX to MathML converter not configured")))
18433 (message "Running %s" cmd)
18434 (setq shell-command-output (shell-command-to-string cmd))
18435 (setq mathml
18436 (when (file-readable-p tmp-out-file)
18437 (with-current-buffer (find-file-noselect tmp-out-file t)
18438 (goto-char (point-min))
18439 (when (re-search-forward
18440 (concat
18441 (regexp-quote
18442 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18443 "\\(.\\|\n\\)*"
18444 (regexp-quote "</math>")) nil t)
18445 (prog1 (match-string 0) (kill-buffer))))))
18446 (cond
18447 (mathml
18448 (setq mathml
18449 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18450 (when mathml-file
18451 (write-region mathml nil mathml-file))
18452 (when (org-called-interactively-p 'any)
18453 (message mathml)))
18454 ((message "LaTeX to MathML conversion failed")
18455 (message shell-command-output)))
18456 (delete-file tmp-in-file)
18457 (when (file-exists-p tmp-out-file)
18458 (delete-file tmp-out-file))
18459 mathml))
18461 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18462 prefix &optional dir)
18463 "Use `org-create-math-formula' but check local cache first."
18464 (let* ((absprefix (expand-file-name prefix dir))
18465 (print-length nil) (print-level nil)
18466 (formula-id (concat
18467 "formula-"
18468 (sha1
18469 (prin1-to-string
18470 (list latex-frag
18471 org-latex-to-mathml-convert-command)))))
18472 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18473 (formula-cache-dir (file-name-directory formula-cache)))
18475 (unless (file-directory-p formula-cache-dir)
18476 (make-directory formula-cache-dir t))
18478 (unless (file-exists-p formula-cache)
18479 (org-create-math-formula latex-frag formula-cache))
18481 (if (file-exists-p formula-cache)
18482 ;; Successful conversion. Return the link to MathML file.
18483 (org-add-props
18484 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18485 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18486 'org-latex-src-embed-type (if latex-frag-type
18487 'paragraph 'character)))
18488 ;; Failed conversion. Return the LaTeX fragment verbatim
18489 latex-frag)))
18491 (defun org-create-formula-image (string tofile options buffer &optional type)
18492 "Create an image from LaTeX source using dvipng or convert.
18493 This function calls either `org-create-formula-image-with-dvipng'
18494 or `org-create-formula-image-with-imagemagick' depending on the
18495 value of `org-latex-create-formula-image-program' or on the value
18496 of the optional TYPE variable.
18498 Note: ultimately these two function should be combined as they
18499 share a good deal of logic."
18500 (org-check-external-command
18501 "latex" "needed to convert LaTeX fragments to images")
18502 (funcall
18503 (case (or type org-latex-create-formula-image-program)
18504 ('dvipng
18505 (org-check-external-command
18506 "dvipng" "needed to convert LaTeX fragments to images")
18507 #'org-create-formula-image-with-dvipng)
18508 ('imagemagick
18509 (org-check-external-command
18510 "convert" "you need to install imagemagick")
18511 #'org-create-formula-image-with-imagemagick)
18512 (t (error
18513 "Invalid value of `org-latex-create-formula-image-program'")))
18514 string tofile options buffer))
18516 (declare-function org-export-get-backend "ox" (name))
18517 (declare-function org-export--get-global-options "ox" (&optional backend))
18518 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18519 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18520 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18521 (defun org-create-formula--latex-header ()
18522 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18523 (let ((info (org-combine-plists (org-export--get-global-options
18524 (org-export-get-backend 'latex))
18525 (org-export--get-inbuffer-options
18526 (org-export-get-backend 'latex)))))
18527 (org-latex-guess-babel-language
18528 (org-latex-guess-inputenc
18529 (org-splice-latex-header
18530 org-format-latex-header
18531 org-latex-default-packages-alist
18532 org-latex-packages-alist t
18533 (plist-get info :latex-header)))
18534 info)))
18536 ;; This function borrows from Ganesh Swami's latex2png.el
18537 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18538 "This calls dvipng."
18539 (require 'ox-latex)
18540 (let* ((tmpdir (if (featurep 'xemacs)
18541 (temp-directory)
18542 temporary-file-directory))
18543 (texfilebase (make-temp-name
18544 (expand-file-name "orgtex" tmpdir)))
18545 (texfile (concat texfilebase ".tex"))
18546 (dvifile (concat texfilebase ".dvi"))
18547 (pngfile (concat texfilebase ".png"))
18548 (fnh (if (featurep 'xemacs)
18549 (font-height (face-font 'default))
18550 (face-attribute 'default :height nil)))
18551 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18552 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18553 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18554 "Black"))
18555 (bg (or (plist-get options (if buffer :background :html-background))
18556 "Transparent")))
18557 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18558 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18559 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18560 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18561 (let ((latex-header (org-create-formula--latex-header)))
18562 (with-temp-file texfile
18563 (insert latex-header)
18564 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18565 (let ((dir default-directory))
18566 (condition-case nil
18567 (progn
18568 (cd tmpdir)
18569 (call-process "latex" nil nil nil texfile))
18570 (error nil))
18571 (cd dir))
18572 (if (not (file-exists-p dvifile))
18573 (progn (message "Failed to create dvi file from %s" texfile) nil)
18574 (condition-case nil
18575 (if (featurep 'xemacs)
18576 (call-process "dvipng" nil nil nil
18577 "-fg" fg "-bg" bg
18578 "-T" "tight"
18579 "-o" pngfile
18580 dvifile)
18581 (call-process "dvipng" nil nil nil
18582 "-fg" fg "-bg" bg
18583 "-D" dpi
18584 ;;"-x" scale "-y" scale
18585 "-T" "tight"
18586 "-o" pngfile
18587 dvifile))
18588 (error nil))
18589 (if (not (file-exists-p pngfile))
18590 (if org-format-latex-signal-error
18591 (error "Failed to create png file from %s" texfile)
18592 (message "Failed to create png file from %s" texfile)
18593 nil)
18594 ;; Use the requested file name and clean up
18595 (copy-file pngfile tofile 'replace)
18596 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18597 (if (file-exists-p (concat texfilebase e))
18598 (delete-file (concat texfilebase e))))
18599 pngfile))))
18601 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18602 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18603 "This calls convert, which is included into imagemagick."
18604 (require 'ox-latex)
18605 (let* ((tmpdir (if (featurep 'xemacs)
18606 (temp-directory)
18607 temporary-file-directory))
18608 (texfilebase (make-temp-name
18609 (expand-file-name "orgtex" tmpdir)))
18610 (texfile (concat texfilebase ".tex"))
18611 (pdffile (concat texfilebase ".pdf"))
18612 (pngfile (concat texfilebase ".png"))
18613 (fnh (if (featurep 'xemacs)
18614 (font-height (face-font 'default))
18615 (face-attribute 'default :height nil)))
18616 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18617 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18618 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18619 "black"))
18620 (bg (or (plist-get options (if buffer :background :html-background))
18621 "white")))
18622 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18623 (setq fg (org-latex-color-format fg)))
18624 (if (eq bg 'default) (setq bg (org-latex-color :background))
18625 (setq bg (org-latex-color-format
18626 (if (string= bg "Transparent") "white" bg))))
18627 (let ((latex-header (org-create-formula--latex-header)))
18628 (with-temp-file texfile
18629 (insert latex-header)
18630 (insert "\n\\begin{document}\n"
18631 "\\definecolor{fg}{rgb}{" fg "}\n"
18632 "\\definecolor{bg}{rgb}{" bg "}\n"
18633 "\n\\pagecolor{bg}\n"
18634 "\n{\\color{fg}\n"
18635 string
18636 "\n}\n"
18637 "\n\\end{document}\n")))
18638 (org-latex-compile texfile t)
18639 (if (not (file-exists-p pdffile))
18640 (progn (message "Failed to create pdf file from %s" texfile) nil)
18641 (condition-case nil
18642 (if (featurep 'xemacs)
18643 (call-process "convert" nil nil nil
18644 "-density" "96"
18645 "-trim"
18646 "-antialias"
18647 pdffile
18648 "-quality" "100"
18649 ;; "-sharpen" "0x1.0"
18650 pngfile)
18651 (call-process "convert" nil nil nil
18652 "-density" dpi
18653 "-trim"
18654 "-antialias"
18655 pdffile
18656 "-quality" "100"
18657 ;; "-sharpen" "0x1.0"
18658 pngfile))
18659 (error nil))
18660 (if (not (file-exists-p pngfile))
18661 (if org-format-latex-signal-error
18662 (error "Failed to create png file from %s" texfile)
18663 (message "Failed to create png file from %s" texfile)
18664 nil)
18665 ;; Use the requested file name and clean up
18666 (copy-file pngfile tofile 'replace)
18667 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18668 (if (file-exists-p (concat texfilebase e))
18669 (delete-file (concat texfilebase e))))
18670 pngfile))))
18672 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18673 "Fill a LaTeX header template TPL.
18674 In the template, the following place holders will be recognized:
18676 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18677 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18678 [PACKAGES] \\usepackage statements for PKG
18679 [NO-PACKAGES] do not include PKG
18680 [EXTRA] the string EXTRA
18681 [NO-EXTRA] do not include EXTRA
18683 For backward compatibility, if both the positive and the negative place
18684 holder is missing, the positive one (without the \"NO-\") will be
18685 assumed to be present at the end of the template.
18686 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18687 EXTRA is a string.
18688 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18689 (let (rpl (end ""))
18690 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18691 (setq rpl (if (or (match-end 1) (not def-pkg))
18692 "" (org-latex-packages-to-string def-pkg snippets-p t))
18693 tpl (replace-match rpl t t tpl))
18694 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18696 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18697 (setq rpl (if (or (match-end 1) (not pkg))
18698 "" (org-latex-packages-to-string pkg snippets-p t))
18699 tpl (replace-match rpl t t tpl))
18700 (if pkg (setq end
18701 (concat end "\n"
18702 (org-latex-packages-to-string pkg snippets-p)))))
18704 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18705 (setq rpl (if (or (match-end 1) (not extra))
18706 "" (concat extra "\n"))
18707 tpl (replace-match rpl t t tpl))
18708 (if (and extra (string-match "\\S-" extra))
18709 (setq end (concat end "\n" extra))))
18711 (if (string-match "\\S-" end)
18712 (concat tpl "\n" end)
18713 tpl)))
18715 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18716 "Turn an alist of packages into a string with the \\usepackage macros."
18717 (setq pkg (mapconcat (lambda(p)
18718 (cond
18719 ((stringp p) p)
18720 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18721 (format "%% Package %s omitted" (cadr p)))
18722 ((equal "" (car p))
18723 (format "\\usepackage{%s}" (cadr p)))
18725 (format "\\usepackage[%s]{%s}"
18726 (car p) (cadr p)))))
18728 "\n"))
18729 (if newline (concat pkg "\n") pkg))
18731 (defun org-dvipng-color (attr)
18732 "Return a RGB color specification for dvipng."
18733 (apply 'format "rgb %s %s %s"
18734 (mapcar 'org-normalize-color
18735 (if (featurep 'xemacs)
18736 (color-rgb-components
18737 (face-property 'default
18738 (cond ((eq attr :foreground) 'foreground)
18739 ((eq attr :background) 'background))))
18740 (color-values (face-attribute 'default attr nil))))))
18742 (defun org-dvipng-color-format (color-name)
18743 "Convert COLOR-NAME to a RGB color value for dvipng."
18744 (apply 'format "rgb %s %s %s"
18745 (mapcar 'org-normalize-color
18746 (color-values color-name))))
18748 (defun org-latex-color (attr)
18749 "Return a RGB color for the LaTeX color package."
18750 (apply 'format "%s,%s,%s"
18751 (mapcar 'org-normalize-color
18752 (if (featurep 'xemacs)
18753 (color-rgb-components
18754 (face-property 'default
18755 (cond ((eq attr :foreground) 'foreground)
18756 ((eq attr :background) 'background))))
18757 (color-values (face-attribute 'default attr nil))))))
18759 (defun org-latex-color-format (color-name)
18760 "Convert COLOR-NAME to a RGB color value."
18761 (apply 'format "%s,%s,%s"
18762 (mapcar 'org-normalize-color
18763 (color-values color-name))))
18765 (defun org-normalize-color (value)
18766 "Return string to be used as color value for an RGB component."
18767 (format "%g" (/ value 65535.0)))
18771 ;; Image display
18773 (defvar org-inline-image-overlays nil)
18774 (make-variable-buffer-local 'org-inline-image-overlays)
18776 (defun org-toggle-inline-images (&optional include-linked)
18777 "Toggle the display of inline images.
18778 INCLUDE-LINKED is passed to `org-display-inline-images'."
18779 (interactive "P")
18780 (if org-inline-image-overlays
18781 (progn
18782 (org-remove-inline-images)
18783 (message "Inline image display turned off"))
18784 (org-display-inline-images include-linked)
18785 (if (and (org-called-interactively-p)
18786 org-inline-image-overlays)
18787 (message "%d images displayed inline"
18788 (length org-inline-image-overlays))
18789 (message "No images to display inline"))))
18791 (defun org-redisplay-inline-images ()
18792 "Refresh the display of inline images."
18793 (interactive)
18794 (if (not org-inline-image-overlays)
18795 (org-toggle-inline-images)
18796 (org-toggle-inline-images)
18797 (org-toggle-inline-images)))
18799 (defun org-display-inline-images (&optional include-linked refresh beg end)
18800 "Display inline images.
18802 An inline image is a link which follows either of these
18803 conventions:
18805 1. Its path is a file with an extension matching return value
18806 from `image-file-name-regexp' and it has no contents.
18808 2. Its description consists in a single link of the previous
18809 type.
18811 When optional argument INCLUDE-LINKED is non-nil, also links with
18812 a text description part will be inlined. This can be nice for
18813 a quick look at those images, but it does not reflect what
18814 exported files will look like.
18816 When optional argument REFRESH is non-nil, refresh existing
18817 images between BEG and END. This will create new image displays
18818 only if necessary. BEG and END default to the buffer
18819 boundaries."
18820 (interactive "P")
18821 (when (display-graphic-p)
18822 (unless refresh
18823 (org-remove-inline-images)
18824 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18825 (org-with-wide-buffer
18826 (goto-char (or beg (point-min)))
18827 (let ((case-fold-search t)
18828 (file-extension-re (org-image-file-name-regexp)))
18829 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18830 (let ((link (save-match-data (org-element-context))))
18831 ;; Check if we're at an inline image.
18832 (when (and (equal (org-element-property :type link) "file")
18833 (or include-linked
18834 (not (org-element-property :contents-begin link)))
18835 (let ((parent (org-element-property :parent link)))
18836 (or (not (eq (org-element-type parent) 'link))
18837 (not (cdr (org-element-contents parent)))))
18838 (org-string-match-p file-extension-re
18839 (org-element-property :path link)))
18840 (let ((file (expand-file-name (org-element-property :path link))))
18841 (when (file-exists-p file)
18842 (let ((width
18843 ;; Apply `org-image-actual-width' specifications.
18844 (cond
18845 ((not (image-type-available-p 'imagemagick)) nil)
18846 ((eq org-image-actual-width t) nil)
18847 ((listp org-image-actual-width)
18849 ;; First try to find a width among
18850 ;; attributes associated to the paragraph
18851 ;; containing link.
18852 (let ((paragraph
18853 (let ((e link))
18854 (while (and (setq e (org-element-property
18855 :parent e))
18856 (not (eq (org-element-type e)
18857 'paragraph))))
18858 e)))
18859 (when paragraph
18860 (save-excursion
18861 (goto-char (org-element-property :begin paragraph))
18862 (when (save-match-data
18863 (re-search-forward
18864 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18865 (org-element-property
18866 :post-affiliated paragraph)
18868 (string-to-number (match-string 1))))))
18869 ;; Otherwise, fall-back to provided number.
18870 (car org-image-actual-width)))
18871 ((numberp org-image-actual-width)
18872 org-image-actual-width)))
18873 (old (get-char-property-and-overlay
18874 (org-element-property :begin link)
18875 'org-image-overlay)))
18876 (if (and (car-safe old) refresh)
18877 (image-refresh (overlay-get (cdr old) 'display))
18878 (let ((image (save-match-data
18879 (create-image file
18880 (and width 'imagemagick)
18882 :width width))))
18883 (when image
18884 (let* ((link
18885 ;; If inline image is the description
18886 ;; of another link, be sure to
18887 ;; consider the latter as the one to
18888 ;; apply the overlay on.
18889 (let ((parent
18890 (org-element-property :parent link)))
18891 (if (eq (org-element-type parent) 'link)
18892 parent
18893 link)))
18894 (ov (make-overlay
18895 (org-element-property :begin link)
18896 (progn
18897 (goto-char
18898 (org-element-property :end link))
18899 (skip-chars-backward " \t")
18900 (point)))))
18901 (overlay-put ov 'display image)
18902 (overlay-put ov 'face 'default)
18903 (overlay-put ov 'org-image-overlay t)
18904 (overlay-put
18905 ov 'modification-hooks
18906 (list 'org-display-inline-remove-overlay))
18907 (push ov org-inline-image-overlays)))))))))))))))
18909 (define-obsolete-function-alias
18910 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18912 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18913 "Remove inline-display overlay if a corresponding region is modified."
18914 (let ((inhibit-modification-hooks t))
18915 (when (and ov after)
18916 (delete ov org-inline-image-overlays)
18917 (delete-overlay ov))))
18919 (defun org-remove-inline-images ()
18920 "Remove inline display of images."
18921 (interactive)
18922 (mapc 'delete-overlay org-inline-image-overlays)
18923 (setq org-inline-image-overlays nil))
18925 ;;;; Key bindings
18927 ;; Outline functions from `outline-mode-prefix-map'
18928 ;; that can be remapped in Org:
18929 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18930 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18931 (define-key org-mode-map [remap outline-forward-same-level]
18932 'org-forward-heading-same-level)
18933 (define-key org-mode-map [remap outline-backward-same-level]
18934 'org-backward-heading-same-level)
18935 (define-key org-mode-map [remap show-branches]
18936 'org-kill-note-or-show-branches)
18937 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18938 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18939 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18941 ;; Outline functions from `outline-mode-prefix-map' that can not
18942 ;; be remapped in Org:
18944 ;; - the column "key binding" shows whether the Outline function is still
18945 ;; available in Org mode on the same key that it has been bound to in
18946 ;; Outline mode:
18947 ;; - "overridden": key used for a different functionality in Org mode
18948 ;; - else: key still bound to the same Outline function in Org mode
18950 ;; | Outline function | key binding | Org replacement |
18951 ;; |------------------------------------+-------------+-----------------------|
18952 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18953 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18954 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18955 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18956 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18957 ;; | `show-entry' | overridden | no replacement |
18958 ;; | `show-children' | `C-c C-i' | visibility cycling |
18959 ;; | `show-branches' | `C-c C-k' | still same function |
18960 ;; | `show-subtree' | overridden | visibility cycling |
18961 ;; | `show-all' | overridden | no replacement |
18962 ;; | `hide-subtree' | overridden | visibility cycling |
18963 ;; | `hide-body' | overridden | no replacement |
18964 ;; | `hide-entry' | overridden | visibility cycling |
18965 ;; | `hide-leaves' | overridden | no replacement |
18966 ;; | `hide-sublevels' | overridden | no replacement |
18967 ;; | `hide-other' | overridden | no replacement |
18969 ;; Make `C-c C-x' a prefix key
18970 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18972 ;; TAB key with modifiers
18973 (org-defkey org-mode-map "\C-i" 'org-cycle)
18974 (org-defkey org-mode-map [(tab)] 'org-cycle)
18975 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18976 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18977 ;; The following line is necessary under Suse GNU/Linux
18978 (unless (featurep 'xemacs)
18979 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18980 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18981 (define-key org-mode-map [backtab] 'org-shifttab)
18983 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18984 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18985 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18987 ;; Cursor keys with modifiers
18988 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18989 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18990 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18991 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18993 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18994 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18995 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18996 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18998 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18999 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19000 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19001 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19003 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19004 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19005 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19006 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19008 ;; Babel keys
19009 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19010 (mapc (lambda (pair)
19011 (define-key org-babel-map (car pair) (cdr pair)))
19012 org-babel-key-bindings)
19014 ;;; Extra keys for tty access.
19015 ;; We only set them when really needed because otherwise the
19016 ;; menus don't show the simple keys
19018 (when (or org-use-extra-keys
19019 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19020 (not window-system))
19021 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19022 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19023 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19024 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19025 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19026 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19027 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19028 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19029 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19030 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19031 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19032 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19033 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19034 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19035 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19036 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19037 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19038 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19039 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19040 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19041 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19042 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19043 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19044 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19045 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19046 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19047 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19048 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19050 ;; All the other keys
19052 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19053 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19054 (if (boundp 'narrow-map)
19055 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19056 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19057 (if (boundp 'narrow-map)
19058 (org-defkey narrow-map "b" 'org-narrow-to-block)
19059 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19060 (if (boundp 'narrow-map)
19061 (org-defkey narrow-map "e" 'org-narrow-to-element)
19062 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19063 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19064 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19065 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19066 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19067 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19068 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19069 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19070 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19071 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19072 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19073 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19074 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19075 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19076 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19077 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19078 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19079 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19080 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19081 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19082 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19083 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19084 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19085 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19086 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19087 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19088 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19089 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19090 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19091 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19092 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19093 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19094 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19095 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19096 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19097 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19098 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19099 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19100 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19101 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19102 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19103 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19104 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19105 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19106 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19107 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19108 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19109 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19110 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19111 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19112 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19113 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19114 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19115 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19116 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19117 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19118 (org-defkey org-mode-map "\C-c^" 'org-sort)
19119 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19120 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19121 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19122 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19123 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19124 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19125 (org-defkey org-mode-map "\C-m" 'org-return)
19126 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19127 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19128 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19129 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19130 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19131 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19132 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19133 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19134 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19135 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19136 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19137 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19138 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19139 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19140 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19141 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19142 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19143 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19144 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19145 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19146 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19147 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19148 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19150 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19151 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19152 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19154 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19155 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19156 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19157 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19158 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19159 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19160 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19161 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19162 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19163 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19164 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19165 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19166 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19167 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19168 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19169 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19170 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19171 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19172 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19173 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19174 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19175 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19176 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19178 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19179 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19180 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19181 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19182 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19184 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19186 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19188 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19189 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19191 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19194 (when (featurep 'xemacs)
19195 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19198 (defconst org-speed-commands-default
19200 ("Outline Navigation")
19201 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19202 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19203 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19204 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19205 ("F" . org-next-block)
19206 ("B" . org-previous-block)
19207 ("u" . (org-speed-move-safe 'outline-up-heading))
19208 ("j" . org-goto)
19209 ("g" . (org-refile t))
19210 ("Outline Visibility")
19211 ("c" . org-cycle)
19212 ("C" . org-shifttab)
19213 (" " . org-display-outline-path)
19214 ("s" . org-narrow-to-subtree)
19215 ("=" . org-columns)
19216 ("Outline Structure Editing")
19217 ("U" . org-shiftmetaup)
19218 ("D" . org-shiftmetadown)
19219 ("r" . org-metaright)
19220 ("l" . org-metaleft)
19221 ("R" . org-shiftmetaright)
19222 ("L" . org-shiftmetaleft)
19223 ("i" . (progn (forward-char 1) (call-interactively
19224 'org-insert-heading-respect-content)))
19225 ("^" . org-sort)
19226 ("w" . org-refile)
19227 ("a" . org-archive-subtree-default-with-confirmation)
19228 ("@" . org-mark-subtree)
19229 ("#" . org-toggle-comment)
19230 ("Clock Commands")
19231 ("I" . org-clock-in)
19232 ("O" . org-clock-out)
19233 ("Meta Data Editing")
19234 ("t" . org-todo)
19235 ("," . (org-priority))
19236 ("0" . (org-priority ?\ ))
19237 ("1" . (org-priority ?A))
19238 ("2" . (org-priority ?B))
19239 ("3" . (org-priority ?C))
19240 (":" . org-set-tags-command)
19241 ("e" . org-set-effort)
19242 ("E" . org-inc-effort)
19243 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19244 (org-entry-put (point) "APPT_WARNTIME" m)))
19245 ("Agenda Views etc")
19246 ("v" . org-agenda)
19247 ("/" . org-sparse-tree)
19248 ("Misc")
19249 ("o" . org-open-at-point)
19250 ("?" . org-speed-command-help)
19251 ("<" . (org-agenda-set-restriction-lock 'subtree))
19252 (">" . (org-agenda-remove-restriction-lock))
19254 "The default speed commands.")
19256 (defun org-print-speed-command (e)
19257 (if (> (length (car e)) 1)
19258 (progn
19259 (princ "\n")
19260 (princ (car e))
19261 (princ "\n")
19262 (princ (make-string (length (car e)) ?-))
19263 (princ "\n"))
19264 (princ (car e))
19265 (princ " ")
19266 (if (symbolp (cdr e))
19267 (princ (symbol-name (cdr e)))
19268 (prin1 (cdr e)))
19269 (princ "\n")))
19271 (defun org-speed-command-help ()
19272 "Show the available speed commands."
19273 (interactive)
19274 (if (not org-use-speed-commands)
19275 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19276 (with-output-to-temp-buffer "*Help*"
19277 (princ "User-defined Speed commands\n===========================\n")
19278 (mapc 'org-print-speed-command org-speed-commands-user)
19279 (princ "\n")
19280 (princ "Built-in Speed commands\n=======================\n")
19281 (mapc 'org-print-speed-command org-speed-commands-default))
19282 (with-current-buffer "*Help*"
19283 (setq truncate-lines t))))
19285 (defun org-speed-move-safe (cmd)
19286 "Execute CMD, but make sure that the cursor always ends up in a headline.
19287 If not, return to the original position and throw an error."
19288 (interactive)
19289 (let ((pos (point)))
19290 (call-interactively cmd)
19291 (unless (and (bolp) (org-at-heading-p))
19292 (goto-char pos)
19293 (error "Boundary reached while executing %s" cmd))))
19295 (defvar org-self-insert-command-undo-counter 0)
19297 (defvar org-table-auto-blank-field) ; defined in org-table.el
19298 (defvar org-speed-command nil)
19300 (define-obsolete-function-alias
19301 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19303 (defun org-speed-command-activate (keys)
19304 "Hook for activating single-letter speed commands.
19305 `org-speed-commands-default' specifies a minimal command set.
19306 Use `org-speed-commands-user' for further customization."
19307 (when (or (and (bolp) (looking-at org-outline-regexp))
19308 (and (functionp org-use-speed-commands)
19309 (funcall org-use-speed-commands)))
19310 (cdr (assoc keys (append org-speed-commands-user
19311 org-speed-commands-default)))))
19313 (define-obsolete-function-alias
19314 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19316 (defun org-babel-speed-command-activate (keys)
19317 "Hook for activating single-letter code block commands."
19318 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19319 (cdr (assoc keys org-babel-key-bindings))))
19321 (defcustom org-speed-command-hook
19322 '(org-speed-command-default-hook org-babel-speed-command-hook)
19323 "Hook for activating speed commands at strategic locations.
19324 Hook functions are called in sequence until a valid handler is
19325 found.
19327 Each hook takes a single argument, a user-pressed command key
19328 which is also a `self-insert-command' from the global map.
19330 Within the hook, examine the cursor position and the command key
19331 and return nil or a valid handler as appropriate. Handler could
19332 be one of an interactive command, a function, or a form.
19334 Set `org-use-speed-commands' to non-nil value to enable this
19335 hook. The default setting is `org-speed-command-activate'."
19336 :group 'org-structure
19337 :version "24.1"
19338 :type 'hook)
19340 (defun org-self-insert-command (N)
19341 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19342 If the cursor is in a table looking at whitespace, the whitespace is
19343 overwritten, and the table is not marked as requiring realignment."
19344 (interactive "p")
19345 (org-check-before-invisible-edit 'insert)
19346 (cond
19347 ((and org-use-speed-commands
19348 (setq org-speed-command
19349 (run-hook-with-args-until-success
19350 'org-speed-command-hook (this-command-keys))))
19351 (cond
19352 ((commandp org-speed-command)
19353 (setq this-command org-speed-command)
19354 (call-interactively org-speed-command))
19355 ((functionp org-speed-command)
19356 (funcall org-speed-command))
19357 ((and org-speed-command (listp org-speed-command))
19358 (eval org-speed-command))
19359 (t (let (org-use-speed-commands)
19360 (call-interactively 'org-self-insert-command)))))
19361 ((and
19362 (org-table-p)
19363 (progn
19364 ;; check if we blank the field, and if that triggers align
19365 (and (featurep 'org-table) org-table-auto-blank-field
19366 (member last-command
19367 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19368 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19369 ;; got extra space, this field does not determine column width
19370 (let (org-table-may-need-update) (org-table-blank-field))
19371 ;; no extra space, this field may determine column width
19372 (org-table-blank-field)))
19374 (eq N 1)
19375 (looking-at "[^|\n]* |"))
19376 (let (org-table-may-need-update)
19377 (goto-char (1- (match-end 0)))
19378 (backward-delete-char 1)
19379 (goto-char (match-beginning 0))
19380 (self-insert-command N)))
19382 (setq org-table-may-need-update t)
19383 (self-insert-command N)
19384 (org-fix-tags-on-the-fly)
19385 (if org-self-insert-cluster-for-undo
19386 (if (not (eq last-command 'org-self-insert-command))
19387 (setq org-self-insert-command-undo-counter 1)
19388 (if (>= org-self-insert-command-undo-counter 20)
19389 (setq org-self-insert-command-undo-counter 1)
19390 (and (> org-self-insert-command-undo-counter 0)
19391 buffer-undo-list (listp buffer-undo-list)
19392 (not (cadr buffer-undo-list)) ; remove nil entry
19393 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19394 (setq org-self-insert-command-undo-counter
19395 (1+ org-self-insert-command-undo-counter))))))))
19397 (defun org-check-before-invisible-edit (kind)
19398 "Check is editing if kind KIND would be dangerous with invisible text around.
19399 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19400 ;; First, try to get out of here as quickly as possible, to reduce overhead
19401 (if (and org-catch-invisible-edits
19402 (or (not (boundp 'visible-mode)) (not visible-mode))
19403 (or (get-char-property (point) 'invisible)
19404 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19405 ;; OK, we need to take a closer look
19406 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19407 (invisible-before-point (if (bobp) nil (get-char-property
19408 (1- (point)) 'invisible)))
19409 (border-and-ok-direction
19411 ;; Check if we are acting predictably before invisible text
19412 (and invisible-at-point (not invisible-before-point)
19413 (memq kind '(insert delete-backward)))
19414 ;; Check if we are acting predictably after invisible text
19415 ;; This works not well, and I have turned it off. It seems
19416 ;; better to always show and stop after invisible text.
19417 ;; (and (not invisible-at-point) invisible-before-point
19418 ;; (memq kind '(insert delete)))
19420 (when (or (memq invisible-at-point '(outline org-hide-block t))
19421 (memq invisible-before-point '(outline org-hide-block t)))
19422 (if (eq org-catch-invisible-edits 'error)
19423 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19424 (if (and org-custom-properties-overlays
19425 (y-or-n-p "Display invisible properties in this buffer? "))
19426 (org-toggle-custom-properties-visibility)
19427 ;; Make the area visible
19428 (save-excursion
19429 (if invisible-before-point
19430 (goto-char (previous-single-char-property-change
19431 (point) 'invisible)))
19432 (org-cycle))
19433 (cond
19434 ((eq org-catch-invisible-edits 'show)
19435 ;; That's it, we do the edit after showing
19436 (message
19437 "Unfolding invisible region around point before editing")
19438 (sit-for 1))
19439 ((and (eq org-catch-invisible-edits 'smart)
19440 border-and-ok-direction)
19441 (message "Unfolding invisible region around point before editing"))
19443 ;; Don't do the edit, make the user repeat it in full visibility
19444 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19446 (defun org-fix-tags-on-the-fly ()
19447 (when (and (equal (char-after (point-at-bol)) ?*)
19448 (org-at-heading-p))
19449 (org-align-tags-here org-tags-column)))
19451 (defun org-delete-backward-char (N)
19452 "Like `delete-backward-char', insert whitespace at field end in tables.
19453 When deleting backwards, in tables this function will insert whitespace in
19454 front of the next \"|\" separator, to keep the table aligned. The table will
19455 still be marked for re-alignment if the field did fill the entire column,
19456 because, in this case the deletion might narrow the column."
19457 (interactive "p")
19458 (save-match-data
19459 (org-check-before-invisible-edit 'delete-backward)
19460 (if (and (org-table-p)
19461 (eq N 1)
19462 (string-match "|" (buffer-substring (point-at-bol) (point)))
19463 (looking-at ".*?|"))
19464 (let ((pos (point))
19465 (noalign (looking-at "[^|\n\r]* |"))
19466 (c org-table-may-need-update))
19467 (backward-delete-char N)
19468 (if (not overwrite-mode)
19469 (progn
19470 (skip-chars-forward "^|")
19471 (insert " ")
19472 (goto-char (1- pos))))
19473 ;; noalign: if there were two spaces at the end, this field
19474 ;; does not determine the width of the column.
19475 (if noalign (setq org-table-may-need-update c)))
19476 (backward-delete-char N)
19477 (org-fix-tags-on-the-fly))))
19479 (defun org-delete-char (N)
19480 "Like `delete-char', but insert whitespace at field end in tables.
19481 When deleting characters, in tables this function will insert whitespace in
19482 front of the next \"|\" separator, to keep the table aligned. The table will
19483 still be marked for re-alignment if the field did fill the entire column,
19484 because, in this case the deletion might narrow the column."
19485 (interactive "p")
19486 (save-match-data
19487 (org-check-before-invisible-edit 'delete)
19488 (if (and (org-table-p)
19489 (not (bolp))
19490 (not (= (char-after) ?|))
19491 (eq N 1))
19492 (if (looking-at ".*?|")
19493 (let ((pos (point))
19494 (noalign (looking-at "[^|\n\r]* |"))
19495 (c org-table-may-need-update))
19496 (replace-match
19497 (concat (substring (match-string 0) 1 -1) " |") nil t)
19498 (goto-char pos)
19499 ;; noalign: if there were two spaces at the end, this field
19500 ;; does not determine the width of the column.
19501 (if noalign (setq org-table-may-need-update c)))
19502 (delete-char N))
19503 (delete-char N)
19504 (org-fix-tags-on-the-fly))))
19506 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19507 (put 'org-self-insert-command 'delete-selection t)
19508 (put 'orgtbl-self-insert-command 'delete-selection t)
19509 (put 'org-delete-char 'delete-selection 'supersede)
19510 (put 'org-delete-backward-char 'delete-selection 'supersede)
19511 (put 'org-yank 'delete-selection 'yank)
19513 ;; Make `flyspell-mode' delay after some commands
19514 (put 'org-self-insert-command 'flyspell-delayed t)
19515 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19516 (put 'org-delete-char 'flyspell-delayed t)
19517 (put 'org-delete-backward-char 'flyspell-delayed t)
19519 ;; Make pabbrev-mode expand after org-mode commands
19520 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19521 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19523 ;; How to do this: Measure non-white length of current string
19524 ;; If equal to column width, we should realign.
19526 (defun org-remap (map &rest commands)
19527 "In MAP, remap the functions given in COMMANDS.
19528 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19529 (let (new old)
19530 (while commands
19531 (setq old (pop commands) new (pop commands))
19532 (if (fboundp 'command-remapping)
19533 (org-defkey map (vector 'remap old) new)
19534 (substitute-key-definition old new map global-map)))))
19536 (defun org-transpose-words ()
19537 "Transpose words for Org.
19538 This uses the `org-mode-transpose-word-syntax-table' syntax
19539 table, which interprets characters in `org-emphasis-alist' as
19540 word constituants."
19541 (interactive)
19542 (with-syntax-table org-mode-transpose-word-syntax-table
19543 (call-interactively 'transpose-words)))
19544 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19546 (when (eq org-enable-table-editor 'optimized)
19547 ;; If the user wants maximum table support, we need to hijack
19548 ;; some standard editing functions
19549 (org-remap org-mode-map
19550 'self-insert-command 'org-self-insert-command
19551 'delete-char 'org-delete-char
19552 'delete-backward-char 'org-delete-backward-char)
19553 (org-defkey org-mode-map "|" 'org-force-self-insert))
19555 (defvar org-ctrl-c-ctrl-c-hook nil
19556 "Hook for functions attaching themselves to `C-c C-c'.
19558 This can be used to add additional functionality to the C-c C-c
19559 key which executes context-dependent commands. This hook is run
19560 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19561 run after the last test.
19563 Each function will be called with no arguments. The function
19564 must check if the context is appropriate for it to act. If yes,
19565 it should do its thing and then return a non-nil value. If the
19566 context is wrong, just do nothing and return nil.")
19568 (defvar org-ctrl-c-ctrl-c-final-hook nil
19569 "Hook for functions attaching themselves to `C-c C-c'.
19571 This can be used to add additional functionality to the C-c C-c
19572 key which executes context-dependent commands. This hook is run
19573 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19574 before the first test.
19576 Each function will be called with no arguments. The function
19577 must check if the context is appropriate for it to act. If yes,
19578 it should do its thing and then return a non-nil value. If the
19579 context is wrong, just do nothing and return nil.")
19581 (defvar org-tab-first-hook nil
19582 "Hook for functions to attach themselves to TAB.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.
19584 This hook runs as the first action when TAB is pressed, even before
19585 `org-cycle' messes around with the `outline-regexp' to cater for
19586 inline tasks and plain list item folding.
19587 If any function in this hook returns t, any other actions that
19588 would have been caused by TAB (such as table field motion or visibility
19589 cycling) will not occur.")
19591 (defvar org-tab-after-check-for-table-hook nil
19592 "Hook for functions to attach themselves to TAB.
19593 See `org-ctrl-c-ctrl-c-hook' for more information.
19594 This hook runs after it has been established that the cursor is not in a
19595 table, but before checking if the cursor is in a headline or if global cycling
19596 should be done.
19597 If any function in this hook returns t, not other actions like visibility
19598 cycling will be done.")
19600 (defvar org-tab-after-check-for-cycling-hook nil
19601 "Hook for functions to attach themselves to TAB.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.
19603 This hook runs after it has been established that not table field motion and
19604 not visibility should be done because of current context. This is probably
19605 the place where a package like yasnippets can hook in.")
19607 (defvar org-tab-before-tab-emulation-hook nil
19608 "Hook for functions to attach themselves to TAB.
19609 See `org-ctrl-c-ctrl-c-hook' for more information.
19610 This hook runs after every other options for TAB have been exhausted, but
19611 before indentation and \t insertion takes place.")
19613 (defvar org-metaleft-hook nil
19614 "Hook for functions attaching themselves to `M-left'.
19615 See `org-ctrl-c-ctrl-c-hook' for more information.")
19616 (defvar org-metaright-hook nil
19617 "Hook for functions attaching themselves to `M-right'.
19618 See `org-ctrl-c-ctrl-c-hook' for more information.")
19619 (defvar org-metaup-hook nil
19620 "Hook for functions attaching themselves to `M-up'.
19621 See `org-ctrl-c-ctrl-c-hook' for more information.")
19622 (defvar org-metadown-hook nil
19623 "Hook for functions attaching themselves to `M-down'.
19624 See `org-ctrl-c-ctrl-c-hook' for more information.")
19625 (defvar org-shiftmetaleft-hook nil
19626 "Hook for functions attaching themselves to `M-S-left'.
19627 See `org-ctrl-c-ctrl-c-hook' for more information.")
19628 (defvar org-shiftmetaright-hook nil
19629 "Hook for functions attaching themselves to `M-S-right'.
19630 See `org-ctrl-c-ctrl-c-hook' for more information.")
19631 (defvar org-shiftmetaup-hook nil
19632 "Hook for functions attaching themselves to `M-S-up'.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftmetadown-hook nil
19635 "Hook for functions attaching themselves to `M-S-down'.
19636 See `org-ctrl-c-ctrl-c-hook' for more information.")
19637 (defvar org-metareturn-hook nil
19638 "Hook for functions attaching themselves to `M-RET'.
19639 See `org-ctrl-c-ctrl-c-hook' for more information.")
19640 (defvar org-shiftup-hook nil
19641 "Hook for functions attaching themselves to `S-up'.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.")
19643 (defvar org-shiftup-final-hook nil
19644 "Hook for functions attaching themselves to `S-up'.
19645 This one runs after all other options except shift-select have been excluded.
19646 See `org-ctrl-c-ctrl-c-hook' for more information.")
19647 (defvar org-shiftdown-hook nil
19648 "Hook for functions attaching themselves to `S-down'.
19649 See `org-ctrl-c-ctrl-c-hook' for more information.")
19650 (defvar org-shiftdown-final-hook nil
19651 "Hook for functions attaching themselves to `S-down'.
19652 This one runs after all other options except shift-select have been excluded.
19653 See `org-ctrl-c-ctrl-c-hook' for more information.")
19654 (defvar org-shiftleft-hook nil
19655 "Hook for functions attaching themselves to `S-left'.
19656 See `org-ctrl-c-ctrl-c-hook' for more information.")
19657 (defvar org-shiftleft-final-hook nil
19658 "Hook for functions attaching themselves to `S-left'.
19659 This one runs after all other options except shift-select have been excluded.
19660 See `org-ctrl-c-ctrl-c-hook' for more information.")
19661 (defvar org-shiftright-hook nil
19662 "Hook for functions attaching themselves to `S-right'.
19663 See `org-ctrl-c-ctrl-c-hook' for more information.")
19664 (defvar org-shiftright-final-hook nil
19665 "Hook for functions attaching themselves to `S-right'.
19666 This one runs after all other options except shift-select have been excluded.
19667 See `org-ctrl-c-ctrl-c-hook' for more information.")
19669 (defun org-modifier-cursor-error ()
19670 "Throw an error, a modified cursor command was applied in wrong context."
19671 (user-error "This command is active in special context like tables, headlines or items"))
19673 (defun org-shiftselect-error ()
19674 "Throw an error because Shift-Cursor command was applied in wrong context."
19675 (if (and (boundp 'shift-select-mode) shift-select-mode)
19676 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19677 (user-error "This command works only in special context like headlines or timestamps")))
19679 (defun org-call-for-shift-select (cmd)
19680 (let ((this-command-keys-shift-translated t))
19681 (call-interactively cmd)))
19683 (defun org-shifttab (&optional arg)
19684 "Global visibility cycling or move to previous table field.
19685 Call `org-table-previous-field' within a table.
19686 When ARG is nil, cycle globally through visibility states.
19687 When ARG is a numeric prefix, show contents of this level."
19688 (interactive "P")
19689 (cond
19690 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19691 ((integerp arg)
19692 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19693 (message "Content view to level: %d" arg)
19694 (org-content (prefix-numeric-value arg2))
19695 (org-cycle-show-empty-lines t)
19696 (setq org-cycle-global-status 'overview)))
19697 (t (call-interactively 'org-global-cycle))))
19699 (defun org-shiftmetaleft ()
19700 "Promote subtree or delete table column.
19701 Calls `org-promote-subtree', `org-outdent-item-tree', or
19702 `org-table-delete-column', depending on context. See the
19703 individual commands for more information."
19704 (interactive)
19705 (cond
19706 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19707 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19708 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19709 ((if (not (org-region-active-p)) (org-at-item-p)
19710 (save-excursion (goto-char (region-beginning))
19711 (org-at-item-p)))
19712 (call-interactively 'org-outdent-item-tree))
19713 (t (org-modifier-cursor-error))))
19715 (defun org-shiftmetaright ()
19716 "Demote subtree or insert table column.
19717 Calls `org-demote-subtree', `org-indent-item-tree', or
19718 `org-table-insert-column', depending on context. See the
19719 individual commands for more information."
19720 (interactive)
19721 (cond
19722 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19723 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19724 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19725 ((if (not (org-region-active-p)) (org-at-item-p)
19726 (save-excursion (goto-char (region-beginning))
19727 (org-at-item-p)))
19728 (call-interactively 'org-indent-item-tree))
19729 (t (org-modifier-cursor-error))))
19731 (defun org-shiftmetaup (&optional arg)
19732 "Move subtree up or kill table row.
19733 Calls `org-move-subtree-up' or `org-table-kill-row' or
19734 `org-move-item-up' or `org-timestamp-up', depending on context.
19735 See the individual commands for more information."
19736 (interactive "P")
19737 (cond
19738 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19739 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19740 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19741 ((org-at-item-p) (call-interactively 'org-move-item-up))
19742 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19743 (call-interactively 'org-timestamp-up)))
19744 (t (call-interactively 'org-drag-line-backward))))
19746 (defun org-shiftmetadown (&optional arg)
19747 "Move subtree down or insert table row.
19748 Calls `org-move-subtree-down' or `org-table-insert-row' or
19749 `org-move-item-down' or `org-timestamp-up', depending on context.
19750 See the individual commands for more information."
19751 (interactive "P")
19752 (cond
19753 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19754 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19755 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19756 ((org-at-item-p) (call-interactively 'org-move-item-down))
19757 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19758 (call-interactively 'org-timestamp-down)))
19759 (t (call-interactively 'org-drag-line-forward))))
19761 (defsubst org-hidden-tree-error ()
19762 (user-error
19763 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19765 (defun org-metaleft (&optional arg)
19766 "Promote heading or move table column to left.
19767 Calls `org-do-promote' or `org-table-move-column', depending on context.
19768 With no specific context, calls the Emacs default `backward-word'.
19769 See the individual commands for more information."
19770 (interactive "P")
19771 (cond
19772 ((run-hook-with-args-until-success 'org-metaleft-hook))
19773 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19774 ((org-with-limited-levels
19775 (or (org-at-heading-p)
19776 (and (org-region-active-p)
19777 (save-excursion
19778 (goto-char (region-beginning))
19779 (org-at-heading-p)))))
19780 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19781 (call-interactively 'org-do-promote))
19782 ;; At an inline task.
19783 ((org-at-heading-p)
19784 (call-interactively 'org-inlinetask-promote))
19785 ((or (org-at-item-p)
19786 (and (org-region-active-p)
19787 (save-excursion
19788 (goto-char (region-beginning))
19789 (org-at-item-p))))
19790 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19791 (call-interactively 'org-outdent-item))
19792 (t (call-interactively 'backward-word))))
19794 (defun org-metaright (&optional arg)
19795 "Demote a subtree, a list item or move table column to right.
19796 In front of a drawer or a block keyword, indent it correctly.
19797 With no specific context, calls the Emacs default `forward-word'.
19798 See the individual commands for more information."
19799 (interactive "P")
19800 (cond
19801 ((run-hook-with-args-until-success 'org-metaright-hook))
19802 ((org-at-table-p) (call-interactively 'org-table-move-column))
19803 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19804 ((org-at-block-p) (call-interactively 'org-indent-block))
19805 ((org-with-limited-levels
19806 (or (org-at-heading-p)
19807 (and (org-region-active-p)
19808 (save-excursion
19809 (goto-char (region-beginning))
19810 (org-at-heading-p)))))
19811 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19812 (call-interactively 'org-do-demote))
19813 ;; At an inline task.
19814 ((org-at-heading-p)
19815 (call-interactively 'org-inlinetask-demote))
19816 ((or (org-at-item-p)
19817 (and (org-region-active-p)
19818 (save-excursion
19819 (goto-char (region-beginning))
19820 (org-at-item-p))))
19821 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19822 (call-interactively 'org-indent-item))
19823 (t (call-interactively 'forward-word))))
19825 (defun org-check-for-hidden (what)
19826 "Check if there are hidden headlines/items in the current visual line.
19827 WHAT can be either `headlines' or `items'. If the current line is
19828 an outline or item heading and it has a folded subtree below it,
19829 this function returns t, nil otherwise."
19830 (let ((re (cond
19831 ((eq what 'headlines) org-outline-regexp-bol)
19832 ((eq what 'items) (org-item-beginning-re))
19833 (t (error "This should not happen"))))
19834 beg end)
19835 (save-excursion
19836 (catch 'exit
19837 (unless (org-region-active-p)
19838 (setq beg (point-at-bol))
19839 (beginning-of-line 2)
19840 (while (and (not (eobp)) ;; this is like `next-line'
19841 (get-char-property (1- (point)) 'invisible))
19842 (beginning-of-line 2))
19843 (setq end (point))
19844 (goto-char beg)
19845 (goto-char (point-at-eol))
19846 (setq end (max end (point)))
19847 (while (re-search-forward re end t)
19848 (if (get-char-property (match-beginning 0) 'invisible)
19849 (throw 'exit t))))
19850 nil))))
19852 (defun org-metaup (&optional arg)
19853 "Move subtree up or move table row up.
19854 Calls `org-move-subtree-up' or `org-table-move-row' or
19855 `org-move-item-up', depending on context. See the individual commands
19856 for more information."
19857 (interactive "P")
19858 (cond
19859 ((run-hook-with-args-until-success 'org-metaup-hook))
19860 ((org-region-active-p)
19861 (let* ((a (min (region-beginning) (region-end)))
19862 (b (1- (max (region-beginning) (region-end))))
19863 (c (save-excursion (goto-char a)
19864 (move-beginning-of-line 0)))
19865 (d (save-excursion (goto-char a)
19866 (move-end-of-line 0) (point))))
19867 (transpose-regions a b c d)
19868 (goto-char c)))
19869 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19870 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19871 ((org-at-item-p) (call-interactively 'org-move-item-up))
19872 (t (org-drag-element-backward))))
19874 (defun org-metadown (&optional arg)
19875 "Move subtree down or move table row down.
19876 Calls `org-move-subtree-down' or `org-table-move-row' or
19877 `org-move-item-down', depending on context. See the individual
19878 commands for more information."
19879 (interactive "P")
19880 (cond
19881 ((run-hook-with-args-until-success 'org-metadown-hook))
19882 ((org-region-active-p)
19883 (let* ((a (min (region-beginning) (region-end)))
19884 (b (max (region-beginning) (region-end)))
19885 (c (save-excursion (goto-char b)
19886 (move-beginning-of-line 1)))
19887 (d (save-excursion (goto-char b)
19888 (move-end-of-line 1) (1+ (point)))))
19889 (transpose-regions a b c d)
19890 (goto-char d)))
19891 ((org-at-table-p) (call-interactively 'org-table-move-row))
19892 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19893 ((org-at-item-p) (call-interactively 'org-move-item-down))
19894 (t (org-drag-element-forward))))
19896 (defun org-shiftup (&optional arg)
19897 "Increase item in timestamp or increase priority of current headline.
19898 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19899 depending on context. See the individual commands for more information."
19900 (interactive "P")
19901 (cond
19902 ((run-hook-with-args-until-success 'org-shiftup-hook))
19903 ((and org-support-shift-select (org-region-active-p))
19904 (org-call-for-shift-select 'previous-line))
19905 ((org-at-timestamp-p t)
19906 (call-interactively (if org-edit-timestamp-down-means-later
19907 'org-timestamp-down 'org-timestamp-up)))
19908 ((and (not (eq org-support-shift-select 'always))
19909 org-enable-priority-commands
19910 (org-at-heading-p))
19911 (call-interactively 'org-priority-up))
19912 ((and (not org-support-shift-select) (org-at-item-p))
19913 (call-interactively 'org-previous-item))
19914 ((org-clocktable-try-shift 'up arg))
19915 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19916 (org-support-shift-select
19917 (org-call-for-shift-select 'previous-line))
19918 (t (org-shiftselect-error))))
19920 (defun org-shiftdown (&optional arg)
19921 "Decrease item in timestamp or decrease priority of current headline.
19922 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19923 depending on context. See the individual commands for more information."
19924 (interactive "P")
19925 (cond
19926 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19927 ((and org-support-shift-select (org-region-active-p))
19928 (org-call-for-shift-select 'next-line))
19929 ((org-at-timestamp-p t)
19930 (call-interactively (if org-edit-timestamp-down-means-later
19931 'org-timestamp-up 'org-timestamp-down)))
19932 ((and (not (eq org-support-shift-select 'always))
19933 org-enable-priority-commands
19934 (org-at-heading-p))
19935 (call-interactively 'org-priority-down))
19936 ((and (not org-support-shift-select) (org-at-item-p))
19937 (call-interactively 'org-next-item))
19938 ((org-clocktable-try-shift 'down arg))
19939 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19940 (org-support-shift-select
19941 (org-call-for-shift-select 'next-line))
19942 (t (org-shiftselect-error))))
19944 (defun org-shiftright (&optional arg)
19945 "Cycle the thing at point or in the current line, depending on context.
19946 Depending on context, this does one of the following:
19948 - switch a timestamp at point one day into the future
19949 - on a headline, switch to the next TODO keyword.
19950 - on an item, switch entire list to the next bullet type
19951 - on a property line, switch to the next allowed value
19952 - on a clocktable definition line, move time block into the future"
19953 (interactive "P")
19954 (cond
19955 ((run-hook-with-args-until-success 'org-shiftright-hook))
19956 ((and org-support-shift-select (org-region-active-p))
19957 (org-call-for-shift-select 'forward-char))
19958 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19959 ((and (not (eq org-support-shift-select 'always))
19960 (org-at-heading-p))
19961 (let ((org-inhibit-logging
19962 (not org-treat-S-cursor-todo-selection-as-state-change))
19963 (org-inhibit-blocking
19964 (not org-treat-S-cursor-todo-selection-as-state-change)))
19965 (org-call-with-arg 'org-todo 'right)))
19966 ((or (and org-support-shift-select
19967 (not (eq org-support-shift-select 'always))
19968 (org-at-item-bullet-p))
19969 (and (not org-support-shift-select) (org-at-item-p)))
19970 (org-call-with-arg 'org-cycle-list-bullet nil))
19971 ((and (not (eq org-support-shift-select 'always))
19972 (org-at-property-p))
19973 (call-interactively 'org-property-next-allowed-value))
19974 ((org-clocktable-try-shift 'right arg))
19975 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19976 (org-support-shift-select
19977 (org-call-for-shift-select 'forward-char))
19978 (t (org-shiftselect-error))))
19980 (defun org-shiftleft (&optional arg)
19981 "Cycle the thing at point or in the current line, depending on context.
19982 Depending on context, this does one of the following:
19984 - switch a timestamp at point one day into the past
19985 - on a headline, switch to the previous TODO keyword.
19986 - on an item, switch entire list to the previous bullet type
19987 - on a property line, switch to the previous allowed value
19988 - on a clocktable definition line, move time block into the past"
19989 (interactive "P")
19990 (cond
19991 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19992 ((and org-support-shift-select (org-region-active-p))
19993 (org-call-for-shift-select 'backward-char))
19994 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19995 ((and (not (eq org-support-shift-select 'always))
19996 (org-at-heading-p))
19997 (let ((org-inhibit-logging
19998 (not org-treat-S-cursor-todo-selection-as-state-change))
19999 (org-inhibit-blocking
20000 (not org-treat-S-cursor-todo-selection-as-state-change)))
20001 (org-call-with-arg 'org-todo 'left)))
20002 ((or (and org-support-shift-select
20003 (not (eq org-support-shift-select 'always))
20004 (org-at-item-bullet-p))
20005 (and (not org-support-shift-select) (org-at-item-p)))
20006 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20007 ((and (not (eq org-support-shift-select 'always))
20008 (org-at-property-p))
20009 (call-interactively 'org-property-previous-allowed-value))
20010 ((org-clocktable-try-shift 'left arg))
20011 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20012 (org-support-shift-select
20013 (org-call-for-shift-select 'backward-char))
20014 (t (org-shiftselect-error))))
20016 (defun org-shiftcontrolright ()
20017 "Switch to next TODO set."
20018 (interactive)
20019 (cond
20020 ((and org-support-shift-select (org-region-active-p))
20021 (org-call-for-shift-select 'forward-word))
20022 ((and (not (eq org-support-shift-select 'always))
20023 (org-at-heading-p))
20024 (org-call-with-arg 'org-todo 'nextset))
20025 (org-support-shift-select
20026 (org-call-for-shift-select 'forward-word))
20027 (t (org-shiftselect-error))))
20029 (defun org-shiftcontrolleft ()
20030 "Switch to previous TODO set."
20031 (interactive)
20032 (cond
20033 ((and org-support-shift-select (org-region-active-p))
20034 (org-call-for-shift-select 'backward-word))
20035 ((and (not (eq org-support-shift-select 'always))
20036 (org-at-heading-p))
20037 (org-call-with-arg 'org-todo 'previousset))
20038 (org-support-shift-select
20039 (org-call-for-shift-select 'backward-word))
20040 (t (org-shiftselect-error))))
20042 (defun org-shiftcontrolup (&optional n)
20043 "Change timestamps synchronously up in CLOCK log lines.
20044 Optional argument N tells to change by that many units."
20045 (interactive "P")
20046 (cond ((and (not org-support-shift-select)
20047 (org-at-clock-log-p)
20048 (org-at-timestamp-p t))
20049 (org-clock-timestamps-up n))
20050 (t (org-shiftselect-error))))
20052 (defun org-shiftcontroldown (&optional n)
20053 "Change timestamps synchronously down in CLOCK log lines.
20054 Optional argument N tells to change by that many units."
20055 (interactive "P")
20056 (cond ((and (not org-support-shift-select)
20057 (org-at-clock-log-p)
20058 (org-at-timestamp-p t))
20059 (org-clock-timestamps-down n))
20060 (t (org-shiftselect-error))))
20062 (defun org-ctrl-c-ret ()
20063 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20064 (interactive)
20065 (cond
20066 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20067 (t (call-interactively 'org-insert-heading))))
20069 (defun org-find-visible ()
20070 (let ((s (point)))
20071 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20072 (get-char-property s 'invisible)))
20074 (defun org-find-invisible ()
20075 (let ((s (point)))
20076 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20077 (not (get-char-property s 'invisible))))
20080 (defun org-copy-visible (beg end)
20081 "Copy the visible parts of the region."
20082 (interactive "r")
20083 (let (snippets s)
20084 (save-excursion
20085 (save-restriction
20086 (narrow-to-region beg end)
20087 (setq s (goto-char (point-min)))
20088 (while (not (= (point) (point-max)))
20089 (goto-char (org-find-invisible))
20090 (push (buffer-substring s (point)) snippets)
20091 (setq s (goto-char (org-find-visible))))))
20092 (kill-new (apply 'concat (nreverse snippets)))))
20094 (defun org-copy-special ()
20095 "Copy region in table or copy current subtree.
20096 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20097 See the individual commands for more information."
20098 (interactive)
20099 (call-interactively
20100 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20102 (defun org-cut-special ()
20103 "Cut region in table or cut current subtree.
20104 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20105 See the individual commands for more information."
20106 (interactive)
20107 (call-interactively
20108 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20110 (defun org-paste-special (arg)
20111 "Paste rectangular region into table, or past subtree relative to level.
20112 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20113 See the individual commands for more information."
20114 (interactive "P")
20115 (if (org-at-table-p)
20116 (org-table-paste-rectangle)
20117 (org-paste-subtree arg)))
20119 (defsubst org-in-fixed-width-region-p ()
20120 "Is point in a fixed-width region?"
20121 (save-match-data
20122 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20124 (defun org-edit-special (&optional arg)
20125 "Call a special editor for the element at point.
20126 When at a table, call the formula editor with `org-table-edit-formulas'.
20127 When in a source code block, call `org-edit-src-code'.
20128 When in a fixed-width region, call `org-edit-fixed-width-region'.
20129 When at an #+INCLUDE keyword, visit the included file.
20130 On a link, call `ffap' to visit the link at point.
20131 Otherwise, return a user error."
20132 (interactive "P")
20133 (let ((element (org-element-at-point)))
20134 (assert (not buffer-read-only) nil
20135 "Buffer is read-only: %s" (buffer-name))
20136 (case (org-element-type element)
20137 (src-block
20138 (if (not arg) (org-edit-src-code)
20139 (let* ((info (org-babel-get-src-block-info))
20140 (lang (nth 0 info))
20141 (params (nth 2 info))
20142 (session (cdr (assq :session params))))
20143 (if (not session) (org-edit-src-code)
20144 ;; At a src-block with a session and function called with
20145 ;; an ARG: switch to the buffer related to the inferior
20146 ;; process.
20147 (switch-to-buffer
20148 (funcall (intern (concat "org-babel-prep-session:" lang))
20149 session params))))))
20150 (keyword
20151 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20152 (find-file
20153 (org-remove-double-quotes
20154 (car (org-split-string (org-element-property :value element)))))
20155 (user-error "No special environment to edit here")))
20156 (table
20157 (if (eq (org-element-property :type element) 'table.el)
20158 (org-edit-src-code)
20159 (call-interactively 'org-table-edit-formulas)))
20160 ;; Only Org tables contain `table-row' type elements.
20161 (table-row (call-interactively 'org-table-edit-formulas))
20162 ((example-block export-block) (org-edit-src-code))
20163 (fixed-width (org-edit-fixed-width-region))
20164 (otherwise
20165 ;; No notable element at point. Though, we may be at a link,
20166 ;; which is an object. Thus, scan deeper.
20167 (if (eq (org-element-type (org-element-context element)) 'link)
20168 (call-interactively 'ffap)
20169 (user-error "No special environment to edit here"))))))
20171 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20172 (defun org-ctrl-c-ctrl-c (&optional arg)
20173 "Set tags in headline, or update according to changed information at point.
20175 This command does many different things, depending on context:
20177 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20178 this is what we do.
20180 - If the cursor is on a statistics cookie, update it.
20182 - If the cursor is in a headline, prompt for tags and insert them
20183 into the current line, aligned to `org-tags-column'. When called
20184 with prefix arg, realign all tags in the current buffer.
20186 - If the cursor is in one of the special #+KEYWORD lines, this
20187 triggers scanning the buffer for these lines and updating the
20188 information.
20190 - If the cursor is inside a table, realign the table. This command
20191 works even if the automatic table editor has been turned off.
20193 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20194 the entire table.
20196 - If the cursor is at a footnote reference or definition, jump to
20197 the corresponding definition or references, respectively.
20199 - If the cursor is a the beginning of a dynamic block, update it.
20201 - If the current buffer is a capture buffer, close note and file it.
20203 - If the cursor is on a <<<target>>>, update radio targets and
20204 corresponding links in this buffer.
20206 - If the cursor is on a numbered item in a plain list, renumber the
20207 ordered list.
20209 - If the cursor is on a checkbox, toggle it.
20211 - If the cursor is on a code block, evaluate it. The variable
20212 `org-confirm-babel-evaluate' can be used to control prompting
20213 before code block evaluation, by default every code block
20214 evaluation requires confirmation. Code block evaluation can be
20215 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20216 (interactive "P")
20217 (cond
20218 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20219 org-occur-highlights
20220 org-latex-fragment-image-overlays)
20221 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20222 (org-remove-occur-highlights)
20223 (org-remove-latex-fragment-image-overlays)
20224 (message "Temporary highlights/overlays removed from current buffer"))
20225 ((and (local-variable-p 'org-finish-function (current-buffer))
20226 (fboundp org-finish-function))
20227 (funcall org-finish-function))
20228 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20230 (let* ((context (org-element-context)) (type (org-element-type context)))
20231 ;; Test if point is within a blank line.
20232 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20233 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20234 (user-error "C-c C-c can do nothing useful at this location"))
20235 ;; When at a link, act according to the parent instead.
20236 (when (eq type 'link)
20237 (setq context (org-element-property :parent context))
20238 (setq type (org-element-type context)))
20239 ;; For convenience: at the first line of a paragraph on the
20240 ;; same line as an item, apply function on that item instead.
20241 (when (eq type 'paragraph)
20242 (let ((parent (org-element-property :parent context)))
20243 (when (and (eq (org-element-type parent) 'item)
20244 (= (point-at-bol) (org-element-property :begin parent)))
20245 (setq context parent type 'item))))
20246 ;; Act according to type of element or object at point.
20247 (case type
20248 (clock (org-clock-update-time-maybe))
20249 (dynamic-block
20250 (save-excursion
20251 (goto-char (org-element-property :post-affiliated context))
20252 (org-update-dblock)))
20253 (footnote-definition
20254 (goto-char (org-element-property :post-affiliated context))
20255 (call-interactively 'org-footnote-action))
20256 (footnote-reference (call-interactively 'org-footnote-action))
20257 ((headline inlinetask)
20258 (save-excursion (goto-char (org-element-property :begin context))
20259 (call-interactively 'org-set-tags)))
20260 (item
20261 ;; At an item: a double C-u set checkbox to "[-]"
20262 ;; unconditionally, whereas a single one will toggle its
20263 ;; presence. Without an universal argument, if the item
20264 ;; has a checkbox, toggle it. Otherwise repair the list.
20265 (let* ((box (org-element-property :checkbox context))
20266 (struct (org-element-property :structure context))
20267 (old-struct (copy-tree struct))
20268 (parents (org-list-parents-alist struct))
20269 (prevs (org-list-prevs-alist struct))
20270 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20271 (org-list-set-checkbox
20272 (org-element-property :begin context) struct
20273 (cond ((equal arg '(16)) "[-]")
20274 ((and (not box) (equal arg '(4))) "[ ]")
20275 ((or (not box) (equal arg '(4))) nil)
20276 ((eq box 'on) "[ ]")
20277 (t "[X]")))
20278 ;; Mimic `org-list-write-struct' but with grabbing
20279 ;; a return value from `org-list-struct-fix-box'.
20280 (org-list-struct-fix-ind struct parents 2)
20281 (org-list-struct-fix-item-end struct)
20282 (org-list-struct-fix-bul struct prevs)
20283 (org-list-struct-fix-ind struct parents)
20284 (let ((block-item
20285 (org-list-struct-fix-box struct parents prevs orderedp)))
20286 (if (and box (equal struct old-struct))
20287 (if (equal arg '(16))
20288 (message "Checkboxes already reset")
20289 (user-error "Cannot toggle this checkbox: %s"
20290 (if (eq box 'on)
20291 "all subitems checked"
20292 "unchecked subitems")))
20293 (org-list-struct-apply-struct struct old-struct)
20294 (org-update-checkbox-count-maybe))
20295 (when block-item
20296 (message "Checkboxes were removed due to empty box at line %d"
20297 (org-current-line block-item))))))
20298 (keyword
20299 (let ((org-inhibit-startup-visibility-stuff t)
20300 (org-startup-align-all-tables nil))
20301 (when (boundp 'org-table-coordinate-overlays)
20302 (mapc 'delete-overlay org-table-coordinate-overlays)
20303 (setq org-table-coordinate-overlays nil))
20304 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20305 (message "Local setup has been refreshed"))
20306 (plain-list
20307 ;; At a plain list, with a double C-u argument, set
20308 ;; checkboxes of each item to "[-]", whereas a single one
20309 ;; will toggle their presence according to the state of the
20310 ;; first item in the list. Without an argument, repair the
20311 ;; list.
20312 (let* ((begin (org-element-property :contents-begin context))
20313 (beginm (move-marker (make-marker) begin))
20314 (struct (org-element-property :structure context))
20315 (old-struct (copy-tree struct))
20316 (first-box (save-excursion
20317 (goto-char begin)
20318 (looking-at org-list-full-item-re)
20319 (match-string-no-properties 3)))
20320 (new-box (cond ((equal arg '(16)) "[-]")
20321 ((equal arg '(4)) (unless first-box "[ ]"))
20322 ((equal first-box "[X]") "[ ]")
20323 (t "[X]"))))
20324 (cond
20325 (arg
20326 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20327 (org-list-get-all-items
20328 begin struct (org-list-prevs-alist struct))))
20329 ((and first-box (eq (point) begin))
20330 ;; For convenience, when point is at bol on the first
20331 ;; item of the list and no argument is provided, simply
20332 ;; toggle checkbox of that item, if any.
20333 (org-list-set-checkbox begin struct new-box)))
20334 (org-list-write-struct
20335 struct (org-list-parents-alist struct) old-struct)
20336 (org-update-checkbox-count-maybe)
20337 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20338 ((property-drawer node-property)
20339 (call-interactively 'org-property-action))
20340 ((radio-target target)
20341 (call-interactively 'org-update-radio-target-regexp))
20342 (statistics-cookie
20343 (call-interactively 'org-update-statistics-cookies))
20344 ((table table-cell table-row)
20345 ;; At a table, recalculate every field and align it. Also
20346 ;; send the table if necessary. If the table has
20347 ;; a `table.el' type, just give up. At a table row or
20348 ;; cell, maybe recalculate line but always align table.
20349 (if (eq (org-element-property :type context) 'table.el)
20350 (message "Use C-c ' to edit table.el tables")
20351 (let ((org-enable-table-editor t))
20352 (if (or (eq type 'table)
20353 ;; Check if point is at a TBLFM line.
20354 (and (eq type 'table-row)
20355 (= (point) (org-element-property :end context))))
20356 (save-excursion
20357 (if (org-at-TBLFM-p)
20358 (progn (require 'org-table)
20359 (org-table-calc-current-TBLFM))
20360 (goto-char (org-element-property :contents-begin context))
20361 (org-call-with-arg 'org-table-recalculate (or arg t))
20362 (orgtbl-send-table 'maybe)))
20363 (org-table-maybe-eval-formula)
20364 (cond (arg (call-interactively 'org-table-recalculate))
20365 ((org-table-maybe-recalculate-line))
20366 (t (org-table-align)))))))
20367 (timestamp (org-timestamp-change 0 'day))
20368 (otherwise
20369 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20370 (user-error
20371 "C-c C-c can do nothing useful at this location")))))))))
20373 (defun org-mode-restart ()
20374 "Restart Org-mode, to scan again for special lines.
20375 Also updates the keyword regular expressions."
20376 (interactive)
20377 (org-mode)
20378 (message "Org-mode restarted"))
20380 (defun org-kill-note-or-show-branches ()
20381 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20382 (interactive)
20383 (if (not org-finish-function)
20384 (progn
20385 (hide-subtree)
20386 (call-interactively 'show-branches))
20387 (let ((org-note-abort t))
20388 (funcall org-finish-function))))
20390 (defun org-open-line (n)
20391 "Insert a new row in tables, call `open-line' elsewhere.
20392 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20393 (interactive "*p")
20394 (cond
20395 ((not org-special-ctrl-o)
20396 (open-line n))
20397 ((org-at-table-p)
20398 (org-table-insert-row))
20400 (open-line n))))
20402 (defun org-return (&optional indent)
20403 "Goto next table row or insert a newline.
20404 Calls `org-table-next-row' or `newline', depending on context.
20405 See the individual commands for more information."
20406 (interactive)
20407 (let (org-ts-what)
20408 (cond
20409 ((or (bobp) (org-in-src-block-p))
20410 (if indent (newline-and-indent) (newline)))
20411 ((org-at-table-p)
20412 (org-table-justify-field-maybe)
20413 (call-interactively 'org-table-next-row))
20414 ;; when `newline-and-indent' is called within a list, make sure
20415 ;; text moved stays inside the item.
20416 ((and (org-in-item-p) indent)
20417 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20418 (progn
20419 (save-match-data (newline))
20420 (org-indent-line-to (length (match-string 0))))
20421 (let ((ind (org-get-indentation)))
20422 (newline)
20423 (if (org-looking-back org-list-end-re)
20424 (org-indent-line)
20425 (org-indent-line-to ind)))))
20426 ((and org-return-follows-link
20427 (org-at-timestamp-p t)
20428 (not (eq org-ts-what 'after)))
20429 (org-follow-timestamp-link))
20430 ((and org-return-follows-link
20431 (let ((tprop (get-text-property (point) 'face)))
20432 (or (eq tprop 'org-link)
20433 (and (listp tprop) (memq 'org-link tprop)))))
20434 (call-interactively 'org-open-at-point))
20435 ((and (org-at-heading-p)
20436 (looking-at
20437 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20438 (org-show-entry)
20439 (end-of-line 1)
20440 (newline))
20441 (t (if indent (newline-and-indent) (newline))))))
20443 (defun org-return-indent ()
20444 "Goto next table row or insert a newline and indent.
20445 Calls `org-table-next-row' or `newline-and-indent', depending on
20446 context. See the individual commands for more information."
20447 (interactive)
20448 (org-return t))
20450 (defun org-ctrl-c-star ()
20451 "Compute table, or change heading status of lines.
20452 Calls `org-table-recalculate' or `org-toggle-heading',
20453 depending on context."
20454 (interactive)
20455 (cond
20456 ((org-at-table-p)
20457 (call-interactively 'org-table-recalculate))
20459 ;; Convert all lines in region to list items
20460 (call-interactively 'org-toggle-heading))))
20462 (defun org-ctrl-c-minus ()
20463 "Insert separator line in table or modify bullet status of line.
20464 Also turns a plain line or a region of lines into list items.
20465 Calls `org-table-insert-hline', `org-toggle-item', or
20466 `org-cycle-list-bullet', depending on context."
20467 (interactive)
20468 (cond
20469 ((org-at-table-p)
20470 (call-interactively 'org-table-insert-hline))
20471 ((org-region-active-p)
20472 (call-interactively 'org-toggle-item))
20473 ((org-in-item-p)
20474 (call-interactively 'org-cycle-list-bullet))
20476 (call-interactively 'org-toggle-item))))
20478 (defun org-toggle-item (arg)
20479 "Convert headings or normal lines to items, items to normal lines.
20480 If there is no active region, only the current line is considered.
20482 If the first non blank line in the region is a headline, convert
20483 all headlines to items, shifting text accordingly.
20485 If it is an item, convert all items to normal lines.
20487 If it is normal text, change region into a list of items.
20488 With a prefix argument ARG, change the region in a single item."
20489 (interactive "P")
20490 (let ((shift-text
20491 (function
20492 ;; Shift text in current section to IND, from point to END.
20493 ;; The function leaves point to END line.
20494 (lambda (ind end)
20495 (let ((min-i 1000) (end (copy-marker end)))
20496 ;; First determine the minimum indentation (MIN-I) of
20497 ;; the text.
20498 (save-excursion
20499 (catch 'exit
20500 (while (< (point) end)
20501 (let ((i (org-get-indentation)))
20502 (cond
20503 ;; Skip blank lines and inline tasks.
20504 ((looking-at "^[ \t]*$"))
20505 ((looking-at org-outline-regexp-bol))
20506 ;; We can't find less than 0 indentation.
20507 ((zerop i) (throw 'exit (setq min-i 0)))
20508 ((< i min-i) (setq min-i i))))
20509 (forward-line))))
20510 ;; Then indent each line so that a line indented to
20511 ;; MIN-I becomes indented to IND. Ignore blank lines
20512 ;; and inline tasks in the process.
20513 (let ((delta (- ind min-i)))
20514 (while (< (point) end)
20515 (unless (or (looking-at "^[ \t]*$")
20516 (looking-at org-outline-regexp-bol))
20517 (org-indent-line-to (+ (org-get-indentation) delta)))
20518 (forward-line)))))))
20519 (skip-blanks
20520 (function
20521 ;; Return beginning of first non-blank line, starting from
20522 ;; line at POS.
20523 (lambda (pos)
20524 (save-excursion
20525 (goto-char pos)
20526 (skip-chars-forward " \r\t\n")
20527 (point-at-bol)))))
20528 beg end)
20529 ;; Determine boundaries of changes.
20530 (if (org-region-active-p)
20531 (setq beg (funcall skip-blanks (region-beginning))
20532 end (copy-marker (region-end)))
20533 (setq beg (funcall skip-blanks (point-at-bol))
20534 end (copy-marker (point-at-eol))))
20535 ;; Depending on the starting line, choose an action on the text
20536 ;; between BEG and END.
20537 (org-with-limited-levels
20538 (save-excursion
20539 (goto-char beg)
20540 (cond
20541 ;; Case 1. Start at an item: de-itemize. Note that it only
20542 ;; happens when a region is active: `org-ctrl-c-minus'
20543 ;; would call `org-cycle-list-bullet' otherwise.
20544 ((org-at-item-p)
20545 (while (< (point) end)
20546 (when (org-at-item-p)
20547 (skip-chars-forward " \t")
20548 (delete-region (point) (match-end 0)))
20549 (forward-line)))
20550 ;; Case 2. Start at an heading: convert to items.
20551 ((org-at-heading-p)
20552 (let* ((bul (org-list-bullet-string "-"))
20553 (bul-len (length bul))
20554 ;; Indentation of the first heading. It should be
20555 ;; relative to the indentation of its parent, if any.
20556 (start-ind (save-excursion
20557 (cond
20558 ((not org-adapt-indentation) 0)
20559 ((not (outline-previous-heading)) 0)
20560 (t (length (match-string 0))))))
20561 ;; Level of first heading. Further headings will be
20562 ;; compared to it to determine hierarchy in the list.
20563 (ref-level (org-reduced-level (org-outline-level))))
20564 (while (< (point) end)
20565 (let* ((level (org-reduced-level (org-outline-level)))
20566 (delta (max 0 (- level ref-level))))
20567 ;; If current headline is less indented than the first
20568 ;; one, set it as reference, in order to preserve
20569 ;; subtrees.
20570 (when (< level ref-level) (setq ref-level level))
20571 (replace-match bul t t)
20572 (org-indent-line-to (+ start-ind (* delta bul-len)))
20573 ;; Ensure all text down to END (or SECTION-END) belongs
20574 ;; to the newly created item.
20575 (let ((section-end (save-excursion
20576 (or (outline-next-heading) (point)))))
20577 (forward-line)
20578 (funcall shift-text
20579 (+ start-ind (* (1+ delta) bul-len))
20580 (min end section-end)))))))
20581 ;; Case 3. Normal line with ARG: make the first line of region
20582 ;; an item, and shift indentation of others lines to
20583 ;; set them as item's body.
20584 (arg (let* ((bul (org-list-bullet-string "-"))
20585 (bul-len (length bul))
20586 (ref-ind (org-get-indentation)))
20587 (skip-chars-forward " \t")
20588 (insert bul)
20589 (forward-line)
20590 (while (< (point) end)
20591 ;; Ensure that lines less indented than first one
20592 ;; still get included in item body.
20593 (funcall shift-text
20594 (+ ref-ind bul-len)
20595 (min end (save-excursion (or (outline-next-heading)
20596 (point)))))
20597 (forward-line))))
20598 ;; Case 4. Normal line without ARG: turn each non-item line
20599 ;; into an item.
20601 (while (< (point) end)
20602 (unless (or (org-at-heading-p) (org-at-item-p))
20603 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20604 (replace-match
20605 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20606 (forward-line))))))))
20608 (defun org-toggle-heading (&optional nstars)
20609 "Convert headings to normal text, or items or text to headings.
20610 If there is no active region, only convert the current line.
20612 With a \\[universal-argument] prefix, convert the whole list at
20613 point into heading.
20615 In a region:
20617 - If the first non blank line is a headline, remove the stars
20618 from all headlines in the region.
20620 - If it is a normal line, turn each and every normal line (i.e.,
20621 not an heading or an item) in the region into headings. If you
20622 want to convert only the first line of this region, use one
20623 universal prefix argument.
20625 - If it is a plain list item, turn all plain list items into headings.
20627 When converting a line into a heading, the number of stars is chosen
20628 such that the lines become children of the current entry. However,
20629 when a numeric prefix argument is given, its value determines the
20630 number of stars to add."
20631 (interactive "P")
20632 (let ((skip-blanks
20633 (function
20634 ;; Return beginning of first non-blank line, starting from
20635 ;; line at POS.
20636 (lambda (pos)
20637 (save-excursion
20638 (goto-char pos)
20639 (while (org-at-comment-p) (forward-line))
20640 (skip-chars-forward " \r\t\n")
20641 (point-at-bol)))))
20642 beg end toggled)
20643 ;; Determine boundaries of changes. If a universal prefix has
20644 ;; been given, put the list in a region. If region ends at a bol,
20645 ;; do not consider the last line to be in the region.
20647 (when (and current-prefix-arg (org-at-item-p))
20648 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20649 (org-mark-element))
20651 (if (org-region-active-p)
20652 (setq beg (funcall skip-blanks (region-beginning))
20653 end (copy-marker (save-excursion
20654 (goto-char (region-end))
20655 (if (bolp) (point) (point-at-eol)))))
20656 (setq beg (funcall skip-blanks (point-at-bol))
20657 end (copy-marker (point-at-eol))))
20658 ;; Ensure inline tasks don't count as headings.
20659 (org-with-limited-levels
20660 (save-excursion
20661 (goto-char beg)
20662 (cond
20663 ;; Case 1. Started at an heading: de-star headings.
20664 ((org-at-heading-p)
20665 (while (< (point) end)
20666 (when (org-at-heading-p t)
20667 (looking-at org-outline-regexp) (replace-match "")
20668 (setq toggled t))
20669 (forward-line)))
20670 ;; Case 2. Started at an item: change items into headlines.
20671 ;; One star will be added by `org-list-to-subtree'.
20672 ((org-at-item-p)
20673 (let* ((stars (make-string
20674 ;; subtract the star that will be added again by
20675 ;; `org-list-to-subtree'
20676 (if (numberp nstars) (1- nstars)
20677 (or (org-current-level) 0))
20678 ?*))
20679 (add-stars
20680 (cond (nstars "") ; stars from prefix only
20681 ((equal stars "") "") ; before first heading
20682 (org-odd-levels-only "*") ; inside heading, odd
20683 (t "")))) ; inside heading, oddeven
20684 (while (< (point) end)
20685 (when (org-at-item-p)
20686 ;; Pay attention to cases when region ends before list.
20687 (let* ((struct (org-list-struct))
20688 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20689 (save-restriction
20690 (narrow-to-region (point) list-end)
20691 (insert
20692 (org-list-to-subtree
20693 (org-list-parse-list t)
20694 '(:istart (concat stars add-stars (funcall get-stars depth))
20695 :icount (concat stars add-stars (funcall get-stars depth)))))))
20696 (setq toggled t))
20697 (forward-line))))
20698 ;; Case 3. Started at normal text: make every line an heading,
20699 ;; skipping headlines and items.
20700 (t (let* ((stars
20701 (make-string
20702 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20703 (add-stars
20704 (cond (nstars "") ; stars from prefix only
20705 ((equal stars "") "*") ; before first heading
20706 (org-odd-levels-only "**") ; inside heading, odd
20707 (t "*"))) ; inside heading, oddeven
20708 (rpl (concat stars add-stars " "))
20709 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20710 (while (< (point) (if (equal nstars '(4)) lend end))
20711 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20712 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20713 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20714 (forward-line)))))))
20715 (unless toggled (message "Cannot toggle heading from here"))))
20717 (defun org-meta-return (&optional arg)
20718 "Insert a new heading or wrap a region in a table.
20719 Calls `org-insert-heading' or `org-table-wrap-region', depending
20720 on context. See the individual commands for more information."
20721 (interactive "P")
20722 (org-check-before-invisible-edit 'insert)
20723 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20724 (let* ((element (org-element-at-point))
20725 (type (org-element-type element)))
20726 (when (eq type 'table-row)
20727 (setq element (org-element-property :parent element))
20728 (setq type 'table))
20729 (if (and (eq type 'table)
20730 (eq (org-element-property :type element) 'org)
20731 (>= (point) (org-element-property :contents-begin element))
20732 (< (point) (org-element-property :contents-end element)))
20733 (call-interactively 'org-table-wrap-region)
20734 (call-interactively 'org-insert-heading)))))
20736 ;;; Menu entries
20738 (defsubst org-in-subtree-not-table-p ()
20739 "Are we in a subtree and not in a table?"
20740 (and (not (org-before-first-heading-p))
20741 (not (org-at-table-p))))
20743 ;; Define the Org-mode menus
20744 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20745 '("Tbl"
20746 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20747 ["Next Field" org-cycle (org-at-table-p)]
20748 ["Previous Field" org-shifttab (org-at-table-p)]
20749 ["Next Row" org-return (org-at-table-p)]
20750 "--"
20751 ["Blank Field" org-table-blank-field (org-at-table-p)]
20752 ["Edit Field" org-table-edit-field (org-at-table-p)]
20753 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20754 "--"
20755 ("Column"
20756 ["Move Column Left" org-metaleft (org-at-table-p)]
20757 ["Move Column Right" org-metaright (org-at-table-p)]
20758 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20759 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20760 ("Row"
20761 ["Move Row Up" org-metaup (org-at-table-p)]
20762 ["Move Row Down" org-metadown (org-at-table-p)]
20763 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20764 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20765 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20766 "--"
20767 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20768 ("Rectangle"
20769 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20770 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20771 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20772 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20773 "--"
20774 ("Calculate"
20775 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20776 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20777 ["Edit Formulas" org-edit-special (org-at-table-p)]
20778 "--"
20779 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20780 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20781 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20782 "--"
20783 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20784 "--"
20785 ["Sum Column/Rectangle" org-table-sum
20786 (or (org-at-table-p) (org-region-active-p))]
20787 ["Which Column?" org-table-current-column (org-at-table-p)])
20788 ["Debug Formulas"
20789 org-table-toggle-formula-debugger
20790 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20791 ["Show Col/Row Numbers"
20792 org-table-toggle-coordinate-overlays
20793 :style toggle
20794 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20795 "--"
20796 ["Create" org-table-create (and (not (org-at-table-p))
20797 org-enable-table-editor)]
20798 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20799 ["Import from File" org-table-import (not (org-at-table-p))]
20800 ["Export to File" org-table-export (org-at-table-p)]
20801 "--"
20802 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20804 (easy-menu-define org-org-menu org-mode-map "Org menu"
20805 '("Org"
20806 ("Show/Hide"
20807 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20808 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20809 ["Sparse Tree..." org-sparse-tree t]
20810 ["Reveal Context" org-reveal t]
20811 ["Show All" show-all t]
20812 "--"
20813 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20814 "--"
20815 ["New Heading" org-insert-heading t]
20816 ("Navigate Headings"
20817 ["Up" outline-up-heading t]
20818 ["Next" outline-next-visible-heading t]
20819 ["Previous" outline-previous-visible-heading t]
20820 ["Next Same Level" outline-forward-same-level t]
20821 ["Previous Same Level" outline-backward-same-level t]
20822 "--"
20823 ["Jump" org-goto t])
20824 ("Edit Structure"
20825 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20826 "--"
20827 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20828 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20829 "--"
20830 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20831 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20832 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20833 "--"
20834 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20835 "--"
20836 ["Copy visible text" org-copy-visible t]
20837 "--"
20838 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20839 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20840 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20841 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20842 "--"
20843 ["Sort Region/Children" org-sort t]
20844 "--"
20845 ["Convert to odd levels" org-convert-to-odd-levels t]
20846 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20847 ("Editing"
20848 ["Emphasis..." org-emphasize t]
20849 ["Edit Source Example" org-edit-special t]
20850 "--"
20851 ["Footnote new/jump" org-footnote-action t]
20852 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20853 ("Archive"
20854 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20855 "--"
20856 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20857 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20858 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20860 "--"
20861 ("Hyperlinks"
20862 ["Store Link (Global)" org-store-link t]
20863 ["Find existing link to here" org-occur-link-in-agenda-files t]
20864 ["Insert Link" org-insert-link t]
20865 ["Follow Link" org-open-at-point t]
20866 "--"
20867 ["Next link" org-next-link t]
20868 ["Previous link" org-previous-link t]
20869 "--"
20870 ["Descriptive Links"
20871 org-toggle-link-display
20872 :style radio
20873 :selected org-descriptive-links
20875 ["Literal Links"
20876 org-toggle-link-display
20877 :style radio
20878 :selected (not org-descriptive-links)])
20879 "--"
20880 ("TODO Lists"
20881 ["TODO/DONE/-" org-todo t]
20882 ("Select keyword"
20883 ["Next keyword" org-shiftright (org-at-heading-p)]
20884 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20885 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20886 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20887 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20888 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20889 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20890 "--"
20891 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20892 :selected org-enforce-todo-dependencies :style toggle :active t]
20893 "Settings for tree at point"
20894 ["Do Children sequentially" org-toggle-ordered-property :style radio
20895 :selected (org-entry-get nil "ORDERED")
20896 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20897 ["Do Children parallel" org-toggle-ordered-property :style radio
20898 :selected (not (org-entry-get nil "ORDERED"))
20899 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20900 "--"
20901 ["Set Priority" org-priority t]
20902 ["Priority Up" org-shiftup t]
20903 ["Priority Down" org-shiftdown t]
20904 "--"
20905 ["Get news from all feeds" org-feed-update-all t]
20906 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20907 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20908 ("TAGS and Properties"
20909 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20910 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20911 "--"
20912 ["Set property" org-set-property (not (org-before-first-heading-p))]
20913 ["Column view of properties" org-columns t]
20914 ["Insert Column View DBlock" org-insert-columns-dblock t])
20915 ("Dates and Scheduling"
20916 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20917 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20918 ("Change Date"
20919 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20920 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20921 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20922 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20923 ["Compute Time Range" org-evaluate-time-range t]
20924 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20925 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20926 "--"
20927 ["Custom time format" org-toggle-time-stamp-overlays
20928 :style radio :selected org-display-custom-times]
20929 "--"
20930 ["Goto Calendar" org-goto-calendar t]
20931 ["Date from Calendar" org-date-from-calendar t]
20932 "--"
20933 ["Start/Restart Timer" org-timer-start t]
20934 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20935 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20936 ["Insert Timer String" org-timer t]
20937 ["Insert Timer Item" org-timer-item t])
20938 ("Logging work"
20939 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20940 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20941 ["Clock out" org-clock-out t]
20942 ["Clock cancel" org-clock-cancel t]
20943 "--"
20944 ["Mark as default task" org-clock-mark-default-task t]
20945 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20946 ["Goto running clock" org-clock-goto t]
20947 "--"
20948 ["Display times" org-clock-display t]
20949 ["Create clock table" org-clock-report t]
20950 "--"
20951 ["Record DONE time"
20952 (progn (setq org-log-done (not org-log-done))
20953 (message "Switching to %s will %s record a timestamp"
20954 (car org-done-keywords)
20955 (if org-log-done "automatically" "not")))
20956 :style toggle :selected org-log-done])
20957 "--"
20958 ["Agenda Command..." org-agenda t]
20959 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20960 ("File List for Agenda")
20961 ("Special views current file"
20962 ["TODO Tree" org-show-todo-tree t]
20963 ["Check Deadlines" org-check-deadlines t]
20964 ["Timeline" org-timeline t]
20965 ["Tags/Property tree" org-match-sparse-tree t])
20966 "--"
20967 ["Export/Publish..." org-export-dispatch t]
20968 ("LaTeX"
20969 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20970 :selected org-cdlatex-mode]
20971 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20972 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20973 ["Modify math symbol" org-cdlatex-math-modify
20974 (org-inside-LaTeX-fragment-p)]
20975 ["Insert citation" org-reftex-citation t]
20976 "--"
20977 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20978 "--"
20979 ("MobileOrg"
20980 ["Push Files and Views" org-mobile-push t]
20981 ["Get Captured and Flagged" org-mobile-pull t]
20982 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20983 "--"
20984 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20985 "--"
20986 ("Documentation"
20987 ["Show Version" org-version t]
20988 ["Info Documentation" org-info t])
20989 ("Customize"
20990 ["Browse Org Group" org-customize t]
20991 "--"
20992 ["Expand This Menu" org-create-customize-menu
20993 (fboundp 'customize-menu-create)])
20994 ["Send bug report" org-submit-bug-report t]
20995 "--"
20996 ("Refresh/Reload"
20997 ["Refresh setup current buffer" org-mode-restart t]
20998 ["Reload Org (after update)" org-reload t]
20999 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21002 (defun org-info (&optional node)
21003 "Read documentation for Org-mode in the info system.
21004 With optional NODE, go directly to that node."
21005 (interactive)
21006 (info (format "(org)%s" (or node ""))))
21008 ;;;###autoload
21009 (defun org-submit-bug-report ()
21010 "Submit a bug report on Org-mode via mail.
21012 Don't hesitate to report any problems or inaccurate documentation.
21014 If you don't have setup sending mail from (X)Emacs, please copy the
21015 output buffer into your mail program, as it gives us important
21016 information about your Org-mode version and configuration."
21017 (interactive)
21018 (require 'reporter)
21019 (org-load-modules-maybe)
21020 (org-require-autoloaded-modules)
21021 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21022 (reporter-submit-bug-report
21023 "emacs-orgmode@gnu.org"
21024 (org-version nil 'full)
21025 (let (list)
21026 (save-window-excursion
21027 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21028 (delete-other-windows)
21029 (erase-buffer)
21030 (insert "You are about to submit a bug report to the Org-mode mailing list.
21032 We would like to add your full Org-mode and Outline configuration to the
21033 bug report. This greatly simplifies the work of the maintainer and
21034 other experts on the mailing list.
21036 HOWEVER, some variables you have customized may contain private
21037 information. The names of customers, colleagues, or friends, might
21038 appear in the form of file names, tags, todo states, or search strings.
21039 If you answer yes to the prompt, you might want to check and remove
21040 such private information before sending the email.")
21041 (add-text-properties (point-min) (point-max) '(face org-warning))
21042 (when (yes-or-no-p "Include your Org-mode configuration ")
21043 (mapatoms
21044 (lambda (v)
21045 (and (boundp v)
21046 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21047 (or (and (symbol-value v)
21048 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21049 (and
21050 (get v 'custom-type) (get v 'standard-value)
21051 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21052 (push v list)))))
21053 (kill-buffer (get-buffer "*Warn about privacy*"))
21054 list))
21055 nil nil
21056 "Remember to cover the basics, that is, what you expected to happen and
21057 what in fact did happen. You don't know how to make a good report? See
21059 http://orgmode.org/manual/Feedback.html#Feedback
21061 Your bug report will be posted to the Org-mode mailing list.
21062 ------------------------------------------------------------------------")
21063 (save-excursion
21064 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21065 (replace-match "\\1Bug: \\3 [\\2]")))))
21068 (defun org-install-agenda-files-menu ()
21069 (let ((bl (buffer-list)))
21070 (save-excursion
21071 (while bl
21072 (set-buffer (pop bl))
21073 (if (derived-mode-p 'org-mode) (setq bl nil)))
21074 (when (derived-mode-p 'org-mode)
21075 (easy-menu-change
21076 '("Org") "File List for Agenda"
21077 (append
21078 (list
21079 ["Edit File List" (org-edit-agenda-file-list) t]
21080 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21081 ["Remove Current File from List" org-remove-file t]
21082 ["Cycle through agenda files" org-cycle-agenda-files t]
21083 ["Occur in all agenda files" org-occur-in-agenda-files t]
21084 "--")
21085 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21087 ;;;; Documentation
21089 (defun org-require-autoloaded-modules ()
21090 (interactive)
21091 (mapc 'require
21092 '(org-agenda org-archive org-attach org-clock org-colview org-id
21093 org-remember org-table org-timer)))
21095 ;;;###autoload
21096 (defun org-reload (&optional uncompiled)
21097 "Reload all org lisp files.
21098 With prefix arg UNCOMPILED, load the uncompiled versions."
21099 (interactive "P")
21100 (require 'loadhist)
21101 (let* ((org-dir (org-find-library-dir "org"))
21102 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21103 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21104 (remove-re (mapconcat 'identity
21105 (mapcar (lambda (f) (concat "^" f "$"))
21106 (list (if (featurep 'xemacs)
21107 "org-colview"
21108 "org-colview-xemacs")
21109 "org" "org-loaddefs" "org-version"))
21110 "\\|"))
21111 (feats (delete-dups
21112 (mapcar 'file-name-sans-extension
21113 (mapcar 'file-name-nondirectory
21114 (delq nil
21115 (mapcar 'feature-file
21116 features))))))
21117 (lfeat (append
21118 (sort
21119 (setq feats
21120 (delq nil (mapcar
21121 (lambda (f)
21122 (if (and (string-match feature-re f)
21123 (not (string-match remove-re f)))
21124 f nil))
21125 feats)))
21126 'string-lessp)
21127 (list "org-version" "org")))
21128 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21129 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21130 load-uncore load-misses)
21131 (setq load-misses
21132 (delq 't
21133 (mapcar (lambda (f)
21134 (or (org-load-noerror-mustsuffix (concat org-dir f))
21135 (and (string= org-dir contrib-dir)
21136 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21137 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21138 (add-to-list 'load-uncore f 'append)
21141 lfeat)))
21142 (if load-uncore
21143 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21144 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21145 (if load-misses
21146 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21147 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21148 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21150 ;;;###autoload
21151 (defun org-customize ()
21152 "Call the customize function with org as argument."
21153 (interactive)
21154 (org-load-modules-maybe)
21155 (org-require-autoloaded-modules)
21156 (customize-browse 'org))
21158 (defun org-create-customize-menu ()
21159 "Create a full customization menu for Org-mode, insert it into the menu."
21160 (interactive)
21161 (org-load-modules-maybe)
21162 (org-require-autoloaded-modules)
21163 (if (fboundp 'customize-menu-create)
21164 (progn
21165 (easy-menu-change
21166 '("Org") "Customize"
21167 `(["Browse Org group" org-customize t]
21168 "--"
21169 ,(customize-menu-create 'org)
21170 ["Set" Custom-set t]
21171 ["Save" Custom-save t]
21172 ["Reset to Current" Custom-reset-current t]
21173 ["Reset to Saved" Custom-reset-saved t]
21174 ["Reset to Standard Settings" Custom-reset-standard t]))
21175 (message "\"Org\"-menu now contains full customization menu"))
21176 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21178 ;;;; Miscellaneous stuff
21180 ;;; Generally useful functions
21182 (defun org-get-at-bol (property)
21183 "Get text property PROPERTY at beginning of line."
21184 (get-text-property (point-at-bol) property))
21186 (defun org-find-text-property-in-string (prop s)
21187 "Return the first non-nil value of property PROP in string S."
21188 (or (get-text-property 0 prop s)
21189 (get-text-property (or (next-single-property-change 0 prop s) 0)
21190 prop s)))
21192 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21193 "Display the given MESSAGE as a warning."
21194 (if (fboundp 'display-warning)
21195 (display-warning 'org message
21196 (if (featurep 'xemacs) 'warning :warning))
21197 (let ((buf (get-buffer-create "*Org warnings*")))
21198 (with-current-buffer buf
21199 (goto-char (point-max))
21200 (insert "Warning (Org): " message)
21201 (unless (bolp)
21202 (newline)))
21203 (display-buffer buf)
21204 (sit-for 0))))
21206 (defun org-eval (form)
21207 "Eval FORM and return result."
21208 (condition-case error
21209 (eval form)
21210 (error (format "%%![Error: %s]" error))))
21212 (defun org-in-clocktable-p ()
21213 "Check if the cursor is in a clocktable."
21214 (let ((pos (point)) start)
21215 (save-excursion
21216 (end-of-line 1)
21217 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21218 (setq start (match-beginning 0))
21219 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21220 (>= (match-end 0) pos)
21221 start))))
21223 (defun org-in-commented-line ()
21224 "Is point in a line starting with `#'?"
21225 (equal (char-after (point-at-bol)) ?#))
21227 (defun org-in-indented-comment-line ()
21228 "Is point in a line starting with `#' after some white space?"
21229 (save-excursion
21230 (save-match-data
21231 (goto-char (point-at-bol))
21232 (looking-at "[ \t]*#"))))
21234 (defun org-in-verbatim-emphasis ()
21235 (save-match-data
21236 (and (org-in-regexp org-emph-re 2)
21237 (>= (point) (match-beginning 3))
21238 (<= (point) (match-end 4))
21239 (member (match-string 3) '("=" "~")))))
21241 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21242 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21243 (if (and marker (marker-buffer marker)
21244 (buffer-live-p (marker-buffer marker)))
21245 (progn
21246 (org-pop-to-buffer-same-window (marker-buffer marker))
21247 (if (or (> marker (point-max)) (< marker (point-min)))
21248 (widen))
21249 (goto-char marker)
21250 (org-show-context 'org-goto))
21251 (if bookmark
21252 (bookmark-jump bookmark)
21253 (error "Cannot find location"))))
21255 (defun org-quote-csv-field (s)
21256 "Quote field for inclusion in CSV material."
21257 (if (string-match "[\",]" s)
21258 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21261 (defun org-force-self-insert (N)
21262 "Needed to enforce self-insert under remapping."
21263 (interactive "p")
21264 (self-insert-command N))
21266 (defun org-string-width (s)
21267 "Compute width of string, ignoring invisible characters.
21268 This ignores character with invisibility property `org-link', and also
21269 characters with property `org-cwidth', because these will become invisible
21270 upon the next fontification round."
21271 (let (b l)
21272 (when (or (eq t buffer-invisibility-spec)
21273 (assq 'org-link buffer-invisibility-spec))
21274 (while (setq b (text-property-any 0 (length s)
21275 'invisible 'org-link s))
21276 (setq s (concat (substring s 0 b)
21277 (substring s (or (next-single-property-change
21278 b 'invisible s) (length s)))))))
21279 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21280 (setq s (concat (substring s 0 b)
21281 (substring s (or (next-single-property-change
21282 b 'org-cwidth s) (length s))))))
21283 (setq l (string-width s) b -1)
21284 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21285 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21288 (defun org-shorten-string (s maxlength)
21289 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21290 If the string is shorter or has length MAXLENGTH, just return the
21291 original string. If it is longer, the functions finds a space in the
21292 string, breaks this string off at that locations and adds three dots
21293 as ellipsis. Including the ellipsis, the string will not be longer
21294 than MAXLENGTH. If finding a good breaking point in the string does
21295 not work, the string is just chopped off in the middle of a word
21296 if necessary."
21297 (if (<= (length s) maxlength)
21299 (let* ((n (max (- maxlength 4) 1))
21300 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21301 (if (string-match re s)
21302 (concat (match-string 1 s) "...")
21303 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21305 (defun org-get-indentation (&optional line)
21306 "Get the indentation of the current line, interpreting tabs.
21307 When LINE is given, assume it represents a line and compute its indentation."
21308 (if line
21309 (if (string-match "^ *" (org-remove-tabs line))
21310 (match-end 0))
21311 (save-excursion
21312 (beginning-of-line 1)
21313 (skip-chars-forward " \t")
21314 (current-column))))
21316 (defun org-get-string-indentation (s)
21317 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21318 (let ((n -1) (i 0) (w tab-width) c)
21319 (catch 'exit
21320 (while (< (setq n (1+ n)) (length s))
21321 (setq c (aref s n))
21322 (cond ((= c ?\ ) (setq i (1+ i)))
21323 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21324 (t (throw 'exit t)))))
21327 (defun org-remove-tabs (s &optional width)
21328 "Replace tabulators in S with spaces.
21329 Assumes that s is a single line, starting in column 0."
21330 (setq width (or width tab-width))
21331 (while (string-match "\t" s)
21332 (setq s (replace-match
21333 (make-string
21334 (- (* width (/ (+ (match-beginning 0) width) width))
21335 (match-beginning 0)) ?\ )
21336 t t s)))
21339 (defun org-fix-indentation (line ind)
21340 "Fix indentation in LINE.
21341 IND is a cons cell with target and minimum indentation.
21342 If the current indentation in LINE is smaller than the minimum,
21343 leave it alone. If it is larger than ind, set it to the target."
21344 (let* ((l (org-remove-tabs line))
21345 (i (org-get-indentation l))
21346 (i1 (car ind)) (i2 (cdr ind)))
21347 (if (>= i i2) (setq l (substring line i2)))
21348 (if (> i1 0)
21349 (concat (make-string i1 ?\ ) l)
21350 l)))
21352 (defun org-remove-indentation (code &optional n)
21353 "Remove the maximum common indentation from the lines in CODE.
21354 N may optionally be the number of spaces to remove."
21355 (with-temp-buffer
21356 (insert code)
21357 (org-do-remove-indentation n)
21358 (buffer-string)))
21360 (defun org-do-remove-indentation (&optional n)
21361 "Remove the maximum common indentation from the buffer."
21362 (untabify (point-min) (point-max))
21363 (let ((min 10000) re)
21364 (if n
21365 (setq min n)
21366 (goto-char (point-min))
21367 (while (re-search-forward "^ *[^ \n]" nil t)
21368 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21369 (unless (or (= min 0) (= min 10000))
21370 (setq re (format "^ \\{%d\\}" min))
21371 (goto-char (point-min))
21372 (while (re-search-forward re nil t)
21373 (replace-match "")
21374 (end-of-line 1))
21375 min)))
21377 (defun org-fill-template (template alist)
21378 "Find each %key of ALIST in TEMPLATE and replace it."
21379 (let ((case-fold-search nil)
21380 entry key value)
21381 (setq alist (sort (copy-sequence alist)
21382 (lambda (a b) (< (length (car a)) (length (car b))))))
21383 (while (setq entry (pop alist))
21384 (setq template
21385 (replace-regexp-in-string
21386 (concat "%" (regexp-quote (car entry)))
21387 (or (cdr entry) "") template t t)))
21388 template))
21390 (defun org-base-buffer (buffer)
21391 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21392 (if (not buffer)
21393 buffer
21394 (or (buffer-base-buffer buffer)
21395 buffer)))
21397 (defun org-trim (s)
21398 "Remove whitespace at beginning and end of string."
21399 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21400 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21403 (defun org-wrap (string &optional width lines)
21404 "Wrap string to either a number of lines, or a width in characters.
21405 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21406 that costs. If there is a word longer than WIDTH, the text is actually
21407 wrapped to the length of that word.
21408 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21409 many lines, whatever width that takes.
21410 The return value is a list of lines, without newlines at the end."
21411 (let* ((words (org-split-string string "[ \t\n]+"))
21412 (maxword (apply 'max (mapcar 'org-string-width words)))
21413 w ll)
21414 (cond (width
21415 (org-do-wrap words (max maxword width)))
21416 (lines
21417 (setq w maxword)
21418 (setq ll (org-do-wrap words maxword))
21419 (if (<= (length ll) lines)
21421 (setq ll words)
21422 (while (> (length ll) lines)
21423 (setq w (1+ w))
21424 (setq ll (org-do-wrap words w)))
21425 ll))
21426 (t (error "Cannot wrap this")))))
21428 (defun org-do-wrap (words width)
21429 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21430 (let (lines line)
21431 (while words
21432 (setq line (pop words))
21433 (while (and words (< (+ (length line) (length (car words))) width))
21434 (setq line (concat line " " (pop words))))
21435 (setq lines (push line lines)))
21436 (nreverse lines)))
21438 (defun org-split-string (string &optional separators)
21439 "Splits STRING into substrings at SEPARATORS.
21440 No empty strings are returned if there are matches at the beginning
21441 and end of string."
21442 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21443 (start 0)
21444 notfirst
21445 (list nil))
21446 (while (and (string-match rexp string
21447 (if (and notfirst
21448 (= start (match-beginning 0))
21449 (< start (length string)))
21450 (1+ start) start))
21451 (< (match-beginning 0) (length string)))
21452 (setq notfirst t)
21453 (or (eq (match-beginning 0) 0)
21454 (and (eq (match-beginning 0) (match-end 0))
21455 (eq (match-beginning 0) start))
21456 (setq list
21457 (cons (substring string start (match-beginning 0))
21458 list)))
21459 (setq start (match-end 0)))
21460 (or (eq start (length string))
21461 (setq list
21462 (cons (substring string start)
21463 list)))
21464 (nreverse list)))
21466 (defun org-quote-vert (s)
21467 "Replace \"|\" with \"\\vert\"."
21468 (while (string-match "|" s)
21469 (setq s (replace-match "\\vert" t t s)))
21472 (defun org-uuidgen-p (s)
21473 "Is S an ID created by UUIDGEN?"
21474 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21476 (defun org-in-src-block-p (&optional inside)
21477 "Whether point is in a code source block.
21478 When INSIDE is non-nil, don't consider we are within a src block
21479 when point is at #+BEGIN_SRC or #+END_SRC."
21480 (let ((case-fold-search t) ov)
21481 (or (and (setq ov (overlays-at (point)))
21482 (memq 'org-block-background
21483 (overlay-properties (car ov))))
21484 (and (not inside)
21485 (save-match-data
21486 (save-excursion
21487 (beginning-of-line)
21488 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21490 (defun org-context ()
21491 "Return a list of contexts of the current cursor position.
21492 If several contexts apply, all are returned.
21493 Each context entry is a list with a symbol naming the context, and
21494 two positions indicating start and end of the context. Possible
21495 contexts are:
21497 :headline anywhere in a headline
21498 :headline-stars on the leading stars in a headline
21499 :todo-keyword on a TODO keyword (including DONE) in a headline
21500 :tags on the TAGS in a headline
21501 :priority on the priority cookie in a headline
21502 :item on the first line of a plain list item
21503 :item-bullet on the bullet/number of a plain list item
21504 :checkbox on the checkbox in a plain list item
21505 :table in an org-mode table
21506 :table-special on a special filed in a table
21507 :table-table in a table.el table
21508 :clocktable in a clocktable
21509 :src-block in a source block
21510 :link on a hyperlink
21511 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21512 :target on a <<target>>
21513 :radio-target on a <<<radio-target>>>
21514 :latex-fragment on a LaTeX fragment
21515 :latex-preview on a LaTeX fragment with overlaid preview image
21517 This function expects the position to be visible because it uses font-lock
21518 faces as a help to recognize the following contexts: :table-special, :link,
21519 and :keyword."
21520 (let* ((f (get-text-property (point) 'face))
21521 (faces (if (listp f) f (list f)))
21522 (case-fold-search t)
21523 (p (point)) clist o)
21524 ;; First the large context
21525 (cond
21526 ((org-at-heading-p t)
21527 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21528 (when (progn
21529 (beginning-of-line 1)
21530 (looking-at org-todo-line-tags-regexp))
21531 (push (org-point-in-group p 1 :headline-stars) clist)
21532 (push (org-point-in-group p 2 :todo-keyword) clist)
21533 (push (org-point-in-group p 4 :tags) clist))
21534 (goto-char p)
21535 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21536 (if (looking-at "\\[#[A-Z0-9]\\]")
21537 (push (org-point-in-group p 0 :priority) clist)))
21539 ((org-at-item-p)
21540 (push (org-point-in-group p 2 :item-bullet) clist)
21541 (push (list :item (point-at-bol)
21542 (save-excursion (org-end-of-item) (point)))
21543 clist)
21544 (and (org-at-item-checkbox-p)
21545 (push (org-point-in-group p 0 :checkbox) clist)))
21547 ((org-at-table-p)
21548 (push (list :table (org-table-begin) (org-table-end)) clist)
21549 (if (memq 'org-formula faces)
21550 (push (list :table-special
21551 (previous-single-property-change p 'face)
21552 (next-single-property-change p 'face)) clist)))
21553 ((org-at-table-p 'any)
21554 (push (list :table-table) clist)))
21555 (goto-char p)
21557 (let ((case-fold-search t))
21558 ;; New the "medium" contexts: clocktables, source blocks
21559 (cond ((org-in-clocktable-p)
21560 (push (list :clocktable
21561 (and (or (looking-at "#\\+BEGIN: clocktable")
21562 (search-backward "#+BEGIN: clocktable" nil t))
21563 (match-beginning 0))
21564 (and (re-search-forward "#\\+END:?" nil t)
21565 (match-end 0))) clist))
21566 ((org-in-src-block-p)
21567 (push (list :src-block
21568 (and (or (looking-at "#\\+BEGIN_SRC")
21569 (search-backward "#+BEGIN_SRC" nil t))
21570 (match-beginning 0))
21571 (and (search-forward "#+END_SRC" nil t)
21572 (match-beginning 0))) clist))))
21573 (goto-char p)
21575 ;; Now the small context
21576 (cond
21577 ((org-at-timestamp-p)
21578 (push (org-point-in-group p 0 :timestamp) clist))
21579 ((memq 'org-link faces)
21580 (push (list :link
21581 (previous-single-property-change p 'face)
21582 (next-single-property-change p 'face)) clist))
21583 ((memq 'org-special-keyword faces)
21584 (push (list :keyword
21585 (previous-single-property-change p 'face)
21586 (next-single-property-change p 'face)) clist))
21587 ((org-at-target-p)
21588 (push (org-point-in-group p 0 :target) clist)
21589 (goto-char (1- (match-beginning 0)))
21590 (if (looking-at org-radio-target-regexp)
21591 (push (org-point-in-group p 0 :radio-target) clist))
21592 (goto-char p))
21593 ((setq o (car (delq nil
21594 (mapcar
21595 (lambda (x)
21596 (if (memq x org-latex-fragment-image-overlays) x))
21597 (overlays-at (point))))))
21598 (push (list :latex-fragment
21599 (overlay-start o) (overlay-end o)) clist)
21600 (push (list :latex-preview
21601 (overlay-start o) (overlay-end o)) clist))
21602 ((org-inside-LaTeX-fragment-p)
21603 ;; FIXME: positions wrong.
21604 (push (list :latex-fragment (point) (point)) clist)))
21606 (setq clist (nreverse (delq nil clist)))
21607 clist))
21609 ;; FIXME: Compare with at-regexp-p Do we need both?
21610 (defun org-in-regexp (re &optional nlines visually)
21611 "Check if point is inside a match of regexp.
21612 Normally only the current line is checked, but you can include NLINES extra
21613 lines both before and after point into the search.
21614 If VISUALLY is set, require that the cursor is not after the match but
21615 really on, so that the block visually is on the match."
21616 (catch 'exit
21617 (let ((pos (point))
21618 (eol (point-at-eol (+ 1 (or nlines 0))))
21619 (inc (if visually 1 0)))
21620 (save-excursion
21621 (beginning-of-line (- 1 (or nlines 0)))
21622 (while (re-search-forward re eol t)
21623 (if (and (<= (match-beginning 0) pos)
21624 (>= (+ inc (match-end 0)) pos))
21625 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21627 (defun org-at-regexp-p (regexp)
21628 "Is point inside a match of REGEXP in the current line?"
21629 (catch 'exit
21630 (save-excursion
21631 (let ((pos (point)) (end (point-at-eol)))
21632 (beginning-of-line 1)
21633 (while (re-search-forward regexp end t)
21634 (if (and (<= (match-beginning 0) pos)
21635 (>= (match-end 0) pos))
21636 (throw 'exit t)))
21637 nil))))
21639 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21640 "Non-nil when point is between matches of START-RE and END-RE.
21642 Also return a non-nil value when point is on one of the matches.
21644 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21645 buffer positions. Default values are the positions of headlines
21646 surrounding the point.
21648 The functions returns a cons cell whose car (resp. cdr) is the
21649 position before START-RE (resp. after END-RE)."
21650 (save-match-data
21651 (let ((pos (point))
21652 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21653 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21654 beg end)
21655 (save-excursion
21656 ;; Point is on a block when on START-RE or if START-RE can be
21657 ;; found before it...
21658 (and (or (org-at-regexp-p start-re)
21659 (re-search-backward start-re limit-up t))
21660 (setq beg (match-beginning 0))
21661 ;; ... and END-RE after it...
21662 (goto-char (match-end 0))
21663 (re-search-forward end-re limit-down t)
21664 (> (setq end (match-end 0)) pos)
21665 ;; ... without another START-RE in-between.
21666 (goto-char (match-beginning 0))
21667 (not (re-search-backward start-re (1+ beg) t))
21668 ;; Return value.
21669 (cons beg end))))))
21671 (defun org-in-block-p (names)
21672 "Non-nil when point belongs to a block whose name belongs to NAMES.
21674 NAMES is a list of strings containing names of blocks.
21676 Return first block name matched, or nil. Beware that in case of
21677 nested blocks, the returned name may not belong to the closest
21678 block from point."
21679 (save-match-data
21680 (catch 'exit
21681 (let ((case-fold-search t)
21682 (lim-up (save-excursion (outline-previous-heading)))
21683 (lim-down (save-excursion (outline-next-heading))))
21684 (mapc (lambda (name)
21685 (let ((n (regexp-quote name)))
21686 (when (org-between-regexps-p
21687 (concat "^[ \t]*#\\+begin_" n)
21688 (concat "^[ \t]*#\\+end_" n)
21689 lim-up lim-down)
21690 (throw 'exit n))))
21691 names))
21692 nil)))
21694 (defun org-in-drawer-p ()
21695 "Non-nil if point is within a drawer.
21696 If point is within a drawer, return it, as parsed data."
21697 (let ((element (save-match-data (org-element-at-point))))
21698 (while (and element (not (memq (org-element-type element)
21699 '(drawer property-drawer))))
21700 (setq element (org-element-property :parent element)))
21701 element))
21703 (defun org-occur-in-agenda-files (regexp &optional nlines)
21704 "Call `multi-occur' with buffers for all agenda files."
21705 (interactive "sOrg-files matching: \np")
21706 (let* ((files (org-agenda-files))
21707 (tnames (mapcar 'file-truename files))
21708 (extra org-agenda-text-search-extra-files)
21710 (when (eq (car extra) 'agenda-archives)
21711 (setq extra (cdr extra))
21712 (setq files (org-add-archive-files files)))
21713 (while (setq f (pop extra))
21714 (unless (member (file-truename f) tnames)
21715 (add-to-list 'files f 'append)
21716 (add-to-list 'tnames (file-truename f) 'append)))
21717 (multi-occur
21718 (mapcar (lambda (x)
21719 (with-current-buffer
21720 (or (get-file-buffer x) (find-file-noselect x))
21721 (widen)
21722 (current-buffer)))
21723 files)
21724 regexp)))
21726 (if (boundp 'occur-mode-find-occurrence-hook)
21727 ;; Emacs 23
21728 (add-hook 'occur-mode-find-occurrence-hook
21729 (lambda ()
21730 (when (derived-mode-p 'org-mode)
21731 (org-reveal))))
21732 ;; Emacs 22
21733 (defadvice occur-mode-goto-occurrence
21734 (after org-occur-reveal activate)
21735 (and (derived-mode-p 'org-mode) (org-reveal)))
21736 (defadvice occur-mode-goto-occurrence-other-window
21737 (after org-occur-reveal activate)
21738 (and (derived-mode-p 'org-mode) (org-reveal)))
21739 (defadvice occur-mode-display-occurrence
21740 (after org-occur-reveal activate)
21741 (when (derived-mode-p 'org-mode)
21742 (let ((pos (occur-mode-find-occurrence)))
21743 (with-current-buffer (marker-buffer pos)
21744 (save-excursion
21745 (goto-char pos)
21746 (org-reveal)))))))
21748 (defun org-occur-link-in-agenda-files ()
21749 "Create a link and search for it in the agendas.
21750 The link is not stored in `org-stored-links', it is just created
21751 for the search purpose."
21752 (interactive)
21753 (let ((link (condition-case nil
21754 (org-store-link nil)
21755 (error "Unable to create a link to here"))))
21756 (org-occur-in-agenda-files (regexp-quote link))))
21758 (defun org-reverse-string (string)
21759 "Return the reverse of STRING."
21760 (apply 'string (reverse (string-to-list string))))
21762 (defsubst org-uniquify (list)
21763 "Non-destructively remove duplicate elements from LIST."
21764 (let ((res (copy-sequence list))) (delete-dups res)))
21766 (defun org-uniquify-alist (alist)
21767 "Merge elements of ALIST with the same key.
21769 For example, in this alist:
21771 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21772 => '((a 1 3) (b 2))
21774 merge (a 1) and (a 3) into (a 1 3).
21776 The function returns the new ALIST."
21777 (let (rtn)
21778 (mapc
21779 (lambda (e)
21780 (let (n)
21781 (if (not (assoc (car e) rtn))
21782 (push e rtn)
21783 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21784 (setq rtn (assq-delete-all (car e) rtn))
21785 (push n rtn))))
21786 alist)
21787 rtn))
21789 (defun org-delete-all (elts list)
21790 "Remove all elements in ELTS from LIST."
21791 (while elts
21792 (setq list (delete (pop elts) list)))
21793 list)
21795 (defun org-count (cl-item cl-seq)
21796 "Count the number of occurrences of ITEM in SEQ.
21797 Taken from `count' in cl-seq.el with all keyword arguments removed."
21798 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21799 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21800 (while (< cl-start cl-end)
21801 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21802 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21803 (setq cl-start (1+ cl-start)))
21804 cl-count))
21806 (defun org-remove-if (predicate seq)
21807 "Remove everything from SEQ that fulfills PREDICATE."
21808 (let (res e)
21809 (while seq
21810 (setq e (pop seq))
21811 (if (not (funcall predicate e)) (push e res)))
21812 (nreverse res)))
21814 (defun org-remove-if-not (predicate seq)
21815 "Remove everything from SEQ that does not fulfill PREDICATE."
21816 (let (res e)
21817 (while seq
21818 (setq e (pop seq))
21819 (if (funcall predicate e) (push e res)))
21820 (nreverse res)))
21822 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21823 "Reduce two-argument FUNCTION across SEQ.
21824 Taken from `reduce' in cl-seq.el with all keyword arguments but
21825 \":initial-value\" removed."
21826 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21827 (cadr (memq :initial-value cl-keys)))
21828 (cl-seq (pop cl-seq))
21829 (t (funcall cl-func)))))
21830 (while cl-seq
21831 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21832 cl-accum))
21834 (defun org-every (pred seq)
21835 "Return true if PREDICATE is true of every element of SEQ.
21836 Adapted from `every' in cl.el."
21837 (catch 'org-every
21838 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21841 (defun org-some (pred seq)
21842 "Return true if PREDICATE is true of any element of SEQ.
21843 Adapted from `some' in cl.el."
21844 (catch 'org-some
21845 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21846 nil))
21848 (defun org-back-over-empty-lines ()
21849 "Move backwards over whitespace, to the beginning of the first empty line.
21850 Returns the number of empty lines passed."
21851 (let ((pos (point)))
21852 (if (cdr (assoc 'heading org-blank-before-new-entry))
21853 (skip-chars-backward " \t\n\r")
21854 (unless (eobp)
21855 (forward-line -1)))
21856 (beginning-of-line 2)
21857 (goto-char (min (point) pos))
21858 (count-lines (point) pos)))
21860 (defun org-skip-whitespace ()
21861 (skip-chars-forward " \t\n\r"))
21863 (defun org-point-in-group (point group &optional context)
21864 "Check if POINT is in match-group GROUP.
21865 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21866 match. If the match group does not exist or point is not inside it,
21867 return nil."
21868 (and (match-beginning group)
21869 (>= point (match-beginning group))
21870 (<= point (match-end group))
21871 (if context
21872 (list context (match-beginning group) (match-end group))
21873 t)))
21875 (defun org-switch-to-buffer-other-window (&rest args)
21876 "Switch to buffer in a second window on the current frame.
21877 In particular, do not allow pop-up frames.
21878 Returns the newly created buffer."
21879 (org-no-popups
21880 (apply 'switch-to-buffer-other-window args)))
21882 (defun org-combine-plists (&rest plists)
21883 "Create a single property list from all plists in PLISTS.
21884 The process starts by copying the first list, and then setting properties
21885 from the other lists. Settings in the last list are the most significant
21886 ones and overrule settings in the other lists."
21887 (let ((rtn (copy-sequence (pop plists)))
21888 p v ls)
21889 (while plists
21890 (setq ls (pop plists))
21891 (while ls
21892 (setq p (pop ls) v (pop ls))
21893 (setq rtn (plist-put rtn p v))))
21894 rtn))
21896 (defun org-replace-escapes (string table)
21897 "Replace %-escapes in STRING with values in TABLE.
21898 TABLE is an association list with keys like \"%a\" and string values.
21899 The sequences in STRING may contain normal field width and padding information,
21900 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21901 so values can contain further %-escapes if they are define later in TABLE."
21902 (let ((tbl (copy-alist table))
21903 (case-fold-search nil)
21904 (pchg 0)
21905 e re rpl)
21906 (while (setq e (pop tbl))
21907 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21908 (when (and (cdr e) (string-match re (cdr e)))
21909 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21910 (safe "SREF"))
21911 (add-text-properties 0 3 (list 'sref sref) safe)
21912 (setcdr e (replace-match safe t t (cdr e)))))
21913 (while (string-match re string)
21914 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21915 (cdr e)))
21916 (setq string (replace-match rpl t t string))))
21917 (while (setq pchg (next-property-change pchg string))
21918 (let ((sref (get-text-property pchg 'sref string)))
21919 (when (and sref (string-match "SREF" string pchg))
21920 (setq string (replace-match sref t t string)))))
21921 string))
21923 (defun org-sublist (list start end)
21924 "Return a section of LIST, from START to END.
21925 Counting starts at 1."
21926 (let (rtn (c start))
21927 (setq list (nthcdr (1- start) list))
21928 (while (and list (<= c end))
21929 (push (pop list) rtn)
21930 (setq c (1+ c)))
21931 (nreverse rtn)))
21933 (defun org-find-base-buffer-visiting (file)
21934 "Like `find-buffer-visiting' but always return the base buffer and
21935 not an indirect buffer."
21936 (let ((buf (or (get-file-buffer file)
21937 (find-buffer-visiting file))))
21938 (if buf
21939 (or (buffer-base-buffer buf) buf)
21940 nil)))
21942 (defun org-image-file-name-regexp (&optional extensions)
21943 "Return regexp matching the file names of images.
21944 If EXTENSIONS is given, only match these."
21945 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21946 (image-file-name-regexp)
21947 (let ((image-file-name-extensions
21948 (or extensions
21949 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21950 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21951 (concat "\\."
21952 (regexp-opt (nconc (mapcar 'upcase
21953 image-file-name-extensions)
21954 image-file-name-extensions)
21956 "\\'"))))
21958 (defun org-file-image-p (file &optional extensions)
21959 "Return non-nil if FILE is an image."
21960 (save-match-data
21961 (string-match (org-image-file-name-regexp extensions) file)))
21963 (defun org-get-cursor-date (&optional with-time)
21964 "Return the date at cursor in as a time.
21965 This works in the calendar and in the agenda, anywhere else it just
21966 returns the current time.
21967 If WITH-TIME is non-nil, returns the time of the event at point (in
21968 the agenda) or the current time of the day."
21969 (let (date day defd tp tm hod mod)
21970 (when with-time
21971 (setq tp (get-text-property (point) 'time))
21972 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21973 (setq hod (string-to-number (match-string 1 tp))
21974 mod (string-to-number (match-string 2 tp))))
21975 (or tp (setq hod (nth 2 (decode-time (current-time)))
21976 mod (nth 1 (decode-time (current-time))))))
21977 (cond
21978 ((eq major-mode 'calendar-mode)
21979 (setq date (calendar-cursor-to-date)
21980 defd (encode-time 0 (or mod 0) (or hod 0)
21981 (nth 1 date) (nth 0 date) (nth 2 date))))
21982 ((eq major-mode 'org-agenda-mode)
21983 (setq day (get-text-property (point) 'day))
21984 (if day
21985 (setq date (calendar-gregorian-from-absolute day)
21986 defd (encode-time 0 (or mod 0) (or hod 0)
21987 (nth 1 date) (nth 0 date) (nth 2 date))))))
21988 (or defd (current-time))))
21990 (defun org-mark-subtree (&optional up)
21991 "Mark the current subtree.
21992 This puts point at the start of the current subtree, and mark at
21993 the end. If a numeric prefix UP is given, move up into the
21994 hierarchy of headlines by UP levels before marking the subtree."
21995 (interactive "P")
21996 (org-with-limited-levels
21997 (cond ((org-at-heading-p) (beginning-of-line))
21998 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21999 (t (outline-previous-visible-heading 1))))
22000 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22001 (if (org-called-interactively-p 'any)
22002 (call-interactively 'org-mark-element)
22003 (org-mark-element)))
22006 ;;; Indentation
22008 (defun org-indent-line ()
22009 "Indent line depending on context."
22010 (interactive)
22011 (let* ((pos (point))
22012 (itemp (org-at-item-p))
22013 (case-fold-search t)
22014 (org-drawer-regexp (or org-drawer-regexp "\000"))
22015 (inline-task-p (and (featurep 'org-inlinetask)
22016 (org-inlinetask-in-task-p)))
22017 (inline-re (and inline-task-p
22018 (org-inlinetask-outline-regexp)))
22019 column)
22020 (if (and orgstruct-is-++ (eq pos (point)))
22021 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22022 (indent-according-to-mode))
22023 (beginning-of-line 1)
22024 (cond
22025 ;; Headings
22026 ((looking-at org-outline-regexp) (setq column 0))
22027 ;; Footnote definition
22028 ((looking-at org-footnote-definition-re) (setq column 0))
22029 ;; Literal examples
22030 ((looking-at "[ \t]*:\\( \\|$\\)")
22031 (setq column (org-get-indentation))) ; do nothing
22032 ;; Lists
22033 ((ignore-errors (goto-char (org-in-item-p)))
22034 (setq column (if itemp
22035 (org-get-indentation)
22036 (org-list-item-body-column (point))))
22037 (goto-char pos))
22038 ;; Drawers
22039 ((and (looking-at "[ \t]*:END:")
22040 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22041 (save-excursion
22042 (goto-char (1- (match-beginning 1)))
22043 (setq column (current-column))))
22044 ;; Special blocks
22045 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22046 (save-excursion
22047 (re-search-backward
22048 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22049 (setq column (org-get-indentation (match-string 0))))
22050 ((and (not (looking-at "[ \t]*#\\+begin_"))
22051 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22052 (save-excursion
22053 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22054 (setq column
22055 (cond ((equal (downcase (match-string 1)) "src")
22056 ;; src blocks: let `org-edit-src-exit' handle them
22057 (org-get-indentation))
22058 ((equal (downcase (match-string 1)) "example")
22059 (max (org-get-indentation)
22060 (org-get-indentation (match-string 0))))
22062 (org-get-indentation (match-string 0))))))
22063 ;; This line has nothing special, look at the previous relevant
22064 ;; line to compute indentation
22066 (beginning-of-line 0)
22067 (while (and (not (bobp))
22068 (not (looking-at org-table-line-regexp))
22069 (not (looking-at org-drawer-regexp))
22070 ;; When point started in an inline task, do not move
22071 ;; above task starting line.
22072 (not (and inline-task-p (looking-at inline-re)))
22073 ;; Skip drawers, blocks, empty lines, verbatim,
22074 ;; comments, tables, footnotes definitions, lists,
22075 ;; inline tasks.
22076 (or (and (looking-at "[ \t]*:END:")
22077 (re-search-backward org-drawer-regexp nil t))
22078 (and (looking-at "[ \t]*#\\+end_")
22079 (re-search-backward "[ \t]*#\\+begin_"nil t))
22080 (looking-at "[ \t]*[\n:#|]")
22081 (looking-at org-footnote-definition-re)
22082 (and (not inline-task-p)
22083 (featurep 'org-inlinetask)
22084 (org-inlinetask-in-task-p)
22085 (or (org-inlinetask-goto-beginning) t))))
22086 (beginning-of-line 0))
22087 (cond
22088 ;; There was a list item above.
22089 ((ignore-errors (goto-char (org-in-item-p)))
22090 (goto-char (org-list-get-top-point (org-list-struct)))
22091 (setq column (org-get-indentation)))
22092 ;; There was an heading above.
22093 ((looking-at "\\*+[ \t]+")
22094 (if (not org-adapt-indentation)
22095 (setq column 0)
22096 (goto-char (match-end 0))
22097 (setq column (current-column))))
22098 ;; A drawer had started and is unfinished
22099 ((looking-at org-drawer-regexp)
22100 (goto-char (1- (match-beginning 1)))
22101 (setq column (current-column)))
22102 ;; Else, nothing noticeable found: get indentation and go on.
22103 (t (setq column (org-get-indentation))))))
22104 ;; Now apply indentation and move cursor accordingly
22105 (goto-char pos)
22106 (if (<= (current-column) (current-indentation))
22107 (org-indent-line-to column)
22108 (save-excursion (org-indent-line-to column)))
22109 ;; Special polishing for properties, see `org-property-format'
22110 (setq column (current-column))
22111 (beginning-of-line 1)
22112 (if (looking-at org-property-re)
22113 (replace-match (concat (match-string 4)
22114 (format org-property-format
22115 (match-string 1) (match-string 3)))
22116 t t))
22117 (org-move-to-column column))))
22119 (defun org-indent-drawer ()
22120 "Indent the drawer at point."
22121 (interactive)
22122 (let ((p (point))
22123 (e (and (save-excursion (re-search-forward ":END:" nil t))
22124 (match-end 0)))
22125 (folded
22126 (save-excursion
22127 (end-of-line)
22128 (when (overlays-at (point))
22129 (member 'invisible (overlay-properties
22130 (car (overlays-at (point)))))))))
22131 (when folded (org-cycle))
22132 (indent-for-tab-command)
22133 (while (and (move-beginning-of-line 2) (< (point) e))
22134 (indent-for-tab-command))
22135 (goto-char p)
22136 (when folded (org-cycle)))
22137 (message "Drawer at point indented"))
22139 (defun org-indent-block ()
22140 "Indent the block at point."
22141 (interactive)
22142 (let ((p (point))
22143 (case-fold-search t)
22144 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22145 (match-end 0)))
22146 (folded
22147 (save-excursion
22148 (end-of-line)
22149 (when (overlays-at (point))
22150 (member 'invisible (overlay-properties
22151 (car (overlays-at (point)))))))))
22152 (when folded (org-cycle))
22153 (indent-for-tab-command)
22154 (while (and (move-beginning-of-line 2) (< (point) e))
22155 (indent-for-tab-command))
22156 (goto-char p)
22157 (when folded (org-cycle)))
22158 (message "Block at point indented"))
22160 (defun org-indent-region (start end)
22161 "Indent region."
22162 (interactive "r")
22163 (save-excursion
22164 (let ((line-end (org-current-line end)))
22165 (goto-char start)
22166 (while (< (org-current-line) line-end)
22167 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22168 (t (call-interactively 'org-indent-line)))
22169 (move-beginning-of-line 2)))))
22172 ;;; Filling
22174 ;; We use our own fill-paragraph and auto-fill functions.
22176 ;; `org-fill-paragraph' relies on adaptive filling and context
22177 ;; checking. Appropriate `fill-prefix' is computed with
22178 ;; `org-adaptive-fill-function'.
22180 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22181 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22182 ;; `org-adaptive-fill-function' value. Internally,
22183 ;; `org-comment-line-break-function' breaks the line.
22185 ;; `org-setup-filling' installs filling and auto-filling related
22186 ;; variables during `org-mode' initialization.
22188 (defvar org-element-paragraph-separate) ; org-element.el
22189 (defun org-setup-filling ()
22190 (require 'org-element)
22191 ;; Prevent auto-fill from inserting unwanted new items.
22192 (when (boundp 'fill-nobreak-predicate)
22193 (org-set-local
22194 'fill-nobreak-predicate
22195 (org-uniquify
22196 (append fill-nobreak-predicate
22197 '(org-fill-line-break-nobreak-p
22198 org-fill-paragraph-with-timestamp-nobreak-p)))))
22199 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22200 (org-set-local 'paragraph-start paragraph-ending)
22201 (org-set-local 'paragraph-separate paragraph-ending))
22202 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22203 (org-set-local 'auto-fill-inhibit-regexp nil)
22204 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22205 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22206 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22208 (defun org-fill-line-break-nobreak-p ()
22209 "Non-nil when a new line at point would create an Org line break."
22210 (save-excursion
22211 (skip-chars-backward "[ \t]")
22212 (skip-chars-backward "\\\\")
22213 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22215 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22216 "Non-nil when a new line at point would split a timestamp."
22217 (and (org-at-timestamp-p t)
22218 (not (looking-at org-ts-regexp-both))))
22220 (declare-function message-in-body-p "message" ())
22221 (defvar orgtbl-line-start-regexp) ; From org-table.el
22222 (defun org-adaptive-fill-function ()
22223 "Compute a fill prefix for the current line.
22224 Return fill prefix, as a string, or nil if current line isn't
22225 meant to be filled. For convenience, if `adaptive-fill-regexp'
22226 matches in paragraphs or comments, use it."
22227 (catch 'exit
22228 (when (derived-mode-p 'message-mode)
22229 (save-excursion
22230 (beginning-of-line)
22231 (cond ((or (not (message-in-body-p))
22232 (looking-at orgtbl-line-start-regexp))
22233 (throw 'exit nil))
22234 ((looking-at message-cite-prefix-regexp)
22235 (throw 'exit (match-string-no-properties 0)))
22236 ((looking-at org-outline-regexp)
22237 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22238 (org-with-wide-buffer
22239 (let* ((p (line-beginning-position))
22240 (element (save-excursion
22241 (beginning-of-line)
22242 (or (ignore-errors (org-element-at-point))
22243 (user-error "An element cannot be parsed line %d"
22244 (line-number-at-pos (point))))))
22245 (type (org-element-type element))
22246 (post-affiliated (org-element-property :post-affiliated element)))
22247 (unless (and post-affiliated (< p post-affiliated))
22248 (case type
22249 (comment
22250 (save-excursion
22251 (beginning-of-line)
22252 (looking-at "[ \t]*")
22253 (concat (match-string 0) "# ")))
22254 (footnote-definition "")
22255 ((item plain-list)
22256 (make-string (org-list-item-body-column
22257 (or post-affiliated
22258 (org-element-property :begin element)))
22259 ? ))
22260 (paragraph
22261 ;; Fill prefix is usually the same as the current line,
22262 ;; unless the paragraph is at the beginning of an item.
22263 (let ((parent (org-element-property :parent element)))
22264 (save-excursion
22265 (beginning-of-line)
22266 (cond ((eq (org-element-type parent) 'item)
22267 (make-string (org-list-item-body-column
22268 (org-element-property :begin parent))
22269 ? ))
22270 ((and adaptive-fill-regexp
22271 ;; Locally disable
22272 ;; `adaptive-fill-function' to let
22273 ;; `fill-context-prefix' handle
22274 ;; `adaptive-fill-regexp' variable.
22275 (let (adaptive-fill-function)
22276 (fill-context-prefix
22277 post-affiliated
22278 (org-element-property :end element)))))
22279 ((looking-at "[ \t]+") (match-string 0))
22280 (t "")))))
22281 (comment-block
22282 ;; Only fill contents if P is within block boundaries.
22283 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22284 (forward-line)
22285 (point)))
22286 (cend (save-excursion
22287 (goto-char (org-element-property :end element))
22288 (skip-chars-backward " \r\t\n")
22289 (line-beginning-position))))
22290 (when (and (>= p cbeg) (< p cend))
22291 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22292 (match-string 0)
22293 ""))))))))))
22295 (declare-function message-goto-body "message" ())
22296 (defvar message-cite-prefix-regexp) ; From message.el
22297 (defun org-fill-paragraph (&optional justify)
22298 "Fill element at point, when applicable.
22300 This function only applies to comment blocks, comments, example
22301 blocks and paragraphs. Also, as a special case, re-align table
22302 when point is at one.
22304 If JUSTIFY is non-nil (interactively, with prefix argument),
22305 justify as well. If `sentence-end-double-space' is non-nil, then
22306 period followed by one space does not end a sentence, so don't
22307 break a line there. The variable `fill-column' controls the
22308 width for filling.
22310 For convenience, when point is at a plain list, an item or
22311 a footnote definition, try to fill the first paragraph within."
22312 (interactive)
22313 (if (and (derived-mode-p 'message-mode)
22314 (or (not (message-in-body-p))
22315 (save-excursion (move-beginning-of-line 1)
22316 (looking-at message-cite-prefix-regexp))))
22317 ;; First ensure filling is correct in message-mode.
22318 (let ((fill-paragraph-function
22319 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22320 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22321 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22322 (paragraph-separate
22323 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22324 (fill-paragraph nil))
22325 (with-syntax-table org-mode-transpose-word-syntax-table
22326 ;; Move to end of line in order to get the first paragraph
22327 ;; within a plain list or a footnote definition.
22328 (let ((element (save-excursion
22329 (end-of-line)
22330 (or (ignore-errors (org-element-at-point))
22331 (user-error "An element cannot be parsed line %d"
22332 (line-number-at-pos (point)))))))
22333 ;; First check if point is in a blank line at the beginning of
22334 ;; the buffer. In that case, ignore filling.
22335 (case (org-element-type element)
22336 ;; Use major mode filling function is src blocks.
22337 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22338 ;; Align Org tables, leave table.el tables as-is.
22339 (table-row (org-table-align) t)
22340 (table
22341 (when (eq (org-element-property :type element) 'org)
22342 (save-excursion
22343 (goto-char (org-element-property :post-affiliated element))
22344 (org-table-align)))
22346 (paragraph
22347 ;; Paragraphs may contain `line-break' type objects.
22348 (let ((beg (max (point-min)
22349 (org-element-property :contents-begin element)))
22350 (end (min (point-max)
22351 (org-element-property :contents-end element))))
22352 ;; Do nothing if point is at an affiliated keyword.
22353 (if (< (line-end-position) beg) t
22354 (when (derived-mode-p 'message-mode)
22355 ;; In `message-mode', do not fill following citation
22356 ;; in current paragraph nor text before message body.
22357 (let ((body-start (save-excursion (message-goto-body))))
22358 (when body-start (setq beg (max body-start beg))))
22359 (when (save-excursion
22360 (re-search-forward
22361 (concat "^" message-cite-prefix-regexp) end t))
22362 (setq end (match-beginning 0))))
22363 ;; Fill paragraph, taking line breaks into account.
22364 ;; For that, slice the paragraph using line breaks as
22365 ;; separators, and fill the parts in reverse order to
22366 ;; avoid messing with markers.
22367 (save-excursion
22368 (goto-char end)
22369 (mapc
22370 (lambda (pos)
22371 (fill-region-as-paragraph pos (point) justify)
22372 (goto-char pos))
22373 ;; Find the list of ending positions for line breaks
22374 ;; in the current paragraph. Add paragraph
22375 ;; beginning to include first slice.
22376 (nreverse
22377 (cons beg
22378 (org-element-map
22379 (org-element--parse-objects
22380 beg end nil (org-element-restriction 'paragraph))
22381 'line-break
22382 (lambda (lb) (org-element-property :end lb)))))))
22383 t)))
22384 ;; Contents of `comment-block' type elements should be
22385 ;; filled as plain text, but only if point is within block
22386 ;; markers.
22387 (comment-block
22388 (let* ((case-fold-search t)
22389 (beg (save-excursion
22390 (goto-char (org-element-property :begin element))
22391 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22392 (forward-line)
22393 (point)))
22394 (end (save-excursion
22395 (goto-char (org-element-property :end element))
22396 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22397 (line-beginning-position))))
22398 (if (or (< (point) beg) (> (point) end)) t
22399 (fill-region-as-paragraph
22400 (save-excursion (end-of-line)
22401 (re-search-backward "^[ \t]*$" beg 'move)
22402 (line-beginning-position))
22403 (save-excursion (beginning-of-line)
22404 (re-search-forward "^[ \t]*$" end 'move)
22405 (line-beginning-position))
22406 justify))))
22407 ;; Fill comments.
22408 (comment
22409 (let ((begin (org-element-property :post-affiliated element))
22410 (end (org-element-property :end element)))
22411 (when (and (>= (point) begin) (<= (point) end))
22412 (let ((begin (save-excursion
22413 (end-of-line)
22414 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22415 (progn (forward-line) (point))
22416 begin)))
22417 (end (save-excursion
22418 (end-of-line)
22419 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22420 (1- (line-beginning-position))
22421 (skip-chars-backward " \r\t\n")
22422 (line-end-position)))))
22423 ;; Do not fill comments when at a blank line.
22424 (when (> end begin)
22425 (let ((fill-prefix
22426 (save-excursion
22427 (beginning-of-line)
22428 (looking-at "[ \t]*#")
22429 (let ((comment-prefix (match-string 0)))
22430 (goto-char (match-end 0))
22431 (if (looking-at adaptive-fill-regexp)
22432 (concat comment-prefix (match-string 0))
22433 (concat comment-prefix " "))))))
22434 (save-excursion
22435 (fill-region-as-paragraph begin end justify))))))
22437 ;; Ignore every other element.
22438 (otherwise t))))))
22440 (defun org-auto-fill-function ()
22441 "Auto-fill function."
22442 ;; Check if auto-filling is meaningful.
22443 (let ((fc (current-fill-column)))
22444 (when (and fc (> (current-column) fc))
22445 (let* ((fill-prefix (org-adaptive-fill-function))
22446 ;; Enforce empty fill prefix, if required. Otherwise, it
22447 ;; will be computed again.
22448 (adaptive-fill-mode (not (equal fill-prefix ""))))
22449 (when fill-prefix (do-auto-fill))))))
22451 (defun org-comment-line-break-function (&optional soft)
22452 "Break line at point and indent, continuing comment if within one.
22453 The inserted newline is marked hard if variable
22454 `use-hard-newlines' is true, unless optional argument SOFT is
22455 non-nil."
22456 (if soft (insert-and-inherit ?\n) (newline 1))
22457 (save-excursion (forward-char -1) (delete-horizontal-space))
22458 (delete-horizontal-space)
22459 (indent-to-left-margin)
22460 (insert-before-markers-and-inherit fill-prefix))
22463 ;;; Comments
22465 ;; Org comments syntax is quite complex. It requires the entire line
22466 ;; to be just a comment. Also, even with the right syntax at the
22467 ;; beginning of line, some some elements (i.e. verse-block or
22468 ;; example-block) don't accept comments. Usual Emacs comment commands
22469 ;; cannot cope with those requirements. Therefore, Org replaces them.
22471 ;; Org still relies on `comment-dwim', but cannot trust
22472 ;; `comment-only-p'. So, `comment-region-function' and
22473 ;; `uncomment-region-function' both point
22474 ;; to`org-comment-or-uncomment-region'. Eventually,
22475 ;; `org-insert-comment' takes care of insertion of comments at the
22476 ;; beginning of line.
22478 ;; `org-setup-comments-handling' install comments related variables
22479 ;; during `org-mode' initialization.
22481 (defun org-setup-comments-handling ()
22482 (interactive)
22483 (org-set-local 'comment-use-syntax nil)
22484 (org-set-local 'comment-start "# ")
22485 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22486 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22487 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22488 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22490 (defun org-insert-comment ()
22491 "Insert an empty comment above current line.
22492 If the line is empty, insert comment at its beginning."
22493 (beginning-of-line)
22494 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22495 (org-indent-line)
22496 (insert "# "))
22498 (defvar comment-empty-lines) ; From newcomment.el.
22499 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22500 "Comment or uncomment each non-blank line in the region.
22501 Uncomment each non-blank line between BEG and END if it only
22502 contains commented lines. Otherwise, comment them."
22503 (save-restriction
22504 ;; Restrict region
22505 (narrow-to-region (save-excursion (goto-char beg)
22506 (skip-chars-forward " \r\t\n" end)
22507 (line-beginning-position))
22508 (save-excursion (goto-char end)
22509 (skip-chars-backward " \r\t\n" beg)
22510 (line-end-position)))
22511 (let ((uncommentp
22512 ;; UNCOMMENTP is non-nil when every non blank line between
22513 ;; BEG and END is a comment.
22514 (save-excursion
22515 (goto-char (point-min))
22516 (while (and (not (eobp))
22517 (let ((element (org-element-at-point)))
22518 (and (eq (org-element-type element) 'comment)
22519 (goto-char (min (point-max)
22520 (org-element-property
22521 :end element)))))))
22522 (eobp))))
22523 (if uncommentp
22524 ;; Only blank lines and comments in region: uncomment it.
22525 (save-excursion
22526 (goto-char (point-min))
22527 (while (not (eobp))
22528 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22529 (replace-match "" nil nil nil 1))
22530 (forward-line)))
22531 ;; Comment each line in region.
22532 (let ((min-indent (point-max)))
22533 ;; First find the minimum indentation across all lines.
22534 (save-excursion
22535 (goto-char (point-min))
22536 (while (and (not (eobp)) (not (zerop min-indent)))
22537 (unless (looking-at "[ \t]*$")
22538 (setq min-indent (min min-indent (current-indentation))))
22539 (forward-line)))
22540 ;; Then loop over all lines.
22541 (save-excursion
22542 (goto-char (point-min))
22543 (while (not (eobp))
22544 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22545 ;; Don't get fooled by invisible text (e.g. link path)
22546 ;; when moving to column MIN-INDENT.
22547 (let ((buffer-invisibility-spec nil))
22548 (org-move-to-column min-indent t))
22549 (insert comment-start))
22550 (forward-line))))))))
22553 ;;; Planning
22555 ;; This section contains tools to operate on timestamp objects, as
22556 ;; returned by, e.g. `org-element-context'.
22558 (defun org-timestamp-has-time-p (timestamp)
22559 "Non-nil when TIMESTAMP has a time specified."
22560 (org-element-property :hour-start timestamp))
22562 (defun org-timestamp-format (timestamp format &optional end utc)
22563 "Format a TIMESTAMP element into a string.
22565 FORMAT is a format specifier to be passed to
22566 `format-time-string'.
22568 When optional argument END is non-nil, use end of date-range or
22569 time-range, if possible.
22571 When optional argument UTC is non-nil, time will be expressed as
22572 Universal Time."
22573 (format-time-string
22574 format
22575 (apply 'encode-time
22576 (cons 0
22577 (mapcar
22578 (lambda (prop) (or (org-element-property prop timestamp) 0))
22579 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22580 '(:minute-start :hour-start :day-start :month-start
22581 :year-start)))))
22582 utc))
22584 (defun org-timestamp-split-range (timestamp &optional end)
22585 "Extract a timestamp object from a date or time range.
22587 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22588 the end of the range. Otherwise, extract its start.
22590 Return a new timestamp object sharing the same parent as
22591 TIMESTAMP."
22592 (let ((type (org-element-property :type timestamp)))
22593 (if (memq type '(active inactive diary)) timestamp
22594 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22595 ;; Set new type.
22596 (org-element-put-property
22597 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22598 ;; Copy start properties over end properties if END is
22599 ;; non-nil. Otherwise, copy end properties over `start' ones.
22600 (let ((p-alist '((:minute-start . :minute-end)
22601 (:hour-start . :hour-end)
22602 (:day-start . :day-end)
22603 (:month-start . :month-end)
22604 (:year-start . :year-end))))
22605 (dolist (p-cell p-alist)
22606 (org-element-put-property
22607 split-ts
22608 (funcall (if end 'car 'cdr) p-cell)
22609 (org-element-property
22610 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22611 ;; Eventually refresh `:raw-value'.
22612 (org-element-put-property split-ts :raw-value nil)
22613 (org-element-put-property
22614 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22616 (defun org-timestamp-translate (timestamp &optional boundary)
22617 "Apply `org-translate-time' on a TIMESTAMP object.
22618 When optional argument BOUNDARY is non-nil, it is either the
22619 symbol `start' or `end'. In this case, only translate the
22620 starting or ending part of TIMESTAMP if it is a date or time
22621 range. Otherwise, translate both parts."
22622 (if (and (not boundary)
22623 (memq (org-element-property :type timestamp)
22624 '(active-range inactive-range)))
22625 (concat
22626 (org-translate-time
22627 (org-element-property :raw-value
22628 (org-timestamp-split-range timestamp)))
22629 "--"
22630 (org-translate-time
22631 (org-element-property :raw-value
22632 (org-timestamp-split-range timestamp t))))
22633 (org-translate-time
22634 (org-element-property
22635 :raw-value
22636 (if (not boundary) timestamp
22637 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22641 ;;; Other stuff.
22643 (defun org-toggle-fixed-width-section (arg)
22644 "Toggle the fixed-width export.
22645 If there is no active region, the QUOTE keyword at the current headline is
22646 inserted or removed. When present, it causes the text between this headline
22647 and the next to be exported as fixed-width text, and unmodified.
22648 If there is an active region, this command adds or removes a colon as the
22649 first character of this line. If the first character of a line is a colon,
22650 this line is also exported in fixed-width font."
22651 (interactive "P")
22652 (let* ((cc 0)
22653 (regionp (org-region-active-p))
22654 (beg (if regionp (region-beginning) (point)))
22655 (end (if regionp (region-end)))
22656 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22657 (case-fold-search nil)
22658 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22659 off)
22660 (if regionp
22661 (save-excursion
22662 (goto-char beg)
22663 (setq cc (current-column))
22664 (beginning-of-line 1)
22665 (setq off (looking-at re))
22666 (while (> nlines 0)
22667 (setq nlines (1- nlines))
22668 (beginning-of-line 1)
22669 (cond
22670 (arg
22671 (org-move-to-column cc t)
22672 (insert ": \n")
22673 (forward-line -1))
22674 ((and off (looking-at re))
22675 (replace-match "" t t nil 1))
22676 ((not off) (org-move-to-column cc t) (insert ": ")))
22677 (forward-line 1)))
22678 (save-excursion
22679 (org-back-to-heading)
22680 (cond
22681 ((looking-at (format org-heading-keyword-regexp-format
22682 org-quote-string))
22683 (goto-char (match-end 1))
22684 (looking-at (concat " +" org-quote-string))
22685 (replace-match "" t t)
22686 (when (eolp) (insert " ")))
22687 ((looking-at org-outline-regexp)
22688 (goto-char (match-end 0))
22689 (insert org-quote-string " ")))))))
22691 (defun org-reftex-citation ()
22692 "Use reftex-citation to insert a citation into the buffer.
22693 This looks for a line like
22695 #+BIBLIOGRAPHY: foo plain option:-d
22697 and derives from it that foo.bib is the bibliography file relevant
22698 for this document. It then installs the necessary environment for RefTeX
22699 to work in this buffer and calls `reftex-citation' to insert a citation
22700 into the buffer.
22702 Export of such citations to both LaTeX and HTML is handled by the contributed
22703 package ox-bibtex by Taru Karttunen."
22704 (interactive)
22705 (let ((reftex-docstruct-symbol 'rds)
22706 (reftex-cite-format "\\cite{%l}")
22707 rds bib)
22708 (save-excursion
22709 (save-restriction
22710 (widen)
22711 (let ((case-fold-search t)
22712 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22713 (if (not (save-excursion
22714 (or (re-search-forward re nil t)
22715 (re-search-backward re nil t))))
22716 (error "No bibliography defined in file")
22717 (setq bib (concat (match-string 1) ".bib")
22718 rds (list (list 'bib bib)))))))
22719 (call-interactively 'reftex-citation)))
22721 ;;;; Functions extending outline functionality
22723 (defun org-beginning-of-line (&optional arg)
22724 "Go to the beginning of the current line. If that is invisible, continue
22725 to a visible line beginning. This makes the function of C-a more intuitive.
22726 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22727 first attempt, and only move to after the tags when the cursor is already
22728 beyond the end of the headline."
22729 (interactive "P")
22730 (let ((pos (point))
22731 (special (if (consp org-special-ctrl-a/e)
22732 (car org-special-ctrl-a/e)
22733 org-special-ctrl-a/e))
22734 deactivate-mark refpos)
22735 (if (org-bound-and-true-p visual-line-mode)
22736 (beginning-of-visual-line 1)
22737 (beginning-of-line 1))
22738 (if (and arg (fboundp 'move-beginning-of-line))
22739 (call-interactively 'move-beginning-of-line)
22740 (if (bobp)
22742 (backward-char 1)
22743 (if (org-truely-invisible-p)
22744 (while (and (not (bobp)) (org-truely-invisible-p))
22745 (backward-char 1)
22746 (beginning-of-line 1))
22747 (forward-char 1))))
22748 (when special
22749 (cond
22750 ((and (looking-at org-complex-heading-regexp)
22751 (= (char-after (match-end 1)) ?\ ))
22752 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22753 (point-at-eol)))
22754 (goto-char
22755 (if (eq special t)
22756 (cond ((> pos refpos) refpos)
22757 ((= pos (point)) refpos)
22758 (t (point)))
22759 (cond ((> pos (point)) (point))
22760 ((not (eq last-command this-command)) (point))
22761 (t refpos)))))
22762 ((org-at-item-p)
22763 ;; Being at an item and not looking at an the item means point
22764 ;; was previously moved to beginning of a visual line, which
22765 ;; doesn't contain the item. Therefore, do nothing special,
22766 ;; just stay here.
22767 (when (looking-at org-list-full-item-re)
22768 ;; Set special position at first white space character after
22769 ;; bullet, and check-box, if any.
22770 (let ((after-bullet
22771 (let ((box (match-end 3)))
22772 (if (not box) (match-end 1)
22773 (let ((after (char-after box)))
22774 (if (and after (= after ? )) (1+ box) box))))))
22775 ;; Special case: Move point to special position when
22776 ;; currently after it or at beginning of line.
22777 (if (eq special t)
22778 (when (or (> pos after-bullet) (= (point) pos))
22779 (goto-char after-bullet))
22780 ;; Reversed case: Move point to special position when
22781 ;; point was already at beginning of line and command is
22782 ;; repeated.
22783 (when (and (= (point) pos) (eq last-command this-command))
22784 (goto-char after-bullet))))))))
22785 (org-no-warnings
22786 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22787 (setq disable-point-adjustment
22788 (or (not (invisible-p (point)))
22789 (not (invisible-p (max (point-min) (1- (point))))))))
22791 (defun org-end-of-line (&optional arg)
22792 "Go to the end of the line.
22793 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22794 tags on the first attempt, and only move to after the tags when
22795 the cursor is already beyond the end of the headline."
22796 (interactive "P")
22797 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22798 org-special-ctrl-a/e))
22799 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22800 'end-of-visual-line)
22801 ((fboundp 'move-end-of-line) 'move-end-of-line)
22802 (t 'end-of-line)))
22803 deactivate-mark)
22804 (if (or (not special) arg) (call-interactively move-fun)
22805 (let* ((element (save-excursion (beginning-of-line)
22806 (org-element-at-point)))
22807 (type (org-element-type element)))
22808 (cond
22809 ((memq type '(headline inlinetask))
22810 (let ((pos (point)))
22811 (beginning-of-line 1)
22812 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22813 (if (eq special t)
22814 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22815 (goto-char (match-beginning 1))
22816 (goto-char (match-end 0)))
22817 (if (or (< pos (match-end 0))
22818 (not (eq this-command last-command)))
22819 (goto-char (match-end 0))
22820 (goto-char (match-beginning 1))))
22821 (call-interactively move-fun))))
22822 ((outline-invisible-p (line-end-position))
22823 ;; If element is hidden, `move-end-of-line' would put point
22824 ;; after it. Use `end-of-line' to stay on current line.
22825 (call-interactively 'end-of-line))
22826 (t (call-interactively move-fun)))))
22827 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22828 (setq disable-point-adjustment
22829 (or (not (invisible-p (point)))
22830 (not (invisible-p (max (point-min) (1- (point))))))))
22832 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22833 (define-key org-mode-map "\C-e" 'org-end-of-line)
22835 (defun org-backward-sentence (&optional arg)
22836 "Go to beginning of sentence, or beginning of table field.
22837 This will call `backward-sentence' or `org-table-beginning-of-field',
22838 depending on context."
22839 (interactive "P")
22840 (cond
22841 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22842 (t (call-interactively 'backward-sentence))))
22844 (defun org-forward-sentence (&optional arg)
22845 "Go to end of sentence, or end of table field.
22846 This will call `forward-sentence' or `org-table-end-of-field',
22847 depending on context."
22848 (interactive "P")
22849 (cond
22850 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22851 (t (call-interactively 'forward-sentence))))
22853 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22854 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22856 (defun org-kill-line (&optional arg)
22857 "Kill line, to tags or end of line."
22858 (interactive "P")
22859 (cond
22860 ((or (not org-special-ctrl-k)
22861 (bolp)
22862 (not (org-at-heading-p)))
22863 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22864 org-ctrl-k-protect-subtree)
22865 (if (or (eq org-ctrl-k-protect-subtree 'error)
22866 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22867 (user-error "C-k aborted as it would kill a hidden subtree")))
22868 (call-interactively
22869 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22870 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22871 (kill-region (point) (match-beginning 1))
22872 (org-set-tags nil t))
22873 (t (kill-region (point) (point-at-eol)))))
22875 (define-key org-mode-map "\C-k" 'org-kill-line)
22877 (defun org-yank (&optional arg)
22878 "Yank. If the kill is a subtree, treat it specially.
22879 This command will look at the current kill and check if is a single
22880 subtree, or a series of subtrees[1]. If it passes the test, and if the
22881 cursor is at the beginning of a line or after the stars of a currently
22882 empty headline, then the yank is handled specially. How exactly depends
22883 on the value of the following variables, both set by default.
22885 org-yank-folded-subtrees
22886 When set, the subtree(s) will be folded after insertion, but only
22887 if doing so would now swallow text after the yanked text.
22889 org-yank-adjusted-subtrees
22890 When set, the subtree will be promoted or demoted in order to
22891 fit into the local outline tree structure, which means that the level
22892 will be adjusted so that it becomes the smaller one of the two
22893 *visible* surrounding headings.
22895 Any prefix to this command will cause `yank' to be called directly with
22896 no special treatment. In particular, a simple \\[universal-argument] prefix \
22897 will just
22898 plainly yank the text as it is.
22900 \[1] The test checks if the first non-white line is a heading
22901 and if there are no other headings with fewer stars."
22902 (interactive "P")
22903 (org-yank-generic 'yank arg))
22905 (defun org-yank-generic (command arg)
22906 "Perform some yank-like command.
22908 This function implements the behavior described in the `org-yank'
22909 documentation. However, it has been generalized to work for any
22910 interactive command with similar behavior."
22912 ;; pretend to be command COMMAND
22913 (setq this-command command)
22915 (if arg
22916 (call-interactively command)
22918 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22919 (and (org-kill-is-subtree-p)
22920 (or (bolp)
22921 (and (looking-at "[ \t]*$")
22922 (string-match
22923 "\\`\\*+\\'"
22924 (buffer-substring (point-at-bol) (point)))))))
22925 swallowp)
22926 (cond
22927 ((and subtreep org-yank-folded-subtrees)
22928 (let ((beg (point))
22929 end)
22930 (if (and subtreep org-yank-adjusted-subtrees)
22931 (org-paste-subtree nil nil 'for-yank)
22932 (call-interactively command))
22934 (setq end (point))
22935 (goto-char beg)
22936 (when (and (bolp) subtreep
22937 (not (setq swallowp
22938 (org-yank-folding-would-swallow-text beg end))))
22939 (org-with-limited-levels
22940 (or (looking-at org-outline-regexp)
22941 (re-search-forward org-outline-regexp-bol end t))
22942 (while (and (< (point) end) (looking-at org-outline-regexp))
22943 (hide-subtree)
22944 (org-cycle-show-empty-lines 'folded)
22945 (condition-case nil
22946 (outline-forward-same-level 1)
22947 (error (goto-char end))))))
22948 (when swallowp
22949 (message
22950 "Inserted text not folded because that would swallow text"))
22952 (goto-char end)
22953 (skip-chars-forward " \t\n\r")
22954 (beginning-of-line 1)
22955 (push-mark beg 'nomsg)))
22956 ((and subtreep org-yank-adjusted-subtrees)
22957 (let ((beg (point-at-bol)))
22958 (org-paste-subtree nil nil 'for-yank)
22959 (push-mark beg 'nomsg)))
22961 (call-interactively command))))))
22963 (defun org-yank-folding-would-swallow-text (beg end)
22964 "Would hide-subtree at BEG swallow any text after END?"
22965 (let (level)
22966 (org-with-limited-levels
22967 (save-excursion
22968 (goto-char beg)
22969 (when (or (looking-at org-outline-regexp)
22970 (re-search-forward org-outline-regexp-bol end t))
22971 (setq level (org-outline-level)))
22972 (goto-char end)
22973 (skip-chars-forward " \t\r\n\v\f")
22974 (if (or (eobp)
22975 (and (bolp) (looking-at org-outline-regexp)
22976 (<= (org-outline-level) level)))
22977 nil ; Nothing would be swallowed
22978 t))))) ; something would swallow
22980 (define-key org-mode-map "\C-y" 'org-yank)
22982 (defun org-truely-invisible-p ()
22983 "Check if point is at a character currently not visible.
22984 This version does not only check the character property, but also
22985 `visible-mode'."
22986 ;; Early versions of noutline don't have `outline-invisible-p'.
22987 (if (org-bound-and-true-p visible-mode)
22989 (outline-invisible-p)))
22991 (defun org-invisible-p2 ()
22992 "Check if point is at a character currently not visible."
22993 (save-excursion
22994 (if (and (eolp) (not (bobp))) (backward-char 1))
22995 ;; Early versions of noutline don't have `outline-invisible-p'.
22996 (outline-invisible-p)))
22998 (defun org-back-to-heading (&optional invisible-ok)
22999 "Call `outline-back-to-heading', but provide a better error message."
23000 (condition-case nil
23001 (outline-back-to-heading invisible-ok)
23002 (error (error "Before first headline at position %d in buffer %s"
23003 (point) (current-buffer)))))
23005 (defun org-before-first-heading-p ()
23006 "Before first heading?"
23007 (save-excursion
23008 (end-of-line)
23009 (null (re-search-backward org-outline-regexp-bol nil t))))
23011 (defun org-at-heading-p (&optional ignored)
23012 (outline-on-heading-p t))
23013 ;; Compatibility alias with Org versions < 7.8.03
23014 (defalias 'org-on-heading-p 'org-at-heading-p)
23016 (defun org-at-comment-p nil
23017 "Is cursor in a line starting with a # character?"
23018 (save-excursion
23019 (beginning-of-line)
23020 (looking-at "^#")))
23022 (defun org-at-drawer-p nil
23023 "Is cursor at a drawer keyword?"
23024 (save-excursion
23025 (move-beginning-of-line 1)
23026 (looking-at org-drawer-regexp)))
23028 (defun org-at-block-p nil
23029 "Is cursor at a block keyword?"
23030 (save-excursion
23031 (move-beginning-of-line 1)
23032 (looking-at org-block-regexp)))
23034 (defun org-point-at-end-of-empty-headline ()
23035 "If point is at the end of an empty headline, return t, else nil.
23036 If the heading only contains a TODO keyword, it is still still considered
23037 empty."
23038 (and (looking-at "[ \t]*$")
23039 (when org-todo-line-regexp
23040 (save-excursion
23041 (beginning-of-line 1)
23042 (let ((case-fold-search nil))
23043 (looking-at org-todo-line-regexp)
23044 (string= (match-string 3) ""))))))
23046 (defun org-at-heading-or-item-p ()
23047 (or (org-at-heading-p) (org-at-item-p)))
23049 (defun org-at-target-p ()
23050 (or (org-in-regexp org-radio-target-regexp)
23051 (org-in-regexp org-target-regexp)))
23052 ;; Compatibility alias with Org versions < 7.8.03
23053 (defalias 'org-on-target-p 'org-at-target-p)
23055 (defun org-up-heading-all (arg)
23056 "Move to the heading line of which the present line is a subheading.
23057 This function considers both visible and invisible heading lines.
23058 With argument, move up ARG levels."
23059 (if (fboundp 'outline-up-heading-all)
23060 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23061 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23063 (defun org-up-heading-safe ()
23064 "Move to the heading line of which the present line is a subheading.
23065 This version will not throw an error. It will return the level of the
23066 headline found, or nil if no higher level is found.
23068 Also, this function will be a lot faster than `outline-up-heading',
23069 because it relies on stars being the outline starters. This can really
23070 make a significant difference in outlines with very many siblings."
23071 (let (start-level re)
23072 (org-back-to-heading t)
23073 (setq start-level (funcall outline-level))
23074 (if (equal start-level 1)
23076 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23077 (if (re-search-backward re nil t)
23078 (funcall outline-level)))))
23080 (defun org-first-sibling-p ()
23081 "Is this heading the first child of its parents?"
23082 (interactive)
23083 (let ((re org-outline-regexp-bol)
23084 level l)
23085 (unless (org-at-heading-p t)
23086 (user-error "Not at a heading"))
23087 (setq level (funcall outline-level))
23088 (save-excursion
23089 (if (not (re-search-backward re nil t))
23091 (setq l (funcall outline-level))
23092 (< l level)))))
23094 (defun org-goto-sibling (&optional previous)
23095 "Goto the next sibling, even if it is invisible.
23096 When PREVIOUS is set, go to the previous sibling instead. Returns t
23097 when a sibling was found. When none is found, return nil and don't
23098 move point."
23099 (let ((fun (if previous 're-search-backward 're-search-forward))
23100 (pos (point))
23101 (re org-outline-regexp-bol)
23102 level l)
23103 (when (condition-case nil (org-back-to-heading t) (error nil))
23104 (setq level (funcall outline-level))
23105 (catch 'exit
23106 (or previous (forward-char 1))
23107 (while (funcall fun re nil t)
23108 (setq l (funcall outline-level))
23109 (when (< l level) (goto-char pos) (throw 'exit nil))
23110 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23111 (goto-char pos)
23112 nil))))
23114 (defun org-show-siblings ()
23115 "Show all siblings of the current headline."
23116 (save-excursion
23117 (while (org-goto-sibling) (org-flag-heading nil)))
23118 (save-excursion
23119 (while (org-goto-sibling 'previous)
23120 (org-flag-heading nil))))
23122 (defun org-goto-first-child ()
23123 "Goto the first child, even if it is invisible.
23124 Return t when a child was found. Otherwise don't move point and
23125 return nil."
23126 (let (level (pos (point)) (re org-outline-regexp-bol))
23127 (when (condition-case nil (org-back-to-heading t) (error nil))
23128 (setq level (outline-level))
23129 (forward-char 1)
23130 (if (and (re-search-forward re nil t) (> (outline-level) level))
23131 (progn (goto-char (match-beginning 0)) t)
23132 (goto-char pos) nil))))
23134 (defun org-show-hidden-entry ()
23135 "Show an entry where even the heading is hidden."
23136 (save-excursion
23137 (org-show-entry)))
23139 (defun org-flag-heading (flag &optional entry)
23140 "Flag the current heading. FLAG non-nil means make invisible.
23141 When ENTRY is non-nil, show the entire entry."
23142 (save-excursion
23143 (org-back-to-heading t)
23144 ;; Check if we should show the entire entry
23145 (if entry
23146 (progn
23147 (org-show-entry)
23148 (save-excursion
23149 (and (outline-next-heading)
23150 (org-flag-heading nil))))
23151 (outline-flag-region (max (point-min) (1- (point)))
23152 (save-excursion (outline-end-of-heading) (point))
23153 flag))))
23155 (defun org-get-next-sibling ()
23156 "Move to next heading of the same level, and return point.
23157 If there is no such heading, return nil.
23158 This is like outline-next-sibling, but invisible headings are ok."
23159 (let ((level (funcall outline-level)))
23160 (outline-next-heading)
23161 (while (and (not (eobp)) (> (funcall outline-level) level))
23162 (outline-next-heading))
23163 (if (or (eobp) (< (funcall outline-level) level))
23165 (point))))
23167 (defun org-get-last-sibling ()
23168 "Move to previous heading of the same level, and return point.
23169 If there is no such heading, return nil."
23170 (let ((opoint (point))
23171 (level (funcall outline-level)))
23172 (outline-previous-heading)
23173 (when (and (/= (point) opoint) (outline-on-heading-p t))
23174 (while (and (> (funcall outline-level) level)
23175 (not (bobp)))
23176 (outline-previous-heading))
23177 (if (< (funcall outline-level) level)
23179 (point)))))
23181 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23182 "Goto to the end of a subtree."
23183 ;; This contains an exact copy of the original function, but it uses
23184 ;; `org-back-to-heading', to make it work also in invisible
23185 ;; trees. And is uses an invisible-ok argument.
23186 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23187 ;; Furthermore, when used inside Org, finding the end of a large subtree
23188 ;; with many children and grandchildren etc, this can be much faster
23189 ;; than the outline version.
23190 (org-back-to-heading invisible-ok)
23191 (let ((first t)
23192 (level (funcall outline-level)))
23193 (if (and (derived-mode-p 'org-mode) (< level 1000))
23194 ;; A true heading (not a plain list item), in Org-mode
23195 ;; This means we can easily find the end by looking
23196 ;; only for the right number of stars. Using a regexp to do
23197 ;; this is so much faster than using a Lisp loop.
23198 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23199 (forward-char 1)
23200 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23201 ;; something else, do it the slow way
23202 (while (and (not (eobp))
23203 (or first (> (funcall outline-level) level)))
23204 (setq first nil)
23205 (outline-next-heading)))
23206 (unless to-heading
23207 (if (memq (preceding-char) '(?\n ?\^M))
23208 (progn
23209 ;; Go to end of line before heading
23210 (forward-char -1)
23211 (if (memq (preceding-char) '(?\n ?\^M))
23212 ;; leave blank line before heading
23213 (forward-char -1))))))
23214 (point))
23216 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23217 "Use Org version in org-mode, for dramatic speed-up."
23218 (if (derived-mode-p 'org-mode)
23219 (progn
23220 (org-end-of-subtree nil t)
23221 (unless (eobp) (backward-char 1)))
23222 ad-do-it))
23224 (defun org-end-of-meta-data-and-drawers ()
23225 "Jump to the first text after meta data and drawers in the current entry.
23226 This will move over empty lines, lines with planning time stamps,
23227 clocking lines, and drawers."
23228 (org-back-to-heading t)
23229 (let ((end (save-excursion (outline-next-heading) (point)))
23230 (re (concat "\\(" org-drawer-regexp "\\)"
23231 "\\|" "[ \t]*" org-keyword-time-regexp)))
23232 (forward-line 1)
23233 (while (re-search-forward re end t)
23234 (if (not (match-end 1))
23235 ;; empty or planning line
23236 (forward-line 1)
23237 ;; a drawer, find the end
23238 (re-search-forward "^[ \t]*:END:" end 'move)
23239 (forward-line 1)))
23240 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23241 (point)))
23243 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23244 "Move forward to the ARG'th subheading at same level as this one.
23245 Stop at the first and last subheadings of a superior heading.
23246 Normally this only looks at visible headings, but when INVISIBLE-OK is
23247 non-nil it will also look at invisible ones."
23248 (interactive "p")
23249 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23250 (if (and arg (< arg 0))
23251 (goto-char (point-min))
23252 (outline-next-heading))
23253 (org-at-heading-p)
23254 (let ((level (- (match-end 0) (match-beginning 0) 1))
23255 (f (if (and arg (< arg 0))
23256 're-search-backward
23257 're-search-forward))
23258 (count (if arg (abs arg) 1))
23259 (result (point)))
23260 (while (and (prog1 (> count 0)
23261 (forward-char (if (and arg (< arg 0)) -1 1)))
23262 (funcall f org-outline-regexp-bol nil 'move))
23263 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23264 (cond ((< l level) (setq count 0))
23265 ((and (= l level)
23266 (or invisible-ok
23267 (progn
23268 (goto-char (line-beginning-position))
23269 (not (outline-invisible-p)))))
23270 (setq count (1- count))
23271 (when (eq l level)
23272 (setq result (point)))))))
23273 (goto-char result))
23274 (beginning-of-line 1)))
23276 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23277 "Move backward to the ARG'th subheading at same level as this one.
23278 Stop at the first and last subheadings of a superior heading."
23279 (interactive "p")
23280 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23282 (defun org-next-block (arg &optional backward block-regexp)
23283 "Jump to the next block.
23284 With a prefix argument ARG, jump forward ARG many source blocks.
23285 When BACKWARD is non-nil, jump to the previous block.
23286 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23287 (interactive "p")
23288 (let ((re (or block-regexp org-block-regexp))
23289 (re-search-fn (or (and backward 're-search-backward)
23290 're-search-forward)))
23291 (if (looking-at re) (forward-char 1))
23292 (condition-case nil
23293 (funcall re-search-fn re nil nil arg)
23294 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23295 (goto-char (match-beginning 0)) (org-show-context)))
23297 (defun org-previous-block (arg &optional block-regexp)
23298 "Jump to the previous block.
23299 With a prefix argument ARG, jump backward ARG many source blocks.
23300 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23301 (interactive "p")
23302 (org-next-block arg t block-regexp))
23304 (defun org-forward-paragraph ()
23305 "Move forward to beginning of next paragraph or equivalent.
23307 The function moves point to the beginning of the next visible
23308 structural element, which can be a paragraph, a table, a list
23309 item, etc. It also provides some special moves for convenience:
23311 - On an affiliated keyword, jump to the beginning of the
23312 relative element.
23313 - On an item or a footnote definition, move to the second
23314 element inside, if any.
23315 - On a table or a property drawer, jump after it.
23316 - On a verse or source block, stop after blank lines."
23317 (interactive)
23318 (when (eobp) (user-error "Cannot move further down"))
23319 (let* ((deactivate-mark nil)
23320 (element (org-element-at-point))
23321 (type (org-element-type element))
23322 (post-affiliated (org-element-property :post-affiliated element))
23323 (contents-begin (org-element-property :contents-begin element))
23324 (contents-end (org-element-property :contents-end element))
23325 (end (let ((end (org-element-property :end element)) (parent element))
23326 (while (and (setq parent (org-element-property :parent parent))
23327 (= (org-element-property :contents-end parent) end))
23328 (setq end (org-element-property :end parent)))
23329 end)))
23330 (cond ((not element)
23331 (skip-chars-forward " \r\t\n")
23332 (or (eobp) (beginning-of-line)))
23333 ;; On affiliated keywords, move to element's beginning.
23334 ((and post-affiliated (< (point) post-affiliated))
23335 (goto-char post-affiliated))
23336 ;; At a table row, move to the end of the table. Similarly,
23337 ;; at a node property, move to the end of the property
23338 ;; drawer.
23339 ((memq type '(node-property table-row))
23340 (goto-char (org-element-property
23341 :end (org-element-property :parent element))))
23342 ((memq type '(property-drawer table)) (goto-char end))
23343 ;; Consider blank lines as separators in verse and source
23344 ;; blocks to ease editing.
23345 ((memq type '(src-block verse-block))
23346 (when (eq type 'src-block)
23347 (setq contents-end
23348 (save-excursion (goto-char end)
23349 (skip-chars-backward " \r\t\n")
23350 (line-beginning-position))))
23351 (beginning-of-line)
23352 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23353 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23354 (goto-char end)
23355 (skip-chars-forward " \r\t\n")
23356 (if (= (point) contents-end) (goto-char end)
23357 (beginning-of-line))))
23358 ;; With no contents, just skip element.
23359 ((not contents-begin) (goto-char end))
23360 ;; If contents are invisible, skip the element altogether.
23361 ((outline-invisible-p (line-end-position))
23362 (case type
23363 (headline
23364 (org-with-limited-levels (outline-next-visible-heading 1)))
23365 ;; At a plain list, make sure we move to the next item
23366 ;; instead of skipping the whole list.
23367 (plain-list (forward-char)
23368 (org-forward-paragraph))
23369 (otherwise (goto-char end))))
23370 ((>= (point) contents-end) (goto-char end))
23371 ((>= (point) contents-begin)
23372 ;; This can only happen on paragraphs and plain lists.
23373 (case type
23374 (paragraph (goto-char end))
23375 ;; At a plain list, try to move to second element in
23376 ;; first item, if possible.
23377 (plain-list (end-of-line)
23378 (org-forward-paragraph))))
23379 ;; When contents start on the middle of a line (e.g. in
23380 ;; items and footnote definitions), try to reach first
23381 ;; element starting after current line.
23382 ((> (line-end-position) contents-begin)
23383 (end-of-line)
23384 (org-forward-paragraph))
23385 (t (goto-char contents-begin)))))
23387 (defun org-backward-paragraph ()
23388 "Move backward to start of previous paragraph or equivalent.
23390 The function moves point to the beginning of the current
23391 structural element, which can be a paragraph, a table, a list
23392 item, etc., or to the beginning of the previous visible one if
23393 point is already there. It also provides some special moves for
23394 convenience:
23396 - On an affiliated keyword, jump to the first one.
23397 - On a table or a property drawer, move to its beginning.
23398 - On a verse or source block, stop before blank lines."
23399 (interactive)
23400 (when (bobp) (user-error "Cannot move further up"))
23401 (let* ((deactivate-mark nil)
23402 (element (org-element-at-point))
23403 (type (org-element-type element))
23404 (contents-begin (org-element-property :contents-begin element))
23405 (contents-end (org-element-property :contents-end element))
23406 (post-affiliated (org-element-property :post-affiliated element))
23407 (begin (org-element-property :begin element)))
23408 (cond
23409 ((not element) (goto-char (point-min)))
23410 ((= (point) begin)
23411 (backward-char)
23412 (org-backward-paragraph))
23413 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23414 ((memq type '(node-property table-row))
23415 (goto-char (org-element-property
23416 :post-affiliated (org-element-property :parent element))))
23417 ((memq type '(property-drawer table)) (goto-char begin))
23418 ((memq type '(src-block verse-block))
23419 (when (eq type 'src-block)
23420 (setq contents-begin
23421 (save-excursion (goto-char begin) (forward-line) (point))))
23422 (if (= (point) contents-begin) (goto-char post-affiliated)
23423 ;; Inside a verse block, see blank lines as paragraph
23424 ;; separators.
23425 (let ((origin (point)))
23426 (skip-chars-backward " \r\t\n" contents-begin)
23427 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23428 (skip-chars-forward " \r\t\n" origin)
23429 (if (= (point) origin) (goto-char contents-begin)
23430 (beginning-of-line))))))
23431 ((not contents-begin) (goto-char (or post-affiliated begin)))
23432 ((eq type 'paragraph)
23433 (goto-char contents-begin)
23434 ;; When at first paragraph in an item or a footnote definition,
23435 ;; move directly to beginning of line.
23436 (let ((parent-contents
23437 (org-element-property
23438 :contents-begin (org-element-property :parent element))))
23439 (when (and parent-contents (= parent-contents contents-begin))
23440 (beginning-of-line))))
23441 ;; At the end of a greater element, move to the beginning of the
23442 ;; last element within.
23443 ((>= (point) contents-end)
23444 (goto-char (1- contents-end))
23445 (org-backward-paragraph))
23446 (t (goto-char (or post-affiliated begin))))
23447 ;; Ensure we never leave point invisible.
23448 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23450 (defun org-forward-element ()
23451 "Move forward by one element.
23452 Move to the next element at the same level, when possible."
23453 (interactive)
23454 (cond ((eobp) (user-error "Cannot move further down"))
23455 ((org-with-limited-levels (org-at-heading-p))
23456 (let ((origin (point)))
23457 (goto-char (org-end-of-subtree nil t))
23458 (unless (org-with-limited-levels (org-at-heading-p))
23459 (goto-char origin)
23460 (user-error "Cannot move further down"))))
23462 (let* ((elem (org-element-at-point))
23463 (end (org-element-property :end elem))
23464 (parent (org-element-property :parent elem)))
23465 (cond ((and parent (= (org-element-property :contents-end parent) end))
23466 (goto-char (org-element-property :end parent)))
23467 ((integer-or-marker-p end) (goto-char end))
23468 (t (message "No element at point")))))))
23470 (defun org-backward-element ()
23471 "Move backward by one element.
23472 Move to the previous element at the same level, when possible."
23473 (interactive)
23474 (cond ((bobp) (user-error "Cannot move further up"))
23475 ((org-with-limited-levels (org-at-heading-p))
23476 ;; At a headline, move to the previous one, if any, or stay
23477 ;; here.
23478 (let ((origin (point)))
23479 (org-with-limited-levels (org-backward-heading-same-level 1))
23480 ;; When current headline has no sibling above, move to its
23481 ;; parent.
23482 (when (= (point) origin)
23483 (or (org-with-limited-levels (org-up-heading-safe))
23484 (progn (goto-char origin)
23485 (user-error "Cannot move further up"))))))
23487 (let* ((trail (org-element-at-point 'keep-trail))
23488 (elem (car trail))
23489 (prev-elem (nth 1 trail))
23490 (beg (org-element-property :begin elem)))
23491 (cond
23492 ;; Move to beginning of current element if point isn't
23493 ;; there already.
23494 ((null beg) (message "No element at point"))
23495 ((/= (point) beg) (goto-char beg))
23496 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23497 ((org-before-first-heading-p) (goto-char (point-min)))
23498 (t (org-back-to-heading)))))))
23500 (defun org-up-element ()
23501 "Move to upper element."
23502 (interactive)
23503 (if (org-with-limited-levels (org-at-heading-p))
23504 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23505 (let* ((elem (org-element-at-point))
23506 (parent (org-element-property :parent elem)))
23507 (if parent (goto-char (org-element-property :begin parent))
23508 (if (org-with-limited-levels (org-before-first-heading-p))
23509 (user-error "No surrounding element")
23510 (org-with-limited-levels (org-back-to-heading)))))))
23512 (defvar org-element-greater-elements)
23513 (defun org-down-element ()
23514 "Move to inner element."
23515 (interactive)
23516 (let ((element (org-element-at-point)))
23517 (cond
23518 ((memq (org-element-type element) '(plain-list table))
23519 (goto-char (org-element-property :contents-begin element))
23520 (forward-char))
23521 ((memq (org-element-type element) org-element-greater-elements)
23522 ;; If contents are hidden, first disclose them.
23523 (when (outline-invisible-p (line-end-position)) (org-cycle))
23524 (goto-char (or (org-element-property :contents-begin element)
23525 (user-error "No content for this element"))))
23526 (t (user-error "No inner element")))))
23528 (defun org-drag-element-backward ()
23529 "Move backward element at point."
23530 (interactive)
23531 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23532 (let* ((trail (org-element-at-point 'keep-trail))
23533 (elem (car trail))
23534 (prev-elem (nth 1 trail)))
23535 ;; Error out if no previous element or previous element is
23536 ;; a parent of the current one.
23537 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23538 (user-error "Cannot drag element backward")
23539 (let ((pos (point)))
23540 (org-element-swap-A-B prev-elem elem)
23541 (goto-char (+ (org-element-property :begin prev-elem)
23542 (- pos (org-element-property :begin elem)))))))))
23544 (defun org-drag-element-forward ()
23545 "Move forward element at point."
23546 (interactive)
23547 (let* ((pos (point))
23548 (elem (org-element-at-point)))
23549 (when (= (point-max) (org-element-property :end elem))
23550 (user-error "Cannot drag element forward"))
23551 (goto-char (org-element-property :end elem))
23552 (let ((next-elem (org-element-at-point)))
23553 (when (or (org-element-nested-p elem next-elem)
23554 (and (eq (org-element-type next-elem) 'headline)
23555 (not (eq (org-element-type elem) 'headline))))
23556 (goto-char pos)
23557 (user-error "Cannot drag element forward"))
23558 ;; Compute new position of point: it's shifted by NEXT-ELEM
23559 ;; body's length (without final blanks) and by the length of
23560 ;; blanks between ELEM and NEXT-ELEM.
23561 (let ((size-next (- (save-excursion
23562 (goto-char (org-element-property :end next-elem))
23563 (skip-chars-backward " \r\t\n")
23564 (forward-line)
23565 ;; Small correction if buffer doesn't end
23566 ;; with a newline character.
23567 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23568 (org-element-property :begin next-elem)))
23569 (size-blank (- (org-element-property :end elem)
23570 (save-excursion
23571 (goto-char (org-element-property :end elem))
23572 (skip-chars-backward " \r\t\n")
23573 (forward-line)
23574 (point)))))
23575 (org-element-swap-A-B elem next-elem)
23576 (goto-char (+ pos size-next size-blank))))))
23578 (defun org-drag-line-forward (arg)
23579 "Drag the line at point ARG lines forward."
23580 (interactive "p")
23581 (dotimes (n (abs arg))
23582 (let ((c (current-column)))
23583 (if (< 0 arg)
23584 (progn
23585 (beginning-of-line 2)
23586 (transpose-lines 1)
23587 (beginning-of-line 0))
23588 (transpose-lines 1)
23589 (beginning-of-line -1))
23590 (org-move-to-column c))))
23592 (defun org-drag-line-backward (arg)
23593 "Drag the line at point ARG lines backward."
23594 (interactive "p")
23595 (org-drag-line-forward (- arg)))
23597 (defun org-mark-element ()
23598 "Put point at beginning of this element, mark at end.
23600 Interactively, if this command is repeated or (in Transient Mark
23601 mode) if the mark is active, it marks the next element after the
23602 ones already marked."
23603 (interactive)
23604 (let (deactivate-mark)
23605 (if (and (org-called-interactively-p 'any)
23606 (or (and (eq last-command this-command) (mark t))
23607 (and transient-mark-mode mark-active)))
23608 (set-mark
23609 (save-excursion
23610 (goto-char (mark))
23611 (goto-char (org-element-property :end (org-element-at-point)))))
23612 (let ((element (org-element-at-point)))
23613 (end-of-line)
23614 (push-mark (org-element-property :end element) t t)
23615 (goto-char (org-element-property :begin element))))))
23617 (defun org-narrow-to-element ()
23618 "Narrow buffer to current element."
23619 (interactive)
23620 (let ((elem (org-element-at-point)))
23621 (cond
23622 ((eq (car elem) 'headline)
23623 (narrow-to-region
23624 (org-element-property :begin elem)
23625 (org-element-property :end elem)))
23626 ((memq (car elem) org-element-greater-elements)
23627 (narrow-to-region
23628 (org-element-property :contents-begin elem)
23629 (org-element-property :contents-end elem)))
23631 (narrow-to-region
23632 (org-element-property :begin elem)
23633 (org-element-property :end elem))))))
23635 (defun org-transpose-element ()
23636 "Transpose current and previous elements, keeping blank lines between.
23637 Point is moved after both elements."
23638 (interactive)
23639 (org-skip-whitespace)
23640 (let ((end (org-element-property :end (org-element-at-point))))
23641 (org-drag-element-backward)
23642 (goto-char end)))
23644 (defun org-unindent-buffer ()
23645 "Un-indent the visible part of the buffer.
23646 Relative indentation (between items, inside blocks, etc.) isn't
23647 modified."
23648 (interactive)
23649 (unless (eq major-mode 'org-mode)
23650 (user-error "Cannot un-indent a buffer not in Org mode"))
23651 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23652 unindent-tree ; For byte-compiler.
23653 (unindent-tree
23654 (function
23655 (lambda (contents)
23656 (mapc
23657 (lambda (element)
23658 (if (memq (org-element-type element) '(headline section))
23659 (funcall unindent-tree (org-element-contents element))
23660 (save-excursion
23661 (save-restriction
23662 (narrow-to-region
23663 (org-element-property :begin element)
23664 (org-element-property :end element))
23665 (org-do-remove-indentation)))))
23666 (reverse contents))))))
23667 (funcall unindent-tree (org-element-contents parse-tree))))
23669 (defun org-show-subtree ()
23670 "Show everything after this heading at deeper levels."
23671 (interactive)
23672 (outline-flag-region
23673 (point)
23674 (save-excursion
23675 (org-end-of-subtree t t))
23676 nil))
23678 (defun org-show-entry ()
23679 "Show the body directly following this heading.
23680 Show the heading too, if it is currently invisible."
23681 (interactive)
23682 (save-excursion
23683 (condition-case nil
23684 (progn
23685 (org-back-to-heading t)
23686 (outline-flag-region
23687 (max (point-min) (1- (point)))
23688 (save-excursion
23689 (if (re-search-forward
23690 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23691 (match-beginning 1)
23692 (point-max)))
23693 nil)
23694 (org-cycle-hide-drawers 'children))
23695 (error nil))))
23697 (defun org-make-options-regexp (kwds &optional extra)
23698 "Make a regular expression for keyword lines."
23699 (concat
23700 "^#\\+\\("
23701 (mapconcat 'regexp-quote kwds "\\|")
23702 (if extra (concat "\\|" extra))
23703 "\\):[ \t]*\\(.*\\)"))
23705 ;; Make isearch reveal the necessary context
23706 (defun org-isearch-end ()
23707 "Reveal context after isearch exits."
23708 (when isearch-success ; only if search was successful
23709 (if (featurep 'xemacs)
23710 ;; Under XEmacs, the hook is run in the correct place,
23711 ;; we directly show the context.
23712 (org-show-context 'isearch)
23713 ;; In Emacs the hook runs *before* restoring the overlays.
23714 ;; So we have to use a one-time post-command-hook to do this.
23715 ;; (Emacs 22 has a special variable, see function `org-mode')
23716 (unless (and (boundp 'isearch-mode-end-hook-quit)
23717 isearch-mode-end-hook-quit)
23718 ;; Only when the isearch was not quitted.
23719 (org-add-hook 'post-command-hook 'org-isearch-post-command
23720 'append 'local)))
23721 (org-fix-ellipsis-at-bol)))
23723 (defun org-isearch-post-command ()
23724 "Remove self from hook, and show context."
23725 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23726 (org-show-context 'isearch))
23729 ;;;; Integration with and fixes for other packages
23731 ;;; Imenu support
23733 (defvar org-imenu-markers nil
23734 "All markers currently used by Imenu.")
23735 (make-variable-buffer-local 'org-imenu-markers)
23737 (defun org-imenu-new-marker (&optional pos)
23738 "Return a new marker for use by Imenu, and remember the marker."
23739 (let ((m (make-marker)))
23740 (move-marker m (or pos (point)))
23741 (push m org-imenu-markers)
23744 (defun org-imenu-get-tree ()
23745 "Produce the index for Imenu."
23746 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23747 (setq org-imenu-markers nil)
23748 (let* ((n org-imenu-depth)
23749 (re (concat "^" (org-get-limited-outline-regexp)))
23750 (subs (make-vector (1+ n) nil))
23751 (last-level 0)
23752 m level head0 head)
23753 (save-excursion
23754 (save-restriction
23755 (widen)
23756 (goto-char (point-max))
23757 (while (re-search-backward re nil t)
23758 (setq level (org-reduced-level (funcall outline-level)))
23759 (when (and (<= level n)
23760 (looking-at org-complex-heading-regexp)
23761 (setq head0 (org-match-string-no-properties 4)))
23762 (setq head (org-link-display-format head0)
23763 m (org-imenu-new-marker))
23764 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23765 (if (>= level last-level)
23766 (push (cons head m) (aref subs level))
23767 (push (cons head (aref subs (1+ level))) (aref subs level))
23768 (loop for i from (1+ level) to n do (aset subs i nil)))
23769 (setq last-level level)))))
23770 (aref subs 1)))
23772 (eval-after-load "imenu"
23773 '(progn
23774 (add-hook 'imenu-after-jump-hook
23775 (lambda ()
23776 (if (derived-mode-p 'org-mode)
23777 (org-show-context 'org-goto))))))
23779 (defun org-link-display-format (link)
23780 "Replace a link with its the description.
23781 If there is no description, use the link target."
23782 (save-match-data
23783 (if (string-match org-bracket-link-analytic-regexp link)
23784 (replace-match (if (match-end 5)
23785 (match-string 5 link)
23786 (concat (match-string 1 link)
23787 (match-string 3 link)))
23788 nil t link)
23789 link)))
23791 (defun org-toggle-link-display ()
23792 "Toggle the literal or descriptive display of links."
23793 (interactive)
23794 (if org-descriptive-links
23795 (progn (org-remove-from-invisibility-spec '(org-link))
23796 (org-restart-font-lock)
23797 (setq org-descriptive-links nil))
23798 (progn (add-to-invisibility-spec '(org-link))
23799 (org-restart-font-lock)
23800 (setq org-descriptive-links t))))
23802 ;; Speedbar support
23804 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23805 "Overlay marking the agenda restriction line in speedbar.")
23806 (overlay-put org-speedbar-restriction-lock-overlay
23807 'face 'org-agenda-restriction-lock)
23808 (overlay-put org-speedbar-restriction-lock-overlay
23809 'help-echo "Agendas are currently limited to this item.")
23810 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23812 (defun org-speedbar-set-agenda-restriction ()
23813 "Restrict future agenda commands to the location at point in speedbar.
23814 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23815 (interactive)
23816 (require 'org-agenda)
23817 (let (p m tp np dir txt)
23818 (cond
23819 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23820 'org-imenu t))
23821 (setq m (get-text-property p 'org-imenu-marker))
23822 (with-current-buffer (marker-buffer m)
23823 (goto-char m)
23824 (org-agenda-set-restriction-lock 'subtree)))
23825 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23826 'speedbar-function 'speedbar-find-file))
23827 (setq tp (previous-single-property-change
23828 (1+ p) 'speedbar-function)
23829 np (next-single-property-change
23830 tp 'speedbar-function)
23831 dir (speedbar-line-directory)
23832 txt (buffer-substring-no-properties (or tp (point-min))
23833 (or np (point-max))))
23834 (with-current-buffer (find-file-noselect
23835 (let ((default-directory dir))
23836 (expand-file-name txt)))
23837 (unless (derived-mode-p 'org-mode)
23838 (user-error "Cannot restrict to non-Org-mode file"))
23839 (org-agenda-set-restriction-lock 'file)))
23840 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23841 (move-overlay org-speedbar-restriction-lock-overlay
23842 (point-at-bol) (point-at-eol))
23843 (setq current-prefix-arg nil)
23844 (org-agenda-maybe-redo)))
23846 (defvar speedbar-file-key-map)
23847 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23848 (eval-after-load "speedbar"
23849 '(progn
23850 (speedbar-add-supported-extension ".org")
23851 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23852 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23853 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23854 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23855 (add-hook 'speedbar-visiting-tag-hook
23856 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23858 ;;; Fixes and Hacks for problems with other packages
23860 ;; Make flyspell not check words in links, to not mess up our keymap
23861 (defvar org-element-affiliated-keywords) ; From org-element.el
23862 (defvar org-element-block-name-alist) ; From org-element.el
23863 (defun org-mode-flyspell-verify ()
23864 "Don't let flyspell put overlays at active buttons, or on
23865 {todo,all-time,additional-option-like}-keywords."
23866 (require 'org-element) ; For `org-element-affiliated-keywords'
23867 (let ((pos (max (1- (point)) (point-min)))
23868 (word (thing-at-point 'word)))
23869 (and (not (get-text-property pos 'keymap))
23870 (not (get-text-property pos 'org-no-flyspell))
23871 (not (member word org-todo-keywords-1))
23872 (not (member word org-all-time-keywords))
23873 (not (member word org-options-keywords))
23874 (not (member word (mapcar 'car org-startup-options)))
23875 (not (member-ignore-case word org-element-affiliated-keywords))
23876 (not (member-ignore-case word (org-get-export-keywords)))
23877 (not (member-ignore-case
23878 word (mapcar 'car org-element-block-name-alist)))
23879 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23880 (not (org-in-src-block-p)))))
23882 (defun org-remove-flyspell-overlays-in (beg end)
23883 "Remove flyspell overlays in region."
23884 (and (org-bound-and-true-p flyspell-mode)
23885 (fboundp 'flyspell-delete-region-overlays)
23886 (flyspell-delete-region-overlays beg end))
23887 (add-text-properties beg end '(org-no-flyspell t)))
23889 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23890 (eval-after-load "bookmark"
23891 '(if (boundp 'bookmark-after-jump-hook)
23892 ;; We can use the hook
23893 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23894 ;; Hook not available, use advice
23895 (defadvice bookmark-jump (after org-make-visible activate)
23896 "Make the position visible."
23897 (org-bookmark-jump-unhide))))
23899 ;; Make sure saveplace shows the location if it was hidden
23900 (eval-after-load "saveplace"
23901 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23902 "Make the position visible."
23903 (org-bookmark-jump-unhide)))
23905 ;; Make sure ecb shows the location if it was hidden
23906 (eval-after-load "ecb"
23907 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23908 "Make hierarchy visible when jumping into location from ECB tree buffer."
23909 (if (derived-mode-p 'org-mode)
23910 (org-show-context))))
23912 (defun org-bookmark-jump-unhide ()
23913 "Unhide the current position, to show the bookmark location."
23914 (and (derived-mode-p 'org-mode)
23915 (or (outline-invisible-p)
23916 (save-excursion (goto-char (max (point-min) (1- (point))))
23917 (outline-invisible-p)))
23918 (org-show-context 'bookmark-jump)))
23920 ;; Make session.el ignore our circular variable
23921 (defvar session-globals-exclude)
23922 (eval-after-load "session"
23923 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23925 ;;;; Finish up
23927 (provide 'org)
23929 (run-hooks 'org-load-hook)
23931 ;;; org.el ends here