Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob4f3bf4b4aab8c45f3773367d1fd2e1ce52f12982
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-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defcustom org-bookmark-names-plist
1036 '(:last-capture "org-capture-last-stored"
1037 :last-refile "org-refile-last-stored"
1038 :last-capture-marker "org-capture-last-stored-marker")
1039 "Names for bookmarks automatically set by some Org commands.
1040 This can provide strings as names for a number of bookmakrs Org sets
1041 automatically. The following keys are currently implemented:
1042 :last-capture
1043 :last-capture-marker
1044 :last-refile
1045 When a key does not show up in the property list, the corresponding bookmark
1046 is not set."
1047 :group 'org-structure
1048 :type 'plist)
1050 (defgroup org-cycle nil
1051 "Options concerning visibility cycling in Org-mode."
1052 :tag "Org Cycle"
1053 :group 'org-structure)
1055 (defcustom org-cycle-skip-children-state-if-no-children t
1056 "Non-nil means skip CHILDREN state in entries that don't have any."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-max-level nil
1061 "Maximum level which should still be subject to visibility cycling.
1062 Levels higher than this will, for cycling, be treated as text, not a headline.
1063 When `org-odd-levels-only' is set, a value of N in this variable actually
1064 means 2N-1 stars as the limiting headline.
1065 When nil, cycle all levels.
1066 Note that the limiting level of cycling is also influenced by
1067 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1068 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1069 than its value."
1070 :group 'org-cycle
1071 :type '(choice
1072 (const :tag "No limit" nil)
1073 (integer :tag "Maximum level")))
1075 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1076 "Names of drawers. Drawers are not opened by cycling on the headline above.
1077 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1078 this:
1079 :DRAWERNAME:
1080 .....
1081 :END:
1082 The drawer \"PROPERTIES\" is special for capturing properties through
1083 the property API.
1085 Drawers can be defined on the per-file basis with a line like:
1087 #+DRAWERS: HIDDEN STATE PROPERTIES"
1088 :group 'org-structure
1089 :group 'org-cycle
1090 :type '(repeat (string :tag "Drawer Name")))
1092 (defcustom org-hide-block-startup nil
1093 "Non-nil means entering Org-mode will fold all blocks.
1094 This can also be set in on a per-file basis with
1096 #+STARTUP: hideblocks
1097 #+STARTUP: showblocks"
1098 :group 'org-startup
1099 :group 'org-cycle
1100 :type 'boolean)
1102 (defcustom org-cycle-global-at-bob nil
1103 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1104 This makes it possible to do global cycling without having to use S-TAB or
1105 \\[universal-argument] TAB. For this special case to work, the first line
1106 of the buffer must not be a headline -- it may be empty or some other text.
1107 When used in this way, `org-cycle-hook' is disabled temporarily to make
1108 sure the cursor stays at the beginning of the buffer. When this option is
1109 nil, don't do anything special at the beginning of the buffer."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-level-after-item/entry-creation t
1114 "Non-nil means cycle entry level or item indentation in new empty entries.
1116 When the cursor is at the end of an empty headline, i.e., with only stars
1117 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1118 and then all possible ancestor states, before returning to the original state.
1119 This makes data entry extremely fast: M-RET to create a new headline,
1120 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1122 When the cursor is at the end of an empty plain list item, one TAB will
1123 make it a subitem, two or more tabs will back up to make this an item
1124 higher up in the item hierarchy."
1125 :group 'org-cycle
1126 :type 'boolean)
1128 (defcustom org-cycle-emulate-tab t
1129 "Where should `org-cycle' emulate TAB.
1130 nil Never
1131 white Only in completely white lines
1132 whitestart Only at the beginning of lines, before the first non-white char
1133 t Everywhere except in headlines
1134 exc-hl-bol Everywhere except at the start of a headline
1135 If TAB is used in a place where it does not emulate TAB, the current subtree
1136 visibility is cycled."
1137 :group 'org-cycle
1138 :type '(choice (const :tag "Never" nil)
1139 (const :tag "Only in completely white lines" white)
1140 (const :tag "Before first char in a line" whitestart)
1141 (const :tag "Everywhere except in headlines" t)
1142 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1144 (defcustom org-cycle-separator-lines 2
1145 "Number of empty lines needed to keep an empty line between collapsed trees.
1146 If you leave an empty line between the end of a subtree and the following
1147 headline, this empty line is hidden when the subtree is folded.
1148 Org-mode will leave (exactly) one empty line visible if the number of
1149 empty lines is equal or larger to the number given in this variable.
1150 So the default 2 means at least 2 empty lines after the end of a subtree
1151 are needed to produce free space between a collapsed subtree and the
1152 following headline.
1154 If the number is negative, and the number of empty lines is at least -N,
1155 all empty lines are shown.
1157 Special case: when 0, never leave empty lines in collapsed view."
1158 :group 'org-cycle
1159 :type 'integer)
1160 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1162 (defcustom org-pre-cycle-hook nil
1163 "Hook that is run before visibility cycling is happening.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that will be set right after running this hook. The
1166 argument is a symbol. Before a global state change, it can have the values
1167 `overview', `content', or `all'. Before a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1173 org-cycle-hide-drawers
1174 org-cycle-hide-inline-tasks
1175 org-cycle-show-empty-lines
1176 org-optimize-window-after-visibility-change)
1177 "Hook that is run after `org-cycle' has changed the buffer visibility.
1178 The function(s) in this hook must accept a single argument which indicates
1179 the new state that was set by the most recent `org-cycle' command. The
1180 argument is a symbol. After a global state change, it can have the values
1181 `overview', `contents', or `all'. After a local state change, it can have
1182 the values `folded', `children', or `subtree'."
1183 :group 'org-cycle
1184 :type 'hook)
1186 (defgroup org-edit-structure nil
1187 "Options concerning structure editing in Org-mode."
1188 :tag "Org Edit Structure"
1189 :group 'org-structure)
1191 (defcustom org-odd-levels-only nil
1192 "Non-nil means skip even levels and only use odd levels for the outline.
1193 This has the effect that two stars are being added/taken away in
1194 promotion/demotion commands. It also influences how levels are
1195 handled by the exporters.
1196 Changing it requires restart of `font-lock-mode' to become effective
1197 for fontification also in regions already fontified.
1198 You may also set this on a per-file basis by adding one of the following
1199 lines to the buffer:
1201 #+STARTUP: odd
1202 #+STARTUP: oddeven"
1203 :group 'org-edit-structure
1204 :group 'org-appearance
1205 :type 'boolean)
1207 (defcustom org-adapt-indentation t
1208 "Non-nil means adapt indentation to outline node level.
1210 When this variable is set, Org assumes that you write outlines by
1211 indenting text in each node to align with the headline (after the stars).
1212 The following issues are influenced by this variable:
1214 - When this is set and the *entire* text in an entry is indented, the
1215 indentation is increased by one space in a demotion command, and
1216 decreased by one in a promotion command. If any line in the entry
1217 body starts with text at column 0, indentation is not changed at all.
1219 - Property drawers and planning information is inserted indented when
1220 this variable s set. When nil, they will not be indented.
1222 - TAB indents a line relative to context. The lines below a headline
1223 will be indented when this variable is set.
1225 Note that this is all about true indentation, by adding and removing
1226 space characters. See also `org-indent.el' which does level-dependent
1227 indentation in a virtual way, i.e. at display time in Emacs."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-special-ctrl-a/e nil
1232 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1234 When t, `C-a' will bring back the cursor to the beginning of the
1235 headline text, i.e. after the stars and after a possible TODO
1236 keyword. In an item, this will be the position after bullet and
1237 check-box, if any. When the cursor is already at that position,
1238 another `C-a' will bring it to the beginning of the line.
1240 `C-e' will jump to the end of the headline, ignoring the presence
1241 of tags in the headline. A second `C-e' will then jump to the
1242 true end of the line, after any tags. This also means that, when
1243 this variable is non-nil, `C-e' also will never jump beyond the
1244 end of the heading of a folded section, i.e. not after the
1245 ellipses.
1247 When set to the symbol `reversed', the first `C-a' or `C-e' works
1248 normally, going to the true line boundary first. Only a directly
1249 following, identical keypress will bring the cursor to the
1250 special positions.
1252 This may also be a cons cell where the behavior for `C-a' and
1253 `C-e' is set separately."
1254 :group 'org-edit-structure
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on: after stars/bullet and before tags first" t)
1258 (const :tag "reversed: true line boundary first" reversed)
1259 (cons :tag "Set C-a and C-e separately"
1260 (choice :tag "Special C-a"
1261 (const :tag "off" nil)
1262 (const :tag "on: after stars/bullet first" t)
1263 (const :tag "reversed: before stars/bullet first" reversed))
1264 (choice :tag "Special C-e"
1265 (const :tag "off" nil)
1266 (const :tag "on: before tags first" t)
1267 (const :tag "reversed: after tags first" reversed)))))
1268 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1270 (defcustom org-special-ctrl-k nil
1271 "Non-nil means `C-k' will behave specially in headlines.
1272 When nil, `C-k' will call the default `kill-line' command.
1273 When t, the following will happen while the cursor is in the headline:
1275 - When the cursor is at the beginning of a headline, kill the entire
1276 line and possible the folded subtree below the line.
1277 - When in the middle of the headline text, kill the headline up to the tags.
1278 - When after the headline text, kill the tags."
1279 :group 'org-edit-structure
1280 :type 'boolean)
1282 (defcustom org-ctrl-k-protect-subtree nil
1283 "Non-nil means, do not delete a hidden subtree with C-k.
1284 When set to the symbol `error', simply throw an error when C-k is
1285 used to kill (part-of) a headline that has hidden text behind it.
1286 Any other non-nil value will result in a query to the user, if it is
1287 OK to kill that hidden subtree. When nil, kill without remorse."
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not protect hidden subtrees" nil)
1292 (const :tag "Protect hidden subtrees with a security query" t)
1293 (const :tag "Never kill a hidden subtree with C-k" error)))
1295 (defcustom org-special-ctrl-o t
1296 "Non-nil means, make `C-o' insert a row in tables."
1297 :group 'org-edit-structure
1298 :type 'boolean)
1300 (defcustom org-catch-invisible-edits nil
1301 "Check if in invisible region before inserting or deleting a character.
1302 Valid values are:
1304 nil Do not check, so just do invisible edits.
1305 error Throw an error and do nothing.
1306 show Make point visible, and do the requested edit.
1307 show-and-error Make point visible, then throw an error and abort the edit.
1308 smart Make point visible, and do insertion/deletion if it is
1309 adjacent to visible text and the change feels predictable.
1310 Never delete a previously invisible character or add in the
1311 middle or right after an invisible region. Basically, this
1312 allows insertion and backward-delete right before ellipses.
1313 FIXME: maybe in this case we should not even show?"
1314 :group 'org-edit-structure
1315 :version "24.1"
1316 :type '(choice
1317 (const :tag "Do not check" nil)
1318 (const :tag "Throw error when trying to edit" error)
1319 (const :tag "Unhide, but do not do the edit" show-and-error)
1320 (const :tag "Show invisible part and do the edit" show)
1321 (const :tag "Be smart and do the right thing" smart)))
1323 (defcustom org-yank-folded-subtrees t
1324 "Non-nil means when yanking subtrees, fold them.
1325 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1326 it starts with a heading and all other headings in it are either children
1327 or siblings, then fold all the subtrees. However, do this only if no
1328 text after the yank would be swallowed into a folded tree by this action."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-yank-adjusted-subtrees nil
1333 "Non-nil means when yanking subtrees, adjust the level.
1334 With this setting, `org-paste-subtree' is used to insert the subtree, see
1335 this function for details."
1336 :group 'org-edit-structure
1337 :type 'boolean)
1339 (defcustom org-M-RET-may-split-line '((default . t))
1340 "Non-nil means M-RET will split the line at the cursor position.
1341 When nil, it will go to the end of the line before making a
1342 new line.
1343 You may also set this option in a different way for different
1344 contexts. Valid contexts are:
1346 headline when creating a new headline
1347 item when creating a new item
1348 table in a table field
1349 default the value to be used for all contexts not explicitly
1350 customized"
1351 :group 'org-structure
1352 :group 'org-table
1353 :type '(choice
1354 (const :tag "Always" t)
1355 (const :tag "Never" nil)
1356 (repeat :greedy t :tag "Individual contexts"
1357 (cons
1358 (choice :tag "Context"
1359 (const headline)
1360 (const item)
1361 (const table)
1362 (const default))
1363 (boolean)))))
1366 (defcustom org-insert-heading-respect-content nil
1367 "Non-nil means insert new headings after the current subtree.
1368 When nil, the new heading is created directly after the current line.
1369 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1370 this variable on for the duration of the command."
1371 :group 'org-structure
1372 :type 'boolean)
1374 (defcustom org-blank-before-new-entry '((heading . auto)
1375 (plain-list-item . auto))
1376 "Should `org-insert-heading' leave a blank line before new heading/item?
1377 The value is an alist, with `heading' and `plain-list-item' as CAR,
1378 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1379 which case Org will look at the surrounding headings/items and try to
1380 make an intelligent decision whether to insert a blank line or not.
1382 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1383 the setting here is ignored and no empty line is inserted to avoid breaking
1384 the list structure."
1385 :group 'org-edit-structure
1386 :type '(list
1387 (cons (const heading)
1388 (choice (const :tag "Never" nil)
1389 (const :tag "Always" t)
1390 (const :tag "Auto" auto)))
1391 (cons (const plain-list-item)
1392 (choice (const :tag "Never" nil)
1393 (const :tag "Always" t)
1394 (const :tag "Auto" auto)))))
1396 (defcustom org-insert-heading-hook nil
1397 "Hook being run after inserting a new heading."
1398 :group 'org-edit-structure
1399 :type 'hook)
1401 (defcustom org-enable-fixed-width-editor t
1402 "Non-nil means lines starting with \":\" are treated as fixed-width.
1403 This currently only means they are never auto-wrapped.
1404 When nil, such lines will be treated like ordinary lines.
1405 See also the QUOTE keyword."
1406 :group 'org-edit-structure
1407 :type 'boolean)
1409 (defcustom org-goto-auto-isearch t
1410 "Non-nil means typing characters in `org-goto' starts incremental search.
1411 When nil, you can use these keybindings to navigate the buffer:
1413 q Quit the org-goto interface
1414 n Go to the next visible heading
1415 p Go to the previous visible heading
1416 f Go one heading forward on same level
1417 b Go one heading backward on same level
1418 u Go one heading up"
1419 :group 'org-edit-structure
1420 :type 'boolean)
1422 (defgroup org-sparse-trees nil
1423 "Options concerning sparse trees in Org-mode."
1424 :tag "Org Sparse Trees"
1425 :group 'org-structure)
1427 (defcustom org-highlight-sparse-tree-matches t
1428 "Non-nil means highlight all matches that define a sparse tree.
1429 The highlights will automatically disappear the next time the buffer is
1430 changed by an edit command."
1431 :group 'org-sparse-trees
1432 :type 'boolean)
1434 (defcustom org-remove-highlights-with-change t
1435 "Non-nil means any change to the buffer will remove temporary highlights.
1436 Such highlights are created by `org-occur' and `org-clock-display'.
1437 When nil, `C-c C-c needs to be used to get rid of the highlights.
1438 The highlights created by `org-preview-latex-fragment' always need
1439 `C-c C-c' to be removed."
1440 :group 'org-sparse-trees
1441 :group 'org-time
1442 :type 'boolean)
1445 (defcustom org-occur-hook '(org-first-headline-recenter)
1446 "Hook that is run after `org-occur' has constructed a sparse tree.
1447 This can be used to recenter the window to show as much of the structure
1448 as possible."
1449 :group 'org-sparse-trees
1450 :type 'hook)
1452 (defgroup org-imenu-and-speedbar nil
1453 "Options concerning imenu and speedbar in Org-mode."
1454 :tag "Org Imenu and Speedbar"
1455 :group 'org-structure)
1457 (defcustom org-imenu-depth 2
1458 "The maximum level for Imenu access to Org-mode headlines.
1459 This also applied for speedbar access."
1460 :group 'org-imenu-and-speedbar
1461 :type 'integer)
1463 (defgroup org-table nil
1464 "Options concerning tables in Org-mode."
1465 :tag "Org Table"
1466 :group 'org)
1468 (defcustom org-enable-table-editor 'optimized
1469 "Non-nil means lines starting with \"|\" are handled by the table editor.
1470 When nil, such lines will be treated like ordinary lines.
1472 When equal to the symbol `optimized', the table editor will be optimized to
1473 do the following:
1474 - Automatic overwrite mode in front of whitespace in table fields.
1475 This makes the structure of the table stay in tact as long as the edited
1476 field does not exceed the column width.
1477 - Minimize the number of realigns. Normally, the table is aligned each time
1478 TAB or RET are pressed to move to another field. With optimization this
1479 happens only if changes to a field might have changed the column width.
1480 Optimization requires replacing the functions `self-insert-command',
1481 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1482 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1483 very good at guessing when a re-align will be necessary, but you can always
1484 force one with \\[org-ctrl-c-ctrl-c].
1486 If you would like to use the optimized version in Org-mode, but the
1487 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1489 This variable can be used to turn on and off the table editor during a session,
1490 but in order to toggle optimization, a restart is required.
1492 See also the variable `org-table-auto-blank-field'."
1493 :group 'org-table
1494 :type '(choice
1495 (const :tag "off" nil)
1496 (const :tag "on" t)
1497 (const :tag "on, optimized" optimized)))
1499 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1500 (version<= emacs-version "24.1"))
1501 "Non-nil means cluster self-insert commands for undo when possible.
1502 If this is set, then, like in the Emacs command loop, 20 consecutive
1503 characters will be undone together.
1504 This is configurable, because there is some impact on typing performance."
1505 :group 'org-table
1506 :type 'boolean)
1508 (defcustom org-table-tab-recognizes-table.el t
1509 "Non-nil means TAB will automatically notice a table.el table.
1510 When it sees such a table, it moves point into it and - if necessary -
1511 calls `table-recognize-table'."
1512 :group 'org-table-editing
1513 :type 'boolean)
1515 (defgroup org-link nil
1516 "Options concerning links in Org-mode."
1517 :tag "Org Link"
1518 :group 'org)
1520 (defvar org-link-abbrev-alist-local nil
1521 "Buffer-local version of `org-link-abbrev-alist', which see.
1522 The value of this is taken from the #+LINK lines.")
1523 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1525 (defcustom org-link-abbrev-alist nil
1526 "Alist of link abbreviations.
1527 The car of each element is a string, to be replaced at the start of a link.
1528 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1529 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1531 [[linkkey:tag][description]]
1533 The 'linkkey' must be a word word, starting with a letter, followed
1534 by letters, numbers, '-' or '_'.
1536 If REPLACE is a string, the tag will simply be appended to create the link.
1537 If the string contains \"%s\", the tag will be inserted there. If the string
1538 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1539 at that point (see the function `url-hexify-string'). If the string contains
1540 the specifier \"%(my-function)\", then the custom function `my-function' will
1541 be invoked: this function takes the tag as its only argument and must return
1542 a string.
1544 REPLACE may also be a function that will be called with the tag as the
1545 only argument to create the link, which should be returned as a string.
1547 See the manual for examples."
1548 :group 'org-link
1549 :type '(repeat
1550 (cons
1551 (string :tag "Protocol")
1552 (choice
1553 (string :tag "Format")
1554 (function)))))
1556 (defcustom org-descriptive-links t
1557 "Non-nil means Org will display descriptive links.
1558 E.g. [[http://orgmode.org][Org website]] will be displayed as
1559 \"Org Website\", hiding the link itself and just displaying its
1560 description. When set to `nil', Org will display the full links
1561 literally.
1563 You can interactively set the value of this variable by calling
1564 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1565 :group 'org-link
1566 :type 'boolean)
1568 (defcustom org-link-file-path-type 'adaptive
1569 "How the path name in file links should be stored.
1570 Valid values are:
1572 relative Relative to the current directory, i.e. the directory of the file
1573 into which the link is being inserted.
1574 absolute Absolute path, if possible with ~ for home directory.
1575 noabbrev Absolute path, no abbreviation of home directory.
1576 adaptive Use relative path for files in the current directory and sub-
1577 directories of it. For other files, use an absolute path."
1578 :group 'org-link
1579 :type '(choice
1580 (const relative)
1581 (const absolute)
1582 (const noabbrev)
1583 (const adaptive)))
1585 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1586 "Types of links that should be activated in Org-mode files.
1587 This is a list of symbols, each leading to the activation of a certain link
1588 type. In principle, it does not hurt to turn on most link types - there may
1589 be a small gain when turning off unused link types. The types are:
1591 bracket The recommended [[link][description]] or [[link]] links with hiding.
1592 angle Links in angular brackets that may contain whitespace like
1593 <bbdb:Carsten Dominik>.
1594 plain Plain links in normal text, no whitespace, like http://google.com.
1595 radio Text that is matched by a radio target, see manual for details.
1596 tag Tag settings in a headline (link to tag search).
1597 date Time stamps (link to calendar).
1598 footnote Footnote labels.
1600 Changing this variable requires a restart of Emacs to become effective."
1601 :group 'org-link
1602 :type '(set :greedy t
1603 (const :tag "Double bracket links" bracket)
1604 (const :tag "Angular bracket links" angle)
1605 (const :tag "Plain text links" plain)
1606 (const :tag "Radio target matches" radio)
1607 (const :tag "Tags" tag)
1608 (const :tag "Timestamps" date)
1609 (const :tag "Footnotes" footnote)))
1611 (defcustom org-make-link-description-function nil
1612 "Function to use for generating link descriptions from links.
1613 When nil, the link location will be used. This function must take
1614 two parameters: the first one is the link, the second one is the
1615 description generated by `org-insert-link'. The function should
1616 return the description to use."
1617 :group 'org-link
1618 :type '(choice (const nil) (function)))
1620 (defgroup org-link-store nil
1621 "Options concerning storing links in Org-mode."
1622 :tag "Org Store Link"
1623 :group 'org-link)
1625 (defcustom org-url-hexify-p t
1626 "When non-nil, hexify URL when creating a link."
1627 :type 'boolean
1628 :version "24.3"
1629 :group 'org-link-store)
1631 (defcustom org-email-link-description-format "Email %c: %.30s"
1632 "Format of the description part of a link to an email or usenet message.
1633 The following %-escapes will be replaced by corresponding information:
1635 %F full \"From\" field
1636 %f name, taken from \"From\" field, address if no name
1637 %T full \"To\" field
1638 %t first name in \"To\" field, address if no name
1639 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1640 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1641 %s subject
1642 %d date
1643 %m message-id.
1645 You may use normal field width specification between the % and the letter.
1646 This is for example useful to limit the length of the subject.
1648 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1649 :group 'org-link-store
1650 :type 'string)
1652 (defcustom org-from-is-user-regexp
1653 (let (r1 r2)
1654 (when (and user-mail-address (not (string= user-mail-address "")))
1655 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1656 (when (and user-full-name (not (string= user-full-name "")))
1657 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1658 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1659 "Regexp matched against the \"From:\" header of an email or usenet message.
1660 It should match if the message is from the user him/herself."
1661 :group 'org-link-store
1662 :type 'regexp)
1664 (defcustom org-context-in-file-links t
1665 "Non-nil means file links from `org-store-link' contain context.
1666 A search string will be added to the file name with :: as separator and
1667 used to find the context when the link is activated by the command
1668 `org-open-at-point'. When this option is t, the entire active region
1669 will be placed in the search string of the file link. If set to a
1670 positive integer, only the first n lines of context will be stored.
1672 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1673 negates this setting for the duration of the command."
1674 :group 'org-link-store
1675 :type '(choice boolean integer))
1677 (defcustom org-keep-stored-link-after-insertion nil
1678 "Non-nil means keep link in list for entire session.
1680 The command `org-store-link' adds a link pointing to the current
1681 location to an internal list. These links accumulate during a session.
1682 The command `org-insert-link' can be used to insert links into any
1683 Org-mode file (offering completion for all stored links). When this
1684 option is nil, every link which has been inserted once using \\[org-insert-link]
1685 will be removed from the list, to make completing the unused links
1686 more efficient."
1687 :group 'org-link-store
1688 :type 'boolean)
1690 (defgroup org-link-follow nil
1691 "Options concerning following links in Org-mode."
1692 :tag "Org Follow Link"
1693 :group 'org-link)
1695 (defcustom org-link-translation-function nil
1696 "Function to translate links with different syntax to Org syntax.
1697 This can be used to translate links created for example by the Planner
1698 or emacs-wiki packages to Org syntax.
1699 The function must accept two parameters, a TYPE containing the link
1700 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1701 which is everything after the link protocol. It should return a cons
1702 with possibly modified values of type and path.
1703 Org contains a function for this, so if you set this variable to
1704 `org-translate-link-from-planner', you should be able follow many
1705 links created by planner."
1706 :group 'org-link-follow
1707 :type '(choice (const nil) (function)))
1709 (defcustom org-follow-link-hook nil
1710 "Hook that is run after a link has been followed."
1711 :group 'org-link-follow
1712 :type 'hook)
1714 (defcustom org-tab-follows-link nil
1715 "Non-nil means on links TAB will follow the link.
1716 Needs to be set before org.el is loaded.
1717 This really should not be used, it does not make sense, and the
1718 implementation is bad."
1719 :group 'org-link-follow
1720 :type 'boolean)
1722 (defcustom org-return-follows-link nil
1723 "Non-nil means on links RET will follow the link.
1724 In tables, the special behavior of RET has precedence."
1725 :group 'org-link-follow
1726 :type 'boolean)
1728 (defcustom org-mouse-1-follows-link
1729 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1730 "Non-nil means mouse-1 on a link will follow the link.
1731 A longer mouse click will still set point. Does not work on XEmacs.
1732 Needs to be set before org.el is loaded."
1733 :group 'org-link-follow
1734 :type 'boolean)
1736 (defcustom org-mark-ring-length 4
1737 "Number of different positions to be recorded in the ring.
1738 Changing this requires a restart of Emacs to work correctly."
1739 :group 'org-link-follow
1740 :type 'integer)
1742 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1743 "Non-nil means internal links in Org files must exactly match a headline.
1744 When nil, the link search tries to match a phrase with all words
1745 in the search text."
1746 :group 'org-link-follow
1747 :version "24.1"
1748 :type '(choice
1749 (const :tag "Use fuzzy text search" nil)
1750 (const :tag "Match only exact headline" t)
1751 (const :tag "Match exact headline or query to create it"
1752 query-to-create)))
1754 (defcustom org-link-frame-setup
1755 '((vm . vm-visit-folder-other-frame)
1756 (vm-imap . vm-visit-imap-folder-other-frame)
1757 (gnus . org-gnus-no-new-news)
1758 (file . find-file-other-window)
1759 (wl . wl-other-frame))
1760 "Setup the frame configuration for following links.
1761 When following a link with Emacs, it may often be useful to display
1762 this link in another window or frame. This variable can be used to
1763 set this up for the different types of links.
1764 For VM, use any of
1765 `vm-visit-folder'
1766 `vm-visit-folder-other-window'
1767 `vm-visit-folder-other-frame'
1768 For Gnus, use any of
1769 `gnus'
1770 `gnus-other-frame'
1771 `org-gnus-no-new-news'
1772 For FILE, use any of
1773 `find-file'
1774 `find-file-other-window'
1775 `find-file-other-frame'
1776 For Wanderlust use any of
1777 `wl'
1778 `wl-other-frame'
1779 For the calendar, use the variable `calendar-setup'.
1780 For BBDB, it is currently only possible to display the matches in
1781 another window."
1782 :group 'org-link-follow
1783 :type '(list
1784 (cons (const vm)
1785 (choice
1786 (const vm-visit-folder)
1787 (const vm-visit-folder-other-window)
1788 (const vm-visit-folder-other-frame)))
1789 (cons (const vm-imap)
1790 (choice
1791 (const vm-visit-imap-folder)
1792 (const vm-visit-imap-folder-other-window)
1793 (const vm-visit-imap-folder-other-frame)))
1794 (cons (const gnus)
1795 (choice
1796 (const gnus)
1797 (const gnus-other-frame)
1798 (const org-gnus-no-new-news)))
1799 (cons (const file)
1800 (choice
1801 (const find-file)
1802 (const find-file-other-window)
1803 (const find-file-other-frame)))
1804 (cons (const wl)
1805 (choice
1806 (const wl)
1807 (const wl-other-frame)))))
1809 (defcustom org-display-internal-link-with-indirect-buffer nil
1810 "Non-nil means use indirect buffer to display infile links.
1811 Activating internal links (from one location in a file to another location
1812 in the same file) normally just jumps to the location. When the link is
1813 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1814 is displayed in
1815 another window. When this option is set, the other window actually displays
1816 an indirect buffer clone of the current buffer, to avoid any visibility
1817 changes to the current buffer."
1818 :group 'org-link-follow
1819 :type 'boolean)
1821 (defcustom org-open-non-existing-files nil
1822 "Non-nil means `org-open-file' will open non-existing files.
1823 When nil, an error will be generated.
1824 This variable applies only to external applications because they
1825 might choke on non-existing files. If the link is to a file that
1826 will be opened in Emacs, the variable is ignored."
1827 :group 'org-link-follow
1828 :type 'boolean)
1830 (defcustom org-open-directory-means-index-dot-org nil
1831 "Non-nil means a link to a directory really means to index.org.
1832 When nil, following a directory link will run dired or open a finder/explorer
1833 window on that directory."
1834 :group 'org-link-follow
1835 :type 'boolean)
1837 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1838 "Function and arguments to call for following mailto links.
1839 This is a list with the first element being a Lisp function, and the
1840 remaining elements being arguments to the function. In string arguments,
1841 %a will be replaced by the address, and %s will be replaced by the subject
1842 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1843 :group 'org-link-follow
1844 :type '(choice
1845 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1846 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1847 (const :tag "message-mail" (message-mail "%a" "%s"))
1848 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1850 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1851 "Non-nil means ask for confirmation before executing shell links.
1852 Shell links can be dangerous: just think about a link
1854 [[shell:rm -rf ~/*][Google Search]]
1856 This link would show up in your Org-mode document as \"Google Search\",
1857 but really it would remove your entire home directory.
1858 Therefore we advise against setting this variable to nil.
1859 Just change it to `y-or-n-p' if you want to confirm with a
1860 single keystroke rather than having to type \"yes\"."
1861 :group 'org-link-follow
1862 :type '(choice
1863 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1864 (const :tag "with y-or-n (faster)" y-or-n-p)
1865 (const :tag "no confirmation (dangerous)" nil)))
1866 (put 'org-confirm-shell-link-function
1867 'safe-local-variable
1868 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1870 (defcustom org-confirm-shell-link-not-regexp ""
1871 "A regexp to skip confirmation for shell links."
1872 :group 'org-link-follow
1873 :version "24.1"
1874 :type 'regexp)
1876 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1877 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1878 Elisp links can be dangerous: just think about a link
1880 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1882 This link would show up in your Org-mode document as \"Google Search\",
1883 but really it would remove your entire home directory.
1884 Therefore we advise against setting this variable to nil.
1885 Just change it to `y-or-n-p' if you want to confirm with a
1886 single keystroke rather than having to type \"yes\"."
1887 :group 'org-link-follow
1888 :type '(choice
1889 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1890 (const :tag "with y-or-n (faster)" y-or-n-p)
1891 (const :tag "no confirmation (dangerous)" nil)))
1892 (put 'org-confirm-shell-link-function
1893 'safe-local-variable
1894 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1896 (defcustom org-confirm-elisp-link-not-regexp ""
1897 "A regexp to skip confirmation for Elisp links."
1898 :group 'org-link-follow
1899 :version "24.1"
1900 :type 'regexp)
1902 (defconst org-file-apps-defaults-gnu
1903 '((remote . emacs)
1904 (system . mailcap)
1905 (t . mailcap))
1906 "Default file applications on a UNIX or GNU/Linux system.
1907 See `org-file-apps'.")
1909 (defconst org-file-apps-defaults-macosx
1910 '((remote . emacs)
1911 (t . "open %s")
1912 (system . "open %s")
1913 ("ps.gz" . "gv %s")
1914 ("eps.gz" . "gv %s")
1915 ("dvi" . "xdvi %s")
1916 ("fig" . "xfig %s"))
1917 "Default file applications on a MacOS X system.
1918 The system \"open\" is known as a default, but we use X11 applications
1919 for some files for which the OS does not have a good default.
1920 See `org-file-apps'.")
1922 (defconst org-file-apps-defaults-windowsnt
1923 (list
1924 '(remote . emacs)
1925 (cons t
1926 (list (if (featurep 'xemacs)
1927 'mswindows-shell-execute
1928 'w32-shell-execute)
1929 "open" 'file))
1930 (cons 'system
1931 (list (if (featurep 'xemacs)
1932 'mswindows-shell-execute
1933 'w32-shell-execute)
1934 "open" 'file)))
1935 "Default file applications on a Windows NT system.
1936 The system \"open\" is used for most files.
1937 See `org-file-apps'.")
1939 (defcustom org-file-apps
1940 '((auto-mode . emacs)
1941 ("\\.mm\\'" . default)
1942 ("\\.x?html?\\'" . default)
1943 ("\\.pdf\\'" . default))
1944 "External applications for opening `file:path' items in a document.
1945 Org-mode uses system defaults for different file types, but
1946 you can use this variable to set the application for a given file
1947 extension. The entries in this list are cons cells where the car identifies
1948 files and the cdr the corresponding command. Possible values for the
1949 file identifier are
1950 \"string\" A string as a file identifier can be interpreted in different
1951 ways, depending on its contents:
1953 - Alphanumeric characters only:
1954 Match links with this file extension.
1955 Example: (\"pdf\" . \"evince %s\")
1956 to open PDFs with evince.
1958 - Regular expression: Match links where the
1959 filename matches the regexp. If you want to
1960 use groups here, use shy groups.
1962 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1963 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1964 to open *.html and *.xhtml with firefox.
1966 - Regular expression which contains (non-shy) groups:
1967 Match links where the whole link, including \"::\", and
1968 anything after that, matches the regexp.
1969 In a custom command string, %1, %2, etc. are replaced with
1970 the parts of the link that were matched by the groups.
1971 For backwards compatibility, if a command string is given
1972 that does not use any of the group matches, this case is
1973 handled identically to the second one (i.e. match against
1974 file name only).
1975 In a custom lisp form, you can access the group matches with
1976 (match-string n link).
1978 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1979 to open [[file:document.pdf::5]] with evince at page 5.
1981 `directory' Matches a directory
1982 `remote' Matches a remote file, accessible through tramp or efs.
1983 Remote files most likely should be visited through Emacs
1984 because external applications cannot handle such paths.
1985 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1986 so all files Emacs knows how to handle. Using this with
1987 command `emacs' will open most files in Emacs. Beware that this
1988 will also open html files inside Emacs, unless you add
1989 (\"html\" . default) to the list as well.
1990 t Default for files not matched by any of the other options.
1991 `system' The system command to open files, like `open' on Windows
1992 and Mac OS X, and mailcap under GNU/Linux. This is the command
1993 that will be selected if you call `C-c C-o' with a double
1994 \\[universal-argument] \\[universal-argument] prefix.
1996 Possible values for the command are:
1997 `emacs' The file will be visited by the current Emacs process.
1998 `default' Use the default application for this file type, which is the
1999 association for t in the list, most likely in the system-specific
2000 part.
2001 This can be used to overrule an unwanted setting in the
2002 system-specific variable.
2003 `system' Use the system command for opening files, like \"open\".
2004 This command is specified by the entry whose car is `system'.
2005 Most likely, the system-specific version of this variable
2006 does define this command, but you can overrule/replace it
2007 here.
2008 string A command to be executed by a shell; %s will be replaced
2009 by the path to the file.
2010 sexp A Lisp form which will be evaluated. The file path will
2011 be available in the Lisp variable `file'.
2012 For more examples, see the system specific constants
2013 `org-file-apps-defaults-macosx'
2014 `org-file-apps-defaults-windowsnt'
2015 `org-file-apps-defaults-gnu'."
2016 :group 'org-link-follow
2017 :type '(repeat
2018 (cons (choice :value ""
2019 (string :tag "Extension")
2020 (const :tag "System command to open files" system)
2021 (const :tag "Default for unrecognized files" t)
2022 (const :tag "Remote file" remote)
2023 (const :tag "Links to a directory" directory)
2024 (const :tag "Any files that have Emacs modes"
2025 auto-mode))
2026 (choice :value ""
2027 (const :tag "Visit with Emacs" emacs)
2028 (const :tag "Use default" default)
2029 (const :tag "Use the system command" system)
2030 (string :tag "Command")
2031 (sexp :tag "Lisp form")))))
2033 (defcustom org-doi-server-url "http://dx.doi.org/"
2034 "The URL of the DOI server."
2035 :type 'string
2036 :version "24.3"
2037 :group 'org-link-follow)
2039 (defgroup org-refile nil
2040 "Options concerning refiling entries in Org-mode."
2041 :tag "Org Refile"
2042 :group 'org)
2044 (defcustom org-directory "~/org"
2045 "Directory with org files.
2046 This is just a default location to look for Org files. There is no need
2047 at all to put your files into this directory. It is only used in the
2048 following situations:
2050 1. When a capture template specifies a target file that is not an
2051 absolute path. The path will then be interpreted relative to
2052 `org-directory'
2053 2. When a capture note is filed away in an interactive way (when exiting the
2054 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2055 with `org-directory' as the default path."
2056 :group 'org-refile
2057 :group 'org-remember
2058 :group 'org-capture
2059 :type 'directory)
2061 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2062 "Default target for storing notes.
2063 Used as a fall back file for org-remember.el and org-capture.el, for
2064 templates that do not specify a target file."
2065 :group 'org-refile
2066 :group 'org-remember
2067 :group 'org-capture
2068 :type '(choice
2069 (const :tag "Default from remember-data-file" nil)
2070 file))
2072 (defcustom org-goto-interface 'outline
2073 "The default interface to be used for `org-goto'.
2074 Allowed values are:
2075 outline The interface shows an outline of the relevant file
2076 and the correct heading is found by moving through
2077 the outline or by searching with incremental search.
2078 outline-path-completion Headlines in the current buffer are offered via
2079 completion. This is the interface also used by
2080 the refile command."
2081 :group 'org-refile
2082 :type '(choice
2083 (const :tag "Outline" outline)
2084 (const :tag "Outline-path-completion" outline-path-completion)))
2086 (defcustom org-goto-max-level 5
2087 "Maximum target level when running `org-goto' with refile interface."
2088 :group 'org-refile
2089 :type 'integer)
2091 (defcustom org-reverse-note-order nil
2092 "Non-nil means store new notes at the beginning of a file or entry.
2093 When nil, new notes will be filed to the end of a file or entry.
2094 This can also be a list with cons cells of regular expressions that
2095 are matched against file names, and values."
2096 :group 'org-remember
2097 :group 'org-capture
2098 :group 'org-refile
2099 :type '(choice
2100 (const :tag "Reverse always" t)
2101 (const :tag "Reverse never" nil)
2102 (repeat :tag "By file name regexp"
2103 (cons regexp boolean))))
2105 (defcustom org-log-refile nil
2106 "Information to record when a task is refiled.
2108 Possible values are:
2110 nil Don't add anything
2111 time Add a time stamp to the task
2112 note Prompt for a note and add it with template `org-log-note-headings'
2114 This option can also be set with on a per-file-basis with
2116 #+STARTUP: nologrefile
2117 #+STARTUP: logrefile
2118 #+STARTUP: lognoterefile
2120 You can have local logging settings for a subtree by setting the LOGGING
2121 property to one or more of these keywords.
2123 When bulk-refiling from the agenda, the value `note' is forbidden and
2124 will temporarily be changed to `time'."
2125 :group 'org-refile
2126 :group 'org-progress
2127 :version "24.1"
2128 :type '(choice
2129 (const :tag "No logging" nil)
2130 (const :tag "Record timestamp" time)
2131 (const :tag "Record timestamp with note." note)))
2133 (defcustom org-refile-targets nil
2134 "Targets for refiling entries with \\[org-refile].
2135 This is a list of cons cells. Each cell contains:
2136 - a specification of the files to be considered, either a list of files,
2137 or a symbol whose function or variable value will be used to retrieve
2138 a file name or a list of file names. If you use `org-agenda-files' for
2139 that, all agenda files will be scanned for targets. Nil means consider
2140 headings in the current buffer.
2141 - A specification of how to find candidate refile targets. This may be
2142 any of:
2143 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2144 This tag has to be present in all target headlines, inheritance will
2145 not be considered.
2146 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2147 todo keyword.
2148 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2149 headlines that are refiling targets.
2150 - a cons cell (:level . N). Any headline of level N is considered a target.
2151 Note that, when `org-odd-levels-only' is set, level corresponds to
2152 order in hierarchy, not to the number of stars.
2153 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2154 Note that, when `org-odd-levels-only' is set, level corresponds to
2155 order in hierarchy, not to the number of stars.
2157 Each element of this list generates a set of possible targets.
2158 The union of these sets is presented (with completion) to
2159 the user by `org-refile'.
2161 You can set the variable `org-refile-target-verify-function' to a function
2162 to verify each headline found by the simple criteria above.
2164 When this variable is nil, all top-level headlines in the current buffer
2165 are used, equivalent to the value `((nil . (:level . 1))'."
2166 :group 'org-refile
2167 :type '(repeat
2168 (cons
2169 (choice :value org-agenda-files
2170 (const :tag "All agenda files" org-agenda-files)
2171 (const :tag "Current buffer" nil)
2172 (function) (variable) (file))
2173 (choice :tag "Identify target headline by"
2174 (cons :tag "Specific tag" (const :value :tag) (string))
2175 (cons :tag "TODO keyword" (const :value :todo) (string))
2176 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2177 (cons :tag "Level number" (const :value :level) (integer))
2178 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2180 (defcustom org-refile-target-verify-function nil
2181 "Function to verify if the headline at point should be a refile target.
2182 The function will be called without arguments, with point at the
2183 beginning of the headline. It should return t and leave point
2184 where it is if the headline is a valid target for refiling.
2186 If the target should not be selected, the function must return nil.
2187 In addition to this, it may move point to a place from where the search
2188 should be continued. For example, the function may decide that the entire
2189 subtree of the current entry should be excluded and move point to the end
2190 of the subtree."
2191 :group 'org-refile
2192 :type '(choice
2193 (const nil)
2194 (function)))
2196 (defcustom org-refile-use-cache nil
2197 "Non-nil means cache refile targets to speed up the process.
2198 The cache for a particular file will be updated automatically when
2199 the buffer has been killed, or when any of the marker used for flagging
2200 refile targets no longer points at a live buffer.
2201 If you have added new entries to a buffer that might themselves be targets,
2202 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2203 find that easier, `C-u C-u C-u C-c C-w'."
2204 :group 'org-refile
2205 :version "24.1"
2206 :type 'boolean)
2208 (defcustom org-refile-use-outline-path nil
2209 "Non-nil means provide refile targets as paths.
2210 So a level 3 headline will be available as level1/level2/level3.
2212 When the value is `file', also include the file name (without directory)
2213 into the path. In this case, you can also stop the completion after
2214 the file name, to get entries inserted as top level in the file.
2216 When `full-file-path', include the full file path."
2217 :group 'org-refile
2218 :type '(choice
2219 (const :tag "Not" nil)
2220 (const :tag "Yes" t)
2221 (const :tag "Start with file name" file)
2222 (const :tag "Start with full file path" full-file-path)))
2224 (defcustom org-outline-path-complete-in-steps t
2225 "Non-nil means complete the outline path in hierarchical steps.
2226 When Org-mode uses the refile interface to select an outline path
2227 \(see variable `org-refile-use-outline-path'), the completion of
2228 the path can be done is a single go, or if can be done in steps down
2229 the headline hierarchy. Going in steps is probably the best if you
2230 do not use a special completion package like `ido' or `icicles'.
2231 However, when using these packages, going in one step can be very
2232 fast, while still showing the whole path to the entry."
2233 :group 'org-refile
2234 :type 'boolean)
2236 (defcustom org-refile-allow-creating-parent-nodes nil
2237 "Non-nil means allow to create new nodes as refile targets.
2238 New nodes are then created by adding \"/new node name\" to the completion
2239 of an existing node. When the value of this variable is `confirm',
2240 new node creation must be confirmed by the user (recommended)
2241 When nil, the completion must match an existing entry.
2243 Note that, if the new heading is not seen by the criteria
2244 listed in `org-refile-targets', multiple instances of the same
2245 heading would be created by trying again to file under the new
2246 heading."
2247 :group 'org-refile
2248 :type '(choice
2249 (const :tag "Never" nil)
2250 (const :tag "Always" t)
2251 (const :tag "Prompt for confirmation" confirm)))
2253 (defcustom org-refile-active-region-within-subtree nil
2254 "Non-nil means also refile active region within a subtree.
2256 By default `org-refile' doesn't allow refiling regions if they
2257 don't contain a set of subtrees, but it might be convenient to
2258 do so sometimes: in that case, the first line of the region is
2259 converted to a headline before refiling."
2260 :group 'org-refile
2261 :version "24.1"
2262 :type 'boolean)
2264 (defgroup org-todo nil
2265 "Options concerning TODO items in Org-mode."
2266 :tag "Org TODO"
2267 :group 'org)
2269 (defgroup org-progress nil
2270 "Options concerning Progress logging in Org-mode."
2271 :tag "Org Progress"
2272 :group 'org-time)
2274 (defvar org-todo-interpretation-widgets
2275 '((:tag "Sequence (cycling hits every state)" sequence)
2276 (:tag "Type (cycling directly to DONE)" type))
2277 "The available interpretation symbols for customizing `org-todo-keywords'.
2278 Interested libraries should add to this list.")
2280 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2281 "List of TODO entry keyword sequences and their interpretation.
2282 \\<org-mode-map>This is a list of sequences.
2284 Each sequence starts with a symbol, either `sequence' or `type',
2285 indicating if the keywords should be interpreted as a sequence of
2286 action steps, or as different types of TODO items. The first
2287 keywords are states requiring action - these states will select a headline
2288 for inclusion into the global TODO list Org-mode produces. If one of
2289 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2290 signify that no further action is necessary. If \"|\" is not found,
2291 the last keyword is treated as the only DONE state of the sequence.
2293 The command \\[org-todo] cycles an entry through these states, and one
2294 additional state where no keyword is present. For details about this
2295 cycling, see the manual.
2297 TODO keywords and interpretation can also be set on a per-file basis with
2298 the special #+SEQ_TODO and #+TYP_TODO lines.
2300 Each keyword can optionally specify a character for fast state selection
2301 \(in combination with the variable `org-use-fast-todo-selection')
2302 and specifiers for state change logging, using the same syntax that
2303 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2304 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2305 indicates to record a time stamp each time this state is selected.
2307 Each keyword may also specify if a timestamp or a note should be
2308 recorded when entering or leaving the state, by adding additional
2309 characters in the parenthesis after the keyword. This looks like this:
2310 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2311 record only the time of the state change. With X and Y being either
2312 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2313 Y when leaving the state if and only if the *target* state does not
2314 define X. You may omit any of the fast-selection key or X or /Y,
2315 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2317 For backward compatibility, this variable may also be just a list
2318 of keywords. In this case the interpretation (sequence or type) will be
2319 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2320 :group 'org-todo
2321 :group 'org-keywords
2322 :type '(choice
2323 (repeat :tag "Old syntax, just keywords"
2324 (string :tag "Keyword"))
2325 (repeat :tag "New syntax"
2326 (cons
2327 (choice
2328 :tag "Interpretation"
2329 ;;Quick and dirty way to see
2330 ;;`org-todo-interpretations'. This takes the
2331 ;;place of item arguments
2332 :convert-widget
2333 (lambda (widget)
2334 (widget-put widget
2335 :args (mapcar
2336 #'(lambda (x)
2337 (widget-convert
2338 (cons 'const x)))
2339 org-todo-interpretation-widgets))
2340 widget))
2341 (repeat
2342 (string :tag "Keyword"))))))
2344 (defvar org-todo-keywords-1 nil
2345 "All TODO and DONE keywords active in a buffer.")
2346 (make-variable-buffer-local 'org-todo-keywords-1)
2347 (defvar org-todo-keywords-for-agenda nil)
2348 (defvar org-done-keywords-for-agenda nil)
2349 (defvar org-drawers-for-agenda nil)
2350 (defvar org-todo-keyword-alist-for-agenda nil)
2351 (defvar org-tag-alist-for-agenda nil
2352 "Alist of all tags from all agenda files.")
2353 (defvar org-tag-groups-alist-for-agenda nil
2354 "Alist of all groups tags from all current agenda files.")
2355 (defvar org-tag-groups-alist nil)
2356 (make-variable-buffer-local 'org-tag-groups-alist)
2357 (defvar org-agenda-contributing-files nil)
2358 (defvar org-not-done-keywords nil)
2359 (make-variable-buffer-local 'org-not-done-keywords)
2360 (defvar org-done-keywords nil)
2361 (make-variable-buffer-local 'org-done-keywords)
2362 (defvar org-todo-heads nil)
2363 (make-variable-buffer-local 'org-todo-heads)
2364 (defvar org-todo-sets nil)
2365 (make-variable-buffer-local 'org-todo-sets)
2366 (defvar org-todo-log-states nil)
2367 (make-variable-buffer-local 'org-todo-log-states)
2368 (defvar org-todo-kwd-alist nil)
2369 (make-variable-buffer-local 'org-todo-kwd-alist)
2370 (defvar org-todo-key-alist nil)
2371 (make-variable-buffer-local 'org-todo-key-alist)
2372 (defvar org-todo-key-trigger nil)
2373 (make-variable-buffer-local 'org-todo-key-trigger)
2375 (defcustom org-todo-interpretation 'sequence
2376 "Controls how TODO keywords are interpreted.
2377 This variable is in principle obsolete and is only used for
2378 backward compatibility, if the interpretation of todo keywords is
2379 not given already in `org-todo-keywords'. See that variable for
2380 more information."
2381 :group 'org-todo
2382 :group 'org-keywords
2383 :type '(choice (const sequence)
2384 (const type)))
2386 (defcustom org-use-fast-todo-selection t
2387 "Non-nil means use the fast todo selection scheme with C-c C-t.
2388 This variable describes if and under what circumstances the cycling
2389 mechanism for TODO keywords will be replaced by a single-key, direct
2390 selection scheme.
2392 When nil, fast selection is never used.
2394 When the symbol `prefix', it will be used when `org-todo' is called
2395 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2396 `C-u t' in an agenda buffer.
2398 When t, fast selection is used by default. In this case, the prefix
2399 argument forces cycling instead.
2401 In all cases, the special interface is only used if access keys have
2402 actually been assigned by the user, i.e. if keywords in the configuration
2403 are followed by a letter in parenthesis, like TODO(t)."
2404 :group 'org-todo
2405 :type '(choice
2406 (const :tag "Never" nil)
2407 (const :tag "By default" t)
2408 (const :tag "Only with C-u C-c C-t" prefix)))
2410 (defcustom org-provide-todo-statistics t
2411 "Non-nil means update todo statistics after insert and toggle.
2412 ALL-HEADLINES means update todo statistics by including headlines
2413 with no TODO keyword as well, counting them as not done.
2414 A list of TODO keywords means the same, but skip keywords that are
2415 not in this list.
2417 When this is set, todo statistics is updated in the parent of the
2418 current entry each time a todo state is changed."
2419 :group 'org-todo
2420 :type '(choice
2421 (const :tag "Yes, only for TODO entries" t)
2422 (const :tag "Yes, including all entries" 'all-headlines)
2423 (repeat :tag "Yes, for TODOs in this list"
2424 (string :tag "TODO keyword"))
2425 (other :tag "No TODO statistics" nil)))
2427 (defcustom org-hierarchical-todo-statistics t
2428 "Non-nil means TODO statistics covers just direct children.
2429 When nil, all entries in the subtree are considered.
2430 This has only an effect if `org-provide-todo-statistics' is set.
2431 To set this to nil for only a single subtree, use a COOKIE_DATA
2432 property and include the word \"recursive\" into the value."
2433 :group 'org-todo
2434 :type 'boolean)
2436 (defcustom org-after-todo-state-change-hook nil
2437 "Hook which is run after the state of a TODO item was changed.
2438 The new state (a string with a TODO keyword, or nil) is available in the
2439 Lisp variable `org-state'."
2440 :group 'org-todo
2441 :type 'hook)
2443 (defvar org-blocker-hook nil
2444 "Hook for functions that are allowed to block a state change.
2446 Functions in this hook should not modify the buffer.
2447 Each function gets as its single argument a property list,
2448 see `org-trigger-hook' for more information about this list.
2450 If any of the functions in this hook returns nil, the state change
2451 is blocked.")
2453 (defvar org-trigger-hook nil
2454 "Hook for functions that are triggered by a state change.
2456 Each function gets as its single argument a property list with at
2457 least the following elements:
2459 (:type type-of-change :position pos-at-entry-start
2460 :from old-state :to new-state)
2462 Depending on the type, more properties may be present.
2464 This mechanism is currently implemented for:
2466 TODO state changes
2467 ------------------
2468 :type todo-state-change
2469 :from previous state (keyword as a string), or nil, or a symbol
2470 'todo' or 'done', to indicate the general type of state.
2471 :to new state, like in :from")
2473 (defcustom org-enforce-todo-dependencies nil
2474 "Non-nil means undone TODO entries will block switching the parent to DONE.
2475 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2476 be blocked if any prior sibling is not yet done.
2477 Finally, if the parent is blocked because of ordered siblings of its own,
2478 the child will also be blocked."
2479 :set (lambda (var val)
2480 (set var val)
2481 (if val
2482 (add-hook 'org-blocker-hook
2483 'org-block-todo-from-children-or-siblings-or-parent)
2484 (remove-hook 'org-blocker-hook
2485 'org-block-todo-from-children-or-siblings-or-parent)))
2486 :group 'org-todo
2487 :type 'boolean)
2489 (defcustom org-enforce-todo-checkbox-dependencies nil
2490 "Non-nil means unchecked boxes will block switching the parent to DONE.
2491 When this is nil, checkboxes have no influence on switching TODO states.
2492 When non-nil, you first need to check off all check boxes before the TODO
2493 entry can be switched to DONE.
2494 This variable needs to be set before org.el is loaded, and you need to
2495 restart Emacs after a change to make the change effective. The only way
2496 to change is while Emacs is running is through the customize interface."
2497 :set (lambda (var val)
2498 (set var val)
2499 (if val
2500 (add-hook 'org-blocker-hook
2501 'org-block-todo-from-checkboxes)
2502 (remove-hook 'org-blocker-hook
2503 'org-block-todo-from-checkboxes)))
2504 :group 'org-todo
2505 :type 'boolean)
2507 (defcustom org-treat-insert-todo-heading-as-state-change nil
2508 "Non-nil means inserting a TODO heading is treated as state change.
2509 So when the command \\[org-insert-todo-heading] is used, state change
2510 logging will apply if appropriate. When nil, the new TODO item will
2511 be inserted directly, and no logging will take place."
2512 :group 'org-todo
2513 :type 'boolean)
2515 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2516 "Non-nil means switching TODO states with S-cursor counts as state change.
2517 This is the default behavior. However, setting this to nil allows a
2518 convenient way to select a TODO state and bypass any logging associated
2519 with that."
2520 :group 'org-todo
2521 :type 'boolean)
2523 (defcustom org-todo-state-tags-triggers nil
2524 "Tag changes that should be triggered by TODO state changes.
2525 This is a list. Each entry is
2527 (state-change (tag . flag) .......)
2529 State-change can be a string with a state, and empty string to indicate the
2530 state that has no TODO keyword, or it can be one of the symbols `todo'
2531 or `done', meaning any not-done or done state, respectively."
2532 :group 'org-todo
2533 :group 'org-tags
2534 :type '(repeat
2535 (cons (choice :tag "When changing to"
2536 (const :tag "Not-done state" todo)
2537 (const :tag "Done state" done)
2538 (string :tag "State"))
2539 (repeat
2540 (cons :tag "Tag action"
2541 (string :tag "Tag")
2542 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2544 (defcustom org-log-done nil
2545 "Information to record when a task moves to the DONE state.
2547 Possible values are:
2549 nil Don't add anything, just change the keyword
2550 time Add a time stamp to the task
2551 note Prompt for a note and add it with template `org-log-note-headings'
2553 This option can also be set with on a per-file-basis with
2555 #+STARTUP: nologdone
2556 #+STARTUP: logdone
2557 #+STARTUP: lognotedone
2559 You can have local logging settings for a subtree by setting the LOGGING
2560 property to one or more of these keywords."
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type '(choice
2564 (const :tag "No logging" nil)
2565 (const :tag "Record CLOSED timestamp" time)
2566 (const :tag "Record CLOSED timestamp with note." note)))
2568 ;; Normalize old uses of org-log-done.
2569 (cond
2570 ((eq org-log-done t) (setq org-log-done 'time))
2571 ((and (listp org-log-done) (memq 'done org-log-done))
2572 (setq org-log-done 'note)))
2574 (defcustom org-log-reschedule nil
2575 "Information to record when the scheduling date of a tasks is modified.
2577 Possible values are:
2579 nil Don't add anything, just change the date
2580 time Add a time stamp to the task
2581 note Prompt for a note and add it with template `org-log-note-headings'
2583 This option can also be set with on a per-file-basis with
2585 #+STARTUP: nologreschedule
2586 #+STARTUP: logreschedule
2587 #+STARTUP: lognotereschedule"
2588 :group 'org-todo
2589 :group 'org-progress
2590 :type '(choice
2591 (const :tag "No logging" nil)
2592 (const :tag "Record timestamp" time)
2593 (const :tag "Record timestamp with note." note)))
2595 (defcustom org-log-redeadline nil
2596 "Information to record when the deadline date of a tasks is modified.
2598 Possible values are:
2600 nil Don't add anything, just change the date
2601 time Add a time stamp to the task
2602 note Prompt for a note and add it with template `org-log-note-headings'
2604 This option can also be set with on a per-file-basis with
2606 #+STARTUP: nologredeadline
2607 #+STARTUP: logredeadline
2608 #+STARTUP: lognoteredeadline
2610 You can have local logging settings for a subtree by setting the LOGGING
2611 property to one or more of these keywords."
2612 :group 'org-todo
2613 :group 'org-progress
2614 :type '(choice
2615 (const :tag "No logging" nil)
2616 (const :tag "Record timestamp" time)
2617 (const :tag "Record timestamp with note." note)))
2619 (defcustom org-log-note-clock-out nil
2620 "Non-nil means record a note when clocking out of an item.
2621 This can also be configured on a per-file basis by adding one of
2622 the following lines anywhere in the buffer:
2624 #+STARTUP: lognoteclock-out
2625 #+STARTUP: nolognoteclock-out"
2626 :group 'org-todo
2627 :group 'org-progress
2628 :type 'boolean)
2630 (defcustom org-log-done-with-time t
2631 "Non-nil means the CLOSED time stamp will contain date and time.
2632 When nil, only the date will be recorded."
2633 :group 'org-progress
2634 :type 'boolean)
2636 (defcustom org-log-note-headings
2637 '((done . "CLOSING NOTE %t")
2638 (state . "State %-12s from %-12S %t")
2639 (note . "Note taken on %t")
2640 (reschedule . "Rescheduled from %S on %t")
2641 (delschedule . "Not scheduled, was %S on %t")
2642 (redeadline . "New deadline from %S on %t")
2643 (deldeadline . "Removed deadline, was %S on %t")
2644 (refile . "Refiled on %t")
2645 (clock-out . ""))
2646 "Headings for notes added to entries.
2647 The value is an alist, with the car being a symbol indicating the note
2648 context, and the cdr is the heading to be used. The heading may also be the
2649 empty string.
2650 %t in the heading will be replaced by a time stamp.
2651 %T will be an active time stamp instead the default inactive one
2652 %d will be replaced by a short-format time stamp.
2653 %D will be replaced by an active short-format time stamp.
2654 %s will be replaced by the new TODO state, in double quotes.
2655 %S will be replaced by the old TODO state, in double quotes.
2656 %u will be replaced by the user name.
2657 %U will be replaced by the full user name.
2659 In fact, it is not a good idea to change the `state' entry, because
2660 agenda log mode depends on the format of these entries."
2661 :group 'org-todo
2662 :group 'org-progress
2663 :type '(list :greedy t
2664 (cons (const :tag "Heading when closing an item" done) string)
2665 (cons (const :tag
2666 "Heading when changing todo state (todo sequence only)"
2667 state) string)
2668 (cons (const :tag "Heading when just taking a note" note) string)
2669 (cons (const :tag "Heading when clocking out" clock-out) string)
2670 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2671 (cons (const :tag "Heading when rescheduling" reschedule) string)
2672 (cons (const :tag "Heading when changing deadline" redeadline) string)
2673 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2674 (cons (const :tag "Heading when refiling" refile) string)))
2676 (unless (assq 'note org-log-note-headings)
2677 (push '(note . "%t") org-log-note-headings))
2679 (defcustom org-log-into-drawer nil
2680 "Non-nil means insert state change notes and time stamps into a drawer.
2681 When nil, state changes notes will be inserted after the headline and
2682 any scheduling and clock lines, but not inside a drawer.
2684 The value of this variable should be the name of the drawer to use.
2685 LOGBOOK is proposed as the default drawer for this purpose, you can
2686 also set this to a string to define the drawer of your choice.
2688 A value of t is also allowed, representing \"LOGBOOK\".
2690 A value of t or nil can also be set with on a per-file-basis with
2692 #+STARTUP: logdrawer
2693 #+STARTUP: nologdrawer
2695 If this variable is set, `org-log-state-notes-insert-after-drawers'
2696 will be ignored.
2698 You can set the property LOG_INTO_DRAWER to overrule this setting for
2699 a subtree."
2700 :group 'org-todo
2701 :group 'org-progress
2702 :type '(choice
2703 (const :tag "Not into a drawer" nil)
2704 (const :tag "LOGBOOK" t)
2705 (string :tag "Other")))
2707 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2709 (defun org-log-into-drawer ()
2710 "Return the value of `org-log-into-drawer', but let properties overrule.
2711 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2712 used instead of the default value."
2713 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2714 (cond
2715 ((not p) org-log-into-drawer)
2716 ((equal p "nil") nil)
2717 ((equal p "t") "LOGBOOK")
2718 (t p))))
2720 (defcustom org-log-state-notes-insert-after-drawers nil
2721 "Non-nil means insert state change notes after any drawers in entry.
2722 Only the drawers that *immediately* follow the headline and the
2723 deadline/scheduled line are skipped.
2724 When nil, insert notes right after the heading and perhaps the line
2725 with deadline/scheduling if present.
2727 This variable will have no effect if `org-log-into-drawer' is
2728 set."
2729 :group 'org-todo
2730 :group 'org-progress
2731 :type 'boolean)
2733 (defcustom org-log-states-order-reversed t
2734 "Non-nil means the latest state note will be directly after heading.
2735 When nil, the state change notes will be ordered according to time.
2737 This option can also be set with on a per-file-basis with
2739 #+STARTUP: logstatesreversed
2740 #+STARTUP: nologstatesreversed"
2741 :group 'org-todo
2742 :group 'org-progress
2743 :type 'boolean)
2745 (defcustom org-todo-repeat-to-state nil
2746 "The TODO state to which a repeater should return the repeating task.
2747 By default this is the first task in a TODO sequence, or the previous state
2748 in a TODO_TYP set. But you can specify another task here.
2749 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2750 :group 'org-todo
2751 :version "24.1"
2752 :type '(choice (const :tag "Head of sequence" nil)
2753 (string :tag "Specific state")))
2755 (defcustom org-log-repeat 'time
2756 "Non-nil means record moving through the DONE state when triggering repeat.
2757 An auto-repeating task is immediately switched back to TODO when
2758 marked DONE. If you are not logging state changes (by adding \"@\"
2759 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2760 record a closing note, there will be no record of the task moving
2761 through DONE. This variable forces taking a note anyway.
2763 nil Don't force a record
2764 time Record a time stamp
2765 note Prompt for a note and add it with template `org-log-note-headings'
2767 This option can also be set with on a per-file-basis with
2769 #+STARTUP: nologrepeat
2770 #+STARTUP: logrepeat
2771 #+STARTUP: lognoterepeat
2773 You can have local logging settings for a subtree by setting the LOGGING
2774 property to one or more of these keywords."
2775 :group 'org-todo
2776 :group 'org-progress
2777 :type '(choice
2778 (const :tag "Don't force a record" nil)
2779 (const :tag "Force recording the DONE state" time)
2780 (const :tag "Force recording a note with the DONE state" note)))
2783 (defgroup org-priorities nil
2784 "Priorities in Org-mode."
2785 :tag "Org Priorities"
2786 :group 'org-todo)
2788 (defcustom org-enable-priority-commands t
2789 "Non-nil means priority commands are active.
2790 When nil, these commands will be disabled, so that you never accidentally
2791 set a priority."
2792 :group 'org-priorities
2793 :type 'boolean)
2795 (defcustom org-highest-priority ?A
2796 "The highest priority of TODO items. A character like ?A, ?B etc.
2797 Must have a smaller ASCII number than `org-lowest-priority'."
2798 :group 'org-priorities
2799 :type 'character)
2801 (defcustom org-lowest-priority ?C
2802 "The lowest priority of TODO items. A character like ?A, ?B etc.
2803 Must have a larger ASCII number than `org-highest-priority'."
2804 :group 'org-priorities
2805 :type 'character)
2807 (defcustom org-default-priority ?B
2808 "The default priority of TODO items.
2809 This is the priority an item gets if no explicit priority is given.
2810 When starting to cycle on an empty priority the first step in the cycle
2811 depends on `org-priority-start-cycle-with-default'. The resulting first
2812 step priority must not exceed the range from `org-highest-priority' to
2813 `org-lowest-priority' which means that `org-default-priority' has to be
2814 in this range exclusive or inclusive the range boundaries. Else the
2815 first step refuses to set the default and the second will fall back
2816 to (depending on the command used) the highest or lowest priority."
2817 :group 'org-priorities
2818 :type 'character)
2820 (defcustom org-priority-start-cycle-with-default t
2821 "Non-nil means start with default priority when starting to cycle.
2822 When this is nil, the first step in the cycle will be (depending on the
2823 command used) one higher or lower than the default priority.
2824 See also `org-default-priority'."
2825 :group 'org-priorities
2826 :type 'boolean)
2828 (defcustom org-get-priority-function nil
2829 "Function to extract the priority from a string.
2830 The string is normally the headline. If this is nil Org computes the
2831 priority from the priority cookie like [#A] in the headline. It returns
2832 an integer, increasing by 1000 for each priority level.
2833 The user can set a different function here, which should take a string
2834 as an argument and return the numeric priority."
2835 :group 'org-priorities
2836 :version "24.1"
2837 :type '(choice
2838 (const nil)
2839 (function)))
2841 (defgroup org-time nil
2842 "Options concerning time stamps and deadlines in Org-mode."
2843 :tag "Org Time"
2844 :group 'org)
2846 (defcustom org-insert-labeled-timestamps-at-point nil
2847 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2848 When nil, these labeled time stamps are forces into the second line of an
2849 entry, just after the headline. When scheduling from the global TODO list,
2850 the time stamp will always be forced into the second line."
2851 :group 'org-time
2852 :type 'boolean)
2854 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2855 "Formats for `format-time-string' which are used for time stamps.
2856 It is not recommended to change this constant.")
2858 (defcustom org-time-stamp-rounding-minutes '(0 5)
2859 "Number of minutes to round time stamps to.
2860 These are two values, the first applies when first creating a time stamp.
2861 The second applies when changing it with the commands `S-up' and `S-down'.
2862 When changing the time stamp, this means that it will change in steps
2863 of N minutes, as given by the second value.
2865 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2866 numbers should be factors of 60, so for example 5, 10, 15.
2868 When this is larger than 1, you can still force an exact time stamp by using
2869 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2870 and by using a prefix arg to `S-up/down' to specify the exact number
2871 of minutes to shift."
2872 :group 'org-time
2873 :get #'(lambda (var) ; Make sure both elements are there
2874 (if (integerp (default-value var))
2875 (list (default-value var) 5)
2876 (default-value var)))
2877 :type '(list
2878 (integer :tag "when inserting times")
2879 (integer :tag "when modifying times")))
2881 ;; Normalize old customizations of this variable.
2882 (when (integerp org-time-stamp-rounding-minutes)
2883 (setq org-time-stamp-rounding-minutes
2884 (list org-time-stamp-rounding-minutes
2885 org-time-stamp-rounding-minutes)))
2887 (defcustom org-display-custom-times nil
2888 "Non-nil means overlay custom formats over all time stamps.
2889 The formats are defined through the variable `org-time-stamp-custom-formats'.
2890 To turn this on on a per-file basis, insert anywhere in the file:
2891 #+STARTUP: customtime"
2892 :group 'org-time
2893 :set 'set-default
2894 :type 'sexp)
2895 (make-variable-buffer-local 'org-display-custom-times)
2897 (defcustom org-time-stamp-custom-formats
2898 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2899 "Custom formats for time stamps. See `format-time-string' for the syntax.
2900 These are overlaid over the default ISO format if the variable
2901 `org-display-custom-times' is set. Time like %H:%M should be at the
2902 end of the second format. The custom formats are also honored by export
2903 commands, if custom time display is turned on at the time of export."
2904 :group 'org-time
2905 :type 'sexp)
2907 (defun org-time-stamp-format (&optional long inactive)
2908 "Get the right format for a time string."
2909 (let ((f (if long (cdr org-time-stamp-formats)
2910 (car org-time-stamp-formats))))
2911 (if inactive
2912 (concat "[" (substring f 1 -1) "]")
2913 f)))
2915 (defcustom org-time-clocksum-format
2916 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2917 "The format string used when creating CLOCKSUM lines.
2918 This is also used when Org mode generates a time duration.
2920 The value can be a single format string containing two
2921 %-sequences, which will be filled with the number of hours and
2922 minutes in that order.
2924 Alternatively, the value can be a plist associating any of the
2925 keys :years, :months, :weeks, :days, :hours or :minutes with
2926 format strings. The time duration is formatted using only the
2927 time components that are needed and concatenating the results.
2928 If a time unit in absent, it falls back to the next smallest
2929 unit.
2931 The keys :require-years, :require-months, :require-days,
2932 :require-weeks, :require-hours, :require-minutes are also
2933 meaningful. A non-nil value for these keys indicates that the
2934 corresponding time component should always be included, even if
2935 its value is 0.
2938 For example,
2940 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2941 :require-minutes t)
2943 means durations longer than a day will be expressed in days,
2944 hours and minutes, and durations less than a day will always be
2945 expressed in hours and minutes (even for durations less than an
2946 hour).
2948 The value
2950 \(:days \"%dd\" :minutes \"%dm\")
2952 means durations longer than a day will be expressed in days and
2953 minutes, and durations less than a day will be expressed entirely
2954 in minutes (even for durations longer than an hour)."
2955 :group 'org-time
2956 :group 'org-clock
2957 :version "24.4"
2958 :package-version '(Org . "8.0")
2959 :type '(choice (string :tag "Format string")
2960 (set :tag "Plist"
2961 (group :inline t (const :tag "Years" :years)
2962 (string :tag "Format string"))
2963 (group :inline t
2964 (const :tag "Always show years" :require-years)
2965 (const t))
2966 (group :inline t (const :tag "Months" :months)
2967 (string :tag "Format string"))
2968 (group :inline t
2969 (const :tag "Always show months" :require-months)
2970 (const t))
2971 (group :inline t (const :tag "Weeks" :weeks)
2972 (string :tag "Format string"))
2973 (group :inline t
2974 (const :tag "Always show weeks" :require-weeks)
2975 (const t))
2976 (group :inline t (const :tag "Days" :days)
2977 (string :tag "Format string"))
2978 (group :inline t
2979 (const :tag "Always show days" :require-days)
2980 (const t))
2981 (group :inline t (const :tag "Hours" :hours)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show hours" :require-hours)
2985 (const t))
2986 (group :inline t (const :tag "Minutes" :minutes)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show minutes" :require-minutes)
2990 (const t)))))
2992 (defcustom org-time-clocksum-use-fractional nil
2993 "When non-nil, \\[org-clock-display] uses fractional times.
2994 See `org-time-clocksum-format' for more on time clock formats."
2995 :group 'org-time
2996 :group 'org-clock
2997 :version "24.3"
2998 :type 'boolean)
3000 (defcustom org-time-clocksum-use-effort-durations nil
3001 "When non-nil, \\[org-clock-display] uses effort durations.
3002 E.g. by default, one day is considered to be a 8 hours effort,
3003 so a task that has been clocked for 16 hours will be displayed
3004 as during 2 days in the clock display or in the clocktable.
3006 See `org-effort-durations' on how to set effort durations
3007 and `org-time-clocksum-format' for more on time clock formats."
3008 :group 'org-time
3009 :group 'org-clock
3010 :version "24.4"
3011 :package-version '(Org . "8.0")
3012 :type 'boolean)
3014 (defcustom org-time-clocksum-fractional-format "%.2f"
3015 "The format string used when creating CLOCKSUM lines,
3016 or when Org mode generates a time duration, if
3017 `org-time-clocksum-use-fractional' is enabled.
3019 The value can be a single format string containing one
3020 %-sequence, which will be filled with the number of hours as
3021 a float.
3023 Alternatively, the value can be a plist associating any of the
3024 keys :years, :months, :weeks, :days, :hours or :minutes with
3025 a format string. The time duration is formatted using the
3026 largest time unit which gives a non-zero integer part. If all
3027 specified formats have zero integer part, the smallest time unit
3028 is used."
3029 :group 'org-time
3030 :type '(choice (string :tag "Format string")
3031 (set (group :inline t (const :tag "Years" :years)
3032 (string :tag "Format string"))
3033 (group :inline t (const :tag "Months" :months)
3034 (string :tag "Format string"))
3035 (group :inline t (const :tag "Weeks" :weeks)
3036 (string :tag "Format string"))
3037 (group :inline t (const :tag "Days" :days)
3038 (string :tag "Format string"))
3039 (group :inline t (const :tag "Hours" :hours)
3040 (string :tag "Format string"))
3041 (group :inline t (const :tag "Minutes" :minutes)
3042 (string :tag "Format string")))))
3044 (defcustom org-deadline-warning-days 14
3045 "Number of days before expiration during which a deadline becomes active.
3046 This variable governs the display in sparse trees and in the agenda.
3047 When 0 or negative, it means use this number (the absolute value of it)
3048 even if a deadline has a different individual lead time specified.
3050 Custom commands can set this variable in the options section."
3051 :group 'org-time
3052 :group 'org-agenda-daily/weekly
3053 :type 'integer)
3055 (defcustom org-scheduled-delay-days 0
3056 "Number of days before a scheduled item becomes active.
3057 This variable governs the display in sparse trees and in the agenda.
3058 The default value (i.e. 0) means: don't delay scheduled item.
3059 When negative, it means use this number (the absolute value of it)
3060 even if a scheduled item has a different individual delay time
3061 specified.
3063 Custom commands can set this variable in the options section."
3064 :group 'org-time
3065 :group 'org-agenda-daily/weekly
3066 :version "24.4"
3067 :package-version '(Org . "8.0")
3068 :type 'integer)
3070 (defcustom org-read-date-prefer-future t
3071 "Non-nil means assume future for incomplete date input from user.
3072 This affects the following situations:
3073 1. The user gives a month but not a year.
3074 For example, if it is April and you enter \"feb 2\", this will be read
3075 as Feb 2, *next* year. \"May 5\", however, will be this year.
3076 2. The user gives a day, but no month.
3077 For example, if today is the 15th, and you enter \"3\", Org-mode will
3078 read this as the third of *next* month. However, if you enter \"17\",
3079 it will be considered as *this* month.
3081 If you set this variable to the symbol `time', then also the following
3082 will work:
3084 3. If the user gives a time.
3085 If the time is before now, it will be interpreted as tomorrow.
3087 Currently none of this works for ISO week specifications.
3089 When this option is nil, the current day, month and year will always be
3090 used as defaults.
3092 See also `org-agenda-jump-prefer-future'."
3093 :group 'org-time
3094 :type '(choice
3095 (const :tag "Never" nil)
3096 (const :tag "Check month and day" t)
3097 (const :tag "Check month, day, and time" time)))
3099 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3100 "Should the agenda jump command prefer the future for incomplete dates?
3101 The default is to do the same as configured in `org-read-date-prefer-future'.
3102 But you can also set a deviating value here.
3103 This may t or nil, or the symbol `org-read-date-prefer-future'."
3104 :group 'org-agenda
3105 :group 'org-time
3106 :version "24.1"
3107 :type '(choice
3108 (const :tag "Use org-read-date-prefer-future"
3109 org-read-date-prefer-future)
3110 (const :tag "Never" nil)
3111 (const :tag "Always" t)))
3113 (defcustom org-read-date-force-compatible-dates t
3114 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3116 Depending on the system Emacs is running on, certain dates cannot
3117 be represented with the type used internally to represent time.
3118 Dates between 1970-1-1 and 2038-1-1 can always be represented
3119 correctly. Some systems allow for earlier dates, some for later,
3120 some for both. One way to find out it to insert any date into an
3121 Org buffer, putting the cursor on the year and hitting S-up and
3122 S-down to test the range.
3124 When this variable is set to t, the date/time prompt will not let
3125 you specify dates outside the 1970-2037 range, so it is certain that
3126 these dates will work in whatever version of Emacs you are
3127 running, and also that you can move a file from one Emacs implementation
3128 to another. WHenever Org is forcing the year for you, it will display
3129 a message and beep.
3131 When this variable is nil, Org will check if the date is
3132 representable in the specific Emacs implementation you are using.
3133 If not, it will force a year, usually the current year, and beep
3134 to remind you. Currently this setting is not recommended because
3135 the likelihood that you will open your Org files in an Emacs that
3136 has limited date range is not negligible.
3138 A workaround for this problem is to use diary sexp dates for time
3139 stamps outside of this range."
3140 :group 'org-time
3141 :version "24.1"
3142 :type 'boolean)
3144 (defcustom org-read-date-display-live t
3145 "Non-nil means display current interpretation of date prompt live.
3146 This display will be in an overlay, in the minibuffer."
3147 :group 'org-time
3148 :type 'boolean)
3150 (defcustom org-read-date-popup-calendar t
3151 "Non-nil means pop up a calendar when prompting for a date.
3152 In the calendar, the date can be selected with mouse-1. However, the
3153 minibuffer will also be active, and you can simply enter the date as well.
3154 When nil, only the minibuffer will be available."
3155 :group 'org-time
3156 :type 'boolean)
3157 (org-defvaralias 'org-popup-calendar-for-date-prompt
3158 'org-read-date-popup-calendar)
3160 (make-obsolete-variable
3161 'org-read-date-minibuffer-setup-hook
3162 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3163 (defcustom org-read-date-minibuffer-setup-hook nil
3164 "Hook to be used to set up keys for the date/time interface.
3165 Add key definitions to `minibuffer-local-map', which will be a
3166 temporary copy.
3168 WARNING: This option is obsolete, you should use
3169 `org-read-date-minibuffer-local-map' to set up keys."
3170 :group 'org-time
3171 :type 'hook)
3173 (defcustom org-extend-today-until 0
3174 "The hour when your day really ends. Must be an integer.
3175 This has influence for the following applications:
3176 - When switching the agenda to \"today\". It it is still earlier than
3177 the time given here, the day recognized as TODAY is actually yesterday.
3178 - When a date is read from the user and it is still before the time given
3179 here, the current date and time will be assumed to be yesterday, 23:59.
3180 Also, timestamps inserted in capture templates follow this rule.
3182 IMPORTANT: This is a feature whose implementation is and likely will
3183 remain incomplete. Really, it is only here because past midnight seems to
3184 be the favorite working time of John Wiegley :-)"
3185 :group 'org-time
3186 :type 'integer)
3188 (defcustom org-use-effective-time nil
3189 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3190 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3191 \"effective time\" of any timestamps between midnight and 8am will be
3192 23:59 of the previous day."
3193 :group 'org-time
3194 :version "24.1"
3195 :type 'boolean)
3197 (defcustom org-use-last-clock-out-time-as-effective-time nil
3198 "When non-nil, use the last clock out time for `org-todo'.
3199 Note that this option has precedence over the combined use of
3200 `org-use-effective-time' and `org-extend-today-until'."
3201 :group 'org-time
3202 :version "24.4"
3203 :package-version '(Org . "8.0")
3204 :type 'boolean)
3206 (defcustom org-edit-timestamp-down-means-later nil
3207 "Non-nil means S-down will increase the time in a time stamp.
3208 When nil, S-up will increase."
3209 :group 'org-time
3210 :type 'boolean)
3212 (defcustom org-calendar-follow-timestamp-change t
3213 "Non-nil means make the calendar window follow timestamp changes.
3214 When a timestamp is modified and the calendar window is visible, it will be
3215 moved to the new date."
3216 :group 'org-time
3217 :type 'boolean)
3219 (defgroup org-tags nil
3220 "Options concerning tags in Org-mode."
3221 :tag "Org Tags"
3222 :group 'org)
3224 (defcustom org-tag-alist nil
3225 "List of tags allowed in Org-mode files.
3226 When this list is nil, Org-mode will base TAG input on what is already in the
3227 buffer.
3228 The value of this variable is an alist, the car of each entry must be a
3229 keyword as a string, the cdr may be a character that is used to select
3230 that tag through the fast-tag-selection interface.
3231 See the manual for details."
3232 :group 'org-tags
3233 :type '(repeat
3234 (choice
3235 (cons (string :tag "Tag name")
3236 (character :tag "Access char"))
3237 (list :tag "Start radio group"
3238 (const :startgroup)
3239 (option (string :tag "Group description")))
3240 (list :tag "Group tags delimiter"
3241 (const :grouptags))
3242 (list :tag "End radio group"
3243 (const :endgroup)
3244 (option (string :tag "Group description")))
3245 (const :tag "New line" (:newline)))))
3247 (defcustom org-tag-persistent-alist nil
3248 "List of tags that will always appear in all Org-mode files.
3249 This is in addition to any in buffer settings or customizations
3250 of `org-tag-alist'.
3251 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3252 The value of this variable is an alist, the car of each entry must be a
3253 keyword as a string, the cdr may be a character that is used to select
3254 that tag through the fast-tag-selection interface.
3255 See the manual for details.
3256 To disable these tags on a per-file basis, insert anywhere in the file:
3257 #+STARTUP: noptag"
3258 :group 'org-tags
3259 :type '(repeat
3260 (choice
3261 (cons (string :tag "Tag name")
3262 (character :tag "Access char"))
3263 (const :tag "Start radio group" (:startgroup))
3264 (const :tag "Group tags delimiter" (:grouptags))
3265 (const :tag "End radio group" (:endgroup))
3266 (const :tag "New line" (:newline)))))
3268 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3269 "If non-nil, always offer completion for all tags of all agenda files.
3270 Instead of customizing this variable directly, you might want to
3271 set it locally for capture buffers, because there no list of
3272 tags in that file can be created dynamically (there are none).
3274 (add-hook 'org-capture-mode-hook
3275 (lambda ()
3276 (set (make-local-variable
3277 'org-complete-tags-always-offer-all-agenda-tags)
3278 t)))"
3279 :group 'org-tags
3280 :version "24.1"
3281 :type 'boolean)
3283 (defvar org-file-tags nil
3284 "List of tags that can be inherited by all entries in the file.
3285 The tags will be inherited if the variable `org-use-tag-inheritance'
3286 says they should be.
3287 This variable is populated from #+FILETAGS lines.")
3289 (defcustom org-use-fast-tag-selection 'auto
3290 "Non-nil means use fast tag selection scheme.
3291 This is a special interface to select and deselect tags with single keys.
3292 When nil, fast selection is never used.
3293 When the symbol `auto', fast selection is used if and only if selection
3294 characters for tags have been configured, either through the variable
3295 `org-tag-alist' or through a #+TAGS line in the buffer.
3296 When t, fast selection is always used and selection keys are assigned
3297 automatically if necessary."
3298 :group 'org-tags
3299 :type '(choice
3300 (const :tag "Always" t)
3301 (const :tag "Never" nil)
3302 (const :tag "When selection characters are configured" auto)))
3304 (defcustom org-fast-tag-selection-single-key nil
3305 "Non-nil means fast tag selection exits after first change.
3306 When nil, you have to press RET to exit it.
3307 During fast tag selection, you can toggle this flag with `C-c'.
3308 This variable can also have the value `expert'. In this case, the window
3309 displaying the tags menu is not even shown, until you press C-c again."
3310 :group 'org-tags
3311 :type '(choice
3312 (const :tag "No" nil)
3313 (const :tag "Yes" t)
3314 (const :tag "Expert" expert)))
3316 (defvar org-fast-tag-selection-include-todo nil
3317 "Non-nil means fast tags selection interface will also offer TODO states.
3318 This is an undocumented feature, you should not rely on it.")
3320 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3321 "The column to which tags should be indented in a headline.
3322 If this number is positive, it specifies the column. If it is negative,
3323 it means that the tags should be flushright to that column. For example,
3324 -80 works well for a normal 80 character screen.
3325 When 0, place tags directly after headline text, with only one space in
3326 between."
3327 :group 'org-tags
3328 :type 'integer)
3330 (defcustom org-auto-align-tags t
3331 "Non-nil keeps tags aligned when modifying headlines.
3332 Some operations (i.e. demoting) change the length of a headline and
3333 therefore shift the tags around. With this option turned on, after
3334 each such operation the tags are again aligned to `org-tags-column'."
3335 :group 'org-tags
3336 :type 'boolean)
3338 (defcustom org-use-tag-inheritance t
3339 "Non-nil means tags in levels apply also for sublevels.
3340 When nil, only the tags directly given in a specific line apply there.
3341 This may also be a list of tags that should be inherited, or a regexp that
3342 matches tags that should be inherited. Additional control is possible
3343 with the variable `org-tags-exclude-from-inheritance' which gives an
3344 explicit list of tags to be excluded from inheritance, even if the value of
3345 `org-use-tag-inheritance' would select it for inheritance.
3347 If this option is t, a match early-on in a tree can lead to a large
3348 number of matches in the subtree when constructing the agenda or creating
3349 a sparse tree. If you only want to see the first match in a tree during
3350 a search, check out the variable `org-tags-match-list-sublevels'."
3351 :group 'org-tags
3352 :type '(choice
3353 (const :tag "Not" nil)
3354 (const :tag "Always" t)
3355 (repeat :tag "Specific tags" (string :tag "Tag"))
3356 (regexp :tag "Tags matched by regexp")))
3358 (defcustom org-tags-exclude-from-inheritance nil
3359 "List of tags that should never be inherited.
3360 This is a way to exclude a few tags from inheritance. For way to do
3361 the opposite, to actively allow inheritance for selected tags,
3362 see the variable `org-use-tag-inheritance'."
3363 :group 'org-tags
3364 :type '(repeat (string :tag "Tag")))
3366 (defun org-tag-inherit-p (tag)
3367 "Check if TAG is one that should be inherited."
3368 (cond
3369 ((member tag org-tags-exclude-from-inheritance) nil)
3370 ((eq org-use-tag-inheritance t) t)
3371 ((not org-use-tag-inheritance) nil)
3372 ((stringp org-use-tag-inheritance)
3373 (string-match org-use-tag-inheritance tag))
3374 ((listp org-use-tag-inheritance)
3375 (member tag org-use-tag-inheritance))
3376 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3378 (defcustom org-tags-match-list-sublevels t
3379 "Non-nil means list also sublevels of headlines matching a search.
3380 This variable applies to tags/property searches, and also to stuck
3381 projects because this search is based on a tags match as well.
3383 When set to the symbol `indented', sublevels are indented with
3384 leading dots.
3386 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3387 the sublevels of a headline matching a tag search often also match
3388 the same search. Listing all of them can create very long lists.
3389 Setting this variable to nil causes subtrees of a match to be skipped.
3391 This variable is semi-obsolete and probably should always be true. It
3392 is better to limit inheritance to certain tags using the variables
3393 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3394 :group 'org-tags
3395 :type '(choice
3396 (const :tag "No, don't list them" nil)
3397 (const :tag "Yes, do list them" t)
3398 (const :tag "List them, indented with leading dots" indented)))
3400 (defcustom org-tags-sort-function nil
3401 "When set, tags are sorted using this function as a comparator."
3402 :group 'org-tags
3403 :type '(choice
3404 (const :tag "No sorting" nil)
3405 (const :tag "Alphabetical" string<)
3406 (const :tag "Reverse alphabetical" string>)
3407 (function :tag "Custom function" nil)))
3409 (defvar org-tags-history nil
3410 "History of minibuffer reads for tags.")
3411 (defvar org-last-tags-completion-table nil
3412 "The last used completion table for tags.")
3413 (defvar org-after-tags-change-hook nil
3414 "Hook that is run after the tags in a line have changed.")
3416 (defgroup org-properties nil
3417 "Options concerning properties in Org-mode."
3418 :tag "Org Properties"
3419 :group 'org)
3421 (defcustom org-property-format "%-10s %s"
3422 "How property key/value pairs should be formatted by `indent-line'.
3423 When `indent-line' hits a property definition, it will format the line
3424 according to this format, mainly to make sure that the values are
3425 lined-up with respect to each other."
3426 :group 'org-properties
3427 :type 'string)
3429 (defcustom org-properties-postprocess-alist nil
3430 "Alist of properties and functions to adjust inserted values.
3431 Elements of this alist must be of the form
3433 ([string] [function])
3435 where [string] must be a property name and [function] must be a
3436 lambda expression: this lambda expression must take one argument,
3437 the value to adjust, and return the new value as a string.
3439 For example, this element will allow the property \"Remaining\"
3440 to be updated wrt the relation between the \"Effort\" property
3441 and the clock summary:
3443 ((\"Remaining\" (lambda(value)
3444 (let ((clocksum (org-clock-sum-current-item))
3445 (effort (org-duration-string-to-minutes
3446 (org-entry-get (point) \"Effort\"))))
3447 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3448 :group 'org-properties
3449 :version "24.1"
3450 :type '(alist :key-type (string :tag "Property")
3451 :value-type (function :tag "Function")))
3453 (defcustom org-use-property-inheritance nil
3454 "Non-nil means properties apply also for sublevels.
3456 This setting is chiefly used during property searches. Turning it on can
3457 cause significant overhead when doing a search, which is why it is not
3458 on by default.
3460 When nil, only the properties directly given in the current entry count.
3461 When t, every property is inherited. The value may also be a list of
3462 properties that should have inheritance, or a regular expression matching
3463 properties that should be inherited.
3465 However, note that some special properties use inheritance under special
3466 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3467 and the properties ending in \"_ALL\" when they are used as descriptor
3468 for valid values of a property.
3470 Note for programmers:
3471 When querying an entry with `org-entry-get', you can control if inheritance
3472 should be used. By default, `org-entry-get' looks only at the local
3473 properties. You can request inheritance by setting the inherit argument
3474 to t (to force inheritance) or to `selective' (to respect the setting
3475 in this variable)."
3476 :group 'org-properties
3477 :type '(choice
3478 (const :tag "Not" nil)
3479 (const :tag "Always" t)
3480 (repeat :tag "Specific properties" (string :tag "Property"))
3481 (regexp :tag "Properties matched by regexp")))
3483 (defun org-property-inherit-p (property)
3484 "Check if PROPERTY is one that should be inherited."
3485 (cond
3486 ((eq org-use-property-inheritance t) t)
3487 ((not org-use-property-inheritance) nil)
3488 ((stringp org-use-property-inheritance)
3489 (string-match org-use-property-inheritance property))
3490 ((listp org-use-property-inheritance)
3491 (member property org-use-property-inheritance))
3492 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3494 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3495 "The default column format, if no other format has been defined.
3496 This variable can be set on the per-file basis by inserting a line
3498 #+COLUMNS: %25ITEM ....."
3499 :group 'org-properties
3500 :type 'string)
3502 (defcustom org-columns-ellipses ".."
3503 "The ellipses to be used when a field in column view is truncated.
3504 When this is the empty string, as many characters as possible are shown,
3505 but then there will be no visual indication that the field has been truncated.
3506 When this is a string of length N, the last N characters of a truncated
3507 field are replaced by this string. If the column is narrower than the
3508 ellipses string, only part of the ellipses string will be shown."
3509 :group 'org-properties
3510 :type 'string)
3512 (defcustom org-columns-modify-value-for-display-function nil
3513 "Function that modifies values for display in column view.
3514 For example, it can be used to cut out a certain part from a time stamp.
3515 The function must take 2 arguments:
3517 column-title The title of the column (*not* the property name)
3518 value The value that should be modified.
3520 The function should return the value that should be displayed,
3521 or nil if the normal value should be used."
3522 :group 'org-properties
3523 :type '(choice (const nil) (function)))
3525 (defcustom org-effort-property "Effort"
3526 "The property that is being used to keep track of effort estimates.
3527 Effort estimates given in this property need to have the format H:MM."
3528 :group 'org-properties
3529 :group 'org-progress
3530 :type '(string :tag "Property"))
3532 (defconst org-global-properties-fixed
3533 '(("VISIBILITY_ALL" . "folded children content all")
3534 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3535 "List of property/value pairs that can be inherited by any entry.
3537 These are fixed values, for the preset properties. The user variable
3538 that can be used to add to this list is `org-global-properties'.
3540 The entries in this list are cons cells where the car is a property
3541 name and cdr is a string with the value. If the value represents
3542 multiple items like an \"_ALL\" property, separate the items by
3543 spaces.")
3545 (defcustom org-global-properties nil
3546 "List of property/value pairs that can be inherited by any entry.
3548 This list will be combined with the constant `org-global-properties-fixed'.
3550 The entries in this list are cons cells where the car is a property
3551 name and cdr is a string with the value.
3553 You can set buffer-local values for the same purpose in the variable
3554 `org-file-properties' this by adding lines like
3556 #+PROPERTY: NAME VALUE"
3557 :group 'org-properties
3558 :type '(repeat
3559 (cons (string :tag "Property")
3560 (string :tag "Value"))))
3562 (defvar org-file-properties nil
3563 "List of property/value pairs that can be inherited by any entry.
3564 Valid for the current buffer.
3565 This variable is populated from #+PROPERTY lines.")
3566 (make-variable-buffer-local 'org-file-properties)
3568 (defgroup org-agenda nil
3569 "Options concerning agenda views in Org-mode."
3570 :tag "Org Agenda"
3571 :group 'org)
3573 (defvar org-category nil
3574 "Variable used by org files to set a category for agenda display.
3575 Such files should use a file variable to set it, for example
3577 # -*- mode: org; org-category: \"ELisp\"
3579 or contain a special line
3581 #+CATEGORY: ELisp
3583 If the file does not specify a category, then file's base name
3584 is used instead.")
3585 (make-variable-buffer-local 'org-category)
3586 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3588 (defcustom org-agenda-files nil
3589 "The files to be used for agenda display.
3590 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3591 \\[org-remove-file]. You can also use customize to edit the list.
3593 If an entry is a directory, all files in that directory that are matched by
3594 `org-agenda-file-regexp' will be part of the file list.
3596 If the value of the variable is not a list but a single file name, then
3597 the list of agenda files is actually stored and maintained in that file, one
3598 agenda file per line. In this file paths can be given relative to
3599 `org-directory'. Tilde expansion and environment variable substitution
3600 are also made."
3601 :group 'org-agenda
3602 :type '(choice
3603 (repeat :tag "List of files and directories" file)
3604 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3606 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3607 "Regular expression to match files for `org-agenda-files'.
3608 If any element in the list in that variable contains a directory instead
3609 of a normal file, all files in that directory that are matched by this
3610 regular expression will be included."
3611 :group 'org-agenda
3612 :type 'regexp)
3614 (defcustom org-agenda-text-search-extra-files nil
3615 "List of extra files to be searched by text search commands.
3616 These files will be searched in addition to the agenda files by the
3617 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3618 Note that these files will only be searched for text search commands,
3619 not for the other agenda views like todo lists, tag searches or the weekly
3620 agenda. This variable is intended to list notes and possibly archive files
3621 that should also be searched by these two commands.
3622 In fact, if the first element in the list is the symbol `agenda-archives',
3623 then all archive files of all agenda files will be added to the search
3624 scope."
3625 :group 'org-agenda
3626 :type '(set :greedy t
3627 (const :tag "Agenda Archives" agenda-archives)
3628 (repeat :inline t (file))))
3630 (org-defvaralias 'org-agenda-multi-occur-extra-files
3631 'org-agenda-text-search-extra-files)
3633 (defcustom org-agenda-skip-unavailable-files nil
3634 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3635 A nil value means to remove them, after a query, from the list."
3636 :group 'org-agenda
3637 :type 'boolean)
3639 (defcustom org-calendar-to-agenda-key [?c]
3640 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3641 The command `org-calendar-goto-agenda' will be bound to this key. The
3642 default is the character `c' because then `c' can be used to switch back and
3643 forth between agenda and calendar."
3644 :group 'org-agenda
3645 :type 'sexp)
3647 (defcustom org-calendar-insert-diary-entry-key [?i]
3648 "The key to be installed in `calendar-mode-map' for adding diary entries.
3649 This option is irrelevant until `org-agenda-diary-file' has been configured
3650 to point to an Org-mode file. When that is the case, the command
3651 `org-agenda-diary-entry' will be bound to the key given here, by default
3652 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3653 if you want to continue doing this, you need to change this to a different
3654 key."
3655 :group 'org-agenda
3656 :type 'sexp)
3658 (defcustom org-agenda-diary-file 'diary-file
3659 "File to which to add new entries with the `i' key in agenda and calendar.
3660 When this is the symbol `diary-file', the functionality in the Emacs
3661 calendar will be used to add entries to the `diary-file'. But when this
3662 points to a file, `org-agenda-diary-entry' will be used instead."
3663 :group 'org-agenda
3664 :type '(choice
3665 (const :tag "The standard Emacs diary file" diary-file)
3666 (file :tag "Special Org file diary entries")))
3668 (eval-after-load "calendar"
3669 '(progn
3670 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3671 'org-calendar-goto-agenda)
3672 (add-hook 'calendar-mode-hook
3673 (lambda ()
3674 (unless (eq org-agenda-diary-file 'diary-file)
3675 (define-key calendar-mode-map
3676 org-calendar-insert-diary-entry-key
3677 'org-agenda-diary-entry))))))
3679 (defgroup org-latex nil
3680 "Options for embedding LaTeX code into Org-mode."
3681 :tag "Org LaTeX"
3682 :group 'org)
3684 (defcustom org-format-latex-options
3685 '(:foreground default :background default :scale 1.0
3686 :html-foreground "Black" :html-background "Transparent"
3687 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3688 "Options for creating images from LaTeX fragments.
3689 This is a property list with the following properties:
3690 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3691 `default' means use the foreground of the default face.
3692 `auto' means use the foreground from the text face.
3693 :background the background color, or \"Transparent\".
3694 `default' means use the background of the default face.
3695 `auto' means use the background from the text face.
3696 :scale a scaling factor for the size of the images, to get more pixels
3697 :html-foreground, :html-background, :html-scale
3698 the same numbers for HTML export.
3699 :matchers a list indicating which matchers should be used to
3700 find LaTeX fragments. Valid members of this list are:
3701 \"begin\" find environments
3702 \"$1\" find single characters surrounded by $.$
3703 \"$\" find math expressions surrounded by $...$
3704 \"$$\" find math expressions surrounded by $$....$$
3705 \"\\(\" find math expressions surrounded by \\(...\\)
3706 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3707 :group 'org-latex
3708 :type 'plist)
3710 (defcustom org-format-latex-signal-error t
3711 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3712 When nil, just push out a message."
3713 :group 'org-latex
3714 :version "24.1"
3715 :type 'boolean)
3717 (defcustom org-latex-to-mathml-jar-file nil
3718 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3719 Use this to specify additional executable file say a jar file.
3721 When using MathToWeb as the converter, specify the full-path to
3722 your mathtoweb.jar file."
3723 :group 'org-latex
3724 :version "24.1"
3725 :type '(choice
3726 (const :tag "None" nil)
3727 (file :tag "JAR file" :must-match t)))
3729 (defcustom org-latex-to-mathml-convert-command nil
3730 "Command to convert LaTeX fragments to MathML.
3731 Replace format-specifiers in the command as noted below and use
3732 `shell-command' to convert LaTeX to MathML.
3733 %j: Executable file in fully expanded form as specified by
3734 `org-latex-to-mathml-jar-file'.
3735 %I: Input LaTeX file in fully expanded form
3736 %o: Output MathML file
3737 This command is used by `org-create-math-formula'.
3739 When using MathToWeb as the converter, set this to
3740 \"java -jar %j -unicode -force -df %o %I\"."
3741 :group 'org-latex
3742 :version "24.1"
3743 :type '(choice
3744 (const :tag "None" nil)
3745 (string :tag "\nShell command")))
3747 (defcustom org-latex-create-formula-image-program 'dvipng
3748 "Program to convert LaTeX fragments with.
3750 dvipng Process the LaTeX fragments to dvi file, then convert
3751 dvi files to png files using dvipng.
3752 This will also include processing of non-math environments.
3753 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3754 to convert pdf files to png files"
3755 :group 'org-latex
3756 :version "24.1"
3757 :type '(choice
3758 (const :tag "dvipng" dvipng)
3759 (const :tag "imagemagick" imagemagick)))
3761 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3762 "Path to store latex preview images.
3763 A relative path here creates many directories relative to the
3764 processed org files paths. An absolute path puts all preview
3765 images at the same place."
3766 :group 'org-latex
3767 :version "24.3"
3768 :type 'string)
3770 (defun org-format-latex-mathml-available-p ()
3771 "Return t if `org-latex-to-mathml-convert-command' is usable."
3772 (save-match-data
3773 (when (and (boundp 'org-latex-to-mathml-convert-command)
3774 org-latex-to-mathml-convert-command)
3775 (let ((executable (car (split-string
3776 org-latex-to-mathml-convert-command))))
3777 (when (executable-find executable)
3778 (if (string-match
3779 "%j" org-latex-to-mathml-convert-command)
3780 (file-readable-p org-latex-to-mathml-jar-file)
3781 t))))))
3783 (defcustom org-format-latex-header "\\documentclass{article}
3784 \\usepackage[usenames]{color}
3785 \[PACKAGES]
3786 \[DEFAULT-PACKAGES]
3787 \\pagestyle{empty} % do not remove
3788 % The settings below are copied from fullpage.sty
3789 \\setlength{\\textwidth}{\\paperwidth}
3790 \\addtolength{\\textwidth}{-3cm}
3791 \\setlength{\\oddsidemargin}{1.5cm}
3792 \\addtolength{\\oddsidemargin}{-2.54cm}
3793 \\setlength{\\evensidemargin}{\\oddsidemargin}
3794 \\setlength{\\textheight}{\\paperheight}
3795 \\addtolength{\\textheight}{-\\headheight}
3796 \\addtolength{\\textheight}{-\\headsep}
3797 \\addtolength{\\textheight}{-\\footskip}
3798 \\addtolength{\\textheight}{-3cm}
3799 \\setlength{\\topmargin}{1.5cm}
3800 \\addtolength{\\topmargin}{-2.54cm}"
3801 "The document header used for processing LaTeX fragments.
3802 It is imperative that this header make sure that no page number
3803 appears on the page. The package defined in the variables
3804 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3805 will either replace the placeholder \"[PACKAGES]\" in this
3806 header, or they will be appended."
3807 :group 'org-latex
3808 :type 'string)
3810 (defun org-set-packages-alist (var val)
3811 "Set the packages alist and make sure it has 3 elements per entry."
3812 (set var (mapcar (lambda (x)
3813 (if (and (consp x) (= (length x) 2))
3814 (list (car x) (nth 1 x) t)
3816 val)))
3818 (defun org-get-packages-alist (var)
3819 "Get the packages alist and make sure it has 3 elements per entry."
3820 (mapcar (lambda (x)
3821 (if (and (consp x) (= (length x) 2))
3822 (list (car x) (nth 1 x) t)
3824 (default-value var)))
3826 (defcustom org-latex-default-packages-alist
3827 '(("AUTO" "inputenc" t)
3828 ("T1" "fontenc" t)
3829 ("" "fixltx2e" nil)
3830 ("" "graphicx" t)
3831 ("" "longtable" nil)
3832 ("" "float" nil)
3833 ("" "wrapfig" nil)
3834 ("" "rotating" nil)
3835 ("normalem" "ulem" t)
3836 ("" "amsmath" t)
3837 ("" "textcomp" t)
3838 ("" "marvosym" t)
3839 ("" "wasysym" t)
3840 ("" "amssymb" t)
3841 ("" "hyperref" nil)
3842 "\\tolerance=1000")
3843 "Alist of default packages to be inserted in the header.
3845 Change this only if one of the packages here causes an
3846 incompatibility with another package you are using.
3848 The packages in this list are needed by one part or another of
3849 Org mode to function properly:
3851 - inputenc, fontenc: for basic font and character selection
3852 - fixltx2e: Important patches of LaTeX itself
3853 - graphicx: for including images
3854 - longtable: For multipage tables
3855 - float, wrapfig: for figure placement
3856 - rotating: for sideways figures and tables
3857 - ulem: for underline and strike-through
3858 - amsmath: for subscript and superscript and math environments
3859 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3860 for interpreting the entities in `org-entities'. You can skip
3861 some of these packages if you don't use any of their symbols.
3862 - hyperref: for cross references
3864 Therefore you should not modify this variable unless you know
3865 what you are doing. The one reason to change it anyway is that
3866 you might be loading some other package that conflicts with one
3867 of the default packages. Each cell is of the format
3868 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3869 the package also needs to be included when compiling LaTeX
3870 snippets into images for inclusion into non-LaTeX output."
3871 :group 'org-latex
3872 :group 'org-export-latex
3873 :set 'org-set-packages-alist
3874 :get 'org-get-packages-alist
3875 :version "24.1"
3876 :type '(repeat
3877 (choice
3878 (list :tag "options/package pair"
3879 (string :tag "options")
3880 (string :tag "package")
3881 (boolean :tag "Snippet"))
3882 (string :tag "A line of LaTeX"))))
3884 (defcustom org-latex-packages-alist nil
3885 "Alist of packages to be inserted in every LaTeX header.
3887 These will be inserted after `org-latex-default-packages-alist'.
3888 Each cell is of the format:
3890 \(\"options\" \"package\" snippet-flag)
3892 SNIPPET-FLAG, when t, indicates that this package is also needed
3893 when turning LaTeX snippets into images for inclusion into
3894 non-LaTeX output.
3896 Make sure that you only list packages here which:
3898 - you want in every file
3899 - do not conflict with the setup in `org-format-latex-header'.
3900 - do not conflict with the default packages in
3901 `org-latex-default-packages-alist'."
3902 :group 'org-latex
3903 :group 'org-export-latex
3904 :set 'org-set-packages-alist
3905 :get 'org-get-packages-alist
3906 :type '(repeat
3907 (choice
3908 (list :tag "options/package pair"
3909 (string :tag "options")
3910 (string :tag "package")
3911 (boolean :tag "Snippet"))
3912 (string :tag "A line of LaTeX"))))
3914 (defgroup org-appearance nil
3915 "Settings for Org-mode appearance."
3916 :tag "Org Appearance"
3917 :group 'org)
3919 (defcustom org-level-color-stars-only nil
3920 "Non-nil means fontify only the stars in each headline.
3921 When nil, the entire headline is fontified.
3922 Changing it requires restart of `font-lock-mode' to become effective
3923 also in regions already fontified."
3924 :group 'org-appearance
3925 :type 'boolean)
3927 (defcustom org-hide-leading-stars nil
3928 "Non-nil means hide the first N-1 stars in a headline.
3929 This works by using the face `org-hide' for these stars. This
3930 face is white for a light background, and black for a dark
3931 background. You may have to customize the face `org-hide' to
3932 make this work.
3933 Changing it requires restart of `font-lock-mode' to become effective
3934 also in regions already fontified.
3935 You may also set this on a per-file basis by adding one of the following
3936 lines to the buffer:
3938 #+STARTUP: hidestars
3939 #+STARTUP: showstars"
3940 :group 'org-appearance
3941 :type 'boolean)
3943 (defcustom org-hidden-keywords nil
3944 "List of symbols corresponding to keywords to be hidden the org buffer.
3945 For example, a value '(title) for this list will make the document's title
3946 appear in the buffer without the initial #+TITLE: keyword."
3947 :group 'org-appearance
3948 :version "24.1"
3949 :type '(set (const :tag "#+AUTHOR" author)
3950 (const :tag "#+DATE" date)
3951 (const :tag "#+EMAIL" email)
3952 (const :tag "#+TITLE" title)))
3954 (defcustom org-custom-properties nil
3955 "List of properties (as strings) with a special meaning.
3956 The default use of these custom properties is to let the user
3957 hide them with `org-toggle-custom-properties-visibility'."
3958 :group 'org-properties
3959 :group 'org-appearance
3960 :version "24.3"
3961 :type '(repeat (string :tag "Property Name")))
3963 (defcustom org-fontify-done-headline nil
3964 "Non-nil means change the face of a headline if it is marked DONE.
3965 Normally, only the TODO/DONE keyword indicates the state of a headline.
3966 When this is non-nil, the headline after the keyword is set to the
3967 `org-headline-done' as an additional indication."
3968 :group 'org-appearance
3969 :type 'boolean)
3971 (defcustom org-fontify-emphasized-text t
3972 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3973 Changing this variable requires a restart of Emacs to take effect."
3974 :group 'org-appearance
3975 :type 'boolean)
3977 (defcustom org-fontify-whole-heading-line nil
3978 "Non-nil means fontify the whole line for headings.
3979 This is useful when setting a background color for the
3980 org-level-* faces."
3981 :group 'org-appearance
3982 :type 'boolean)
3984 (defcustom org-highlight-latex-and-related nil
3985 "Non-nil means highlight LaTeX related syntax in the buffer.
3986 When non nil, the value should be a list containing any of the
3987 following symbols:
3988 `latex' Highlight LaTeX snippets and environments.
3989 `script' Highlight subscript and superscript.
3990 `entities' Highlight entities."
3991 :group 'org-appearance
3992 :version "24.4"
3993 :package-version '(Org . "8.0")
3994 :type '(choice
3995 (const :tag "No highlighting" nil)
3996 (set :greedy t :tag "Highlight"
3997 (const :tag "LaTeX snippets and environments" latex)
3998 (const :tag "Subscript and superscript" script)
3999 (const :tag "Entities" entities))))
4001 (defcustom org-hide-emphasis-markers nil
4002 "Non-nil mean font-lock should hide the emphasis marker characters."
4003 :group 'org-appearance
4004 :type 'boolean)
4006 (defcustom org-pretty-entities nil
4007 "Non-nil means show entities as UTF8 characters.
4008 When nil, the \\name form remains in the buffer."
4009 :group 'org-appearance
4010 :version "24.1"
4011 :type 'boolean)
4013 (defcustom org-pretty-entities-include-sub-superscripts t
4014 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4015 :group 'org-appearance
4016 :version "24.1"
4017 :type 'boolean)
4019 (defvar org-emph-re nil
4020 "Regular expression for matching emphasis.
4021 After a match, the match groups contain these elements:
4022 0 The match of the full regular expression, including the characters
4023 before and after the proper match
4024 1 The character before the proper match, or empty at beginning of line
4025 2 The proper match, including the leading and trailing markers
4026 3 The leading marker like * or /, indicating the type of highlighting
4027 4 The text between the emphasis markers, not including the markers
4028 5 The character after the match, empty at the end of a line")
4029 (defvar org-verbatim-re nil
4030 "Regular expression for matching verbatim text.")
4031 (defvar org-emphasis-regexp-components) ; defined just below
4032 (defvar org-emphasis-alist) ; defined just below
4033 (defun org-set-emph-re (var val)
4034 "Set variable and compute the emphasis regular expression."
4035 (set var val)
4036 (when (and (boundp 'org-emphasis-alist)
4037 (boundp 'org-emphasis-regexp-components)
4038 org-emphasis-alist org-emphasis-regexp-components)
4039 (let* ((e org-emphasis-regexp-components)
4040 (pre (car e))
4041 (post (nth 1 e))
4042 (border (nth 2 e))
4043 (body (nth 3 e))
4044 (nl (nth 4 e))
4045 (body1 (concat body "*?"))
4046 (markers (mapconcat 'car org-emphasis-alist ""))
4047 (vmarkers (mapconcat
4048 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4049 org-emphasis-alist "")))
4050 ;; make sure special characters appear at the right position in the class
4051 (if (string-match "\\^" markers)
4052 (setq markers (concat (replace-match "" t t markers) "^")))
4053 (if (string-match "-" markers)
4054 (setq markers (concat (replace-match "" t t markers) "-")))
4055 (if (string-match "\\^" vmarkers)
4056 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4057 (if (string-match "-" vmarkers)
4058 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4059 (if (> nl 0)
4060 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4061 (int-to-string nl) "\\}")))
4062 ;; Make the regexp
4063 (setq org-emph-re
4064 (concat "\\([" pre "]\\|^\\)"
4065 "\\("
4066 "\\([" markers "]\\)"
4067 "\\("
4068 "[^" border "]\\|"
4069 "[^" border "]"
4070 body1
4071 "[^" border "]"
4072 "\\)"
4073 "\\3\\)"
4074 "\\([" post "]\\|$\\)"))
4075 (setq org-verbatim-re
4076 (concat "\\([" pre "]\\|^\\)"
4077 "\\("
4078 "\\([" vmarkers "]\\)"
4079 "\\("
4080 "[^" border "]\\|"
4081 "[^" border "]"
4082 body1
4083 "[^" border "]"
4084 "\\)"
4085 "\\3\\)"
4086 "\\([" post "]\\|$\\)")))))
4088 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4089 ;; set this option proved cumbersome. See this message/thread:
4090 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4091 (defvar org-emphasis-regexp-components
4092 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4093 "Components used to build the regular expression for emphasis.
4094 This is a list with five entries. Terminology: In an emphasis string
4095 like \" *strong word* \", we call the initial space PREMATCH, the final
4096 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4097 and \"trong wor\" is the body. The different components in this variable
4098 specify what is allowed/forbidden in each part:
4100 pre Chars allowed as prematch. Beginning of line will be allowed too.
4101 post Chars allowed as postmatch. End of line will be allowed too.
4102 border The chars *forbidden* as border characters.
4103 body-regexp A regexp like \".\" to match a body character. Don't use
4104 non-shy groups here, and don't allow newline here.
4105 newline The maximum number of newlines allowed in an emphasis exp.
4107 You need to reload Org or to restart Emacs after customizing this.")
4109 (defcustom org-emphasis-alist
4110 `(("*" bold)
4111 ("/" italic)
4112 ("_" underline)
4113 ("=" org-code verbatim)
4114 ("~" org-verbatim verbatim)
4115 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4116 "Alist of characters and faces to emphasize text.
4117 Text starting and ending with a special character will be emphasized,
4118 for example *bold*, _underlined_ and /italic/. This variable sets the
4119 marker characters and the face to be used by font-lock for highlighting
4120 in Org-mode Emacs buffers.
4122 You need to reload Org or to restart Emacs after customizing this."
4123 :group 'org-appearance
4124 :set 'org-set-emph-re
4125 :version "24.4"
4126 :package-version '(Org . "8.0")
4127 :type '(repeat
4128 (list
4129 (string :tag "Marker character")
4130 (choice
4131 (face :tag "Font-lock-face")
4132 (plist :tag "Face property list"))
4133 (option (const verbatim)))))
4135 (defvar org-protecting-blocks
4136 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4137 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4138 This is needed for font-lock setup.")
4140 ;;; Miscellaneous options
4142 (defgroup org-completion nil
4143 "Completion in Org-mode."
4144 :tag "Org Completion"
4145 :group 'org)
4147 (defcustom org-completion-use-ido nil
4148 "Non-nil means use ido completion wherever possible.
4149 Note that `ido-mode' must be active for this variable to be relevant.
4150 If you decide to turn this variable on, you might well want to turn off
4151 `org-outline-path-complete-in-steps'.
4152 See also `org-completion-use-iswitchb'."
4153 :group 'org-completion
4154 :type 'boolean)
4156 (defcustom org-completion-use-iswitchb nil
4157 "Non-nil means use iswitchb completion wherever possible.
4158 Note that `iswitchb-mode' must be active for this variable to be relevant.
4159 If you decide to turn this variable on, you might well want to turn off
4160 `org-outline-path-complete-in-steps'.
4161 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4162 :group 'org-completion
4163 :type 'boolean)
4165 (defcustom org-completion-fallback-command 'hippie-expand
4166 "The expansion command called by \\[pcomplete] in normal context.
4167 Normal means, no org-mode-specific context."
4168 :group 'org-completion
4169 :type 'function)
4171 ;;; Functions and variables from their packages
4172 ;; Declared here to avoid compiler warnings
4174 ;; XEmacs only
4175 (defvar outline-mode-menu-heading)
4176 (defvar outline-mode-menu-show)
4177 (defvar outline-mode-menu-hide)
4178 (defvar zmacs-regions) ; XEmacs regions
4180 ;; Emacs only
4181 (defvar mark-active)
4183 ;; Various packages
4184 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4185 (declare-function calendar-forward-day "cal-move" (arg))
4186 (declare-function calendar-goto-date "cal-move" (date))
4187 (declare-function calendar-goto-today "cal-move" ())
4188 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4189 (defvar calc-embedded-close-formula)
4190 (defvar calc-embedded-open-formula)
4191 (declare-function cdlatex-tab "ext:cdlatex" ())
4192 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4193 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4194 (defvar font-lock-unfontify-region-function)
4195 (declare-function iswitchb-read-buffer "iswitchb"
4196 (prompt &optional default require-match start matches-set))
4197 (defvar iswitchb-temp-buflist)
4198 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4199 (defvar org-agenda-tags-todo-honor-ignore-options)
4200 (declare-function org-agenda-skip "org-agenda" ())
4201 (declare-function
4202 org-agenda-format-item "org-agenda"
4203 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4204 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4205 (declare-function org-agenda-change-all-lines "org-agenda"
4206 (newhead hdmarker &optional fixface just-this))
4207 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4208 (declare-function org-agenda-maybe-redo "org-agenda" ())
4209 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4210 (beg end))
4211 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4212 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4213 "org-agenda" (&optional end))
4214 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4215 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4216 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4217 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4218 (declare-function org-indent-mode "org-indent" (&optional arg))
4219 (declare-function parse-time-string "parse-time" (string))
4220 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4221 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4222 (defvar remember-data-file)
4223 (defvar texmathp-why)
4224 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4225 (declare-function table--at-cell-p "table" (position &optional object at-column))
4227 (defvar org-latex-regexps)
4229 ;;; Autoload and prepare some org modules
4231 ;; Some table stuff that needs to be defined here, because it is used
4232 ;; by the functions setting up org-mode or checking for table context.
4234 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4235 "Detect an org-type or table-type table.")
4236 (defconst org-table-line-regexp "^[ \t]*|"
4237 "Detect an org-type table line.")
4238 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4239 "Detect an org-type table line.")
4240 (defconst org-table-hline-regexp "^[ \t]*|-"
4241 "Detect an org-type table hline.")
4242 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4243 "Detect a table-type table hline.")
4244 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4245 "Detect the first line outside a table when searching from within it.
4246 This works for both table types.")
4248 ;; Autoload the functions in org-table.el that are needed by functions here.
4250 (eval-and-compile
4251 (org-autoload "org-table"
4252 '(org-table-begin org-table-blank-field org-table-end)))
4254 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4255 "Detect a #+TBLFM line.")
4257 ;;;###autoload
4258 (defun turn-on-orgtbl ()
4259 "Unconditionally turn on `orgtbl-mode'."
4260 (require 'org-table)
4261 (orgtbl-mode 1))
4263 (defun org-at-table-p (&optional table-type)
4264 "Return t if the cursor is inside an org-type table.
4265 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4266 (if org-enable-table-editor
4267 (save-excursion
4268 (beginning-of-line 1)
4269 (looking-at (if table-type org-table-any-line-regexp
4270 org-table-line-regexp)))
4271 nil))
4272 (defsubst org-table-p () (org-at-table-p))
4274 (defun org-at-table.el-p ()
4275 "Return t if and only if we are at a table.el table."
4276 (and (org-at-table-p 'any)
4277 (save-excursion
4278 (goto-char (org-table-begin 'any))
4279 (looking-at org-table1-hline-regexp))))
4281 (defun org-table-recognize-table.el ()
4282 "If there is a table.el table nearby, recognize it and move into it."
4283 (if org-table-tab-recognizes-table.el
4284 (if (org-at-table.el-p)
4285 (progn
4286 (beginning-of-line 1)
4287 (if (looking-at org-table-dataline-regexp)
4289 (if (looking-at org-table1-hline-regexp)
4290 (progn
4291 (beginning-of-line 2)
4292 (if (looking-at org-table-any-border-regexp)
4293 (beginning-of-line -1)))))
4294 (if (re-search-forward "|" (org-table-end t) t)
4295 (progn
4296 (require 'table)
4297 (if (table--at-cell-p (point))
4299 (message "recognizing table.el table...")
4300 (table-recognize-table)
4301 (message "recognizing table.el table...done")))
4302 (error "This should not happen"))
4304 nil)
4305 nil))
4307 (defun org-at-table-hline-p ()
4308 "Return t if the cursor is inside a hline in a table."
4309 (if org-enable-table-editor
4310 (save-excursion
4311 (beginning-of-line 1)
4312 (looking-at org-table-hline-regexp))
4313 nil))
4315 (defun org-table-map-tables (function &optional quietly)
4316 "Apply FUNCTION to the start of all tables in the buffer."
4317 (save-excursion
4318 (save-restriction
4319 (widen)
4320 (goto-char (point-min))
4321 (while (re-search-forward org-table-any-line-regexp nil t)
4322 (unless quietly
4323 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4324 (beginning-of-line 1)
4325 (when (and (looking-at org-table-line-regexp)
4326 ;; Exclude tables in src/example/verbatim/clocktable blocks
4327 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4328 (save-excursion (funcall function))
4329 (or (looking-at org-table-line-regexp)
4330 (forward-char 1)))
4331 (re-search-forward org-table-any-border-regexp nil 1))))
4332 (unless quietly (message "Mapping tables: done")))
4334 ;; Declare and autoload functions from org-agenda.el
4336 (eval-and-compile
4337 (org-autoload "org-agenda"
4338 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4340 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4341 (declare-function org-clock-update-mode-line "org-clock" ())
4342 (declare-function org-resolve-clocks "org-clock"
4343 (&optional also-non-dangling-p prompt last-valid))
4345 (defun org-at-TBLFM-p (&optional pos)
4346 "Return t when point (or POS) is in #+TBLFM line."
4347 (save-excursion
4348 (let ((pos pos)))
4349 (goto-char (or pos (point)))
4350 (beginning-of-line 1)
4351 (looking-at org-TBLFM-regexp)))
4353 (defvar org-clock-start-time)
4354 (defvar org-clock-marker (make-marker)
4355 "Marker recording the last clock-in.")
4356 (defvar org-clock-hd-marker (make-marker)
4357 "Marker recording the last clock-in, but the headline position.")
4358 (defvar org-clock-heading ""
4359 "The heading of the current clock entry.")
4360 (defun org-clock-is-active ()
4361 "Return the buffer where the clock is currently running.
4362 Return nil if no clock is running."
4363 (marker-buffer org-clock-marker))
4365 (eval-and-compile
4366 (org-autoload "org-clock" '(org-clock-remove-overlays
4367 org-clock-update-time-maybe
4368 org-clocktable-shift)))
4370 (defun org-check-running-clock ()
4371 "Check if the current buffer contains the running clock.
4372 If yes, offer to stop it and to save the buffer with the changes."
4373 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4374 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4375 (buffer-name))))
4376 (org-clock-out)
4377 (when (y-or-n-p "Save changed buffer?")
4378 (save-buffer))))
4380 (defun org-clocktable-try-shift (dir n)
4381 "Check if this line starts a clock table, if yes, shift the time block."
4382 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4383 (org-clocktable-shift dir n)))
4385 ;;;###autoload
4386 (defun org-clock-persistence-insinuate ()
4387 "Set up hooks for clock persistence."
4388 (require 'org-clock)
4389 (add-hook 'org-mode-hook 'org-clock-load)
4390 (add-hook 'kill-emacs-hook 'org-clock-save))
4392 ;; Define the variable already here, to make sure we have it.
4393 (defvar org-indent-mode nil
4394 "Non-nil if Org-Indent mode is enabled.
4395 Use the command `org-indent-mode' to change this variable.")
4397 ;; Autoload archiving code
4398 ;; The stuff that is needed for cycling and tags has to be defined here.
4400 (defgroup org-archive nil
4401 "Options concerning archiving in Org-mode."
4402 :tag "Org Archive"
4403 :group 'org-structure)
4405 (defcustom org-archive-location "%s_archive::"
4406 "The location where subtrees should be archived.
4408 The value of this variable is a string, consisting of two parts,
4409 separated by a double-colon. The first part is a filename and
4410 the second part is a headline.
4412 When the filename is omitted, archiving happens in the same file.
4413 %s in the filename will be replaced by the current file
4414 name (without the directory part). Archiving to a different file
4415 is useful to keep archived entries from contributing to the
4416 Org-mode Agenda.
4418 The archived entries will be filed as subtrees of the specified
4419 headline. When the headline is omitted, the subtrees are simply
4420 filed away at the end of the file, as top-level entries. Also in
4421 the heading you can use %s to represent the file name, this can be
4422 useful when using the same archive for a number of different files.
4424 Here are a few examples:
4425 \"%s_archive::\"
4426 If the current file is Projects.org, archive in file
4427 Projects.org_archive, as top-level trees. This is the default.
4429 \"::* Archived Tasks\"
4430 Archive in the current file, under the top-level headline
4431 \"* Archived Tasks\".
4433 \"~/org/archive.org::\"
4434 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4436 \"~/org/archive.org::* From %s\"
4437 Archive in file ~/org/archive.org (absolute path), under headlines
4438 \"From FILENAME\" where file name is the current file name.
4440 \"~/org/datetree.org::datetree/* Finished Tasks\"
4441 The \"datetree/\" string is special, signifying to archive
4442 items to the datetree. Items are placed in either the CLOSED
4443 date of the item, or the current date if there is no CLOSED date.
4444 The heading will be a subentry to the current date. There doesn't
4445 need to be a heading, but there always needs to be a slash after
4446 datetree. For example, to store archived items directly in the
4447 datetree, use \"~/org/datetree.org::datetree/\".
4449 \"basement::** Finished Tasks\"
4450 Archive in file ./basement (relative path), as level 3 trees
4451 below the level 2 heading \"** Finished Tasks\".
4453 You may set this option on a per-file basis by adding to the buffer a
4454 line like
4456 #+ARCHIVE: basement::** Finished Tasks
4458 You may also define it locally for a subtree by setting an ARCHIVE property
4459 in the entry. If such a property is found in an entry, or anywhere up
4460 the hierarchy, it will be used."
4461 :group 'org-archive
4462 :type 'string)
4464 (defcustom org-archive-tag "ARCHIVE"
4465 "The tag that marks a subtree as archived.
4466 An archived subtree does not open during visibility cycling, and does
4467 not contribute to the agenda listings.
4468 After changing this, font-lock must be restarted in the relevant buffers to
4469 get the proper fontification."
4470 :group 'org-archive
4471 :group 'org-keywords
4472 :type 'string)
4474 (defcustom org-agenda-skip-archived-trees t
4475 "Non-nil means the agenda will skip any items located in archived trees.
4476 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4477 variable is no longer recommended, you should leave it at the value t.
4478 Instead, use the key `v' to cycle the archives-mode in the agenda."
4479 :group 'org-archive
4480 :group 'org-agenda-skip
4481 :type 'boolean)
4483 (defcustom org-columns-skip-archived-trees t
4484 "Non-nil means ignore archived trees when creating column view."
4485 :group 'org-archive
4486 :group 'org-properties
4487 :type 'boolean)
4489 (defcustom org-cycle-open-archived-trees nil
4490 "Non-nil means `org-cycle' will open archived trees.
4491 An archived tree is a tree marked with the tag ARCHIVE.
4492 When nil, archived trees will stay folded. You can still open them with
4493 normal outline commands like `show-all', but not with the cycling commands."
4494 :group 'org-archive
4495 :group 'org-cycle
4496 :type 'boolean)
4498 (defcustom org-sparse-tree-open-archived-trees nil
4499 "Non-nil means sparse tree construction shows matches in archived trees.
4500 When nil, matches in these trees are highlighted, but the trees are kept in
4501 collapsed state."
4502 :group 'org-archive
4503 :group 'org-sparse-trees
4504 :type 'boolean)
4506 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4507 "The default date type when building a sparse tree.
4508 When this is nil, a date is a scheduled or a deadline timestamp.
4509 Otherwise, these types are allowed:
4511 all: all timestamps
4512 active: only active timestamps (<...>)
4513 inactive: only inactive timestamps (<...)
4514 scheduled: only scheduled timestamps
4515 deadline: only deadline timestamps"
4516 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4517 (const :tag "All timestamps" all)
4518 (const :tag "Only active timestamps" active)
4519 (const :tag "Only inactive timestamps" inactive)
4520 (const :tag "Only scheduled timestamps" scheduled)
4521 (const :tag "Only deadline timestamps" deadline)
4522 (const :tag "Only closed timestamps" closed))
4523 :version "24.3"
4524 :group 'org-sparse-trees)
4526 (defun org-cycle-hide-archived-subtrees (state)
4527 "Re-hide all archived subtrees after a visibility state change."
4528 (when (and (not org-cycle-open-archived-trees)
4529 (not (memq state '(overview folded))))
4530 (save-excursion
4531 (let* ((globalp (memq state '(contents all)))
4532 (beg (if globalp (point-min) (point)))
4533 (end (if globalp (point-max) (org-end-of-subtree t))))
4534 (org-hide-archived-subtrees beg end)
4535 (goto-char beg)
4536 (if (looking-at (concat ".*:" org-archive-tag ":"))
4537 (message "%s" (substitute-command-keys
4538 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4540 (defun org-force-cycle-archived ()
4541 "Cycle subtree even if it is archived."
4542 (interactive)
4543 (setq this-command 'org-cycle)
4544 (let ((org-cycle-open-archived-trees t))
4545 (call-interactively 'org-cycle)))
4547 (defun org-hide-archived-subtrees (beg end)
4548 "Re-hide all archived subtrees after a visibility state change."
4549 (save-excursion
4550 (let* ((re (concat ":" org-archive-tag ":")))
4551 (goto-char beg)
4552 (while (re-search-forward re end t)
4553 (when (org-at-heading-p)
4554 (org-flag-subtree t)
4555 (org-end-of-subtree t))))))
4557 (declare-function outline-end-of-heading "outline" ())
4558 (declare-function outline-flag-region "outline" (from to flag))
4559 (defun org-flag-subtree (flag)
4560 (save-excursion
4561 (org-back-to-heading t)
4562 (outline-end-of-heading)
4563 (outline-flag-region (point)
4564 (progn (org-end-of-subtree t) (point))
4565 flag)))
4567 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4569 (eval-and-compile
4570 (org-autoload "org-archive"
4571 '(org-add-archive-files)))
4573 ;; Autoload Column View Code
4575 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4576 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4577 (declare-function org-columns-compute "org-colview" (property))
4579 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4580 '(org-columns-number-to-string
4581 org-columns-get-format-and-top-level
4582 org-columns-compute
4583 org-columns-remove-overlays))
4585 ;; Autoload ID code
4587 (declare-function org-id-store-link "org-id")
4588 (declare-function org-id-locations-load "org-id")
4589 (declare-function org-id-locations-save "org-id")
4590 (defvar org-id-track-globally)
4591 (org-autoload "org-id"
4592 '(org-id-new
4593 org-id-copy
4594 org-id-get-with-outline-path-completion
4595 org-id-get-with-outline-drilling))
4597 ;;; Variables for pre-computed regular expressions, all buffer local
4599 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4600 "Matches first line of a hidden block.")
4601 (make-variable-buffer-local 'org-drawer-regexp)
4602 (defvar org-todo-regexp nil
4603 "Matches any of the TODO state keywords.")
4604 (make-variable-buffer-local 'org-todo-regexp)
4605 (defvar org-not-done-regexp nil
4606 "Matches any of the TODO state keywords except the last one.")
4607 (make-variable-buffer-local 'org-not-done-regexp)
4608 (defvar org-not-done-heading-regexp nil
4609 "Matches a TODO headline that is not done.")
4610 (make-variable-buffer-local 'org-not-done-regexp)
4611 (defvar org-todo-line-regexp nil
4612 "Matches a headline and puts TODO state into group 2 if present.")
4613 (make-variable-buffer-local 'org-todo-line-regexp)
4614 (defvar org-complex-heading-regexp nil
4615 "Matches a headline and puts everything into groups:
4616 group 1: the stars
4617 group 2: The todo keyword, maybe
4618 group 3: Priority cookie
4619 group 4: True headline
4620 group 5: Tags")
4621 (make-variable-buffer-local 'org-complex-heading-regexp)
4622 (defvar org-complex-heading-regexp-format nil
4623 "Printf format to make regexp to match an exact headline.
4624 This regexp will match the headline of any node which has the
4625 exact headline text that is put into the format, but may have any
4626 TODO state, priority and tags.")
4627 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4628 (defvar org-todo-line-tags-regexp nil
4629 "Matches a headline and puts TODO state into group 2 if present.
4630 Also put tags into group 4 if tags are present.")
4631 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4632 (defvar org-ds-keyword-length 12
4633 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4634 (make-variable-buffer-local 'org-ds-keyword-length)
4635 (defvar org-deadline-regexp nil
4636 "Matches the DEADLINE keyword.")
4637 (make-variable-buffer-local 'org-deadline-regexp)
4638 (defvar org-deadline-time-regexp nil
4639 "Matches the DEADLINE keyword together with a time stamp.")
4640 (make-variable-buffer-local 'org-deadline-time-regexp)
4641 (defvar org-deadline-time-hour-regexp nil
4642 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4643 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4644 (defvar org-deadline-line-regexp nil
4645 "Matches the DEADLINE keyword and the rest of the line.")
4646 (make-variable-buffer-local 'org-deadline-line-regexp)
4647 (defvar org-scheduled-regexp nil
4648 "Matches the SCHEDULED keyword.")
4649 (make-variable-buffer-local 'org-scheduled-regexp)
4650 (defvar org-scheduled-time-regexp nil
4651 "Matches the SCHEDULED keyword together with a time stamp.")
4652 (make-variable-buffer-local 'org-scheduled-time-regexp)
4653 (defvar org-scheduled-time-hour-regexp nil
4654 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4655 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4656 (defvar org-closed-time-regexp nil
4657 "Matches the CLOSED keyword together with a time stamp.")
4658 (make-variable-buffer-local 'org-closed-time-regexp)
4660 (defvar org-keyword-time-regexp nil
4661 "Matches any of the 4 keywords, together with the time stamp.")
4662 (make-variable-buffer-local 'org-keyword-time-regexp)
4663 (defvar org-keyword-time-not-clock-regexp nil
4664 "Matches any of the 3 keywords, together with the time stamp.")
4665 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4666 (defvar org-maybe-keyword-time-regexp nil
4667 "Matches a timestamp, possibly preceded by a keyword.")
4668 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4669 (defvar org-all-time-keywords nil
4670 "List of time keywords.")
4671 (make-variable-buffer-local 'org-all-time-keywords)
4673 (defconst org-plain-time-of-day-regexp
4674 (concat
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\(--?"
4678 "\\(\\<[012]?[0-9]"
4679 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4680 "\\)?")
4681 "Regular expression to match a plain time or time range.
4682 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4683 groups carry important information:
4684 0 the full match
4685 1 the first time, range or not
4686 8 the second time, if it is a range.")
4688 (defconst org-plain-time-extension-regexp
4689 (concat
4690 "\\(\\<[012]?[0-9]"
4691 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4692 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4693 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4694 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4695 groups carry important information:
4696 0 the full match
4697 7 hours of duration
4698 9 minutes of duration")
4700 (defconst org-stamp-time-of-day-regexp
4701 (concat
4702 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4703 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4704 "\\(--?"
4705 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4706 "Regular expression to match a timestamp time or time range.
4707 After a match, the following groups carry important information:
4708 0 the full match
4709 1 date plus weekday, for back referencing to make sure both times are on the same day
4710 2 the first time, range or not
4711 4 the second time, if it is a range.")
4713 (defconst org-startup-options
4714 '(("fold" org-startup-folded t)
4715 ("overview" org-startup-folded t)
4716 ("nofold" org-startup-folded nil)
4717 ("showall" org-startup-folded nil)
4718 ("showeverything" org-startup-folded showeverything)
4719 ("content" org-startup-folded content)
4720 ("indent" org-startup-indented t)
4721 ("noindent" org-startup-indented nil)
4722 ("hidestars" org-hide-leading-stars t)
4723 ("showstars" org-hide-leading-stars nil)
4724 ("odd" org-odd-levels-only t)
4725 ("oddeven" org-odd-levels-only nil)
4726 ("align" org-startup-align-all-tables t)
4727 ("noalign" org-startup-align-all-tables nil)
4728 ("inlineimages" org-startup-with-inline-images t)
4729 ("noinlineimages" org-startup-with-inline-images nil)
4730 ("latexpreview" org-startup-with-latex-preview t)
4731 ("nolatexpreview" org-startup-with-latex-preview nil)
4732 ("customtime" org-display-custom-times t)
4733 ("logdone" org-log-done time)
4734 ("lognotedone" org-log-done note)
4735 ("nologdone" org-log-done nil)
4736 ("lognoteclock-out" org-log-note-clock-out t)
4737 ("nolognoteclock-out" org-log-note-clock-out nil)
4738 ("logrepeat" org-log-repeat state)
4739 ("lognoterepeat" org-log-repeat note)
4740 ("logdrawer" org-log-into-drawer t)
4741 ("nologdrawer" org-log-into-drawer nil)
4742 ("logstatesreversed" org-log-states-order-reversed t)
4743 ("nologstatesreversed" org-log-states-order-reversed nil)
4744 ("nologrepeat" org-log-repeat nil)
4745 ("logreschedule" org-log-reschedule time)
4746 ("lognotereschedule" org-log-reschedule note)
4747 ("nologreschedule" org-log-reschedule nil)
4748 ("logredeadline" org-log-redeadline time)
4749 ("lognoteredeadline" org-log-redeadline note)
4750 ("nologredeadline" org-log-redeadline nil)
4751 ("logrefile" org-log-refile time)
4752 ("lognoterefile" org-log-refile note)
4753 ("nologrefile" org-log-refile nil)
4754 ("fninline" org-footnote-define-inline t)
4755 ("nofninline" org-footnote-define-inline nil)
4756 ("fnlocal" org-footnote-section nil)
4757 ("fnauto" org-footnote-auto-label t)
4758 ("fnprompt" org-footnote-auto-label nil)
4759 ("fnconfirm" org-footnote-auto-label confirm)
4760 ("fnplain" org-footnote-auto-label plain)
4761 ("fnadjust" org-footnote-auto-adjust t)
4762 ("nofnadjust" org-footnote-auto-adjust nil)
4763 ("constcgs" constants-unit-system cgs)
4764 ("constSI" constants-unit-system SI)
4765 ("noptag" org-tag-persistent-alist nil)
4766 ("hideblocks" org-hide-block-startup t)
4767 ("nohideblocks" org-hide-block-startup nil)
4768 ("beamer" org-startup-with-beamer-mode t)
4769 ("entitiespretty" org-pretty-entities t)
4770 ("entitiesplain" org-pretty-entities nil))
4771 "Variable associated with STARTUP options for org-mode.
4772 Each element is a list of three items: the startup options (as written
4773 in the #+STARTUP line), the corresponding variable, and the value to set
4774 this variable to if the option is found. An optional forth element PUSH
4775 means to push this value onto the list in the variable.")
4777 (defun org-update-property-plist (key val props)
4778 "Update PROPS with KEY and VAL."
4779 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4780 (key (if appending (substring key 0 (- (length key) 1)) key))
4781 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4782 (previous (cdr (assoc key props))))
4783 (if appending
4784 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4785 (cons (cons key val) remainder))))
4787 (defconst org-block-regexp
4788 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4789 "Regular expression for hiding blocks.")
4790 (defconst org-heading-keyword-regexp-format
4791 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4792 "Printf format for a regexp matching a headline with some keyword.
4793 This regexp will match the headline of any node which has the
4794 exact keyword that is put into the format. The keyword isn't in
4795 any group by default, but the stars and the body are.")
4796 (defconst org-heading-keyword-maybe-regexp-format
4797 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4798 "Printf format for a regexp matching a headline, possibly with some keyword.
4799 This regexp can match any headline with the specified keyword, or
4800 without a keyword. The keyword isn't in any group by default,
4801 but the stars and the body are.")
4803 (defcustom org-group-tags t
4804 "When non-nil (the default), use group tags.
4805 This can be turned on/off through `org-toggle-tags-groups'."
4806 :group 'org-tags
4807 :group 'org-startup
4808 :type 'boolean)
4810 (defun org-toggle-tags-groups ()
4811 "Toggle support for group tags.
4812 Support for group tags is controlled by the option
4813 `org-group-tags', which is non-nil by default."
4814 (interactive)
4815 (setq org-group-tags (not org-group-tags))
4816 (cond ((and (derived-mode-p 'org-agenda-mode)
4817 org-group-tags)
4818 (org-agenda-redo))
4819 ((derived-mode-p 'org-mode)
4820 (let ((org-inhibit-startup t)) (org-mode))))
4821 (message "Groups tags support has been turned %s"
4822 (if org-group-tags "on" "off")))
4824 (defun org-set-regexps-and-options-for-tags ()
4825 "Precompute variables used for tags."
4826 (when (derived-mode-p 'org-mode)
4827 (org-set-local 'org-file-tags nil)
4828 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4829 (splitre "[ \t]+")
4830 (start 0)
4831 tags ftags key value)
4832 (save-excursion
4833 (save-restriction
4834 (widen)
4835 (goto-char (point-min))
4836 (while (re-search-forward re nil t)
4837 (setq key (upcase (org-match-string-no-properties 1))
4838 value (org-match-string-no-properties 2))
4839 (if (stringp value) (setq value (org-trim value)))
4840 (cond
4841 ((equal key "TAGS")
4842 (setq tags (append tags (if tags '("\\n") nil)
4843 (org-split-string value splitre))))
4844 ((equal key "FILETAGS")
4845 (when (string-match "\\S-" value)
4846 (setq ftags
4847 (append
4848 ftags
4849 (apply 'append
4850 (mapcar (lambda (x) (org-split-string x ":"))
4851 (org-split-string value)))))))))))
4852 ;; Process the file tags.
4853 (and ftags (org-set-local 'org-file-tags
4854 (mapcar 'org-add-prop-inherited ftags)))
4855 (org-set-local 'org-tag-groups-alist nil)
4856 ;; Process the tags.
4857 (when (and (not tags) org-tag-alist)
4858 (setq tags
4859 (mapcar
4860 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4861 ((eq (car tg) :endgroup) "}")
4862 ((eq (car tg) :grouptags) ":")
4863 ((eq (car tg) :newline) "\n")
4864 (t (concat (car tg)
4865 (if (characterp (cdr tg))
4866 (format "(%s)" (char-to-string (cdr tg))) "")))))
4867 org-tag-alist)))
4868 (let (e tgs g)
4869 (while (setq e (pop tags))
4870 (cond
4871 ((equal e "{")
4872 (progn (push '(:startgroup) tgs)
4873 (when (equal (nth 1 tags) ":")
4874 (push (list (replace-regexp-in-string
4875 "(.+)$" "" (nth 0 tags)))
4876 org-tag-groups-alist)
4877 (setq g 0))))
4878 ((equal e ":") (push '(:grouptags) tgs))
4879 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4880 ((equal e "\\n") (push '(:newline) tgs))
4881 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4882 (push (cons (match-string 1 e)
4883 (string-to-char (match-string 2 e))) tgs)
4884 (if (and g (> g 0))
4885 (setcar org-tag-groups-alist
4886 (append (car org-tag-groups-alist)
4887 (list (match-string 1 e)))))
4888 (if g (setq g (1+ g))))
4889 (t (push (list e) tgs)
4890 (if (and g (> g 0))
4891 (setcar org-tag-groups-alist
4892 (append (car org-tag-groups-alist) (list e))))
4893 (if g (setq g (1+ g))))))
4894 (org-set-local 'org-tag-alist nil)
4895 (while (setq e (pop tgs))
4896 (or (and (stringp (car e))
4897 (assoc (car e) org-tag-alist))
4898 (push e org-tag-alist)))
4899 ;; Return a list with tag variables
4900 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4902 (defvar org-ota nil)
4903 (defun org-set-regexps-and-options ()
4904 "Precompute regular expressions used in the current buffer."
4905 (when (derived-mode-p 'org-mode)
4906 (org-set-local 'org-todo-kwd-alist nil)
4907 (org-set-local 'org-todo-key-alist nil)
4908 (org-set-local 'org-todo-key-trigger nil)
4909 (org-set-local 'org-todo-keywords-1 nil)
4910 (org-set-local 'org-done-keywords nil)
4911 (org-set-local 'org-todo-heads nil)
4912 (org-set-local 'org-todo-sets nil)
4913 (org-set-local 'org-todo-log-states nil)
4914 (org-set-local 'org-file-properties nil)
4915 (let ((re (org-make-options-regexp
4916 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4917 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4918 "SETUPFILE" "OPTIONS")
4919 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4920 (splitre "[ \t]+")
4921 (scripts org-use-sub-superscripts)
4922 kwds kws0 kwsa key log value cat arch const links hw dws
4923 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4924 (start 0))
4925 (save-excursion
4926 (save-restriction
4927 (widen)
4928 (goto-char (point-min))
4929 (while
4930 (or (and
4931 ext-setup-or-nil
4932 (not org-ota)
4933 (let (ret)
4934 (with-temp-buffer
4935 (insert ext-setup-or-nil)
4936 (let ((major-mode 'org-mode) org-ota)
4937 (setq ret (save-match-data
4938 (org-set-regexps-and-options-for-tags)))))
4939 ;; Append setupfile tags to existing tags
4940 (setq org-ota t)
4941 (setq org-file-tags
4942 (delq nil (append org-file-tags (nth 0 ret)))
4943 org-tag-alist
4944 (delq nil (append org-tag-alist (nth 1 ret)))
4945 org-tag-groups-alist
4946 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4947 (and ext-setup-or-nil
4948 (string-match re ext-setup-or-nil start)
4949 (setq start (match-end 0)))
4950 (and (setq ext-setup-or-nil nil start 0)
4951 (re-search-forward re nil t)))
4952 (setq key (upcase (match-string 1 ext-setup-or-nil))
4953 value (org-match-string-no-properties 2 ext-setup-or-nil))
4954 (if (stringp value) (setq value (org-trim value)))
4955 (cond
4956 ((equal key "CATEGORY")
4957 (setq cat value))
4958 ((member key '("SEQ_TODO" "TODO"))
4959 (push (cons 'sequence (org-split-string value splitre)) kwds))
4960 ((equal key "TYP_TODO")
4961 (push (cons 'type (org-split-string value splitre)) kwds))
4962 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4963 ;; general TODO-like setup
4964 (push (cons (intern (downcase (match-string 1 key)))
4965 (org-split-string value splitre)) kwds))
4966 ((equal key "COLUMNS")
4967 (org-set-local 'org-columns-default-format value))
4968 ((equal key "LINK")
4969 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4970 (push (cons (match-string 1 value)
4971 (org-trim (match-string 2 value)))
4972 links)))
4973 ((equal key "PRIORITIES")
4974 (setq prio (org-split-string value " +")))
4975 ((equal key "PROPERTY")
4976 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4977 (setq props (org-update-property-plist (match-string 1 value)
4978 (match-string 2 value)
4979 props))))
4980 ((equal key "DRAWERS")
4981 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4982 ((equal key "CONSTANTS")
4983 (org-table-set-constants))
4984 ((equal key "STARTUP")
4985 (let ((opts (org-split-string value splitre))
4986 l var val)
4987 (while (setq l (pop opts))
4988 (when (setq l (assoc l org-startup-options))
4989 (setq var (nth 1 l) val (nth 2 l))
4990 (if (not (nth 3 l))
4991 (set (make-local-variable var) val)
4992 (if (not (listp (symbol-value var)))
4993 (set (make-local-variable var) nil))
4994 (set (make-local-variable var) (symbol-value var))
4995 (add-to-list var val))))))
4996 ((equal key "ARCHIVE")
4997 (setq arch value)
4998 (remove-text-properties 0 (length arch)
4999 '(face t fontified t) arch))
5000 ((equal key "OPTIONS")
5001 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5002 (setq scripts (read (match-string 2 value)))))
5003 ((and (equal key "SETUPFILE")
5004 ;; Prevent checking in Gnus messages
5005 (not buffer-read-only))
5006 (setq setup-contents (org-file-contents
5007 (expand-file-name
5008 (org-remove-double-quotes value))
5009 'noerror))
5010 (if (not ext-setup-or-nil)
5011 (setq ext-setup-or-nil setup-contents start 0)
5012 (setq ext-setup-or-nil
5013 (concat (substring ext-setup-or-nil 0 start)
5014 "\n" setup-contents "\n"
5015 (substring ext-setup-or-nil start)))))))
5016 ;; search for property blocks
5017 (goto-char (point-min))
5018 (while (re-search-forward org-block-regexp nil t)
5019 (when (equal "PROPERTY" (upcase (match-string 1)))
5020 (setq value (replace-regexp-in-string
5021 "[\n\r]" " " (match-string 4)))
5022 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5023 (setq props (org-update-property-plist (match-string 1 value)
5024 (match-string 2 value)
5025 props)))))))
5026 (org-set-local 'org-use-sub-superscripts scripts)
5027 (when cat
5028 (org-set-local 'org-category (intern cat))
5029 (push (cons "CATEGORY" cat) props))
5030 (when prio
5031 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5032 (setq prio (mapcar 'string-to-char prio))
5033 (org-set-local 'org-highest-priority (nth 0 prio))
5034 (org-set-local 'org-lowest-priority (nth 1 prio))
5035 (org-set-local 'org-default-priority (nth 2 prio)))
5036 (and props (org-set-local 'org-file-properties (nreverse props)))
5037 (and drawers (org-set-local 'org-drawers drawers))
5038 (and arch (org-set-local 'org-archive-location arch))
5039 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5040 ;; Process the TODO keywords
5041 (unless kwds
5042 ;; Use the global values as if they had been given locally.
5043 (setq kwds (default-value 'org-todo-keywords))
5044 (if (stringp (car kwds))
5045 (setq kwds (list (cons org-todo-interpretation
5046 (default-value 'org-todo-keywords)))))
5047 (setq kwds (reverse kwds)))
5048 (setq kwds (nreverse kwds))
5049 (let (inter kws kw)
5050 (while (setq kws (pop kwds))
5051 (let ((kws (or
5052 (run-hook-with-args-until-success
5053 'org-todo-setup-filter-hook kws)
5054 kws)))
5055 (setq inter (pop kws) sep (member "|" kws)
5056 kws0 (delete "|" (copy-sequence kws))
5057 kwsa nil
5058 kws1 (mapcar
5059 (lambda (x)
5060 ;; 1 2
5061 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5062 (progn
5063 (setq kw (match-string 1 x)
5064 key (and (match-end 2) (match-string 2 x))
5065 log (org-extract-log-state-settings x))
5066 (push (cons kw (and key (string-to-char key))) kwsa)
5067 (and log (push log org-todo-log-states))
5069 (error "Invalid TODO keyword %s" x)))
5070 kws0)
5071 kwsa (if kwsa (append '((:startgroup))
5072 (nreverse kwsa)
5073 '((:endgroup))))
5074 hw (car kws1)
5075 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5076 tail (list inter hw (car dws) (org-last dws))))
5077 (add-to-list 'org-todo-heads hw 'append)
5078 (push kws1 org-todo-sets)
5079 (setq org-done-keywords (append org-done-keywords dws nil))
5080 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5081 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5082 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5083 (setq org-todo-sets (nreverse org-todo-sets)
5084 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5085 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5086 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5087 ;; Compute the regular expressions and other local variables.
5088 ;; Using `org-outline-regexp-bol' would complicate them much,
5089 ;; because of the fixed white space at the end of that string.
5090 (if (not org-done-keywords)
5091 (setq org-done-keywords (and org-todo-keywords-1
5092 (list (org-last org-todo-keywords-1)))))
5093 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5094 (length org-scheduled-string)
5095 (length org-clock-string)
5096 (length org-closed-string)))
5097 org-drawer-regexp
5098 (concat "^[ \t]*:\\("
5099 (mapconcat 'regexp-quote org-drawers "\\|")
5100 "\\):[ \t]*$")
5101 org-not-done-keywords
5102 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5103 org-todo-regexp
5104 (concat "\\("
5105 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5106 "\\)")
5107 org-not-done-regexp
5108 (concat "\\("
5109 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5110 "\\)")
5111 org-not-done-heading-regexp
5112 (format org-heading-keyword-regexp-format org-not-done-regexp)
5113 org-todo-line-regexp
5114 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5115 org-complex-heading-regexp
5116 (concat "^\\(\\*+\\)"
5117 "\\(?: +" org-todo-regexp "\\)?"
5118 "\\(?: +\\(\\[#.\\]\\)\\)?"
5119 "\\(?: +\\(.*?\\)\\)??"
5120 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5121 "[ \t]*$")
5122 org-complex-heading-regexp-format
5123 (concat "^\\(\\*+\\)"
5124 "\\(?: +" org-todo-regexp "\\)?"
5125 "\\(?: +\\(\\[#.\\]\\)\\)?"
5126 "\\(?: +"
5127 ;; Stats cookies can be stuck to body.
5128 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5129 "\\(%s\\)"
5130 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5131 "\\)"
5132 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5133 "[ \t]*$")
5134 org-todo-line-tags-regexp
5135 (concat "^\\(\\*+\\)"
5136 "\\(?: +" org-todo-regexp "\\)?"
5137 "\\(?: +\\(.*?\\)\\)??"
5138 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5139 "[ \t]*$")
5140 org-deadline-regexp (concat "\\<" org-deadline-string)
5141 org-deadline-time-regexp
5142 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5143 org-deadline-time-hour-regexp
5144 (concat "\\<" org-deadline-string
5145 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5146 org-deadline-line-regexp
5147 (concat "\\<\\(" org-deadline-string "\\).*")
5148 org-scheduled-regexp
5149 (concat "\\<" org-scheduled-string)
5150 org-scheduled-time-regexp
5151 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5152 org-scheduled-time-hour-regexp
5153 (concat "\\<" org-scheduled-string
5154 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5155 org-closed-time-regexp
5156 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5157 org-keyword-time-regexp
5158 (concat "\\<\\(" org-scheduled-string
5159 "\\|" org-deadline-string
5160 "\\|" org-closed-string
5161 "\\|" org-clock-string "\\)"
5162 " *[[<]\\([^]>]+\\)[]>]")
5163 org-keyword-time-not-clock-regexp
5164 (concat "\\<\\(" org-scheduled-string
5165 "\\|" org-deadline-string
5166 "\\|" org-closed-string
5167 "\\)"
5168 " *[[<]\\([^]>]+\\)[]>]")
5169 org-maybe-keyword-time-regexp
5170 (concat "\\(\\<\\(" org-scheduled-string
5171 "\\|" org-deadline-string
5172 "\\|" org-closed-string
5173 "\\|" org-clock-string "\\)\\)?"
5174 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5175 org-all-time-keywords
5176 (mapcar (lambda (w) (substring w 0 -1))
5177 (list org-scheduled-string org-deadline-string
5178 org-clock-string org-closed-string)))
5179 (setq org-ota nil)
5180 (org-compute-latex-and-related-regexp))))
5182 (defun org-file-contents (file &optional noerror)
5183 "Return the contents of FILE, as a string."
5184 (if (or (not file)
5185 (not (file-readable-p file)))
5186 (if noerror
5187 (message "Cannot read file \"%s\"" file)
5188 (error "Cannot read file \"%s\"" file))
5189 (with-temp-buffer
5190 (insert-file-contents file)
5191 (buffer-string))))
5193 (defun org-extract-log-state-settings (x)
5194 "Extract the log state setting from a TODO keyword string.
5195 This will extract info from a string like \"WAIT(w@/!)\"."
5196 (let (kw key log1 log2)
5197 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5198 (setq kw (match-string 1 x)
5199 key (and (match-end 2) (match-string 2 x))
5200 log1 (and (match-end 3) (match-string 3 x))
5201 log2 (and (match-end 4) (match-string 4 x)))
5202 (and (or log1 log2)
5203 (list kw
5204 (and log1 (if (equal log1 "!") 'time 'note))
5205 (and log2 (if (equal log2 "!") 'time 'note)))))))
5207 (defun org-remove-keyword-keys (list)
5208 "Remove a pair of parenthesis at the end of each string in LIST."
5209 (mapcar (lambda (x)
5210 (if (string-match "(.*)$" x)
5211 (substring x 0 (match-beginning 0))
5213 list))
5215 (defun org-assign-fast-keys (alist)
5216 "Assign fast keys to a keyword-key alist.
5217 Respect keys that are already there."
5218 (let (new e (alt ?0))
5219 (while (setq e (pop alist))
5220 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5221 (cdr e)) ;; Key already assigned.
5222 (push e new)
5223 (let ((clist (string-to-list (downcase (car e))))
5224 (used (append new alist)))
5225 (when (= (car clist) ?@)
5226 (pop clist))
5227 (while (and clist (rassoc (car clist) used))
5228 (pop clist))
5229 (unless clist
5230 (while (rassoc alt used)
5231 (incf alt)))
5232 (push (cons (car e) (or (car clist) alt)) new))))
5233 (nreverse new)))
5235 ;;; Some variables used in various places
5237 (defvar org-window-configuration nil
5238 "Used in various places to store a window configuration.")
5239 (defvar org-selected-window nil
5240 "Used in various places to store a window configuration.")
5241 (defvar org-finish-function nil
5242 "Function to be called when `C-c C-c' is used.
5243 This is for getting out of special buffers like capture.")
5246 ;; FIXME: Occasionally check by commenting these, to make sure
5247 ;; no other functions uses these, forgetting to let-bind them.
5248 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5249 (defvar org-last-state)
5250 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5252 ;; Defined somewhere in this file, but used before definition.
5253 (defvar org-entities) ;; defined in org-entities.el
5254 (defvar org-struct-menu)
5255 (defvar org-org-menu)
5256 (defvar org-tbl-menu)
5258 ;;;; Define the Org-mode
5260 ;; We use a before-change function to check if a table might need
5261 ;; an update.
5262 (defvar org-table-may-need-update t
5263 "Indicates that a table might need an update.
5264 This variable is set by `org-before-change-function'.
5265 `org-table-align' sets it back to nil.")
5266 (defun org-before-change-function (beg end)
5267 "Every change indicates that a table might need an update."
5268 (setq org-table-may-need-update t))
5269 (defvar org-mode-map)
5270 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5271 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5272 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5273 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5274 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5275 (defvar org-table-buffer-is-an nil)
5277 (defvar bidi-paragraph-direction)
5278 (defvar buffer-face-mode-face)
5280 (require 'outline)
5281 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5282 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5283 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5285 ;; Other stuff we need.
5286 (require 'time-date)
5287 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5288 (require 'easymenu)
5289 (require 'overlay)
5291 ;; (require 'org-macs) moved higher up in the file before it is first used
5292 (require 'org-entities)
5293 ;; (require 'org-compat) moved higher up in the file before it is first used
5294 (require 'org-faces)
5295 (require 'org-list)
5296 (require 'org-pcomplete)
5297 (require 'org-src)
5298 (require 'org-footnote)
5299 (require 'org-macro)
5301 ;; babel
5302 (require 'ob)
5304 ;;;###autoload
5305 (define-derived-mode org-mode outline-mode "Org"
5306 "Outline-based notes management and organizer, alias
5307 \"Carsten's outline-mode for keeping track of everything.\"
5309 Org-mode develops organizational tasks around a NOTES file which
5310 contains information about projects as plain text. Org-mode is
5311 implemented on top of outline-mode, which is ideal to keep the content
5312 of large files well structured. It supports ToDo items, deadlines and
5313 time stamps, which magically appear in the diary listing of the Emacs
5314 calendar. Tables are easily created with a built-in table editor.
5315 Plain text URL-like links connect to websites, emails (VM), Usenet
5316 messages (Gnus), BBDB entries, and any files related to the project.
5317 For printing and sharing of notes, an Org-mode file (or a part of it)
5318 can be exported as a structured ASCII or HTML file.
5320 The following commands are available:
5322 \\{org-mode-map}"
5324 ;; Get rid of Outline menus, they are not needed
5325 ;; Need to do this here because define-derived-mode sets up
5326 ;; the keymap so late. Still, it is a waste to call this each time
5327 ;; we switch another buffer into org-mode.
5328 (if (featurep 'xemacs)
5329 (when (boundp 'outline-mode-menu-heading)
5330 ;; Assume this is Greg's port, it uses easymenu
5331 (easy-menu-remove outline-mode-menu-heading)
5332 (easy-menu-remove outline-mode-menu-show)
5333 (easy-menu-remove outline-mode-menu-hide))
5334 (define-key org-mode-map [menu-bar headings] 'undefined)
5335 (define-key org-mode-map [menu-bar hide] 'undefined)
5336 (define-key org-mode-map [menu-bar show] 'undefined))
5338 (org-load-modules-maybe)
5339 (easy-menu-add org-org-menu)
5340 (easy-menu-add org-tbl-menu)
5341 (org-install-agenda-files-menu)
5342 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5343 (add-to-invisibility-spec '(org-cwidth))
5344 (add-to-invisibility-spec '(org-hide-block . t))
5345 (when (featurep 'xemacs)
5346 (org-set-local 'line-move-ignore-invisible t))
5347 (org-set-local 'outline-regexp org-outline-regexp)
5348 (org-set-local 'outline-level 'org-outline-level)
5349 (setq bidi-paragraph-direction 'left-to-right)
5350 (when (and org-ellipsis
5351 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5352 (fboundp 'make-glyph-code))
5353 (unless org-display-table
5354 (setq org-display-table (make-display-table)))
5355 (set-display-table-slot
5356 org-display-table 4
5357 (vconcat (mapcar
5358 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5359 org-ellipsis)))
5360 (if (stringp org-ellipsis) org-ellipsis "..."))))
5361 (setq buffer-display-table org-display-table))
5362 (org-set-regexps-and-options-for-tags)
5363 (org-set-regexps-and-options)
5364 (org-set-font-lock-defaults)
5365 (when (and org-tag-faces (not org-tags-special-faces-re))
5366 ;; tag faces set outside customize.... force initialization.
5367 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5368 ;; Calc embedded
5369 (org-set-local 'calc-embedded-open-mode "# ")
5370 ;; Modify a few syntax entries
5371 (modify-syntax-entry ?@ "w")
5372 (modify-syntax-entry ?\" "\"")
5373 (if org-startup-truncated (setq truncate-lines t))
5374 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5375 (org-set-local 'font-lock-unfontify-region-function
5376 'org-unfontify-region)
5377 ;; Activate before-change-function
5378 (org-set-local 'org-table-may-need-update t)
5379 (org-add-hook 'before-change-functions 'org-before-change-function nil
5380 'local)
5381 ;; Check for running clock before killing a buffer
5382 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5383 ;; Initialize macros templates.
5384 (org-macro-initialize-templates)
5385 ;; Initialize radio targets.
5386 (org-update-radio-target-regexp)
5387 ;; Indentation.
5388 (org-set-local 'indent-line-function 'org-indent-line)
5389 (org-set-local 'indent-region-function 'org-indent-region)
5390 ;; Filling and auto-filling.
5391 (org-setup-filling)
5392 ;; Comments.
5393 (org-setup-comments-handling)
5394 ;; Beginning/end of defun
5395 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5396 (org-set-local 'end-of-defun-function 'org-forward-element)
5397 ;; Next error for sparse trees
5398 (org-set-local 'next-error-function 'org-occur-next-match)
5399 ;; Make sure dependence stuff works reliably, even for users who set it
5400 ;; too late :-(
5401 (if org-enforce-todo-dependencies
5402 (add-hook 'org-blocker-hook
5403 'org-block-todo-from-children-or-siblings-or-parent)
5404 (remove-hook 'org-blocker-hook
5405 'org-block-todo-from-children-or-siblings-or-parent))
5406 (if org-enforce-todo-checkbox-dependencies
5407 (add-hook 'org-blocker-hook
5408 'org-block-todo-from-checkboxes)
5409 (remove-hook 'org-blocker-hook
5410 'org-block-todo-from-checkboxes))
5412 ;; Align options lines
5413 (org-set-local
5414 'align-mode-rules-list
5415 '((org-in-buffer-settings
5416 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5417 (modes . '(org-mode)))))
5419 ;; Imenu
5420 (org-set-local 'imenu-create-index-function
5421 'org-imenu-get-tree)
5423 ;; Make isearch reveal context
5424 (if (or (featurep 'xemacs)
5425 (not (boundp 'outline-isearch-open-invisible-function)))
5426 ;; Emacs 21 and XEmacs make use of the hook
5427 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5428 ;; Emacs 22 deals with this through a special variable
5429 (org-set-local 'outline-isearch-open-invisible-function
5430 (lambda (&rest ignore) (org-show-context 'isearch)))
5431 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5433 ;; Setup the pcomplete hooks
5434 (set (make-local-variable 'pcomplete-command-completion-function)
5435 'org-pcomplete-initial)
5436 (set (make-local-variable 'pcomplete-command-name-function)
5437 'org-command-at-point)
5438 (set (make-local-variable 'pcomplete-default-completion-function)
5439 'ignore)
5440 (set (make-local-variable 'pcomplete-parse-arguments-function)
5441 'org-parse-arguments)
5442 (set (make-local-variable 'pcomplete-termination-string) "")
5443 (when (>= emacs-major-version 23)
5444 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5446 ;; If empty file that did not turn on org-mode automatically, make it to.
5447 (if (and org-insert-mode-line-in-empty-file
5448 (org-called-interactively-p 'any)
5449 (= (point-min) (point-max)))
5450 (insert "# -*- mode: org -*-\n\n"))
5451 (unless org-inhibit-startup
5452 (org-unmodified
5453 (and org-startup-with-beamer-mode (org-beamer-mode))
5454 (when org-startup-align-all-tables
5455 (org-table-map-tables 'org-table-align 'quietly))
5456 (when org-startup-with-inline-images
5457 (org-display-inline-images))
5458 (when org-startup-with-latex-preview
5459 (org-preview-latex-fragment))
5460 (unless org-inhibit-startup-visibility-stuff
5461 (org-set-startup-visibility))))
5462 ;; Try to set org-hide correctly
5463 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5465 ;; Update `customize-package-emacs-version-alist'
5466 (add-to-list 'customize-package-emacs-version-alist
5467 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5468 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5469 ("8.0" . "24.4")))
5471 (defvar org-mode-transpose-word-syntax-table
5472 (let ((st (make-syntax-table)))
5473 (mapc (lambda(c) (modify-syntax-entry
5474 (string-to-char (car c)) "w p" st))
5475 org-emphasis-alist)
5476 st))
5478 (when (fboundp 'abbrev-table-put)
5479 (abbrev-table-put org-mode-abbrev-table
5480 :parents (list text-mode-abbrev-table)))
5482 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5484 (defsubst org-fix-ellipsis-at-bol ()
5485 (save-excursion (goto-char (window-start)) (recenter 0)))
5487 (defun org-find-invisible-foreground ()
5488 (let ((candidates (remove
5489 "unspecified-bg"
5490 (nconc
5491 (list (face-background 'default)
5492 (face-background 'org-default))
5493 (mapcar
5494 (lambda (alist)
5495 (when (boundp alist)
5496 (cdr (assoc 'background-color (symbol-value alist)))))
5497 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5498 (list (face-foreground 'org-hide))))))
5499 (car (remove nil candidates))))
5501 (defun org-current-time (&optional rounding-minutes past)
5502 "Current time, possibly rounded to ROUNDING-MINUTES.
5503 When ROUNDING-MINUTES is not an integer, fall back on the car of
5504 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5505 the rounding returns a past time."
5506 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5507 (car org-time-stamp-rounding-minutes)))
5508 (time (decode-time)) res)
5509 (if (< r 1)
5510 (current-time)
5511 (setq res
5512 (apply 'encode-time
5513 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5514 (nthcdr 2 time))))
5515 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5516 (seconds-to-time (- (org-float-time res) (* r 60)))
5517 res))))
5519 (defun org-today ()
5520 "Return today date, considering `org-extend-today-until'."
5521 (time-to-days
5522 (time-subtract (current-time)
5523 (list 0 (* 3600 org-extend-today-until) 0))))
5525 ;;;; Font-Lock stuff, including the activators
5527 (defvar org-mouse-map (make-sparse-keymap))
5528 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5529 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5530 (when org-mouse-1-follows-link
5531 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5532 (when org-tab-follows-link
5533 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5534 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5536 (require 'font-lock)
5538 (defconst org-non-link-chars "]\t\n\r<>")
5539 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5540 "shell" "elisp" "doi" "message"))
5541 (defvar org-link-types-re nil
5542 "Matches a link that has a url-like prefix like \"http:\"")
5543 (defvar org-link-re-with-space nil
5544 "Matches a link with spaces, optional angular brackets around it.")
5545 (defvar org-link-re-with-space2 nil
5546 "Matches a link with spaces, optional angular brackets around it.")
5547 (defvar org-link-re-with-space3 nil
5548 "Matches a link with spaces, only for internal part in bracket links.")
5549 (defvar org-angle-link-re nil
5550 "Matches link with angular brackets, spaces are allowed.")
5551 (defvar org-plain-link-re nil
5552 "Matches plain link, without spaces.")
5553 (defvar org-bracket-link-regexp nil
5554 "Matches a link in double brackets.")
5555 (defvar org-bracket-link-analytic-regexp nil
5556 "Regular expression used to analyze links.
5557 Here is what the match groups contain after a match:
5558 1: http:
5559 2: http
5560 3: path
5561 4: [desc]
5562 5: desc")
5563 (defvar org-bracket-link-analytic-regexp++ nil
5564 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5565 (defvar org-any-link-re nil
5566 "Regular expression matching any link.")
5568 (defconst org-match-sexp-depth 3
5569 "Number of stacked braces for sub/superscript matching.")
5571 (defun org-create-multibrace-regexp (left right n)
5572 "Create a regular expression which will match a balanced sexp.
5573 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5574 as single character strings.
5575 The regexp returned will match the entire expression including the
5576 delimiters. It will also define a single group which contains the
5577 match except for the outermost delimiters. The maximum depth of
5578 stacked delimiters is N. Escaping delimiters is not possible."
5579 (let* ((nothing (concat "[^" left right "]*?"))
5580 (or "\\|")
5581 (re nothing)
5582 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5583 (while (> n 1)
5584 (setq n (1- n)
5585 re (concat re or next)
5586 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5587 (concat left "\\(" re "\\)" right)))
5589 (defvar org-match-substring-regexp
5590 (concat
5591 "\\(\\S-\\)\\([_^]\\)\\("
5592 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5593 "\\|"
5594 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5595 "\\|"
5596 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5597 "The regular expression matching a sub- or superscript.")
5599 (defvar org-match-substring-with-braces-regexp
5600 (concat
5601 "\\(\\S-\\)\\([_^]\\)\\("
5602 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5603 "\\)")
5604 "The regular expression matching a sub- or superscript, forcing braces.")
5606 (defun org-make-link-regexps ()
5607 "Update the link regular expressions.
5608 This should be called after the variable `org-link-types' has changed."
5609 (setq org-link-types-re
5610 (concat
5611 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5612 org-link-re-with-space
5613 (concat
5614 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5615 "\\([^" org-non-link-chars " ]"
5616 "[^" org-non-link-chars "]*"
5617 "[^" org-non-link-chars " ]\\)>?")
5618 org-link-re-with-space2
5619 (concat
5620 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5621 "\\([^" org-non-link-chars " ]"
5622 "[^\t\n\r]*"
5623 "[^" org-non-link-chars " ]\\)>?")
5624 org-link-re-with-space3
5625 (concat
5626 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5627 "\\([^" org-non-link-chars " ]"
5628 "[^\t\n\r]*\\)")
5629 org-angle-link-re
5630 (concat
5631 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5632 "\\([^" org-non-link-chars " ]"
5633 "[^" org-non-link-chars "]*"
5634 "\\)>")
5635 org-plain-link-re
5636 (concat
5637 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5638 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5639 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5640 org-bracket-link-regexp
5641 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5642 org-bracket-link-analytic-regexp
5643 (concat
5644 "\\[\\["
5645 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5646 "\\([^]]+\\)"
5647 "\\]"
5648 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5649 "\\]")
5650 org-bracket-link-analytic-regexp++
5651 (concat
5652 "\\[\\["
5653 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5654 "\\([^]]+\\)"
5655 "\\]"
5656 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5657 "\\]")
5658 org-any-link-re
5659 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5660 org-angle-link-re "\\)\\|\\("
5661 org-plain-link-re "\\)")))
5663 (org-make-link-regexps)
5665 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5666 "Regular expression for fast time stamp matching.")
5667 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5668 "Regular expression for fast time stamp matching.")
5669 (defconst org-ts-regexp0
5670 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5671 "Regular expression matching time strings for analysis.
5672 This one does not require the space after the date, so it can be used
5673 on a string that terminates immediately after the date.")
5674 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5675 "Regular expression matching time strings for analysis.")
5676 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5677 "Regular expression matching time stamps, with groups.")
5678 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5679 "Regular expression matching time stamps (also [..]), with groups.")
5680 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5681 "Regular expression matching a time stamp range.")
5682 (defconst org-tr-regexp-both
5683 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5684 "Regular expression matching a time stamp range.")
5685 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5686 org-ts-regexp "\\)?")
5687 "Regular expression matching a time stamp or time stamp range.")
5688 (defconst org-tsr-regexp-both
5689 (concat org-ts-regexp-both "\\(--?-?"
5690 org-ts-regexp-both "\\)?")
5691 "Regular expression matching a time stamp or time stamp range.
5692 The time stamps may be either active or inactive.")
5694 (defvar org-emph-face nil)
5696 (defun org-do-emphasis-faces (limit)
5697 "Run through the buffer and add overlays to emphasized strings."
5698 (let (rtn a)
5699 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5700 (if (not (= (char-after (match-beginning 3))
5701 (char-after (match-beginning 4))))
5702 (progn
5703 (setq rtn t)
5704 (setq a (assoc (match-string 3) org-emphasis-alist))
5705 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5706 'face
5707 (nth 1 a))
5708 (and (nth 4 a)
5709 (org-remove-flyspell-overlays-in
5710 (match-beginning 0) (match-end 0)))
5711 (add-text-properties (match-beginning 2) (match-end 2)
5712 '(font-lock-multiline t org-emphasis t))
5713 (when org-hide-emphasis-markers
5714 (add-text-properties (match-end 4) (match-beginning 5)
5715 '(invisible org-link))
5716 (add-text-properties (match-beginning 3) (match-end 3)
5717 '(invisible org-link)))))
5718 (backward-char 1))
5719 rtn))
5721 (defun org-emphasize (&optional char)
5722 "Insert or change an emphasis, i.e. a font like bold or italic.
5723 If there is an active region, change that region to a new emphasis.
5724 If there is no region, just insert the marker characters and position
5725 the cursor between them.
5726 CHAR should be the marker character. If it is a space, it means to
5727 remove the emphasis of the selected region.
5728 If CHAR is not given (for example in an interactive call) it will be
5729 prompted for."
5730 (interactive)
5731 (let ((erc org-emphasis-regexp-components)
5732 (prompt "")
5733 (string "") beg end move c s)
5734 (if (org-region-active-p)
5735 (setq beg (region-beginning) end (region-end)
5736 string (buffer-substring beg end))
5737 (setq move t))
5739 (unless char
5740 (message "Emphasis marker or tag: [%s]"
5741 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5742 (setq char (read-char-exclusive)))
5743 (if (equal char ?\ )
5744 (setq s "" move nil)
5745 (unless (assoc (char-to-string char) org-emphasis-alist)
5746 (user-error "No such emphasis marker: \"%c\"" char))
5747 (setq s (char-to-string char)))
5748 (while (and (> (length string) 1)
5749 (equal (substring string 0 1) (substring string -1))
5750 (assoc (substring string 0 1) org-emphasis-alist))
5751 (setq string (substring string 1 -1)))
5752 (setq string (concat s string s))
5753 (if beg (delete-region beg end))
5754 (unless (or (bolp)
5755 (string-match (concat "[" (nth 0 erc) "\n]")
5756 (char-to-string (char-before (point)))))
5757 (insert " "))
5758 (unless (or (eobp)
5759 (string-match (concat "[" (nth 1 erc) "\n]")
5760 (char-to-string (char-after (point)))))
5761 (insert " ") (backward-char 1))
5762 (insert string)
5763 (and move (backward-char 1))))
5765 (defconst org-nonsticky-props
5766 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5768 (defsubst org-rear-nonsticky-at (pos)
5769 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5771 (defun org-activate-plain-links (limit)
5772 "Run through the buffer and add overlays to links."
5773 (let (f hl)
5774 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5775 (not (org-in-src-block-p)))
5776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5777 (setq f (get-text-property (match-beginning 0) 'face))
5778 (setq hl (org-match-string-no-properties 0))
5779 (if (or (eq f 'org-tag)
5780 (and (listp f) (memq 'org-tag f)))
5782 (add-text-properties (match-beginning 0) (match-end 0)
5783 (list 'mouse-face 'highlight
5784 'face 'org-link
5785 'htmlize-link `(:uri ,hl)
5786 'keymap org-mouse-map))
5787 (org-rear-nonsticky-at (match-end 0)))
5788 t)))
5790 (defun org-activate-code (limit)
5791 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5792 (progn
5793 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5794 (remove-text-properties (match-beginning 0) (match-end 0)
5795 '(display t invisible t intangible t))
5796 t)))
5798 (defcustom org-src-fontify-natively nil
5799 "When non-nil, fontify code in code blocks."
5800 :type 'boolean
5801 :version "24.1"
5802 :group 'org-appearance
5803 :group 'org-babel)
5805 (defcustom org-allow-promoting-top-level-subtree nil
5806 "When non-nil, allow promoting a top level subtree.
5807 The leading star of the top level headline will be replaced
5808 by a #."
5809 :type 'boolean
5810 :version "24.1"
5811 :group 'org-appearance)
5813 (defun org-fontify-meta-lines-and-blocks (limit)
5814 (condition-case nil
5815 (org-fontify-meta-lines-and-blocks-1 limit)
5816 (error (message "org-mode fontification error"))))
5818 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5819 "Fontify #+ lines and blocks."
5820 (let ((case-fold-search t))
5821 (if (re-search-forward
5822 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5823 limit t)
5824 (let ((beg (match-beginning 0))
5825 (block-start (match-end 0))
5826 (block-end nil)
5827 (lang (match-string 7))
5828 (beg1 (line-beginning-position 2))
5829 (dc1 (downcase (match-string 2)))
5830 (dc3 (downcase (match-string 3)))
5831 end end1 quoting block-type ovl)
5832 (cond
5833 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5834 ;; a single line of backend-specific content
5835 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5836 (remove-text-properties (match-beginning 0) (match-end 0)
5837 '(display t invisible t intangible t))
5838 (add-text-properties (match-beginning 1) (match-end 3)
5839 '(font-lock-fontified t face org-meta-line))
5840 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5841 '(font-lock-fontified t face org-block))
5842 ; for backend-specific code
5844 ((and (match-end 4) (equal dc3 "+begin"))
5845 ;; Truly a block
5846 (setq block-type (downcase (match-string 5))
5847 quoting (member block-type org-protecting-blocks))
5848 (when (re-search-forward
5849 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5850 nil t) ;; on purpose, we look further than LIMIT
5851 (setq end (min (point-max) (match-end 0))
5852 end1 (min (point-max) (1- (match-beginning 0))))
5853 (setq block-end (match-beginning 0))
5854 (when quoting
5855 (remove-text-properties beg end
5856 '(display t invisible t intangible t)))
5857 (add-text-properties
5858 beg end
5859 '(font-lock-fontified t font-lock-multiline t))
5860 (add-text-properties beg beg1 '(face org-meta-line))
5861 (add-text-properties end1 (min (point-max) (1+ end))
5862 '(face org-meta-line)) ; for end_src
5863 (cond
5864 ((and lang (not (string= lang "")) org-src-fontify-natively)
5865 (org-src-font-lock-fontify-block lang block-start block-end)
5866 ;; remove old background overlays
5867 (mapc (lambda (ov)
5868 (if (eq (overlay-get ov 'face) 'org-block-background)
5869 (delete-overlay ov)))
5870 (overlays-at (/ (+ beg1 block-end) 2)))
5871 ;; add a background overlay
5872 (setq ovl (make-overlay beg1 block-end))
5873 (overlay-put ovl 'face 'org-block-background)
5874 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5875 (quoting
5876 (add-text-properties beg1 (min (point-max) (1+ end1))
5877 '(face org-block))) ; end of source block
5878 ((not org-fontify-quote-and-verse-blocks))
5879 ((string= block-type "quote")
5880 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5881 ((string= block-type "verse")
5882 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5883 (add-text-properties beg beg1 '(face org-block-begin-line))
5884 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5885 '(face org-block-end-line))
5887 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5888 (add-text-properties
5889 beg (match-end 3)
5890 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5891 '(font-lock-fontified t invisible t)
5892 '(font-lock-fontified t face org-document-info-keyword)))
5893 (add-text-properties
5894 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5895 (if (string-equal dc1 "+title:")
5896 '(font-lock-fontified t face org-document-title)
5897 '(font-lock-fontified t face org-document-info))))
5898 ((or (equal dc1 "+results")
5899 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5900 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5901 "+call:" "+header:" "+headers:" "+name:"))
5902 (and (match-end 4) (equal dc3 "+attr")))
5903 (add-text-properties
5904 beg (match-end 0)
5905 '(font-lock-fontified t face org-meta-line))
5907 ((member dc3 '(" " ""))
5908 (add-text-properties
5909 beg (match-end 0)
5910 '(font-lock-fontified t face font-lock-comment-face)))
5911 ((not (member (char-after beg) '(?\ ?\t)))
5912 ;; just any other in-buffer setting, but not indented
5913 (add-text-properties
5914 beg (match-end 0)
5915 '(font-lock-fontified t face org-meta-line))
5917 (t nil))))))
5919 (defun org-activate-angle-links (limit)
5920 "Run through the buffer and add overlays to links."
5921 (if (and (re-search-forward org-angle-link-re limit t)
5922 (not (org-in-src-block-p)))
5923 (progn
5924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5925 (add-text-properties (match-beginning 0) (match-end 0)
5926 (list 'mouse-face 'highlight
5927 'keymap org-mouse-map))
5928 (org-rear-nonsticky-at (match-end 0))
5929 t)))
5931 (defun org-activate-footnote-links (limit)
5932 "Run through the buffer and add overlays to footnotes."
5933 (let ((fn (org-footnote-next-reference-or-definition limit)))
5934 (when fn
5935 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5936 (org-remove-flyspell-overlays-in beg end)
5937 (add-text-properties beg end
5938 (list 'mouse-face 'highlight
5939 'keymap org-mouse-map
5940 'help-echo
5941 (if (= (point-at-bol) beg)
5942 "Footnote definition"
5943 "Footnote reference")
5944 'font-lock-fontified t
5945 'font-lock-multiline t
5946 'face 'org-footnote))))))
5948 (defun org-activate-bracket-links (limit)
5949 "Run through the buffer and add overlays to bracketed links."
5950 (if (and (re-search-forward org-bracket-link-regexp limit t)
5951 (not (org-in-src-block-p)))
5952 (let* ((hl (org-match-string-no-properties 1))
5953 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5954 (ip (org-maybe-intangible
5955 (list 'invisible 'org-link
5956 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5960 'font-lock-multiline t 'help-echo help
5961 'htmlize-link `(:uri ,hl))))
5962 ;; We need to remove the invisible property here. Table narrowing
5963 ;; may have made some of this invisible.
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (remove-text-properties (match-beginning 0) (match-end 0)
5966 '(invisible nil))
5967 (if (match-end 3)
5968 (progn
5969 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5970 (org-rear-nonsticky-at (match-beginning 3))
5971 (add-text-properties (match-beginning 3) (match-end 3) vp)
5972 (org-rear-nonsticky-at (match-end 3))
5973 (add-text-properties (match-end 3) (match-end 0) ip)
5974 (org-rear-nonsticky-at (match-end 0)))
5975 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5976 (org-rear-nonsticky-at (match-beginning 1))
5977 (add-text-properties (match-beginning 1) (match-end 1) vp)
5978 (org-rear-nonsticky-at (match-end 1))
5979 (add-text-properties (match-end 1) (match-end 0) ip)
5980 (org-rear-nonsticky-at (match-end 0)))
5981 t)))
5983 (defun org-activate-dates (limit)
5984 "Run through the buffer and add overlays to dates."
5985 (if (and (re-search-forward org-tsr-regexp-both limit t)
5986 (not (equal (char-before (match-beginning 0)) 91)))
5987 (progn
5988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (add-text-properties (match-beginning 0) (match-end 0)
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map))
5992 (org-rear-nonsticky-at (match-end 0))
5993 (when org-display-custom-times
5994 (if (match-end 3)
5995 (org-display-custom-time (match-beginning 3) (match-end 3)))
5996 (org-display-custom-time (match-beginning 1) (match-end 1)))
5997 t)))
5999 (defvar org-target-link-regexp nil
6000 "Regular expression matching radio targets in plain text.")
6001 (make-variable-buffer-local 'org-target-link-regexp)
6002 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6003 "Regular expression matching a link target.")
6004 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6005 "Regular expression matching a radio target.")
6006 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6007 "Regular expression matching any target.")
6009 (defun org-activate-target-links (limit)
6010 "Run through the buffer and add overlays to target matches."
6011 (when org-target-link-regexp
6012 (let ((case-fold-search t))
6013 (if (re-search-forward org-target-link-regexp limit t)
6014 (progn
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (add-text-properties (match-beginning 0) (match-end 0)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map
6019 'help-echo "Radio target link"
6020 'org-linked-text t))
6021 (org-rear-nonsticky-at (match-end 0))
6022 t)))))
6024 (defun org-update-radio-target-regexp ()
6025 "Find all radio targets in this file and update the regular expression."
6026 (interactive)
6027 (when (memq 'radio org-activate-links)
6028 (setq org-target-link-regexp
6029 (org-make-target-link-regexp (org-all-targets 'radio)))
6030 (org-restart-font-lock)))
6032 (defun org-hide-wide-columns (limit)
6033 (let (s e)
6034 (setq s (text-property-any (point) (or limit (point-max))
6035 'org-cwidth t))
6036 (when s
6037 (setq e (next-single-property-change s 'org-cwidth))
6038 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6039 (goto-char e)
6040 t)))
6042 (defvar org-latex-and-related-regexp nil
6043 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6044 (defvar org-match-substring-regexp)
6045 (defvar org-match-substring-with-braces-regexp)
6047 (defun org-compute-latex-and-related-regexp ()
6048 "Compute regular expression for LaTeX, entities and sub/superscript.
6049 Result depends on variable `org-highlight-latex-and-related'."
6050 (org-set-local
6051 'org-latex-and-related-regexp
6052 (let* ((re-sub
6053 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6054 ((eq org-use-sub-superscripts '{})
6055 (list org-match-substring-with-braces-regexp))
6056 (org-use-sub-superscripts (list org-match-substring-regexp))))
6057 (re-latex
6058 (when (memq 'latex org-highlight-latex-and-related)
6059 (let ((matchers (plist-get org-format-latex-options :matchers)))
6060 (delq nil
6061 (mapcar (lambda (x)
6062 (and (member (car x) matchers) (nth 1 x)))
6063 org-latex-regexps)))))
6064 (re-entities
6065 (when (memq 'entities org-highlight-latex-and-related)
6066 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6067 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6069 (defun org-do-latex-and-related (limit)
6070 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6071 LIMIT bounds the search for syntax to highlight. Stop at first
6072 highlighted object, if any. Return t if some highlighting was
6073 done, nil otherwise."
6074 (when (org-string-nw-p org-latex-and-related-regexp)
6075 (catch 'found
6076 (while (re-search-forward org-latex-and-related-regexp limit t)
6077 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6078 'face))
6079 '(org-code org-verbatim underline))
6080 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6081 '(?_ ?^))
6083 0)))
6084 (font-lock-prepend-text-property
6085 (+ offset (match-beginning 0)) (match-end 0)
6086 'face 'org-latex-and-related)
6087 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6088 '(font-lock-multiline t)))
6089 (throw 'found t)))
6090 nil)))
6092 (defun org-restart-font-lock ()
6093 "Restart `font-lock-mode', to force refontification."
6094 (when (and (boundp 'font-lock-mode) font-lock-mode)
6095 (font-lock-mode -1)
6096 (font-lock-mode 1)))
6098 (defun org-all-targets (&optional radio)
6099 "Return a list of all targets in this file.
6100 When optional argument RADIO is non-nil, only find radio
6101 targets."
6102 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6103 (save-excursion
6104 (goto-char (point-min))
6105 (while (re-search-forward re nil t)
6106 ;; Make sure point is really within the object.
6107 (backward-char)
6108 (let ((obj (org-element-context)))
6109 (when (memq (org-element-type obj) '(radio-target target))
6110 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6111 rtn)))
6113 (defun org-make-target-link-regexp (targets)
6114 "Make regular expression matching all strings in TARGETS.
6115 The regular expression finds the targets also if there is a line break
6116 between words."
6117 (and targets
6118 (concat
6119 "\\<\\("
6120 (mapconcat
6121 (lambda (x)
6122 (setq x (regexp-quote x))
6123 (while (string-match " +" x)
6124 (setq x (replace-match "\\s-+" t t x)))
6126 targets
6127 "\\|")
6128 "\\)\\>")))
6130 (defun org-activate-tags (limit)
6131 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6132 (progn
6133 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6134 (add-text-properties (match-beginning 1) (match-end 1)
6135 (list 'mouse-face 'highlight
6136 'keymap org-mouse-map))
6137 (org-rear-nonsticky-at (match-end 1))
6138 t)))
6140 (defun org-outline-level ()
6141 "Compute the outline level of the heading at point.
6142 If this is called at a normal headline, the level is the number of stars.
6143 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6144 (save-excursion
6145 (if (not (condition-case nil
6146 (org-back-to-heading t)
6147 (error nil)))
6149 (looking-at org-outline-regexp)
6150 (1- (- (match-end 0) (match-beginning 0))))))
6152 (defvar org-font-lock-keywords nil)
6154 (defsubst org-re-property (property &optional literal)
6155 "Return a regexp matching a PROPERTY line.
6156 Match group 3 will be set to the value if it exists."
6157 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6158 (if literal property (regexp-quote property))
6159 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6161 (defconst org-property-re
6162 (org-re-property ".*?" 'literal)
6163 "Regular expression matching a property line.
6164 There are four matching groups:
6165 1: :PROPKEY: including the leading and trailing colon,
6166 2: PROPKEY without the leading and trailing colon,
6167 3: PROPVAL without leading or trailing spaces,
6168 4: the indentation of the current line,
6169 5: trailing whitespace.")
6171 (defvar org-font-lock-hook nil
6172 "Functions to be called for special font lock stuff.")
6174 (defvar org-font-lock-set-keywords-hook nil
6175 "Functions that can manipulate `org-font-lock-extra-keywords'.
6176 This is called after `org-font-lock-extra-keywords' is defined, but before
6177 it is installed to be used by font lock. This can be useful if something
6178 needs to be inserted at a specific position in the font-lock sequence.")
6180 (defun org-font-lock-hook (limit)
6181 "Run `org-font-lock-hook' within LIMIT."
6182 (run-hook-with-args 'org-font-lock-hook limit))
6184 (defun org-set-font-lock-defaults ()
6185 "Set font lock defaults for the current buffer."
6186 (let* ((em org-fontify-emphasized-text)
6187 (lk org-activate-links)
6188 (org-font-lock-extra-keywords
6189 (list
6190 ;; Call the hook
6191 '(org-font-lock-hook)
6192 ;; Headlines
6193 `(,(if org-fontify-whole-heading-line
6194 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6195 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6196 (1 (org-get-level-face 1))
6197 (2 (org-get-level-face 2))
6198 (3 (org-get-level-face 3)))
6199 ;; Table lines
6200 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6201 (1 'org-table t))
6202 ;; Table internals
6203 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6204 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6205 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6206 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6207 ;; Drawers
6208 (list org-drawer-regexp '(0 'org-special-keyword t))
6209 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6210 ;; Properties
6211 (list org-property-re
6212 '(1 'org-special-keyword t)
6213 '(3 'org-property-value t))
6214 ;; Links
6215 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6216 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6217 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6218 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6219 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6220 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6221 (if (memq 'footnote lk) '(org-activate-footnote-links))
6222 ;; Targets.
6223 (list org-any-target-regexp '(0 'org-target t))
6224 ;; Diary sexps.
6225 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6226 ;; Macro
6227 '("{{{.+}}}" (0 'org-macro t))
6228 '(org-hide-wide-columns (0 nil append))
6229 ;; TODO keyword
6230 (list (format org-heading-keyword-regexp-format
6231 org-todo-regexp)
6232 '(2 (org-get-todo-face 2) t))
6233 ;; DONE
6234 (if org-fontify-done-headline
6235 (list (format org-heading-keyword-regexp-format
6236 (concat
6237 "\\(?:"
6238 (mapconcat 'regexp-quote org-done-keywords "\\|")
6239 "\\)"))
6240 '(2 'org-headline-done t))
6241 nil)
6242 ;; Priorities
6243 '(org-font-lock-add-priority-faces)
6244 ;; Tags
6245 '(org-font-lock-add-tag-faces)
6246 ;; Tags groups
6247 (if (and org-group-tags org-tag-groups-alist)
6248 (list (concat org-outline-regexp-bol ".+\\(:"
6249 (regexp-opt (mapcar 'car org-tag-groups-alist))
6250 ":\\).*$")
6251 '(1 'org-tag-group prepend)))
6252 ;; Special keywords
6253 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6254 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6255 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6256 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6257 ;; Emphasis
6258 (if em
6259 (if (featurep 'xemacs)
6260 '(org-do-emphasis-faces (0 nil append))
6261 '(org-do-emphasis-faces)))
6262 ;; Checkboxes
6263 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6264 1 'org-checkbox prepend)
6265 (if (cdr (assq 'checkbox org-list-automatic-rules))
6266 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6267 (0 (org-get-checkbox-statistics-face) t)))
6268 ;; Description list items
6269 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6270 1 'org-list-dt prepend)
6271 ;; ARCHIVEd headings
6272 (list (concat
6273 org-outline-regexp-bol
6274 "\\(.*:" org-archive-tag ":.*\\)")
6275 '(1 'org-archived prepend))
6276 ;; Specials
6277 '(org-do-latex-and-related)
6278 '(org-fontify-entities)
6279 '(org-raise-scripts)
6280 ;; Code
6281 '(org-activate-code (1 'org-code t))
6282 ;; COMMENT
6283 (list (format org-heading-keyword-regexp-format
6284 (concat "\\("
6285 org-comment-string "\\|" org-quote-string
6286 "\\)"))
6287 '(2 'org-special-keyword t))
6288 ;; Blocks and meta lines
6289 '(org-fontify-meta-lines-and-blocks))))
6290 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6291 (run-hooks 'org-font-lock-set-keywords-hook)
6292 ;; Now set the full font-lock-keywords
6293 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6294 (org-set-local 'font-lock-defaults
6295 '(org-font-lock-keywords t nil nil backward-paragraph))
6296 (kill-local-variable 'font-lock-keywords) nil))
6298 (defun org-toggle-pretty-entities ()
6299 "Toggle the composition display of entities as UTF8 characters."
6300 (interactive)
6301 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6302 (org-restart-font-lock)
6303 (if org-pretty-entities
6304 (message "Entities are now displayed as UTF8 characters")
6305 (save-restriction
6306 (widen)
6307 (org-decompose-region (point-min) (point-max))
6308 (message "Entities are now displayed as plain text"))))
6310 (defvar org-custom-properties-overlays nil
6311 "List of overlays used for custom properties.")
6312 (make-variable-buffer-local 'org-custom-properties-overlays)
6314 (defun org-toggle-custom-properties-visibility ()
6315 "Display or hide properties in `org-custom-properties'."
6316 (interactive)
6317 (if org-custom-properties-overlays
6318 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6319 (setq org-custom-properties-overlays nil))
6320 (unless (not org-custom-properties)
6321 (save-excursion
6322 (save-restriction
6323 (widen)
6324 (goto-char (point-min))
6325 (while (re-search-forward org-property-re nil t)
6326 (mapc (lambda(p)
6327 (when (equal p (substring (match-string 1) 1 -1))
6328 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6329 (overlay-put o 'invisible t)
6330 (overlay-put o 'org-custom-property t)
6331 (push o org-custom-properties-overlays))))
6332 org-custom-properties)))))))
6334 (defun org-fontify-entities (limit)
6335 "Find an entity to fontify."
6336 (let (ee)
6337 (when org-pretty-entities
6338 (catch 'match
6339 (while (re-search-forward
6340 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6341 limit t)
6342 (if (and (not (org-in-indented-comment-line))
6343 (setq ee (org-entity-get (match-string 1)))
6344 (= (length (nth 6 ee)) 1))
6345 (let*
6346 ((end (if (equal (match-string 2) "{}")
6347 (match-end 2)
6348 (match-end 1))))
6349 (add-text-properties
6350 (match-beginning 0) end
6351 (list 'font-lock-fontified t))
6352 (compose-region (match-beginning 0) end
6353 (nth 6 ee) nil)
6354 (backward-char 1)
6355 (throw 'match t))))
6356 nil))))
6358 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6359 "Fontify string S like in Org-mode."
6360 (with-temp-buffer
6361 (insert s)
6362 (let ((org-odd-levels-only odd-levels))
6363 (org-mode)
6364 (font-lock-fontify-buffer)
6365 (buffer-string))))
6367 (defvar org-m nil)
6368 (defvar org-l nil)
6369 (defvar org-f nil)
6370 (defun org-get-level-face (n)
6371 "Get the right face for match N in font-lock matching of headlines."
6372 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6373 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6374 (if org-cycle-level-faces
6375 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6376 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6377 (cond
6378 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6379 ((eq n 2) org-f)
6380 (t (if org-level-color-stars-only nil org-f))))
6383 (defun org-get-todo-face (kwd)
6384 "Get the right face for a TODO keyword KWD.
6385 If KWD is a number, get the corresponding match group."
6386 (if (numberp kwd) (setq kwd (match-string kwd)))
6387 (or (org-face-from-face-or-color
6388 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6389 (and (member kwd org-done-keywords) 'org-done)
6390 'org-todo))
6392 (defun org-face-from-face-or-color (context inherit face-or-color)
6393 "Create a face list that inherits INHERIT, but sets the foreground color.
6394 When FACE-OR-COLOR is not a string, just return it."
6395 (if (stringp face-or-color)
6396 (list :inherit inherit
6397 (cdr (assoc context org-faces-easy-properties))
6398 face-or-color)
6399 face-or-color))
6401 (defun org-font-lock-add-tag-faces (limit)
6402 "Add the special tag faces."
6403 (when (and org-tag-faces org-tags-special-faces-re)
6404 (while (re-search-forward org-tags-special-faces-re limit t)
6405 (add-text-properties (match-beginning 1) (match-end 1)
6406 (list 'face (org-get-tag-face 1)
6407 'font-lock-fontified t))
6408 (backward-char 1))))
6410 (defun org-font-lock-add-priority-faces (limit)
6411 "Add the special priority faces."
6412 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6413 (when (save-match-data (org-at-heading-p))
6414 (add-text-properties
6415 (match-beginning 0) (match-end 0)
6416 (list 'face (or (org-face-from-face-or-color
6417 'priority 'org-priority
6418 (cdr (assoc (char-after (match-beginning 1))
6419 org-priority-faces)))
6420 'org-priority)
6421 'font-lock-fontified t)))))
6423 (defun org-get-tag-face (kwd)
6424 "Get the right face for a TODO keyword KWD.
6425 If KWD is a number, get the corresponding match group."
6426 (if (numberp kwd) (setq kwd (match-string kwd)))
6427 (or (org-face-from-face-or-color
6428 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6429 'org-tag))
6431 (defun org-unfontify-region (beg end &optional maybe_loudly)
6432 "Remove fontification and activation overlays from links."
6433 (font-lock-default-unfontify-region beg end)
6434 (let* ((buffer-undo-list t)
6435 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6436 (inhibit-modification-hooks t)
6437 deactivate-mark buffer-file-name buffer-file-truename)
6438 (org-decompose-region beg end)
6439 (remove-text-properties beg end
6440 '(mouse-face t keymap t org-linked-text t
6441 invisible t intangible t
6442 org-no-flyspell t org-emphasis t))
6443 (org-remove-font-lock-display-properties beg end)))
6445 (defconst org-script-display '(((raise -0.3) (height 0.7))
6446 ((raise 0.3) (height 0.7))
6447 ((raise -0.5))
6448 ((raise 0.5)))
6449 "Display properties for showing superscripts and subscripts.")
6451 (defun org-remove-font-lock-display-properties (beg end)
6452 "Remove specific display properties that have been added by font lock.
6453 The will remove the raise properties that are used to show superscripts
6454 and subscripts."
6455 (let (next prop)
6456 (while (< beg end)
6457 (setq next (next-single-property-change beg 'display nil end)
6458 prop (get-text-property beg 'display))
6459 (if (member prop org-script-display)
6460 (put-text-property beg next 'display nil))
6461 (setq beg next))))
6463 (defun org-raise-scripts (limit)
6464 "Add raise properties to sub/superscripts."
6465 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6466 (if (re-search-forward
6467 (if (eq org-use-sub-superscripts t)
6468 org-match-substring-regexp
6469 org-match-substring-with-braces-regexp)
6470 limit t)
6471 (let* ((pos (point)) table-p comment-p
6472 (mpos (match-beginning 3))
6473 (emph-p (get-text-property mpos 'org-emphasis))
6474 (link-p (get-text-property mpos 'mouse-face))
6475 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6476 (goto-char (point-at-bol))
6477 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6478 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6479 (goto-char pos)
6480 ;; Handle a_b^c
6481 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6482 (if (or comment-p emph-p link-p keyw-p)
6484 (put-text-property (match-beginning 3) (match-end 0)
6485 'display
6486 (if (equal (char-after (match-beginning 2)) ?^)
6487 (nth (if table-p 3 1) org-script-display)
6488 (nth (if table-p 2 0) org-script-display)))
6489 (add-text-properties (match-beginning 2) (match-end 2)
6490 (list 'invisible t
6491 'org-dwidth t 'org-dwidth-n 1))
6492 (if (and (eq (char-after (match-beginning 3)) ?{)
6493 (eq (char-before (match-end 3)) ?}))
6494 (progn
6495 (add-text-properties
6496 (match-beginning 3) (1+ (match-beginning 3))
6497 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6498 (add-text-properties
6499 (1- (match-end 3)) (match-end 3)
6500 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6501 t)))))
6503 ;;;; Visibility cycling, including org-goto and indirect buffer
6505 ;;; Cycling
6507 (defvar org-cycle-global-status nil)
6508 (make-variable-buffer-local 'org-cycle-global-status)
6509 (put 'org-cycle-global-status 'org-state t)
6510 (defvar org-cycle-subtree-status nil)
6511 (make-variable-buffer-local 'org-cycle-subtree-status)
6512 (put 'org-cycle-subtree-status 'org-state t)
6514 (defvar org-inlinetask-min-level)
6516 (defun org-unlogged-message (&rest args)
6517 "Display a message, but avoid logging it in the *Messages* buffer."
6518 (let ((message-log-max nil))
6519 (apply 'message args)))
6521 ;;;###autoload
6522 (defun org-cycle (&optional arg)
6523 "TAB-action and visibility cycling for Org-mode.
6525 This is the command invoked in Org-mode by the TAB key. Its main purpose
6526 is outline visibility cycling, but it also invokes other actions
6527 in special contexts.
6529 - When this function is called with a prefix argument, rotate the entire
6530 buffer through 3 states (global cycling)
6531 1. OVERVIEW: Show only top-level headlines.
6532 2. CONTENTS: Show all headlines of all levels, but no body text.
6533 3. SHOW ALL: Show everything.
6534 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6535 determined by the variable `org-startup-folded', and by any VISIBILITY
6536 properties in the buffer.
6537 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6538 including any drawers.
6540 - When inside a table, re-align the table and move to the next field.
6542 - When point is at the beginning of a headline, rotate the subtree started
6543 by this line through 3 different states (local cycling)
6544 1. FOLDED: Only the main headline is shown.
6545 2. CHILDREN: The main headline and the direct children are shown.
6546 From this state, you can move to one of the children
6547 and zoom in further.
6548 3. SUBTREE: Show the entire subtree, including body text.
6549 If there is no subtree, switch directly from CHILDREN to FOLDED.
6551 - When point is at the beginning of an empty headline and the variable
6552 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6553 of the headline by demoting and promoting it to likely levels. This
6554 speeds up creation document structure by pressing TAB once or several
6555 times right after creating a new headline.
6557 - When there is a numeric prefix, go up to a heading with level ARG, do
6558 a `show-subtree' and return to the previous cursor position. If ARG
6559 is negative, go up that many levels.
6561 - When point is not at the beginning of a headline, execute the global
6562 binding for TAB, which is re-indenting the line. See the option
6563 `org-cycle-emulate-tab' for details.
6565 - Special case: if point is at the beginning of the buffer and there is
6566 no headline in line 1, this function will act as if called with prefix arg
6567 (C-u TAB, same as S-TAB) also when called without prefix arg.
6568 But only if also the variable `org-cycle-global-at-bob' is t."
6569 (interactive "P")
6570 (org-load-modules-maybe)
6571 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6572 (and org-cycle-level-after-item/entry-creation
6573 (or (org-cycle-level)
6574 (org-cycle-item-indentation))))
6575 (let* ((limit-level
6576 (or org-cycle-max-level
6577 (and (boundp 'org-inlinetask-min-level)
6578 org-inlinetask-min-level
6579 (1- org-inlinetask-min-level))))
6580 (nstars (and limit-level
6581 (if org-odd-levels-only
6582 (and limit-level (1- (* limit-level 2)))
6583 limit-level)))
6584 (org-outline-regexp
6585 (if (not (derived-mode-p 'org-mode))
6586 outline-regexp
6587 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6588 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6589 (not (looking-at org-outline-regexp))))
6590 (org-cycle-hook
6591 (if bob-special
6592 (delq 'org-optimize-window-after-visibility-change
6593 (copy-sequence org-cycle-hook))
6594 org-cycle-hook))
6595 (pos (point)))
6597 (if (or bob-special (equal arg '(4)))
6598 ;; special case: use global cycling
6599 (setq arg t))
6601 (cond
6603 ((equal arg '(16))
6604 (setq last-command 'dummy)
6605 (org-set-startup-visibility)
6606 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6608 ((equal arg '(64))
6609 (show-all)
6610 (org-unlogged-message "Entire buffer visible, including drawers"))
6612 ;; Table: enter it or move to the next field.
6613 ((org-at-table-p 'any)
6614 (if (org-at-table.el-p)
6615 (message "Use C-c ' to edit table.el tables")
6616 (if arg (org-table-edit-field t)
6617 (org-table-justify-field-maybe)
6618 (call-interactively 'org-table-next-field))))
6620 ((run-hook-with-args-until-success
6621 'org-tab-after-check-for-table-hook))
6623 ;; Global cycling: delegate to `org-cycle-internal-global'.
6624 ((eq arg t) (org-cycle-internal-global))
6626 ;; Drawers: delegate to `org-flag-drawer'.
6627 ((and org-drawers org-drawer-regexp
6628 (save-excursion
6629 (beginning-of-line 1)
6630 (looking-at org-drawer-regexp)))
6631 (org-flag-drawer ; toggle block visibility
6632 (not (get-char-property (match-end 0) 'invisible))))
6634 ;; Show-subtree, ARG levels up from here.
6635 ((integerp arg)
6636 (save-excursion
6637 (org-back-to-heading)
6638 (outline-up-heading (if (< arg 0) (- arg)
6639 (- (funcall outline-level) arg)))
6640 (org-show-subtree)))
6642 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6643 ((and (featurep 'org-inlinetask)
6644 (org-inlinetask-at-task-p)
6645 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6646 (org-inlinetask-toggle-visibility))
6648 ((org-try-cdlatex-tab))
6650 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6651 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6652 (save-excursion (beginning-of-line 1)
6653 (looking-at org-outline-regexp)))
6654 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6655 (org-cycle-internal-local))
6657 ;; From there: TAB emulation and template completion.
6658 (buffer-read-only (org-back-to-heading))
6660 ((run-hook-with-args-until-success
6661 'org-tab-after-check-for-cycling-hook))
6663 ((org-try-structure-completion))
6665 ((run-hook-with-args-until-success
6666 'org-tab-before-tab-emulation-hook))
6668 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6669 (or (not (bolp))
6670 (not (looking-at org-outline-regexp))))
6671 (call-interactively (global-key-binding "\t")))
6673 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6674 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6675 (or (and (eq org-cycle-emulate-tab 'white)
6676 (= (match-end 0) (point-at-eol)))
6677 (and (eq org-cycle-emulate-tab 'whitestart)
6678 (>= (match-end 0) pos))))
6680 (eq org-cycle-emulate-tab t))
6681 (call-interactively (global-key-binding "\t")))
6683 (t (save-excursion
6684 (org-back-to-heading)
6685 (org-cycle)))))))
6687 (defun org-cycle-internal-global ()
6688 "Do the global cycling action."
6689 ;; Hack to avoid display of messages for .org attachments in Gnus
6690 (let ((ga (string-match "\\*fontification" (buffer-name))))
6691 (cond
6692 ((and (eq last-command this-command)
6693 (eq org-cycle-global-status 'overview))
6694 ;; We just created the overview - now do table of contents
6695 ;; This can be slow in very large buffers, so indicate action
6696 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6697 (unless ga (org-unlogged-message "CONTENTS..."))
6698 (org-content)
6699 (unless ga (org-unlogged-message "CONTENTS...done"))
6700 (setq org-cycle-global-status 'contents)
6701 (run-hook-with-args 'org-cycle-hook 'contents))
6703 ((and (eq last-command this-command)
6704 (eq org-cycle-global-status 'contents))
6705 ;; We just showed the table of contents - now show everything
6706 (run-hook-with-args 'org-pre-cycle-hook 'all)
6707 (show-all)
6708 (unless ga (org-unlogged-message "SHOW ALL"))
6709 (setq org-cycle-global-status 'all)
6710 (run-hook-with-args 'org-cycle-hook 'all))
6713 ;; Default action: go to overview
6714 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6715 (org-overview)
6716 (unless ga (org-unlogged-message "OVERVIEW"))
6717 (setq org-cycle-global-status 'overview)
6718 (run-hook-with-args 'org-cycle-hook 'overview)))))
6720 (defun org-cycle-internal-local ()
6721 "Do the local cycling action."
6722 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6723 ;; First, determine end of headline (EOH), end of subtree or item
6724 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6725 (save-excursion
6726 (if (org-at-item-p)
6727 (progn
6728 (beginning-of-line)
6729 (setq struct (org-list-struct))
6730 (setq eoh (point-at-eol))
6731 (setq eos (org-list-get-item-end-before-blank (point) struct))
6732 (setq has-children (org-list-has-child-p (point) struct)))
6733 (org-back-to-heading)
6734 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6735 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6736 (setq has-children
6737 (or (save-excursion
6738 (let ((level (funcall outline-level)))
6739 (outline-next-heading)
6740 (and (org-at-heading-p t)
6741 (> (funcall outline-level) level))))
6742 (save-excursion
6743 (org-list-search-forward (org-item-beginning-re) eos t)))))
6744 ;; Determine end invisible part of buffer (EOL)
6745 (beginning-of-line 2)
6746 ;; XEmacs doesn't have `next-single-char-property-change'
6747 (if (featurep 'xemacs)
6748 (while (and (not (eobp)) ;; this is like `next-line'
6749 (get-char-property (1- (point)) 'invisible))
6750 (beginning-of-line 2))
6751 (while (and (not (eobp)) ;; this is like `next-line'
6752 (get-char-property (1- (point)) 'invisible))
6753 (goto-char (next-single-char-property-change (point) 'invisible))
6754 (and (eolp) (beginning-of-line 2))))
6755 (setq eol (point)))
6756 ;; Find out what to do next and set `this-command'
6757 (cond
6758 ((= eos eoh)
6759 ;; Nothing is hidden behind this heading
6760 (unless (org-before-first-heading-p)
6761 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6762 (org-unlogged-message "EMPTY ENTRY")
6763 (setq org-cycle-subtree-status nil)
6764 (save-excursion
6765 (goto-char eos)
6766 (outline-next-heading)
6767 (if (outline-invisible-p) (org-flag-heading nil))))
6768 ((and (or (>= eol eos)
6769 (not (string-match "\\S-" (buffer-substring eol eos))))
6770 (or has-children
6771 (not (setq children-skipped
6772 org-cycle-skip-children-state-if-no-children))))
6773 ;; Entire subtree is hidden in one line: children view
6774 (unless (org-before-first-heading-p)
6775 (run-hook-with-args 'org-pre-cycle-hook 'children))
6776 (if (org-at-item-p)
6777 (org-list-set-item-visibility (point-at-bol) struct 'children)
6778 (org-show-entry)
6779 (org-with-limited-levels (show-children))
6780 ;; FIXME: This slows down the func way too much.
6781 ;; How keep drawers hidden in subtree anyway?
6782 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6783 ;; (org-cycle-hide-drawers 'subtree))
6785 ;; Fold every list in subtree to top-level items.
6786 (when (eq org-cycle-include-plain-lists 'integrate)
6787 (save-excursion
6788 (org-back-to-heading)
6789 (while (org-list-search-forward (org-item-beginning-re) eos t)
6790 (beginning-of-line 1)
6791 (let* ((struct (org-list-struct))
6792 (prevs (org-list-prevs-alist struct))
6793 (end (org-list-get-bottom-point struct)))
6794 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6795 (org-list-get-all-items (point) struct prevs))
6796 (goto-char (if (< end eos) end eos)))))))
6797 (org-unlogged-message "CHILDREN")
6798 (save-excursion
6799 (goto-char eos)
6800 (outline-next-heading)
6801 (if (outline-invisible-p) (org-flag-heading nil)))
6802 (setq org-cycle-subtree-status 'children)
6803 (unless (org-before-first-heading-p)
6804 (run-hook-with-args 'org-cycle-hook 'children)))
6805 ((or children-skipped
6806 (and (eq last-command this-command)
6807 (eq org-cycle-subtree-status 'children)))
6808 ;; We just showed the children, or no children are there,
6809 ;; now show everything.
6810 (unless (org-before-first-heading-p)
6811 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6812 (outline-flag-region eoh eos nil)
6813 (org-unlogged-message
6814 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6815 (setq org-cycle-subtree-status 'subtree)
6816 (unless (org-before-first-heading-p)
6817 (run-hook-with-args 'org-cycle-hook 'subtree)))
6819 ;; Default action: hide the subtree.
6820 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6821 (outline-flag-region eoh eos t)
6822 (org-unlogged-message "FOLDED")
6823 (setq org-cycle-subtree-status 'folded)
6824 (unless (org-before-first-heading-p)
6825 (run-hook-with-args 'org-cycle-hook 'folded))))))
6827 ;;;###autoload
6828 (defun org-global-cycle (&optional arg)
6829 "Cycle the global visibility. For details see `org-cycle'.
6830 With \\[universal-argument] prefix arg, switch to startup visibility.
6831 With a numeric prefix, show all headlines up to that level."
6832 (interactive "P")
6833 (let ((org-cycle-include-plain-lists
6834 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6835 (cond
6836 ((integerp arg)
6837 (show-all)
6838 (hide-sublevels arg)
6839 (setq org-cycle-global-status 'contents))
6840 ((equal arg '(4))
6841 (org-set-startup-visibility)
6842 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6844 (org-cycle '(4))))))
6846 (defun org-set-startup-visibility ()
6847 "Set the visibility required by startup options and properties."
6848 (cond
6849 ((eq org-startup-folded t)
6850 (org-cycle '(4)))
6851 ((eq org-startup-folded 'content)
6852 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6853 (org-cycle '(4)) (org-cycle '(4)))))
6854 (unless (eq org-startup-folded 'showeverything)
6855 (if org-hide-block-startup (org-hide-block-all))
6856 (org-set-visibility-according-to-property 'no-cleanup)
6857 (org-cycle-hide-archived-subtrees 'all)
6858 (org-cycle-hide-drawers 'all)
6859 (org-cycle-show-empty-lines t)))
6861 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6862 "Switch subtree visibilities according to :VISIBILITY: property."
6863 (interactive)
6864 (let (org-show-entry-below state)
6865 (save-excursion
6866 (goto-char (point-min))
6867 (while (re-search-forward
6868 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6869 nil t)
6870 (setq state (match-string 1))
6871 (save-excursion
6872 (org-back-to-heading t)
6873 (hide-subtree)
6874 (org-reveal)
6875 (cond
6876 ((equal state '("fold" "folded"))
6877 (hide-subtree))
6878 ((equal state "children")
6879 (org-show-hidden-entry)
6880 (show-children))
6881 ((equal state "content")
6882 (save-excursion
6883 (save-restriction
6884 (org-narrow-to-subtree)
6885 (org-content))))
6886 ((member state '("all" "showall"))
6887 (show-subtree)))))
6888 (unless no-cleanup
6889 (org-cycle-hide-archived-subtrees 'all)
6890 (org-cycle-hide-drawers 'all)
6891 (org-cycle-show-empty-lines 'all)))))
6893 ;; This function uses outline-regexp instead of the more fundamental
6894 ;; org-outline-regexp so that org-cycle-global works outside of Org
6895 ;; buffers, where outline-regexp is needed.
6896 (defun org-overview ()
6897 "Switch to overview mode, showing only top-level headlines.
6898 Really, this shows all headlines with level equal or greater than the level
6899 of the first headline in the buffer. This is important, because if the
6900 first headline is not level one, then (hide-sublevels 1) gives confusing
6901 results."
6902 (interactive)
6903 (let ((pos (point))
6904 (level (save-excursion
6905 (goto-char (point-min))
6906 (if (re-search-forward (concat "^" outline-regexp) nil t)
6907 (progn
6908 (goto-char (match-beginning 0))
6909 (funcall outline-level))))))
6910 (and level (hide-sublevels level))
6911 (recenter '(4))
6912 (goto-char pos)))
6914 (defun org-content (&optional arg)
6915 "Show all headlines in the buffer, like a table of contents.
6916 With numerical argument N, show content up to level N."
6917 (interactive "P")
6918 (save-excursion
6919 ;; Visit all headings and show their offspring
6920 (and (integerp arg) (org-overview))
6921 (goto-char (point-max))
6922 (catch 'exit
6923 (while (and (progn (condition-case nil
6924 (outline-previous-visible-heading 1)
6925 (error (goto-char (point-min))))
6927 (looking-at org-outline-regexp))
6928 (if (integerp arg)
6929 (show-children (1- arg))
6930 (show-branches))
6931 (if (bobp) (throw 'exit nil))))))
6934 (defun org-optimize-window-after-visibility-change (state)
6935 "Adjust the window after a change in outline visibility.
6936 This function is the default value of the hook `org-cycle-hook'."
6937 (when (get-buffer-window (current-buffer))
6938 (cond
6939 ((eq state 'content) nil)
6940 ((eq state 'all) nil)
6941 ((eq state 'folded) nil)
6942 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6943 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6945 (defun org-remove-empty-overlays-at (pos)
6946 "Remove outline overlays that do not contain non-white stuff."
6947 (mapc
6948 (lambda (o)
6949 (and (eq 'outline (overlay-get o 'invisible))
6950 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6951 (overlay-end o))))
6952 (delete-overlay o)))
6953 (overlays-at pos)))
6955 (defun org-clean-visibility-after-subtree-move ()
6956 "Fix visibility issues after moving a subtree."
6957 ;; First, find a reasonable region to look at:
6958 ;; Start two siblings above, end three below
6959 (let* ((beg (save-excursion
6960 (and (org-get-last-sibling)
6961 (org-get-last-sibling))
6962 (point)))
6963 (end (save-excursion
6964 (and (org-get-next-sibling)
6965 (org-get-next-sibling)
6966 (org-get-next-sibling))
6967 (if (org-at-heading-p)
6968 (point-at-eol)
6969 (point))))
6970 (level (looking-at "\\*+"))
6971 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6972 (save-excursion
6973 (save-restriction
6974 (narrow-to-region beg end)
6975 (when re
6976 ;; Properly fold already folded siblings
6977 (goto-char (point-min))
6978 (while (re-search-forward re nil t)
6979 (if (and (not (outline-invisible-p))
6980 (save-excursion
6981 (goto-char (point-at-eol)) (outline-invisible-p)))
6982 (hide-entry))))
6983 (org-cycle-show-empty-lines 'overview)
6984 (org-cycle-hide-drawers 'overview)))))
6986 (defun org-cycle-show-empty-lines (state)
6987 "Show empty lines above all visible headlines.
6988 The region to be covered depends on STATE when called through
6989 `org-cycle-hook'. Lisp program can use t for STATE to get the
6990 entire buffer covered. Note that an empty line is only shown if there
6991 are at least `org-cycle-separator-lines' empty lines before the headline."
6992 (when (not (= org-cycle-separator-lines 0))
6993 (save-excursion
6994 (let* ((n (abs org-cycle-separator-lines))
6995 (re (cond
6996 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6997 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6998 (t (let ((ns (number-to-string (- n 2))))
6999 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7000 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7001 beg end b e)
7002 (cond
7003 ((memq state '(overview contents t))
7004 (setq beg (point-min) end (point-max)))
7005 ((memq state '(children folded))
7006 (setq beg (point) end (progn (org-end-of-subtree t t)
7007 (beginning-of-line 2)
7008 (point)))))
7009 (when beg
7010 (goto-char beg)
7011 (while (re-search-forward re end t)
7012 (unless (get-char-property (match-end 1) 'invisible)
7013 (setq e (match-end 1))
7014 (if (< org-cycle-separator-lines 0)
7015 (setq b (save-excursion
7016 (goto-char (match-beginning 0))
7017 (org-back-over-empty-lines)
7018 (if (save-excursion
7019 (goto-char (max (point-min) (1- (point))))
7020 (org-at-heading-p))
7021 (1- (point))
7022 (point))))
7023 (setq b (match-beginning 1)))
7024 (outline-flag-region b e nil)))))))
7025 ;; Never hide empty lines at the end of the file.
7026 (save-excursion
7027 (goto-char (point-max))
7028 (outline-previous-heading)
7029 (outline-end-of-heading)
7030 (if (and (looking-at "[ \t\n]+")
7031 (= (match-end 0) (point-max)))
7032 (outline-flag-region (point) (match-end 0) nil))))
7034 (defun org-show-empty-lines-in-parent ()
7035 "Move to the parent and re-show empty lines before visible headlines."
7036 (save-excursion
7037 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7038 (org-cycle-show-empty-lines context))))
7040 (defun org-files-list ()
7041 "Return `org-agenda-files' list, plus all open org-mode files.
7042 This is useful for operations that need to scan all of a user's
7043 open and agenda-wise Org files."
7044 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7045 (dolist (buf (buffer-list))
7046 (with-current-buffer buf
7047 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7048 (let ((file (expand-file-name (buffer-file-name))))
7049 (unless (member file files)
7050 (push file files))))))
7051 files))
7053 (defsubst org-entry-beginning-position ()
7054 "Return the beginning position of the current entry."
7055 (save-excursion (outline-back-to-heading t) (point)))
7057 (defsubst org-entry-end-position ()
7058 "Return the end position of the current entry."
7059 (save-excursion (outline-next-heading) (point)))
7061 (defun org-cycle-hide-drawers (state)
7062 "Re-hide all drawers after a visibility state change."
7063 (when (and (derived-mode-p 'org-mode)
7064 (not (memq state '(overview folded contents))))
7065 (save-excursion
7066 (let* ((globalp (memq state '(contents all)))
7067 (beg (if globalp (point-min) (point)))
7068 (end (if globalp (point-max)
7069 (if (eq state 'children)
7070 (save-excursion (outline-next-heading) (point))
7071 (org-end-of-subtree t)))))
7072 (goto-char beg)
7073 (while (re-search-forward org-drawer-regexp end t)
7074 (org-flag-drawer t))))))
7076 (defun org-cycle-hide-inline-tasks (state)
7077 "Re-hide inline task when switching to 'contents visibility state."
7078 (when (and (eq state 'contents)
7079 (boundp 'org-inlinetask-min-level)
7080 org-inlinetask-min-level)
7081 (hide-sublevels (1- org-inlinetask-min-level))))
7083 (defun org-flag-drawer (flag)
7084 "When FLAG is non-nil, hide the drawer we are within.
7085 Otherwise make it visible."
7086 (save-excursion
7087 (beginning-of-line 1)
7088 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7089 (let ((b (match-end 0)))
7090 (if (re-search-forward
7091 "^[ \t]*:END:"
7092 (save-excursion (outline-next-heading) (point)) t)
7093 (outline-flag-region b (point-at-eol) flag)
7094 (user-error ":END: line missing at position %s" b))))))
7096 (defun org-subtree-end-visible-p ()
7097 "Is the end of the current subtree visible?"
7098 (pos-visible-in-window-p
7099 (save-excursion (org-end-of-subtree t) (point))))
7101 (defun org-first-headline-recenter (&optional N)
7102 "Move cursor to the first headline and recenter the headline.
7103 Optional argument N means put the headline into the Nth line of the window."
7104 (goto-char (point-min))
7105 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7106 (beginning-of-line)
7107 (recenter (prefix-numeric-value N))))
7109 ;;; Saving and restoring visibility
7111 (defun org-outline-overlay-data (&optional use-markers)
7112 "Return a list of the locations of all outline overlays.
7113 These are overlays with the `invisible' property value `outline'.
7114 The return value is a list of cons cells, with start and stop
7115 positions for each overlay.
7116 If USE-MARKERS is set, return the positions as markers."
7117 (let (beg end)
7118 (save-excursion
7119 (save-restriction
7120 (widen)
7121 (delq nil
7122 (mapcar (lambda (o)
7123 (when (eq (overlay-get o 'invisible) 'outline)
7124 (setq beg (overlay-start o)
7125 end (overlay-end o))
7126 (and beg end (> end beg)
7127 (if use-markers
7128 (cons (move-marker (make-marker) beg)
7129 (move-marker (make-marker) end))
7130 (cons beg end)))))
7131 (overlays-in (point-min) (point-max))))))))
7133 (defun org-set-outline-overlay-data (data)
7134 "Create visibility overlays for all positions in DATA.
7135 DATA should have been made by `org-outline-overlay-data'."
7136 (let (o)
7137 (save-excursion
7138 (save-restriction
7139 (widen)
7140 (show-all)
7141 (mapc (lambda (c)
7142 (outline-flag-region (car c) (cdr c) t))
7143 data)))))
7145 ;;; Folding of blocks
7147 (defvar org-hide-block-overlays nil
7148 "Overlays hiding blocks.")
7149 (make-variable-buffer-local 'org-hide-block-overlays)
7151 (defun org-block-map (function &optional start end)
7152 "Call FUNCTION at the head of all source blocks in the current buffer.
7153 Optional arguments START and END can be used to limit the range."
7154 (let ((start (or start (point-min)))
7155 (end (or end (point-max))))
7156 (save-excursion
7157 (goto-char start)
7158 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7159 (save-excursion
7160 (save-match-data
7161 (goto-char (match-beginning 0))
7162 (funcall function)))))))
7164 (defun org-hide-block-toggle-all ()
7165 "Toggle the visibility of all blocks in the current buffer."
7166 (org-block-map #'org-hide-block-toggle))
7168 (defun org-hide-block-all ()
7169 "Fold all blocks in the current buffer."
7170 (interactive)
7171 (org-show-block-all)
7172 (org-block-map #'org-hide-block-toggle-maybe))
7174 (defun org-show-block-all ()
7175 "Unfold all blocks in the current buffer."
7176 (interactive)
7177 (mapc 'delete-overlay org-hide-block-overlays)
7178 (setq org-hide-block-overlays nil))
7180 (defun org-hide-block-toggle-maybe ()
7181 "Toggle visibility of block at point."
7182 (interactive)
7183 (let ((case-fold-search t))
7184 (if (save-excursion
7185 (beginning-of-line 1)
7186 (looking-at org-block-regexp))
7187 (progn (org-hide-block-toggle)
7188 t) ;; to signal that we took action
7189 nil))) ;; to signal that we did not
7191 (defun org-hide-block-toggle (&optional force)
7192 "Toggle the visibility of the current block."
7193 (interactive)
7194 (save-excursion
7195 (beginning-of-line)
7196 (if (re-search-forward org-block-regexp nil t)
7197 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7198 (end (match-end 0)) ;; end of entire body
7200 (if (memq t (mapcar (lambda (overlay)
7201 (eq (overlay-get overlay 'invisible)
7202 'org-hide-block))
7203 (overlays-at start)))
7204 (if (or (not force) (eq force 'off))
7205 (mapc (lambda (ov)
7206 (when (member ov org-hide-block-overlays)
7207 (setq org-hide-block-overlays
7208 (delq ov org-hide-block-overlays)))
7209 (when (eq (overlay-get ov 'invisible)
7210 'org-hide-block)
7211 (delete-overlay ov)))
7212 (overlays-at start)))
7213 (setq ov (make-overlay start end))
7214 (overlay-put ov 'invisible 'org-hide-block)
7215 ;; make the block accessible to isearch
7216 (overlay-put
7217 ov 'isearch-open-invisible
7218 (lambda (ov)
7219 (when (member ov org-hide-block-overlays)
7220 (setq org-hide-block-overlays
7221 (delq ov org-hide-block-overlays)))
7222 (when (eq (overlay-get ov 'invisible)
7223 'org-hide-block)
7224 (delete-overlay ov))))
7225 (push ov org-hide-block-overlays)))
7226 (user-error "Not looking at a source block"))))
7228 ;; org-tab-after-check-for-cycling-hook
7229 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7230 ;; Remove overlays when changing major mode
7231 (add-hook 'org-mode-hook
7232 (lambda () (org-add-hook 'change-major-mode-hook
7233 'org-show-block-all 'append 'local)))
7235 ;;; Org-goto
7237 (defvar org-goto-window-configuration nil)
7238 (defvar org-goto-marker nil)
7239 (defvar org-goto-map)
7240 (defun org-goto-map ()
7241 "Set the keymap `org-goto'."
7242 (setq org-goto-map
7243 (let ((map (make-sparse-keymap)))
7244 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7245 mouse-drag-region universal-argument org-occur))
7246 cmd)
7247 (while (setq cmd (pop cmds))
7248 (substitute-key-definition cmd cmd map global-map)))
7249 (suppress-keymap map)
7250 (org-defkey map "\C-m" 'org-goto-ret)
7251 (org-defkey map [(return)] 'org-goto-ret)
7252 (org-defkey map [(left)] 'org-goto-left)
7253 (org-defkey map [(right)] 'org-goto-right)
7254 (org-defkey map [(control ?g)] 'org-goto-quit)
7255 (org-defkey map "\C-i" 'org-cycle)
7256 (org-defkey map [(tab)] 'org-cycle)
7257 (org-defkey map [(down)] 'outline-next-visible-heading)
7258 (org-defkey map [(up)] 'outline-previous-visible-heading)
7259 (if org-goto-auto-isearch
7260 (if (fboundp 'define-key-after)
7261 (define-key-after map [t] 'org-goto-local-auto-isearch)
7262 nil)
7263 (org-defkey map "q" 'org-goto-quit)
7264 (org-defkey map "n" 'outline-next-visible-heading)
7265 (org-defkey map "p" 'outline-previous-visible-heading)
7266 (org-defkey map "f" 'outline-forward-same-level)
7267 (org-defkey map "b" 'outline-backward-same-level)
7268 (org-defkey map "u" 'outline-up-heading))
7269 (org-defkey map "/" 'org-occur)
7270 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7271 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7272 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7273 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7274 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7275 map)))
7277 (defconst org-goto-help
7278 "Browse buffer copy, to find location or copy text.%s
7279 RET=jump to location C-g=quit and return to previous location
7280 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7282 (defvar org-goto-start-pos) ; dynamically scoped parameter
7284 (defun org-goto (&optional alternative-interface)
7285 "Look up a different location in the current file, keeping current visibility.
7287 When you want look-up or go to a different location in a
7288 document, the fastest way is often to fold the entire buffer and
7289 then dive into the tree. This method has the disadvantage, that
7290 the previous location will be folded, which may not be what you
7291 want.
7293 This command works around this by showing a copy of the current
7294 buffer in an indirect buffer, in overview mode. You can dive
7295 into the tree in that copy, use org-occur and incremental search
7296 to find a location. When pressing RET or `Q', the command
7297 returns to the original buffer in which the visibility is still
7298 unchanged. After RET it will also jump to the location selected
7299 in the indirect buffer and expose the headline hierarchy above.
7301 With a prefix argument, use the alternative interface: e.g. if
7302 `org-goto-interface' is 'outline use 'outline-path-completion."
7303 (interactive "P")
7304 (org-goto-map)
7305 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7306 (org-refile-use-outline-path t)
7307 (org-refile-target-verify-function nil)
7308 (interface
7309 (if (not alternative-interface)
7310 org-goto-interface
7311 (if (eq org-goto-interface 'outline)
7312 'outline-path-completion
7313 'outline)))
7314 (org-goto-start-pos (point))
7315 (selected-point
7316 (if (eq interface 'outline)
7317 (car (org-get-location (current-buffer) org-goto-help))
7318 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7319 (org-refile-check-position pa)
7320 (nth 3 pa)))))
7321 (if selected-point
7322 (progn
7323 (org-mark-ring-push org-goto-start-pos)
7324 (goto-char selected-point)
7325 (if (or (outline-invisible-p) (org-invisible-p2))
7326 (org-show-context 'org-goto)))
7327 (message "Quit"))))
7329 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7330 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7331 (defvar org-goto-local-auto-isearch-map) ; defined below
7333 (defun org-get-location (buf help)
7334 "Let the user select a location in the Org-mode buffer BUF.
7335 This function uses a recursive edit. It returns the selected position
7336 or nil."
7337 (org-no-popups
7338 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7339 (isearch-hide-immediately nil)
7340 (isearch-search-fun-function
7341 (lambda () 'org-goto-local-search-headings))
7342 (org-goto-selected-point org-goto-exit-command))
7343 (save-excursion
7344 (save-window-excursion
7345 (delete-other-windows)
7346 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7347 (org-pop-to-buffer-same-window
7348 (condition-case nil
7349 (make-indirect-buffer (current-buffer) "*org-goto*")
7350 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7351 (with-output-to-temp-buffer "*Org Help*"
7352 (princ (format help (if org-goto-auto-isearch
7353 " Just type for auto-isearch."
7354 " n/p/f/b/u to navigate, q to quit."))))
7355 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7356 (setq buffer-read-only nil)
7357 (let ((org-startup-truncated t)
7358 (org-startup-folded nil)
7359 (org-startup-align-all-tables nil))
7360 (org-mode)
7361 (org-overview))
7362 (setq buffer-read-only t)
7363 (if (and (boundp 'org-goto-start-pos)
7364 (integer-or-marker-p org-goto-start-pos))
7365 (let ((org-show-hierarchy-above t)
7366 (org-show-siblings t)
7367 (org-show-following-heading t))
7368 (goto-char org-goto-start-pos)
7369 (and (outline-invisible-p) (org-show-context)))
7370 (goto-char (point-min)))
7371 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7372 (message "Select location and press RET")
7373 (use-local-map org-goto-map)
7374 (recursive-edit)))
7375 (kill-buffer "*org-goto*")
7376 (cons org-goto-selected-point org-goto-exit-command))))
7378 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7379 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7380 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7381 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7383 (defun org-goto-local-search-headings (string bound noerror)
7384 "Search and make sure that any matches are in headlines."
7385 (catch 'return
7386 (while (if isearch-forward
7387 (search-forward string bound noerror)
7388 (search-backward string bound noerror))
7389 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7390 (and (member :headline context)
7391 (not (member :tags context))))
7392 (throw 'return (point))))))
7394 (defun org-goto-local-auto-isearch ()
7395 "Start isearch."
7396 (interactive)
7397 (goto-char (point-min))
7398 (let ((keys (this-command-keys)))
7399 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7400 (isearch-mode t)
7401 (isearch-process-search-char (string-to-char keys)))))
7403 (defun org-goto-ret (&optional arg)
7404 "Finish `org-goto' by going to the new location."
7405 (interactive "P")
7406 (setq org-goto-selected-point (point)
7407 org-goto-exit-command 'return)
7408 (throw 'exit nil))
7410 (defun org-goto-left ()
7411 "Finish `org-goto' by going to the new location."
7412 (interactive)
7413 (if (org-at-heading-p)
7414 (progn
7415 (beginning-of-line 1)
7416 (setq org-goto-selected-point (point)
7417 org-goto-exit-command 'left)
7418 (throw 'exit nil))
7419 (user-error "Not on a heading")))
7421 (defun org-goto-right ()
7422 "Finish `org-goto' by going to the new location."
7423 (interactive)
7424 (if (org-at-heading-p)
7425 (progn
7426 (setq org-goto-selected-point (point)
7427 org-goto-exit-command 'right)
7428 (throw 'exit nil))
7429 (user-error "Not on a heading")))
7431 (defun org-goto-quit ()
7432 "Finish `org-goto' without cursor motion."
7433 (interactive)
7434 (setq org-goto-selected-point nil)
7435 (setq org-goto-exit-command 'quit)
7436 (throw 'exit nil))
7438 ;;; Indirect buffer display of subtrees
7440 (defvar org-indirect-dedicated-frame nil
7441 "This is the frame being used for indirect tree display.")
7442 (defvar org-last-indirect-buffer nil)
7444 (defun org-tree-to-indirect-buffer (&optional arg)
7445 "Create indirect buffer and narrow it to current subtree.
7446 With a numerical prefix ARG, go up to this level and then take that tree.
7447 If ARG is negative, go up that many levels.
7449 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7450 indirect buffer previously made with this command, to avoid proliferation of
7451 indirect buffers. However, when you call the command with a \
7452 \\[universal-argument] prefix, or
7453 when `org-indirect-buffer-display' is `new-frame', the last buffer
7454 is kept so that you can work with several indirect buffers at the same time.
7455 If `org-indirect-buffer-display' is `dedicated-frame', the \
7456 \\[universal-argument] prefix also
7457 requests that a new frame be made for the new buffer, so that the dedicated
7458 frame is not changed."
7459 (interactive "P")
7460 (let ((cbuf (current-buffer))
7461 (cwin (selected-window))
7462 (pos (point))
7463 beg end level heading ibuf)
7464 (save-excursion
7465 (org-back-to-heading t)
7466 (when (numberp arg)
7467 (setq level (org-outline-level))
7468 (if (< arg 0) (setq arg (+ level arg)))
7469 (while (> (setq level (org-outline-level)) arg)
7470 (org-up-heading-safe)))
7471 (setq beg (point)
7472 heading (org-get-heading))
7473 (org-end-of-subtree t t)
7474 (if (org-at-heading-p) (backward-char 1))
7475 (setq end (point)))
7476 (if (and (buffer-live-p org-last-indirect-buffer)
7477 (not (eq org-indirect-buffer-display 'new-frame))
7478 (not arg))
7479 (kill-buffer org-last-indirect-buffer))
7480 (setq ibuf (org-get-indirect-buffer cbuf)
7481 org-last-indirect-buffer ibuf)
7482 (cond
7483 ((or (eq org-indirect-buffer-display 'new-frame)
7484 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7485 (select-frame (make-frame))
7486 (delete-other-windows)
7487 (org-pop-to-buffer-same-window ibuf)
7488 (org-set-frame-title heading))
7489 ((eq org-indirect-buffer-display 'dedicated-frame)
7490 (raise-frame
7491 (select-frame (or (and org-indirect-dedicated-frame
7492 (frame-live-p org-indirect-dedicated-frame)
7493 org-indirect-dedicated-frame)
7494 (setq org-indirect-dedicated-frame (make-frame)))))
7495 (delete-other-windows)
7496 (org-pop-to-buffer-same-window ibuf)
7497 (org-set-frame-title (concat "Indirect: " heading)))
7498 ((eq org-indirect-buffer-display 'current-window)
7499 (org-pop-to-buffer-same-window ibuf))
7500 ((eq org-indirect-buffer-display 'other-window)
7501 (pop-to-buffer ibuf))
7502 (t (error "Invalid value")))
7503 (if (featurep 'xemacs)
7504 (save-excursion (org-mode) (turn-on-font-lock)))
7505 (narrow-to-region beg end)
7506 (show-all)
7507 (goto-char pos)
7508 (run-hook-with-args 'org-cycle-hook 'all)
7509 (and (window-live-p cwin) (select-window cwin))))
7511 (defun org-get-indirect-buffer (&optional buffer)
7512 (setq buffer (or buffer (current-buffer)))
7513 (let ((n 1) (base (buffer-name buffer)) bname)
7514 (while (buffer-live-p
7515 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7516 (setq n (1+ n)))
7517 (condition-case nil
7518 (make-indirect-buffer buffer bname 'clone)
7519 (error (make-indirect-buffer buffer bname)))))
7521 (defun org-set-frame-title (title)
7522 "Set the title of the current frame to the string TITLE."
7523 ;; FIXME: how to name a single frame in XEmacs???
7524 (unless (featurep 'xemacs)
7525 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7527 ;;;; Structure editing
7529 ;;; Inserting headlines
7531 (defun org-previous-line-empty-p (&optional next)
7532 "Is the previous line a blank line?
7533 When NEXT is non-nil, check the next line instead."
7534 (save-excursion
7535 (and (not (bobp))
7536 (or (beginning-of-line (if next 2 0)) t)
7537 (save-match-data
7538 (looking-at "[ \t]*$")))))
7540 (defun org-insert-heading (&optional arg invisible-ok)
7541 "Insert a new heading or item with same depth at point.
7542 If point is in a plain list and ARG is nil, create a new list item.
7543 With one universal prefix argument, insert a heading even in lists.
7544 With two universal prefix arguments, insert the heading at the end
7545 of the parent subtree.
7547 If point is at the beginning of a headline, insert a sibling before
7548 the current headline. If point is not at the beginning, split the line
7549 and create a new headline with the text in the current line after point
7550 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7552 If point is at the beginning of a normal line, turn this line into
7553 a heading.
7555 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7556 This is important for non-interactive uses of the command."
7557 (interactive "P")
7558 (if (org-called-interactively-p 'any) (org-reveal))
7559 (let ((itemp (org-in-item-p))
7560 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7561 (respect-content (or org-insert-heading-respect-content
7562 (equal arg '(16))))
7563 (initial-content "")
7564 (adjust-empty-lines t))
7566 (cond
7568 ((or (= (buffer-size) 0)
7569 (and (not (save-excursion
7570 (and (ignore-errors (org-back-to-heading invisible-ok))
7571 (org-at-heading-p))))
7572 (or arg (not itemp))))
7573 ;; At beginning of buffer or so high up that only a heading
7574 ;; makes sense.
7575 (insert
7576 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7577 (if (org-in-src-block-p) ",* " "* "))
7578 (run-hooks 'org-insert-heading-hook))
7580 ((and itemp (not (equal arg '(4))))
7581 ;; Insert an item
7582 (org-insert-item))
7585 ;; Insert a heading
7586 (save-restriction
7587 (widen)
7588 (let* ((level nil)
7589 (on-heading (org-at-heading-p))
7590 (empty-line-p (if on-heading
7591 (org-previous-line-empty-p)
7592 ;; We will decide later
7593 nil))
7594 ;; Get a level string to fall back on
7595 (fix-level
7596 (save-excursion
7597 (org-back-to-heading t)
7598 (if (org-previous-line-empty-p) (setq empty-line-p t))
7599 (looking-at org-outline-regexp)
7600 (make-string (1- (length (match-string 0))) ?*)))
7601 (stars
7602 (save-excursion
7603 (condition-case nil
7604 (progn
7605 (org-back-to-heading invisible-ok)
7606 (when (and (not on-heading)
7607 (featurep 'org-inlinetask)
7608 (integerp org-inlinetask-min-level)
7609 (>= (length (match-string 0))
7610 org-inlinetask-min-level))
7611 ;; Find a heading level before the inline task
7612 (while (and (setq level (org-up-heading-safe))
7613 (>= level org-inlinetask-min-level)))
7614 (if (org-at-heading-p)
7615 (org-back-to-heading invisible-ok)
7616 (error "This should not happen")))
7617 (unless (and (save-excursion
7618 (save-match-data
7619 (org-backward-heading-same-level
7620 1 invisible-ok))
7621 (= (point) (match-beginning 0)))
7622 (not (org-previous-line-empty-p t)))
7623 (setq empty-line-p (or empty-line-p
7624 (org-previous-line-empty-p))))
7625 (match-string 0))
7626 (error (or fix-level "* ")))))
7627 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7628 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7629 pos hide-previous previous-pos)
7631 ;; If we insert after content, move there and clean up whitespace
7632 (when respect-content
7633 (org-end-of-subtree nil t)
7634 (skip-chars-backward " \r\n")
7635 (and (looking-at "[ \t]+") (replace-match ""))
7636 (unless (eobp) (forward-char 1))
7637 (when (looking-at "^\\*")
7638 (unless (bobp) (backward-char 1))
7639 (insert "\n")))
7641 ;; If we are splitting, grab the text that should be moved to the new headline
7642 (when may-split
7643 (if (org-on-heading-p)
7644 ;; This is a heading, we split intelligently (keeping tags)
7645 (let ((pos (point)))
7646 (goto-char (point-at-bol))
7647 (unless (looking-at org-complex-heading-regexp)
7648 (error "This should not happen"))
7649 (when (and (match-beginning 4)
7650 (> pos (match-beginning 4))
7651 (< pos (match-end 4)))
7652 (setq initial-content (buffer-substring pos (match-end 4)))
7653 (goto-char pos)
7654 (delete-region (point) (match-end 4))
7655 (if (looking-at "[ \t]*$")
7656 (replace-match "")
7657 (insert (make-string (length initial-content) ?\ )))
7658 (setq initial-content (org-trim initial-content)))
7659 (goto-char pos))
7660 ;; a normal line
7661 (unless (bolp)
7662 (setq initial-content (buffer-substring (point) (point-at-eol)))
7663 (delete-region (point) (point-at-eol))
7664 (setq initial-content (org-trim initial-content)))))
7666 ;; If we are at the beginning of the line, insert before it. Else after
7667 (cond
7668 ((and (bolp) (looking-at "[ \t]*$")))
7669 ((and (bolp) (not (looking-at "[ \t]*$")))
7670 (open-line 1))
7672 (goto-char (point-at-eol))
7673 (insert "\n")))
7675 ;; Insert the new heading
7676 (insert stars)
7677 (just-one-space)
7678 (insert initial-content)
7679 (when adjust-empty-lines
7680 (if (or (not blank)
7681 (and blank (not (org-previous-line-empty-p))))
7682 (org-N-empty-lines-before-current (if blank 1 0))))
7683 (run-hooks 'org-insert-heading-hook)))))))
7685 (defun org-N-empty-lines-before-current (N)
7686 "Make the number of empty lines before current exactly N.
7687 So this will delete or add empty lines."
7688 (save-excursion
7689 (goto-char (point-at-bol))
7690 (if (looking-back "\\s-+" nil 'greedy)
7691 (replace-match ""))
7692 (or (bobp) (insert "\n"))
7693 (while (> N 0)
7694 (insert "\n")
7695 (setq N (1- N)))))
7697 (defun org-get-heading (&optional no-tags no-todo)
7698 "Return the heading of the current entry, without the stars.
7699 When NO-TAGS is non-nil, don't include tags.
7700 When NO-TODO is non-nil, don't include TODO keywords."
7701 (save-excursion
7702 (org-back-to-heading t)
7703 (cond
7704 ((and no-tags no-todo)
7705 (looking-at org-complex-heading-regexp)
7706 (match-string 4))
7707 (no-tags
7708 (looking-at (concat org-outline-regexp
7709 "\\(.*?\\)"
7710 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7711 (match-string 1))
7712 (no-todo
7713 (looking-at org-todo-line-regexp)
7714 (match-string 3))
7715 (t (looking-at org-heading-regexp)
7716 (match-string 2)))))
7718 (defvar orgstruct-mode) ; defined below
7720 (defun org-heading-components ()
7721 "Return the components of the current heading.
7722 This is a list with the following elements:
7723 - the level as an integer
7724 - the reduced level, different if `org-odd-levels-only' is set.
7725 - the TODO keyword, or nil
7726 - the priority character, like ?A, or nil if no priority is given
7727 - the headline text itself, or the tags string if no headline text
7728 - the tags string, or nil."
7729 (save-excursion
7730 (org-back-to-heading t)
7731 (if (let (case-fold-search)
7732 (looking-at
7733 (if orgstruct-mode
7734 org-heading-regexp
7735 org-complex-heading-regexp)))
7736 (if orgstruct-mode
7737 (list (length (match-string 1))
7738 (org-reduced-level (length (match-string 1)))
7741 (match-string 2)
7742 nil)
7743 (list (length (match-string 1))
7744 (org-reduced-level (length (match-string 1)))
7745 (org-match-string-no-properties 2)
7746 (and (match-end 3) (aref (match-string 3) 2))
7747 (org-match-string-no-properties 4)
7748 (org-match-string-no-properties 5))))))
7750 (defun org-get-entry ()
7751 "Get the entry text, after heading, entire subtree."
7752 (save-excursion
7753 (org-back-to-heading t)
7754 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7756 (defun org-insert-heading-after-current ()
7757 "Insert a new heading with same level as current, after current subtree."
7758 (interactive)
7759 (org-back-to-heading)
7760 (org-insert-heading)
7761 (org-move-subtree-down)
7762 (end-of-line 1))
7764 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7765 "Insert heading with `org-insert-heading-respect-content' set to t."
7766 (interactive "P")
7767 (let ((org-insert-heading-respect-content t))
7768 (org-insert-heading '(4) invisible-ok)))
7770 (defun org-insert-todo-heading-respect-content (&optional force-state)
7771 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7772 (interactive "P")
7773 (let ((org-insert-heading-respect-content t))
7774 (org-insert-todo-heading force-state '(4))))
7776 (defun org-insert-todo-heading (arg &optional force-heading)
7777 "Insert a new heading with the same level and TODO state as current heading.
7778 If the heading has no TODO state, or if the state is DONE, use the first
7779 state (TODO by default). Also one prefix arg, force first state. With two
7780 prefix args, force inserting at the end of the parent subtree."
7781 (interactive "P")
7782 (when (or force-heading (not (org-insert-item 'checkbox)))
7783 (org-insert-heading (or (and (equal arg '(16)) '(16))
7784 force-heading))
7785 (save-excursion
7786 (org-back-to-heading)
7787 (outline-previous-heading)
7788 (looking-at org-todo-line-regexp))
7789 (let*
7790 ((new-mark-x
7791 (if (or arg
7792 (not (match-beginning 2))
7793 (member (match-string 2) org-done-keywords))
7794 (car org-todo-keywords-1)
7795 (match-string 2)))
7796 (new-mark
7798 (run-hook-with-args-until-success
7799 'org-todo-get-default-hook new-mark-x nil)
7800 new-mark-x)))
7801 (beginning-of-line 1)
7802 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7803 (if org-treat-insert-todo-heading-as-state-change
7804 (org-todo new-mark)
7805 (insert new-mark " "))))
7806 (when org-provide-todo-statistics
7807 (org-update-parent-todo-statistics))))
7809 (defun org-insert-subheading (arg)
7810 "Insert a new subheading and demote it.
7811 Works for outline headings and for plain lists alike."
7812 (interactive "P")
7813 (org-insert-heading arg)
7814 (cond
7815 ((org-at-heading-p) (org-do-demote))
7816 ((org-at-item-p) (org-indent-item))))
7818 (defun org-insert-todo-subheading (arg)
7819 "Insert a new subheading with TODO keyword or checkbox and demote it.
7820 Works for outline headings and for plain lists alike."
7821 (interactive "P")
7822 (org-insert-todo-heading arg)
7823 (cond
7824 ((org-at-heading-p) (org-do-demote))
7825 ((org-at-item-p) (org-indent-item))))
7827 ;;; Promotion and Demotion
7829 (defvar org-after-demote-entry-hook nil
7830 "Hook run after an entry has been demoted.
7831 The cursor will be at the beginning of the entry.
7832 When a subtree is being demoted, the hook will be called for each node.")
7834 (defvar org-after-promote-entry-hook nil
7835 "Hook run after an entry has been promoted.
7836 The cursor will be at the beginning of the entry.
7837 When a subtree is being promoted, the hook will be called for each node.")
7839 (defun org-promote-subtree ()
7840 "Promote the entire subtree.
7841 See also `org-promote'."
7842 (interactive)
7843 (save-excursion
7844 (org-with-limited-levels (org-map-tree 'org-promote)))
7845 (org-fix-position-after-promote))
7847 (defun org-demote-subtree ()
7848 "Demote the entire subtree. See `org-demote'.
7849 See also `org-promote'."
7850 (interactive)
7851 (save-excursion
7852 (org-with-limited-levels (org-map-tree 'org-demote)))
7853 (org-fix-position-after-promote))
7856 (defun org-do-promote ()
7857 "Promote the current heading higher up the tree.
7858 If the region is active in `transient-mark-mode', promote all headings
7859 in the region."
7860 (interactive)
7861 (save-excursion
7862 (if (org-region-active-p)
7863 (org-map-region 'org-promote (region-beginning) (region-end))
7864 (org-promote)))
7865 (org-fix-position-after-promote))
7867 (defun org-do-demote ()
7868 "Demote the current heading lower down the tree.
7869 If the region is active in `transient-mark-mode', demote all headings
7870 in the region."
7871 (interactive)
7872 (save-excursion
7873 (if (org-region-active-p)
7874 (org-map-region 'org-demote (region-beginning) (region-end))
7875 (org-demote)))
7876 (org-fix-position-after-promote))
7878 (defun org-fix-position-after-promote ()
7879 "Make sure that after pro/demotion cursor position is right."
7880 (let ((pos (point)))
7881 (when (save-excursion
7882 (beginning-of-line 1)
7883 (looking-at org-todo-line-regexp)
7884 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7885 (cond ((eobp) (insert " "))
7886 ((eolp) (insert " "))
7887 ((equal (char-after) ?\ ) (forward-char 1))))))
7889 (defun org-current-level ()
7890 "Return the level of the current entry, or nil if before the first headline.
7891 The level is the number of stars at the beginning of the headline."
7892 (save-excursion
7893 (org-with-limited-levels
7894 (if (ignore-errors (org-back-to-heading t))
7895 (funcall outline-level)))))
7897 (defun org-get-previous-line-level ()
7898 "Return the outline depth of the last headline before the current line.
7899 Returns 0 for the first headline in the buffer, and nil if before the
7900 first headline."
7901 (let ((current-level (org-current-level))
7902 (prev-level (when (> (line-number-at-pos) 1)
7903 (save-excursion
7904 (beginning-of-line 0)
7905 (org-current-level)))))
7906 (cond ((null current-level) nil) ; Before first headline
7907 ((null prev-level) 0) ; At first headline
7908 (prev-level))))
7910 (defun org-reduced-level (l)
7911 "Compute the effective level of a heading.
7912 This takes into account the setting of `org-odd-levels-only'."
7913 (cond
7914 ((zerop l) 0)
7915 (org-odd-levels-only (1+ (floor (/ l 2))))
7916 (t l)))
7918 (defun org-level-increment ()
7919 "Return the number of stars that will be added or removed at a
7920 time to headlines when structure editing, based on the value of
7921 `org-odd-levels-only'."
7922 (if org-odd-levels-only 2 1))
7924 (defun org-get-valid-level (level &optional change)
7925 "Rectify a level change under the influence of `org-odd-levels-only'
7926 LEVEL is a current level, CHANGE is by how much the level should be
7927 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7928 even level numbers will become the next higher odd number."
7929 (if org-odd-levels-only
7930 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7931 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7932 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7933 (max 1 (+ level (or change 0)))))
7935 (if (boundp 'define-obsolete-function-alias)
7936 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7937 (define-obsolete-function-alias 'org-get-legal-level
7938 'org-get-valid-level)
7939 (define-obsolete-function-alias 'org-get-legal-level
7940 'org-get-valid-level "23.1")))
7942 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7943 ;; ̀org-with-limited-levels'
7944 (defun org-promote ()
7945 "Promote the current heading higher up the tree.
7946 If the region is active in `transient-mark-mode', promote all headings
7947 in the region."
7948 (org-back-to-heading t)
7949 (let* ((level (save-match-data (funcall outline-level)))
7950 (after-change-functions (remove 'flyspell-after-change-function
7951 after-change-functions))
7952 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7953 (diff (abs (- level (length up-head) -1))))
7954 (cond ((and (= level 1) org-called-with-limited-levels
7955 org-allow-promoting-top-level-subtree)
7956 (replace-match "# " nil t))
7957 ((= level 1)
7958 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7959 (t (replace-match up-head nil t)))
7960 ;; Fixup tag positioning
7961 (unless (= level 1)
7962 (and org-auto-align-tags (org-set-tags nil t))
7963 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7964 (run-hooks 'org-after-promote-entry-hook)))
7966 (defun org-demote ()
7967 "Demote the current heading lower down the tree.
7968 If the region is active in `transient-mark-mode', demote all headings
7969 in the region."
7970 (org-back-to-heading t)
7971 (let* ((level (save-match-data (funcall outline-level)))
7972 (after-change-functions (remove 'flyspell-after-change-function
7973 after-change-functions))
7974 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7975 (diff (abs (- level (length down-head) -1))))
7976 (replace-match down-head nil t)
7977 ;; Fixup tag positioning
7978 (and org-auto-align-tags (org-set-tags nil t))
7979 (if org-adapt-indentation (org-fixup-indentation diff))
7980 (run-hooks 'org-after-demote-entry-hook)))
7982 (defun org-cycle-level ()
7983 "Cycle the level of an empty headline through possible states.
7984 This goes first to child, then to parent, level, then up the hierarchy.
7985 After top level, it switches back to sibling level."
7986 (interactive)
7987 (let ((org-adapt-indentation nil))
7988 (when (org-point-at-end-of-empty-headline)
7989 (setq this-command 'org-cycle-level) ; Only needed for caching
7990 (let ((cur-level (org-current-level))
7991 (prev-level (org-get-previous-line-level)))
7992 (cond
7993 ;; If first headline in file, promote to top-level.
7994 ((= prev-level 0)
7995 (loop repeat (/ (- cur-level 1) (org-level-increment))
7996 do (org-do-promote)))
7997 ;; If same level as prev, demote one.
7998 ((= prev-level cur-level)
7999 (org-do-demote))
8000 ;; If parent is top-level, promote to top level if not already.
8001 ((= prev-level 1)
8002 (loop repeat (/ (- cur-level 1) (org-level-increment))
8003 do (org-do-promote)))
8004 ;; If top-level, return to prev-level.
8005 ((= cur-level 1)
8006 (loop repeat (/ (- prev-level 1) (org-level-increment))
8007 do (org-do-demote)))
8008 ;; If less than prev-level, promote one.
8009 ((< cur-level prev-level)
8010 (org-do-promote))
8011 ;; If deeper than prev-level, promote until higher than
8012 ;; prev-level.
8013 ((> cur-level prev-level)
8014 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8015 do (org-do-promote))))
8016 t))))
8018 (defun org-map-tree (fun)
8019 "Call FUN for every heading underneath the current one."
8020 (org-back-to-heading)
8021 (let ((level (funcall outline-level)))
8022 (save-excursion
8023 (funcall fun)
8024 (while (and (progn
8025 (outline-next-heading)
8026 (> (funcall outline-level) level))
8027 (not (eobp)))
8028 (funcall fun)))))
8030 (defun org-map-region (fun beg end)
8031 "Call FUN for every heading between BEG and END."
8032 (let ((org-ignore-region t))
8033 (save-excursion
8034 (setq end (copy-marker end))
8035 (goto-char beg)
8036 (if (and (re-search-forward org-outline-regexp-bol nil t)
8037 (< (point) end))
8038 (funcall fun))
8039 (while (and (progn
8040 (outline-next-heading)
8041 (< (point) end))
8042 (not (eobp)))
8043 (funcall fun)))))
8045 (defvar org-property-end-re) ; silence byte-compiler
8046 (defun org-fixup-indentation (diff)
8047 "Change the indentation in the current entry by DIFF.
8048 However, if any line in the current entry has no indentation, or if it
8049 would end up with no indentation after the change, nothing at all is done."
8050 (save-excursion
8051 (let ((end (save-excursion (outline-next-heading)
8052 (point-marker)))
8053 (prohibit (if (> diff 0)
8054 "^\\S-"
8055 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8056 col)
8057 (unless (save-excursion (end-of-line 1)
8058 (re-search-forward prohibit end t))
8059 (while (and (< (point) end)
8060 (re-search-forward "^[ \t]+" end t))
8061 (goto-char (match-end 0))
8062 (setq col (current-column))
8063 (if (< diff 0) (replace-match ""))
8064 (org-indent-to-column (+ diff col))))
8065 (move-marker end nil))))
8067 (defun org-convert-to-odd-levels ()
8068 "Convert an org-mode file with all levels allowed to one with odd levels.
8069 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8070 level 5 etc."
8071 (interactive)
8072 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8073 (let ((outline-level 'org-outline-level)
8074 (org-odd-levels-only nil) n)
8075 (save-excursion
8076 (goto-char (point-min))
8077 (while (re-search-forward "^\\*\\*+ " nil t)
8078 (setq n (- (length (match-string 0)) 2))
8079 (while (>= (setq n (1- n)) 0)
8080 (org-demote))
8081 (end-of-line 1))))))
8083 (defun org-convert-to-oddeven-levels ()
8084 "Convert an org-mode file with only odd levels to one with odd/even levels.
8085 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8086 file contains a section with an even level, conversion would
8087 destroy the structure of the file. An error is signaled in this
8088 case."
8089 (interactive)
8090 (goto-char (point-min))
8091 ;; First check if there are no even levels
8092 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8093 (org-show-context t)
8094 (error "Not all levels are odd in this file. Conversion not possible"))
8095 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8096 (let ((outline-regexp org-outline-regexp)
8097 (outline-level 'org-outline-level)
8098 (org-odd-levels-only nil) n)
8099 (save-excursion
8100 (goto-char (point-min))
8101 (while (re-search-forward "^\\*\\*+ " nil t)
8102 (setq n (/ (1- (length (match-string 0))) 2))
8103 (while (>= (setq n (1- n)) 0)
8104 (org-promote))
8105 (end-of-line 1))))))
8107 (defun org-tr-level (n)
8108 "Make N odd if required."
8109 (if org-odd-levels-only (1+ (/ n 2)) n))
8111 ;;; Vertical tree motion, cutting and pasting of subtrees
8113 (defun org-move-subtree-up (&optional arg)
8114 "Move the current subtree up past ARG headlines of the same level."
8115 (interactive "p")
8116 (org-move-subtree-down (- (prefix-numeric-value arg))))
8118 (defun org-move-subtree-down (&optional arg)
8119 "Move the current subtree down past ARG headlines of the same level."
8120 (interactive "p")
8121 (setq arg (prefix-numeric-value arg))
8122 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8123 'org-get-last-sibling))
8124 (ins-point (make-marker))
8125 (cnt (abs arg))
8126 (col (current-column))
8127 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8128 ;; Select the tree
8129 (org-back-to-heading)
8130 (setq beg0 (point))
8131 (save-excursion
8132 (setq ne-beg (org-back-over-empty-lines))
8133 (setq beg (point)))
8134 (save-match-data
8135 (save-excursion (outline-end-of-heading)
8136 (setq folded (outline-invisible-p)))
8137 (outline-end-of-subtree))
8138 (outline-next-heading)
8139 (setq ne-end (org-back-over-empty-lines))
8140 (setq end (point))
8141 (goto-char beg0)
8142 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8143 ;; include less whitespace
8144 (save-excursion
8145 (goto-char beg)
8146 (forward-line (- ne-beg ne-end))
8147 (setq beg (point))))
8148 ;; Find insertion point, with error handling
8149 (while (> cnt 0)
8150 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8151 (progn (goto-char beg0)
8152 (user-error "Cannot move past superior level or buffer limit")))
8153 (setq cnt (1- cnt)))
8154 (if (> arg 0)
8155 ;; Moving forward - still need to move over subtree
8156 (progn (org-end-of-subtree t t)
8157 (save-excursion
8158 (org-back-over-empty-lines)
8159 (or (bolp) (newline)))))
8160 (setq ne-ins (org-back-over-empty-lines))
8161 (move-marker ins-point (point))
8162 (setq txt (buffer-substring beg end))
8163 (org-save-markers-in-region beg end)
8164 (delete-region beg end)
8165 (org-remove-empty-overlays-at beg)
8166 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8167 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8168 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8169 (let ((bbb (point)))
8170 (insert-before-markers txt)
8171 (org-reinstall-markers-in-region bbb)
8172 (move-marker ins-point bbb))
8173 (or (bolp) (insert "\n"))
8174 (setq ins-end (point))
8175 (goto-char ins-point)
8176 (org-skip-whitespace)
8177 (when (and (< arg 0)
8178 (org-first-sibling-p)
8179 (> ne-ins ne-beg))
8180 ;; Move whitespace back to beginning
8181 (save-excursion
8182 (goto-char ins-end)
8183 (let ((kill-whole-line t))
8184 (kill-line (- ne-ins ne-beg)) (point)))
8185 (insert (make-string (- ne-ins ne-beg) ?\n)))
8186 (move-marker ins-point nil)
8187 (if folded
8188 (hide-subtree)
8189 (org-show-entry)
8190 (show-children)
8191 (org-cycle-hide-drawers 'children))
8192 (org-clean-visibility-after-subtree-move)
8193 ;; move back to the initial column we were at
8194 (move-to-column col)))
8196 (defvar org-subtree-clip ""
8197 "Clipboard for cut and paste of subtrees.
8198 This is actually only a copy of the kill, because we use the normal kill
8199 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8201 (defvar org-subtree-clip-folded nil
8202 "Was the last copied subtree folded?
8203 This is used to fold the tree back after pasting.")
8205 (defun org-cut-subtree (&optional n)
8206 "Cut the current subtree into the clipboard.
8207 With prefix arg N, cut this many sequential subtrees.
8208 This is a short-hand for marking the subtree and then cutting it."
8209 (interactive "p")
8210 (org-copy-subtree n 'cut))
8212 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8213 "Copy the current subtree it in the clipboard.
8214 With prefix arg N, copy this many sequential subtrees.
8215 This is a short-hand for marking the subtree and then copying it.
8216 If CUT is non-nil, actually cut the subtree.
8217 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8218 of some markers in the region, even if CUT is non-nil. This is
8219 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8220 (interactive "p")
8221 (let (beg end folded (beg0 (point)))
8222 (if (org-called-interactively-p 'any)
8223 (org-back-to-heading nil) ; take what looks like a subtree
8224 (org-back-to-heading t)) ; take what is really there
8225 (setq beg (point))
8226 (skip-chars-forward " \t\r\n")
8227 (save-match-data
8228 (if nosubtrees
8229 (outline-next-heading)
8230 (save-excursion (outline-end-of-heading)
8231 (setq folded (outline-invisible-p)))
8232 (condition-case nil
8233 (org-forward-heading-same-level (1- n) t)
8234 (error nil))
8235 (org-end-of-subtree t t)))
8236 (setq end (point))
8237 (goto-char beg0)
8238 (when (> end beg)
8239 (setq org-subtree-clip-folded folded)
8240 (when (or cut force-store-markers)
8241 (org-save-markers-in-region beg end))
8242 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8243 (setq org-subtree-clip (current-kill 0))
8244 (message "%s: Subtree(s) with %d characters"
8245 (if cut "Cut" "Copied")
8246 (length org-subtree-clip)))))
8248 (defun org-paste-subtree (&optional level tree for-yank)
8249 "Paste the clipboard as a subtree, with modification of headline level.
8250 The entire subtree is promoted or demoted in order to match a new headline
8251 level.
8253 If the cursor is at the beginning of a headline, the same level as
8254 that headline is used to paste the tree.
8256 If not, the new level is derived from the *visible* headings
8257 before and after the insertion point, and taken to be the inferior headline
8258 level of the two. So if the previous visible heading is level 3 and the
8259 next is level 4 (or vice versa), level 4 will be used for insertion.
8260 This makes sure that the subtree remains an independent subtree and does
8261 not swallow low level entries.
8263 You can also force a different level, either by using a numeric prefix
8264 argument, or by inserting the heading marker by hand. For example, if the
8265 cursor is after \"*****\", then the tree will be shifted to level 5.
8267 If optional TREE is given, use this text instead of the kill ring.
8269 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8270 move back over whitespace before inserting, and move point to the end of
8271 the inserted text when done."
8272 (interactive "P")
8273 (setq tree (or tree (and kill-ring (current-kill 0))))
8274 (unless (org-kill-is-subtree-p tree)
8275 (user-error "%s"
8276 (substitute-command-keys
8277 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8278 (org-with-limited-levels
8279 (let* ((visp (not (outline-invisible-p)))
8280 (txt tree)
8281 (^re_ "\\(\\*+\\)[ \t]*")
8282 (old-level (if (string-match org-outline-regexp-bol txt)
8283 (- (match-end 0) (match-beginning 0) 1)
8284 -1))
8285 (force-level (cond (level (prefix-numeric-value level))
8286 ((and (looking-at "[ \t]*$")
8287 (string-match
8288 "^\\*+$" (buffer-substring
8289 (point-at-bol) (point))))
8290 (- (match-end 1) (match-beginning 1)))
8291 ((and (bolp)
8292 (looking-at org-outline-regexp))
8293 (- (match-end 0) (point) 1))))
8294 (previous-level (save-excursion
8295 (condition-case nil
8296 (progn
8297 (outline-previous-visible-heading 1)
8298 (if (looking-at ^re_)
8299 (- (match-end 0) (match-beginning 0) 1)
8301 (error 1))))
8302 (next-level (save-excursion
8303 (condition-case nil
8304 (progn
8305 (or (looking-at org-outline-regexp)
8306 (outline-next-visible-heading 1))
8307 (if (looking-at ^re_)
8308 (- (match-end 0) (match-beginning 0) 1)
8310 (error 1))))
8311 (new-level (or force-level (max previous-level next-level)))
8312 (shift (if (or (= old-level -1)
8313 (= new-level -1)
8314 (= old-level new-level))
8316 (- new-level old-level)))
8317 (delta (if (> shift 0) -1 1))
8318 (func (if (> shift 0) 'org-demote 'org-promote))
8319 (org-odd-levels-only nil)
8320 beg end newend)
8321 ;; Remove the forced level indicator
8322 (if force-level
8323 (delete-region (point-at-bol) (point)))
8324 ;; Paste
8325 (beginning-of-line (if (bolp) 1 2))
8326 (setq beg (point))
8327 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8328 (insert-before-markers txt)
8329 (unless (string-match "\n\\'" txt) (insert "\n"))
8330 (setq newend (point))
8331 (org-reinstall-markers-in-region beg)
8332 (setq end (point))
8333 (goto-char beg)
8334 (skip-chars-forward " \t\n\r")
8335 (setq beg (point))
8336 (if (and (outline-invisible-p) visp)
8337 (save-excursion (outline-show-heading)))
8338 ;; Shift if necessary
8339 (unless (= shift 0)
8340 (save-restriction
8341 (narrow-to-region beg end)
8342 (while (not (= shift 0))
8343 (org-map-region func (point-min) (point-max))
8344 (setq shift (+ delta shift)))
8345 (goto-char (point-min))
8346 (setq newend (point-max))))
8347 (when (or (org-called-interactively-p 'interactive) for-yank)
8348 (message "Clipboard pasted as level %d subtree" new-level))
8349 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8350 kill-ring
8351 (eq org-subtree-clip (current-kill 0))
8352 org-subtree-clip-folded)
8353 ;; The tree was folded before it was killed/copied
8354 (hide-subtree))
8355 (and for-yank (goto-char newend)))))
8357 (defun org-kill-is-subtree-p (&optional txt)
8358 "Check if the current kill is an outline subtree, or a set of trees.
8359 Returns nil if kill does not start with a headline, or if the first
8360 headline level is not the largest headline level in the tree.
8361 So this will actually accept several entries of equal levels as well,
8362 which is OK for `org-paste-subtree'.
8363 If optional TXT is given, check this string instead of the current kill."
8364 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8365 (re (org-get-limited-outline-regexp))
8366 (^re (concat "^" re))
8367 (start-level (and kill
8368 (string-match
8369 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8370 kill)
8371 (- (match-end 2) (match-beginning 2) 1)))
8372 (start (1+ (or (match-beginning 2) -1))))
8373 (if (not start-level)
8374 (progn
8375 nil) ;; does not even start with a heading
8376 (catch 'exit
8377 (while (setq start (string-match ^re kill (1+ start)))
8378 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8379 (throw 'exit nil)))
8380 t))))
8382 (defvar org-markers-to-move nil
8383 "Markers that should be moved with a cut-and-paste operation.
8384 Those markers are stored together with their positions relative to
8385 the start of the region.")
8387 (defun org-save-markers-in-region (beg end)
8388 "Check markers in region.
8389 If these markers are between BEG and END, record their position relative
8390 to BEG, so that after moving the block of text, we can put the markers back
8391 into place.
8392 This function gets called just before an entry or tree gets cut from the
8393 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8394 called immediately, to move the markers with the entries."
8395 (setq org-markers-to-move nil)
8396 (when (featurep 'org-clock)
8397 (org-clock-save-markers-for-cut-and-paste beg end))
8398 (when (featurep 'org-agenda)
8399 (org-agenda-save-markers-for-cut-and-paste beg end)))
8401 (defun org-check-and-save-marker (marker beg end)
8402 "Check if MARKER is between BEG and END.
8403 If yes, remember the marker and the distance to BEG."
8404 (when (and (marker-buffer marker)
8405 (equal (marker-buffer marker) (current-buffer)))
8406 (if (and (>= marker beg) (< marker end))
8407 (push (cons marker (- marker beg)) org-markers-to-move))))
8409 (defun org-reinstall-markers-in-region (beg)
8410 "Move all remembered markers to their position relative to BEG."
8411 (mapc (lambda (x)
8412 (move-marker (car x) (+ beg (cdr x))))
8413 org-markers-to-move)
8414 (setq org-markers-to-move nil))
8416 (defun org-narrow-to-subtree ()
8417 "Narrow buffer to the current subtree."
8418 (interactive)
8419 (save-excursion
8420 (save-match-data
8421 (org-with-limited-levels
8422 (narrow-to-region
8423 (progn (org-back-to-heading t) (point))
8424 (progn (org-end-of-subtree t t)
8425 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8426 (point)))))))
8428 (defun org-narrow-to-block ()
8429 "Narrow buffer to the current block."
8430 (interactive)
8431 (let* ((case-fold-search t)
8432 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8433 "^[ \t]*#\\+end_.*")))
8434 (if blockp
8435 (narrow-to-region (car blockp) (cdr blockp))
8436 (user-error "Not in a block"))))
8438 (eval-when-compile
8439 (defvar org-property-drawer-re))
8441 (defvar org-property-start-re) ;; defined below
8442 (defun org-clone-subtree-with-time-shift (n &optional shift)
8443 "Clone the task (subtree) at point N times.
8444 The clones will be inserted as siblings.
8446 In interactive use, the user will be prompted for the number of
8447 clones to be produced. If the entry has a timestamp, the user
8448 will also be prompted for a time shift, which may be a repeater
8449 as used in time stamps, for example `+3d'. To disable this,
8450 you can call the function with a universal prefix argument.
8452 When a valid repeater is given and the entry contains any time
8453 stamps, the clones will become a sequence in time, with time
8454 stamps in the subtree shifted for each clone produced. If SHIFT
8455 is nil or the empty string, time stamps will be left alone. The
8456 ID property of the original subtree is removed.
8458 If the original subtree did contain time stamps with a repeater,
8459 the following will happen:
8460 - the repeater will be removed in each clone
8461 - an additional clone will be produced, with the current, unshifted
8462 date(s) in the entry.
8463 - the original entry will be placed *after* all the clones, with
8464 repeater intact.
8465 - the start days in the repeater in the original entry will be shifted
8466 to past the last clone.
8467 In this way you can spell out a number of instances of a repeating task,
8468 and still retain the repeater to cover future instances of the task."
8469 (interactive "nNumber of clones to produce: ")
8470 (let ((shift
8471 (or shift
8472 (if (and (not (equal current-prefix-arg '(4)))
8473 (save-excursion
8474 (re-search-forward org-ts-regexp-both
8475 (save-excursion
8476 (org-end-of-subtree t)
8477 (point)) t)))
8478 (read-from-minibuffer
8479 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8480 ""))) ;; No time shift
8481 (n-no-remove -1)
8482 (drawer-re org-drawer-regexp)
8483 beg end template task idprop
8484 shift-n shift-what doshift nmin nmax)
8485 (if (not (and (integerp n) (> n 0)))
8486 (error "Invalid number of replications %s" n))
8487 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8488 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8489 shift)))
8490 (error "Invalid shift specification %s" shift))
8491 (when doshift
8492 (setq shift-n (string-to-number (match-string 1 shift))
8493 shift-what (cdr (assoc (match-string 2 shift)
8494 '(("d" . day) ("w" . week)
8495 ("m" . month) ("y" . year))))))
8496 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8497 (setq nmin 1 nmax n)
8498 (org-back-to-heading t)
8499 (setq beg (point))
8500 (setq idprop (org-entry-get nil "ID"))
8501 (org-end-of-subtree t t)
8502 (or (bolp) (insert "\n"))
8503 (setq end (point))
8504 (setq template (buffer-substring beg end))
8505 (when (and doshift
8506 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8507 (delete-region beg end)
8508 (setq end beg)
8509 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8510 (goto-char end)
8511 (loop for n from nmin to nmax do
8512 ;; prepare clone
8513 (with-temp-buffer
8514 (insert template)
8515 (org-mode)
8516 (goto-char (point-min))
8517 (org-show-subtree)
8518 (and idprop (if org-clone-delete-id
8519 (org-entry-delete nil "ID")
8520 (org-id-get-create t)))
8521 (unless (= n 0)
8522 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8523 (kill-whole-line))
8524 (goto-char (point-min))
8525 (while (re-search-forward drawer-re nil t)
8526 (mapc (lambda (d)
8527 (org-remove-empty-drawer-at d (point))) org-drawers)))
8528 (goto-char (point-min))
8529 (when doshift
8530 (while (re-search-forward org-ts-regexp-both nil t)
8531 (org-timestamp-change (* n shift-n) shift-what))
8532 (unless (= n n-no-remove)
8533 (goto-char (point-min))
8534 (while (re-search-forward org-ts-regexp nil t)
8535 (save-excursion
8536 (goto-char (match-beginning 0))
8537 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8538 (delete-region (match-beginning 1) (match-end 1)))))))
8539 (setq task (buffer-string)))
8540 (insert task))
8541 (goto-char beg)))
8543 ;;; Outline Sorting
8545 (defun org-sort (with-case)
8546 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8547 Optional argument WITH-CASE means sort case-sensitively."
8548 (interactive "P")
8549 (cond
8550 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8551 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8553 (org-call-with-arg 'org-sort-entries with-case))))
8555 (defun org-sort-remove-invisible (s)
8556 "Remove invisible links from string S."
8557 (remove-text-properties 0 (length s) org-rm-props s)
8558 (while (string-match org-bracket-link-regexp s)
8559 (setq s (replace-match (if (match-end 2)
8560 (match-string 3 s)
8561 (match-string 1 s)) t t s)))
8562 (let ((st (format " %s " s)))
8563 (while (string-match org-emph-re st)
8564 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8565 (setq s (substring st 1 -1)))
8568 (defvar org-priority-regexp) ; defined later in the file
8570 (defvar org-after-sorting-entries-or-items-hook nil
8571 "Hook that is run after a bunch of entries or items have been sorted.
8572 When children are sorted, the cursor is in the parent line when this
8573 hook gets called. When a region or a plain list is sorted, the cursor
8574 will be in the first entry of the sorted region/list.")
8576 (defun org-sort-entries
8577 (&optional with-case sorting-type getkey-func compare-func property)
8578 "Sort entries on a certain level of an outline tree.
8579 If there is an active region, the entries in the region are sorted.
8580 Else, if the cursor is before the first entry, sort the top-level items.
8581 Else, the children of the entry at point are sorted.
8583 Sorting can be alphabetically, numerically, by date/time as given by
8584 a time stamp, by a property, by priority order, or by a custom function.
8586 The command prompts for the sorting type unless it has been given to the
8587 function through the SORTING-TYPE argument, which needs to be a character,
8588 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8589 precise meaning of each character:
8591 n Numerically, by converting the beginning of the entry/item to a number.
8592 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8593 o By order of TODO keywords.
8594 t By date/time, either the first active time stamp in the entry, or, if
8595 none exist, by the first inactive one.
8596 s By the scheduled date/time.
8597 d By deadline date/time.
8598 c By creation time, which is assumed to be the first inactive time stamp
8599 at the beginning of a line.
8600 p By priority according to the cookie.
8601 r By the value of a property.
8603 Capital letters will reverse the sort order.
8605 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8606 called with point at the beginning of the record. It must return either
8607 a string or a number that should serve as the sorting key for that record.
8609 Comparing entries ignores case by default. However, with an optional argument
8610 WITH-CASE, the sorting considers case as well.
8612 Sorting is done against the visible part of the headlines, it ignores hidden
8613 links."
8614 (interactive "P")
8615 (let ((case-func (if with-case 'identity 'downcase))
8616 (cmstr
8617 ;; The clock marker is lost when using `sort-subr', let's
8618 ;; store the clocking string.
8619 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8620 (save-excursion
8621 (goto-char org-clock-marker)
8622 (looking-back "^.*") (match-string-no-properties 0))))
8623 start beg end stars re re2
8624 txt what tmp)
8625 ;; Find beginning and end of region to sort
8626 (cond
8627 ((org-region-active-p)
8628 ;; we will sort the region
8629 (setq end (region-end)
8630 what "region")
8631 (goto-char (region-beginning))
8632 (if (not (org-at-heading-p)) (outline-next-heading))
8633 (setq start (point)))
8634 ((or (org-at-heading-p)
8635 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8636 ;; we will sort the children of the current headline
8637 (org-back-to-heading)
8638 (setq start (point)
8639 end (progn (org-end-of-subtree t t)
8640 (or (bolp) (insert "\n"))
8641 (org-back-over-empty-lines)
8642 (point))
8643 what "children")
8644 (goto-char start)
8645 (show-subtree)
8646 (outline-next-heading))
8648 ;; we will sort the top-level entries in this file
8649 (goto-char (point-min))
8650 (or (org-at-heading-p) (outline-next-heading))
8651 (setq start (point))
8652 (goto-char (point-max))
8653 (beginning-of-line 1)
8654 (when (looking-at ".*?\\S-")
8655 ;; File ends in a non-white line
8656 (end-of-line 1)
8657 (insert "\n"))
8658 (setq end (point-max))
8659 (setq what "top-level")
8660 (goto-char start)
8661 (show-all)))
8663 (setq beg (point))
8664 (if (>= beg end) (user-error "Nothing to sort"))
8666 (looking-at "\\(\\*+\\)")
8667 (setq stars (match-string 1)
8668 re (concat "^" (regexp-quote stars) " +")
8669 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8670 txt (buffer-substring beg end))
8671 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8672 (if (and (not (equal stars "*")) (string-match re2 txt))
8673 (user-error "Region to sort contains a level above the first entry"))
8675 (unless sorting-type
8676 (message
8677 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8678 [t]ime [s]cheduled [d]eadline [c]reated
8679 A/N/P/R/O/F/T/S/D/C means reversed:"
8680 what)
8681 (setq sorting-type (read-char-exclusive))
8683 (unless getkey-func
8684 (and (= (downcase sorting-type) ?f)
8685 (setq getkey-func
8686 (org-icompleting-read "Sort using function: "
8687 obarray 'fboundp t nil nil))
8688 (setq getkey-func (intern getkey-func))))
8690 (and (= (downcase sorting-type) ?r)
8691 (not property)
8692 (setq property
8693 (org-icompleting-read "Property: "
8694 (mapcar 'list (org-buffer-property-keys t))
8695 nil t))))
8697 (message "Sorting entries...")
8699 (save-restriction
8700 (narrow-to-region start end)
8701 (let ((dcst (downcase sorting-type))
8702 (case-fold-search nil)
8703 (now (current-time)))
8704 (sort-subr
8705 (/= dcst sorting-type)
8706 ;; This function moves to the beginning character of the "record" to
8707 ;; be sorted.
8708 (lambda nil
8709 (if (re-search-forward re nil t)
8710 (goto-char (match-beginning 0))
8711 (goto-char (point-max))))
8712 ;; This function moves to the last character of the "record" being
8713 ;; sorted.
8714 (lambda nil
8715 (save-match-data
8716 (condition-case nil
8717 (outline-forward-same-level 1)
8718 (error
8719 (goto-char (point-max))))))
8720 ;; This function returns the value that gets sorted against.
8721 (lambda nil
8722 (cond
8723 ((= dcst ?n)
8724 (if (looking-at org-complex-heading-regexp)
8725 (string-to-number (org-sort-remove-invisible (match-string 4)))
8726 nil))
8727 ((= dcst ?a)
8728 (if (looking-at org-complex-heading-regexp)
8729 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8730 nil))
8731 ((= dcst ?t)
8732 (let ((end (save-excursion (outline-next-heading) (point))))
8733 (if (or (re-search-forward org-ts-regexp end t)
8734 (re-search-forward org-ts-regexp-both end t))
8735 (org-time-string-to-seconds (match-string 0))
8736 (org-float-time now))))
8737 ((= dcst ?c)
8738 (let ((end (save-excursion (outline-next-heading) (point))))
8739 (if (re-search-forward
8740 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8741 end t)
8742 (org-time-string-to-seconds (match-string 0))
8743 (org-float-time now))))
8744 ((= dcst ?s)
8745 (let ((end (save-excursion (outline-next-heading) (point))))
8746 (if (re-search-forward org-scheduled-time-regexp end t)
8747 (org-time-string-to-seconds (match-string 1))
8748 (org-float-time now))))
8749 ((= dcst ?d)
8750 (let ((end (save-excursion (outline-next-heading) (point))))
8751 (if (re-search-forward org-deadline-time-regexp end t)
8752 (org-time-string-to-seconds (match-string 1))
8753 (org-float-time now))))
8754 ((= dcst ?p)
8755 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8756 (string-to-char (match-string 2))
8757 org-default-priority))
8758 ((= dcst ?r)
8759 (or (org-entry-get nil property) ""))
8760 ((= dcst ?o)
8761 (if (looking-at org-complex-heading-regexp)
8762 (- 9999 (length (member (match-string 2)
8763 org-todo-keywords-1)))))
8764 ((= dcst ?f)
8765 (if getkey-func
8766 (progn
8767 (setq tmp (funcall getkey-func))
8768 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8769 tmp)
8770 (error "Invalid key function `%s'" getkey-func)))
8771 (t (error "Invalid sorting type `%c'" sorting-type))))
8773 (cond
8774 ((= dcst ?a) 'string<)
8775 ((= dcst ?f) compare-func)
8776 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8777 (run-hooks 'org-after-sorting-entries-or-items-hook)
8778 ;; Reset the clock marker if needed
8779 (when cmstr
8780 (save-excursion
8781 (goto-char start)
8782 (search-forward cmstr nil t)
8783 (move-marker org-clock-marker (point))))
8784 (message "Sorting entries...done")))
8786 (defun org-do-sort (table what &optional with-case sorting-type)
8787 "Sort TABLE of WHAT according to SORTING-TYPE.
8788 The user will be prompted for the SORTING-TYPE if the call to this
8789 function does not specify it. WHAT is only for the prompt, to indicate
8790 what is being sorted. The sorting key will be extracted from
8791 the car of the elements of the table.
8792 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8793 (unless sorting-type
8794 (message
8795 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8796 what)
8797 (setq sorting-type (read-char-exclusive)))
8798 (let ((dcst (downcase sorting-type))
8799 extractfun comparefun)
8800 ;; Define the appropriate functions
8801 (cond
8802 ((= dcst ?n)
8803 (setq extractfun 'string-to-number
8804 comparefun (if (= dcst sorting-type) '< '>)))
8805 ((= dcst ?a)
8806 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8807 (lambda(x) (downcase (org-sort-remove-invisible x))))
8808 comparefun (if (= dcst sorting-type)
8809 'string<
8810 (lambda (a b) (and (not (string< a b))
8811 (not (string= a b)))))))
8812 ((= dcst ?t)
8813 (setq extractfun
8814 (lambda (x)
8815 (if (or (string-match org-ts-regexp x)
8816 (string-match org-ts-regexp-both x))
8817 (org-float-time
8818 (org-time-string-to-time (match-string 0 x)))
8820 comparefun (if (= dcst sorting-type) '< '>)))
8821 (t (error "Invalid sorting type `%c'" sorting-type)))
8823 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8824 table)
8825 (lambda (a b) (funcall comparefun (car a) (car b))))))
8828 ;;; The orgstruct minor mode
8830 ;; Define a minor mode which can be used in other modes in order to
8831 ;; integrate the org-mode structure editing commands.
8833 ;; This is really a hack, because the org-mode structure commands use
8834 ;; keys which normally belong to the major mode. Here is how it
8835 ;; works: The minor mode defines all the keys necessary to operate the
8836 ;; structure commands, but wraps the commands into a function which
8837 ;; tests if the cursor is currently at a headline or a plain list
8838 ;; item. If that is the case, the structure command is used,
8839 ;; temporarily setting many Org-mode variables like regular
8840 ;; expressions for filling etc. However, when any of those keys is
8841 ;; used at a different location, function uses `key-binding' to look
8842 ;; up if the key has an associated command in another currently active
8843 ;; keymap (minor modes, major mode, global), and executes that
8844 ;; command. There might be problems if any of the keys is otherwise
8845 ;; used as a prefix key.
8847 (defcustom orgstruct-heading-prefix-regexp nil
8848 "Regexp that matches the custom prefix of Org headlines in
8849 orgstruct(++)-mode."
8850 :group 'org
8851 :version "24.4"
8852 :package-version '(Org . "8.0")
8853 :type 'string)
8854 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8856 (defcustom orgstruct-setup-hook nil
8857 "Hook run after orgstruct-mode-map is filled."
8858 :group 'org
8859 :version "24.4"
8860 :package-version '(Org . "8.0")
8861 :type 'hook)
8863 (defvar orgstruct-initialized nil)
8865 (defvar org-local-vars nil
8866 "List of local variables, for use by `orgstruct-mode'.")
8868 ;;;###autoload
8869 (define-minor-mode orgstruct-mode
8870 "Toggle the minor mode `orgstruct-mode'.
8871 This mode is for using Org-mode structure commands in other
8872 modes. The following keys behave as if Org-mode were active, if
8873 the cursor is on a headline, or on a plain list item (both as
8874 defined by Org-mode)."
8875 nil " OrgStruct" (make-sparse-keymap)
8876 (funcall (if orgstruct-mode
8877 'add-to-invisibility-spec
8878 'remove-from-invisibility-spec)
8879 '(outline . t))
8880 (when orgstruct-mode
8881 (org-load-modules-maybe)
8882 (unless orgstruct-initialized
8883 (orgstruct-setup)
8884 (setq orgstruct-initialized t))))
8886 ;;;###autoload
8887 (defun turn-on-orgstruct ()
8888 "Unconditionally turn on `orgstruct-mode'."
8889 (orgstruct-mode 1))
8891 (defvar org-fb-vars nil)
8892 (make-variable-buffer-local 'org-fb-vars)
8893 (defun orgstruct++-mode (&optional arg)
8894 "Toggle `orgstruct-mode', the enhanced version of it.
8895 In addition to setting orgstruct-mode, this also exports all
8896 indentation and autofilling variables from org-mode into the
8897 buffer. It will also recognize item context in multiline items."
8898 (interactive "P")
8899 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8900 (if (< arg 1)
8901 (progn (orgstruct-mode -1)
8902 (mapc (lambda(v)
8903 (org-set-local (car v)
8904 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8905 org-fb-vars))
8906 (orgstruct-mode 1)
8907 (setq org-fb-vars nil)
8908 (unless org-local-vars
8909 (setq org-local-vars (org-get-local-variables)))
8910 (let (var val)
8911 (mapc
8912 (lambda (x)
8913 (when (string-match
8914 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8915 (symbol-name (car x)))
8916 (setq var (car x) val (nth 1 x))
8917 (push (list var `(quote ,(eval var))) org-fb-vars)
8918 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8919 org-local-vars)
8920 (org-set-local 'orgstruct-is-++ t))))
8922 (defvar orgstruct-is-++ nil
8923 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8924 (make-variable-buffer-local 'orgstruct-is-++)
8926 ;;;###autoload
8927 (defun turn-on-orgstruct++ ()
8928 "Unconditionally turn on `orgstruct++-mode'."
8929 (orgstruct++-mode 1))
8931 (defun orgstruct-error ()
8932 "Error when there is no default binding for a structure key."
8933 (interactive)
8934 (funcall (if (fboundp 'user-error)
8935 'user-error
8936 'error)
8937 "This key has no function outside structure elements"))
8939 (defun orgstruct-setup ()
8940 "Setup orgstruct keymap."
8941 (dolist (cell '((org-demote . t)
8942 (org-metaleft . t)
8943 (org-metaright . t)
8944 (org-promote . t)
8945 (org-shiftmetaleft . t)
8946 (org-shiftmetaright . t)
8947 org-backward-element
8948 org-backward-heading-same-level
8949 org-ctrl-c-ret
8950 org-ctrl-c-minus
8951 org-ctrl-c-star
8952 org-cycle
8953 org-forward-heading-same-level
8954 org-insert-heading
8955 org-insert-heading-respect-content
8956 org-kill-note-or-show-branches
8957 org-mark-subtree
8958 org-meta-return
8959 org-metadown
8960 org-metaup
8961 org-narrow-to-subtree
8962 org-promote-subtree
8963 org-reveal
8964 org-shiftdown
8965 org-shiftleft
8966 org-shiftmetadown
8967 org-shiftmetaup
8968 org-shiftright
8969 org-shifttab
8970 org-shifttab
8971 org-shiftup
8972 org-show-subtree
8973 org-sort
8974 org-up-element
8975 outline-demote
8976 outline-next-visible-heading
8977 outline-previous-visible-heading
8978 outline-promote
8979 outline-up-heading
8980 show-children))
8981 (let ((f (or (car-safe cell) cell))
8982 (disable-when-heading-prefix (cdr-safe cell)))
8983 (when (fboundp f)
8984 (let ((new-bindings))
8985 (dolist (binding (nconc (where-is-internal f org-mode-map)
8986 (where-is-internal f outline-mode-map)))
8987 (push binding new-bindings)
8988 ;; TODO use local-function-key-map
8989 (dolist (rep '(("<tab>" . "TAB")
8990 ("<return>" . "RET")
8991 ("<escape>" . "ESC")
8992 ("<delete>" . "DEL")))
8993 (setq binding (read-kbd-macro
8994 (let ((case-fold-search))
8995 (replace-regexp-in-string
8996 (regexp-quote (cdr rep))
8997 (car rep)
8998 (key-description binding)))))
8999 (pushnew binding new-bindings :test 'equal)))
9000 (dolist (binding new-bindings)
9001 (let ((key (lookup-key orgstruct-mode-map binding)))
9002 (when (or (not key) (numberp key))
9003 (condition-case nil
9004 (org-defkey orgstruct-mode-map
9005 binding
9006 (orgstruct-make-binding f binding disable-when-heading-prefix))
9007 (error nil)))))))))
9008 (run-hooks 'orgstruct-setup-hook))
9010 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9011 "Create a function for binding in the structure minor mode.
9012 FUN is the command to call inside a table. KEY is the key that
9013 should be checked in for a command to execute outside of tables.
9014 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9015 if `orgstruct-heading-prefix-regexp' is non-nil."
9016 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9017 (let ((nname name)
9018 (i 0))
9019 (while (fboundp (intern nname))
9020 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9021 (setq name (intern nname)))
9022 (eval
9023 (let ((bindings '((org-heading-regexp
9024 (concat "^"
9025 orgstruct-heading-prefix-regexp
9026 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9027 (org-outline-regexp
9028 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9029 (org-outline-regexp-bol
9030 (concat "^" org-outline-regexp))
9031 (outline-regexp org-outline-regexp)
9032 (outline-heading-end-regexp "\n")
9033 (outline-level 'org-outline-level)
9034 (outline-heading-alist))))
9035 `(defun ,name (arg)
9036 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9037 "Outside of structure, run the binding of `"
9038 (key-description key) "'."
9039 (when disable-when-heading-prefix
9040 (concat
9041 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9042 "back to the default binding due to limitations of Org's implementation of\n"
9043 "`" (symbol-name fun) "'.")))
9044 (interactive "p")
9045 (let* ((disable
9046 ,(when disable-when-heading-prefix
9047 '(and orgstruct-heading-prefix-regexp
9048 (not (string= orgstruct-heading-prefix-regexp "")))))
9049 (fallback
9050 (or disable
9051 (not
9052 (let* ,bindings
9053 (org-context-p 'headline 'item
9054 ,(when (memq fun
9055 '(org-insert-heading
9056 org-insert-heading-respect-content
9057 org-meta-return))
9058 '(when orgstruct-is-++
9059 'item-body))))))))
9060 (if fallback
9061 (let* ((orgstruct-mode)
9062 (binding
9063 (loop with key = ,key
9064 for rep in
9065 '(nil
9066 ("<\\([^>]*\\)tab>" . "\\1TAB")
9067 ("<\\([^>]*\\)return>" . "\\1RET")
9068 ("<\\([^>]*\\)escape>" . "\\1ESC")
9069 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9071 (when rep
9072 (setq key (read-kbd-macro
9073 (let ((case-fold-search))
9074 (replace-regexp-in-string
9075 (car rep)
9076 (cdr rep)
9077 (key-description key))))))
9078 thereis (key-binding key))))
9079 (if (keymapp binding)
9080 (set-temporary-overlay-map binding)
9081 (let ((func (or binding
9082 (unless disable
9083 'orgstruct-error))))
9084 (when func
9085 (call-interactively func)))))
9086 (org-run-like-in-org-mode
9087 (lambda ()
9088 (interactive)
9089 (let* ,bindings
9090 (call-interactively ',fun)))))))))
9091 name))
9093 (defun org-contextualize-keys (alist contexts)
9094 "Return valid elements in ALIST depending on CONTEXTS.
9096 `org-agenda-custom-commands' or `org-capture-templates' are the
9097 values used for ALIST, and `org-agenda-custom-commands-contexts'
9098 or `org-capture-templates-contexts' are the associated contexts
9099 definitions."
9100 (let ((contexts
9101 ;; normalize contexts
9102 (mapcar
9103 (lambda(c) (cond ((listp (cadr c))
9104 (list (car c) (car c) (cadr c)))
9105 ((string= "" (cadr c))
9106 (list (car c) (car c) (caddr c)))
9107 (t c))) contexts))
9108 (a alist) c r s)
9109 ;; loop over all commands or templates
9110 (while (setq c (pop a))
9111 (let (vrules repl)
9112 (cond
9113 ((not (assoc (car c) contexts))
9114 (push c r))
9115 ((and (assoc (car c) contexts)
9116 (setq vrules (org-contextualize-validate-key
9117 (car c) contexts)))
9118 (mapc (lambda (vr)
9119 (when (not (equal (car vr) (cadr vr)))
9120 (setq repl vr))) vrules)
9121 (if (not repl) (push c r)
9122 (push (cadr repl) s)
9123 (push
9124 (cons (car c)
9125 (cdr (or (assoc (cadr repl) alist)
9126 (error "Undefined key `%s' as contextual replacement for `%s'"
9127 (cadr repl) (car c)))))
9128 r))))))
9129 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9130 (delq
9132 (delete-dups
9133 (mapcar (lambda (x)
9134 (let ((tpl (car x)))
9135 (when (not (delq
9137 (mapcar (lambda(y)
9138 (equal y tpl)) s))) x)))
9139 (reverse r))))))
9141 (defun org-contextualize-validate-key (key contexts)
9142 "Check CONTEXTS for agenda or capture KEY."
9143 (let (r rr res)
9144 (while (setq r (pop contexts))
9145 (mapc
9146 (lambda (rr)
9147 (when
9148 (and (equal key (car r))
9149 (if (functionp rr) (funcall rr)
9150 (or (and (eq (car rr) 'in-file)
9151 (buffer-file-name)
9152 (string-match (cdr rr) (buffer-file-name)))
9153 (and (eq (car rr) 'in-mode)
9154 (string-match (cdr rr) (symbol-name major-mode)))
9155 (and (eq (car rr) 'in-buffer)
9156 (string-match (cdr rr) (buffer-name)))
9157 (when (and (eq (car rr) 'not-in-file)
9158 (buffer-file-name))
9159 (not (string-match (cdr rr) (buffer-file-name))))
9160 (when (eq (car rr) 'not-in-mode)
9161 (not (string-match (cdr rr) (symbol-name major-mode))))
9162 (when (eq (car rr) 'not-in-buffer)
9163 (not (string-match (cdr rr) (buffer-name)))))))
9164 (push r res)))
9165 (car (last r))))
9166 (delete-dups (delq nil res))))
9168 (defun org-context-p (&rest contexts)
9169 "Check if local context is any of CONTEXTS.
9170 Possible values in the list of contexts are `table', `headline', and `item'."
9171 (let ((pos (point)))
9172 (goto-char (point-at-bol))
9173 (prog1 (or (and (memq 'table contexts)
9174 (looking-at "[ \t]*|"))
9175 (and (memq 'headline contexts)
9176 (looking-at org-outline-regexp))
9177 (and (memq 'item contexts)
9178 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9179 (and (memq 'item-body contexts)
9180 (org-in-item-p)))
9181 (goto-char pos))))
9183 (defun org-get-local-variables ()
9184 "Return a list of all local variables in an Org mode buffer."
9185 (let (varlist)
9186 (with-current-buffer (get-buffer-create "*Org tmp*")
9187 (erase-buffer)
9188 (org-mode)
9189 (setq varlist (buffer-local-variables)))
9190 (kill-buffer "*Org tmp*")
9191 (delq nil
9192 (mapcar
9193 (lambda (x)
9194 (setq x
9195 (if (symbolp x)
9196 (list x)
9197 (list (car x) (cdr x))))
9198 (if (and (not (get (car x) 'org-state))
9199 (string-match
9200 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9201 (symbol-name (car x))))
9202 x nil))
9203 varlist))))
9205 (defun org-clone-local-variables (from-buffer &optional regexp)
9206 "Clone local variables from FROM-BUFFER.
9207 Optional argument REGEXP selects variables to clone."
9208 (mapc
9209 (lambda (pair)
9210 (and (symbolp (car pair))
9211 (or (null regexp)
9212 (string-match regexp (symbol-name (car pair))))
9213 (set (make-local-variable (car pair))
9214 (cdr pair))))
9215 (buffer-local-variables from-buffer)))
9217 ;;;###autoload
9218 (defun org-run-like-in-org-mode (cmd)
9219 "Run a command, pretending that the current buffer is in Org-mode.
9220 This will temporarily bind local variables that are typically bound in
9221 Org-mode to the values they have in Org-mode, and then interactively
9222 call CMD."
9223 (org-load-modules-maybe)
9224 (unless org-local-vars
9225 (setq org-local-vars (org-get-local-variables)))
9226 (let (binds)
9227 (dolist (var org-local-vars)
9228 (when (or (not (boundp (car var)))
9229 (eq (symbol-value (car var))
9230 (default-value (car var))))
9231 (push (list (car var) `(quote ,(cadr var))) binds)))
9232 (eval `(let ,binds
9233 (call-interactively (quote ,cmd))))))
9235 ;;;; Archiving
9237 (defun org-get-category (&optional pos force-refresh)
9238 "Get the category applying to position POS."
9239 (save-match-data
9240 (if force-refresh (org-refresh-category-properties))
9241 (let ((pos (or pos (point))))
9242 (or (get-text-property pos 'org-category)
9243 (progn (org-refresh-category-properties)
9244 (get-text-property pos 'org-category))))))
9246 (defun org-refresh-category-properties ()
9247 "Refresh category text properties in the buffer."
9248 (let ((case-fold-search t)
9249 (inhibit-read-only t)
9250 (def-cat (cond
9251 ((null org-category)
9252 (if buffer-file-name
9253 (file-name-sans-extension
9254 (file-name-nondirectory buffer-file-name))
9255 "???"))
9256 ((symbolp org-category) (symbol-name org-category))
9257 (t org-category)))
9258 beg end cat pos optionp)
9259 (org-with-silent-modifications
9260 (save-excursion
9261 (save-restriction
9262 (widen)
9263 (goto-char (point-min))
9264 (put-text-property (point) (point-max) 'org-category def-cat)
9265 (while (re-search-forward
9266 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9267 (setq pos (match-end 0)
9268 optionp (equal (char-after (match-beginning 0)) ?#)
9269 cat (org-trim (match-string 2)))
9270 (if optionp
9271 (setq beg (point-at-bol) end (point-max))
9272 (org-back-to-heading t)
9273 (setq beg (point) end (org-end-of-subtree t t)))
9274 (put-text-property beg end 'org-category cat)
9275 (put-text-property beg end 'org-category-position beg)
9276 (goto-char pos)))))))
9278 (defun org-refresh-properties (dprop tprop)
9279 "Refresh buffer text properties.
9280 DPROP is the drawer property and TPROP is the corresponding text
9281 property to set."
9282 (let ((case-fold-search t)
9283 (inhibit-read-only t) p)
9284 (org-with-silent-modifications
9285 (save-excursion
9286 (save-restriction
9287 (widen)
9288 (goto-char (point-min))
9289 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9290 (setq p (org-match-string-no-properties 1))
9291 (save-excursion
9292 (org-back-to-heading t)
9293 (put-text-property
9294 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9297 ;;;; Link Stuff
9299 ;;; Link abbreviations
9301 (defun org-link-expand-abbrev (link)
9302 "Apply replacements as defined in `org-link-abbrev-alist'."
9303 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9304 (let* ((key (match-string 1 link))
9305 (as (or (assoc key org-link-abbrev-alist-local)
9306 (assoc key org-link-abbrev-alist)))
9307 (tag (and (match-end 2) (match-string 3 link)))
9308 rpl)
9309 (if (not as)
9310 link
9311 (setq rpl (cdr as))
9312 (cond
9313 ((symbolp rpl) (funcall rpl tag))
9314 ((string-match "%(\\([^)]+\\))" rpl)
9315 (replace-match
9316 (save-match-data
9317 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9318 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9319 ((string-match "%h" rpl)
9320 (replace-match (url-hexify-string (or tag "")) t t rpl))
9321 (t (concat rpl tag)))))
9322 link))
9324 ;;; Storing and inserting links
9326 (defvar org-insert-link-history nil
9327 "Minibuffer history for links inserted with `org-insert-link'.")
9329 (defvar org-stored-links nil
9330 "Contains the links stored with `org-store-link'.")
9332 (defvar org-store-link-plist nil
9333 "Plist with info about the most recently link created with `org-store-link'.")
9335 (defvar org-link-protocols nil
9336 "Link protocols added to Org-mode using `org-add-link-type'.")
9338 (defvar org-store-link-functions nil
9339 "List of functions that are called to create and store a link.
9340 Each function will be called in turn until one returns a non-nil
9341 value. Each function should check if it is responsible for creating
9342 this link (for example by looking at the major mode).
9343 If not, it must exit and return nil.
9344 If yes, it should return a non-nil value after a calling
9345 `org-store-link-props' with a list of properties and values.
9346 Special properties are:
9348 :type The link prefix, like \"http\". This must be given.
9349 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9350 This is obligatory as well.
9351 :description Optional default description for the second pair
9352 of brackets in an Org-mode link. The user can still change
9353 this when inserting this link into an Org-mode buffer.
9355 In addition to these, any additional properties can be specified
9356 and then used in capture templates.")
9358 (defun org-add-link-type (type &optional follow export)
9359 "Add TYPE to the list of `org-link-types'.
9360 Re-compute all regular expressions depending on `org-link-types'
9362 FOLLOW and EXPORT are two functions.
9364 FOLLOW should take the link path as the single argument and do whatever
9365 is necessary to follow the link, for example find a file or display
9366 a mail message.
9368 EXPORT should format the link path for export to one of the export formats.
9369 It should be a function accepting three arguments:
9371 path the path of the link, the text after the prefix (like \"http:\")
9372 desc the description of the link, if any, or a description added by
9373 org-export-normalize-links if there is none
9374 format the export format, a symbol like `html' or `latex' or `ascii'..
9376 The function may use the FORMAT information to return different values
9377 depending on the format. The return value will be put literally into
9378 the exported file. If the return value is nil, this means Org should
9379 do what it normally does with links which do not have EXPORT defined.
9381 Org-mode has a built-in default for exporting links. If you are happy with
9382 this default, there is no need to define an export function for the link
9383 type. For a simple example of an export function, see `org-bbdb.el'."
9384 (add-to-list 'org-link-types type t)
9385 (org-make-link-regexps)
9386 (if (assoc type org-link-protocols)
9387 (setcdr (assoc type org-link-protocols) (list follow export))
9388 (push (list type follow export) org-link-protocols)))
9390 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9391 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9393 ;;;###autoload
9394 (defun org-store-link (arg)
9395 "\\<org-mode-map>Store an org-link to the current location.
9396 This link is added to `org-stored-links' and can later be inserted
9397 into an org-buffer with \\[org-insert-link].
9399 For some link types, a prefix arg is interpreted.
9400 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9401 For file links, arg negates `org-context-in-file-links'.
9403 A double prefix arg force skipping storing functions that are not
9404 part of Org's core.
9406 A triple prefix arg force storing a link for each line in the
9407 active region."
9408 (interactive "P")
9409 (org-load-modules-maybe)
9410 (if (and (equal arg '(64)) (org-region-active-p))
9411 (save-excursion
9412 (let ((end (region-end)))
9413 (goto-char (region-beginning))
9414 (set-mark (point))
9415 (while (< (point-at-eol) end)
9416 (move-end-of-line 1) (activate-mark)
9417 (let (current-prefix-arg)
9418 (call-interactively 'org-store-link))
9419 (move-beginning-of-line 2)
9420 (set-mark (point)))))
9421 (org-with-limited-levels
9422 (setq org-store-link-plist nil)
9423 (let (link cpltxt desc description search
9424 txt custom-id agenda-link sfuns sfunsn)
9425 (cond
9427 ;; Store a link using an external link type
9428 ((and (not (equal arg '(16)))
9429 (setq sfuns
9430 (delq
9431 nil (mapcar (lambda (f)
9432 (let (fs) (if (funcall f) (push f fs))))
9433 org-store-link-functions))
9434 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9435 (or (and (cdr sfuns)
9436 (funcall (intern
9437 (completing-read
9438 "Which function for creating the link? "
9439 sfunsn t (car sfunsn)))))
9440 (funcall (caar sfuns)))
9441 (setq link (plist-get org-store-link-plist :link)
9442 desc (or (plist-get org-store-link-plist
9443 :description) link))))
9445 ;; Store a link from a source code buffer
9446 ((org-src-edit-buffer-p)
9447 (let (label gc)
9448 (while (or (not label)
9449 (save-excursion
9450 (save-restriction
9451 (widen)
9452 (goto-char (point-min))
9453 (re-search-forward
9454 (regexp-quote (format org-coderef-label-format label))
9455 nil t))))
9456 (when label (message "Label exists already") (sit-for 2))
9457 (setq label (read-string "Code line label: " label)))
9458 (end-of-line 1)
9459 (setq link (format org-coderef-label-format label))
9460 (setq gc (- 79 (length link)))
9461 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9462 (insert link)
9463 (setq link (concat "(" label ")") desc nil)))
9465 ;; We are in the agenda, link to referenced location
9466 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9467 (let ((m (or (get-text-property (point) 'org-hd-marker)
9468 (get-text-property (point) 'org-marker))))
9469 (when m
9470 (org-with-point-at m
9471 (setq agenda-link
9472 (if (org-called-interactively-p 'any)
9473 (call-interactively 'org-store-link)
9474 (org-store-link nil)))))))
9476 ((eq major-mode 'calendar-mode)
9477 (let ((cd (calendar-cursor-to-date)))
9478 (setq link
9479 (format-time-string
9480 (car org-time-stamp-formats)
9481 (apply 'encode-time
9482 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9483 nil nil nil))))
9484 (org-store-link-props :type "calendar" :date cd)))
9486 ((eq major-mode 'help-mode)
9487 (setq link (concat "help:" (save-excursion
9488 (goto-char (point-min))
9489 (looking-at "^[^ ]+")
9490 (match-string 0))))
9491 (org-store-link-props :type "help"))
9493 ((eq major-mode 'w3-mode)
9494 (setq cpltxt (if (and (buffer-name)
9495 (not (string-match "Untitled" (buffer-name))))
9496 (buffer-name)
9497 (url-view-url t))
9498 link (url-view-url t))
9499 (org-store-link-props :type "w3" :url (url-view-url t)))
9501 ((eq major-mode 'image-mode)
9502 (setq cpltxt (concat "file:"
9503 (abbreviate-file-name buffer-file-name))
9504 link cpltxt)
9505 (org-store-link-props :type "image" :file buffer-file-name))
9507 ;; In dired, store a link to the file of the current line
9508 ((eq major-mode 'dired-mode)
9509 (let ((file (dired-get-filename nil t)))
9510 (setq file (if file
9511 (abbreviate-file-name
9512 (expand-file-name (dired-get-filename nil t)))
9513 ;; otherwise, no file so use current directory.
9514 default-directory))
9515 (setq cpltxt (concat "file:" file)
9516 link cpltxt)))
9518 ((setq search (run-hook-with-args-until-success
9519 'org-create-file-search-functions))
9520 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9521 "::" search))
9522 (setq cpltxt (or description link)))
9524 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9525 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9526 (cond
9527 ;; Store a link using the target at point
9528 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9529 (setq cpltxt
9530 (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))
9533 "::" (match-string 1))
9534 link cpltxt))
9535 ((and (featurep 'org-id)
9536 (or (eq org-id-link-to-org-use-id t)
9537 (and (org-called-interactively-p 'any)
9538 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9539 (and (eq org-id-link-to-org-use-id
9540 'create-if-interactive-and-no-custom-id)
9541 (not custom-id))))
9542 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9543 ;; Store a link using the ID at point
9544 (setq link (condition-case nil
9545 (prog1 (org-id-store-link)
9546 (setq desc (plist-get org-store-link-plist
9547 :description)))
9548 (error
9549 ;; Probably before first headline, link only to file
9550 (concat "file:"
9551 (abbreviate-file-name
9552 (buffer-file-name (buffer-base-buffer))))))))
9554 ;; Just link to current headline
9555 (setq cpltxt (concat "file:"
9556 (abbreviate-file-name
9557 (buffer-file-name (buffer-base-buffer)))))
9558 ;; Add a context search string
9559 (when (org-xor org-context-in-file-links arg)
9560 (let* ((ee (org-element-at-point))
9561 (et (org-element-type ee))
9562 (ev (plist-get (cadr ee) :value))
9563 (ek (plist-get (cadr ee) :key))
9564 (eok (and (stringp ek) (string-match "name" ek))))
9565 (setq txt (cond
9566 ((org-at-heading-p) nil)
9567 ((and (eq et 'keyword) eok) ev)
9568 ((org-region-active-p)
9569 (buffer-substring (region-beginning) (region-end)))))
9570 (when (or (null txt) (string-match "\\S-" txt))
9571 (setq cpltxt
9572 (concat cpltxt "::"
9573 (condition-case nil
9574 (org-make-org-heading-search-string txt)
9575 (error "")))
9576 desc (or (and (eq et 'keyword) eok ev)
9577 (nth 4 (ignore-errors (org-heading-components)))
9578 "NONE")))))
9579 (if (string-match "::\\'" cpltxt)
9580 (setq cpltxt (substring cpltxt 0 -2)))
9581 (setq link cpltxt))))
9583 ((buffer-file-name (buffer-base-buffer))
9584 ;; Just link to this file here.
9585 (setq cpltxt (concat "file:"
9586 (abbreviate-file-name
9587 (buffer-file-name (buffer-base-buffer)))))
9588 ;; Add a context string.
9589 (when (org-xor org-context-in-file-links arg)
9590 (setq txt (if (org-region-active-p)
9591 (buffer-substring (region-beginning) (region-end))
9592 (buffer-substring (point-at-bol) (point-at-eol))))
9593 ;; Only use search option if there is some text.
9594 (when (string-match "\\S-" txt)
9595 (setq cpltxt
9596 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9597 desc "NONE")))
9598 (setq link cpltxt))
9600 ((org-called-interactively-p 'interactive)
9601 (user-error "No method for storing a link from this buffer"))
9603 (t (setq link nil)))
9605 ;; We're done setting link and desc, clean up
9606 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9607 (setq link (or link cpltxt)
9608 desc (or desc cpltxt))
9609 (cond ((equal desc "NONE") (setq desc nil))
9610 ((string-match org-bracket-link-analytic-regexp desc)
9611 (let ((d0 (match-string 3 desc))
9612 (p0 (match-string 5 desc)))
9613 (setq desc
9614 (replace-regexp-in-string
9615 org-bracket-link-regexp
9616 (concat (or p0 d0)
9617 (if (equal (length (match-string 0 desc))
9618 (length desc)) "*" "")) desc)))))
9620 ;; Return the link
9621 (if (not (and (or (org-called-interactively-p 'any)
9622 executing-kbd-macro) link))
9623 (or agenda-link (and link (org-make-link-string link desc)))
9624 (push (list link desc) org-stored-links)
9625 (message "Stored: %s" (or desc link))
9626 (when custom-id
9627 (setq link (concat "file:" (abbreviate-file-name
9628 (buffer-file-name)) "::#" custom-id))
9629 (push (list link desc) org-stored-links)))))))
9631 (defun org-store-link-props (&rest plist)
9632 "Store link properties, extract names and addresses."
9633 (let (x adr)
9634 (when (setq x (plist-get plist :from))
9635 (setq adr (mail-extract-address-components x))
9636 (setq plist (plist-put plist :fromname (car adr)))
9637 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9638 (when (setq x (plist-get plist :to))
9639 (setq adr (mail-extract-address-components x))
9640 (setq plist (plist-put plist :toname (car adr)))
9641 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9642 (let ((from (plist-get plist :from))
9643 (to (plist-get plist :to)))
9644 (when (and from to org-from-is-user-regexp)
9645 (setq plist
9646 (plist-put plist :fromto
9647 (if (string-match org-from-is-user-regexp from)
9648 (concat "to %t")
9649 (concat "from %f"))))))
9650 (setq org-store-link-plist plist))
9652 (defun org-add-link-props (&rest plist)
9653 "Add these properties to the link property list."
9654 (let (key value)
9655 (while plist
9656 (setq key (pop plist) value (pop plist))
9657 (setq org-store-link-plist
9658 (plist-put org-store-link-plist key value)))))
9660 (defun org-email-link-description (&optional fmt)
9661 "Return the description part of an email link.
9662 This takes information from `org-store-link-plist' and formats it
9663 according to FMT (default from `org-email-link-description-format')."
9664 (setq fmt (or fmt org-email-link-description-format))
9665 (let* ((p org-store-link-plist)
9666 (to (plist-get p :toaddress))
9667 (from (plist-get p :fromaddress))
9668 (table
9669 (list
9670 (cons "%c" (plist-get p :fromto))
9671 (cons "%F" (plist-get p :from))
9672 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9673 (cons "%T" (plist-get p :to))
9674 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9675 (cons "%s" (plist-get p :subject))
9676 (cons "%d" (plist-get p :date))
9677 (cons "%m" (plist-get p :message-id)))))
9678 (when (string-match "%c" fmt)
9679 ;; Check if the user wrote this message
9680 (if (and org-from-is-user-regexp from to
9681 (save-match-data (string-match org-from-is-user-regexp from)))
9682 (setq fmt (replace-match "to %t" t t fmt))
9683 (setq fmt (replace-match "from %f" t t fmt))))
9684 (org-replace-escapes fmt table)))
9686 (defun org-make-org-heading-search-string (&optional string)
9687 "Make search string for the current headline or STRING."
9688 (let ((s (or string
9689 (and (derived-mode-p 'org-mode)
9690 (save-excursion
9691 (org-back-to-heading t)
9692 (org-element-property :raw-value (org-element-at-point))))))
9693 (lines org-context-in-file-links))
9694 (or string (setq s (concat "*" s))) ; Add * for headlines
9695 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9696 (when (and string (integerp lines) (> lines 0))
9697 (let ((slines (org-split-string s "\n")))
9698 (when (< lines (length slines))
9699 (setq s (mapconcat
9700 'identity
9701 (reverse (nthcdr (- (length slines) lines)
9702 (reverse slines))) "\n")))))
9703 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9705 (defun org-make-link-string (link &optional description)
9706 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9707 (unless (string-match "\\S-" link)
9708 (error "Empty link"))
9709 (when (and description
9710 (stringp description)
9711 (not (string-match "\\S-" description)))
9712 (setq description nil))
9713 (when (stringp description)
9714 ;; Remove brackets from the description, they are fatal.
9715 (while (string-match "\\[" description)
9716 (setq description (replace-match "{" t t description)))
9717 (while (string-match "\\]" description)
9718 (setq description (replace-match "}" t t description))))
9719 (when (equal link description)
9720 ;; No description needed, it is identical
9721 (setq description nil))
9722 (when (and (not description)
9723 (not (string-match (org-image-file-name-regexp) link))
9724 (not (equal link (org-link-escape link))))
9725 (setq description (org-extract-attributes link)))
9726 (setq link
9727 (cond ((string-match (org-image-file-name-regexp) link) link)
9728 ((string-match org-link-types-re link)
9729 (concat (match-string 1 link)
9730 (org-link-escape (substring link (match-end 1)))))
9731 (t (org-link-escape link))))
9732 (concat "[[" link "]"
9733 (if description (concat "[" description "]") "")
9734 "]"))
9736 (defconst org-link-escape-chars
9737 ;;%20 %2B %3B %3D %5B %5D
9738 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9739 "List of characters that should be escaped in link.
9740 This is the list that is used for internal purposes.")
9742 (defconst org-link-escape-chars-browser
9743 ;;%20 %22
9744 '(?\ ?\")
9745 "List of escapes for characters that are problematic in links.
9746 This is the list that is used before handing over to the browser.")
9748 (defun org-link-escape (text &optional table merge)
9749 "Return percent escaped representation of TEXT.
9750 TEXT is a string with the text to escape.
9751 Optional argument TABLE is a list with characters that should be
9752 escaped. When nil, `org-link-escape-chars' is used.
9753 If optional argument MERGE is set, merge TABLE into
9754 `org-link-escape-chars'."
9755 (cond
9756 ((and table merge)
9757 (mapc (lambda (defchr)
9758 (unless (member defchr table)
9759 (setq table (cons defchr table)))) org-link-escape-chars))
9760 ((null table)
9761 (setq table org-link-escape-chars)))
9762 (mapconcat
9763 (lambda (char)
9764 (if (or (member char table)
9765 (and (or (< char 32) (= char ?\%) (> char 126))
9766 org-url-hexify-p))
9767 (mapconcat (lambda (sequence-element)
9768 (format "%%%.2X" sequence-element))
9769 (or (encode-coding-char char 'utf-8)
9770 (error "Unable to percent escape character: %s"
9771 (char-to-string char))) "")
9772 (char-to-string char))) text ""))
9774 (defun org-link-escape-browser (text)
9775 (if (org-string-match-p
9776 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9777 text)
9778 (org-link-escape text org-link-escape-chars-browser)
9779 text))
9781 (defun org-link-unescape (str)
9782 "Unhex hexified Unicode strings as returned from the JavaScript function
9783 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9784 (unless (and (null str) (string= "" str))
9785 (let ((pos 0) (case-fold-search t) unhexed)
9786 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9787 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9788 (setq str (replace-match unhexed t t str))
9789 (setq pos (+ pos (length unhexed))))))
9790 str)
9792 (defun org-link-unescape-compound (hex)
9793 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9794 Note: this function also decodes single byte encodings like
9795 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9796 (save-match-data
9797 (let* ((bytes (cdr (split-string hex "%")))
9798 (ret "")
9799 (eat 0)
9800 (sum 0))
9801 (while bytes
9802 (let* ((val (string-to-number (pop bytes) 16))
9803 (shift-xor
9804 (if (= 0 eat)
9805 (cond
9806 ((>= val 252) (cons 6 252))
9807 ((>= val 248) (cons 5 248))
9808 ((>= val 240) (cons 4 240))
9809 ((>= val 224) (cons 3 224))
9810 ((>= val 192) (cons 2 192))
9811 (t (cons 0 0)))
9812 (cons 6 128))))
9813 (if (>= val 192) (setq eat (car shift-xor)))
9814 (setq val (logxor val (cdr shift-xor)))
9815 (setq sum (+ (lsh sum (car shift-xor)) val))
9816 (if (> eat 0) (setq eat (- eat 1)))
9817 (cond
9818 ((= 0 eat) ;multi byte
9819 (setq ret (concat ret (org-char-to-string sum)))
9820 (setq sum 0))
9821 ((not bytes) ; single byte(s)
9822 (setq ret (org-link-unescape-single-byte-sequence hex))))
9823 )) ;; end (while bytes
9824 ret )))
9826 (defun org-link-unescape-single-byte-sequence (hex)
9827 "Unhexify hex-encoded single byte character sequences."
9828 (mapconcat (lambda (byte)
9829 (char-to-string (string-to-number byte 16)))
9830 (cdr (split-string hex "%")) ""))
9832 (defun org-xor (a b)
9833 "Exclusive or."
9834 (if a (not b) b))
9836 (defun org-fixup-message-id-for-http (s)
9837 "Replace special characters in a message id, so it can be used in an http query."
9838 (when (string-match "%" s)
9839 (setq s (mapconcat (lambda (c)
9840 (if (eq c ?%)
9841 "%25"
9842 (char-to-string c)))
9843 s "")))
9844 (while (string-match "<" s)
9845 (setq s (replace-match "%3C" t t s)))
9846 (while (string-match ">" s)
9847 (setq s (replace-match "%3E" t t s)))
9848 (while (string-match "@" s)
9849 (setq s (replace-match "%40" t t s)))
9852 (defun org-link-prettify (link)
9853 "Return a human-readable representation of LINK.
9854 The car of LINK must be a raw link the cdr of LINK must be either
9855 a link description or nil."
9856 (let ((desc (or (cadr link) "<no description>")))
9857 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9858 "<" (car link) ">")))
9860 ;;;###autoload
9861 (defun org-insert-link-global ()
9862 "Insert a link like Org-mode does.
9863 This command can be called in any mode to insert a link in Org-mode syntax."
9864 (interactive)
9865 (org-load-modules-maybe)
9866 (org-run-like-in-org-mode 'org-insert-link))
9868 (defun org-insert-all-links (&optional keep)
9869 "Insert all links in `org-stored-links'."
9870 (interactive "P")
9871 (let ((links (copy-sequence org-stored-links)) l)
9872 (while (setq l (if keep (pop links) (pop org-stored-links)))
9873 (insert "- ")
9874 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9875 (insert "\n"))))
9877 (defun org-link-fontify-links-to-this-file ()
9878 "Fontify links to the current file in `org-stored-links'."
9879 (let ((f (buffer-file-name)) a b)
9880 (setq a (mapcar (lambda(l)
9881 (let ((ll (car l)))
9882 (when (and (string-match "^file:\\(.+\\)::" ll)
9883 (equal f (expand-file-name (match-string 1 ll))))
9884 ll)))
9885 org-stored-links))
9886 (when (featurep 'org-id)
9887 (setq b (mapcar (lambda(l)
9888 (let ((ll (car l)))
9889 (when (and (string-match "^id:\\(.+\\)$" ll)
9890 (equal f (expand-file-name
9891 (or (org-id-find-id-file
9892 (match-string 1 ll)) ""))))
9893 ll)))
9894 org-stored-links)))
9895 (mapcar (lambda(l)
9896 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9897 (delq nil (append a b)))))
9899 (defvar org-link-links-in-this-file nil)
9900 (defun org-insert-link (&optional complete-file link-location default-description)
9901 "Insert a link. At the prompt, enter the link.
9903 Completion can be used to insert any of the link protocol prefixes like
9904 http or ftp in use.
9906 The history can be used to select a link previously stored with
9907 `org-store-link'. When the empty string is entered (i.e. if you just
9908 press RET at the prompt), the link defaults to the most recently
9909 stored link. As SPC triggers completion in the minibuffer, you need to
9910 use M-SPC or C-q SPC to force the insertion of a space character.
9912 You will also be prompted for a description, and if one is given, it will
9913 be displayed in the buffer instead of the link.
9915 If there is already a link at point, this command will allow you to edit link
9916 and description parts.
9918 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9919 be selected using completion. The path to the file will be relative to the
9920 current directory if the file is in the current directory or a subdirectory.
9921 Otherwise, the link will be the absolute path as completed in the minibuffer
9922 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9923 option `org-link-file-path-type'.
9925 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9926 the current directory or below.
9928 With three \\[universal-argument] prefixes, negate the meaning of
9929 `org-keep-stored-link-after-insertion'.
9931 If `org-make-link-description-function' is non-nil, this function will be
9932 called with the link target, and the result will be the default
9933 link description.
9935 If the LINK-LOCATION parameter is non-nil, this value will be
9936 used as the link location instead of reading one interactively.
9938 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9939 be used as the default description."
9940 (interactive "P")
9941 (let* ((wcf (current-window-configuration))
9942 (origbuf (current-buffer))
9943 (region (if (org-region-active-p)
9944 (buffer-substring (region-beginning) (region-end))))
9945 (remove (and region (list (region-beginning) (region-end))))
9946 (desc region)
9947 tmphist ; byte-compile incorrectly complains about this
9948 (link link-location)
9949 (abbrevs org-link-abbrev-alist-local)
9950 entry file all-prefixes auto-desc)
9951 (cond
9952 (link-location) ; specified by arg, just use it.
9953 ((org-in-regexp org-bracket-link-regexp 1)
9954 ;; We do have a link at point, and we are going to edit it.
9955 (setq remove (list (match-beginning 0) (match-end 0)))
9956 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9957 (setq link (read-string "Link: "
9958 (org-link-unescape
9959 (org-match-string-no-properties 1)))))
9960 ((or (org-in-regexp org-angle-link-re)
9961 (org-in-regexp org-plain-link-re))
9962 ;; Convert to bracket link
9963 (setq remove (list (match-beginning 0) (match-end 0))
9964 link (read-string "Link: "
9965 (org-remove-angle-brackets (match-string 0)))))
9966 ((member complete-file '((4) (16)))
9967 ;; Completing read for file names.
9968 (setq link (org-file-complete-link complete-file)))
9970 ;; Read link, with completion for stored links.
9971 (org-link-fontify-links-to-this-file)
9972 (org-switch-to-buffer-other-window "*Org Links*")
9973 (with-current-buffer "*Org Links*"
9974 (erase-buffer)
9975 (insert "Insert a link.
9976 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9977 (when org-stored-links
9978 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9979 (insert (mapconcat 'org-link-prettify
9980 (reverse org-stored-links) "\n")))
9981 (goto-char (point-min)))
9982 (let ((cw (selected-window)))
9983 (select-window (get-buffer-window "*Org Links*" 'visible))
9984 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9985 (unless (pos-visible-in-window-p (point-max))
9986 (org-fit-window-to-buffer))
9987 (and (window-live-p cw) (select-window cw)))
9988 ;; Fake a link history, containing the stored links.
9989 (setq tmphist (append (mapcar 'car org-stored-links)
9990 org-insert-link-history))
9991 (setq all-prefixes (append (mapcar 'car abbrevs)
9992 (mapcar 'car org-link-abbrev-alist)
9993 org-link-types))
9994 (unwind-protect
9995 (progn
9996 (setq link
9997 (org-completing-read
9998 "Link: "
9999 (append
10000 (mapcar (lambda (x) (concat x ":"))
10001 all-prefixes)
10002 (mapcar 'car org-stored-links))
10003 nil nil nil
10004 'tmphist
10005 (caar org-stored-links)))
10006 (if (not (string-match "\\S-" link))
10007 (user-error "No link selected"))
10008 (mapc (lambda(l)
10009 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10010 org-stored-links)
10011 (if (or (member link all-prefixes)
10012 (and (equal ":" (substring link -1))
10013 (member (substring link 0 -1) all-prefixes)
10014 (setq link (substring link 0 -1))))
10015 (setq link (with-current-buffer origbuf
10016 (org-link-try-special-completion link)))))
10017 (set-window-configuration wcf)
10018 (kill-buffer "*Org Links*"))
10019 (setq entry (assoc link org-stored-links))
10020 (or entry (push link org-insert-link-history))
10021 (setq desc (or desc (nth 1 entry)))))
10023 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10024 (not org-keep-stored-link-after-insertion))
10025 (setq org-stored-links (delq (assoc link org-stored-links)
10026 org-stored-links)))
10028 (if (string-match org-plain-link-re link)
10029 ;; URL-like link, normalize the use of angular brackets.
10030 (setq link (org-remove-angle-brackets link)))
10032 ;; Check if we are linking to the current file with a search
10033 ;; option If yes, simplify the link by using only the search
10034 ;; option.
10035 (when (and buffer-file-name
10036 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10037 (let* ((path (match-string 1 link))
10038 (case-fold-search nil)
10039 (search (match-string 2 link)))
10040 (save-match-data
10041 (if (equal (file-truename buffer-file-name) (file-truename path))
10042 ;; We are linking to this same file, with a search option
10043 (setq link search)))))
10045 ;; Check if we can/should use a relative path. If yes, simplify the link
10046 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10047 (let* ((type (match-string 1 link))
10048 (path (match-string 2 link))
10049 (origpath path)
10050 (case-fold-search nil))
10051 (cond
10052 ((or (eq org-link-file-path-type 'absolute)
10053 (equal complete-file '(16)))
10054 (setq path (abbreviate-file-name (expand-file-name path))))
10055 ((eq org-link-file-path-type 'noabbrev)
10056 (setq path (expand-file-name path)))
10057 ((eq org-link-file-path-type 'relative)
10058 (setq path (file-relative-name path)))
10060 (save-match-data
10061 (if (string-match (concat "^" (regexp-quote
10062 (expand-file-name
10063 (file-name-as-directory
10064 default-directory))))
10065 (expand-file-name path))
10066 ;; We are linking a file with relative path name.
10067 (setq path (substring (expand-file-name path)
10068 (match-end 0)))
10069 (setq path (abbreviate-file-name (expand-file-name path)))))))
10070 (setq link (concat type path))
10071 (if (equal desc origpath)
10072 (setq desc path))))
10074 (if org-make-link-description-function
10075 (setq desc
10076 (or (condition-case nil
10077 (funcall org-make-link-description-function link desc)
10078 (error (progn (message "Can't get link description from `%s'"
10079 (symbol-name org-make-link-description-function))
10080 (sit-for 2) nil)))
10081 (read-string "Description: " default-description)))
10082 (if default-description (setq desc default-description)
10083 (setq desc (or (and auto-desc desc)
10084 (read-string "Description: " desc)))))
10086 (unless (string-match "\\S-" desc) (setq desc nil))
10087 (if remove (apply 'delete-region remove))
10088 (insert (org-make-link-string link desc))))
10090 (defun org-link-try-special-completion (type)
10091 "If there is completion support for link type TYPE, offer it."
10092 (let ((fun (intern (concat "org-" type "-complete-link"))))
10093 (if (functionp fun)
10094 (funcall fun)
10095 (read-string "Link (no completion support): " (concat type ":")))))
10097 (defun org-file-complete-link (&optional arg)
10098 "Create a file link using completion."
10099 (let (file link)
10100 (setq file (org-iread-file-name "File: "))
10101 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10102 (pwd1 (file-name-as-directory (abbreviate-file-name
10103 (expand-file-name ".")))))
10104 (cond
10105 ((equal arg '(16))
10106 (setq link (concat
10107 "file:"
10108 (abbreviate-file-name (expand-file-name file)))))
10109 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10110 (setq link (concat "file:" (match-string 1 file))))
10111 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10112 (expand-file-name file))
10113 (setq link (concat
10114 "file:" (match-string 1 (expand-file-name file)))))
10115 (t (setq link (concat "file:" file)))))
10116 link))
10118 (defun org-iread-file-name (&rest args)
10119 "Read-file-name using `ido-mode' speedup if available.
10120 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10121 See `read-file-name' for a description of parameters."
10122 (org-without-partial-completion
10123 (if (and org-completion-use-ido
10124 (fboundp 'ido-read-file-name)
10125 (boundp 'ido-mode) ido-mode
10126 (listp (second args)))
10127 (let ((ido-enter-matching-directory nil))
10128 (apply 'ido-read-file-name args))
10129 (apply 'read-file-name args))))
10131 (defun org-completing-read (&rest args)
10132 "Completing-read with SPACE being a normal character."
10133 (let ((enable-recursive-minibuffers t)
10134 (minibuffer-local-completion-map
10135 (copy-keymap minibuffer-local-completion-map)))
10136 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10137 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10138 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10139 (apply 'org-icompleting-read args)))
10141 (defun org-completing-read-no-i (&rest args)
10142 (let (org-completion-use-ido org-completion-use-iswitchb)
10143 (apply 'org-completing-read args)))
10145 (defun org-iswitchb-completing-read (prompt choices &rest args)
10146 "Use iswitch as a completing-read replacement to choose from choices.
10147 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10148 from."
10149 (let* ((iswitchb-use-virtual-buffers nil)
10150 (iswitchb-make-buflist-hook
10151 (lambda ()
10152 (setq iswitchb-temp-buflist choices))))
10153 (iswitchb-read-buffer prompt)))
10155 (defun org-icompleting-read (&rest args)
10156 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10157 (org-without-partial-completion
10158 (if (and org-completion-use-ido
10159 (fboundp 'ido-completing-read)
10160 (boundp 'ido-mode) ido-mode
10161 (listp (second args)))
10162 (let ((ido-enter-matching-directory nil))
10163 (apply 'ido-completing-read (concat (car args))
10164 (if (consp (car (nth 1 args)))
10165 (mapcar 'car (nth 1 args))
10166 (nth 1 args))
10167 (cddr args)))
10168 (if (and org-completion-use-iswitchb
10169 (boundp 'iswitchb-mode) iswitchb-mode
10170 (listp (second args)))
10171 (apply 'org-iswitchb-completing-read (concat (car args))
10172 (if (consp (car (nth 1 args)))
10173 (mapcar 'car (nth 1 args))
10174 (nth 1 args))
10175 (cddr args))
10176 (apply 'completing-read args)))))
10178 (defun org-extract-attributes (s)
10179 "Extract the attributes cookie from a string and set as text property."
10180 (let (a attr (start 0) key value)
10181 (save-match-data
10182 (when (string-match "{{\\([^}]+\\)}}$" s)
10183 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10184 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10185 (setq key (match-string 1 a) value (match-string 2 a)
10186 start (match-end 0)
10187 attr (plist-put attr (intern key) value))))
10188 (org-add-props s nil 'org-attr attr))
10191 ;;; Opening/following a link
10193 (defvar org-link-search-failed nil)
10195 (defvar org-open-link-functions nil
10196 "Hook for functions finding a plain text link.
10197 These functions must take a single argument, the link content.
10198 They will be called for links that look like [[link text][description]]
10199 when LINK TEXT does not have a protocol like \"http:\" and does not look
10200 like a filename (e.g. \"./blue.png\").
10202 These functions will be called *before* Org attempts to resolve the
10203 link by doing text searches in the current buffer - so if you want a
10204 link \"[[target]]\" to still find \"<<target>>\", your function should
10205 handle this as a special case.
10207 When the function does handle the link, it must return a non-nil value.
10208 If it decides that it is not responsible for this link, it must return
10209 nil to indicate that that Org-mode can continue with other options
10210 like exact and fuzzy text search.")
10212 (defun org-next-link (&optional search-backward)
10213 "Move forward to the next link.
10214 If the link is in hidden text, expose it."
10215 (interactive "P")
10216 (when (and org-link-search-failed (eq this-command last-command))
10217 (goto-char (point-min))
10218 (message "Link search wrapped back to beginning of buffer"))
10219 (setq org-link-search-failed nil)
10220 (let* ((pos (point))
10221 (ct (org-context))
10222 (a (assoc :link ct))
10223 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10224 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10225 ((looking-at org-any-link-re)
10226 ;; Don't stay stuck at link without an org-link face
10227 (forward-char (if search-backward -1 1))))
10228 (if (funcall srch-fun org-any-link-re nil t)
10229 (progn
10230 (goto-char (match-beginning 0))
10231 (if (outline-invisible-p) (org-show-context)))
10232 (goto-char pos)
10233 (setq org-link-search-failed t)
10234 (message "No further link found"))))
10236 (defun org-previous-link ()
10237 "Move backward to the previous link.
10238 If the link is in hidden text, expose it."
10239 (interactive)
10240 (funcall 'org-next-link t))
10242 (defun org-translate-link (s)
10243 "Translate a link string if a translation function has been defined."
10244 (if (and org-link-translation-function
10245 (fboundp org-link-translation-function)
10246 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10247 (progn
10248 (setq s (funcall org-link-translation-function
10249 (match-string 1 s) (match-string 2 s)))
10250 (concat (car s) ":" (cdr s)))
10253 (defun org-translate-link-from-planner (type path)
10254 "Translate a link from Emacs Planner syntax so that Org can follow it.
10255 This is still an experimental function, your mileage may vary."
10256 (cond
10257 ((member type '("http" "https" "news" "ftp"))
10258 ;; standard Internet links are the same.
10259 nil)
10260 ((and (equal type "irc") (string-match "^//" path))
10261 ;; Planner has two / at the beginning of an irc link, we have 1.
10262 ;; We should have zero, actually....
10263 (setq path (substring path 1)))
10264 ((and (equal type "lisp") (string-match "^/" path))
10265 ;; Planner has a slash, we do not.
10266 (setq type "elisp" path (substring path 1)))
10267 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10268 ;; A typical message link. Planner has the id after the final slash,
10269 ;; we separate it with a hash mark
10270 (setq path (concat (match-string 1 path) "#"
10271 (org-remove-angle-brackets (match-string 2 path))))))
10272 (cons type path))
10274 (defun org-find-file-at-mouse (ev)
10275 "Open file link or URL at mouse."
10276 (interactive "e")
10277 (mouse-set-point ev)
10278 (org-open-at-point 'in-emacs))
10280 (defun org-open-at-mouse (ev)
10281 "Open file link or URL at mouse.
10282 See the docstring of `org-open-file' for details."
10283 (interactive "e")
10284 (mouse-set-point ev)
10285 (if (eq major-mode 'org-agenda-mode)
10286 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10287 (org-open-at-point))
10289 (defvar org-window-config-before-follow-link nil
10290 "The window configuration before following a link.
10291 This is saved in case the need arises to restore it.")
10293 (defvar org-open-link-marker (make-marker)
10294 "Marker pointing to the location where `org-open-at-point; was called.")
10296 ;;;###autoload
10297 (defun org-open-at-point-global ()
10298 "Follow a link like Org-mode does.
10299 This command can be called in any mode to follow a link that has
10300 Org-mode syntax."
10301 (interactive)
10302 (org-run-like-in-org-mode 'org-open-at-point))
10304 ;;;###autoload
10305 (defun org-open-link-from-string (s &optional arg reference-buffer)
10306 "Open a link in the string S, as if it was in Org-mode."
10307 (interactive "sLink: \nP")
10308 (let ((reference-buffer (or reference-buffer (current-buffer))))
10309 (with-temp-buffer
10310 (let ((org-inhibit-startup (not reference-buffer)))
10311 (org-mode)
10312 (insert s)
10313 (goto-char (point-min))
10314 (when reference-buffer
10315 (setq org-link-abbrev-alist-local
10316 (with-current-buffer reference-buffer
10317 org-link-abbrev-alist-local)))
10318 (org-open-at-point arg reference-buffer)))))
10320 (defvar org-open-at-point-functions nil
10321 "Hook that is run when following a link at point.
10323 Functions in this hook must return t if they identify and follow
10324 a link at point. If they don't find anything interesting at point,
10325 they must return nil.")
10327 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10328 (defun org-open-at-point (&optional arg reference-buffer)
10329 "Open link at or after point.
10330 If there is no link at point, this function will search forward up to
10331 the end of the current line.
10332 Normally, files will be opened by an appropriate application. If the
10333 optional prefix argument ARG is non-nil, Emacs will visit the file.
10334 With a double prefix argument, try to open outside of Emacs, in the
10335 application the system uses for this file type."
10336 (interactive "P")
10337 ;; if in a code block, then open the block's results
10338 (unless (call-interactively #'org-babel-open-src-block-result)
10339 (org-load-modules-maybe)
10340 (move-marker org-open-link-marker (point))
10341 (setq org-window-config-before-follow-link (current-window-configuration))
10342 (org-remove-occur-highlights nil nil t)
10343 (cond
10344 ((and (org-at-heading-p)
10345 (not (org-at-timestamp-p t))
10346 (not (org-in-regexp
10347 (concat org-plain-link-re "\\|"
10348 org-bracket-link-regexp "\\|"
10349 org-angle-link-re "\\|"
10350 "[ \t]:[^ \t\n]+:[ \t]*$")))
10351 (not (get-text-property (point) 'org-linked-text)))
10352 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10353 (lk0 (car lkall))
10354 (lk (if (stringp lk0) (list lk0) lk0))
10355 (lkend (cdr lkall)))
10356 (mapcar (lambda(l)
10357 (search-forward l nil lkend)
10358 (goto-char (match-beginning 0))
10359 (org-open-at-point))
10360 lk))
10361 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10362 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10363 ((and (org-at-timestamp-p t)
10364 (not (org-in-regexp org-bracket-link-regexp)))
10365 (org-follow-timestamp-link))
10366 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10367 (not (org-in-regexp org-any-link-re)))
10368 (org-footnote-action))
10370 (let (type path link line search (pos (point)))
10371 (catch 'match
10372 (save-excursion
10373 (skip-chars-forward "^]\n\r")
10374 (when (org-in-regexp org-bracket-link-regexp 1)
10375 (setq link (org-extract-attributes
10376 (org-link-unescape (org-match-string-no-properties 1))))
10377 (while (string-match " *\n *" link)
10378 (setq link (replace-match " " t t link)))
10379 (setq link (org-link-expand-abbrev link))
10380 (cond
10381 ((or (file-name-absolute-p link)
10382 (string-match "^\\.\\.?/" link))
10383 (setq type "file" path link))
10384 ((string-match org-link-re-with-space3 link)
10385 (setq type (match-string 1 link) path (match-string 2 link)))
10386 ((string-match "^help:+\\(.+\\)" link)
10387 (setq type "help" path (match-string 1 link)))
10388 (t (setq type "thisfile" path link)))
10389 (throw 'match t)))
10391 (when (get-text-property (point) 'org-linked-text)
10392 (setq type "thisfile"
10393 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10394 (1+ (point)) (point))
10395 path (buffer-substring
10396 (or (previous-single-property-change pos 'org-linked-text)
10397 (point-min))
10398 (or (next-single-property-change pos 'org-linked-text)
10399 (point-max)))
10400 ;; Ensure we will search for a <<<radio>>> link, not
10401 ;; a simple reference like <<ref>>
10402 path (concat "<" path))
10403 (throw 'match t))
10405 (save-excursion
10406 (when (or (org-in-regexp org-angle-link-re)
10407 (let ((match (org-in-regexp org-plain-link-re)))
10408 ;; Check a plain link is not within a bracket link
10409 (and match
10410 (save-excursion
10411 (progn
10412 (goto-char (car match))
10413 (not (org-in-regexp org-bracket-link-regexp))))))
10414 (let ((line_ending (save-excursion (end-of-line) (point))))
10415 ;; We are in a line before a plain or bracket link
10416 (or (re-search-forward org-plain-link-re line_ending t)
10417 (re-search-forward org-bracket-link-regexp line_ending t))))
10418 (setq type (match-string 1)
10419 path (org-link-unescape (match-string 2)))
10420 (throw 'match t)))
10421 (save-excursion
10422 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10423 (setq type "tags"
10424 path (match-string 1))
10425 (while (string-match ":" path)
10426 (setq path (replace-match "+" t t path)))
10427 (throw 'match t)))
10428 (when (org-in-regexp "<\\([^><\n]+\\)>")
10429 (setq type "tree-match"
10430 path (match-string 1))
10431 (throw 'match t)))
10432 (unless path
10433 (user-error "No link found"))
10435 ;; switch back to reference buffer
10436 ;; needed when if called in a temporary buffer through
10437 ;; org-open-link-from-string
10438 (with-current-buffer (or reference-buffer (current-buffer))
10440 ;; Remove any trailing spaces in path
10441 (if (string-match " +\\'" path)
10442 (setq path (replace-match "" t t path)))
10443 (if (and org-link-translation-function
10444 (fboundp org-link-translation-function))
10445 ;; Check if we need to translate the link
10446 (let ((tmp (funcall org-link-translation-function type path)))
10447 (setq type (car tmp) path (cdr tmp))))
10449 (cond
10451 ((assoc type org-link-protocols)
10452 (funcall (nth 1 (assoc type org-link-protocols)) path))
10454 ((equal type "help")
10455 (let ((f-or-v (intern path)))
10456 (cond ((fboundp f-or-v)
10457 (describe-function f-or-v))
10458 ((boundp f-or-v)
10459 (describe-variable f-or-v))
10460 (t (error "Not a known function or variable")))))
10462 ((equal type "mailto")
10463 (let ((cmd (car org-link-mailto-program))
10464 (args (cdr org-link-mailto-program)) args1
10465 (address path) (subject "") a)
10466 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10467 (setq address (match-string 1 path)
10468 subject (org-link-escape (match-string 2 path))))
10469 (while args
10470 (cond
10471 ((not (stringp (car args))) (push (pop args) args1))
10472 (t (setq a (pop args))
10473 (if (string-match "%a" a)
10474 (setq a (replace-match address t t a)))
10475 (if (string-match "%s" a)
10476 (setq a (replace-match subject t t a)))
10477 (push a args1))))
10478 (apply cmd (nreverse args1))))
10480 ((member type '("http" "https" "ftp" "news"))
10481 (browse-url (concat type ":" (org-link-escape-browser path))))
10483 ((string= type "doi")
10484 (browse-url (concat org-doi-server-url
10485 (org-link-escape-browser path))))
10487 ((member type '("message"))
10488 (browse-url (concat type ":" path)))
10490 ((string= type "tags")
10491 (org-tags-view arg path))
10493 ((string= type "tree-match")
10494 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10496 ((string= type "file")
10497 (if (string-match "::\\([0-9]+\\)\\'" path)
10498 (setq line (string-to-number (match-string 1 path))
10499 path (substring path 0 (match-beginning 0)))
10500 (if (string-match "::\\(.+\\)\\'" path)
10501 (setq search (match-string 1 path)
10502 path (substring path 0 (match-beginning 0)))))
10503 (if (string-match "[*?{]" (file-name-nondirectory path))
10504 (dired path)
10505 (org-open-file path arg line search)))
10507 ((string= type "shell")
10508 (let ((buf (generate-new-buffer "*Org Shell Output"))
10509 (cmd path))
10510 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10511 (string-match org-confirm-shell-link-not-regexp cmd))
10512 (not org-confirm-shell-link-function)
10513 (funcall org-confirm-shell-link-function
10514 (format "Execute \"%s\" in shell? "
10515 (org-add-props cmd nil
10516 'face 'org-warning))))
10517 (progn
10518 (message "Executing %s" cmd)
10519 (shell-command cmd buf)
10520 (if (featurep 'midnight)
10521 (setq clean-buffer-list-kill-buffer-names
10522 (cons buf clean-buffer-list-kill-buffer-names))))
10523 (error "Abort"))))
10525 ((string= type "elisp")
10526 (let ((cmd path))
10527 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10528 (string-match org-confirm-elisp-link-not-regexp cmd))
10529 (not org-confirm-elisp-link-function)
10530 (funcall org-confirm-elisp-link-function
10531 (format "Execute \"%s\" as elisp? "
10532 (org-add-props cmd nil
10533 'face 'org-warning))))
10534 (message "%s => %s" cmd
10535 (if (equal (string-to-char cmd) ?\()
10536 (eval (read cmd))
10537 (call-interactively (read cmd))))
10538 (error "Abort"))))
10540 ((and (string= type "thisfile")
10541 (or (run-hook-with-args-until-success
10542 'org-open-link-functions path)
10543 (and (string-match "^id:" link)
10544 (or (featurep 'org-id) (require 'org-id))
10545 (progn
10546 (funcall (nth 1 (assoc "id" org-link-protocols))
10547 (substring path 3))
10548 t)))))
10550 ((string= type "thisfile")
10551 (if arg
10552 (switch-to-buffer-other-window
10553 (org-get-buffer-for-internal-link (current-buffer)))
10554 (org-mark-ring-push))
10555 (let ((cmd `(org-link-search
10556 ,path
10557 ,(cond ((equal arg '(4)) ''occur)
10558 ((equal arg '(16)) ''org-occur))
10559 ,pos)))
10560 (condition-case nil (let ((org-link-search-inhibit-query t))
10561 (eval cmd))
10562 (error (progn (widen) (eval cmd))))))
10564 (t (browse-url-at-point)))))))
10565 (move-marker org-open-link-marker nil)
10566 (run-hook-with-args 'org-follow-link-hook)))
10568 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10569 "Offer links in the current entry and return the selected link.
10570 If there is only one link, return it.
10571 If NTH is an integer, return the NTH link found.
10572 If ZERO is a string, check also this string for a link, and if
10573 there is one, return it."
10574 (with-current-buffer buffer
10575 (save-excursion
10576 (save-restriction
10577 (widen)
10578 (goto-char marker)
10579 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10580 "\\(" org-angle-link-re "\\)\\|"
10581 "\\(" org-plain-link-re "\\)"))
10582 (cnt ?0)
10583 (in-emacs (if (integerp nth) nil nth))
10584 have-zero end links link c)
10585 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10586 (push (match-string 0 zero) links)
10587 (setq cnt (1- cnt) have-zero t))
10588 (save-excursion
10589 (org-back-to-heading t)
10590 (setq end (save-excursion (outline-next-heading) (point)))
10591 (while (re-search-forward re end t)
10592 (push (match-string 0) links))
10593 (setq links (org-uniquify (reverse links))))
10594 (cond
10595 ((null links)
10596 (message "No links"))
10597 ((equal (length links) 1)
10598 (setq link (car links)))
10599 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10600 (setq link (nth (if have-zero nth (1- nth)) links)))
10601 (t ; we have to select a link
10602 (save-excursion
10603 (save-window-excursion
10604 (delete-other-windows)
10605 (with-output-to-temp-buffer "*Select Link*"
10606 (mapc (lambda (l)
10607 (if (not (string-match org-bracket-link-regexp l))
10608 (princ (format "[%c] %s\n" (incf cnt)
10609 (org-remove-angle-brackets l)))
10610 (if (match-end 3)
10611 (princ (format "[%c] %s (%s)\n" (incf cnt)
10612 (match-string 3 l) (match-string 1 l)))
10613 (princ (format "[%c] %s\n" (incf cnt)
10614 (match-string 1 l))))))
10615 links))
10616 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10617 (message "Select link to open, RET to open all:")
10618 (setq c (read-char-exclusive))
10619 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10620 (when (equal c ?q) (error "Abort"))
10621 (if (equal c ?\C-m)
10622 (setq link links)
10623 (setq nth (- c ?0))
10624 (if have-zero (setq nth (1+ nth)))
10625 (unless (and (integerp nth) (>= (length links) nth))
10626 (user-error "Invalid link selection"))
10627 (setq link (nth (1- nth) links)))))
10628 (cons link end))))))
10630 ;; Add special file links that specify the way of opening
10632 (org-add-link-type "file+sys" 'org-open-file-with-system)
10633 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10634 (defun org-open-file-with-system (path)
10635 "Open file at PATH using the system way of opening it."
10636 (org-open-file path 'system))
10637 (defun org-open-file-with-emacs (path)
10638 "Open file at PATH in Emacs."
10639 (org-open-file path 'emacs))
10642 ;;; File search
10644 (defvar org-create-file-search-functions nil
10645 "List of functions to construct the right search string for a file link.
10646 These functions are called in turn with point at the location to
10647 which the link should point.
10649 A function in the hook should first test if it would like to
10650 handle this file type, for example by checking the `major-mode'
10651 or the file extension. If it decides not to handle this file, it
10652 should just return nil to give other functions a chance. If it
10653 does handle the file, it must return the search string to be used
10654 when following the link. The search string will be part of the
10655 file link, given after a double colon, and `org-open-at-point'
10656 will automatically search for it. If special measures must be
10657 taken to make the search successful, another function should be
10658 added to the companion hook `org-execute-file-search-functions',
10659 which see.
10661 A function in this hook may also use `setq' to set the variable
10662 `description' to provide a suggestion for the descriptive text to
10663 be used for this link when it gets inserted into an Org-mode
10664 buffer with \\[org-insert-link].")
10666 (defvar org-execute-file-search-functions nil
10667 "List of functions to execute a file search triggered by a link.
10669 Functions added to this hook must accept a single argument, the
10670 search string that was part of the file link, the part after the
10671 double colon. The function must first check if it would like to
10672 handle this search, for example by checking the `major-mode' or
10673 the file extension. If it decides not to handle this search, it
10674 should just return nil to give other functions a chance. If it
10675 does handle the search, it must return a non-nil value to keep
10676 other functions from trying.
10678 Each function can access the current prefix argument through the
10679 variable `current-prefix-arg'. Note that a single prefix is used
10680 to force opening a link in Emacs, so it may be good to only use a
10681 numeric or double prefix to guide the search function.
10683 In case this is needed, a function in this hook can also restore
10684 the window configuration before `org-open-at-point' was called using:
10686 (set-window-configuration org-window-config-before-follow-link)")
10688 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10689 (defun org-link-search (s &optional type avoid-pos stealth)
10690 "Search for a link search option.
10691 If S is surrounded by forward slashes, it is interpreted as a
10692 regular expression. In org-mode files, this will create an `org-occur'
10693 sparse tree. In ordinary files, `occur' will be used to list matches.
10694 If the current buffer is in `dired-mode', grep will be used to search
10695 in all files. If AVOID-POS is given, ignore matches near that position.
10697 When optional argument STEALTH is non-nil, do not modify
10698 visibility around point, thus ignoring
10699 `org-show-hierarchy-above', `org-show-following-heading' and
10700 `org-show-siblings' variables."
10701 (let ((case-fold-search t)
10702 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10703 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10704 (append '(("") (" ") ("\t") ("\n"))
10705 org-emphasis-alist)
10706 "\\|") "\\)"))
10707 (pos (point))
10708 (pre nil) (post nil)
10709 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10710 (cond
10711 ;; First check if there are any special search functions
10712 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10713 ;; Now try the builtin stuff
10714 ((and (equal (string-to-char s0) ?#)
10715 (> (length s0) 1)
10716 (save-excursion
10717 (goto-char (point-min))
10718 (and
10719 (re-search-forward
10720 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10721 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10722 (setq type 'dedicated
10723 pos (match-beginning 0))))
10724 ;; There is an exact target for this
10725 (goto-char pos)
10726 (org-back-to-heading t)))
10727 ((save-excursion
10728 (goto-char (point-min))
10729 (and
10730 (re-search-forward
10731 (concat "<<" (regexp-quote s0) ">>") nil t)
10732 (setq type 'dedicated
10733 pos (match-beginning 0))))
10734 ;; There is an exact target for this
10735 (goto-char pos))
10736 ((save-excursion
10737 (goto-char (point-min))
10738 (and
10739 (re-search-forward
10740 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10741 (setq type 'dedicated pos (match-beginning 0))))
10742 ;; Found an element with a matching #+name affiliated keyword.
10743 (goto-char pos))
10744 ((and (string-match "^(\\(.*\\))$" s0)
10745 (save-excursion
10746 (goto-char (point-min))
10747 (and
10748 (re-search-forward
10749 (concat "[^[]" (regexp-quote
10750 (format org-coderef-label-format
10751 (match-string 1 s0))))
10752 nil t)
10753 (setq type 'dedicated
10754 pos (1+ (match-beginning 0))))))
10755 ;; There is a coderef target for this
10756 (goto-char pos))
10757 ((string-match "^/\\(.*\\)/$" s)
10758 ;; A regular expression
10759 (cond
10760 ((derived-mode-p 'org-mode)
10761 (org-occur (match-string 1 s)))
10762 (t (org-do-occur (match-string 1 s)))))
10763 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10764 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10765 (goto-char (point-min))
10766 (cond
10767 ((let (case-fold-search)
10768 (re-search-forward (format org-complex-heading-regexp-format
10769 (regexp-quote s))
10770 nil t))
10771 ;; OK, found a match
10772 (setq type 'dedicated)
10773 (goto-char (match-beginning 0)))
10774 ((and (not org-link-search-inhibit-query)
10775 (eq org-link-search-must-match-exact-headline 'query-to-create)
10776 (y-or-n-p "No match - create this as a new heading? "))
10777 (goto-char (point-max))
10778 (or (bolp) (newline))
10779 (insert "* " s "\n")
10780 (beginning-of-line 0))
10782 (goto-char pos)
10783 (error "No match"))))
10785 ;; A normal search string
10786 (when (equal (string-to-char s) ?*)
10787 ;; Anchor on headlines, post may include tags.
10788 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10789 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10790 s (substring s 1)))
10791 (remove-text-properties
10792 0 (length s)
10793 '(face nil mouse-face nil keymap nil fontified nil) s)
10794 ;; Make a series of regular expressions to find a match
10795 (setq words (org-split-string s "[ \n\r\t]+")
10797 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10798 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10799 "\\)" markers)
10800 re2a_ (concat "\\(" (mapconcat 'downcase words
10801 "[ \t\r\n]+") "\\)[ \t\r\n]")
10802 re2a (concat "[ \t\r\n]" re2a_)
10803 re4_ (concat "\\(" (mapconcat 'downcase words
10804 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10805 re4 (concat "[^a-zA-Z_]" re4_)
10807 re1 (concat pre re2 post)
10808 re3 (concat pre (if pre re4_ re4) post)
10809 re5 (concat pre ".*" re4)
10810 re2 (concat pre re2)
10811 re2a (concat pre (if pre re2a_ re2a))
10812 re4 (concat pre (if pre re4_ re4))
10813 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10814 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10815 re5 "\\)"))
10816 (cond
10817 ((eq type 'org-occur) (org-occur reall))
10818 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10819 (t (goto-char (point-min))
10820 (setq type 'fuzzy)
10821 (if (or (and (org-search-not-self 1 re0 nil t)
10822 (setq type 'dedicated))
10823 (org-search-not-self 1 re1 nil t)
10824 (org-search-not-self 1 re2 nil t)
10825 (org-search-not-self 1 re2a nil t)
10826 (org-search-not-self 1 re3 nil t)
10827 (org-search-not-self 1 re4 nil t)
10828 (org-search-not-self 1 re5 nil t))
10829 (goto-char (match-beginning 1))
10830 (goto-char pos)
10831 (error "No match"))))))
10832 (and (derived-mode-p 'org-mode)
10833 (not stealth)
10834 (org-show-context 'link-search))
10835 type))
10837 (defun org-search-not-self (group &rest args)
10838 "Execute `re-search-forward', but only accept matches that do not
10839 enclose the position of `org-open-link-marker'."
10840 (let ((m org-open-link-marker))
10841 (catch 'exit
10842 (while (apply 're-search-forward args)
10843 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10844 (goto-char (match-end group))
10845 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10846 (> (match-beginning 0) (marker-position m))
10847 (< (match-end 0) (marker-position m)))
10848 (save-match-data
10849 (or (not (org-in-regexp
10850 org-bracket-link-analytic-regexp 1))
10851 (not (match-end 4)) ; no description
10852 (and (<= (match-beginning 4) (point))
10853 (>= (match-end 4) (point))))))
10854 (throw 'exit (point))))))))
10856 (defun org-get-buffer-for-internal-link (buffer)
10857 "Return a buffer to be used for displaying the link target of internal links."
10858 (cond
10859 ((not org-display-internal-link-with-indirect-buffer)
10860 buffer)
10861 ((string-match "(Clone)$" (buffer-name buffer))
10862 (message "Buffer is already a clone, not making another one")
10863 ;; we also do not modify visibility in this case
10864 buffer)
10865 (t ; make a new indirect buffer for displaying the link
10866 (let* ((bn (buffer-name buffer))
10867 (ibn (concat bn "(Clone)"))
10868 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10869 (with-current-buffer ib (org-overview))
10870 ib))))
10872 (defun org-do-occur (regexp &optional cleanup)
10873 "Call the Emacs command `occur'.
10874 If CLEANUP is non-nil, remove the printout of the regular expression
10875 in the *Occur* buffer. This is useful if the regex is long and not useful
10876 to read."
10877 (occur regexp)
10878 (when cleanup
10879 (let ((cwin (selected-window)) win beg end)
10880 (when (setq win (get-buffer-window "*Occur*"))
10881 (select-window win))
10882 (goto-char (point-min))
10883 (when (re-search-forward "match[a-z]+" nil t)
10884 (setq beg (match-end 0))
10885 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10886 (setq end (1- (match-beginning 0)))))
10887 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10888 (goto-char (point-min))
10889 (select-window cwin))))
10891 ;;; The mark ring for links jumps
10893 (defvar org-mark-ring nil
10894 "Mark ring for positions before jumps in Org-mode.")
10895 (defvar org-mark-ring-last-goto nil
10896 "Last position in the mark ring used to go back.")
10897 ;; Fill and close the ring
10898 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10899 (loop for i from 1 to org-mark-ring-length do
10900 (push (make-marker) org-mark-ring))
10901 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10902 org-mark-ring)
10904 (defun org-mark-ring-push (&optional pos buffer)
10905 "Put the current position or POS into the mark ring and rotate it."
10906 (interactive)
10907 (setq pos (or pos (point)))
10908 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10909 (move-marker (car org-mark-ring)
10910 (or pos (point))
10911 (or buffer (current-buffer)))
10912 (message "%s"
10913 (substitute-command-keys
10914 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10916 (defun org-mark-ring-goto (&optional n)
10917 "Jump to the previous position in the mark ring.
10918 With prefix arg N, jump back that many stored positions. When
10919 called several times in succession, walk through the entire ring.
10920 Org-mode commands jumping to a different position in the current file,
10921 or to another Org-mode file, automatically push the old position
10922 onto the ring."
10923 (interactive "p")
10924 (let (p m)
10925 (if (eq last-command this-command)
10926 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10927 (setq p org-mark-ring))
10928 (setq org-mark-ring-last-goto p)
10929 (setq m (car p))
10930 (org-pop-to-buffer-same-window (marker-buffer m))
10931 (goto-char m)
10932 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10934 (defun org-remove-angle-brackets (s)
10935 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10936 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10938 (defun org-add-angle-brackets (s)
10939 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10940 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10942 (defun org-remove-double-quotes (s)
10943 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10944 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10947 ;;; Following specific links
10949 (defun org-follow-timestamp-link ()
10950 "Open an agenda view for the time-stamp date/range at point."
10951 (cond
10952 ((org-at-date-range-p t)
10953 (let ((org-agenda-start-on-weekday)
10954 (t1 (match-string 1))
10955 (t2 (match-string 2)) tt1 tt2)
10956 (setq tt1 (time-to-days (org-time-string-to-time t1))
10957 tt2 (time-to-days (org-time-string-to-time t2)))
10958 (let ((org-agenda-buffer-tmp-name
10959 (format "*Org Agenda(a:%s)"
10960 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10961 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10962 ((org-at-timestamp-p t)
10963 (let ((org-agenda-buffer-tmp-name
10964 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10965 (org-agenda-list nil (time-to-days (org-time-string-to-time
10966 (substring (match-string 1) 0 10)))
10967 1)))
10968 (t (error "This should not happen"))))
10971 ;;; Following file links
10972 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10973 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10974 (declare-function mailcap-mime-info
10975 "mailcap" (string &optional request no-decode))
10976 (defvar org-wait nil)
10977 (defun org-open-file (path &optional in-emacs line search)
10978 "Open the file at PATH.
10979 First, this expands any special file name abbreviations. Then the
10980 configuration variable `org-file-apps' is checked if it contains an
10981 entry for this file type, and if yes, the corresponding command is launched.
10983 If no application is found, Emacs simply visits the file.
10985 With optional prefix argument IN-EMACS, Emacs will visit the file.
10986 With a double \\[universal-argument] \\[universal-argument] \
10987 prefix arg, Org tries to avoid opening in Emacs
10988 and to use an external application to visit the file.
10990 Optional LINE specifies a line to go to, optional SEARCH a string
10991 to search for. If LINE or SEARCH is given, the file will be
10992 opened in Emacs, unless an entry from org-file-apps that makes
10993 use of groups in a regexp matches.
10995 If you want to change the way frames are used when following a
10996 link, please customize `org-link-frame-setup'.
10998 If the file does not exist, an error is thrown."
10999 (let* ((file (if (equal path "")
11000 buffer-file-name
11001 (substitute-in-file-name (expand-file-name path))))
11002 (file-apps (append org-file-apps (org-default-apps)))
11003 (apps (org-remove-if
11004 'org-file-apps-entry-match-against-dlink-p file-apps))
11005 (apps-dlink (org-remove-if-not
11006 'org-file-apps-entry-match-against-dlink-p file-apps))
11007 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11008 (dirp (if remp nil (file-directory-p file)))
11009 (file (if (and dirp org-open-directory-means-index-dot-org)
11010 (concat (file-name-as-directory file) "index.org")
11011 file))
11012 (a-m-a-p (assq 'auto-mode apps))
11013 (dfile (downcase file))
11014 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11015 (link (cond ((and (eq line nil)
11016 (eq search nil))
11017 file)
11018 (line
11019 (concat file "::" (number-to-string line)))
11020 (search
11021 (concat file "::" search))))
11022 (dlink (downcase link))
11023 (old-buffer (current-buffer))
11024 (old-pos (point))
11025 (old-mode major-mode)
11026 ext cmd link-match-data)
11027 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11028 (setq ext (match-string 1 dfile))
11029 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11030 (setq ext (match-string 1 dfile))))
11031 (cond
11032 ((member in-emacs '((16) system))
11033 (setq cmd (cdr (assoc 'system apps))))
11034 (in-emacs (setq cmd 'emacs))
11036 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11037 (and dirp (cdr (assoc 'directory apps)))
11038 ; first, try matching against apps-dlink
11039 ; if we get a match here, store the match data for later
11040 (let ((match (assoc-default dlink apps-dlink
11041 'string-match)))
11042 (if match
11043 (progn (setq link-match-data (match-data))
11044 match)
11045 (progn (setq in-emacs (or in-emacs line search))
11046 nil))) ; if we have no match in apps-dlink,
11047 ; always open the file in emacs if line or search
11048 ; is given (for backwards compatibility)
11049 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11050 'string-match)
11051 (cdr (assoc ext apps))
11052 (cdr (assoc t apps))))))
11053 (when (eq cmd 'system)
11054 (setq cmd (cdr (assoc 'system apps))))
11055 (when (eq cmd 'default)
11056 (setq cmd (cdr (assoc t apps))))
11057 (when (eq cmd 'mailcap)
11058 (require 'mailcap)
11059 (mailcap-parse-mailcaps)
11060 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11061 (command (mailcap-mime-info mime-type)))
11062 (if (stringp command)
11063 (setq cmd command)
11064 (setq cmd 'emacs))))
11065 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11066 (not (file-exists-p file))
11067 (not org-open-non-existing-files))
11068 (user-error "No such file: %s" file))
11069 (cond
11070 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11071 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11072 (while (string-match "['\"]%s['\"]" cmd)
11073 (setq cmd (replace-match "%s" t t cmd)))
11074 (while (string-match "%s" cmd)
11075 (setq cmd (replace-match
11076 (save-match-data
11077 (shell-quote-argument
11078 (convert-standard-filename file)))
11079 t t cmd)))
11081 ;; Replace "%1", "%2" etc. in command with group matches from regex
11082 (save-match-data
11083 (let ((match-index 1)
11084 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11085 (set-match-data link-match-data)
11086 (while (<= match-index number-of-groups)
11087 (let ((regex (concat "%" (number-to-string match-index)))
11088 (replace-with (match-string match-index dlink)))
11089 (while (string-match regex cmd)
11090 (setq cmd (replace-match replace-with t t cmd))))
11091 (setq match-index (+ match-index 1)))))
11093 (save-window-excursion
11094 (message "Running %s...done" cmd)
11095 (start-process-shell-command cmd nil cmd)
11096 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11097 ((or (stringp cmd)
11098 (eq cmd 'emacs))
11099 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11100 (widen)
11101 (if line (org-goto-line line)
11102 (if search (org-link-search search))))
11103 ((consp cmd)
11104 (let ((file (convert-standard-filename file)))
11105 (save-match-data
11106 (set-match-data link-match-data)
11107 (eval cmd))))
11108 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11109 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11110 (or (not (equal old-buffer (current-buffer)))
11111 (not (equal old-pos (point))))
11112 (org-mark-ring-push old-pos old-buffer))))
11114 (defun org-file-apps-entry-match-against-dlink-p (entry)
11115 "This function returns non-nil if `entry' uses a regular
11116 expression which should be matched against the whole link by
11117 org-open-file.
11119 It assumes that is the case when the entry uses a regular
11120 expression which has at least one grouping construct and the
11121 action is either a lisp form or a command string containing
11122 '%1', i.e. using at least one subexpression match as a
11123 parameter."
11124 (let ((selector (car entry))
11125 (action (cdr entry)))
11126 (if (stringp selector)
11127 (and (> (regexp-opt-depth selector) 0)
11128 (or (and (stringp action)
11129 (string-match "%[0-9]" action))
11130 (consp action)))
11131 nil)))
11133 (defun org-default-apps ()
11134 "Return the default applications for this operating system."
11135 (cond
11136 ((eq system-type 'darwin)
11137 org-file-apps-defaults-macosx)
11138 ((eq system-type 'windows-nt)
11139 org-file-apps-defaults-windowsnt)
11140 (t org-file-apps-defaults-gnu)))
11142 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11143 "Convert extensions to regular expressions in the cars of LIST.
11144 Also, weed out any non-string entries, because the return value is used
11145 only for regexp matching.
11146 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11147 point to the symbol `emacs', indicating that the file should
11148 be opened in Emacs."
11149 (append
11150 (delq nil
11151 (mapcar (lambda (x)
11152 (if (not (stringp (car x)))
11154 (if (string-match "\\W" (car x))
11156 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11157 list))
11158 (if add-auto-mode
11159 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11161 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11162 (defun org-file-remote-p (file)
11163 "Test whether FILE specifies a location on a remote system.
11164 Return non-nil if the location is indeed remote.
11166 For example, the filename \"/user@host:/foo\" specifies a location
11167 on the system \"/user@host:\"."
11168 (cond ((fboundp 'file-remote-p)
11169 (file-remote-p file))
11170 ((fboundp 'tramp-handle-file-remote-p)
11171 (tramp-handle-file-remote-p file))
11172 ((and (boundp 'ange-ftp-name-format)
11173 (string-match (car ange-ftp-name-format) file))
11174 t)))
11177 ;;;; Refiling
11179 (defun org-get-org-file ()
11180 "Read a filename, with default directory `org-directory'."
11181 (let ((default (or org-default-notes-file remember-data-file)))
11182 (read-file-name (format "File name [%s]: " default)
11183 (file-name-as-directory org-directory)
11184 default)))
11186 (defun org-notes-order-reversed-p ()
11187 "Check if the current file should receive notes in reversed order."
11188 (cond
11189 ((not org-reverse-note-order) nil)
11190 ((eq t org-reverse-note-order) t)
11191 ((not (listp org-reverse-note-order)) nil)
11192 (t (catch 'exit
11193 (let ((all org-reverse-note-order)
11194 entry)
11195 (while (setq entry (pop all))
11196 (if (string-match (car entry) buffer-file-name)
11197 (throw 'exit (cdr entry))))
11198 nil)))))
11200 (defvar org-refile-target-table nil
11201 "The list of refile targets, created by `org-refile'.")
11203 (defvar org-agenda-new-buffers nil
11204 "Buffers created to visit agenda files.")
11206 (defvar org-refile-cache nil
11207 "Cache for refile targets.")
11209 (defvar org-refile-markers nil
11210 "All the markers used for caching refile locations.")
11212 (defun org-refile-marker (pos)
11213 "Get a new refile marker, but only if caching is in use."
11214 (if (not org-refile-use-cache)
11216 (let ((m (make-marker)))
11217 (move-marker m pos)
11218 (push m org-refile-markers)
11219 m)))
11221 (defun org-refile-cache-clear ()
11222 "Clear the refile cache and disable all the markers."
11223 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11224 (setq org-refile-markers nil)
11225 (setq org-refile-cache nil)
11226 (message "Refile cache has been cleared"))
11228 (defun org-refile-cache-check-set (set)
11229 "Check if all the markers in the cache still have live buffers."
11230 (let (marker)
11231 (catch 'exit
11232 (while (and set (setq marker (nth 3 (pop set))))
11233 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11234 (when (and marker (null (marker-buffer marker)))
11235 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11236 (sit-for 3)
11237 (throw 'exit nil)))
11238 t)))
11240 (defun org-refile-cache-put (set &rest identifiers)
11241 "Push the refile targets SET into the cache, under IDENTIFIERS."
11242 (let* ((key (sha1 (prin1-to-string identifiers)))
11243 (entry (assoc key org-refile-cache)))
11244 (if entry
11245 (setcdr entry set)
11246 (push (cons key set) org-refile-cache))))
11248 (defun org-refile-cache-get (&rest identifiers)
11249 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11250 (cond
11251 ((not org-refile-cache) nil)
11252 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11254 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11255 org-refile-cache))))
11256 (and set (org-refile-cache-check-set set) set)))))
11258 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11259 "Produce a table with refile targets."
11260 (let ((case-fold-search nil)
11261 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11262 (entries (or org-refile-targets '((nil . (:level . 1)))))
11263 targets tgs txt re files f desc descre fast-path-p level pos0)
11264 (message "Getting targets...")
11265 (with-current-buffer (or default-buffer (current-buffer))
11266 (while (setq entry (pop entries))
11267 (setq files (car entry) desc (cdr entry))
11268 (setq fast-path-p nil)
11269 (cond
11270 ((null files) (setq files (list (current-buffer))))
11271 ((eq files 'org-agenda-files)
11272 (setq files (org-agenda-files 'unrestricted)))
11273 ((and (symbolp files) (fboundp files))
11274 (setq files (funcall files)))
11275 ((and (symbolp files) (boundp files))
11276 (setq files (symbol-value files))))
11277 (if (stringp files) (setq files (list files)))
11278 (cond
11279 ((eq (car desc) :tag)
11280 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11281 ((eq (car desc) :todo)
11282 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11283 ((eq (car desc) :regexp)
11284 (setq descre (cdr desc)))
11285 ((eq (car desc) :level)
11286 (setq descre (concat "^\\*\\{" (number-to-string
11287 (if org-odd-levels-only
11288 (1- (* 2 (cdr desc)))
11289 (cdr desc)))
11290 "\\}[ \t]")))
11291 ((eq (car desc) :maxlevel)
11292 (setq fast-path-p t)
11293 (setq descre (concat "^\\*\\{1," (number-to-string
11294 (if org-odd-levels-only
11295 (1- (* 2 (cdr desc)))
11296 (cdr desc)))
11297 "\\}[ \t]")))
11298 (t (error "Bad refiling target description %s" desc)))
11299 (while (setq f (pop files))
11300 (with-current-buffer
11301 (if (bufferp f) f (org-get-agenda-file-buffer f))
11303 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11304 (progn
11305 (if (bufferp f) (setq f (buffer-file-name
11306 (buffer-base-buffer f))))
11307 (setq f (and f (expand-file-name f)))
11308 (if (eq org-refile-use-outline-path 'file)
11309 (push (list (file-name-nondirectory f) f nil nil) tgs))
11310 (save-excursion
11311 (save-restriction
11312 (widen)
11313 (goto-char (point-min))
11314 (while (re-search-forward descre nil t)
11315 (goto-char (setq pos0 (point-at-bol)))
11316 (catch 'next
11317 (when org-refile-target-verify-function
11318 (save-match-data
11319 (or (funcall org-refile-target-verify-function)
11320 (throw 'next t))))
11321 (when (and (looking-at org-complex-heading-regexp)
11322 (not (member (match-string 4) excluded-entries))
11323 (match-string 4))
11324 (setq level (org-reduced-level
11325 (- (match-end 1) (match-beginning 1)))
11326 txt (org-link-display-format (match-string 4))
11327 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11328 re (format org-complex-heading-regexp-format
11329 (regexp-quote (match-string 4))))
11330 (when org-refile-use-outline-path
11331 (setq txt (mapconcat
11332 'org-protect-slash
11333 (append
11334 (if (eq org-refile-use-outline-path
11335 'file)
11336 (list (file-name-nondirectory
11337 (buffer-file-name
11338 (buffer-base-buffer))))
11339 (if (eq org-refile-use-outline-path
11340 'full-file-path)
11341 (list (buffer-file-name
11342 (buffer-base-buffer)))))
11343 (org-get-outline-path fast-path-p
11344 level txt)
11345 (list txt))
11346 "/")))
11347 (push (list txt f re (org-refile-marker (point)))
11348 tgs)))
11349 (when (= (point) pos0)
11350 ;; verification function has not moved point
11351 (goto-char (point-at-eol))))))))
11352 (when org-refile-use-cache
11353 (org-refile-cache-put tgs (buffer-file-name) descre))
11354 (setq targets (append tgs targets))))))
11355 (message "Getting targets...done")
11356 (nreverse targets)))
11358 (defun org-protect-slash (s)
11359 (while (string-match "/" s)
11360 (setq s (replace-match "\\" t t s)))
11363 (defvar org-olpa (make-vector 20 nil))
11365 (defun org-get-outline-path (&optional fastp level heading)
11366 "Return the outline path to the current entry, as a list.
11368 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11369 routine which makes outline path derivations for an entire file,
11370 avoiding backtracing. Refile target collection makes use of that."
11371 (if fastp
11372 (progn
11373 (if (> level 19)
11374 (error "Outline path failure, more than 19 levels"))
11375 (loop for i from level upto 19 do
11376 (aset org-olpa i nil))
11377 (prog1
11378 (delq nil (append org-olpa nil))
11379 (aset org-olpa level heading)))
11380 (let (rtn case-fold-search)
11381 (save-excursion
11382 (save-restriction
11383 (widen)
11384 (while (org-up-heading-safe)
11385 (when (looking-at org-complex-heading-regexp)
11386 (push (org-trim
11387 (replace-regexp-in-string
11388 ;; Remove statistical/checkboxes cookies
11389 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11390 (org-match-string-no-properties 4)))
11391 rtn)))
11392 rtn)))))
11394 (defun org-format-outline-path (path &optional width prefix separator)
11395 "Format the outline path PATH for display.
11396 WIDTH is the maximum number of characters that is available.
11397 PREFIX is a prefix to be included in the returned string,
11398 such as the file name.
11399 SEPARATOR is inserted between the different parts of the path,
11400 the default is \"/\"."
11401 (setq width (or width 79))
11402 (if prefix (setq width (- width (length prefix))))
11403 (if (not path)
11404 (or prefix "")
11405 (let* ((nsteps (length path))
11406 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11407 (maxwidth (if (<= total-width width)
11408 10000 ;; everything fits
11409 ;; we need to shorten the level headings
11410 (/ (- width nsteps) nsteps)))
11411 (org-odd-levels-only nil)
11412 (n 0)
11413 (total (1+ (length prefix))))
11414 (setq maxwidth (max maxwidth 10))
11415 (concat prefix
11416 (if prefix (or separator "/"))
11417 (mapconcat
11418 (lambda (h)
11419 (setq n (1+ n))
11420 (if (and (= n nsteps) (< maxwidth 10000))
11421 (setq maxwidth (- total-width total)))
11422 (if (< (length h) maxwidth)
11423 (progn (setq total (+ total (length h) 1)) h)
11424 (setq h (substring h 0 (- maxwidth 2))
11425 total (+ total maxwidth 1))
11426 (if (string-match "[ \t]+\\'" h)
11427 (setq h (substring h 0 (match-beginning 0))))
11428 (setq h (concat h "..")))
11429 (org-add-props h nil 'face
11430 (nth (% (1- n) org-n-level-faces)
11431 org-level-faces))
11433 path (or separator "/"))))))
11435 (defun org-display-outline-path (&optional file current separator just-return-string)
11436 "Display the current outline path in the echo area.
11438 If FILE is non-nil, prepend the output with the file name.
11439 If CURRENT is non-nil, append the current heading to the output.
11440 SEPARATOR is passed through to `org-format-outline-path'. It separates
11441 the different parts of the path and defaults to \"/\".
11442 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11443 (interactive "P")
11444 (let* (case-fold-search
11445 (bfn (buffer-file-name (buffer-base-buffer)))
11446 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11447 res)
11448 (if current (setq path (append path
11449 (save-excursion
11450 (org-back-to-heading t)
11451 (if (looking-at org-complex-heading-regexp)
11452 (list (match-string 4)))))))
11453 (setq res
11454 (org-format-outline-path
11455 path
11456 (1- (frame-width))
11457 (and file bfn (concat (file-name-nondirectory bfn) separator))
11458 separator))
11459 (if just-return-string
11460 (org-no-properties res)
11461 (org-unlogged-message "%s" res))))
11463 (defvar org-refile-history nil
11464 "History for refiling operations.")
11466 (defvar org-after-refile-insert-hook nil
11467 "Hook run after `org-refile' has inserted its stuff at the new location.
11468 Note that this is still *before* the stuff will be removed from
11469 the *old* location.")
11471 (defvar org-capture-last-stored-marker)
11472 (defvar org-refile-keep nil
11473 "Non-nil means `org-refile' will copy instead of refile.")
11475 (defun org-copy ()
11476 "Like `org-refile', but copy."
11477 (interactive)
11478 (let ((org-refile-keep t))
11479 (funcall 'org-refile nil nil nil "Copy")))
11481 (defun org-refile (&optional goto default-buffer rfloc msg)
11482 "Move the entry or entries at point to another heading.
11483 The list of target headings is compiled using the information in
11484 `org-refile-targets', which see.
11486 At the target location, the entry is filed as a subitem of the target
11487 heading. Depending on `org-reverse-note-order', the new subitem will
11488 either be the first or the last subitem.
11490 If there is an active region, all entries in that region will be moved.
11491 However, the region must fulfill the requirement that the first heading
11492 is the first one sets the top-level of the moved text - at most siblings
11493 below it are allowed.
11495 With prefix arg GOTO, the command will only visit the target location
11496 and not actually move anything.
11498 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11499 go to the location where the last refiling operation has put the subtree.
11501 With a numeric prefix argument of `2', refile to the running clock.
11503 With a numeric prefix argument of `3', emulate `org-refile-keep'
11504 being set to `t' and copy to the target location, don't move it.
11505 Beware that keeping refiled entries may result in duplicated ID
11506 properties.
11508 RFLOC can be a refile location obtained in a different way.
11510 MSG is a string to replace \"Refile\" in the default prompt with
11511 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11513 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11515 If you are using target caching (see `org-refile-use-cache'),
11516 you have to clear the target cache in order to find new targets.
11517 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11518 prefix argument (`C-u C-u C-u C-c C-w')."
11520 (interactive "P")
11521 (if (member goto '(0 (64)))
11522 (org-refile-cache-clear)
11523 (let* ((actionmsg (or msg "Refile"))
11524 (cbuf (current-buffer))
11525 (regionp (org-region-active-p))
11526 (region-start (and regionp (region-beginning)))
11527 (region-end (and regionp (region-end)))
11528 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11529 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11530 pos it nbuf file re level reversed)
11531 (setq last-command nil)
11532 (when regionp
11533 (goto-char region-start)
11534 (or (bolp) (goto-char (point-at-bol)))
11535 (setq region-start (point))
11536 (unless (or (org-kill-is-subtree-p
11537 (buffer-substring region-start region-end))
11538 (prog1 org-refile-active-region-within-subtree
11539 (let ((s (point-at-eol)))
11540 (org-toggle-heading)
11541 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11542 (user-error "The region is not a (sequence of) subtree(s)")))
11543 (if (equal goto '(16))
11544 (org-refile-goto-last-stored)
11545 (when (or
11546 (and (equal goto 2)
11547 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11548 (prog1
11549 (setq it (list (or org-clock-heading "running clock")
11550 (buffer-file-name
11551 (marker-buffer org-clock-hd-marker))
11553 (marker-position org-clock-hd-marker)))
11554 (setq goto nil)))
11555 (setq it (or rfloc
11556 (let (heading-text)
11557 (save-excursion
11558 (unless goto
11559 (org-back-to-heading t)
11560 (setq heading-text
11561 (nth 4 (org-heading-components))))
11563 (org-refile-get-location
11564 (cond (goto "Goto")
11565 (regionp (concat actionmsg " region to"))
11566 (t (concat actionmsg " subtree \""
11567 heading-text "\" to")))
11568 default-buffer
11569 (and (not (equal '(4) goto))
11570 org-refile-allow-creating-parent-nodes)
11571 goto))))))
11572 (setq file (nth 1 it)
11573 re (nth 2 it)
11574 pos (nth 3 it))
11575 (if (and (not goto)
11577 (equal (buffer-file-name) file)
11578 (if regionp
11579 (and (>= pos region-start)
11580 (<= pos region-end))
11581 (and (>= pos (point))
11582 (< pos (save-excursion
11583 (org-end-of-subtree t t))))))
11584 (error "Cannot refile to position inside the tree or region"))
11586 (setq nbuf (or (find-buffer-visiting file)
11587 (find-file-noselect file)))
11588 (if (and goto (not (equal goto 3)))
11589 (progn
11590 (org-pop-to-buffer-same-window nbuf)
11591 (goto-char pos)
11592 (org-show-context 'org-goto))
11593 (if regionp
11594 (progn
11595 (org-kill-new (buffer-substring region-start region-end))
11596 (org-save-markers-in-region region-start region-end))
11597 (org-copy-subtree 1 nil t))
11598 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11599 (find-file-noselect file)))
11600 (setq reversed (org-notes-order-reversed-p))
11601 (save-excursion
11602 (save-restriction
11603 (widen)
11604 (if pos
11605 (progn
11606 (goto-char pos)
11607 (looking-at org-outline-regexp)
11608 (setq level (org-get-valid-level (funcall outline-level) 1))
11609 (goto-char
11610 (if reversed
11611 (or (outline-next-heading) (point-max))
11612 (or (save-excursion (org-get-next-sibling))
11613 (org-end-of-subtree t t)
11614 (point-max)))))
11615 (setq level 1)
11616 (if (not reversed)
11617 (goto-char (point-max))
11618 (goto-char (point-min))
11619 (or (outline-next-heading) (goto-char (point-max)))))
11620 (if (not (bolp)) (newline))
11621 (org-paste-subtree level)
11622 (when org-log-refile
11623 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11624 (unless (eq org-log-refile 'note)
11625 (save-excursion (org-add-log-note))))
11626 (and org-auto-align-tags
11627 (let ((org-loop-over-headlines-in-active-region nil))
11628 (org-set-tags nil t)))
11629 (let ((bookmark-name (plist-get org-bookmark-names-plist
11630 :last-refile)))
11631 (when bookmark-name
11632 (with-demoted-errors
11633 (bookmark-set bookmark-name))))
11634 ;; If we are refiling for capture, make sure that the
11635 ;; last-capture pointers point here
11636 (when (org-bound-and-true-p org-refile-for-capture)
11637 (let ((bookmark-name (plist-get org-bookmark-names-plist
11638 :last-capture-marker)))
11639 (when bookmark-name
11640 (with-demoted-errors
11641 (bookmark-set bookmark-name))))
11642 (move-marker org-capture-last-stored-marker (point)))
11643 (if (fboundp 'deactivate-mark) (deactivate-mark))
11644 (run-hooks 'org-after-refile-insert-hook))))
11645 (unless org-refile-keep
11646 (if regionp
11647 (delete-region (point) (+ (point) (- region-end region-start)))
11648 (delete-region
11649 (and (org-back-to-heading t) (point))
11650 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11651 (when (featurep 'org-inlinetask)
11652 (org-inlinetask-remove-END-maybe))
11653 (setq org-markers-to-move nil)
11654 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11656 (defun org-refile-goto-last-stored ()
11657 "Go to the location where the last refile was stored."
11658 (interactive)
11659 (bookmark-jump "org-refile-last-stored")
11660 (message "This is the location of the last refile"))
11662 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11663 no-exclude)
11664 "Prompt the user for a refile location, using PROMPT.
11665 PROMPT should not be suffixed with a colon and a space, because
11666 this function appends the default value from
11667 `org-refile-history' automatically, if that is not empty.
11668 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11669 this is used for the GOTO interface."
11670 (let ((org-refile-targets org-refile-targets)
11671 (org-refile-use-outline-path org-refile-use-outline-path)
11672 excluded-entries)
11673 (when (and (derived-mode-p 'org-mode)
11674 (not org-refile-use-cache)
11675 (not no-exclude))
11676 (org-map-tree
11677 (lambda()
11678 (setq excluded-entries
11679 (append excluded-entries (list (org-get-heading t t)))))))
11680 (setq org-refile-target-table
11681 (org-refile-get-targets default-buffer excluded-entries)))
11682 (unless org-refile-target-table
11683 (user-error "No refile targets"))
11684 (let* ((cbuf (current-buffer))
11685 (partial-completion-mode nil)
11686 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11687 (cfunc (if (and org-refile-use-outline-path
11688 org-outline-path-complete-in-steps)
11689 'org-olpath-completing-read
11690 'org-icompleting-read))
11691 (extra (if org-refile-use-outline-path "/" ""))
11692 (cbnex (concat (buffer-name) extra))
11693 (filename (and cfn (expand-file-name cfn)))
11694 (tbl (mapcar
11695 (lambda (x)
11696 (if (and (not (member org-refile-use-outline-path
11697 '(file full-file-path)))
11698 (not (equal filename (nth 1 x))))
11699 (cons (concat (car x) extra " ("
11700 (file-name-nondirectory (nth 1 x)) ")")
11701 (cdr x))
11702 (cons (concat (car x) extra) (cdr x))))
11703 org-refile-target-table))
11704 (completion-ignore-case t)
11705 cdef
11706 (prompt (concat prompt
11707 (or (and (car org-refile-history)
11708 (concat " (default " (car org-refile-history) ")"))
11709 (and (assoc cbnex tbl) (setq cdef cbnex)
11710 (concat " (default " cbnex ")"))) ": "))
11711 pa answ parent-target child parent old-hist)
11712 (setq old-hist org-refile-history)
11713 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11714 nil 'org-refile-history (or cdef (car org-refile-history))))
11715 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11716 (org-refile-check-position pa)
11717 (if pa
11718 (progn
11719 (when (or (not org-refile-history)
11720 (not (eq old-hist org-refile-history))
11721 (not (equal (car pa) (car org-refile-history))))
11722 (setq org-refile-history
11723 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11724 org-refile-history
11725 (cdr org-refile-history))))
11726 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11727 (pop org-refile-history)))
11729 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11730 (progn
11731 (setq parent (match-string 1 answ)
11732 child (match-string 2 answ))
11733 (setq parent-target (or (assoc parent tbl)
11734 (assoc (concat parent "/") tbl)))
11735 (when (and parent-target
11736 (or (eq new-nodes t)
11737 (and (eq new-nodes 'confirm)
11738 (y-or-n-p (format "Create new node \"%s\"? "
11739 child)))))
11740 (org-refile-new-child parent-target child)))
11741 (user-error "Invalid target location")))))
11743 (declare-function org-string-nw-p "org-macs" (s))
11744 (defun org-refile-check-position (refile-pointer)
11745 "Check if the refile pointer matches the headline to which it points."
11746 (let* ((file (nth 1 refile-pointer))
11747 (re (nth 2 refile-pointer))
11748 (pos (nth 3 refile-pointer))
11749 buffer)
11750 (if (and (not (markerp pos)) (not file))
11751 (user-error "Please save the buffer to a file before refiling")
11752 (when (org-string-nw-p re)
11753 (setq buffer (if (markerp pos)
11754 (marker-buffer pos)
11755 (or (find-buffer-visiting file)
11756 (find-file-noselect file))))
11757 (with-current-buffer buffer
11758 (save-excursion
11759 (save-restriction
11760 (widen)
11761 (goto-char pos)
11762 (beginning-of-line 1)
11763 (unless (org-looking-at-p re)
11764 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11766 (defun org-refile-new-child (parent-target child)
11767 "Use refile target PARENT-TARGET to add new CHILD below it."
11768 (unless parent-target
11769 (error "Cannot find parent for new node"))
11770 (let ((file (nth 1 parent-target))
11771 (pos (nth 3 parent-target))
11772 level)
11773 (with-current-buffer (or (find-buffer-visiting file)
11774 (find-file-noselect file))
11775 (save-excursion
11776 (save-restriction
11777 (widen)
11778 (if pos
11779 (goto-char pos)
11780 (goto-char (point-max))
11781 (if (not (bolp)) (newline)))
11782 (when (looking-at org-outline-regexp)
11783 (setq level (funcall outline-level))
11784 (org-end-of-subtree t t))
11785 (org-back-over-empty-lines)
11786 (insert "\n" (make-string
11787 (if pos (org-get-valid-level level 1) 1) ?*)
11788 " " child "\n")
11789 (beginning-of-line 0)
11790 (list (concat (car parent-target) "/" child) file "" (point)))))))
11792 (defun org-olpath-completing-read (prompt collection &rest args)
11793 "Read an outline path like a file name."
11794 (let ((thetable collection)
11795 (org-completion-use-ido nil) ; does not work with ido.
11796 (org-completion-use-iswitchb nil)) ; or iswitchb
11797 (apply
11798 'org-icompleting-read prompt
11799 (lambda (string predicate &optional flag)
11800 (let (rtn r f (l (length string)))
11801 (cond
11802 ((eq flag nil)
11803 ;; try completion
11804 (try-completion string thetable))
11805 ((eq flag t)
11806 ;; all-completions
11807 (setq rtn (all-completions string thetable predicate))
11808 (mapcar
11809 (lambda (x)
11810 (setq r (substring x l))
11811 (if (string-match " ([^)]*)$" x)
11812 (setq f (match-string 0 x))
11813 (setq f ""))
11814 (if (string-match "/" r)
11815 (concat string (substring r 0 (match-end 0)) f)
11817 rtn))
11818 ((eq flag 'lambda)
11819 ;; exact match?
11820 (assoc string thetable)))))
11821 args)))
11823 ;;;; Dynamic blocks
11825 (defun org-find-dblock (name)
11826 "Find the first dynamic block with name NAME in the buffer.
11827 If not found, stay at current position and return nil."
11828 (let ((case-fold-search t) pos)
11829 (save-excursion
11830 (goto-char (point-min))
11831 (setq pos (and (re-search-forward
11832 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11833 (match-beginning 0))))
11834 (if pos (goto-char pos))
11835 pos))
11837 (defconst org-dblock-start-re
11838 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11839 "Matches the start line of a dynamic block, with parameters.")
11841 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11842 "Matches the end of a dynamic block.")
11844 (defun org-create-dblock (plist)
11845 "Create a dynamic block section, with parameters taken from PLIST.
11846 PLIST must contain a :name entry which is used as name of the block."
11847 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11848 (end-of-line 1)
11849 (newline))
11850 (let ((col (current-column))
11851 (name (plist-get plist :name)))
11852 (insert "#+BEGIN: " name)
11853 (while plist
11854 (if (eq (car plist) :name)
11855 (setq plist (cddr plist))
11856 (insert " " (prin1-to-string (pop plist)))))
11857 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11858 (beginning-of-line -2)))
11860 (defun org-prepare-dblock ()
11861 "Prepare dynamic block for refresh.
11862 This empties the block, puts the cursor at the insert position and returns
11863 the property list including an extra property :name with the block name."
11864 (unless (looking-at org-dblock-start-re)
11865 (user-error "Not at a dynamic block"))
11866 (let* ((begdel (1+ (match-end 0)))
11867 (name (org-no-properties (match-string 1)))
11868 (params (append (list :name name)
11869 (read (concat "(" (match-string 3) ")")))))
11870 (save-excursion
11871 (beginning-of-line 1)
11872 (skip-chars-forward " \t")
11873 (setq params (plist-put params :indentation-column (current-column))))
11874 (unless (re-search-forward org-dblock-end-re nil t)
11875 (error "Dynamic block not terminated"))
11876 (setq params
11877 (append params
11878 (list :content (buffer-substring
11879 begdel (match-beginning 0)))))
11880 (delete-region begdel (match-beginning 0))
11881 (goto-char begdel)
11882 (open-line 1)
11883 params))
11885 (defun org-map-dblocks (&optional command)
11886 "Apply COMMAND to all dynamic blocks in the current buffer.
11887 If COMMAND is not given, use `org-update-dblock'."
11888 (let ((cmd (or command 'org-update-dblock)))
11889 (save-excursion
11890 (goto-char (point-min))
11891 (while (re-search-forward org-dblock-start-re nil t)
11892 (goto-char (match-beginning 0))
11893 (save-excursion
11894 (condition-case nil
11895 (funcall cmd)
11896 (error (message "Error during update of dynamic block"))))
11897 (unless (re-search-forward org-dblock-end-re nil t)
11898 (error "Dynamic block not terminated"))))))
11900 (defun org-dblock-update (&optional arg)
11901 "User command for updating dynamic blocks.
11902 Update the dynamic block at point. With prefix ARG, update all dynamic
11903 blocks in the buffer."
11904 (interactive "P")
11905 (if arg
11906 (org-update-all-dblocks)
11907 (or (looking-at org-dblock-start-re)
11908 (org-beginning-of-dblock))
11909 (org-update-dblock)))
11911 (defun org-update-dblock ()
11912 "Update the dynamic block at point.
11913 This means to empty the block, parse for parameters and then call
11914 the correct writing function."
11915 (interactive)
11916 (save-window-excursion
11917 (let* ((pos (point))
11918 (line (org-current-line))
11919 (params (org-prepare-dblock))
11920 (name (plist-get params :name))
11921 (indent (plist-get params :indentation-column))
11922 (cmd (intern (concat "org-dblock-write:" name))))
11923 (message "Updating dynamic block `%s' at line %d..." name line)
11924 (funcall cmd params)
11925 (message "Updating dynamic block `%s' at line %d...done" name line)
11926 (goto-char pos)
11927 (when (and indent (> indent 0))
11928 (setq indent (make-string indent ?\ ))
11929 (save-excursion
11930 (org-beginning-of-dblock)
11931 (forward-line 1)
11932 (while (not (looking-at org-dblock-end-re))
11933 (insert indent)
11934 (beginning-of-line 2))
11935 (when (looking-at org-dblock-end-re)
11936 (and (looking-at "[ \t]+")
11937 (replace-match ""))
11938 (insert indent)))))))
11940 (defun org-beginning-of-dblock ()
11941 "Find the beginning of the dynamic block at point.
11942 Error if there is no such block at point."
11943 (let ((pos (point))
11944 beg)
11945 (end-of-line 1)
11946 (if (and (re-search-backward org-dblock-start-re nil t)
11947 (setq beg (match-beginning 0))
11948 (re-search-forward org-dblock-end-re nil t)
11949 (> (match-end 0) pos))
11950 (goto-char beg)
11951 (goto-char pos)
11952 (error "Not in a dynamic block"))))
11954 (defun org-update-all-dblocks ()
11955 "Update all dynamic blocks in the buffer.
11956 This function can be used in a hook."
11957 (interactive)
11958 (when (derived-mode-p 'org-mode)
11959 (org-map-dblocks 'org-update-dblock)))
11962 ;;;; Completion
11964 (declare-function org-export-backend-name "org-export" (cl-x))
11965 (declare-function org-export-backend-options "org-export" (cl-x))
11966 (defun org-get-export-keywords ()
11967 "Return a list of all currently understood export keywords.
11968 Export keywords include options, block names, attributes and
11969 keywords relative to each registered export back-end."
11970 (let (keywords)
11971 (dolist (backend
11972 (org-bound-and-true-p org-export--registered-backends)
11973 (delq nil keywords))
11974 ;; Back-end name (for keywords, like #+LATEX:)
11975 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11976 (dolist (option-entry (org-export-backend-options backend))
11977 ;; Back-end options.
11978 (push (nth 1 option-entry) keywords)))))
11980 (defconst org-options-keywords
11981 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11982 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11983 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11984 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11985 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11987 (defcustom org-structure-template-alist
11988 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11989 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11990 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11991 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11992 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11993 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11994 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11995 "<literal style=\"latex\">\n?\n</literal>")
11996 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11997 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11998 "<literal style=\"html\">\n?\n</literal>")
11999 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12000 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12001 ("A" "#+ASCII: " "")
12002 ("i" "#+INDEX: ?" "#+INDEX: ?")
12003 ("I" "#+INCLUDE: %file ?"
12004 "<include file=%file markup=\"?\">"))
12005 "Structure completion elements.
12006 This is a list of abbreviation keys and values. The value gets inserted
12007 if you type `<' followed by the key and then press the completion key,
12008 usually `M-TAB'. %file will be replaced by a file name after prompting
12009 for the file using completion. The cursor will be placed at the position
12010 of the `?` in the template.
12011 There are two templates for each key, the first uses the original Org syntax,
12012 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12013 the default when the /org-mtags.el/ module has been loaded. See also the
12014 variable `org-mtags-prefer-muse-templates'."
12015 :group 'org-completion
12016 :type '(repeat
12017 (list
12018 (string :tag "Key")
12019 (string :tag "Template")
12020 (string :tag "Muse Template"))))
12022 (defun org-try-structure-completion ()
12023 "Try to complete a structure template before point.
12024 This looks for strings like \"<e\" on an otherwise empty line and
12025 expands them."
12026 (let ((l (buffer-substring (point-at-bol) (point)))
12028 (when (and (looking-at "[ \t]*$")
12029 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12030 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12031 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12032 (match-beginning 1)) a)
12033 t)))
12035 (defun org-complete-expand-structure-template (start cell)
12036 "Expand a structure template."
12037 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12038 (rpl (nth (if musep 2 1) cell))
12039 (ind ""))
12040 (delete-region start (point))
12041 (when (string-match "\\`#\\+" rpl)
12042 (cond
12043 ((bolp))
12044 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12045 (setq ind (buffer-substring (point-at-bol) (point))))
12046 (t (newline))))
12047 (setq start (point))
12048 (if (string-match "%file" rpl)
12049 (setq rpl (replace-match
12050 (concat
12051 "\""
12052 (save-match-data
12053 (abbreviate-file-name (read-file-name "Include file: ")))
12054 "\"")
12055 t t rpl)))
12056 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12057 (concat "\n" ind)))
12058 (insert rpl)
12059 (if (re-search-backward "\\?" start t) (delete-char 1))))
12061 ;;;; TODO, DEADLINE, Comments
12063 (defun org-toggle-comment ()
12064 "Change the COMMENT state of an entry."
12065 (interactive)
12066 (save-excursion
12067 (org-back-to-heading)
12068 (let (case-fold-search)
12069 (cond
12070 ((looking-at (format org-heading-keyword-regexp-format
12071 org-comment-string))
12072 (goto-char (match-end 1))
12073 (looking-at (concat " +" org-comment-string))
12074 (replace-match "" t t)
12075 (when (eolp) (insert " ")))
12076 ((looking-at org-outline-regexp)
12077 (goto-char (match-end 0))
12078 (insert org-comment-string " "))))))
12080 (defvar org-last-todo-state-is-todo nil
12081 "This is non-nil when the last TODO state change led to a TODO state.
12082 If the last change removed the TODO tag or switched to DONE, then
12083 this is nil.")
12085 (defvar org-setting-tags nil) ; dynamically skipped
12087 (defvar org-todo-setup-filter-hook nil
12088 "Hook for functions that pre-filter todo specs.
12089 Each function takes a todo spec and returns either nil or the spec
12090 transformed into canonical form." )
12092 (defvar org-todo-get-default-hook nil
12093 "Hook for functions that get a default item for todo.
12094 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12095 nil or a string to be used for the todo mark." )
12097 (defvar org-agenda-headline-snapshot-before-repeat)
12099 (defun org-current-effective-time ()
12100 "Return current time adjusted for `org-extend-today-until' variable."
12101 (let* ((ct (org-current-time))
12102 (dct (decode-time ct))
12103 (ct1
12104 (cond
12105 (org-use-last-clock-out-time-as-effective-time
12106 (or (org-clock-get-last-clock-out-time) ct))
12107 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12108 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12109 (t ct))))
12110 ct1))
12112 (defun org-todo-yesterday (&optional arg)
12113 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12114 (interactive "P")
12115 (if (eq major-mode 'org-agenda-mode)
12116 (apply 'org-agenda-todo-yesterday arg)
12117 (let* ((hour (third (decode-time
12118 (org-current-time))))
12119 (org-extend-today-until (1+ hour)))
12120 (org-todo arg))))
12122 (defvar org-block-entry-blocking ""
12123 "First entry preventing the TODO state change.")
12125 (defun org-todo (&optional arg)
12126 "Change the TODO state of an item.
12127 The state of an item is given by a keyword at the start of the heading,
12128 like
12129 *** TODO Write paper
12130 *** DONE Call mom
12132 The different keywords are specified in the variable `org-todo-keywords'.
12133 By default the available states are \"TODO\" and \"DONE\".
12134 So for this example: when the item starts with TODO, it is changed to DONE.
12135 When it starts with DONE, the DONE is removed. And when neither TODO nor
12136 DONE are present, add TODO at the beginning of the heading.
12138 With \\[universal-argument] prefix arg, use completion to determine the new \
12139 state.
12140 With numeric prefix arg, switch to that state.
12141 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12142 keywords (nextset).
12143 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12144 With a numeric prefix arg of 0, inhibit note taking for the change.
12146 For calling through lisp, arg is also interpreted in the following way:
12147 'none -> empty state
12148 \"\"(empty string) -> switch to empty state
12149 'done -> switch to DONE
12150 'nextset -> switch to the next set of keywords
12151 'previousset -> switch to the previous set of keywords
12152 \"WAITING\" -> switch to the specified keyword, but only if it
12153 really is a member of `org-todo-keywords'."
12154 (interactive "P")
12155 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12156 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12157 'region-start-level 'region))
12158 org-loop-over-headlines-in-active-region)
12159 (org-map-entries
12160 `(org-todo ,arg)
12161 org-loop-over-headlines-in-active-region
12162 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12163 (if (equal arg '(16)) (setq arg 'nextset))
12164 (let ((org-blocker-hook org-blocker-hook)
12165 commentp
12166 case-fold-search)
12167 (when (equal arg '(64))
12168 (setq arg nil org-blocker-hook nil))
12169 (when (and org-blocker-hook
12170 (or org-inhibit-blocking
12171 (org-entry-get nil "NOBLOCKING")))
12172 (setq org-blocker-hook nil))
12173 (save-excursion
12174 (catch 'exit
12175 (org-back-to-heading t)
12176 (when (looking-at (concat "^\\*+ " org-comment-string))
12177 (org-toggle-comment)
12178 (setq commentp t))
12179 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12180 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12181 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12182 (let* ((match-data (match-data))
12183 (startpos (point-at-bol))
12184 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12185 (org-log-done org-log-done)
12186 (org-log-repeat org-log-repeat)
12187 (org-todo-log-states org-todo-log-states)
12188 (org-inhibit-logging
12189 (if (equal arg 0)
12190 (progn (setq arg nil) 'note) org-inhibit-logging))
12191 (this (match-string 1))
12192 (hl-pos (match-beginning 0))
12193 (head (org-get-todo-sequence-head this))
12194 (ass (assoc head org-todo-kwd-alist))
12195 (interpret (nth 1 ass))
12196 (done-word (nth 3 ass))
12197 (final-done-word (nth 4 ass))
12198 (org-last-state (or this ""))
12199 (completion-ignore-case t)
12200 (member (member this org-todo-keywords-1))
12201 (tail (cdr member))
12202 (org-state (cond
12203 ((and org-todo-key-trigger
12204 (or (and (equal arg '(4))
12205 (eq org-use-fast-todo-selection 'prefix))
12206 (and (not arg) org-use-fast-todo-selection
12207 (not (eq org-use-fast-todo-selection
12208 'prefix)))))
12209 ;; Use fast selection
12210 (org-fast-todo-selection))
12211 ((and (equal arg '(4))
12212 (or (not org-use-fast-todo-selection)
12213 (not org-todo-key-trigger)))
12214 ;; Read a state with completion
12215 (org-icompleting-read
12216 "State: " (mapcar 'list org-todo-keywords-1)
12217 nil t))
12218 ((eq arg 'right)
12219 (if this
12220 (if tail (car tail) nil)
12221 (car org-todo-keywords-1)))
12222 ((eq arg 'left)
12223 (if (equal member org-todo-keywords-1)
12225 (if this
12226 (nth (- (length org-todo-keywords-1)
12227 (length tail) 2)
12228 org-todo-keywords-1)
12229 (org-last org-todo-keywords-1))))
12230 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12231 (setq arg nil))) ; hack to fall back to cycling
12232 (arg
12233 ;; user or caller requests a specific state
12234 (cond
12235 ((equal arg "") nil)
12236 ((eq arg 'none) nil)
12237 ((eq arg 'done) (or done-word (car org-done-keywords)))
12238 ((eq arg 'nextset)
12239 (or (car (cdr (member head org-todo-heads)))
12240 (car org-todo-heads)))
12241 ((eq arg 'previousset)
12242 (let ((org-todo-heads (reverse org-todo-heads)))
12243 (or (car (cdr (member head org-todo-heads)))
12244 (car org-todo-heads))))
12245 ((car (member arg org-todo-keywords-1)))
12246 ((stringp arg)
12247 (user-error "State `%s' not valid in this file" arg))
12248 ((nth (1- (prefix-numeric-value arg))
12249 org-todo-keywords-1))))
12250 ((null member) (or head (car org-todo-keywords-1)))
12251 ((equal this final-done-word) nil) ;; -> make empty
12252 ((null tail) nil) ;; -> first entry
12253 ((memq interpret '(type priority))
12254 (if (eq this-command last-command)
12255 (car tail)
12256 (if (> (length tail) 0)
12257 (or done-word (car org-done-keywords))
12258 nil)))
12260 (car tail))))
12261 (org-state (or
12262 (run-hook-with-args-until-success
12263 'org-todo-get-default-hook org-state org-last-state)
12264 org-state))
12265 (next (if org-state (concat " " org-state " ") " "))
12266 (change-plist (list :type 'todo-state-change :from this :to org-state
12267 :position startpos))
12268 dolog now-done-p)
12269 (when org-blocker-hook
12270 (setq org-last-todo-state-is-todo
12271 (not (member this org-done-keywords)))
12272 (unless (save-excursion
12273 (save-match-data
12274 (org-with-wide-buffer
12275 (run-hook-with-args-until-failure
12276 'org-blocker-hook change-plist))))
12277 (if (org-called-interactively-p 'interactive)
12278 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12279 this org-state org-block-entry-blocking)
12280 ;; fail silently
12281 (message "TODO state change from %s to %s blocked (by \"%s\")"
12282 this org-state org-block-entry-blocking)
12283 (throw 'exit nil))))
12284 (store-match-data match-data)
12285 (replace-match next t t)
12286 (unless (pos-visible-in-window-p hl-pos)
12287 (message "TODO state changed to %s" (org-trim next)))
12288 (unless head
12289 (setq head (org-get-todo-sequence-head org-state)
12290 ass (assoc head org-todo-kwd-alist)
12291 interpret (nth 1 ass)
12292 done-word (nth 3 ass)
12293 final-done-word (nth 4 ass)))
12294 (when (memq arg '(nextset previousset))
12295 (message "Keyword-Set %d/%d: %s"
12296 (- (length org-todo-sets) -1
12297 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12298 (length org-todo-sets)
12299 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12300 (setq org-last-todo-state-is-todo
12301 (not (member org-state org-done-keywords)))
12302 (setq now-done-p (and (member org-state org-done-keywords)
12303 (not (member this org-done-keywords))))
12304 (and logging (org-local-logging logging))
12305 (when (and (or org-todo-log-states org-log-done)
12306 (not (eq org-inhibit-logging t))
12307 (not (memq arg '(nextset previousset))))
12308 ;; we need to look at recording a time and note
12309 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12310 (nth 2 (assoc this org-todo-log-states))))
12311 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12312 (setq dolog 'time))
12313 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12314 (and org-state
12315 (member org-state org-not-done-keywords)
12316 (not (member this org-not-done-keywords))))
12317 ;; This is now a todo state and was not one before
12318 ;; If there was a CLOSED time stamp, get rid of it.
12319 (org-add-planning-info nil nil 'closed))
12320 (when (and now-done-p org-log-done)
12321 ;; It is now done, and it was not done before
12322 (org-add-planning-info 'closed (org-current-effective-time))
12323 (if (and (not dolog) (eq 'note org-log-done))
12324 (org-add-log-setup 'done org-state this 'findpos 'note)))
12325 (when (and org-state dolog)
12326 ;; This is a non-nil state, and we need to log it
12327 (org-add-log-setup 'state org-state this 'findpos dolog)))
12328 ;; Fixup tag positioning
12329 (org-todo-trigger-tag-changes org-state)
12330 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12331 (when org-provide-todo-statistics
12332 (org-update-parent-todo-statistics))
12333 (run-hooks 'org-after-todo-state-change-hook)
12334 (if (and arg (not (member org-state org-done-keywords)))
12335 (setq head (org-get-todo-sequence-head org-state)))
12336 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12337 ;; Do we need to trigger a repeat?
12338 (when now-done-p
12339 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12340 ;; This is for the agenda, take a snapshot of the headline.
12341 (save-match-data
12342 (setq org-agenda-headline-snapshot-before-repeat
12343 (org-get-heading))))
12344 (org-auto-repeat-maybe org-state))
12345 ;; Fixup cursor location if close to the keyword
12346 (if (and (outline-on-heading-p)
12347 (not (bolp))
12348 (save-excursion (beginning-of-line 1)
12349 (looking-at org-todo-line-regexp))
12350 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12351 (progn
12352 (goto-char (or (match-end 2) (match-end 1)))
12353 (and (looking-at " ") (just-one-space))))
12354 (when org-trigger-hook
12355 (save-excursion
12356 (run-hook-with-args 'org-trigger-hook change-plist)))
12357 (when commentp (org-toggle-comment))))))))
12359 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12360 "Block turning an entry into a TODO, using the hierarchy.
12361 This checks whether the current task should be blocked from state
12362 changes. Such blocking occurs when:
12364 1. The task has children which are not all in a completed state.
12366 2. A task has a parent with the property :ORDERED:, and there
12367 are siblings prior to the current task with incomplete
12368 status.
12370 3. The parent of the task is blocked because it has siblings that should
12371 be done first, or is child of a block grandparent TODO entry."
12373 (if (not org-enforce-todo-dependencies)
12374 t ; if locally turned off don't block
12375 (catch 'dont-block
12376 ;; If this is not a todo state change, or if this entry is already DONE,
12377 ;; do not block
12378 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12379 (member (plist-get change-plist :from)
12380 (cons 'done org-done-keywords))
12381 (member (plist-get change-plist :to)
12382 (cons 'todo org-not-done-keywords))
12383 (not (plist-get change-plist :to)))
12384 (throw 'dont-block t))
12385 ;; If this task has children, and any are undone, it's blocked
12386 (save-excursion
12387 (org-back-to-heading t)
12388 (let ((this-level (funcall outline-level)))
12389 (outline-next-heading)
12390 (let ((child-level (funcall outline-level)))
12391 (while (and (not (eobp))
12392 (> child-level this-level))
12393 ;; this todo has children, check whether they are all
12394 ;; completed
12395 (if (and (not (org-entry-is-done-p))
12396 (org-entry-is-todo-p))
12397 (progn (setq org-block-entry-blocking (org-get-heading))
12398 (throw 'dont-block nil)))
12399 (outline-next-heading)
12400 (setq child-level (funcall outline-level))))))
12401 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12402 ;; any previous siblings are undone, it's blocked
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (let* ((pos (point))
12406 (parent-pos (and (org-up-heading-safe) (point))))
12407 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12408 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12409 (forward-line 1)
12410 (re-search-forward org-not-done-heading-regexp pos t))
12411 (setq org-block-entry-blocking (match-string 0))
12412 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12413 ;; Search further up the hierarchy, to see if an ancestor is blocked
12414 (while t
12415 (goto-char parent-pos)
12416 (if (not (looking-at org-not-done-heading-regexp))
12417 (throw 'dont-block t)) ; do not block, parent is not a TODO
12418 (setq pos (point))
12419 (setq parent-pos (and (org-up-heading-safe) (point)))
12420 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12421 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12422 (forward-line 1)
12423 (re-search-forward org-not-done-heading-regexp pos t)
12424 (setq org-block-entry-blocking (org-get-heading)))
12425 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12427 (defcustom org-track-ordered-property-with-tag nil
12428 "Should the ORDERED property also be shown as a tag?
12429 The ORDERED property decides if an entry should require subtasks to be
12430 completed in sequence. Since a property is not very visible, setting
12431 this option means that toggling the ORDERED property with the command
12432 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12433 not relevant for the behavior, but it makes things more visible.
12435 Note that toggling the tag with tags commands will not change the property
12436 and therefore not influence behavior!
12438 This can be t, meaning the tag ORDERED should be used, It can also be a
12439 string to select a different tag for this task."
12440 :group 'org-todo
12441 :type '(choice
12442 (const :tag "No tracking" nil)
12443 (const :tag "Track with ORDERED tag" t)
12444 (string :tag "Use other tag")))
12446 (defun org-toggle-ordered-property ()
12447 "Toggle the ORDERED property of the current entry.
12448 For better visibility, you can track the value of this property with a tag.
12449 See variable `org-track-ordered-property-with-tag'."
12450 (interactive)
12451 (let* ((t1 org-track-ordered-property-with-tag)
12452 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12453 (save-excursion
12454 (org-back-to-heading)
12455 (if (org-entry-get nil "ORDERED")
12456 (progn
12457 (org-delete-property "ORDERED" "PROPERTIES")
12458 (and tag (org-toggle-tag tag 'off))
12459 (message "Subtasks can be completed in arbitrary order"))
12460 (org-entry-put nil "ORDERED" "t")
12461 (and tag (org-toggle-tag tag 'on))
12462 (message "Subtasks must be completed in sequence")))))
12464 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12465 (defun org-block-todo-from-checkboxes (change-plist)
12466 "Block turning an entry into a TODO, using checkboxes.
12467 This checks whether the current task should be blocked from state
12468 changes because there are unchecked boxes in this entry."
12469 (if (not org-enforce-todo-checkbox-dependencies)
12470 t ; if locally turned off don't block
12471 (catch 'dont-block
12472 ;; If this is not a todo state change, or if this entry is already DONE,
12473 ;; do not block
12474 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12475 (member (plist-get change-plist :from)
12476 (cons 'done org-done-keywords))
12477 (member (plist-get change-plist :to)
12478 (cons 'todo org-not-done-keywords))
12479 (not (plist-get change-plist :to)))
12480 (throw 'dont-block t))
12481 ;; If this task has checkboxes that are not checked, it's blocked
12482 (save-excursion
12483 (org-back-to-heading t)
12484 (let ((beg (point)) end)
12485 (outline-next-heading)
12486 (setq end (point))
12487 (goto-char beg)
12488 (if (org-list-search-forward
12489 (concat (org-item-beginning-re)
12490 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12491 "\\[[- ]\\]")
12492 end t)
12493 (progn
12494 (if (boundp 'org-blocked-by-checkboxes)
12495 (setq org-blocked-by-checkboxes t))
12496 (throw 'dont-block nil)))))
12497 t))) ; do not block
12499 (defun org-entry-blocked-p ()
12500 "Is the current entry blocked?"
12501 (org-with-silent-modifications
12502 (if (org-entry-get nil "NOBLOCKING")
12503 nil ;; Never block this entry
12504 (not (run-hook-with-args-until-failure
12505 'org-blocker-hook
12506 (list :type 'todo-state-change
12507 :position (point)
12508 :from 'todo
12509 :to 'done))))))
12511 (defun org-update-statistics-cookies (all)
12512 "Update the statistics cookie, either from TODO or from checkboxes.
12513 This should be called with the cursor in a line with a statistics cookie."
12514 (interactive "P")
12515 (if all
12516 (progn
12517 (org-update-checkbox-count 'all)
12518 (org-map-entries 'org-update-parent-todo-statistics))
12519 (if (not (org-at-heading-p))
12520 (org-update-checkbox-count)
12521 (let ((pos (point-marker))
12522 end l1 l2)
12523 (ignore-errors (org-back-to-heading t))
12524 (if (not (org-at-heading-p))
12525 (org-update-checkbox-count)
12526 (setq l1 (org-outline-level))
12527 (setq end (save-excursion
12528 (outline-next-heading)
12529 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12530 (point)))
12531 (if (and (save-excursion
12532 (re-search-forward
12533 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12534 (not (save-excursion (re-search-forward
12535 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12536 (org-update-checkbox-count)
12537 (if (and l2 (> l2 l1))
12538 (progn
12539 (goto-char end)
12540 (org-update-parent-todo-statistics))
12541 (goto-char pos)
12542 (beginning-of-line 1)
12543 (while (re-search-forward
12544 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12545 (point-at-eol) t)
12546 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12547 (goto-char pos)
12548 (move-marker pos nil)))))
12550 (defvar org-entry-property-inherited-from) ;; defined below
12551 (defun org-update-parent-todo-statistics ()
12552 "Update any statistics cookie in the parent of the current headline.
12553 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12554 the entire subtree and this will travel up the hierarchy and update
12555 statistics everywhere."
12556 (let* ((prop (save-excursion (org-up-heading-safe)
12557 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12558 (recursive (or (not org-hierarchical-todo-statistics)
12559 (and prop (string-match "\\<recursive\\>" prop))))
12560 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12562 (first t)
12563 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12564 level ltoggle l1 new ndel
12565 (cnt-all 0) (cnt-done 0) is-percent kwd
12566 checkbox-beg ov ovs ove cookie-present)
12567 (catch 'exit
12568 (save-excursion
12569 (beginning-of-line 1)
12570 (setq ltoggle (funcall outline-level))
12571 ;; Three situations are to consider:
12573 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12574 ;; to the top-level ancestor on the headline;
12576 ;; 2. If parent has "recursive" property, repeat up to the
12577 ;; headline setting that property, taking inheritance into
12578 ;; account;
12580 ;; 3. Else, move up to direct parent and proceed only once.
12581 (while (and (setq level (org-up-heading-safe))
12582 (or recursive first)
12583 (>= (point) lim))
12584 (setq first nil cookie-present nil)
12585 (unless (and level
12586 (not (string-match
12587 "\\<checkbox\\>"
12588 (downcase (or (org-entry-get nil "COOKIE_DATA")
12589 "")))))
12590 (throw 'exit nil))
12591 (while (re-search-forward box-re (point-at-eol) t)
12592 (setq cnt-all 0 cnt-done 0 cookie-present t)
12593 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12594 (save-match-data
12595 (unless (outline-next-heading) (throw 'exit nil))
12596 (while (and (looking-at org-complex-heading-regexp)
12597 (> (setq l1 (length (match-string 1))) level))
12598 (setq kwd (and (or recursive (= l1 ltoggle))
12599 (match-string 2)))
12600 (if (or (eq org-provide-todo-statistics 'all-headlines)
12601 (and (listp org-provide-todo-statistics)
12602 (or (member kwd org-provide-todo-statistics)
12603 (member kwd org-done-keywords))))
12604 (setq cnt-all (1+ cnt-all))
12605 (if (eq org-provide-todo-statistics t)
12606 (and kwd (setq cnt-all (1+ cnt-all)))))
12607 (and (member kwd org-done-keywords)
12608 (setq cnt-done (1+ cnt-done)))
12609 (outline-next-heading)))
12610 (setq new
12611 (if is-percent
12612 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12613 (format "[%d/%d]" cnt-done cnt-all))
12614 ndel (- (match-end 0) checkbox-beg))
12615 ;; handle overlays when updating cookie from column view
12616 (when (setq ov (car (overlays-at checkbox-beg)))
12617 (setq ovs (overlay-start ov) ove (overlay-end ov))
12618 (delete-overlay ov))
12619 (goto-char checkbox-beg)
12620 (insert new)
12621 (delete-region (point) (+ (point) ndel))
12622 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12623 (when ov (move-overlay ov ovs ove)))
12624 (when cookie-present
12625 (run-hook-with-args 'org-after-todo-statistics-hook
12626 cnt-done (- cnt-all cnt-done))))))
12627 (run-hooks 'org-todo-statistics-hook)))
12629 (defvar org-after-todo-statistics-hook nil
12630 "Hook that is called after a TODO statistics cookie has been updated.
12631 Each function is called with two arguments: the number of not-done entries
12632 and the number of done entries.
12634 For example, the following function, when added to this hook, will switch
12635 an entry to DONE when all children are done, and back to TODO when new
12636 entries are set to a TODO status. Note that this hook is only called
12637 when there is a statistics cookie in the headline!
12639 (defun org-summary-todo (n-done n-not-done)
12640 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12641 (let (org-log-done org-log-states) ; turn off logging
12642 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12645 (defvar org-todo-statistics-hook nil
12646 "Hook that is run whenever Org thinks TODO statistics should be updated.
12647 This hook runs even if there is no statistics cookie present, in which case
12648 `org-after-todo-statistics-hook' would not run.")
12650 (defun org-todo-trigger-tag-changes (state)
12651 "Apply the changes defined in `org-todo-state-tags-triggers'."
12652 (let ((l org-todo-state-tags-triggers)
12653 changes)
12654 (when (or (not state) (equal state ""))
12655 (setq changes (append changes (cdr (assoc "" l)))))
12656 (when (and (stringp state) (> (length state) 0))
12657 (setq changes (append changes (cdr (assoc state l)))))
12658 (when (member state org-not-done-keywords)
12659 (setq changes (append changes (cdr (assoc 'todo l)))))
12660 (when (member state org-done-keywords)
12661 (setq changes (append changes (cdr (assoc 'done l)))))
12662 (dolist (c changes)
12663 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12665 (defun org-local-logging (value)
12666 "Get logging settings from a property VALUE."
12667 (let* (words w a)
12668 ;; directly set the variables, they are already local.
12669 (setq org-log-done nil
12670 org-log-repeat nil
12671 org-todo-log-states nil)
12672 (setq words (org-split-string value))
12673 (while (setq w (pop words))
12674 (cond
12675 ((setq a (assoc w org-startup-options))
12676 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12677 (set (nth 1 a) (nth 2 a))))
12678 ((setq a (org-extract-log-state-settings w))
12679 (and (member (car a) org-todo-keywords-1)
12680 (push a org-todo-log-states)))))))
12682 (defun org-get-todo-sequence-head (kwd)
12683 "Return the head of the TODO sequence to which KWD belongs.
12684 If KWD is not set, check if there is a text property remembering the
12685 right sequence."
12686 (let (p)
12687 (cond
12688 ((not kwd)
12689 (or (get-text-property (point-at-bol) 'org-todo-head)
12690 (progn
12691 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12692 nil (point-at-eol)))
12693 (get-text-property p 'org-todo-head))))
12694 ((not (member kwd org-todo-keywords-1))
12695 (car org-todo-keywords-1))
12696 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12698 (defun org-fast-todo-selection ()
12699 "Fast TODO keyword selection with single keys.
12700 Returns the new TODO keyword, or nil if no state change should occur."
12701 (let* ((fulltable org-todo-key-alist)
12702 (done-keywords org-done-keywords) ;; needed for the faces.
12703 (maxlen (apply 'max (mapcar
12704 (lambda (x)
12705 (if (stringp (car x)) (string-width (car x)) 0))
12706 fulltable)))
12707 (expert nil)
12708 (fwidth (+ maxlen 3 1 3))
12709 (ncol (/ (- (window-width) 4) fwidth))
12710 tg cnt e c tbl
12711 groups ingroup)
12712 (save-excursion
12713 (save-window-excursion
12714 (if expert
12715 (set-buffer (get-buffer-create " *Org todo*"))
12716 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12717 (erase-buffer)
12718 (org-set-local 'org-done-keywords done-keywords)
12719 (setq tbl fulltable cnt 0)
12720 (while (setq e (pop tbl))
12721 (cond
12722 ((equal e '(:startgroup))
12723 (push '() groups) (setq ingroup t)
12724 (when (not (= cnt 0))
12725 (setq cnt 0)
12726 (insert "\n"))
12727 (insert "{ "))
12728 ((equal e '(:endgroup))
12729 (setq ingroup nil cnt 0)
12730 (insert "}\n"))
12731 ((equal e '(:newline))
12732 (when (not (= cnt 0))
12733 (setq cnt 0)
12734 (insert "\n")
12735 (setq e (car tbl))
12736 (while (equal (car tbl) '(:newline))
12737 (insert "\n")
12738 (setq tbl (cdr tbl)))))
12740 (setq tg (car e) c (cdr e))
12741 (if ingroup (push tg (car groups)))
12742 (setq tg (org-add-props tg nil 'face
12743 (org-get-todo-face tg)))
12744 (if (and (= cnt 0) (not ingroup)) (insert " "))
12745 (insert "[" c "] " tg (make-string
12746 (- fwidth 4 (length tg)) ?\ ))
12747 (when (= (setq cnt (1+ cnt)) ncol)
12748 (insert "\n")
12749 (if ingroup (insert " "))
12750 (setq cnt 0)))))
12751 (insert "\n")
12752 (goto-char (point-min))
12753 (if (not expert) (org-fit-window-to-buffer))
12754 (message "[a-z..]:Set [SPC]:clear")
12755 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12756 (cond
12757 ((or (= c ?\C-g)
12758 (and (= c ?q) (not (rassoc c fulltable))))
12759 (setq quit-flag t))
12760 ((= c ?\ ) nil)
12761 ((setq e (rassoc c fulltable) tg (car e))
12763 (t (setq quit-flag t)))))))
12765 (defun org-entry-is-todo-p ()
12766 (member (org-get-todo-state) org-not-done-keywords))
12768 (defun org-entry-is-done-p ()
12769 (member (org-get-todo-state) org-done-keywords))
12771 (defun org-get-todo-state ()
12772 "Return the TODO keyword of the current subtree."
12773 (save-excursion
12774 (org-back-to-heading t)
12775 (and (looking-at org-todo-line-regexp)
12776 (match-end 2)
12777 (match-string 2))))
12779 (defun org-at-date-range-p (&optional inactive-ok)
12780 "Is the cursor inside a date range?"
12781 (interactive)
12782 (save-excursion
12783 (catch 'exit
12784 (let ((pos (point)))
12785 (skip-chars-backward "^[<\r\n")
12786 (skip-chars-backward "<[")
12787 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12788 (>= (match-end 0) pos)
12789 (throw 'exit t))
12790 (skip-chars-backward "^<[\r\n")
12791 (skip-chars-backward "<[")
12792 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12793 (>= (match-end 0) pos)
12794 (throw 'exit t)))
12795 nil)))
12797 (defun org-get-repeat (&optional tagline)
12798 "Check if there is a deadline/schedule with repeater in this entry."
12799 (save-match-data
12800 (save-excursion
12801 (org-back-to-heading t)
12802 (and (re-search-forward (if tagline
12803 (concat tagline "\\s-*" org-repeat-re)
12804 org-repeat-re)
12805 (org-entry-end-position) t)
12806 (match-string-no-properties 1)))))
12808 (defvar org-last-changed-timestamp)
12809 (defvar org-last-inserted-timestamp)
12810 (defvar org-log-post-message)
12811 (defvar org-log-note-purpose)
12812 (defvar org-log-note-how)
12813 (defvar org-log-note-extra)
12814 (defun org-auto-repeat-maybe (done-word)
12815 "Check if the current headline contains a repeated deadline/schedule.
12816 If yes, set TODO state back to what it was and change the base date
12817 of repeating deadline/scheduled time stamps to new date.
12818 This function is run automatically after each state change to a DONE state."
12819 ;; last-state is dynamically scoped into this function
12820 (let* ((repeat (org-get-repeat))
12821 (aa (assoc org-last-state org-todo-kwd-alist))
12822 (interpret (nth 1 aa))
12823 (head (nth 2 aa))
12824 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12825 (msg "Entry repeats: ")
12826 (org-log-done nil)
12827 (org-todo-log-states nil)
12828 re type n what ts time to-state)
12829 (when repeat
12830 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12831 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12832 org-todo-repeat-to-state))
12833 (unless (and to-state (member to-state org-todo-keywords-1))
12834 (setq to-state (if (eq interpret 'type) org-last-state head)))
12835 (org-todo to-state)
12836 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12837 (org-entry-put nil "LAST_REPEAT" (format-time-string
12838 (org-time-stamp-format t t))))
12839 (when org-log-repeat
12840 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12841 (memq 'org-add-log-note post-command-hook))
12842 ;; OK, we are already setup for some record
12843 (if (eq org-log-repeat 'note)
12844 ;; make sure we take a note, not only a time stamp
12845 (setq org-log-note-how 'note))
12846 ;; Set up for taking a record
12847 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12848 org-last-state
12849 'findpos org-log-repeat)))
12850 (org-back-to-heading t)
12851 (org-add-planning-info nil nil 'closed)
12852 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12853 org-deadline-time-regexp "\\)\\|\\("
12854 org-ts-regexp "\\)"))
12855 (while (re-search-forward
12856 re (save-excursion (outline-next-heading) (point)) t)
12857 (setq type (if (match-end 1) org-scheduled-string
12858 (if (match-end 3) org-deadline-string "Plain:"))
12859 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12860 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12861 (setq n (string-to-number (match-string 2 ts))
12862 what (match-string 3 ts))
12863 (if (equal what "w") (setq n (* n 7) what "d"))
12864 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12865 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12866 ;; Preparation, see if we need to modify the start date for the change
12867 (when (match-end 1)
12868 (setq time (save-match-data (org-time-string-to-time ts)))
12869 (cond
12870 ((equal (match-string 1 ts) ".")
12871 ;; Shift starting date to today
12872 (org-timestamp-change
12873 (- (org-today) (time-to-days time))
12874 'day))
12875 ((equal (match-string 1 ts) "+")
12876 (let ((nshiftmax 10) (nshift 0))
12877 (while (or (= nshift 0)
12878 (<= (time-to-days time)
12879 (time-to-days (current-time))))
12880 (when (= (incf nshift) nshiftmax)
12881 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12882 (error "Abort")))
12883 (org-timestamp-change n (cdr (assoc what whata)))
12884 (org-at-timestamp-p t)
12885 (setq ts (match-string 1))
12886 (setq time (save-match-data (org-time-string-to-time ts)))))
12887 (org-timestamp-change (- n) (cdr (assoc what whata)))
12888 ;; rematch, so that we have everything in place for the real shift
12889 (org-at-timestamp-p t)
12890 (setq ts (match-string 1))
12891 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12892 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12893 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12894 (setq org-log-post-message msg)
12895 (message "%s" msg))))
12897 (defun org-show-todo-tree (arg)
12898 "Make a compact tree which shows all headlines marked with TODO.
12899 The tree will show the lines where the regexp matches, and all higher
12900 headlines above the match.
12901 With a \\[universal-argument] prefix, prompt for a regexp to match.
12902 With a numeric prefix N, construct a sparse tree for the Nth element
12903 of `org-todo-keywords-1'."
12904 (interactive "P")
12905 (let ((case-fold-search nil)
12906 (kwd-re
12907 (cond ((null arg) org-not-done-regexp)
12908 ((equal arg '(4))
12909 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12910 (mapcar 'list org-todo-keywords-1))))
12911 (concat "\\("
12912 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12913 "\\)\\>")))
12914 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12915 (regexp-quote (nth (1- (prefix-numeric-value arg))
12916 org-todo-keywords-1)))
12917 (t (user-error "Invalid prefix argument: %s" arg)))))
12918 (message "%d TODO entries found"
12919 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12921 (defun org-deadline (arg &optional time)
12922 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12923 With one universal prefix argument, remove any deadline from the item.
12924 With two universal prefix arguments, prompt for a warning delay.
12925 With argument TIME, set the deadline at the corresponding date. TIME
12926 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12927 (interactive "P")
12928 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12929 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12930 'region-start-level 'region))
12931 org-loop-over-headlines-in-active-region)
12932 (org-map-entries
12933 `(org-deadline ',arg ,time)
12934 org-loop-over-headlines-in-active-region
12935 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12936 (let* ((old-date (org-entry-get nil "DEADLINE"))
12937 (old-date-time (if old-date (org-time-string-to-time old-date)))
12938 (repeater (and old-date
12939 (string-match
12940 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12941 old-date)
12942 (match-string 1 old-date))))
12943 (cond
12944 ((equal arg '(4))
12945 (when (and old-date org-log-redeadline)
12946 (org-add-log-setup 'deldeadline nil old-date 'findpos
12947 org-log-redeadline))
12948 (org-remove-timestamp-with-keyword org-deadline-string)
12949 (message "Item no longer has a deadline."))
12950 ((equal arg '(16))
12951 (save-excursion
12952 (if (re-search-forward
12953 org-deadline-time-regexp
12954 (save-excursion (outline-next-heading) (point)) t)
12955 (let* ((rpl0 (match-string 1))
12956 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12957 (replace-match
12958 (concat org-deadline-string
12959 " <" rpl
12960 (format " -%dd"
12961 (abs
12962 (- (time-to-days
12963 (save-match-data
12964 (org-read-date nil t nil "Warn starting from" old-date-time)))
12965 (time-to-days old-date-time))))
12966 ">") t t))
12967 (user-error "No deadline information to update"))))
12969 (org-add-planning-info 'deadline time 'closed)
12970 (when (and old-date org-log-redeadline
12971 (not (equal old-date
12972 (substring org-last-inserted-timestamp 1 -1))))
12973 (org-add-log-setup 'redeadline nil old-date 'findpos
12974 org-log-redeadline))
12975 (when repeater
12976 (save-excursion
12977 (org-back-to-heading t)
12978 (when (re-search-forward (concat org-deadline-string " "
12979 org-last-inserted-timestamp)
12980 (save-excursion
12981 (outline-next-heading) (point)) t)
12982 (goto-char (1- (match-end 0)))
12983 (insert " " repeater)
12984 (setq org-last-inserted-timestamp
12985 (concat (substring org-last-inserted-timestamp 0 -1)
12986 " " repeater
12987 (substring org-last-inserted-timestamp -1))))))
12988 (message "Deadline on %s" org-last-inserted-timestamp))))))
12990 (defun org-schedule (arg &optional time)
12991 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12992 With one universal prefix argument, remove any scheduling date from the item.
12993 With two universal prefix arguments, prompt for a delay cookie.
12994 With argument TIME, scheduled at the corresponding date. TIME can
12995 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12996 (interactive "P")
12997 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12998 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12999 'region-start-level 'region))
13000 org-loop-over-headlines-in-active-region)
13001 (org-map-entries
13002 `(org-schedule ',arg ,time)
13003 org-loop-over-headlines-in-active-region
13004 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13005 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13006 (old-date-time (if old-date (org-time-string-to-time old-date)))
13007 (repeater (and old-date
13008 (string-match
13009 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13010 old-date)
13011 (match-string 1 old-date))))
13012 (cond
13013 ((equal arg '(4))
13014 (progn
13015 (when (and old-date org-log-reschedule)
13016 (org-add-log-setup 'delschedule nil old-date 'findpos
13017 org-log-reschedule))
13018 (org-remove-timestamp-with-keyword org-scheduled-string)
13019 (message "Item is no longer scheduled.")))
13020 ((equal arg '(16))
13021 (save-excursion
13022 (if (re-search-forward
13023 org-scheduled-time-regexp
13024 (save-excursion (outline-next-heading) (point)) t)
13025 (let* ((rpl0 (match-string 1))
13026 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13027 (replace-match
13028 (concat org-scheduled-string
13029 " <" rpl
13030 (format " -%dd"
13031 (abs
13032 (- (time-to-days
13033 (save-match-data
13034 (org-read-date nil t nil "Delay until" old-date-time)))
13035 (time-to-days old-date-time))))
13036 ">") t t))
13037 (user-error "No scheduled information to update"))))
13039 (org-add-planning-info 'scheduled time 'closed)
13040 (when (and old-date org-log-reschedule
13041 (not (equal old-date
13042 (substring org-last-inserted-timestamp 1 -1))))
13043 (org-add-log-setup 'reschedule nil old-date 'findpos
13044 org-log-reschedule))
13045 (when repeater
13046 (save-excursion
13047 (org-back-to-heading t)
13048 (when (re-search-forward (concat org-scheduled-string " "
13049 org-last-inserted-timestamp)
13050 (save-excursion
13051 (outline-next-heading) (point)) t)
13052 (goto-char (1- (match-end 0)))
13053 (insert " " repeater)
13054 (setq org-last-inserted-timestamp
13055 (concat (substring org-last-inserted-timestamp 0 -1)
13056 " " repeater
13057 (substring org-last-inserted-timestamp -1))))))
13058 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13060 (defun org-get-scheduled-time (pom &optional inherit)
13061 "Get the scheduled time as a time tuple, of a format suitable
13062 for calling org-schedule with, or if there is no scheduling,
13063 returns nil."
13064 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13065 (when time
13066 (apply 'encode-time (org-parse-time-string time)))))
13068 (defun org-get-deadline-time (pom &optional inherit)
13069 "Get the deadline as a time tuple, of a format suitable for
13070 calling org-deadline with, or if there is no scheduling, returns
13071 nil."
13072 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13073 (when time
13074 (apply 'encode-time (org-parse-time-string time)))))
13076 (defun org-remove-timestamp-with-keyword (keyword)
13077 "Remove all time stamps with KEYWORD in the current entry."
13078 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13079 beg)
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (setq beg (point))
13083 (outline-next-heading)
13084 (while (re-search-backward re beg t)
13085 (replace-match "")
13086 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13087 (equal (char-before) ?\ ))
13088 (backward-delete-char 1)
13089 (if (string-match "^[ \t]*$" (buffer-substring
13090 (point-at-bol) (point-at-eol)))
13091 (delete-region (point-at-bol)
13092 (min (point-max) (1+ (point-at-eol))))))))))
13094 (defun org-add-planning-info (what &optional time &rest remove)
13095 "Insert new timestamp with keyword in the line directly after the headline.
13096 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13097 If non is given, the user is prompted for a date.
13098 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13099 be removed."
13100 (interactive)
13101 (let (org-time-was-given org-end-time-was-given ts
13102 end default-time default-input)
13104 (catch 'exit
13105 (when (and (memq what '(scheduled deadline))
13106 (or (not time)
13107 (and (stringp time)
13108 (string-match "^[-+]+[0-9]" time))))
13109 ;; Try to get a default date/time from existing timestamp
13110 (save-excursion
13111 (org-back-to-heading t)
13112 (setq end (save-excursion (outline-next-heading) (point)))
13113 (when (re-search-forward (if (eq what 'scheduled)
13114 org-scheduled-time-regexp
13115 org-deadline-time-regexp)
13116 end t)
13117 (setq ts (match-string 1)
13118 default-time
13119 (apply 'encode-time (org-parse-time-string ts))
13120 default-input (and ts (org-get-compact-tod ts))))))
13121 (when what
13122 (setq time
13123 (if (stringp time)
13124 ;; This is a string (relative or absolute), set proper date
13125 (apply 'encode-time
13126 (org-read-date-analyze
13127 time default-time (decode-time default-time)))
13128 ;; If necessary, get the time from the user
13129 (or time (org-read-date nil 'to-time nil nil
13130 default-time default-input)))))
13132 (when (and org-insert-labeled-timestamps-at-point
13133 (member what '(scheduled deadline)))
13134 (insert
13135 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13136 (org-insert-time-stamp time org-time-was-given
13137 nil nil nil (list org-end-time-was-given))
13138 (setq what nil))
13139 (save-excursion
13140 (save-restriction
13141 (let (col list elt ts buffer-invisibility-spec)
13142 (org-back-to-heading t)
13143 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13144 (goto-char (match-end 1))
13145 (setq col (current-column))
13146 (goto-char (match-end 0))
13147 (if (eobp) (insert "\n") (forward-char 1))
13148 (when (and (not what)
13149 (not (looking-at
13150 (concat "[ \t]*"
13151 org-keyword-time-not-clock-regexp))))
13152 ;; Nothing to add, nothing to remove...... :-)
13153 (throw 'exit nil))
13154 (if (and (not (looking-at org-outline-regexp))
13155 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13156 "[^\r\n]*"))
13157 (not (equal (match-string 1) org-clock-string)))
13158 (narrow-to-region (match-beginning 0) (match-end 0))
13159 (insert-before-markers "\n")
13160 (backward-char 1)
13161 (narrow-to-region (point) (point))
13162 (and org-adapt-indentation (org-indent-to-column col)))
13163 ;; Check if we have to remove something.
13164 (setq list (cons what remove))
13165 (while list
13166 (setq elt (pop list))
13167 (when (or (and (eq elt 'scheduled)
13168 (re-search-forward org-scheduled-time-regexp nil t))
13169 (and (eq elt 'deadline)
13170 (re-search-forward org-deadline-time-regexp nil t))
13171 (and (eq elt 'closed)
13172 (re-search-forward org-closed-time-regexp nil t)))
13173 (replace-match "")
13174 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13175 (and (looking-at "[ \t]+") (replace-match ""))
13176 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13177 (when what
13178 (insert
13179 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13180 (cond ((eq what 'scheduled) org-scheduled-string)
13181 ((eq what 'deadline) org-deadline-string)
13182 ((eq what 'closed) org-closed-string))
13183 " ")
13184 (setq ts (org-insert-time-stamp
13185 time
13186 (or org-time-was-given
13187 (and (eq what 'closed) org-log-done-with-time))
13188 (eq what 'closed)
13189 nil nil (list org-end-time-was-given)))
13190 (insert
13191 (if (not (or (bolp) (eq (char-before) ?\ )
13192 (memq (char-after) '(32 10))
13193 (eobp))) " " ""))
13194 (end-of-line 1))
13195 (goto-char (point-min))
13196 (widen)
13197 (if (and (looking-at "[ \t]*\n")
13198 (equal (char-before) ?\n))
13199 (delete-region (1- (point)) (point-at-eol)))
13200 ts))))))
13202 (defvar org-log-note-marker (make-marker))
13203 (defvar org-log-note-purpose nil)
13204 (defvar org-log-note-state nil)
13205 (defvar org-log-note-previous-state nil)
13206 (defvar org-log-note-how nil)
13207 (defvar org-log-note-extra nil)
13208 (defvar org-log-note-window-configuration nil)
13209 (defvar org-log-note-return-to (make-marker))
13210 (defvar org-log-note-effective-time nil
13211 "Remembered current time so that dynamically scoped
13212 `org-extend-today-until' affects tha timestamps in state change
13213 log")
13215 (defvar org-log-post-message nil
13216 "Message to be displayed after a log note has been stored.
13217 The auto-repeater uses this.")
13219 (defun org-add-note ()
13220 "Add a note to the current entry.
13221 This is done in the same way as adding a state change note."
13222 (interactive)
13223 (org-add-log-setup 'note nil nil 'findpos nil))
13225 (defvar org-property-end-re)
13226 (defun org-add-log-setup (&optional purpose state prev-state
13227 findpos how extra)
13228 "Set up the post command hook to take a note.
13229 If this is about to TODO state change, the new state is expected in STATE.
13230 When FINDPOS is non-nil, find the correct position for the note in
13231 the current entry. If not, assume that it can be inserted at point.
13232 HOW is an indicator what kind of note should be created.
13233 EXTRA is additional text that will be inserted into the notes buffer."
13234 (let* ((org-log-into-drawer (org-log-into-drawer))
13235 (drawer (cond ((stringp org-log-into-drawer)
13236 org-log-into-drawer)
13237 (org-log-into-drawer "LOGBOOK"))))
13238 (save-restriction
13239 (save-excursion
13240 (when findpos
13241 (org-back-to-heading t)
13242 (narrow-to-region (point) (save-excursion
13243 (outline-next-heading) (point)))
13244 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13245 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13246 "[^\r\n]*\\)?"))
13247 (goto-char (match-end 0))
13248 (cond
13249 (drawer
13250 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13251 nil t)
13252 (progn
13253 (goto-char (match-end 0))
13254 (or org-log-states-order-reversed
13255 (and (re-search-forward org-property-end-re nil t)
13256 (goto-char (1- (match-beginning 0))))))
13257 (insert "\n:" drawer ":\n:END:")
13258 (beginning-of-line 0)
13259 (org-indent-line)
13260 (beginning-of-line 2)
13261 (org-indent-line)
13262 (end-of-line 0)))
13263 ((and org-log-state-notes-insert-after-drawers
13264 (save-excursion
13265 (forward-line) (looking-at org-drawer-regexp)))
13266 (forward-line)
13267 (while (looking-at org-drawer-regexp)
13268 (goto-char (match-end 0))
13269 (re-search-forward org-property-end-re (point-max) t)
13270 (forward-line))
13271 (forward-line -1)))
13272 (unless org-log-states-order-reversed
13273 (and (= (char-after) ?\n) (forward-char 1))
13274 (org-skip-over-state-notes)
13275 (skip-chars-backward " \t\n\r")))
13276 (move-marker org-log-note-marker (point))
13277 (setq org-log-note-purpose purpose
13278 org-log-note-state state
13279 org-log-note-previous-state prev-state
13280 org-log-note-how how
13281 org-log-note-extra extra
13282 org-log-note-effective-time (org-current-effective-time))
13283 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13285 (defun org-skip-over-state-notes ()
13286 "Skip past the list of State notes in an entry."
13287 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13288 (when (ignore-errors (goto-char (org-in-item-p)))
13289 (let* ((struct (org-list-struct))
13290 (prevs (org-list-prevs-alist struct)))
13291 (while (looking-at "[ \t]*- State")
13292 (goto-char (or (org-list-get-next-item (point) struct prevs)
13293 (org-list-get-item-end (point) struct)))))))
13295 (defun org-add-log-note (&optional purpose)
13296 "Pop up a window for taking a note, and add this note later at point."
13297 (remove-hook 'post-command-hook 'org-add-log-note)
13298 (setq org-log-note-window-configuration (current-window-configuration))
13299 (delete-other-windows)
13300 (move-marker org-log-note-return-to (point))
13301 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13302 (goto-char org-log-note-marker)
13303 (org-switch-to-buffer-other-window "*Org Note*")
13304 (erase-buffer)
13305 (if (memq org-log-note-how '(time state))
13306 (let (current-prefix-arg) (org-store-log-note))
13307 (let ((org-inhibit-startup t)) (org-mode))
13308 (insert (format "# Insert note for %s.
13309 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13310 (cond
13311 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13312 ((eq org-log-note-purpose 'done) "closed todo item")
13313 ((eq org-log-note-purpose 'state)
13314 (format "state change from \"%s\" to \"%s\""
13315 (or org-log-note-previous-state "")
13316 (or org-log-note-state "")))
13317 ((eq org-log-note-purpose 'reschedule)
13318 "rescheduling")
13319 ((eq org-log-note-purpose 'delschedule)
13320 "no longer scheduled")
13321 ((eq org-log-note-purpose 'redeadline)
13322 "changing deadline")
13323 ((eq org-log-note-purpose 'deldeadline)
13324 "removing deadline")
13325 ((eq org-log-note-purpose 'refile)
13326 "refiling")
13327 ((eq org-log-note-purpose 'note)
13328 "this entry")
13329 (t (error "This should not happen")))))
13330 (if org-log-note-extra (insert org-log-note-extra))
13331 (org-set-local 'org-finish-function 'org-store-log-note)
13332 (run-hooks 'org-log-buffer-setup-hook)))
13334 (defvar org-note-abort nil) ; dynamically scoped
13335 (defun org-store-log-note ()
13336 "Finish taking a log note, and insert it to where it belongs."
13337 (let ((txt (buffer-string)))
13338 (kill-buffer (current-buffer))
13339 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13340 lines ind bul)
13341 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13342 (setq txt (replace-match "" t t txt)))
13343 (if (string-match "\\s-+\\'" txt)
13344 (setq txt (replace-match "" t t txt)))
13345 (setq lines (org-split-string txt "\n"))
13346 (when (and note (string-match "\\S-" note))
13347 (setq note
13348 (org-replace-escapes
13349 note
13350 (list (cons "%u" (user-login-name))
13351 (cons "%U" user-full-name)
13352 (cons "%t" (format-time-string
13353 (org-time-stamp-format 'long 'inactive)
13354 org-log-note-effective-time))
13355 (cons "%T" (format-time-string
13356 (org-time-stamp-format 'long nil)
13357 org-log-note-effective-time))
13358 (cons "%d" (format-time-string
13359 (org-time-stamp-format nil 'inactive)
13360 org-log-note-effective-time))
13361 (cons "%D" (format-time-string
13362 (org-time-stamp-format nil nil)
13363 org-log-note-effective-time))
13364 (cons "%s" (if org-log-note-state
13365 (concat "\"" org-log-note-state "\"")
13366 ""))
13367 (cons "%S" (if org-log-note-previous-state
13368 (concat "\"" org-log-note-previous-state "\"")
13369 "\"\"")))))
13370 (if lines (setq note (concat note " \\\\")))
13371 (push note lines))
13372 (when (or current-prefix-arg org-note-abort)
13373 (when org-log-into-drawer
13374 (org-remove-empty-drawer-at
13375 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13376 org-log-note-marker))
13377 (setq lines nil))
13378 (when lines
13379 (with-current-buffer (marker-buffer org-log-note-marker)
13380 (save-excursion
13381 (goto-char org-log-note-marker)
13382 (move-marker org-log-note-marker nil)
13383 (end-of-line 1)
13384 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13385 (setq ind (save-excursion
13386 (if (ignore-errors (goto-char (org-in-item-p)))
13387 (let ((struct (org-list-struct)))
13388 (org-list-get-ind
13389 (org-list-get-top-point struct) struct))
13390 (skip-chars-backward " \r\t\n")
13391 (cond
13392 ((and (org-at-heading-p)
13393 org-adapt-indentation)
13394 (1+ (org-current-level)))
13395 ((org-at-heading-p) 0)
13396 (t (org-get-indentation))))))
13397 (setq bul (org-list-bullet-string "-"))
13398 (org-indent-line-to ind)
13399 (insert bul (pop lines))
13400 (let ((ind-body (+ (length bul) ind)))
13401 (while lines
13402 (insert "\n")
13403 (org-indent-line-to ind-body)
13404 (insert (pop lines))))
13405 (message "Note stored")
13406 (org-back-to-heading t)
13407 (org-cycle-hide-drawers 'children))
13408 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13409 ;; from within `org-add-log-note' because `buffer-undo-list'
13410 ;; is then modified outside of `org-with-remote-undo'.
13411 (when (eq this-command 'org-agenda-todo)
13412 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13413 ;; Don't add undo information when called from `org-agenda-todo'
13414 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13415 (set-window-configuration org-log-note-window-configuration)
13416 (with-current-buffer (marker-buffer org-log-note-return-to)
13417 (goto-char org-log-note-return-to))
13418 (move-marker org-log-note-return-to nil)
13419 (and org-log-post-message (message "%s" org-log-post-message))))
13421 (defun org-remove-empty-drawer-at (drawer pos)
13422 "Remove an empty drawer DRAWER at position POS.
13423 POS may also be a marker."
13424 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13425 (save-excursion
13426 (save-restriction
13427 (widen)
13428 (goto-char pos)
13429 (if (org-in-regexp
13430 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13431 (replace-match ""))))))
13433 (defvar org-ts-type nil)
13434 (defun org-sparse-tree (&optional arg type)
13435 "Create a sparse tree, prompt for the details.
13436 This command can create sparse trees. You first need to select the type
13437 of match used to create the tree:
13439 t Show all TODO entries.
13440 T Show entries with a specific TODO keyword.
13441 m Show entries selected by a tags/property match.
13442 p Enter a property name and its value (both with completion on existing
13443 names/values) and show entries with that property.
13444 r Show entries matching a regular expression (`/' can be used as well).
13445 b Show deadlines and scheduled items before a date.
13446 a Show deadlines and scheduled items after a date.
13447 d Show deadlines due within `org-deadline-warning-days'.
13448 D Show deadlines and scheduled items between a date range."
13449 (interactive "P")
13450 (let (ans kwd value ts-type)
13451 (setq type (or type org-sparse-tree-default-date-type))
13452 (setq org-ts-type type)
13453 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13454 (cond ((eq type 'all) "all timestamps")
13455 ((eq type 'scheduled) "only scheduled")
13456 ((eq type 'deadline) "only deadline")
13457 ((eq type 'active) "only active timestamps")
13458 ((eq type 'inactive) "only inactive timestamps")
13459 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13460 ((eq type 'closed) "with a closed time-stamp")
13461 (t "scheduled/deadline")))
13462 (setq ans (read-char-exclusive))
13463 (cond
13464 ((equal ans ?c)
13465 (org-sparse-tree
13466 arg (cadr (member type '(scheduled-or-deadline
13467 all scheduled deadline active inactive closed)))))
13468 ((equal ans ?d)
13469 (call-interactively 'org-check-deadlines))
13470 ((equal ans ?b)
13471 (call-interactively 'org-check-before-date))
13472 ((equal ans ?a)
13473 (call-interactively 'org-check-after-date))
13474 ((equal ans ?D)
13475 (call-interactively 'org-check-dates-range))
13476 ((equal ans ?t)
13477 (call-interactively 'org-show-todo-tree))
13478 ((equal ans ?T)
13479 (org-show-todo-tree '(4)))
13480 ((member ans '(?T ?m))
13481 (call-interactively 'org-match-sparse-tree))
13482 ((member ans '(?p ?P))
13483 (setq kwd (org-icompleting-read "Property: "
13484 (mapcar 'list (org-buffer-property-keys))))
13485 (setq value (org-icompleting-read "Value: "
13486 (mapcar 'list (org-property-values kwd))))
13487 (unless (string-match "\\`{.*}\\'" value)
13488 (setq value (concat "\"" value "\"")))
13489 (org-match-sparse-tree arg (concat kwd "=" value)))
13490 ((member ans '(?r ?R ?/))
13491 (call-interactively 'org-occur))
13492 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13494 (defvar org-occur-highlights nil
13495 "List of overlays used for occur matches.")
13496 (make-variable-buffer-local 'org-occur-highlights)
13497 (defvar org-occur-parameters nil
13498 "Parameters of the active org-occur calls.
13499 This is a list, each call to org-occur pushes as cons cell,
13500 containing the regular expression and the callback, onto the list.
13501 The list can contain several entries if `org-occur' has been called
13502 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13503 will only contain one set of parameters. When the highlights are
13504 removed (for example with `C-c C-c', or with the next edit (depending
13505 on `org-remove-highlights-with-change'), this variable is emptied
13506 as well.")
13507 (make-variable-buffer-local 'org-occur-parameters)
13509 (defun org-occur (regexp &optional keep-previous callback)
13510 "Make a compact tree which shows all matches of REGEXP.
13511 The tree will show the lines where the regexp matches, and all higher
13512 headlines above the match. It will also show the heading after the match,
13513 to make sure editing the matching entry is easy.
13514 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13515 call to `org-occur' will be kept, to allow stacking of calls to this
13516 command.
13517 If CALLBACK is non-nil, it is a function which is called to confirm
13518 that the match should indeed be shown."
13519 (interactive "sRegexp: \nP")
13520 (when (equal regexp "")
13521 (user-error "Regexp cannot be empty"))
13522 (unless keep-previous
13523 (org-remove-occur-highlights nil nil t))
13524 (push (cons regexp callback) org-occur-parameters)
13525 (let ((cnt 0))
13526 (save-excursion
13527 (goto-char (point-min))
13528 (if (or (not keep-previous) ; do not want to keep
13529 (not org-occur-highlights)) ; no previous matches
13530 ;; hide everything
13531 (org-overview))
13532 (while (re-search-forward regexp nil t)
13533 (when (or (not callback)
13534 (save-match-data (funcall callback)))
13535 (setq cnt (1+ cnt))
13536 (when org-highlight-sparse-tree-matches
13537 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13538 (org-show-context 'occur-tree))))
13539 (when org-remove-highlights-with-change
13540 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13541 nil 'local))
13542 (unless org-sparse-tree-open-archived-trees
13543 (org-hide-archived-subtrees (point-min) (point-max)))
13544 (run-hooks 'org-occur-hook)
13545 (if (org-called-interactively-p 'interactive)
13546 (message "%d match(es) for regexp %s" cnt regexp))
13547 cnt))
13549 (defun org-occur-next-match (&optional n reset)
13550 "Function for `next-error-function' to find sparse tree matches.
13551 N is the number of matches to move, when negative move backwards.
13552 RESET is entirely ignored - this function always goes back to the
13553 starting point when no match is found."
13554 (let* ((limit (if (< n 0) (point-min) (point-max)))
13555 (search-func (if (< n 0)
13556 'previous-single-char-property-change
13557 'next-single-char-property-change))
13558 (n (abs n))
13559 (pos (point))
13561 (catch 'exit
13562 (while (setq p1 (funcall search-func (point) 'org-type))
13563 (when (equal p1 limit)
13564 (goto-char pos)
13565 (error "No more matches"))
13566 (when (equal (get-char-property p1 'org-type) 'org-occur)
13567 (setq n (1- n))
13568 (when (= n 0)
13569 (goto-char p1)
13570 (throw 'exit (point))))
13571 (goto-char p1))
13572 (goto-char p1)
13573 (error "No more matches"))))
13575 (defun org-show-context (&optional key)
13576 "Make sure point and context are visible.
13577 How much context is shown depends upon the variables
13578 `org-show-hierarchy-above', `org-show-following-heading',
13579 `org-show-entry-below' and `org-show-siblings'."
13580 (let ((heading-p (org-at-heading-p t))
13581 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13582 (following-p (org-get-alist-option org-show-following-heading key))
13583 (entry-p (org-get-alist-option org-show-entry-below key))
13584 (siblings-p (org-get-alist-option org-show-siblings key)))
13585 ;; Show heading or entry text
13586 (if (and heading-p (not entry-p))
13587 (org-flag-heading nil) ; only show the heading
13588 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13589 (org-show-hidden-entry))) ; show entire entry
13590 (when following-p
13591 ;; Show next sibling, or heading below text
13592 (save-excursion
13593 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13594 (org-flag-heading nil))))
13595 (when siblings-p (org-show-siblings))
13596 (when hierarchy-p
13597 ;; show all higher headings, possibly with siblings
13598 (save-excursion
13599 (while (and (condition-case nil
13600 (progn (org-up-heading-all 1) t)
13601 (error nil))
13602 (not (bobp)))
13603 (org-flag-heading nil)
13604 (when siblings-p (org-show-siblings)))))
13605 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13607 (defvar org-reveal-start-hook nil
13608 "Hook run before revealing a location.")
13610 (defun org-reveal (&optional siblings)
13611 "Show current entry, hierarchy above it, and the following headline.
13612 This can be used to show a consistent set of context around locations
13613 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13614 not t for the search context.
13616 With optional argument SIBLINGS, on each level of the hierarchy all
13617 siblings are shown. This repairs the tree structure to what it would
13618 look like when opened with hierarchical calls to `org-cycle'.
13619 With double optional argument \\[universal-argument] \\[universal-argument], \
13620 go to the parent and show the
13621 entire tree."
13622 (interactive "P")
13623 (run-hooks 'org-reveal-start-hook)
13624 (let ((org-show-hierarchy-above t)
13625 (org-show-following-heading t)
13626 (org-show-siblings (if siblings t org-show-siblings)))
13627 (org-show-context nil))
13628 (when (equal siblings '(16))
13629 (save-excursion
13630 (when (org-up-heading-safe)
13631 (org-show-subtree)
13632 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13634 (defun org-highlight-new-match (beg end)
13635 "Highlight from BEG to END and mark the highlight is an occur headline."
13636 (let ((ov (make-overlay beg end)))
13637 (overlay-put ov 'face 'secondary-selection)
13638 (overlay-put ov 'org-type 'org-occur)
13639 (push ov org-occur-highlights)))
13641 (defun org-remove-occur-highlights (&optional beg end noremove)
13642 "Remove the occur highlights from the buffer.
13643 BEG and END are ignored. If NOREMOVE is nil, remove this function
13644 from the `before-change-functions' in the current buffer."
13645 (interactive)
13646 (unless org-inhibit-highlight-removal
13647 (mapc 'delete-overlay org-occur-highlights)
13648 (setq org-occur-highlights nil)
13649 (setq org-occur-parameters nil)
13650 (unless noremove
13651 (remove-hook 'before-change-functions
13652 'org-remove-occur-highlights 'local))))
13654 ;;;; Priorities
13656 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13657 "Regular expression matching the priority indicator.")
13659 (defvar org-remove-priority-next-time nil)
13661 (defun org-priority-up ()
13662 "Increase the priority of the current item."
13663 (interactive)
13664 (org-priority 'up))
13666 (defun org-priority-down ()
13667 "Decrease the priority of the current item."
13668 (interactive)
13669 (org-priority 'down))
13671 (defun org-priority (&optional action show)
13672 "Change the priority of an item.
13673 ACTION can be `set', `up', `down', or a character."
13674 (interactive "P")
13675 (if (equal action '(4))
13676 (org-show-priority)
13677 (unless org-enable-priority-commands
13678 (user-error "Priority commands are disabled"))
13679 (setq action (or action 'set))
13680 (let (current new news have remove)
13681 (save-excursion
13682 (org-back-to-heading t)
13683 (if (looking-at org-priority-regexp)
13684 (setq current (string-to-char (match-string 2))
13685 have t))
13686 (cond
13687 ((eq action 'remove)
13688 (setq remove t new ?\ ))
13689 ((or (eq action 'set)
13690 (if (featurep 'xemacs) (characterp action) (integerp action)))
13691 (if (not (eq action 'set))
13692 (setq new action)
13693 (message "Priority %c-%c, SPC to remove: "
13694 org-highest-priority org-lowest-priority)
13695 (save-match-data
13696 (setq new (read-char-exclusive))))
13697 (if (and (= (upcase org-highest-priority) org-highest-priority)
13698 (= (upcase org-lowest-priority) org-lowest-priority))
13699 (setq new (upcase new)))
13700 (cond ((equal new ?\ ) (setq remove t))
13701 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13702 (user-error "Priority must be between `%c' and `%c'"
13703 org-highest-priority org-lowest-priority))))
13704 ((eq action 'up)
13705 (setq new (if have
13706 (1- current) ; normal cycling
13707 ;; last priority was empty
13708 (if (eq last-command this-command)
13709 org-lowest-priority ; wrap around empty to lowest
13710 ;; default
13711 (if org-priority-start-cycle-with-default
13712 org-default-priority
13713 (1- org-default-priority))))))
13714 ((eq action 'down)
13715 (setq new (if have
13716 (1+ current) ; normal cycling
13717 ;; last priority was empty
13718 (if (eq last-command this-command)
13719 org-highest-priority ; wrap around empty to highest
13720 ;; default
13721 (if org-priority-start-cycle-with-default
13722 org-default-priority
13723 (1+ org-default-priority))))))
13724 (t (user-error "Invalid action")))
13725 (if (or (< (upcase new) org-highest-priority)
13726 (> (upcase new) org-lowest-priority))
13727 (if (and (memq action '(up down))
13728 (not have) (not (eq last-command this-command)))
13729 ;; `new' is from default priority
13730 (error
13731 "The default can not be set, see `org-default-priority' why")
13732 ;; normal cycling: `new' is beyond highest/lowest priority
13733 ;; and is wrapped around to the empty priority
13734 (setq remove t)))
13735 (setq news (format "%c" new))
13736 (if have
13737 (if remove
13738 (replace-match "" t t nil 1)
13739 (replace-match news t t nil 2))
13740 (if remove
13741 (user-error "No priority cookie found in line")
13742 (let ((case-fold-search nil))
13743 (looking-at org-todo-line-regexp))
13744 (if (match-end 2)
13745 (progn
13746 (goto-char (match-end 2))
13747 (insert " [#" news "]"))
13748 (goto-char (match-beginning 3))
13749 (insert "[#" news "] "))))
13750 (org-preserve-lc (org-set-tags nil 'align)))
13751 (if remove
13752 (message "Priority removed")
13753 (message "Priority of current item set to %s" news)))))
13755 (defun org-show-priority ()
13756 "Show the priority of the current item.
13757 This priority is composed of the main priority given with the [#A] cookies,
13758 and by additional input from the age of a schedules or deadline entry."
13759 (interactive)
13760 (let ((pri (if (eq major-mode 'org-agenda-mode)
13761 (org-get-at-bol 'priority)
13762 (save-excursion
13763 (save-match-data
13764 (beginning-of-line)
13765 (and (looking-at org-heading-regexp)
13766 (org-get-priority (match-string 0))))))))
13767 (message "Priority is %d" (if pri pri -1000))))
13769 (defun org-get-priority (s)
13770 "Find priority cookie and return priority."
13771 (save-match-data
13772 (if (functionp org-get-priority-function)
13773 (funcall org-get-priority-function)
13774 (if (not (string-match org-priority-regexp s))
13775 (* 1000 (- org-lowest-priority org-default-priority))
13776 (* 1000 (- org-lowest-priority
13777 (string-to-char (match-string 2 s))))))))
13779 ;;;; Tags
13781 (defvar org-agenda-archives-mode)
13782 (defvar org-map-continue-from nil
13783 "Position from where mapping should continue.
13784 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13786 (defvar org-scanner-tags nil
13787 "The current tag list while the tags scanner is running.")
13788 (defvar org-trust-scanner-tags nil
13789 "Should `org-get-tags-at' use the tags for the scanner.
13790 This is for internal dynamical scoping only.
13791 When this is non-nil, the function `org-get-tags-at' will return the value
13792 of `org-scanner-tags' instead of building the list by itself. This
13793 can lead to large speed-ups when the tags scanner is used in a file with
13794 many entries, and when the list of tags is retrieved, for example to
13795 obtain a list of properties. Building the tags list for each entry in such
13796 a file becomes an N^2 operation - but with this variable set, it scales
13797 as N.")
13799 (defun org-scan-tags (action matcher todo-only &optional start-level)
13800 "Sca headline tags with inheritance and produce output ACTION.
13802 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13803 or `agenda' to produce an entry list for an agenda view. It can also be
13804 a Lisp form or a function that should be called at each matched headline, in
13805 this case the return value is a list of all return values from these calls.
13807 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13808 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13809 only lines with a not-done TODO keyword are included in the output.
13810 This should be the same variable that was scoped into
13811 and set by `org-make-tags-matcher' when it constructed MATCHER.
13813 START-LEVEL can be a string with asterisks, reducing the scope to
13814 headlines matching this string."
13815 (require 'org-agenda)
13816 (let* ((re (concat "^"
13817 (if start-level
13818 ;; Get the correct level to match
13819 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13820 org-outline-regexp)
13821 " *\\(\\<\\("
13822 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13823 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13824 (props (list 'face 'default
13825 'done-face 'org-agenda-done
13826 'undone-face 'default
13827 'mouse-face 'highlight
13828 'org-not-done-regexp org-not-done-regexp
13829 'org-todo-regexp org-todo-regexp
13830 'org-complex-heading-regexp org-complex-heading-regexp
13831 'help-echo
13832 (format "mouse-2 or RET jump to org file %s"
13833 (abbreviate-file-name
13834 (or (buffer-file-name (buffer-base-buffer))
13835 (buffer-name (buffer-base-buffer)))))))
13836 (org-map-continue-from nil)
13837 lspos tags tags-list
13838 (tags-alist (list (cons 0 org-file-tags)))
13839 (llast 0) rtn rtn1 level category i txt
13840 todo marker entry priority)
13841 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13842 (setq action (list 'lambda nil action)))
13843 (save-excursion
13844 (goto-char (point-min))
13845 (when (eq action 'sparse-tree)
13846 (org-overview)
13847 (org-remove-occur-highlights))
13848 (while (let (case-fold-search)
13849 (re-search-forward re nil t))
13850 (setq org-map-continue-from nil)
13851 (catch :skip
13852 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13853 tags (if (match-end 4) (org-match-string-no-properties 4)))
13854 (goto-char (setq lspos (match-beginning 0)))
13855 (setq level (org-reduced-level (org-outline-level))
13856 category (org-get-category))
13857 (setq i llast llast level)
13858 ;; remove tag lists from same and sublevels
13859 (while (>= i level)
13860 (when (setq entry (assoc i tags-alist))
13861 (setq tags-alist (delete entry tags-alist)))
13862 (setq i (1- i)))
13863 ;; add the next tags
13864 (when tags
13865 (setq tags (org-split-string tags ":")
13866 tags-alist
13867 (cons (cons level tags) tags-alist)))
13868 ;; compile tags for current headline
13869 (setq tags-list
13870 (if org-use-tag-inheritance
13871 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13872 tags)
13873 org-scanner-tags tags-list)
13874 (when org-use-tag-inheritance
13875 (setcdr (car tags-alist)
13876 (mapcar (lambda (x)
13877 (setq x (copy-sequence x))
13878 (org-add-prop-inherited x))
13879 (cdar tags-alist))))
13880 (when (and tags org-use-tag-inheritance
13881 (or (not (eq t org-use-tag-inheritance))
13882 org-tags-exclude-from-inheritance))
13883 ;; selective inheritance, remove uninherited ones
13884 (setcdr (car tags-alist)
13885 (org-remove-uninherited-tags (cdar tags-alist))))
13886 (when (and
13888 ;; eval matcher only when the todo condition is OK
13889 (and (or (not todo-only) (member todo org-not-done-keywords))
13890 (let ((case-fold-search t) (org-trust-scanner-tags t))
13891 (eval matcher)))
13893 ;; Call the skipper, but return t if it does not skip,
13894 ;; so that the `and' form continues evaluating
13895 (progn
13896 (unless (eq action 'sparse-tree) (org-agenda-skip))
13899 ;; Check if timestamps are deselecting this entry
13900 (or (not todo-only)
13901 (and (member todo org-not-done-keywords)
13902 (or (not org-agenda-tags-todo-honor-ignore-options)
13903 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13905 ;; select this headline
13906 (cond
13907 ((eq action 'sparse-tree)
13908 (and org-highlight-sparse-tree-matches
13909 (org-get-heading) (match-end 0)
13910 (org-highlight-new-match
13911 (match-beginning 1) (match-end 1)))
13912 (org-show-context 'tags-tree))
13913 ((eq action 'agenda)
13914 (setq txt (org-agenda-format-item
13916 (concat
13917 (if (eq org-tags-match-list-sublevels 'indented)
13918 (make-string (1- level) ?.) "")
13919 (org-get-heading))
13920 level category
13921 tags-list)
13922 priority (org-get-priority txt))
13923 (goto-char lspos)
13924 (setq marker (org-agenda-new-marker))
13925 (org-add-props txt props
13926 'org-marker marker 'org-hd-marker marker 'org-category category
13927 'todo-state todo
13928 'priority priority 'type "tagsmatch")
13929 (push txt rtn))
13930 ((functionp action)
13931 (setq org-map-continue-from nil)
13932 (save-excursion
13933 (setq rtn1 (funcall action))
13934 (push rtn1 rtn)))
13935 (t (user-error "Invalid action")))
13937 ;; if we are to skip sublevels, jump to end of subtree
13938 (unless org-tags-match-list-sublevels
13939 (org-end-of-subtree t)
13940 (backward-char 1))))
13941 ;; Get the correct position from where to continue
13942 (if org-map-continue-from
13943 (goto-char org-map-continue-from)
13944 (and (= (point) lspos) (end-of-line 1)))))
13945 (when (and (eq action 'sparse-tree)
13946 (not org-sparse-tree-open-archived-trees))
13947 (org-hide-archived-subtrees (point-min) (point-max)))
13948 (nreverse rtn)))
13950 (defun org-remove-uninherited-tags (tags)
13951 "Remove all tags that are not inherited from the list TAGS."
13952 (cond
13953 ((eq org-use-tag-inheritance t)
13954 (if org-tags-exclude-from-inheritance
13955 (org-delete-all org-tags-exclude-from-inheritance tags)
13956 tags))
13957 ((not org-use-tag-inheritance) nil)
13958 ((stringp org-use-tag-inheritance)
13959 (delq nil (mapcar
13960 (lambda (x)
13961 (if (and (string-match org-use-tag-inheritance x)
13962 (not (member x org-tags-exclude-from-inheritance)))
13963 x nil))
13964 tags)))
13965 ((listp org-use-tag-inheritance)
13966 (delq nil (mapcar
13967 (lambda (x)
13968 (if (member x org-use-tag-inheritance) x nil))
13969 tags)))))
13971 (defun org-match-sparse-tree (&optional todo-only match)
13972 "Create a sparse tree according to tags string MATCH.
13973 MATCH can contain positive and negative selection of tags, like
13974 \"+WORK+URGENT-WITHBOSS\".
13975 If optional argument TODO-ONLY is non-nil, only select lines that are
13976 also TODO lines."
13977 (interactive "P")
13978 (org-agenda-prepare-buffers (list (current-buffer)))
13979 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13981 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13983 (defvar org-cached-props nil)
13984 (defun org-cached-entry-get (pom property)
13985 (if (or (eq t org-use-property-inheritance)
13986 (and (stringp org-use-property-inheritance)
13987 (string-match org-use-property-inheritance property))
13988 (and (listp org-use-property-inheritance)
13989 (member property org-use-property-inheritance)))
13990 ;; Caching is not possible, check it directly
13991 (org-entry-get pom property 'inherit)
13992 ;; Get all properties, so that we can do complicated checks easily
13993 (cdr (assoc property (or org-cached-props
13994 (setq org-cached-props
13995 (org-entry-properties pom)))))))
13997 (defun org-global-tags-completion-table (&optional files)
13998 "Return the list of all tags in all agenda buffer/files.
13999 Optional FILES argument is a list of files which can be used
14000 instead of the agenda files."
14001 (save-excursion
14002 (org-uniquify
14003 (delq nil
14004 (apply 'append
14005 (mapcar
14006 (lambda (file)
14007 (set-buffer (find-file-noselect file))
14008 (append (org-get-buffer-tags)
14009 (mapcar (lambda (x) (if (stringp (car-safe x))
14010 (list (car-safe x)) nil))
14011 org-tag-alist)))
14012 (if (and files (car files))
14013 files
14014 (org-agenda-files))))))))
14016 (defun org-make-tags-matcher (match)
14017 "Create the TAGS/TODO matcher form for the selection string MATCH.
14019 The variable `todo-only' is scoped dynamically into this function.
14020 It will be set to t if the matcher restricts matching to TODO entries,
14021 otherwise will not be touched.
14023 Returns a cons of the selection string MATCH and the constructed
14024 lisp form implementing the matcher. The matcher is to be evaluated
14025 at an Org entry, with point on the headline, and returns t if the
14026 entry matches the selection string MATCH. The returned lisp form
14027 references two variables with information about the entry, which
14028 must be bound around the form's evaluation: todo, the TODO keyword
14029 at the entry (or nil of none); and tags-list, the list of all tags
14030 at the entry including inherited ones. Additionally, the category
14031 of the entry (if any) must be specified as the text property
14032 'org-category on the headline.
14034 See also `org-scan-tags'.
14036 (declare (special todo-only))
14037 (unless (boundp 'todo-only)
14038 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14039 (unless match
14040 ;; Get a new match request, with completion against the global
14041 ;; tags table and the local tags in current buffer
14042 (let ((org-last-tags-completion-table
14043 (org-uniquify
14044 (delq nil (append (org-get-buffer-tags)
14045 (org-global-tags-completion-table))))))
14046 (setq match (org-completing-read-no-i
14047 "Match: " 'org-tags-completion-function nil nil nil
14048 'org-tags-history))))
14050 ;; Parse the string and create a lisp form
14051 (let ((match0 match)
14052 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14053 minus tag mm
14054 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14055 orterms term orlist re-p str-p level-p level-op time-p
14056 prop-p pn pv po gv rest (start 0) (ss 0))
14057 ;; Expand group tags
14058 (setq match (org-tags-expand match))
14060 ;; Check if there is a TODO part of this match, which would be the
14061 ;; part after a "/". TO make sure that this slash is not part of
14062 ;; a property value to be matched against, we also check that there
14063 ;; is no " after that slash.
14064 ;; First, find the last slash
14065 (while (string-match "/+" match ss)
14066 (setq start (match-beginning 0) ss (match-end 0)))
14067 (if (and (string-match "/+" match start)
14068 (not (save-match-data (string-match "\"" match start))))
14069 ;; match contains also a todo-matching request
14070 (progn
14071 (setq tagsmatch (substring match 0 (match-beginning 0))
14072 todomatch (substring match (match-end 0)))
14073 (if (string-match "^!" todomatch)
14074 (setq todo-only t todomatch (substring todomatch 1)))
14075 (if (string-match "^\\s-*$" todomatch)
14076 (setq todomatch nil)))
14077 ;; only matching tags
14078 (setq tagsmatch match todomatch nil))
14080 ;; Make the tags matcher
14081 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14082 (setq tagsmatcher t)
14083 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14084 (while (setq term (pop orterms))
14085 (while (and (equal (substring term -1) "\\") orterms)
14086 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14087 (while (string-match re term)
14088 (setq rest (substring term (match-end 0))
14089 minus (and (match-end 1)
14090 (equal (match-string 1 term) "-"))
14091 tag (save-match-data (replace-regexp-in-string
14092 "\\\\-" "-"
14093 (match-string 2 term)))
14094 re-p (equal (string-to-char tag) ?{)
14095 level-p (match-end 4)
14096 prop-p (match-end 5)
14097 mm (cond
14098 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14099 (level-p
14100 (setq level-op (org-op-to-function (match-string 3 term)))
14101 `(,level-op level ,(string-to-number
14102 (match-string 4 term))))
14103 (prop-p
14104 (setq pn (match-string 5 term)
14105 po (match-string 6 term)
14106 pv (match-string 7 term)
14107 re-p (equal (string-to-char pv) ?{)
14108 str-p (equal (string-to-char pv) ?\")
14109 time-p (save-match-data
14110 (string-match "^\"[[<].*[]>]\"$" pv))
14111 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14112 (if time-p (setq pv (org-matcher-time pv)))
14113 (setq po (org-op-to-function po (if time-p 'time str-p)))
14114 (cond
14115 ((equal pn "CATEGORY")
14116 (setq gv '(get-text-property (point) 'org-category)))
14117 ((equal pn "TODO")
14118 (setq gv 'todo))
14120 (setq gv `(org-cached-entry-get nil ,pn))))
14121 (if re-p
14122 (if (eq po 'org<>)
14123 `(not (string-match ,pv (or ,gv "")))
14124 `(string-match ,pv (or ,gv "")))
14125 (if str-p
14126 `(,po (or ,gv "") ,pv)
14127 `(,po (string-to-number (or ,gv ""))
14128 ,(string-to-number pv) ))))
14129 (t `(member ,tag tags-list)))
14130 mm (if minus (list 'not mm) mm)
14131 term rest)
14132 (push mm tagsmatcher))
14133 (push (if (> (length tagsmatcher) 1)
14134 (cons 'and tagsmatcher)
14135 (car tagsmatcher))
14136 orlist)
14137 (setq tagsmatcher nil))
14138 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14139 (setq tagsmatcher
14140 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14141 ;; Make the todo matcher
14142 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14143 (setq todomatcher t)
14144 (setq orterms (org-split-string todomatch "|") orlist nil)
14145 (while (setq term (pop orterms))
14146 (while (string-match re term)
14147 (setq minus (and (match-end 1)
14148 (equal (match-string 1 term) "-"))
14149 kwd (match-string 2 term)
14150 re-p (equal (string-to-char kwd) ?{)
14151 term (substring term (match-end 0))
14152 mm (if re-p
14153 `(string-match ,(substring kwd 1 -1) todo)
14154 (list 'equal 'todo kwd))
14155 mm (if minus (list 'not mm) mm))
14156 (push mm todomatcher))
14157 (push (if (> (length todomatcher) 1)
14158 (cons 'and todomatcher)
14159 (car todomatcher))
14160 orlist)
14161 (setq todomatcher nil))
14162 (setq todomatcher (if (> (length orlist) 1)
14163 (cons 'or orlist) (car orlist))))
14165 ;; Return the string and lisp forms of the matcher
14166 (setq matcher (if todomatcher
14167 (list 'and tagsmatcher todomatcher)
14168 tagsmatcher))
14169 (when todo-only
14170 (setq matcher (list 'and '(member todo org-not-done-keywords)
14171 matcher)))
14172 (cons match0 matcher)))
14174 (defun org-tags-expand (match &optional single-as-list downcased)
14175 "Expand group tags in MATCH.
14177 This replaces every group tag in MATCH with a regexp tag search.
14178 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14179 will be replaced like this:
14181 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14182 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14183 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14185 Replacing by a regexp preserves the structure of the match.
14186 E.g., this expansion
14188 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14190 will match anything tagged with \"Lab\" and \"Home\", or tagged
14191 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14193 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14194 assumed to be a single group tag, and the function will return
14195 the list of tags in this group.
14197 When DOWNCASE is non-nil, expand downcased TAGS."
14198 (if org-group-tags
14199 (let* ((case-fold-search t)
14200 (stable org-mode-syntax-table)
14201 (tal (or org-tag-groups-alist-for-agenda
14202 org-tag-groups-alist))
14203 (tal (if downcased
14204 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14205 (tml (mapcar 'car tal))
14206 (rtnmatch match) rpl)
14207 ;; @ and _ are allowed as word-components in tags
14208 (modify-syntax-entry ?@ "w" stable)
14209 (modify-syntax-entry ?_ "w" stable)
14210 (while (and tml
14211 (with-syntax-table stable
14212 (string-match
14213 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14214 (regexp-opt tml) "\\>\\)") rtnmatch)))
14215 (let* ((dir (match-string 1 rtnmatch))
14216 (tag (match-string 2 rtnmatch))
14217 (tag (if downcased (downcase tag) tag)))
14218 (setq tml (delete tag tml))
14219 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14220 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14221 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14222 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14223 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14224 (if single-as-list
14225 (or (reverse rpl) (list rtnmatch))
14226 rtnmatch))
14227 (if single-as-list (list (if downcased (downcase match) match))
14228 match)))
14230 (defun org-op-to-function (op &optional stringp)
14231 "Turn an operator into the appropriate function."
14232 (setq op
14233 (cond
14234 ((equal op "<" ) '(< string< org-time<))
14235 ((equal op ">" ) '(> org-string> org-time>))
14236 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14237 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14238 ((member op '("=" "==")) '(= string= org-time=))
14239 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14240 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14242 (defun org<> (a b) (not (= a b)))
14243 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14244 (defun org-string>= (a b) (not (string< a b)))
14245 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14246 (defun org-string<> (a b) (not (string= a b)))
14247 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14248 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14249 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14250 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14251 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14252 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14253 (defun org-2ft (s)
14254 "Convert S to a floating point time.
14255 If S is already a number, just return it. If it is a string, parse
14256 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14257 (cond
14258 ((numberp s) s)
14259 ((stringp s)
14260 (condition-case nil
14261 (float-time (apply 'encode-time (org-parse-time-string s)))
14262 (error 0.)))
14263 (t 0.)))
14265 (defun org-time-today ()
14266 "Time in seconds today at 0:00.
14267 Returns the float number of seconds since the beginning of the
14268 epoch to the beginning of today (00:00)."
14269 (float-time (apply 'encode-time
14270 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14272 (defun org-matcher-time (s)
14273 "Interpret a time comparison value."
14274 (save-match-data
14275 (cond
14276 ((string= s "<now>") (float-time))
14277 ((string= s "<today>") (org-time-today))
14278 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14279 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14280 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14281 (+ (org-time-today)
14282 (* (string-to-number (match-string 1 s))
14283 (cdr (assoc (match-string 2 s)
14284 '(("d" . 86400.0) ("w" . 604800.0)
14285 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14286 (t (org-2ft s)))))
14288 (defun org-match-any-p (re list)
14289 "Does re match any element of list?"
14290 (setq list (mapcar (lambda (x) (string-match re x)) list))
14291 (delq nil list))
14293 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14294 (defvar org-tags-overlay (make-overlay 1 1))
14295 (org-detach-overlay org-tags-overlay)
14297 (defun org-get-local-tags-at (&optional pos)
14298 "Get a list of tags defined in the current headline."
14299 (org-get-tags-at pos 'local))
14301 (defun org-get-local-tags ()
14302 "Get a list of tags defined in the current headline."
14303 (org-get-tags-at nil 'local))
14305 (defun org-get-tags-at (&optional pos local)
14306 "Get a list of all headline tags applicable at POS.
14307 POS defaults to point. If tags are inherited, the list contains
14308 the targets in the same sequence as the headlines appear, i.e.
14309 the tags of the current headline come last.
14310 When LOCAL is non-nil, only return tags from the current headline,
14311 ignore inherited ones."
14312 (interactive)
14313 (if (and org-trust-scanner-tags
14314 (or (not pos) (equal pos (point)))
14315 (not local))
14316 org-scanner-tags
14317 (let (tags ltags lastpos parent)
14318 (save-excursion
14319 (save-restriction
14320 (widen)
14321 (goto-char (or pos (point)))
14322 (save-match-data
14323 (catch 'done
14324 (condition-case nil
14325 (progn
14326 (org-back-to-heading t)
14327 (while (not (equal lastpos (point)))
14328 (setq lastpos (point))
14329 (when (looking-at
14330 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14331 (setq ltags (org-split-string
14332 (org-match-string-no-properties 1) ":"))
14333 (when parent
14334 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14335 (setq tags (append
14336 (if parent
14337 (org-remove-uninherited-tags ltags)
14338 ltags)
14339 tags)))
14340 (or org-use-tag-inheritance (throw 'done t))
14341 (if local (throw 'done t))
14342 (or (org-up-heading-safe) (error nil))
14343 (setq parent t)))
14344 (error nil)))))
14345 (if local
14346 tags
14347 (reverse (delete-dups
14348 (reverse (append
14349 (org-remove-uninherited-tags
14350 org-file-tags) tags)))))))))
14352 (defun org-add-prop-inherited (s)
14353 (add-text-properties 0 (length s) '(inherited t) s)
14356 (defun org-toggle-tag (tag &optional onoff)
14357 "Toggle the tag TAG for the current line.
14358 If ONOFF is `on' or `off', don't toggle but set to this state."
14359 (let (res current)
14360 (save-excursion
14361 (org-back-to-heading t)
14362 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14363 (point-at-eol) t)
14364 (progn
14365 (setq current (match-string 1))
14366 (replace-match ""))
14367 (setq current ""))
14368 (setq current (nreverse (org-split-string current ":")))
14369 (cond
14370 ((eq onoff 'on)
14371 (setq res t)
14372 (or (member tag current) (push tag current)))
14373 ((eq onoff 'off)
14374 (or (not (member tag current)) (setq current (delete tag current))))
14375 (t (if (member tag current)
14376 (setq current (delete tag current))
14377 (setq res t)
14378 (push tag current))))
14379 (end-of-line 1)
14380 (if current
14381 (progn
14382 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14383 (org-set-tags nil t))
14384 (delete-horizontal-space))
14385 (run-hooks 'org-after-tags-change-hook))
14386 res))
14388 (defun org-align-tags-here (to-col)
14389 ;; Assumes that this is a headline
14390 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14391 (beginning-of-line 1)
14392 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14393 (< pos (match-beginning 2)))
14394 (progn
14395 (setq tags-l (- (match-end 2) (match-beginning 2)))
14396 (goto-char (match-beginning 1))
14397 (insert " ")
14398 (delete-region (point) (1+ (match-beginning 2)))
14399 (setq ncol (max (current-column)
14400 (1+ col)
14401 (if (> to-col 0)
14402 to-col
14403 (- (abs to-col) tags-l))))
14404 (setq p (point))
14405 (insert (make-string (- ncol (current-column)) ?\ ))
14406 (setq ncol (current-column))
14407 (when indent-tabs-mode (tabify p (point-at-eol)))
14408 (org-move-to-column (min ncol col) t))
14409 (goto-char pos))))
14411 (defun org-set-tags-command (&optional arg just-align)
14412 "Call the set-tags command for the current entry."
14413 (interactive "P")
14414 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14415 (org-set-tags arg just-align)
14416 (save-excursion
14417 (unless (and (org-region-active-p)
14418 org-loop-over-headlines-in-active-region)
14419 (org-back-to-heading t))
14420 (org-set-tags arg just-align))))
14422 (defun org-set-tags-to (data)
14423 "Set the tags of the current entry to DATA, replacing the current tags.
14424 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14425 If DATA is nil or the empty string, any tags will be removed."
14426 (interactive "sTags: ")
14427 (setq data
14428 (cond
14429 ((eq data nil) "")
14430 ((equal data "") "")
14431 ((stringp data)
14432 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14433 ":"))
14434 ((listp data)
14435 (concat ":" (mapconcat 'identity data ":") ":"))))
14436 (when data
14437 (save-excursion
14438 (org-back-to-heading t)
14439 (when (looking-at org-complex-heading-regexp)
14440 (if (match-end 5)
14441 (progn
14442 (goto-char (match-beginning 5))
14443 (insert data)
14444 (delete-region (point) (point-at-eol))
14445 (org-set-tags nil 'align))
14446 (goto-char (point-at-eol))
14447 (insert " " data)
14448 (org-set-tags nil 'align)))
14449 (beginning-of-line 1)
14450 (if (looking-at ".*?\\([ \t]+\\)$")
14451 (delete-region (match-beginning 1) (match-end 1))))))
14453 (defun org-align-all-tags ()
14454 "Align the tags i all headings."
14455 (interactive)
14456 (save-excursion
14457 (or (ignore-errors (org-back-to-heading t))
14458 (outline-next-heading))
14459 (if (org-at-heading-p)
14460 (org-set-tags t)
14461 (message "No headings"))))
14463 (defvar org-indent-indentation-per-level)
14464 (defun org-set-tags (&optional arg just-align)
14465 "Set the tags for the current headline.
14466 With prefix ARG, realign all tags in headings in the current buffer."
14467 (interactive "P")
14468 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14469 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14470 'region-start-level 'region))
14471 org-loop-over-headlines-in-active-region)
14472 (org-map-entries
14473 ;; We don't use ARG and JUST-ALIGN here these args are not
14474 ;; useful when looping over headlines
14475 `(org-set-tags)
14476 org-loop-over-headlines-in-active-region
14477 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14478 (let* ((re org-outline-regexp-bol)
14479 (current (unless arg (org-get-tags-string)))
14480 (col (current-column))
14481 (org-setting-tags t)
14482 table current-tags inherited-tags ; computed below when needed
14483 tags p0 c0 c1 rpl di tc level)
14484 (if arg
14485 (save-excursion
14486 (goto-char (point-min))
14487 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14488 (while (re-search-forward re nil t)
14489 (org-set-tags nil t)
14490 (end-of-line 1)))
14491 (message "All tags realigned to column %d" org-tags-column))
14492 (if just-align
14493 (setq tags current)
14494 ;; Get a new set of tags from the user
14495 (save-excursion
14496 (setq table (append org-tag-persistent-alist
14497 (or org-tag-alist (org-get-buffer-tags))
14498 (and
14499 org-complete-tags-always-offer-all-agenda-tags
14500 (org-global-tags-completion-table
14501 (org-agenda-files))))
14502 org-last-tags-completion-table table
14503 current-tags (org-split-string current ":")
14504 inherited-tags (nreverse
14505 (nthcdr (length current-tags)
14506 (nreverse (org-get-tags-at))))
14507 tags
14508 (if (or (eq t org-use-fast-tag-selection)
14509 (and org-use-fast-tag-selection
14510 (delq nil (mapcar 'cdr table))))
14511 (org-fast-tag-selection
14512 current-tags inherited-tags table
14513 (if org-fast-tag-selection-include-todo
14514 org-todo-key-alist))
14515 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14516 (org-trim
14517 (org-icompleting-read "Tags: "
14518 'org-tags-completion-function
14519 nil nil current 'org-tags-history))))))
14520 (while (string-match "[-+&]+" tags)
14521 ;; No boolean logic, just a list
14522 (setq tags (replace-match ":" t t tags))))
14524 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14526 (if org-tags-sort-function
14527 (setq tags (mapconcat 'identity
14528 (sort (org-split-string
14529 tags (org-re "[^[:alnum:]_@#%]+"))
14530 org-tags-sort-function) ":")))
14532 (if (string-match "\\`[\t ]*\\'" tags)
14533 (setq tags "")
14534 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14535 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14537 ;; Insert new tags at the correct column
14538 (beginning-of-line 1)
14539 (setq level (or (and (looking-at org-outline-regexp)
14540 (- (match-end 0) (point) 1))
14542 (cond
14543 ((and (equal current "") (equal tags "")))
14544 ((re-search-forward
14545 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14546 (point-at-eol) t)
14547 (if (equal tags "")
14548 (setq rpl "")
14549 (goto-char (match-beginning 0))
14550 (setq c0 (current-column)
14551 ;; compute offset for the case of org-indent-mode active
14552 di (if org-indent-mode
14553 (* (1- org-indent-indentation-per-level) (1- level))
14555 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14556 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14557 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14558 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14559 (replace-match rpl t t)
14560 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14561 tags)
14562 (t (error "Tags alignment failed")))
14563 (org-move-to-column col)
14564 (unless just-align
14565 (run-hooks 'org-after-tags-change-hook))))))
14567 (defun org-change-tag-in-region (beg end tag off)
14568 "Add or remove TAG for each entry in the region.
14569 This works in the agenda, and also in an org-mode buffer."
14570 (interactive
14571 (list (region-beginning) (region-end)
14572 (let ((org-last-tags-completion-table
14573 (if (derived-mode-p 'org-mode)
14574 (org-uniquify
14575 (delq nil (append (org-get-buffer-tags)
14576 (org-global-tags-completion-table))))
14577 (org-global-tags-completion-table))))
14578 (org-icompleting-read
14579 "Tag: " 'org-tags-completion-function nil nil nil
14580 'org-tags-history))
14581 (progn
14582 (message "[s]et or [r]emove? ")
14583 (equal (read-char-exclusive) ?r))))
14584 (if (fboundp 'deactivate-mark) (deactivate-mark))
14585 (let ((agendap (equal major-mode 'org-agenda-mode))
14586 l1 l2 m buf pos newhead (cnt 0))
14587 (goto-char end)
14588 (setq l2 (1- (org-current-line)))
14589 (goto-char beg)
14590 (setq l1 (org-current-line))
14591 (loop for l from l1 to l2 do
14592 (org-goto-line l)
14593 (setq m (get-text-property (point) 'org-hd-marker))
14594 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14595 (and agendap m))
14596 (setq buf (if agendap (marker-buffer m) (current-buffer))
14597 pos (if agendap m (point)))
14598 (with-current-buffer buf
14599 (save-excursion
14600 (save-restriction
14601 (goto-char pos)
14602 (setq cnt (1+ cnt))
14603 (org-toggle-tag tag (if off 'off 'on))
14604 (setq newhead (org-get-heading)))))
14605 (and agendap (org-agenda-change-all-lines newhead m))))
14606 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14608 (defun org-tags-completion-function (string predicate &optional flag)
14609 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14610 (confirm (lambda (x) (stringp (car x)))))
14611 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14612 (setq s1 (match-string 1 string)
14613 s2 (match-string 2 string))
14614 (setq s1 "" s2 string))
14615 (cond
14616 ((eq flag nil)
14617 ;; try completion
14618 (setq rtn (try-completion s2 ctable confirm))
14619 (if (stringp rtn)
14620 (setq rtn
14621 (concat s1 s2 (substring rtn (length s2))
14622 (if (and org-add-colon-after-tag-completion
14623 (assoc rtn ctable))
14624 ":" ""))))
14625 rtn)
14626 ((eq flag t)
14627 ;; all-completions
14628 (all-completions s2 ctable confirm))
14629 ((eq flag 'lambda)
14630 ;; exact match?
14631 (assoc s2 ctable)))))
14633 (defun org-fast-tag-insert (kwd tags face &optional end)
14634 "Insert KDW, and the TAGS, the latter with face FACE.
14635 Also insert END."
14636 (insert (format "%-12s" (concat kwd ":"))
14637 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14638 (or end "")))
14640 (defun org-fast-tag-show-exit (flag)
14641 (save-excursion
14642 (org-goto-line 3)
14643 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14644 (replace-match ""))
14645 (when flag
14646 (end-of-line 1)
14647 (org-move-to-column (- (window-width) 19) t)
14648 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14650 (defun org-set-current-tags-overlay (current prefix)
14651 "Add an overlay to CURRENT tag with PREFIX."
14652 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14653 (if (featurep 'xemacs)
14654 (org-overlay-display org-tags-overlay (concat prefix s)
14655 'secondary-selection)
14656 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14657 (org-overlay-display org-tags-overlay (concat prefix s)))))
14659 (defvar org-last-tag-selection-key nil)
14660 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14661 "Fast tag selection with single keys.
14662 CURRENT is the current list of tags in the headline, INHERITED is the
14663 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14664 possibly with grouping information. TODO-TABLE is a similar table with
14665 TODO keywords, should these have keys assigned to them.
14666 If the keys are nil, a-z are automatically assigned.
14667 Returns the new tags string, or nil to not change the current settings."
14668 (let* ((fulltable (append table todo-table))
14669 (maxlen (apply 'max (mapcar
14670 (lambda (x)
14671 (if (stringp (car x)) (string-width (car x)) 0))
14672 fulltable)))
14673 (buf (current-buffer))
14674 (expert (eq org-fast-tag-selection-single-key 'expert))
14675 (buffer-tags nil)
14676 (fwidth (+ maxlen 3 1 3))
14677 (ncol (/ (- (window-width) 4) fwidth))
14678 (i-face 'org-done)
14679 (c-face 'org-todo)
14680 tg cnt e c char c1 c2 ntable tbl rtn
14681 ov-start ov-end ov-prefix
14682 (exit-after-next org-fast-tag-selection-single-key)
14683 (done-keywords org-done-keywords)
14684 groups ingroup)
14685 (save-excursion
14686 (beginning-of-line 1)
14687 (if (looking-at
14688 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14689 (setq ov-start (match-beginning 1)
14690 ov-end (match-end 1)
14691 ov-prefix "")
14692 (setq ov-start (1- (point-at-eol))
14693 ov-end (1+ ov-start))
14694 (skip-chars-forward "^\n\r")
14695 (setq ov-prefix
14696 (concat
14697 (buffer-substring (1- (point)) (point))
14698 (if (> (current-column) org-tags-column)
14700 (make-string (- org-tags-column (current-column)) ?\ ))))))
14701 (move-overlay org-tags-overlay ov-start ov-end)
14702 (save-window-excursion
14703 (if expert
14704 (set-buffer (get-buffer-create " *Org tags*"))
14705 (delete-other-windows)
14706 (split-window-vertically)
14707 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14708 (erase-buffer)
14709 (org-set-local 'org-done-keywords done-keywords)
14710 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14711 (org-fast-tag-insert "Current" current c-face "\n\n")
14712 (org-fast-tag-show-exit exit-after-next)
14713 (org-set-current-tags-overlay current ov-prefix)
14714 (setq tbl fulltable char ?a cnt 0)
14715 (while (setq e (pop tbl))
14716 (cond
14717 ((equal (car e) :startgroup)
14718 (push '() groups) (setq ingroup t)
14719 (when (not (= cnt 0))
14720 (setq cnt 0)
14721 (insert "\n"))
14722 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14723 ((equal (car e) :endgroup)
14724 (setq ingroup nil cnt 0)
14725 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14726 ((equal e '(:newline))
14727 (when (not (= cnt 0))
14728 (setq cnt 0)
14729 (insert "\n")
14730 (setq e (car tbl))
14731 (while (equal (car tbl) '(:newline))
14732 (insert "\n")
14733 (setq tbl (cdr tbl)))))
14734 ((equal e '(:grouptags)) nil)
14736 (setq tg (copy-sequence (car e)) c2 nil)
14737 (if (cdr e)
14738 (setq c (cdr e))
14739 ;; automatically assign a character.
14740 (setq c1 (string-to-char
14741 (downcase (substring
14742 tg (if (= (string-to-char tg) ?@) 1 0)))))
14743 (if (or (rassoc c1 ntable) (rassoc c1 table))
14744 (while (or (rassoc char ntable) (rassoc char table))
14745 (setq char (1+ char)))
14746 (setq c2 c1))
14747 (setq c (or c2 char)))
14748 (if ingroup (push tg (car groups)))
14749 (setq tg (org-add-props tg nil 'face
14750 (cond
14751 ((not (assoc tg table))
14752 (org-get-todo-face tg))
14753 ((member tg current) c-face)
14754 ((member tg inherited) i-face))))
14755 (if (equal (caar tbl) :grouptags)
14756 (org-add-props tg nil 'face 'org-tag-group))
14757 (if (and (= cnt 0) (not ingroup)) (insert " "))
14758 (insert "[" c "] " tg (make-string
14759 (- fwidth 4 (length tg)) ?\ ))
14760 (push (cons tg c) ntable)
14761 (when (= (setq cnt (1+ cnt)) ncol)
14762 (insert "\n")
14763 (if ingroup (insert " "))
14764 (setq cnt 0)))))
14765 (setq ntable (nreverse ntable))
14766 (insert "\n")
14767 (goto-char (point-min))
14768 (if (not expert) (org-fit-window-to-buffer))
14769 (setq rtn
14770 (catch 'exit
14771 (while t
14772 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14773 (if (not groups) "no " "")
14774 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14775 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14776 (setq org-last-tag-selection-key c)
14777 (cond
14778 ((= c ?\r) (throw 'exit t))
14779 ((= c ?!)
14780 (setq groups (not groups))
14781 (goto-char (point-min))
14782 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14783 ((= c ?\C-c)
14784 (if (not expert)
14785 (org-fast-tag-show-exit
14786 (setq exit-after-next (not exit-after-next)))
14787 (setq expert nil)
14788 (delete-other-windows)
14789 (set-window-buffer (split-window-vertically) " *Org tags*")
14790 (org-switch-to-buffer-other-window " *Org tags*")
14791 (org-fit-window-to-buffer)))
14792 ((or (= c ?\C-g)
14793 (and (= c ?q) (not (rassoc c ntable))))
14794 (org-detach-overlay org-tags-overlay)
14795 (setq quit-flag t))
14796 ((= c ?\ )
14797 (setq current nil)
14798 (if exit-after-next (setq exit-after-next 'now)))
14799 ((= c ?\t)
14800 (condition-case nil
14801 (setq tg (org-icompleting-read
14802 "Tag: "
14803 (or buffer-tags
14804 (with-current-buffer buf
14805 (org-get-buffer-tags)))))
14806 (quit (setq tg "")))
14807 (when (string-match "\\S-" tg)
14808 (add-to-list 'buffer-tags (list tg))
14809 (if (member tg current)
14810 (setq current (delete tg current))
14811 (push tg current)))
14812 (if exit-after-next (setq exit-after-next 'now)))
14813 ((setq e (rassoc c todo-table) tg (car e))
14814 (with-current-buffer buf
14815 (save-excursion (org-todo tg)))
14816 (if exit-after-next (setq exit-after-next 'now)))
14817 ((setq e (rassoc c ntable) tg (car e))
14818 (if (member tg current)
14819 (setq current (delete tg current))
14820 (loop for g in groups do
14821 (if (member tg g)
14822 (mapc (lambda (x)
14823 (setq current (delete x current)))
14824 g)))
14825 (push tg current))
14826 (if exit-after-next (setq exit-after-next 'now))))
14828 ;; Create a sorted list
14829 (setq current
14830 (sort current
14831 (lambda (a b)
14832 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14833 (if (eq exit-after-next 'now) (throw 'exit t))
14834 (goto-char (point-min))
14835 (beginning-of-line 2)
14836 (delete-region (point) (point-at-eol))
14837 (org-fast-tag-insert "Current" current c-face)
14838 (org-set-current-tags-overlay current ov-prefix)
14839 (while (re-search-forward
14840 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14841 (setq tg (match-string 1))
14842 (add-text-properties
14843 (match-beginning 1) (match-end 1)
14844 (list 'face
14845 (cond
14846 ((member tg current) c-face)
14847 ((member tg inherited) i-face)
14848 (t (get-text-property (match-beginning 1) 'face))))))
14849 (goto-char (point-min)))))
14850 (org-detach-overlay org-tags-overlay)
14851 (if rtn
14852 (mapconcat 'identity current ":")
14853 nil))))
14855 (defun org-get-tags-string ()
14856 "Get the TAGS string in the current headline."
14857 (unless (org-at-heading-p t)
14858 (user-error "Not on a heading"))
14859 (save-excursion
14860 (beginning-of-line 1)
14861 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14862 (org-match-string-no-properties 1)
14863 "")))
14865 (defun org-get-tags ()
14866 "Get the list of tags specified in the current headline."
14867 (org-split-string (org-get-tags-string) ":"))
14869 (defun org-get-buffer-tags ()
14870 "Get a table of all tags used in the buffer, for completion."
14871 (let (tags)
14872 (save-excursion
14873 (goto-char (point-min))
14874 (while (re-search-forward
14875 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14876 (when (equal (char-after (point-at-bol 0)) ?*)
14877 (mapc (lambda (x) (add-to-list 'tags x))
14878 (org-split-string (org-match-string-no-properties 1) ":")))))
14879 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14880 (mapcar 'list tags)))
14882 ;;;; The mapping API
14884 (defun org-map-entries (func &optional match scope &rest skip)
14885 "Call FUNC at each headline selected by MATCH in SCOPE.
14887 FUNC is a function or a lisp form. The function will be called without
14888 arguments, with the cursor positioned at the beginning of the headline.
14889 The return values of all calls to the function will be collected and
14890 returned as a list.
14892 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14893 does not need to preserve point. After evaluation, the cursor will be
14894 moved to the end of the line (presumably of the headline of the
14895 processed entry) and search continues from there. Under some
14896 circumstances, this may not produce the wanted results. For example,
14897 if you have removed (e.g. archived) the current (sub)tree it could
14898 mean that the next entry will be skipped entirely. In such cases, you
14899 can specify the position from where search should continue by making
14900 FUNC set the variable `org-map-continue-from' to the desired buffer
14901 position.
14903 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14904 Only headlines that are matched by this query will be considered during
14905 the iteration. When MATCH is nil or t, all headlines will be
14906 visited by the iteration.
14908 SCOPE determines the scope of this command. It can be any of:
14910 nil The current buffer, respecting the restriction if any
14911 tree The subtree started with the entry at point
14912 region The entries within the active region, if any
14913 region-start-level
14914 The entries within the active region, but only those at
14915 the same level than the first one.
14916 file The current buffer, without restriction
14917 file-with-archives
14918 The current buffer, and any archives associated with it
14919 agenda All agenda files
14920 agenda-with-archives
14921 All agenda files with any archive files associated with them
14922 \(file1 file2 ...)
14923 If this is a list, all files in the list will be scanned
14925 The remaining args are treated as settings for the skipping facilities of
14926 the scanner. The following items can be given here:
14928 archive skip trees with the archive tag
14929 comment skip trees with the COMMENT keyword
14930 function or Emacs Lisp form:
14931 will be used as value for `org-agenda-skip-function', so
14932 whenever the function returns a position, FUNC will not be
14933 called for that entry and search will continue from the
14934 position returned
14936 If your function needs to retrieve the tags including inherited tags
14937 at the *current* entry, you can use the value of the variable
14938 `org-scanner-tags' which will be much faster than getting the value
14939 with `org-get-tags-at'. If your function gets properties with
14940 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14941 to t around the call to `org-entry-properties' to get the same speedup.
14942 Note that if your function moves around to retrieve tags and properties at
14943 a *different* entry, you cannot use these techniques."
14944 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14945 (not (org-region-active-p)))
14946 (let* ((org-agenda-archives-mode nil) ; just to make sure
14947 (org-agenda-skip-archived-trees (memq 'archive skip))
14948 (org-agenda-skip-comment-trees (memq 'comment skip))
14949 (org-agenda-skip-function
14950 (car (org-delete-all '(comment archive) skip)))
14951 (org-tags-match-list-sublevels t)
14952 (start-level (eq scope 'region-start-level))
14953 matcher file res
14954 org-todo-keywords-for-agenda
14955 org-done-keywords-for-agenda
14956 org-todo-keyword-alist-for-agenda
14957 org-drawers-for-agenda
14958 org-tag-alist-for-agenda
14959 todo-only)
14961 (cond
14962 ((eq match t) (setq matcher t))
14963 ((eq match nil) (setq matcher t))
14964 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14966 (save-window-excursion
14967 (save-restriction
14968 (cond ((eq scope 'tree)
14969 (org-back-to-heading t)
14970 (org-narrow-to-subtree)
14971 (setq scope nil))
14972 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14973 (org-region-active-p))
14974 ;; If needed, set start-level to a string like "2"
14975 (when start-level
14976 (save-excursion
14977 (goto-char (region-beginning))
14978 (unless (org-at-heading-p) (outline-next-heading))
14979 (setq start-level (org-current-level))))
14980 (narrow-to-region (region-beginning)
14981 (save-excursion
14982 (goto-char (region-end))
14983 (unless (and (bolp) (org-at-heading-p))
14984 (outline-next-heading))
14985 (point)))
14986 (setq scope nil)))
14988 (if (not scope)
14989 (progn
14990 (org-agenda-prepare-buffers
14991 (list (buffer-file-name (current-buffer))))
14992 (setq res (org-scan-tags func matcher todo-only start-level)))
14993 ;; Get the right scope
14994 (cond
14995 ((and scope (listp scope) (symbolp (car scope)))
14996 (setq scope (eval scope)))
14997 ((eq scope 'agenda)
14998 (setq scope (org-agenda-files t)))
14999 ((eq scope 'agenda-with-archives)
15000 (setq scope (org-agenda-files t))
15001 (setq scope (org-add-archive-files scope)))
15002 ((eq scope 'file)
15003 (setq scope (list (buffer-file-name))))
15004 ((eq scope 'file-with-archives)
15005 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15006 (org-agenda-prepare-buffers scope)
15007 (while (setq file (pop scope))
15008 (with-current-buffer (org-find-base-buffer-visiting file)
15009 (save-excursion
15010 (save-restriction
15011 (widen)
15012 (goto-char (point-min))
15013 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15014 res)))
15016 ;;;; Properties
15018 ;;; Setting and retrieving properties
15020 (defconst org-special-properties
15021 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15022 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15023 "The special properties valid in Org-mode.
15025 These are properties that are not defined in the property drawer,
15026 but in some other way.")
15028 (defconst org-default-properties
15029 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15030 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15031 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15032 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15033 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15034 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15035 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15036 "Some properties that are used by Org-mode for various purposes.
15037 Being in this list makes sure that they are offered for completion.")
15039 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15040 "Regular expression matching the first line of a property drawer.")
15042 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15043 "Regular expression matching the last line of a property drawer.")
15045 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15046 "Regular expression matching the first line of a property drawer.")
15048 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15049 "Regular expression matching the first line of a property drawer.")
15051 (defconst org-property-drawer-re
15052 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
15053 org-property-end-re "\\)\n?")
15054 "Matches an entire property drawer.")
15056 (defconst org-clock-drawer-re
15057 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
15058 org-property-end-re "\\)\n?")
15059 "Matches an entire clock drawer.")
15061 (defun org-property-action ()
15062 "Do an action on properties."
15063 (interactive)
15064 (let (c)
15065 (org-at-property-p)
15066 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15067 (setq c (read-char-exclusive))
15068 (cond
15069 ((equal c ?s)
15070 (call-interactively 'org-set-property))
15071 ((equal c ?d)
15072 (call-interactively 'org-delete-property))
15073 ((equal c ?D)
15074 (call-interactively 'org-delete-property-globally))
15075 ((equal c ?c)
15076 (call-interactively 'org-compute-property-at-point))
15077 (t (user-error "No such property action %c" c)))))
15079 (defun org-inc-effort ()
15080 "Increment the value of the effort property in the current entry."
15081 (interactive)
15082 (org-set-effort nil t))
15084 (defvar org-clock-effort) ;; Defined in org-clock.el
15085 (defvar org-clock-current-task) ;; Defined in org-clock.el
15086 (defun org-set-effort (&optional value increment)
15087 "Set the effort property of the current entry.
15088 With numerical prefix arg, use the nth allowed value, 0 stands for the
15089 10th allowed value.
15091 When INCREMENT is non-nil, set the property to the next allowed value."
15092 (interactive "P")
15093 (if (equal value 0) (setq value 10))
15094 (let* ((completion-ignore-case t)
15095 (prop org-effort-property)
15096 (cur (org-entry-get nil prop))
15097 (allowed (org-property-get-allowed-values nil prop 'table))
15098 (existing (mapcar 'list (org-property-values prop)))
15099 (heading (nth 4 (org-heading-components)))
15101 (val (cond
15102 ((stringp value) value)
15103 ((and allowed (integerp value))
15104 (or (car (nth (1- value) allowed))
15105 (car (org-last allowed))))
15106 ((and allowed increment)
15107 (or (caadr (member (list cur) allowed))
15108 (user-error "Allowed effort values are not set")))
15109 (allowed
15110 (message "Select 1-9,0, [RET%s]: %s"
15111 (if cur (concat "=" cur) "")
15112 (mapconcat 'car allowed " "))
15113 (setq rpl (read-char-exclusive))
15114 (if (equal rpl ?\r)
15116 (setq rpl (- rpl ?0))
15117 (if (equal rpl 0) (setq rpl 10))
15118 (if (and (> rpl 0) (<= rpl (length allowed)))
15119 (car (nth (1- rpl) allowed))
15120 (org-completing-read "Effort: " allowed nil))))
15122 (let (org-completion-use-ido org-completion-use-iswitchb)
15123 (org-completing-read
15124 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15125 (concat "[" cur "]") "")
15126 ": ")
15127 existing nil nil "" nil cur))))))
15128 (unless (equal (org-entry-get nil prop) val)
15129 (org-entry-put nil prop val))
15130 (save-excursion
15131 (org-back-to-heading t)
15132 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15133 (when (string= heading org-clock-current-task)
15134 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15135 (org-clock-update-mode-line))
15136 (message "%s is now %s" prop val)))
15138 (defun org-at-property-p ()
15139 "Is cursor inside a property drawer?"
15140 (save-excursion
15141 (when (equal 'node-property (car (org-element-at-point)))
15142 (beginning-of-line 1)
15143 (looking-at org-property-re))))
15145 (defun org-get-property-block (&optional beg end force)
15146 "Return the (beg . end) range of the body of the property drawer.
15147 BEG and END are the beginning and end of the current subtree, or of
15148 the part before the first headline. If they are not given, they will
15149 be found. If the drawer does not exist and FORCE is non-nil, create
15150 the drawer."
15151 (catch 'exit
15152 (save-excursion
15153 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15154 (progn (org-back-to-heading t) (point))))
15155 (end (or end (and (not (outline-next-heading)) (point-max))
15156 (point))))
15157 (goto-char beg)
15158 (if (re-search-forward org-property-start-re end t)
15159 (setq beg (1+ (match-end 0)))
15160 (if force
15161 (save-excursion
15162 (org-insert-property-drawer)
15163 (setq end (progn (outline-next-heading) (point))))
15164 (throw 'exit nil))
15165 (goto-char beg)
15166 (if (re-search-forward org-property-start-re end t)
15167 (setq beg (1+ (match-end 0)))))
15168 (if (re-search-forward org-property-end-re end t)
15169 (setq end (match-beginning 0))
15170 (or force (throw 'exit nil))
15171 (goto-char beg)
15172 (setq end beg)
15173 (org-indent-line)
15174 (insert ":END:\n"))
15175 (cons beg end)))))
15177 (defun org-entry-properties (&optional pom which specific)
15178 "Get all properties of the entry at point-or-marker POM.
15179 This includes the TODO keyword, the tags, time strings for deadline,
15180 scheduled, and clocking, and any additional properties defined in the
15181 entry. The return value is an alist, keys may occur multiple times
15182 if the property key was used several times.
15183 POM may also be nil, in which case the current entry is used.
15184 If WHICH is nil or `all', get all properties. If WHICH is
15185 `special' or `standard', only get that subclass. If WHICH
15186 is a string only get exactly this property. SPECIFIC can be a string, the
15187 specific property we are interested in. Specifying it can speed
15188 things up because then unnecessary parsing is avoided."
15189 (setq which (or which 'all))
15190 (org-with-point-at pom
15191 (let ((clockstr (substring org-clock-string 0 -1))
15192 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15193 (case-fold-search nil)
15194 beg end range props sum-props key key1 value string clocksum clocksumt)
15195 (save-excursion
15196 (when (condition-case nil
15197 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15198 (error nil))
15199 (setq beg (point))
15200 (setq sum-props (get-text-property (point) 'org-summaries))
15201 (setq clocksum (get-text-property (point) :org-clock-minutes)
15202 clocksumt (get-text-property (point) :org-clock-minutes-today))
15203 (outline-next-heading)
15204 (setq end (point))
15205 (when (memq which '(all special))
15206 ;; Get the special properties, like TODO and tags
15207 (goto-char beg)
15208 (when (and (or (not specific) (string= specific "TODO"))
15209 (looking-at org-todo-line-regexp) (match-end 2))
15210 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15211 (when (and (or (not specific) (string= specific "PRIORITY"))
15212 (looking-at org-priority-regexp))
15213 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15214 (when (or (not specific) (string= specific "FILE"))
15215 (push (cons "FILE" buffer-file-name) props))
15216 (when (and (or (not specific) (string= specific "TAGS"))
15217 (setq value (org-get-tags-string))
15218 (string-match "\\S-" value))
15219 (push (cons "TAGS" value) props))
15220 (when (and (or (not specific) (string= specific "ALLTAGS"))
15221 (setq value (org-get-tags-at)))
15222 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15223 ":"))
15224 props))
15225 (when (or (not specific) (string= specific "BLOCKED"))
15226 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15227 (when (or (not specific)
15228 (member specific
15229 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15230 "TIMESTAMP" "TIMESTAMP_IA")))
15231 (catch 'match
15232 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15233 (setq key (if (match-end 1)
15234 (substring (org-match-string-no-properties 1)
15235 0 -1))
15236 string (if (equal key clockstr)
15237 (org-trim
15238 (buffer-substring-no-properties
15239 (match-beginning 3) (goto-char
15240 (point-at-eol))))
15241 (substring (org-match-string-no-properties 3)
15242 1 -1)))
15243 ;; Get the correct property name from the key. This is
15244 ;; necessary if the user has configured time keywords.
15245 (setq key1 (concat key ":"))
15246 (cond
15247 ((not key)
15248 (setq key
15249 (if (= (char-after (match-beginning 3)) ?\[)
15250 "TIMESTAMP_IA" "TIMESTAMP")))
15251 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15252 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15253 ((equal key1 org-closed-string) (setq key "CLOSED"))
15254 ((equal key1 org-clock-string) (setq key "CLOCK")))
15255 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15256 (progn
15257 (push (cons key string) props)
15258 ;; no need to search further if match is found
15259 (throw 'match t))
15260 (when (or (equal key "CLOCK") (not (assoc key props)))
15261 (push (cons key string) props)))))))
15263 (when (memq which '(all standard))
15264 ;; Get the standard properties, like :PROP: ...
15265 (setq range (org-get-property-block beg end))
15266 (when range
15267 (goto-char (car range))
15268 (while (re-search-forward org-property-re
15269 (cdr range) t)
15270 (setq key (org-match-string-no-properties 2)
15271 value (org-trim (or (org-match-string-no-properties 3) "")))
15272 (unless (member key excluded)
15273 (push (cons key (or value "")) props)))))
15274 (if clocksum
15275 (push (cons "CLOCKSUM"
15276 (org-columns-number-to-string (/ (float clocksum) 60.)
15277 'add_times))
15278 props))
15279 (if clocksumt
15280 (push (cons "CLOCKSUM_T"
15281 (org-columns-number-to-string (/ (float clocksumt) 60.)
15282 'add_times))
15283 props))
15284 (unless (assoc "CATEGORY" props)
15285 (push (cons "CATEGORY" (org-get-category)) props))
15286 (append sum-props (nreverse props)))))))
15288 (defun org-entry-get (pom property &optional inherit literal-nil)
15289 "Get value of PROPERTY for entry or content at point-or-marker POM.
15290 If INHERIT is non-nil and the entry does not have the property,
15291 then also check higher levels of the hierarchy.
15292 If INHERIT is the symbol `selective', use inheritance only if the setting
15293 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15294 If the property is present but empty, the return value is the empty string.
15295 If the property is not present at all, nil is returned.
15297 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15298 do not interpret it as the list atom nil. This is used for inheritance
15299 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15300 (org-with-point-at pom
15301 (if (and inherit (if (eq inherit 'selective)
15302 (org-property-inherit-p property)
15304 (org-entry-get-with-inheritance property literal-nil)
15305 (if (member property org-special-properties)
15306 ;; We need a special property. Use `org-entry-properties' to
15307 ;; retrieve it, but specify the wanted property
15308 (cdr (assoc property (org-entry-properties nil 'special property)))
15309 (let ((range (org-get-property-block)))
15310 (when (and range (not (eq (car range) (cdr range))))
15311 (let* ((props (list (or (assoc property org-file-properties)
15312 (assoc property org-global-properties)
15313 (assoc property org-global-properties-fixed))))
15314 (ap (lambda (key)
15315 (when (re-search-forward
15316 (org-re-property key) (cdr range) t)
15317 (setq props
15318 (org-update-property-plist
15320 (if (match-end 3)
15321 (org-match-string-no-properties 3) "")
15322 props)))))
15323 val)
15324 (goto-char (car range))
15325 (funcall ap property)
15326 (goto-char (car range))
15327 (while (funcall ap (concat property "+")))
15328 (setq val (cdr (assoc property props)))
15329 (when val (if literal-nil val (org-not-nil val))))))))))
15331 (defun org-property-or-variable-value (var &optional inherit)
15332 "Check if there is a property fixing the value of VAR.
15333 If yes, return this value. If not, return the current value of the variable."
15334 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15335 (if (and prop (stringp prop) (string-match "\\S-" prop))
15336 (read prop)
15337 (symbol-value var))))
15339 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15340 "Delete the property PROPERTY from entry at point-or-marker POM.
15341 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15342 an empty drawer to delete."
15343 (org-with-point-at pom
15344 (if (member property org-special-properties)
15345 nil ; cannot delete these properties.
15346 (let ((range (org-get-property-block)))
15347 (if (and range
15348 (goto-char (car range))
15349 (re-search-forward
15350 (org-re-property property)
15351 (cdr range) t))
15352 (progn
15353 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15354 (and delete-empty-drawer
15355 (org-remove-empty-drawer-at
15356 delete-empty-drawer (car range)))
15358 nil)))))
15360 ;; Multi-values properties are properties that contain multiple values
15361 ;; These values are assumed to be single words, separated by whitespace.
15362 (defun org-entry-add-to-multivalued-property (pom property value)
15363 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15364 (let* ((old (org-entry-get pom property))
15365 (values (and old (org-split-string old "[ \t]"))))
15366 (setq value (org-entry-protect-space value))
15367 (unless (member value values)
15368 (setq values (append values (list value)))
15369 (org-entry-put pom property
15370 (mapconcat 'identity values " ")))))
15372 (defun org-entry-remove-from-multivalued-property (pom property value)
15373 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15374 (let* ((old (org-entry-get pom property))
15375 (values (and old (org-split-string old "[ \t]"))))
15376 (setq value (org-entry-protect-space value))
15377 (when (member value values)
15378 (setq values (delete value values))
15379 (org-entry-put pom property
15380 (mapconcat 'identity values " ")))))
15382 (defun org-entry-member-in-multivalued-property (pom property value)
15383 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15384 (let* ((old (org-entry-get pom property))
15385 (values (and old (org-split-string old "[ \t]"))))
15386 (setq value (org-entry-protect-space value))
15387 (member value values)))
15389 (defun org-entry-get-multivalued-property (pom property)
15390 "Return a list of values in a multivalued property."
15391 (let* ((value (org-entry-get pom property))
15392 (values (and value (org-split-string value "[ \t]"))))
15393 (mapcar 'org-entry-restore-space values)))
15395 (defun org-entry-put-multivalued-property (pom property &rest values)
15396 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15397 VALUES should be a list of strings. Spaces will be protected."
15398 (org-entry-put pom property
15399 (mapconcat 'org-entry-protect-space values " "))
15400 (let* ((value (org-entry-get pom property))
15401 (values (and value (org-split-string value "[ \t]"))))
15402 (mapcar 'org-entry-restore-space values)))
15404 (defun org-entry-protect-space (s)
15405 "Protect spaces and newline in string S."
15406 (while (string-match " " s)
15407 (setq s (replace-match "%20" t t s)))
15408 (while (string-match "\n" s)
15409 (setq s (replace-match "%0A" t t s)))
15412 (defun org-entry-restore-space (s)
15413 "Restore spaces and newline in string S."
15414 (while (string-match "%20" s)
15415 (setq s (replace-match " " t t s)))
15416 (while (string-match "%0A" s)
15417 (setq s (replace-match "\n" t t s)))
15420 (defvar org-entry-property-inherited-from (make-marker)
15421 "Marker pointing to the entry from where a property was inherited.
15422 Each call to `org-entry-get-with-inheritance' will set this marker to the
15423 location of the entry where the inheritance search matched. If there was
15424 no match, the marker will point nowhere.
15425 Note that also `org-entry-get' calls this function, if the INHERIT flag
15426 is set.")
15428 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15429 "Get PROPERTY of entry or content at point, search higher levels if needed.
15430 The search will stop at the first ancestor which has the property defined.
15431 If the value found is \"nil\", return nil to show that the property
15432 should be considered as undefined (this is the meaning of nil here).
15433 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15434 (move-marker org-entry-property-inherited-from nil)
15435 (let (tmp)
15436 (save-excursion
15437 (save-restriction
15438 (widen)
15439 (catch 'ex
15440 (while t
15441 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15442 (or (ignore-errors (org-back-to-heading t))
15443 (goto-char (point-min)))
15444 (move-marker org-entry-property-inherited-from (point))
15445 (throw 'ex tmp))
15446 (or (ignore-errors (org-up-heading-safe))
15447 (throw 'ex nil))))))
15448 (setq tmp (or tmp
15449 (cdr (assoc property org-file-properties))
15450 (cdr (assoc property org-global-properties))
15451 (cdr (assoc property org-global-properties-fixed))))
15452 (if literal-nil tmp (org-not-nil tmp))))
15454 (defvar org-property-changed-functions nil
15455 "Hook called when the value of a property has changed.
15456 Each hook function should accept two arguments, the name of the property
15457 and the new value.")
15459 (defun org-entry-put (pom property value)
15460 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15461 (org-with-point-at pom
15462 (org-back-to-heading t)
15463 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15464 range)
15465 (cond
15466 ((equal property "TODO")
15467 (when (and (stringp value) (string-match "\\S-" value)
15468 (not (member value org-todo-keywords-1)))
15469 (user-error "\"%s\" is not a valid TODO state" value))
15470 (if (or (not value)
15471 (not (string-match "\\S-" value)))
15472 (setq value 'none))
15473 (org-todo value)
15474 (org-set-tags nil 'align))
15475 ((equal property "PRIORITY")
15476 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15477 (string-to-char value) ?\ ))
15478 (org-set-tags nil 'align))
15479 ((equal property "CLOCKSUM")
15480 (if (not (re-search-forward
15481 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15482 (error "Cannot find a clock log")
15483 (goto-char (- (match-end 1) 2))
15484 (cond
15485 ((eq value 'earlier) (org-timestamp-down))
15486 ((eq value 'later) (org-timestamp-up)))
15487 (org-clock-sum-current-item)))
15488 ((equal property "SCHEDULED")
15489 (if (re-search-forward org-scheduled-time-regexp end t)
15490 (cond
15491 ((eq value 'earlier) (org-timestamp-change -1 'day))
15492 ((eq value 'later) (org-timestamp-change 1 'day))
15493 (t (call-interactively 'org-schedule)))
15494 (call-interactively 'org-schedule)))
15495 ((equal property "DEADLINE")
15496 (if (re-search-forward org-deadline-time-regexp end t)
15497 (cond
15498 ((eq value 'earlier) (org-timestamp-change -1 'day))
15499 ((eq value 'later) (org-timestamp-change 1 'day))
15500 (t (call-interactively 'org-deadline)))
15501 (call-interactively 'org-deadline)))
15502 ((member property org-special-properties)
15503 (error "The %s property can not yet be set with `org-entry-put'"
15504 property))
15505 (t ; a non-special property
15506 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15507 (setq range (org-get-property-block beg end 'force))
15508 (goto-char (car range))
15509 (if (re-search-forward
15510 (org-re-property property) (cdr range) t)
15511 (progn
15512 (delete-region (match-beginning 0) (match-end 0))
15513 (goto-char (match-beginning 0)))
15514 (goto-char (cdr range))
15515 (insert "\n")
15516 (backward-char 1)
15517 (org-indent-line))
15518 (insert ":" property ":")
15519 (and value (insert " " value))
15520 (org-indent-line)))))
15521 (run-hook-with-args 'org-property-changed-functions property value)))
15523 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15524 "Get all property keys in the current buffer.
15525 With INCLUDE-SPECIALS, also list the special properties that reflect things
15526 like tags and TODO state.
15527 With INCLUDE-DEFAULTS, also include properties that has special meaning
15528 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15529 and others.
15530 With INCLUDE-COLUMNS, also include property names given in COLUMN
15531 formats in the current buffer."
15532 (let (rtn range cfmt s p)
15533 (save-excursion
15534 (save-restriction
15535 (widen)
15536 (goto-char (point-min))
15537 (while (re-search-forward org-property-start-re nil t)
15538 (setq range (org-get-property-block))
15539 (goto-char (car range))
15540 (while (re-search-forward org-property-re
15541 (cdr range) t)
15542 (add-to-list 'rtn (org-match-string-no-properties 2)))
15543 (outline-next-heading))))
15545 (when include-specials
15546 (setq rtn (append org-special-properties rtn)))
15548 (when include-defaults
15549 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15550 (add-to-list 'rtn org-effort-property))
15552 (when include-columns
15553 (save-excursion
15554 (save-restriction
15555 (widen)
15556 (goto-char (point-min))
15557 (while (re-search-forward
15558 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15559 nil t)
15560 (setq cfmt (match-string 2) s 0)
15561 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15562 cfmt s)
15563 (setq s (match-end 0)
15564 p (match-string 1 cfmt))
15565 (unless (or (equal p "ITEM")
15566 (member p org-special-properties))
15567 (add-to-list 'rtn (match-string 1 cfmt))))))))
15569 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15571 (defun org-property-values (key)
15572 "Return a list of all values of property KEY in the current buffer."
15573 (save-excursion
15574 (save-restriction
15575 (widen)
15576 (goto-char (point-min))
15577 (let ((re (org-re-property key))
15578 values)
15579 (while (re-search-forward re nil t)
15580 (add-to-list 'values (org-trim (match-string 3))))
15581 (delete "" values)))))
15583 (defun org-insert-property-drawer ()
15584 "Insert a property drawer into the current entry."
15585 (org-back-to-heading t)
15586 (looking-at org-outline-regexp)
15587 (let ((indent (if org-adapt-indentation
15588 (- (match-end 0) (match-beginning 0))
15590 (beg (point))
15591 (re (concat "^[ \t]*" org-keyword-time-regexp))
15592 end hiddenp)
15593 (outline-next-heading)
15594 (setq end (point))
15595 (goto-char beg)
15596 (while (re-search-forward re end t))
15597 (setq hiddenp (outline-invisible-p))
15598 (end-of-line 1)
15599 (and (equal (char-after) ?\n) (forward-char 1))
15600 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15601 (if (member (match-string 1) '("CLOCK:" ":END:"))
15602 ;; just skip this line
15603 (beginning-of-line 2)
15604 ;; Drawer start, find the end
15605 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15606 (beginning-of-line 1)))
15607 (org-skip-over-state-notes)
15608 (skip-chars-backward " \t\n\r")
15609 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15610 (forward-char 1))
15611 (goto-char (point-at-eol))
15612 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15613 (beginning-of-line 0)
15614 (org-indent-to-column indent)
15615 (beginning-of-line 2)
15616 (org-indent-to-column indent)
15617 (beginning-of-line 0)
15618 (if hiddenp
15619 (save-excursion
15620 (org-back-to-heading t)
15621 (hide-entry))
15622 (org-flag-drawer t))))
15624 (defun org-insert-drawer (&optional arg drawer)
15625 "Insert a drawer at point.
15627 Optional argument DRAWER, when non-nil, is a string representing
15628 drawer's name. Otherwise, the user is prompted for a name.
15630 If a region is active, insert the drawer around that region
15631 instead.
15633 Point is left between drawer's boundaries."
15634 (interactive "P")
15635 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15636 "LOGBOOK"))
15637 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15638 ;; internally by Org. They are meant to be inserted
15639 ;; automatically.
15640 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15641 ;; Remove system drawers from list. Note: For some reason,
15642 ;; `org-completing-read' ignores the predicate while
15643 ;; `completing-read' handles it fine.
15644 (drawer (if arg "PROPERTIES"
15645 (or drawer
15646 (completing-read
15647 "Drawer: " org-drawers
15648 (lambda (d) (not (member d system-drawers))))))))
15649 (cond
15650 ;; With C-u, fall back on `org-insert-property-drawer'
15651 (arg (org-insert-property-drawer))
15652 ;; With an active region, insert a drawer at point.
15653 ((not (org-region-active-p))
15654 (progn
15655 (unless (bolp) (insert "\n"))
15656 (insert (format ":%s:\n\n:END:\n" drawer))
15657 (forward-line -2)))
15658 ;; Otherwise, insert the drawer at point
15660 (let ((rbeg (region-beginning))
15661 (rend (copy-marker (region-end))))
15662 (unwind-protect
15663 (progn
15664 (goto-char rbeg)
15665 (beginning-of-line)
15666 (when (save-excursion
15667 (re-search-forward org-outline-regexp-bol rend t))
15668 (user-error "Drawers cannot contain headlines"))
15669 ;; Position point at the beginning of the first
15670 ;; non-blank line in region. Insert drawer's opening
15671 ;; there, then indent it.
15672 (org-skip-whitespace)
15673 (beginning-of-line)
15674 (insert ":" drawer ":\n")
15675 (forward-line -1)
15676 (indent-for-tab-command)
15677 ;; Move point to the beginning of the first blank line
15678 ;; after the last non-blank line in region. Insert
15679 ;; drawer's closing, then indent it.
15680 (goto-char rend)
15681 (skip-chars-backward " \r\t\n")
15682 (insert "\n:END:")
15683 (deactivate-mark t)
15684 (indent-for-tab-command)
15685 (unless (eolp) (insert "\n")))
15686 ;; Clear marker, whatever the outcome of insertion is.
15687 (set-marker rend nil)))))))
15689 (defvar org-property-set-functions-alist nil
15690 "Property set function alist.
15691 Each entry should have the following format:
15693 (PROPERTY . READ-FUNCTION)
15695 The read function will be called with the same argument as
15696 `org-completing-read'.")
15698 (defun org-set-property-function (property)
15699 "Get the function that should be used to set PROPERTY.
15700 This is computed according to `org-property-set-functions-alist'."
15701 (or (cdr (assoc property org-property-set-functions-alist))
15702 'org-completing-read))
15704 (defun org-read-property-value (property)
15705 "Read PROPERTY value from user."
15706 (let* ((completion-ignore-case t)
15707 (allowed (org-property-get-allowed-values nil property 'table))
15708 (cur (org-entry-get nil property))
15709 (prompt (concat property " value"
15710 (if (and cur (string-match "\\S-" cur))
15711 (concat " [" cur "]") "") ": "))
15712 (set-function (org-set-property-function property))
15713 (val (if allowed
15714 (funcall set-function prompt allowed nil
15715 (not (get-text-property 0 'org-unrestricted
15716 (caar allowed))))
15717 (let (org-completion-use-ido org-completion-use-iswitchb)
15718 (funcall set-function prompt
15719 (mapcar 'list (org-property-values property))
15720 nil nil "" nil cur)))))
15721 (if (equal val "")
15723 val)))
15725 (defvar org-last-set-property nil)
15726 (defvar org-last-set-property-value nil)
15727 (defun org-read-property-name ()
15728 "Read a property name."
15729 (let* ((completion-ignore-case t)
15730 (keys (org-buffer-property-keys nil t t))
15731 (default-prop (or (save-excursion
15732 (save-match-data
15733 (beginning-of-line)
15734 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15735 (null (string= (match-string 1) "END"))
15736 (match-string 1))))
15737 org-last-set-property))
15738 (property (org-icompleting-read
15739 (concat "Property"
15740 (if default-prop (concat " [" default-prop "]") "")
15741 ": ")
15742 (mapcar 'list keys)
15743 nil nil nil nil
15744 default-prop)))
15745 (if (member property keys)
15746 property
15747 (or (cdr (assoc (downcase property)
15748 (mapcar (lambda (x) (cons (downcase x) x))
15749 keys)))
15750 property))))
15752 (defun org-set-property-and-value (use-last)
15753 "Allow to set [PROPERTY]: [value] direction from prompt.
15754 When use-default, don't even ask, just use the last
15755 \"[PROPERTY]: [value]\" string from the history."
15756 (interactive "P")
15757 (let* ((completion-ignore-case t)
15758 (pv (or (and use-last org-last-set-property-value)
15759 (org-completing-read
15760 "Enter a \"[Property]: [value]\" pair: "
15761 nil nil nil nil nil
15762 org-last-set-property-value)))
15763 prop val)
15764 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15765 (setq prop (match-string 1 pv)
15766 val (match-string 2 pv))
15767 (org-set-property prop val))))
15769 (defun org-set-property (property value)
15770 "In the current entry, set PROPERTY to VALUE.
15771 When called interactively, this will prompt for a property name, offering
15772 completion on existing and default properties. And then it will prompt
15773 for a value, offering completion either on allowed values (via an inherited
15774 xxx_ALL property) or on existing values in other instances of this property
15775 in the current file."
15776 (interactive (list nil nil))
15777 (let* ((property (or property (org-read-property-name)))
15778 (value (or value (org-read-property-value property)))
15779 (fn (cdr (assoc property org-properties-postprocess-alist))))
15780 (setq org-last-set-property property)
15781 (setq org-last-set-property-value (concat property ": " value))
15782 ;; Possibly postprocess the inserted value:
15783 (when fn (setq value (funcall fn value)))
15784 (unless (equal (org-entry-get nil property) value)
15785 (org-entry-put nil property value))))
15787 (defun org-delete-property (property &optional delete-empty-drawer)
15788 "In the current entry, delete PROPERTY.
15789 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15790 an empty drawer to delete."
15791 (interactive
15792 (let* ((completion-ignore-case t)
15793 (prop (org-icompleting-read "Property: "
15794 (org-entry-properties nil 'standard))))
15795 (list prop)))
15796 (message "Property %s %s" property
15797 (if (org-entry-delete nil property delete-empty-drawer)
15798 "deleted"
15799 "was not present in the entry")))
15801 (defun org-delete-property-globally (property)
15802 "Remove PROPERTY globally, from all entries."
15803 (interactive
15804 (let* ((completion-ignore-case t)
15805 (prop (org-icompleting-read
15806 "Globally remove property: "
15807 (mapcar 'list (org-buffer-property-keys)))))
15808 (list prop)))
15809 (save-excursion
15810 (save-restriction
15811 (widen)
15812 (goto-char (point-min))
15813 (let ((cnt 0))
15814 (while (re-search-forward
15815 (org-re-property property)
15816 nil t)
15817 (setq cnt (1+ cnt))
15818 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15819 (message "Property \"%s\" removed from %d entries" property cnt)))))
15821 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15823 (defun org-compute-property-at-point ()
15824 "Compute the property at point.
15825 This looks for an enclosing column format, extracts the operator and
15826 then applies it to the property in the column format's scope."
15827 (interactive)
15828 (unless (org-at-property-p)
15829 (user-error "Not at a property"))
15830 (let ((prop (org-match-string-no-properties 2)))
15831 (org-columns-get-format-and-top-level)
15832 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15833 (user-error "No operator defined for property %s" prop))
15834 (org-columns-compute prop)))
15836 (defvar org-property-allowed-value-functions nil
15837 "Hook for functions supplying allowed values for a specific property.
15838 The functions must take a single argument, the name of the property, and
15839 return a flat list of allowed values. If \":ETC\" is one of
15840 the values, this means that these values are intended as defaults for
15841 completion, but that other values should be allowed too.
15842 The functions must return nil if they are not responsible for this
15843 property.")
15845 (defun org-property-get-allowed-values (pom property &optional table)
15846 "Get allowed values for the property PROPERTY.
15847 When TABLE is non-nil, return an alist that can directly be used for
15848 completion."
15849 (let (vals)
15850 (cond
15851 ((equal property "TODO")
15852 (setq vals (org-with-point-at pom
15853 (append org-todo-keywords-1 '("")))))
15854 ((equal property "PRIORITY")
15855 (let ((n org-lowest-priority))
15856 (while (>= n org-highest-priority)
15857 (push (char-to-string n) vals)
15858 (setq n (1- n)))))
15859 ((member property org-special-properties))
15860 ((setq vals (run-hook-with-args-until-success
15861 'org-property-allowed-value-functions property)))
15863 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15864 (when (and vals (string-match "\\S-" vals))
15865 (setq vals (car (read-from-string (concat "(" vals ")"))))
15866 (setq vals (mapcar (lambda (x)
15867 (cond ((stringp x) x)
15868 ((numberp x) (number-to-string x))
15869 ((symbolp x) (symbol-name x))
15870 (t "???")))
15871 vals)))))
15872 (when (member ":ETC" vals)
15873 (setq vals (remove ":ETC" vals))
15874 (org-add-props (car vals) '(org-unrestricted t)))
15875 (if table (mapcar 'list vals) vals)))
15877 (defun org-property-previous-allowed-value (&optional previous)
15878 "Switch to the next allowed value for this property."
15879 (interactive)
15880 (org-property-next-allowed-value t))
15882 (defun org-property-next-allowed-value (&optional previous)
15883 "Switch to the next allowed value for this property."
15884 (interactive)
15885 (unless (org-at-property-p)
15886 (user-error "Not at a property"))
15887 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15888 (key (match-string 2))
15889 (value (match-string 3))
15890 (allowed (or (org-property-get-allowed-values (point) key)
15891 (and (member value '("[ ]" "[-]" "[X]"))
15892 '("[ ]" "[X]"))))
15893 (heading (save-match-data (nth 4 (org-heading-components))))
15894 nval)
15895 (unless allowed
15896 (user-error "Allowed values for this property have not been defined"))
15897 (if previous (setq allowed (reverse allowed)))
15898 (if (member value allowed)
15899 (setq nval (car (cdr (member value allowed)))))
15900 (setq nval (or nval (car allowed)))
15901 (if (equal nval value)
15902 (user-error "Only one allowed value for this property"))
15903 (org-at-property-p)
15904 (replace-match (concat " :" key ": " nval) t t)
15905 (org-indent-line)
15906 (beginning-of-line 1)
15907 (skip-chars-forward " \t")
15908 (when (equal prop org-effort-property)
15909 (save-excursion
15910 (org-back-to-heading t)
15911 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15912 (when (string= org-clock-current-task heading)
15913 (setq org-clock-effort nval)
15914 (org-clock-update-mode-line)))
15915 (run-hook-with-args 'org-property-changed-functions key nval)))
15917 (defun org-find-olp (path &optional this-buffer)
15918 "Return a marker pointing to the entry at outline path OLP.
15919 If anything goes wrong, throw an error.
15920 You can wrap this call to catch the error like this:
15922 (condition-case msg
15923 (org-mobile-locate-entry (match-string 4))
15924 (error (nth 1 msg)))
15926 The return value will then be either a string with the error message,
15927 or a marker if everything is OK.
15929 If THIS-BUFFER is set, the outline path does not contain a file,
15930 only headings."
15931 (let* ((file (if this-buffer buffer-file-name (pop path)))
15932 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15933 (level 1)
15934 (lmin 1)
15935 (lmax 1)
15936 limit re end found pos heading cnt flevel)
15937 (unless buffer (error "File not found :%s" file))
15938 (with-current-buffer buffer
15939 (save-excursion
15940 (save-restriction
15941 (widen)
15942 (setq limit (point-max))
15943 (goto-char (point-min))
15944 (while (setq heading (pop path))
15945 (setq re (format org-complex-heading-regexp-format
15946 (regexp-quote heading)))
15947 (setq cnt 0 pos (point))
15948 (while (re-search-forward re end t)
15949 (setq level (- (match-end 1) (match-beginning 1)))
15950 (if (and (>= level lmin) (<= level lmax))
15951 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15952 (when (= cnt 0) (error "Heading not found on level %d: %s"
15953 lmax heading))
15954 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15955 lmax heading))
15956 (goto-char found)
15957 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15958 (setq end (save-excursion (org-end-of-subtree t t))))
15959 (when (org-at-heading-p)
15960 (point-marker)))))))
15962 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15963 "Find node HEADING in BUFFER.
15964 Return a marker to the heading if it was found, or nil if not.
15965 If POS-ONLY is set, return just the position instead of a marker.
15967 The heading text must match exact, but it may have a TODO keyword,
15968 a priority cookie and tags in the standard locations."
15969 (with-current-buffer (or buffer (current-buffer))
15970 (save-excursion
15971 (save-restriction
15972 (widen)
15973 (goto-char (point-min))
15974 (let (case-fold-search)
15975 (if (re-search-forward
15976 (format org-complex-heading-regexp-format
15977 (regexp-quote heading)) nil t)
15978 (if pos-only
15979 (match-beginning 0)
15980 (move-marker (make-marker) (match-beginning 0)))))))))
15982 (defun org-find-exact-heading-in-directory (heading &optional dir)
15983 "Find Org node headline HEADING in all .org files in directory DIR.
15984 When the target headline is found, return a marker to this location."
15985 (let ((files (directory-files (or dir default-directory)
15986 nil "\\`[^.#].*\\.org\\'"))
15987 file visiting m buffer)
15988 (catch 'found
15989 (while (setq file (pop files))
15990 (message "trying %s" file)
15991 (setq visiting (org-find-base-buffer-visiting file))
15992 (setq buffer (or visiting (find-file-noselect file)))
15993 (setq m (org-find-exact-headline-in-buffer
15994 heading buffer))
15995 (when (and (not m) (not visiting)) (kill-buffer buffer))
15996 (and m (throw 'found m))))))
15998 (defun org-find-entry-with-id (ident)
15999 "Locate the entry that contains the ID property with exact value IDENT.
16000 IDENT can be a string, a symbol or a number, this function will search for
16001 the string representation of it.
16002 Return the position where this entry starts, or nil if there is no such entry."
16003 (interactive "sID: ")
16004 (let ((id (cond
16005 ((stringp ident) ident)
16006 ((symbol-name ident) (symbol-name ident))
16007 ((numberp ident) (number-to-string ident))
16008 (t (error "IDENT %s must be a string, symbol or number" ident))))
16009 (case-fold-search nil))
16010 (save-excursion
16011 (save-restriction
16012 (widen)
16013 (goto-char (point-min))
16014 (when (re-search-forward
16015 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16016 nil t)
16017 (org-back-to-heading t)
16018 (point))))))
16020 ;;;; Timestamps
16022 (defvar org-last-changed-timestamp nil)
16023 (defvar org-last-inserted-timestamp nil
16024 "The last time stamp inserted with `org-insert-time-stamp'.")
16025 (defvar org-time-was-given) ; dynamically scoped parameter
16026 (defvar org-end-time-was-given) ; dynamically scoped parameter
16027 (defvar org-ts-what) ; dynamically scoped parameter
16029 (defun org-time-stamp (arg &optional inactive)
16030 "Prompt for a date/time and insert a time stamp.
16031 If the user specifies a time like HH:MM or if this command is
16032 called with at least one prefix argument, the time stamp contains
16033 the date and the time. Otherwise, only the date is be included.
16035 All parts of a date not specified by the user is filled in from
16036 the current date/time. So if you just press return without
16037 typing anything, the time stamp will represent the current
16038 date/time.
16040 If there is already a timestamp at the cursor, it will be
16041 modified.
16043 With two universal prefix arguments, insert an active timestamp
16044 with the current time without prompting the user.
16046 When called from lisp, the timestamp is inactive if INACTIVE is
16047 non-nil."
16048 (interactive "P")
16049 (let* ((ts nil)
16050 (default-time
16051 ;; Default time is either today, or, when entering a range,
16052 ;; the range start.
16053 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16054 (save-excursion
16055 (re-search-backward
16056 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16057 (- (point) 20) t)))
16058 (apply 'encode-time (org-parse-time-string (match-string 1)))
16059 (current-time)))
16060 (default-input (and ts (org-get-compact-tod ts)))
16061 (repeater (save-excursion
16062 (save-match-data
16063 (beginning-of-line)
16064 (when (re-search-forward
16065 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16066 (save-excursion (progn (end-of-line) (point))) t)
16067 (match-string 0)))))
16068 org-time-was-given org-end-time-was-given time)
16069 (cond
16070 ((and (org-at-timestamp-p t)
16071 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16072 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16073 (insert "--")
16074 (setq time (let ((this-command this-command))
16075 (org-read-date arg 'totime nil nil
16076 default-time default-input inactive)))
16077 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16078 ((org-at-timestamp-p t)
16079 (setq time (let ((this-command this-command))
16080 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16081 (when (org-at-timestamp-p t) ; just to get the match data
16082 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16083 (replace-match "")
16084 (setq org-last-changed-timestamp
16085 (org-insert-time-stamp
16086 time (or org-time-was-given arg)
16087 inactive nil nil (list org-end-time-was-given)))
16088 (when repeater (goto-char (1- (point))) (insert " " repeater)
16089 (setq org-last-changed-timestamp
16090 (concat (substring org-last-inserted-timestamp 0 -1)
16091 " " repeater ">"))))
16092 (message "Timestamp updated"))
16093 ((equal arg '(16))
16094 (org-insert-time-stamp (current-time) t inactive))
16096 (setq time (let ((this-command this-command))
16097 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16098 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16099 nil nil (list org-end-time-was-given))))))
16101 ;; FIXME: can we use this for something else, like computing time differences?
16102 (defun org-get-compact-tod (s)
16103 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16104 (let* ((t1 (match-string 1 s))
16105 (h1 (string-to-number (match-string 2 s)))
16106 (m1 (string-to-number (match-string 3 s)))
16107 (t2 (and (match-end 4) (match-string 5 s)))
16108 (h2 (and t2 (string-to-number (match-string 6 s))))
16109 (m2 (and t2 (string-to-number (match-string 7 s))))
16110 dh dm)
16111 (if (not t2)
16113 (setq dh (- h2 h1) dm (- m2 m1))
16114 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16115 (concat t1 "+" (number-to-string dh)
16116 (and (/= 0 dm) (format ":%02d" dm)))))))
16118 (defun org-time-stamp-inactive (&optional arg)
16119 "Insert an inactive time stamp.
16120 An inactive time stamp is enclosed in square brackets instead of angle
16121 brackets. It is inactive in the sense that it does not trigger agenda entries,
16122 does not link to the calendar and cannot be changed with the S-cursor keys.
16123 So these are more for recording a certain time/date."
16124 (interactive "P")
16125 (org-time-stamp arg 'inactive))
16127 (defvar org-date-ovl (make-overlay 1 1))
16128 (overlay-put org-date-ovl 'face 'org-date-selected)
16129 (org-detach-overlay org-date-ovl)
16131 (defvar org-ans1) ; dynamically scoped parameter
16132 (defvar org-ans2) ; dynamically scoped parameter
16134 (defvar org-plain-time-of-day-regexp) ; defined below
16136 (defvar org-overriding-default-time nil) ; dynamically scoped
16137 (defvar org-read-date-overlay nil)
16138 (defvar org-dcst nil) ; dynamically scoped
16139 (defvar org-read-date-history nil)
16140 (defvar org-read-date-final-answer nil)
16141 (defvar org-read-date-analyze-futurep nil)
16142 (defvar org-read-date-analyze-forced-year nil)
16143 (defvar org-read-date-inactive)
16145 (defvar org-read-date-minibuffer-local-map
16146 (let* ((org-replace-disputed-keys nil)
16147 (map (make-sparse-keymap)))
16148 (set-keymap-parent map minibuffer-local-map)
16149 (org-defkey map (kbd ".")
16150 (lambda () (interactive)
16151 ;; Are we at the beginning of the prompt?
16152 (if (looking-back "^[^:]+: ")
16153 (org-eval-in-calendar '(calendar-goto-today))
16154 (insert "."))))
16155 (org-defkey map (kbd "C-.")
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(calendar-goto-today))))
16158 (org-defkey map [(meta shift left)]
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-backward-month 1))))
16161 (org-defkey map [(meta shift right)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-forward-month 1))))
16164 (org-defkey map [(meta shift up)]
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(calendar-backward-year 1))))
16167 (org-defkey map [(meta shift down)]
16168 (lambda () (interactive)
16169 (org-eval-in-calendar '(calendar-forward-year 1))))
16170 (org-defkey map [?\e (shift left)]
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(calendar-backward-month 1))))
16173 (org-defkey map [?\e (shift right)]
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(calendar-forward-month 1))))
16176 (org-defkey map [?\e (shift up)]
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(calendar-backward-year 1))))
16179 (org-defkey map [?\e (shift down)]
16180 (lambda () (interactive)
16181 (org-eval-in-calendar '(calendar-forward-year 1))))
16182 (org-defkey map [(shift up)]
16183 (lambda () (interactive)
16184 (org-eval-in-calendar '(calendar-backward-week 1))))
16185 (org-defkey map [(shift down)]
16186 (lambda () (interactive)
16187 (org-eval-in-calendar '(calendar-forward-week 1))))
16188 (org-defkey map [(shift left)]
16189 (lambda () (interactive)
16190 (org-eval-in-calendar '(calendar-backward-day 1))))
16191 (org-defkey map [(shift right)]
16192 (lambda () (interactive)
16193 (org-eval-in-calendar '(calendar-forward-day 1))))
16194 (org-defkey map "!"
16195 (lambda () (interactive)
16196 (org-eval-in-calendar '(diary-view-entries))
16197 (message "")))
16198 (org-defkey map ">"
16199 (lambda () (interactive)
16200 (org-eval-in-calendar '(scroll-calendar-left 1))))
16201 (org-defkey map "<"
16202 (lambda () (interactive)
16203 (org-eval-in-calendar '(scroll-calendar-right 1))))
16204 (org-defkey map "\C-v"
16205 (lambda () (interactive)
16206 (org-eval-in-calendar
16207 '(calendar-scroll-left-three-months 1))))
16208 (org-defkey map "\M-v"
16209 (lambda () (interactive)
16210 (org-eval-in-calendar
16211 '(calendar-scroll-right-three-months 1))))
16212 map)
16213 "Keymap for minibuffer commands when using `org-read-date'.")
16215 (defun org-read-date (&optional org-with-time to-time from-string prompt
16216 default-time default-input inactive)
16217 "Read a date, possibly a time, and make things smooth for the user.
16218 The prompt will suggest to enter an ISO date, but you can also enter anything
16219 which will at least partially be understood by `parse-time-string'.
16220 Unrecognized parts of the date will default to the current day, month, year,
16221 hour and minute. If this command is called to replace a timestamp at point,
16222 or to enter the second timestamp of a range, the default time is taken
16223 from the existing stamp. Furthermore, the command prefers the future,
16224 so if you are giving a date where the year is not given, and the day-month
16225 combination is already past in the current year, it will assume you
16226 mean next year. For details, see the manual. A few examples:
16228 3-2-5 --> 2003-02-05
16229 feb 15 --> currentyear-02-15
16230 2/15 --> currentyear-02-15
16231 sep 12 9 --> 2009-09-12
16232 12:45 --> today 12:45
16233 22 sept 0:34 --> currentyear-09-22 0:34
16234 12 --> currentyear-currentmonth-12
16235 Fri --> nearest Friday after today
16236 -Tue --> last Tuesday
16237 etc.
16239 Furthermore you can specify a relative date by giving, as the *first* thing
16240 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16241 change in days weeks, months, years.
16242 With a single plus or minus, the date is relative to today. With a double
16243 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16244 +4d --> four days from today
16245 +4 --> same as above
16246 +2w --> two weeks from today
16247 ++5 --> five days from default date
16249 The function understands only English month and weekday abbreviations.
16251 While prompting, a calendar is popped up - you can also select the
16252 date with the mouse (button 1). The calendar shows a period of three
16253 months. To scroll it to other months, use the keys `>' and `<'.
16254 If you don't like the calendar, turn it off with
16255 \(setq org-read-date-popup-calendar nil)
16257 With optional argument TO-TIME, the date will immediately be converted
16258 to an internal time.
16259 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16260 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16261 still enter a time, and this function will inform the calling routine
16262 about this change. The calling routine may then choose to change the
16263 format used to insert the time stamp into the buffer to include the time.
16264 With optional argument FROM-STRING, read from this string instead from
16265 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16266 the time/date that is used for everything that is not specified by the
16267 user."
16268 (require 'parse-time)
16269 (let* ((org-time-stamp-rounding-minutes
16270 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16271 (org-dcst org-display-custom-times)
16272 (ct (org-current-time))
16273 (org-def (or org-overriding-default-time default-time ct))
16274 (org-defdecode (decode-time org-def))
16275 (dummy (progn
16276 (when (< (nth 2 org-defdecode) org-extend-today-until)
16277 (setcar (nthcdr 2 org-defdecode) -1)
16278 (setcar (nthcdr 1 org-defdecode) 59)
16279 (setq org-def (apply 'encode-time org-defdecode)
16280 org-defdecode (decode-time org-def)))))
16281 (mouse-autoselect-window nil) ; Don't let the mouse jump
16282 (calendar-frame-setup nil)
16283 (calendar-setup nil)
16284 (calendar-move-hook nil)
16285 (calendar-view-diary-initially-flag nil)
16286 (calendar-view-holidays-initially-flag nil)
16287 (timestr (format-time-string
16288 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16289 (prompt (concat (if prompt (concat prompt " ") "")
16290 (format "Date+time [%s]: " timestr)))
16291 ans (org-ans0 "") org-ans1 org-ans2 final)
16293 (cond
16294 (from-string (setq ans from-string))
16295 (org-read-date-popup-calendar
16296 (save-excursion
16297 (save-window-excursion
16298 (calendar)
16299 (org-eval-in-calendar '(setq cursor-type nil) t)
16300 (unwind-protect
16301 (progn
16302 (calendar-forward-day (- (time-to-days org-def)
16303 (calendar-absolute-from-gregorian
16304 (calendar-current-date))))
16305 (org-eval-in-calendar nil t)
16306 (let* ((old-map (current-local-map))
16307 (map (copy-keymap calendar-mode-map))
16308 (minibuffer-local-map
16309 (copy-keymap org-read-date-minibuffer-local-map)))
16310 (org-defkey map (kbd "RET") 'org-calendar-select)
16311 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16312 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16313 (unwind-protect
16314 (progn
16315 (use-local-map map)
16316 (setq org-read-date-inactive inactive)
16317 (add-hook 'post-command-hook 'org-read-date-display)
16318 (setq org-ans0 (read-string prompt default-input
16319 'org-read-date-history nil))
16320 ;; org-ans0: from prompt
16321 ;; org-ans1: from mouse click
16322 ;; org-ans2: from calendar motion
16323 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16324 (remove-hook 'post-command-hook 'org-read-date-display)
16325 (use-local-map old-map)
16326 (when org-read-date-overlay
16327 (delete-overlay org-read-date-overlay)
16328 (setq org-read-date-overlay nil)))))
16329 (bury-buffer "*Calendar*")))))
16331 (t ; Naked prompt only
16332 (unwind-protect
16333 (setq ans (read-string prompt default-input
16334 'org-read-date-history timestr))
16335 (when org-read-date-overlay
16336 (delete-overlay org-read-date-overlay)
16337 (setq org-read-date-overlay nil)))))
16339 (setq final (org-read-date-analyze ans org-def org-defdecode))
16341 (when org-read-date-analyze-forced-year
16342 (message "Year was forced into %s"
16343 (if org-read-date-force-compatible-dates
16344 "compatible range (1970-2037)"
16345 "range representable on this machine"))
16346 (ding))
16348 ;; One round trip to get rid of 34th of August and stuff like that....
16349 (setq final (decode-time (apply 'encode-time final)))
16351 (setq org-read-date-final-answer ans)
16353 (if to-time
16354 (apply 'encode-time final)
16355 (if (and (boundp 'org-time-was-given) org-time-was-given)
16356 (format "%04d-%02d-%02d %02d:%02d"
16357 (nth 5 final) (nth 4 final) (nth 3 final)
16358 (nth 2 final) (nth 1 final))
16359 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16361 (defvar org-def)
16362 (defvar org-defdecode)
16363 (defvar org-with-time)
16364 (defun org-read-date-display ()
16365 "Display the current date prompt interpretation in the minibuffer."
16366 (when org-read-date-display-live
16367 (when org-read-date-overlay
16368 (delete-overlay org-read-date-overlay))
16369 (when (minibufferp (current-buffer))
16370 (save-excursion
16371 (end-of-line 1)
16372 (while (not (equal (buffer-substring
16373 (max (point-min) (- (point) 4)) (point))
16374 " "))
16375 (insert " ")))
16376 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16377 " " (or org-ans1 org-ans2)))
16378 (org-end-time-was-given nil)
16379 (f (org-read-date-analyze ans org-def org-defdecode))
16380 (fmts (if org-dcst
16381 org-time-stamp-custom-formats
16382 org-time-stamp-formats))
16383 (fmt (if (or org-with-time
16384 (and (boundp 'org-time-was-given) org-time-was-given))
16385 (cdr fmts)
16386 (car fmts)))
16387 (txt (format-time-string fmt (apply 'encode-time f)))
16388 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16389 (txt (concat "=> " txt)))
16390 (when (and org-end-time-was-given
16391 (string-match org-plain-time-of-day-regexp txt))
16392 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16393 org-end-time-was-given
16394 (substring txt (match-end 0)))))
16395 (when org-read-date-analyze-futurep
16396 (setq txt (concat txt " (=>F)")))
16397 (setq org-read-date-overlay
16398 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16399 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16401 (defun org-read-date-analyze (ans org-def org-defdecode)
16402 "Analyze the combined answer of the date prompt."
16403 ;; FIXME: cleanup and comment
16404 (let ((nowdecode (decode-time (current-time)))
16405 delta deltan deltaw deltadef year month day
16406 hour minute second wday pm h2 m2 tl wday1
16407 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16408 (setq org-read-date-analyze-futurep nil
16409 org-read-date-analyze-forced-year nil)
16410 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16411 (setq ans "+0"))
16413 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16414 (setq ans (replace-match "" t t ans)
16415 deltan (car delta)
16416 deltaw (nth 1 delta)
16417 deltadef (nth 2 delta)))
16419 ;; Check if there is an iso week date in there. If yes, store the
16420 ;; info and postpone interpreting it until the rest of the parsing
16421 ;; is done.
16422 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16423 (setq iso-year (if (match-end 1)
16424 (org-small-year-to-year
16425 (string-to-number (match-string 1 ans))))
16426 iso-weekday (if (match-end 3)
16427 (string-to-number (match-string 3 ans)))
16428 iso-week (string-to-number (match-string 2 ans)))
16429 (setq ans (replace-match "" t t ans)))
16431 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16432 (when (string-match
16433 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16434 (setq year (if (match-end 2)
16435 (string-to-number (match-string 2 ans))
16436 (progn (setq kill-year t)
16437 (string-to-number (format-time-string "%Y"))))
16438 month (string-to-number (match-string 3 ans))
16439 day (string-to-number (match-string 4 ans)))
16440 (if (< year 100) (setq year (+ 2000 year)))
16441 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16442 t nil ans)))
16444 ;; Help matching dotted european dates
16445 (when (string-match
16446 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16447 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16448 (setq kill-year t)
16449 (string-to-number (format-time-string "%Y")))
16450 day (string-to-number (match-string 1 ans))
16451 month (string-to-number (match-string 2 ans))
16452 ans (replace-match (format "%04d-%02d-%02d" year month day)
16453 t nil ans)))
16455 ;; Help matching american dates, like 5/30 or 5/30/7
16456 (when (string-match
16457 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16458 (setq year (if (match-end 4)
16459 (string-to-number (match-string 4 ans))
16460 (progn (setq kill-year t)
16461 (string-to-number (format-time-string "%Y"))))
16462 month (string-to-number (match-string 1 ans))
16463 day (string-to-number (match-string 2 ans)))
16464 (if (< year 100) (setq year (+ 2000 year)))
16465 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16466 t nil ans)))
16467 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16468 ;; If there is a time with am/pm, and *no* time without it, we convert
16469 ;; so that matching will be successful.
16470 (loop for i from 1 to 2 do ; twice, for end time as well
16471 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16472 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16473 (setq hour (string-to-number (match-string 1 ans))
16474 minute (if (match-end 3)
16475 (string-to-number (match-string 3 ans))
16477 pm (equal ?p
16478 (string-to-char (downcase (match-string 4 ans)))))
16479 (if (and (= hour 12) (not pm))
16480 (setq hour 0)
16481 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16482 (setq ans (replace-match (format "%02d:%02d" hour minute)
16483 t t ans))))
16485 ;; Check if a time range is given as a duration
16486 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16487 (setq hour (string-to-number (match-string 1 ans))
16488 h2 (+ hour (string-to-number (match-string 3 ans)))
16489 minute (string-to-number (match-string 2 ans))
16490 m2 (+ minute (if (match-end 5) (string-to-number
16491 (match-string 5 ans))0)))
16492 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16493 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16494 t t ans)))
16496 ;; Check if there is a time range
16497 (when (boundp 'org-end-time-was-given)
16498 (setq org-time-was-given nil)
16499 (when (and (string-match org-plain-time-of-day-regexp ans)
16500 (match-end 8))
16501 (setq org-end-time-was-given (match-string 8 ans))
16502 (setq ans (concat (substring ans 0 (match-beginning 7))
16503 (substring ans (match-end 7))))))
16505 (setq tl (parse-time-string ans)
16506 day (or (nth 3 tl) (nth 3 org-defdecode))
16507 month (or (nth 4 tl)
16508 (if (and org-read-date-prefer-future
16509 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16510 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16511 (nth 4 org-defdecode)))
16512 year (or (and (not kill-year) (nth 5 tl))
16513 (if (and org-read-date-prefer-future
16514 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16515 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16516 (nth 5 org-defdecode)))
16517 hour (or (nth 2 tl) (nth 2 org-defdecode))
16518 minute (or (nth 1 tl) (nth 1 org-defdecode))
16519 second (or (nth 0 tl) 0)
16520 wday (nth 6 tl))
16522 (when (and (eq org-read-date-prefer-future 'time)
16523 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16524 (equal day (nth 3 nowdecode))
16525 (equal month (nth 4 nowdecode))
16526 (equal year (nth 5 nowdecode))
16527 (nth 2 tl)
16528 (or (< (nth 2 tl) (nth 2 nowdecode))
16529 (and (= (nth 2 tl) (nth 2 nowdecode))
16530 (nth 1 tl)
16531 (< (nth 1 tl) (nth 1 nowdecode)))))
16532 (setq day (1+ day)
16533 futurep t))
16535 ;; Special date definitions below
16536 (cond
16537 (iso-week
16538 ;; There was an iso week
16539 (require 'cal-iso)
16540 (setq futurep nil)
16541 (setq year (or iso-year year)
16542 day (or iso-weekday wday 1)
16543 wday nil ; to make sure that the trigger below does not match
16544 iso-date (calendar-gregorian-from-absolute
16545 (calendar-absolute-from-iso
16546 (list iso-week day year))))
16547 ; FIXME: Should we also push ISO weeks into the future?
16548 ; (when (and org-read-date-prefer-future
16549 ; (not iso-year)
16550 ; (< (calendar-absolute-from-gregorian iso-date)
16551 ; (time-to-days (current-time))))
16552 ; (setq year (1+ year)
16553 ; iso-date (calendar-gregorian-from-absolute
16554 ; (calendar-absolute-from-iso
16555 ; (list iso-week day year)))))
16556 (setq month (car iso-date)
16557 year (nth 2 iso-date)
16558 day (nth 1 iso-date)))
16559 (deltan
16560 (setq futurep nil)
16561 (unless deltadef
16562 (let ((now (decode-time (current-time))))
16563 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16564 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16565 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16566 ((equal deltaw "m") (setq month (+ month deltan)))
16567 ((equal deltaw "y") (setq year (+ year deltan)))))
16568 ((and wday (not (nth 3 tl)))
16569 ;; Weekday was given, but no day, so pick that day in the week
16570 ;; on or after the derived date.
16571 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16572 (unless (equal wday wday1)
16573 (setq day (+ day (% (- wday wday1 -7) 7))))))
16574 (if (and (boundp 'org-time-was-given)
16575 (nth 2 tl))
16576 (setq org-time-was-given t))
16577 (if (< year 100) (setq year (+ 2000 year)))
16578 ;; Check of the date is representable
16579 (if org-read-date-force-compatible-dates
16580 (progn
16581 (if (< year 1970)
16582 (setq year 1970 org-read-date-analyze-forced-year t))
16583 (if (> year 2037)
16584 (setq year 2037 org-read-date-analyze-forced-year t)))
16585 (condition-case nil
16586 (ignore (encode-time second minute hour day month year))
16587 (error
16588 (setq year (nth 5 org-defdecode))
16589 (setq org-read-date-analyze-forced-year t))))
16590 (setq org-read-date-analyze-futurep futurep)
16591 (list second minute hour day month year)))
16593 (defvar parse-time-weekdays)
16594 (defun org-read-date-get-relative (s today default)
16595 "Check string S for special relative date string.
16596 TODAY and DEFAULT are internal times, for today and for a default.
16597 Return shift list (N what def-flag)
16598 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16599 N is the number of WHATs to shift.
16600 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16601 the DEFAULT date rather than TODAY."
16602 (require 'parse-time)
16603 (when (and
16604 (string-match
16605 (concat
16606 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16607 "\\([0-9]+\\)?"
16608 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16609 "\\([ \t]\\|$\\)") s)
16610 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16611 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16612 (string-to-char (substring (match-string 1 s) -1))
16613 ?+))
16614 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16615 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16616 (what (if (match-end 3) (match-string 3 s) "d"))
16617 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16618 (date (if rel default today))
16619 (wday (nth 6 (decode-time date)))
16620 delta)
16621 (if wday1
16622 (progn
16623 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16624 (if (= delta 0) (setq delta 7))
16625 (if (= dir ?-)
16626 (progn
16627 (setq delta (- delta 7))
16628 (if (= delta 0) (setq delta -7))))
16629 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16630 (list delta "d" rel))
16631 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16633 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16634 "Turn a user-specified date into the internal representation.
16635 The internal representation needed by the calendar is (month day year).
16636 This is a wrapper to handle the brain-dead convention in calendar that
16637 user function argument order change dependent on argument order."
16638 (if (boundp 'calendar-date-style)
16639 (cond
16640 ((eq calendar-date-style 'american)
16641 (list arg1 arg2 arg3))
16642 ((eq calendar-date-style 'european)
16643 (list arg2 arg1 arg3))
16644 ((eq calendar-date-style 'iso)
16645 (list arg2 arg3 arg1)))
16646 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16647 (if (org-bound-and-true-p european-calendar-style)
16648 (list arg2 arg1 arg3)
16649 (list arg1 arg2 arg3)))))
16651 (defun org-eval-in-calendar (form &optional keepdate)
16652 "Eval FORM in the calendar window and return to current window.
16653 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16654 otherwise stick to the current value of `org-ans2'."
16655 (let ((sf (selected-frame))
16656 (sw (selected-window)))
16657 (select-window (get-buffer-window "*Calendar*" t))
16658 (eval form)
16659 (when (and (not keepdate) (calendar-cursor-to-date))
16660 (let* ((date (calendar-cursor-to-date))
16661 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16662 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16663 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16664 (select-window sw)
16665 (org-select-frame-set-input-focus sf)))
16667 (defun org-calendar-select ()
16668 "Return to `org-read-date' with the date currently selected.
16669 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16670 (interactive)
16671 (when (calendar-cursor-to-date)
16672 (let* ((date (calendar-cursor-to-date))
16673 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16674 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16675 (if (active-minibuffer-window) (exit-minibuffer))))
16677 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16678 "Insert a date stamp for the date given by the internal TIME.
16679 WITH-HM means use the stamp format that includes the time of the day.
16680 INACTIVE means use square brackets instead of angular ones, so that the
16681 stamp will not contribute to the agenda.
16682 PRE and POST are optional strings to be inserted before and after the
16683 stamp.
16684 The command returns the inserted time stamp."
16685 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16686 stamp)
16687 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16688 (insert-before-markers (or pre ""))
16689 (when (listp extra)
16690 (setq extra (car extra))
16691 (if (and (stringp extra)
16692 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16693 (setq extra (format "-%02d:%02d"
16694 (string-to-number (match-string 1 extra))
16695 (string-to-number (match-string 2 extra))))
16696 (setq extra nil)))
16697 (when extra
16698 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16699 (insert-before-markers (setq stamp (format-time-string fmt time)))
16700 (insert-before-markers (or post ""))
16701 (setq org-last-inserted-timestamp stamp)))
16703 (defun org-toggle-time-stamp-overlays ()
16704 "Toggle the use of custom time stamp formats."
16705 (interactive)
16706 (setq org-display-custom-times (not org-display-custom-times))
16707 (unless org-display-custom-times
16708 (let ((p (point-min)) (bmp (buffer-modified-p)))
16709 (while (setq p (next-single-property-change p 'display))
16710 (if (and (get-text-property p 'display)
16711 (eq (get-text-property p 'face) 'org-date))
16712 (remove-text-properties
16713 p (setq p (next-single-property-change p 'display))
16714 '(display t))))
16715 (set-buffer-modified-p bmp)))
16716 (if (featurep 'xemacs)
16717 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16718 (org-restart-font-lock)
16719 (setq org-table-may-need-update t)
16720 (if org-display-custom-times
16721 (message "Time stamps are overlaid with custom format")
16722 (message "Time stamp overlays removed")))
16724 (defun org-display-custom-time (beg end)
16725 "Overlay modified time stamp format over timestamp between BEG and END."
16726 (let* ((ts (buffer-substring beg end))
16727 t1 w1 with-hm tf time str w2 (off 0))
16728 (save-match-data
16729 (setq t1 (org-parse-time-string ts t))
16730 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16731 (setq off (- (match-end 0) (match-beginning 0)))))
16732 (setq end (- end off))
16733 (setq w1 (- end beg)
16734 with-hm (and (nth 1 t1) (nth 2 t1))
16735 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16736 time (org-fix-decoded-time t1)
16737 str (org-add-props
16738 (format-time-string
16739 (substring tf 1 -1) (apply 'encode-time time))
16740 nil 'mouse-face 'highlight)
16741 w2 (length str))
16742 (if (not (= w2 w1))
16743 (add-text-properties (1+ beg) (+ 2 beg)
16744 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16745 (if (featurep 'xemacs)
16746 (progn
16747 (put-text-property beg end 'invisible t)
16748 (put-text-property beg end 'end-glyph (make-glyph str)))
16749 (put-text-property beg end 'display str))))
16751 (defun org-translate-time (string)
16752 "Translate all timestamps in STRING to custom format.
16753 But do this only if the variable `org-display-custom-times' is set."
16754 (when org-display-custom-times
16755 (save-match-data
16756 (let* ((start 0)
16757 (re org-ts-regexp-both)
16758 t1 with-hm inactive tf time str beg end)
16759 (while (setq start (string-match re string start))
16760 (setq beg (match-beginning 0)
16761 end (match-end 0)
16762 t1 (save-match-data
16763 (org-parse-time-string (substring string beg end) t))
16764 with-hm (and (nth 1 t1) (nth 2 t1))
16765 inactive (equal (substring string beg (1+ beg)) "[")
16766 tf (funcall (if with-hm 'cdr 'car)
16767 org-time-stamp-custom-formats)
16768 time (org-fix-decoded-time t1)
16769 str (format-time-string
16770 (concat
16771 (if inactive "[" "<") (substring tf 1 -1)
16772 (if inactive "]" ">"))
16773 (apply 'encode-time time))
16774 string (replace-match str t t string)
16775 start (+ start (length str)))))))
16776 string)
16778 (defun org-fix-decoded-time (time)
16779 "Set 0 instead of nil for the first 6 elements of time.
16780 Don't touch the rest."
16781 (let ((n 0))
16782 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16784 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16786 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16787 "Difference between TIMESTAMP-STRING and now in days.
16788 If SECONDS is non-nil, return the difference in seconds."
16789 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16790 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16791 (funcall fdiff (current-time)))))
16793 (defun org-deadline-close (timestamp-string &optional ndays)
16794 "Is the time in TIMESTAMP-STRING close to the current date?"
16795 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16796 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16797 (not (org-entry-is-done-p))))
16799 (defun org-get-wdays (ts &optional delay zero-delay)
16800 "Get the deadline lead time appropriate for timestring TS.
16801 When DELAY is non-nil, get the delay time for scheduled items
16802 instead of the deadline lead time. When ZERO-DELAY is non-nil
16803 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16804 don't try to find the delay cookie in the scheduled timestamp."
16805 (let ((tv (if delay org-scheduled-delay-days
16806 org-deadline-warning-days)))
16807 (cond
16808 ((or (and delay (< tv 0))
16809 (and delay zero-delay (<= tv 0))
16810 (and (not delay) (<= tv 0)))
16811 ;; Enforce this value no matter what
16812 (- tv))
16813 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16814 ;; lead time is specified.
16815 (floor (* (string-to-number (match-string 1 ts))
16816 (cdr (assoc (match-string 2 ts)
16817 '(("d" . 1) ("w" . 7)
16818 ("m" . 30.4) ("y" . 365.25)
16819 ("h" . 0.041667)))))))
16820 ;; go for the default.
16821 (t tv))))
16823 (defun org-calendar-select-mouse (ev)
16824 "Return to `org-read-date' with the date currently selected.
16825 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16826 (interactive "e")
16827 (mouse-set-point ev)
16828 (when (calendar-cursor-to-date)
16829 (let* ((date (calendar-cursor-to-date))
16830 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16831 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16832 (if (active-minibuffer-window) (exit-minibuffer))))
16834 (defun org-check-deadlines (ndays)
16835 "Check if there are any deadlines due or past due.
16836 A deadline is considered due if it happens within `org-deadline-warning-days'
16837 days from today's date. If the deadline appears in an entry marked DONE,
16838 it is not shown. The prefix arg NDAYS can be used to test that many
16839 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16840 (interactive "P")
16841 (let* ((org-warn-days
16842 (cond
16843 ((equal ndays '(4)) 100000)
16844 (ndays (prefix-numeric-value ndays))
16845 (t (abs org-deadline-warning-days))))
16846 (case-fold-search nil)
16847 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16848 (callback
16849 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16851 (message "%d deadlines past-due or due within %d days"
16852 (org-occur regexp nil callback)
16853 org-warn-days)))
16855 (defsubst org-re-timestamp (type)
16856 "Return a regexp for timestamp TYPE.
16857 Allowed values for TYPE are:
16859 all: all timestamps
16860 active: only active timestamps (<...>)
16861 inactive: only inactive timestamps ([...])
16862 scheduled: only scheduled timestamps
16863 deadline: only deadline timestamps
16864 closed: only closed time-stamps
16866 When TYPE is nil, fall back on returning a regexp that matches
16867 both scheduled and deadline timestamps."
16868 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16869 ((eq type 'active) org-ts-regexp)
16870 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16871 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16872 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16873 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16874 ((eq type 'scheduled-or-deadline)
16875 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16877 (defun org-check-before-date (date)
16878 "Check if there are deadlines or scheduled entries before DATE."
16879 (interactive (list (org-read-date)))
16880 (let ((case-fold-search nil)
16881 (regexp (org-re-timestamp org-ts-type))
16882 (callback
16883 (lambda () (time-less-p
16884 (org-time-string-to-time (match-string 1))
16885 (org-time-string-to-time date)))))
16886 (message "%d entries before %s"
16887 (org-occur regexp nil callback) date)))
16889 (defun org-check-after-date (date)
16890 "Check if there are deadlines or scheduled entries after DATE."
16891 (interactive (list (org-read-date)))
16892 (let ((case-fold-search nil)
16893 (regexp (org-re-timestamp org-ts-type))
16894 (callback
16895 (lambda () (not
16896 (time-less-p
16897 (org-time-string-to-time (match-string 1))
16898 (org-time-string-to-time date))))))
16899 (message "%d entries after %s"
16900 (org-occur regexp nil callback) date)))
16902 (defun org-check-dates-range (start-date end-date)
16903 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16904 (interactive (list (org-read-date nil nil nil "Range starts")
16905 (org-read-date nil nil nil "Range end")))
16906 (let ((case-fold-search nil)
16907 (regexp (org-re-timestamp org-ts-type))
16908 (callback
16909 (lambda ()
16910 (let ((match (match-string 1)))
16911 (and
16912 (not (time-less-p
16913 (org-time-string-to-time match)
16914 (org-time-string-to-time start-date)))
16915 (time-less-p
16916 (org-time-string-to-time match)
16917 (org-time-string-to-time end-date)))))))
16918 (message "%d entries between %s and %s"
16919 (org-occur regexp nil callback) start-date end-date)))
16921 (defun org-evaluate-time-range (&optional to-buffer)
16922 "Evaluate a time range by computing the difference between start and end.
16923 Normally the result is just printed in the echo area, but with prefix arg
16924 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16925 If the time range is actually in a table, the result is inserted into the
16926 next column.
16927 For time difference computation, a year is assumed to be exactly 365
16928 days in order to avoid rounding problems."
16929 (interactive "P")
16931 (org-clock-update-time-maybe)
16932 (save-excursion
16933 (unless (org-at-date-range-p t)
16934 (goto-char (point-at-bol))
16935 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16936 (if (not (org-at-date-range-p t))
16937 (user-error "Not at a time-stamp range, and none found in current line")))
16938 (let* ((ts1 (match-string 1))
16939 (ts2 (match-string 2))
16940 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16941 (match-end (match-end 0))
16942 (time1 (org-time-string-to-time ts1))
16943 (time2 (org-time-string-to-time ts2))
16944 (t1 (org-float-time time1))
16945 (t2 (org-float-time time2))
16946 (diff (abs (- t2 t1)))
16947 (negative (< (- t2 t1) 0))
16948 ;; (ys (floor (* 365 24 60 60)))
16949 (ds (* 24 60 60))
16950 (hs (* 60 60))
16951 (fy "%dy %dd %02d:%02d")
16952 (fy1 "%dy %dd")
16953 (fd "%dd %02d:%02d")
16954 (fd1 "%dd")
16955 (fh "%02d:%02d")
16956 y d h m align)
16957 (if havetime
16958 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16960 d (floor (/ diff ds)) diff (mod diff ds)
16961 h (floor (/ diff hs)) diff (mod diff hs)
16962 m (floor (/ diff 60)))
16963 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16965 d (floor (+ (/ diff ds) 0.5))
16966 h 0 m 0))
16967 (if (not to-buffer)
16968 (message "%s" (org-make-tdiff-string y d h m))
16969 (if (org-at-table-p)
16970 (progn
16971 (goto-char match-end)
16972 (setq align t)
16973 (and (looking-at " *|") (goto-char (match-end 0))))
16974 (goto-char match-end))
16975 (if (looking-at
16976 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16977 (replace-match ""))
16978 (if negative (insert " -"))
16979 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16980 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16981 (insert " " (format fh h m))))
16982 (if align (org-table-align))
16983 (message "Time difference inserted")))))
16985 (defun org-make-tdiff-string (y d h m)
16986 (let ((fmt "")
16987 (l nil))
16988 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16989 l (push y l)))
16990 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16991 l (push d l)))
16992 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16993 l (push h l)))
16994 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16995 l (push m l)))
16996 (apply 'format fmt (nreverse l))))
16998 (defun org-time-string-to-time (s &optional buffer pos)
16999 "Convert a timestamp string into internal time."
17000 (condition-case errdata
17001 (apply 'encode-time (org-parse-time-string s))
17002 (error (error "Bad timestamp `%s'%s\nError was: %s"
17003 s (if (not (and buffer pos))
17005 (format " at %d in buffer `%s'" pos buffer))
17006 (cdr errdata)))))
17008 (defun org-time-string-to-seconds (s)
17009 "Convert a timestamp string to a number of seconds."
17010 (org-float-time (org-time-string-to-time s)))
17012 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17013 "Convert a time stamp to an absolute day number.
17014 If there is a specifier for a cyclic time stamp, get the closest
17015 date to DAYNR.
17016 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17017 The variable `date' is bound by the calendar when this is called."
17018 (cond
17019 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17020 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17021 daynr
17022 (+ daynr 1000)))
17023 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17024 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17025 (time-to-days (current-time))) (match-string 0 s)
17026 prefer show-all))
17027 (t (time-to-days
17028 (condition-case errdata
17029 (apply 'encode-time (org-parse-time-string s))
17030 (error (error "Bad timestamp `%s'%s\nError was: %s"
17031 s (if (not (and buffer pos))
17033 (format " at %d in buffer `%s'" pos buffer))
17034 (cdr errdata))))))))
17036 (defun org-days-to-iso-week (days)
17037 "Return the iso week number."
17038 (require 'cal-iso)
17039 (car (calendar-iso-from-absolute days)))
17041 (defun org-small-year-to-year (year)
17042 "Convert 2-digit years into 4-digit years.
17043 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17044 The year 2000 cannot be abbreviated. Any year larger than 99
17045 is returned unchanged."
17046 (if (< year 38)
17047 (setq year (+ 2000 year))
17048 (if (< year 100)
17049 (setq year (+ 1900 year))))
17050 year)
17052 (defun org-time-from-absolute (d)
17053 "Return the time corresponding to date D.
17054 D may be an absolute day number, or a calendar-type list (month day year)."
17055 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17056 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17058 (defun org-calendar-holiday ()
17059 "List of holidays, for Diary display in Org-mode."
17060 (require 'holidays)
17061 (let ((hl (funcall
17062 (if (fboundp 'calendar-check-holidays)
17063 'calendar-check-holidays 'check-calendar-holidays) date)))
17064 (if hl (mapconcat 'identity hl "; "))))
17066 (defun org-diary-sexp-entry (sexp entry date)
17067 "Process a SEXP diary ENTRY for DATE."
17068 (require 'diary-lib)
17069 (let ((result (if calendar-debug-sexp
17070 (let ((stack-trace-on-error t))
17071 (eval (car (read-from-string sexp))))
17072 (condition-case nil
17073 (eval (car (read-from-string sexp)))
17074 (error
17075 (beep)
17076 (message "Bad sexp at line %d in %s: %s"
17077 (org-current-line)
17078 (buffer-file-name) sexp)
17079 (sleep-for 2))))))
17080 (cond ((stringp result) (split-string result "; "))
17081 ((and (consp result)
17082 (not (consp (cdr result)))
17083 (stringp (cdr result))) (cdr result))
17084 ((and (consp result)
17085 (stringp (car result))) result)
17086 (result entry))))
17088 (defun org-diary-to-ical-string (frombuf)
17089 "Get iCalendar entries from diary entries in buffer FROMBUF.
17090 This uses the icalendar.el library."
17091 (let* ((tmpdir (if (featurep 'xemacs)
17092 (temp-directory)
17093 temporary-file-directory))
17094 (tmpfile (make-temp-name
17095 (expand-file-name "orgics" tmpdir)))
17096 buf rtn b e)
17097 (with-current-buffer frombuf
17098 (icalendar-export-region (point-min) (point-max) tmpfile)
17099 (setq buf (find-buffer-visiting tmpfile))
17100 (set-buffer buf)
17101 (goto-char (point-min))
17102 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17103 (setq b (match-beginning 0)))
17104 (goto-char (point-max))
17105 (if (re-search-backward "^END:VEVENT" nil t)
17106 (setq e (match-end 0)))
17107 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17108 (kill-buffer buf)
17109 (delete-file tmpfile)
17110 rtn))
17112 (defun org-closest-date (start current change prefer show-all)
17113 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17114 When PREFER is `past', return a date that is either CURRENT or past.
17115 When PREFER is `future', return a date that is either CURRENT or future.
17116 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17117 ;; Make the proper lists from the dates
17118 (catch 'exit
17119 (let ((a1 '(("h" . hour)
17120 ("d" . day)
17121 ("w" . week)
17122 ("m" . month)
17123 ("y" . year)))
17124 (shour (nth 2 (org-parse-time-string start)))
17125 dn dw sday cday n1 n2 n0
17126 d m y y1 y2 date1 date2 nmonths nm ny m2)
17128 (setq start (org-date-to-gregorian start)
17129 current (org-date-to-gregorian
17130 (if show-all
17131 current
17132 (time-to-days (current-time))))
17133 sday (calendar-absolute-from-gregorian start)
17134 cday (calendar-absolute-from-gregorian current))
17136 (if (<= cday sday) (throw 'exit sday))
17138 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17139 (setq dn (string-to-number (match-string 1 change))
17140 dw (cdr (assoc (match-string 2 change) a1)))
17141 (user-error "Invalid change specifier: %s" change))
17142 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17143 (cond
17144 ((eq dw 'hour)
17145 (let ((missing-hours
17146 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17147 dn)))
17148 (setq n1 (if (zerop missing-hours) cday
17149 (- cday (1+ (floor (/ missing-hours 24)))))
17150 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17151 ((eq dw 'day)
17152 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17153 n2 (+ n1 dn)))
17154 ((eq dw 'year)
17155 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17156 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17157 (setq date1 (list m d y1)
17158 n1 (calendar-absolute-from-gregorian date1)
17159 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17160 n2 (calendar-absolute-from-gregorian date2)))
17161 ((eq dw 'month)
17162 ;; approx number of month between the two dates
17163 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17164 ;; How often does dn fit in there?
17165 (setq d (nth 1 start) m (car start) y (nth 2 start)
17166 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17167 m (+ m nm)
17168 ny (floor (/ m 12))
17169 y (+ y ny)
17170 m (- m (* ny 12)))
17171 (while (> m 12) (setq m (- m 12) y (1+ y)))
17172 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17173 (setq m2 (+ m dn) y2 y)
17174 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17175 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17176 (while (<= n2 cday)
17177 (setq n1 n2 m m2 y y2)
17178 (setq m2 (+ m dn) y2 y)
17179 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17180 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17181 ;; Make sure n1 is the earlier date
17182 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17183 (if show-all
17184 (cond
17185 ((eq prefer 'past) (if (= cday n2) n2 n1))
17186 ((eq prefer 'future) (if (= cday n1) n1 n2))
17187 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17188 (cond
17189 ((eq prefer 'past) (if (= cday n2) n2 n1))
17190 ((eq prefer 'future) (if (= cday n1) n1 n2))
17191 (t (if (= cday n1) n1 n2)))))))
17193 (defun org-date-to-gregorian (date)
17194 "Turn any specification of DATE into a Gregorian date for the calendar."
17195 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17196 ((and (listp date) (= (length date) 3)) date)
17197 ((stringp date)
17198 (setq date (org-parse-time-string date))
17199 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17200 ((listp date)
17201 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17203 (defun org-parse-time-string (s &optional nodefault)
17204 "Parse the standard Org-mode time string.
17205 This should be a lot faster than the normal `parse-time-string'.
17206 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17207 hour and minute fields will be nil if not given."
17208 (cond ((string-match org-ts-regexp0 s)
17209 (list 0
17210 (if (or (match-beginning 8) (not nodefault))
17211 (string-to-number (or (match-string 8 s) "0")))
17212 (if (or (match-beginning 7) (not nodefault))
17213 (string-to-number (or (match-string 7 s) "0")))
17214 (string-to-number (match-string 4 s))
17215 (string-to-number (match-string 3 s))
17216 (string-to-number (match-string 2 s))
17217 nil nil nil))
17218 ((string-match "^<[^>]+>$" s)
17219 (decode-time (seconds-to-time (org-matcher-time s))))
17220 (t (error "Not a standard Org-mode time string: %s" s))))
17222 (defun org-timestamp-up (&optional arg)
17223 "Increase the date item at the cursor by one.
17224 If the cursor is on the year, change the year. If it is on the month,
17225 the day or the time, change that.
17226 With prefix ARG, change by that many units."
17227 (interactive "p")
17228 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17230 (defun org-timestamp-down (&optional arg)
17231 "Decrease the date item at the cursor by one.
17232 If the cursor is on the year, change the year. If it is on the month,
17233 the day or the time, change that.
17234 With prefix ARG, change by that many units."
17235 (interactive "p")
17236 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17238 (defun org-timestamp-up-day (&optional arg)
17239 "Increase the date in the time stamp by one day.
17240 With prefix ARG, change that many days."
17241 (interactive "p")
17242 (if (and (not (org-at-timestamp-p t))
17243 (org-at-heading-p))
17244 (org-todo 'up)
17245 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17247 (defun org-timestamp-down-day (&optional arg)
17248 "Decrease the date in the time stamp by one day.
17249 With prefix ARG, change that many days."
17250 (interactive "p")
17251 (if (and (not (org-at-timestamp-p t))
17252 (org-at-heading-p))
17253 (org-todo 'down)
17254 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17256 (defun org-at-timestamp-p (&optional inactive-ok)
17257 "Determine if the cursor is in or at a timestamp."
17258 (interactive)
17259 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17260 (pos (point))
17261 (ans (or (looking-at tsr)
17262 (save-excursion
17263 (skip-chars-backward "^[<\n\r\t")
17264 (if (> (point) (point-min)) (backward-char 1))
17265 (and (looking-at tsr)
17266 (> (- (match-end 0) pos) -1))))))
17267 (and ans
17268 (boundp 'org-ts-what)
17269 (setq org-ts-what
17270 (cond
17271 ((= pos (match-beginning 0)) 'bracket)
17272 ;; Point is considered to be "on the bracket" whether
17273 ;; it's really on it or right after it.
17274 ((= pos (1- (match-end 0))) 'bracket)
17275 ((= pos (match-end 0)) 'after)
17276 ((org-pos-in-match-range pos 2) 'year)
17277 ((org-pos-in-match-range pos 3) 'month)
17278 ((org-pos-in-match-range pos 7) 'hour)
17279 ((org-pos-in-match-range pos 8) 'minute)
17280 ((or (org-pos-in-match-range pos 4)
17281 (org-pos-in-match-range pos 5)) 'day)
17282 ((and (> pos (or (match-end 8) (match-end 5)))
17283 (< pos (match-end 0)))
17284 (- pos (or (match-end 8) (match-end 5))))
17285 (t 'day))))
17286 ans))
17288 (defun org-toggle-timestamp-type ()
17289 "Toggle the type (<active> or [inactive]) of a time stamp."
17290 (interactive)
17291 (when (org-at-timestamp-p t)
17292 (let ((beg (match-beginning 0)) (end (match-end 0))
17293 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17294 (save-excursion
17295 (goto-char beg)
17296 (while (re-search-forward "[][<>]" end t)
17297 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17298 t t)))
17299 (message "Timestamp is now %sactive"
17300 (if (equal (char-after beg) ?<) "" "in")))))
17302 (defun org-at-clock-log-p nil
17303 "Is the cursor on the clock log line?"
17304 (save-excursion
17305 (move-beginning-of-line 1)
17306 (looking-at "^[ \t]*CLOCK:")))
17308 (defvar org-clock-history) ; defined in org-clock.el
17309 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17310 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17311 "Change the date in the time stamp at point.
17312 The date will be changed by N times WHAT. WHAT can be `day', `month',
17313 `year', `minute', `second'. If WHAT is not given, the cursor position
17314 in the timestamp determines what will be changed.
17315 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17316 (let ((origin (point)) origin-cat
17317 with-hm inactive
17318 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17319 org-ts-what
17320 extra rem
17321 ts time time0 fixnext clrgx)
17322 (if (not (org-at-timestamp-p t))
17323 (user-error "Not at a timestamp"))
17324 (if (and (not what) (eq org-ts-what 'bracket))
17325 (org-toggle-timestamp-type)
17326 ;; Point isn't on brackets. Remember the part of the time-stamp
17327 ;; the point was in. Indeed, size of time-stamps may change,
17328 ;; but point must be kept in the same category nonetheless.
17329 (setq origin-cat org-ts-what)
17330 (if (and (not what) (not (eq org-ts-what 'day))
17331 org-display-custom-times
17332 (get-text-property (point) 'display)
17333 (not (get-text-property (1- (point)) 'display)))
17334 (setq org-ts-what 'day))
17335 (setq org-ts-what (or what org-ts-what)
17336 inactive (= (char-after (match-beginning 0)) ?\[)
17337 ts (match-string 0))
17338 (replace-match "")
17339 (when (string-match
17340 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17342 (setq extra (match-string 1 ts))
17343 (if suppress-tmp-delay
17344 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17345 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17346 (setq with-hm t))
17347 (setq time0 (org-parse-time-string ts))
17348 (when (and updown
17349 (eq org-ts-what 'minute)
17350 (not current-prefix-arg))
17351 ;; This looks like s-up and s-down. Change by one rounding step.
17352 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17353 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17354 (setcar (cdr time0) (+ (nth 1 time0)
17355 (if (> n 0) (- rem) (- dm rem))))))
17356 (setq time
17357 (encode-time (or (car time0) 0)
17358 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17359 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17360 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17361 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17362 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17363 (nthcdr 6 time0)))
17364 (when (and (member org-ts-what '(hour minute))
17365 extra
17366 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17367 (setq extra (org-modify-ts-extra
17368 extra
17369 (if (eq org-ts-what 'hour) 2 5)
17370 n dm)))
17371 (when (integerp org-ts-what)
17372 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17373 (if (eq what 'calendar)
17374 (let ((cal-date (org-get-date-from-calendar)))
17375 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17376 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17377 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17378 (setcar time0 (or (car time0) 0))
17379 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17380 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17381 (setq time (apply 'encode-time time0))))
17382 ;; Insert the new time-stamp, and ensure point stays in the same
17383 ;; category as before (i.e. not after the last position in that
17384 ;; category).
17385 (let ((pos (point)))
17386 ;; Stay before inserted string. `save-excursion' is of no use.
17387 (setq org-last-changed-timestamp
17388 (org-insert-time-stamp time with-hm inactive nil nil extra))
17389 (goto-char pos))
17390 (save-match-data
17391 (looking-at org-ts-regexp3)
17392 (goto-char (cond
17393 ;; `day' category ends before `hour' if any, or at
17394 ;; the end of the day name.
17395 ((eq origin-cat 'day)
17396 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17397 ((eq origin-cat 'hour) (min (match-end 7) origin))
17398 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17399 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17400 ;; `year' and `month' have both fixed size: point
17401 ;; couldn't have moved into another part.
17402 (t origin))))
17403 ;; Update clock if on a CLOCK line.
17404 (org-clock-update-time-maybe)
17405 ;; Maybe adjust the closest clock in `org-clock-history'
17406 (when org-clock-adjust-closest
17407 (if (not (and (org-at-clock-log-p)
17408 (< 1 (length (delq nil (mapcar 'marker-position
17409 org-clock-history))))))
17410 (message "No clock to adjust")
17411 (cond ((save-excursion ; fix previous clock?
17412 (re-search-backward org-ts-regexp0 nil t)
17413 (org-looking-back (concat org-clock-string " \\[")))
17414 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17415 ((save-excursion ; fix next clock?
17416 (re-search-backward org-ts-regexp0 nil t)
17417 (looking-at (concat org-ts-regexp0 "\\] =>")))
17418 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17419 (save-window-excursion
17420 ;; Find closest clock to point, adjust the previous/next one in history
17421 (let* ((p (save-excursion (org-back-to-heading t)))
17422 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17423 (clfixnth
17424 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17425 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17426 (if (not clfixpos)
17427 (message "No clock to adjust")
17428 (save-excursion
17429 (org-goto-marker-or-bmk clfixpos)
17430 (org-show-subtree)
17431 (when (re-search-forward clrgx nil t)
17432 (goto-char (match-beginning 1))
17433 (let (org-clock-adjust-closest)
17434 (org-timestamp-change n org-ts-what updown))
17435 (message "Clock adjusted in %s for heading: %s"
17436 (file-name-nondirectory (buffer-file-name))
17437 (org-get-heading t t)))))))))
17438 ;; Try to recenter the calendar window, if any.
17439 (if (and org-calendar-follow-timestamp-change
17440 (get-buffer-window "*Calendar*" t)
17441 (memq org-ts-what '(day month year)))
17442 (org-recenter-calendar (time-to-days time))))))
17444 (defun org-modify-ts-extra (s pos n dm)
17445 "Change the different parts of the lead-time and repeat fields in timestamp."
17446 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17447 ng h m new rem)
17448 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17449 (cond
17450 ((or (org-pos-in-match-range pos 2)
17451 (org-pos-in-match-range pos 3))
17452 (setq m (string-to-number (match-string 3 s))
17453 h (string-to-number (match-string 2 s)))
17454 (if (org-pos-in-match-range pos 2)
17455 (setq h (+ h n))
17456 (setq n (* dm (org-no-warnings (signum n))))
17457 (when (not (= 0 (setq rem (% m dm))))
17458 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17459 (setq m (+ m n)))
17460 (if (< m 0) (setq m (+ m 60) h (1- h)))
17461 (if (> m 59) (setq m (- m 60) h (1+ h)))
17462 (setq h (min 24 (max 0 h)))
17463 (setq ng 1 new (format "-%02d:%02d" h m)))
17464 ((org-pos-in-match-range pos 6)
17465 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17466 ((org-pos-in-match-range pos 5)
17467 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17469 ((org-pos-in-match-range pos 9)
17470 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17471 ((org-pos-in-match-range pos 8)
17472 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17474 (when ng
17475 (setq s (concat
17476 (substring s 0 (match-beginning ng))
17478 (substring s (match-end ng))))))
17481 (defun org-recenter-calendar (date)
17482 "If the calendar is visible, recenter it to DATE."
17483 (let ((cwin (get-buffer-window "*Calendar*" t)))
17484 (when cwin
17485 (let ((calendar-move-hook nil))
17486 (with-selected-window cwin
17487 (calendar-goto-date (if (listp date) date
17488 (calendar-gregorian-from-absolute date))))))))
17490 (defun org-goto-calendar (&optional arg)
17491 "Go to the Emacs calendar at the current date.
17492 If there is a time stamp in the current line, go to that date.
17493 A prefix ARG can be used to force the current date."
17494 (interactive "P")
17495 (let ((tsr org-ts-regexp) diff
17496 (calendar-move-hook nil)
17497 (calendar-view-holidays-initially-flag nil)
17498 (calendar-view-diary-initially-flag nil))
17499 (if (or (org-at-timestamp-p)
17500 (save-excursion
17501 (beginning-of-line 1)
17502 (looking-at (concat ".*" tsr))))
17503 (let ((d1 (time-to-days (current-time)))
17504 (d2 (time-to-days
17505 (org-time-string-to-time (match-string 1)))))
17506 (setq diff (- d2 d1))))
17507 (calendar)
17508 (calendar-goto-today)
17509 (if (and diff (not arg)) (calendar-forward-day diff))))
17511 (defun org-get-date-from-calendar ()
17512 "Return a list (month day year) of date at point in calendar."
17513 (with-current-buffer "*Calendar*"
17514 (save-match-data
17515 (calendar-cursor-to-date))))
17517 (defun org-date-from-calendar ()
17518 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17519 If there is already a time stamp at the cursor position, update it."
17520 (interactive)
17521 (if (org-at-timestamp-p t)
17522 (org-timestamp-change 0 'calendar)
17523 (let ((cal-date (org-get-date-from-calendar)))
17524 (org-insert-time-stamp
17525 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17527 (defcustom org-effort-durations
17528 `(("h" . 60)
17529 ("d" . ,(* 60 8))
17530 ("w" . ,(* 60 8 5))
17531 ("m" . ,(* 60 8 5 4))
17532 ("y" . ,(* 60 8 5 40)))
17533 "Conversion factor to minutes for an effort modifier.
17535 Each entry has the form (MODIFIER . MINUTES).
17537 In an effort string, a number followed by MODIFIER is multiplied
17538 by the specified number of MINUTES to obtain an effort in
17539 minutes.
17541 For example, if the value of this variable is ((\"hours\" . 60)), then an
17542 effort string \"2hours\" is equivalent to 120 minutes."
17543 :group 'org-agenda
17544 :version "24.1"
17545 :type '(alist :key-type (string :tag "Modifier")
17546 :value-type (number :tag "Minutes")))
17548 (defun org-minutes-to-clocksum-string (m)
17549 "Format number of minutes as a clocksum string.
17550 The format is determined by `org-time-clocksum-format',
17551 `org-time-clocksum-use-fractional' and
17552 `org-time-clocksum-fractional-format' and
17553 `org-time-clocksum-use-effort-durations'."
17554 (let ((clocksum "")
17555 (m (round m)) ; Don't allow fractions of minutes
17556 h d w mo y fmt n)
17557 (setq h (if org-time-clocksum-use-effort-durations
17558 (cdr (assoc "h" org-effort-durations)) 60)
17559 d (if org-time-clocksum-use-effort-durations
17560 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17561 w (if org-time-clocksum-use-effort-durations
17562 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17563 mo (if org-time-clocksum-use-effort-durations
17564 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17565 y (if org-time-clocksum-use-effort-durations
17566 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17567 ;; fractional format
17568 (if org-time-clocksum-use-fractional
17569 (cond
17570 ;; single format string
17571 ((stringp org-time-clocksum-fractional-format)
17572 (format org-time-clocksum-fractional-format (/ m (float h))))
17573 ;; choice of fractional formats for different time units
17574 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17575 (> (/ (truncate m) (* y d h)) 0))
17576 (format fmt (/ m (* y d (float h)))))
17577 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17578 (> (/ (truncate m) (* mo d h)) 0))
17579 (format fmt (/ m (* mo d (float h)))))
17580 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17581 (> (/ (truncate m) (* w d h)) 0))
17582 (format fmt (/ m (* w d (float h)))))
17583 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17584 (> (/ (truncate m) (* d h)) 0))
17585 (format fmt (/ m (* d (float h)))))
17586 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17587 (> (/ (truncate m) h) 0))
17588 (format fmt (/ m (float h))))
17589 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17590 (format fmt m))
17591 ;; fall back to smallest time unit with a format
17592 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17593 (format fmt (/ m (float h))))
17594 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17595 (format fmt (/ m (* d (float h)))))
17596 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17597 (format fmt (/ m (* w d (float h)))))
17598 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17599 (format fmt (/ m (* mo d (float h)))))
17600 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17601 (format fmt (/ m (* y d (float h))))))
17602 ;; standard (non-fractional) format, with single format string
17603 (if (stringp org-time-clocksum-format)
17604 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17605 ;; separate formats components
17606 (and (setq fmt (plist-get org-time-clocksum-format :years))
17607 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17608 (plist-get org-time-clocksum-format :require-years))
17609 (setq clocksum (concat clocksum (format fmt n))
17610 m (- m (* n y d h))))
17611 (and (setq fmt (plist-get org-time-clocksum-format :months))
17612 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17613 (plist-get org-time-clocksum-format :require-months))
17614 (setq clocksum (concat clocksum (format fmt n))
17615 m (- m (* n mo d h))))
17616 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17617 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17618 (plist-get org-time-clocksum-format :require-weeks))
17619 (setq clocksum (concat clocksum (format fmt n))
17620 m (- m (* n w d h))))
17621 (and (setq fmt (plist-get org-time-clocksum-format :days))
17622 (or (> (setq n (/ (truncate m) (* d h))) 0)
17623 (plist-get org-time-clocksum-format :require-days))
17624 (setq clocksum (concat clocksum (format fmt n))
17625 m (- m (* n d h))))
17626 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17627 (or (> (setq n (/ (truncate m) h)) 0)
17628 (plist-get org-time-clocksum-format :require-hours))
17629 (setq clocksum (concat clocksum (format fmt n))
17630 m (- m (* n h))))
17631 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17632 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17633 (setq clocksum (concat clocksum (format fmt m))))
17634 ;; return formatted time duration
17635 clocksum))))
17637 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17638 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17639 "Org mode version 8.0")
17641 (defun org-hours-to-clocksum-string (n)
17642 (org-minutes-to-clocksum-string (* n 60)))
17644 (defun org-hh:mm-string-to-minutes (s)
17645 "Convert a string H:MM to a number of minutes.
17646 If the string is just a number, interpret it as minutes.
17647 In fact, the first hh:mm or number in the string will be taken,
17648 there can be extra stuff in the string.
17649 If no number is found, the return value is 0."
17650 (cond
17651 ((integerp s) s)
17652 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17653 (+ (* (string-to-number (match-string 1 s)) 60)
17654 (string-to-number (match-string 2 s))))
17655 ((string-match "\\([0-9]+\\)" s)
17656 (string-to-number (match-string 1 s)))
17657 (t 0)))
17659 (defcustom org-image-actual-width t
17660 "Should we use the actual width of images when inlining them?
17662 When set to `t', always use the image width.
17664 When set to a number, use imagemagick (when available) to set
17665 the image's width to this value.
17667 When set to a number in a list, try to get the width from any
17668 #+ATTR.* keyword if it matches a width specification like
17670 #+ATTR_HTML: :width 300px
17672 and fall back on that number if none is found.
17674 When set to nil, try to get the width from an #+ATTR.* keyword
17675 and fall back on the original width if none is found.
17677 This requires Emacs >= 24.1, build with imagemagick support."
17678 :group 'org-appearance
17679 :version "24.4"
17680 :package-version '(Org . "8.0")
17681 :type '(choice
17682 (const :tag "Use the image width" t)
17683 (integer :tag "Use a number of pixels")
17684 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17685 (const :tag "Use #+ATTR* or don't resize" nil)))
17687 (defcustom org-agenda-inhibit-startup nil
17688 "Inhibit startup when preparing agenda buffers.
17689 When this variable is `t' (the default), the initialization of
17690 the Org agenda buffers is inhibited: e.g. the visibility state
17691 is not set, the tables are not re-aligned, etc."
17692 :type 'boolean
17693 :version "24.3"
17694 :group 'org-agenda)
17696 (defcustom org-agenda-ignore-drawer-properties nil
17697 "Avoid updating text properties when building the agenda.
17698 Properties are used to prepare buffers for effort estimates, appointments,
17699 and subtree-local categories.
17700 If you don't use these in the agenda, you can add them to this list and
17701 agenda building will be a bit faster.
17702 The value is a list, with zero or more of the symbols `effort', `appt',
17703 or `category'."
17704 :type '(set :greedy t
17705 (const effort)
17706 (const appt)
17707 (const category))
17708 :version "24.3"
17709 :group 'org-agenda)
17711 (defun org-duration-string-to-minutes (s &optional output-to-string)
17712 "Convert a duration string S to minutes.
17714 A bare number is interpreted as minutes, modifiers can be set by
17715 customizing `org-effort-durations' (which see).
17717 Entries containing a colon are interpreted as H:MM by
17718 `org-hh:mm-string-to-minutes'."
17719 (let ((result 0)
17720 (re (concat "\\([0-9.]+\\) *\\("
17721 (regexp-opt (mapcar 'car org-effort-durations))
17722 "\\)")))
17723 (while (string-match re s)
17724 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17725 (string-to-number (match-string 1 s))))
17726 (setq s (replace-match "" nil t s)))
17727 (setq result (floor result))
17728 (incf result (org-hh:mm-string-to-minutes s))
17729 (if output-to-string (number-to-string result) result)))
17731 ;;;; Files
17733 (defun org-save-all-org-buffers ()
17734 "Save all Org-mode buffers without user confirmation."
17735 (interactive)
17736 (message "Saving all Org-mode buffers...")
17737 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17738 (when (featurep 'org-id) (org-id-locations-save))
17739 (message "Saving all Org-mode buffers... done"))
17741 (defun org-revert-all-org-buffers ()
17742 "Revert all Org-mode buffers.
17743 Prompt for confirmation when there are unsaved changes.
17744 Be sure you know what you are doing before letting this function
17745 overwrite your changes.
17747 This function is useful in a setup where one tracks org files
17748 with a version control system, to revert on one machine after pulling
17749 changes from another. I believe the procedure must be like this:
17751 1. M-x org-save-all-org-buffers
17752 2. Pull changes from the other machine, resolve conflicts
17753 3. M-x org-revert-all-org-buffers"
17754 (interactive)
17755 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17756 (user-error "Abort"))
17757 (save-excursion
17758 (save-window-excursion
17759 (mapc
17760 (lambda (b)
17761 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17762 (with-current-buffer b buffer-file-name))
17763 (org-pop-to-buffer-same-window b)
17764 (revert-buffer t 'no-confirm)))
17765 (buffer-list))
17766 (when (and (featurep 'org-id) org-id-track-globally)
17767 (org-id-locations-load)))))
17769 ;;;; Agenda files
17771 ;;;###autoload
17772 (defun org-switchb (&optional arg)
17773 "Switch between Org buffers.
17774 With one prefix argument, restrict available buffers to files.
17775 With two prefix arguments, restrict available buffers to agenda files.
17777 Defaults to `iswitchb' for buffer name completion.
17778 Set `org-completion-use-ido' to make it use ido instead."
17779 (interactive "P")
17780 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17781 ((equal arg '(16)) (org-buffer-list 'agenda))
17782 (t (org-buffer-list))))
17783 (org-completion-use-iswitchb org-completion-use-iswitchb)
17784 (org-completion-use-ido org-completion-use-ido))
17785 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17786 (setq org-completion-use-iswitchb t))
17787 (org-pop-to-buffer-same-window
17788 (org-icompleting-read "Org buffer: "
17789 (mapcar 'list (mapcar 'buffer-name blist))
17790 nil t))))
17792 ;;; Define some older names previously used for this functionality
17793 ;;;###autoload
17794 (defalias 'org-ido-switchb 'org-switchb)
17795 ;;;###autoload
17796 (defalias 'org-iswitchb 'org-switchb)
17798 (defun org-buffer-list (&optional predicate exclude-tmp)
17799 "Return a list of Org buffers.
17800 PREDICATE can be `export', `files' or `agenda'.
17802 export restrict the list to Export buffers.
17803 files restrict the list to buffers visiting Org files.
17804 agenda restrict the list to buffers visiting agenda files.
17806 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17807 (let* ((bfn nil)
17808 (agenda-files (and (eq predicate 'agenda)
17809 (mapcar 'file-truename (org-agenda-files t))))
17810 (filter
17811 (cond
17812 ((eq predicate 'files)
17813 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17814 ((eq predicate 'export)
17815 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17816 ((eq predicate 'agenda)
17817 (lambda (b)
17818 (with-current-buffer b
17819 (and (derived-mode-p 'org-mode)
17820 (setq bfn (buffer-file-name b))
17821 (member (file-truename bfn) agenda-files)))))
17822 (t (lambda (b) (with-current-buffer b
17823 (or (derived-mode-p 'org-mode)
17824 (string-match "\*Org .*Export"
17825 (buffer-name b)))))))))
17826 (delq nil
17827 (mapcar
17828 (lambda(b)
17829 (if (and (funcall filter b)
17830 (or (not exclude-tmp)
17831 (not (string-match "tmp" (buffer-name b)))))
17833 nil))
17834 (buffer-list)))))
17836 (defun org-agenda-files (&optional unrestricted archives)
17837 "Get the list of agenda files.
17838 Optional UNRESTRICTED means return the full list even if a restriction
17839 is currently in place.
17840 When ARCHIVES is t, include all archive files that are really being
17841 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17842 `org-agenda-archives-mode' is t."
17843 (let ((files
17844 (cond
17845 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17846 ((stringp org-agenda-files) (org-read-agenda-file-list))
17847 ((listp org-agenda-files) org-agenda-files)
17848 (t (error "Invalid value of `org-agenda-files'")))))
17849 (setq files (apply 'append
17850 (mapcar (lambda (f)
17851 (if (file-directory-p f)
17852 (directory-files
17853 f t org-agenda-file-regexp)
17854 (list f)))
17855 files)))
17856 (when org-agenda-skip-unavailable-files
17857 (setq files (delq nil
17858 (mapcar (function
17859 (lambda (file)
17860 (and (file-readable-p file) file)))
17861 files))))
17862 (when (or (eq archives t)
17863 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17864 (setq files (org-add-archive-files files)))
17865 files))
17867 (defun org-agenda-file-p (&optional file)
17868 "Return non-nil, if FILE is an agenda file.
17869 If FILE is omitted, use the file associated with the current
17870 buffer."
17871 (member (or file (buffer-file-name))
17872 (org-agenda-files t)))
17874 (defun org-edit-agenda-file-list ()
17875 "Edit the list of agenda files.
17876 Depending on setup, this either uses customize to edit the variable
17877 `org-agenda-files', or it visits the file that is holding the list. In the
17878 latter case, the buffer is set up in a way that saving it automatically kills
17879 the buffer and restores the previous window configuration."
17880 (interactive)
17881 (if (stringp org-agenda-files)
17882 (let ((cw (current-window-configuration)))
17883 (find-file org-agenda-files)
17884 (org-set-local 'org-window-configuration cw)
17885 (org-add-hook 'after-save-hook
17886 (lambda ()
17887 (set-window-configuration
17888 (prog1 org-window-configuration
17889 (kill-buffer (current-buffer))))
17890 (org-install-agenda-files-menu)
17891 (message "New agenda file list installed"))
17892 nil 'local)
17893 (message "%s" (substitute-command-keys
17894 "Edit list and finish with \\[save-buffer]")))
17895 (customize-variable 'org-agenda-files)))
17897 (defun org-store-new-agenda-file-list (list)
17898 "Set new value for the agenda file list and save it correctly."
17899 (if (stringp org-agenda-files)
17900 (let ((fe (org-read-agenda-file-list t)) b u)
17901 (while (setq b (find-buffer-visiting org-agenda-files))
17902 (kill-buffer b))
17903 (with-temp-file org-agenda-files
17904 (insert
17905 (mapconcat
17906 (lambda (f) ;; Keep un-expanded entries.
17907 (if (setq u (assoc f fe))
17908 (cdr u)
17910 list "\n")
17911 "\n")))
17912 (let ((org-mode-hook nil) (org-inhibit-startup t)
17913 (org-insert-mode-line-in-empty-file nil))
17914 (setq org-agenda-files list)
17915 (customize-save-variable 'org-agenda-files org-agenda-files))))
17917 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17918 "Read the list of agenda files from a file.
17919 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17920 filenames, used by `org-store-new-agenda-file-list' to write back
17921 un-expanded file names."
17922 (when (file-directory-p org-agenda-files)
17923 (error "`org-agenda-files' cannot be a single directory"))
17924 (when (stringp org-agenda-files)
17925 (with-temp-buffer
17926 (insert-file-contents org-agenda-files)
17927 (mapcar
17928 (lambda (f)
17929 (let ((e (expand-file-name (substitute-in-file-name f)
17930 org-directory)))
17931 (if pair-with-expansion
17932 (cons e f)
17933 e)))
17934 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17936 ;;;###autoload
17937 (defun org-cycle-agenda-files ()
17938 "Cycle through the files in `org-agenda-files'.
17939 If the current buffer visits an agenda file, find the next one in the list.
17940 If the current buffer does not, find the first agenda file."
17941 (interactive)
17942 (let* ((fs (org-agenda-files t))
17943 (files (append fs (list (car fs))))
17944 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17945 file)
17946 (unless files (user-error "No agenda files"))
17947 (catch 'exit
17948 (while (setq file (pop files))
17949 (if (equal (file-truename file) tcf)
17950 (when (car files)
17951 (find-file (car files))
17952 (throw 'exit t))))
17953 (find-file (car fs)))
17954 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17956 (defun org-agenda-file-to-front (&optional to-end)
17957 "Move/add the current file to the top of the agenda file list.
17958 If the file is not present in the list, it is added to the front. If it is
17959 present, it is moved there. With optional argument TO-END, add/move to the
17960 end of the list."
17961 (interactive "P")
17962 (let ((org-agenda-skip-unavailable-files nil)
17963 (file-alist (mapcar (lambda (x)
17964 (cons (file-truename x) x))
17965 (org-agenda-files t)))
17966 (ctf (file-truename
17967 (or buffer-file-name
17968 (user-error "Please save the current buffer to a file"))))
17969 x had)
17970 (setq x (assoc ctf file-alist) had x)
17972 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17973 (if to-end
17974 (setq file-alist (append (delq x file-alist) (list x)))
17975 (setq file-alist (cons x (delq x file-alist))))
17976 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17977 (org-install-agenda-files-menu)
17978 (message "File %s to %s of agenda file list"
17979 (if had "moved" "added") (if to-end "end" "front"))))
17981 (defun org-remove-file (&optional file)
17982 "Remove current file from the list of files in variable `org-agenda-files'.
17983 These are the files which are being checked for agenda entries.
17984 Optional argument FILE means use this file instead of the current."
17985 (interactive)
17986 (let* ((org-agenda-skip-unavailable-files nil)
17987 (file (or file buffer-file-name
17988 (user-error "Current buffer does not visit a file")))
17989 (true-file (file-truename file))
17990 (afile (abbreviate-file-name file))
17991 (files (delq nil (mapcar
17992 (lambda (x)
17993 (if (equal true-file
17994 (file-truename x))
17995 nil x))
17996 (org-agenda-files t)))))
17997 (if (not (= (length files) (length (org-agenda-files t))))
17998 (progn
17999 (org-store-new-agenda-file-list files)
18000 (org-install-agenda-files-menu)
18001 (message "Removed file: %s" afile))
18002 (message "File was not in list: %s (not removed)" afile))))
18004 (defun org-file-menu-entry (file)
18005 (vector file (list 'find-file file) t))
18007 (defun org-check-agenda-file (file)
18008 "Make sure FILE exists. If not, ask user what to do."
18009 (when (not (file-exists-p file))
18010 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18011 (abbreviate-file-name file))
18012 (let ((r (downcase (read-char-exclusive))))
18013 (cond
18014 ((equal r ?r)
18015 (org-remove-file file)
18016 (throw 'nextfile t))
18017 (t (error "Abort"))))))
18019 (defun org-get-agenda-file-buffer (file)
18020 "Get a buffer visiting FILE. If the buffer needs to be created, add
18021 it to the list of buffers which might be released later."
18022 (let ((buf (org-find-base-buffer-visiting file)))
18023 (if buf
18024 buf ; just return it
18025 ;; Make a new buffer and remember it
18026 (setq buf (find-file-noselect file))
18027 (if buf (push buf org-agenda-new-buffers))
18028 buf)))
18030 (defun org-release-buffers (blist)
18031 "Release all buffers in list, asking the user for confirmation when needed.
18032 When a buffer is unmodified, it is just killed. When modified, it is saved
18033 \(if the user agrees) and then killed."
18034 (let (buf file)
18035 (while (setq buf (pop blist))
18036 (setq file (buffer-file-name buf))
18037 (when (and (buffer-modified-p buf)
18038 file
18039 (y-or-n-p (format "Save file %s? " file)))
18040 (with-current-buffer buf (save-buffer)))
18041 (kill-buffer buf))))
18043 (defun org-agenda-prepare-buffers (files)
18044 "Create buffers for all agenda files, protect archived trees and comments."
18045 (interactive)
18046 (let ((pa '(:org-archived t))
18047 (pc '(:org-comment t))
18048 (pall '(:org-archived t :org-comment t))
18049 (inhibit-read-only t)
18050 (org-inhibit-startup org-agenda-inhibit-startup)
18051 (rea (concat ":" org-archive-tag ":"))
18052 file re)
18053 (setq org-tag-alist-for-agenda nil
18054 org-tag-groups-alist-for-agenda nil)
18055 (save-excursion
18056 (save-restriction
18057 (while (setq file (pop files))
18058 (catch 'nextfile
18059 (if (bufferp file)
18060 (set-buffer file)
18061 (org-check-agenda-file file)
18062 (set-buffer (org-get-agenda-file-buffer file)))
18063 (widen)
18064 (org-set-regexps-and-options-for-tags)
18065 (goto-char (point-min))
18066 (let ((case-fold-search t))
18067 (when (search-forward "#+setupfile" nil t)
18068 ;; Don't set all regexps and options systematically as
18069 ;; this is only run for setting agenda tags from setup
18070 ;; file
18071 (org-set-regexps-and-options)))
18072 (or (memq 'category org-agenda-ignore-drawer-properties)
18073 (org-refresh-category-properties))
18074 (or (memq 'effort org-agenda-ignore-drawer-properties)
18075 (org-refresh-properties org-effort-property 'org-effort))
18076 (or (memq 'appt org-agenda-ignore-drawer-properties)
18077 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18078 (setq org-todo-keywords-for-agenda
18079 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18080 (setq org-done-keywords-for-agenda
18081 (append org-done-keywords-for-agenda org-done-keywords))
18082 (setq org-todo-keyword-alist-for-agenda
18083 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18084 (setq org-drawers-for-agenda
18085 (append org-drawers-for-agenda org-drawers))
18086 (setq org-tag-alist-for-agenda
18087 (org-uniquify
18088 (append org-tag-alist-for-agenda
18089 org-tag-alist
18090 org-tag-persistent-alist)))
18091 (if org-group-tags
18092 (setq org-tag-groups-alist-for-agenda
18093 (org-uniquify-alist
18094 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18095 (org-with-silent-modifications
18096 (save-excursion
18097 (remove-text-properties (point-min) (point-max) pall)
18098 (when org-agenda-skip-archived-trees
18099 (goto-char (point-min))
18100 (while (re-search-forward rea nil t)
18101 (if (org-at-heading-p t)
18102 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18103 (goto-char (point-min))
18104 (setq re (format org-heading-keyword-regexp-format
18105 org-comment-string))
18106 (while (re-search-forward re nil t)
18107 (add-text-properties
18108 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18109 (setq org-todo-keywords-for-agenda
18110 (org-uniquify org-todo-keywords-for-agenda))
18111 (setq org-todo-keyword-alist-for-agenda
18112 (org-uniquify org-todo-keyword-alist-for-agenda))))
18115 ;;;; CDLaTeX minor mode
18117 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18118 "Keymap for the minor `org-cdlatex-mode'.")
18120 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18121 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18122 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18123 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18124 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18126 (defvar org-cdlatex-texmathp-advice-is-done nil
18127 "Flag remembering if we have applied the advice to texmathp already.")
18129 (define-minor-mode org-cdlatex-mode
18130 "Toggle the minor `org-cdlatex-mode'.
18131 This mode supports entering LaTeX environment and math in LaTeX fragments
18132 in Org-mode.
18133 \\{org-cdlatex-mode-map}"
18134 nil " OCDL" nil
18135 (when org-cdlatex-mode
18136 (require 'cdlatex)
18137 (run-hooks 'cdlatex-mode-hook)
18138 (cdlatex-compute-tables))
18139 (unless org-cdlatex-texmathp-advice-is-done
18140 (setq org-cdlatex-texmathp-advice-is-done t)
18141 (defadvice texmathp (around org-math-always-on activate)
18142 "Always return t in org-mode buffers.
18143 This is because we want to insert math symbols without dollars even outside
18144 the LaTeX math segments. If Orgmode thinks that point is actually inside
18145 an embedded LaTeX fragment, let texmathp do its job.
18146 \\[org-cdlatex-mode-map]"
18147 (interactive)
18148 (let (p)
18149 (cond
18150 ((not (derived-mode-p 'org-mode)) ad-do-it)
18151 ((eq this-command 'cdlatex-math-symbol)
18152 (setq ad-return-value t
18153 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18155 (let ((p (org-inside-LaTeX-fragment-p)))
18156 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18157 (setq ad-return-value t
18158 texmathp-why '("Org-mode embedded math" . 0))
18159 (if p ad-do-it)))))))))
18161 (defun turn-on-org-cdlatex ()
18162 "Unconditionally turn on `org-cdlatex-mode'."
18163 (org-cdlatex-mode 1))
18165 (defun org-try-cdlatex-tab ()
18166 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18167 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18168 - inside a LaTeX fragment, or
18169 - after the first word in a line, where an abbreviation expansion could
18170 insert a LaTeX environment."
18171 (when org-cdlatex-mode
18172 (cond
18173 ;; Before any word on the line: No expansion possible.
18174 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18175 ;; Just after first word on the line: Expand it. Make sure it
18176 ;; cannot happen on headlines, though.
18177 ((save-excursion
18178 (skip-chars-backward "a-zA-Z0-9*")
18179 (skip-chars-backward " \t")
18180 (and (bolp) (not (org-at-heading-p))))
18181 (cdlatex-tab) t)
18182 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18184 (defun org-cdlatex-underscore-caret (&optional arg)
18185 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18186 Revert to the normal definition outside of these fragments."
18187 (interactive "P")
18188 (if (org-inside-LaTeX-fragment-p)
18189 (call-interactively 'cdlatex-sub-superscript)
18190 (let (org-cdlatex-mode)
18191 (call-interactively (key-binding (vector last-input-event))))))
18193 (defun org-cdlatex-math-modify (&optional arg)
18194 "Execute `cdlatex-math-modify' in LaTeX fragments.
18195 Revert to the normal definition outside of these fragments."
18196 (interactive "P")
18197 (if (org-inside-LaTeX-fragment-p)
18198 (call-interactively 'cdlatex-math-modify)
18199 (let (org-cdlatex-mode)
18200 (call-interactively (key-binding (vector last-input-event))))))
18204 ;;;; LaTeX fragments
18206 (defvar org-latex-regexps
18207 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18208 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18209 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18210 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18211 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18212 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18213 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18214 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18215 "Regular expressions for matching embedded LaTeX.")
18217 (defun org-inside-LaTeX-fragment-p ()
18218 "Test if point is inside a LaTeX fragment.
18219 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18220 sequence appearing also before point.
18221 Even though the matchers for math are configurable, this function assumes
18222 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18223 delimiters are skipped when they have been removed by customization.
18224 The return value is nil, or a cons cell with the delimiter and the
18225 position of this delimiter.
18227 This function does a reasonably good job, but can locally be fooled by
18228 for example currency specifications. For example it will assume being in
18229 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18230 fragments that are properly closed, but during editing, we have to live
18231 with the uncertainty caused by missing closing delimiters. This function
18232 looks only before point, not after."
18233 (catch 'exit
18234 (let ((pos (point))
18235 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18236 (lim (progn
18237 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18238 (point)))
18239 dd-on str (start 0) m re)
18240 (goto-char pos)
18241 (when dodollar
18242 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18243 re (nth 1 (assoc "$" org-latex-regexps)))
18244 (while (string-match re str start)
18245 (cond
18246 ((= (match-end 0) (length str))
18247 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18248 ((= (match-end 0) (- (length str) 5))
18249 (throw 'exit nil))
18250 (t (setq start (match-end 0))))))
18251 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18252 (goto-char pos)
18253 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18254 (and (match-beginning 2) (throw 'exit nil))
18255 ;; count $$
18256 (while (re-search-backward "\\$\\$" lim t)
18257 (setq dd-on (not dd-on)))
18258 (goto-char pos)
18259 (if dd-on (cons "$$" m))))))
18261 (defun org-inside-latex-macro-p ()
18262 "Is point inside a LaTeX macro or its arguments?"
18263 (save-match-data
18264 (org-in-regexp
18265 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18267 (defvar org-latex-fragment-image-overlays nil
18268 "List of overlays carrying the images of latex fragments.")
18269 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18271 (defun org-remove-latex-fragment-image-overlays ()
18272 "Remove all overlays with LaTeX fragment images in current buffer."
18273 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18274 (setq org-latex-fragment-image-overlays nil))
18276 (defun org-preview-latex-fragment (&optional subtree)
18277 "Preview the LaTeX fragment at point, or all locally or globally.
18278 If the cursor is in a LaTeX fragment, create the image and overlay
18279 it over the source code. If there is no fragment at point, display
18280 all fragments in the current text, from one headline to the next. With
18281 prefix SUBTREE, display all fragments in the current subtree. With a
18282 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18283 the cursor is before the first headline,
18284 display all fragments in the buffer.
18285 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18286 (interactive "P")
18287 (unless buffer-file-name
18288 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18289 (when (display-graphic-p)
18290 (org-remove-latex-fragment-image-overlays)
18291 (save-excursion
18292 (save-restriction
18293 (let (beg end at msg)
18294 (cond
18295 ((or (equal subtree '(16))
18296 (not (save-excursion
18297 (re-search-backward org-outline-regexp-bol nil t))))
18298 (setq beg (point-min) end (point-max)
18299 msg "Creating images for buffer...%s"))
18300 ((equal subtree '(4))
18301 (org-back-to-heading)
18302 (setq beg (point) end (org-end-of-subtree t)
18303 msg "Creating images for subtree...%s"))
18305 (if (setq at (org-inside-LaTeX-fragment-p))
18306 (goto-char (max (point-min) (- (cdr at) 2)))
18307 (org-back-to-heading))
18308 (setq beg (point) end (progn (outline-next-heading) (point))
18309 msg (if at "Creating image...%s"
18310 "Creating images for entry...%s"))))
18311 (message msg "")
18312 (narrow-to-region beg end)
18313 (goto-char beg)
18314 (org-format-latex
18315 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18316 (file-name-nondirectory
18317 buffer-file-name)))
18318 default-directory 'overlays msg at 'forbuffer
18319 org-latex-create-formula-image-program)
18320 (message msg "done. Use `C-c C-c' to remove images."))))))
18322 (defun org-format-latex (prefix &optional dir overlays msg at
18323 forbuffer processing-type)
18324 "Replace LaTeX fragments with links to an image, and produce images.
18325 Some of the options can be changed using the variable
18326 `org-format-latex-options'."
18327 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18328 (let* ((prefixnodir (file-name-nondirectory prefix))
18329 (absprefix (expand-file-name prefix dir))
18330 (todir (file-name-directory absprefix))
18331 (opt org-format-latex-options)
18332 (optnew org-format-latex-options)
18333 (matchers (plist-get opt :matchers))
18334 (re-list org-latex-regexps)
18335 (cnt 0) txt hash link beg end re e checkdir
18336 string
18337 m n block-type block linkfile movefile ov)
18338 ;; Check the different regular expressions
18339 (while (setq e (pop re-list))
18340 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18341 block (if block-type "\n\n" ""))
18342 (when (member m matchers)
18343 (goto-char (point-min))
18344 (while (re-search-forward re nil t)
18345 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18346 (or (not overlays)
18347 (not (eq (get-char-property (match-beginning n)
18348 'org-overlay-type)
18349 'org-latex-overlay))))
18350 (cond
18351 ((eq processing-type 'verbatim))
18352 ((eq processing-type 'mathjax)
18353 ;; Prepare for MathJax processing.
18354 (setq string (match-string n))
18355 (when (member m '("$" "$1"))
18356 (save-excursion
18357 (delete-region (match-beginning n) (match-end n))
18358 (goto-char (match-beginning n))
18359 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18360 ((or (eq processing-type 'dvipng)
18361 (eq processing-type 'imagemagick))
18362 ;; Process to an image.
18363 (setq txt (match-string n)
18364 beg (match-beginning n) end (match-end n)
18365 cnt (1+ cnt))
18366 (let ((face (face-at-point))
18367 (fg (plist-get opt :foreground))
18368 (bg (plist-get opt :background))
18369 ;; Ensure full list is printed.
18370 print-length print-level)
18371 (when forbuffer
18372 ;; Get the colors from the face at point.
18373 (goto-char beg)
18374 (when (eq fg 'auto)
18375 (setq fg (face-attribute face :foreground nil 'default)))
18376 (when (eq bg 'auto)
18377 (setq bg (face-attribute face :background nil 'default)))
18378 (setq optnew (copy-sequence opt))
18379 (plist-put optnew :foreground fg)
18380 (plist-put optnew :background bg))
18381 (setq hash (sha1 (prin1-to-string
18382 (list org-format-latex-header
18383 org-latex-default-packages-alist
18384 org-latex-packages-alist
18385 org-format-latex-options
18386 forbuffer txt fg bg)))
18387 linkfile (format "%s_%s.png" prefix hash)
18388 movefile (format "%s_%s.png" absprefix hash)))
18389 (setq link (concat block "[[file:" linkfile "]]" block))
18390 (if msg (message msg cnt))
18391 (goto-char beg)
18392 (unless checkdir ; Ensure the directory exists.
18393 (setq checkdir t)
18394 (or (file-directory-p todir) (make-directory todir t)))
18395 (unless (file-exists-p movefile)
18396 (org-create-formula-image
18397 txt movefile optnew forbuffer processing-type))
18398 (if overlays
18399 (progn
18400 (mapc (lambda (o)
18401 (if (eq (overlay-get o 'org-overlay-type)
18402 'org-latex-overlay)
18403 (delete-overlay o)))
18404 (overlays-in beg end))
18405 (setq ov (make-overlay beg end))
18406 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18407 (if (featurep 'xemacs)
18408 (progn
18409 (overlay-put ov 'invisible t)
18410 (overlay-put
18411 ov 'end-glyph
18412 (make-glyph (vector 'png :file movefile))))
18413 (overlay-put
18414 ov 'display
18415 (list 'image :type 'png :file movefile :ascent 'center)))
18416 (push ov org-latex-fragment-image-overlays)
18417 (goto-char end))
18418 (delete-region beg end)
18419 (insert (org-add-props link
18420 (list 'org-latex-src
18421 (replace-regexp-in-string
18422 "\"" "" txt)
18423 'org-latex-src-embed-type
18424 (if block-type 'paragraph 'character))))))
18425 ((eq processing-type 'mathml)
18426 ;; Process to MathML
18427 (unless (save-match-data (org-format-latex-mathml-available-p))
18428 (user-error "LaTeX to MathML converter not configured"))
18429 (setq txt (match-string n)
18430 beg (match-beginning n) end (match-end n)
18431 cnt (1+ cnt))
18432 (if msg (message msg cnt))
18433 (goto-char beg)
18434 (delete-region beg end)
18435 (insert (org-format-latex-as-mathml
18436 txt block-type prefix dir)))
18438 (error "Unknown conversion type %s for LaTeX fragments"
18439 processing-type)))))))))
18441 (defun org-create-math-formula (latex-frag &optional mathml-file)
18442 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18443 Use `org-latex-to-mathml-convert-command'. If the conversion is
18444 sucessful, return the portion between \"<math...> </math>\"
18445 elements otherwise return nil. When MATHML-FILE is specified,
18446 write the results in to that file. When invoked as an
18447 interactive command, prompt for LATEX-FRAG, with initial value
18448 set to the current active region and echo the results for user
18449 inspection."
18450 (interactive (list (let ((frag (when (org-region-active-p)
18451 (buffer-substring-no-properties
18452 (region-beginning) (region-end)))))
18453 (read-string "LaTeX Fragment: " frag nil frag))))
18454 (unless latex-frag (error "Invalid LaTeX fragment"))
18455 (let* ((tmp-in-file (file-relative-name
18456 (make-temp-name (expand-file-name "ltxmathml-in"))))
18457 (ignore (write-region latex-frag nil tmp-in-file))
18458 (tmp-out-file (file-relative-name
18459 (make-temp-name (expand-file-name "ltxmathml-out"))))
18460 (cmd (format-spec
18461 org-latex-to-mathml-convert-command
18462 `((?j . ,(shell-quote-argument
18463 (expand-file-name org-latex-to-mathml-jar-file)))
18464 (?I . ,(shell-quote-argument tmp-in-file))
18465 (?o . ,(shell-quote-argument tmp-out-file)))))
18466 mathml shell-command-output)
18467 (when (org-called-interactively-p 'any)
18468 (unless (org-format-latex-mathml-available-p)
18469 (user-error "LaTeX to MathML converter not configured")))
18470 (message "Running %s" cmd)
18471 (setq shell-command-output (shell-command-to-string cmd))
18472 (setq mathml
18473 (when (file-readable-p tmp-out-file)
18474 (with-current-buffer (find-file-noselect tmp-out-file t)
18475 (goto-char (point-min))
18476 (when (re-search-forward
18477 (concat
18478 (regexp-quote
18479 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18480 "\\(.\\|\n\\)*"
18481 (regexp-quote "</math>")) nil t)
18482 (prog1 (match-string 0) (kill-buffer))))))
18483 (cond
18484 (mathml
18485 (setq mathml
18486 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18487 (when mathml-file
18488 (write-region mathml nil mathml-file))
18489 (when (org-called-interactively-p 'any)
18490 (message mathml)))
18491 ((message "LaTeX to MathML conversion failed")
18492 (message shell-command-output)))
18493 (delete-file tmp-in-file)
18494 (when (file-exists-p tmp-out-file)
18495 (delete-file tmp-out-file))
18496 mathml))
18498 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18499 prefix &optional dir)
18500 "Use `org-create-math-formula' but check local cache first."
18501 (let* ((absprefix (expand-file-name prefix dir))
18502 (print-length nil) (print-level nil)
18503 (formula-id (concat
18504 "formula-"
18505 (sha1
18506 (prin1-to-string
18507 (list latex-frag
18508 org-latex-to-mathml-convert-command)))))
18509 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18510 (formula-cache-dir (file-name-directory formula-cache)))
18512 (unless (file-directory-p formula-cache-dir)
18513 (make-directory formula-cache-dir t))
18515 (unless (file-exists-p formula-cache)
18516 (org-create-math-formula latex-frag formula-cache))
18518 (if (file-exists-p formula-cache)
18519 ;; Successful conversion. Return the link to MathML file.
18520 (org-add-props
18521 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18522 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18523 'org-latex-src-embed-type (if latex-frag-type
18524 'paragraph 'character)))
18525 ;; Failed conversion. Return the LaTeX fragment verbatim
18526 latex-frag)))
18528 (defun org-create-formula-image (string tofile options buffer &optional type)
18529 "Create an image from LaTeX source using dvipng or convert.
18530 This function calls either `org-create-formula-image-with-dvipng'
18531 or `org-create-formula-image-with-imagemagick' depending on the
18532 value of `org-latex-create-formula-image-program' or on the value
18533 of the optional TYPE variable.
18535 Note: ultimately these two function should be combined as they
18536 share a good deal of logic."
18537 (org-check-external-command
18538 "latex" "needed to convert LaTeX fragments to images")
18539 (funcall
18540 (case (or type org-latex-create-formula-image-program)
18541 ('dvipng
18542 (org-check-external-command
18543 "dvipng" "needed to convert LaTeX fragments to images")
18544 #'org-create-formula-image-with-dvipng)
18545 ('imagemagick
18546 (org-check-external-command
18547 "convert" "you need to install imagemagick")
18548 #'org-create-formula-image-with-imagemagick)
18549 (t (error
18550 "Invalid value of `org-latex-create-formula-image-program'")))
18551 string tofile options buffer))
18553 (declare-function org-export-get-backend "ox" (name))
18554 (declare-function org-export--get-global-options "ox" (&optional backend))
18555 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18556 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18557 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18558 (defun org-create-formula--latex-header ()
18559 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18560 (let ((info (org-combine-plists (org-export--get-global-options
18561 (org-export-get-backend 'latex))
18562 (org-export--get-inbuffer-options
18563 (org-export-get-backend 'latex)))))
18564 (org-latex-guess-babel-language
18565 (org-latex-guess-inputenc
18566 (org-splice-latex-header
18567 org-format-latex-header
18568 org-latex-default-packages-alist
18569 org-latex-packages-alist t
18570 (plist-get info :latex-header)))
18571 info)))
18573 ;; This function borrows from Ganesh Swami's latex2png.el
18574 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18575 "This calls dvipng."
18576 (require 'ox-latex)
18577 (let* ((tmpdir (if (featurep 'xemacs)
18578 (temp-directory)
18579 temporary-file-directory))
18580 (texfilebase (make-temp-name
18581 (expand-file-name "orgtex" tmpdir)))
18582 (texfile (concat texfilebase ".tex"))
18583 (dvifile (concat texfilebase ".dvi"))
18584 (pngfile (concat texfilebase ".png"))
18585 (fnh (if (featurep 'xemacs)
18586 (font-height (face-font 'default))
18587 (face-attribute 'default :height nil)))
18588 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18589 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18590 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18591 "Black"))
18592 (bg (or (plist-get options (if buffer :background :html-background))
18593 "Transparent")))
18594 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18595 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18596 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18597 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18598 (let ((latex-header (org-create-formula--latex-header)))
18599 (with-temp-file texfile
18600 (insert latex-header)
18601 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18602 (let ((dir default-directory))
18603 (condition-case nil
18604 (progn
18605 (cd tmpdir)
18606 (call-process "latex" nil nil nil texfile))
18607 (error nil))
18608 (cd dir))
18609 (if (not (file-exists-p dvifile))
18610 (progn (message "Failed to create dvi file from %s" texfile) nil)
18611 (condition-case nil
18612 (if (featurep 'xemacs)
18613 (call-process "dvipng" nil nil nil
18614 "-fg" fg "-bg" bg
18615 "-T" "tight"
18616 "-o" pngfile
18617 dvifile)
18618 (call-process "dvipng" nil nil nil
18619 "-fg" fg "-bg" bg
18620 "-D" dpi
18621 ;;"-x" scale "-y" scale
18622 "-T" "tight"
18623 "-o" pngfile
18624 dvifile))
18625 (error nil))
18626 (if (not (file-exists-p pngfile))
18627 (if org-format-latex-signal-error
18628 (error "Failed to create png file from %s" texfile)
18629 (message "Failed to create png file from %s" texfile)
18630 nil)
18631 ;; Use the requested file name and clean up
18632 (copy-file pngfile tofile 'replace)
18633 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18634 (if (file-exists-p (concat texfilebase e))
18635 (delete-file (concat texfilebase e))))
18636 pngfile))))
18638 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18639 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18640 "This calls convert, which is included into imagemagick."
18641 (require 'ox-latex)
18642 (let* ((tmpdir (if (featurep 'xemacs)
18643 (temp-directory)
18644 temporary-file-directory))
18645 (texfilebase (make-temp-name
18646 (expand-file-name "orgtex" tmpdir)))
18647 (texfile (concat texfilebase ".tex"))
18648 (pdffile (concat texfilebase ".pdf"))
18649 (pngfile (concat texfilebase ".png"))
18650 (fnh (if (featurep 'xemacs)
18651 (font-height (face-font 'default))
18652 (face-attribute 'default :height nil)))
18653 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18654 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18655 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18656 "black"))
18657 (bg (or (plist-get options (if buffer :background :html-background))
18658 "white")))
18659 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18660 (setq fg (org-latex-color-format fg)))
18661 (if (eq bg 'default) (setq bg (org-latex-color :background))
18662 (setq bg (org-latex-color-format
18663 (if (string= bg "Transparent") "white" bg))))
18664 (let ((latex-header (org-create-formula--latex-header)))
18665 (with-temp-file texfile
18666 (insert latex-header)
18667 (insert "\n\\begin{document}\n"
18668 "\\definecolor{fg}{rgb}{" fg "}\n"
18669 "\\definecolor{bg}{rgb}{" bg "}\n"
18670 "\n\\pagecolor{bg}\n"
18671 "\n{\\color{fg}\n"
18672 string
18673 "\n}\n"
18674 "\n\\end{document}\n")))
18675 (org-latex-compile texfile t)
18676 (if (not (file-exists-p pdffile))
18677 (progn (message "Failed to create pdf file from %s" texfile) nil)
18678 (condition-case nil
18679 (if (featurep 'xemacs)
18680 (call-process "convert" nil nil nil
18681 "-density" "96"
18682 "-trim"
18683 "-antialias"
18684 pdffile
18685 "-quality" "100"
18686 ;; "-sharpen" "0x1.0"
18687 pngfile)
18688 (call-process "convert" nil nil nil
18689 "-density" dpi
18690 "-trim"
18691 "-antialias"
18692 pdffile
18693 "-quality" "100"
18694 ;; "-sharpen" "0x1.0"
18695 pngfile))
18696 (error nil))
18697 (if (not (file-exists-p pngfile))
18698 (if org-format-latex-signal-error
18699 (error "Failed to create png file from %s" texfile)
18700 (message "Failed to create png file from %s" texfile)
18701 nil)
18702 ;; Use the requested file name and clean up
18703 (copy-file pngfile tofile 'replace)
18704 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18705 (if (file-exists-p (concat texfilebase e))
18706 (delete-file (concat texfilebase e))))
18707 pngfile))))
18709 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18710 "Fill a LaTeX header template TPL.
18711 In the template, the following place holders will be recognized:
18713 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18714 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18715 [PACKAGES] \\usepackage statements for PKG
18716 [NO-PACKAGES] do not include PKG
18717 [EXTRA] the string EXTRA
18718 [NO-EXTRA] do not include EXTRA
18720 For backward compatibility, if both the positive and the negative place
18721 holder is missing, the positive one (without the \"NO-\") will be
18722 assumed to be present at the end of the template.
18723 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18724 EXTRA is a string.
18725 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18726 (let (rpl (end ""))
18727 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18728 (setq rpl (if (or (match-end 1) (not def-pkg))
18729 "" (org-latex-packages-to-string def-pkg snippets-p t))
18730 tpl (replace-match rpl t t tpl))
18731 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18733 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18734 (setq rpl (if (or (match-end 1) (not pkg))
18735 "" (org-latex-packages-to-string pkg snippets-p t))
18736 tpl (replace-match rpl t t tpl))
18737 (if pkg (setq end
18738 (concat end "\n"
18739 (org-latex-packages-to-string pkg snippets-p)))))
18741 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18742 (setq rpl (if (or (match-end 1) (not extra))
18743 "" (concat extra "\n"))
18744 tpl (replace-match rpl t t tpl))
18745 (if (and extra (string-match "\\S-" extra))
18746 (setq end (concat end "\n" extra))))
18748 (if (string-match "\\S-" end)
18749 (concat tpl "\n" end)
18750 tpl)))
18752 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18753 "Turn an alist of packages into a string with the \\usepackage macros."
18754 (setq pkg (mapconcat (lambda(p)
18755 (cond
18756 ((stringp p) p)
18757 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18758 (format "%% Package %s omitted" (cadr p)))
18759 ((equal "" (car p))
18760 (format "\\usepackage{%s}" (cadr p)))
18762 (format "\\usepackage[%s]{%s}"
18763 (car p) (cadr p)))))
18765 "\n"))
18766 (if newline (concat pkg "\n") pkg))
18768 (defun org-dvipng-color (attr)
18769 "Return a RGB color specification for dvipng."
18770 (apply 'format "rgb %s %s %s"
18771 (mapcar 'org-normalize-color
18772 (if (featurep 'xemacs)
18773 (color-rgb-components
18774 (face-property 'default
18775 (cond ((eq attr :foreground) 'foreground)
18776 ((eq attr :background) 'background))))
18777 (color-values (face-attribute 'default attr nil))))))
18779 (defun org-dvipng-color-format (color-name)
18780 "Convert COLOR-NAME to a RGB color value for dvipng."
18781 (apply 'format "rgb %s %s %s"
18782 (mapcar 'org-normalize-color
18783 (color-values color-name))))
18785 (defun org-latex-color (attr)
18786 "Return a RGB color for the LaTeX color package."
18787 (apply 'format "%s,%s,%s"
18788 (mapcar 'org-normalize-color
18789 (if (featurep 'xemacs)
18790 (color-rgb-components
18791 (face-property 'default
18792 (cond ((eq attr :foreground) 'foreground)
18793 ((eq attr :background) 'background))))
18794 (color-values (face-attribute 'default attr nil))))))
18796 (defun org-latex-color-format (color-name)
18797 "Convert COLOR-NAME to a RGB color value."
18798 (apply 'format "%s,%s,%s"
18799 (mapcar 'org-normalize-color
18800 (color-values color-name))))
18802 (defun org-normalize-color (value)
18803 "Return string to be used as color value for an RGB component."
18804 (format "%g" (/ value 65535.0)))
18808 ;; Image display
18810 (defvar org-inline-image-overlays nil)
18811 (make-variable-buffer-local 'org-inline-image-overlays)
18813 (defun org-toggle-inline-images (&optional include-linked)
18814 "Toggle the display of inline images.
18815 INCLUDE-LINKED is passed to `org-display-inline-images'."
18816 (interactive "P")
18817 (if org-inline-image-overlays
18818 (progn
18819 (org-remove-inline-images)
18820 (message "Inline image display turned off"))
18821 (org-display-inline-images include-linked)
18822 (if (and (org-called-interactively-p)
18823 org-inline-image-overlays)
18824 (message "%d images displayed inline"
18825 (length org-inline-image-overlays))
18826 (message "No images to display inline"))))
18828 (defun org-redisplay-inline-images ()
18829 "Refresh the display of inline images."
18830 (interactive)
18831 (if (not org-inline-image-overlays)
18832 (org-toggle-inline-images)
18833 (org-toggle-inline-images)
18834 (org-toggle-inline-images)))
18836 (defun org-display-inline-images (&optional include-linked refresh beg end)
18837 "Display inline images.
18838 Normally only links without a description part are inlined, because this
18839 is how it will work for export. When INCLUDE-LINKED is set, also links
18840 with a description part will be inlined. This can be nice for a quick
18841 look at those images, but it does not reflect what exported files will look
18842 like.
18843 When REFRESH is set, refresh existing images between BEG and END.
18844 This will create new image displays only if necessary.
18845 BEG and END default to the buffer boundaries."
18846 (interactive "P")
18847 (when (display-graphic-p)
18848 (unless refresh
18849 (org-remove-inline-images)
18850 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18851 (save-excursion
18852 (save-restriction
18853 (widen)
18854 (setq beg (or beg (point-min)) end (or end (point-max)))
18855 (goto-char beg)
18856 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18857 (substring (org-image-file-name-regexp) 0 -2)
18858 "\\)\\]" (if include-linked "" "\\]")))
18859 (case-fold-search t)
18860 old file ov img type attrwidth width)
18861 (while (re-search-forward re end t)
18862 (setq old (get-char-property-and-overlay (match-beginning 1)
18863 'org-image-overlay)
18864 file (expand-file-name
18865 (concat (or (match-string 3) "") (match-string 4))))
18866 (when (image-type-available-p 'imagemagick)
18867 (setq attrwidth (if (or (listp org-image-actual-width)
18868 (null org-image-actual-width))
18869 (save-excursion
18870 (save-match-data
18871 (when (re-search-backward
18872 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18873 (save-excursion
18874 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18875 (string-to-number (match-string 1))))))
18876 width (cond ((eq org-image-actual-width t) nil)
18877 ((null org-image-actual-width) attrwidth)
18878 ((numberp org-image-actual-width)
18879 org-image-actual-width)
18880 ((listp org-image-actual-width)
18881 (or attrwidth (car org-image-actual-width))))
18882 type (if width 'imagemagick)))
18883 (when (file-exists-p file)
18884 (if (and (car-safe old) refresh)
18885 (image-refresh (overlay-get (cdr old) 'display))
18886 (setq img (save-match-data (create-image file type nil :width width)))
18887 (when img
18888 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18889 (overlay-put ov 'display img)
18890 (overlay-put ov 'face 'default)
18891 (overlay-put ov 'org-image-overlay t)
18892 (overlay-put ov 'modification-hooks
18893 (list 'org-display-inline-remove-overlay))
18894 (push ov org-inline-image-overlays))))))))))
18896 (define-obsolete-function-alias
18897 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18899 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18900 "Remove inline-display overlay if a corresponding region is modified."
18901 (let ((inhibit-modification-hooks t))
18902 (when (and ov after)
18903 (delete ov org-inline-image-overlays)
18904 (delete-overlay ov))))
18906 (defun org-remove-inline-images ()
18907 "Remove inline display of images."
18908 (interactive)
18909 (mapc 'delete-overlay org-inline-image-overlays)
18910 (setq org-inline-image-overlays nil))
18912 ;;;; Key bindings
18914 ;; Outline functions from `outline-mode-prefix-map'
18915 ;; that can be remapped in Org:
18916 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18917 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18918 (define-key org-mode-map [remap outline-forward-same-level]
18919 'org-forward-heading-same-level)
18920 (define-key org-mode-map [remap outline-backward-same-level]
18921 'org-backward-heading-same-level)
18922 (define-key org-mode-map [remap show-branches]
18923 'org-kill-note-or-show-branches)
18924 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18925 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18926 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18928 ;; Outline functions from `outline-mode-prefix-map' that can not
18929 ;; be remapped in Org:
18931 ;; - the column "key binding" shows whether the Outline function is still
18932 ;; available in Org mode on the same key that it has been bound to in
18933 ;; Outline mode:
18934 ;; - "overridden": key used for a different functionality in Org mode
18935 ;; - else: key still bound to the same Outline function in Org mode
18937 ;; | Outline function | key binding | Org replacement |
18938 ;; |------------------------------------+-------------+-----------------------|
18939 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18940 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18941 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18942 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18943 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18944 ;; | `show-entry' | overridden | no replacement |
18945 ;; | `show-children' | `C-c C-i' | visibility cycling |
18946 ;; | `show-branches' | `C-c C-k' | still same function |
18947 ;; | `show-subtree' | overridden | visibility cycling |
18948 ;; | `show-all' | overridden | no replacement |
18949 ;; | `hide-subtree' | overridden | visibility cycling |
18950 ;; | `hide-body' | overridden | no replacement |
18951 ;; | `hide-entry' | overridden | visibility cycling |
18952 ;; | `hide-leaves' | overridden | no replacement |
18953 ;; | `hide-sublevels' | overridden | no replacement |
18954 ;; | `hide-other' | overridden | no replacement |
18956 ;; Make `C-c C-x' a prefix key
18957 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18959 ;; TAB key with modifiers
18960 (org-defkey org-mode-map "\C-i" 'org-cycle)
18961 (org-defkey org-mode-map [(tab)] 'org-cycle)
18962 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18963 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18964 ;; The following line is necessary under Suse GNU/Linux
18965 (unless (featurep 'xemacs)
18966 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18967 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18968 (define-key org-mode-map [backtab] 'org-shifttab)
18970 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18971 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18972 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18974 ;; Cursor keys with modifiers
18975 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18976 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18977 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18978 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18980 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18981 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18982 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18983 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18985 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18986 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18987 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18988 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18990 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18991 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18992 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18993 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18995 ;; Babel keys
18996 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18997 (mapc (lambda (pair)
18998 (define-key org-babel-map (car pair) (cdr pair)))
18999 org-babel-key-bindings)
19001 ;;; Extra keys for tty access.
19002 ;; We only set them when really needed because otherwise the
19003 ;; menus don't show the simple keys
19005 (when (or org-use-extra-keys
19006 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19007 (not window-system))
19008 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19009 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19010 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19011 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19012 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19013 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19014 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19015 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19016 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19017 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19018 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19019 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19020 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19021 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19022 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19023 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19024 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19025 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19026 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19027 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19028 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19029 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19030 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19031 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19032 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19033 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19034 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19035 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19037 ;; All the other keys
19039 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19040 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19041 (if (boundp 'narrow-map)
19042 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19043 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19044 (if (boundp 'narrow-map)
19045 (org-defkey narrow-map "b" 'org-narrow-to-block)
19046 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19047 (if (boundp 'narrow-map)
19048 (org-defkey narrow-map "e" 'org-narrow-to-element)
19049 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19050 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19051 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19052 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19053 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19054 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19055 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19056 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19057 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19058 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19059 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19060 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19061 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19062 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19063 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19064 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19065 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19066 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19067 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19068 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19069 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19070 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19071 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19072 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19073 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19074 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19075 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19076 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19077 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19078 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19079 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19080 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19081 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19082 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19083 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19084 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19085 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19086 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19087 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19088 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19089 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19090 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19091 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19092 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19093 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19094 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19095 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19096 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19097 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19098 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19099 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19100 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19101 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19102 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19103 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19104 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19105 (org-defkey org-mode-map "\C-c^" 'org-sort)
19106 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19107 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19108 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19109 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19110 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19111 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19112 (org-defkey org-mode-map "\C-m" 'org-return)
19113 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19114 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19115 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19116 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19117 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19118 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19119 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19120 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19121 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19122 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19123 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19124 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19125 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19126 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19127 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19128 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19129 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19130 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19131 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19132 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19133 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19134 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19135 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19137 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19138 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19139 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19141 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19142 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19143 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19144 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19145 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19146 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19147 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19148 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19149 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19150 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19151 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19152 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19153 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19154 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19155 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19156 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19157 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19158 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19159 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19160 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19161 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19162 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19163 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19165 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19166 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19167 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19168 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19169 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19171 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19173 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19175 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19176 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19178 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19181 (when (featurep 'xemacs)
19182 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19185 (defconst org-speed-commands-default
19187 ("Outline Navigation")
19188 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19189 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19190 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19191 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19192 ("F" . org-next-block)
19193 ("B" . org-previous-block)
19194 ("u" . (org-speed-move-safe 'outline-up-heading))
19195 ("j" . org-goto)
19196 ("g" . (org-refile t))
19197 ("Outline Visibility")
19198 ("c" . org-cycle)
19199 ("C" . org-shifttab)
19200 (" " . org-display-outline-path)
19201 ("s" . org-narrow-to-subtree)
19202 ("=" . org-columns)
19203 ("Outline Structure Editing")
19204 ("U" . org-shiftmetaup)
19205 ("D" . org-shiftmetadown)
19206 ("r" . org-metaright)
19207 ("l" . org-metaleft)
19208 ("R" . org-shiftmetaright)
19209 ("L" . org-shiftmetaleft)
19210 ("i" . (progn (forward-char 1) (call-interactively
19211 'org-insert-heading-respect-content)))
19212 ("^" . org-sort)
19213 ("w" . org-refile)
19214 ("a" . org-archive-subtree-default-with-confirmation)
19215 ("@" . org-mark-subtree)
19216 ("#" . org-toggle-comment)
19217 ("Clock Commands")
19218 ("I" . org-clock-in)
19219 ("O" . org-clock-out)
19220 ("Meta Data Editing")
19221 ("t" . org-todo)
19222 ("," . (org-priority))
19223 ("0" . (org-priority ?\ ))
19224 ("1" . (org-priority ?A))
19225 ("2" . (org-priority ?B))
19226 ("3" . (org-priority ?C))
19227 (":" . org-set-tags-command)
19228 ("e" . org-set-effort)
19229 ("E" . org-inc-effort)
19230 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19231 (org-entry-put (point) "APPT_WARNTIME" m)))
19232 ("Agenda Views etc")
19233 ("v" . org-agenda)
19234 ("/" . org-sparse-tree)
19235 ("Misc")
19236 ("o" . org-open-at-point)
19237 ("?" . org-speed-command-help)
19238 ("<" . (org-agenda-set-restriction-lock 'subtree))
19239 (">" . (org-agenda-remove-restriction-lock))
19241 "The default speed commands.")
19243 (defun org-print-speed-command (e)
19244 (if (> (length (car e)) 1)
19245 (progn
19246 (princ "\n")
19247 (princ (car e))
19248 (princ "\n")
19249 (princ (make-string (length (car e)) ?-))
19250 (princ "\n"))
19251 (princ (car e))
19252 (princ " ")
19253 (if (symbolp (cdr e))
19254 (princ (symbol-name (cdr e)))
19255 (prin1 (cdr e)))
19256 (princ "\n")))
19258 (defun org-speed-command-help ()
19259 "Show the available speed commands."
19260 (interactive)
19261 (if (not org-use-speed-commands)
19262 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19263 (with-output-to-temp-buffer "*Help*"
19264 (princ "User-defined Speed commands\n===========================\n")
19265 (mapc 'org-print-speed-command org-speed-commands-user)
19266 (princ "\n")
19267 (princ "Built-in Speed commands\n=======================\n")
19268 (mapc 'org-print-speed-command org-speed-commands-default))
19269 (with-current-buffer "*Help*"
19270 (setq truncate-lines t))))
19272 (defun org-speed-move-safe (cmd)
19273 "Execute CMD, but make sure that the cursor always ends up in a headline.
19274 If not, return to the original position and throw an error."
19275 (interactive)
19276 (let ((pos (point)))
19277 (call-interactively cmd)
19278 (unless (and (bolp) (org-at-heading-p))
19279 (goto-char pos)
19280 (error "Boundary reached while executing %s" cmd))))
19282 (defvar org-self-insert-command-undo-counter 0)
19284 (defvar org-table-auto-blank-field) ; defined in org-table.el
19285 (defvar org-speed-command nil)
19287 (define-obsolete-function-alias
19288 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19290 (defun org-speed-command-activate (keys)
19291 "Hook for activating single-letter speed commands.
19292 `org-speed-commands-default' specifies a minimal command set.
19293 Use `org-speed-commands-user' for further customization."
19294 (when (or (and (bolp) (looking-at org-outline-regexp))
19295 (and (functionp org-use-speed-commands)
19296 (funcall org-use-speed-commands)))
19297 (cdr (assoc keys (append org-speed-commands-user
19298 org-speed-commands-default)))))
19300 (define-obsolete-function-alias
19301 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19303 (defun org-babel-speed-command-activate (keys)
19304 "Hook for activating single-letter code block commands."
19305 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19306 (cdr (assoc keys org-babel-key-bindings))))
19308 (defcustom org-speed-command-hook
19309 '(org-speed-command-default-hook org-babel-speed-command-hook)
19310 "Hook for activating speed commands at strategic locations.
19311 Hook functions are called in sequence until a valid handler is
19312 found.
19314 Each hook takes a single argument, a user-pressed command key
19315 which is also a `self-insert-command' from the global map.
19317 Within the hook, examine the cursor position and the command key
19318 and return nil or a valid handler as appropriate. Handler could
19319 be one of an interactive command, a function, or a form.
19321 Set `org-use-speed-commands' to non-nil value to enable this
19322 hook. The default setting is `org-speed-command-activate'."
19323 :group 'org-structure
19324 :version "24.1"
19325 :type 'hook)
19327 (defun org-self-insert-command (N)
19328 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19329 If the cursor is in a table looking at whitespace, the whitespace is
19330 overwritten, and the table is not marked as requiring realignment."
19331 (interactive "p")
19332 (org-check-before-invisible-edit 'insert)
19333 (cond
19334 ((and org-use-speed-commands
19335 (setq org-speed-command
19336 (run-hook-with-args-until-success
19337 'org-speed-command-hook (this-command-keys))))
19338 (cond
19339 ((commandp org-speed-command)
19340 (setq this-command org-speed-command)
19341 (call-interactively org-speed-command))
19342 ((functionp org-speed-command)
19343 (funcall org-speed-command))
19344 ((and org-speed-command (listp org-speed-command))
19345 (eval org-speed-command))
19346 (t (let (org-use-speed-commands)
19347 (call-interactively 'org-self-insert-command)))))
19348 ((and
19349 (org-table-p)
19350 (progn
19351 ;; check if we blank the field, and if that triggers align
19352 (and (featurep 'org-table) org-table-auto-blank-field
19353 (member last-command
19354 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19355 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19356 ;; got extra space, this field does not determine column width
19357 (let (org-table-may-need-update) (org-table-blank-field))
19358 ;; no extra space, this field may determine column width
19359 (org-table-blank-field)))
19361 (eq N 1)
19362 (looking-at "[^|\n]* |"))
19363 (let (org-table-may-need-update)
19364 (goto-char (1- (match-end 0)))
19365 (backward-delete-char 1)
19366 (goto-char (match-beginning 0))
19367 (self-insert-command N)))
19369 (setq org-table-may-need-update t)
19370 (self-insert-command N)
19371 (org-fix-tags-on-the-fly)
19372 (if org-self-insert-cluster-for-undo
19373 (if (not (eq last-command 'org-self-insert-command))
19374 (setq org-self-insert-command-undo-counter 1)
19375 (if (>= org-self-insert-command-undo-counter 20)
19376 (setq org-self-insert-command-undo-counter 1)
19377 (and (> org-self-insert-command-undo-counter 0)
19378 buffer-undo-list (listp buffer-undo-list)
19379 (not (cadr buffer-undo-list)) ; remove nil entry
19380 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19381 (setq org-self-insert-command-undo-counter
19382 (1+ org-self-insert-command-undo-counter))))))))
19384 (defun org-check-before-invisible-edit (kind)
19385 "Check is editing if kind KIND would be dangerous with invisible text around.
19386 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19387 ;; First, try to get out of here as quickly as possible, to reduce overhead
19388 (if (and org-catch-invisible-edits
19389 (or (not (boundp 'visible-mode)) (not visible-mode))
19390 (or (get-char-property (point) 'invisible)
19391 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19392 ;; OK, we need to take a closer look
19393 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19394 (invisible-before-point (if (bobp) nil (get-char-property
19395 (1- (point)) 'invisible)))
19396 (border-and-ok-direction
19398 ;; Check if we are acting predictably before invisible text
19399 (and invisible-at-point (not invisible-before-point)
19400 (memq kind '(insert delete-backward)))
19401 ;; Check if we are acting predictably after invisible text
19402 ;; This works not well, and I have turned it off. It seems
19403 ;; better to always show and stop after invisible text.
19404 ;; (and (not invisible-at-point) invisible-before-point
19405 ;; (memq kind '(insert delete)))
19407 (when (or (memq invisible-at-point '(outline org-hide-block t))
19408 (memq invisible-before-point '(outline org-hide-block t)))
19409 (if (eq org-catch-invisible-edits 'error)
19410 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19411 (if (and org-custom-properties-overlays
19412 (y-or-n-p "Display invisible properties in this buffer? "))
19413 (org-toggle-custom-properties-visibility)
19414 ;; Make the area visible
19415 (save-excursion
19416 (if invisible-before-point
19417 (goto-char (previous-single-char-property-change
19418 (point) 'invisible)))
19419 (org-cycle))
19420 (cond
19421 ((eq org-catch-invisible-edits 'show)
19422 ;; That's it, we do the edit after showing
19423 (message
19424 "Unfolding invisible region around point before editing")
19425 (sit-for 1))
19426 ((and (eq org-catch-invisible-edits 'smart)
19427 border-and-ok-direction)
19428 (message "Unfolding invisible region around point before editing"))
19430 ;; Don't do the edit, make the user repeat it in full visibility
19431 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19433 (defun org-fix-tags-on-the-fly ()
19434 (when (and (equal (char-after (point-at-bol)) ?*)
19435 (org-at-heading-p))
19436 (org-align-tags-here org-tags-column)))
19438 (defun org-delete-backward-char (N)
19439 "Like `delete-backward-char', insert whitespace at field end in tables.
19440 When deleting backwards, in tables this function will insert whitespace in
19441 front of the next \"|\" separator, to keep the table aligned. The table will
19442 still be marked for re-alignment if the field did fill the entire column,
19443 because, in this case the deletion might narrow the column."
19444 (interactive "p")
19445 (save-match-data
19446 (org-check-before-invisible-edit 'delete-backward)
19447 (if (and (org-table-p)
19448 (eq N 1)
19449 (string-match "|" (buffer-substring (point-at-bol) (point)))
19450 (looking-at ".*?|"))
19451 (let ((pos (point))
19452 (noalign (looking-at "[^|\n\r]* |"))
19453 (c org-table-may-need-update))
19454 (backward-delete-char N)
19455 (if (not overwrite-mode)
19456 (progn
19457 (skip-chars-forward "^|")
19458 (insert " ")
19459 (goto-char (1- pos))))
19460 ;; noalign: if there were two spaces at the end, this field
19461 ;; does not determine the width of the column.
19462 (if noalign (setq org-table-may-need-update c)))
19463 (backward-delete-char N)
19464 (org-fix-tags-on-the-fly))))
19466 (defun org-delete-char (N)
19467 "Like `delete-char', but insert whitespace at field end in tables.
19468 When deleting characters, in tables this function will insert whitespace in
19469 front of the next \"|\" separator, to keep the table aligned. The table will
19470 still be marked for re-alignment if the field did fill the entire column,
19471 because, in this case the deletion might narrow the column."
19472 (interactive "p")
19473 (save-match-data
19474 (org-check-before-invisible-edit 'delete)
19475 (if (and (org-table-p)
19476 (not (bolp))
19477 (not (= (char-after) ?|))
19478 (eq N 1))
19479 (if (looking-at ".*?|")
19480 (let ((pos (point))
19481 (noalign (looking-at "[^|\n\r]* |"))
19482 (c org-table-may-need-update))
19483 (replace-match
19484 (concat (substring (match-string 0) 1 -1) " |") nil t)
19485 (goto-char pos)
19486 ;; noalign: if there were two spaces at the end, this field
19487 ;; does not determine the width of the column.
19488 (if noalign (setq org-table-may-need-update c)))
19489 (delete-char N))
19490 (delete-char N)
19491 (org-fix-tags-on-the-fly))))
19493 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19494 (put 'org-self-insert-command 'delete-selection t)
19495 (put 'orgtbl-self-insert-command 'delete-selection t)
19496 (put 'org-delete-char 'delete-selection 'supersede)
19497 (put 'org-delete-backward-char 'delete-selection 'supersede)
19498 (put 'org-yank 'delete-selection 'yank)
19500 ;; Make `flyspell-mode' delay after some commands
19501 (put 'org-self-insert-command 'flyspell-delayed t)
19502 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19503 (put 'org-delete-char 'flyspell-delayed t)
19504 (put 'org-delete-backward-char 'flyspell-delayed t)
19506 ;; Make pabbrev-mode expand after org-mode commands
19507 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19508 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19510 ;; How to do this: Measure non-white length of current string
19511 ;; If equal to column width, we should realign.
19513 (defun org-remap (map &rest commands)
19514 "In MAP, remap the functions given in COMMANDS.
19515 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19516 (let (new old)
19517 (while commands
19518 (setq old (pop commands) new (pop commands))
19519 (if (fboundp 'command-remapping)
19520 (org-defkey map (vector 'remap old) new)
19521 (substitute-key-definition old new map global-map)))))
19523 (defun org-transpose-words ()
19524 "Transpose words for Org.
19525 This uses the `org-mode-transpose-word-syntax-table' syntax
19526 table, which interprets characters in `org-emphasis-alist' as
19527 word constituants."
19528 (interactive)
19529 (with-syntax-table org-mode-transpose-word-syntax-table
19530 (call-interactively 'transpose-words)))
19531 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19533 (when (eq org-enable-table-editor 'optimized)
19534 ;; If the user wants maximum table support, we need to hijack
19535 ;; some standard editing functions
19536 (org-remap org-mode-map
19537 'self-insert-command 'org-self-insert-command
19538 'delete-char 'org-delete-char
19539 'delete-backward-char 'org-delete-backward-char)
19540 (org-defkey org-mode-map "|" 'org-force-self-insert))
19542 (defvar org-ctrl-c-ctrl-c-hook nil
19543 "Hook for functions attaching themselves to `C-c C-c'.
19545 This can be used to add additional functionality to the C-c C-c
19546 key which executes context-dependent commands. This hook is run
19547 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19548 run after the last test.
19550 Each function will be called with no arguments. The function
19551 must check if the context is appropriate for it to act. If yes,
19552 it should do its thing and then return a non-nil value. If the
19553 context is wrong, just do nothing and return nil.")
19555 (defvar org-ctrl-c-ctrl-c-final-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 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19561 before the first 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-tab-first-hook nil
19569 "Hook for functions to attach themselves to TAB.
19570 See `org-ctrl-c-ctrl-c-hook' for more information.
19571 This hook runs as the first action when TAB is pressed, even before
19572 `org-cycle' messes around with the `outline-regexp' to cater for
19573 inline tasks and plain list item folding.
19574 If any function in this hook returns t, any other actions that
19575 would have been caused by TAB (such as table field motion or visibility
19576 cycling) will not occur.")
19578 (defvar org-tab-after-check-for-table-hook nil
19579 "Hook for functions to attach themselves to TAB.
19580 See `org-ctrl-c-ctrl-c-hook' for more information.
19581 This hook runs after it has been established that the cursor is not in a
19582 table, but before checking if the cursor is in a headline or if global cycling
19583 should be done.
19584 If any function in this hook returns t, not other actions like visibility
19585 cycling will be done.")
19587 (defvar org-tab-after-check-for-cycling-hook nil
19588 "Hook for functions to attach themselves to TAB.
19589 See `org-ctrl-c-ctrl-c-hook' for more information.
19590 This hook runs after it has been established that not table field motion and
19591 not visibility should be done because of current context. This is probably
19592 the place where a package like yasnippets can hook in.")
19594 (defvar org-tab-before-tab-emulation-hook nil
19595 "Hook for functions to attach themselves to TAB.
19596 See `org-ctrl-c-ctrl-c-hook' for more information.
19597 This hook runs after every other options for TAB have been exhausted, but
19598 before indentation and \t insertion takes place.")
19600 (defvar org-metaleft-hook nil
19601 "Hook for functions attaching themselves to `M-left'.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.")
19603 (defvar org-metaright-hook nil
19604 "Hook for functions attaching themselves to `M-right'.
19605 See `org-ctrl-c-ctrl-c-hook' for more information.")
19606 (defvar org-metaup-hook nil
19607 "Hook for functions attaching themselves to `M-up'.
19608 See `org-ctrl-c-ctrl-c-hook' for more information.")
19609 (defvar org-metadown-hook nil
19610 "Hook for functions attaching themselves to `M-down'.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19612 (defvar org-shiftmetaleft-hook nil
19613 "Hook for functions attaching themselves to `M-S-left'.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.")
19615 (defvar org-shiftmetaright-hook nil
19616 "Hook for functions attaching themselves to `M-S-right'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-shiftmetaup-hook nil
19619 "Hook for functions attaching themselves to `M-S-up'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-shiftmetadown-hook nil
19622 "Hook for functions attaching themselves to `M-S-down'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-metareturn-hook nil
19625 "Hook for functions attaching themselves to `M-RET'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftup-hook nil
19628 "Hook for functions attaching themselves to `S-up'.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.")
19630 (defvar org-shiftup-final-hook nil
19631 "Hook for functions attaching themselves to `S-up'.
19632 This one runs after all other options except shift-select have been excluded.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftdown-hook nil
19635 "Hook for functions attaching themselves to `S-down'.
19636 See `org-ctrl-c-ctrl-c-hook' for more information.")
19637 (defvar org-shiftdown-final-hook nil
19638 "Hook for functions attaching themselves to `S-down'.
19639 This one runs after all other options except shift-select have been excluded.
19640 See `org-ctrl-c-ctrl-c-hook' for more information.")
19641 (defvar org-shiftleft-hook nil
19642 "Hook for functions attaching themselves to `S-left'.
19643 See `org-ctrl-c-ctrl-c-hook' for more information.")
19644 (defvar org-shiftleft-final-hook nil
19645 "Hook for functions attaching themselves to `S-left'.
19646 This one runs after all other options except shift-select have been excluded.
19647 See `org-ctrl-c-ctrl-c-hook' for more information.")
19648 (defvar org-shiftright-hook nil
19649 "Hook for functions attaching themselves to `S-right'.
19650 See `org-ctrl-c-ctrl-c-hook' for more information.")
19651 (defvar org-shiftright-final-hook nil
19652 "Hook for functions attaching themselves to `S-right'.
19653 This one runs after all other options except shift-select have been excluded.
19654 See `org-ctrl-c-ctrl-c-hook' for more information.")
19656 (defun org-modifier-cursor-error ()
19657 "Throw an error, a modified cursor command was applied in wrong context."
19658 (user-error "This command is active in special context like tables, headlines or items"))
19660 (defun org-shiftselect-error ()
19661 "Throw an error because Shift-Cursor command was applied in wrong context."
19662 (if (and (boundp 'shift-select-mode) shift-select-mode)
19663 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19664 (user-error "This command works only in special context like headlines or timestamps")))
19666 (defun org-call-for-shift-select (cmd)
19667 (let ((this-command-keys-shift-translated t))
19668 (call-interactively cmd)))
19670 (defun org-shifttab (&optional arg)
19671 "Global visibility cycling or move to previous table field.
19672 Call `org-table-previous-field' within a table.
19673 When ARG is nil, cycle globally through visibility states.
19674 When ARG is a numeric prefix, show contents of this level."
19675 (interactive "P")
19676 (cond
19677 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19678 ((integerp arg)
19679 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19680 (message "Content view to level: %d" arg)
19681 (org-content (prefix-numeric-value arg2))
19682 (org-cycle-show-empty-lines t)
19683 (setq org-cycle-global-status 'overview)))
19684 (t (call-interactively 'org-global-cycle))))
19686 (defun org-shiftmetaleft ()
19687 "Promote subtree or delete table column.
19688 Calls `org-promote-subtree', `org-outdent-item-tree', or
19689 `org-table-delete-column', depending on context. See the
19690 individual commands for more information."
19691 (interactive)
19692 (cond
19693 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19694 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19695 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19696 ((if (not (org-region-active-p)) (org-at-item-p)
19697 (save-excursion (goto-char (region-beginning))
19698 (org-at-item-p)))
19699 (call-interactively 'org-outdent-item-tree))
19700 (t (org-modifier-cursor-error))))
19702 (defun org-shiftmetaright ()
19703 "Demote subtree or insert table column.
19704 Calls `org-demote-subtree', `org-indent-item-tree', or
19705 `org-table-insert-column', depending on context. See the
19706 individual commands for more information."
19707 (interactive)
19708 (cond
19709 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19710 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19711 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19712 ((if (not (org-region-active-p)) (org-at-item-p)
19713 (save-excursion (goto-char (region-beginning))
19714 (org-at-item-p)))
19715 (call-interactively 'org-indent-item-tree))
19716 (t (org-modifier-cursor-error))))
19718 (defun org-shiftmetaup (&optional arg)
19719 "Move subtree up or kill table row.
19720 Calls `org-move-subtree-up' or `org-table-kill-row' or
19721 `org-move-item-up' or `org-timestamp-up', depending on context.
19722 See the individual commands for more information."
19723 (interactive "P")
19724 (cond
19725 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19726 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19727 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19728 ((org-at-item-p) (call-interactively 'org-move-item-up))
19729 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19730 (call-interactively 'org-timestamp-up)))
19731 (t (call-interactively 'org-drag-line-backward))))
19733 (defun org-shiftmetadown (&optional arg)
19734 "Move subtree down or insert table row.
19735 Calls `org-move-subtree-down' or `org-table-insert-row' or
19736 `org-move-item-down' or `org-timestamp-up', depending on context.
19737 See the individual commands for more information."
19738 (interactive "P")
19739 (cond
19740 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19741 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19742 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19743 ((org-at-item-p) (call-interactively 'org-move-item-down))
19744 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19745 (call-interactively 'org-timestamp-down)))
19746 (t (call-interactively 'org-drag-line-forward))))
19748 (defsubst org-hidden-tree-error ()
19749 (user-error
19750 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19752 (defun org-metaleft (&optional arg)
19753 "Promote heading or move table column to left.
19754 Calls `org-do-promote' or `org-table-move-column', depending on context.
19755 With no specific context, calls the Emacs default `backward-word'.
19756 See the individual commands for more information."
19757 (interactive "P")
19758 (cond
19759 ((run-hook-with-args-until-success 'org-metaleft-hook))
19760 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19761 ((org-with-limited-levels
19762 (or (org-at-heading-p)
19763 (and (org-region-active-p)
19764 (save-excursion
19765 (goto-char (region-beginning))
19766 (org-at-heading-p)))))
19767 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19768 (call-interactively 'org-do-promote))
19769 ;; At an inline task.
19770 ((org-at-heading-p)
19771 (call-interactively 'org-inlinetask-promote))
19772 ((or (org-at-item-p)
19773 (and (org-region-active-p)
19774 (save-excursion
19775 (goto-char (region-beginning))
19776 (org-at-item-p))))
19777 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19778 (call-interactively 'org-outdent-item))
19779 (t (call-interactively 'backward-word))))
19781 (defun org-metaright (&optional arg)
19782 "Demote a subtree, a list item or move table column to right.
19783 In front of a drawer or a block keyword, indent it correctly.
19784 With no specific context, calls the Emacs default `forward-word'.
19785 See the individual commands for more information."
19786 (interactive "P")
19787 (cond
19788 ((run-hook-with-args-until-success 'org-metaright-hook))
19789 ((org-at-table-p) (call-interactively 'org-table-move-column))
19790 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19791 ((org-at-block-p) (call-interactively 'org-indent-block))
19792 ((org-with-limited-levels
19793 (or (org-at-heading-p)
19794 (and (org-region-active-p)
19795 (save-excursion
19796 (goto-char (region-beginning))
19797 (org-at-heading-p)))))
19798 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19799 (call-interactively 'org-do-demote))
19800 ;; At an inline task.
19801 ((org-at-heading-p)
19802 (call-interactively 'org-inlinetask-demote))
19803 ((or (org-at-item-p)
19804 (and (org-region-active-p)
19805 (save-excursion
19806 (goto-char (region-beginning))
19807 (org-at-item-p))))
19808 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19809 (call-interactively 'org-indent-item))
19810 (t (call-interactively 'forward-word))))
19812 (defun org-check-for-hidden (what)
19813 "Check if there are hidden headlines/items in the current visual line.
19814 WHAT can be either `headlines' or `items'. If the current line is
19815 an outline or item heading and it has a folded subtree below it,
19816 this function returns t, nil otherwise."
19817 (let ((re (cond
19818 ((eq what 'headlines) org-outline-regexp-bol)
19819 ((eq what 'items) (org-item-beginning-re))
19820 (t (error "This should not happen"))))
19821 beg end)
19822 (save-excursion
19823 (catch 'exit
19824 (unless (org-region-active-p)
19825 (setq beg (point-at-bol))
19826 (beginning-of-line 2)
19827 (while (and (not (eobp)) ;; this is like `next-line'
19828 (get-char-property (1- (point)) 'invisible))
19829 (beginning-of-line 2))
19830 (setq end (point))
19831 (goto-char beg)
19832 (goto-char (point-at-eol))
19833 (setq end (max end (point)))
19834 (while (re-search-forward re end t)
19835 (if (get-char-property (match-beginning 0) 'invisible)
19836 (throw 'exit t))))
19837 nil))))
19839 (defun org-metaup (&optional arg)
19840 "Move subtree up or move table row up.
19841 Calls `org-move-subtree-up' or `org-table-move-row' or
19842 `org-move-item-up', depending on context. See the individual commands
19843 for more information."
19844 (interactive "P")
19845 (cond
19846 ((run-hook-with-args-until-success 'org-metaup-hook))
19847 ((org-region-active-p)
19848 (let* ((a (min (region-beginning) (region-end)))
19849 (b (1- (max (region-beginning) (region-end))))
19850 (c (save-excursion (goto-char a)
19851 (move-beginning-of-line 0)))
19852 (d (save-excursion (goto-char a)
19853 (move-end-of-line 0) (point))))
19854 (transpose-regions a b c d)
19855 (goto-char c)))
19856 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19857 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19858 ((org-at-item-p) (call-interactively 'org-move-item-up))
19859 (t (org-drag-element-backward))))
19861 (defun org-metadown (&optional arg)
19862 "Move subtree down or move table row down.
19863 Calls `org-move-subtree-down' or `org-table-move-row' or
19864 `org-move-item-down', depending on context. See the individual
19865 commands for more information."
19866 (interactive "P")
19867 (cond
19868 ((run-hook-with-args-until-success 'org-metadown-hook))
19869 ((org-region-active-p)
19870 (let* ((a (min (region-beginning) (region-end)))
19871 (b (max (region-beginning) (region-end)))
19872 (c (save-excursion (goto-char b)
19873 (move-beginning-of-line 1)))
19874 (d (save-excursion (goto-char b)
19875 (move-end-of-line 1) (1+ (point)))))
19876 (transpose-regions a b c d)
19877 (goto-char d)))
19878 ((org-at-table-p) (call-interactively 'org-table-move-row))
19879 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19880 ((org-at-item-p) (call-interactively 'org-move-item-down))
19881 (t (org-drag-element-forward))))
19883 (defun org-shiftup (&optional arg)
19884 "Increase item in timestamp or increase priority of current headline.
19885 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19886 depending on context. See the individual commands for more information."
19887 (interactive "P")
19888 (cond
19889 ((run-hook-with-args-until-success 'org-shiftup-hook))
19890 ((and org-support-shift-select (org-region-active-p))
19891 (org-call-for-shift-select 'previous-line))
19892 ((org-at-timestamp-p t)
19893 (call-interactively (if org-edit-timestamp-down-means-later
19894 'org-timestamp-down 'org-timestamp-up)))
19895 ((and (not (eq org-support-shift-select 'always))
19896 org-enable-priority-commands
19897 (org-at-heading-p))
19898 (call-interactively 'org-priority-up))
19899 ((and (not org-support-shift-select) (org-at-item-p))
19900 (call-interactively 'org-previous-item))
19901 ((org-clocktable-try-shift 'up arg))
19902 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19903 (org-support-shift-select
19904 (org-call-for-shift-select 'previous-line))
19905 (t (org-shiftselect-error))))
19907 (defun org-shiftdown (&optional arg)
19908 "Decrease item in timestamp or decrease priority of current headline.
19909 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19910 depending on context. See the individual commands for more information."
19911 (interactive "P")
19912 (cond
19913 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19914 ((and org-support-shift-select (org-region-active-p))
19915 (org-call-for-shift-select 'next-line))
19916 ((org-at-timestamp-p t)
19917 (call-interactively (if org-edit-timestamp-down-means-later
19918 'org-timestamp-up 'org-timestamp-down)))
19919 ((and (not (eq org-support-shift-select 'always))
19920 org-enable-priority-commands
19921 (org-at-heading-p))
19922 (call-interactively 'org-priority-down))
19923 ((and (not org-support-shift-select) (org-at-item-p))
19924 (call-interactively 'org-next-item))
19925 ((org-clocktable-try-shift 'down arg))
19926 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19927 (org-support-shift-select
19928 (org-call-for-shift-select 'next-line))
19929 (t (org-shiftselect-error))))
19931 (defun org-shiftright (&optional arg)
19932 "Cycle the thing at point or in the current line, depending on context.
19933 Depending on context, this does one of the following:
19935 - switch a timestamp at point one day into the future
19936 - on a headline, switch to the next TODO keyword.
19937 - on an item, switch entire list to the next bullet type
19938 - on a property line, switch to the next allowed value
19939 - on a clocktable definition line, move time block into the future"
19940 (interactive "P")
19941 (cond
19942 ((run-hook-with-args-until-success 'org-shiftright-hook))
19943 ((and org-support-shift-select (org-region-active-p))
19944 (org-call-for-shift-select 'forward-char))
19945 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19946 ((and (not (eq org-support-shift-select 'always))
19947 (org-at-heading-p))
19948 (let ((org-inhibit-logging
19949 (not org-treat-S-cursor-todo-selection-as-state-change))
19950 (org-inhibit-blocking
19951 (not org-treat-S-cursor-todo-selection-as-state-change)))
19952 (org-call-with-arg 'org-todo 'right)))
19953 ((or (and org-support-shift-select
19954 (not (eq org-support-shift-select 'always))
19955 (org-at-item-bullet-p))
19956 (and (not org-support-shift-select) (org-at-item-p)))
19957 (org-call-with-arg 'org-cycle-list-bullet nil))
19958 ((and (not (eq org-support-shift-select 'always))
19959 (org-at-property-p))
19960 (call-interactively 'org-property-next-allowed-value))
19961 ((org-clocktable-try-shift 'right arg))
19962 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19963 (org-support-shift-select
19964 (org-call-for-shift-select 'forward-char))
19965 (t (org-shiftselect-error))))
19967 (defun org-shiftleft (&optional arg)
19968 "Cycle the thing at point or in the current line, depending on context.
19969 Depending on context, this does one of the following:
19971 - switch a timestamp at point one day into the past
19972 - on a headline, switch to the previous TODO keyword.
19973 - on an item, switch entire list to the previous bullet type
19974 - on a property line, switch to the previous allowed value
19975 - on a clocktable definition line, move time block into the past"
19976 (interactive "P")
19977 (cond
19978 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19979 ((and org-support-shift-select (org-region-active-p))
19980 (org-call-for-shift-select 'backward-char))
19981 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19982 ((and (not (eq org-support-shift-select 'always))
19983 (org-at-heading-p))
19984 (let ((org-inhibit-logging
19985 (not org-treat-S-cursor-todo-selection-as-state-change))
19986 (org-inhibit-blocking
19987 (not org-treat-S-cursor-todo-selection-as-state-change)))
19988 (org-call-with-arg 'org-todo 'left)))
19989 ((or (and org-support-shift-select
19990 (not (eq org-support-shift-select 'always))
19991 (org-at-item-bullet-p))
19992 (and (not org-support-shift-select) (org-at-item-p)))
19993 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19994 ((and (not (eq org-support-shift-select 'always))
19995 (org-at-property-p))
19996 (call-interactively 'org-property-previous-allowed-value))
19997 ((org-clocktable-try-shift 'left arg))
19998 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19999 (org-support-shift-select
20000 (org-call-for-shift-select 'backward-char))
20001 (t (org-shiftselect-error))))
20003 (defun org-shiftcontrolright ()
20004 "Switch to next TODO set."
20005 (interactive)
20006 (cond
20007 ((and org-support-shift-select (org-region-active-p))
20008 (org-call-for-shift-select 'forward-word))
20009 ((and (not (eq org-support-shift-select 'always))
20010 (org-at-heading-p))
20011 (org-call-with-arg 'org-todo 'nextset))
20012 (org-support-shift-select
20013 (org-call-for-shift-select 'forward-word))
20014 (t (org-shiftselect-error))))
20016 (defun org-shiftcontrolleft ()
20017 "Switch to previous TODO set."
20018 (interactive)
20019 (cond
20020 ((and org-support-shift-select (org-region-active-p))
20021 (org-call-for-shift-select 'backward-word))
20022 ((and (not (eq org-support-shift-select 'always))
20023 (org-at-heading-p))
20024 (org-call-with-arg 'org-todo 'previousset))
20025 (org-support-shift-select
20026 (org-call-for-shift-select 'backward-word))
20027 (t (org-shiftselect-error))))
20029 (defun org-shiftcontrolup (&optional n)
20030 "Change timestamps synchronously up in CLOCK log lines.
20031 Optional argument N tells to change by that many units."
20032 (interactive "P")
20033 (cond ((and (not org-support-shift-select)
20034 (org-at-clock-log-p)
20035 (org-at-timestamp-p t))
20036 (org-clock-timestamps-up n))
20037 (t (org-shiftselect-error))))
20039 (defun org-shiftcontroldown (&optional n)
20040 "Change timestamps synchronously down in CLOCK log lines.
20041 Optional argument N tells to change by that many units."
20042 (interactive "P")
20043 (cond ((and (not org-support-shift-select)
20044 (org-at-clock-log-p)
20045 (org-at-timestamp-p t))
20046 (org-clock-timestamps-down n))
20047 (t (org-shiftselect-error))))
20049 (defun org-ctrl-c-ret ()
20050 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20051 (interactive)
20052 (cond
20053 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20054 (t (call-interactively 'org-insert-heading))))
20056 (defun org-find-visible ()
20057 (let ((s (point)))
20058 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20059 (get-char-property s 'invisible)))
20061 (defun org-find-invisible ()
20062 (let ((s (point)))
20063 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20064 (not (get-char-property s 'invisible))))
20067 (defun org-copy-visible (beg end)
20068 "Copy the visible parts of the region."
20069 (interactive "r")
20070 (let (snippets s)
20071 (save-excursion
20072 (save-restriction
20073 (narrow-to-region beg end)
20074 (setq s (goto-char (point-min)))
20075 (while (not (= (point) (point-max)))
20076 (goto-char (org-find-invisible))
20077 (push (buffer-substring s (point)) snippets)
20078 (setq s (goto-char (org-find-visible))))))
20079 (kill-new (apply 'concat (nreverse snippets)))))
20081 (defun org-copy-special ()
20082 "Copy region in table or copy current subtree.
20083 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20084 See the individual commands for more information."
20085 (interactive)
20086 (call-interactively
20087 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20089 (defun org-cut-special ()
20090 "Cut region in table or cut current subtree.
20091 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20092 See the individual commands for more information."
20093 (interactive)
20094 (call-interactively
20095 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20097 (defun org-paste-special (arg)
20098 "Paste rectangular region into table, or past subtree relative to level.
20099 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20100 See the individual commands for more information."
20101 (interactive "P")
20102 (if (org-at-table-p)
20103 (org-table-paste-rectangle)
20104 (org-paste-subtree arg)))
20106 (defsubst org-in-fixed-width-region-p ()
20107 "Is point in a fixed-width region?"
20108 (save-match-data
20109 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20111 (defun org-edit-special (&optional arg)
20112 "Call a special editor for the element at point.
20113 When at a table, call the formula editor with `org-table-edit-formulas'.
20114 When in a source code block, call `org-edit-src-code'.
20115 When in a fixed-width region, call `org-edit-fixed-width-region'.
20116 When at an #+INCLUDE keyword, visit the included file.
20117 On a link, call `ffap' to visit the link at point.
20118 Otherwise, return a user error."
20119 (interactive "P")
20120 (let ((element (org-element-at-point)))
20121 (assert (not buffer-read-only) nil
20122 "Buffer is read-only: %s" (buffer-name))
20123 (case (org-element-type element)
20124 (src-block
20125 (if (not arg) (org-edit-src-code)
20126 (let* ((info (org-babel-get-src-block-info))
20127 (lang (nth 0 info))
20128 (params (nth 2 info))
20129 (session (cdr (assq :session params))))
20130 (if (not session) (org-edit-src-code)
20131 ;; At a src-block with a session and function called with
20132 ;; an ARG: switch to the buffer related to the inferior
20133 ;; process.
20134 (switch-to-buffer
20135 (funcall (intern (concat "org-babel-prep-session:" lang))
20136 session params))))))
20137 (keyword
20138 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20139 (find-file
20140 (org-remove-double-quotes
20141 (car (org-split-string (org-element-property :value element)))))
20142 (user-error "No special environment to edit here")))
20143 (table
20144 (if (eq (org-element-property :type element) 'table.el)
20145 (org-edit-src-code)
20146 (call-interactively 'org-table-edit-formulas)))
20147 ;; Only Org tables contain `table-row' type elements.
20148 (table-row (call-interactively 'org-table-edit-formulas))
20149 ((example-block export-block) (org-edit-src-code))
20150 (fixed-width (org-edit-fixed-width-region))
20151 (otherwise
20152 ;; No notable element at point. Though, we may be at a link,
20153 ;; which is an object. Thus, scan deeper.
20154 (if (eq (org-element-type (org-element-context element)) 'link)
20155 (call-interactively 'ffap)
20156 (user-error "No special environment to edit here"))))))
20158 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20159 (defun org-ctrl-c-ctrl-c (&optional arg)
20160 "Set tags in headline, or update according to changed information at point.
20162 This command does many different things, depending on context:
20164 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20165 this is what we do.
20167 - If the cursor is on a statistics cookie, update it.
20169 - If the cursor is in a headline, prompt for tags and insert them
20170 into the current line, aligned to `org-tags-column'. When called
20171 with prefix arg, realign all tags in the current buffer.
20173 - If the cursor is in one of the special #+KEYWORD lines, this
20174 triggers scanning the buffer for these lines and updating the
20175 information.
20177 - If the cursor is inside a table, realign the table. This command
20178 works even if the automatic table editor has been turned off.
20180 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20181 the entire table.
20183 - If the cursor is at a footnote reference or definition, jump to
20184 the corresponding definition or references, respectively.
20186 - If the cursor is a the beginning of a dynamic block, update it.
20188 - If the current buffer is a capture buffer, close note and file it.
20190 - If the cursor is on a <<<target>>>, update radio targets and
20191 corresponding links in this buffer.
20193 - If the cursor is on a numbered item in a plain list, renumber the
20194 ordered list.
20196 - If the cursor is on a checkbox, toggle it.
20198 - If the cursor is on a code block, evaluate it. The variable
20199 `org-confirm-babel-evaluate' can be used to control prompting
20200 before code block evaluation, by default every code block
20201 evaluation requires confirmation. Code block evaluation can be
20202 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20203 (interactive "P")
20204 (cond
20205 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20206 org-occur-highlights
20207 org-latex-fragment-image-overlays)
20208 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20209 (org-remove-occur-highlights)
20210 (org-remove-latex-fragment-image-overlays)
20211 (message "Temporary highlights/overlays removed from current buffer"))
20212 ((and (local-variable-p 'org-finish-function (current-buffer))
20213 (fboundp org-finish-function))
20214 (funcall org-finish-function))
20215 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20217 (let* ((context (org-element-context)) (type (org-element-type context)))
20218 ;; Test if point is within a blank line.
20219 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20220 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20221 (user-error "C-c C-c can do nothing useful at this location"))
20222 ;; When at a link, act according to the parent instead.
20223 (when (eq type 'link)
20224 (setq context (org-element-property :parent context))
20225 (setq type (org-element-type context)))
20226 ;; For convenience: at the first line of a paragraph on the
20227 ;; same line as an item, apply function on that item instead.
20228 (when (eq type 'paragraph)
20229 (let ((parent (org-element-property :parent context)))
20230 (when (and (eq (org-element-type parent) 'item)
20231 (= (point-at-bol) (org-element-property :begin parent)))
20232 (setq context parent type 'item))))
20233 ;; Act according to type of element or object at point.
20234 (case type
20235 (clock (org-clock-update-time-maybe))
20236 (dynamic-block
20237 (save-excursion
20238 (goto-char (org-element-property :post-affiliated context))
20239 (org-update-dblock)))
20240 (footnote-definition
20241 (goto-char (org-element-property :post-affiliated context))
20242 (call-interactively 'org-footnote-action))
20243 (footnote-reference (call-interactively 'org-footnote-action))
20244 ((headline inlinetask)
20245 (save-excursion (goto-char (org-element-property :begin context))
20246 (call-interactively 'org-set-tags)))
20247 (item
20248 ;; At an item: a double C-u set checkbox to "[-]"
20249 ;; unconditionally, whereas a single one will toggle its
20250 ;; presence. Without an universal argument, if the item
20251 ;; has a checkbox, toggle it. Otherwise repair the list.
20252 (let* ((box (org-element-property :checkbox context))
20253 (struct (org-element-property :structure context))
20254 (old-struct (copy-tree struct))
20255 (parents (org-list-parents-alist struct))
20256 (prevs (org-list-prevs-alist struct))
20257 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20258 (org-list-set-checkbox
20259 (org-element-property :begin context) struct
20260 (cond ((equal arg '(16)) "[-]")
20261 ((and (not box) (equal arg '(4))) "[ ]")
20262 ((or (not box) (equal arg '(4))) nil)
20263 ((eq box 'on) "[ ]")
20264 (t "[X]")))
20265 ;; Mimic `org-list-write-struct' but with grabbing
20266 ;; a return value from `org-list-struct-fix-box'.
20267 (org-list-struct-fix-ind struct parents 2)
20268 (org-list-struct-fix-item-end struct)
20269 (org-list-struct-fix-bul struct prevs)
20270 (org-list-struct-fix-ind struct parents)
20271 (let ((block-item
20272 (org-list-struct-fix-box struct parents prevs orderedp)))
20273 (if (and box (equal struct old-struct))
20274 (if (equal arg '(16))
20275 (message "Checkboxes already reset")
20276 (user-error "Cannot toggle this checkbox: %s"
20277 (if (eq box 'on)
20278 "all subitems checked"
20279 "unchecked subitems")))
20280 (org-list-struct-apply-struct struct old-struct)
20281 (org-update-checkbox-count-maybe))
20282 (when block-item
20283 (message "Checkboxes were removed due to empty box at line %d"
20284 (org-current-line block-item))))))
20285 (keyword
20286 (let ((org-inhibit-startup-visibility-stuff t)
20287 (org-startup-align-all-tables nil))
20288 (when (boundp 'org-table-coordinate-overlays)
20289 (mapc 'delete-overlay org-table-coordinate-overlays)
20290 (setq org-table-coordinate-overlays nil))
20291 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20292 (message "Local setup has been refreshed"))
20293 (plain-list
20294 ;; At a plain list, with a double C-u argument, set
20295 ;; checkboxes of each item to "[-]", whereas a single one
20296 ;; will toggle their presence according to the state of the
20297 ;; first item in the list. Without an argument, repair the
20298 ;; list.
20299 (let* ((begin (org-element-property :contents-begin context))
20300 (beginm (move-marker (make-marker) begin))
20301 (struct (org-element-property :structure context))
20302 (old-struct (copy-tree struct))
20303 (first-box (save-excursion
20304 (goto-char begin)
20305 (looking-at org-list-full-item-re)
20306 (match-string-no-properties 3)))
20307 (new-box (cond ((equal arg '(16)) "[-]")
20308 ((equal arg '(4)) (unless first-box "[ ]"))
20309 ((equal first-box "[X]") "[ ]")
20310 (t "[X]"))))
20311 (cond
20312 (arg
20313 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20314 (org-list-get-all-items
20315 begin struct (org-list-prevs-alist struct))))
20316 ((and first-box (eq (point) begin))
20317 ;; For convenience, when point is at bol on the first
20318 ;; item of the list and no argument is provided, simply
20319 ;; toggle checkbox of that item, if any.
20320 (org-list-set-checkbox begin struct new-box)))
20321 (org-list-write-struct
20322 struct (org-list-parents-alist struct) old-struct)
20323 (org-update-checkbox-count-maybe)
20324 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20325 ((property-drawer node-property)
20326 (call-interactively 'org-property-action))
20327 ((radio-target target)
20328 (call-interactively 'org-update-radio-target-regexp))
20329 (statistics-cookie
20330 (call-interactively 'org-update-statistics-cookies))
20331 ((table table-cell table-row)
20332 ;; At a table, recalculate every field and align it. Also
20333 ;; send the table if necessary. If the table has
20334 ;; a `table.el' type, just give up. At a table row or
20335 ;; cell, maybe recalculate line but always align table.
20336 (if (eq (org-element-property :type context) 'table.el)
20337 (message "Use C-c ' to edit table.el tables")
20338 (let ((org-enable-table-editor t))
20339 (if (or (eq type 'table)
20340 ;; Check if point is at a TBLFM line.
20341 (and (eq type 'table-row)
20342 (= (point) (org-element-property :end context))))
20343 (save-excursion
20344 (if (org-at-TBLFM-p)
20345 (progn (require 'org-table)
20346 (org-table-calc-current-TBLFM))
20347 (goto-char (org-element-property :contents-begin context))
20348 (org-call-with-arg 'org-table-recalculate (or arg t))
20349 (orgtbl-send-table 'maybe)))
20350 (org-table-maybe-eval-formula)
20351 (cond (arg (call-interactively 'org-table-recalculate))
20352 ((org-table-maybe-recalculate-line))
20353 (t (org-table-align)))))))
20354 (timestamp (org-timestamp-change 0 'day))
20355 (otherwise
20356 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20357 (user-error
20358 "C-c C-c can do nothing useful at this location")))))))))
20360 (defun org-mode-restart ()
20361 "Restart Org-mode, to scan again for special lines.
20362 Also updates the keyword regular expressions."
20363 (interactive)
20364 (org-mode)
20365 (message "Org-mode restarted"))
20367 (defun org-kill-note-or-show-branches ()
20368 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20369 (interactive)
20370 (if (not org-finish-function)
20371 (progn
20372 (hide-subtree)
20373 (call-interactively 'show-branches))
20374 (let ((org-note-abort t))
20375 (funcall org-finish-function))))
20377 (defun org-open-line (n)
20378 "Insert a new row in tables, call `open-line' elsewhere.
20379 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20380 (interactive "*p")
20381 (cond
20382 ((not org-special-ctrl-o)
20383 (open-line n))
20384 ((org-at-table-p)
20385 (org-table-insert-row))
20387 (open-line n))))
20389 (defun org-return (&optional indent)
20390 "Goto next table row or insert a newline.
20391 Calls `org-table-next-row' or `newline', depending on context.
20392 See the individual commands for more information."
20393 (interactive)
20394 (let (org-ts-what)
20395 (cond
20396 ((or (bobp) (org-in-src-block-p))
20397 (if indent (newline-and-indent) (newline)))
20398 ((org-at-table-p)
20399 (org-table-justify-field-maybe)
20400 (call-interactively 'org-table-next-row))
20401 ;; when `newline-and-indent' is called within a list, make sure
20402 ;; text moved stays inside the item.
20403 ((and (org-in-item-p) indent)
20404 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20405 (progn
20406 (save-match-data (newline))
20407 (org-indent-line-to (length (match-string 0))))
20408 (let ((ind (org-get-indentation)))
20409 (newline)
20410 (if (org-looking-back org-list-end-re)
20411 (org-indent-line)
20412 (org-indent-line-to ind)))))
20413 ((and org-return-follows-link
20414 (org-at-timestamp-p t)
20415 (not (eq org-ts-what 'after)))
20416 (org-follow-timestamp-link))
20417 ((and org-return-follows-link
20418 (let ((tprop (get-text-property (point) 'face)))
20419 (or (eq tprop 'org-link)
20420 (and (listp tprop) (memq 'org-link tprop)))))
20421 (call-interactively 'org-open-at-point))
20422 ((and (org-at-heading-p)
20423 (looking-at
20424 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20425 (org-show-entry)
20426 (end-of-line 1)
20427 (newline))
20428 (t (if indent (newline-and-indent) (newline))))))
20430 (defun org-return-indent ()
20431 "Goto next table row or insert a newline and indent.
20432 Calls `org-table-next-row' or `newline-and-indent', depending on
20433 context. See the individual commands for more information."
20434 (interactive)
20435 (org-return t))
20437 (defun org-ctrl-c-star ()
20438 "Compute table, or change heading status of lines.
20439 Calls `org-table-recalculate' or `org-toggle-heading',
20440 depending on context."
20441 (interactive)
20442 (cond
20443 ((org-at-table-p)
20444 (call-interactively 'org-table-recalculate))
20446 ;; Convert all lines in region to list items
20447 (call-interactively 'org-toggle-heading))))
20449 (defun org-ctrl-c-minus ()
20450 "Insert separator line in table or modify bullet status of line.
20451 Also turns a plain line or a region of lines into list items.
20452 Calls `org-table-insert-hline', `org-toggle-item', or
20453 `org-cycle-list-bullet', depending on context."
20454 (interactive)
20455 (cond
20456 ((org-at-table-p)
20457 (call-interactively 'org-table-insert-hline))
20458 ((org-region-active-p)
20459 (call-interactively 'org-toggle-item))
20460 ((org-in-item-p)
20461 (call-interactively 'org-cycle-list-bullet))
20463 (call-interactively 'org-toggle-item))))
20465 (defun org-toggle-item (arg)
20466 "Convert headings or normal lines to items, items to normal lines.
20467 If there is no active region, only the current line is considered.
20469 If the first non blank line in the region is a headline, convert
20470 all headlines to items, shifting text accordingly.
20472 If it is an item, convert all items to normal lines.
20474 If it is normal text, change region into a list of items.
20475 With a prefix argument ARG, change the region in a single item."
20476 (interactive "P")
20477 (let ((shift-text
20478 (function
20479 ;; Shift text in current section to IND, from point to END.
20480 ;; The function leaves point to END line.
20481 (lambda (ind end)
20482 (let ((min-i 1000) (end (copy-marker end)))
20483 ;; First determine the minimum indentation (MIN-I) of
20484 ;; the text.
20485 (save-excursion
20486 (catch 'exit
20487 (while (< (point) end)
20488 (let ((i (org-get-indentation)))
20489 (cond
20490 ;; Skip blank lines and inline tasks.
20491 ((looking-at "^[ \t]*$"))
20492 ((looking-at org-outline-regexp-bol))
20493 ;; We can't find less than 0 indentation.
20494 ((zerop i) (throw 'exit (setq min-i 0)))
20495 ((< i min-i) (setq min-i i))))
20496 (forward-line))))
20497 ;; Then indent each line so that a line indented to
20498 ;; MIN-I becomes indented to IND. Ignore blank lines
20499 ;; and inline tasks in the process.
20500 (let ((delta (- ind min-i)))
20501 (while (< (point) end)
20502 (unless (or (looking-at "^[ \t]*$")
20503 (looking-at org-outline-regexp-bol))
20504 (org-indent-line-to (+ (org-get-indentation) delta)))
20505 (forward-line)))))))
20506 (skip-blanks
20507 (function
20508 ;; Return beginning of first non-blank line, starting from
20509 ;; line at POS.
20510 (lambda (pos)
20511 (save-excursion
20512 (goto-char pos)
20513 (skip-chars-forward " \r\t\n")
20514 (point-at-bol)))))
20515 beg end)
20516 ;; Determine boundaries of changes.
20517 (if (org-region-active-p)
20518 (setq beg (funcall skip-blanks (region-beginning))
20519 end (copy-marker (region-end)))
20520 (setq beg (funcall skip-blanks (point-at-bol))
20521 end (copy-marker (point-at-eol))))
20522 ;; Depending on the starting line, choose an action on the text
20523 ;; between BEG and END.
20524 (org-with-limited-levels
20525 (save-excursion
20526 (goto-char beg)
20527 (cond
20528 ;; Case 1. Start at an item: de-itemize. Note that it only
20529 ;; happens when a region is active: `org-ctrl-c-minus'
20530 ;; would call `org-cycle-list-bullet' otherwise.
20531 ((org-at-item-p)
20532 (while (< (point) end)
20533 (when (org-at-item-p)
20534 (skip-chars-forward " \t")
20535 (delete-region (point) (match-end 0)))
20536 (forward-line)))
20537 ;; Case 2. Start at an heading: convert to items.
20538 ((org-at-heading-p)
20539 (let* ((bul (org-list-bullet-string "-"))
20540 (bul-len (length bul))
20541 ;; Indentation of the first heading. It should be
20542 ;; relative to the indentation of its parent, if any.
20543 (start-ind (save-excursion
20544 (cond
20545 ((not org-adapt-indentation) 0)
20546 ((not (outline-previous-heading)) 0)
20547 (t (length (match-string 0))))))
20548 ;; Level of first heading. Further headings will be
20549 ;; compared to it to determine hierarchy in the list.
20550 (ref-level (org-reduced-level (org-outline-level))))
20551 (while (< (point) end)
20552 (let* ((level (org-reduced-level (org-outline-level)))
20553 (delta (max 0 (- level ref-level))))
20554 ;; If current headline is less indented than the first
20555 ;; one, set it as reference, in order to preserve
20556 ;; subtrees.
20557 (when (< level ref-level) (setq ref-level level))
20558 (replace-match bul t t)
20559 (org-indent-line-to (+ start-ind (* delta bul-len)))
20560 ;; Ensure all text down to END (or SECTION-END) belongs
20561 ;; to the newly created item.
20562 (let ((section-end (save-excursion
20563 (or (outline-next-heading) (point)))))
20564 (forward-line)
20565 (funcall shift-text
20566 (+ start-ind (* (1+ delta) bul-len))
20567 (min end section-end)))))))
20568 ;; Case 3. Normal line with ARG: make the first line of region
20569 ;; an item, and shift indentation of others lines to
20570 ;; set them as item's body.
20571 (arg (let* ((bul (org-list-bullet-string "-"))
20572 (bul-len (length bul))
20573 (ref-ind (org-get-indentation)))
20574 (skip-chars-forward " \t")
20575 (insert bul)
20576 (forward-line)
20577 (while (< (point) end)
20578 ;; Ensure that lines less indented than first one
20579 ;; still get included in item body.
20580 (funcall shift-text
20581 (+ ref-ind bul-len)
20582 (min end (save-excursion (or (outline-next-heading)
20583 (point)))))
20584 (forward-line))))
20585 ;; Case 4. Normal line without ARG: turn each non-item line
20586 ;; into an item.
20588 (while (< (point) end)
20589 (unless (or (org-at-heading-p) (org-at-item-p))
20590 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20591 (replace-match
20592 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20593 (forward-line))))))))
20595 (defun org-toggle-heading (&optional nstars)
20596 "Convert headings to normal text, or items or text to headings.
20597 If there is no active region, only convert the current line.
20599 With a \\[universal-argument] prefix, convert the whole list at
20600 point into heading.
20602 In a region:
20604 - If the first non blank line is a headline, remove the stars
20605 from all headlines in the region.
20607 - If it is a normal line, turn each and every normal line (i.e.,
20608 not an heading or an item) in the region into headings. If you
20609 want to convert only the first line of this region, use one
20610 universal prefix argument.
20612 - If it is a plain list item, turn all plain list items into headings.
20614 When converting a line into a heading, the number of stars is chosen
20615 such that the lines become children of the current entry. However,
20616 when a numeric prefix argument is given, its value determines the
20617 number of stars to add."
20618 (interactive "P")
20619 (let ((skip-blanks
20620 (function
20621 ;; Return beginning of first non-blank line, starting from
20622 ;; line at POS.
20623 (lambda (pos)
20624 (save-excursion
20625 (goto-char pos)
20626 (while (org-at-comment-p) (forward-line))
20627 (skip-chars-forward " \r\t\n")
20628 (point-at-bol)))))
20629 beg end toggled)
20630 ;; Determine boundaries of changes. If a universal prefix has
20631 ;; been given, put the list in a region. If region ends at a bol,
20632 ;; do not consider the last line to be in the region.
20634 (when (and current-prefix-arg (org-at-item-p))
20635 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20636 (org-mark-element))
20638 (if (org-region-active-p)
20639 (setq beg (funcall skip-blanks (region-beginning))
20640 end (copy-marker (save-excursion
20641 (goto-char (region-end))
20642 (if (bolp) (point) (point-at-eol)))))
20643 (setq beg (funcall skip-blanks (point-at-bol))
20644 end (copy-marker (point-at-eol))))
20645 ;; Ensure inline tasks don't count as headings.
20646 (org-with-limited-levels
20647 (save-excursion
20648 (goto-char beg)
20649 (cond
20650 ;; Case 1. Started at an heading: de-star headings.
20651 ((org-at-heading-p)
20652 (while (< (point) end)
20653 (when (org-at-heading-p t)
20654 (looking-at org-outline-regexp) (replace-match "")
20655 (setq toggled t))
20656 (forward-line)))
20657 ;; Case 2. Started at an item: change items into headlines.
20658 ;; One star will be added by `org-list-to-subtree'.
20659 ((org-at-item-p)
20660 (let* ((stars (make-string
20661 ;; subtract the star that will be added again by
20662 ;; `org-list-to-subtree'
20663 (if (numberp nstars) (1- nstars)
20664 (or (org-current-level) 0))
20665 ?*))
20666 (add-stars
20667 (cond (nstars "") ; stars from prefix only
20668 ((equal stars "") "") ; before first heading
20669 (org-odd-levels-only "*") ; inside heading, odd
20670 (t "")))) ; inside heading, oddeven
20671 (while (< (point) end)
20672 (when (org-at-item-p)
20673 ;; Pay attention to cases when region ends before list.
20674 (let* ((struct (org-list-struct))
20675 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20676 (save-restriction
20677 (narrow-to-region (point) list-end)
20678 (insert
20679 (org-list-to-subtree
20680 (org-list-parse-list t)
20681 '(:istart (concat stars add-stars (funcall get-stars depth))
20682 :icount (concat stars add-stars (funcall get-stars depth)))))))
20683 (setq toggled t))
20684 (forward-line))))
20685 ;; Case 3. Started at normal text: make every line an heading,
20686 ;; skipping headlines and items.
20687 (t (let* ((stars
20688 (make-string
20689 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20690 (add-stars
20691 (cond (nstars "") ; stars from prefix only
20692 ((equal stars "") "*") ; before first heading
20693 (org-odd-levels-only "**") ; inside heading, odd
20694 (t "*"))) ; inside heading, oddeven
20695 (rpl (concat stars add-stars " "))
20696 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20697 (while (< (point) (if (equal nstars '(4)) lend end))
20698 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20699 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20700 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20701 (forward-line)))))))
20702 (unless toggled (message "Cannot toggle heading from here"))))
20704 (defun org-meta-return (&optional arg)
20705 "Insert a new heading or wrap a region in a table.
20706 Calls `org-insert-heading' or `org-table-wrap-region', depending
20707 on context. See the individual commands for more information."
20708 (interactive "P")
20709 (org-check-before-invisible-edit 'insert)
20710 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20711 (let* ((element (org-element-at-point))
20712 (type (org-element-type element)))
20713 (when (eq type 'table-row)
20714 (setq element (org-element-property :parent element))
20715 (setq type 'table))
20716 (if (and (eq type 'table)
20717 (eq (org-element-property :type element) 'org)
20718 (>= (point) (org-element-property :contents-begin element))
20719 (< (point) (org-element-property :contents-end element)))
20720 (call-interactively 'org-table-wrap-region)
20721 (call-interactively 'org-insert-heading)))))
20723 ;;; Menu entries
20725 (defsubst org-in-subtree-not-table-p ()
20726 "Are we in a subtree and not in a table?"
20727 (and (not (org-before-first-heading-p))
20728 (not (org-at-table-p))))
20730 ;; Define the Org-mode menus
20731 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20732 '("Tbl"
20733 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20734 ["Next Field" org-cycle (org-at-table-p)]
20735 ["Previous Field" org-shifttab (org-at-table-p)]
20736 ["Next Row" org-return (org-at-table-p)]
20737 "--"
20738 ["Blank Field" org-table-blank-field (org-at-table-p)]
20739 ["Edit Field" org-table-edit-field (org-at-table-p)]
20740 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20741 "--"
20742 ("Column"
20743 ["Move Column Left" org-metaleft (org-at-table-p)]
20744 ["Move Column Right" org-metaright (org-at-table-p)]
20745 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20746 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20747 ("Row"
20748 ["Move Row Up" org-metaup (org-at-table-p)]
20749 ["Move Row Down" org-metadown (org-at-table-p)]
20750 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20751 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20752 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20753 "--"
20754 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20755 ("Rectangle"
20756 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20757 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20758 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20759 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20760 "--"
20761 ("Calculate"
20762 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20763 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20764 ["Edit Formulas" org-edit-special (org-at-table-p)]
20765 "--"
20766 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20767 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20768 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20769 "--"
20770 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20771 "--"
20772 ["Sum Column/Rectangle" org-table-sum
20773 (or (org-at-table-p) (org-region-active-p))]
20774 ["Which Column?" org-table-current-column (org-at-table-p)])
20775 ["Debug Formulas"
20776 org-table-toggle-formula-debugger
20777 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20778 ["Show Col/Row Numbers"
20779 org-table-toggle-coordinate-overlays
20780 :style toggle
20781 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20782 "--"
20783 ["Create" org-table-create (and (not (org-at-table-p))
20784 org-enable-table-editor)]
20785 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20786 ["Import from File" org-table-import (not (org-at-table-p))]
20787 ["Export to File" org-table-export (org-at-table-p)]
20788 "--"
20789 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20791 (easy-menu-define org-org-menu org-mode-map "Org menu"
20792 '("Org"
20793 ("Show/Hide"
20794 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20795 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20796 ["Sparse Tree..." org-sparse-tree t]
20797 ["Reveal Context" org-reveal t]
20798 ["Show All" show-all t]
20799 "--"
20800 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20801 "--"
20802 ["New Heading" org-insert-heading t]
20803 ("Navigate Headings"
20804 ["Up" outline-up-heading t]
20805 ["Next" outline-next-visible-heading t]
20806 ["Previous" outline-previous-visible-heading t]
20807 ["Next Same Level" outline-forward-same-level t]
20808 ["Previous Same Level" outline-backward-same-level t]
20809 "--"
20810 ["Jump" org-goto t])
20811 ("Edit Structure"
20812 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20813 "--"
20814 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20815 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20816 "--"
20817 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20818 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20819 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20820 "--"
20821 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20822 "--"
20823 ["Copy visible text" org-copy-visible t]
20824 "--"
20825 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20826 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20827 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20828 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20829 "--"
20830 ["Sort Region/Children" org-sort t]
20831 "--"
20832 ["Convert to odd levels" org-convert-to-odd-levels t]
20833 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20834 ("Editing"
20835 ["Emphasis..." org-emphasize t]
20836 ["Edit Source Example" org-edit-special t]
20837 "--"
20838 ["Footnote new/jump" org-footnote-action t]
20839 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20840 ("Archive"
20841 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20842 "--"
20843 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20844 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20845 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20847 "--"
20848 ("Hyperlinks"
20849 ["Store Link (Global)" org-store-link t]
20850 ["Find existing link to here" org-occur-link-in-agenda-files t]
20851 ["Insert Link" org-insert-link t]
20852 ["Follow Link" org-open-at-point t]
20853 "--"
20854 ["Next link" org-next-link t]
20855 ["Previous link" org-previous-link t]
20856 "--"
20857 ["Descriptive Links"
20858 org-toggle-link-display
20859 :style radio
20860 :selected org-descriptive-links
20862 ["Literal Links"
20863 org-toggle-link-display
20864 :style radio
20865 :selected (not org-descriptive-links)])
20866 "--"
20867 ("TODO Lists"
20868 ["TODO/DONE/-" org-todo t]
20869 ("Select keyword"
20870 ["Next keyword" org-shiftright (org-at-heading-p)]
20871 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20872 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20873 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20874 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20875 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20876 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20877 "--"
20878 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20879 :selected org-enforce-todo-dependencies :style toggle :active t]
20880 "Settings for tree at point"
20881 ["Do Children sequentially" org-toggle-ordered-property :style radio
20882 :selected (org-entry-get nil "ORDERED")
20883 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20884 ["Do Children parallel" org-toggle-ordered-property :style radio
20885 :selected (not (org-entry-get nil "ORDERED"))
20886 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20887 "--"
20888 ["Set Priority" org-priority t]
20889 ["Priority Up" org-shiftup t]
20890 ["Priority Down" org-shiftdown t]
20891 "--"
20892 ["Get news from all feeds" org-feed-update-all t]
20893 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20894 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20895 ("TAGS and Properties"
20896 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20897 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20898 "--"
20899 ["Set property" org-set-property (not (org-before-first-heading-p))]
20900 ["Column view of properties" org-columns t]
20901 ["Insert Column View DBlock" org-insert-columns-dblock t])
20902 ("Dates and Scheduling"
20903 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20904 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20905 ("Change Date"
20906 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20907 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20908 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20909 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20910 ["Compute Time Range" org-evaluate-time-range t]
20911 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20912 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20913 "--"
20914 ["Custom time format" org-toggle-time-stamp-overlays
20915 :style radio :selected org-display-custom-times]
20916 "--"
20917 ["Goto Calendar" org-goto-calendar t]
20918 ["Date from Calendar" org-date-from-calendar t]
20919 "--"
20920 ["Start/Restart Timer" org-timer-start t]
20921 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20922 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20923 ["Insert Timer String" org-timer t]
20924 ["Insert Timer Item" org-timer-item t])
20925 ("Logging work"
20926 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20927 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20928 ["Clock out" org-clock-out t]
20929 ["Clock cancel" org-clock-cancel t]
20930 "--"
20931 ["Mark as default task" org-clock-mark-default-task t]
20932 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20933 ["Goto running clock" org-clock-goto t]
20934 "--"
20935 ["Display times" org-clock-display t]
20936 ["Create clock table" org-clock-report t]
20937 "--"
20938 ["Record DONE time"
20939 (progn (setq org-log-done (not org-log-done))
20940 (message "Switching to %s will %s record a timestamp"
20941 (car org-done-keywords)
20942 (if org-log-done "automatically" "not")))
20943 :style toggle :selected org-log-done])
20944 "--"
20945 ["Agenda Command..." org-agenda t]
20946 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20947 ("File List for Agenda")
20948 ("Special views current file"
20949 ["TODO Tree" org-show-todo-tree t]
20950 ["Check Deadlines" org-check-deadlines t]
20951 ["Timeline" org-timeline t]
20952 ["Tags/Property tree" org-match-sparse-tree t])
20953 "--"
20954 ["Export/Publish..." org-export-dispatch t]
20955 ("LaTeX"
20956 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20957 :selected org-cdlatex-mode]
20958 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20959 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20960 ["Modify math symbol" org-cdlatex-math-modify
20961 (org-inside-LaTeX-fragment-p)]
20962 ["Insert citation" org-reftex-citation t]
20963 "--"
20964 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20965 "--"
20966 ("MobileOrg"
20967 ["Push Files and Views" org-mobile-push t]
20968 ["Get Captured and Flagged" org-mobile-pull t]
20969 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20970 "--"
20971 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20972 "--"
20973 ("Documentation"
20974 ["Show Version" org-version t]
20975 ["Info Documentation" org-info t])
20976 ("Customize"
20977 ["Browse Org Group" org-customize t]
20978 "--"
20979 ["Expand This Menu" org-create-customize-menu
20980 (fboundp 'customize-menu-create)])
20981 ["Send bug report" org-submit-bug-report t]
20982 "--"
20983 ("Refresh/Reload"
20984 ["Refresh setup current buffer" org-mode-restart t]
20985 ["Reload Org (after update)" org-reload t]
20986 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20989 (defun org-info (&optional node)
20990 "Read documentation for Org-mode in the info system.
20991 With optional NODE, go directly to that node."
20992 (interactive)
20993 (info (format "(org)%s" (or node ""))))
20995 ;;;###autoload
20996 (defun org-submit-bug-report ()
20997 "Submit a bug report on Org-mode via mail.
20999 Don't hesitate to report any problems or inaccurate documentation.
21001 If you don't have setup sending mail from (X)Emacs, please copy the
21002 output buffer into your mail program, as it gives us important
21003 information about your Org-mode version and configuration."
21004 (interactive)
21005 (require 'reporter)
21006 (org-load-modules-maybe)
21007 (org-require-autoloaded-modules)
21008 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21009 (reporter-submit-bug-report
21010 "emacs-orgmode@gnu.org"
21011 (org-version nil 'full)
21012 (let (list)
21013 (save-window-excursion
21014 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21015 (delete-other-windows)
21016 (erase-buffer)
21017 (insert "You are about to submit a bug report to the Org-mode mailing list.
21019 We would like to add your full Org-mode and Outline configuration to the
21020 bug report. This greatly simplifies the work of the maintainer and
21021 other experts on the mailing list.
21023 HOWEVER, some variables you have customized may contain private
21024 information. The names of customers, colleagues, or friends, might
21025 appear in the form of file names, tags, todo states, or search strings.
21026 If you answer yes to the prompt, you might want to check and remove
21027 such private information before sending the email.")
21028 (add-text-properties (point-min) (point-max) '(face org-warning))
21029 (when (yes-or-no-p "Include your Org-mode configuration ")
21030 (mapatoms
21031 (lambda (v)
21032 (and (boundp v)
21033 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21034 (or (and (symbol-value v)
21035 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21036 (and
21037 (get v 'custom-type) (get v 'standard-value)
21038 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21039 (push v list)))))
21040 (kill-buffer (get-buffer "*Warn about privacy*"))
21041 list))
21042 nil nil
21043 "Remember to cover the basics, that is, what you expected to happen and
21044 what in fact did happen. You don't know how to make a good report? See
21046 http://orgmode.org/manual/Feedback.html#Feedback
21048 Your bug report will be posted to the Org-mode mailing list.
21049 ------------------------------------------------------------------------")
21050 (save-excursion
21051 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21052 (replace-match "\\1Bug: \\3 [\\2]")))))
21055 (defun org-install-agenda-files-menu ()
21056 (let ((bl (buffer-list)))
21057 (save-excursion
21058 (while bl
21059 (set-buffer (pop bl))
21060 (if (derived-mode-p 'org-mode) (setq bl nil)))
21061 (when (derived-mode-p 'org-mode)
21062 (easy-menu-change
21063 '("Org") "File List for Agenda"
21064 (append
21065 (list
21066 ["Edit File List" (org-edit-agenda-file-list) t]
21067 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21068 ["Remove Current File from List" org-remove-file t]
21069 ["Cycle through agenda files" org-cycle-agenda-files t]
21070 ["Occur in all agenda files" org-occur-in-agenda-files t]
21071 "--")
21072 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21074 ;;;; Documentation
21076 (defun org-require-autoloaded-modules ()
21077 (interactive)
21078 (mapc 'require
21079 '(org-agenda org-archive org-attach org-clock org-colview org-id
21080 org-remember org-table org-timer)))
21082 ;;;###autoload
21083 (defun org-reload (&optional uncompiled)
21084 "Reload all org lisp files.
21085 With prefix arg UNCOMPILED, load the uncompiled versions."
21086 (interactive "P")
21087 (require 'loadhist)
21088 (let* ((org-dir (org-find-library-dir "org"))
21089 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21090 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21091 (remove-re (mapconcat 'identity
21092 (mapcar (lambda (f) (concat "^" f "$"))
21093 (list (if (featurep 'xemacs)
21094 "org-colview"
21095 "org-colview-xemacs")
21096 "org" "org-loaddefs" "org-version"))
21097 "\\|"))
21098 (feats (delete-dups
21099 (mapcar 'file-name-sans-extension
21100 (mapcar 'file-name-nondirectory
21101 (delq nil
21102 (mapcar 'feature-file
21103 features))))))
21104 (lfeat (append
21105 (sort
21106 (setq feats
21107 (delq nil (mapcar
21108 (lambda (f)
21109 (if (and (string-match feature-re f)
21110 (not (string-match remove-re f)))
21111 f nil))
21112 feats)))
21113 'string-lessp)
21114 (list "org-version" "org")))
21115 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21116 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21117 load-uncore load-misses)
21118 (setq load-misses
21119 (delq 't
21120 (mapcar (lambda (f)
21121 (or (org-load-noerror-mustsuffix (concat org-dir f))
21122 (and (string= org-dir contrib-dir)
21123 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21124 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21125 (add-to-list 'load-uncore f 'append)
21128 lfeat)))
21129 (if load-uncore
21130 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21131 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21132 (if load-misses
21133 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21134 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21135 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21137 ;;;###autoload
21138 (defun org-customize ()
21139 "Call the customize function with org as argument."
21140 (interactive)
21141 (org-load-modules-maybe)
21142 (org-require-autoloaded-modules)
21143 (customize-browse 'org))
21145 (defun org-create-customize-menu ()
21146 "Create a full customization menu for Org-mode, insert it into the menu."
21147 (interactive)
21148 (org-load-modules-maybe)
21149 (org-require-autoloaded-modules)
21150 (if (fboundp 'customize-menu-create)
21151 (progn
21152 (easy-menu-change
21153 '("Org") "Customize"
21154 `(["Browse Org group" org-customize t]
21155 "--"
21156 ,(customize-menu-create 'org)
21157 ["Set" Custom-set t]
21158 ["Save" Custom-save t]
21159 ["Reset to Current" Custom-reset-current t]
21160 ["Reset to Saved" Custom-reset-saved t]
21161 ["Reset to Standard Settings" Custom-reset-standard t]))
21162 (message "\"Org\"-menu now contains full customization menu"))
21163 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21165 ;;;; Miscellaneous stuff
21167 ;;; Generally useful functions
21169 (defun org-get-at-bol (property)
21170 "Get text property PROPERTY at beginning of line."
21171 (get-text-property (point-at-bol) property))
21173 (defun org-find-text-property-in-string (prop s)
21174 "Return the first non-nil value of property PROP in string S."
21175 (or (get-text-property 0 prop s)
21176 (get-text-property (or (next-single-property-change 0 prop s) 0)
21177 prop s)))
21179 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21180 "Display the given MESSAGE as a warning."
21181 (if (fboundp 'display-warning)
21182 (display-warning 'org message
21183 (if (featurep 'xemacs) 'warning :warning))
21184 (let ((buf (get-buffer-create "*Org warnings*")))
21185 (with-current-buffer buf
21186 (goto-char (point-max))
21187 (insert "Warning (Org): " message)
21188 (unless (bolp)
21189 (newline)))
21190 (display-buffer buf)
21191 (sit-for 0))))
21193 (defun org-eval (form)
21194 "Eval FORM and return result."
21195 (condition-case error
21196 (eval form)
21197 (error (format "%%![Error: %s]" error))))
21199 (defun org-in-clocktable-p ()
21200 "Check if the cursor is in a clocktable."
21201 (let ((pos (point)) start)
21202 (save-excursion
21203 (end-of-line 1)
21204 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21205 (setq start (match-beginning 0))
21206 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21207 (>= (match-end 0) pos)
21208 start))))
21210 (defun org-in-commented-line ()
21211 "Is point in a line starting with `#'?"
21212 (equal (char-after (point-at-bol)) ?#))
21214 (defun org-in-indented-comment-line ()
21215 "Is point in a line starting with `#' after some white space?"
21216 (save-excursion
21217 (save-match-data
21218 (goto-char (point-at-bol))
21219 (looking-at "[ \t]*#"))))
21221 (defun org-in-verbatim-emphasis ()
21222 (save-match-data
21223 (and (org-in-regexp org-emph-re 2)
21224 (>= (point) (match-beginning 3))
21225 (<= (point) (match-end 4))
21226 (member (match-string 3) '("=" "~")))))
21228 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21229 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21230 (if (and marker (marker-buffer marker)
21231 (buffer-live-p (marker-buffer marker)))
21232 (progn
21233 (org-pop-to-buffer-same-window (marker-buffer marker))
21234 (if (or (> marker (point-max)) (< marker (point-min)))
21235 (widen))
21236 (goto-char marker)
21237 (org-show-context 'org-goto))
21238 (if bookmark
21239 (bookmark-jump bookmark)
21240 (error "Cannot find location"))))
21242 (defun org-quote-csv-field (s)
21243 "Quote field for inclusion in CSV material."
21244 (if (string-match "[\",]" s)
21245 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21248 (defun org-force-self-insert (N)
21249 "Needed to enforce self-insert under remapping."
21250 (interactive "p")
21251 (self-insert-command N))
21253 (defun org-string-width (s)
21254 "Compute width of string, ignoring invisible characters.
21255 This ignores character with invisibility property `org-link', and also
21256 characters with property `org-cwidth', because these will become invisible
21257 upon the next fontification round."
21258 (let (b l)
21259 (when (or (eq t buffer-invisibility-spec)
21260 (assq 'org-link buffer-invisibility-spec))
21261 (while (setq b (text-property-any 0 (length s)
21262 'invisible 'org-link s))
21263 (setq s (concat (substring s 0 b)
21264 (substring s (or (next-single-property-change
21265 b 'invisible s) (length s)))))))
21266 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21267 (setq s (concat (substring s 0 b)
21268 (substring s (or (next-single-property-change
21269 b 'org-cwidth s) (length s))))))
21270 (setq l (string-width s) b -1)
21271 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21272 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21275 (defun org-shorten-string (s maxlength)
21276 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21277 If the string is shorter or has length MAXLENGTH, just return the
21278 original string. If it is longer, the functions finds a space in the
21279 string, breaks this string off at that locations and adds three dots
21280 as ellipsis. Including the ellipsis, the string will not be longer
21281 than MAXLENGTH. If finding a good breaking point in the string does
21282 not work, the string is just chopped off in the middle of a word
21283 if necessary."
21284 (if (<= (length s) maxlength)
21286 (let* ((n (max (- maxlength 4) 1))
21287 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21288 (if (string-match re s)
21289 (concat (match-string 1 s) "...")
21290 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21292 (defun org-get-indentation (&optional line)
21293 "Get the indentation of the current line, interpreting tabs.
21294 When LINE is given, assume it represents a line and compute its indentation."
21295 (if line
21296 (if (string-match "^ *" (org-remove-tabs line))
21297 (match-end 0))
21298 (save-excursion
21299 (beginning-of-line 1)
21300 (skip-chars-forward " \t")
21301 (current-column))))
21303 (defun org-get-string-indentation (s)
21304 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21305 (let ((n -1) (i 0) (w tab-width) c)
21306 (catch 'exit
21307 (while (< (setq n (1+ n)) (length s))
21308 (setq c (aref s n))
21309 (cond ((= c ?\ ) (setq i (1+ i)))
21310 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21311 (t (throw 'exit t)))))
21314 (defun org-remove-tabs (s &optional width)
21315 "Replace tabulators in S with spaces.
21316 Assumes that s is a single line, starting in column 0."
21317 (setq width (or width tab-width))
21318 (while (string-match "\t" s)
21319 (setq s (replace-match
21320 (make-string
21321 (- (* width (/ (+ (match-beginning 0) width) width))
21322 (match-beginning 0)) ?\ )
21323 t t s)))
21326 (defun org-fix-indentation (line ind)
21327 "Fix indentation in LINE.
21328 IND is a cons cell with target and minimum indentation.
21329 If the current indentation in LINE is smaller than the minimum,
21330 leave it alone. If it is larger than ind, set it to the target."
21331 (let* ((l (org-remove-tabs line))
21332 (i (org-get-indentation l))
21333 (i1 (car ind)) (i2 (cdr ind)))
21334 (if (>= i i2) (setq l (substring line i2)))
21335 (if (> i1 0)
21336 (concat (make-string i1 ?\ ) l)
21337 l)))
21339 (defun org-remove-indentation (code &optional n)
21340 "Remove the maximum common indentation from the lines in CODE.
21341 N may optionally be the number of spaces to remove."
21342 (with-temp-buffer
21343 (insert code)
21344 (org-do-remove-indentation n)
21345 (buffer-string)))
21347 (defun org-do-remove-indentation (&optional n)
21348 "Remove the maximum common indentation from the buffer."
21349 (untabify (point-min) (point-max))
21350 (let ((min 10000) re)
21351 (if n
21352 (setq min n)
21353 (goto-char (point-min))
21354 (while (re-search-forward "^ *[^ \n]" nil t)
21355 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21356 (unless (or (= min 0) (= min 10000))
21357 (setq re (format "^ \\{%d\\}" min))
21358 (goto-char (point-min))
21359 (while (re-search-forward re nil t)
21360 (replace-match "")
21361 (end-of-line 1))
21362 min)))
21364 (defun org-fill-template (template alist)
21365 "Find each %key of ALIST in TEMPLATE and replace it."
21366 (let ((case-fold-search nil)
21367 entry key value)
21368 (setq alist (sort (copy-sequence alist)
21369 (lambda (a b) (< (length (car a)) (length (car b))))))
21370 (while (setq entry (pop alist))
21371 (setq template
21372 (replace-regexp-in-string
21373 (concat "%" (regexp-quote (car entry)))
21374 (or (cdr entry) "") template t t)))
21375 template))
21377 (defun org-base-buffer (buffer)
21378 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21379 (if (not buffer)
21380 buffer
21381 (or (buffer-base-buffer buffer)
21382 buffer)))
21384 (defun org-trim (s)
21385 "Remove whitespace at beginning and end of string."
21386 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21387 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21390 (defun org-wrap (string &optional width lines)
21391 "Wrap string to either a number of lines, or a width in characters.
21392 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21393 that costs. If there is a word longer than WIDTH, the text is actually
21394 wrapped to the length of that word.
21395 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21396 many lines, whatever width that takes.
21397 The return value is a list of lines, without newlines at the end."
21398 (let* ((words (org-split-string string "[ \t\n]+"))
21399 (maxword (apply 'max (mapcar 'org-string-width words)))
21400 w ll)
21401 (cond (width
21402 (org-do-wrap words (max maxword width)))
21403 (lines
21404 (setq w maxword)
21405 (setq ll (org-do-wrap words maxword))
21406 (if (<= (length ll) lines)
21408 (setq ll words)
21409 (while (> (length ll) lines)
21410 (setq w (1+ w))
21411 (setq ll (org-do-wrap words w)))
21412 ll))
21413 (t (error "Cannot wrap this")))))
21415 (defun org-do-wrap (words width)
21416 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21417 (let (lines line)
21418 (while words
21419 (setq line (pop words))
21420 (while (and words (< (+ (length line) (length (car words))) width))
21421 (setq line (concat line " " (pop words))))
21422 (setq lines (push line lines)))
21423 (nreverse lines)))
21425 (defun org-split-string (string &optional separators)
21426 "Splits STRING into substrings at SEPARATORS.
21427 No empty strings are returned if there are matches at the beginning
21428 and end of string."
21429 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21430 (start 0)
21431 notfirst
21432 (list nil))
21433 (while (and (string-match rexp string
21434 (if (and notfirst
21435 (= start (match-beginning 0))
21436 (< start (length string)))
21437 (1+ start) start))
21438 (< (match-beginning 0) (length string)))
21439 (setq notfirst t)
21440 (or (eq (match-beginning 0) 0)
21441 (and (eq (match-beginning 0) (match-end 0))
21442 (eq (match-beginning 0) start))
21443 (setq list
21444 (cons (substring string start (match-beginning 0))
21445 list)))
21446 (setq start (match-end 0)))
21447 (or (eq start (length string))
21448 (setq list
21449 (cons (substring string start)
21450 list)))
21451 (nreverse list)))
21453 (defun org-quote-vert (s)
21454 "Replace \"|\" with \"\\vert\"."
21455 (while (string-match "|" s)
21456 (setq s (replace-match "\\vert" t t s)))
21459 (defun org-uuidgen-p (s)
21460 "Is S an ID created by UUIDGEN?"
21461 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21463 (defun org-in-src-block-p (&optional inside)
21464 "Whether point is in a code source block.
21465 When INSIDE is non-nil, don't consider we are within a src block
21466 when point is at #+BEGIN_SRC or #+END_SRC."
21467 (let ((case-fold-search t) ov)
21468 (or (and (setq ov (overlays-at (point)))
21469 (memq 'org-block-background
21470 (overlay-properties (car ov))))
21471 (and (not inside)
21472 (save-match-data
21473 (save-excursion
21474 (beginning-of-line)
21475 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21477 (defun org-context ()
21478 "Return a list of contexts of the current cursor position.
21479 If several contexts apply, all are returned.
21480 Each context entry is a list with a symbol naming the context, and
21481 two positions indicating start and end of the context. Possible
21482 contexts are:
21484 :headline anywhere in a headline
21485 :headline-stars on the leading stars in a headline
21486 :todo-keyword on a TODO keyword (including DONE) in a headline
21487 :tags on the TAGS in a headline
21488 :priority on the priority cookie in a headline
21489 :item on the first line of a plain list item
21490 :item-bullet on the bullet/number of a plain list item
21491 :checkbox on the checkbox in a plain list item
21492 :table in an org-mode table
21493 :table-special on a special filed in a table
21494 :table-table in a table.el table
21495 :clocktable in a clocktable
21496 :src-block in a source block
21497 :link on a hyperlink
21498 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21499 :target on a <<target>>
21500 :radio-target on a <<<radio-target>>>
21501 :latex-fragment on a LaTeX fragment
21502 :latex-preview on a LaTeX fragment with overlaid preview image
21504 This function expects the position to be visible because it uses font-lock
21505 faces as a help to recognize the following contexts: :table-special, :link,
21506 and :keyword."
21507 (let* ((f (get-text-property (point) 'face))
21508 (faces (if (listp f) f (list f)))
21509 (case-fold-search t)
21510 (p (point)) clist o)
21511 ;; First the large context
21512 (cond
21513 ((org-at-heading-p t)
21514 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21515 (when (progn
21516 (beginning-of-line 1)
21517 (looking-at org-todo-line-tags-regexp))
21518 (push (org-point-in-group p 1 :headline-stars) clist)
21519 (push (org-point-in-group p 2 :todo-keyword) clist)
21520 (push (org-point-in-group p 4 :tags) clist))
21521 (goto-char p)
21522 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21523 (if (looking-at "\\[#[A-Z0-9]\\]")
21524 (push (org-point-in-group p 0 :priority) clist)))
21526 ((org-at-item-p)
21527 (push (org-point-in-group p 2 :item-bullet) clist)
21528 (push (list :item (point-at-bol)
21529 (save-excursion (org-end-of-item) (point)))
21530 clist)
21531 (and (org-at-item-checkbox-p)
21532 (push (org-point-in-group p 0 :checkbox) clist)))
21534 ((org-at-table-p)
21535 (push (list :table (org-table-begin) (org-table-end)) clist)
21536 (if (memq 'org-formula faces)
21537 (push (list :table-special
21538 (previous-single-property-change p 'face)
21539 (next-single-property-change p 'face)) clist)))
21540 ((org-at-table-p 'any)
21541 (push (list :table-table) clist)))
21542 (goto-char p)
21544 (let ((case-fold-search t))
21545 ;; New the "medium" contexts: clocktables, source blocks
21546 (cond ((org-in-clocktable-p)
21547 (push (list :clocktable
21548 (and (or (looking-at "#\\+BEGIN: clocktable")
21549 (search-backward "#+BEGIN: clocktable" nil t))
21550 (match-beginning 0))
21551 (and (re-search-forward "#\\+END:?" nil t)
21552 (match-end 0))) clist))
21553 ((org-in-src-block-p)
21554 (push (list :src-block
21555 (and (or (looking-at "#\\+BEGIN_SRC")
21556 (search-backward "#+BEGIN_SRC" nil t))
21557 (match-beginning 0))
21558 (and (search-forward "#+END_SRC" nil t)
21559 (match-beginning 0))) clist))))
21560 (goto-char p)
21562 ;; Now the small context
21563 (cond
21564 ((org-at-timestamp-p)
21565 (push (org-point-in-group p 0 :timestamp) clist))
21566 ((memq 'org-link faces)
21567 (push (list :link
21568 (previous-single-property-change p 'face)
21569 (next-single-property-change p 'face)) clist))
21570 ((memq 'org-special-keyword faces)
21571 (push (list :keyword
21572 (previous-single-property-change p 'face)
21573 (next-single-property-change p 'face)) clist))
21574 ((org-at-target-p)
21575 (push (org-point-in-group p 0 :target) clist)
21576 (goto-char (1- (match-beginning 0)))
21577 (if (looking-at org-radio-target-regexp)
21578 (push (org-point-in-group p 0 :radio-target) clist))
21579 (goto-char p))
21580 ((setq o (car (delq nil
21581 (mapcar
21582 (lambda (x)
21583 (if (memq x org-latex-fragment-image-overlays) x))
21584 (overlays-at (point))))))
21585 (push (list :latex-fragment
21586 (overlay-start o) (overlay-end o)) clist)
21587 (push (list :latex-preview
21588 (overlay-start o) (overlay-end o)) clist))
21589 ((org-inside-LaTeX-fragment-p)
21590 ;; FIXME: positions wrong.
21591 (push (list :latex-fragment (point) (point)) clist)))
21593 (setq clist (nreverse (delq nil clist)))
21594 clist))
21596 ;; FIXME: Compare with at-regexp-p Do we need both?
21597 (defun org-in-regexp (re &optional nlines visually)
21598 "Check if point is inside a match of regexp.
21599 Normally only the current line is checked, but you can include NLINES extra
21600 lines both before and after point into the search.
21601 If VISUALLY is set, require that the cursor is not after the match but
21602 really on, so that the block visually is on the match."
21603 (catch 'exit
21604 (let ((pos (point))
21605 (eol (point-at-eol (+ 1 (or nlines 0))))
21606 (inc (if visually 1 0)))
21607 (save-excursion
21608 (beginning-of-line (- 1 (or nlines 0)))
21609 (while (re-search-forward re eol t)
21610 (if (and (<= (match-beginning 0) pos)
21611 (>= (+ inc (match-end 0)) pos))
21612 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21614 (defun org-at-regexp-p (regexp)
21615 "Is point inside a match of REGEXP in the current line?"
21616 (catch 'exit
21617 (save-excursion
21618 (let ((pos (point)) (end (point-at-eol)))
21619 (beginning-of-line 1)
21620 (while (re-search-forward regexp end t)
21621 (if (and (<= (match-beginning 0) pos)
21622 (>= (match-end 0) pos))
21623 (throw 'exit t)))
21624 nil))))
21626 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21627 "Non-nil when point is between matches of START-RE and END-RE.
21629 Also return a non-nil value when point is on one of the matches.
21631 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21632 buffer positions. Default values are the positions of headlines
21633 surrounding the point.
21635 The functions returns a cons cell whose car (resp. cdr) is the
21636 position before START-RE (resp. after END-RE)."
21637 (save-match-data
21638 (let ((pos (point))
21639 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21640 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21641 beg end)
21642 (save-excursion
21643 ;; Point is on a block when on START-RE or if START-RE can be
21644 ;; found before it...
21645 (and (or (org-at-regexp-p start-re)
21646 (re-search-backward start-re limit-up t))
21647 (setq beg (match-beginning 0))
21648 ;; ... and END-RE after it...
21649 (goto-char (match-end 0))
21650 (re-search-forward end-re limit-down t)
21651 (> (setq end (match-end 0)) pos)
21652 ;; ... without another START-RE in-between.
21653 (goto-char (match-beginning 0))
21654 (not (re-search-backward start-re (1+ beg) t))
21655 ;; Return value.
21656 (cons beg end))))))
21658 (defun org-in-block-p (names)
21659 "Non-nil when point belongs to a block whose name belongs to NAMES.
21661 NAMES is a list of strings containing names of blocks.
21663 Return first block name matched, or nil. Beware that in case of
21664 nested blocks, the returned name may not belong to the closest
21665 block from point."
21666 (save-match-data
21667 (catch 'exit
21668 (let ((case-fold-search t)
21669 (lim-up (save-excursion (outline-previous-heading)))
21670 (lim-down (save-excursion (outline-next-heading))))
21671 (mapc (lambda (name)
21672 (let ((n (regexp-quote name)))
21673 (when (org-between-regexps-p
21674 (concat "^[ \t]*#\\+begin_" n)
21675 (concat "^[ \t]*#\\+end_" n)
21676 lim-up lim-down)
21677 (throw 'exit n))))
21678 names))
21679 nil)))
21681 (defun org-in-drawer-p ()
21682 "Is point within a drawer?"
21683 (save-match-data
21684 (let ((case-fold-search t)
21685 (lim-up (save-excursion (outline-previous-heading)))
21686 (lim-down (save-excursion (outline-next-heading))))
21687 (org-between-regexps-p
21688 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21689 "^[ \t]*:end:.*$"
21690 lim-up lim-down))))
21692 (defun org-occur-in-agenda-files (regexp &optional nlines)
21693 "Call `multi-occur' with buffers for all agenda files."
21694 (interactive "sOrg-files matching: \np")
21695 (let* ((files (org-agenda-files))
21696 (tnames (mapcar 'file-truename files))
21697 (extra org-agenda-text-search-extra-files)
21699 (when (eq (car extra) 'agenda-archives)
21700 (setq extra (cdr extra))
21701 (setq files (org-add-archive-files files)))
21702 (while (setq f (pop extra))
21703 (unless (member (file-truename f) tnames)
21704 (add-to-list 'files f 'append)
21705 (add-to-list 'tnames (file-truename f) 'append)))
21706 (multi-occur
21707 (mapcar (lambda (x)
21708 (with-current-buffer
21709 (or (get-file-buffer x) (find-file-noselect x))
21710 (widen)
21711 (current-buffer)))
21712 files)
21713 regexp)))
21715 (if (boundp 'occur-mode-find-occurrence-hook)
21716 ;; Emacs 23
21717 (add-hook 'occur-mode-find-occurrence-hook
21718 (lambda ()
21719 (when (derived-mode-p 'org-mode)
21720 (org-reveal))))
21721 ;; Emacs 22
21722 (defadvice occur-mode-goto-occurrence
21723 (after org-occur-reveal activate)
21724 (and (derived-mode-p 'org-mode) (org-reveal)))
21725 (defadvice occur-mode-goto-occurrence-other-window
21726 (after org-occur-reveal activate)
21727 (and (derived-mode-p 'org-mode) (org-reveal)))
21728 (defadvice occur-mode-display-occurrence
21729 (after org-occur-reveal activate)
21730 (when (derived-mode-p 'org-mode)
21731 (let ((pos (occur-mode-find-occurrence)))
21732 (with-current-buffer (marker-buffer pos)
21733 (save-excursion
21734 (goto-char pos)
21735 (org-reveal)))))))
21737 (defun org-occur-link-in-agenda-files ()
21738 "Create a link and search for it in the agendas.
21739 The link is not stored in `org-stored-links', it is just created
21740 for the search purpose."
21741 (interactive)
21742 (let ((link (condition-case nil
21743 (org-store-link nil)
21744 (error "Unable to create a link to here"))))
21745 (org-occur-in-agenda-files (regexp-quote link))))
21747 (defun org-reverse-string (string)
21748 "Return the reverse of STRING."
21749 (apply 'string (reverse (string-to-list string))))
21751 (defsubst org-uniquify (list)
21752 "Non-destructively remove duplicate elements from LIST."
21753 (let ((res (copy-sequence list))) (delete-dups res)))
21755 (defun org-uniquify-alist (alist)
21756 "Merge elements of ALIST with the same key.
21758 For example, in this alist:
21760 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21761 => '((a 1 3) (b 2))
21763 merge (a 1) and (a 3) into (a 1 3).
21765 The function returns the new ALIST."
21766 (let (rtn)
21767 (mapc
21768 (lambda (e)
21769 (let (n)
21770 (if (not (assoc (car e) rtn))
21771 (push e rtn)
21772 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21773 (setq rtn (assq-delete-all (car e) rtn))
21774 (push n rtn))))
21775 alist)
21776 rtn))
21778 (defun org-delete-all (elts list)
21779 "Remove all elements in ELTS from LIST."
21780 (while elts
21781 (setq list (delete (pop elts) list)))
21782 list)
21784 (defun org-count (cl-item cl-seq)
21785 "Count the number of occurrences of ITEM in SEQ.
21786 Taken from `count' in cl-seq.el with all keyword arguments removed."
21787 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21788 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21789 (while (< cl-start cl-end)
21790 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21791 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21792 (setq cl-start (1+ cl-start)))
21793 cl-count))
21795 (defun org-remove-if (predicate seq)
21796 "Remove everything from SEQ that fulfills PREDICATE."
21797 (let (res e)
21798 (while seq
21799 (setq e (pop seq))
21800 (if (not (funcall predicate e)) (push e res)))
21801 (nreverse res)))
21803 (defun org-remove-if-not (predicate seq)
21804 "Remove everything from SEQ that does not fulfill PREDICATE."
21805 (let (res e)
21806 (while seq
21807 (setq e (pop seq))
21808 (if (funcall predicate e) (push e res)))
21809 (nreverse res)))
21811 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21812 "Reduce two-argument FUNCTION across SEQ.
21813 Taken from `reduce' in cl-seq.el with all keyword arguments but
21814 \":initial-value\" removed."
21815 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21816 (cadr (memq :initial-value cl-keys)))
21817 (cl-seq (pop cl-seq))
21818 (t (funcall cl-func)))))
21819 (while cl-seq
21820 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21821 cl-accum))
21823 (defun org-every (pred seq)
21824 "Return true if PREDICATE is true of every element of SEQ.
21825 Adapted from `every' in cl.el."
21826 (catch 'org-every
21827 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21830 (defun org-some (pred seq)
21831 "Return true if PREDICATE is true of any element of SEQ.
21832 Adapted from `some' in cl.el."
21833 (catch 'org-some
21834 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21835 nil))
21837 (defun org-back-over-empty-lines ()
21838 "Move backwards over whitespace, to the beginning of the first empty line.
21839 Returns the number of empty lines passed."
21840 (let ((pos (point)))
21841 (if (cdr (assoc 'heading org-blank-before-new-entry))
21842 (skip-chars-backward " \t\n\r")
21843 (unless (eobp)
21844 (forward-line -1)))
21845 (beginning-of-line 2)
21846 (goto-char (min (point) pos))
21847 (count-lines (point) pos)))
21849 (defun org-skip-whitespace ()
21850 (skip-chars-forward " \t\n\r"))
21852 (defun org-point-in-group (point group &optional context)
21853 "Check if POINT is in match-group GROUP.
21854 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21855 match. If the match group does not exist or point is not inside it,
21856 return nil."
21857 (and (match-beginning group)
21858 (>= point (match-beginning group))
21859 (<= point (match-end group))
21860 (if context
21861 (list context (match-beginning group) (match-end group))
21862 t)))
21864 (defun org-switch-to-buffer-other-window (&rest args)
21865 "Switch to buffer in a second window on the current frame.
21866 In particular, do not allow pop-up frames.
21867 Returns the newly created buffer."
21868 (org-no-popups
21869 (apply 'switch-to-buffer-other-window args)))
21871 (defun org-combine-plists (&rest plists)
21872 "Create a single property list from all plists in PLISTS.
21873 The process starts by copying the first list, and then setting properties
21874 from the other lists. Settings in the last list are the most significant
21875 ones and overrule settings in the other lists."
21876 (let ((rtn (copy-sequence (pop plists)))
21877 p v ls)
21878 (while plists
21879 (setq ls (pop plists))
21880 (while ls
21881 (setq p (pop ls) v (pop ls))
21882 (setq rtn (plist-put rtn p v))))
21883 rtn))
21885 (defun org-replace-escapes (string table)
21886 "Replace %-escapes in STRING with values in TABLE.
21887 TABLE is an association list with keys like \"%a\" and string values.
21888 The sequences in STRING may contain normal field width and padding information,
21889 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21890 so values can contain further %-escapes if they are define later in TABLE."
21891 (let ((tbl (copy-alist table))
21892 (case-fold-search nil)
21893 (pchg 0)
21894 e re rpl)
21895 (while (setq e (pop tbl))
21896 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21897 (when (and (cdr e) (string-match re (cdr e)))
21898 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21899 (safe "SREF"))
21900 (add-text-properties 0 3 (list 'sref sref) safe)
21901 (setcdr e (replace-match safe t t (cdr e)))))
21902 (while (string-match re string)
21903 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21904 (cdr e)))
21905 (setq string (replace-match rpl t t string))))
21906 (while (setq pchg (next-property-change pchg string))
21907 (let ((sref (get-text-property pchg 'sref string)))
21908 (when (and sref (string-match "SREF" string pchg))
21909 (setq string (replace-match sref t t string)))))
21910 string))
21912 (defun org-sublist (list start end)
21913 "Return a section of LIST, from START to END.
21914 Counting starts at 1."
21915 (let (rtn (c start))
21916 (setq list (nthcdr (1- start) list))
21917 (while (and list (<= c end))
21918 (push (pop list) rtn)
21919 (setq c (1+ c)))
21920 (nreverse rtn)))
21922 (defun org-find-base-buffer-visiting (file)
21923 "Like `find-buffer-visiting' but always return the base buffer and
21924 not an indirect buffer."
21925 (let ((buf (or (get-file-buffer file)
21926 (find-buffer-visiting file))))
21927 (if buf
21928 (or (buffer-base-buffer buf) buf)
21929 nil)))
21931 (defun org-image-file-name-regexp (&optional extensions)
21932 "Return regexp matching the file names of images.
21933 If EXTENSIONS is given, only match these."
21934 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21935 (image-file-name-regexp)
21936 (let ((image-file-name-extensions
21937 (or extensions
21938 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21939 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21940 (concat "\\."
21941 (regexp-opt (nconc (mapcar 'upcase
21942 image-file-name-extensions)
21943 image-file-name-extensions)
21945 "\\'"))))
21947 (defun org-file-image-p (file &optional extensions)
21948 "Return non-nil if FILE is an image."
21949 (save-match-data
21950 (string-match (org-image-file-name-regexp extensions) file)))
21952 (defun org-get-cursor-date (&optional with-time)
21953 "Return the date at cursor in as a time.
21954 This works in the calendar and in the agenda, anywhere else it just
21955 returns the current time.
21956 If WITH-TIME is non-nil, returns the time of the event at point (in
21957 the agenda) or the current time of the day."
21958 (let (date day defd tp tm hod mod)
21959 (when with-time
21960 (setq tp (get-text-property (point) 'time))
21961 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21962 (setq hod (string-to-number (match-string 1 tp))
21963 mod (string-to-number (match-string 2 tp))))
21964 (or tp (setq hod (nth 2 (decode-time (current-time)))
21965 mod (nth 1 (decode-time (current-time))))))
21966 (cond
21967 ((eq major-mode 'calendar-mode)
21968 (setq date (calendar-cursor-to-date)
21969 defd (encode-time 0 (or mod 0) (or hod 0)
21970 (nth 1 date) (nth 0 date) (nth 2 date))))
21971 ((eq major-mode 'org-agenda-mode)
21972 (setq day (get-text-property (point) 'day))
21973 (if day
21974 (setq date (calendar-gregorian-from-absolute day)
21975 defd (encode-time 0 (or mod 0) (or hod 0)
21976 (nth 1 date) (nth 0 date) (nth 2 date))))))
21977 (or defd (current-time))))
21979 (defun org-mark-subtree (&optional up)
21980 "Mark the current subtree.
21981 This puts point at the start of the current subtree, and mark at
21982 the end. If a numeric prefix UP is given, move up into the
21983 hierarchy of headlines by UP levels before marking the subtree."
21984 (interactive "P")
21985 (org-with-limited-levels
21986 (cond ((org-at-heading-p) (beginning-of-line))
21987 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21988 (t (outline-previous-visible-heading 1))))
21989 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21990 (if (org-called-interactively-p 'any)
21991 (call-interactively 'org-mark-element)
21992 (org-mark-element)))
21995 ;;; Indentation
21997 (defun org-indent-line ()
21998 "Indent line depending on context."
21999 (interactive)
22000 (let* ((pos (point))
22001 (itemp (org-at-item-p))
22002 (case-fold-search t)
22003 (org-drawer-regexp (or org-drawer-regexp "\000"))
22004 (inline-task-p (and (featurep 'org-inlinetask)
22005 (org-inlinetask-in-task-p)))
22006 (inline-re (and inline-task-p
22007 (org-inlinetask-outline-regexp)))
22008 column)
22009 (if (and orgstruct-is-++ (eq pos (point)))
22010 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22011 (indent-according-to-mode))
22012 (beginning-of-line 1)
22013 (cond
22014 ;; Headings
22015 ((looking-at org-outline-regexp) (setq column 0))
22016 ;; Footnote definition
22017 ((looking-at org-footnote-definition-re) (setq column 0))
22018 ;; Literal examples
22019 ((looking-at "[ \t]*:\\( \\|$\\)")
22020 (setq column (org-get-indentation))) ; do nothing
22021 ;; Lists
22022 ((ignore-errors (goto-char (org-in-item-p)))
22023 (setq column (if itemp
22024 (org-get-indentation)
22025 (org-list-item-body-column (point))))
22026 (goto-char pos))
22027 ;; Drawers
22028 ((and (looking-at "[ \t]*:END:")
22029 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22030 (save-excursion
22031 (goto-char (1- (match-beginning 1)))
22032 (setq column (current-column))))
22033 ;; Special blocks
22034 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22035 (save-excursion
22036 (re-search-backward
22037 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22038 (setq column (org-get-indentation (match-string 0))))
22039 ((and (not (looking-at "[ \t]*#\\+begin_"))
22040 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22041 (save-excursion
22042 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22043 (setq column
22044 (cond ((equal (downcase (match-string 1)) "src")
22045 ;; src blocks: let `org-edit-src-exit' handle them
22046 (org-get-indentation))
22047 ((equal (downcase (match-string 1)) "example")
22048 (max (org-get-indentation)
22049 (org-get-indentation (match-string 0))))
22051 (org-get-indentation (match-string 0))))))
22052 ;; This line has nothing special, look at the previous relevant
22053 ;; line to compute indentation
22055 (beginning-of-line 0)
22056 (while (and (not (bobp))
22057 (not (looking-at org-table-line-regexp))
22058 (not (looking-at org-drawer-regexp))
22059 ;; When point started in an inline task, do not move
22060 ;; above task starting line.
22061 (not (and inline-task-p (looking-at inline-re)))
22062 ;; Skip drawers, blocks, empty lines, verbatim,
22063 ;; comments, tables, footnotes definitions, lists,
22064 ;; inline tasks.
22065 (or (and (looking-at "[ \t]*:END:")
22066 (re-search-backward org-drawer-regexp nil t))
22067 (and (looking-at "[ \t]*#\\+end_")
22068 (re-search-backward "[ \t]*#\\+begin_"nil t))
22069 (looking-at "[ \t]*[\n:#|]")
22070 (looking-at org-footnote-definition-re)
22071 (and (not inline-task-p)
22072 (featurep 'org-inlinetask)
22073 (org-inlinetask-in-task-p)
22074 (or (org-inlinetask-goto-beginning) t))))
22075 (beginning-of-line 0))
22076 (cond
22077 ;; There was a list item above.
22078 ((ignore-errors (goto-char (org-in-item-p)))
22079 (goto-char (org-list-get-top-point (org-list-struct)))
22080 (setq column (org-get-indentation)))
22081 ;; There was an heading above.
22082 ((looking-at "\\*+[ \t]+")
22083 (if (not org-adapt-indentation)
22084 (setq column 0)
22085 (goto-char (match-end 0))
22086 (setq column (current-column))))
22087 ;; A drawer had started and is unfinished
22088 ((looking-at org-drawer-regexp)
22089 (goto-char (1- (match-beginning 1)))
22090 (setq column (current-column)))
22091 ;; Else, nothing noticeable found: get indentation and go on.
22092 (t (setq column (org-get-indentation))))))
22093 ;; Now apply indentation and move cursor accordingly
22094 (goto-char pos)
22095 (if (<= (current-column) (current-indentation))
22096 (org-indent-line-to column)
22097 (save-excursion (org-indent-line-to column)))
22098 ;; Special polishing for properties, see `org-property-format'
22099 (setq column (current-column))
22100 (beginning-of-line 1)
22101 (if (looking-at org-property-re)
22102 (replace-match (concat (match-string 4)
22103 (format org-property-format
22104 (match-string 1) (match-string 3)))
22105 t t))
22106 (org-move-to-column column))))
22108 (defun org-indent-drawer ()
22109 "Indent the drawer at point."
22110 (interactive)
22111 (let ((p (point))
22112 (e (and (save-excursion (re-search-forward ":END:" nil t))
22113 (match-end 0)))
22114 (folded
22115 (save-excursion
22116 (end-of-line)
22117 (when (overlays-at (point))
22118 (member 'invisible (overlay-properties
22119 (car (overlays-at (point)))))))))
22120 (when folded (org-cycle))
22121 (indent-for-tab-command)
22122 (while (and (move-beginning-of-line 2) (< (point) e))
22123 (indent-for-tab-command))
22124 (goto-char p)
22125 (when folded (org-cycle)))
22126 (message "Drawer at point indented"))
22128 (defun org-indent-block ()
22129 "Indent the block at point."
22130 (interactive)
22131 (let ((p (point))
22132 (case-fold-search t)
22133 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22134 (match-end 0)))
22135 (folded
22136 (save-excursion
22137 (end-of-line)
22138 (when (overlays-at (point))
22139 (member 'invisible (overlay-properties
22140 (car (overlays-at (point)))))))))
22141 (when folded (org-cycle))
22142 (indent-for-tab-command)
22143 (while (and (move-beginning-of-line 2) (< (point) e))
22144 (indent-for-tab-command))
22145 (goto-char p)
22146 (when folded (org-cycle)))
22147 (message "Block at point indented"))
22149 (defun org-indent-region (start end)
22150 "Indent region."
22151 (interactive "r")
22152 (save-excursion
22153 (let ((line-end (org-current-line end)))
22154 (goto-char start)
22155 (while (< (org-current-line) line-end)
22156 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22157 (t (call-interactively 'org-indent-line)))
22158 (move-beginning-of-line 2)))))
22161 ;;; Filling
22163 ;; We use our own fill-paragraph and auto-fill functions.
22165 ;; `org-fill-paragraph' relies on adaptive filling and context
22166 ;; checking. Appropriate `fill-prefix' is computed with
22167 ;; `org-adaptive-fill-function'.
22169 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22170 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22171 ;; `org-adaptive-fill-function' value. Internally,
22172 ;; `org-comment-line-break-function' breaks the line.
22174 ;; `org-setup-filling' installs filling and auto-filling related
22175 ;; variables during `org-mode' initialization.
22177 (defvar org-element-paragraph-separate) ; org-element.el
22178 (defun org-setup-filling ()
22179 (require 'org-element)
22180 ;; Prevent auto-fill from inserting unwanted new items.
22181 (when (boundp 'fill-nobreak-predicate)
22182 (org-set-local
22183 'fill-nobreak-predicate
22184 (org-uniquify
22185 (append fill-nobreak-predicate
22186 '(org-fill-line-break-nobreak-p
22187 org-fill-paragraph-with-timestamp-nobreak-p)))))
22188 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22189 (org-set-local 'paragraph-start paragraph-ending)
22190 (org-set-local 'paragraph-separate paragraph-ending))
22191 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22192 (org-set-local 'auto-fill-inhibit-regexp nil)
22193 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22194 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22195 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22197 (defun org-fill-line-break-nobreak-p ()
22198 "Non-nil when a new line at point would create an Org line break."
22199 (save-excursion
22200 (skip-chars-backward "[ \t]")
22201 (skip-chars-backward "\\\\")
22202 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22204 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22205 "Non-nil when a new line at point would split a timestamp."
22206 (and (org-at-timestamp-p t)
22207 (not (looking-at org-ts-regexp-both))))
22209 (declare-function message-in-body-p "message" ())
22210 (defvar orgtbl-line-start-regexp) ; From org-table.el
22211 (defun org-adaptive-fill-function ()
22212 "Compute a fill prefix for the current line.
22213 Return fill prefix, as a string, or nil if current line isn't
22214 meant to be filled. For convenience, if `adaptive-fill-regexp'
22215 matches in paragraphs or comments, use it."
22216 (catch 'exit
22217 (when (derived-mode-p 'message-mode)
22218 (save-excursion
22219 (beginning-of-line)
22220 (cond ((or (not (message-in-body-p))
22221 (looking-at orgtbl-line-start-regexp))
22222 (throw 'exit nil))
22223 ((looking-at message-cite-prefix-regexp)
22224 (throw 'exit (match-string-no-properties 0)))
22225 ((looking-at org-outline-regexp)
22226 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22227 (org-with-wide-buffer
22228 (let* ((p (line-beginning-position))
22229 (element (save-excursion
22230 (beginning-of-line)
22231 (or (ignore-errors (org-element-at-point))
22232 (user-error "An element cannot be parsed line %d"
22233 (line-number-at-pos (point))))))
22234 (type (org-element-type element))
22235 (post-affiliated (org-element-property :post-affiliated element)))
22236 (unless (and post-affiliated (< p post-affiliated))
22237 (case type
22238 (comment
22239 (save-excursion
22240 (beginning-of-line)
22241 (looking-at "[ \t]*")
22242 (concat (match-string 0) "# ")))
22243 (footnote-definition "")
22244 ((item plain-list)
22245 (make-string (org-list-item-body-column
22246 (or post-affiliated
22247 (org-element-property :begin element)))
22248 ? ))
22249 (paragraph
22250 ;; Fill prefix is usually the same as the current line,
22251 ;; unless the paragraph is at the beginning of an item.
22252 (let ((parent (org-element-property :parent element)))
22253 (save-excursion
22254 (beginning-of-line)
22255 (cond ((eq (org-element-type parent) 'item)
22256 (make-string (org-list-item-body-column
22257 (org-element-property :begin parent))
22258 ? ))
22259 ((and adaptive-fill-regexp
22260 ;; Locally disable
22261 ;; `adaptive-fill-function' to let
22262 ;; `fill-context-prefix' handle
22263 ;; `adaptive-fill-regexp' variable.
22264 (let (adaptive-fill-function)
22265 (fill-context-prefix
22266 post-affiliated
22267 (org-element-property :end element)))))
22268 ((looking-at "[ \t]+") (match-string 0))
22269 (t "")))))
22270 (comment-block
22271 ;; Only fill contents if P is within block boundaries.
22272 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22273 (forward-line)
22274 (point)))
22275 (cend (save-excursion
22276 (goto-char (org-element-property :end element))
22277 (skip-chars-backward " \r\t\n")
22278 (line-beginning-position))))
22279 (when (and (>= p cbeg) (< p cend))
22280 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22281 (match-string 0)
22282 ""))))))))))
22284 (declare-function message-goto-body "message" ())
22285 (defvar message-cite-prefix-regexp) ; From message.el
22286 (defun org-fill-paragraph (&optional justify)
22287 "Fill element at point, when applicable.
22289 This function only applies to comment blocks, comments, example
22290 blocks and paragraphs. Also, as a special case, re-align table
22291 when point is at one.
22293 If JUSTIFY is non-nil (interactively, with prefix argument),
22294 justify as well. If `sentence-end-double-space' is non-nil, then
22295 period followed by one space does not end a sentence, so don't
22296 break a line there. The variable `fill-column' controls the
22297 width for filling.
22299 For convenience, when point is at a plain list, an item or
22300 a footnote definition, try to fill the first paragraph within."
22301 (interactive)
22302 (if (and (derived-mode-p 'message-mode)
22303 (or (not (message-in-body-p))
22304 (save-excursion (move-beginning-of-line 1)
22305 (looking-at message-cite-prefix-regexp))))
22306 ;; First ensure filling is correct in message-mode.
22307 (let ((fill-paragraph-function
22308 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22309 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22310 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22311 (paragraph-separate
22312 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22313 (fill-paragraph nil))
22314 (with-syntax-table org-mode-transpose-word-syntax-table
22315 ;; Move to end of line in order to get the first paragraph
22316 ;; within a plain list or a footnote definition.
22317 (let ((element (save-excursion
22318 (end-of-line)
22319 (or (ignore-errors (org-element-at-point))
22320 (user-error "An element cannot be parsed line %d"
22321 (line-number-at-pos (point)))))))
22322 ;; First check if point is in a blank line at the beginning of
22323 ;; the buffer. In that case, ignore filling.
22324 (case (org-element-type element)
22325 ;; Use major mode filling function is src blocks.
22326 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22327 ;; Align Org tables, leave table.el tables as-is.
22328 (table-row (org-table-align) t)
22329 (table
22330 (when (eq (org-element-property :type element) 'org)
22331 (save-excursion
22332 (goto-char (org-element-property :post-affiliated element))
22333 (org-table-align)))
22335 (paragraph
22336 ;; Paragraphs may contain `line-break' type objects.
22337 (let ((beg (max (point-min)
22338 (org-element-property :contents-begin element)))
22339 (end (min (point-max)
22340 (org-element-property :contents-end element))))
22341 ;; Do nothing if point is at an affiliated keyword.
22342 (if (< (line-end-position) beg) t
22343 (when (derived-mode-p 'message-mode)
22344 ;; In `message-mode', do not fill following citation
22345 ;; in current paragraph nor text before message body.
22346 (let ((body-start (save-excursion (message-goto-body))))
22347 (when body-start (setq beg (max body-start beg))))
22348 (when (save-excursion
22349 (re-search-forward
22350 (concat "^" message-cite-prefix-regexp) end t))
22351 (setq end (match-beginning 0))))
22352 ;; Fill paragraph, taking line breaks into account.
22353 ;; For that, slice the paragraph using line breaks as
22354 ;; separators, and fill the parts in reverse order to
22355 ;; avoid messing with markers.
22356 (save-excursion
22357 (goto-char end)
22358 (mapc
22359 (lambda (pos)
22360 (fill-region-as-paragraph pos (point) justify)
22361 (goto-char pos))
22362 ;; Find the list of ending positions for line breaks
22363 ;; in the current paragraph. Add paragraph
22364 ;; beginning to include first slice.
22365 (nreverse
22366 (cons beg
22367 (org-element-map
22368 (org-element--parse-objects
22369 beg end nil (org-element-restriction 'paragraph))
22370 'line-break
22371 (lambda (lb) (org-element-property :end lb)))))))
22372 t)))
22373 ;; Contents of `comment-block' type elements should be
22374 ;; filled as plain text, but only if point is within block
22375 ;; markers.
22376 (comment-block
22377 (let* ((case-fold-search t)
22378 (beg (save-excursion
22379 (goto-char (org-element-property :begin element))
22380 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22381 (forward-line)
22382 (point)))
22383 (end (save-excursion
22384 (goto-char (org-element-property :end element))
22385 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22386 (line-beginning-position))))
22387 (if (or (< (point) beg) (> (point) end)) t
22388 (fill-region-as-paragraph
22389 (save-excursion (end-of-line)
22390 (re-search-backward "^[ \t]*$" beg 'move)
22391 (line-beginning-position))
22392 (save-excursion (beginning-of-line)
22393 (re-search-forward "^[ \t]*$" end 'move)
22394 (line-beginning-position))
22395 justify))))
22396 ;; Fill comments.
22397 (comment
22398 (let ((begin (org-element-property :post-affiliated element))
22399 (end (org-element-property :end element)))
22400 (when (and (>= (point) begin) (<= (point) end))
22401 (let ((begin (save-excursion
22402 (end-of-line)
22403 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22404 (progn (forward-line) (point))
22405 begin)))
22406 (end (save-excursion
22407 (end-of-line)
22408 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22409 (1- (line-beginning-position))
22410 (skip-chars-backward " \r\t\n")
22411 (line-end-position)))))
22412 ;; Do not fill comments when at a blank line.
22413 (when (> end begin)
22414 (let ((fill-prefix
22415 (save-excursion
22416 (beginning-of-line)
22417 (looking-at "[ \t]*#")
22418 (let ((comment-prefix (match-string 0)))
22419 (goto-char (match-end 0))
22420 (if (looking-at adaptive-fill-regexp)
22421 (concat comment-prefix (match-string 0))
22422 (concat comment-prefix " "))))))
22423 (save-excursion
22424 (fill-region-as-paragraph begin end justify))))))
22426 ;; Ignore every other element.
22427 (otherwise t))))))
22429 (defun org-auto-fill-function ()
22430 "Auto-fill function."
22431 ;; Check if auto-filling is meaningful.
22432 (let ((fc (current-fill-column)))
22433 (when (and fc (> (current-column) fc))
22434 (let* ((fill-prefix (org-adaptive-fill-function))
22435 ;; Enforce empty fill prefix, if required. Otherwise, it
22436 ;; will be computed again.
22437 (adaptive-fill-mode (not (equal fill-prefix ""))))
22438 (when fill-prefix (do-auto-fill))))))
22440 (defun org-comment-line-break-function (&optional soft)
22441 "Break line at point and indent, continuing comment if within one.
22442 The inserted newline is marked hard if variable
22443 `use-hard-newlines' is true, unless optional argument SOFT is
22444 non-nil."
22445 (if soft (insert-and-inherit ?\n) (newline 1))
22446 (save-excursion (forward-char -1) (delete-horizontal-space))
22447 (delete-horizontal-space)
22448 (indent-to-left-margin)
22449 (insert-before-markers-and-inherit fill-prefix))
22452 ;;; Comments
22454 ;; Org comments syntax is quite complex. It requires the entire line
22455 ;; to be just a comment. Also, even with the right syntax at the
22456 ;; beginning of line, some some elements (i.e. verse-block or
22457 ;; example-block) don't accept comments. Usual Emacs comment commands
22458 ;; cannot cope with those requirements. Therefore, Org replaces them.
22460 ;; Org still relies on `comment-dwim', but cannot trust
22461 ;; `comment-only-p'. So, `comment-region-function' and
22462 ;; `uncomment-region-function' both point
22463 ;; to`org-comment-or-uncomment-region'. Eventually,
22464 ;; `org-insert-comment' takes care of insertion of comments at the
22465 ;; beginning of line.
22467 ;; `org-setup-comments-handling' install comments related variables
22468 ;; during `org-mode' initialization.
22470 (defun org-setup-comments-handling ()
22471 (interactive)
22472 (org-set-local 'comment-use-syntax nil)
22473 (org-set-local 'comment-start "# ")
22474 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22475 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22476 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22477 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22479 (defun org-insert-comment ()
22480 "Insert an empty comment above current line.
22481 If the line is empty, insert comment at its beginning."
22482 (beginning-of-line)
22483 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22484 (org-indent-line)
22485 (insert "# "))
22487 (defvar comment-empty-lines) ; From newcomment.el.
22488 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22489 "Comment or uncomment each non-blank line in the region.
22490 Uncomment each non-blank line between BEG and END if it only
22491 contains commented lines. Otherwise, comment them."
22492 (save-restriction
22493 ;; Restrict region
22494 (narrow-to-region (save-excursion (goto-char beg)
22495 (skip-chars-forward " \r\t\n" end)
22496 (line-beginning-position))
22497 (save-excursion (goto-char end)
22498 (skip-chars-backward " \r\t\n" beg)
22499 (line-end-position)))
22500 (let ((uncommentp
22501 ;; UNCOMMENTP is non-nil when every non blank line between
22502 ;; BEG and END is a comment.
22503 (save-excursion
22504 (goto-char (point-min))
22505 (while (and (not (eobp))
22506 (let ((element (org-element-at-point)))
22507 (and (eq (org-element-type element) 'comment)
22508 (goto-char (min (point-max)
22509 (org-element-property
22510 :end element)))))))
22511 (eobp))))
22512 (if uncommentp
22513 ;; Only blank lines and comments in region: uncomment it.
22514 (save-excursion
22515 (goto-char (point-min))
22516 (while (not (eobp))
22517 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22518 (replace-match "" nil nil nil 1))
22519 (forward-line)))
22520 ;; Comment each line in region.
22521 (let ((min-indent (point-max)))
22522 ;; First find the minimum indentation across all lines.
22523 (save-excursion
22524 (goto-char (point-min))
22525 (while (and (not (eobp)) (not (zerop min-indent)))
22526 (unless (looking-at "[ \t]*$")
22527 (setq min-indent (min min-indent (current-indentation))))
22528 (forward-line)))
22529 ;; Then loop over all lines.
22530 (save-excursion
22531 (goto-char (point-min))
22532 (while (not (eobp))
22533 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22534 ;; Don't get fooled by invisible text (e.g. link path)
22535 ;; when moving to column MIN-INDENT.
22536 (let ((buffer-invisibility-spec nil))
22537 (org-move-to-column min-indent t))
22538 (insert comment-start))
22539 (forward-line))))))))
22542 ;;; Planning
22544 ;; This section contains tools to operate on timestamp objects, as
22545 ;; returned by, e.g. `org-element-context'.
22547 (defun org-timestamp-has-time-p (timestamp)
22548 "Non-nil when TIMESTAMP has a time specified."
22549 (org-element-property :hour-start timestamp))
22551 (defun org-timestamp-format (timestamp format &optional end utc)
22552 "Format a TIMESTAMP element into a string.
22554 FORMAT is a format specifier to be passed to
22555 `format-time-string'.
22557 When optional argument END is non-nil, use end of date-range or
22558 time-range, if possible.
22560 When optional argument UTC is non-nil, time will be expressed as
22561 Universal Time."
22562 (format-time-string
22563 format
22564 (apply 'encode-time
22565 (cons 0
22566 (mapcar
22567 (lambda (prop) (or (org-element-property prop timestamp) 0))
22568 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22569 '(:minute-start :hour-start :day-start :month-start
22570 :year-start)))))
22571 utc))
22573 (defun org-timestamp-split-range (timestamp &optional end)
22574 "Extract a timestamp object from a date or time range.
22576 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22577 the end of the range. Otherwise, extract its start.
22579 Return a new timestamp object sharing the same parent as
22580 TIMESTAMP."
22581 (let ((type (org-element-property :type timestamp)))
22582 (if (memq type '(active inactive diary)) timestamp
22583 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22584 ;; Set new type.
22585 (org-element-put-property
22586 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22587 ;; Copy start properties over end properties if END is
22588 ;; non-nil. Otherwise, copy end properties over `start' ones.
22589 (let ((p-alist '((:minute-start . :minute-end)
22590 (:hour-start . :hour-end)
22591 (:day-start . :day-end)
22592 (:month-start . :month-end)
22593 (:year-start . :year-end))))
22594 (dolist (p-cell p-alist)
22595 (org-element-put-property
22596 split-ts
22597 (funcall (if end 'car 'cdr) p-cell)
22598 (org-element-property
22599 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22600 ;; Eventually refresh `:raw-value'.
22601 (org-element-put-property split-ts :raw-value nil)
22602 (org-element-put-property
22603 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22605 (defun org-timestamp-translate (timestamp &optional boundary)
22606 "Apply `org-translate-time' on a TIMESTAMP object.
22607 When optional argument BOUNDARY is non-nil, it is either the
22608 symbol `start' or `end'. In this case, only translate the
22609 starting or ending part of TIMESTAMP if it is a date or time
22610 range. Otherwise, translate both parts."
22611 (if (and (not boundary)
22612 (memq (org-element-property :type timestamp)
22613 '(active-range inactive-range)))
22614 (concat
22615 (org-translate-time
22616 (org-element-property :raw-value
22617 (org-timestamp-split-range timestamp)))
22618 "--"
22619 (org-translate-time
22620 (org-element-property :raw-value
22621 (org-timestamp-split-range timestamp t))))
22622 (org-translate-time
22623 (org-element-property
22624 :raw-value
22625 (if (not boundary) timestamp
22626 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22630 ;;; Other stuff.
22632 (defun org-toggle-fixed-width-section (arg)
22633 "Toggle the fixed-width export.
22634 If there is no active region, the QUOTE keyword at the current headline is
22635 inserted or removed. When present, it causes the text between this headline
22636 and the next to be exported as fixed-width text, and unmodified.
22637 If there is an active region, this command adds or removes a colon as the
22638 first character of this line. If the first character of a line is a colon,
22639 this line is also exported in fixed-width font."
22640 (interactive "P")
22641 (let* ((cc 0)
22642 (regionp (org-region-active-p))
22643 (beg (if regionp (region-beginning) (point)))
22644 (end (if regionp (region-end)))
22645 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22646 (case-fold-search nil)
22647 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22648 off)
22649 (if regionp
22650 (save-excursion
22651 (goto-char beg)
22652 (setq cc (current-column))
22653 (beginning-of-line 1)
22654 (setq off (looking-at re))
22655 (while (> nlines 0)
22656 (setq nlines (1- nlines))
22657 (beginning-of-line 1)
22658 (cond
22659 (arg
22660 (org-move-to-column cc t)
22661 (insert ": \n")
22662 (forward-line -1))
22663 ((and off (looking-at re))
22664 (replace-match "" t t nil 1))
22665 ((not off) (org-move-to-column cc t) (insert ": ")))
22666 (forward-line 1)))
22667 (save-excursion
22668 (org-back-to-heading)
22669 (cond
22670 ((looking-at (format org-heading-keyword-regexp-format
22671 org-quote-string))
22672 (goto-char (match-end 1))
22673 (looking-at (concat " +" org-quote-string))
22674 (replace-match "" t t)
22675 (when (eolp) (insert " ")))
22676 ((looking-at org-outline-regexp)
22677 (goto-char (match-end 0))
22678 (insert org-quote-string " ")))))))
22680 (defun org-reftex-citation ()
22681 "Use reftex-citation to insert a citation into the buffer.
22682 This looks for a line like
22684 #+BIBLIOGRAPHY: foo plain option:-d
22686 and derives from it that foo.bib is the bibliography file relevant
22687 for this document. It then installs the necessary environment for RefTeX
22688 to work in this buffer and calls `reftex-citation' to insert a citation
22689 into the buffer.
22691 Export of such citations to both LaTeX and HTML is handled by the contributed
22692 package ox-bibtex by Taru Karttunen."
22693 (interactive)
22694 (let ((reftex-docstruct-symbol 'rds)
22695 (reftex-cite-format "\\cite{%l}")
22696 rds bib)
22697 (save-excursion
22698 (save-restriction
22699 (widen)
22700 (let ((case-fold-search t)
22701 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22702 (if (not (save-excursion
22703 (or (re-search-forward re nil t)
22704 (re-search-backward re nil t))))
22705 (error "No bibliography defined in file")
22706 (setq bib (concat (match-string 1) ".bib")
22707 rds (list (list 'bib bib)))))))
22708 (call-interactively 'reftex-citation)))
22710 ;;;; Functions extending outline functionality
22712 (defun org-beginning-of-line (&optional arg)
22713 "Go to the beginning of the current line. If that is invisible, continue
22714 to a visible line beginning. This makes the function of C-a more intuitive.
22715 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22716 first attempt, and only move to after the tags when the cursor is already
22717 beyond the end of the headline."
22718 (interactive "P")
22719 (let ((pos (point))
22720 (special (if (consp org-special-ctrl-a/e)
22721 (car org-special-ctrl-a/e)
22722 org-special-ctrl-a/e))
22723 deactivate-mark refpos)
22724 (if (org-bound-and-true-p visual-line-mode)
22725 (beginning-of-visual-line 1)
22726 (beginning-of-line 1))
22727 (if (and arg (fboundp 'move-beginning-of-line))
22728 (call-interactively 'move-beginning-of-line)
22729 (if (bobp)
22731 (backward-char 1)
22732 (if (org-truely-invisible-p)
22733 (while (and (not (bobp)) (org-truely-invisible-p))
22734 (backward-char 1)
22735 (beginning-of-line 1))
22736 (forward-char 1))))
22737 (when special
22738 (cond
22739 ((and (looking-at org-complex-heading-regexp)
22740 (= (char-after (match-end 1)) ?\ ))
22741 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22742 (point-at-eol)))
22743 (goto-char
22744 (if (eq special t)
22745 (cond ((> pos refpos) refpos)
22746 ((= pos (point)) refpos)
22747 (t (point)))
22748 (cond ((> pos (point)) (point))
22749 ((not (eq last-command this-command)) (point))
22750 (t refpos)))))
22751 ((org-at-item-p)
22752 ;; Being at an item and not looking at an the item means point
22753 ;; was previously moved to beginning of a visual line, which
22754 ;; doesn't contain the item. Therefore, do nothing special,
22755 ;; just stay here.
22756 (when (looking-at org-list-full-item-re)
22757 ;; Set special position at first white space character after
22758 ;; bullet, and check-box, if any.
22759 (let ((after-bullet
22760 (let ((box (match-end 3)))
22761 (if (not box) (match-end 1)
22762 (let ((after (char-after box)))
22763 (if (and after (= after ? )) (1+ box) box))))))
22764 ;; Special case: Move point to special position when
22765 ;; currently after it or at beginning of line.
22766 (if (eq special t)
22767 (when (or (> pos after-bullet) (= (point) pos))
22768 (goto-char after-bullet))
22769 ;; Reversed case: Move point to special position when
22770 ;; point was already at beginning of line and command is
22771 ;; repeated.
22772 (when (and (= (point) pos) (eq last-command this-command))
22773 (goto-char after-bullet))))))))
22774 (org-no-warnings
22775 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22776 (setq disable-point-adjustment
22777 (or (not (invisible-p (point)))
22778 (not (invisible-p (max (point-min) (1- (point))))))))
22780 (defun org-end-of-line (&optional arg)
22781 "Go to the end of the line.
22782 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22783 tags on the first attempt, and only move to after the tags when
22784 the cursor is already beyond the end of the headline."
22785 (interactive "P")
22786 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22787 org-special-ctrl-a/e))
22788 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22789 'end-of-visual-line)
22790 ((fboundp 'move-end-of-line) 'move-end-of-line)
22791 (t 'end-of-line)))
22792 deactivate-mark)
22793 (if (or (not special) arg) (call-interactively move-fun)
22794 (let* ((element (save-excursion (beginning-of-line)
22795 (org-element-at-point)))
22796 (type (org-element-type element)))
22797 (cond
22798 ((memq type '(headline inlinetask))
22799 (let ((pos (point)))
22800 (beginning-of-line 1)
22801 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22802 (if (eq special t)
22803 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22804 (goto-char (match-beginning 1))
22805 (goto-char (match-end 0)))
22806 (if (or (< pos (match-end 0))
22807 (not (eq this-command last-command)))
22808 (goto-char (match-end 0))
22809 (goto-char (match-beginning 1))))
22810 (call-interactively move-fun))))
22811 ((outline-invisible-p (line-end-position))
22812 ;; If element is hidden, `move-end-of-line' would put point
22813 ;; after it. Use `end-of-line' to stay on current line.
22814 (call-interactively 'end-of-line))
22815 (t (call-interactively move-fun)))))
22816 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22817 (setq disable-point-adjustment
22818 (or (not (invisible-p (point)))
22819 (not (invisible-p (max (point-min) (1- (point))))))))
22821 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22822 (define-key org-mode-map "\C-e" 'org-end-of-line)
22824 (defun org-backward-sentence (&optional arg)
22825 "Go to beginning of sentence, or beginning of table field.
22826 This will call `backward-sentence' or `org-table-beginning-of-field',
22827 depending on context."
22828 (interactive "P")
22829 (cond
22830 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22831 (t (call-interactively 'backward-sentence))))
22833 (defun org-forward-sentence (&optional arg)
22834 "Go to end of sentence, or end of table field.
22835 This will call `forward-sentence' or `org-table-end-of-field',
22836 depending on context."
22837 (interactive "P")
22838 (cond
22839 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22840 (t (call-interactively 'forward-sentence))))
22842 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22843 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22845 (defun org-kill-line (&optional arg)
22846 "Kill line, to tags or end of line."
22847 (interactive "P")
22848 (cond
22849 ((or (not org-special-ctrl-k)
22850 (bolp)
22851 (not (org-at-heading-p)))
22852 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22853 org-ctrl-k-protect-subtree)
22854 (if (or (eq org-ctrl-k-protect-subtree 'error)
22855 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22856 (user-error "C-k aborted as it would kill a hidden subtree")))
22857 (call-interactively
22858 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22859 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22860 (kill-region (point) (match-beginning 1))
22861 (org-set-tags nil t))
22862 (t (kill-region (point) (point-at-eol)))))
22864 (define-key org-mode-map "\C-k" 'org-kill-line)
22866 (defun org-yank (&optional arg)
22867 "Yank. If the kill is a subtree, treat it specially.
22868 This command will look at the current kill and check if is a single
22869 subtree, or a series of subtrees[1]. If it passes the test, and if the
22870 cursor is at the beginning of a line or after the stars of a currently
22871 empty headline, then the yank is handled specially. How exactly depends
22872 on the value of the following variables, both set by default.
22874 org-yank-folded-subtrees
22875 When set, the subtree(s) will be folded after insertion, but only
22876 if doing so would now swallow text after the yanked text.
22878 org-yank-adjusted-subtrees
22879 When set, the subtree will be promoted or demoted in order to
22880 fit into the local outline tree structure, which means that the level
22881 will be adjusted so that it becomes the smaller one of the two
22882 *visible* surrounding headings.
22884 Any prefix to this command will cause `yank' to be called directly with
22885 no special treatment. In particular, a simple \\[universal-argument] prefix \
22886 will just
22887 plainly yank the text as it is.
22889 \[1] The test checks if the first non-white line is a heading
22890 and if there are no other headings with fewer stars."
22891 (interactive "P")
22892 (org-yank-generic 'yank arg))
22894 (defun org-yank-generic (command arg)
22895 "Perform some yank-like command.
22897 This function implements the behavior described in the `org-yank'
22898 documentation. However, it has been generalized to work for any
22899 interactive command with similar behavior."
22901 ;; pretend to be command COMMAND
22902 (setq this-command command)
22904 (if arg
22905 (call-interactively command)
22907 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22908 (and (org-kill-is-subtree-p)
22909 (or (bolp)
22910 (and (looking-at "[ \t]*$")
22911 (string-match
22912 "\\`\\*+\\'"
22913 (buffer-substring (point-at-bol) (point)))))))
22914 swallowp)
22915 (cond
22916 ((and subtreep org-yank-folded-subtrees)
22917 (let ((beg (point))
22918 end)
22919 (if (and subtreep org-yank-adjusted-subtrees)
22920 (org-paste-subtree nil nil 'for-yank)
22921 (call-interactively command))
22923 (setq end (point))
22924 (goto-char beg)
22925 (when (and (bolp) subtreep
22926 (not (setq swallowp
22927 (org-yank-folding-would-swallow-text beg end))))
22928 (org-with-limited-levels
22929 (or (looking-at org-outline-regexp)
22930 (re-search-forward org-outline-regexp-bol end t))
22931 (while (and (< (point) end) (looking-at org-outline-regexp))
22932 (hide-subtree)
22933 (org-cycle-show-empty-lines 'folded)
22934 (condition-case nil
22935 (outline-forward-same-level 1)
22936 (error (goto-char end))))))
22937 (when swallowp
22938 (message
22939 "Inserted text not folded because that would swallow text"))
22941 (goto-char end)
22942 (skip-chars-forward " \t\n\r")
22943 (beginning-of-line 1)
22944 (push-mark beg 'nomsg)))
22945 ((and subtreep org-yank-adjusted-subtrees)
22946 (let ((beg (point-at-bol)))
22947 (org-paste-subtree nil nil 'for-yank)
22948 (push-mark beg 'nomsg)))
22950 (call-interactively command))))))
22952 (defun org-yank-folding-would-swallow-text (beg end)
22953 "Would hide-subtree at BEG swallow any text after END?"
22954 (let (level)
22955 (org-with-limited-levels
22956 (save-excursion
22957 (goto-char beg)
22958 (when (or (looking-at org-outline-regexp)
22959 (re-search-forward org-outline-regexp-bol end t))
22960 (setq level (org-outline-level)))
22961 (goto-char end)
22962 (skip-chars-forward " \t\r\n\v\f")
22963 (if (or (eobp)
22964 (and (bolp) (looking-at org-outline-regexp)
22965 (<= (org-outline-level) level)))
22966 nil ; Nothing would be swallowed
22967 t))))) ; something would swallow
22969 (define-key org-mode-map "\C-y" 'org-yank)
22971 (defun org-truely-invisible-p ()
22972 "Check if point is at a character currently not visible.
22973 This version does not only check the character property, but also
22974 `visible-mode'."
22975 ;; Early versions of noutline don't have `outline-invisible-p'.
22976 (if (org-bound-and-true-p visible-mode)
22978 (outline-invisible-p)))
22980 (defun org-invisible-p2 ()
22981 "Check if point is at a character currently not visible."
22982 (save-excursion
22983 (if (and (eolp) (not (bobp))) (backward-char 1))
22984 ;; Early versions of noutline don't have `outline-invisible-p'.
22985 (outline-invisible-p)))
22987 (defun org-back-to-heading (&optional invisible-ok)
22988 "Call `outline-back-to-heading', but provide a better error message."
22989 (condition-case nil
22990 (outline-back-to-heading invisible-ok)
22991 (error (error "Before first headline at position %d in buffer %s"
22992 (point) (current-buffer)))))
22994 (defun org-before-first-heading-p ()
22995 "Before first heading?"
22996 (save-excursion
22997 (end-of-line)
22998 (null (re-search-backward org-outline-regexp-bol nil t))))
23000 (defun org-at-heading-p (&optional ignored)
23001 (outline-on-heading-p t))
23002 ;; Compatibility alias with Org versions < 7.8.03
23003 (defalias 'org-on-heading-p 'org-at-heading-p)
23005 (defun org-at-comment-p nil
23006 "Is cursor in a line starting with a # character?"
23007 (save-excursion
23008 (beginning-of-line)
23009 (looking-at "^#")))
23011 (defun org-at-drawer-p nil
23012 "Is cursor at a drawer keyword?"
23013 (save-excursion
23014 (move-beginning-of-line 1)
23015 (looking-at org-drawer-regexp)))
23017 (defun org-at-block-p nil
23018 "Is cursor at a block keyword?"
23019 (save-excursion
23020 (move-beginning-of-line 1)
23021 (looking-at org-block-regexp)))
23023 (defun org-point-at-end-of-empty-headline ()
23024 "If point is at the end of an empty headline, return t, else nil.
23025 If the heading only contains a TODO keyword, it is still still considered
23026 empty."
23027 (and (looking-at "[ \t]*$")
23028 (when org-todo-line-regexp
23029 (save-excursion
23030 (beginning-of-line 1)
23031 (let ((case-fold-search nil))
23032 (looking-at org-todo-line-regexp)
23033 (string= (match-string 3) ""))))))
23035 (defun org-at-heading-or-item-p ()
23036 (or (org-at-heading-p) (org-at-item-p)))
23038 (defun org-at-target-p ()
23039 (or (org-in-regexp org-radio-target-regexp)
23040 (org-in-regexp org-target-regexp)))
23041 ;; Compatibility alias with Org versions < 7.8.03
23042 (defalias 'org-on-target-p 'org-at-target-p)
23044 (defun org-up-heading-all (arg)
23045 "Move to the heading line of which the present line is a subheading.
23046 This function considers both visible and invisible heading lines.
23047 With argument, move up ARG levels."
23048 (if (fboundp 'outline-up-heading-all)
23049 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23050 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23052 (defun org-up-heading-safe ()
23053 "Move to the heading line of which the present line is a subheading.
23054 This version will not throw an error. It will return the level of the
23055 headline found, or nil if no higher level is found.
23057 Also, this function will be a lot faster than `outline-up-heading',
23058 because it relies on stars being the outline starters. This can really
23059 make a significant difference in outlines with very many siblings."
23060 (let (start-level re)
23061 (org-back-to-heading t)
23062 (setq start-level (funcall outline-level))
23063 (if (equal start-level 1)
23065 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23066 (if (re-search-backward re nil t)
23067 (funcall outline-level)))))
23069 (defun org-first-sibling-p ()
23070 "Is this heading the first child of its parents?"
23071 (interactive)
23072 (let ((re org-outline-regexp-bol)
23073 level l)
23074 (unless (org-at-heading-p t)
23075 (user-error "Not at a heading"))
23076 (setq level (funcall outline-level))
23077 (save-excursion
23078 (if (not (re-search-backward re nil t))
23080 (setq l (funcall outline-level))
23081 (< l level)))))
23083 (defun org-goto-sibling (&optional previous)
23084 "Goto the next sibling, even if it is invisible.
23085 When PREVIOUS is set, go to the previous sibling instead. Returns t
23086 when a sibling was found. When none is found, return nil and don't
23087 move point."
23088 (let ((fun (if previous 're-search-backward 're-search-forward))
23089 (pos (point))
23090 (re org-outline-regexp-bol)
23091 level l)
23092 (when (condition-case nil (org-back-to-heading t) (error nil))
23093 (setq level (funcall outline-level))
23094 (catch 'exit
23095 (or previous (forward-char 1))
23096 (while (funcall fun re nil t)
23097 (setq l (funcall outline-level))
23098 (when (< l level) (goto-char pos) (throw 'exit nil))
23099 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23100 (goto-char pos)
23101 nil))))
23103 (defun org-show-siblings ()
23104 "Show all siblings of the current headline."
23105 (save-excursion
23106 (while (org-goto-sibling) (org-flag-heading nil)))
23107 (save-excursion
23108 (while (org-goto-sibling 'previous)
23109 (org-flag-heading nil))))
23111 (defun org-goto-first-child ()
23112 "Goto the first child, even if it is invisible.
23113 Return t when a child was found. Otherwise don't move point and
23114 return nil."
23115 (let (level (pos (point)) (re org-outline-regexp-bol))
23116 (when (condition-case nil (org-back-to-heading t) (error nil))
23117 (setq level (outline-level))
23118 (forward-char 1)
23119 (if (and (re-search-forward re nil t) (> (outline-level) level))
23120 (progn (goto-char (match-beginning 0)) t)
23121 (goto-char pos) nil))))
23123 (defun org-show-hidden-entry ()
23124 "Show an entry where even the heading is hidden."
23125 (save-excursion
23126 (org-show-entry)))
23128 (defun org-flag-heading (flag &optional entry)
23129 "Flag the current heading. FLAG non-nil means make invisible.
23130 When ENTRY is non-nil, show the entire entry."
23131 (save-excursion
23132 (org-back-to-heading t)
23133 ;; Check if we should show the entire entry
23134 (if entry
23135 (progn
23136 (org-show-entry)
23137 (save-excursion
23138 (and (outline-next-heading)
23139 (org-flag-heading nil))))
23140 (outline-flag-region (max (point-min) (1- (point)))
23141 (save-excursion (outline-end-of-heading) (point))
23142 flag))))
23144 (defun org-get-next-sibling ()
23145 "Move to next heading of the same level, and return point.
23146 If there is no such heading, return nil.
23147 This is like outline-next-sibling, but invisible headings are ok."
23148 (let ((level (funcall outline-level)))
23149 (outline-next-heading)
23150 (while (and (not (eobp)) (> (funcall outline-level) level))
23151 (outline-next-heading))
23152 (if (or (eobp) (< (funcall outline-level) level))
23154 (point))))
23156 (defun org-get-last-sibling ()
23157 "Move to previous heading of the same level, and return point.
23158 If there is no such heading, return nil."
23159 (let ((opoint (point))
23160 (level (funcall outline-level)))
23161 (outline-previous-heading)
23162 (when (and (/= (point) opoint) (outline-on-heading-p t))
23163 (while (and (> (funcall outline-level) level)
23164 (not (bobp)))
23165 (outline-previous-heading))
23166 (if (< (funcall outline-level) level)
23168 (point)))))
23170 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23171 "Goto to the end of a subtree."
23172 ;; This contains an exact copy of the original function, but it uses
23173 ;; `org-back-to-heading', to make it work also in invisible
23174 ;; trees. And is uses an invisible-ok argument.
23175 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23176 ;; Furthermore, when used inside Org, finding the end of a large subtree
23177 ;; with many children and grandchildren etc, this can be much faster
23178 ;; than the outline version.
23179 (org-back-to-heading invisible-ok)
23180 (let ((first t)
23181 (level (funcall outline-level)))
23182 (if (and (derived-mode-p 'org-mode) (< level 1000))
23183 ;; A true heading (not a plain list item), in Org-mode
23184 ;; This means we can easily find the end by looking
23185 ;; only for the right number of stars. Using a regexp to do
23186 ;; this is so much faster than using a Lisp loop.
23187 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23188 (forward-char 1)
23189 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23190 ;; something else, do it the slow way
23191 (while (and (not (eobp))
23192 (or first (> (funcall outline-level) level)))
23193 (setq first nil)
23194 (outline-next-heading)))
23195 (unless to-heading
23196 (if (memq (preceding-char) '(?\n ?\^M))
23197 (progn
23198 ;; Go to end of line before heading
23199 (forward-char -1)
23200 (if (memq (preceding-char) '(?\n ?\^M))
23201 ;; leave blank line before heading
23202 (forward-char -1))))))
23203 (point))
23205 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23206 "Use Org version in org-mode, for dramatic speed-up."
23207 (if (derived-mode-p 'org-mode)
23208 (progn
23209 (org-end-of-subtree nil t)
23210 (unless (eobp) (backward-char 1)))
23211 ad-do-it))
23213 (defun org-end-of-meta-data-and-drawers ()
23214 "Jump to the first text after meta data and drawers in the current entry.
23215 This will move over empty lines, lines with planning time stamps,
23216 clocking lines, and drawers."
23217 (org-back-to-heading t)
23218 (let ((end (save-excursion (outline-next-heading) (point)))
23219 (re (concat "\\(" org-drawer-regexp "\\)"
23220 "\\|" "[ \t]*" org-keyword-time-regexp)))
23221 (forward-line 1)
23222 (while (re-search-forward re end t)
23223 (if (not (match-end 1))
23224 ;; empty or planning line
23225 (forward-line 1)
23226 ;; a drawer, find the end
23227 (re-search-forward "^[ \t]*:END:" end 'move)
23228 (forward-line 1)))
23229 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23230 (point)))
23232 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23233 "Move forward to the ARG'th subheading at same level as this one.
23234 Stop at the first and last subheadings of a superior heading.
23235 Normally this only looks at visible headings, but when INVISIBLE-OK is
23236 non-nil it will also look at invisible ones."
23237 (interactive "p")
23238 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23239 (if (and arg (< arg 0))
23240 (goto-char (point-min))
23241 (outline-next-heading))
23242 (org-at-heading-p)
23243 (let ((level (- (match-end 0) (match-beginning 0) 1))
23244 (f (if (and arg (< arg 0))
23245 're-search-backward
23246 're-search-forward))
23247 (count (if arg (abs arg) 1))
23248 (result (point)))
23249 (while (and (prog1 (> count 0)
23250 (forward-char (if (and arg (< arg 0)) -1 1)))
23251 (funcall f org-outline-regexp-bol nil 'move))
23252 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23253 (cond ((< l level) (setq count 0))
23254 ((and (= l level)
23255 (or invisible-ok
23256 (progn
23257 (goto-char (line-beginning-position))
23258 (not (outline-invisible-p)))))
23259 (setq count (1- count))
23260 (when (eq l level)
23261 (setq result (point)))))))
23262 (goto-char result))
23263 (beginning-of-line 1)))
23265 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23266 "Move backward to the ARG'th subheading at same level as this one.
23267 Stop at the first and last subheadings of a superior heading."
23268 (interactive "p")
23269 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23271 (defun org-next-block (arg &optional backward block-regexp)
23272 "Jump to the next block.
23273 With a prefix argument ARG, jump forward ARG many source blocks.
23274 When BACKWARD is non-nil, jump to the previous block.
23275 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23276 (interactive "p")
23277 (let ((re (or block-regexp org-block-regexp))
23278 (re-search-fn (or (and backward 're-search-backward)
23279 're-search-forward)))
23280 (if (looking-at re) (forward-char 1))
23281 (condition-case nil
23282 (funcall re-search-fn re nil nil arg)
23283 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23284 (goto-char (match-beginning 0)) (org-show-context)))
23286 (defun org-previous-block (arg &optional block-regexp)
23287 "Jump to the previous block.
23288 With a prefix argument ARG, jump backward ARG many source blocks.
23289 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23290 (interactive "p")
23291 (org-next-block arg t block-regexp))
23293 (defun org-forward-paragraph ()
23294 "Move forward to beginning of next paragraph or equivalent.
23296 The function moves point to the beginning of the next visible
23297 structural element, which can be a paragraph, a table, a list
23298 item, etc. It also provides some special moves for convenience:
23300 - On an affiliated keyword, jump to the beginning of the
23301 relative element.
23302 - On an item or a footnote definition, move to the second
23303 element inside, if any.
23304 - On a table or a property drawer, jump after it.
23305 - On a verse or source block, stop after blank lines."
23306 (interactive)
23307 (when (eobp) (user-error "Cannot move further down"))
23308 (let* ((deactivate-mark nil)
23309 (element (org-element-at-point))
23310 (type (org-element-type element))
23311 (post-affiliated (org-element-property :post-affiliated element))
23312 (contents-begin (org-element-property :contents-begin element))
23313 (contents-end (org-element-property :contents-end element))
23314 (end (let ((end (org-element-property :end element)) (parent element))
23315 (while (and (setq parent (org-element-property :parent parent))
23316 (= (org-element-property :contents-end parent) end))
23317 (setq end (org-element-property :end parent)))
23318 end)))
23319 (cond ((not element)
23320 (skip-chars-forward " \r\t\n")
23321 (or (eobp) (beginning-of-line)))
23322 ;; On affiliated keywords, move to element's beginning.
23323 ((and post-affiliated (< (point) post-affiliated))
23324 (goto-char post-affiliated))
23325 ;; At a table row, move to the end of the table. Similarly,
23326 ;; at a node property, move to the end of the property
23327 ;; drawer.
23328 ((memq type '(node-property table-row))
23329 (goto-char (org-element-property
23330 :end (org-element-property :parent element))))
23331 ((memq type '(property-drawer table)) (goto-char end))
23332 ;; Consider blank lines as separators in verse and source
23333 ;; blocks to ease editing.
23334 ((memq type '(src-block verse-block))
23335 (when (eq type 'src-block)
23336 (setq contents-end
23337 (save-excursion (goto-char end)
23338 (skip-chars-backward " \r\t\n")
23339 (line-beginning-position))))
23340 (beginning-of-line)
23341 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23342 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23343 (goto-char end)
23344 (skip-chars-forward " \r\t\n")
23345 (if (= (point) contents-end) (goto-char end)
23346 (beginning-of-line))))
23347 ;; With no contents, just skip element.
23348 ((not contents-begin) (goto-char end))
23349 ;; If contents are invisible, skip the element altogether.
23350 ((outline-invisible-p (line-end-position))
23351 (case type
23352 (headline
23353 (org-with-limited-levels (outline-next-visible-heading 1)))
23354 ;; At a plain list, make sure we move to the next item
23355 ;; instead of skipping the whole list.
23356 (plain-list (forward-char)
23357 (org-forward-paragraph))
23358 (otherwise (goto-char end))))
23359 ((>= (point) contents-end) (goto-char end))
23360 ((>= (point) contents-begin)
23361 ;; This can only happen on paragraphs and plain lists.
23362 (case type
23363 (paragraph (goto-char end))
23364 ;; At a plain list, try to move to second element in
23365 ;; first item, if possible.
23366 (plain-list (end-of-line)
23367 (org-forward-paragraph))))
23368 ;; When contents start on the middle of a line (e.g. in
23369 ;; items and footnote definitions), try to reach first
23370 ;; element starting after current line.
23371 ((> (line-end-position) contents-begin)
23372 (end-of-line)
23373 (org-forward-paragraph))
23374 (t (goto-char contents-begin)))))
23376 (defun org-backward-paragraph ()
23377 "Move backward to start of previous paragraph or equivalent.
23379 The function moves point to the beginning of the current
23380 structural element, which can be a paragraph, a table, a list
23381 item, etc., or to the beginning of the previous visible one if
23382 point is already there. It also provides some special moves for
23383 convenience:
23385 - On an affiliated keyword, jump to the first one.
23386 - On a table or a property drawer, move to its beginning.
23387 - On a verse or source block, stop before blank lines."
23388 (interactive)
23389 (when (bobp) (user-error "Cannot move further up"))
23390 (let* ((deactivate-mark nil)
23391 (element (org-element-at-point))
23392 (type (org-element-type element))
23393 (contents-begin (org-element-property :contents-begin element))
23394 (contents-end (org-element-property :contents-end element))
23395 (post-affiliated (org-element-property :post-affiliated element))
23396 (begin (org-element-property :begin element)))
23397 (cond
23398 ((not element) (goto-char (point-min)))
23399 ((= (point) begin)
23400 (backward-char)
23401 (org-backward-paragraph))
23402 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23403 ((memq type '(node-property table-row))
23404 (goto-char (org-element-property
23405 :post-affiliated (org-element-property :parent element))))
23406 ((memq type '(property-drawer table)) (goto-char begin))
23407 ((memq type '(src-block verse-block))
23408 (when (eq type 'src-block)
23409 (setq contents-begin
23410 (save-excursion (goto-char begin) (forward-line) (point))))
23411 (if (= (point) contents-begin) (goto-char post-affiliated)
23412 ;; Inside a verse block, see blank lines as paragraph
23413 ;; separators.
23414 (let ((origin (point)))
23415 (skip-chars-backward " \r\t\n" contents-begin)
23416 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23417 (skip-chars-forward " \r\t\n" origin)
23418 (if (= (point) origin) (goto-char contents-begin)
23419 (beginning-of-line))))))
23420 ((not contents-begin) (goto-char (or post-affiliated begin)))
23421 ((eq type 'paragraph)
23422 (goto-char contents-begin)
23423 ;; When at first paragraph in an item or a footnote definition,
23424 ;; move directly to beginning of line.
23425 (let ((parent-contents
23426 (org-element-property
23427 :contents-begin (org-element-property :parent element))))
23428 (when (and parent-contents (= parent-contents contents-begin))
23429 (beginning-of-line))))
23430 ;; At the end of a greater element, move to the beginning of the
23431 ;; last element within.
23432 ((>= (point) contents-end)
23433 (goto-char (1- contents-end))
23434 (org-backward-paragraph))
23435 (t (goto-char (or post-affiliated begin))))
23436 ;; Ensure we never leave point invisible.
23437 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23439 (defun org-forward-element ()
23440 "Move forward by one element.
23441 Move to the next element at the same level, when possible."
23442 (interactive)
23443 (cond ((eobp) (user-error "Cannot move further down"))
23444 ((org-with-limited-levels (org-at-heading-p))
23445 (let ((origin (point)))
23446 (goto-char (org-end-of-subtree nil t))
23447 (unless (org-with-limited-levels (org-at-heading-p))
23448 (goto-char origin)
23449 (user-error "Cannot move further down"))))
23451 (let* ((elem (org-element-at-point))
23452 (end (org-element-property :end elem))
23453 (parent (org-element-property :parent elem)))
23454 (cond ((and parent (= (org-element-property :contents-end parent) end))
23455 (goto-char (org-element-property :end parent)))
23456 ((integer-or-marker-p end) (goto-char end))
23457 (t (message "No element at point")))))))
23459 (defun org-backward-element ()
23460 "Move backward by one element.
23461 Move to the previous element at the same level, when possible."
23462 (interactive)
23463 (cond ((bobp) (user-error "Cannot move further up"))
23464 ((org-with-limited-levels (org-at-heading-p))
23465 ;; At a headline, move to the previous one, if any, or stay
23466 ;; here.
23467 (let ((origin (point)))
23468 (org-with-limited-levels (org-backward-heading-same-level 1))
23469 ;; When current headline has no sibling above, move to its
23470 ;; parent.
23471 (when (= (point) origin)
23472 (or (org-with-limited-levels (org-up-heading-safe))
23473 (progn (goto-char origin)
23474 (user-error "Cannot move further up"))))))
23476 (let* ((trail (org-element-at-point 'keep-trail))
23477 (elem (car trail))
23478 (prev-elem (nth 1 trail))
23479 (beg (org-element-property :begin elem)))
23480 (cond
23481 ;; Move to beginning of current element if point isn't
23482 ;; there already.
23483 ((null beg) (message "No element at point"))
23484 ((/= (point) beg) (goto-char beg))
23485 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23486 ((org-before-first-heading-p) (goto-char (point-min)))
23487 (t (org-back-to-heading)))))))
23489 (defun org-up-element ()
23490 "Move to upper element."
23491 (interactive)
23492 (if (org-with-limited-levels (org-at-heading-p))
23493 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23494 (let* ((elem (org-element-at-point))
23495 (parent (org-element-property :parent elem)))
23496 (if parent (goto-char (org-element-property :begin parent))
23497 (if (org-with-limited-levels (org-before-first-heading-p))
23498 (user-error "No surrounding element")
23499 (org-with-limited-levels (org-back-to-heading)))))))
23501 (defvar org-element-greater-elements)
23502 (defun org-down-element ()
23503 "Move to inner element."
23504 (interactive)
23505 (let ((element (org-element-at-point)))
23506 (cond
23507 ((memq (org-element-type element) '(plain-list table))
23508 (goto-char (org-element-property :contents-begin element))
23509 (forward-char))
23510 ((memq (org-element-type element) org-element-greater-elements)
23511 ;; If contents are hidden, first disclose them.
23512 (when (outline-invisible-p (line-end-position)) (org-cycle))
23513 (goto-char (or (org-element-property :contents-begin element)
23514 (user-error "No content for this element"))))
23515 (t (user-error "No inner element")))))
23517 (defun org-drag-element-backward ()
23518 "Move backward element at point."
23519 (interactive)
23520 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23521 (let* ((trail (org-element-at-point 'keep-trail))
23522 (elem (car trail))
23523 (prev-elem (nth 1 trail)))
23524 ;; Error out if no previous element or previous element is
23525 ;; a parent of the current one.
23526 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23527 (user-error "Cannot drag element backward")
23528 (let ((pos (point)))
23529 (org-element-swap-A-B prev-elem elem)
23530 (goto-char (+ (org-element-property :begin prev-elem)
23531 (- pos (org-element-property :begin elem)))))))))
23533 (defun org-drag-element-forward ()
23534 "Move forward element at point."
23535 (interactive)
23536 (let* ((pos (point))
23537 (elem (org-element-at-point)))
23538 (when (= (point-max) (org-element-property :end elem))
23539 (user-error "Cannot drag element forward"))
23540 (goto-char (org-element-property :end elem))
23541 (let ((next-elem (org-element-at-point)))
23542 (when (or (org-element-nested-p elem next-elem)
23543 (and (eq (org-element-type next-elem) 'headline)
23544 (not (eq (org-element-type elem) 'headline))))
23545 (goto-char pos)
23546 (user-error "Cannot drag element forward"))
23547 ;; Compute new position of point: it's shifted by NEXT-ELEM
23548 ;; body's length (without final blanks) and by the length of
23549 ;; blanks between ELEM and NEXT-ELEM.
23550 (let ((size-next (- (save-excursion
23551 (goto-char (org-element-property :end next-elem))
23552 (skip-chars-backward " \r\t\n")
23553 (forward-line)
23554 ;; Small correction if buffer doesn't end
23555 ;; with a newline character.
23556 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23557 (org-element-property :begin next-elem)))
23558 (size-blank (- (org-element-property :end elem)
23559 (save-excursion
23560 (goto-char (org-element-property :end elem))
23561 (skip-chars-backward " \r\t\n")
23562 (forward-line)
23563 (point)))))
23564 (org-element-swap-A-B elem next-elem)
23565 (goto-char (+ pos size-next size-blank))))))
23567 (defun org-drag-line-forward (arg)
23568 "Drag the line at point ARG lines forward."
23569 (interactive "p")
23570 (dotimes (n (abs arg))
23571 (let ((c (current-column)))
23572 (if (< 0 arg)
23573 (progn
23574 (beginning-of-line 2)
23575 (transpose-lines 1)
23576 (beginning-of-line 0))
23577 (transpose-lines 1)
23578 (beginning-of-line -1))
23579 (org-move-to-column c))))
23581 (defun org-drag-line-backward (arg)
23582 "Drag the line at point ARG lines backward."
23583 (interactive "p")
23584 (org-drag-line-forward (- arg)))
23586 (defun org-mark-element ()
23587 "Put point at beginning of this element, mark at end.
23589 Interactively, if this command is repeated or (in Transient Mark
23590 mode) if the mark is active, it marks the next element after the
23591 ones already marked."
23592 (interactive)
23593 (let (deactivate-mark)
23594 (if (and (org-called-interactively-p 'any)
23595 (or (and (eq last-command this-command) (mark t))
23596 (and transient-mark-mode mark-active)))
23597 (set-mark
23598 (save-excursion
23599 (goto-char (mark))
23600 (goto-char (org-element-property :end (org-element-at-point)))))
23601 (let ((element (org-element-at-point)))
23602 (end-of-line)
23603 (push-mark (org-element-property :end element) t t)
23604 (goto-char (org-element-property :begin element))))))
23606 (defun org-narrow-to-element ()
23607 "Narrow buffer to current element."
23608 (interactive)
23609 (let ((elem (org-element-at-point)))
23610 (cond
23611 ((eq (car elem) 'headline)
23612 (narrow-to-region
23613 (org-element-property :begin elem)
23614 (org-element-property :end elem)))
23615 ((memq (car elem) org-element-greater-elements)
23616 (narrow-to-region
23617 (org-element-property :contents-begin elem)
23618 (org-element-property :contents-end elem)))
23620 (narrow-to-region
23621 (org-element-property :begin elem)
23622 (org-element-property :end elem))))))
23624 (defun org-transpose-element ()
23625 "Transpose current and previous elements, keeping blank lines between.
23626 Point is moved after both elements."
23627 (interactive)
23628 (org-skip-whitespace)
23629 (let ((end (org-element-property :end (org-element-at-point))))
23630 (org-drag-element-backward)
23631 (goto-char end)))
23633 (defun org-unindent-buffer ()
23634 "Un-indent the visible part of the buffer.
23635 Relative indentation (between items, inside blocks, etc.) isn't
23636 modified."
23637 (interactive)
23638 (unless (eq major-mode 'org-mode)
23639 (user-error "Cannot un-indent a buffer not in Org mode"))
23640 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23641 unindent-tree ; For byte-compiler.
23642 (unindent-tree
23643 (function
23644 (lambda (contents)
23645 (mapc
23646 (lambda (element)
23647 (if (memq (org-element-type element) '(headline section))
23648 (funcall unindent-tree (org-element-contents element))
23649 (save-excursion
23650 (save-restriction
23651 (narrow-to-region
23652 (org-element-property :begin element)
23653 (org-element-property :end element))
23654 (org-do-remove-indentation)))))
23655 (reverse contents))))))
23656 (funcall unindent-tree (org-element-contents parse-tree))))
23658 (defun org-show-subtree ()
23659 "Show everything after this heading at deeper levels."
23660 (interactive)
23661 (outline-flag-region
23662 (point)
23663 (save-excursion
23664 (org-end-of-subtree t t))
23665 nil))
23667 (defun org-show-entry ()
23668 "Show the body directly following this heading.
23669 Show the heading too, if it is currently invisible."
23670 (interactive)
23671 (save-excursion
23672 (condition-case nil
23673 (progn
23674 (org-back-to-heading t)
23675 (outline-flag-region
23676 (max (point-min) (1- (point)))
23677 (save-excursion
23678 (if (re-search-forward
23679 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23680 (match-beginning 1)
23681 (point-max)))
23682 nil)
23683 (org-cycle-hide-drawers 'children))
23684 (error nil))))
23686 (defun org-make-options-regexp (kwds &optional extra)
23687 "Make a regular expression for keyword lines."
23688 (concat
23689 "^#\\+\\("
23690 (mapconcat 'regexp-quote kwds "\\|")
23691 (if extra (concat "\\|" extra))
23692 "\\):[ \t]*\\(.*\\)"))
23694 ;; Make isearch reveal the necessary context
23695 (defun org-isearch-end ()
23696 "Reveal context after isearch exits."
23697 (when isearch-success ; only if search was successful
23698 (if (featurep 'xemacs)
23699 ;; Under XEmacs, the hook is run in the correct place,
23700 ;; we directly show the context.
23701 (org-show-context 'isearch)
23702 ;; In Emacs the hook runs *before* restoring the overlays.
23703 ;; So we have to use a one-time post-command-hook to do this.
23704 ;; (Emacs 22 has a special variable, see function `org-mode')
23705 (unless (and (boundp 'isearch-mode-end-hook-quit)
23706 isearch-mode-end-hook-quit)
23707 ;; Only when the isearch was not quitted.
23708 (org-add-hook 'post-command-hook 'org-isearch-post-command
23709 'append 'local)))
23710 (org-fix-ellipsis-at-bol)))
23712 (defun org-isearch-post-command ()
23713 "Remove self from hook, and show context."
23714 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23715 (org-show-context 'isearch))
23718 ;;;; Integration with and fixes for other packages
23720 ;;; Imenu support
23722 (defvar org-imenu-markers nil
23723 "All markers currently used by Imenu.")
23724 (make-variable-buffer-local 'org-imenu-markers)
23726 (defun org-imenu-new-marker (&optional pos)
23727 "Return a new marker for use by Imenu, and remember the marker."
23728 (let ((m (make-marker)))
23729 (move-marker m (or pos (point)))
23730 (push m org-imenu-markers)
23733 (defun org-imenu-get-tree ()
23734 "Produce the index for Imenu."
23735 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23736 (setq org-imenu-markers nil)
23737 (let* ((n org-imenu-depth)
23738 (re (concat "^" (org-get-limited-outline-regexp)))
23739 (subs (make-vector (1+ n) nil))
23740 (last-level 0)
23741 m level head0 head)
23742 (save-excursion
23743 (save-restriction
23744 (widen)
23745 (goto-char (point-max))
23746 (while (re-search-backward re nil t)
23747 (setq level (org-reduced-level (funcall outline-level)))
23748 (when (and (<= level n)
23749 (looking-at org-complex-heading-regexp)
23750 (setq head0 (org-match-string-no-properties 4)))
23751 (setq head (org-link-display-format head0)
23752 m (org-imenu-new-marker))
23753 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23754 (if (>= level last-level)
23755 (push (cons head m) (aref subs level))
23756 (push (cons head (aref subs (1+ level))) (aref subs level))
23757 (loop for i from (1+ level) to n do (aset subs i nil)))
23758 (setq last-level level)))))
23759 (aref subs 1)))
23761 (eval-after-load "imenu"
23762 '(progn
23763 (add-hook 'imenu-after-jump-hook
23764 (lambda ()
23765 (if (derived-mode-p 'org-mode)
23766 (org-show-context 'org-goto))))))
23768 (defun org-link-display-format (link)
23769 "Replace a link with its the description.
23770 If there is no description, use the link target."
23771 (save-match-data
23772 (if (string-match org-bracket-link-analytic-regexp link)
23773 (replace-match (if (match-end 5)
23774 (match-string 5 link)
23775 (concat (match-string 1 link)
23776 (match-string 3 link)))
23777 nil t link)
23778 link)))
23780 (defun org-toggle-link-display ()
23781 "Toggle the literal or descriptive display of links."
23782 (interactive)
23783 (if org-descriptive-links
23784 (progn (org-remove-from-invisibility-spec '(org-link))
23785 (org-restart-font-lock)
23786 (setq org-descriptive-links nil))
23787 (progn (add-to-invisibility-spec '(org-link))
23788 (org-restart-font-lock)
23789 (setq org-descriptive-links t))))
23791 ;; Speedbar support
23793 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23794 "Overlay marking the agenda restriction line in speedbar.")
23795 (overlay-put org-speedbar-restriction-lock-overlay
23796 'face 'org-agenda-restriction-lock)
23797 (overlay-put org-speedbar-restriction-lock-overlay
23798 'help-echo "Agendas are currently limited to this item.")
23799 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23801 (defun org-speedbar-set-agenda-restriction ()
23802 "Restrict future agenda commands to the location at point in speedbar.
23803 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23804 (interactive)
23805 (require 'org-agenda)
23806 (let (p m tp np dir txt)
23807 (cond
23808 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23809 'org-imenu t))
23810 (setq m (get-text-property p 'org-imenu-marker))
23811 (with-current-buffer (marker-buffer m)
23812 (goto-char m)
23813 (org-agenda-set-restriction-lock 'subtree)))
23814 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23815 'speedbar-function 'speedbar-find-file))
23816 (setq tp (previous-single-property-change
23817 (1+ p) 'speedbar-function)
23818 np (next-single-property-change
23819 tp 'speedbar-function)
23820 dir (speedbar-line-directory)
23821 txt (buffer-substring-no-properties (or tp (point-min))
23822 (or np (point-max))))
23823 (with-current-buffer (find-file-noselect
23824 (let ((default-directory dir))
23825 (expand-file-name txt)))
23826 (unless (derived-mode-p 'org-mode)
23827 (user-error "Cannot restrict to non-Org-mode file"))
23828 (org-agenda-set-restriction-lock 'file)))
23829 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23830 (move-overlay org-speedbar-restriction-lock-overlay
23831 (point-at-bol) (point-at-eol))
23832 (setq current-prefix-arg nil)
23833 (org-agenda-maybe-redo)))
23835 (defvar speedbar-file-key-map)
23836 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23837 (eval-after-load "speedbar"
23838 '(progn
23839 (speedbar-add-supported-extension ".org")
23840 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23841 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23842 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23843 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23844 (add-hook 'speedbar-visiting-tag-hook
23845 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23847 ;;; Fixes and Hacks for problems with other packages
23849 ;; Make flyspell not check words in links, to not mess up our keymap
23850 (defvar org-element-affiliated-keywords) ; From org-element.el
23851 (defvar org-element-block-name-alist) ; From org-element.el
23852 (defun org-mode-flyspell-verify ()
23853 "Don't let flyspell put overlays at active buttons, or on
23854 {todo,all-time,additional-option-like}-keywords."
23855 (require 'org-element) ; For `org-element-affiliated-keywords'
23856 (let ((pos (max (1- (point)) (point-min)))
23857 (word (thing-at-point 'word)))
23858 (and (not (get-text-property pos 'keymap))
23859 (not (get-text-property pos 'org-no-flyspell))
23860 (not (member word org-todo-keywords-1))
23861 (not (member word org-all-time-keywords))
23862 (not (member word org-options-keywords))
23863 (not (member word (mapcar 'car org-startup-options)))
23864 (not (member-ignore-case word org-element-affiliated-keywords))
23865 (not (member-ignore-case word (org-get-export-keywords)))
23866 (not (member-ignore-case
23867 word (mapcar 'car org-element-block-name-alist)))
23868 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23869 (not (org-in-src-block-p)))))
23871 (defun org-remove-flyspell-overlays-in (beg end)
23872 "Remove flyspell overlays in region."
23873 (and (org-bound-and-true-p flyspell-mode)
23874 (fboundp 'flyspell-delete-region-overlays)
23875 (flyspell-delete-region-overlays beg end))
23876 (add-text-properties beg end '(org-no-flyspell t)))
23878 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23879 (eval-after-load "bookmark"
23880 '(if (boundp 'bookmark-after-jump-hook)
23881 ;; We can use the hook
23882 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23883 ;; Hook not available, use advice
23884 (defadvice bookmark-jump (after org-make-visible activate)
23885 "Make the position visible."
23886 (org-bookmark-jump-unhide))))
23888 ;; Make sure saveplace shows the location if it was hidden
23889 (eval-after-load "saveplace"
23890 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23891 "Make the position visible."
23892 (org-bookmark-jump-unhide)))
23894 ;; Make sure ecb shows the location if it was hidden
23895 (eval-after-load "ecb"
23896 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23897 "Make hierarchy visible when jumping into location from ECB tree buffer."
23898 (if (derived-mode-p 'org-mode)
23899 (org-show-context))))
23901 (defun org-bookmark-jump-unhide ()
23902 "Unhide the current position, to show the bookmark location."
23903 (and (derived-mode-p 'org-mode)
23904 (or (outline-invisible-p)
23905 (save-excursion (goto-char (max (point-min) (1- (point))))
23906 (outline-invisible-p)))
23907 (org-show-context 'bookmark-jump)))
23909 ;; Make session.el ignore our circular variable
23910 (defvar session-globals-exclude)
23911 (eval-after-load "session"
23912 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23914 ;;;; Finish up
23916 (provide 'org)
23918 (run-hooks 'org-load-hook)
23920 ;;; org.el ends here