Update copyright years again.
[org-mode.git] / lisp / org.el
blobedbcc09cd10264e84525e3c33cfdd734d9ddb395
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 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-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (version1 (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 version1))
313 version1)))
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.
658 If you want to control how Org exports those characters, see
659 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
660 used to be an alias for `org-export-with-sub-superscripts' in
661 Org <8.0, it is not anymore.
663 When this option is turned on, you can use TeX-like syntax for
664 sub- and superscripts within the buffer. Several characters after
665 \"_\" or \"^\" will be considered as a single item - so grouping
666 with {} is normally not needed. For example, the following things
667 will be parsed as single sub- or superscripts:
669 10^24 or 10^tau several digits will be considered 1 item.
670 10^-12 or 10^-tau a leading sign with digits or a word
671 x^2-y^3 will be read as x^2 - y^3, because items are
672 terminated by almost any nonword/nondigit char.
673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
675 Still, ambiguity is possible. So when in doubt, use {} to enclose
676 the sub/superscript. If you set this variable to the symbol `{}',
677 the braces are *required* in order to trigger interpretations as
678 sub/superscript. This can be helpful in documents that need \"_\"
679 frequently in plain text."
680 :group 'org-startup
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type '(choice
684 (const :tag "Always interpret" t)
685 (const :tag "Only with braces" {})
686 (const :tag "Never interpret" nil)))
688 (defcustom org-startup-with-beamer-mode nil
689 "Non-nil means turn on `org-beamer-mode' on startup.
690 This can also be configured on a per-file basis by adding one of
691 the following lines anywhere in the buffer:
693 #+STARTUP: beamer"
694 :group 'org-startup
695 :version "24.1"
696 :type 'boolean)
698 (defcustom org-startup-align-all-tables nil
699 "Non-nil means align all tables when visiting a file.
700 This is useful when the column width in tables is forced with <N> cookies
701 in table fields. Such tables will look correct only after the first re-align.
702 This can also be configured on a per-file basis by adding one of
703 the following lines anywhere in the buffer:
704 #+STARTUP: align
705 #+STARTUP: noalign"
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-startup-with-inline-images nil
710 "Non-nil means show inline images when loading a new Org file.
711 This can also be configured on a per-file basis by adding one of
712 the following lines anywhere in the buffer:
713 #+STARTUP: inlineimages
714 #+STARTUP: noinlineimages"
715 :group 'org-startup
716 :version "24.1"
717 :type 'boolean)
719 (defcustom org-startup-with-latex-preview nil
720 "Non-nil means preview LaTeX fragments when loading a new Org file.
722 This can also be configured on a per-file basis by adding one of
723 the following lines anywhere in the buffer:
724 #+STARTUP: latexpreview
725 #+STARTUP: nolatexpreview"
726 :group 'org-startup
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type 'boolean)
731 (defcustom org-insert-mode-line-in-empty-file nil
732 "Non-nil means insert the first line setting Org-mode in empty files.
733 When the function `org-mode' is called interactively in an empty file, this
734 normally means that the file name does not automatically trigger Org-mode.
735 To ensure that the file will always be in Org-mode in the future, a
736 line enforcing Org-mode will be inserted into the buffer, if this option
737 has been set."
738 :group 'org-startup
739 :type 'boolean)
741 (defcustom org-replace-disputed-keys nil
742 "Non-nil means use alternative key bindings for some keys.
743 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
744 These keys are also used by other packages like shift-selection-mode'
745 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
746 If you want to use Org-mode together with one of these other modes,
747 or more generally if you would like to move some Org-mode commands to
748 other keys, set this variable and configure the keys with the variable
749 `org-disputed-keys'.
751 This option is only relevant at load-time of Org-mode, and must be set
752 *before* org.el is loaded. Changing it requires a restart of Emacs to
753 become effective."
754 :group 'org-startup
755 :type 'boolean)
757 (defcustom org-use-extra-keys nil
758 "Non-nil means use extra key sequence definitions for certain commands.
759 This happens automatically if you run XEmacs or if `window-system'
760 is nil. This variable lets you do the same manually. You must
761 set it before loading org.
763 Example: on Carbon Emacs 22 running graphically, with an external
764 keyboard on a Powerbook, the default way of setting M-left might
765 not work for either Alt or ESC. Setting this variable will make
766 it work for ESC."
767 :group 'org-startup
768 :type 'boolean)
770 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
772 (defcustom org-disputed-keys
773 '(([(shift up)] . [(meta p)])
774 ([(shift down)] . [(meta n)])
775 ([(shift left)] . [(meta -)])
776 ([(shift right)] . [(meta +)])
777 ([(control shift right)] . [(meta shift +)])
778 ([(control shift left)] . [(meta shift -)]))
779 "Keys for which Org-mode and other modes compete.
780 This is an alist, cars are the default keys, second element specifies
781 the alternative to use when `org-replace-disputed-keys' is t.
783 Keys can be specified in any syntax supported by `define-key'.
784 The value of this option takes effect only at Org-mode's startup,
785 therefore you'll have to restart Emacs to apply it after changing."
786 :group 'org-startup
787 :type 'alist)
789 (defun org-key (key)
790 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
791 Or return the original if not disputed.
792 Also apply the translations defined in `org-xemacs-key-equivalents'."
793 (when org-replace-disputed-keys
794 (let* ((nkey (key-description key))
795 (x (org-find-if (lambda (x)
796 (equal (key-description (car x)) nkey))
797 org-disputed-keys)))
798 (setq key (if x (cdr x) key))))
799 (when (featurep 'xemacs)
800 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
801 key)
803 (defun org-find-if (predicate seq)
804 (catch 'exit
805 (while seq
806 (if (funcall predicate (car seq))
807 (throw 'exit (car seq))
808 (pop seq)))))
810 (defun org-defkey (keymap key def)
811 "Define a key, possibly translated, as returned by `org-key'."
812 (define-key keymap (org-key key) def))
814 (defcustom org-ellipsis nil
815 "The ellipsis to use in the Org-mode outline.
816 When nil, just use the standard three dots. When a string, use that instead,
817 When a face, use the standard 3 dots, but with the specified face.
818 The change affects only Org-mode (which will then use its own display table).
819 Changing this requires executing `M-x org-mode' in a buffer to become
820 effective."
821 :group 'org-startup
822 :type '(choice (const :tag "Default" nil)
823 (face :tag "Face" :value org-warning)
824 (string :tag "String" :value "...#")))
826 (defvar org-display-table nil
827 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
829 (defgroup org-keywords nil
830 "Keywords in Org-mode."
831 :tag "Org Keywords"
832 :group 'org)
834 (defcustom org-deadline-string "DEADLINE:"
835 "String to mark deadline entries.
836 A deadline is this string, followed by a time stamp. Should be a word,
837 terminated by a colon. You can insert a schedule keyword and
838 a timestamp with \\[org-deadline].
839 Changes become only effective after restarting Emacs."
840 :group 'org-keywords
841 :type 'string)
843 (defcustom org-scheduled-string "SCHEDULED:"
844 "String to mark scheduled TODO entries.
845 A schedule is this string, followed by a time stamp. Should be a word,
846 terminated by a colon. You can insert a schedule keyword and
847 a timestamp with \\[org-schedule].
848 Changes become only effective after restarting Emacs."
849 :group 'org-keywords
850 :type 'string)
852 (defcustom org-closed-string "CLOSED:"
853 "String used as the prefix for timestamps logging closing a TODO entry."
854 :group 'org-keywords
855 :type 'string)
857 (defcustom org-clock-string "CLOCK:"
858 "String used as prefix for timestamps clocking work hours on an item."
859 :group 'org-keywords
860 :type 'string)
862 (defcustom org-closed-keep-when-no-todo nil
863 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
864 :group 'org-todo
865 :group 'org-keywords
866 :version "24.4"
867 :package-version '(Org . "8.0")
868 :type 'boolean)
870 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
871 org-scheduled-string "\\|"
872 org-deadline-string "\\|"
873 org-closed-string "\\|"
874 org-clock-string "\\)")
875 "Matches a line with planning or clock info.")
877 (defcustom org-comment-string "COMMENT"
878 "Entries starting with this keyword will never be exported.
879 An entry can be toggled between COMMENT and normal with
880 \\[org-toggle-comment].
881 Changes become only effective after restarting Emacs."
882 :group 'org-keywords
883 :type 'string)
885 (defcustom org-quote-string "QUOTE"
886 "Entries starting with this keyword will be exported in fixed-width font.
887 Quoting applies only to the text in the entry following the headline, and does
888 not extend beyond the next headline, even if that is lower level.
889 An entry can be toggled between QUOTE and normal with
890 \\[org-toggle-fixed-width-section]."
891 :group 'org-keywords
892 :type 'string)
894 (defconst org-repeat-re
895 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
896 "Regular expression for specifying repeated events.
897 After a match, group 1 contains the repeat expression.")
899 (defgroup org-structure nil
900 "Options concerning the general structure of Org-mode files."
901 :tag "Org Structure"
902 :group 'org)
904 (defgroup org-reveal-location nil
905 "Options about how to make context of a location visible."
906 :tag "Org Reveal Location"
907 :group 'org-structure)
909 (defconst org-context-choice
910 '(choice
911 (const :tag "Always" t)
912 (const :tag "Never" nil)
913 (repeat :greedy t :tag "Individual contexts"
914 (cons
915 (choice :tag "Context"
916 (const agenda)
917 (const org-goto)
918 (const occur-tree)
919 (const tags-tree)
920 (const link-search)
921 (const mark-goto)
922 (const bookmark-jump)
923 (const isearch)
924 (const default))
925 (boolean))))
926 "Contexts for the reveal options.")
928 (defcustom org-show-hierarchy-above '((default . t))
929 "Non-nil means show full hierarchy when revealing a location.
930 Org-mode often shows locations in an org-mode file which might have
931 been invisible before. When this is set, the hierarchy of headings
932 above the exposed location is shown.
933 Turning this off for example for sparse trees makes them very compact.
934 Instead of t, this can also be an alist specifying this option for different
935 contexts. Valid contexts are
936 agenda when exposing an entry from the agenda
937 org-goto when using the command `org-goto' on key C-c C-j
938 occur-tree when using the command `org-occur' on key C-c /
939 tags-tree when constructing a sparse tree based on tags matches
940 link-search when exposing search matches associated with a link
941 mark-goto when exposing the jump goal of a mark
942 bookmark-jump when exposing a bookmark location
943 isearch when exiting from an incremental search
944 default default for all contexts not set explicitly"
945 :group 'org-reveal-location
946 :type org-context-choice)
948 (defcustom org-show-following-heading '((default . nil))
949 "Non-nil means show following heading when revealing a location.
950 Org-mode often shows locations in an org-mode file which might have
951 been invisible before. When this is set, the heading following the
952 match is shown.
953 Turning this off for example for sparse trees makes them very compact,
954 but makes it harder to edit the location of the match. In such a case,
955 use the command \\[org-reveal] to show more context.
956 Instead of t, this can also be an alist specifying this option for different
957 contexts. See `org-show-hierarchy-above' for valid contexts."
958 :group 'org-reveal-location
959 :type org-context-choice)
961 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
962 "Non-nil means show all sibling heading when revealing a location.
963 Org-mode often shows locations in an org-mode file which might have
964 been invisible before. When this is set, the sibling of the current entry
965 heading are all made visible. If `org-show-hierarchy-above' is t,
966 the same happens on each level of the hierarchy above the current entry.
968 By default this is on for the isearch context, off for all other contexts.
969 Turning this off for example for sparse trees makes them very compact,
970 but makes it harder to edit the location of the match. In such a case,
971 use the command \\[org-reveal] to show more context.
972 Instead of t, this can also be an alist specifying this option for different
973 contexts. See `org-show-hierarchy-above' for valid contexts."
974 :group 'org-reveal-location
975 :type org-context-choice
976 :version "24.4"
977 :package-version '(Org . "8.0"))
979 (defcustom org-show-entry-below '((default . nil))
980 "Non-nil means show the entry below a headline when revealing a location.
981 Org-mode often shows locations in an org-mode file which might have
982 been invisible before. When this is set, the text below the headline that is
983 exposed is also shown.
985 By default this is off for all contexts.
986 Instead of t, this can also be an alist specifying this option for different
987 contexts. See `org-show-hierarchy-above' for valid contexts."
988 :group 'org-reveal-location
989 :type org-context-choice)
991 (defcustom org-indirect-buffer-display 'other-window
992 "How should indirect tree buffers be displayed?
993 This applies to indirect buffers created with the commands
994 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
995 Valid values are:
996 current-window Display in the current window
997 other-window Just display in another window.
998 dedicated-frame Create one new frame, and re-use it each time.
999 new-frame Make a new frame each time. Note that in this case
1000 previously-made indirect buffers are kept, and you need to
1001 kill these buffers yourself."
1002 :group 'org-structure
1003 :group 'org-agenda-windows
1004 :type '(choice
1005 (const :tag "In current window" current-window)
1006 (const :tag "In current frame, other window" other-window)
1007 (const :tag "Each time a new frame" new-frame)
1008 (const :tag "One dedicated frame" dedicated-frame)))
1010 (defcustom org-use-speed-commands nil
1011 "Non-nil means activate single letter commands at beginning of a headline.
1012 This may also be a function to test for appropriate locations where speed
1013 commands should be active."
1014 :group 'org-structure
1015 :type '(choice
1016 (const :tag "Never" nil)
1017 (const :tag "At beginning of headline stars" t)
1018 (function)))
1020 (defcustom org-speed-commands-user nil
1021 "Alist of additional speed commands.
1022 This list will be checked before `org-speed-commands-default'
1023 when the variable `org-use-speed-commands' is non-nil
1024 and when the cursor is at the beginning of a headline.
1025 The car if each entry is a string with a single letter, which must
1026 be assigned to `self-insert-command' in the global map.
1027 The cdr is either a command to be called interactively, a function
1028 to be called, or a form to be evaluated.
1029 An entry that is just a list with a single string will be interpreted
1030 as a descriptive headline that will be added when listing the speed
1031 commands in the Help buffer using the `?' speed command."
1032 :group 'org-structure
1033 :type '(repeat :value ("k" . ignore)
1034 (choice :value ("k" . ignore)
1035 (list :tag "Descriptive Headline" (string :tag "Headline"))
1036 (cons :tag "Letter and Command"
1037 (string :tag "Command letter")
1038 (choice
1039 (function)
1040 (sexp))))))
1042 (defcustom org-bookmark-names-plist
1043 '(:last-capture "org-capture-last-stored"
1044 :last-refile "org-refile-last-stored"
1045 :last-capture-marker "org-capture-last-stored-marker")
1046 "Names for bookmarks automatically set by some Org commands.
1047 This can provide strings as names for a number of bookmarks Org sets
1048 automatically. The following keys are currently implemented:
1049 :last-capture
1050 :last-capture-marker
1051 :last-refile
1052 When a key does not show up in the property list, the corresponding bookmark
1053 is not set."
1054 :group 'org-structure
1055 :type 'plist)
1057 (defgroup org-cycle nil
1058 "Options concerning visibility cycling in Org-mode."
1059 :tag "Org Cycle"
1060 :group 'org-structure)
1062 (defcustom org-cycle-skip-children-state-if-no-children t
1063 "Non-nil means skip CHILDREN state in entries that don't have any."
1064 :group 'org-cycle
1065 :type 'boolean)
1067 (defcustom org-cycle-max-level nil
1068 "Maximum level which should still be subject to visibility cycling.
1069 Levels higher than this will, for cycling, be treated as text, not a headline.
1070 When `org-odd-levels-only' is set, a value of N in this variable actually
1071 means 2N-1 stars as the limiting headline.
1072 When nil, cycle all levels.
1073 Note that the limiting level of cycling is also influenced by
1074 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1075 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1076 than its value."
1077 :group 'org-cycle
1078 :type '(choice
1079 (const :tag "No limit" nil)
1080 (integer :tag "Maximum level")))
1082 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1083 "Names of drawers. Drawers are not opened by cycling on the headline above.
1084 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1085 this:
1086 :DRAWERNAME:
1087 .....
1088 :END:
1089 The drawer \"PROPERTIES\" is special for capturing properties through
1090 the property API.
1092 Drawers can be defined on the per-file basis with a line like:
1094 #+DRAWERS: HIDDEN STATE PROPERTIES"
1095 :group 'org-structure
1096 :group 'org-cycle
1097 :type '(repeat (string :tag "Drawer Name")))
1099 (defcustom org-hide-block-startup nil
1100 "Non-nil means entering Org-mode will fold all blocks.
1101 This can also be set in on a per-file basis with
1103 #+STARTUP: hideblocks
1104 #+STARTUP: showblocks"
1105 :group 'org-startup
1106 :group 'org-cycle
1107 :type 'boolean)
1109 (defcustom org-cycle-global-at-bob nil
1110 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1111 This makes it possible to do global cycling without having to use S-TAB or
1112 \\[universal-argument] TAB. For this special case to work, the first line
1113 of the buffer must not be a headline -- it may be empty or some other text.
1114 When used in this way, `org-cycle-hook' is disabled temporarily to make
1115 sure the cursor stays at the beginning of the buffer. When this option is
1116 nil, don't do anything special at the beginning of the buffer."
1117 :group 'org-cycle
1118 :type 'boolean)
1120 (defcustom org-cycle-level-after-item/entry-creation t
1121 "Non-nil means cycle entry level or item indentation in new empty entries.
1123 When the cursor is at the end of an empty headline, i.e., with only stars
1124 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1125 and then all possible ancestor states, before returning to the original state.
1126 This makes data entry extremely fast: M-RET to create a new headline,
1127 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1129 When the cursor is at the end of an empty plain list item, one TAB will
1130 make it a subitem, two or more tabs will back up to make this an item
1131 higher up in the item hierarchy."
1132 :group 'org-cycle
1133 :type 'boolean)
1135 (defcustom org-cycle-emulate-tab t
1136 "Where should `org-cycle' emulate TAB.
1137 nil Never
1138 white Only in completely white lines
1139 whitestart Only at the beginning of lines, before the first non-white char
1140 t Everywhere except in headlines
1141 exc-hl-bol Everywhere except at the start of a headline
1142 If TAB is used in a place where it does not emulate TAB, the current subtree
1143 visibility is cycled."
1144 :group 'org-cycle
1145 :type '(choice (const :tag "Never" nil)
1146 (const :tag "Only in completely white lines" white)
1147 (const :tag "Before first char in a line" whitestart)
1148 (const :tag "Everywhere except in headlines" t)
1149 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1151 (defcustom org-cycle-separator-lines 2
1152 "Number of empty lines needed to keep an empty line between collapsed trees.
1153 If you leave an empty line between the end of a subtree and the following
1154 headline, this empty line is hidden when the subtree is folded.
1155 Org-mode will leave (exactly) one empty line visible if the number of
1156 empty lines is equal or larger to the number given in this variable.
1157 So the default 2 means at least 2 empty lines after the end of a subtree
1158 are needed to produce free space between a collapsed subtree and the
1159 following headline.
1161 If the number is negative, and the number of empty lines is at least -N,
1162 all empty lines are shown.
1164 Special case: when 0, never leave empty lines in collapsed view."
1165 :group 'org-cycle
1166 :type 'integer)
1167 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1169 (defcustom org-pre-cycle-hook nil
1170 "Hook that is run before visibility cycling is happening.
1171 The function(s) in this hook must accept a single argument which indicates
1172 the new state that will be set right after running this hook. The
1173 argument is a symbol. Before a global state change, it can have the values
1174 `overview', `content', or `all'. Before a local state change, it can have
1175 the values `folded', `children', or `subtree'."
1176 :group 'org-cycle
1177 :type 'hook)
1179 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1180 org-cycle-hide-drawers
1181 org-cycle-hide-inline-tasks
1182 org-cycle-show-empty-lines
1183 org-optimize-window-after-visibility-change)
1184 "Hook that is run after `org-cycle' has changed the buffer visibility.
1185 The function(s) in this hook must accept a single argument which indicates
1186 the new state that was set by the most recent `org-cycle' command. The
1187 argument is a symbol. After a global state change, it can have the values
1188 `overview', `contents', or `all'. After a local state change, it can have
1189 the values `folded', `children', or `subtree'."
1190 :group 'org-cycle
1191 :type 'hook)
1193 (defgroup org-edit-structure nil
1194 "Options concerning structure editing in Org-mode."
1195 :tag "Org Edit Structure"
1196 :group 'org-structure)
1198 (defcustom org-odd-levels-only nil
1199 "Non-nil means skip even levels and only use odd levels for the outline.
1200 This has the effect that two stars are being added/taken away in
1201 promotion/demotion commands. It also influences how levels are
1202 handled by the exporters.
1203 Changing it requires restart of `font-lock-mode' to become effective
1204 for fontification also in regions already fontified.
1205 You may also set this on a per-file basis by adding one of the following
1206 lines to the buffer:
1208 #+STARTUP: odd
1209 #+STARTUP: oddeven"
1210 :group 'org-edit-structure
1211 :group 'org-appearance
1212 :type 'boolean)
1214 (defcustom org-adapt-indentation t
1215 "Non-nil means adapt indentation to outline node level.
1217 When this variable is set, Org assumes that you write outlines by
1218 indenting text in each node to align with the headline (after the stars).
1219 The following issues are influenced by this variable:
1221 - When this is set and the *entire* text in an entry is indented, the
1222 indentation is increased by one space in a demotion command, and
1223 decreased by one in a promotion command. If any line in the entry
1224 body starts with text at column 0, indentation is not changed at all.
1226 - Property drawers and planning information is inserted indented when
1227 this variable s set. When nil, they will not be indented.
1229 - TAB indents a line relative to context. The lines below a headline
1230 will be indented when this variable is set.
1232 Note that this is all about true indentation, by adding and removing
1233 space characters. See also `org-indent.el' which does level-dependent
1234 indentation in a virtual way, i.e. at display time in Emacs."
1235 :group 'org-edit-structure
1236 :type 'boolean)
1238 (defcustom org-special-ctrl-a/e nil
1239 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1241 When t, `C-a' will bring back the cursor to the beginning of the
1242 headline text, i.e. after the stars and after a possible TODO
1243 keyword. In an item, this will be the position after bullet and
1244 check-box, if any. When the cursor is already at that position,
1245 another `C-a' will bring it to the beginning of the line.
1247 `C-e' will jump to the end of the headline, ignoring the presence
1248 of tags in the headline. A second `C-e' will then jump to the
1249 true end of the line, after any tags. This also means that, when
1250 this variable is non-nil, `C-e' also will never jump beyond the
1251 end of the heading of a folded section, i.e. not after the
1252 ellipses.
1254 When set to the symbol `reversed', the first `C-a' or `C-e' works
1255 normally, going to the true line boundary first. Only a directly
1256 following, identical keypress will bring the cursor to the
1257 special positions.
1259 This may also be a cons cell where the behavior for `C-a' and
1260 `C-e' is set separately."
1261 :group 'org-edit-structure
1262 :type '(choice
1263 (const :tag "off" nil)
1264 (const :tag "on: after stars/bullet and before tags first" t)
1265 (const :tag "reversed: true line boundary first" reversed)
1266 (cons :tag "Set C-a and C-e separately"
1267 (choice :tag "Special C-a"
1268 (const :tag "off" nil)
1269 (const :tag "on: after stars/bullet first" t)
1270 (const :tag "reversed: before stars/bullet first" reversed))
1271 (choice :tag "Special C-e"
1272 (const :tag "off" nil)
1273 (const :tag "on: before tags first" t)
1274 (const :tag "reversed: after tags first" reversed)))))
1275 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1277 (defcustom org-special-ctrl-k nil
1278 "Non-nil means `C-k' will behave specially in headlines.
1279 When nil, `C-k' will call the default `kill-line' command.
1280 When t, the following will happen while the cursor is in the headline:
1282 - When the cursor is at the beginning of a headline, kill the entire
1283 line and possible the folded subtree below the line.
1284 - When in the middle of the headline text, kill the headline up to the tags.
1285 - When after the headline text, kill the tags."
1286 :group 'org-edit-structure
1287 :type 'boolean)
1289 (defcustom org-ctrl-k-protect-subtree nil
1290 "Non-nil means, do not delete a hidden subtree with C-k.
1291 When set to the symbol `error', simply throw an error when C-k is
1292 used to kill (part-of) a headline that has hidden text behind it.
1293 Any other non-nil value will result in a query to the user, if it is
1294 OK to kill that hidden subtree. When nil, kill without remorse."
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not protect hidden subtrees" nil)
1299 (const :tag "Protect hidden subtrees with a security query" t)
1300 (const :tag "Never kill a hidden subtree with C-k" error)))
1302 (defcustom org-special-ctrl-o t
1303 "Non-nil means, make `C-o' insert a row in tables."
1304 :group 'org-edit-structure
1305 :type 'boolean)
1307 (defcustom org-catch-invisible-edits nil
1308 "Check if in invisible region before inserting or deleting a character.
1309 Valid values are:
1311 nil Do not check, so just do invisible edits.
1312 error Throw an error and do nothing.
1313 show Make point visible, and do the requested edit.
1314 show-and-error Make point visible, then throw an error and abort the edit.
1315 smart Make point visible, and do insertion/deletion if it is
1316 adjacent to visible text and the change feels predictable.
1317 Never delete a previously invisible character or add in the
1318 middle or right after an invisible region. Basically, this
1319 allows insertion and backward-delete right before ellipses.
1320 FIXME: maybe in this case we should not even show?"
1321 :group 'org-edit-structure
1322 :version "24.1"
1323 :type '(choice
1324 (const :tag "Do not check" nil)
1325 (const :tag "Throw error when trying to edit" error)
1326 (const :tag "Unhide, but do not do the edit" show-and-error)
1327 (const :tag "Show invisible part and do the edit" show)
1328 (const :tag "Be smart and do the right thing" smart)))
1330 (defcustom org-yank-folded-subtrees t
1331 "Non-nil means when yanking subtrees, fold them.
1332 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1333 it starts with a heading and all other headings in it are either children
1334 or siblings, then fold all the subtrees. However, do this only if no
1335 text after the yank would be swallowed into a folded tree by this action."
1336 :group 'org-edit-structure
1337 :type 'boolean)
1339 (defcustom org-yank-adjusted-subtrees nil
1340 "Non-nil means when yanking subtrees, adjust the level.
1341 With this setting, `org-paste-subtree' is used to insert the subtree, see
1342 this function for details."
1343 :group 'org-edit-structure
1344 :type 'boolean)
1346 (defcustom org-M-RET-may-split-line '((default . t))
1347 "Non-nil means M-RET will split the line at the cursor position.
1348 When nil, it will go to the end of the line before making a
1349 new line.
1350 You may also set this option in a different way for different
1351 contexts. Valid contexts are:
1353 headline when creating a new headline
1354 item when creating a new item
1355 table in a table field
1356 default the value to be used for all contexts not explicitly
1357 customized"
1358 :group 'org-structure
1359 :group 'org-table
1360 :type '(choice
1361 (const :tag "Always" t)
1362 (const :tag "Never" nil)
1363 (repeat :greedy t :tag "Individual contexts"
1364 (cons
1365 (choice :tag "Context"
1366 (const headline)
1367 (const item)
1368 (const table)
1369 (const default))
1370 (boolean)))))
1373 (defcustom org-insert-heading-respect-content nil
1374 "Non-nil means insert new headings after the current subtree.
1375 When nil, the new heading is created directly after the current line.
1376 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1377 this variable on for the duration of the command."
1378 :group 'org-structure
1379 :type 'boolean)
1381 (defcustom org-blank-before-new-entry '((heading . auto)
1382 (plain-list-item . auto))
1383 "Should `org-insert-heading' leave a blank line before new heading/item?
1384 The value is an alist, with `heading' and `plain-list-item' as CAR,
1385 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1386 which case Org will look at the surrounding headings/items and try to
1387 make an intelligent decision whether to insert a blank line or not.
1389 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1390 the setting here is ignored and no empty line is inserted to avoid breaking
1391 the list structure."
1392 :group 'org-edit-structure
1393 :type '(list
1394 (cons (const heading)
1395 (choice (const :tag "Never" nil)
1396 (const :tag "Always" t)
1397 (const :tag "Auto" auto)))
1398 (cons (const plain-list-item)
1399 (choice (const :tag "Never" nil)
1400 (const :tag "Always" t)
1401 (const :tag "Auto" auto)))))
1403 (defcustom org-insert-heading-hook nil
1404 "Hook being run after inserting a new heading."
1405 :group 'org-edit-structure
1406 :type 'hook)
1408 (defcustom org-enable-fixed-width-editor t
1409 "Non-nil means lines starting with \":\" are treated as fixed-width.
1410 This currently only means they are never auto-wrapped.
1411 When nil, such lines will be treated like ordinary lines.
1412 See also the QUOTE keyword."
1413 :group 'org-edit-structure
1414 :type 'boolean)
1416 (defcustom org-goto-auto-isearch t
1417 "Non-nil means typing characters in `org-goto' starts incremental search.
1418 When nil, you can use these keybindings to navigate the buffer:
1420 q Quit the org-goto interface
1421 n Go to the next visible heading
1422 p Go to the previous visible heading
1423 f Go one heading forward on same level
1424 b Go one heading backward on same level
1425 u Go one heading up"
1426 :group 'org-edit-structure
1427 :type 'boolean)
1429 (defgroup org-sparse-trees nil
1430 "Options concerning sparse trees in Org-mode."
1431 :tag "Org Sparse Trees"
1432 :group 'org-structure)
1434 (defcustom org-highlight-sparse-tree-matches t
1435 "Non-nil means highlight all matches that define a sparse tree.
1436 The highlights will automatically disappear the next time the buffer is
1437 changed by an edit command."
1438 :group 'org-sparse-trees
1439 :type 'boolean)
1441 (defcustom org-remove-highlights-with-change t
1442 "Non-nil means any change to the buffer will remove temporary highlights.
1443 Such highlights are created by `org-occur' and `org-clock-display'.
1444 When nil, `C-c C-c needs to be used to get rid of the highlights.
1445 The highlights created by `org-preview-latex-fragment' always need
1446 `C-c C-c' to be removed."
1447 :group 'org-sparse-trees
1448 :group 'org-time
1449 :type 'boolean)
1452 (defcustom org-occur-hook '(org-first-headline-recenter)
1453 "Hook that is run after `org-occur' has constructed a sparse tree.
1454 This can be used to recenter the window to show as much of the structure
1455 as possible."
1456 :group 'org-sparse-trees
1457 :type 'hook)
1459 (defgroup org-imenu-and-speedbar nil
1460 "Options concerning imenu and speedbar in Org-mode."
1461 :tag "Org Imenu and Speedbar"
1462 :group 'org-structure)
1464 (defcustom org-imenu-depth 2
1465 "The maximum level for Imenu access to Org-mode headlines.
1466 This also applied for speedbar access."
1467 :group 'org-imenu-and-speedbar
1468 :type 'integer)
1470 (defgroup org-table nil
1471 "Options concerning tables in Org-mode."
1472 :tag "Org Table"
1473 :group 'org)
1475 (defcustom org-enable-table-editor 'optimized
1476 "Non-nil means lines starting with \"|\" are handled by the table editor.
1477 When nil, such lines will be treated like ordinary lines.
1479 When equal to the symbol `optimized', the table editor will be optimized to
1480 do the following:
1481 - Automatic overwrite mode in front of whitespace in table fields.
1482 This makes the structure of the table stay in tact as long as the edited
1483 field does not exceed the column width.
1484 - Minimize the number of realigns. Normally, the table is aligned each time
1485 TAB or RET are pressed to move to another field. With optimization this
1486 happens only if changes to a field might have changed the column width.
1487 Optimization requires replacing the functions `self-insert-command',
1488 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1489 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1490 very good at guessing when a re-align will be necessary, but you can always
1491 force one with \\[org-ctrl-c-ctrl-c].
1493 If you would like to use the optimized version in Org-mode, but the
1494 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1496 This variable can be used to turn on and off the table editor during a session,
1497 but in order to toggle optimization, a restart is required.
1499 See also the variable `org-table-auto-blank-field'."
1500 :group 'org-table
1501 :type '(choice
1502 (const :tag "off" nil)
1503 (const :tag "on" t)
1504 (const :tag "on, optimized" optimized)))
1506 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1507 (version<= emacs-version "24.1"))
1508 "Non-nil means cluster self-insert commands for undo when possible.
1509 If this is set, then, like in the Emacs command loop, 20 consecutive
1510 characters will be undone together.
1511 This is configurable, because there is some impact on typing performance."
1512 :group 'org-table
1513 :type 'boolean)
1515 (defcustom org-table-tab-recognizes-table.el t
1516 "Non-nil means TAB will automatically notice a table.el table.
1517 When it sees such a table, it moves point into it and - if necessary -
1518 calls `table-recognize-table'."
1519 :group 'org-table-editing
1520 :type 'boolean)
1522 (defgroup org-link nil
1523 "Options concerning links in Org-mode."
1524 :tag "Org Link"
1525 :group 'org)
1527 (defvar org-link-abbrev-alist-local nil
1528 "Buffer-local version of `org-link-abbrev-alist', which see.
1529 The value of this is taken from the #+LINK lines.")
1530 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1532 (defcustom org-link-abbrev-alist nil
1533 "Alist of link abbreviations.
1534 The car of each element is a string, to be replaced at the start of a link.
1535 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1536 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1538 [[linkkey:tag][description]]
1540 The 'linkkey' must be a word word, starting with a letter, followed
1541 by letters, numbers, '-' or '_'.
1543 If REPLACE is a string, the tag will simply be appended to create the link.
1544 If the string contains \"%s\", the tag will be inserted there. If the string
1545 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1546 at that point (see the function `url-hexify-string'). If the string contains
1547 the specifier \"%(my-function)\", then the custom function `my-function' will
1548 be invoked: this function takes the tag as its only argument and must return
1549 a string.
1551 REPLACE may also be a function that will be called with the tag as the
1552 only argument to create the link, which should be returned as a string.
1554 See the manual for examples."
1555 :group 'org-link
1556 :type '(repeat
1557 (cons
1558 (string :tag "Protocol")
1559 (choice
1560 (string :tag "Format")
1561 (function)))))
1563 (defcustom org-descriptive-links t
1564 "Non-nil means Org will display descriptive links.
1565 E.g. [[http://orgmode.org][Org website]] will be displayed as
1566 \"Org Website\", hiding the link itself and just displaying its
1567 description. When set to `nil', Org will display the full links
1568 literally.
1570 You can interactively set the value of this variable by calling
1571 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1572 :group 'org-link
1573 :type 'boolean)
1575 (defcustom org-link-file-path-type 'adaptive
1576 "How the path name in file links should be stored.
1577 Valid values are:
1579 relative Relative to the current directory, i.e. the directory of the file
1580 into which the link is being inserted.
1581 absolute Absolute path, if possible with ~ for home directory.
1582 noabbrev Absolute path, no abbreviation of home directory.
1583 adaptive Use relative path for files in the current directory and sub-
1584 directories of it. For other files, use an absolute path."
1585 :group 'org-link
1586 :type '(choice
1587 (const relative)
1588 (const absolute)
1589 (const noabbrev)
1590 (const adaptive)))
1592 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1593 "Types of links that should be activated in Org-mode files.
1594 This is a list of symbols, each leading to the activation of a certain link
1595 type. In principle, it does not hurt to turn on most link types - there may
1596 be a small gain when turning off unused link types. The types are:
1598 bracket The recommended [[link][description]] or [[link]] links with hiding.
1599 angle Links in angular brackets that may contain whitespace like
1600 <bbdb:Carsten Dominik>.
1601 plain Plain links in normal text, no whitespace, like http://google.com.
1602 radio Text that is matched by a radio target, see manual for details.
1603 tag Tag settings in a headline (link to tag search).
1604 date Time stamps (link to calendar).
1605 footnote Footnote labels.
1607 Changing this variable requires a restart of Emacs to become effective."
1608 :group 'org-link
1609 :type '(set :greedy t
1610 (const :tag "Double bracket links" bracket)
1611 (const :tag "Angular bracket links" angle)
1612 (const :tag "Plain text links" plain)
1613 (const :tag "Radio target matches" radio)
1614 (const :tag "Tags" tag)
1615 (const :tag "Timestamps" date)
1616 (const :tag "Footnotes" footnote)))
1618 (defcustom org-make-link-description-function nil
1619 "Function to use for generating link descriptions from links.
1620 When nil, the link location will be used. This function must take
1621 two parameters: the first one is the link, the second one is the
1622 description generated by `org-insert-link'. The function should
1623 return the description to use."
1624 :group 'org-link
1625 :type '(choice (const nil) (function)))
1627 (defgroup org-link-store nil
1628 "Options concerning storing links in Org-mode."
1629 :tag "Org Store Link"
1630 :group 'org-link)
1632 (defcustom org-url-hexify-p t
1633 "When non-nil, hexify URL when creating a link."
1634 :type 'boolean
1635 :version "24.3"
1636 :group 'org-link-store)
1638 (defcustom org-email-link-description-format "Email %c: %.30s"
1639 "Format of the description part of a link to an email or usenet message.
1640 The following %-escapes will be replaced by corresponding information:
1642 %F full \"From\" field
1643 %f name, taken from \"From\" field, address if no name
1644 %T full \"To\" field
1645 %t first name in \"To\" field, address if no name
1646 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1647 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1648 %s subject
1649 %d date
1650 %m message-id.
1652 You may use normal field width specification between the % and the letter.
1653 This is for example useful to limit the length of the subject.
1655 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1656 :group 'org-link-store
1657 :type 'string)
1659 (defcustom org-from-is-user-regexp
1660 (let (r1 r2)
1661 (when (and user-mail-address (not (string= user-mail-address "")))
1662 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1663 (when (and user-full-name (not (string= user-full-name "")))
1664 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1665 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1666 "Regexp matched against the \"From:\" header of an email or usenet message.
1667 It should match if the message is from the user him/herself."
1668 :group 'org-link-store
1669 :type 'regexp)
1671 (defcustom org-context-in-file-links t
1672 "Non-nil means file links from `org-store-link' contain context.
1673 A search string will be added to the file name with :: as separator and
1674 used to find the context when the link is activated by the command
1675 `org-open-at-point'. When this option is t, the entire active region
1676 will be placed in the search string of the file link. If set to a
1677 positive integer, only the first n lines of context will be stored.
1679 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1680 negates this setting for the duration of the command."
1681 :group 'org-link-store
1682 :type '(choice boolean integer))
1684 (defcustom org-keep-stored-link-after-insertion nil
1685 "Non-nil means keep link in list for entire session.
1687 The command `org-store-link' adds a link pointing to the current
1688 location to an internal list. These links accumulate during a session.
1689 The command `org-insert-link' can be used to insert links into any
1690 Org-mode file (offering completion for all stored links). When this
1691 option is nil, every link which has been inserted once using \\[org-insert-link]
1692 will be removed from the list, to make completing the unused links
1693 more efficient."
1694 :group 'org-link-store
1695 :type 'boolean)
1697 (defgroup org-link-follow nil
1698 "Options concerning following links in Org-mode."
1699 :tag "Org Follow Link"
1700 :group 'org-link)
1702 (defcustom org-link-translation-function nil
1703 "Function to translate links with different syntax to Org syntax.
1704 This can be used to translate links created for example by the Planner
1705 or emacs-wiki packages to Org syntax.
1706 The function must accept two parameters, a TYPE containing the link
1707 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1708 which is everything after the link protocol. It should return a cons
1709 with possibly modified values of type and path.
1710 Org contains a function for this, so if you set this variable to
1711 `org-translate-link-from-planner', you should be able follow many
1712 links created by planner."
1713 :group 'org-link-follow
1714 :type '(choice (const nil) (function)))
1716 (defcustom org-follow-link-hook nil
1717 "Hook that is run after a link has been followed."
1718 :group 'org-link-follow
1719 :type 'hook)
1721 (defcustom org-tab-follows-link nil
1722 "Non-nil means on links TAB will follow the link.
1723 Needs to be set before org.el is loaded.
1724 This really should not be used, it does not make sense, and the
1725 implementation is bad."
1726 :group 'org-link-follow
1727 :type 'boolean)
1729 (defcustom org-return-follows-link nil
1730 "Non-nil means on links RET will follow the link.
1731 In tables, the special behavior of RET has precedence."
1732 :group 'org-link-follow
1733 :type 'boolean)
1735 (defcustom org-mouse-1-follows-link
1736 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1737 "Non-nil means mouse-1 on a link will follow the link.
1738 A longer mouse click will still set point. Does not work on XEmacs.
1739 Needs to be set before org.el is loaded."
1740 :group 'org-link-follow
1741 :version "24.4"
1742 :package-version '(Org . "8.3")
1743 :type '(choice
1744 (const :tag "A double click follows the link" double)
1745 (const :tag "Unconditionally follow the link with mouse-1" t)
1746 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1748 (defcustom org-mark-ring-length 4
1749 "Number of different positions to be recorded in the ring.
1750 Changing this requires a restart of Emacs to work correctly."
1751 :group 'org-link-follow
1752 :type 'integer)
1754 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1755 "Non-nil means internal links in Org files must exactly match a headline.
1756 When nil, the link search tries to match a phrase with all words
1757 in the search text."
1758 :group 'org-link-follow
1759 :version "24.1"
1760 :type '(choice
1761 (const :tag "Use fuzzy text search" nil)
1762 (const :tag "Match only exact headline" t)
1763 (const :tag "Match exact headline or query to create it"
1764 query-to-create)))
1766 (defcustom org-link-frame-setup
1767 '((vm . vm-visit-folder-other-frame)
1768 (vm-imap . vm-visit-imap-folder-other-frame)
1769 (gnus . org-gnus-no-new-news)
1770 (file . find-file-other-window)
1771 (wl . wl-other-frame))
1772 "Setup the frame configuration for following links.
1773 When following a link with Emacs, it may often be useful to display
1774 this link in another window or frame. This variable can be used to
1775 set this up for the different types of links.
1776 For VM, use any of
1777 `vm-visit-folder'
1778 `vm-visit-folder-other-window'
1779 `vm-visit-folder-other-frame'
1780 For Gnus, use any of
1781 `gnus'
1782 `gnus-other-frame'
1783 `org-gnus-no-new-news'
1784 For FILE, use any of
1785 `find-file'
1786 `find-file-other-window'
1787 `find-file-other-frame'
1788 For Wanderlust use any of
1789 `wl'
1790 `wl-other-frame'
1791 For the calendar, use the variable `calendar-setup'.
1792 For BBDB, it is currently only possible to display the matches in
1793 another window."
1794 :group 'org-link-follow
1795 :type '(list
1796 (cons (const vm)
1797 (choice
1798 (const vm-visit-folder)
1799 (const vm-visit-folder-other-window)
1800 (const vm-visit-folder-other-frame)))
1801 (cons (const vm-imap)
1802 (choice
1803 (const vm-visit-imap-folder)
1804 (const vm-visit-imap-folder-other-window)
1805 (const vm-visit-imap-folder-other-frame)))
1806 (cons (const gnus)
1807 (choice
1808 (const gnus)
1809 (const gnus-other-frame)
1810 (const org-gnus-no-new-news)))
1811 (cons (const file)
1812 (choice
1813 (const find-file)
1814 (const find-file-other-window)
1815 (const find-file-other-frame)))
1816 (cons (const wl)
1817 (choice
1818 (const wl)
1819 (const wl-other-frame)))))
1821 (defcustom org-display-internal-link-with-indirect-buffer nil
1822 "Non-nil means use indirect buffer to display infile links.
1823 Activating internal links (from one location in a file to another location
1824 in the same file) normally just jumps to the location. When the link is
1825 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1826 is displayed in
1827 another window. When this option is set, the other window actually displays
1828 an indirect buffer clone of the current buffer, to avoid any visibility
1829 changes to the current buffer."
1830 :group 'org-link-follow
1831 :type 'boolean)
1833 (defcustom org-open-non-existing-files nil
1834 "Non-nil means `org-open-file' will open non-existing files.
1835 When nil, an error will be generated.
1836 This variable applies only to external applications because they
1837 might choke on non-existing files. If the link is to a file that
1838 will be opened in Emacs, the variable is ignored."
1839 :group 'org-link-follow
1840 :type 'boolean)
1842 (defcustom org-open-directory-means-index-dot-org nil
1843 "Non-nil means a link to a directory really means to index.org.
1844 When nil, following a directory link will run dired or open a finder/explorer
1845 window on that directory."
1846 :group 'org-link-follow
1847 :type 'boolean)
1849 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1850 "Function and arguments to call for following mailto links.
1851 This is a list with the first element being a Lisp function, and the
1852 remaining elements being arguments to the function. In string arguments,
1853 %a will be replaced by the address, and %s will be replaced by the subject
1854 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1855 :group 'org-link-follow
1856 :type '(choice
1857 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1858 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1859 (const :tag "message-mail" (message-mail "%a" "%s"))
1860 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1862 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1863 "Non-nil means ask for confirmation before executing shell links.
1864 Shell links can be dangerous: just think about a link
1866 [[shell:rm -rf ~/*][Google Search]]
1868 This link would show up in your Org-mode document as \"Google Search\",
1869 but really it would remove your entire home directory.
1870 Therefore we advise against setting this variable to nil.
1871 Just change it to `y-or-n-p' if you want to confirm with a
1872 single keystroke rather than having to type \"yes\"."
1873 :group 'org-link-follow
1874 :type '(choice
1875 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1876 (const :tag "with y-or-n (faster)" y-or-n-p)
1877 (const :tag "no confirmation (dangerous)" nil)))
1878 (put 'org-confirm-shell-link-function
1879 'safe-local-variable
1880 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1882 (defcustom org-confirm-shell-link-not-regexp ""
1883 "A regexp to skip confirmation for shell links."
1884 :group 'org-link-follow
1885 :version "24.1"
1886 :type 'regexp)
1888 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1889 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1890 Elisp links can be dangerous: just think about a link
1892 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1894 This link would show up in your Org-mode document as \"Google Search\",
1895 but really it would remove your entire home directory.
1896 Therefore we advise against setting this variable to nil.
1897 Just change it to `y-or-n-p' if you want to confirm with a
1898 single keystroke rather than having to type \"yes\"."
1899 :group 'org-link-follow
1900 :type '(choice
1901 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1902 (const :tag "with y-or-n (faster)" y-or-n-p)
1903 (const :tag "no confirmation (dangerous)" nil)))
1904 (put 'org-confirm-shell-link-function
1905 'safe-local-variable
1906 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1908 (defcustom org-confirm-elisp-link-not-regexp ""
1909 "A regexp to skip confirmation for Elisp links."
1910 :group 'org-link-follow
1911 :version "24.1"
1912 :type 'regexp)
1914 (defconst org-file-apps-defaults-gnu
1915 '((remote . emacs)
1916 (system . mailcap)
1917 (t . mailcap))
1918 "Default file applications on a UNIX or GNU/Linux system.
1919 See `org-file-apps'.")
1921 (defconst org-file-apps-defaults-macosx
1922 '((remote . emacs)
1923 (t . "open %s")
1924 (system . "open %s")
1925 ("ps.gz" . "gv %s")
1926 ("eps.gz" . "gv %s")
1927 ("dvi" . "xdvi %s")
1928 ("fig" . "xfig %s"))
1929 "Default file applications on a MacOS X system.
1930 The system \"open\" is known as a default, but we use X11 applications
1931 for some files for which the OS does not have a good default.
1932 See `org-file-apps'.")
1934 (defconst org-file-apps-defaults-windowsnt
1935 (list
1936 '(remote . emacs)
1937 (cons t
1938 (list (if (featurep 'xemacs)
1939 'mswindows-shell-execute
1940 'w32-shell-execute)
1941 "open" 'file))
1942 (cons 'system
1943 (list (if (featurep 'xemacs)
1944 'mswindows-shell-execute
1945 'w32-shell-execute)
1946 "open" 'file)))
1947 "Default file applications on a Windows NT system.
1948 The system \"open\" is used for most files.
1949 See `org-file-apps'.")
1951 (defcustom org-file-apps
1952 '((auto-mode . emacs)
1953 ("\\.mm\\'" . default)
1954 ("\\.x?html?\\'" . default)
1955 ("\\.pdf\\'" . default))
1956 "External applications for opening `file:path' items in a document.
1957 Org-mode uses system defaults for different file types, but
1958 you can use this variable to set the application for a given file
1959 extension. The entries in this list are cons cells where the car identifies
1960 files and the cdr the corresponding command. Possible values for the
1961 file identifier are
1962 \"string\" A string as a file identifier can be interpreted in different
1963 ways, depending on its contents:
1965 - Alphanumeric characters only:
1966 Match links with this file extension.
1967 Example: (\"pdf\" . \"evince %s\")
1968 to open PDFs with evince.
1970 - Regular expression: Match links where the
1971 filename matches the regexp. If you want to
1972 use groups here, use shy groups.
1974 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1975 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1976 to open *.html and *.xhtml with firefox.
1978 - Regular expression which contains (non-shy) groups:
1979 Match links where the whole link, including \"::\", and
1980 anything after that, matches the regexp.
1981 In a custom command string, %1, %2, etc. are replaced with
1982 the parts of the link that were matched by the groups.
1983 For backwards compatibility, if a command string is given
1984 that does not use any of the group matches, this case is
1985 handled identically to the second one (i.e. match against
1986 file name only).
1987 In a custom lisp form, you can access the group matches with
1988 (match-string n link).
1990 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1991 to open [[file:document.pdf::5]] with evince at page 5.
1993 `directory' Matches a directory
1994 `remote' Matches a remote file, accessible through tramp or efs.
1995 Remote files most likely should be visited through Emacs
1996 because external applications cannot handle such paths.
1997 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1998 so all files Emacs knows how to handle. Using this with
1999 command `emacs' will open most files in Emacs. Beware that this
2000 will also open html files inside Emacs, unless you add
2001 (\"html\" . default) to the list as well.
2002 t Default for files not matched by any of the other options.
2003 `system' The system command to open files, like `open' on Windows
2004 and Mac OS X, and mailcap under GNU/Linux. This is the command
2005 that will be selected if you call `C-c C-o' with a double
2006 \\[universal-argument] \\[universal-argument] prefix.
2008 Possible values for the command are:
2009 `emacs' The file will be visited by the current Emacs process.
2010 `default' Use the default application for this file type, which is the
2011 association for t in the list, most likely in the system-specific
2012 part.
2013 This can be used to overrule an unwanted setting in the
2014 system-specific variable.
2015 `system' Use the system command for opening files, like \"open\".
2016 This command is specified by the entry whose car is `system'.
2017 Most likely, the system-specific version of this variable
2018 does define this command, but you can overrule/replace it
2019 here.
2020 string A command to be executed by a shell; %s will be replaced
2021 by the path to the file.
2022 sexp A Lisp form which will be evaluated. The file path will
2023 be available in the Lisp variable `file'.
2024 For more examples, see the system specific constants
2025 `org-file-apps-defaults-macosx'
2026 `org-file-apps-defaults-windowsnt'
2027 `org-file-apps-defaults-gnu'."
2028 :group 'org-link-follow
2029 :type '(repeat
2030 (cons (choice :value ""
2031 (string :tag "Extension")
2032 (const :tag "System command to open files" system)
2033 (const :tag "Default for unrecognized files" t)
2034 (const :tag "Remote file" remote)
2035 (const :tag "Links to a directory" directory)
2036 (const :tag "Any files that have Emacs modes"
2037 auto-mode))
2038 (choice :value ""
2039 (const :tag "Visit with Emacs" emacs)
2040 (const :tag "Use default" default)
2041 (const :tag "Use the system command" system)
2042 (string :tag "Command")
2043 (sexp :tag "Lisp form")))))
2045 (defcustom org-doi-server-url "http://dx.doi.org/"
2046 "The URL of the DOI server."
2047 :type 'string
2048 :version "24.3"
2049 :group 'org-link-follow)
2051 (defgroup org-refile nil
2052 "Options concerning refiling entries in Org-mode."
2053 :tag "Org Refile"
2054 :group 'org)
2056 (defcustom org-directory "~/org"
2057 "Directory with org files.
2058 This is just a default location to look for Org files. There is no need
2059 at all to put your files into this directory. It is only used in the
2060 following situations:
2062 1. When a capture template specifies a target file that is not an
2063 absolute path. The path will then be interpreted relative to
2064 `org-directory'
2065 2. When a capture note is filed away in an interactive way (when exiting the
2066 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2067 with `org-directory' as the default path."
2068 :group 'org-refile
2069 :group 'org-capture
2070 :type 'directory)
2072 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2073 "Default target for storing notes.
2074 Used as a fall back file for org-capture.el, for templates that
2075 do not specify a target file."
2076 :group 'org-refile
2077 :group 'org-capture
2078 :type '(choice
2079 (const :tag "Default from remember-data-file" nil)
2080 file))
2082 (defcustom org-goto-interface 'outline
2083 "The default interface to be used for `org-goto'.
2084 Allowed values are:
2085 outline The interface shows an outline of the relevant file
2086 and the correct heading is found by moving through
2087 the outline or by searching with incremental search.
2088 outline-path-completion Headlines in the current buffer are offered via
2089 completion. This is the interface also used by
2090 the refile command."
2091 :group 'org-refile
2092 :type '(choice
2093 (const :tag "Outline" outline)
2094 (const :tag "Outline-path-completion" outline-path-completion)))
2096 (defcustom org-goto-max-level 5
2097 "Maximum target level when running `org-goto' with refile interface."
2098 :group 'org-refile
2099 :type 'integer)
2101 (defcustom org-reverse-note-order nil
2102 "Non-nil means store new notes at the beginning of a file or entry.
2103 When nil, new notes will be filed to the end of a file or entry.
2104 This can also be a list with cons cells of regular expressions that
2105 are matched against file names, and values."
2106 :group 'org-capture
2107 :group 'org-refile
2108 :type '(choice
2109 (const :tag "Reverse always" t)
2110 (const :tag "Reverse never" nil)
2111 (repeat :tag "By file name regexp"
2112 (cons regexp boolean))))
2114 (defcustom org-log-refile nil
2115 "Information to record when a task is refiled.
2117 Possible values are:
2119 nil Don't add anything
2120 time Add a time stamp to the task
2121 note Prompt for a note and add it with template `org-log-note-headings'
2123 This option can also be set with on a per-file-basis with
2125 #+STARTUP: nologrefile
2126 #+STARTUP: logrefile
2127 #+STARTUP: lognoterefile
2129 You can have local logging settings for a subtree by setting the LOGGING
2130 property to one or more of these keywords.
2132 When bulk-refiling from the agenda, the value `note' is forbidden and
2133 will temporarily be changed to `time'."
2134 :group 'org-refile
2135 :group 'org-progress
2136 :version "24.1"
2137 :type '(choice
2138 (const :tag "No logging" nil)
2139 (const :tag "Record timestamp" time)
2140 (const :tag "Record timestamp with note." note)))
2142 (defcustom org-refile-targets nil
2143 "Targets for refiling entries with \\[org-refile].
2144 This is a list of cons cells. Each cell contains:
2145 - a specification of the files to be considered, either a list of files,
2146 or a symbol whose function or variable value will be used to retrieve
2147 a file name or a list of file names. If you use `org-agenda-files' for
2148 that, all agenda files will be scanned for targets. Nil means consider
2149 headings in the current buffer.
2150 - A specification of how to find candidate refile targets. This may be
2151 any of:
2152 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2153 This tag has to be present in all target headlines, inheritance will
2154 not be considered.
2155 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2156 todo keyword.
2157 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2158 headlines that are refiling targets.
2159 - a cons cell (:level . N). Any headline of level N is considered a target.
2160 Note that, when `org-odd-levels-only' is set, level corresponds to
2161 order in hierarchy, not to the number of stars.
2162 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2163 Note that, when `org-odd-levels-only' is set, level corresponds to
2164 order in hierarchy, not to the number of stars.
2166 Each element of this list generates a set of possible targets.
2167 The union of these sets is presented (with completion) to
2168 the user by `org-refile'.
2170 You can set the variable `org-refile-target-verify-function' to a function
2171 to verify each headline found by the simple criteria above.
2173 When this variable is nil, all top-level headlines in the current buffer
2174 are used, equivalent to the value `((nil . (:level . 1))'."
2175 :group 'org-refile
2176 :type '(repeat
2177 (cons
2178 (choice :value org-agenda-files
2179 (const :tag "All agenda files" org-agenda-files)
2180 (const :tag "Current buffer" nil)
2181 (function) (variable) (file))
2182 (choice :tag "Identify target headline by"
2183 (cons :tag "Specific tag" (const :value :tag) (string))
2184 (cons :tag "TODO keyword" (const :value :todo) (string))
2185 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2186 (cons :tag "Level number" (const :value :level) (integer))
2187 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2189 (defcustom org-refile-target-verify-function nil
2190 "Function to verify if the headline at point should be a refile target.
2191 The function will be called without arguments, with point at the
2192 beginning of the headline. It should return t and leave point
2193 where it is if the headline is a valid target for refiling.
2195 If the target should not be selected, the function must return nil.
2196 In addition to this, it may move point to a place from where the search
2197 should be continued. For example, the function may decide that the entire
2198 subtree of the current entry should be excluded and move point to the end
2199 of the subtree."
2200 :group 'org-refile
2201 :type '(choice
2202 (const nil)
2203 (function)))
2205 (defcustom org-refile-use-cache nil
2206 "Non-nil means cache refile targets to speed up the process.
2207 The cache for a particular file will be updated automatically when
2208 the buffer has been killed, or when any of the marker used for flagging
2209 refile targets no longer points at a live buffer.
2210 If you have added new entries to a buffer that might themselves be targets,
2211 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2212 find that easier, `C-u C-u C-u C-c C-w'."
2213 :group 'org-refile
2214 :version "24.1"
2215 :type 'boolean)
2217 (defcustom org-refile-use-outline-path nil
2218 "Non-nil means provide refile targets as paths.
2219 So a level 3 headline will be available as level1/level2/level3.
2221 When the value is `file', also include the file name (without directory)
2222 into the path. In this case, you can also stop the completion after
2223 the file name, to get entries inserted as top level in the file.
2225 When `full-file-path', include the full file path."
2226 :group 'org-refile
2227 :type '(choice
2228 (const :tag "Not" nil)
2229 (const :tag "Yes" t)
2230 (const :tag "Start with file name" file)
2231 (const :tag "Start with full file path" full-file-path)))
2233 (defcustom org-outline-path-complete-in-steps t
2234 "Non-nil means complete the outline path in hierarchical steps.
2235 When Org-mode uses the refile interface to select an outline path
2236 \(see variable `org-refile-use-outline-path'), the completion of
2237 the path can be done is a single go, or if can be done in steps down
2238 the headline hierarchy. Going in steps is probably the best if you
2239 do not use a special completion package like `ido' or `icicles'.
2240 However, when using these packages, going in one step can be very
2241 fast, while still showing the whole path to the entry."
2242 :group 'org-refile
2243 :type 'boolean)
2245 (defcustom org-refile-allow-creating-parent-nodes nil
2246 "Non-nil means allow to create new nodes as refile targets.
2247 New nodes are then created by adding \"/new node name\" to the completion
2248 of an existing node. When the value of this variable is `confirm',
2249 new node creation must be confirmed by the user (recommended).
2250 When nil, the completion must match an existing entry.
2252 Note that, if the new heading is not seen by the criteria
2253 listed in `org-refile-targets', multiple instances of the same
2254 heading would be created by trying again to file under the new
2255 heading."
2256 :group 'org-refile
2257 :type '(choice
2258 (const :tag "Never" nil)
2259 (const :tag "Always" t)
2260 (const :tag "Prompt for confirmation" confirm)))
2262 (defcustom org-refile-active-region-within-subtree nil
2263 "Non-nil means also refile active region within a subtree.
2265 By default `org-refile' doesn't allow refiling regions if they
2266 don't contain a set of subtrees, but it might be convenient to
2267 do so sometimes: in that case, the first line of the region is
2268 converted to a headline before refiling."
2269 :group 'org-refile
2270 :version "24.1"
2271 :type 'boolean)
2273 (defgroup org-todo nil
2274 "Options concerning TODO items in Org-mode."
2275 :tag "Org TODO"
2276 :group 'org)
2278 (defgroup org-progress nil
2279 "Options concerning Progress logging in Org-mode."
2280 :tag "Org Progress"
2281 :group 'org-time)
2283 (defvar org-todo-interpretation-widgets
2284 '((:tag "Sequence (cycling hits every state)" sequence)
2285 (:tag "Type (cycling directly to DONE)" type))
2286 "The available interpretation symbols for customizing `org-todo-keywords'.
2287 Interested libraries should add to this list.")
2289 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2290 "List of TODO entry keyword sequences and their interpretation.
2291 \\<org-mode-map>This is a list of sequences.
2293 Each sequence starts with a symbol, either `sequence' or `type',
2294 indicating if the keywords should be interpreted as a sequence of
2295 action steps, or as different types of TODO items. The first
2296 keywords are states requiring action - these states will select a headline
2297 for inclusion into the global TODO list Org-mode produces. If one of
2298 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2299 signify that no further action is necessary. If \"|\" is not found,
2300 the last keyword is treated as the only DONE state of the sequence.
2302 The command \\[org-todo] cycles an entry through these states, and one
2303 additional state where no keyword is present. For details about this
2304 cycling, see the manual.
2306 TODO keywords and interpretation can also be set on a per-file basis with
2307 the special #+SEQ_TODO and #+TYP_TODO lines.
2309 Each keyword can optionally specify a character for fast state selection
2310 \(in combination with the variable `org-use-fast-todo-selection')
2311 and specifiers for state change logging, using the same syntax that
2312 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2313 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2314 indicates to record a time stamp each time this state is selected.
2316 Each keyword may also specify if a timestamp or a note should be
2317 recorded when entering or leaving the state, by adding additional
2318 characters in the parenthesis after the keyword. This looks like this:
2319 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2320 record only the time of the state change. With X and Y being either
2321 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2322 Y when leaving the state if and only if the *target* state does not
2323 define X. You may omit any of the fast-selection key or X or /Y,
2324 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2326 For backward compatibility, this variable may also be just a list
2327 of keywords. In this case the interpretation (sequence or type) will be
2328 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2329 :group 'org-todo
2330 :group 'org-keywords
2331 :type '(choice
2332 (repeat :tag "Old syntax, just keywords"
2333 (string :tag "Keyword"))
2334 (repeat :tag "New syntax"
2335 (cons
2336 (choice
2337 :tag "Interpretation"
2338 ;;Quick and dirty way to see
2339 ;;`org-todo-interpretations'. This takes the
2340 ;;place of item arguments
2341 :convert-widget
2342 (lambda (widget)
2343 (widget-put widget
2344 :args (mapcar
2345 #'(lambda (x)
2346 (widget-convert
2347 (cons 'const x)))
2348 org-todo-interpretation-widgets))
2349 widget))
2350 (repeat
2351 (string :tag "Keyword"))))))
2353 (defvar org-todo-keywords-1 nil
2354 "All TODO and DONE keywords active in a buffer.")
2355 (make-variable-buffer-local 'org-todo-keywords-1)
2356 (defvar org-todo-keywords-for-agenda nil)
2357 (defvar org-done-keywords-for-agenda nil)
2358 (defvar org-drawers-for-agenda nil)
2359 (defvar org-todo-keyword-alist-for-agenda nil)
2360 (defvar org-tag-alist-for-agenda nil
2361 "Alist of all tags from all agenda files.")
2362 (defvar org-tag-groups-alist-for-agenda nil
2363 "Alist of all groups tags from all current agenda files.")
2364 (defvar org-tag-groups-alist nil)
2365 (make-variable-buffer-local 'org-tag-groups-alist)
2366 (defvar org-agenda-contributing-files nil)
2367 (defvar org-not-done-keywords nil)
2368 (make-variable-buffer-local 'org-not-done-keywords)
2369 (defvar org-done-keywords nil)
2370 (make-variable-buffer-local 'org-done-keywords)
2371 (defvar org-todo-heads nil)
2372 (make-variable-buffer-local 'org-todo-heads)
2373 (defvar org-todo-sets nil)
2374 (make-variable-buffer-local 'org-todo-sets)
2375 (defvar org-todo-log-states nil)
2376 (make-variable-buffer-local 'org-todo-log-states)
2377 (defvar org-todo-kwd-alist nil)
2378 (make-variable-buffer-local 'org-todo-kwd-alist)
2379 (defvar org-todo-key-alist nil)
2380 (make-variable-buffer-local 'org-todo-key-alist)
2381 (defvar org-todo-key-trigger nil)
2382 (make-variable-buffer-local 'org-todo-key-trigger)
2384 (defcustom org-todo-interpretation 'sequence
2385 "Controls how TODO keywords are interpreted.
2386 This variable is in principle obsolete and is only used for
2387 backward compatibility, if the interpretation of todo keywords is
2388 not given already in `org-todo-keywords'. See that variable for
2389 more information."
2390 :group 'org-todo
2391 :group 'org-keywords
2392 :type '(choice (const sequence)
2393 (const type)))
2395 (defcustom org-use-fast-todo-selection t
2396 "Non-nil means use the fast todo selection scheme with C-c C-t.
2397 This variable describes if and under what circumstances the cycling
2398 mechanism for TODO keywords will be replaced by a single-key, direct
2399 selection scheme.
2401 When nil, fast selection is never used.
2403 When the symbol `prefix', it will be used when `org-todo' is called
2404 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2405 `C-u t' in an agenda buffer.
2407 When t, fast selection is used by default. In this case, the prefix
2408 argument forces cycling instead.
2410 In all cases, the special interface is only used if access keys have
2411 actually been assigned by the user, i.e. if keywords in the configuration
2412 are followed by a letter in parenthesis, like TODO(t)."
2413 :group 'org-todo
2414 :type '(choice
2415 (const :tag "Never" nil)
2416 (const :tag "By default" t)
2417 (const :tag "Only with C-u C-c C-t" prefix)))
2419 (defcustom org-provide-todo-statistics t
2420 "Non-nil means update todo statistics after insert and toggle.
2421 ALL-HEADLINES means update todo statistics by including headlines
2422 with no TODO keyword as well, counting them as not done.
2423 A list of TODO keywords means the same, but skip keywords that are
2424 not in this list.
2426 When this is set, todo statistics is updated in the parent of the
2427 current entry each time a todo state is changed."
2428 :group 'org-todo
2429 :type '(choice
2430 (const :tag "Yes, only for TODO entries" t)
2431 (const :tag "Yes, including all entries" all-headlines)
2432 (repeat :tag "Yes, for TODOs in this list"
2433 (string :tag "TODO keyword"))
2434 (other :tag "No TODO statistics" nil)))
2436 (defcustom org-hierarchical-todo-statistics t
2437 "Non-nil means TODO statistics covers just direct children.
2438 When nil, all entries in the subtree are considered.
2439 This has only an effect if `org-provide-todo-statistics' is set.
2440 To set this to nil for only a single subtree, use a COOKIE_DATA
2441 property and include the word \"recursive\" into the value."
2442 :group 'org-todo
2443 :type 'boolean)
2445 (defcustom org-after-todo-state-change-hook nil
2446 "Hook which is run after the state of a TODO item was changed.
2447 The new state (a string with a TODO keyword, or nil) is available in the
2448 Lisp variable `org-state'."
2449 :group 'org-todo
2450 :type 'hook)
2452 (defvar org-blocker-hook nil
2453 "Hook for functions that are allowed to block a state change.
2455 Functions in this hook should not modify the buffer.
2456 Each function gets as its single argument a property list,
2457 see `org-trigger-hook' for more information about this list.
2459 If any of the functions in this hook returns nil, the state change
2460 is blocked.")
2462 (defvar org-trigger-hook nil
2463 "Hook for functions that are triggered by a state change.
2465 Each function gets as its single argument a property list with at
2466 least the following elements:
2468 (:type type-of-change :position pos-at-entry-start
2469 :from old-state :to new-state)
2471 Depending on the type, more properties may be present.
2473 This mechanism is currently implemented for:
2475 TODO state changes
2476 ------------------
2477 :type todo-state-change
2478 :from previous state (keyword as a string), or nil, or a symbol
2479 'todo' or 'done', to indicate the general type of state.
2480 :to new state, like in :from")
2482 (defcustom org-enforce-todo-dependencies nil
2483 "Non-nil means undone TODO entries will block switching the parent to DONE.
2484 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2485 be blocked if any prior sibling is not yet done.
2486 Finally, if the parent is blocked because of ordered siblings of its own,
2487 the child will also be blocked."
2488 :set (lambda (var val)
2489 (set var val)
2490 (if val
2491 (add-hook 'org-blocker-hook
2492 'org-block-todo-from-children-or-siblings-or-parent)
2493 (remove-hook 'org-blocker-hook
2494 'org-block-todo-from-children-or-siblings-or-parent)))
2495 :group 'org-todo
2496 :type 'boolean)
2498 (defcustom org-enforce-todo-checkbox-dependencies nil
2499 "Non-nil means unchecked boxes will block switching the parent to DONE.
2500 When this is nil, checkboxes have no influence on switching TODO states.
2501 When non-nil, you first need to check off all check boxes before the TODO
2502 entry can be switched to DONE.
2503 This variable needs to be set before org.el is loaded, and you need to
2504 restart Emacs after a change to make the change effective. The only way
2505 to change is while Emacs is running is through the customize interface."
2506 :set (lambda (var val)
2507 (set var val)
2508 (if val
2509 (add-hook 'org-blocker-hook
2510 'org-block-todo-from-checkboxes)
2511 (remove-hook 'org-blocker-hook
2512 'org-block-todo-from-checkboxes)))
2513 :group 'org-todo
2514 :type 'boolean)
2516 (defcustom org-treat-insert-todo-heading-as-state-change nil
2517 "Non-nil means inserting a TODO heading is treated as state change.
2518 So when the command \\[org-insert-todo-heading] is used, state change
2519 logging will apply if appropriate. When nil, the new TODO item will
2520 be inserted directly, and no logging will take place."
2521 :group 'org-todo
2522 :type 'boolean)
2524 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2525 "Non-nil means switching TODO states with S-cursor counts as state change.
2526 This is the default behavior. However, setting this to nil allows a
2527 convenient way to select a TODO state and bypass any logging associated
2528 with that."
2529 :group 'org-todo
2530 :type 'boolean)
2532 (defcustom org-todo-state-tags-triggers nil
2533 "Tag changes that should be triggered by TODO state changes.
2534 This is a list. Each entry is
2536 (state-change (tag . flag) .......)
2538 State-change can be a string with a state, and empty string to indicate the
2539 state that has no TODO keyword, or it can be one of the symbols `todo'
2540 or `done', meaning any not-done or done state, respectively."
2541 :group 'org-todo
2542 :group 'org-tags
2543 :type '(repeat
2544 (cons (choice :tag "When changing to"
2545 (const :tag "Not-done state" todo)
2546 (const :tag "Done state" done)
2547 (string :tag "State"))
2548 (repeat
2549 (cons :tag "Tag action"
2550 (string :tag "Tag")
2551 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2553 (defcustom org-log-done nil
2554 "Information to record when a task moves to the DONE state.
2556 Possible values are:
2558 nil Don't add anything, just change the keyword
2559 time Add a time stamp to the task
2560 note Prompt for a note and add it with template `org-log-note-headings'
2562 This option can also be set with on a per-file-basis with
2564 #+STARTUP: nologdone
2565 #+STARTUP: logdone
2566 #+STARTUP: lognotedone
2568 You can have local logging settings for a subtree by setting the LOGGING
2569 property to one or more of these keywords."
2570 :group 'org-todo
2571 :group 'org-progress
2572 :type '(choice
2573 (const :tag "No logging" nil)
2574 (const :tag "Record CLOSED timestamp" time)
2575 (const :tag "Record CLOSED timestamp with note." note)))
2577 ;; Normalize old uses of org-log-done.
2578 (cond
2579 ((eq org-log-done t) (setq org-log-done 'time))
2580 ((and (listp org-log-done) (memq 'done org-log-done))
2581 (setq org-log-done 'note)))
2583 (defcustom org-log-reschedule nil
2584 "Information to record when the scheduling date of a tasks is modified.
2586 Possible values are:
2588 nil Don't add anything, just change the date
2589 time Add a time stamp to the task
2590 note Prompt for a note and add it with template `org-log-note-headings'
2592 This option can also be set with on a per-file-basis with
2594 #+STARTUP: nologreschedule
2595 #+STARTUP: logreschedule
2596 #+STARTUP: lognotereschedule"
2597 :group 'org-todo
2598 :group 'org-progress
2599 :type '(choice
2600 (const :tag "No logging" nil)
2601 (const :tag "Record timestamp" time)
2602 (const :tag "Record timestamp with note." note)))
2604 (defcustom org-log-redeadline nil
2605 "Information to record when the deadline date of a tasks is modified.
2607 Possible values are:
2609 nil Don't add anything, just change the date
2610 time Add a time stamp to the task
2611 note Prompt for a note and add it with template `org-log-note-headings'
2613 This option can also be set with on a per-file-basis with
2615 #+STARTUP: nologredeadline
2616 #+STARTUP: logredeadline
2617 #+STARTUP: lognoteredeadline
2619 You can have local logging settings for a subtree by setting the LOGGING
2620 property to one or more of these keywords."
2621 :group 'org-todo
2622 :group 'org-progress
2623 :type '(choice
2624 (const :tag "No logging" nil)
2625 (const :tag "Record timestamp" time)
2626 (const :tag "Record timestamp with note." note)))
2628 (defcustom org-log-note-clock-out nil
2629 "Non-nil means record a note when clocking out of an item.
2630 This can also be configured on a per-file basis by adding one of
2631 the following lines anywhere in the buffer:
2633 #+STARTUP: lognoteclock-out
2634 #+STARTUP: nolognoteclock-out"
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type 'boolean)
2639 (defcustom org-log-done-with-time t
2640 "Non-nil means the CLOSED time stamp will contain date and time.
2641 When nil, only the date will be recorded."
2642 :group 'org-progress
2643 :type 'boolean)
2645 (defcustom org-log-note-headings
2646 '((done . "CLOSING NOTE %t")
2647 (state . "State %-12s from %-12S %t")
2648 (note . "Note taken on %t")
2649 (reschedule . "Rescheduled from %S on %t")
2650 (delschedule . "Not scheduled, was %S on %t")
2651 (redeadline . "New deadline from %S on %t")
2652 (deldeadline . "Removed deadline, was %S on %t")
2653 (refile . "Refiled on %t")
2654 (clock-out . ""))
2655 "Headings for notes added to entries.
2656 The value is an alist, with the car being a symbol indicating the note
2657 context, and the cdr is the heading to be used. The heading may also be the
2658 empty string.
2659 %t in the heading will be replaced by a time stamp.
2660 %T will be an active time stamp instead the default inactive one
2661 %d will be replaced by a short-format time stamp.
2662 %D will be replaced by an active short-format time stamp.
2663 %s will be replaced by the new TODO state, in double quotes.
2664 %S will be replaced by the old TODO state, in double quotes.
2665 %u will be replaced by the user name.
2666 %U will be replaced by the full user name.
2668 In fact, it is not a good idea to change the `state' entry, because
2669 agenda log mode depends on the format of these entries."
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type '(list :greedy t
2673 (cons (const :tag "Heading when closing an item" done) string)
2674 (cons (const :tag
2675 "Heading when changing todo state (todo sequence only)"
2676 state) string)
2677 (cons (const :tag "Heading when just taking a note" note) string)
2678 (cons (const :tag "Heading when rescheduling" reschedule) string)
2679 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2680 (cons (const :tag "Heading when changing deadline" redeadline) string)
2681 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2682 (cons (const :tag "Heading when refiling" refile) string)
2683 (cons (const :tag "Heading when clocking out" clock-out) string)))
2685 (unless (assq 'note org-log-note-headings)
2686 (push '(note . "%t") org-log-note-headings))
2688 (defcustom org-log-into-drawer nil
2689 "Non-nil means insert state change notes and time stamps into a drawer.
2690 When nil, state changes notes will be inserted after the headline and
2691 any scheduling and clock lines, but not inside a drawer.
2693 The value of this variable should be the name of the drawer to use.
2694 LOGBOOK is proposed as the default drawer for this purpose, you can
2695 also set this to a string to define the drawer of your choice.
2697 A value of t is also allowed, representing \"LOGBOOK\".
2699 A value of t or nil can also be set with on a per-file-basis with
2701 #+STARTUP: logdrawer
2702 #+STARTUP: nologdrawer
2704 If this variable is set, `org-log-state-notes-insert-after-drawers'
2705 will be ignored.
2707 You can set the property LOG_INTO_DRAWER to overrule this setting for
2708 a subtree."
2709 :group 'org-todo
2710 :group 'org-progress
2711 :type '(choice
2712 (const :tag "Not into a drawer" nil)
2713 (const :tag "LOGBOOK" t)
2714 (string :tag "Other")))
2716 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2718 (defun org-log-into-drawer ()
2719 "Return the value of `org-log-into-drawer', but let properties overrule.
2720 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2721 used instead of the default value."
2722 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2723 (cond
2724 ((not p) org-log-into-drawer)
2725 ((equal p "nil") nil)
2726 ((equal p "t") "LOGBOOK")
2727 (t p))))
2729 (defcustom org-log-state-notes-insert-after-drawers nil
2730 "Non-nil means insert state change notes after any drawers in entry.
2731 Only the drawers that *immediately* follow the headline and the
2732 deadline/scheduled line are skipped.
2733 When nil, insert notes right after the heading and perhaps the line
2734 with deadline/scheduling if present.
2736 This variable will have no effect if `org-log-into-drawer' is
2737 set."
2738 :group 'org-todo
2739 :group 'org-progress
2740 :type 'boolean)
2742 (defcustom org-log-states-order-reversed t
2743 "Non-nil means the latest state note will be directly after heading.
2744 When nil, the state change notes will be ordered according to time.
2746 This option can also be set with on a per-file-basis with
2748 #+STARTUP: logstatesreversed
2749 #+STARTUP: nologstatesreversed"
2750 :group 'org-todo
2751 :group 'org-progress
2752 :type 'boolean)
2754 (defcustom org-todo-repeat-to-state nil
2755 "The TODO state to which a repeater should return the repeating task.
2756 By default this is the first task in a TODO sequence, or the previous state
2757 in a TODO_TYP set. But you can specify another task here.
2758 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2759 :group 'org-todo
2760 :version "24.1"
2761 :type '(choice (const :tag "Head of sequence" nil)
2762 (string :tag "Specific state")))
2764 (defcustom org-log-repeat 'time
2765 "Non-nil means record moving through the DONE state when triggering repeat.
2766 An auto-repeating task is immediately switched back to TODO when
2767 marked DONE. If you are not logging state changes (by adding \"@\"
2768 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2769 record a closing note, there will be no record of the task moving
2770 through DONE. This variable forces taking a note anyway.
2772 nil Don't force a record
2773 time Record a time stamp
2774 note Prompt for a note and add it with template `org-log-note-headings'
2776 This option can also be set with on a per-file-basis with
2778 #+STARTUP: nologrepeat
2779 #+STARTUP: logrepeat
2780 #+STARTUP: lognoterepeat
2782 You can have local logging settings for a subtree by setting the LOGGING
2783 property to one or more of these keywords."
2784 :group 'org-todo
2785 :group 'org-progress
2786 :type '(choice
2787 (const :tag "Don't force a record" nil)
2788 (const :tag "Force recording the DONE state" time)
2789 (const :tag "Force recording a note with the DONE state" note)))
2792 (defgroup org-priorities nil
2793 "Priorities in Org-mode."
2794 :tag "Org Priorities"
2795 :group 'org-todo)
2797 (defcustom org-enable-priority-commands t
2798 "Non-nil means priority commands are active.
2799 When nil, these commands will be disabled, so that you never accidentally
2800 set a priority."
2801 :group 'org-priorities
2802 :type 'boolean)
2804 (defcustom org-highest-priority ?A
2805 "The highest priority of TODO items. A character like ?A, ?B etc.
2806 Must have a smaller ASCII number than `org-lowest-priority'."
2807 :group 'org-priorities
2808 :type 'character)
2810 (defcustom org-lowest-priority ?C
2811 "The lowest priority of TODO items. A character like ?A, ?B etc.
2812 Must have a larger ASCII number than `org-highest-priority'."
2813 :group 'org-priorities
2814 :type 'character)
2816 (defcustom org-default-priority ?B
2817 "The default priority of TODO items.
2818 This is the priority an item gets if no explicit priority is given.
2819 When starting to cycle on an empty priority the first step in the cycle
2820 depends on `org-priority-start-cycle-with-default'. The resulting first
2821 step priority must not exceed the range from `org-highest-priority' to
2822 `org-lowest-priority' which means that `org-default-priority' has to be
2823 in this range exclusive or inclusive the range boundaries. Else the
2824 first step refuses to set the default and the second will fall back
2825 to (depending on the command used) the highest or lowest priority."
2826 :group 'org-priorities
2827 :type 'character)
2829 (defcustom org-priority-start-cycle-with-default t
2830 "Non-nil means start with default priority when starting to cycle.
2831 When this is nil, the first step in the cycle will be (depending on the
2832 command used) one higher or lower than the default priority.
2833 See also `org-default-priority'."
2834 :group 'org-priorities
2835 :type 'boolean)
2837 (defcustom org-get-priority-function nil
2838 "Function to extract the priority from a string.
2839 The string is normally the headline. If this is nil Org computes the
2840 priority from the priority cookie like [#A] in the headline. It returns
2841 an integer, increasing by 1000 for each priority level.
2842 The user can set a different function here, which should take a string
2843 as an argument and return the numeric priority."
2844 :group 'org-priorities
2845 :version "24.1"
2846 :type '(choice
2847 (const nil)
2848 (function)))
2850 (defgroup org-time nil
2851 "Options concerning time stamps and deadlines in Org-mode."
2852 :tag "Org Time"
2853 :group 'org)
2855 (defcustom org-insert-labeled-timestamps-at-point nil
2856 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2857 When nil, these labeled time stamps are forces into the second line of an
2858 entry, just after the headline. When scheduling from the global TODO list,
2859 the time stamp will always be forced into the second line."
2860 :group 'org-time
2861 :type 'boolean)
2863 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2864 "Formats for `format-time-string' which are used for time stamps.
2865 It is not recommended to change this constant.")
2867 (defcustom org-time-stamp-rounding-minutes '(0 5)
2868 "Number of minutes to round time stamps to.
2869 These are two values, the first applies when first creating a time stamp.
2870 The second applies when changing it with the commands `S-up' and `S-down'.
2871 When changing the time stamp, this means that it will change in steps
2872 of N minutes, as given by the second value.
2874 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2875 numbers should be factors of 60, so for example 5, 10, 15.
2877 When this is larger than 1, you can still force an exact time stamp by using
2878 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2879 and by using a prefix arg to `S-up/down' to specify the exact number
2880 of minutes to shift."
2881 :group 'org-time
2882 :get #'(lambda (var) ; Make sure both elements are there
2883 (if (integerp (default-value var))
2884 (list (default-value var) 5)
2885 (default-value var)))
2886 :type '(list
2887 (integer :tag "when inserting times")
2888 (integer :tag "when modifying times")))
2890 ;; Normalize old customizations of this variable.
2891 (when (integerp org-time-stamp-rounding-minutes)
2892 (setq org-time-stamp-rounding-minutes
2893 (list org-time-stamp-rounding-minutes
2894 org-time-stamp-rounding-minutes)))
2896 (defcustom org-display-custom-times nil
2897 "Non-nil means overlay custom formats over all time stamps.
2898 The formats are defined through the variable `org-time-stamp-custom-formats'.
2899 To turn this on on a per-file basis, insert anywhere in the file:
2900 #+STARTUP: customtime"
2901 :group 'org-time
2902 :set 'set-default
2903 :type 'sexp)
2904 (make-variable-buffer-local 'org-display-custom-times)
2906 (defcustom org-time-stamp-custom-formats
2907 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2908 "Custom formats for time stamps. See `format-time-string' for the syntax.
2909 These are overlaid over the default ISO format if the variable
2910 `org-display-custom-times' is set. Time like %H:%M should be at the
2911 end of the second format. The custom formats are also honored by export
2912 commands, if custom time display is turned on at the time of export."
2913 :group 'org-time
2914 :type 'sexp)
2916 (defun org-time-stamp-format (&optional long inactive)
2917 "Get the right format for a time string."
2918 (let ((f (if long (cdr org-time-stamp-formats)
2919 (car org-time-stamp-formats))))
2920 (if inactive
2921 (concat "[" (substring f 1 -1) "]")
2922 f)))
2924 (defcustom org-time-clocksum-format
2925 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2926 "The format string used when creating CLOCKSUM lines.
2927 This is also used when Org mode generates a time duration.
2929 The value can be a single format string containing two
2930 %-sequences, which will be filled with the number of hours and
2931 minutes in that order.
2933 Alternatively, the value can be a plist associating any of the
2934 keys :years, :months, :weeks, :days, :hours or :minutes with
2935 format strings. The time duration is formatted using only the
2936 time components that are needed and concatenating the results.
2937 If a time unit in absent, it falls back to the next smallest
2938 unit.
2940 The keys :require-years, :require-months, :require-days,
2941 :require-weeks, :require-hours, :require-minutes are also
2942 meaningful. A non-nil value for these keys indicates that the
2943 corresponding time component should always be included, even if
2944 its value is 0.
2947 For example,
2949 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2950 :require-minutes t)
2952 means durations longer than a day will be expressed in days,
2953 hours and minutes, and durations less than a day will always be
2954 expressed in hours and minutes (even for durations less than an
2955 hour).
2957 The value
2959 \(:days \"%dd\" :minutes \"%dm\")
2961 means durations longer than a day will be expressed in days and
2962 minutes, and durations less than a day will be expressed entirely
2963 in minutes (even for durations longer than an hour)."
2964 :group 'org-time
2965 :group 'org-clock
2966 :version "24.4"
2967 :package-version '(Org . "8.0")
2968 :type '(choice (string :tag "Format string")
2969 (set :tag "Plist"
2970 (group :inline t (const :tag "Years" :years)
2971 (string :tag "Format string"))
2972 (group :inline t
2973 (const :tag "Always show years" :require-years)
2974 (const t))
2975 (group :inline t (const :tag "Months" :months)
2976 (string :tag "Format string"))
2977 (group :inline t
2978 (const :tag "Always show months" :require-months)
2979 (const t))
2980 (group :inline t (const :tag "Weeks" :weeks)
2981 (string :tag "Format string"))
2982 (group :inline t
2983 (const :tag "Always show weeks" :require-weeks)
2984 (const t))
2985 (group :inline t (const :tag "Days" :days)
2986 (string :tag "Format string"))
2987 (group :inline t
2988 (const :tag "Always show days" :require-days)
2989 (const t))
2990 (group :inline t (const :tag "Hours" :hours)
2991 (string :tag "Format string"))
2992 (group :inline t
2993 (const :tag "Always show hours" :require-hours)
2994 (const t))
2995 (group :inline t (const :tag "Minutes" :minutes)
2996 (string :tag "Format string"))
2997 (group :inline t
2998 (const :tag "Always show minutes" :require-minutes)
2999 (const t)))))
3001 (defcustom org-time-clocksum-use-fractional nil
3002 "When non-nil, \\[org-clock-display] uses fractional times.
3003 See `org-time-clocksum-format' for more on time clock formats."
3004 :group 'org-time
3005 :group 'org-clock
3006 :version "24.3"
3007 :type 'boolean)
3009 (defcustom org-time-clocksum-use-effort-durations nil
3010 "When non-nil, \\[org-clock-display] uses effort durations.
3011 E.g. by default, one day is considered to be a 8 hours effort,
3012 so a task that has been clocked for 16 hours will be displayed
3013 as during 2 days in the clock display or in the clocktable.
3015 See `org-effort-durations' on how to set effort durations
3016 and `org-time-clocksum-format' for more on time clock formats."
3017 :group 'org-time
3018 :group 'org-clock
3019 :version "24.4"
3020 :package-version '(Org . "8.0")
3021 :type 'boolean)
3023 (defcustom org-time-clocksum-fractional-format "%.2f"
3024 "The format string used when creating CLOCKSUM lines,
3025 or when Org mode generates a time duration, if
3026 `org-time-clocksum-use-fractional' is enabled.
3028 The value can be a single format string containing one
3029 %-sequence, which will be filled with the number of hours as
3030 a float.
3032 Alternatively, the value can be a plist associating any of the
3033 keys :years, :months, :weeks, :days, :hours or :minutes with
3034 a format string. The time duration is formatted using the
3035 largest time unit which gives a non-zero integer part. If all
3036 specified formats have zero integer part, the smallest time unit
3037 is used."
3038 :group 'org-time
3039 :type '(choice (string :tag "Format string")
3040 (set (group :inline t (const :tag "Years" :years)
3041 (string :tag "Format string"))
3042 (group :inline t (const :tag "Months" :months)
3043 (string :tag "Format string"))
3044 (group :inline t (const :tag "Weeks" :weeks)
3045 (string :tag "Format string"))
3046 (group :inline t (const :tag "Days" :days)
3047 (string :tag "Format string"))
3048 (group :inline t (const :tag "Hours" :hours)
3049 (string :tag "Format string"))
3050 (group :inline t (const :tag "Minutes" :minutes)
3051 (string :tag "Format string")))))
3053 (defcustom org-deadline-warning-days 14
3054 "Number of days before expiration during which a deadline becomes active.
3055 This variable governs the display in sparse trees and in the agenda.
3056 When 0 or negative, it means use this number (the absolute value of it)
3057 even if a deadline has a different individual lead time specified.
3059 Custom commands can set this variable in the options section."
3060 :group 'org-time
3061 :group 'org-agenda-daily/weekly
3062 :type 'integer)
3064 (defcustom org-scheduled-delay-days 0
3065 "Number of days before a scheduled item becomes active.
3066 This variable governs the display in sparse trees and in the agenda.
3067 The default value (i.e. 0) means: don't delay scheduled item.
3068 When negative, it means use this number (the absolute value of it)
3069 even if a scheduled item has a different individual delay time
3070 specified.
3072 Custom commands can set this variable in the options section."
3073 :group 'org-time
3074 :group 'org-agenda-daily/weekly
3075 :version "24.4"
3076 :package-version '(Org . "8.0")
3077 :type 'integer)
3079 (defcustom org-read-date-prefer-future t
3080 "Non-nil means assume future for incomplete date input from user.
3081 This affects the following situations:
3082 1. The user gives a month but not a year.
3083 For example, if it is April and you enter \"feb 2\", this will be read
3084 as Feb 2, *next* year. \"May 5\", however, will be this year.
3085 2. The user gives a day, but no month.
3086 For example, if today is the 15th, and you enter \"3\", Org-mode will
3087 read this as the third of *next* month. However, if you enter \"17\",
3088 it will be considered as *this* month.
3090 If you set this variable to the symbol `time', then also the following
3091 will work:
3093 3. If the user gives a time.
3094 If the time is before now, it will be interpreted as tomorrow.
3096 Currently none of this works for ISO week specifications.
3098 When this option is nil, the current day, month and year will always be
3099 used as defaults.
3101 See also `org-agenda-jump-prefer-future'."
3102 :group 'org-time
3103 :type '(choice
3104 (const :tag "Never" nil)
3105 (const :tag "Check month and day" t)
3106 (const :tag "Check month, day, and time" time)))
3108 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3109 "Should the agenda jump command prefer the future for incomplete dates?
3110 The default is to do the same as configured in `org-read-date-prefer-future'.
3111 But you can also set a deviating value here.
3112 This may t or nil, or the symbol `org-read-date-prefer-future'."
3113 :group 'org-agenda
3114 :group 'org-time
3115 :version "24.1"
3116 :type '(choice
3117 (const :tag "Use org-read-date-prefer-future"
3118 org-read-date-prefer-future)
3119 (const :tag "Never" nil)
3120 (const :tag "Always" t)))
3122 (defcustom org-read-date-force-compatible-dates t
3123 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3125 Depending on the system Emacs is running on, certain dates cannot
3126 be represented with the type used internally to represent time.
3127 Dates between 1970-1-1 and 2038-1-1 can always be represented
3128 correctly. Some systems allow for earlier dates, some for later,
3129 some for both. One way to find out it to insert any date into an
3130 Org buffer, putting the cursor on the year and hitting S-up and
3131 S-down to test the range.
3133 When this variable is set to t, the date/time prompt will not let
3134 you specify dates outside the 1970-2037 range, so it is certain that
3135 these dates will work in whatever version of Emacs you are
3136 running, and also that you can move a file from one Emacs implementation
3137 to another. WHenever Org is forcing the year for you, it will display
3138 a message and beep.
3140 When this variable is nil, Org will check if the date is
3141 representable in the specific Emacs implementation you are using.
3142 If not, it will force a year, usually the current year, and beep
3143 to remind you. Currently this setting is not recommended because
3144 the likelihood that you will open your Org files in an Emacs that
3145 has limited date range is not negligible.
3147 A workaround for this problem is to use diary sexp dates for time
3148 stamps outside of this range."
3149 :group 'org-time
3150 :version "24.1"
3151 :type 'boolean)
3153 (defcustom org-read-date-display-live t
3154 "Non-nil means display current interpretation of date prompt live.
3155 This display will be in an overlay, in the minibuffer."
3156 :group 'org-time
3157 :type 'boolean)
3159 (defcustom org-read-date-popup-calendar t
3160 "Non-nil means pop up a calendar when prompting for a date.
3161 In the calendar, the date can be selected with mouse-1. However, the
3162 minibuffer will also be active, and you can simply enter the date as well.
3163 When nil, only the minibuffer will be available."
3164 :group 'org-time
3165 :type 'boolean)
3166 (org-defvaralias 'org-popup-calendar-for-date-prompt
3167 'org-read-date-popup-calendar)
3169 (make-obsolete-variable
3170 'org-read-date-minibuffer-setup-hook
3171 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3172 (defcustom org-read-date-minibuffer-setup-hook nil
3173 "Hook to be used to set up keys for the date/time interface.
3174 Add key definitions to `minibuffer-local-map', which will be a
3175 temporary copy.
3177 WARNING: This option is obsolete, you should use
3178 `org-read-date-minibuffer-local-map' to set up keys."
3179 :group 'org-time
3180 :type 'hook)
3182 (defcustom org-extend-today-until 0
3183 "The hour when your day really ends. Must be an integer.
3184 This has influence for the following applications:
3185 - When switching the agenda to \"today\". It it is still earlier than
3186 the time given here, the day recognized as TODAY is actually yesterday.
3187 - When a date is read from the user and it is still before the time given
3188 here, the current date and time will be assumed to be yesterday, 23:59.
3189 Also, timestamps inserted in capture templates follow this rule.
3191 IMPORTANT: This is a feature whose implementation is and likely will
3192 remain incomplete. Really, it is only here because past midnight seems to
3193 be the favorite working time of John Wiegley :-)"
3194 :group 'org-time
3195 :type 'integer)
3197 (defcustom org-use-effective-time nil
3198 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3199 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3200 \"effective time\" of any timestamps between midnight and 8am will be
3201 23:59 of the previous day."
3202 :group 'org-time
3203 :version "24.1"
3204 :type 'boolean)
3206 (defcustom org-use-last-clock-out-time-as-effective-time nil
3207 "When non-nil, use the last clock out time for `org-todo'.
3208 Note that this option has precedence over the combined use of
3209 `org-use-effective-time' and `org-extend-today-until'."
3210 :group 'org-time
3211 :version "24.4"
3212 :package-version '(Org . "8.0")
3213 :type 'boolean)
3215 (defcustom org-edit-timestamp-down-means-later nil
3216 "Non-nil means S-down will increase the time in a time stamp.
3217 When nil, S-up will increase."
3218 :group 'org-time
3219 :type 'boolean)
3221 (defcustom org-calendar-follow-timestamp-change t
3222 "Non-nil means make the calendar window follow timestamp changes.
3223 When a timestamp is modified and the calendar window is visible, it will be
3224 moved to the new date."
3225 :group 'org-time
3226 :type 'boolean)
3228 (defgroup org-tags nil
3229 "Options concerning tags in Org-mode."
3230 :tag "Org Tags"
3231 :group 'org)
3233 (defcustom org-tag-alist nil
3234 "List of tags allowed in Org-mode files.
3235 When this list is nil, Org-mode will base TAG input on what is already in the
3236 buffer.
3237 The value of this variable is an alist, the car of each entry must be a
3238 keyword as a string, the cdr may be a character that is used to select
3239 that tag through the fast-tag-selection interface.
3240 See the manual for details."
3241 :group 'org-tags
3242 :type '(repeat
3243 (choice
3244 (cons (string :tag "Tag name")
3245 (character :tag "Access char"))
3246 (list :tag "Start radio group"
3247 (const :startgroup)
3248 (option (string :tag "Group description")))
3249 (list :tag "Group tags delimiter"
3250 (const :grouptags))
3251 (list :tag "End radio group"
3252 (const :endgroup)
3253 (option (string :tag "Group description")))
3254 (const :tag "New line" (:newline)))))
3256 (defcustom org-tag-persistent-alist nil
3257 "List of tags that will always appear in all Org-mode files.
3258 This is in addition to any in buffer settings or customizations
3259 of `org-tag-alist'.
3260 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3261 The value of this variable is an alist, the car of each entry must be a
3262 keyword as a string, the cdr may be a character that is used to select
3263 that tag through the fast-tag-selection interface.
3264 See the manual for details.
3265 To disable these tags on a per-file basis, insert anywhere in the file:
3266 #+STARTUP: noptag"
3267 :group 'org-tags
3268 :type '(repeat
3269 (choice
3270 (cons (string :tag "Tag name")
3271 (character :tag "Access char"))
3272 (const :tag "Start radio group" (:startgroup))
3273 (const :tag "Group tags delimiter" (:grouptags))
3274 (const :tag "End radio group" (:endgroup))
3275 (const :tag "New line" (:newline)))))
3277 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3278 "If non-nil, always offer completion for all tags of all agenda files.
3279 Instead of customizing this variable directly, you might want to
3280 set it locally for capture buffers, because there no list of
3281 tags in that file can be created dynamically (there are none).
3283 (add-hook 'org-capture-mode-hook
3284 (lambda ()
3285 (set (make-local-variable
3286 'org-complete-tags-always-offer-all-agenda-tags)
3287 t)))"
3288 :group 'org-tags
3289 :version "24.1"
3290 :type 'boolean)
3292 (defvar org-file-tags nil
3293 "List of tags that can be inherited by all entries in the file.
3294 The tags will be inherited if the variable `org-use-tag-inheritance'
3295 says they should be.
3296 This variable is populated from #+FILETAGS lines.")
3298 (defcustom org-use-fast-tag-selection 'auto
3299 "Non-nil means use fast tag selection scheme.
3300 This is a special interface to select and deselect tags with single keys.
3301 When nil, fast selection is never used.
3302 When the symbol `auto', fast selection is used if and only if selection
3303 characters for tags have been configured, either through the variable
3304 `org-tag-alist' or through a #+TAGS line in the buffer.
3305 When t, fast selection is always used and selection keys are assigned
3306 automatically if necessary."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "Always" t)
3310 (const :tag "Never" nil)
3311 (const :tag "When selection characters are configured" auto)))
3313 (defcustom org-fast-tag-selection-single-key nil
3314 "Non-nil means fast tag selection exits after first change.
3315 When nil, you have to press RET to exit it.
3316 During fast tag selection, you can toggle this flag with `C-c'.
3317 This variable can also have the value `expert'. In this case, the window
3318 displaying the tags menu is not even shown, until you press C-c again."
3319 :group 'org-tags
3320 :type '(choice
3321 (const :tag "No" nil)
3322 (const :tag "Yes" t)
3323 (const :tag "Expert" expert)))
3325 (defvar org-fast-tag-selection-include-todo nil
3326 "Non-nil means fast tags selection interface will also offer TODO states.
3327 This is an undocumented feature, you should not rely on it.")
3329 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3330 "The column to which tags should be indented in a headline.
3331 If this number is positive, it specifies the column. If it is negative,
3332 it means that the tags should be flushright to that column. For example,
3333 -80 works well for a normal 80 character screen.
3334 When 0, place tags directly after headline text, with only one space in
3335 between."
3336 :group 'org-tags
3337 :type 'integer)
3339 (defcustom org-auto-align-tags t
3340 "Non-nil keeps tags aligned when modifying headlines.
3341 Some operations (i.e. demoting) change the length of a headline and
3342 therefore shift the tags around. With this option turned on, after
3343 each such operation the tags are again aligned to `org-tags-column'."
3344 :group 'org-tags
3345 :type 'boolean)
3347 (defcustom org-use-tag-inheritance t
3348 "Non-nil means tags in levels apply also for sublevels.
3349 When nil, only the tags directly given in a specific line apply there.
3350 This may also be a list of tags that should be inherited, or a regexp that
3351 matches tags that should be inherited. Additional control is possible
3352 with the variable `org-tags-exclude-from-inheritance' which gives an
3353 explicit list of tags to be excluded from inheritance, even if the value of
3354 `org-use-tag-inheritance' would select it for inheritance.
3356 If this option is t, a match early-on in a tree can lead to a large
3357 number of matches in the subtree when constructing the agenda or creating
3358 a sparse tree. If you only want to see the first match in a tree during
3359 a search, check out the variable `org-tags-match-list-sublevels'."
3360 :group 'org-tags
3361 :type '(choice
3362 (const :tag "Not" nil)
3363 (const :tag "Always" t)
3364 (repeat :tag "Specific tags" (string :tag "Tag"))
3365 (regexp :tag "Tags matched by regexp")))
3367 (defcustom org-tags-exclude-from-inheritance nil
3368 "List of tags that should never be inherited.
3369 This is a way to exclude a few tags from inheritance. For way to do
3370 the opposite, to actively allow inheritance for selected tags,
3371 see the variable `org-use-tag-inheritance'."
3372 :group 'org-tags
3373 :type '(repeat (string :tag "Tag")))
3375 (defun org-tag-inherit-p (tag)
3376 "Check if TAG is one that should be inherited."
3377 (cond
3378 ((member tag org-tags-exclude-from-inheritance) nil)
3379 ((eq org-use-tag-inheritance t) t)
3380 ((not org-use-tag-inheritance) nil)
3381 ((stringp org-use-tag-inheritance)
3382 (string-match org-use-tag-inheritance tag))
3383 ((listp org-use-tag-inheritance)
3384 (member tag org-use-tag-inheritance))
3385 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3387 (defcustom org-tags-match-list-sublevels t
3388 "Non-nil means list also sublevels of headlines matching a search.
3389 This variable applies to tags/property searches, and also to stuck
3390 projects because this search is based on a tags match as well.
3392 When set to the symbol `indented', sublevels are indented with
3393 leading dots.
3395 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3396 the sublevels of a headline matching a tag search often also match
3397 the same search. Listing all of them can create very long lists.
3398 Setting this variable to nil causes subtrees of a match to be skipped.
3400 This variable is semi-obsolete and probably should always be true. It
3401 is better to limit inheritance to certain tags using the variables
3402 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3403 :group 'org-tags
3404 :type '(choice
3405 (const :tag "No, don't list them" nil)
3406 (const :tag "Yes, do list them" t)
3407 (const :tag "List them, indented with leading dots" indented)))
3409 (defcustom org-tags-sort-function nil
3410 "When set, tags are sorted using this function as a comparator."
3411 :group 'org-tags
3412 :type '(choice
3413 (const :tag "No sorting" nil)
3414 (const :tag "Alphabetical" string<)
3415 (const :tag "Reverse alphabetical" string>)
3416 (function :tag "Custom function" nil)))
3418 (defvar org-tags-history nil
3419 "History of minibuffer reads for tags.")
3420 (defvar org-last-tags-completion-table nil
3421 "The last used completion table for tags.")
3422 (defvar org-after-tags-change-hook nil
3423 "Hook that is run after the tags in a line have changed.")
3425 (defgroup org-properties nil
3426 "Options concerning properties in Org-mode."
3427 :tag "Org Properties"
3428 :group 'org)
3430 (defcustom org-property-format "%-10s %s"
3431 "How property key/value pairs should be formatted by `indent-line'.
3432 When `indent-line' hits a property definition, it will format the line
3433 according to this format, mainly to make sure that the values are
3434 lined-up with respect to each other."
3435 :group 'org-properties
3436 :type 'string)
3438 (defcustom org-properties-postprocess-alist nil
3439 "Alist of properties and functions to adjust inserted values.
3440 Elements of this alist must be of the form
3442 ([string] [function])
3444 where [string] must be a property name and [function] must be a
3445 lambda expression: this lambda expression must take one argument,
3446 the value to adjust, and return the new value as a string.
3448 For example, this element will allow the property \"Remaining\"
3449 to be updated wrt the relation between the \"Effort\" property
3450 and the clock summary:
3452 ((\"Remaining\" (lambda(value)
3453 (let ((clocksum (org-clock-sum-current-item))
3454 (effort (org-duration-string-to-minutes
3455 (org-entry-get (point) \"Effort\"))))
3456 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3457 :group 'org-properties
3458 :version "24.1"
3459 :type '(alist :key-type (string :tag "Property")
3460 :value-type (function :tag "Function")))
3462 (defcustom org-use-property-inheritance nil
3463 "Non-nil means properties apply also for sublevels.
3465 This setting is chiefly used during property searches. Turning it on can
3466 cause significant overhead when doing a search, which is why it is not
3467 on by default.
3469 When nil, only the properties directly given in the current entry count.
3470 When t, every property is inherited. The value may also be a list of
3471 properties that should have inheritance, or a regular expression matching
3472 properties that should be inherited.
3474 However, note that some special properties use inheritance under special
3475 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3476 and the properties ending in \"_ALL\" when they are used as descriptor
3477 for valid values of a property.
3479 Note for programmers:
3480 When querying an entry with `org-entry-get', you can control if inheritance
3481 should be used. By default, `org-entry-get' looks only at the local
3482 properties. You can request inheritance by setting the inherit argument
3483 to t (to force inheritance) or to `selective' (to respect the setting
3484 in this variable)."
3485 :group 'org-properties
3486 :type '(choice
3487 (const :tag "Not" nil)
3488 (const :tag "Always" t)
3489 (repeat :tag "Specific properties" (string :tag "Property"))
3490 (regexp :tag "Properties matched by regexp")))
3492 (defun org-property-inherit-p (property)
3493 "Check if PROPERTY is one that should be inherited."
3494 (cond
3495 ((eq org-use-property-inheritance t) t)
3496 ((not org-use-property-inheritance) nil)
3497 ((stringp org-use-property-inheritance)
3498 (string-match org-use-property-inheritance property))
3499 ((listp org-use-property-inheritance)
3500 (member property org-use-property-inheritance))
3501 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3503 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3504 "The default column format, if no other format has been defined.
3505 This variable can be set on the per-file basis by inserting a line
3507 #+COLUMNS: %25ITEM ....."
3508 :group 'org-properties
3509 :type 'string)
3511 (defcustom org-columns-ellipses ".."
3512 "The ellipses to be used when a field in column view is truncated.
3513 When this is the empty string, as many characters as possible are shown,
3514 but then there will be no visual indication that the field has been truncated.
3515 When this is a string of length N, the last N characters of a truncated
3516 field are replaced by this string. If the column is narrower than the
3517 ellipses string, only part of the ellipses string will be shown."
3518 :group 'org-properties
3519 :type 'string)
3521 (defcustom org-columns-modify-value-for-display-function nil
3522 "Function that modifies values for display in column view.
3523 For example, it can be used to cut out a certain part from a time stamp.
3524 The function must take 2 arguments:
3526 column-title The title of the column (*not* the property name)
3527 value The value that should be modified.
3529 The function should return the value that should be displayed,
3530 or nil if the normal value should be used."
3531 :group 'org-properties
3532 :type '(choice (const nil) (function)))
3534 (defcustom org-effort-property "Effort"
3535 "The property that is being used to keep track of effort estimates.
3536 Effort estimates given in this property need to have the format H:MM."
3537 :group 'org-properties
3538 :group 'org-progress
3539 :type '(string :tag "Property"))
3541 (defconst org-global-properties-fixed
3542 '(("VISIBILITY_ALL" . "folded children content all")
3543 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3544 "List of property/value pairs that can be inherited by any entry.
3546 These are fixed values, for the preset properties. The user variable
3547 that can be used to add to this list is `org-global-properties'.
3549 The entries in this list are cons cells where the car is a property
3550 name and cdr is a string with the value. If the value represents
3551 multiple items like an \"_ALL\" property, separate the items by
3552 spaces.")
3554 (defcustom org-global-properties nil
3555 "List of property/value pairs that can be inherited by any entry.
3557 This list will be combined with the constant `org-global-properties-fixed'.
3559 The entries in this list are cons cells where the car is a property
3560 name and cdr is a string with the value.
3562 You can set buffer-local values for the same purpose in the variable
3563 `org-file-properties' this by adding lines like
3565 #+PROPERTY: NAME VALUE"
3566 :group 'org-properties
3567 :type '(repeat
3568 (cons (string :tag "Property")
3569 (string :tag "Value"))))
3571 (defvar org-file-properties nil
3572 "List of property/value pairs that can be inherited by any entry.
3573 Valid for the current buffer.
3574 This variable is populated from #+PROPERTY lines.")
3575 (make-variable-buffer-local 'org-file-properties)
3577 (defgroup org-agenda nil
3578 "Options concerning agenda views in Org-mode."
3579 :tag "Org Agenda"
3580 :group 'org)
3582 (defvar org-category nil
3583 "Variable used by org files to set a category for agenda display.
3584 Such files should use a file variable to set it, for example
3586 # -*- mode: org; org-category: \"ELisp\"
3588 or contain a special line
3590 #+CATEGORY: ELisp
3592 If the file does not specify a category, then file's base name
3593 is used instead.")
3594 (make-variable-buffer-local 'org-category)
3595 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3597 (defcustom org-agenda-files nil
3598 "The files to be used for agenda display.
3599 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3600 \\[org-remove-file]. You can also use customize to edit the list.
3602 If an entry is a directory, all files in that directory that are matched by
3603 `org-agenda-file-regexp' will be part of the file list.
3605 If the value of the variable is not a list but a single file name, then
3606 the list of agenda files is actually stored and maintained in that file, one
3607 agenda file per line. In this file paths can be given relative to
3608 `org-directory'. Tilde expansion and environment variable substitution
3609 are also made."
3610 :group 'org-agenda
3611 :type '(choice
3612 (repeat :tag "List of files and directories" file)
3613 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3615 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3616 "Regular expression to match files for `org-agenda-files'.
3617 If any element in the list in that variable contains a directory instead
3618 of a normal file, all files in that directory that are matched by this
3619 regular expression will be included."
3620 :group 'org-agenda
3621 :type 'regexp)
3623 (defcustom org-agenda-text-search-extra-files nil
3624 "List of extra files to be searched by text search commands.
3625 These files will be searched in addition to the agenda files by the
3626 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3627 Note that these files will only be searched for text search commands,
3628 not for the other agenda views like todo lists, tag searches or the weekly
3629 agenda. This variable is intended to list notes and possibly archive files
3630 that should also be searched by these two commands.
3631 In fact, if the first element in the list is the symbol `agenda-archives',
3632 then all archive files of all agenda files will be added to the search
3633 scope."
3634 :group 'org-agenda
3635 :type '(set :greedy t
3636 (const :tag "Agenda Archives" agenda-archives)
3637 (repeat :inline t (file))))
3639 (org-defvaralias 'org-agenda-multi-occur-extra-files
3640 'org-agenda-text-search-extra-files)
3642 (defcustom org-agenda-skip-unavailable-files nil
3643 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3644 A nil value means to remove them, after a query, from the list."
3645 :group 'org-agenda
3646 :type 'boolean)
3648 (defcustom org-calendar-to-agenda-key [?c]
3649 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3650 The command `org-calendar-goto-agenda' will be bound to this key. The
3651 default is the character `c' because then `c' can be used to switch back and
3652 forth between agenda and calendar."
3653 :group 'org-agenda
3654 :type 'sexp)
3656 (defcustom org-calendar-insert-diary-entry-key [?i]
3657 "The key to be installed in `calendar-mode-map' for adding diary entries.
3658 This option is irrelevant until `org-agenda-diary-file' has been configured
3659 to point to an Org-mode file. When that is the case, the command
3660 `org-agenda-diary-entry' will be bound to the key given here, by default
3661 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3662 if you want to continue doing this, you need to change this to a different
3663 key."
3664 :group 'org-agenda
3665 :type 'sexp)
3667 (defcustom org-agenda-diary-file 'diary-file
3668 "File to which to add new entries with the `i' key in agenda and calendar.
3669 When this is the symbol `diary-file', the functionality in the Emacs
3670 calendar will be used to add entries to the `diary-file'. But when this
3671 points to a file, `org-agenda-diary-entry' will be used instead."
3672 :group 'org-agenda
3673 :type '(choice
3674 (const :tag "The standard Emacs diary file" diary-file)
3675 (file :tag "Special Org file diary entries")))
3677 (eval-after-load "calendar"
3678 '(progn
3679 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3680 'org-calendar-goto-agenda)
3681 (add-hook 'calendar-mode-hook
3682 (lambda ()
3683 (unless (eq org-agenda-diary-file 'diary-file)
3684 (define-key calendar-mode-map
3685 org-calendar-insert-diary-entry-key
3686 'org-agenda-diary-entry))))))
3688 (defgroup org-latex nil
3689 "Options for embedding LaTeX code into Org-mode."
3690 :tag "Org LaTeX"
3691 :group 'org)
3693 (defcustom org-format-latex-options
3694 '(:foreground default :background default :scale 1.0
3695 :html-foreground "Black" :html-background "Transparent"
3696 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3697 "Options for creating images from LaTeX fragments.
3698 This is a property list with the following properties:
3699 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3700 `default' means use the foreground of the default face.
3701 `auto' means use the foreground from the text face.
3702 :background the background color, or \"Transparent\".
3703 `default' means use the background of the default face.
3704 `auto' means use the background from the text face.
3705 :scale a scaling factor for the size of the images, to get more pixels
3706 :html-foreground, :html-background, :html-scale
3707 the same numbers for HTML export.
3708 :matchers a list indicating which matchers should be used to
3709 find LaTeX fragments. Valid members of this list are:
3710 \"begin\" find environments
3711 \"$1\" find single characters surrounded by $.$
3712 \"$\" find math expressions surrounded by $...$
3713 \"$$\" find math expressions surrounded by $$....$$
3714 \"\\(\" find math expressions surrounded by \\(...\\)
3715 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3716 :group 'org-latex
3717 :type 'plist)
3719 (defcustom org-format-latex-signal-error t
3720 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3721 When nil, just push out a message."
3722 :group 'org-latex
3723 :version "24.1"
3724 :type 'boolean)
3726 (defcustom org-latex-to-mathml-jar-file nil
3727 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3728 Use this to specify additional executable file say a jar file.
3730 When using MathToWeb as the converter, specify the full-path to
3731 your mathtoweb.jar file."
3732 :group 'org-latex
3733 :version "24.1"
3734 :type '(choice
3735 (const :tag "None" nil)
3736 (file :tag "JAR file" :must-match t)))
3738 (defcustom org-latex-to-mathml-convert-command nil
3739 "Command to convert LaTeX fragments to MathML.
3740 Replace format-specifiers in the command as noted below and use
3741 `shell-command' to convert LaTeX to MathML.
3742 %j: Executable file in fully expanded form as specified by
3743 `org-latex-to-mathml-jar-file'.
3744 %I: Input LaTeX file in fully expanded form
3745 %o: Output MathML file
3746 This command is used by `org-create-math-formula'.
3748 When using MathToWeb as the converter, set this to
3749 \"java -jar %j -unicode -force -df %o %I\"."
3750 :group 'org-latex
3751 :version "24.1"
3752 :type '(choice
3753 (const :tag "None" nil)
3754 (string :tag "\nShell command")))
3756 (defcustom org-latex-create-formula-image-program 'dvipng
3757 "Program to convert LaTeX fragments with.
3759 dvipng Process the LaTeX fragments to dvi file, then convert
3760 dvi files to png files using dvipng.
3761 This will also include processing of non-math environments.
3762 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3763 to convert pdf files to png files"
3764 :group 'org-latex
3765 :version "24.1"
3766 :type '(choice
3767 (const :tag "dvipng" dvipng)
3768 (const :tag "imagemagick" imagemagick)))
3770 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3771 "Path to store latex preview images.
3772 A relative path here creates many directories relative to the
3773 processed org files paths. An absolute path puts all preview
3774 images at the same place."
3775 :group 'org-latex
3776 :version "24.3"
3777 :type 'string)
3779 (defun org-format-latex-mathml-available-p ()
3780 "Return t if `org-latex-to-mathml-convert-command' is usable."
3781 (save-match-data
3782 (when (and (boundp 'org-latex-to-mathml-convert-command)
3783 org-latex-to-mathml-convert-command)
3784 (let ((executable (car (split-string
3785 org-latex-to-mathml-convert-command))))
3786 (when (executable-find executable)
3787 (if (string-match
3788 "%j" org-latex-to-mathml-convert-command)
3789 (file-readable-p org-latex-to-mathml-jar-file)
3790 t))))))
3792 (defcustom org-format-latex-header "\\documentclass{article}
3793 \\usepackage[usenames]{color}
3794 \[PACKAGES]
3795 \[DEFAULT-PACKAGES]
3796 \\pagestyle{empty} % do not remove
3797 % The settings below are copied from fullpage.sty
3798 \\setlength{\\textwidth}{\\paperwidth}
3799 \\addtolength{\\textwidth}{-3cm}
3800 \\setlength{\\oddsidemargin}{1.5cm}
3801 \\addtolength{\\oddsidemargin}{-2.54cm}
3802 \\setlength{\\evensidemargin}{\\oddsidemargin}
3803 \\setlength{\\textheight}{\\paperheight}
3804 \\addtolength{\\textheight}{-\\headheight}
3805 \\addtolength{\\textheight}{-\\headsep}
3806 \\addtolength{\\textheight}{-\\footskip}
3807 \\addtolength{\\textheight}{-3cm}
3808 \\setlength{\\topmargin}{1.5cm}
3809 \\addtolength{\\topmargin}{-2.54cm}"
3810 "The document header used for processing LaTeX fragments.
3811 It is imperative that this header make sure that no page number
3812 appears on the page. The package defined in the variables
3813 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3814 will either replace the placeholder \"[PACKAGES]\" in this
3815 header, or they will be appended."
3816 :group 'org-latex
3817 :type 'string)
3819 (defun org-set-packages-alist (var val)
3820 "Set the packages alist and make sure it has 3 elements per entry."
3821 (set var (mapcar (lambda (x)
3822 (if (and (consp x) (= (length x) 2))
3823 (list (car x) (nth 1 x) t)
3825 val)))
3827 (defun org-get-packages-alist (var)
3828 "Get the packages alist and make sure it has 3 elements per entry."
3829 (mapcar (lambda (x)
3830 (if (and (consp x) (= (length x) 2))
3831 (list (car x) (nth 1 x) t)
3833 (default-value var)))
3835 (defcustom org-latex-default-packages-alist
3836 '(("AUTO" "inputenc" t)
3837 ("T1" "fontenc" t)
3838 ("" "fixltx2e" nil)
3839 ("" "graphicx" t)
3840 ("" "longtable" nil)
3841 ("" "float" nil)
3842 ("" "wrapfig" nil)
3843 ("" "rotating" nil)
3844 ("normalem" "ulem" t)
3845 ("" "amsmath" t)
3846 ("" "textcomp" t)
3847 ("" "marvosym" t)
3848 ("" "wasysym" t)
3849 ("" "amssymb" t)
3850 ("" "hyperref" nil)
3851 "\\tolerance=1000")
3852 "Alist of default packages to be inserted in the header.
3854 Change this only if one of the packages here causes an
3855 incompatibility with another package you are using.
3857 The packages in this list are needed by one part or another of
3858 Org mode to function properly:
3860 - inputenc, fontenc: for basic font and character selection
3861 - fixltx2e: Important patches of LaTeX itself
3862 - graphicx: for including images
3863 - longtable: For multipage tables
3864 - float, wrapfig: for figure placement
3865 - rotating: for sideways figures and tables
3866 - ulem: for underline and strike-through
3867 - amsmath: for subscript and superscript and math environments
3868 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3869 for interpreting the entities in `org-entities'. You can skip
3870 some of these packages if you don't use any of their symbols.
3871 - hyperref: for cross references
3873 Therefore you should not modify this variable unless you know
3874 what you are doing. The one reason to change it anyway is that
3875 you might be loading some other package that conflicts with one
3876 of the default packages. Each cell is of the format
3877 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3878 the package also needs to be included when compiling LaTeX
3879 snippets into images for inclusion into non-LaTeX output."
3880 :group 'org-latex
3881 :group 'org-export-latex
3882 :set 'org-set-packages-alist
3883 :get 'org-get-packages-alist
3884 :version "24.1"
3885 :type '(repeat
3886 (choice
3887 (list :tag "options/package pair"
3888 (string :tag "options")
3889 (string :tag "package")
3890 (boolean :tag "Snippet"))
3891 (string :tag "A line of LaTeX"))))
3893 (defcustom org-latex-packages-alist nil
3894 "Alist of packages to be inserted in every LaTeX header.
3896 These will be inserted after `org-latex-default-packages-alist'.
3897 Each cell is of the format:
3899 \(\"options\" \"package\" snippet-flag)
3901 SNIPPET-FLAG, when t, indicates that this package is also needed
3902 when turning LaTeX snippets into images for inclusion into
3903 non-LaTeX output.
3905 Make sure that you only list packages here which:
3907 - you want in every file
3908 - do not conflict with the setup in `org-format-latex-header'.
3909 - do not conflict with the default packages in
3910 `org-latex-default-packages-alist'."
3911 :group 'org-latex
3912 :group 'org-export-latex
3913 :set 'org-set-packages-alist
3914 :get 'org-get-packages-alist
3915 :type '(repeat
3916 (choice
3917 (list :tag "options/package pair"
3918 (string :tag "options")
3919 (string :tag "package")
3920 (boolean :tag "Snippet"))
3921 (string :tag "A line of LaTeX"))))
3923 (defgroup org-appearance nil
3924 "Settings for Org-mode appearance."
3925 :tag "Org Appearance"
3926 :group 'org)
3928 (defcustom org-level-color-stars-only nil
3929 "Non-nil means fontify only the stars in each headline.
3930 When nil, the entire headline is fontified.
3931 Changing it requires restart of `font-lock-mode' to become effective
3932 also in regions already fontified."
3933 :group 'org-appearance
3934 :type 'boolean)
3936 (defcustom org-hide-leading-stars nil
3937 "Non-nil means hide the first N-1 stars in a headline.
3938 This works by using the face `org-hide' for these stars. This
3939 face is white for a light background, and black for a dark
3940 background. You may have to customize the face `org-hide' to
3941 make this work.
3942 Changing it requires restart of `font-lock-mode' to become effective
3943 also in regions already fontified.
3944 You may also set this on a per-file basis by adding one of the following
3945 lines to the buffer:
3947 #+STARTUP: hidestars
3948 #+STARTUP: showstars"
3949 :group 'org-appearance
3950 :type 'boolean)
3952 (defcustom org-hidden-keywords nil
3953 "List of symbols corresponding to keywords to be hidden the org buffer.
3954 For example, a value '(title) for this list will make the document's title
3955 appear in the buffer without the initial #+TITLE: keyword."
3956 :group 'org-appearance
3957 :version "24.1"
3958 :type '(set (const :tag "#+AUTHOR" author)
3959 (const :tag "#+DATE" date)
3960 (const :tag "#+EMAIL" email)
3961 (const :tag "#+TITLE" title)))
3963 (defcustom org-custom-properties nil
3964 "List of properties (as strings) with a special meaning.
3965 The default use of these custom properties is to let the user
3966 hide them with `org-toggle-custom-properties-visibility'."
3967 :group 'org-properties
3968 :group 'org-appearance
3969 :version "24.3"
3970 :type '(repeat (string :tag "Property Name")))
3972 (defcustom org-fontify-done-headline nil
3973 "Non-nil means change the face of a headline if it is marked DONE.
3974 Normally, only the TODO/DONE keyword indicates the state of a headline.
3975 When this is non-nil, the headline after the keyword is set to the
3976 `org-headline-done' as an additional indication."
3977 :group 'org-appearance
3978 :type 'boolean)
3980 (defcustom org-fontify-emphasized-text t
3981 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3982 Changing this variable requires a restart of Emacs to take effect."
3983 :group 'org-appearance
3984 :type 'boolean)
3986 (defcustom org-fontify-whole-heading-line nil
3987 "Non-nil means fontify the whole line for headings.
3988 This is useful when setting a background color for the
3989 org-level-* faces."
3990 :group 'org-appearance
3991 :type 'boolean)
3993 (defcustom org-highlight-latex-and-related nil
3994 "Non-nil means highlight LaTeX related syntax in the buffer.
3995 When non nil, the value should be a list containing any of the
3996 following symbols:
3997 `latex' Highlight LaTeX snippets and environments.
3998 `script' Highlight subscript and superscript.
3999 `entities' Highlight entities."
4000 :group 'org-appearance
4001 :version "24.4"
4002 :package-version '(Org . "8.0")
4003 :type '(choice
4004 (const :tag "No highlighting" nil)
4005 (set :greedy t :tag "Highlight"
4006 (const :tag "LaTeX snippets and environments" latex)
4007 (const :tag "Subscript and superscript" script)
4008 (const :tag "Entities" entities))))
4010 (defcustom org-hide-emphasis-markers nil
4011 "Non-nil mean font-lock should hide the emphasis marker characters."
4012 :group 'org-appearance
4013 :type 'boolean)
4015 (defcustom org-pretty-entities nil
4016 "Non-nil means show entities as UTF8 characters.
4017 When nil, the \\name form remains in the buffer."
4018 :group 'org-appearance
4019 :version "24.1"
4020 :type 'boolean)
4022 (defcustom org-pretty-entities-include-sub-superscripts t
4023 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4024 :group 'org-appearance
4025 :version "24.1"
4026 :type 'boolean)
4028 (defvar org-emph-re nil
4029 "Regular expression for matching emphasis.
4030 After a match, the match groups contain these elements:
4031 0 The match of the full regular expression, including the characters
4032 before and after the proper match
4033 1 The character before the proper match, or empty at beginning of line
4034 2 The proper match, including the leading and trailing markers
4035 3 The leading marker like * or /, indicating the type of highlighting
4036 4 The text between the emphasis markers, not including the markers
4037 5 The character after the match, empty at the end of a line")
4038 (defvar org-verbatim-re nil
4039 "Regular expression for matching verbatim text.")
4040 (defvar org-emphasis-regexp-components) ; defined just below
4041 (defvar org-emphasis-alist) ; defined just below
4042 (defun org-set-emph-re (var val)
4043 "Set variable and compute the emphasis regular expression."
4044 (set var val)
4045 (when (and (boundp 'org-emphasis-alist)
4046 (boundp 'org-emphasis-regexp-components)
4047 org-emphasis-alist org-emphasis-regexp-components)
4048 (let* ((e org-emphasis-regexp-components)
4049 (pre (car e))
4050 (post (nth 1 e))
4051 (border (nth 2 e))
4052 (body (nth 3 e))
4053 (nl (nth 4 e))
4054 (body1 (concat body "*?"))
4055 (markers (mapconcat 'car org-emphasis-alist ""))
4056 (vmarkers (mapconcat
4057 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4058 org-emphasis-alist "")))
4059 ;; make sure special characters appear at the right position in the class
4060 (if (string-match "\\^" markers)
4061 (setq markers (concat (replace-match "" t t markers) "^")))
4062 (if (string-match "-" markers)
4063 (setq markers (concat (replace-match "" t t markers) "-")))
4064 (if (string-match "\\^" vmarkers)
4065 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4066 (if (string-match "-" vmarkers)
4067 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4068 (if (> nl 0)
4069 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4070 (int-to-string nl) "\\}")))
4071 ;; Make the regexp
4072 (setq org-emph-re
4073 (concat "\\([" pre "]\\|^\\)"
4074 "\\("
4075 "\\([" markers "]\\)"
4076 "\\("
4077 "[^" border "]\\|"
4078 "[^" border "]"
4079 body1
4080 "[^" border "]"
4081 "\\)"
4082 "\\3\\)"
4083 "\\([" post "]\\|$\\)"))
4084 (setq org-verbatim-re
4085 (concat "\\([" pre "]\\|^\\)"
4086 "\\("
4087 "\\([" vmarkers "]\\)"
4088 "\\("
4089 "[^" border "]\\|"
4090 "[^" border "]"
4091 body1
4092 "[^" border "]"
4093 "\\)"
4094 "\\3\\)"
4095 "\\([" post "]\\|$\\)")))))
4097 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4098 ;; set this option proved cumbersome. See this message/thread:
4099 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4100 (defvar org-emphasis-regexp-components
4101 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4102 "Components used to build the regular expression for emphasis.
4103 This is a list with five entries. Terminology: In an emphasis string
4104 like \" *strong word* \", we call the initial space PREMATCH, the final
4105 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4106 and \"trong wor\" is the body. The different components in this variable
4107 specify what is allowed/forbidden in each part:
4109 pre Chars allowed as prematch. Beginning of line will be allowed too.
4110 post Chars allowed as postmatch. End of line will be allowed too.
4111 border The chars *forbidden* as border characters.
4112 body-regexp A regexp like \".\" to match a body character. Don't use
4113 non-shy groups here, and don't allow newline here.
4114 newline The maximum number of newlines allowed in an emphasis exp.
4116 You need to reload Org or to restart Emacs after customizing this.")
4118 (defcustom org-emphasis-alist
4119 `(("*" bold)
4120 ("/" italic)
4121 ("_" underline)
4122 ("=" org-code verbatim)
4123 ("~" org-verbatim verbatim)
4124 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4125 "Alist of characters and faces to emphasize text.
4126 Text starting and ending with a special character will be emphasized,
4127 for example *bold*, _underlined_ and /italic/. This variable sets the
4128 marker characters and the face to be used by font-lock for highlighting
4129 in Org-mode Emacs buffers.
4131 You need to reload Org or to restart Emacs after customizing this."
4132 :group 'org-appearance
4133 :set 'org-set-emph-re
4134 :version "24.4"
4135 :package-version '(Org . "8.0")
4136 :type '(repeat
4137 (list
4138 (string :tag "Marker character")
4139 (choice
4140 (face :tag "Font-lock-face")
4141 (plist :tag "Face property list"))
4142 (option (const verbatim)))))
4144 (defvar org-protecting-blocks
4145 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4146 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4147 This is needed for font-lock setup.")
4149 ;;; Miscellaneous options
4151 (defgroup org-completion nil
4152 "Completion in Org-mode."
4153 :tag "Org Completion"
4154 :group 'org)
4156 (defcustom org-completion-use-ido nil
4157 "Non-nil means use ido completion wherever possible.
4158 Note that `ido-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 See also `org-completion-use-iswitchb'."
4162 :group 'org-completion
4163 :type 'boolean)
4165 (defcustom org-completion-use-iswitchb nil
4166 "Non-nil means use iswitchb completion wherever possible.
4167 Note that `iswitchb-mode' must be active for this variable to be relevant.
4168 If you decide to turn this variable on, you might well want to turn off
4169 `org-outline-path-complete-in-steps'.
4170 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4171 :group 'org-completion
4172 :type 'boolean)
4174 (defcustom org-completion-fallback-command 'hippie-expand
4175 "The expansion command called by \\[pcomplete] in normal context.
4176 Normal means, no org-mode-specific context."
4177 :group 'org-completion
4178 :type 'function)
4180 ;;; Functions and variables from their packages
4181 ;; Declared here to avoid compiler warnings
4183 ;; XEmacs only
4184 (defvar outline-mode-menu-heading)
4185 (defvar outline-mode-menu-show)
4186 (defvar outline-mode-menu-hide)
4187 (defvar zmacs-regions) ; XEmacs regions
4189 ;; Emacs only
4190 (defvar mark-active)
4192 ;; Various packages
4193 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4194 (declare-function calendar-forward-day "cal-move" (arg))
4195 (declare-function calendar-goto-date "cal-move" (date))
4196 (declare-function calendar-goto-today "cal-move" ())
4197 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4198 (defvar calc-embedded-close-formula)
4199 (defvar calc-embedded-open-formula)
4200 (declare-function cdlatex-tab "ext:cdlatex" ())
4201 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4202 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4203 (defvar font-lock-unfontify-region-function)
4204 (declare-function iswitchb-read-buffer "iswitchb"
4205 (prompt &optional default require-match start matches-set))
4206 (defvar iswitchb-temp-buflist)
4207 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4208 (defvar org-agenda-tags-todo-honor-ignore-options)
4209 (declare-function org-agenda-skip "org-agenda" ())
4210 (declare-function
4211 org-agenda-format-item "org-agenda"
4212 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4213 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4214 (declare-function org-agenda-change-all-lines "org-agenda"
4215 (newhead hdmarker &optional fixface just-this))
4216 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4217 (declare-function org-agenda-maybe-redo "org-agenda" ())
4218 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4219 (beg end))
4220 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4221 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4222 "org-agenda" (&optional end))
4223 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4224 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4225 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4226 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4227 (declare-function org-indent-mode "org-indent" (&optional arg))
4228 (declare-function parse-time-string "parse-time" (string))
4229 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4230 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4231 (defvar remember-data-file)
4232 (defvar texmathp-why)
4233 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4234 (declare-function table--at-cell-p "table" (position &optional object at-column))
4236 (defvar org-latex-regexps)
4238 ;;; Autoload and prepare some org modules
4240 ;; Some table stuff that needs to be defined here, because it is used
4241 ;; by the functions setting up org-mode or checking for table context.
4243 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4244 "Detect an org-type or table-type table.")
4245 (defconst org-table-line-regexp "^[ \t]*|"
4246 "Detect an org-type table line.")
4247 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4248 "Detect an org-type table line.")
4249 (defconst org-table-hline-regexp "^[ \t]*|-"
4250 "Detect an org-type table hline.")
4251 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4252 "Detect a table-type table hline.")
4253 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4254 "Detect the first line outside a table when searching from within it.
4255 This works for both table types.")
4257 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4258 "Detect a #+TBLFM line.")
4260 ;;;###autoload
4261 (defun turn-on-orgtbl ()
4262 "Unconditionally turn on `orgtbl-mode'."
4263 (require 'org-table)
4264 (orgtbl-mode 1))
4266 (defun org-at-table-p (&optional table-type)
4267 "Return t if the cursor is inside an org-type table.
4268 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4269 (if org-enable-table-editor
4270 (save-excursion
4271 (beginning-of-line 1)
4272 (looking-at (if table-type org-table-any-line-regexp
4273 org-table-line-regexp)))
4274 nil))
4275 (defsubst org-table-p () (org-at-table-p))
4277 (defun org-at-table.el-p ()
4278 "Return t if and only if we are at a table.el table."
4279 (and (org-at-table-p 'any)
4280 (save-excursion
4281 (goto-char (org-table-begin 'any))
4282 (looking-at org-table1-hline-regexp))))
4284 (defun org-table-recognize-table.el ()
4285 "If there is a table.el table nearby, recognize it and move into it."
4286 (if org-table-tab-recognizes-table.el
4287 (if (org-at-table.el-p)
4288 (progn
4289 (beginning-of-line 1)
4290 (if (looking-at org-table-dataline-regexp)
4292 (if (looking-at org-table1-hline-regexp)
4293 (progn
4294 (beginning-of-line 2)
4295 (if (looking-at org-table-any-border-regexp)
4296 (beginning-of-line -1)))))
4297 (if (re-search-forward "|" (org-table-end t) t)
4298 (progn
4299 (require 'table)
4300 (if (table--at-cell-p (point))
4302 (message "recognizing table.el table...")
4303 (table-recognize-table)
4304 (message "recognizing table.el table...done")))
4305 (error "This should not happen"))
4307 nil)
4308 nil))
4310 (defun org-at-table-hline-p ()
4311 "Return t if the cursor is inside a hline in a table."
4312 (if org-enable-table-editor
4313 (save-excursion
4314 (beginning-of-line 1)
4315 (looking-at org-table-hline-regexp))
4316 nil))
4318 (defun org-table-map-tables (function &optional quietly)
4319 "Apply FUNCTION to the start of all tables in the buffer."
4320 (save-excursion
4321 (save-restriction
4322 (widen)
4323 (goto-char (point-min))
4324 (while (re-search-forward org-table-any-line-regexp nil t)
4325 (unless quietly
4326 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4327 (beginning-of-line 1)
4328 (when (and (looking-at org-table-line-regexp)
4329 ;; Exclude tables in src/example/verbatim/clocktable blocks
4330 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4331 (save-excursion (funcall function))
4332 (or (looking-at org-table-line-regexp)
4333 (forward-char 1)))
4334 (re-search-forward org-table-any-border-regexp nil 1))))
4335 (unless quietly (message "Mapping tables: done")))
4337 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4338 (declare-function org-clock-update-mode-line "org-clock" ())
4339 (declare-function org-resolve-clocks "org-clock"
4340 (&optional also-non-dangling-p prompt last-valid))
4342 (defun org-at-TBLFM-p (&optional pos)
4343 "Return t when point (or POS) is in #+TBLFM line."
4344 (save-excursion
4345 (let ((pos pos)))
4346 (goto-char (or pos (point)))
4347 (beginning-of-line 1)
4348 (looking-at org-TBLFM-regexp)))
4350 (defvar org-clock-start-time)
4351 (defvar org-clock-marker (make-marker)
4352 "Marker recording the last clock-in.")
4353 (defvar org-clock-hd-marker (make-marker)
4354 "Marker recording the last clock-in, but the headline position.")
4355 (defvar org-clock-heading ""
4356 "The heading of the current clock entry.")
4357 (defun org-clock-is-active ()
4358 "Return the buffer where the clock is currently running.
4359 Return nil if no clock is running."
4360 (marker-buffer org-clock-marker))
4362 (defun org-check-running-clock ()
4363 "Check if the current buffer contains the running clock.
4364 If yes, offer to stop it and to save the buffer with the changes."
4365 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4366 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4367 (buffer-name))))
4368 (org-clock-out)
4369 (when (y-or-n-p "Save changed buffer?")
4370 (save-buffer))))
4372 (defun org-clocktable-try-shift (dir n)
4373 "Check if this line starts a clock table, if yes, shift the time block."
4374 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4375 (org-clocktable-shift dir n)))
4377 ;;;###autoload
4378 (defun org-clock-persistence-insinuate ()
4379 "Set up hooks for clock persistence."
4380 (require 'org-clock)
4381 (add-hook 'org-mode-hook 'org-clock-load)
4382 (add-hook 'kill-emacs-hook 'org-clock-save))
4384 ;; Define the variable already here, to make sure we have it.
4385 (defvar org-indent-mode nil
4386 "Non-nil if Org-Indent mode is enabled.
4387 Use the command `org-indent-mode' to change this variable.")
4389 ;; Autoload archiving code
4390 ;; The stuff that is needed for cycling and tags has to be defined here.
4392 (defgroup org-archive nil
4393 "Options concerning archiving in Org-mode."
4394 :tag "Org Archive"
4395 :group 'org-structure)
4397 (defcustom org-archive-location "%s_archive::"
4398 "The location where subtrees should be archived.
4400 The value of this variable is a string, consisting of two parts,
4401 separated by a double-colon. The first part is a filename and
4402 the second part is a headline.
4404 When the filename is omitted, archiving happens in the same file.
4405 %s in the filename will be replaced by the current file
4406 name (without the directory part). Archiving to a different file
4407 is useful to keep archived entries from contributing to the
4408 Org-mode Agenda.
4410 The archived entries will be filed as subtrees of the specified
4411 headline. When the headline is omitted, the subtrees are simply
4412 filed away at the end of the file, as top-level entries. Also in
4413 the heading you can use %s to represent the file name, this can be
4414 useful when using the same archive for a number of different files.
4416 Here are a few examples:
4417 \"%s_archive::\"
4418 If the current file is Projects.org, archive in file
4419 Projects.org_archive, as top-level trees. This is the default.
4421 \"::* Archived Tasks\"
4422 Archive in the current file, under the top-level headline
4423 \"* Archived Tasks\".
4425 \"~/org/archive.org::\"
4426 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4428 \"~/org/archive.org::* From %s\"
4429 Archive in file ~/org/archive.org (absolute path), under headlines
4430 \"From FILENAME\" where file name is the current file name.
4432 \"~/org/datetree.org::datetree/* Finished Tasks\"
4433 The \"datetree/\" string is special, signifying to archive
4434 items to the datetree. Items are placed in either the CLOSED
4435 date of the item, or the current date if there is no CLOSED date.
4436 The heading will be a subentry to the current date. There doesn't
4437 need to be a heading, but there always needs to be a slash after
4438 datetree. For example, to store archived items directly in the
4439 datetree, use \"~/org/datetree.org::datetree/\".
4441 \"basement::** Finished Tasks\"
4442 Archive in file ./basement (relative path), as level 3 trees
4443 below the level 2 heading \"** Finished Tasks\".
4445 You may set this option on a per-file basis by adding to the buffer a
4446 line like
4448 #+ARCHIVE: basement::** Finished Tasks
4450 You may also define it locally for a subtree by setting an ARCHIVE property
4451 in the entry. If such a property is found in an entry, or anywhere up
4452 the hierarchy, it will be used."
4453 :group 'org-archive
4454 :type 'string)
4456 (defcustom org-archive-tag "ARCHIVE"
4457 "The tag that marks a subtree as archived.
4458 An archived subtree does not open during visibility cycling, and does
4459 not contribute to the agenda listings.
4460 After changing this, font-lock must be restarted in the relevant buffers to
4461 get the proper fontification."
4462 :group 'org-archive
4463 :group 'org-keywords
4464 :type 'string)
4466 (defcustom org-agenda-skip-archived-trees t
4467 "Non-nil means the agenda will skip any items located in archived trees.
4468 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4469 variable is no longer recommended, you should leave it at the value t.
4470 Instead, use the key `v' to cycle the archives-mode in the agenda."
4471 :group 'org-archive
4472 :group 'org-agenda-skip
4473 :type 'boolean)
4475 (defcustom org-columns-skip-archived-trees t
4476 "Non-nil means ignore archived trees when creating column view."
4477 :group 'org-archive
4478 :group 'org-properties
4479 :type 'boolean)
4481 (defcustom org-cycle-open-archived-trees nil
4482 "Non-nil means `org-cycle' will open archived trees.
4483 An archived tree is a tree marked with the tag ARCHIVE.
4484 When nil, archived trees will stay folded. You can still open them with
4485 normal outline commands like `show-all', but not with the cycling commands."
4486 :group 'org-archive
4487 :group 'org-cycle
4488 :type 'boolean)
4490 (defcustom org-sparse-tree-open-archived-trees nil
4491 "Non-nil means sparse tree construction shows matches in archived trees.
4492 When nil, matches in these trees are highlighted, but the trees are kept in
4493 collapsed state."
4494 :group 'org-archive
4495 :group 'org-sparse-trees
4496 :type 'boolean)
4498 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4499 "The default date type when building a sparse tree.
4500 When this is nil, a date is a scheduled or a deadline timestamp.
4501 Otherwise, these types are allowed:
4503 all: all timestamps
4504 active: only active timestamps (<...>)
4505 inactive: only inactive timestamps (<...)
4506 scheduled: only scheduled timestamps
4507 deadline: only deadline timestamps"
4508 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4509 (const :tag "All timestamps" all)
4510 (const :tag "Only active timestamps" active)
4511 (const :tag "Only inactive timestamps" inactive)
4512 (const :tag "Only scheduled timestamps" scheduled)
4513 (const :tag "Only deadline timestamps" deadline)
4514 (const :tag "Only closed timestamps" closed))
4515 :version "24.3"
4516 :group 'org-sparse-trees)
4518 (defun org-cycle-hide-archived-subtrees (state)
4519 "Re-hide all archived subtrees after a visibility state change."
4520 (when (and (not org-cycle-open-archived-trees)
4521 (not (memq state '(overview folded))))
4522 (save-excursion
4523 (let* ((globalp (memq state '(contents all)))
4524 (beg (if globalp (point-min) (point)))
4525 (end (if globalp (point-max) (org-end-of-subtree t))))
4526 (org-hide-archived-subtrees beg end)
4527 (goto-char beg)
4528 (if (looking-at (concat ".*:" org-archive-tag ":"))
4529 (message "%s" (substitute-command-keys
4530 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4532 (defun org-force-cycle-archived ()
4533 "Cycle subtree even if it is archived."
4534 (interactive)
4535 (setq this-command 'org-cycle)
4536 (let ((org-cycle-open-archived-trees t))
4537 (call-interactively 'org-cycle)))
4539 (defun org-hide-archived-subtrees (beg end)
4540 "Re-hide all archived subtrees after a visibility state change."
4541 (save-excursion
4542 (let* ((re (concat ":" org-archive-tag ":")))
4543 (goto-char beg)
4544 (while (re-search-forward re end t)
4545 (when (org-at-heading-p)
4546 (org-flag-subtree t)
4547 (org-end-of-subtree t))))))
4549 (declare-function outline-end-of-heading "outline" ())
4550 (declare-function outline-flag-region "outline" (from to flag))
4551 (defun org-flag-subtree (flag)
4552 (save-excursion
4553 (org-back-to-heading t)
4554 (outline-end-of-heading)
4555 (outline-flag-region (point)
4556 (progn (org-end-of-subtree t) (point))
4557 flag)))
4559 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4561 ;; Declare Column View Code
4563 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4564 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4565 (declare-function org-columns-compute "org-colview" (property))
4567 ;; Declare ID code
4569 (declare-function org-id-store-link "org-id")
4570 (declare-function org-id-locations-load "org-id")
4571 (declare-function org-id-locations-save "org-id")
4572 (defvar org-id-track-globally)
4574 ;;; Variables for pre-computed regular expressions, all buffer local
4576 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4577 "Matches first line of a hidden block.")
4578 (make-variable-buffer-local 'org-drawer-regexp)
4579 (defvar org-todo-regexp nil
4580 "Matches any of the TODO state keywords.")
4581 (make-variable-buffer-local 'org-todo-regexp)
4582 (defvar org-not-done-regexp nil
4583 "Matches any of the TODO state keywords except the last one.")
4584 (make-variable-buffer-local 'org-not-done-regexp)
4585 (defvar org-not-done-heading-regexp nil
4586 "Matches a TODO headline that is not done.")
4587 (make-variable-buffer-local 'org-not-done-regexp)
4588 (defvar org-todo-line-regexp nil
4589 "Matches a headline and puts TODO state into group 2 if present.")
4590 (make-variable-buffer-local 'org-todo-line-regexp)
4591 (defvar org-complex-heading-regexp nil
4592 "Matches a headline and puts everything into groups:
4593 group 1: the stars
4594 group 2: The todo keyword, maybe
4595 group 3: Priority cookie
4596 group 4: True headline
4597 group 5: Tags")
4598 (make-variable-buffer-local 'org-complex-heading-regexp)
4599 (defvar org-complex-heading-regexp-format nil
4600 "Printf format to make regexp to match an exact headline.
4601 This regexp will match the headline of any node which has the
4602 exact headline text that is put into the format, but may have any
4603 TODO state, priority and tags.")
4604 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4605 (defvar org-todo-line-tags-regexp nil
4606 "Matches a headline and puts TODO state into group 2 if present.
4607 Also put tags into group 4 if tags are present.")
4608 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4609 (defvar org-ds-keyword-length 12
4610 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4611 (make-variable-buffer-local 'org-ds-keyword-length)
4612 (defvar org-deadline-regexp nil
4613 "Matches the DEADLINE keyword.")
4614 (make-variable-buffer-local 'org-deadline-regexp)
4615 (defvar org-deadline-time-regexp nil
4616 "Matches the DEADLINE keyword together with a time stamp.")
4617 (make-variable-buffer-local 'org-deadline-time-regexp)
4618 (defvar org-deadline-time-hour-regexp nil
4619 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4620 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4621 (defvar org-deadline-line-regexp nil
4622 "Matches the DEADLINE keyword and the rest of the line.")
4623 (make-variable-buffer-local 'org-deadline-line-regexp)
4624 (defvar org-scheduled-regexp nil
4625 "Matches the SCHEDULED keyword.")
4626 (make-variable-buffer-local 'org-scheduled-regexp)
4627 (defvar org-scheduled-time-regexp nil
4628 "Matches the SCHEDULED keyword together with a time stamp.")
4629 (make-variable-buffer-local 'org-scheduled-time-regexp)
4630 (defvar org-scheduled-time-hour-regexp nil
4631 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4632 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4633 (defvar org-closed-time-regexp nil
4634 "Matches the CLOSED keyword together with a time stamp.")
4635 (make-variable-buffer-local 'org-closed-time-regexp)
4637 (defvar org-keyword-time-regexp nil
4638 "Matches any of the 4 keywords, together with the time stamp.")
4639 (make-variable-buffer-local 'org-keyword-time-regexp)
4640 (defvar org-keyword-time-not-clock-regexp nil
4641 "Matches any of the 3 keywords, together with the time stamp.")
4642 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4643 (defvar org-maybe-keyword-time-regexp nil
4644 "Matches a timestamp, possibly preceded by a keyword.")
4645 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4646 (defvar org-all-time-keywords nil
4647 "List of time keywords.")
4648 (make-variable-buffer-local 'org-all-time-keywords)
4650 (defconst org-plain-time-of-day-regexp
4651 (concat
4652 "\\(\\<[012]?[0-9]"
4653 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4654 "\\(--?"
4655 "\\(\\<[012]?[0-9]"
4656 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4657 "\\)?")
4658 "Regular expression to match a plain time or time range.
4659 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4660 groups carry important information:
4661 0 the full match
4662 1 the first time, range or not
4663 8 the second time, if it is a range.")
4665 (defconst org-plain-time-extension-regexp
4666 (concat
4667 "\\(\\<[012]?[0-9]"
4668 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4669 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4670 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4671 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4672 groups carry important information:
4673 0 the full match
4674 7 hours of duration
4675 9 minutes of duration")
4677 (defconst org-stamp-time-of-day-regexp
4678 (concat
4679 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4680 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4681 "\\(--?"
4682 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4683 "Regular expression to match a timestamp time or time range.
4684 After a match, the following groups carry important information:
4685 0 the full match
4686 1 date plus weekday, for back referencing to make sure both times are on the same day
4687 2 the first time, range or not
4688 4 the second time, if it is a range.")
4690 (defconst org-startup-options
4691 '(("fold" org-startup-folded t)
4692 ("overview" org-startup-folded t)
4693 ("nofold" org-startup-folded nil)
4694 ("showall" org-startup-folded nil)
4695 ("showeverything" org-startup-folded showeverything)
4696 ("content" org-startup-folded content)
4697 ("indent" org-startup-indented t)
4698 ("noindent" org-startup-indented nil)
4699 ("hidestars" org-hide-leading-stars t)
4700 ("showstars" org-hide-leading-stars nil)
4701 ("odd" org-odd-levels-only t)
4702 ("oddeven" org-odd-levels-only nil)
4703 ("align" org-startup-align-all-tables t)
4704 ("noalign" org-startup-align-all-tables nil)
4705 ("inlineimages" org-startup-with-inline-images t)
4706 ("noinlineimages" org-startup-with-inline-images nil)
4707 ("latexpreview" org-startup-with-latex-preview t)
4708 ("nolatexpreview" org-startup-with-latex-preview nil)
4709 ("customtime" org-display-custom-times t)
4710 ("logdone" org-log-done time)
4711 ("lognotedone" org-log-done note)
4712 ("nologdone" org-log-done nil)
4713 ("lognoteclock-out" org-log-note-clock-out t)
4714 ("nolognoteclock-out" org-log-note-clock-out nil)
4715 ("logrepeat" org-log-repeat state)
4716 ("lognoterepeat" org-log-repeat note)
4717 ("logdrawer" org-log-into-drawer t)
4718 ("nologdrawer" org-log-into-drawer nil)
4719 ("logstatesreversed" org-log-states-order-reversed t)
4720 ("nologstatesreversed" org-log-states-order-reversed nil)
4721 ("nologrepeat" org-log-repeat nil)
4722 ("logreschedule" org-log-reschedule time)
4723 ("lognotereschedule" org-log-reschedule note)
4724 ("nologreschedule" org-log-reschedule nil)
4725 ("logredeadline" org-log-redeadline time)
4726 ("lognoteredeadline" org-log-redeadline note)
4727 ("nologredeadline" org-log-redeadline nil)
4728 ("logrefile" org-log-refile time)
4729 ("lognoterefile" org-log-refile note)
4730 ("nologrefile" org-log-refile nil)
4731 ("fninline" org-footnote-define-inline t)
4732 ("nofninline" org-footnote-define-inline nil)
4733 ("fnlocal" org-footnote-section nil)
4734 ("fnauto" org-footnote-auto-label t)
4735 ("fnprompt" org-footnote-auto-label nil)
4736 ("fnconfirm" org-footnote-auto-label confirm)
4737 ("fnplain" org-footnote-auto-label plain)
4738 ("fnadjust" org-footnote-auto-adjust t)
4739 ("nofnadjust" org-footnote-auto-adjust nil)
4740 ("constcgs" constants-unit-system cgs)
4741 ("constSI" constants-unit-system SI)
4742 ("noptag" org-tag-persistent-alist nil)
4743 ("hideblocks" org-hide-block-startup t)
4744 ("nohideblocks" org-hide-block-startup nil)
4745 ("beamer" org-startup-with-beamer-mode t)
4746 ("entitiespretty" org-pretty-entities t)
4747 ("entitiesplain" org-pretty-entities nil))
4748 "Variable associated with STARTUP options for org-mode.
4749 Each element is a list of three items: the startup options (as written
4750 in the #+STARTUP line), the corresponding variable, and the value to set
4751 this variable to if the option is found. An optional forth element PUSH
4752 means to push this value onto the list in the variable.")
4754 (defun org-update-property-plist (key val props)
4755 "Update PROPS with KEY and VAL."
4756 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4757 (key (if appending (substring key 0 (- (length key) 1)) key))
4758 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4759 (previous (cdr (assoc key props))))
4760 (if appending
4761 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4762 (cons (cons key val) remainder))))
4764 (defconst org-block-regexp
4765 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4766 "Regular expression for hiding blocks.")
4767 (defconst org-heading-keyword-regexp-format
4768 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4769 "Printf format for a regexp matching a headline with some keyword.
4770 This regexp will match the headline of any node which has the
4771 exact keyword that is put into the format. The keyword isn't in
4772 any group by default, but the stars and the body are.")
4773 (defconst org-heading-keyword-maybe-regexp-format
4774 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4775 "Printf format for a regexp matching a headline, possibly with some keyword.
4776 This regexp can match any headline with the specified keyword, or
4777 without a keyword. The keyword isn't in any group by default,
4778 but the stars and the body are.")
4780 (defcustom org-group-tags t
4781 "When non-nil (the default), use group tags.
4782 This can be turned on/off through `org-toggle-tags-groups'."
4783 :group 'org-tags
4784 :group 'org-startup
4785 :type 'boolean)
4787 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4789 (defun org-toggle-tags-groups ()
4790 "Toggle support for group tags.
4791 Support for group tags is controlled by the option
4792 `org-group-tags', which is non-nil by default."
4793 (interactive)
4794 (setq org-group-tags (not org-group-tags))
4795 (cond ((and (derived-mode-p 'org-agenda-mode)
4796 org-group-tags)
4797 (org-agenda-redo))
4798 ((derived-mode-p 'org-mode)
4799 (let ((org-inhibit-startup t)) (org-mode))))
4800 (message "Groups tags support has been turned %s"
4801 (if org-group-tags "on" "off")))
4803 (defun org-set-regexps-and-options-for-tags ()
4804 "Precompute variables used for tags."
4805 (when (derived-mode-p 'org-mode)
4806 (org-set-local 'org-file-tags nil)
4807 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4808 (splitre "[ \t]+")
4809 (start 0)
4810 tags ftags key value)
4811 (save-excursion
4812 (save-restriction
4813 (widen)
4814 (goto-char (point-min))
4815 (while (re-search-forward re nil t)
4816 (setq key (upcase (org-match-string-no-properties 1))
4817 value (org-match-string-no-properties 2))
4818 (if (stringp value) (setq value (org-trim value)))
4819 (cond
4820 ((equal key "TAGS")
4821 (setq tags (append tags (if tags '("\\n") nil)
4822 (org-split-string value splitre))))
4823 ((equal key "FILETAGS")
4824 (when (string-match "\\S-" value)
4825 (setq ftags
4826 (append
4827 ftags
4828 (apply 'append
4829 (mapcar (lambda (x) (org-split-string x ":"))
4830 (org-split-string value)))))))))))
4831 ;; Process the file tags.
4832 (and ftags (org-set-local 'org-file-tags
4833 (mapcar 'org-add-prop-inherited ftags)))
4834 (org-set-local 'org-tag-groups-alist nil)
4835 ;; Process the tags.
4836 (when (and (not tags) org-tag-alist)
4837 (setq tags
4838 (mapcar
4839 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4840 ((eq (car tg) :endgroup) "}")
4841 ((eq (car tg) :grouptags) ":")
4842 ((eq (car tg) :newline) "\n")
4843 (t (concat (car tg)
4844 (if (characterp (cdr tg))
4845 (format "(%s)" (char-to-string (cdr tg))) "")))))
4846 org-tag-alist)))
4847 (let (e tgs g)
4848 (while (setq e (pop tags))
4849 (cond
4850 ((equal e "{")
4851 (progn (push '(:startgroup) tgs)
4852 (when (equal (nth 1 tags) ":")
4853 (push (list (replace-regexp-in-string
4854 "(.+)$" "" (nth 0 tags)))
4855 org-tag-groups-alist)
4856 (setq g 0))))
4857 ((equal e ":") (push '(:grouptags) tgs))
4858 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4859 ((equal e "\\n") (push '(:newline) tgs))
4860 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4861 (push (cons (match-string 1 e)
4862 (string-to-char (match-string 2 e))) tgs)
4863 (if (and g (> g 0))
4864 (setcar org-tag-groups-alist
4865 (append (car org-tag-groups-alist)
4866 (list (match-string 1 e)))))
4867 (if g (setq g (1+ g))))
4868 (t (push (list e) tgs)
4869 (if (and g (> g 0))
4870 (setcar org-tag-groups-alist
4871 (append (car org-tag-groups-alist) (list e))))
4872 (if g (setq g (1+ g))))))
4873 (org-set-local 'org-tag-alist nil)
4874 (while (setq e (pop tgs))
4875 (or (and (stringp (car e))
4876 (assoc (car e) org-tag-alist))
4877 (push e org-tag-alist)))
4878 ;; Return a list with tag variables
4879 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4881 (defvar org-ota nil)
4882 (defun org-set-regexps-and-options ()
4883 "Precompute regular expressions used in the current buffer."
4884 (when (derived-mode-p 'org-mode)
4885 (org-set-local 'org-todo-kwd-alist nil)
4886 (org-set-local 'org-todo-key-alist nil)
4887 (org-set-local 'org-todo-key-trigger nil)
4888 (org-set-local 'org-todo-keywords-1 nil)
4889 (org-set-local 'org-done-keywords nil)
4890 (org-set-local 'org-todo-heads nil)
4891 (org-set-local 'org-todo-sets nil)
4892 (org-set-local 'org-todo-log-states nil)
4893 (org-set-local 'org-file-properties nil)
4894 (let ((re (org-make-options-regexp
4895 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4896 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4897 "SETUPFILE" "OPTIONS")
4898 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4899 (splitre "[ \t]+")
4900 (scripts org-use-sub-superscripts)
4901 kwds kws0 kwsa key log value cat arch const links hw dws
4902 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4903 (start 0))
4904 (save-excursion
4905 (save-restriction
4906 (widen)
4907 (goto-char (point-min))
4908 (while
4909 (or (and
4910 ext-setup-or-nil
4911 (not org-ota)
4912 (let (ret)
4913 (with-temp-buffer
4914 (insert ext-setup-or-nil)
4915 (let ((major-mode 'org-mode) org-ota)
4916 (setq ret (save-match-data
4917 (org-set-regexps-and-options-for-tags)))))
4918 ;; Append setupfile tags to existing tags
4919 (setq org-ota t)
4920 (setq org-file-tags
4921 (delq nil (append org-file-tags (nth 0 ret)))
4922 org-tag-alist
4923 (delq nil (append org-tag-alist (nth 1 ret)))
4924 org-tag-groups-alist
4925 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4926 (and ext-setup-or-nil
4927 (string-match re ext-setup-or-nil start)
4928 (setq start (match-end 0)))
4929 (and (setq ext-setup-or-nil nil start 0)
4930 (re-search-forward re nil t)))
4931 (setq key (upcase (match-string 1 ext-setup-or-nil))
4932 value (org-match-string-no-properties 2 ext-setup-or-nil))
4933 (if (stringp value) (setq value (org-trim value)))
4934 (cond
4935 ((equal key "CATEGORY")
4936 (setq cat value))
4937 ((member key '("SEQ_TODO" "TODO"))
4938 (push (cons 'sequence (org-split-string value splitre)) kwds))
4939 ((equal key "TYP_TODO")
4940 (push (cons 'type (org-split-string value splitre)) kwds))
4941 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4942 ;; general TODO-like setup
4943 (push (cons (intern (downcase (match-string 1 key)))
4944 (org-split-string value splitre)) kwds))
4945 ((equal key "COLUMNS")
4946 (org-set-local 'org-columns-default-format value))
4947 ((equal key "LINK")
4948 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4949 (push (cons (match-string 1 value)
4950 (org-trim (match-string 2 value)))
4951 links)))
4952 ((equal key "PRIORITIES")
4953 (setq prio (org-split-string value " +")))
4954 ((equal key "PROPERTY")
4955 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4956 (setq props (org-update-property-plist (match-string 1 value)
4957 (match-string 2 value)
4958 props))))
4959 ((equal key "DRAWERS")
4960 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4961 ((equal key "CONSTANTS")
4962 (org-table-set-constants))
4963 ((equal key "STARTUP")
4964 (let ((opts (org-split-string value splitre))
4965 l var val)
4966 (while (setq l (pop opts))
4967 (when (setq l (assoc l org-startup-options))
4968 (setq var (nth 1 l) val (nth 2 l))
4969 (if (not (nth 3 l))
4970 (set (make-local-variable var) val)
4971 (if (not (listp (symbol-value var)))
4972 (set (make-local-variable var) nil))
4973 (set (make-local-variable var) (symbol-value var))
4974 (add-to-list var val))))))
4975 ((equal key "ARCHIVE")
4976 (setq arch value)
4977 (remove-text-properties 0 (length arch)
4978 '(face t fontified t) arch))
4979 ((equal key "OPTIONS")
4980 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4981 (setq scripts (read (match-string 2 value)))))
4982 ((and (equal key "SETUPFILE")
4983 ;; Prevent checking in Gnus messages
4984 (not buffer-read-only))
4985 (setq setup-contents (org-file-contents
4986 (expand-file-name
4987 (org-remove-double-quotes value))
4988 'noerror))
4989 (if (not ext-setup-or-nil)
4990 (setq ext-setup-or-nil setup-contents start 0)
4991 (setq ext-setup-or-nil
4992 (concat (substring ext-setup-or-nil 0 start)
4993 "\n" setup-contents "\n"
4994 (substring ext-setup-or-nil start)))))))
4995 ;; search for property blocks
4996 (goto-char (point-min))
4997 (while (re-search-forward org-block-regexp nil t)
4998 (when (equal "PROPERTY" (upcase (match-string 1)))
4999 (setq value (replace-regexp-in-string
5000 "[\n\r]" " " (match-string 4)))
5001 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5002 (setq props (org-update-property-plist (match-string 1 value)
5003 (match-string 2 value)
5004 props)))))))
5005 (org-set-local 'org-use-sub-superscripts scripts)
5006 (when cat
5007 (org-set-local 'org-category (intern cat))
5008 (push (cons "CATEGORY" cat) props))
5009 (when prio
5010 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5011 (setq prio (mapcar 'string-to-char prio))
5012 (org-set-local 'org-highest-priority (nth 0 prio))
5013 (org-set-local 'org-lowest-priority (nth 1 prio))
5014 (org-set-local 'org-default-priority (nth 2 prio)))
5015 (and props (org-set-local 'org-file-properties (nreverse props)))
5016 (and drawers (org-set-local 'org-drawers drawers))
5017 (and arch (org-set-local 'org-archive-location arch))
5018 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5019 ;; Process the TODO keywords
5020 (unless kwds
5021 ;; Use the global values as if they had been given locally.
5022 (setq kwds (default-value 'org-todo-keywords))
5023 (if (stringp (car kwds))
5024 (setq kwds (list (cons org-todo-interpretation
5025 (default-value 'org-todo-keywords)))))
5026 (setq kwds (reverse kwds)))
5027 (setq kwds (nreverse kwds))
5028 (let (inter kws kw)
5029 (while (setq kws (pop kwds))
5030 (let ((kws (or
5031 (run-hook-with-args-until-success
5032 'org-todo-setup-filter-hook kws)
5033 kws)))
5034 (setq inter (pop kws) sep (member "|" kws)
5035 kws0 (delete "|" (copy-sequence kws))
5036 kwsa nil
5037 kws1 (mapcar
5038 (lambda (x)
5039 ;; 1 2
5040 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5041 (progn
5042 (setq kw (match-string 1 x)
5043 key (and (match-end 2) (match-string 2 x))
5044 log (org-extract-log-state-settings x))
5045 (push (cons kw (and key (string-to-char key))) kwsa)
5046 (and log (push log org-todo-log-states))
5048 (error "Invalid TODO keyword %s" x)))
5049 kws0)
5050 kwsa (if kwsa (append '((:startgroup))
5051 (nreverse kwsa)
5052 '((:endgroup))))
5053 hw (car kws1)
5054 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5055 tail (list inter hw (car dws) (org-last dws))))
5056 (add-to-list 'org-todo-heads hw 'append)
5057 (push kws1 org-todo-sets)
5058 (setq org-done-keywords (append org-done-keywords dws nil))
5059 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5060 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5061 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5062 (setq org-todo-sets (nreverse org-todo-sets)
5063 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5064 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5065 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5066 ;; Compute the regular expressions and other local variables.
5067 ;; Using `org-outline-regexp-bol' would complicate them much,
5068 ;; because of the fixed white space at the end of that string.
5069 (if (not org-done-keywords)
5070 (setq org-done-keywords (and org-todo-keywords-1
5071 (list (org-last org-todo-keywords-1)))))
5072 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5073 (length org-scheduled-string)
5074 (length org-clock-string)
5075 (length org-closed-string)))
5076 org-drawer-regexp
5077 (concat "^[ \t]*:\\("
5078 (mapconcat 'regexp-quote org-drawers "\\|")
5079 "\\):[ \t]*$")
5080 org-not-done-keywords
5081 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5082 org-todo-regexp
5083 (concat "\\("
5084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5085 "\\)")
5086 org-not-done-regexp
5087 (concat "\\("
5088 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5089 "\\)")
5090 org-not-done-heading-regexp
5091 (format org-heading-keyword-regexp-format org-not-done-regexp)
5092 org-todo-line-regexp
5093 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5094 org-complex-heading-regexp
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +\\(.*?\\)\\)??"
5099 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5100 "[ \t]*$")
5101 org-complex-heading-regexp-format
5102 (concat "^\\(\\*+\\)"
5103 "\\(?: +" org-todo-regexp "\\)?"
5104 "\\(?: +\\(\\[#.\\]\\)\\)?"
5105 "\\(?: +"
5106 ;; Stats cookies can be stuck to body.
5107 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5108 "\\(%s\\)"
5109 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5110 "\\)"
5111 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5112 "[ \t]*$")
5113 org-todo-line-tags-regexp
5114 (concat "^\\(\\*+\\)"
5115 "\\(?: +" org-todo-regexp "\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-deadline-regexp (concat "\\<" org-deadline-string)
5120 org-deadline-time-regexp
5121 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5122 org-deadline-time-hour-regexp
5123 (concat "\\<" org-deadline-string
5124 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5125 org-deadline-line-regexp
5126 (concat "\\<\\(" org-deadline-string "\\).*")
5127 org-scheduled-regexp
5128 (concat "\\<" org-scheduled-string)
5129 org-scheduled-time-regexp
5130 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5131 org-scheduled-time-hour-regexp
5132 (concat "\\<" org-scheduled-string
5133 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5134 org-closed-time-regexp
5135 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5136 org-keyword-time-regexp
5137 (concat "\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\|" org-clock-string "\\)"
5141 " *[[<]\\([^]>]+\\)[]>]")
5142 org-keyword-time-not-clock-regexp
5143 (concat "\\<\\(" org-scheduled-string
5144 "\\|" org-deadline-string
5145 "\\|" org-closed-string
5146 "\\)"
5147 " *[[<]\\([^]>]+\\)[]>]")
5148 org-maybe-keyword-time-regexp
5149 (concat "\\(\\<\\(" org-scheduled-string
5150 "\\|" org-deadline-string
5151 "\\|" org-closed-string
5152 "\\|" org-clock-string "\\)\\)?"
5153 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5154 org-all-time-keywords
5155 (mapcar (lambda (w) (substring w 0 -1))
5156 (list org-scheduled-string org-deadline-string
5157 org-clock-string org-closed-string)))
5158 (setq org-ota nil)
5159 (org-compute-latex-and-related-regexp))))
5161 (defun org-file-contents (file &optional noerror)
5162 "Return the contents of FILE, as a string."
5163 (if (or (not file)
5164 (not (file-readable-p file)))
5165 (if noerror
5166 (message "Cannot read file \"%s\"" file)
5167 (error "Cannot read file \"%s\"" file))
5168 (with-temp-buffer
5169 (insert-file-contents file)
5170 (buffer-string))))
5172 (defun org-extract-log-state-settings (x)
5173 "Extract the log state setting from a TODO keyword string.
5174 This will extract info from a string like \"WAIT(w@/!)\"."
5175 (let (kw key log1 log2)
5176 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5177 (setq kw (match-string 1 x)
5178 key (and (match-end 2) (match-string 2 x))
5179 log1 (and (match-end 3) (match-string 3 x))
5180 log2 (and (match-end 4) (match-string 4 x)))
5181 (and (or log1 log2)
5182 (list kw
5183 (and log1 (if (equal log1 "!") 'time 'note))
5184 (and log2 (if (equal log2 "!") 'time 'note)))))))
5186 (defun org-remove-keyword-keys (list)
5187 "Remove a pair of parenthesis at the end of each string in LIST."
5188 (mapcar (lambda (x)
5189 (if (string-match "(.*)$" x)
5190 (substring x 0 (match-beginning 0))
5192 list))
5194 (defun org-assign-fast-keys (alist)
5195 "Assign fast keys to a keyword-key alist.
5196 Respect keys that are already there."
5197 (let (new e (alt ?0))
5198 (while (setq e (pop alist))
5199 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5200 (cdr e)) ;; Key already assigned.
5201 (push e new)
5202 (let ((clist (string-to-list (downcase (car e))))
5203 (used (append new alist)))
5204 (when (= (car clist) ?@)
5205 (pop clist))
5206 (while (and clist (rassoc (car clist) used))
5207 (pop clist))
5208 (unless clist
5209 (while (rassoc alt used)
5210 (incf alt)))
5211 (push (cons (car e) (or (car clist) alt)) new))))
5212 (nreverse new)))
5214 ;;; Some variables used in various places
5216 (defvar org-window-configuration nil
5217 "Used in various places to store a window configuration.")
5218 (defvar org-selected-window nil
5219 "Used in various places to store a window configuration.")
5220 (defvar org-finish-function nil
5221 "Function to be called when `C-c C-c' is used.
5222 This is for getting out of special buffers like capture.")
5225 ;; FIXME: Occasionally check by commenting these, to make sure
5226 ;; no other functions uses these, forgetting to let-bind them.
5227 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5228 (defvar org-last-state)
5229 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5231 ;; Defined somewhere in this file, but used before definition.
5232 (defvar org-entities) ;; defined in org-entities.el
5233 (defvar org-struct-menu)
5234 (defvar org-org-menu)
5235 (defvar org-tbl-menu)
5237 ;;;; Define the Org-mode
5239 ;; We use a before-change function to check if a table might need
5240 ;; an update.
5241 (defvar org-table-may-need-update t
5242 "Indicates that a table might need an update.
5243 This variable is set by `org-before-change-function'.
5244 `org-table-align' sets it back to nil.")
5245 (defun org-before-change-function (beg end)
5246 "Every change indicates that a table might need an update."
5247 (setq org-table-may-need-update t))
5248 (defvar org-mode-map)
5249 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5250 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5251 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5252 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5253 (defvar org-table-buffer-is-an nil)
5255 (defvar bidi-paragraph-direction)
5256 (defvar buffer-face-mode-face)
5258 (require 'outline)
5259 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5260 (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"))
5261 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5263 ;; Other stuff we need.
5264 (require 'time-date)
5265 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5266 (require 'easymenu)
5267 (require 'overlay)
5269 ;; (require 'org-macs) moved higher up in the file before it is first used
5270 (require 'org-entities)
5271 ;; (require 'org-compat) moved higher up in the file before it is first used
5272 (require 'org-faces)
5273 (require 'org-list)
5274 (require 'org-pcomplete)
5275 (require 'org-src)
5276 (require 'org-footnote)
5277 (require 'org-macro)
5279 ;; babel
5280 (require 'ob)
5282 ;;;###autoload
5283 (define-derived-mode org-mode outline-mode "Org"
5284 "Outline-based notes management and organizer, alias
5285 \"Carsten's outline-mode for keeping track of everything.\"
5287 Org-mode develops organizational tasks around a NOTES file which
5288 contains information about projects as plain text. Org-mode is
5289 implemented on top of outline-mode, which is ideal to keep the content
5290 of large files well structured. It supports ToDo items, deadlines and
5291 time stamps, which magically appear in the diary listing of the Emacs
5292 calendar. Tables are easily created with a built-in table editor.
5293 Plain text URL-like links connect to websites, emails (VM), Usenet
5294 messages (Gnus), BBDB entries, and any files related to the project.
5295 For printing and sharing of notes, an Org-mode file (or a part of it)
5296 can be exported as a structured ASCII or HTML file.
5298 The following commands are available:
5300 \\{org-mode-map}"
5302 ;; Get rid of Outline menus, they are not needed
5303 ;; Need to do this here because define-derived-mode sets up
5304 ;; the keymap so late. Still, it is a waste to call this each time
5305 ;; we switch another buffer into org-mode.
5306 (if (featurep 'xemacs)
5307 (when (boundp 'outline-mode-menu-heading)
5308 ;; Assume this is Greg's port, it uses easymenu
5309 (easy-menu-remove outline-mode-menu-heading)
5310 (easy-menu-remove outline-mode-menu-show)
5311 (easy-menu-remove outline-mode-menu-hide))
5312 (define-key org-mode-map [menu-bar headings] 'undefined)
5313 (define-key org-mode-map [menu-bar hide] 'undefined)
5314 (define-key org-mode-map [menu-bar show] 'undefined))
5316 (org-load-modules-maybe)
5317 (easy-menu-add org-org-menu)
5318 (easy-menu-add org-tbl-menu)
5319 (org-install-agenda-files-menu)
5320 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5321 (add-to-invisibility-spec '(org-cwidth))
5322 (add-to-invisibility-spec '(org-hide-block . t))
5323 (when (featurep 'xemacs)
5324 (org-set-local 'line-move-ignore-invisible t))
5325 (org-set-local 'outline-regexp org-outline-regexp)
5326 (org-set-local 'outline-level 'org-outline-level)
5327 (setq bidi-paragraph-direction 'left-to-right)
5328 (when (and org-ellipsis
5329 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5330 (fboundp 'make-glyph-code))
5331 (unless org-display-table
5332 (setq org-display-table (make-display-table)))
5333 (set-display-table-slot
5334 org-display-table 4
5335 (vconcat (mapcar
5336 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5337 org-ellipsis)))
5338 (if (stringp org-ellipsis) org-ellipsis "..."))))
5339 (setq buffer-display-table org-display-table))
5340 (org-set-regexps-and-options-for-tags)
5341 (org-set-regexps-and-options)
5342 (org-set-font-lock-defaults)
5343 (when (and org-tag-faces (not org-tags-special-faces-re))
5344 ;; tag faces set outside customize.... force initialization.
5345 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5346 ;; Calc embedded
5347 (org-set-local 'calc-embedded-open-mode "# ")
5348 ;; Modify a few syntax entries
5349 (modify-syntax-entry ?@ "w")
5350 (modify-syntax-entry ?\" "\"")
5351 (if org-startup-truncated (setq truncate-lines t))
5352 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5353 (org-set-local 'font-lock-unfontify-region-function
5354 'org-unfontify-region)
5355 ;; Activate before-change-function
5356 (org-set-local 'org-table-may-need-update t)
5357 (org-add-hook 'before-change-functions 'org-before-change-function nil
5358 'local)
5359 ;; Check for running clock before killing a buffer
5360 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5361 ;; Initialize macros templates.
5362 (org-macro-initialize-templates)
5363 ;; Initialize radio targets.
5364 (org-update-radio-target-regexp)
5365 ;; Indentation.
5366 (org-set-local 'indent-line-function 'org-indent-line)
5367 (org-set-local 'indent-region-function 'org-indent-region)
5368 ;; Filling and auto-filling.
5369 (org-setup-filling)
5370 ;; Comments.
5371 (org-setup-comments-handling)
5372 ;; Beginning/end of defun
5373 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5374 (org-set-local 'end-of-defun-function 'org-forward-element)
5375 ;; Next error for sparse trees
5376 (org-set-local 'next-error-function 'org-occur-next-match)
5377 ;; Make sure dependence stuff works reliably, even for users who set it
5378 ;; too late :-(
5379 (if org-enforce-todo-dependencies
5380 (add-hook 'org-blocker-hook
5381 'org-block-todo-from-children-or-siblings-or-parent)
5382 (remove-hook 'org-blocker-hook
5383 'org-block-todo-from-children-or-siblings-or-parent))
5384 (if org-enforce-todo-checkbox-dependencies
5385 (add-hook 'org-blocker-hook
5386 'org-block-todo-from-checkboxes)
5387 (remove-hook 'org-blocker-hook
5388 'org-block-todo-from-checkboxes))
5390 ;; Align options lines
5391 (org-set-local
5392 'align-mode-rules-list
5393 '((org-in-buffer-settings
5394 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5395 (modes . '(org-mode)))))
5397 ;; Imenu
5398 (org-set-local 'imenu-create-index-function
5399 'org-imenu-get-tree)
5401 ;; Make isearch reveal context
5402 (if (or (featurep 'xemacs)
5403 (not (boundp 'outline-isearch-open-invisible-function)))
5404 ;; Emacs 21 and XEmacs make use of the hook
5405 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5406 ;; Emacs 22 deals with this through a special variable
5407 (org-set-local 'outline-isearch-open-invisible-function
5408 (lambda (&rest ignore) (org-show-context 'isearch)))
5409 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5411 ;; Setup the pcomplete hooks
5412 (set (make-local-variable 'pcomplete-command-completion-function)
5413 'org-pcomplete-initial)
5414 (set (make-local-variable 'pcomplete-command-name-function)
5415 'org-command-at-point)
5416 (set (make-local-variable 'pcomplete-default-completion-function)
5417 'ignore)
5418 (set (make-local-variable 'pcomplete-parse-arguments-function)
5419 'org-parse-arguments)
5420 (set (make-local-variable 'pcomplete-termination-string) "")
5421 (when (>= emacs-major-version 23)
5422 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5424 ;; If empty file that did not turn on org-mode automatically, make it to.
5425 (if (and org-insert-mode-line-in-empty-file
5426 (org-called-interactively-p 'any)
5427 (= (point-min) (point-max)))
5428 (insert "# -*- mode: org -*-\n\n"))
5429 (unless org-inhibit-startup
5430 (org-unmodified
5431 (and org-startup-with-beamer-mode (org-beamer-mode))
5432 (when org-startup-align-all-tables
5433 (org-table-map-tables 'org-table-align 'quietly))
5434 (when org-startup-with-inline-images
5435 (org-display-inline-images))
5436 (when org-startup-with-latex-preview
5437 (org-preview-latex-fragment))
5438 (unless org-inhibit-startup-visibility-stuff
5439 (org-set-startup-visibility))))
5440 ;; Try to set org-hide correctly
5441 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5443 ;; Update `customize-package-emacs-version-alist'
5444 (add-to-list 'customize-package-emacs-version-alist
5445 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5446 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5447 ("8.0" . "24.4")))
5449 (defvar org-mode-transpose-word-syntax-table
5450 (let ((st (make-syntax-table)))
5451 (mapc (lambda(c) (modify-syntax-entry
5452 (string-to-char (car c)) "w p" st))
5453 org-emphasis-alist)
5454 st))
5456 (when (fboundp 'abbrev-table-put)
5457 (abbrev-table-put org-mode-abbrev-table
5458 :parents (list text-mode-abbrev-table)))
5460 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5462 (defsubst org-fix-ellipsis-at-bol ()
5463 (save-excursion (goto-char (window-start)) (recenter 0)))
5465 (defun org-find-invisible-foreground ()
5466 (let ((candidates (remove
5467 "unspecified-bg"
5468 (nconc
5469 (list (face-background 'default)
5470 (face-background 'org-default))
5471 (mapcar
5472 (lambda (alist)
5473 (when (boundp alist)
5474 (cdr (assoc 'background-color (symbol-value alist)))))
5475 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5476 (list (face-foreground 'org-hide))))))
5477 (car (remove nil candidates))))
5479 (defun org-current-time (&optional rounding-minutes past)
5480 "Current time, possibly rounded to ROUNDING-MINUTES.
5481 When ROUNDING-MINUTES is not an integer, fall back on the car of
5482 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5483 the rounding returns a past time."
5484 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5485 (car org-time-stamp-rounding-minutes)))
5486 (time (decode-time)) res)
5487 (if (< r 1)
5488 (current-time)
5489 (setq res
5490 (apply 'encode-time
5491 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5492 (nthcdr 2 time))))
5493 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5494 (seconds-to-time (- (org-float-time res) (* r 60)))
5495 res))))
5497 (defun org-today ()
5498 "Return today date, considering `org-extend-today-until'."
5499 (time-to-days
5500 (time-subtract (current-time)
5501 (list 0 (* 3600 org-extend-today-until) 0))))
5503 ;;;; Font-Lock stuff, including the activators
5505 (defvar org-mouse-map (make-sparse-keymap))
5506 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5507 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5508 (when org-mouse-1-follows-link
5509 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5510 (when org-tab-follows-link
5511 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5512 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5514 (require 'font-lock)
5516 (defconst org-non-link-chars "]\t\n\r<>")
5517 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5518 "shell" "elisp" "doi" "message"))
5519 (defvar org-link-types-re nil
5520 "Matches a link that has a url-like prefix like \"http:\"")
5521 (defvar org-link-re-with-space nil
5522 "Matches a link with spaces, optional angular brackets around it.")
5523 (defvar org-link-re-with-space2 nil
5524 "Matches a link with spaces, optional angular brackets around it.")
5525 (defvar org-link-re-with-space3 nil
5526 "Matches a link with spaces, only for internal part in bracket links.")
5527 (defvar org-angle-link-re nil
5528 "Matches link with angular brackets, spaces are allowed.")
5529 (defvar org-plain-link-re nil
5530 "Matches plain link, without spaces.")
5531 (defvar org-bracket-link-regexp nil
5532 "Matches a link in double brackets.")
5533 (defvar org-bracket-link-analytic-regexp nil
5534 "Regular expression used to analyze links.
5535 Here is what the match groups contain after a match:
5536 1: http:
5537 2: http
5538 3: path
5539 4: [desc]
5540 5: desc")
5541 (defvar org-bracket-link-analytic-regexp++ nil
5542 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5543 (defvar org-any-link-re nil
5544 "Regular expression matching any link.")
5546 (defconst org-match-sexp-depth 3
5547 "Number of stacked braces for sub/superscript matching.")
5549 (defun org-create-multibrace-regexp (left right n)
5550 "Create a regular expression which will match a balanced sexp.
5551 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5552 as single character strings.
5553 The regexp returned will match the entire expression including the
5554 delimiters. It will also define a single group which contains the
5555 match except for the outermost delimiters. The maximum depth of
5556 stacked delimiters is N. Escaping delimiters is not possible."
5557 (let* ((nothing (concat "[^" left right "]*?"))
5558 (or "\\|")
5559 (re nothing)
5560 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5561 (while (> n 1)
5562 (setq n (1- n)
5563 re (concat re or next)
5564 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5565 (concat left "\\(" re "\\)" right)))
5567 (defvar org-match-substring-regexp
5568 (concat
5569 "\\(\\S-\\)\\([_^]\\)\\("
5570 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5571 "\\|"
5572 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5573 "\\|"
5574 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5575 "The regular expression matching a sub- or superscript.")
5577 (defvar org-match-substring-with-braces-regexp
5578 (concat
5579 "\\(\\S-\\)\\([_^]\\)\\("
5580 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5581 "\\)")
5582 "The regular expression matching a sub- or superscript, forcing braces.")
5584 (defun org-make-link-regexps ()
5585 "Update the link regular expressions.
5586 This should be called after the variable `org-link-types' has changed."
5587 (setq org-link-types-re
5588 (concat
5589 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5590 org-link-re-with-space
5591 (concat
5592 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5593 "\\([^" org-non-link-chars " ]"
5594 "[^" org-non-link-chars "]*"
5595 "[^" org-non-link-chars " ]\\)>?")
5596 org-link-re-with-space2
5597 (concat
5598 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5599 "\\([^" org-non-link-chars " ]"
5600 "[^\t\n\r]*"
5601 "[^" org-non-link-chars " ]\\)>?")
5602 org-link-re-with-space3
5603 (concat
5604 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5605 "\\([^" org-non-link-chars " ]"
5606 "[^\t\n\r]*\\)")
5607 org-angle-link-re
5608 (concat
5609 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5610 "\\([^" org-non-link-chars " ]"
5611 "[^" org-non-link-chars "]*"
5612 "\\)>")
5613 org-plain-link-re
5614 (concat
5615 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5616 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5617 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5618 org-bracket-link-regexp
5619 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5620 org-bracket-link-analytic-regexp
5621 (concat
5622 "\\[\\["
5623 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5624 "\\([^]]+\\)"
5625 "\\]"
5626 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5627 "\\]")
5628 org-bracket-link-analytic-regexp++
5629 (concat
5630 "\\[\\["
5631 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5632 "\\([^]]+\\)"
5633 "\\]"
5634 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5635 "\\]")
5636 org-any-link-re
5637 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5638 org-angle-link-re "\\)\\|\\("
5639 org-plain-link-re "\\)")))
5641 (org-make-link-regexps)
5643 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5644 "Regular expression for fast time stamp matching.")
5645 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5646 "Regular expression for fast time stamp matching.")
5647 (defconst org-ts-regexp0
5648 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5649 "Regular expression matching time strings for analysis.
5650 This one does not require the space after the date, so it can be used
5651 on a string that terminates immediately after the date.")
5652 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5653 "Regular expression matching time strings for analysis.")
5654 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5655 "Regular expression matching time stamps, with groups.")
5656 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5657 "Regular expression matching time stamps (also [..]), with groups.")
5658 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5659 "Regular expression matching a time stamp range.")
5660 (defconst org-tr-regexp-both
5661 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5662 "Regular expression matching a time stamp range.")
5663 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5664 org-ts-regexp "\\)?")
5665 "Regular expression matching a time stamp or time stamp range.")
5666 (defconst org-tsr-regexp-both
5667 (concat org-ts-regexp-both "\\(--?-?"
5668 org-ts-regexp-both "\\)?")
5669 "Regular expression matching a time stamp or time stamp range.
5670 The time stamps may be either active or inactive.")
5672 (defvar org-emph-face nil)
5674 (defun org-do-emphasis-faces (limit)
5675 "Run through the buffer and add overlays to emphasized strings."
5676 (let (rtn a)
5677 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5678 (if (not (= (char-after (match-beginning 3))
5679 (char-after (match-beginning 4))))
5680 (progn
5681 (setq rtn t)
5682 (setq a (assoc (match-string 3) org-emphasis-alist))
5683 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5684 'face
5685 (nth 1 a))
5686 (and (nth 2 a)
5687 (org-remove-flyspell-overlays-in
5688 (match-beginning 0) (match-end 0)))
5689 (add-text-properties (match-beginning 2) (match-end 2)
5690 '(font-lock-multiline t org-emphasis t))
5691 (when org-hide-emphasis-markers
5692 (add-text-properties (match-end 4) (match-beginning 5)
5693 '(invisible org-link))
5694 (add-text-properties (match-beginning 3) (match-end 3)
5695 '(invisible org-link)))))
5696 (goto-char (1+ (match-beginning 0))))
5697 rtn))
5699 (defun org-emphasize (&optional char)
5700 "Insert or change an emphasis, i.e. a font like bold or italic.
5701 If there is an active region, change that region to a new emphasis.
5702 If there is no region, just insert the marker characters and position
5703 the cursor between them.
5704 CHAR should be the marker character. If it is a space, it means to
5705 remove the emphasis of the selected region.
5706 If CHAR is not given (for example in an interactive call) it will be
5707 prompted for."
5708 (interactive)
5709 (let ((erc org-emphasis-regexp-components)
5710 (prompt "")
5711 (string "") beg end move c s)
5712 (if (org-region-active-p)
5713 (setq beg (region-beginning) end (region-end)
5714 string (buffer-substring beg end))
5715 (setq move t))
5717 (unless char
5718 (message "Emphasis marker or tag: [%s]"
5719 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5720 (setq char (read-char-exclusive)))
5721 (if (equal char ?\ )
5722 (setq s "" move nil)
5723 (unless (assoc (char-to-string char) org-emphasis-alist)
5724 (user-error "No such emphasis marker: \"%c\"" char))
5725 (setq s (char-to-string char)))
5726 (while (and (> (length string) 1)
5727 (equal (substring string 0 1) (substring string -1))
5728 (assoc (substring string 0 1) org-emphasis-alist))
5729 (setq string (substring string 1 -1)))
5730 (setq string (concat s string s))
5731 (if beg (delete-region beg end))
5732 (unless (or (bolp)
5733 (string-match (concat "[" (nth 0 erc) "\n]")
5734 (char-to-string (char-before (point)))))
5735 (insert " "))
5736 (unless (or (eobp)
5737 (string-match (concat "[" (nth 1 erc) "\n]")
5738 (char-to-string (char-after (point)))))
5739 (insert " ") (backward-char 1))
5740 (insert string)
5741 (and move (backward-char 1))))
5743 (defconst org-nonsticky-props
5744 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5746 (defsubst org-rear-nonsticky-at (pos)
5747 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5749 (defun org-activate-plain-links (limit)
5750 "Run through the buffer and add overlays to links."
5751 (let (f hl)
5752 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5753 (not (org-in-src-block-p)))
5754 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5755 (setq f (get-text-property (match-beginning 0) 'face))
5756 (setq hl (org-match-string-no-properties 0))
5757 (if (or (eq f 'org-tag)
5758 (and (listp f) (memq 'org-tag f)))
5760 (add-text-properties (match-beginning 0) (match-end 0)
5761 (list 'mouse-face 'highlight
5762 'face 'org-link
5763 'htmlize-link `(:uri ,hl)
5764 'keymap org-mouse-map))
5765 (org-rear-nonsticky-at (match-end 0)))
5766 t)))
5768 (defun org-activate-code (limit)
5769 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5770 (progn
5771 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5772 (remove-text-properties (match-beginning 0) (match-end 0)
5773 '(display t invisible t intangible t))
5774 t)))
5776 (defcustom org-src-fontify-natively nil
5777 "When non-nil, fontify code in code blocks."
5778 :type 'boolean
5779 :version "24.1"
5780 :group 'org-appearance
5781 :group 'org-babel)
5783 (defcustom org-allow-promoting-top-level-subtree nil
5784 "When non-nil, allow promoting a top level subtree.
5785 The leading star of the top level headline will be replaced
5786 by a #."
5787 :type 'boolean
5788 :version "24.1"
5789 :group 'org-appearance)
5791 (defun org-fontify-meta-lines-and-blocks (limit)
5792 (condition-case nil
5793 (org-fontify-meta-lines-and-blocks-1 limit)
5794 (error (message "org-mode fontification error"))))
5796 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5797 "Fontify #+ lines and blocks."
5798 (let ((case-fold-search t))
5799 (if (re-search-forward
5800 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5801 limit t)
5802 (let ((beg (match-beginning 0))
5803 (block-start (match-end 0))
5804 (block-end nil)
5805 (lang (match-string 7))
5806 (beg1 (line-beginning-position 2))
5807 (dc1 (downcase (match-string 2)))
5808 (dc3 (downcase (match-string 3)))
5809 end end1 quoting block-type ovl)
5810 (cond
5811 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5812 ;; a single line of backend-specific content
5813 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5814 (remove-text-properties (match-beginning 0) (match-end 0)
5815 '(display t invisible t intangible t))
5816 (add-text-properties (match-beginning 1) (match-end 3)
5817 '(font-lock-fontified t face org-meta-line))
5818 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5819 '(font-lock-fontified t face org-block))
5820 ; for backend-specific code
5822 ((and (match-end 4) (equal dc3 "+begin"))
5823 ;; Truly a block
5824 (setq block-type (downcase (match-string 5))
5825 quoting (member block-type org-protecting-blocks))
5826 (when (re-search-forward
5827 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5828 nil t) ;; on purpose, we look further than LIMIT
5829 (setq end (min (point-max) (match-end 0))
5830 end1 (min (point-max) (1- (match-beginning 0))))
5831 (setq block-end (match-beginning 0))
5832 (when quoting
5833 (remove-text-properties beg end
5834 '(display t invisible t intangible t)))
5835 (add-text-properties
5836 beg end
5837 '(font-lock-fontified t font-lock-multiline t))
5838 (add-text-properties beg beg1 '(face org-meta-line))
5839 (add-text-properties end1 (min (point-max) (1+ end))
5840 '(face org-meta-line)) ; for end_src
5841 (cond
5842 ((and lang (not (string= lang "")) org-src-fontify-natively)
5843 (org-src-font-lock-fontify-block lang block-start block-end)
5844 ;; remove old background overlays
5845 (mapc (lambda (ov)
5846 (if (eq (overlay-get ov 'face) 'org-block-background)
5847 (delete-overlay ov)))
5848 (overlays-at (/ (+ beg1 block-end) 2)))
5849 ;; add a background overlay
5850 (setq ovl (make-overlay beg1 block-end))
5851 (overlay-put ovl 'face 'org-block-background)
5852 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5853 (quoting
5854 (add-text-properties beg1 (min (point-max) (1+ end1))
5855 '(face org-block))) ; end of source block
5856 ((not org-fontify-quote-and-verse-blocks))
5857 ((string= block-type "quote")
5858 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5859 ((string= block-type "verse")
5860 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5861 (add-text-properties beg beg1 '(face org-block-begin-line))
5862 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5863 '(face org-block-end-line))
5865 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5866 (add-text-properties
5867 beg (match-end 3)
5868 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5869 '(font-lock-fontified t invisible t)
5870 '(font-lock-fontified t face org-document-info-keyword)))
5871 (add-text-properties
5872 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5873 (if (string-equal dc1 "+title:")
5874 '(font-lock-fontified t face org-document-title)
5875 '(font-lock-fontified t face org-document-info))))
5876 ((or (equal dc1 "+results")
5877 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5878 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5879 "+call:" "+header:" "+headers:" "+name:"))
5880 (and (match-end 4) (equal dc3 "+attr")))
5881 (add-text-properties
5882 beg (match-end 0)
5883 '(font-lock-fontified t face org-meta-line))
5885 ((member dc3 '(" " ""))
5886 (add-text-properties
5887 beg (match-end 0)
5888 '(font-lock-fontified t face font-lock-comment-face)))
5889 ((not (member (char-after beg) '(?\ ?\t)))
5890 ;; just any other in-buffer setting, but not indented
5891 (add-text-properties
5892 beg (match-end 0)
5893 '(font-lock-fontified t face org-meta-line))
5895 (t nil))))))
5897 (defun org-activate-angle-links (limit)
5898 "Run through the buffer and add overlays to links."
5899 (if (and (re-search-forward org-angle-link-re limit t)
5900 (not (org-in-src-block-p)))
5901 (progn
5902 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5903 (add-text-properties (match-beginning 0) (match-end 0)
5904 (list 'mouse-face 'highlight
5905 'keymap org-mouse-map))
5906 (org-rear-nonsticky-at (match-end 0))
5907 t)))
5909 (defun org-activate-footnote-links (limit)
5910 "Run through the buffer and add overlays to footnotes."
5911 (let ((fn (org-footnote-next-reference-or-definition limit)))
5912 (when fn
5913 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5914 (org-remove-flyspell-overlays-in beg end)
5915 (add-text-properties beg end
5916 (list 'mouse-face 'highlight
5917 'keymap org-mouse-map
5918 'help-echo
5919 (if (= (point-at-bol) beg)
5920 "Footnote definition"
5921 "Footnote reference")
5922 'font-lock-fontified t
5923 'font-lock-multiline t
5924 'face 'org-footnote))))))
5926 (defun org-activate-bracket-links (limit)
5927 "Run through the buffer and add overlays to bracketed links."
5928 (if (and (re-search-forward org-bracket-link-regexp limit t)
5929 (not (org-in-src-block-p)))
5930 (let* ((hl (org-match-string-no-properties 1))
5931 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5932 (ip (org-maybe-intangible
5933 (list 'invisible 'org-link
5934 'keymap org-mouse-map 'mouse-face 'highlight
5935 'font-lock-multiline t 'help-echo help
5936 'htmlize-link `(:uri ,hl))))
5937 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5938 'font-lock-multiline t 'help-echo help
5939 'htmlize-link `(:uri ,hl))))
5940 ;; We need to remove the invisible property here. Table narrowing
5941 ;; may have made some of this invisible.
5942 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5943 (remove-text-properties (match-beginning 0) (match-end 0)
5944 '(invisible nil))
5945 (if (match-end 3)
5946 (progn
5947 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5948 (org-rear-nonsticky-at (match-beginning 3))
5949 (add-text-properties (match-beginning 3) (match-end 3) vp)
5950 (org-rear-nonsticky-at (match-end 3))
5951 (add-text-properties (match-end 3) (match-end 0) ip)
5952 (org-rear-nonsticky-at (match-end 0)))
5953 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5954 (org-rear-nonsticky-at (match-beginning 1))
5955 (add-text-properties (match-beginning 1) (match-end 1) vp)
5956 (org-rear-nonsticky-at (match-end 1))
5957 (add-text-properties (match-end 1) (match-end 0) ip)
5958 (org-rear-nonsticky-at (match-end 0)))
5959 t)))
5961 (defun org-activate-dates (limit)
5962 "Run through the buffer and add overlays to dates."
5963 (if (and (re-search-forward org-tsr-regexp-both limit t)
5964 (not (equal (char-before (match-beginning 0)) 91)))
5965 (progn
5966 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5967 (add-text-properties (match-beginning 0) (match-end 0)
5968 (list 'mouse-face 'highlight
5969 'keymap org-mouse-map))
5970 (org-rear-nonsticky-at (match-end 0))
5971 (when org-display-custom-times
5972 (if (match-end 3)
5973 (org-display-custom-time (match-beginning 3) (match-end 3)))
5974 (org-display-custom-time (match-beginning 1) (match-end 1)))
5975 t)))
5977 (defvar org-target-link-regexp nil
5978 "Regular expression matching radio targets in plain text.")
5979 (make-variable-buffer-local 'org-target-link-regexp)
5980 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5981 "Regular expression matching a link target.")
5982 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5983 "Regular expression matching a radio target.")
5984 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5985 "Regular expression matching any target.")
5987 (defun org-activate-target-links (limit)
5988 "Run through the buffer and add overlays to target matches."
5989 (when org-target-link-regexp
5990 (let ((case-fold-search t))
5991 (if (re-search-forward org-target-link-regexp limit t)
5992 (progn
5993 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5994 (add-text-properties (match-beginning 0) (match-end 0)
5995 (list 'mouse-face 'highlight
5996 'keymap org-mouse-map
5997 'help-echo "Radio target link"
5998 'org-linked-text t))
5999 (org-rear-nonsticky-at (match-end 0))
6000 t)))))
6002 (defun org-update-radio-target-regexp ()
6003 "Find all radio targets in this file and update the regular expression."
6004 (interactive)
6005 (when (memq 'radio org-activate-links)
6006 (setq org-target-link-regexp
6007 (org-make-target-link-regexp (org-all-targets 'radio)))
6008 (org-restart-font-lock)))
6010 (defun org-hide-wide-columns (limit)
6011 (let (s e)
6012 (setq s (text-property-any (point) (or limit (point-max))
6013 'org-cwidth t))
6014 (when s
6015 (setq e (next-single-property-change s 'org-cwidth))
6016 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6017 (goto-char e)
6018 t)))
6020 (defvar org-latex-and-related-regexp nil
6021 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6022 (defvar org-match-substring-regexp)
6023 (defvar org-match-substring-with-braces-regexp)
6025 (defun org-compute-latex-and-related-regexp ()
6026 "Compute regular expression for LaTeX, entities and sub/superscript.
6027 Result depends on variable `org-highlight-latex-and-related'."
6028 (org-set-local
6029 'org-latex-and-related-regexp
6030 (let* ((re-sub
6031 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6032 ((eq org-use-sub-superscripts '{})
6033 (list org-match-substring-with-braces-regexp))
6034 (org-use-sub-superscripts (list org-match-substring-regexp))))
6035 (re-latex
6036 (when (memq 'latex org-highlight-latex-and-related)
6037 (let ((matchers (plist-get org-format-latex-options :matchers)))
6038 (delq nil
6039 (mapcar (lambda (x)
6040 (and (member (car x) matchers) (nth 1 x)))
6041 org-latex-regexps)))))
6042 (re-entities
6043 (when (memq 'entities org-highlight-latex-and-related)
6044 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6045 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6047 (defun org-do-latex-and-related (limit)
6048 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6049 LIMIT bounds the search for syntax to highlight. Stop at first
6050 highlighted object, if any. Return t if some highlighting was
6051 done, nil otherwise."
6052 (when (org-string-nw-p org-latex-and-related-regexp)
6053 (catch 'found
6054 (while (re-search-forward org-latex-and-related-regexp limit t)
6055 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6056 'face))
6057 '(org-code org-verbatim underline))
6058 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6059 '(?_ ?^))
6061 0)))
6062 (font-lock-prepend-text-property
6063 (+ offset (match-beginning 0)) (match-end 0)
6064 'face 'org-latex-and-related)
6065 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6066 '(font-lock-multiline t)))
6067 (throw 'found t)))
6068 nil)))
6070 (defun org-restart-font-lock ()
6071 "Restart `font-lock-mode', to force refontification."
6072 (when (and (boundp 'font-lock-mode) font-lock-mode)
6073 (font-lock-mode -1)
6074 (font-lock-mode 1)))
6076 (defun org-all-targets (&optional radio)
6077 "Return a list of all targets in this file.
6078 When optional argument RADIO is non-nil, only find radio
6079 targets."
6080 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6081 (save-excursion
6082 (goto-char (point-min))
6083 (while (re-search-forward re nil t)
6084 ;; Make sure point is really within the object.
6085 (backward-char)
6086 (let ((obj (org-element-context)))
6087 (when (memq (org-element-type obj) '(radio-target target))
6088 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6089 rtn)))
6091 (defun org-make-target-link-regexp (targets)
6092 "Make regular expression matching all strings in TARGETS.
6093 The regular expression finds the targets also if there is a line break
6094 between words."
6095 (and targets
6096 (concat
6097 "\\<\\("
6098 (mapconcat
6099 (lambda (x)
6100 (setq x (regexp-quote x))
6101 (while (string-match " +" x)
6102 (setq x (replace-match "\\s-+" t t x)))
6104 targets
6105 "\\|")
6106 "\\)\\>")))
6108 (defun org-activate-tags (limit)
6109 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6110 (progn
6111 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6112 (add-text-properties (match-beginning 1) (match-end 1)
6113 (list 'mouse-face 'highlight
6114 'keymap org-mouse-map))
6115 (org-rear-nonsticky-at (match-end 1))
6116 t)))
6118 (defun org-outline-level ()
6119 "Compute the outline level of the heading at point.
6120 If this is called at a normal headline, the level is the number of stars.
6121 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6122 (save-excursion
6123 (if (not (condition-case nil
6124 (org-back-to-heading t)
6125 (error nil)))
6127 (looking-at org-outline-regexp)
6128 (1- (- (match-end 0) (match-beginning 0))))))
6130 (defvar org-font-lock-keywords nil)
6132 (defsubst org-re-property (property &optional literal)
6133 "Return a regexp matching a PROPERTY line.
6134 Match group 3 will be set to the value if it exists."
6135 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6136 (if literal property (regexp-quote property))
6137 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6139 (defconst org-property-re
6140 (org-re-property ".*?" 'literal)
6141 "Regular expression matching a property line.
6142 There are four matching groups:
6143 1: :PROPKEY: including the leading and trailing colon,
6144 2: PROPKEY without the leading and trailing colon,
6145 3: PROPVAL without leading or trailing spaces,
6146 4: the indentation of the current line,
6147 5: trailing whitespace.")
6149 (defvar org-font-lock-hook nil
6150 "Functions to be called for special font lock stuff.")
6152 (defvar org-font-lock-set-keywords-hook nil
6153 "Functions that can manipulate `org-font-lock-extra-keywords'.
6154 This is called after `org-font-lock-extra-keywords' is defined, but before
6155 it is installed to be used by font lock. This can be useful if something
6156 needs to be inserted at a specific position in the font-lock sequence.")
6158 (defun org-font-lock-hook (limit)
6159 "Run `org-font-lock-hook' within LIMIT."
6160 (run-hook-with-args 'org-font-lock-hook limit))
6162 (defun org-set-font-lock-defaults ()
6163 "Set font lock defaults for the current buffer."
6164 (let* ((em org-fontify-emphasized-text)
6165 (lk org-activate-links)
6166 (org-font-lock-extra-keywords
6167 (list
6168 ;; Call the hook
6169 '(org-font-lock-hook)
6170 ;; Headlines
6171 `(,(if org-fontify-whole-heading-line
6172 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6173 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6174 (1 (org-get-level-face 1))
6175 (2 (org-get-level-face 2))
6176 (3 (org-get-level-face 3)))
6177 ;; Table lines
6178 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6179 (1 'org-table t))
6180 ;; Table internals
6181 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6182 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6183 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6184 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6185 ;; Drawers
6186 (list org-drawer-regexp '(0 'org-special-keyword t))
6187 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6188 ;; Properties
6189 (list org-property-re
6190 '(1 'org-special-keyword t)
6191 '(3 'org-property-value t))
6192 ;; Links
6193 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6194 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6195 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6196 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6197 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6198 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6199 (if (memq 'footnote lk) '(org-activate-footnote-links))
6200 ;; Targets.
6201 (list org-any-target-regexp '(0 'org-target t))
6202 ;; Diary sexps.
6203 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6204 ;; Macro
6205 '("{{{.+}}}" (0 'org-macro t))
6206 '(org-hide-wide-columns (0 nil append))
6207 ;; TODO keyword
6208 (list (format org-heading-keyword-regexp-format
6209 org-todo-regexp)
6210 '(2 (org-get-todo-face 2) t))
6211 ;; DONE
6212 (if org-fontify-done-headline
6213 (list (format org-heading-keyword-regexp-format
6214 (concat
6215 "\\(?:"
6216 (mapconcat 'regexp-quote org-done-keywords "\\|")
6217 "\\)"))
6218 '(2 'org-headline-done t))
6219 nil)
6220 ;; Priorities
6221 '(org-font-lock-add-priority-faces)
6222 ;; Tags
6223 '(org-font-lock-add-tag-faces)
6224 ;; Tags groups
6225 (if (and org-group-tags org-tag-groups-alist)
6226 (list (concat org-outline-regexp-bol ".+\\(:"
6227 (regexp-opt (mapcar 'car org-tag-groups-alist))
6228 ":\\).*$")
6229 '(1 'org-tag-group prepend)))
6230 ;; Special keywords
6231 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6232 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6233 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6234 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6235 ;; Emphasis
6236 (if em
6237 (if (featurep 'xemacs)
6238 '(org-do-emphasis-faces (0 nil append))
6239 '(org-do-emphasis-faces)))
6240 ;; Checkboxes
6241 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6242 1 'org-checkbox prepend)
6243 (if (cdr (assq 'checkbox org-list-automatic-rules))
6244 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6245 (0 (org-get-checkbox-statistics-face) t)))
6246 ;; Description list items
6247 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6248 1 'org-list-dt prepend)
6249 ;; ARCHIVEd headings
6250 (list (concat
6251 org-outline-regexp-bol
6252 "\\(.*:" org-archive-tag ":.*\\)")
6253 '(1 'org-archived prepend))
6254 ;; Specials
6255 '(org-do-latex-and-related)
6256 '(org-fontify-entities)
6257 '(org-raise-scripts)
6258 ;; Code
6259 '(org-activate-code (1 'org-code t))
6260 ;; COMMENT
6261 (list (format org-heading-keyword-regexp-format
6262 (concat "\\("
6263 org-comment-string "\\|" org-quote-string
6264 "\\)"))
6265 '(2 'org-special-keyword t))
6266 ;; Blocks and meta lines
6267 '(org-fontify-meta-lines-and-blocks))))
6268 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6269 (run-hooks 'org-font-lock-set-keywords-hook)
6270 ;; Now set the full font-lock-keywords
6271 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6272 (org-set-local 'font-lock-defaults
6273 '(org-font-lock-keywords t nil nil backward-paragraph))
6274 (kill-local-variable 'font-lock-keywords) nil))
6276 (defun org-toggle-pretty-entities ()
6277 "Toggle the composition display of entities as UTF8 characters."
6278 (interactive)
6279 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6280 (org-restart-font-lock)
6281 (if org-pretty-entities
6282 (message "Entities are now displayed as UTF8 characters")
6283 (save-restriction
6284 (widen)
6285 (org-decompose-region (point-min) (point-max))
6286 (message "Entities are now displayed as plain text"))))
6288 (defvar org-custom-properties-overlays nil
6289 "List of overlays used for custom properties.")
6290 (make-variable-buffer-local 'org-custom-properties-overlays)
6292 (defun org-toggle-custom-properties-visibility ()
6293 "Display or hide properties in `org-custom-properties'."
6294 (interactive)
6295 (if org-custom-properties-overlays
6296 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6297 (setq org-custom-properties-overlays nil))
6298 (unless (not org-custom-properties)
6299 (save-excursion
6300 (save-restriction
6301 (widen)
6302 (goto-char (point-min))
6303 (while (re-search-forward org-property-re nil t)
6304 (mapc (lambda(p)
6305 (when (equal p (substring (match-string 1) 1 -1))
6306 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6307 (overlay-put o 'invisible t)
6308 (overlay-put o 'org-custom-property t)
6309 (push o org-custom-properties-overlays))))
6310 org-custom-properties)))))))
6312 (defun org-fontify-entities (limit)
6313 "Find an entity to fontify."
6314 (let (ee)
6315 (when org-pretty-entities
6316 (catch 'match
6317 (while (re-search-forward
6318 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6319 limit t)
6320 (if (and (not (org-in-indented-comment-line))
6321 (setq ee (org-entity-get (match-string 1)))
6322 (= (length (nth 6 ee)) 1))
6323 (let*
6324 ((end (if (equal (match-string 2) "{}")
6325 (match-end 2)
6326 (match-end 1))))
6327 (add-text-properties
6328 (match-beginning 0) end
6329 (list 'font-lock-fontified t))
6330 (compose-region (match-beginning 0) end
6331 (nth 6 ee) nil)
6332 (backward-char 1)
6333 (throw 'match t))))
6334 nil))))
6336 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6337 "Fontify string S like in Org-mode."
6338 (with-temp-buffer
6339 (insert s)
6340 (let ((org-odd-levels-only odd-levels))
6341 (org-mode)
6342 (font-lock-fontify-buffer)
6343 (buffer-string))))
6345 (defvar org-m nil)
6346 (defvar org-l nil)
6347 (defvar org-f nil)
6348 (defun org-get-level-face (n)
6349 "Get the right face for match N in font-lock matching of headlines."
6350 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6351 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6352 (if org-cycle-level-faces
6353 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6354 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6355 (cond
6356 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6357 ((eq n 2) org-f)
6358 (t (if org-level-color-stars-only nil org-f))))
6361 (defun org-get-todo-face (kwd)
6362 "Get the right face for a TODO keyword KWD.
6363 If KWD is a number, get the corresponding match group."
6364 (if (numberp kwd) (setq kwd (match-string kwd)))
6365 (or (org-face-from-face-or-color
6366 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6367 (and (member kwd org-done-keywords) 'org-done)
6368 'org-todo))
6370 (defun org-face-from-face-or-color (context inherit face-or-color)
6371 "Create a face list that inherits INHERIT, but sets the foreground color.
6372 When FACE-OR-COLOR is not a string, just return it."
6373 (if (stringp face-or-color)
6374 (list :inherit inherit
6375 (cdr (assoc context org-faces-easy-properties))
6376 face-or-color)
6377 face-or-color))
6379 (defun org-font-lock-add-tag-faces (limit)
6380 "Add the special tag faces."
6381 (when (and org-tag-faces org-tags-special-faces-re)
6382 (while (re-search-forward org-tags-special-faces-re limit t)
6383 (add-text-properties (match-beginning 1) (match-end 1)
6384 (list 'face (org-get-tag-face 1)
6385 'font-lock-fontified t))
6386 (backward-char 1))))
6388 (defun org-font-lock-add-priority-faces (limit)
6389 "Add the special priority faces."
6390 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6391 (when (save-match-data (org-at-heading-p))
6392 (add-text-properties
6393 (match-beginning 0) (match-end 0)
6394 (list 'face (or (org-face-from-face-or-color
6395 'priority 'org-priority
6396 (cdr (assoc (char-after (match-beginning 1))
6397 org-priority-faces)))
6398 'org-priority)
6399 'font-lock-fontified t)))))
6401 (defun org-get-tag-face (kwd)
6402 "Get the right face for a TODO keyword KWD.
6403 If KWD is a number, get the corresponding match group."
6404 (if (numberp kwd) (setq kwd (match-string kwd)))
6405 (or (org-face-from-face-or-color
6406 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6407 'org-tag))
6409 (defun org-unfontify-region (beg end &optional maybe_loudly)
6410 "Remove fontification and activation overlays from links."
6411 (font-lock-default-unfontify-region beg end)
6412 (let* ((buffer-undo-list t)
6413 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6414 (inhibit-modification-hooks t)
6415 deactivate-mark buffer-file-name buffer-file-truename)
6416 (org-decompose-region beg end)
6417 (remove-text-properties beg end
6418 '(mouse-face t keymap t org-linked-text t
6419 invisible t intangible t
6420 org-no-flyspell t org-emphasis t))
6421 (org-remove-font-lock-display-properties beg end)))
6423 (defconst org-script-display '(((raise -0.3) (height 0.7))
6424 ((raise 0.3) (height 0.7))
6425 ((raise -0.5))
6426 ((raise 0.5)))
6427 "Display properties for showing superscripts and subscripts.")
6429 (defun org-remove-font-lock-display-properties (beg end)
6430 "Remove specific display properties that have been added by font lock.
6431 The will remove the raise properties that are used to show superscripts
6432 and subscripts."
6433 (let (next prop)
6434 (while (< beg end)
6435 (setq next (next-single-property-change beg 'display nil end)
6436 prop (get-text-property beg 'display))
6437 (if (member prop org-script-display)
6438 (put-text-property beg next 'display nil))
6439 (setq beg next))))
6441 (defun org-raise-scripts (limit)
6442 "Add raise properties to sub/superscripts."
6443 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6444 (if (re-search-forward
6445 (if (eq org-use-sub-superscripts t)
6446 org-match-substring-regexp
6447 org-match-substring-with-braces-regexp)
6448 limit t)
6449 (let* ((pos (point)) table-p comment-p
6450 (mpos (match-beginning 3))
6451 (emph-p (get-text-property mpos 'org-emphasis))
6452 (link-p (get-text-property mpos 'mouse-face))
6453 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6454 (goto-char (point-at-bol))
6455 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6456 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6457 (goto-char pos)
6458 ;; Handle a_b^c
6459 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6460 (if (or comment-p emph-p link-p keyw-p)
6462 (put-text-property (match-beginning 3) (match-end 0)
6463 'display
6464 (if (equal (char-after (match-beginning 2)) ?^)
6465 (nth (if table-p 3 1) org-script-display)
6466 (nth (if table-p 2 0) org-script-display)))
6467 (add-text-properties (match-beginning 2) (match-end 2)
6468 (list 'invisible t
6469 'org-dwidth t 'org-dwidth-n 1))
6470 (if (and (eq (char-after (match-beginning 3)) ?{)
6471 (eq (char-before (match-end 3)) ?}))
6472 (progn
6473 (add-text-properties
6474 (match-beginning 3) (1+ (match-beginning 3))
6475 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6476 (add-text-properties
6477 (1- (match-end 3)) (match-end 3)
6478 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6479 t)))))
6481 ;;;; Visibility cycling, including org-goto and indirect buffer
6483 ;;; Cycling
6485 (defvar org-cycle-global-status nil)
6486 (make-variable-buffer-local 'org-cycle-global-status)
6487 (put 'org-cycle-global-status 'org-state t)
6488 (defvar org-cycle-subtree-status nil)
6489 (make-variable-buffer-local 'org-cycle-subtree-status)
6490 (put 'org-cycle-subtree-status 'org-state t)
6492 (defvar org-inlinetask-min-level)
6494 (defun org-unlogged-message (&rest args)
6495 "Display a message, but avoid logging it in the *Messages* buffer."
6496 (let ((message-log-max nil))
6497 (apply 'message args)))
6499 ;;;###autoload
6500 (defun org-cycle (&optional arg)
6501 "TAB-action and visibility cycling for Org-mode.
6503 This is the command invoked in Org-mode by the TAB key. Its main purpose
6504 is outline visibility cycling, but it also invokes other actions
6505 in special contexts.
6507 - When this function is called with a prefix argument, rotate the entire
6508 buffer through 3 states (global cycling)
6509 1. OVERVIEW: Show only top-level headlines.
6510 2. CONTENTS: Show all headlines of all levels, but no body text.
6511 3. SHOW ALL: Show everything.
6512 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6513 determined by the variable `org-startup-folded', and by any VISIBILITY
6514 properties in the buffer.
6515 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6516 including any drawers.
6518 - When inside a table, re-align the table and move to the next field.
6520 - When point is at the beginning of a headline, rotate the subtree started
6521 by this line through 3 different states (local cycling)
6522 1. FOLDED: Only the main headline is shown.
6523 2. CHILDREN: The main headline and the direct children are shown.
6524 From this state, you can move to one of the children
6525 and zoom in further.
6526 3. SUBTREE: Show the entire subtree, including body text.
6527 If there is no subtree, switch directly from CHILDREN to FOLDED.
6529 - When point is at the beginning of an empty headline and the variable
6530 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6531 of the headline by demoting and promoting it to likely levels. This
6532 speeds up creation document structure by pressing TAB once or several
6533 times right after creating a new headline.
6535 - When there is a numeric prefix, go up to a heading with level ARG, do
6536 a `show-subtree' and return to the previous cursor position. If ARG
6537 is negative, go up that many levels.
6539 - When point is not at the beginning of a headline, execute the global
6540 binding for TAB, which is re-indenting the line. See the option
6541 `org-cycle-emulate-tab' for details.
6543 - Special case: if point is at the beginning of the buffer and there is
6544 no headline in line 1, this function will act as if called with prefix arg
6545 (C-u TAB, same as S-TAB) also when called without prefix arg.
6546 But only if also the variable `org-cycle-global-at-bob' is t."
6547 (interactive "P")
6548 (org-load-modules-maybe)
6549 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6550 (and org-cycle-level-after-item/entry-creation
6551 (or (org-cycle-level)
6552 (org-cycle-item-indentation))))
6553 (let* ((limit-level
6554 (or org-cycle-max-level
6555 (and (boundp 'org-inlinetask-min-level)
6556 org-inlinetask-min-level
6557 (1- org-inlinetask-min-level))))
6558 (nstars (and limit-level
6559 (if org-odd-levels-only
6560 (and limit-level (1- (* limit-level 2)))
6561 limit-level)))
6562 (org-outline-regexp
6563 (if (not (derived-mode-p 'org-mode))
6564 outline-regexp
6565 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6566 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6567 (not (looking-at org-outline-regexp))))
6568 (org-cycle-hook
6569 (if bob-special
6570 (delq 'org-optimize-window-after-visibility-change
6571 (copy-sequence org-cycle-hook))
6572 org-cycle-hook))
6573 (pos (point)))
6575 (if (or bob-special (equal arg '(4)))
6576 ;; special case: use global cycling
6577 (setq arg t))
6579 (cond
6581 ((equal arg '(16))
6582 (setq last-command 'dummy)
6583 (org-set-startup-visibility)
6584 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6586 ((equal arg '(64))
6587 (show-all)
6588 (org-unlogged-message "Entire buffer visible, including drawers"))
6590 ;; Table: enter it or move to the next field.
6591 ((org-at-table-p 'any)
6592 (if (org-at-table.el-p)
6593 (message "Use C-c ' to edit table.el tables")
6594 (if arg (org-table-edit-field t)
6595 (org-table-justify-field-maybe)
6596 (call-interactively 'org-table-next-field))))
6598 ((run-hook-with-args-until-success
6599 'org-tab-after-check-for-table-hook))
6601 ;; Global cycling: delegate to `org-cycle-internal-global'.
6602 ((eq arg t) (org-cycle-internal-global))
6604 ;; Drawers: delegate to `org-flag-drawer'.
6605 ((and org-drawers org-drawer-regexp
6606 (save-excursion
6607 (beginning-of-line 1)
6608 (looking-at org-drawer-regexp)))
6609 (org-flag-drawer ; toggle block visibility
6610 (not (get-char-property (match-end 0) 'invisible))))
6612 ;; Show-subtree, ARG levels up from here.
6613 ((integerp arg)
6614 (save-excursion
6615 (org-back-to-heading)
6616 (outline-up-heading (if (< arg 0) (- arg)
6617 (- (funcall outline-level) arg)))
6618 (org-show-subtree)))
6620 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6621 ((and (featurep 'org-inlinetask)
6622 (org-inlinetask-at-task-p)
6623 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6624 (org-inlinetask-toggle-visibility))
6626 ((org-try-cdlatex-tab))
6628 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6629 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6630 (save-excursion (beginning-of-line 1)
6631 (looking-at org-outline-regexp)))
6632 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6633 (org-cycle-internal-local))
6635 ;; From there: TAB emulation and template completion.
6636 (buffer-read-only (org-back-to-heading))
6638 ((run-hook-with-args-until-success
6639 'org-tab-after-check-for-cycling-hook))
6641 ((org-try-structure-completion))
6643 ((run-hook-with-args-until-success
6644 'org-tab-before-tab-emulation-hook))
6646 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6647 (or (not (bolp))
6648 (not (looking-at org-outline-regexp))))
6649 (call-interactively (global-key-binding "\t")))
6651 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6652 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6653 (or (and (eq org-cycle-emulate-tab 'white)
6654 (= (match-end 0) (point-at-eol)))
6655 (and (eq org-cycle-emulate-tab 'whitestart)
6656 (>= (match-end 0) pos))))
6658 (eq org-cycle-emulate-tab t))
6659 (call-interactively (global-key-binding "\t")))
6661 (t (save-excursion
6662 (org-back-to-heading)
6663 (org-cycle)))))))
6665 (defun org-cycle-internal-global ()
6666 "Do the global cycling action."
6667 ;; Hack to avoid display of messages for .org attachments in Gnus
6668 (let ((ga (string-match "\\*fontification" (buffer-name))))
6669 (cond
6670 ((and (eq last-command this-command)
6671 (eq org-cycle-global-status 'overview))
6672 ;; We just created the overview - now do table of contents
6673 ;; This can be slow in very large buffers, so indicate action
6674 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6675 (unless ga (org-unlogged-message "CONTENTS..."))
6676 (org-content)
6677 (unless ga (org-unlogged-message "CONTENTS...done"))
6678 (setq org-cycle-global-status 'contents)
6679 (run-hook-with-args 'org-cycle-hook 'contents))
6681 ((and (eq last-command this-command)
6682 (eq org-cycle-global-status 'contents))
6683 ;; We just showed the table of contents - now show everything
6684 (run-hook-with-args 'org-pre-cycle-hook 'all)
6685 (show-all)
6686 (unless ga (org-unlogged-message "SHOW ALL"))
6687 (setq org-cycle-global-status 'all)
6688 (run-hook-with-args 'org-cycle-hook 'all))
6691 ;; Default action: go to overview
6692 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6693 (org-overview)
6694 (unless ga (org-unlogged-message "OVERVIEW"))
6695 (setq org-cycle-global-status 'overview)
6696 (run-hook-with-args 'org-cycle-hook 'overview)))))
6698 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6700 (defun org-cycle-internal-local ()
6701 "Do the local cycling action."
6702 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6703 ;; First, determine end of headline (EOH), end of subtree or item
6704 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6705 (save-excursion
6706 (if (org-at-item-p)
6707 (progn
6708 (beginning-of-line)
6709 (setq struct (org-list-struct))
6710 (setq eoh (point-at-eol))
6711 (setq eos (org-list-get-item-end-before-blank (point) struct))
6712 (setq has-children (org-list-has-child-p (point) struct)))
6713 (org-back-to-heading)
6714 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6715 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6716 (setq has-children
6717 (or (save-excursion
6718 (let ((level (funcall outline-level)))
6719 (outline-next-heading)
6720 (and (org-at-heading-p t)
6721 (> (funcall outline-level) level))))
6722 (save-excursion
6723 (org-list-search-forward (org-item-beginning-re) eos t)))))
6724 ;; Determine end invisible part of buffer (EOL)
6725 (beginning-of-line 2)
6726 ;; XEmacs doesn't have `next-single-char-property-change'
6727 (if (featurep 'xemacs)
6728 (while (and (not (eobp)) ;; this is like `next-line'
6729 (get-char-property (1- (point)) 'invisible))
6730 (beginning-of-line 2))
6731 (while (and (not (eobp)) ;; this is like `next-line'
6732 (get-char-property (1- (point)) 'invisible))
6733 (goto-char (next-single-char-property-change (point) 'invisible))
6734 (and (eolp) (beginning-of-line 2))))
6735 (setq eol (point)))
6736 ;; Find out what to do next and set `this-command'
6737 (cond
6738 ((= eos eoh)
6739 ;; Nothing is hidden behind this heading
6740 (unless (org-before-first-heading-p)
6741 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6742 (org-unlogged-message "EMPTY ENTRY")
6743 (setq org-cycle-subtree-status nil)
6744 (save-excursion
6745 (goto-char eos)
6746 (outline-next-heading)
6747 (if (outline-invisible-p) (org-flag-heading nil))))
6748 ((and (or (>= eol eos)
6749 (not (string-match "\\S-" (buffer-substring eol eos))))
6750 (or has-children
6751 (not (setq children-skipped
6752 org-cycle-skip-children-state-if-no-children))))
6753 ;; Entire subtree is hidden in one line: children view
6754 (unless (org-before-first-heading-p)
6755 (run-hook-with-args 'org-pre-cycle-hook 'children))
6756 (if (org-at-item-p)
6757 (org-list-set-item-visibility (point-at-bol) struct 'children)
6758 (org-show-entry)
6759 (org-with-limited-levels (show-children))
6760 ;; FIXME: This slows down the func way too much.
6761 ;; How keep drawers hidden in subtree anyway?
6762 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6763 ;; (org-cycle-hide-drawers 'subtree))
6765 ;; Fold every list in subtree to top-level items.
6766 (when (eq org-cycle-include-plain-lists 'integrate)
6767 (save-excursion
6768 (org-back-to-heading)
6769 (while (org-list-search-forward (org-item-beginning-re) eos t)
6770 (beginning-of-line 1)
6771 (let* ((struct (org-list-struct))
6772 (prevs (org-list-prevs-alist struct))
6773 (end (org-list-get-bottom-point struct)))
6774 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6775 (org-list-get-all-items (point) struct prevs))
6776 (goto-char (if (< end eos) end eos)))))))
6777 (org-unlogged-message "CHILDREN")
6778 (save-excursion
6779 (goto-char eos)
6780 (outline-next-heading)
6781 (if (outline-invisible-p) (org-flag-heading nil)))
6782 (setq org-cycle-subtree-status 'children)
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-cycle-hook 'children)))
6785 ((or children-skipped
6786 (and (eq last-command this-command)
6787 (eq org-cycle-subtree-status 'children)))
6788 ;; We just showed the children, or no children are there,
6789 ;; now show everything.
6790 (unless (org-before-first-heading-p)
6791 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6792 (outline-flag-region eoh eos nil)
6793 (org-unlogged-message
6794 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6795 (setq org-cycle-subtree-status 'subtree)
6796 (unless (org-before-first-heading-p)
6797 (run-hook-with-args 'org-cycle-hook 'subtree)))
6799 ;; Default action: hide the subtree.
6800 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6801 (outline-flag-region eoh eos t)
6802 (org-unlogged-message "FOLDED")
6803 (setq org-cycle-subtree-status 'folded)
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-cycle-hook 'folded))))))
6807 ;;;###autoload
6808 (defun org-global-cycle (&optional arg)
6809 "Cycle the global visibility. For details see `org-cycle'.
6810 With \\[universal-argument] prefix arg, switch to startup visibility.
6811 With a numeric prefix, show all headlines up to that level."
6812 (interactive "P")
6813 (let ((org-cycle-include-plain-lists
6814 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6815 (cond
6816 ((integerp arg)
6817 (show-all)
6818 (hide-sublevels arg)
6819 (setq org-cycle-global-status 'contents))
6820 ((equal arg '(4))
6821 (org-set-startup-visibility)
6822 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6824 (org-cycle '(4))))))
6826 (defun org-set-startup-visibility ()
6827 "Set the visibility required by startup options and properties."
6828 (cond
6829 ((eq org-startup-folded t)
6830 (org-overview))
6831 ((eq org-startup-folded 'content)
6832 (org-content))
6833 ((or (eq org-startup-folded 'showeverything)
6834 (eq org-startup-folded nil))
6835 (show-all)))
6836 (unless (eq org-startup-folded 'showeverything)
6837 (if org-hide-block-startup (org-hide-block-all))
6838 (org-set-visibility-according-to-property 'no-cleanup)
6839 (org-cycle-hide-archived-subtrees 'all)
6840 (org-cycle-hide-drawers 'all)
6841 (org-cycle-show-empty-lines t)))
6843 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6844 "Switch subtree visibilities according to :VISIBILITY: property."
6845 (interactive)
6846 (let (org-show-entry-below state)
6847 (save-excursion
6848 (goto-char (point-min))
6849 (while (re-search-forward
6850 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6851 nil t)
6852 (setq state (match-string 1))
6853 (save-excursion
6854 (org-back-to-heading t)
6855 (hide-subtree)
6856 (org-reveal)
6857 (cond
6858 ((equal state '("fold" "folded"))
6859 (hide-subtree))
6860 ((equal state "children")
6861 (org-show-hidden-entry)
6862 (show-children))
6863 ((equal state "content")
6864 (save-excursion
6865 (save-restriction
6866 (org-narrow-to-subtree)
6867 (org-content))))
6868 ((member state '("all" "showall"))
6869 (show-subtree)))))
6870 (unless no-cleanup
6871 (org-cycle-hide-archived-subtrees 'all)
6872 (org-cycle-hide-drawers 'all)
6873 (org-cycle-show-empty-lines 'all)))))
6875 ;; This function uses outline-regexp instead of the more fundamental
6876 ;; org-outline-regexp so that org-cycle-global works outside of Org
6877 ;; buffers, where outline-regexp is needed.
6878 (defun org-overview ()
6879 "Switch to overview mode, showing only top-level headlines.
6880 Really, this shows all headlines with level equal or greater than the level
6881 of the first headline in the buffer. This is important, because if the
6882 first headline is not level one, then (hide-sublevels 1) gives confusing
6883 results."
6884 (interactive)
6885 (let ((pos (point))
6886 (level (save-excursion
6887 (goto-char (point-min))
6888 (if (re-search-forward (concat "^" outline-regexp) nil t)
6889 (progn
6890 (goto-char (match-beginning 0))
6891 (funcall outline-level))))))
6892 (and level (hide-sublevels level))
6893 (recenter '(4))
6894 (goto-char pos)))
6896 (defun org-content (&optional arg)
6897 "Show all headlines in the buffer, like a table of contents.
6898 With numerical argument N, show content up to level N."
6899 (interactive "P")
6900 (save-excursion
6901 ;; Visit all headings and show their offspring
6902 (and (integerp arg) (org-overview))
6903 (goto-char (point-max))
6904 (catch 'exit
6905 (while (and (progn (condition-case nil
6906 (outline-previous-visible-heading 1)
6907 (error (goto-char (point-min))))
6909 (looking-at org-outline-regexp))
6910 (if (integerp arg)
6911 (show-children (1- arg))
6912 (show-branches))
6913 (if (bobp) (throw 'exit nil))))))
6915 (defun org-optimize-window-after-visibility-change (state)
6916 "Adjust the window after a change in outline visibility.
6917 This function is the default value of the hook `org-cycle-hook'."
6918 (when (get-buffer-window (current-buffer))
6919 (cond
6920 ((eq state 'content) nil)
6921 ((eq state 'all) nil)
6922 ((eq state 'folded) nil)
6923 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6924 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6926 (defun org-remove-empty-overlays-at (pos)
6927 "Remove outline overlays that do not contain non-white stuff."
6928 (mapc
6929 (lambda (o)
6930 (and (eq 'outline (overlay-get o 'invisible))
6931 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6932 (overlay-end o))))
6933 (delete-overlay o)))
6934 (overlays-at pos)))
6936 (defun org-clean-visibility-after-subtree-move ()
6937 "Fix visibility issues after moving a subtree."
6938 ;; First, find a reasonable region to look at:
6939 ;; Start two siblings above, end three below
6940 (let* ((beg (save-excursion
6941 (and (org-get-last-sibling)
6942 (org-get-last-sibling))
6943 (point)))
6944 (end (save-excursion
6945 (and (org-get-next-sibling)
6946 (org-get-next-sibling)
6947 (org-get-next-sibling))
6948 (if (org-at-heading-p)
6949 (point-at-eol)
6950 (point))))
6951 (level (looking-at "\\*+"))
6952 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6953 (save-excursion
6954 (save-restriction
6955 (narrow-to-region beg end)
6956 (when re
6957 ;; Properly fold already folded siblings
6958 (goto-char (point-min))
6959 (while (re-search-forward re nil t)
6960 (if (and (not (outline-invisible-p))
6961 (save-excursion
6962 (goto-char (point-at-eol)) (outline-invisible-p)))
6963 (hide-entry))))
6964 (org-cycle-show-empty-lines 'overview)
6965 (org-cycle-hide-drawers 'overview)))))
6967 (defun org-cycle-show-empty-lines (state)
6968 "Show empty lines above all visible headlines.
6969 The region to be covered depends on STATE when called through
6970 `org-cycle-hook'. Lisp program can use t for STATE to get the
6971 entire buffer covered. Note that an empty line is only shown if there
6972 are at least `org-cycle-separator-lines' empty lines before the headline."
6973 (when (not (= org-cycle-separator-lines 0))
6974 (save-excursion
6975 (let* ((n (abs org-cycle-separator-lines))
6976 (re (cond
6977 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6978 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6979 (t (let ((ns (number-to-string (- n 2))))
6980 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6981 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6982 beg end b e)
6983 (cond
6984 ((memq state '(overview contents t))
6985 (setq beg (point-min) end (point-max)))
6986 ((memq state '(children folded))
6987 (setq beg (point) end (progn (org-end-of-subtree t t)
6988 (beginning-of-line 2)
6989 (point)))))
6990 (when beg
6991 (goto-char beg)
6992 (while (re-search-forward re end t)
6993 (unless (get-char-property (match-end 1) 'invisible)
6994 (setq e (match-end 1))
6995 (if (< org-cycle-separator-lines 0)
6996 (setq b (save-excursion
6997 (goto-char (match-beginning 0))
6998 (org-back-over-empty-lines)
6999 (if (save-excursion
7000 (goto-char (max (point-min) (1- (point))))
7001 (org-at-heading-p))
7002 (1- (point))
7003 (point))))
7004 (setq b (match-beginning 1)))
7005 (outline-flag-region b e nil)))))))
7006 ;; Never hide empty lines at the end of the file.
7007 (save-excursion
7008 (goto-char (point-max))
7009 (outline-previous-heading)
7010 (outline-end-of-heading)
7011 (if (and (looking-at "[ \t\n]+")
7012 (= (match-end 0) (point-max)))
7013 (outline-flag-region (point) (match-end 0) nil))))
7015 (defun org-show-empty-lines-in-parent ()
7016 "Move to the parent and re-show empty lines before visible headlines."
7017 (save-excursion
7018 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7019 (org-cycle-show-empty-lines context))))
7021 (defun org-files-list ()
7022 "Return `org-agenda-files' list, plus all open org-mode files.
7023 This is useful for operations that need to scan all of a user's
7024 open and agenda-wise Org files."
7025 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7026 (dolist (buf (buffer-list))
7027 (with-current-buffer buf
7028 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7029 (let ((file (expand-file-name (buffer-file-name))))
7030 (unless (member file files)
7031 (push file files))))))
7032 files))
7034 (defsubst org-entry-beginning-position ()
7035 "Return the beginning position of the current entry."
7036 (save-excursion (outline-back-to-heading t) (point)))
7038 (defsubst org-entry-end-position ()
7039 "Return the end position of the current entry."
7040 (save-excursion (outline-next-heading) (point)))
7042 (defun org-cycle-hide-drawers (state)
7043 "Re-hide all drawers after a visibility state change."
7044 (when (and (derived-mode-p 'org-mode)
7045 (not (memq state '(overview folded contents))))
7046 (save-excursion
7047 (let* ((globalp (memq state '(contents all)))
7048 (beg (if globalp (point-min) (point)))
7049 (end (if globalp (point-max)
7050 (if (eq state 'children)
7051 (save-excursion (outline-next-heading) (point))
7052 (org-end-of-subtree t)))))
7053 (goto-char beg)
7054 (while (re-search-forward org-drawer-regexp end t)
7055 (org-flag-drawer t))))))
7057 (defun org-cycle-hide-inline-tasks (state)
7058 "Re-hide inline tasks when switching to 'contents or 'children
7059 visibility state."
7060 (case state
7061 (contents
7062 (when (org-bound-and-true-p org-inlinetask-min-level)
7063 (hide-sublevels (1- org-inlinetask-min-level))))
7064 (children
7065 (when (featurep 'org-inlinetask)
7066 (save-excursion
7067 (while (and (outline-next-heading)
7068 (org-inlinetask-at-task-p))
7069 (org-inlinetask-toggle-visibility)
7070 (org-inlinetask-goto-end)))))))
7072 (defun org-flag-drawer (flag)
7073 "When FLAG is non-nil, hide the drawer we are within.
7074 Otherwise make it visible."
7075 (save-excursion
7076 (beginning-of-line 1)
7077 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7078 (let ((b (match-end 0)))
7079 (if (re-search-forward
7080 "^[ \t]*:END:"
7081 (save-excursion (outline-next-heading) (point)) t)
7082 (outline-flag-region b (point-at-eol) flag)
7083 (user-error ":END: line missing at position %s" b))))))
7085 (defun org-subtree-end-visible-p ()
7086 "Is the end of the current subtree visible?"
7087 (pos-visible-in-window-p
7088 (save-excursion (org-end-of-subtree t) (point))))
7090 (defun org-first-headline-recenter (&optional N)
7091 "Move cursor to the first headline and recenter the headline.
7092 Optional argument N means put the headline into the Nth line of the window."
7093 (goto-char (point-min))
7094 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7095 (beginning-of-line)
7096 (recenter (prefix-numeric-value N))))
7098 ;;; Saving and restoring visibility
7100 (defun org-outline-overlay-data (&optional use-markers)
7101 "Return a list of the locations of all outline overlays.
7102 These are overlays with the `invisible' property value `outline'.
7103 The return value is a list of cons cells, with start and stop
7104 positions for each overlay.
7105 If USE-MARKERS is set, return the positions as markers."
7106 (let (beg end)
7107 (save-excursion
7108 (save-restriction
7109 (widen)
7110 (delq nil
7111 (mapcar (lambda (o)
7112 (when (eq (overlay-get o 'invisible) 'outline)
7113 (setq beg (overlay-start o)
7114 end (overlay-end o))
7115 (and beg end (> end beg)
7116 (if use-markers
7117 (cons (move-marker (make-marker) beg)
7118 (move-marker (make-marker) end))
7119 (cons beg end)))))
7120 (overlays-in (point-min) (point-max))))))))
7122 (defun org-set-outline-overlay-data (data)
7123 "Create visibility overlays for all positions in DATA.
7124 DATA should have been made by `org-outline-overlay-data'."
7125 (let (o)
7126 (save-excursion
7127 (save-restriction
7128 (widen)
7129 (show-all)
7130 (mapc (lambda (c)
7131 (outline-flag-region (car c) (cdr c) t))
7132 data)))))
7134 ;;; Folding of blocks
7136 (defvar org-hide-block-overlays nil
7137 "Overlays hiding blocks.")
7138 (make-variable-buffer-local 'org-hide-block-overlays)
7140 (defun org-block-map (function &optional start end)
7141 "Call FUNCTION at the head of all source blocks in the current buffer.
7142 Optional arguments START and END can be used to limit the range."
7143 (let ((start (or start (point-min)))
7144 (end (or end (point-max))))
7145 (save-excursion
7146 (goto-char start)
7147 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7148 (save-excursion
7149 (save-match-data
7150 (goto-char (match-beginning 0))
7151 (funcall function)))))))
7153 (defun org-hide-block-toggle-all ()
7154 "Toggle the visibility of all blocks in the current buffer."
7155 (org-block-map #'org-hide-block-toggle))
7157 (defun org-hide-block-all ()
7158 "Fold all blocks in the current buffer."
7159 (interactive)
7160 (org-show-block-all)
7161 (org-block-map #'org-hide-block-toggle-maybe))
7163 (defun org-show-block-all ()
7164 "Unfold all blocks in the current buffer."
7165 (interactive)
7166 (mapc 'delete-overlay org-hide-block-overlays)
7167 (setq org-hide-block-overlays nil))
7169 (defun org-hide-block-toggle-maybe ()
7170 "Toggle visibility of block at point."
7171 (interactive)
7172 (let ((case-fold-search t))
7173 (if (save-excursion
7174 (beginning-of-line 1)
7175 (looking-at org-block-regexp))
7176 (progn (org-hide-block-toggle)
7177 t) ;; to signal that we took action
7178 nil))) ;; to signal that we did not
7180 (defun org-hide-block-toggle (&optional force)
7181 "Toggle the visibility of the current block."
7182 (interactive)
7183 (save-excursion
7184 (beginning-of-line)
7185 (if (re-search-forward org-block-regexp nil t)
7186 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7187 (end (match-end 0)) ;; end of entire body
7189 (if (memq t (mapcar (lambda (overlay)
7190 (eq (overlay-get overlay 'invisible)
7191 'org-hide-block))
7192 (overlays-at start)))
7193 (if (or (not force) (eq force 'off))
7194 (mapc (lambda (ov)
7195 (when (member ov org-hide-block-overlays)
7196 (setq org-hide-block-overlays
7197 (delq ov org-hide-block-overlays)))
7198 (when (eq (overlay-get ov 'invisible)
7199 'org-hide-block)
7200 (delete-overlay ov)))
7201 (overlays-at start)))
7202 (setq ov (make-overlay start end))
7203 (overlay-put ov 'invisible 'org-hide-block)
7204 ;; make the block accessible to isearch
7205 (overlay-put
7206 ov 'isearch-open-invisible
7207 (lambda (ov)
7208 (when (member ov org-hide-block-overlays)
7209 (setq org-hide-block-overlays
7210 (delq ov org-hide-block-overlays)))
7211 (when (eq (overlay-get ov 'invisible)
7212 'org-hide-block)
7213 (delete-overlay ov))))
7214 (push ov org-hide-block-overlays)))
7215 (user-error "Not looking at a source block"))))
7217 ;; org-tab-after-check-for-cycling-hook
7218 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7219 ;; Remove overlays when changing major mode
7220 (add-hook 'org-mode-hook
7221 (lambda () (org-add-hook 'change-major-mode-hook
7222 'org-show-block-all 'append 'local)))
7224 ;;; Org-goto
7226 (defvar org-goto-window-configuration nil)
7227 (defvar org-goto-marker nil)
7228 (defvar org-goto-map)
7229 (defun org-goto-map ()
7230 "Set the keymap `org-goto'."
7231 (setq org-goto-map
7232 (let ((map (make-sparse-keymap)))
7233 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7234 mouse-drag-region universal-argument org-occur))
7235 cmd)
7236 (while (setq cmd (pop cmds))
7237 (substitute-key-definition cmd cmd map global-map)))
7238 (suppress-keymap map)
7239 (org-defkey map "\C-m" 'org-goto-ret)
7240 (org-defkey map [(return)] 'org-goto-ret)
7241 (org-defkey map [(left)] 'org-goto-left)
7242 (org-defkey map [(right)] 'org-goto-right)
7243 (org-defkey map [(control ?g)] 'org-goto-quit)
7244 (org-defkey map "\C-i" 'org-cycle)
7245 (org-defkey map [(tab)] 'org-cycle)
7246 (org-defkey map [(down)] 'outline-next-visible-heading)
7247 (org-defkey map [(up)] 'outline-previous-visible-heading)
7248 (if org-goto-auto-isearch
7249 (if (fboundp 'define-key-after)
7250 (define-key-after map [t] 'org-goto-local-auto-isearch)
7251 nil)
7252 (org-defkey map "q" 'org-goto-quit)
7253 (org-defkey map "n" 'outline-next-visible-heading)
7254 (org-defkey map "p" 'outline-previous-visible-heading)
7255 (org-defkey map "f" 'outline-forward-same-level)
7256 (org-defkey map "b" 'outline-backward-same-level)
7257 (org-defkey map "u" 'outline-up-heading))
7258 (org-defkey map "/" 'org-occur)
7259 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7260 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7261 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7262 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7263 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7264 map)))
7266 (defconst org-goto-help
7267 "Browse buffer copy, to find location or copy text.%s
7268 RET=jump to location C-g=quit and return to previous location
7269 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7271 (defvar org-goto-start-pos) ; dynamically scoped parameter
7273 (defun org-goto (&optional alternative-interface)
7274 "Look up a different location in the current file, keeping current visibility.
7276 When you want look-up or go to a different location in a
7277 document, the fastest way is often to fold the entire buffer and
7278 then dive into the tree. This method has the disadvantage, that
7279 the previous location will be folded, which may not be what you
7280 want.
7282 This command works around this by showing a copy of the current
7283 buffer in an indirect buffer, in overview mode. You can dive
7284 into the tree in that copy, use org-occur and incremental search
7285 to find a location. When pressing RET or `Q', the command
7286 returns to the original buffer in which the visibility is still
7287 unchanged. After RET it will also jump to the location selected
7288 in the indirect buffer and expose the headline hierarchy above.
7290 With a prefix argument, use the alternative interface: e.g. if
7291 `org-goto-interface' is 'outline use 'outline-path-completion."
7292 (interactive "P")
7293 (org-goto-map)
7294 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7295 (org-refile-use-outline-path t)
7296 (org-refile-target-verify-function nil)
7297 (interface
7298 (if (not alternative-interface)
7299 org-goto-interface
7300 (if (eq org-goto-interface 'outline)
7301 'outline-path-completion
7302 'outline)))
7303 (org-goto-start-pos (point))
7304 (selected-point
7305 (if (eq interface 'outline)
7306 (car (org-get-location (current-buffer) org-goto-help))
7307 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7308 (org-refile-check-position pa)
7309 (nth 3 pa)))))
7310 (if selected-point
7311 (progn
7312 (org-mark-ring-push org-goto-start-pos)
7313 (goto-char selected-point)
7314 (if (or (outline-invisible-p) (org-invisible-p2))
7315 (org-show-context 'org-goto)))
7316 (message "Quit"))))
7318 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7319 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7320 (defvar org-goto-local-auto-isearch-map) ; defined below
7322 (defun org-get-location (buf help)
7323 "Let the user select a location in the Org-mode buffer BUF.
7324 This function uses a recursive edit. It returns the selected position
7325 or nil."
7326 (org-no-popups
7327 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7328 (isearch-hide-immediately nil)
7329 (isearch-search-fun-function
7330 (lambda () 'org-goto-local-search-headings))
7331 (org-goto-selected-point org-goto-exit-command))
7332 (save-excursion
7333 (save-window-excursion
7334 (delete-other-windows)
7335 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7336 (org-pop-to-buffer-same-window
7337 (condition-case nil
7338 (make-indirect-buffer (current-buffer) "*org-goto*")
7339 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7340 (with-output-to-temp-buffer "*Org Help*"
7341 (princ (format help (if org-goto-auto-isearch
7342 " Just type for auto-isearch."
7343 " n/p/f/b/u to navigate, q to quit."))))
7344 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7345 (setq buffer-read-only nil)
7346 (let ((org-startup-truncated t)
7347 (org-startup-folded nil)
7348 (org-startup-align-all-tables nil))
7349 (org-mode)
7350 (org-overview))
7351 (setq buffer-read-only t)
7352 (if (and (boundp 'org-goto-start-pos)
7353 (integer-or-marker-p org-goto-start-pos))
7354 (let ((org-show-hierarchy-above t)
7355 (org-show-siblings t)
7356 (org-show-following-heading t))
7357 (goto-char org-goto-start-pos)
7358 (and (outline-invisible-p) (org-show-context)))
7359 (goto-char (point-min)))
7360 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7361 (message "Select location and press RET")
7362 (use-local-map org-goto-map)
7363 (recursive-edit)))
7364 (kill-buffer "*org-goto*")
7365 (cons org-goto-selected-point org-goto-exit-command))))
7367 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7368 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7369 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7370 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7372 (defun org-goto-local-search-headings (string bound noerror)
7373 "Search and make sure that any matches are in headlines."
7374 (catch 'return
7375 (while (if isearch-forward
7376 (search-forward string bound noerror)
7377 (search-backward string bound noerror))
7378 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7379 (and (member :headline context)
7380 (not (member :tags context))))
7381 (throw 'return (point))))))
7383 (defun org-goto-local-auto-isearch ()
7384 "Start isearch."
7385 (interactive)
7386 (goto-char (point-min))
7387 (let ((keys (this-command-keys)))
7388 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7389 (isearch-mode t)
7390 (isearch-process-search-char (string-to-char keys)))))
7392 (defun org-goto-ret (&optional arg)
7393 "Finish `org-goto' by going to the new location."
7394 (interactive "P")
7395 (setq org-goto-selected-point (point)
7396 org-goto-exit-command 'return)
7397 (throw 'exit nil))
7399 (defun org-goto-left ()
7400 "Finish `org-goto' by going to the new location."
7401 (interactive)
7402 (if (org-at-heading-p)
7403 (progn
7404 (beginning-of-line 1)
7405 (setq org-goto-selected-point (point)
7406 org-goto-exit-command 'left)
7407 (throw 'exit nil))
7408 (user-error "Not on a heading")))
7410 (defun org-goto-right ()
7411 "Finish `org-goto' by going to the new location."
7412 (interactive)
7413 (if (org-at-heading-p)
7414 (progn
7415 (setq org-goto-selected-point (point)
7416 org-goto-exit-command 'right)
7417 (throw 'exit nil))
7418 (user-error "Not on a heading")))
7420 (defun org-goto-quit ()
7421 "Finish `org-goto' without cursor motion."
7422 (interactive)
7423 (setq org-goto-selected-point nil)
7424 (setq org-goto-exit-command 'quit)
7425 (throw 'exit nil))
7427 ;;; Indirect buffer display of subtrees
7429 (defvar org-indirect-dedicated-frame nil
7430 "This is the frame being used for indirect tree display.")
7431 (defvar org-last-indirect-buffer nil)
7433 (defun org-tree-to-indirect-buffer (&optional arg)
7434 "Create indirect buffer and narrow it to current subtree.
7435 With a numerical prefix ARG, go up to this level and then take that tree.
7436 If ARG is negative, go up that many levels.
7438 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7439 indirect buffer previously made with this command, to avoid proliferation of
7440 indirect buffers. However, when you call the command with a \
7441 \\[universal-argument] prefix, or
7442 when `org-indirect-buffer-display' is `new-frame', the last buffer
7443 is kept so that you can work with several indirect buffers at the same time.
7444 If `org-indirect-buffer-display' is `dedicated-frame', the \
7445 \\[universal-argument] prefix also
7446 requests that a new frame be made for the new buffer, so that the dedicated
7447 frame is not changed."
7448 (interactive "P")
7449 (let ((cbuf (current-buffer))
7450 (cwin (selected-window))
7451 (pos (point))
7452 beg end level heading ibuf)
7453 (save-excursion
7454 (org-back-to-heading t)
7455 (when (numberp arg)
7456 (setq level (org-outline-level))
7457 (if (< arg 0) (setq arg (+ level arg)))
7458 (while (> (setq level (org-outline-level)) arg)
7459 (org-up-heading-safe)))
7460 (setq beg (point)
7461 heading (org-get-heading))
7462 (org-end-of-subtree t t)
7463 (if (org-at-heading-p) (backward-char 1))
7464 (setq end (point)))
7465 (if (and (buffer-live-p org-last-indirect-buffer)
7466 (not (eq org-indirect-buffer-display 'new-frame))
7467 (not arg))
7468 (kill-buffer org-last-indirect-buffer))
7469 (setq ibuf (org-get-indirect-buffer cbuf)
7470 org-last-indirect-buffer ibuf)
7471 (cond
7472 ((or (eq org-indirect-buffer-display 'new-frame)
7473 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7474 (select-frame (make-frame))
7475 (delete-other-windows)
7476 (org-pop-to-buffer-same-window ibuf)
7477 (org-set-frame-title heading))
7478 ((eq org-indirect-buffer-display 'dedicated-frame)
7479 (raise-frame
7480 (select-frame (or (and org-indirect-dedicated-frame
7481 (frame-live-p org-indirect-dedicated-frame)
7482 org-indirect-dedicated-frame)
7483 (setq org-indirect-dedicated-frame (make-frame)))))
7484 (delete-other-windows)
7485 (org-pop-to-buffer-same-window ibuf)
7486 (org-set-frame-title (concat "Indirect: " heading)))
7487 ((eq org-indirect-buffer-display 'current-window)
7488 (org-pop-to-buffer-same-window ibuf))
7489 ((eq org-indirect-buffer-display 'other-window)
7490 (pop-to-buffer ibuf))
7491 (t (error "Invalid value")))
7492 (if (featurep 'xemacs)
7493 (save-excursion (org-mode) (turn-on-font-lock)))
7494 (narrow-to-region beg end)
7495 (show-all)
7496 (goto-char pos)
7497 (run-hook-with-args 'org-cycle-hook 'all)
7498 (and (window-live-p cwin) (select-window cwin))))
7500 (defun org-get-indirect-buffer (&optional buffer)
7501 (setq buffer (or buffer (current-buffer)))
7502 (let ((n 1) (base (buffer-name buffer)) bname)
7503 (while (buffer-live-p
7504 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7505 (setq n (1+ n)))
7506 (condition-case nil
7507 (make-indirect-buffer buffer bname 'clone)
7508 (error (make-indirect-buffer buffer bname)))))
7510 (defun org-set-frame-title (title)
7511 "Set the title of the current frame to the string TITLE."
7512 ;; FIXME: how to name a single frame in XEmacs???
7513 (unless (featurep 'xemacs)
7514 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7516 ;;;; Structure editing
7518 ;;; Inserting headlines
7520 (defun org-previous-line-empty-p (&optional next)
7521 "Is the previous line a blank line?
7522 When NEXT is non-nil, check the next line instead."
7523 (save-excursion
7524 (and (not (bobp))
7525 (or (beginning-of-line (if next 2 0)) t)
7526 (save-match-data
7527 (looking-at "[ \t]*$")))))
7529 (defun org-insert-heading (&optional arg invisible-ok)
7530 "Insert a new heading or item with same depth at point.
7531 If point is in a plain list and ARG is nil, create a new list item.
7532 With one universal prefix argument, insert a heading even in lists.
7533 With two universal prefix arguments, insert the heading at the end
7534 of the parent subtree.
7536 If point is at the beginning of a headline, insert a sibling before
7537 the current headline. If point is not at the beginning, split the line
7538 and create a new headline with the text in the current line after point
7539 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7541 If point is at the beginning of a normal line, turn this line into
7542 a heading.
7544 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7545 This is important for non-interactive uses of the command."
7546 (interactive "P")
7547 (if (org-called-interactively-p 'any) (org-reveal))
7548 (let ((itemp (org-in-item-p))
7549 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7550 (respect-content (or org-insert-heading-respect-content
7551 (equal arg '(16))))
7552 (initial-content "")
7553 (adjust-empty-lines t))
7555 (cond
7557 ((or (= (buffer-size) 0)
7558 (and (not (save-excursion
7559 (and (ignore-errors (org-back-to-heading invisible-ok))
7560 (org-at-heading-p))))
7561 (or arg (not itemp))))
7562 ;; At beginning of buffer or so high up that only a heading
7563 ;; makes sense.
7564 (insert
7565 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7566 (if (org-in-src-block-p) ",* " "* "))
7567 (run-hooks 'org-insert-heading-hook))
7569 ((and itemp (not (equal arg '(4))))
7570 ;; Insert an item
7571 (org-insert-item))
7574 ;; Insert a heading
7575 (save-restriction
7576 (widen)
7577 (let* ((level nil)
7578 (on-heading (org-at-heading-p))
7579 (empty-line-p (if on-heading
7580 (org-previous-line-empty-p)
7581 ;; We will decide later
7582 nil))
7583 ;; Get a level string to fall back on
7584 (fix-level
7585 (save-excursion
7586 (org-back-to-heading t)
7587 (if (org-previous-line-empty-p) (setq empty-line-p t))
7588 (looking-at org-outline-regexp)
7589 (make-string (1- (length (match-string 0))) ?*)))
7590 (stars
7591 (save-excursion
7592 (condition-case nil
7593 (progn
7594 (org-back-to-heading invisible-ok)
7595 (when (and (not on-heading)
7596 (featurep 'org-inlinetask)
7597 (integerp org-inlinetask-min-level)
7598 (>= (length (match-string 0))
7599 org-inlinetask-min-level))
7600 ;; Find a heading level before the inline task
7601 (while (and (setq level (org-up-heading-safe))
7602 (>= level org-inlinetask-min-level)))
7603 (if (org-at-heading-p)
7604 (org-back-to-heading invisible-ok)
7605 (error "This should not happen")))
7606 (unless (and (save-excursion
7607 (save-match-data
7608 (org-backward-heading-same-level
7609 1 invisible-ok))
7610 (= (point) (match-beginning 0)))
7611 (not (org-previous-line-empty-p t)))
7612 (setq empty-line-p (or empty-line-p
7613 (org-previous-line-empty-p))))
7614 (match-string 0))
7615 (error (or fix-level "* ")))))
7616 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7617 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7618 pos hide-previous previous-pos)
7620 ;; If we insert after content, move there and clean up whitespace
7621 (when respect-content
7622 (org-end-of-subtree nil t)
7623 (skip-chars-backward " \r\n")
7624 (and (looking-at "[ \t]+") (replace-match ""))
7625 (unless (eobp) (forward-char 1))
7626 (when (looking-at "^\\*")
7627 (unless (bobp) (backward-char 1))
7628 (insert "\n")))
7630 ;; If we are splitting, grab the text that should be moved to the new headline
7631 (when may-split
7632 (if (org-on-heading-p)
7633 ;; This is a heading, we split intelligently (keeping tags)
7634 (let ((pos (point)))
7635 (goto-char (point-at-bol))
7636 (unless (looking-at org-complex-heading-regexp)
7637 (error "This should not happen"))
7638 (when (and (match-beginning 4)
7639 (> pos (match-beginning 4))
7640 (< pos (match-end 4)))
7641 (setq initial-content (buffer-substring pos (match-end 4)))
7642 (goto-char pos)
7643 (delete-region (point) (match-end 4))
7644 (if (looking-at "[ \t]*$")
7645 (replace-match "")
7646 (insert (make-string (length initial-content) ?\ )))
7647 (setq initial-content (org-trim initial-content)))
7648 (goto-char pos))
7649 ;; a normal line
7650 (unless (bolp)
7651 (setq initial-content (buffer-substring (point) (point-at-eol)))
7652 (delete-region (point) (point-at-eol))
7653 (setq initial-content (org-trim initial-content)))))
7655 ;; If we are at the beginning of the line, insert before it. Else after
7656 (cond
7657 ((and (bolp) (looking-at "[ \t]*$")))
7658 ((and (bolp) (not (looking-at "[ \t]*$")))
7659 (open-line 1))
7661 (goto-char (point-at-eol))
7662 (insert "\n")))
7664 ;; Insert the new heading
7665 (insert stars)
7666 (just-one-space)
7667 (insert initial-content)
7668 (when adjust-empty-lines
7669 (if (or (not blank)
7670 (and blank (not (org-previous-line-empty-p))))
7671 (org-N-empty-lines-before-current (if blank 1 0))))
7672 (run-hooks 'org-insert-heading-hook)))))))
7674 (defun org-N-empty-lines-before-current (N)
7675 "Make the number of empty lines before current exactly N.
7676 So this will delete or add empty lines."
7677 (save-excursion
7678 (goto-char (point-at-bol))
7679 (if (looking-back "\\s-+" nil 'greedy)
7680 (replace-match ""))
7681 (or (bobp) (insert "\n"))
7682 (while (> N 0)
7683 (insert "\n")
7684 (setq N (1- N)))))
7686 (defun org-get-heading (&optional no-tags no-todo)
7687 "Return the heading of the current entry, without the stars.
7688 When NO-TAGS is non-nil, don't include tags.
7689 When NO-TODO is non-nil, don't include TODO keywords."
7690 (save-excursion
7691 (org-back-to-heading t)
7692 (cond
7693 ((and no-tags no-todo)
7694 (looking-at org-complex-heading-regexp)
7695 (match-string 4))
7696 (no-tags
7697 (looking-at (concat org-outline-regexp
7698 "\\(.*?\\)"
7699 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7700 (match-string 1))
7701 (no-todo
7702 (looking-at org-todo-line-regexp)
7703 (match-string 3))
7704 (t (looking-at org-heading-regexp)
7705 (match-string 2)))))
7707 (defvar orgstruct-mode) ; defined below
7709 (defun org-heading-components ()
7710 "Return the components of the current heading.
7711 This is a list with the following elements:
7712 - the level as an integer
7713 - the reduced level, different if `org-odd-levels-only' is set.
7714 - the TODO keyword, or nil
7715 - the priority character, like ?A, or nil if no priority is given
7716 - the headline text itself, or the tags string if no headline text
7717 - the tags string, or nil."
7718 (save-excursion
7719 (org-back-to-heading t)
7720 (if (let (case-fold-search)
7721 (looking-at
7722 (if orgstruct-mode
7723 org-heading-regexp
7724 org-complex-heading-regexp)))
7725 (if orgstruct-mode
7726 (list (length (match-string 1))
7727 (org-reduced-level (length (match-string 1)))
7730 (match-string 2)
7731 nil)
7732 (list (length (match-string 1))
7733 (org-reduced-level (length (match-string 1)))
7734 (org-match-string-no-properties 2)
7735 (and (match-end 3) (aref (match-string 3) 2))
7736 (org-match-string-no-properties 4)
7737 (org-match-string-no-properties 5))))))
7739 (defun org-get-entry ()
7740 "Get the entry text, after heading, entire subtree."
7741 (save-excursion
7742 (org-back-to-heading t)
7743 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7745 (defun org-insert-heading-after-current ()
7746 "Insert a new heading with same level as current, after current subtree."
7747 (interactive)
7748 (org-back-to-heading)
7749 (org-insert-heading)
7750 (org-move-subtree-down)
7751 (end-of-line 1))
7753 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7754 "Insert heading with `org-insert-heading-respect-content' set to t."
7755 (interactive "P")
7756 (let ((org-insert-heading-respect-content t))
7757 (org-insert-heading '(4) invisible-ok)))
7759 (defun org-insert-todo-heading-respect-content (&optional force-state)
7760 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7761 (interactive "P")
7762 (let ((org-insert-heading-respect-content t))
7763 (org-insert-todo-heading force-state '(4))))
7765 (defun org-insert-todo-heading (arg &optional force-heading)
7766 "Insert a new heading with the same level and TODO state as current heading.
7767 If the heading has no TODO state, or if the state is DONE, use the first
7768 state (TODO by default). Also one prefix arg, force first state. With two
7769 prefix args, force inserting at the end of the parent subtree."
7770 (interactive "P")
7771 (when (or force-heading (not (org-insert-item 'checkbox)))
7772 (org-insert-heading (or (and (equal arg '(16)) '(16))
7773 force-heading))
7774 (save-excursion
7775 (org-back-to-heading)
7776 (outline-previous-heading)
7777 (looking-at org-todo-line-regexp))
7778 (let*
7779 ((new-mark-x
7780 (if (or arg
7781 (not (match-beginning 2))
7782 (member (match-string 2) org-done-keywords))
7783 (car org-todo-keywords-1)
7784 (match-string 2)))
7785 (new-mark
7787 (run-hook-with-args-until-success
7788 'org-todo-get-default-hook new-mark-x nil)
7789 new-mark-x)))
7790 (beginning-of-line 1)
7791 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7792 (if org-treat-insert-todo-heading-as-state-change
7793 (org-todo new-mark)
7794 (insert new-mark " "))))
7795 (when org-provide-todo-statistics
7796 (org-update-parent-todo-statistics))))
7798 (defun org-insert-subheading (arg)
7799 "Insert a new subheading and demote it.
7800 Works for outline headings and for plain lists alike."
7801 (interactive "P")
7802 (org-insert-heading arg)
7803 (cond
7804 ((org-at-heading-p) (org-do-demote))
7805 ((org-at-item-p) (org-indent-item))))
7807 (defun org-insert-todo-subheading (arg)
7808 "Insert a new subheading with TODO keyword or checkbox and demote it.
7809 Works for outline headings and for plain lists alike."
7810 (interactive "P")
7811 (org-insert-todo-heading arg)
7812 (cond
7813 ((org-at-heading-p) (org-do-demote))
7814 ((org-at-item-p) (org-indent-item))))
7816 ;;; Promotion and Demotion
7818 (defvar org-after-demote-entry-hook nil
7819 "Hook run after an entry has been demoted.
7820 The cursor will be at the beginning of the entry.
7821 When a subtree is being demoted, the hook will be called for each node.")
7823 (defvar org-after-promote-entry-hook nil
7824 "Hook run after an entry has been promoted.
7825 The cursor will be at the beginning of the entry.
7826 When a subtree is being promoted, the hook will be called for each node.")
7828 (defun org-promote-subtree ()
7829 "Promote the entire subtree.
7830 See also `org-promote'."
7831 (interactive)
7832 (save-excursion
7833 (org-with-limited-levels (org-map-tree 'org-promote)))
7834 (org-fix-position-after-promote))
7836 (defun org-demote-subtree ()
7837 "Demote the entire subtree. See `org-demote'.
7838 See also `org-promote'."
7839 (interactive)
7840 (save-excursion
7841 (org-with-limited-levels (org-map-tree 'org-demote)))
7842 (org-fix-position-after-promote))
7845 (defun org-do-promote ()
7846 "Promote the current heading higher up the tree.
7847 If the region is active in `transient-mark-mode', promote all headings
7848 in the region."
7849 (interactive)
7850 (save-excursion
7851 (if (org-region-active-p)
7852 (org-map-region 'org-promote (region-beginning) (region-end))
7853 (org-promote)))
7854 (org-fix-position-after-promote))
7856 (defun org-do-demote ()
7857 "Demote the current heading lower down the tree.
7858 If the region is active in `transient-mark-mode', demote all headings
7859 in the region."
7860 (interactive)
7861 (save-excursion
7862 (if (org-region-active-p)
7863 (org-map-region 'org-demote (region-beginning) (region-end))
7864 (org-demote)))
7865 (org-fix-position-after-promote))
7867 (defun org-fix-position-after-promote ()
7868 "Make sure that after pro/demotion cursor position is right."
7869 (let ((pos (point)))
7870 (when (save-excursion
7871 (beginning-of-line 1)
7872 (looking-at org-todo-line-regexp)
7873 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7874 (cond ((eobp) (insert " "))
7875 ((eolp) (insert " "))
7876 ((equal (char-after) ?\ ) (forward-char 1))))))
7878 (defun org-current-level ()
7879 "Return the level of the current entry, or nil if before the first headline.
7880 The level is the number of stars at the beginning of the headline."
7881 (save-excursion
7882 (org-with-limited-levels
7883 (if (ignore-errors (org-back-to-heading t))
7884 (funcall outline-level)))))
7886 (defun org-get-previous-line-level ()
7887 "Return the outline depth of the last headline before the current line.
7888 Returns 0 for the first headline in the buffer, and nil if before the
7889 first headline."
7890 (let ((current-level (org-current-level))
7891 (prev-level (when (> (line-number-at-pos) 1)
7892 (save-excursion
7893 (beginning-of-line 0)
7894 (org-current-level)))))
7895 (cond ((null current-level) nil) ; Before first headline
7896 ((null prev-level) 0) ; At first headline
7897 (prev-level))))
7899 (defun org-reduced-level (l)
7900 "Compute the effective level of a heading.
7901 This takes into account the setting of `org-odd-levels-only'."
7902 (cond
7903 ((zerop l) 0)
7904 (org-odd-levels-only (1+ (floor (/ l 2))))
7905 (t l)))
7907 (defun org-level-increment ()
7908 "Return the number of stars that will be added or removed at a
7909 time to headlines when structure editing, based on the value of
7910 `org-odd-levels-only'."
7911 (if org-odd-levels-only 2 1))
7913 (defun org-get-valid-level (level &optional change)
7914 "Rectify a level change under the influence of `org-odd-levels-only'
7915 LEVEL is a current level, CHANGE is by how much the level should be
7916 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7917 even level numbers will become the next higher odd number."
7918 (if org-odd-levels-only
7919 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7920 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7921 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7922 (max 1 (+ level (or change 0)))))
7924 (if (boundp 'define-obsolete-function-alias)
7925 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7926 (define-obsolete-function-alias 'org-get-legal-level
7927 'org-get-valid-level)
7928 (define-obsolete-function-alias 'org-get-legal-level
7929 'org-get-valid-level "23.1")))
7931 (defun org-promote ()
7932 "Promote the current heading higher up the tree.
7933 If the region is active in `transient-mark-mode', promote all headings
7934 in the region."
7935 (org-back-to-heading t)
7936 (let* ((level (save-match-data (funcall outline-level)))
7937 (after-change-functions (remove 'flyspell-after-change-function
7938 after-change-functions))
7939 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7940 (diff (abs (- level (length up-head) -1))))
7941 (cond ((and (= level 1) org-called-with-limited-levels
7942 org-allow-promoting-top-level-subtree)
7943 (replace-match "# " nil t))
7944 ((= level 1)
7945 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7946 (t (replace-match up-head nil t)))
7947 ;; Fixup tag positioning
7948 (unless (= level 1)
7949 (and org-auto-align-tags (org-set-tags nil t))
7950 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7951 (run-hooks 'org-after-promote-entry-hook)))
7953 (defun org-demote ()
7954 "Demote the current heading lower down the tree.
7955 If the region is active in `transient-mark-mode', demote all headings
7956 in the region."
7957 (org-back-to-heading t)
7958 (let* ((level (save-match-data (funcall outline-level)))
7959 (after-change-functions (remove 'flyspell-after-change-function
7960 after-change-functions))
7961 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7962 (diff (abs (- level (length down-head) -1))))
7963 (replace-match down-head nil t)
7964 ;; Fixup tag positioning
7965 (and org-auto-align-tags (org-set-tags nil t))
7966 (if org-adapt-indentation (org-fixup-indentation diff))
7967 (run-hooks 'org-after-demote-entry-hook)))
7969 (defun org-cycle-level ()
7970 "Cycle the level of an empty headline through possible states.
7971 This goes first to child, then to parent, level, then up the hierarchy.
7972 After top level, it switches back to sibling level."
7973 (interactive)
7974 (let ((org-adapt-indentation nil))
7975 (when (org-point-at-end-of-empty-headline)
7976 (setq this-command 'org-cycle-level) ; Only needed for caching
7977 (let ((cur-level (org-current-level))
7978 (prev-level (org-get-previous-line-level)))
7979 (cond
7980 ;; If first headline in file, promote to top-level.
7981 ((= prev-level 0)
7982 (loop repeat (/ (- cur-level 1) (org-level-increment))
7983 do (org-do-promote)))
7984 ;; If same level as prev, demote one.
7985 ((= prev-level cur-level)
7986 (org-do-demote))
7987 ;; If parent is top-level, promote to top level if not already.
7988 ((= prev-level 1)
7989 (loop repeat (/ (- cur-level 1) (org-level-increment))
7990 do (org-do-promote)))
7991 ;; If top-level, return to prev-level.
7992 ((= cur-level 1)
7993 (loop repeat (/ (- prev-level 1) (org-level-increment))
7994 do (org-do-demote)))
7995 ;; If less than prev-level, promote one.
7996 ((< cur-level prev-level)
7997 (org-do-promote))
7998 ;; If deeper than prev-level, promote until higher than
7999 ;; prev-level.
8000 ((> cur-level prev-level)
8001 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8002 do (org-do-promote))))
8003 t))))
8005 (defun org-map-tree (fun)
8006 "Call FUN for every heading underneath the current one."
8007 (org-back-to-heading)
8008 (let ((level (funcall outline-level)))
8009 (save-excursion
8010 (funcall fun)
8011 (while (and (progn
8012 (outline-next-heading)
8013 (> (funcall outline-level) level))
8014 (not (eobp)))
8015 (funcall fun)))))
8017 (defun org-map-region (fun beg end)
8018 "Call FUN for every heading between BEG and END."
8019 (let ((org-ignore-region t))
8020 (save-excursion
8021 (setq end (copy-marker end))
8022 (goto-char beg)
8023 (if (and (re-search-forward org-outline-regexp-bol nil t)
8024 (< (point) end))
8025 (funcall fun))
8026 (while (and (progn
8027 (outline-next-heading)
8028 (< (point) end))
8029 (not (eobp)))
8030 (funcall fun)))))
8032 (defvar org-property-end-re) ; silence byte-compiler
8033 (defun org-fixup-indentation (diff)
8034 "Change the indentation in the current entry by DIFF.
8035 However, if any line in the current entry has no indentation, or if it
8036 would end up with no indentation after the change, nothing at all is done."
8037 (save-excursion
8038 (let ((end (save-excursion (outline-next-heading)
8039 (point-marker)))
8040 (prohibit (if (> diff 0)
8041 "^\\S-"
8042 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8043 col)
8044 (unless (save-excursion (end-of-line 1)
8045 (re-search-forward prohibit end t))
8046 (while (and (< (point) end)
8047 (re-search-forward "^[ \t]+" end t))
8048 (goto-char (match-end 0))
8049 (setq col (current-column))
8050 (if (< diff 0) (replace-match ""))
8051 (org-indent-to-column (+ diff col))))
8052 (move-marker end nil))))
8054 (defun org-convert-to-odd-levels ()
8055 "Convert an org-mode file with all levels allowed to one with odd levels.
8056 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8057 level 5 etc."
8058 (interactive)
8059 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8060 (let ((outline-level 'org-outline-level)
8061 (org-odd-levels-only nil) n)
8062 (save-excursion
8063 (goto-char (point-min))
8064 (while (re-search-forward "^\\*\\*+ " nil t)
8065 (setq n (- (length (match-string 0)) 2))
8066 (while (>= (setq n (1- n)) 0)
8067 (org-demote))
8068 (end-of-line 1))))))
8070 (defun org-convert-to-oddeven-levels ()
8071 "Convert an org-mode file with only odd levels to one with odd/even levels.
8072 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8073 file contains a section with an even level, conversion would
8074 destroy the structure of the file. An error is signaled in this
8075 case."
8076 (interactive)
8077 (goto-char (point-min))
8078 ;; First check if there are no even levels
8079 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8080 (org-show-context t)
8081 (error "Not all levels are odd in this file. Conversion not possible"))
8082 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8083 (let ((outline-regexp org-outline-regexp)
8084 (outline-level 'org-outline-level)
8085 (org-odd-levels-only nil) n)
8086 (save-excursion
8087 (goto-char (point-min))
8088 (while (re-search-forward "^\\*\\*+ " nil t)
8089 (setq n (/ (1- (length (match-string 0))) 2))
8090 (while (>= (setq n (1- n)) 0)
8091 (org-promote))
8092 (end-of-line 1))))))
8094 (defun org-tr-level (n)
8095 "Make N odd if required."
8096 (if org-odd-levels-only (1+ (/ n 2)) n))
8098 ;;; Vertical tree motion, cutting and pasting of subtrees
8100 (defun org-move-subtree-up (&optional arg)
8101 "Move the current subtree up past ARG headlines of the same level."
8102 (interactive "p")
8103 (org-move-subtree-down (- (prefix-numeric-value arg))))
8105 (defun org-move-subtree-down (&optional arg)
8106 "Move the current subtree down past ARG headlines of the same level."
8107 (interactive "p")
8108 (setq arg (prefix-numeric-value arg))
8109 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8110 'org-get-last-sibling))
8111 (ins-point (make-marker))
8112 (cnt (abs arg))
8113 (col (current-column))
8114 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8115 ;; Select the tree
8116 (org-back-to-heading)
8117 (setq beg0 (point))
8118 (save-excursion
8119 (setq ne-beg (org-back-over-empty-lines))
8120 (setq beg (point)))
8121 (save-match-data
8122 (save-excursion (outline-end-of-heading)
8123 (setq folded (outline-invisible-p)))
8124 (outline-end-of-subtree))
8125 (outline-next-heading)
8126 (setq ne-end (org-back-over-empty-lines))
8127 (setq end (point))
8128 (goto-char beg0)
8129 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8130 ;; include less whitespace
8131 (save-excursion
8132 (goto-char beg)
8133 (forward-line (- ne-beg ne-end))
8134 (setq beg (point))))
8135 ;; Find insertion point, with error handling
8136 (while (> cnt 0)
8137 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8138 (progn (goto-char beg0)
8139 (user-error "Cannot move past superior level or buffer limit")))
8140 (setq cnt (1- cnt)))
8141 (if (> arg 0)
8142 ;; Moving forward - still need to move over subtree
8143 (progn (org-end-of-subtree t t)
8144 (save-excursion
8145 (org-back-over-empty-lines)
8146 (or (bolp) (newline)))))
8147 (setq ne-ins (org-back-over-empty-lines))
8148 (move-marker ins-point (point))
8149 (setq txt (buffer-substring beg end))
8150 (org-save-markers-in-region beg end)
8151 (delete-region beg end)
8152 (org-remove-empty-overlays-at beg)
8153 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8154 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8155 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8156 (let ((bbb (point)))
8157 (insert-before-markers txt)
8158 (org-reinstall-markers-in-region bbb)
8159 (move-marker ins-point bbb))
8160 (or (bolp) (insert "\n"))
8161 (setq ins-end (point))
8162 (goto-char ins-point)
8163 (org-skip-whitespace)
8164 (when (and (< arg 0)
8165 (org-first-sibling-p)
8166 (> ne-ins ne-beg))
8167 ;; Move whitespace back to beginning
8168 (save-excursion
8169 (goto-char ins-end)
8170 (let ((kill-whole-line t))
8171 (kill-line (- ne-ins ne-beg)) (point)))
8172 (insert (make-string (- ne-ins ne-beg) ?\n)))
8173 (move-marker ins-point nil)
8174 (if folded
8175 (hide-subtree)
8176 (org-show-entry)
8177 (show-children)
8178 (org-cycle-hide-drawers 'children))
8179 (org-clean-visibility-after-subtree-move)
8180 ;; move back to the initial column we were at
8181 (move-to-column col)))
8183 (defvar org-subtree-clip ""
8184 "Clipboard for cut and paste of subtrees.
8185 This is actually only a copy of the kill, because we use the normal kill
8186 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8188 (defvar org-subtree-clip-folded nil
8189 "Was the last copied subtree folded?
8190 This is used to fold the tree back after pasting.")
8192 (defun org-cut-subtree (&optional n)
8193 "Cut the current subtree into the clipboard.
8194 With prefix arg N, cut this many sequential subtrees.
8195 This is a short-hand for marking the subtree and then cutting it."
8196 (interactive "p")
8197 (org-copy-subtree n 'cut))
8199 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8200 "Copy the current subtree it in the clipboard.
8201 With prefix arg N, copy this many sequential subtrees.
8202 This is a short-hand for marking the subtree and then copying it.
8203 If CUT is non-nil, actually cut the subtree.
8204 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8205 of some markers in the region, even if CUT is non-nil. This is
8206 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8207 (interactive "p")
8208 (let (beg end folded (beg0 (point)))
8209 (if (org-called-interactively-p 'any)
8210 (org-back-to-heading nil) ; take what looks like a subtree
8211 (org-back-to-heading t)) ; take what is really there
8212 (setq beg (point))
8213 (skip-chars-forward " \t\r\n")
8214 (save-match-data
8215 (if nosubtrees
8216 (outline-next-heading)
8217 (save-excursion (outline-end-of-heading)
8218 (setq folded (outline-invisible-p)))
8219 (condition-case nil
8220 (org-forward-heading-same-level (1- n) t)
8221 (error nil))
8222 (org-end-of-subtree t t)))
8223 (setq end (point))
8224 (goto-char beg0)
8225 (when (> end beg)
8226 (setq org-subtree-clip-folded folded)
8227 (when (or cut force-store-markers)
8228 (org-save-markers-in-region beg end))
8229 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8230 (setq org-subtree-clip (current-kill 0))
8231 (message "%s: Subtree(s) with %d characters"
8232 (if cut "Cut" "Copied")
8233 (length org-subtree-clip)))))
8235 (defun org-paste-subtree (&optional level tree for-yank)
8236 "Paste the clipboard as a subtree, with modification of headline level.
8237 The entire subtree is promoted or demoted in order to match a new headline
8238 level.
8240 If the cursor is at the beginning of a headline, the same level as
8241 that headline is used to paste the tree.
8243 If not, the new level is derived from the *visible* headings
8244 before and after the insertion point, and taken to be the inferior headline
8245 level of the two. So if the previous visible heading is level 3 and the
8246 next is level 4 (or vice versa), level 4 will be used for insertion.
8247 This makes sure that the subtree remains an independent subtree and does
8248 not swallow low level entries.
8250 You can also force a different level, either by using a numeric prefix
8251 argument, or by inserting the heading marker by hand. For example, if the
8252 cursor is after \"*****\", then the tree will be shifted to level 5.
8254 If optional TREE is given, use this text instead of the kill ring.
8256 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8257 move back over whitespace before inserting, and move point to the end of
8258 the inserted text when done."
8259 (interactive "P")
8260 (setq tree (or tree (and kill-ring (current-kill 0))))
8261 (unless (org-kill-is-subtree-p tree)
8262 (user-error "%s"
8263 (substitute-command-keys
8264 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8265 (org-with-limited-levels
8266 (let* ((visp (not (outline-invisible-p)))
8267 (txt tree)
8268 (^re_ "\\(\\*+\\)[ \t]*")
8269 (old-level (if (string-match org-outline-regexp-bol txt)
8270 (- (match-end 0) (match-beginning 0) 1)
8271 -1))
8272 (force-level (cond (level (prefix-numeric-value level))
8273 ((and (looking-at "[ \t]*$")
8274 (string-match
8275 "^\\*+$" (buffer-substring
8276 (point-at-bol) (point))))
8277 (- (match-end 1) (match-beginning 1)))
8278 ((and (bolp)
8279 (looking-at org-outline-regexp))
8280 (- (match-end 0) (point) 1))))
8281 (previous-level (save-excursion
8282 (condition-case nil
8283 (progn
8284 (outline-previous-visible-heading 1)
8285 (if (looking-at ^re_)
8286 (- (match-end 0) (match-beginning 0) 1)
8288 (error 1))))
8289 (next-level (save-excursion
8290 (condition-case nil
8291 (progn
8292 (or (looking-at org-outline-regexp)
8293 (outline-next-visible-heading 1))
8294 (if (looking-at ^re_)
8295 (- (match-end 0) (match-beginning 0) 1)
8297 (error 1))))
8298 (new-level (or force-level (max previous-level next-level)))
8299 (shift (if (or (= old-level -1)
8300 (= new-level -1)
8301 (= old-level new-level))
8303 (- new-level old-level)))
8304 (delta (if (> shift 0) -1 1))
8305 (func (if (> shift 0) 'org-demote 'org-promote))
8306 (org-odd-levels-only nil)
8307 beg end newend)
8308 ;; Remove the forced level indicator
8309 (if force-level
8310 (delete-region (point-at-bol) (point)))
8311 ;; Paste
8312 (beginning-of-line (if (bolp) 1 2))
8313 (setq beg (point))
8314 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8315 (insert-before-markers txt)
8316 (unless (string-match "\n\\'" txt) (insert "\n"))
8317 (setq newend (point))
8318 (org-reinstall-markers-in-region beg)
8319 (setq end (point))
8320 (goto-char beg)
8321 (skip-chars-forward " \t\n\r")
8322 (setq beg (point))
8323 (if (and (outline-invisible-p) visp)
8324 (save-excursion (outline-show-heading)))
8325 ;; Shift if necessary
8326 (unless (= shift 0)
8327 (save-restriction
8328 (narrow-to-region beg end)
8329 (while (not (= shift 0))
8330 (org-map-region func (point-min) (point-max))
8331 (setq shift (+ delta shift)))
8332 (goto-char (point-min))
8333 (setq newend (point-max))))
8334 (when (or (org-called-interactively-p 'interactive) for-yank)
8335 (message "Clipboard pasted as level %d subtree" new-level))
8336 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8337 kill-ring
8338 (eq org-subtree-clip (current-kill 0))
8339 org-subtree-clip-folded)
8340 ;; The tree was folded before it was killed/copied
8341 (hide-subtree))
8342 (and for-yank (goto-char newend)))))
8344 (defun org-kill-is-subtree-p (&optional txt)
8345 "Check if the current kill is an outline subtree, or a set of trees.
8346 Returns nil if kill does not start with a headline, or if the first
8347 headline level is not the largest headline level in the tree.
8348 So this will actually accept several entries of equal levels as well,
8349 which is OK for `org-paste-subtree'.
8350 If optional TXT is given, check this string instead of the current kill."
8351 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8352 (re (org-get-limited-outline-regexp))
8353 (^re (concat "^" re))
8354 (start-level (and kill
8355 (string-match
8356 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8357 kill)
8358 (- (match-end 2) (match-beginning 2) 1)))
8359 (start (1+ (or (match-beginning 2) -1))))
8360 (if (not start-level)
8361 (progn
8362 nil) ;; does not even start with a heading
8363 (catch 'exit
8364 (while (setq start (string-match ^re kill (1+ start)))
8365 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8366 (throw 'exit nil)))
8367 t))))
8369 (defvar org-markers-to-move nil
8370 "Markers that should be moved with a cut-and-paste operation.
8371 Those markers are stored together with their positions relative to
8372 the start of the region.")
8374 (defun org-save-markers-in-region (beg end)
8375 "Check markers in region.
8376 If these markers are between BEG and END, record their position relative
8377 to BEG, so that after moving the block of text, we can put the markers back
8378 into place.
8379 This function gets called just before an entry or tree gets cut from the
8380 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8381 called immediately, to move the markers with the entries."
8382 (setq org-markers-to-move nil)
8383 (when (featurep 'org-clock)
8384 (org-clock-save-markers-for-cut-and-paste beg end))
8385 (when (featurep 'org-agenda)
8386 (org-agenda-save-markers-for-cut-and-paste beg end)))
8388 (defun org-check-and-save-marker (marker beg end)
8389 "Check if MARKER is between BEG and END.
8390 If yes, remember the marker and the distance to BEG."
8391 (when (and (marker-buffer marker)
8392 (equal (marker-buffer marker) (current-buffer)))
8393 (if (and (>= marker beg) (< marker end))
8394 (push (cons marker (- marker beg)) org-markers-to-move))))
8396 (defun org-reinstall-markers-in-region (beg)
8397 "Move all remembered markers to their position relative to BEG."
8398 (mapc (lambda (x)
8399 (move-marker (car x) (+ beg (cdr x))))
8400 org-markers-to-move)
8401 (setq org-markers-to-move nil))
8403 (defun org-narrow-to-subtree ()
8404 "Narrow buffer to the current subtree."
8405 (interactive)
8406 (save-excursion
8407 (save-match-data
8408 (org-with-limited-levels
8409 (narrow-to-region
8410 (progn (org-back-to-heading t) (point))
8411 (progn (org-end-of-subtree t t)
8412 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8413 (point)))))))
8415 (defun org-narrow-to-block ()
8416 "Narrow buffer to the current block."
8417 (interactive)
8418 (let* ((case-fold-search t)
8419 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8420 "^[ \t]*#\\+end_.*")))
8421 (if blockp
8422 (narrow-to-region (car blockp) (cdr blockp))
8423 (user-error "Not in a block"))))
8425 (eval-when-compile
8426 (defvar org-property-drawer-re))
8428 (defvar org-property-start-re) ;; defined below
8429 (defun org-clone-subtree-with-time-shift (n &optional shift)
8430 "Clone the task (subtree) at point N times.
8431 The clones will be inserted as siblings.
8433 In interactive use, the user will be prompted for the number of
8434 clones to be produced. If the entry has a timestamp, the user
8435 will also be prompted for a time shift, which may be a repeater
8436 as used in time stamps, for example `+3d'. To disable this,
8437 you can call the function with a universal prefix argument.
8439 When a valid repeater is given and the entry contains any time
8440 stamps, the clones will become a sequence in time, with time
8441 stamps in the subtree shifted for each clone produced. If SHIFT
8442 is nil or the empty string, time stamps will be left alone. The
8443 ID property of the original subtree is removed.
8445 If the original subtree did contain time stamps with a repeater,
8446 the following will happen:
8447 - the repeater will be removed in each clone
8448 - an additional clone will be produced, with the current, unshifted
8449 date(s) in the entry.
8450 - the original entry will be placed *after* all the clones, with
8451 repeater intact.
8452 - the start days in the repeater in the original entry will be shifted
8453 to past the last clone.
8454 In this way you can spell out a number of instances of a repeating task,
8455 and still retain the repeater to cover future instances of the task."
8456 (interactive "nNumber of clones to produce: ")
8457 (let ((shift
8458 (or shift
8459 (if (and (not (equal current-prefix-arg '(4)))
8460 (save-excursion
8461 (re-search-forward org-ts-regexp-both
8462 (save-excursion
8463 (org-end-of-subtree t)
8464 (point)) t)))
8465 (read-from-minibuffer
8466 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8467 ""))) ;; No time shift
8468 (n-no-remove -1)
8469 (drawer-re org-drawer-regexp)
8470 beg end template task idprop
8471 shift-n shift-what doshift nmin nmax)
8472 (if (not (and (integerp n) (> n 0)))
8473 (error "Invalid number of replications %s" n))
8474 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8475 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8476 shift)))
8477 (error "Invalid shift specification %s" shift))
8478 (when doshift
8479 (setq shift-n (string-to-number (match-string 1 shift))
8480 shift-what (cdr (assoc (match-string 2 shift)
8481 '(("d" . day) ("w" . week)
8482 ("m" . month) ("y" . year))))))
8483 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8484 (setq nmin 1 nmax n)
8485 (org-back-to-heading t)
8486 (setq beg (point))
8487 (setq idprop (org-entry-get nil "ID"))
8488 (org-end-of-subtree t t)
8489 (or (bolp) (insert "\n"))
8490 (setq end (point))
8491 (setq template (buffer-substring beg end))
8492 (when (and doshift
8493 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8494 (delete-region beg end)
8495 (setq end beg)
8496 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8497 (goto-char end)
8498 (loop for n from nmin to nmax do
8499 ;; prepare clone
8500 (with-temp-buffer
8501 (insert template)
8502 (org-mode)
8503 (goto-char (point-min))
8504 (org-show-subtree)
8505 (and idprop (if org-clone-delete-id
8506 (org-entry-delete nil "ID")
8507 (org-id-get-create t)))
8508 (unless (= n 0)
8509 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8510 (kill-whole-line))
8511 (goto-char (point-min))
8512 (while (re-search-forward drawer-re nil t)
8513 (mapc (lambda (d)
8514 (org-remove-empty-drawer-at d (point))) org-drawers)))
8515 (goto-char (point-min))
8516 (when doshift
8517 (while (re-search-forward org-ts-regexp-both nil t)
8518 (org-timestamp-change (* n shift-n) shift-what))
8519 (unless (= n n-no-remove)
8520 (goto-char (point-min))
8521 (while (re-search-forward org-ts-regexp nil t)
8522 (save-excursion
8523 (goto-char (match-beginning 0))
8524 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8525 (delete-region (match-beginning 1) (match-end 1)))))))
8526 (setq task (buffer-string)))
8527 (insert task))
8528 (goto-char beg)))
8530 ;;; Outline Sorting
8532 (defun org-sort (with-case)
8533 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8534 Optional argument WITH-CASE means sort case-sensitively."
8535 (interactive "P")
8536 (cond
8537 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8538 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8540 (org-call-with-arg 'org-sort-entries with-case))))
8542 (defun org-sort-remove-invisible (s)
8543 "Remove invisible links from string S."
8544 (remove-text-properties 0 (length s) org-rm-props s)
8545 (while (string-match org-bracket-link-regexp s)
8546 (setq s (replace-match (if (match-end 2)
8547 (match-string 3 s)
8548 (match-string 1 s)) t t s)))
8549 (let ((st (format " %s " s)))
8550 (while (string-match org-emph-re st)
8551 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8552 (setq s (substring st 1 -1)))
8555 (defvar org-priority-regexp) ; defined later in the file
8557 (defvar org-after-sorting-entries-or-items-hook nil
8558 "Hook that is run after a bunch of entries or items have been sorted.
8559 When children are sorted, the cursor is in the parent line when this
8560 hook gets called. When a region or a plain list is sorted, the cursor
8561 will be in the first entry of the sorted region/list.")
8563 (defun org-sort-entries
8564 (&optional with-case sorting-type getkey-func compare-func property)
8565 "Sort entries on a certain level of an outline tree.
8566 If there is an active region, the entries in the region are sorted.
8567 Else, if the cursor is before the first entry, sort the top-level items.
8568 Else, the children of the entry at point are sorted.
8570 Sorting can be alphabetically, numerically, by date/time as given by
8571 a time stamp, by a property, by priority order, or by a custom function.
8573 The command prompts for the sorting type unless it has been given to the
8574 function through the SORTING-TYPE argument, which needs to be a character,
8575 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8576 precise meaning of each character:
8578 n Numerically, by converting the beginning of the entry/item to a number.
8579 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8580 o By order of TODO keywords.
8581 t By date/time, either the first active time stamp in the entry, or, if
8582 none exist, by the first inactive one.
8583 s By the scheduled date/time.
8584 d By deadline date/time.
8585 c By creation time, which is assumed to be the first inactive time stamp
8586 at the beginning of a line.
8587 p By priority according to the cookie.
8588 r By the value of a property.
8590 Capital letters will reverse the sort order.
8592 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8593 called with point at the beginning of the record. It must return either
8594 a string or a number that should serve as the sorting key for that record.
8596 Comparing entries ignores case by default. However, with an optional argument
8597 WITH-CASE, the sorting considers case as well.
8599 Sorting is done against the visible part of the headlines, it ignores hidden
8600 links."
8601 (interactive "P")
8602 (let ((case-func (if with-case 'identity 'downcase))
8603 (cmstr
8604 ;; The clock marker is lost when using `sort-subr', let's
8605 ;; store the clocking string.
8606 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8607 (save-excursion
8608 (goto-char org-clock-marker)
8609 (looking-back "^.*") (match-string-no-properties 0))))
8610 start beg end stars re re2
8611 txt what tmp)
8612 ;; Find beginning and end of region to sort
8613 (cond
8614 ((org-region-active-p)
8615 ;; we will sort the region
8616 (setq end (region-end)
8617 what "region")
8618 (goto-char (region-beginning))
8619 (if (not (org-at-heading-p)) (outline-next-heading))
8620 (setq start (point)))
8621 ((or (org-at-heading-p)
8622 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8623 ;; we will sort the children of the current headline
8624 (org-back-to-heading)
8625 (setq start (point)
8626 end (progn (org-end-of-subtree t t)
8627 (or (bolp) (insert "\n"))
8628 (org-back-over-empty-lines)
8629 (point))
8630 what "children")
8631 (goto-char start)
8632 (show-subtree)
8633 (outline-next-heading))
8635 ;; we will sort the top-level entries in this file
8636 (goto-char (point-min))
8637 (or (org-at-heading-p) (outline-next-heading))
8638 (setq start (point))
8639 (goto-char (point-max))
8640 (beginning-of-line 1)
8641 (when (looking-at ".*?\\S-")
8642 ;; File ends in a non-white line
8643 (end-of-line 1)
8644 (insert "\n"))
8645 (setq end (point-max))
8646 (setq what "top-level")
8647 (goto-char start)
8648 (show-all)))
8650 (setq beg (point))
8651 (if (>= beg end) (user-error "Nothing to sort"))
8653 (looking-at "\\(\\*+\\)")
8654 (setq stars (match-string 1)
8655 re (concat "^" (regexp-quote stars) " +")
8656 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8657 txt (buffer-substring beg end))
8658 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8659 (if (and (not (equal stars "*")) (string-match re2 txt))
8660 (user-error "Region to sort contains a level above the first entry"))
8662 (unless sorting-type
8663 (message
8664 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8665 [t]ime [s]cheduled [d]eadline [c]reated
8666 A/N/P/R/O/F/T/S/D/C means reversed:"
8667 what)
8668 (setq sorting-type (read-char-exclusive))
8670 (unless getkey-func
8671 (and (= (downcase sorting-type) ?f)
8672 (setq getkey-func
8673 (org-icompleting-read "Sort using function: "
8674 obarray 'fboundp t nil nil))
8675 (setq getkey-func (intern getkey-func))))
8677 (and (= (downcase sorting-type) ?r)
8678 (not property)
8679 (setq property
8680 (org-icompleting-read "Property: "
8681 (mapcar 'list (org-buffer-property-keys t))
8682 nil t))))
8684 (message "Sorting entries...")
8686 (save-restriction
8687 (narrow-to-region start end)
8688 (let ((dcst (downcase sorting-type))
8689 (case-fold-search nil)
8690 (now (current-time)))
8691 (sort-subr
8692 (/= dcst sorting-type)
8693 ;; This function moves to the beginning character of the "record" to
8694 ;; be sorted.
8695 (lambda nil
8696 (if (re-search-forward re nil t)
8697 (goto-char (match-beginning 0))
8698 (goto-char (point-max))))
8699 ;; This function moves to the last character of the "record" being
8700 ;; sorted.
8701 (lambda nil
8702 (save-match-data
8703 (condition-case nil
8704 (outline-forward-same-level 1)
8705 (error
8706 (goto-char (point-max))))))
8707 ;; This function returns the value that gets sorted against.
8708 (lambda nil
8709 (cond
8710 ((= dcst ?n)
8711 (if (looking-at org-complex-heading-regexp)
8712 (string-to-number (org-sort-remove-invisible (match-string 4)))
8713 nil))
8714 ((= dcst ?a)
8715 (if (looking-at org-complex-heading-regexp)
8716 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8717 nil))
8718 ((= dcst ?t)
8719 (let ((end (save-excursion (outline-next-heading) (point))))
8720 (if (or (re-search-forward org-ts-regexp end t)
8721 (re-search-forward org-ts-regexp-both end t))
8722 (org-time-string-to-seconds (match-string 0))
8723 (org-float-time now))))
8724 ((= dcst ?c)
8725 (let ((end (save-excursion (outline-next-heading) (point))))
8726 (if (re-search-forward
8727 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8728 end t)
8729 (org-time-string-to-seconds (match-string 0))
8730 (org-float-time now))))
8731 ((= dcst ?s)
8732 (let ((end (save-excursion (outline-next-heading) (point))))
8733 (if (re-search-forward org-scheduled-time-regexp end t)
8734 (org-time-string-to-seconds (match-string 1))
8735 (org-float-time now))))
8736 ((= dcst ?d)
8737 (let ((end (save-excursion (outline-next-heading) (point))))
8738 (if (re-search-forward org-deadline-time-regexp end t)
8739 (org-time-string-to-seconds (match-string 1))
8740 (org-float-time now))))
8741 ((= dcst ?p)
8742 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8743 (string-to-char (match-string 2))
8744 org-default-priority))
8745 ((= dcst ?r)
8746 (or (org-entry-get nil property) ""))
8747 ((= dcst ?o)
8748 (if (looking-at org-complex-heading-regexp)
8749 (- 9999 (length (member (match-string 2)
8750 org-todo-keywords-1)))))
8751 ((= dcst ?f)
8752 (if getkey-func
8753 (progn
8754 (setq tmp (funcall getkey-func))
8755 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8756 tmp)
8757 (error "Invalid key function `%s'" getkey-func)))
8758 (t (error "Invalid sorting type `%c'" sorting-type))))
8760 (cond
8761 ((= dcst ?a) 'string<)
8762 ((= dcst ?f) compare-func)
8763 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8764 (run-hooks 'org-after-sorting-entries-or-items-hook)
8765 ;; Reset the clock marker if needed
8766 (when cmstr
8767 (save-excursion
8768 (goto-char start)
8769 (search-forward cmstr nil t)
8770 (move-marker org-clock-marker (point))))
8771 (message "Sorting entries...done")))
8773 (defun org-do-sort (table what &optional with-case sorting-type)
8774 "Sort TABLE of WHAT according to SORTING-TYPE.
8775 The user will be prompted for the SORTING-TYPE if the call to this
8776 function does not specify it. WHAT is only for the prompt, to indicate
8777 what is being sorted. The sorting key will be extracted from
8778 the car of the elements of the table.
8779 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8780 (unless sorting-type
8781 (message
8782 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8783 what)
8784 (setq sorting-type (read-char-exclusive)))
8785 (let ((dcst (downcase sorting-type))
8786 extractfun comparefun)
8787 ;; Define the appropriate functions
8788 (cond
8789 ((= dcst ?n)
8790 (setq extractfun 'string-to-number
8791 comparefun (if (= dcst sorting-type) '< '>)))
8792 ((= dcst ?a)
8793 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8794 (lambda(x) (downcase (org-sort-remove-invisible x))))
8795 comparefun (if (= dcst sorting-type)
8796 'string<
8797 (lambda (a b) (and (not (string< a b))
8798 (not (string= a b)))))))
8799 ((= dcst ?t)
8800 (setq extractfun
8801 (lambda (x)
8802 (if (or (string-match org-ts-regexp x)
8803 (string-match org-ts-regexp-both x))
8804 (org-float-time
8805 (org-time-string-to-time (match-string 0 x)))
8807 comparefun (if (= dcst sorting-type) '< '>)))
8808 (t (error "Invalid sorting type `%c'" sorting-type)))
8810 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8811 table)
8812 (lambda (a b) (funcall comparefun (car a) (car b))))))
8815 ;;; The orgstruct minor mode
8817 ;; Define a minor mode which can be used in other modes in order to
8818 ;; integrate the org-mode structure editing commands.
8820 ;; This is really a hack, because the org-mode structure commands use
8821 ;; keys which normally belong to the major mode. Here is how it
8822 ;; works: The minor mode defines all the keys necessary to operate the
8823 ;; structure commands, but wraps the commands into a function which
8824 ;; tests if the cursor is currently at a headline or a plain list
8825 ;; item. If that is the case, the structure command is used,
8826 ;; temporarily setting many Org-mode variables like regular
8827 ;; expressions for filling etc. However, when any of those keys is
8828 ;; used at a different location, function uses `key-binding' to look
8829 ;; up if the key has an associated command in another currently active
8830 ;; keymap (minor modes, major mode, global), and executes that
8831 ;; command. There might be problems if any of the keys is otherwise
8832 ;; used as a prefix key.
8834 (defcustom orgstruct-heading-prefix-regexp ""
8835 "Regexp that matches the custom prefix of Org headlines in
8836 orgstruct(++)-mode."
8837 :group 'org
8838 :version "24.4"
8839 :package-version '(Org . "8.3")
8840 :type 'regexp)
8841 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8843 (defcustom orgstruct-setup-hook nil
8844 "Hook run after orgstruct-mode-map is filled."
8845 :group 'org
8846 :version "24.4"
8847 :package-version '(Org . "8.0")
8848 :type 'hook)
8850 (defvar orgstruct-initialized nil)
8852 (defvar org-local-vars nil
8853 "List of local variables, for use by `orgstruct-mode'.")
8855 ;;;###autoload
8856 (define-minor-mode orgstruct-mode
8857 "Toggle the minor mode `orgstruct-mode'.
8858 This mode is for using Org-mode structure commands in other
8859 modes. The following keys behave as if Org-mode were active, if
8860 the cursor is on a headline, or on a plain list item (both as
8861 defined by Org-mode)."
8862 nil " OrgStruct" (make-sparse-keymap)
8863 (funcall (if orgstruct-mode
8864 'add-to-invisibility-spec
8865 'remove-from-invisibility-spec)
8866 '(outline . t))
8867 (when orgstruct-mode
8868 (org-load-modules-maybe)
8869 (unless orgstruct-initialized
8870 (orgstruct-setup)
8871 (setq orgstruct-initialized t))))
8873 ;;;###autoload
8874 (defun turn-on-orgstruct ()
8875 "Unconditionally turn on `orgstruct-mode'."
8876 (orgstruct-mode 1))
8878 (defvar org-fb-vars nil)
8879 (make-variable-buffer-local 'org-fb-vars)
8880 (defun orgstruct++-mode (&optional arg)
8881 "Toggle `orgstruct-mode', the enhanced version of it.
8882 In addition to setting orgstruct-mode, this also exports all
8883 indentation and autofilling variables from org-mode into the
8884 buffer. It will also recognize item context in multiline items."
8885 (interactive "P")
8886 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8887 (if (< arg 1)
8888 (progn (orgstruct-mode -1)
8889 (mapc (lambda(v)
8890 (org-set-local (car v)
8891 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8892 org-fb-vars))
8893 (orgstruct-mode 1)
8894 (setq org-fb-vars nil)
8895 (unless org-local-vars
8896 (setq org-local-vars (org-get-local-variables)))
8897 (let (var val)
8898 (mapc
8899 (lambda (x)
8900 (when (string-match
8901 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8902 (symbol-name (car x)))
8903 (setq var (car x) val (nth 1 x))
8904 (push (list var `(quote ,(eval var))) org-fb-vars)
8905 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8906 org-local-vars)
8907 (org-set-local 'orgstruct-is-++ t))))
8909 (defvar orgstruct-is-++ nil
8910 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8911 (make-variable-buffer-local 'orgstruct-is-++)
8913 ;;;###autoload
8914 (defun turn-on-orgstruct++ ()
8915 "Unconditionally turn on `orgstruct++-mode'."
8916 (orgstruct++-mode 1))
8918 (defun orgstruct-error ()
8919 "Error when there is no default binding for a structure key."
8920 (interactive)
8921 (funcall (if (fboundp 'user-error)
8922 'user-error
8923 'error)
8924 "This key has no function outside structure elements"))
8926 (defun orgstruct-setup ()
8927 "Setup orgstruct keymap."
8928 (dolist (cell '((org-demote . t)
8929 (org-metaleft . t)
8930 (org-metaright . t)
8931 (org-promote . t)
8932 (org-shiftmetaleft . t)
8933 (org-shiftmetaright . t)
8934 org-backward-element
8935 org-backward-heading-same-level
8936 org-ctrl-c-ret
8937 org-ctrl-c-minus
8938 org-ctrl-c-star
8939 org-cycle
8940 org-forward-heading-same-level
8941 org-insert-heading
8942 org-insert-heading-respect-content
8943 org-kill-note-or-show-branches
8944 org-mark-subtree
8945 org-meta-return
8946 org-metadown
8947 org-metaup
8948 org-narrow-to-subtree
8949 org-promote-subtree
8950 org-reveal
8951 org-shiftdown
8952 org-shiftleft
8953 org-shiftmetadown
8954 org-shiftmetaup
8955 org-shiftright
8956 org-shifttab
8957 org-shifttab
8958 org-shiftup
8959 org-show-subtree
8960 org-sort
8961 org-up-element
8962 outline-demote
8963 outline-next-visible-heading
8964 outline-previous-visible-heading
8965 outline-promote
8966 outline-up-heading
8967 show-children))
8968 (let ((f (or (car-safe cell) cell))
8969 (disable-when-heading-prefix (cdr-safe cell)))
8970 (when (fboundp f)
8971 (let ((new-bindings))
8972 (dolist (binding (nconc (where-is-internal f org-mode-map)
8973 (where-is-internal f outline-mode-map)))
8974 (push binding new-bindings)
8975 ;; TODO use local-function-key-map
8976 (dolist (rep '(("<tab>" . "TAB")
8977 ("<return>" . "RET")
8978 ("<escape>" . "ESC")
8979 ("<delete>" . "DEL")))
8980 (setq binding (read-kbd-macro
8981 (let ((case-fold-search))
8982 (replace-regexp-in-string
8983 (regexp-quote (cdr rep))
8984 (car rep)
8985 (key-description binding)))))
8986 (pushnew binding new-bindings :test 'equal)))
8987 (dolist (binding new-bindings)
8988 (let ((key (lookup-key orgstruct-mode-map binding)))
8989 (when (or (not key) (numberp key))
8990 (condition-case nil
8991 (org-defkey orgstruct-mode-map
8992 binding
8993 (orgstruct-make-binding f binding disable-when-heading-prefix))
8994 (error nil)))))))))
8995 (run-hooks 'orgstruct-setup-hook))
8997 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8998 "Create a function for binding in the structure minor mode.
8999 FUN is the command to call inside a table. KEY is the key that
9000 should be checked in for a command to execute outside of tables.
9001 Non-nil `disable-when-heading-prefix' means to disable the command
9002 if `orgstruct-heading-prefix-regexp' is not empty."
9003 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9004 (let ((nname name)
9005 (i 0))
9006 (while (fboundp (intern nname))
9007 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9008 (setq name (intern nname)))
9009 (eval
9010 (let ((bindings '((org-heading-regexp
9011 (concat "^"
9012 orgstruct-heading-prefix-regexp
9013 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9014 (org-outline-regexp
9015 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9016 (org-outline-regexp-bol
9017 (concat "^" org-outline-regexp))
9018 (outline-regexp org-outline-regexp)
9019 (outline-heading-end-regexp "\n")
9020 (outline-level 'org-outline-level)
9021 (outline-heading-alist))))
9022 `(defun ,name (arg)
9023 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9024 "Outside of structure, run the binding of `"
9025 (key-description key) "'."
9026 (when disable-when-heading-prefix
9027 (concat
9028 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9029 "back to the default binding due to limitations of Org's implementation of\n"
9030 "`" (symbol-name fun) "'.")))
9031 (interactive "p")
9032 (let* ((disable
9033 ,(and disable-when-heading-prefix
9034 '(not (string= orgstruct-heading-prefix-regexp ""))))
9035 (fallback
9036 (or disable
9037 (not
9038 (let* ,bindings
9039 (org-context-p 'headline 'item
9040 ,(when (memq fun
9041 '(org-insert-heading
9042 org-insert-heading-respect-content
9043 org-meta-return))
9044 '(when orgstruct-is-++
9045 'item-body))))))))
9046 (if fallback
9047 (let* ((orgstruct-mode)
9048 (binding
9049 (loop with key = ,key
9050 for rep in
9051 '(nil
9052 ("<\\([^>]*\\)tab>" . "\\1TAB")
9053 ("<\\([^>]*\\)return>" . "\\1RET")
9054 ("<\\([^>]*\\)escape>" . "\\1ESC")
9055 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9057 (when rep
9058 (setq key (read-kbd-macro
9059 (let ((case-fold-search))
9060 (replace-regexp-in-string
9061 (car rep)
9062 (cdr rep)
9063 (key-description key))))))
9064 thereis (key-binding key))))
9065 (if (keymapp binding)
9066 (set-transient-map binding)
9067 (let ((func (or binding
9068 (unless disable
9069 'orgstruct-error))))
9070 (when func
9071 (call-interactively func)))))
9072 (org-run-like-in-org-mode
9073 (lambda ()
9074 (interactive)
9075 (let* ,bindings
9076 (call-interactively ',fun)))))))))
9077 name))
9079 (defun org-contextualize-keys (alist contexts)
9080 "Return valid elements in ALIST depending on CONTEXTS.
9082 `org-agenda-custom-commands' or `org-capture-templates' are the
9083 values used for ALIST, and `org-agenda-custom-commands-contexts'
9084 or `org-capture-templates-contexts' are the associated contexts
9085 definitions."
9086 (let ((contexts
9087 ;; normalize contexts
9088 (mapcar
9089 (lambda(c) (cond ((listp (cadr c))
9090 (list (car c) (car c) (cadr c)))
9091 ((string= "" (cadr c))
9092 (list (car c) (car c) (caddr c)))
9093 (t c))) contexts))
9094 (a alist) c r s)
9095 ;; loop over all commands or templates
9096 (while (setq c (pop a))
9097 (let (vrules repl)
9098 (cond
9099 ((not (assoc (car c) contexts))
9100 (push c r))
9101 ((and (assoc (car c) contexts)
9102 (setq vrules (org-contextualize-validate-key
9103 (car c) contexts)))
9104 (mapc (lambda (vr)
9105 (when (not (equal (car vr) (cadr vr)))
9106 (setq repl vr))) vrules)
9107 (if (not repl) (push c r)
9108 (push (cadr repl) s)
9109 (push
9110 (cons (car c)
9111 (cdr (or (assoc (cadr repl) alist)
9112 (error "Undefined key `%s' as contextual replacement for `%s'"
9113 (cadr repl) (car c)))))
9114 r))))))
9115 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9116 (delq
9118 (delete-dups
9119 (mapcar (lambda (x)
9120 (let ((tpl (car x)))
9121 (when (not (delq
9123 (mapcar (lambda(y)
9124 (equal y tpl)) s))) x)))
9125 (reverse r))))))
9127 (defun org-contextualize-validate-key (key contexts)
9128 "Check CONTEXTS for agenda or capture KEY."
9129 (let (r rr res)
9130 (while (setq r (pop contexts))
9131 (mapc
9132 (lambda (rr)
9133 (when
9134 (and (equal key (car r))
9135 (if (functionp rr) (funcall rr)
9136 (or (and (eq (car rr) 'in-file)
9137 (buffer-file-name)
9138 (string-match (cdr rr) (buffer-file-name)))
9139 (and (eq (car rr) 'in-mode)
9140 (string-match (cdr rr) (symbol-name major-mode)))
9141 (and (eq (car rr) 'in-buffer)
9142 (string-match (cdr rr) (buffer-name)))
9143 (when (and (eq (car rr) 'not-in-file)
9144 (buffer-file-name))
9145 (not (string-match (cdr rr) (buffer-file-name))))
9146 (when (eq (car rr) 'not-in-mode)
9147 (not (string-match (cdr rr) (symbol-name major-mode))))
9148 (when (eq (car rr) 'not-in-buffer)
9149 (not (string-match (cdr rr) (buffer-name)))))))
9150 (push r res)))
9151 (car (last r))))
9152 (delete-dups (delq nil res))))
9154 (defun org-context-p (&rest contexts)
9155 "Check if local context is any of CONTEXTS.
9156 Possible values in the list of contexts are `table', `headline', and `item'."
9157 (let ((pos (point)))
9158 (goto-char (point-at-bol))
9159 (prog1 (or (and (memq 'table contexts)
9160 (looking-at "[ \t]*|"))
9161 (and (memq 'headline contexts)
9162 (looking-at org-outline-regexp))
9163 (and (memq 'item contexts)
9164 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9165 (and (memq 'item-body contexts)
9166 (org-in-item-p)))
9167 (goto-char pos))))
9169 (defun org-get-local-variables ()
9170 "Return a list of all local variables in an Org mode buffer."
9171 (let (varlist)
9172 (with-current-buffer (get-buffer-create "*Org tmp*")
9173 (erase-buffer)
9174 (org-mode)
9175 (setq varlist (buffer-local-variables)))
9176 (kill-buffer "*Org tmp*")
9177 (delq nil
9178 (mapcar
9179 (lambda (x)
9180 (setq x
9181 (if (symbolp x)
9182 (list x)
9183 (list (car x) (cdr x))))
9184 (if (and (not (get (car x) 'org-state))
9185 (string-match
9186 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9187 (symbol-name (car x))))
9188 x nil))
9189 varlist))))
9191 (defun org-clone-local-variables (from-buffer &optional regexp)
9192 "Clone local variables from FROM-BUFFER.
9193 Optional argument REGEXP selects variables to clone."
9194 (mapc
9195 (lambda (pair)
9196 (and (symbolp (car pair))
9197 (or (null regexp)
9198 (string-match regexp (symbol-name (car pair))))
9199 (set (make-local-variable (car pair))
9200 (cdr pair))))
9201 (buffer-local-variables from-buffer)))
9203 ;;;###autoload
9204 (defun org-run-like-in-org-mode (cmd)
9205 "Run a command, pretending that the current buffer is in Org-mode.
9206 This will temporarily bind local variables that are typically bound in
9207 Org-mode to the values they have in Org-mode, and then interactively
9208 call CMD."
9209 (org-load-modules-maybe)
9210 (unless org-local-vars
9211 (setq org-local-vars (org-get-local-variables)))
9212 (let (binds)
9213 (dolist (var org-local-vars)
9214 (when (or (not (boundp (car var)))
9215 (eq (symbol-value (car var))
9216 (default-value (car var))))
9217 (push (list (car var) `(quote ,(cadr var))) binds)))
9218 (eval `(let ,binds
9219 (call-interactively (quote ,cmd))))))
9221 ;;;; Archiving
9223 (defun org-get-category (&optional pos force-refresh)
9224 "Get the category applying to position POS."
9225 (save-match-data
9226 (if force-refresh (org-refresh-category-properties))
9227 (let ((pos (or pos (point))))
9228 (or (get-text-property pos 'org-category)
9229 (progn (org-refresh-category-properties)
9230 (get-text-property pos 'org-category))))))
9232 (defun org-refresh-category-properties ()
9233 "Refresh category text properties in the buffer."
9234 (let ((case-fold-search t)
9235 (inhibit-read-only t)
9236 (def-cat (cond
9237 ((null org-category)
9238 (if buffer-file-name
9239 (file-name-sans-extension
9240 (file-name-nondirectory buffer-file-name))
9241 "???"))
9242 ((symbolp org-category) (symbol-name org-category))
9243 (t org-category)))
9244 beg end cat pos optionp)
9245 (org-with-silent-modifications
9246 (save-excursion
9247 (save-restriction
9248 (widen)
9249 (goto-char (point-min))
9250 (put-text-property (point) (point-max) 'org-category def-cat)
9251 (while (re-search-forward
9252 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9253 (setq pos (match-end 0)
9254 optionp (equal (char-after (match-beginning 0)) ?#)
9255 cat (org-trim (match-string 2)))
9256 (if optionp
9257 (setq beg (point-at-bol) end (point-max))
9258 (org-back-to-heading t)
9259 (setq beg (point) end (org-end-of-subtree t t)))
9260 (put-text-property beg end 'org-category cat)
9261 (put-text-property beg end 'org-category-position beg)
9262 (goto-char pos)))))))
9264 (defun org-refresh-properties (dprop tprop)
9265 "Refresh buffer text properties.
9266 DPROP is the drawer property and TPROP is the corresponding text
9267 property to set."
9268 (let ((case-fold-search t)
9269 (inhibit-read-only t) p)
9270 (org-with-silent-modifications
9271 (save-excursion
9272 (save-restriction
9273 (widen)
9274 (goto-char (point-min))
9275 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9276 (setq p (org-match-string-no-properties 1))
9277 (save-excursion
9278 (org-back-to-heading t)
9279 (put-text-property
9280 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9283 ;;;; Link Stuff
9285 ;;; Link abbreviations
9287 (defun org-link-expand-abbrev (link)
9288 "Apply replacements as defined in `org-link-abbrev-alist'."
9289 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9290 (let* ((key (match-string 1 link))
9291 (as (or (assoc key org-link-abbrev-alist-local)
9292 (assoc key org-link-abbrev-alist)))
9293 (tag (and (match-end 2) (match-string 3 link)))
9294 rpl)
9295 (if (not as)
9296 link
9297 (setq rpl (cdr as))
9298 (cond
9299 ((symbolp rpl) (funcall rpl tag))
9300 ((string-match "%(\\([^)]+\\))" rpl)
9301 (replace-match
9302 (save-match-data
9303 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9304 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9305 ((string-match "%h" rpl)
9306 (replace-match (url-hexify-string (or tag "")) t t rpl))
9307 (t (concat rpl tag)))))
9308 link))
9310 ;;; Storing and inserting links
9312 (defvar org-insert-link-history nil
9313 "Minibuffer history for links inserted with `org-insert-link'.")
9315 (defvar org-stored-links nil
9316 "Contains the links stored with `org-store-link'.")
9318 (defvar org-store-link-plist nil
9319 "Plist with info about the most recently link created with `org-store-link'.")
9321 (defvar org-link-protocols nil
9322 "Link protocols added to Org-mode using `org-add-link-type'.")
9324 (defvar org-store-link-functions nil
9325 "List of functions that are called to create and store a link.
9326 Each function will be called in turn until one returns a non-nil
9327 value. Each function should check if it is responsible for creating
9328 this link (for example by looking at the major mode).
9329 If not, it must exit and return nil.
9330 If yes, it should return a non-nil value after a calling
9331 `org-store-link-props' with a list of properties and values.
9332 Special properties are:
9334 :type The link prefix, like \"http\". This must be given.
9335 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9336 This is obligatory as well.
9337 :description Optional default description for the second pair
9338 of brackets in an Org-mode link. The user can still change
9339 this when inserting this link into an Org-mode buffer.
9341 In addition to these, any additional properties can be specified
9342 and then used in capture templates.")
9344 (defun org-add-link-type (type &optional follow export)
9345 "Add TYPE to the list of `org-link-types'.
9346 Re-compute all regular expressions depending on `org-link-types'
9348 FOLLOW and EXPORT are two functions.
9350 FOLLOW should take the link path as the single argument and do whatever
9351 is necessary to follow the link, for example find a file or display
9352 a mail message.
9354 EXPORT should format the link path for export to one of the export formats.
9355 It should be a function accepting three arguments:
9357 path the path of the link, the text after the prefix (like \"http:\")
9358 desc the description of the link, if any, or a description added by
9359 org-export-normalize-links if there is none
9360 format the export format, a symbol like `html' or `latex' or `ascii'..
9362 The function may use the FORMAT information to return different values
9363 depending on the format. The return value will be put literally into
9364 the exported file. If the return value is nil, this means Org should
9365 do what it normally does with links which do not have EXPORT defined.
9367 Org-mode has a built-in default for exporting links. If you are happy with
9368 this default, there is no need to define an export function for the link
9369 type. For a simple example of an export function, see `org-bbdb.el'."
9370 (add-to-list 'org-link-types type t)
9371 (org-make-link-regexps)
9372 (if (assoc type org-link-protocols)
9373 (setcdr (assoc type org-link-protocols) (list follow export))
9374 (push (list type follow export) org-link-protocols)))
9376 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9377 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9379 ;;;###autoload
9380 (defun org-store-link (arg)
9381 "\\<org-mode-map>Store an org-link to the current location.
9382 This link is added to `org-stored-links' and can later be inserted
9383 into an org-buffer with \\[org-insert-link].
9385 For some link types, a prefix arg is interpreted.
9386 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9387 For file links, arg negates `org-context-in-file-links'.
9389 A double prefix arg force skipping storing functions that are not
9390 part of Org's core.
9392 A triple prefix arg force storing a link for each line in the
9393 active region."
9394 (interactive "P")
9395 (org-load-modules-maybe)
9396 (if (and (equal arg '(64)) (org-region-active-p))
9397 (save-excursion
9398 (let ((end (region-end)))
9399 (goto-char (region-beginning))
9400 (set-mark (point))
9401 (while (< (point-at-eol) end)
9402 (move-end-of-line 1) (activate-mark)
9403 (let (current-prefix-arg)
9404 (call-interactively 'org-store-link))
9405 (move-beginning-of-line 2)
9406 (set-mark (point)))))
9407 (org-with-limited-levels
9408 (setq org-store-link-plist nil)
9409 (let (link cpltxt desc description search
9410 txt custom-id agenda-link sfuns sfunsn)
9411 (cond
9413 ;; Store a link using an external link type
9414 ((and (not (equal arg '(16)))
9415 (setq sfuns
9416 (delq
9417 nil (mapcar (lambda (f)
9418 (let (fs) (if (funcall f) (push f fs))))
9419 org-store-link-functions))
9420 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9421 (or (and (cdr sfuns)
9422 (funcall (intern
9423 (completing-read
9424 "Which function for creating the link? "
9425 sfunsn t (car sfunsn)))))
9426 (funcall (caar sfuns)))
9427 (setq link (plist-get org-store-link-plist :link)
9428 desc (or (plist-get org-store-link-plist
9429 :description) link))))
9431 ;; Store a link from a source code buffer
9432 ((org-src-edit-buffer-p)
9433 (let (label gc)
9434 (while (or (not label)
9435 (save-excursion
9436 (save-restriction
9437 (widen)
9438 (goto-char (point-min))
9439 (re-search-forward
9440 (regexp-quote (format org-coderef-label-format label))
9441 nil t))))
9442 (when label (message "Label exists already") (sit-for 2))
9443 (setq label (read-string "Code line label: " label)))
9444 (end-of-line 1)
9445 (setq link (format org-coderef-label-format label))
9446 (setq gc (- 79 (length link)))
9447 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9448 (insert link)
9449 (setq link (concat "(" label ")") desc nil)))
9451 ;; We are in the agenda, link to referenced location
9452 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9453 (let ((m (or (get-text-property (point) 'org-hd-marker)
9454 (get-text-property (point) 'org-marker))))
9455 (when m
9456 (org-with-point-at m
9457 (setq agenda-link
9458 (if (org-called-interactively-p 'any)
9459 (call-interactively 'org-store-link)
9460 (org-store-link nil)))))))
9462 ((eq major-mode 'calendar-mode)
9463 (let ((cd (calendar-cursor-to-date)))
9464 (setq link
9465 (format-time-string
9466 (car org-time-stamp-formats)
9467 (apply 'encode-time
9468 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9469 nil nil nil))))
9470 (org-store-link-props :type "calendar" :date cd)))
9472 ((eq major-mode 'help-mode)
9473 (setq link (concat "help:" (save-excursion
9474 (goto-char (point-min))
9475 (looking-at "^[^ ]+")
9476 (match-string 0))))
9477 (org-store-link-props :type "help"))
9479 ((eq major-mode 'w3-mode)
9480 (setq cpltxt (if (and (buffer-name)
9481 (not (string-match "Untitled" (buffer-name))))
9482 (buffer-name)
9483 (url-view-url t))
9484 link (url-view-url t))
9485 (org-store-link-props :type "w3" :url (url-view-url t)))
9487 ((eq major-mode 'image-mode)
9488 (setq cpltxt (concat "file:"
9489 (abbreviate-file-name buffer-file-name))
9490 link cpltxt)
9491 (org-store-link-props :type "image" :file buffer-file-name))
9493 ;; In dired, store a link to the file of the current line
9494 ((eq major-mode 'dired-mode)
9495 (let ((file (dired-get-filename nil t)))
9496 (setq file (if file
9497 (abbreviate-file-name
9498 (expand-file-name (dired-get-filename nil t)))
9499 ;; otherwise, no file so use current directory.
9500 default-directory))
9501 (setq cpltxt (concat "file:" file)
9502 link cpltxt)))
9504 ((setq search (run-hook-with-args-until-success
9505 'org-create-file-search-functions))
9506 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9507 "::" search))
9508 (setq cpltxt (or description link)))
9510 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9511 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9512 (cond
9513 ;; Store a link using the target at point
9514 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9515 (setq cpltxt
9516 (concat "file:"
9517 (abbreviate-file-name
9518 (buffer-file-name (buffer-base-buffer)))
9519 "::" (match-string 1))
9520 link cpltxt))
9521 ((and (featurep 'org-id)
9522 (or (eq org-id-link-to-org-use-id t)
9523 (and (org-called-interactively-p 'any)
9524 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9525 (and (eq org-id-link-to-org-use-id
9526 'create-if-interactive-and-no-custom-id)
9527 (not custom-id))))
9528 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9529 ;; Store a link using the ID at point
9530 (setq link (condition-case nil
9531 (prog1 (org-id-store-link)
9532 (setq desc (plist-get org-store-link-plist
9533 :description)))
9534 (error
9535 ;; Probably before first headline, link only to file
9536 (concat "file:"
9537 (abbreviate-file-name
9538 (buffer-file-name (buffer-base-buffer))))))))
9540 ;; Just link to current headline
9541 (setq cpltxt (concat "file:"
9542 (abbreviate-file-name
9543 (buffer-file-name (buffer-base-buffer)))))
9544 ;; Add a context search string
9545 (when (org-xor org-context-in-file-links arg)
9546 (let* ((ee (org-element-at-point))
9547 (et (org-element-type ee))
9548 (ev (plist-get (cadr ee) :value))
9549 (ek (plist-get (cadr ee) :key))
9550 (eok (and (stringp ek) (string-match "name" ek))))
9551 (setq txt (cond
9552 ((org-at-heading-p) nil)
9553 ((and (eq et 'keyword) eok) ev)
9554 ((org-region-active-p)
9555 (buffer-substring (region-beginning) (region-end)))))
9556 (when (or (null txt) (string-match "\\S-" txt))
9557 (setq cpltxt
9558 (concat cpltxt "::"
9559 (condition-case nil
9560 (org-make-org-heading-search-string txt)
9561 (error "")))
9562 desc (or (and (eq et 'keyword) eok ev)
9563 (nth 4 (ignore-errors (org-heading-components)))
9564 "NONE")))))
9565 (if (string-match "::\\'" cpltxt)
9566 (setq cpltxt (substring cpltxt 0 -2)))
9567 (setq link cpltxt))))
9569 ((buffer-file-name (buffer-base-buffer))
9570 ;; Just link to this file here.
9571 (setq cpltxt (concat "file:"
9572 (abbreviate-file-name
9573 (buffer-file-name (buffer-base-buffer)))))
9574 ;; Add a context string.
9575 (when (org-xor org-context-in-file-links arg)
9576 (setq txt (if (org-region-active-p)
9577 (buffer-substring (region-beginning) (region-end))
9578 (buffer-substring (point-at-bol) (point-at-eol))))
9579 ;; Only use search option if there is some text.
9580 (when (string-match "\\S-" txt)
9581 (setq cpltxt
9582 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9583 desc "NONE")))
9584 (setq link cpltxt))
9586 ((org-called-interactively-p 'interactive)
9587 (user-error "No method for storing a link from this buffer"))
9589 (t (setq link nil)))
9591 ;; We're done setting link and desc, clean up
9592 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9593 (setq link (or link cpltxt)
9594 desc (or desc cpltxt))
9595 (cond ((equal desc "NONE") (setq desc nil))
9596 ((string-match org-bracket-link-analytic-regexp desc)
9597 (let ((d0 (match-string 3 desc))
9598 (p0 (match-string 5 desc)))
9599 (setq desc
9600 (replace-regexp-in-string
9601 org-bracket-link-regexp
9602 (concat (or p0 d0)
9603 (if (equal (length (match-string 0 desc))
9604 (length desc)) "*" "")) desc)))))
9606 ;; Return the link
9607 (if (not (and (or (org-called-interactively-p 'any)
9608 executing-kbd-macro) link))
9609 (or agenda-link (and link (org-make-link-string link desc)))
9610 (push (list link desc) org-stored-links)
9611 (message "Stored: %s" (or desc link))
9612 (when custom-id
9613 (setq link (concat "file:" (abbreviate-file-name
9614 (buffer-file-name)) "::#" custom-id))
9615 (push (list link desc) org-stored-links)))))))
9617 (defun org-store-link-props (&rest plist)
9618 "Store link properties, extract names and addresses."
9619 (let (x adr)
9620 (when (setq x (plist-get plist :from))
9621 (setq adr (mail-extract-address-components x))
9622 (setq plist (plist-put plist :fromname (car adr)))
9623 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9624 (when (setq x (plist-get plist :to))
9625 (setq adr (mail-extract-address-components x))
9626 (setq plist (plist-put plist :toname (car adr)))
9627 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9628 (let ((from (plist-get plist :from))
9629 (to (plist-get plist :to)))
9630 (when (and from to org-from-is-user-regexp)
9631 (setq plist
9632 (plist-put plist :fromto
9633 (if (string-match org-from-is-user-regexp from)
9634 (concat "to %t")
9635 (concat "from %f"))))))
9636 (setq org-store-link-plist plist))
9638 (defun org-add-link-props (&rest plist)
9639 "Add these properties to the link property list."
9640 (let (key value)
9641 (while plist
9642 (setq key (pop plist) value (pop plist))
9643 (setq org-store-link-plist
9644 (plist-put org-store-link-plist key value)))))
9646 (defun org-email-link-description (&optional fmt)
9647 "Return the description part of an email link.
9648 This takes information from `org-store-link-plist' and formats it
9649 according to FMT (default from `org-email-link-description-format')."
9650 (setq fmt (or fmt org-email-link-description-format))
9651 (let* ((p org-store-link-plist)
9652 (to (plist-get p :toaddress))
9653 (from (plist-get p :fromaddress))
9654 (table
9655 (list
9656 (cons "%c" (plist-get p :fromto))
9657 (cons "%F" (plist-get p :from))
9658 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9659 (cons "%T" (plist-get p :to))
9660 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9661 (cons "%s" (plist-get p :subject))
9662 (cons "%d" (plist-get p :date))
9663 (cons "%m" (plist-get p :message-id)))))
9664 (when (string-match "%c" fmt)
9665 ;; Check if the user wrote this message
9666 (if (and org-from-is-user-regexp from to
9667 (save-match-data (string-match org-from-is-user-regexp from)))
9668 (setq fmt (replace-match "to %t" t t fmt))
9669 (setq fmt (replace-match "from %f" t t fmt))))
9670 (org-replace-escapes fmt table)))
9672 (defun org-make-org-heading-search-string (&optional string)
9673 "Make search string for the current headline or STRING."
9674 (let ((s (or string
9675 (and (derived-mode-p 'org-mode)
9676 (save-excursion
9677 (org-back-to-heading t)
9678 (org-element-property :raw-value (org-element-at-point))))))
9679 (lines org-context-in-file-links))
9680 (or string (setq s (concat "*" s))) ; Add * for headlines
9681 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9682 (when (and string (integerp lines) (> lines 0))
9683 (let ((slines (org-split-string s "\n")))
9684 (when (< lines (length slines))
9685 (setq s (mapconcat
9686 'identity
9687 (reverse (nthcdr (- (length slines) lines)
9688 (reverse slines))) "\n")))))
9689 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9691 (defun org-make-link-string (link &optional description)
9692 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9693 (unless (string-match "\\S-" link)
9694 (error "Empty link"))
9695 (when (and description
9696 (stringp description)
9697 (not (string-match "\\S-" description)))
9698 (setq description nil))
9699 (when (stringp description)
9700 ;; Remove brackets from the description, they are fatal.
9701 (while (string-match "\\[" description)
9702 (setq description (replace-match "{" t t description)))
9703 (while (string-match "\\]" description)
9704 (setq description (replace-match "}" t t description))))
9705 (when (equal link description)
9706 ;; No description needed, it is identical
9707 (setq description nil))
9708 (when (and (not description)
9709 (not (string-match (org-image-file-name-regexp) link))
9710 (not (equal link (org-link-escape link))))
9711 (setq description (org-extract-attributes link)))
9712 (setq link
9713 (cond ((string-match (org-image-file-name-regexp) link) link)
9714 ((string-match org-link-types-re link)
9715 (concat (match-string 1 link)
9716 (org-link-escape (substring link (match-end 1)))))
9717 (t (org-link-escape link))))
9718 (concat "[[" link "]"
9719 (if description (concat "[" description "]") "")
9720 "]"))
9722 (defconst org-link-escape-chars
9723 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9724 "List of characters that should be escaped in link.
9725 This is the list that is used for internal purposes.")
9727 (defconst org-link-escape-chars-browser
9728 '(?\ ?\")
9729 "List of escapes for characters that are problematic in links.
9730 This is the list that is used before handing over to the browser.")
9732 (defun org-link-escape (text &optional table merge)
9733 "Return percent escaped representation of TEXT.
9734 TEXT is a string with the text to escape.
9735 Optional argument TABLE is a list with characters that should be
9736 escaped. When nil, `org-link-escape-chars' is used.
9737 If optional argument MERGE is set, merge TABLE into
9738 `org-link-escape-chars'."
9739 (cond
9740 ((and table merge)
9741 (mapc (lambda (defchr)
9742 (unless (member defchr table)
9743 (setq table (cons defchr table)))) org-link-escape-chars))
9744 ((null table)
9745 (setq table org-link-escape-chars)))
9746 (mapconcat
9747 (lambda (char)
9748 (if (or (member char table)
9749 (and (or (< char 32) (= char 37) (> char 126))
9750 org-url-hexify-p))
9751 (mapconcat (lambda (sequence-element)
9752 (format "%%%.2X" sequence-element))
9753 (or (encode-coding-char char 'utf-8)
9754 (error "Unable to percent escape character: %s"
9755 (char-to-string char))) "")
9756 (char-to-string char))) text ""))
9758 (defun org-link-unescape (str)
9759 "Unhex hexified Unicode strings as returned from the JavaScript function
9760 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9761 (unless (and (null str) (string= "" str))
9762 (let ((pos 0) (case-fold-search t) unhexed)
9763 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9764 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9765 (setq str (replace-match unhexed t t str))
9766 (setq pos (+ pos (length unhexed))))))
9767 str)
9769 (defun org-link-unescape-compound (hex)
9770 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9771 Note: this function also decodes single byte encodings like
9772 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9773 (save-match-data
9774 (let* ((bytes (cdr (split-string hex "%")))
9775 (ret "")
9776 (eat 0)
9777 (sum 0))
9778 (while bytes
9779 (let* ((val (string-to-number (pop bytes) 16))
9780 (shift-xor
9781 (if (= 0 eat)
9782 (cond
9783 ((>= val 252) (cons 6 252))
9784 ((>= val 248) (cons 5 248))
9785 ((>= val 240) (cons 4 240))
9786 ((>= val 224) (cons 3 224))
9787 ((>= val 192) (cons 2 192))
9788 (t (cons 0 0)))
9789 (cons 6 128))))
9790 (if (>= val 192) (setq eat (car shift-xor)))
9791 (setq val (logxor val (cdr shift-xor)))
9792 (setq sum (+ (lsh sum (car shift-xor)) val))
9793 (if (> eat 0) (setq eat (- eat 1)))
9794 (cond
9795 ((= 0 eat) ;multi byte
9796 (setq ret (concat ret (org-char-to-string sum)))
9797 (setq sum 0))
9798 ((not bytes) ; single byte(s)
9799 (setq ret (org-link-unescape-single-byte-sequence hex))))
9800 )) ;; end (while bytes
9801 ret )))
9803 (defun org-link-unescape-single-byte-sequence (hex)
9804 "Unhexify hex-encoded single byte character sequences."
9805 (mapconcat (lambda (byte)
9806 (char-to-string (string-to-number byte 16)))
9807 (cdr (split-string hex "%")) ""))
9809 (defun org-xor (a b)
9810 "Exclusive or."
9811 (if a (not b) b))
9813 (defun org-fixup-message-id-for-http (s)
9814 "Replace special characters in a message id, so it can be used in an http query."
9815 (when (string-match "%" s)
9816 (setq s (mapconcat (lambda (c)
9817 (if (eq c ?%)
9818 "%25"
9819 (char-to-string c)))
9820 s "")))
9821 (while (string-match "<" s)
9822 (setq s (replace-match "%3C" t t s)))
9823 (while (string-match ">" s)
9824 (setq s (replace-match "%3E" t t s)))
9825 (while (string-match "@" s)
9826 (setq s (replace-match "%40" t t s)))
9829 (defun org-link-prettify (link)
9830 "Return a human-readable representation of LINK.
9831 The car of LINK must be a raw link the cdr of LINK must be either
9832 a link description or nil."
9833 (let ((desc (or (cadr link) "<no description>")))
9834 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9835 "<" (car link) ">")))
9837 ;;;###autoload
9838 (defun org-insert-link-global ()
9839 "Insert a link like Org-mode does.
9840 This command can be called in any mode to insert a link in Org-mode syntax."
9841 (interactive)
9842 (org-load-modules-maybe)
9843 (org-run-like-in-org-mode 'org-insert-link))
9845 (defun org-insert-all-links (&optional keep)
9846 "Insert all links in `org-stored-links'."
9847 (interactive "P")
9848 (let ((links (copy-sequence org-stored-links)) l)
9849 (while (setq l (if keep (pop links) (pop org-stored-links)))
9850 (insert "- ")
9851 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9852 (insert "\n"))))
9854 (defun org-link-fontify-links-to-this-file ()
9855 "Fontify links to the current file in `org-stored-links'."
9856 (let ((f (buffer-file-name)) a b)
9857 (setq a (mapcar (lambda(l)
9858 (let ((ll (car l)))
9859 (when (and (string-match "^file:\\(.+\\)::" ll)
9860 (equal f (expand-file-name (match-string 1 ll))))
9861 ll)))
9862 org-stored-links))
9863 (when (featurep 'org-id)
9864 (setq b (mapcar (lambda(l)
9865 (let ((ll (car l)))
9866 (when (and (string-match "^id:\\(.+\\)$" ll)
9867 (equal f (expand-file-name
9868 (or (org-id-find-id-file
9869 (match-string 1 ll)) ""))))
9870 ll)))
9871 org-stored-links)))
9872 (mapcar (lambda(l)
9873 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9874 (delq nil (append a b)))))
9876 (defvar org-link-links-in-this-file nil)
9877 (defun org-insert-link (&optional complete-file link-location default-description)
9878 "Insert a link. At the prompt, enter the link.
9880 Completion can be used to insert any of the link protocol prefixes like
9881 http or ftp in use.
9883 The history can be used to select a link previously stored with
9884 `org-store-link'. When the empty string is entered (i.e. if you just
9885 press RET at the prompt), the link defaults to the most recently
9886 stored link. As SPC triggers completion in the minibuffer, you need to
9887 use M-SPC or C-q SPC to force the insertion of a space character.
9889 You will also be prompted for a description, and if one is given, it will
9890 be displayed in the buffer instead of the link.
9892 If there is already a link at point, this command will allow you to edit link
9893 and description parts.
9895 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9896 be selected using completion. The path to the file will be relative to the
9897 current directory if the file is in the current directory or a subdirectory.
9898 Otherwise, the link will be the absolute path as completed in the minibuffer
9899 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9900 option `org-link-file-path-type'.
9902 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9903 the current directory or below.
9905 With three \\[universal-argument] prefixes, negate the meaning of
9906 `org-keep-stored-link-after-insertion'.
9908 If `org-make-link-description-function' is non-nil, this function will be
9909 called with the link target, and the result will be the default
9910 link description.
9912 If the LINK-LOCATION parameter is non-nil, this value will be
9913 used as the link location instead of reading one interactively.
9915 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9916 be used as the default description."
9917 (interactive "P")
9918 (let* ((wcf (current-window-configuration))
9919 (origbuf (current-buffer))
9920 (region (if (org-region-active-p)
9921 (buffer-substring (region-beginning) (region-end))))
9922 (remove (and region (list (region-beginning) (region-end))))
9923 (desc region)
9924 tmphist ; byte-compile incorrectly complains about this
9925 (link link-location)
9926 (abbrevs org-link-abbrev-alist-local)
9927 entry file all-prefixes auto-desc)
9928 (cond
9929 (link-location) ; specified by arg, just use it.
9930 ((org-in-regexp org-bracket-link-regexp 1)
9931 ;; We do have a link at point, and we are going to edit it.
9932 (setq remove (list (match-beginning 0) (match-end 0)))
9933 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9934 (setq link (read-string "Link: "
9935 (org-link-unescape
9936 (org-match-string-no-properties 1)))))
9937 ((or (org-in-regexp org-angle-link-re)
9938 (org-in-regexp org-plain-link-re))
9939 ;; Convert to bracket link
9940 (setq remove (list (match-beginning 0) (match-end 0))
9941 link (read-string "Link: "
9942 (org-remove-angle-brackets (match-string 0)))))
9943 ((member complete-file '((4) (16)))
9944 ;; Completing read for file names.
9945 (setq link (org-file-complete-link complete-file)))
9947 ;; Read link, with completion for stored links.
9948 (org-link-fontify-links-to-this-file)
9949 (org-switch-to-buffer-other-window "*Org Links*")
9950 (with-current-buffer "*Org Links*"
9951 (erase-buffer)
9952 (insert "Insert a link.
9953 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9954 (when org-stored-links
9955 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9956 (insert (mapconcat 'org-link-prettify
9957 (reverse org-stored-links) "\n")))
9958 (goto-char (point-min)))
9959 (let ((cw (selected-window)))
9960 (select-window (get-buffer-window "*Org Links*" 'visible))
9961 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9962 (unless (pos-visible-in-window-p (point-max))
9963 (org-fit-window-to-buffer))
9964 (and (window-live-p cw) (select-window cw)))
9965 ;; Fake a link history, containing the stored links.
9966 (setq tmphist (append (mapcar 'car org-stored-links)
9967 org-insert-link-history))
9968 (setq all-prefixes (append (mapcar 'car abbrevs)
9969 (mapcar 'car org-link-abbrev-alist)
9970 org-link-types))
9971 (unwind-protect
9972 (progn
9973 (setq link
9974 (org-completing-read
9975 "Link: "
9976 (append
9977 (mapcar (lambda (x) (concat x ":"))
9978 all-prefixes)
9979 (mapcar 'car org-stored-links))
9980 nil nil nil
9981 'tmphist
9982 (caar org-stored-links)))
9983 (if (not (string-match "\\S-" link))
9984 (user-error "No link selected"))
9985 (mapc (lambda(l)
9986 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9987 org-stored-links)
9988 (if (or (member link all-prefixes)
9989 (and (equal ":" (substring link -1))
9990 (member (substring link 0 -1) all-prefixes)
9991 (setq link (substring link 0 -1))))
9992 (setq link (with-current-buffer origbuf
9993 (org-link-try-special-completion link)))))
9994 (set-window-configuration wcf)
9995 (kill-buffer "*Org Links*"))
9996 (setq entry (assoc link org-stored-links))
9997 (or entry (push link org-insert-link-history))
9998 (setq desc (or desc (nth 1 entry)))))
10000 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10001 (not org-keep-stored-link-after-insertion))
10002 (setq org-stored-links (delq (assoc link org-stored-links)
10003 org-stored-links)))
10005 (if (and (string-match org-plain-link-re link)
10006 (not (string-match org-ts-regexp link)))
10007 ;; URL-like link, normalize the use of angular brackets.
10008 (setq link (org-remove-angle-brackets link)))
10010 ;; Check if we are linking to the current file with a search
10011 ;; option If yes, simplify the link by using only the search
10012 ;; option.
10013 (when (and buffer-file-name
10014 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10015 (let* ((path (match-string 1 link))
10016 (case-fold-search nil)
10017 (search (match-string 2 link)))
10018 (save-match-data
10019 (if (equal (file-truename buffer-file-name) (file-truename path))
10020 ;; We are linking to this same file, with a search option
10021 (setq link search)))))
10023 ;; Check if we can/should use a relative path. If yes, simplify the link
10024 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10025 (let* ((type (match-string 1 link))
10026 (path (match-string 2 link))
10027 (origpath path)
10028 (case-fold-search nil))
10029 (cond
10030 ((or (eq org-link-file-path-type 'absolute)
10031 (equal complete-file '(16)))
10032 (setq path (abbreviate-file-name (expand-file-name path))))
10033 ((eq org-link-file-path-type 'noabbrev)
10034 (setq path (expand-file-name path)))
10035 ((eq org-link-file-path-type 'relative)
10036 (setq path (file-relative-name path)))
10038 (save-match-data
10039 (if (string-match (concat "^" (regexp-quote
10040 (expand-file-name
10041 (file-name-as-directory
10042 default-directory))))
10043 (expand-file-name path))
10044 ;; We are linking a file with relative path name.
10045 (setq path (substring (expand-file-name path)
10046 (match-end 0)))
10047 (setq path (abbreviate-file-name (expand-file-name path)))))))
10048 (setq link (concat type path))
10049 (if (equal desc origpath)
10050 (setq desc path))))
10052 (if org-make-link-description-function
10053 (setq desc
10054 (or (condition-case nil
10055 (funcall org-make-link-description-function link desc)
10056 (error (progn (message "Can't get link description from `%s'"
10057 (symbol-name org-make-link-description-function))
10058 (sit-for 2) nil)))
10059 (read-string "Description: " default-description)))
10060 (if default-description (setq desc default-description)
10061 (setq desc (or (and auto-desc desc)
10062 (read-string "Description: " desc)))))
10064 (unless (string-match "\\S-" desc) (setq desc nil))
10065 (if remove (apply 'delete-region remove))
10066 (insert (org-make-link-string link desc))))
10068 (defun org-link-try-special-completion (type)
10069 "If there is completion support for link type TYPE, offer it."
10070 (let ((fun (intern (concat "org-" type "-complete-link"))))
10071 (if (functionp fun)
10072 (funcall fun)
10073 (read-string "Link (no completion support): " (concat type ":")))))
10075 (defun org-file-complete-link (&optional arg)
10076 "Create a file link using completion."
10077 (let (file link)
10078 (setq file (org-iread-file-name "File: "))
10079 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10080 (pwd1 (file-name-as-directory (abbreviate-file-name
10081 (expand-file-name ".")))))
10082 (cond
10083 ((equal arg '(16))
10084 (setq link (concat
10085 "file:"
10086 (abbreviate-file-name (expand-file-name file)))))
10087 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10088 (setq link (concat "file:" (match-string 1 file))))
10089 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10090 (expand-file-name file))
10091 (setq link (concat
10092 "file:" (match-string 1 (expand-file-name file)))))
10093 (t (setq link (concat "file:" file)))))
10094 link))
10096 (defun org-iread-file-name (&rest args)
10097 "Read-file-name using `ido-mode' speedup if available.
10098 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10099 See `read-file-name' for a description of parameters."
10100 (org-without-partial-completion
10101 (if (and org-completion-use-ido
10102 (fboundp 'ido-read-file-name)
10103 (boundp 'ido-mode) ido-mode
10104 (listp (second args)))
10105 (let ((ido-enter-matching-directory nil))
10106 (apply 'ido-read-file-name args))
10107 (apply 'read-file-name args))))
10109 (defun org-completing-read (&rest args)
10110 "Completing-read with SPACE being a normal character."
10111 (let ((enable-recursive-minibuffers t)
10112 (minibuffer-local-completion-map
10113 (copy-keymap minibuffer-local-completion-map)))
10114 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10115 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10116 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10117 (apply 'org-icompleting-read args)))
10119 (defun org-completing-read-no-i (&rest args)
10120 (let (org-completion-use-ido org-completion-use-iswitchb)
10121 (apply 'org-completing-read args)))
10123 (defun org-iswitchb-completing-read (prompt choices &rest args)
10124 "Use iswitch as a completing-read replacement to choose from choices.
10125 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10126 from."
10127 (let* ((iswitchb-use-virtual-buffers nil)
10128 (iswitchb-make-buflist-hook
10129 (lambda ()
10130 (setq iswitchb-temp-buflist choices))))
10131 (iswitchb-read-buffer prompt)))
10133 (defun org-icompleting-read (&rest args)
10134 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10135 (org-without-partial-completion
10136 (if (and org-completion-use-ido
10137 (fboundp 'ido-completing-read)
10138 (boundp 'ido-mode) ido-mode
10139 (listp (second args)))
10140 (let ((ido-enter-matching-directory nil))
10141 (apply 'ido-completing-read (concat (car args))
10142 (if (consp (car (nth 1 args)))
10143 (mapcar 'car (nth 1 args))
10144 (nth 1 args))
10145 (cddr args)))
10146 (if (and org-completion-use-iswitchb
10147 (boundp 'iswitchb-mode) iswitchb-mode
10148 (listp (second args)))
10149 (apply 'org-iswitchb-completing-read (concat (car args))
10150 (if (consp (car (nth 1 args)))
10151 (mapcar 'car (nth 1 args))
10152 (nth 1 args))
10153 (cddr args))
10154 (apply 'completing-read args)))))
10156 (defun org-extract-attributes (s)
10157 "Extract the attributes cookie from a string and set as text property."
10158 (let (a attr (start 0) key value)
10159 (save-match-data
10160 (when (string-match "{{\\([^}]+\\)}}$" s)
10161 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10162 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10163 (setq key (match-string 1 a) value (match-string 2 a)
10164 start (match-end 0)
10165 attr (plist-put attr (intern key) value))))
10166 (org-add-props s nil 'org-attr attr))
10169 ;;; Opening/following a link
10171 (defvar org-link-search-failed nil)
10173 (defvar org-open-link-functions nil
10174 "Hook for functions finding a plain text link.
10175 These functions must take a single argument, the link content.
10176 They will be called for links that look like [[link text][description]]
10177 when LINK TEXT does not have a protocol like \"http:\" and does not look
10178 like a filename (e.g. \"./blue.png\").
10180 These functions will be called *before* Org attempts to resolve the
10181 link by doing text searches in the current buffer - so if you want a
10182 link \"[[target]]\" to still find \"<<target>>\", your function should
10183 handle this as a special case.
10185 When the function does handle the link, it must return a non-nil value.
10186 If it decides that it is not responsible for this link, it must return
10187 nil to indicate that that Org-mode can continue with other options
10188 like exact and fuzzy text search.")
10190 (defun org-next-link (&optional search-backward)
10191 "Move forward to the next link.
10192 If the link is in hidden text, expose it."
10193 (interactive "P")
10194 (when (and org-link-search-failed (eq this-command last-command))
10195 (goto-char (point-min))
10196 (message "Link search wrapped back to beginning of buffer"))
10197 (setq org-link-search-failed nil)
10198 (let* ((pos (point))
10199 (ct (org-context))
10200 (a (assoc :link ct))
10201 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10202 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10203 ((looking-at org-any-link-re)
10204 ;; Don't stay stuck at link without an org-link face
10205 (forward-char (if search-backward -1 1))))
10206 (if (funcall srch-fun org-any-link-re nil t)
10207 (progn
10208 (goto-char (match-beginning 0))
10209 (if (outline-invisible-p) (org-show-context)))
10210 (goto-char pos)
10211 (setq org-link-search-failed t)
10212 (message "No further link found"))))
10214 (defun org-previous-link ()
10215 "Move backward to the previous link.
10216 If the link is in hidden text, expose it."
10217 (interactive)
10218 (funcall 'org-next-link t))
10220 (defun org-translate-link (s)
10221 "Translate a link string if a translation function has been defined."
10222 (if (and org-link-translation-function
10223 (fboundp org-link-translation-function)
10224 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10225 (progn
10226 (setq s (funcall org-link-translation-function
10227 (match-string 1 s) (match-string 2 s)))
10228 (concat (car s) ":" (cdr s)))
10231 (defun org-translate-link-from-planner (type path)
10232 "Translate a link from Emacs Planner syntax so that Org can follow it.
10233 This is still an experimental function, your mileage may vary."
10234 (cond
10235 ((member type '("http" "https" "news" "ftp"))
10236 ;; standard Internet links are the same.
10237 nil)
10238 ((and (equal type "irc") (string-match "^//" path))
10239 ;; Planner has two / at the beginning of an irc link, we have 1.
10240 ;; We should have zero, actually....
10241 (setq path (substring path 1)))
10242 ((and (equal type "lisp") (string-match "^/" path))
10243 ;; Planner has a slash, we do not.
10244 (setq type "elisp" path (substring path 1)))
10245 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10246 ;; A typical message link. Planner has the id after the final slash,
10247 ;; we separate it with a hash mark
10248 (setq path (concat (match-string 1 path) "#"
10249 (org-remove-angle-brackets (match-string 2 path))))))
10250 (cons type path))
10252 (defun org-find-file-at-mouse (ev)
10253 "Open file link or URL at mouse."
10254 (interactive "e")
10255 (mouse-set-point ev)
10256 (org-open-at-point 'in-emacs))
10258 (defun org-open-at-mouse (ev)
10259 "Open file link or URL at mouse.
10260 See the docstring of `org-open-file' for details."
10261 (interactive "e")
10262 (mouse-set-point ev)
10263 (if (eq major-mode 'org-agenda-mode)
10264 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10265 (org-open-at-point))
10267 (defvar org-window-config-before-follow-link nil
10268 "The window configuration before following a link.
10269 This is saved in case the need arises to restore it.")
10271 (defvar org-open-link-marker (make-marker)
10272 "Marker pointing to the location where `org-open-at-point; was called.")
10274 ;;;###autoload
10275 (defun org-open-at-point-global ()
10276 "Follow a link like Org-mode does.
10277 This command can be called in any mode to follow a link that has
10278 Org-mode syntax."
10279 (interactive)
10280 (org-run-like-in-org-mode 'org-open-at-point))
10282 ;;;###autoload
10283 (defun org-open-link-from-string (s &optional arg reference-buffer)
10284 "Open a link in the string S, as if it was in Org-mode."
10285 (interactive "sLink: \nP")
10286 (let ((reference-buffer (or reference-buffer (current-buffer))))
10287 (with-temp-buffer
10288 (let ((org-inhibit-startup (not reference-buffer)))
10289 (org-mode)
10290 (insert s)
10291 (goto-char (point-min))
10292 (when reference-buffer
10293 (setq org-link-abbrev-alist-local
10294 (with-current-buffer reference-buffer
10295 org-link-abbrev-alist-local)))
10296 (org-open-at-point arg reference-buffer)))))
10298 (defvar org-open-at-point-functions nil
10299 "Hook that is run when following a link at point.
10301 Functions in this hook must return t if they identify and follow
10302 a link at point. If they don't find anything interesting at point,
10303 they must return nil.")
10305 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10306 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10307 (defun org-open-at-point (&optional arg reference-buffer)
10308 "Open link at or after point.
10309 If there is no link at point, this function will search forward up to
10310 the end of the current line.
10311 Normally, files will be opened by an appropriate application. If the
10312 optional prefix argument ARG is non-nil, Emacs will visit the file.
10313 With a double prefix argument, try to open outside of Emacs, in the
10314 application the system uses for this file type."
10315 (interactive "P")
10316 ;; if in a code block, then open the block's results
10317 (unless (call-interactively #'org-babel-open-src-block-result)
10318 (org-load-modules-maybe)
10319 (move-marker org-open-link-marker (point))
10320 (setq org-window-config-before-follow-link (current-window-configuration))
10321 (org-remove-occur-highlights nil nil t)
10322 (cond
10323 ((and (org-at-heading-p)
10324 (not (org-at-timestamp-p t))
10325 (not (org-in-regexp
10326 (concat org-plain-link-re "\\|"
10327 org-bracket-link-regexp "\\|"
10328 org-angle-link-re "\\|"
10329 "[ \t]:[^ \t\n]+:[ \t]*$")))
10330 (not (get-text-property (point) 'org-linked-text)))
10331 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10332 (lk0 (car lkall))
10333 (lk (if (stringp lk0) (list lk0) lk0))
10334 (lkend (cdr lkall)))
10335 (mapcar (lambda(l)
10336 (search-forward l nil lkend)
10337 (goto-char (match-beginning 0))
10338 (org-open-at-point))
10339 lk))
10340 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10341 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10342 ((and (org-at-timestamp-p t)
10343 (not (org-in-regexp org-bracket-link-regexp)))
10344 (org-follow-timestamp-link))
10345 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10346 (not (org-in-regexp org-any-link-re)))
10347 (org-footnote-action))
10349 (let (type path link line search (pos (point)))
10350 (catch 'match
10351 (save-excursion
10352 (skip-chars-forward "^]\n\r")
10353 (when (org-in-regexp org-bracket-link-regexp 1)
10354 (setq link (org-extract-attributes
10355 (org-link-unescape (org-match-string-no-properties 1))))
10356 (while (string-match " *\n *" link)
10357 (setq link (replace-match " " t t link)))
10358 (setq link (org-link-expand-abbrev link))
10359 (cond
10360 ((or (file-name-absolute-p link)
10361 (string-match "^\\.\\.?/" link))
10362 (setq type "file" path link))
10363 ((string-match org-link-re-with-space3 link)
10364 (setq type (match-string 1 link) path (match-string 2 link)))
10365 ((string-match "^help:+\\(.+\\)" link)
10366 (setq type "help" path (match-string 1 link)))
10367 (t (setq type "thisfile" path link)))
10368 (throw 'match t)))
10370 (when (get-text-property (point) 'org-linked-text)
10371 (setq type "thisfile"
10372 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10373 (1+ (point)) (point))
10374 path (buffer-substring
10375 (or (previous-single-property-change pos 'org-linked-text)
10376 (point-min))
10377 (or (next-single-property-change pos 'org-linked-text)
10378 (point-max)))
10379 ;; Ensure we will search for a <<<radio>>> link, not
10380 ;; a simple reference like <<ref>>
10381 path (concat "<" path))
10382 (throw 'match t))
10384 (save-excursion
10385 (when (or (org-in-regexp org-angle-link-re)
10386 (let ((match (org-in-regexp org-plain-link-re)))
10387 ;; Check a plain link is not within a bracket link
10388 (and match
10389 (save-excursion
10390 (progn
10391 (goto-char (car match))
10392 (not (org-in-regexp org-bracket-link-regexp))))))
10393 (let ((line_ending (save-excursion (end-of-line) (point))))
10394 ;; We are in a line before a plain or bracket link
10395 (or (re-search-forward org-plain-link-re line_ending t)
10396 (re-search-forward org-bracket-link-regexp line_ending t))))
10397 (setq type (match-string 1)
10398 path (org-link-unescape (match-string 2)))
10399 (throw 'match t)))
10400 (save-excursion
10401 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10402 (setq type "tags"
10403 path (match-string 1))
10404 (while (string-match ":" path)
10405 (setq path (replace-match "+" t t path)))
10406 (throw 'match t)))
10407 (when (org-in-regexp "<\\([^><\n]+\\)>")
10408 (setq type "tree-match"
10409 path (match-string 1))
10410 (throw 'match t)))
10411 (unless path
10412 (user-error "No link found"))
10414 ;; switch back to reference buffer
10415 ;; needed when if called in a temporary buffer through
10416 ;; org-open-link-from-string
10417 (with-current-buffer (or reference-buffer (current-buffer))
10419 ;; Remove any trailing spaces in path
10420 (if (string-match " +\\'" path)
10421 (setq path (replace-match "" t t path)))
10422 (if (and org-link-translation-function
10423 (fboundp org-link-translation-function))
10424 ;; Check if we need to translate the link
10425 (let ((tmp (funcall org-link-translation-function type path)))
10426 (setq type (car tmp) path (cdr tmp))))
10428 (cond
10430 ((assoc type org-link-protocols)
10431 (funcall (nth 1 (assoc type org-link-protocols)) path))
10433 ((equal type "help")
10434 (let ((f-or-v (intern path)))
10435 (cond ((fboundp f-or-v)
10436 (describe-function f-or-v))
10437 ((boundp f-or-v)
10438 (describe-variable f-or-v))
10439 (t (error "Not a known function or variable")))))
10441 ((equal type "mailto")
10442 (let ((cmd (car org-link-mailto-program))
10443 (args (cdr org-link-mailto-program)) args1
10444 (address path) (subject "") a)
10445 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10446 (setq address (match-string 1 path)
10447 subject (org-link-escape (match-string 2 path))))
10448 (while args
10449 (cond
10450 ((not (stringp (car args))) (push (pop args) args1))
10451 (t (setq a (pop args))
10452 (if (string-match "%a" a)
10453 (setq a (replace-match address t t a)))
10454 (if (string-match "%s" a)
10455 (setq a (replace-match subject t t a)))
10456 (push a args1))))
10457 (apply cmd (nreverse args1))))
10459 ((member type '("http" "https" "ftp" "news"))
10460 (browse-url
10461 (concat type ":"
10462 (if (org-string-match-p
10463 (concat "[[:nonascii:]"
10464 org-link-escape-chars-browser "]")
10465 path)
10466 (org-link-escape path org-link-escape-chars-browser)
10467 path))))
10469 ((string= type "doi")
10470 (browse-url
10471 (concat org-doi-server-url
10472 (if (org-string-match-p
10473 (concat "[[:nonascii:]"
10474 org-link-escape-chars-browser "]")
10475 path)
10476 (org-link-escape path org-link-escape-chars-browser)
10477 path))))
10479 ((member type '("message"))
10480 (browse-url (concat type ":" path)))
10482 ((string= type "tags")
10483 (org-tags-view arg path))
10485 ((string= type "tree-match")
10486 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10488 ((string= type "file")
10489 (if (string-match "::\\([0-9]+\\)\\'" path)
10490 (setq line (string-to-number (match-string 1 path))
10491 path (substring path 0 (match-beginning 0)))
10492 (if (string-match "::\\(.+\\)\\'" path)
10493 (setq search (match-string 1 path)
10494 path (substring path 0 (match-beginning 0)))))
10495 (if (string-match "[*?{]" (file-name-nondirectory path))
10496 (dired path)
10497 (org-open-file path arg line search)))
10499 ((string= type "shell")
10500 (let ((buf (generate-new-buffer "*Org Shell Output"))
10501 (cmd path))
10502 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10503 (string-match org-confirm-shell-link-not-regexp cmd))
10504 (not org-confirm-shell-link-function)
10505 (funcall org-confirm-shell-link-function
10506 (format "Execute \"%s\" in shell? "
10507 (org-add-props cmd nil
10508 'face 'org-warning))))
10509 (progn
10510 (message "Executing %s" cmd)
10511 (shell-command cmd buf)
10512 (if (featurep 'midnight)
10513 (setq clean-buffer-list-kill-buffer-names
10514 (cons buf clean-buffer-list-kill-buffer-names))))
10515 (error "Abort"))))
10517 ((string= type "elisp")
10518 (let ((cmd path))
10519 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10520 (string-match org-confirm-elisp-link-not-regexp cmd))
10521 (not org-confirm-elisp-link-function)
10522 (funcall org-confirm-elisp-link-function
10523 (format "Execute \"%s\" as elisp? "
10524 (org-add-props cmd nil
10525 'face 'org-warning))))
10526 (message "%s => %s" cmd
10527 (if (equal (string-to-char cmd) ?\()
10528 (eval (read cmd))
10529 (call-interactively (read cmd))))
10530 (error "Abort"))))
10532 ((and (string= type "thisfile")
10533 (or (run-hook-with-args-until-success
10534 'org-open-link-functions path)
10535 (and link
10536 (string-match "^id:" link)
10537 (or (featurep 'org-id) (require 'org-id))
10538 (progn
10539 (funcall (nth 1 (assoc "id" org-link-protocols))
10540 (substring path 3))
10541 t)))))
10543 ((string= type "thisfile")
10544 (if arg
10545 (switch-to-buffer-other-window
10546 (org-get-buffer-for-internal-link (current-buffer)))
10547 (org-mark-ring-push))
10548 (let ((cmd `(org-link-search
10549 ,path
10550 ,(cond ((equal arg '(4)) ''occur)
10551 ((equal arg '(16)) ''org-occur))
10552 ,pos)))
10553 (condition-case nil (let ((org-link-search-inhibit-query t))
10554 (eval cmd))
10555 (error (progn (widen) (eval cmd))))))
10557 (t (browse-url-at-point)))))))
10558 (move-marker org-open-link-marker nil)
10559 (run-hook-with-args 'org-follow-link-hook)))
10561 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10562 "Offer links in the current entry and return the selected link.
10563 If there is only one link, return it.
10564 If NTH is an integer, return the NTH link found.
10565 If ZERO is a string, check also this string for a link, and if
10566 there is one, return it."
10567 (with-current-buffer buffer
10568 (save-excursion
10569 (save-restriction
10570 (widen)
10571 (goto-char marker)
10572 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10573 "\\(" org-angle-link-re "\\)\\|"
10574 "\\(" org-plain-link-re "\\)"))
10575 (cnt ?0)
10576 (in-emacs (if (integerp nth) nil nth))
10577 have-zero end links link c)
10578 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10579 (push (match-string 0 zero) links)
10580 (setq cnt (1- cnt) have-zero t))
10581 (save-excursion
10582 (org-back-to-heading t)
10583 (setq end (save-excursion (outline-next-heading) (point)))
10584 (while (re-search-forward re end t)
10585 (push (match-string 0) links))
10586 (setq links (org-uniquify (reverse links))))
10587 (cond
10588 ((null links)
10589 (message "No links"))
10590 ((equal (length links) 1)
10591 (setq link (car links)))
10592 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10593 (setq link (nth (if have-zero nth (1- nth)) links)))
10594 (t ; we have to select a link
10595 (save-excursion
10596 (save-window-excursion
10597 (delete-other-windows)
10598 (with-output-to-temp-buffer "*Select Link*"
10599 (mapc (lambda (l)
10600 (if (not (string-match org-bracket-link-regexp l))
10601 (princ (format "[%c] %s\n" (incf cnt)
10602 (org-remove-angle-brackets l)))
10603 (if (match-end 3)
10604 (princ (format "[%c] %s (%s)\n" (incf cnt)
10605 (match-string 3 l) (match-string 1 l)))
10606 (princ (format "[%c] %s\n" (incf cnt)
10607 (match-string 1 l))))))
10608 links))
10609 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10610 (message "Select link to open, RET to open all:")
10611 (setq c (read-char-exclusive))
10612 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10613 (when (equal c ?q) (error "Abort"))
10614 (if (equal c ?\C-m)
10615 (setq link links)
10616 (setq nth (- c ?0))
10617 (if have-zero (setq nth (1+ nth)))
10618 (unless (and (integerp nth) (>= (length links) nth))
10619 (user-error "Invalid link selection"))
10620 (setq link (nth (1- nth) links)))))
10621 (cons link end))))))
10623 ;; Add special file links that specify the way of opening
10625 (org-add-link-type "file+sys" 'org-open-file-with-system)
10626 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10627 (defun org-open-file-with-system (path)
10628 "Open file at PATH using the system way of opening it."
10629 (org-open-file path 'system))
10630 (defun org-open-file-with-emacs (path)
10631 "Open file at PATH in Emacs."
10632 (org-open-file path 'emacs))
10635 ;;; File search
10637 (defvar org-create-file-search-functions nil
10638 "List of functions to construct the right search string for a file link.
10639 These functions are called in turn with point at the location to
10640 which the link should point.
10642 A function in the hook should first test if it would like to
10643 handle this file type, for example by checking the `major-mode'
10644 or the file extension. If it decides not to handle this file, it
10645 should just return nil to give other functions a chance. If it
10646 does handle the file, it must return the search string to be used
10647 when following the link. The search string will be part of the
10648 file link, given after a double colon, and `org-open-at-point'
10649 will automatically search for it. If special measures must be
10650 taken to make the search successful, another function should be
10651 added to the companion hook `org-execute-file-search-functions',
10652 which see.
10654 A function in this hook may also use `setq' to set the variable
10655 `description' to provide a suggestion for the descriptive text to
10656 be used for this link when it gets inserted into an Org-mode
10657 buffer with \\[org-insert-link].")
10659 (defvar org-execute-file-search-functions nil
10660 "List of functions to execute a file search triggered by a link.
10662 Functions added to this hook must accept a single argument, the
10663 search string that was part of the file link, the part after the
10664 double colon. The function must first check if it would like to
10665 handle this search, for example by checking the `major-mode' or
10666 the file extension. If it decides not to handle this search, it
10667 should just return nil to give other functions a chance. If it
10668 does handle the search, it must return a non-nil value to keep
10669 other functions from trying.
10671 Each function can access the current prefix argument through the
10672 variable `current-prefix-arg'. Note that a single prefix is used
10673 to force opening a link in Emacs, so it may be good to only use a
10674 numeric or double prefix to guide the search function.
10676 In case this is needed, a function in this hook can also restore
10677 the window configuration before `org-open-at-point' was called using:
10679 (set-window-configuration org-window-config-before-follow-link)")
10681 (defun org-link-search (s &optional type avoid-pos stealth)
10682 "Search for a link search option.
10683 If S is surrounded by forward slashes, it is interpreted as a
10684 regular expression. In org-mode files, this will create an `org-occur'
10685 sparse tree. In ordinary files, `occur' will be used to list matches.
10686 If the current buffer is in `dired-mode', grep will be used to search
10687 in all files. If AVOID-POS is given, ignore matches near that position.
10689 When optional argument STEALTH is non-nil, do not modify
10690 visibility around point, thus ignoring
10691 `org-show-hierarchy-above', `org-show-following-heading' and
10692 `org-show-siblings' variables."
10693 (let ((case-fold-search t)
10694 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10695 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10696 (append '(("") (" ") ("\t") ("\n"))
10697 org-emphasis-alist)
10698 "\\|") "\\)"))
10699 (pos (point))
10700 (pre nil) (post nil)
10701 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10702 (cond
10703 ;; First check if there are any special search functions
10704 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10705 ;; Now try the builtin stuff
10706 ((and (equal (string-to-char s0) ?#)
10707 (> (length s0) 1)
10708 (save-excursion
10709 (goto-char (point-min))
10710 (and
10711 (re-search-forward
10712 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10713 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10714 (setq type 'dedicated
10715 pos (match-beginning 0))))
10716 ;; There is an exact target for this
10717 (goto-char pos)
10718 (org-back-to-heading t)))
10719 ((save-excursion
10720 (goto-char (point-min))
10721 (and
10722 (re-search-forward
10723 (concat "<<" (regexp-quote s0) ">>") nil t)
10724 (setq type 'dedicated
10725 pos (match-beginning 0))))
10726 ;; There is an exact target for this
10727 (goto-char pos))
10728 ((save-excursion
10729 (goto-char (point-min))
10730 (and
10731 (re-search-forward
10732 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10733 (setq type 'dedicated pos (match-beginning 0))))
10734 ;; Found an element with a matching #+name affiliated keyword.
10735 (goto-char pos))
10736 ((and (string-match "^(\\(.*\\))$" s0)
10737 (save-excursion
10738 (goto-char (point-min))
10739 (and
10740 (re-search-forward
10741 (concat "[^[]" (regexp-quote
10742 (format org-coderef-label-format
10743 (match-string 1 s0))))
10744 nil t)
10745 (setq type 'dedicated
10746 pos (1+ (match-beginning 0))))))
10747 ;; There is a coderef target for this
10748 (goto-char pos))
10749 ((string-match "^/\\(.*\\)/$" s)
10750 ;; A regular expression
10751 (cond
10752 ((derived-mode-p 'org-mode)
10753 (org-occur (match-string 1 s)))
10754 (t (org-do-occur (match-string 1 s)))))
10755 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10756 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10757 (goto-char (point-min))
10758 (cond
10759 ((let (case-fold-search)
10760 (re-search-forward (format org-complex-heading-regexp-format
10761 (regexp-quote s))
10762 nil t))
10763 ;; OK, found a match
10764 (setq type 'dedicated)
10765 (goto-char (match-beginning 0)))
10766 ((and (not org-link-search-inhibit-query)
10767 (eq org-link-search-must-match-exact-headline 'query-to-create)
10768 (y-or-n-p "No match - create this as a new heading? "))
10769 (goto-char (point-max))
10770 (or (bolp) (newline))
10771 (insert "* " s "\n")
10772 (beginning-of-line 0))
10774 (goto-char pos)
10775 (error "No match"))))
10777 ;; A normal search string
10778 (when (equal (string-to-char s) ?*)
10779 ;; Anchor on headlines, post may include tags.
10780 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10781 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10782 s (substring s 1)))
10783 (remove-text-properties
10784 0 (length s)
10785 '(face nil mouse-face nil keymap nil fontified nil) s)
10786 ;; Make a series of regular expressions to find a match
10787 (setq words (org-split-string s "[ \n\r\t]+")
10789 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10790 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10791 "\\)" markers)
10792 re2a_ (concat "\\(" (mapconcat 'downcase words
10793 "[ \t\r\n]+") "\\)[ \t\r\n]")
10794 re2a (concat "[ \t\r\n]" re2a_)
10795 re4_ (concat "\\(" (mapconcat 'downcase words
10796 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10797 re4 (concat "[^a-zA-Z_]" re4_)
10799 re1 (concat pre re2 post)
10800 re3 (concat pre (if pre re4_ re4) post)
10801 re5 (concat pre ".*" re4)
10802 re2 (concat pre re2)
10803 re2a (concat pre (if pre re2a_ re2a))
10804 re4 (concat pre (if pre re4_ re4))
10805 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10806 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10807 re5 "\\)"))
10808 (cond
10809 ((eq type 'org-occur) (org-occur reall))
10810 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10811 (t (goto-char (point-min))
10812 (setq type 'fuzzy)
10813 (if (or (and (org-search-not-self 1 re0 nil t)
10814 (setq type 'dedicated))
10815 (org-search-not-self 1 re1 nil t)
10816 (org-search-not-self 1 re2 nil t)
10817 (org-search-not-self 1 re2a nil t)
10818 (org-search-not-self 1 re3 nil t)
10819 (org-search-not-self 1 re4 nil t)
10820 (org-search-not-self 1 re5 nil t))
10821 (goto-char (match-beginning 1))
10822 (goto-char pos)
10823 (error "No match"))))))
10824 (and (derived-mode-p 'org-mode)
10825 (not stealth)
10826 (org-show-context 'link-search))
10827 type))
10829 (defun org-search-not-self (group &rest args)
10830 "Execute `re-search-forward', but only accept matches that do not
10831 enclose the position of `org-open-link-marker'."
10832 (let ((m org-open-link-marker))
10833 (catch 'exit
10834 (while (apply 're-search-forward args)
10835 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10836 (goto-char (match-end group))
10837 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10838 (> (match-beginning 0) (marker-position m))
10839 (< (match-end 0) (marker-position m)))
10840 (save-match-data
10841 (or (not (org-in-regexp
10842 org-bracket-link-analytic-regexp 1))
10843 (not (match-end 4)) ; no description
10844 (and (<= (match-beginning 4) (point))
10845 (>= (match-end 4) (point))))))
10846 (throw 'exit (point))))))))
10848 (defun org-get-buffer-for-internal-link (buffer)
10849 "Return a buffer to be used for displaying the link target of internal links."
10850 (cond
10851 ((not org-display-internal-link-with-indirect-buffer)
10852 buffer)
10853 ((string-match "(Clone)$" (buffer-name buffer))
10854 (message "Buffer is already a clone, not making another one")
10855 ;; we also do not modify visibility in this case
10856 buffer)
10857 (t ; make a new indirect buffer for displaying the link
10858 (let* ((bn (buffer-name buffer))
10859 (ibn (concat bn "(Clone)"))
10860 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10861 (with-current-buffer ib (org-overview))
10862 ib))))
10864 (defun org-do-occur (regexp &optional cleanup)
10865 "Call the Emacs command `occur'.
10866 If CLEANUP is non-nil, remove the printout of the regular expression
10867 in the *Occur* buffer. This is useful if the regex is long and not useful
10868 to read."
10869 (occur regexp)
10870 (when cleanup
10871 (let ((cwin (selected-window)) win beg end)
10872 (when (setq win (get-buffer-window "*Occur*"))
10873 (select-window win))
10874 (goto-char (point-min))
10875 (when (re-search-forward "match[a-z]+" nil t)
10876 (setq beg (match-end 0))
10877 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10878 (setq end (1- (match-beginning 0)))))
10879 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10880 (goto-char (point-min))
10881 (select-window cwin))))
10883 ;;; The mark ring for links jumps
10885 (defvar org-mark-ring nil
10886 "Mark ring for positions before jumps in Org-mode.")
10887 (defvar org-mark-ring-last-goto nil
10888 "Last position in the mark ring used to go back.")
10889 ;; Fill and close the ring
10890 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10891 (loop for i from 1 to org-mark-ring-length do
10892 (push (make-marker) org-mark-ring))
10893 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10894 org-mark-ring)
10896 (defun org-mark-ring-push (&optional pos buffer)
10897 "Put the current position or POS into the mark ring and rotate it."
10898 (interactive)
10899 (setq pos (or pos (point)))
10900 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10901 (move-marker (car org-mark-ring)
10902 (or pos (point))
10903 (or buffer (current-buffer)))
10904 (message "%s"
10905 (substitute-command-keys
10906 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10908 (defun org-mark-ring-goto (&optional n)
10909 "Jump to the previous position in the mark ring.
10910 With prefix arg N, jump back that many stored positions. When
10911 called several times in succession, walk through the entire ring.
10912 Org-mode commands jumping to a different position in the current file,
10913 or to another Org-mode file, automatically push the old position
10914 onto the ring."
10915 (interactive "p")
10916 (let (p m)
10917 (if (eq last-command this-command)
10918 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10919 (setq p org-mark-ring))
10920 (setq org-mark-ring-last-goto p)
10921 (setq m (car p))
10922 (org-pop-to-buffer-same-window (marker-buffer m))
10923 (goto-char m)
10924 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10926 (defun org-remove-angle-brackets (s)
10927 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10928 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10930 (defun org-add-angle-brackets (s)
10931 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10932 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10934 (defun org-remove-double-quotes (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)))
10939 ;;; Following specific links
10941 (defun org-follow-timestamp-link ()
10942 "Open an agenda view for the time-stamp date/range at point."
10943 (cond
10944 ((org-at-date-range-p t)
10945 (let ((org-agenda-start-on-weekday)
10946 (t1 (match-string 1))
10947 (t2 (match-string 2)) tt1 tt2)
10948 (setq tt1 (time-to-days (org-time-string-to-time t1))
10949 tt2 (time-to-days (org-time-string-to-time t2)))
10950 (let ((org-agenda-buffer-tmp-name
10951 (format "*Org Agenda(a:%s)"
10952 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10953 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10954 ((org-at-timestamp-p t)
10955 (let ((org-agenda-buffer-tmp-name
10956 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10957 (org-agenda-list nil (time-to-days (org-time-string-to-time
10958 (substring (match-string 1) 0 10)))
10959 1)))
10960 (t (error "This should not happen"))))
10963 ;;; Following file links
10964 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10965 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10966 (declare-function mailcap-mime-info
10967 "mailcap" (string &optional request no-decode))
10968 (defvar org-wait nil)
10969 (defun org-open-file (path &optional in-emacs line search)
10970 "Open the file at PATH.
10971 First, this expands any special file name abbreviations. Then the
10972 configuration variable `org-file-apps' is checked if it contains an
10973 entry for this file type, and if yes, the corresponding command is launched.
10975 If no application is found, Emacs simply visits the file.
10977 With optional prefix argument IN-EMACS, Emacs will visit the file.
10978 With a double \\[universal-argument] \\[universal-argument] \
10979 prefix arg, Org tries to avoid opening in Emacs
10980 and to use an external application to visit the file.
10982 Optional LINE specifies a line to go to, optional SEARCH a string
10983 to search for. If LINE or SEARCH is given, the file will be
10984 opened in Emacs, unless an entry from org-file-apps that makes
10985 use of groups in a regexp matches.
10987 If you want to change the way frames are used when following a
10988 link, please customize `org-link-frame-setup'.
10990 If the file does not exist, an error is thrown."
10991 (let* ((file (if (equal path "")
10992 buffer-file-name
10993 (substitute-in-file-name (expand-file-name path))))
10994 (file-apps (append org-file-apps (org-default-apps)))
10995 (apps (org-remove-if
10996 'org-file-apps-entry-match-against-dlink-p file-apps))
10997 (apps-dlink (org-remove-if-not
10998 'org-file-apps-entry-match-against-dlink-p file-apps))
10999 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11000 (dirp (if remp nil (file-directory-p file)))
11001 (file (if (and dirp org-open-directory-means-index-dot-org)
11002 (concat (file-name-as-directory file) "index.org")
11003 file))
11004 (a-m-a-p (assq 'auto-mode apps))
11005 (dfile (downcase file))
11006 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11007 (link (cond ((and (eq line nil)
11008 (eq search nil))
11009 file)
11010 (line
11011 (concat file "::" (number-to-string line)))
11012 (search
11013 (concat file "::" search))))
11014 (dlink (downcase link))
11015 (old-buffer (current-buffer))
11016 (old-pos (point))
11017 (old-mode major-mode)
11018 ext cmd link-match-data)
11019 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11020 (setq ext (match-string 1 dfile))
11021 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11022 (setq ext (match-string 1 dfile))))
11023 (cond
11024 ((member in-emacs '((16) system))
11025 (setq cmd (cdr (assoc 'system apps))))
11026 (in-emacs (setq cmd 'emacs))
11028 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11029 (and dirp (cdr (assoc 'directory apps)))
11030 ; first, try matching against apps-dlink
11031 ; if we get a match here, store the match data for later
11032 (let ((match (assoc-default dlink apps-dlink
11033 'string-match)))
11034 (if match
11035 (progn (setq link-match-data (match-data))
11036 match)
11037 (progn (setq in-emacs (or in-emacs line search))
11038 nil))) ; if we have no match in apps-dlink,
11039 ; always open the file in emacs if line or search
11040 ; is given (for backwards compatibility)
11041 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11042 'string-match)
11043 (cdr (assoc ext apps))
11044 (cdr (assoc t apps))))))
11045 (when (eq cmd 'system)
11046 (setq cmd (cdr (assoc 'system apps))))
11047 (when (eq cmd 'default)
11048 (setq cmd (cdr (assoc t apps))))
11049 (when (eq cmd 'mailcap)
11050 (require 'mailcap)
11051 (mailcap-parse-mailcaps)
11052 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11053 (command (mailcap-mime-info mime-type)))
11054 (if (stringp command)
11055 (setq cmd command)
11056 (setq cmd 'emacs))))
11057 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11058 (not (file-exists-p file))
11059 (not org-open-non-existing-files))
11060 (user-error "No such file: %s" file))
11061 (cond
11062 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11063 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11064 (while (string-match "['\"]%s['\"]" cmd)
11065 (setq cmd (replace-match "%s" t t cmd)))
11066 (while (string-match "%s" cmd)
11067 (setq cmd (replace-match
11068 (save-match-data
11069 (shell-quote-argument
11070 (convert-standard-filename file)))
11071 t t cmd)))
11073 ;; Replace "%1", "%2" etc. in command with group matches from regex
11074 (save-match-data
11075 (let ((match-index 1)
11076 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11077 (set-match-data link-match-data)
11078 (while (<= match-index number-of-groups)
11079 (let ((regex (concat "%" (number-to-string match-index)))
11080 (replace-with (match-string match-index dlink)))
11081 (while (string-match regex cmd)
11082 (setq cmd (replace-match replace-with t t cmd))))
11083 (setq match-index (+ match-index 1)))))
11085 (save-window-excursion
11086 (message "Running %s...done" cmd)
11087 (start-process-shell-command cmd nil cmd)
11088 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11089 ((or (stringp cmd)
11090 (eq cmd 'emacs))
11091 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11092 (widen)
11093 (if line (org-goto-line line)
11094 (if search (org-link-search search))))
11095 ((consp cmd)
11096 (let ((file (convert-standard-filename file)))
11097 (save-match-data
11098 (set-match-data link-match-data)
11099 (eval cmd))))
11100 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11101 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11102 (or (not (equal old-buffer (current-buffer)))
11103 (not (equal old-pos (point))))
11104 (org-mark-ring-push old-pos old-buffer))))
11106 (defun org-file-apps-entry-match-against-dlink-p (entry)
11107 "This function returns non-nil if `entry' uses a regular
11108 expression which should be matched against the whole link by
11109 org-open-file.
11111 It assumes that is the case when the entry uses a regular
11112 expression which has at least one grouping construct and the
11113 action is either a lisp form or a command string containing
11114 '%1', i.e. using at least one subexpression match as a
11115 parameter."
11116 (let ((selector (car entry))
11117 (action (cdr entry)))
11118 (if (stringp selector)
11119 (and (> (regexp-opt-depth selector) 0)
11120 (or (and (stringp action)
11121 (string-match "%[0-9]" action))
11122 (consp action)))
11123 nil)))
11125 (defun org-default-apps ()
11126 "Return the default applications for this operating system."
11127 (cond
11128 ((eq system-type 'darwin)
11129 org-file-apps-defaults-macosx)
11130 ((eq system-type 'windows-nt)
11131 org-file-apps-defaults-windowsnt)
11132 (t org-file-apps-defaults-gnu)))
11134 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11135 "Convert extensions to regular expressions in the cars of LIST.
11136 Also, weed out any non-string entries, because the return value is used
11137 only for regexp matching.
11138 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11139 point to the symbol `emacs', indicating that the file should
11140 be opened in Emacs."
11141 (append
11142 (delq nil
11143 (mapcar (lambda (x)
11144 (if (not (stringp (car x)))
11146 (if (string-match "\\W" (car x))
11148 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11149 list))
11150 (if add-auto-mode
11151 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11153 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11154 (defun org-file-remote-p (file)
11155 "Test whether FILE specifies a location on a remote system.
11156 Return non-nil if the location is indeed remote.
11158 For example, the filename \"/user@host:/foo\" specifies a location
11159 on the system \"/user@host:\"."
11160 (cond ((fboundp 'file-remote-p)
11161 (file-remote-p file))
11162 ((fboundp 'tramp-handle-file-remote-p)
11163 (tramp-handle-file-remote-p file))
11164 ((and (boundp 'ange-ftp-name-format)
11165 (string-match (car ange-ftp-name-format) file))
11166 t)))
11169 ;;;; Refiling
11171 (defun org-get-org-file ()
11172 "Read a filename, with default directory `org-directory'."
11173 (let ((default (or org-default-notes-file remember-data-file)))
11174 (read-file-name (format "File name [%s]: " default)
11175 (file-name-as-directory org-directory)
11176 default)))
11178 (defun org-notes-order-reversed-p ()
11179 "Check if the current file should receive notes in reversed order."
11180 (cond
11181 ((not org-reverse-note-order) nil)
11182 ((eq t org-reverse-note-order) t)
11183 ((not (listp org-reverse-note-order)) nil)
11184 (t (catch 'exit
11185 (let ((all org-reverse-note-order)
11186 entry)
11187 (while (setq entry (pop all))
11188 (if (string-match (car entry) buffer-file-name)
11189 (throw 'exit (cdr entry))))
11190 nil)))))
11192 (defvar org-refile-target-table nil
11193 "The list of refile targets, created by `org-refile'.")
11195 (defvar org-agenda-new-buffers nil
11196 "Buffers created to visit agenda files.")
11198 (defvar org-refile-cache nil
11199 "Cache for refile targets.")
11201 (defvar org-refile-markers nil
11202 "All the markers used for caching refile locations.")
11204 (defun org-refile-marker (pos)
11205 "Get a new refile marker, but only if caching is in use."
11206 (if (not org-refile-use-cache)
11208 (let ((m (make-marker)))
11209 (move-marker m pos)
11210 (push m org-refile-markers)
11211 m)))
11213 (defun org-refile-cache-clear ()
11214 "Clear the refile cache and disable all the markers."
11215 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11216 (setq org-refile-markers nil)
11217 (setq org-refile-cache nil)
11218 (message "Refile cache has been cleared"))
11220 (defun org-refile-cache-check-set (set)
11221 "Check if all the markers in the cache still have live buffers."
11222 (let (marker)
11223 (catch 'exit
11224 (while (and set (setq marker (nth 3 (pop set))))
11225 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11226 (when (and marker (null (marker-buffer marker)))
11227 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11228 (sit-for 3)
11229 (throw 'exit nil)))
11230 t)))
11232 (defun org-refile-cache-put (set &rest identifiers)
11233 "Push the refile targets SET into the cache, under IDENTIFIERS."
11234 (let* ((key (sha1 (prin1-to-string identifiers)))
11235 (entry (assoc key org-refile-cache)))
11236 (if entry
11237 (setcdr entry set)
11238 (push (cons key set) org-refile-cache))))
11240 (defun org-refile-cache-get (&rest identifiers)
11241 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11242 (cond
11243 ((not org-refile-cache) nil)
11244 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11246 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11247 org-refile-cache))))
11248 (and set (org-refile-cache-check-set set) set)))))
11250 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11251 "Produce a table with refile targets."
11252 (let ((case-fold-search nil)
11253 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11254 (entries (or org-refile-targets '((nil . (:level . 1)))))
11255 targets tgs txt re files f desc descre fast-path-p level pos0)
11256 (message "Getting targets...")
11257 (with-current-buffer (or default-buffer (current-buffer))
11258 (while (setq entry (pop entries))
11259 (setq files (car entry) desc (cdr entry))
11260 (setq fast-path-p nil)
11261 (cond
11262 ((null files) (setq files (list (current-buffer))))
11263 ((eq files 'org-agenda-files)
11264 (setq files (org-agenda-files 'unrestricted)))
11265 ((and (symbolp files) (fboundp files))
11266 (setq files (funcall files)))
11267 ((and (symbolp files) (boundp files))
11268 (setq files (symbol-value files))))
11269 (if (stringp files) (setq files (list files)))
11270 (cond
11271 ((eq (car desc) :tag)
11272 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11273 ((eq (car desc) :todo)
11274 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11275 ((eq (car desc) :regexp)
11276 (setq descre (cdr desc)))
11277 ((eq (car desc) :level)
11278 (setq descre (concat "^\\*\\{" (number-to-string
11279 (if org-odd-levels-only
11280 (1- (* 2 (cdr desc)))
11281 (cdr desc)))
11282 "\\}[ \t]")))
11283 ((eq (car desc) :maxlevel)
11284 (setq fast-path-p t)
11285 (setq descre (concat "^\\*\\{1," (number-to-string
11286 (if org-odd-levels-only
11287 (1- (* 2 (cdr desc)))
11288 (cdr desc)))
11289 "\\}[ \t]")))
11290 (t (error "Bad refiling target description %s" desc)))
11291 (while (setq f (pop files))
11292 (with-current-buffer
11293 (if (bufferp f) f (org-get-agenda-file-buffer f))
11295 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11296 (progn
11297 (if (bufferp f) (setq f (buffer-file-name
11298 (buffer-base-buffer f))))
11299 (setq f (and f (expand-file-name f)))
11300 (if (eq org-refile-use-outline-path 'file)
11301 (push (list (file-name-nondirectory f) f nil nil) tgs))
11302 (save-excursion
11303 (save-restriction
11304 (widen)
11305 (goto-char (point-min))
11306 (while (re-search-forward descre nil t)
11307 (goto-char (setq pos0 (point-at-bol)))
11308 (catch 'next
11309 (when org-refile-target-verify-function
11310 (save-match-data
11311 (or (funcall org-refile-target-verify-function)
11312 (throw 'next t))))
11313 (when (and (looking-at org-complex-heading-regexp)
11314 (not (member (match-string 4) excluded-entries))
11315 (match-string 4))
11316 (setq level (org-reduced-level
11317 (- (match-end 1) (match-beginning 1)))
11318 txt (org-link-display-format (match-string 4))
11319 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11320 re (format org-complex-heading-regexp-format
11321 (regexp-quote (match-string 4))))
11322 (when org-refile-use-outline-path
11323 (setq txt (mapconcat
11324 'org-protect-slash
11325 (append
11326 (if (eq org-refile-use-outline-path
11327 'file)
11328 (list (file-name-nondirectory
11329 (buffer-file-name
11330 (buffer-base-buffer))))
11331 (if (eq org-refile-use-outline-path
11332 'full-file-path)
11333 (list (buffer-file-name
11334 (buffer-base-buffer)))))
11335 (org-get-outline-path fast-path-p
11336 level txt)
11337 (list txt))
11338 "/")))
11339 (push (list txt f re (org-refile-marker (point)))
11340 tgs)))
11341 (when (= (point) pos0)
11342 ;; verification function has not moved point
11343 (goto-char (point-at-eol))))))))
11344 (when org-refile-use-cache
11345 (org-refile-cache-put tgs (buffer-file-name) descre))
11346 (setq targets (append tgs targets))))))
11347 (message "Getting targets...done")
11348 (nreverse targets)))
11350 (defun org-protect-slash (s)
11351 (while (string-match "/" s)
11352 (setq s (replace-match "\\" t t s)))
11355 (defvar org-olpa (make-vector 20 nil))
11357 (defun org-get-outline-path (&optional fastp level heading)
11358 "Return the outline path to the current entry, as a list.
11360 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11361 routine which makes outline path derivations for an entire file,
11362 avoiding backtracing. Refile target collection makes use of that."
11363 (if fastp
11364 (progn
11365 (if (> level 19)
11366 (error "Outline path failure, more than 19 levels"))
11367 (loop for i from level upto 19 do
11368 (aset org-olpa i nil))
11369 (prog1
11370 (delq nil (append org-olpa nil))
11371 (aset org-olpa level heading)))
11372 (let (rtn case-fold-search)
11373 (save-excursion
11374 (save-restriction
11375 (widen)
11376 (while (org-up-heading-safe)
11377 (when (looking-at org-complex-heading-regexp)
11378 (push (org-trim
11379 (replace-regexp-in-string
11380 ;; Remove statistical/checkboxes cookies
11381 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11382 (org-match-string-no-properties 4)))
11383 rtn)))
11384 rtn)))))
11386 (defun org-format-outline-path (path &optional width prefix separator)
11387 "Format the outline path PATH for display.
11388 WIDTH is the maximum number of characters that is available.
11389 PREFIX is a prefix to be included in the returned string,
11390 such as the file name.
11391 SEPARATOR is inserted between the different parts of the path,
11392 the default is \"/\"."
11393 (setq width (or width 79))
11394 (if prefix (setq width (- width (length prefix))))
11395 (if (not path)
11396 (or prefix "")
11397 (let* ((nsteps (length path))
11398 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11399 (maxwidth (if (<= total-width width)
11400 10000 ;; everything fits
11401 ;; we need to shorten the level headings
11402 (/ (- width nsteps) nsteps)))
11403 (org-odd-levels-only nil)
11404 (n 0)
11405 (total (1+ (length prefix))))
11406 (setq maxwidth (max maxwidth 10))
11407 (concat prefix
11408 (if prefix (or separator "/"))
11409 (mapconcat
11410 (lambda (h)
11411 (setq n (1+ n))
11412 (if (and (= n nsteps) (< maxwidth 10000))
11413 (setq maxwidth (- total-width total)))
11414 (if (< (length h) maxwidth)
11415 (progn (setq total (+ total (length h) 1)) h)
11416 (setq h (substring h 0 (- maxwidth 2))
11417 total (+ total maxwidth 1))
11418 (if (string-match "[ \t]+\\'" h)
11419 (setq h (substring h 0 (match-beginning 0))))
11420 (setq h (concat h "..")))
11421 (org-add-props h nil 'face
11422 (nth (% (1- n) org-n-level-faces)
11423 org-level-faces))
11425 path (or separator "/"))))))
11427 (defun org-display-outline-path (&optional file current separator just-return-string)
11428 "Display the current outline path in the echo area.
11430 If FILE is non-nil, prepend the output with the file name.
11431 If CURRENT is non-nil, append the current heading to the output.
11432 SEPARATOR is passed through to `org-format-outline-path'. It separates
11433 the different parts of the path and defaults to \"/\".
11434 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11435 (interactive "P")
11436 (let* (case-fold-search
11437 (bfn (buffer-file-name (buffer-base-buffer)))
11438 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11439 res)
11440 (if current (setq path (append path
11441 (save-excursion
11442 (org-back-to-heading t)
11443 (if (looking-at org-complex-heading-regexp)
11444 (list (match-string 4)))))))
11445 (setq res
11446 (org-format-outline-path
11447 path
11448 (1- (frame-width))
11449 (and file bfn (concat (file-name-nondirectory bfn) separator))
11450 separator))
11451 (if just-return-string
11452 (org-no-properties res)
11453 (org-unlogged-message "%s" res))))
11455 (defvar org-refile-history nil
11456 "History for refiling operations.")
11458 (defvar org-after-refile-insert-hook nil
11459 "Hook run after `org-refile' has inserted its stuff at the new location.
11460 Note that this is still *before* the stuff will be removed from
11461 the *old* location.")
11463 (defvar org-capture-last-stored-marker)
11464 (defvar org-refile-keep nil
11465 "Non-nil means `org-refile' will copy instead of refile.")
11467 (defun org-copy ()
11468 "Like `org-refile', but copy."
11469 (interactive)
11470 (let ((org-refile-keep t))
11471 (funcall 'org-refile nil nil nil "Copy")))
11473 (defun org-refile (&optional goto default-buffer rfloc msg)
11474 "Move the entry or entries at point to another heading.
11475 The list of target headings is compiled using the information in
11476 `org-refile-targets', which see.
11478 At the target location, the entry is filed as a subitem of the target
11479 heading. Depending on `org-reverse-note-order', the new subitem will
11480 either be the first or the last subitem.
11482 If there is an active region, all entries in that region will be moved.
11483 However, the region must fulfill the requirement that the first heading
11484 is the first one sets the top-level of the moved text - at most siblings
11485 below it are allowed.
11487 With prefix arg GOTO, the command will only visit the target location
11488 and not actually move anything.
11490 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11491 go to the location where the last refiling operation has put the subtree.
11493 With a numeric prefix argument of `2', refile to the running clock.
11495 With a numeric prefix argument of `3', emulate `org-refile-keep'
11496 being set to `t' and copy to the target location, don't move it.
11497 Beware that keeping refiled entries may result in duplicated ID
11498 properties.
11500 RFLOC can be a refile location obtained in a different way.
11502 MSG is a string to replace \"Refile\" in the default prompt with
11503 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11505 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11507 If you are using target caching (see `org-refile-use-cache'),
11508 you have to clear the target cache in order to find new targets.
11509 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11510 prefix argument (`C-u C-u C-u C-c C-w')."
11512 (interactive "P")
11513 (if (member goto '(0 (64)))
11514 (org-refile-cache-clear)
11515 (let* ((actionmsg (or msg "Refile"))
11516 (cbuf (current-buffer))
11517 (regionp (org-region-active-p))
11518 (region-start (and regionp (region-beginning)))
11519 (region-end (and regionp (region-end)))
11520 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11521 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11522 pos it nbuf file re level reversed)
11523 (setq last-command nil)
11524 (when regionp
11525 (goto-char region-start)
11526 (or (bolp) (goto-char (point-at-bol)))
11527 (setq region-start (point))
11528 (unless (or (org-kill-is-subtree-p
11529 (buffer-substring region-start region-end))
11530 (prog1 org-refile-active-region-within-subtree
11531 (let ((s (point-at-eol)))
11532 (org-toggle-heading)
11533 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11534 (user-error "The region is not a (sequence of) subtree(s)")))
11535 (if (equal goto '(16))
11536 (org-refile-goto-last-stored)
11537 (when (or
11538 (and (equal goto 2)
11539 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11540 (prog1
11541 (setq it (list (or org-clock-heading "running clock")
11542 (buffer-file-name
11543 (marker-buffer org-clock-hd-marker))
11545 (marker-position org-clock-hd-marker)))
11546 (setq goto nil)))
11547 (setq it (or rfloc
11548 (let (heading-text)
11549 (save-excursion
11550 (unless goto
11551 (org-back-to-heading t)
11552 (setq heading-text
11553 (nth 4 (org-heading-components))))
11555 (org-refile-get-location
11556 (cond (goto "Goto")
11557 (regionp (concat actionmsg " region to"))
11558 (t (concat actionmsg " subtree \""
11559 heading-text "\" to")))
11560 default-buffer
11561 (and (not (equal '(4) goto))
11562 org-refile-allow-creating-parent-nodes)
11563 goto))))))
11564 (setq file (nth 1 it)
11565 re (nth 2 it)
11566 pos (nth 3 it))
11567 (if (and (not goto)
11569 (equal (buffer-file-name) file)
11570 (if regionp
11571 (and (>= pos region-start)
11572 (<= pos region-end))
11573 (and (>= pos (point))
11574 (< pos (save-excursion
11575 (org-end-of-subtree t t))))))
11576 (error "Cannot refile to position inside the tree or region"))
11578 (setq nbuf (or (find-buffer-visiting file)
11579 (find-file-noselect file)))
11580 (if (and goto (not (equal goto 3)))
11581 (progn
11582 (org-pop-to-buffer-same-window nbuf)
11583 (goto-char pos)
11584 (org-show-context 'org-goto))
11585 (if regionp
11586 (progn
11587 (org-kill-new (buffer-substring region-start region-end))
11588 (org-save-markers-in-region region-start region-end))
11589 (org-copy-subtree 1 nil t))
11590 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11591 (find-file-noselect file)))
11592 (setq reversed (org-notes-order-reversed-p))
11593 (save-excursion
11594 (save-restriction
11595 (widen)
11596 (if pos
11597 (progn
11598 (goto-char pos)
11599 (looking-at org-outline-regexp)
11600 (setq level (org-get-valid-level (funcall outline-level) 1))
11601 (goto-char
11602 (if reversed
11603 (or (outline-next-heading) (point-max))
11604 (or (save-excursion (org-get-next-sibling))
11605 (org-end-of-subtree t t)
11606 (point-max)))))
11607 (setq level 1)
11608 (if (not reversed)
11609 (goto-char (point-max))
11610 (goto-char (point-min))
11611 (or (outline-next-heading) (goto-char (point-max)))))
11612 (if (not (bolp)) (newline))
11613 (org-paste-subtree level)
11614 (when org-log-refile
11615 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11616 (unless (eq org-log-refile 'note)
11617 (save-excursion (org-add-log-note))))
11618 (and org-auto-align-tags
11619 (let ((org-loop-over-headlines-in-active-region nil))
11620 (org-set-tags nil t)))
11621 (let ((bookmark-name (plist-get org-bookmark-names-plist
11622 :last-refile)))
11623 (when bookmark-name
11624 (with-demoted-errors
11625 (bookmark-set bookmark-name))))
11626 ;; If we are refiling for capture, make sure that the
11627 ;; last-capture pointers point here
11628 (when (org-bound-and-true-p org-refile-for-capture)
11629 (let ((bookmark-name (plist-get org-bookmark-names-plist
11630 :last-capture-marker)))
11631 (when bookmark-name
11632 (with-demoted-errors
11633 (bookmark-set bookmark-name))))
11634 (move-marker org-capture-last-stored-marker (point)))
11635 (if (fboundp 'deactivate-mark) (deactivate-mark))
11636 (run-hooks 'org-after-refile-insert-hook))))
11637 (unless org-refile-keep
11638 (if regionp
11639 (delete-region (point) (+ (point) (- region-end region-start)))
11640 (delete-region
11641 (and (org-back-to-heading t) (point))
11642 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11643 (when (featurep 'org-inlinetask)
11644 (org-inlinetask-remove-END-maybe))
11645 (setq org-markers-to-move nil)
11646 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11648 (defun org-refile-goto-last-stored ()
11649 "Go to the location where the last refile was stored."
11650 (interactive)
11651 (bookmark-jump "org-refile-last-stored")
11652 (message "This is the location of the last refile"))
11654 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11655 no-exclude)
11656 "Prompt the user for a refile location, using PROMPT.
11657 PROMPT should not be suffixed with a colon and a space, because
11658 this function appends the default value from
11659 `org-refile-history' automatically, if that is not empty.
11660 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11661 this is used for the GOTO interface."
11662 (let ((org-refile-targets org-refile-targets)
11663 (org-refile-use-outline-path org-refile-use-outline-path)
11664 excluded-entries)
11665 (when (and (derived-mode-p 'org-mode)
11666 (not org-refile-use-cache)
11667 (not no-exclude))
11668 (org-map-tree
11669 (lambda()
11670 (setq excluded-entries
11671 (append excluded-entries (list (org-get-heading t t)))))))
11672 (setq org-refile-target-table
11673 (org-refile-get-targets default-buffer excluded-entries)))
11674 (unless org-refile-target-table
11675 (user-error "No refile targets"))
11676 (let* ((cbuf (current-buffer))
11677 (partial-completion-mode nil)
11678 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11679 (cfunc (if (and org-refile-use-outline-path
11680 org-outline-path-complete-in-steps)
11681 'org-olpath-completing-read
11682 'org-icompleting-read))
11683 (extra (if org-refile-use-outline-path "/" ""))
11684 (cbnex (concat (buffer-name) extra))
11685 (filename (and cfn (expand-file-name cfn)))
11686 (tbl (mapcar
11687 (lambda (x)
11688 (if (and (not (member org-refile-use-outline-path
11689 '(file full-file-path)))
11690 (not (equal filename (nth 1 x))))
11691 (cons (concat (car x) extra " ("
11692 (file-name-nondirectory (nth 1 x)) ")")
11693 (cdr x))
11694 (cons (concat (car x) extra) (cdr x))))
11695 org-refile-target-table))
11696 (completion-ignore-case t)
11697 cdef
11698 (prompt (concat prompt
11699 (or (and (car org-refile-history)
11700 (concat " (default " (car org-refile-history) ")"))
11701 (and (assoc cbnex tbl) (setq cdef cbnex)
11702 (concat " (default " cbnex ")"))) ": "))
11703 pa answ parent-target child parent old-hist)
11704 (setq old-hist org-refile-history)
11705 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11706 nil 'org-refile-history (or cdef (car org-refile-history))))
11707 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11708 (if pa
11709 (progn
11710 (org-refile-check-position pa)
11711 (when (or (not org-refile-history)
11712 (not (eq old-hist org-refile-history))
11713 (not (equal (car pa) (car org-refile-history))))
11714 (setq org-refile-history
11715 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11716 org-refile-history
11717 (cdr org-refile-history))))
11718 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11719 (pop org-refile-history)))
11721 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11722 (progn
11723 (setq parent (match-string 1 answ)
11724 child (match-string 2 answ))
11725 (setq parent-target (or (assoc parent tbl)
11726 (assoc (concat parent "/") tbl)))
11727 (when (and parent-target
11728 (or (eq new-nodes t)
11729 (and (eq new-nodes 'confirm)
11730 (y-or-n-p (format "Create new node \"%s\"? "
11731 child)))))
11732 (org-refile-new-child parent-target child)))
11733 (user-error "Invalid target location")))))
11735 (declare-function org-string-nw-p "org-macs" (s))
11736 (defun org-refile-check-position (refile-pointer)
11737 "Check if the refile pointer matches the headline to which it points."
11738 (let* ((file (nth 1 refile-pointer))
11739 (re (nth 2 refile-pointer))
11740 (pos (nth 3 refile-pointer))
11741 buffer)
11742 (if (and (not (markerp pos)) (not file))
11743 (user-error "Please save the buffer to a file before refiling")
11744 (when (org-string-nw-p re)
11745 (setq buffer (if (markerp pos)
11746 (marker-buffer pos)
11747 (or (find-buffer-visiting file)
11748 (find-file-noselect file))))
11749 (with-current-buffer buffer
11750 (save-excursion
11751 (save-restriction
11752 (widen)
11753 (goto-char pos)
11754 (beginning-of-line 1)
11755 (unless (org-looking-at-p re)
11756 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11758 (defun org-refile-new-child (parent-target child)
11759 "Use refile target PARENT-TARGET to add new CHILD below it."
11760 (unless parent-target
11761 (error "Cannot find parent for new node"))
11762 (let ((file (nth 1 parent-target))
11763 (pos (nth 3 parent-target))
11764 level)
11765 (with-current-buffer (or (find-buffer-visiting file)
11766 (find-file-noselect file))
11767 (save-excursion
11768 (save-restriction
11769 (widen)
11770 (if pos
11771 (goto-char pos)
11772 (goto-char (point-max))
11773 (if (not (bolp)) (newline)))
11774 (when (looking-at org-outline-regexp)
11775 (setq level (funcall outline-level))
11776 (org-end-of-subtree t t))
11777 (org-back-over-empty-lines)
11778 (insert "\n" (make-string
11779 (if pos (org-get-valid-level level 1) 1) ?*)
11780 " " child "\n")
11781 (beginning-of-line 0)
11782 (list (concat (car parent-target) "/" child) file "" (point)))))))
11784 (defun org-olpath-completing-read (prompt collection &rest args)
11785 "Read an outline path like a file name."
11786 (let ((thetable collection)
11787 (org-completion-use-ido nil) ; does not work with ido.
11788 (org-completion-use-iswitchb nil)) ; or iswitchb
11789 (apply
11790 'org-icompleting-read prompt
11791 (lambda (string predicate &optional flag)
11792 (let (rtn r f (l (length string)))
11793 (cond
11794 ((eq flag nil)
11795 ;; try completion
11796 (try-completion string thetable))
11797 ((eq flag t)
11798 ;; all-completions
11799 (setq rtn (all-completions string thetable predicate))
11800 (mapcar
11801 (lambda (x)
11802 (setq r (substring x l))
11803 (if (string-match " ([^)]*)$" x)
11804 (setq f (match-string 0 x))
11805 (setq f ""))
11806 (if (string-match "/" r)
11807 (concat string (substring r 0 (match-end 0)) f)
11809 rtn))
11810 ((eq flag 'lambda)
11811 ;; exact match?
11812 (assoc string thetable)))))
11813 args)))
11815 ;;;; Dynamic blocks
11817 (defun org-find-dblock (name)
11818 "Find the first dynamic block with name NAME in the buffer.
11819 If not found, stay at current position and return nil."
11820 (let ((case-fold-search t) pos)
11821 (save-excursion
11822 (goto-char (point-min))
11823 (setq pos (and (re-search-forward
11824 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11825 (match-beginning 0))))
11826 (if pos (goto-char pos))
11827 pos))
11829 (defconst org-dblock-start-re
11830 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11831 "Matches the start line of a dynamic block, with parameters.")
11833 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11834 "Matches the end of a dynamic block.")
11836 (defun org-create-dblock (plist)
11837 "Create a dynamic block section, with parameters taken from PLIST.
11838 PLIST must contain a :name entry which is used as name of the block."
11839 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11840 (end-of-line 1)
11841 (newline))
11842 (let ((col (current-column))
11843 (name (plist-get plist :name)))
11844 (insert "#+BEGIN: " name)
11845 (while plist
11846 (if (eq (car plist) :name)
11847 (setq plist (cddr plist))
11848 (insert " " (prin1-to-string (pop plist)))))
11849 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11850 (beginning-of-line -2)))
11852 (defun org-prepare-dblock ()
11853 "Prepare dynamic block for refresh.
11854 This empties the block, puts the cursor at the insert position and returns
11855 the property list including an extra property :name with the block name."
11856 (unless (looking-at org-dblock-start-re)
11857 (user-error "Not at a dynamic block"))
11858 (let* ((begdel (1+ (match-end 0)))
11859 (name (org-no-properties (match-string 1)))
11860 (params (append (list :name name)
11861 (read (concat "(" (match-string 3) ")")))))
11862 (save-excursion
11863 (beginning-of-line 1)
11864 (skip-chars-forward " \t")
11865 (setq params (plist-put params :indentation-column (current-column))))
11866 (unless (re-search-forward org-dblock-end-re nil t)
11867 (error "Dynamic block not terminated"))
11868 (setq params
11869 (append params
11870 (list :content (buffer-substring
11871 begdel (match-beginning 0)))))
11872 (delete-region begdel (match-beginning 0))
11873 (goto-char begdel)
11874 (open-line 1)
11875 params))
11877 (defun org-map-dblocks (&optional command)
11878 "Apply COMMAND to all dynamic blocks in the current buffer.
11879 If COMMAND is not given, use `org-update-dblock'."
11880 (let ((cmd (or command 'org-update-dblock)))
11881 (save-excursion
11882 (goto-char (point-min))
11883 (while (re-search-forward org-dblock-start-re nil t)
11884 (goto-char (match-beginning 0))
11885 (save-excursion
11886 (condition-case nil
11887 (funcall cmd)
11888 (error (message "Error during update of dynamic block"))))
11889 (unless (re-search-forward org-dblock-end-re nil t)
11890 (error "Dynamic block not terminated"))))))
11892 (defun org-dblock-update (&optional arg)
11893 "User command for updating dynamic blocks.
11894 Update the dynamic block at point. With prefix ARG, update all dynamic
11895 blocks in the buffer."
11896 (interactive "P")
11897 (if arg
11898 (org-update-all-dblocks)
11899 (or (looking-at org-dblock-start-re)
11900 (org-beginning-of-dblock))
11901 (org-update-dblock)))
11903 (defun org-update-dblock ()
11904 "Update the dynamic block at point.
11905 This means to empty the block, parse for parameters and then call
11906 the correct writing function."
11907 (interactive)
11908 (save-window-excursion
11909 (let* ((pos (point))
11910 (line (org-current-line))
11911 (params (org-prepare-dblock))
11912 (name (plist-get params :name))
11913 (indent (plist-get params :indentation-column))
11914 (cmd (intern (concat "org-dblock-write:" name))))
11915 (message "Updating dynamic block `%s' at line %d..." name line)
11916 (funcall cmd params)
11917 (message "Updating dynamic block `%s' at line %d...done" name line)
11918 (goto-char pos)
11919 (when (and indent (> indent 0))
11920 (setq indent (make-string indent ?\ ))
11921 (save-excursion
11922 (org-beginning-of-dblock)
11923 (forward-line 1)
11924 (while (not (looking-at org-dblock-end-re))
11925 (insert indent)
11926 (beginning-of-line 2))
11927 (when (looking-at org-dblock-end-re)
11928 (and (looking-at "[ \t]+")
11929 (replace-match ""))
11930 (insert indent)))))))
11932 (defun org-beginning-of-dblock ()
11933 "Find the beginning of the dynamic block at point.
11934 Error if there is no such block at point."
11935 (let ((pos (point))
11936 beg)
11937 (end-of-line 1)
11938 (if (and (re-search-backward org-dblock-start-re nil t)
11939 (setq beg (match-beginning 0))
11940 (re-search-forward org-dblock-end-re nil t)
11941 (> (match-end 0) pos))
11942 (goto-char beg)
11943 (goto-char pos)
11944 (error "Not in a dynamic block"))))
11946 (defun org-update-all-dblocks ()
11947 "Update all dynamic blocks in the buffer.
11948 This function can be used in a hook."
11949 (interactive)
11950 (when (derived-mode-p 'org-mode)
11951 (org-map-dblocks 'org-update-dblock)))
11954 ;;;; Completion
11956 (declare-function org-export-backend-name "org-export" (cl-x))
11957 (declare-function org-export-backend-options "org-export" (cl-x))
11958 (defun org-get-export-keywords ()
11959 "Return a list of all currently understood export keywords.
11960 Export keywords include options, block names, attributes and
11961 keywords relative to each registered export back-end."
11962 (let (keywords)
11963 (dolist (backend
11964 (org-bound-and-true-p org-export--registered-backends)
11965 (delq nil keywords))
11966 ;; Back-end name (for keywords, like #+LATEX:)
11967 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11968 (dolist (option-entry (org-export-backend-options backend))
11969 ;; Back-end options.
11970 (push (nth 1 option-entry) keywords)))))
11972 (defconst org-options-keywords
11973 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11974 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11975 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11976 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11977 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11979 (defcustom org-structure-template-alist
11980 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11981 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11982 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11983 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11984 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11985 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11986 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11987 "<literal style=\"latex\">\n?\n</literal>")
11988 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11989 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11990 "<literal style=\"html\">\n?\n</literal>")
11991 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11992 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11993 ("A" "#+ASCII: " "")
11994 ("i" "#+INDEX: ?" "#+INDEX: ?")
11995 ("I" "#+INCLUDE: %file ?"
11996 "<include file=%file markup=\"?\">"))
11997 "Structure completion elements.
11998 This is a list of abbreviation keys and values. The value gets inserted
11999 if you type `<' followed by the key and then press the completion key,
12000 usually `M-TAB'. %file will be replaced by a file name after prompting
12001 for the file using completion. The cursor will be placed at the position
12002 of the `?` in the template.
12003 There are two templates for each key, the first uses the original Org syntax,
12004 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12005 the default when the /org-mtags.el/ module has been loaded. See also the
12006 variable `org-mtags-prefer-muse-templates'."
12007 :group 'org-completion
12008 :type '(repeat
12009 (list
12010 (string :tag "Key")
12011 (string :tag "Template")
12012 (string :tag "Muse Template"))))
12014 (defun org-try-structure-completion ()
12015 "Try to complete a structure template before point.
12016 This looks for strings like \"<e\" on an otherwise empty line and
12017 expands them."
12018 (let ((l (buffer-substring (point-at-bol) (point)))
12020 (when (and (looking-at "[ \t]*$")
12021 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12022 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12023 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12024 (match-beginning 1)) a)
12025 t)))
12027 (defun org-complete-expand-structure-template (start cell)
12028 "Expand a structure template."
12029 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12030 (rpl (nth (if musep 2 1) cell))
12031 (ind ""))
12032 (delete-region start (point))
12033 (when (string-match "\\`#\\+" rpl)
12034 (cond
12035 ((bolp))
12036 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12037 (setq ind (buffer-substring (point-at-bol) (point))))
12038 (t (newline))))
12039 (setq start (point))
12040 (if (string-match "%file" rpl)
12041 (setq rpl (replace-match
12042 (concat
12043 "\""
12044 (save-match-data
12045 (abbreviate-file-name (read-file-name "Include file: ")))
12046 "\"")
12047 t t rpl)))
12048 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12049 (concat "\n" ind)))
12050 (insert rpl)
12051 (if (re-search-backward "\\?" start t) (delete-char 1))))
12053 ;;;; TODO, DEADLINE, Comments
12055 (defun org-toggle-comment ()
12056 "Change the COMMENT state of an entry."
12057 (interactive)
12058 (save-excursion
12059 (org-back-to-heading)
12060 (let (case-fold-search)
12061 (cond
12062 ((looking-at (format org-heading-keyword-regexp-format
12063 org-comment-string))
12064 (goto-char (match-end 1))
12065 (looking-at (concat " +" org-comment-string))
12066 (replace-match "" t t)
12067 (when (eolp) (insert " ")))
12068 ((looking-at org-outline-regexp)
12069 (goto-char (match-end 0))
12070 (insert org-comment-string " "))))))
12072 (defvar org-last-todo-state-is-todo nil
12073 "This is non-nil when the last TODO state change led to a TODO state.
12074 If the last change removed the TODO tag or switched to DONE, then
12075 this is nil.")
12077 (defvar org-setting-tags nil) ; dynamically skipped
12079 (defvar org-todo-setup-filter-hook nil
12080 "Hook for functions that pre-filter todo specs.
12081 Each function takes a todo spec and returns either nil or the spec
12082 transformed into canonical form." )
12084 (defvar org-todo-get-default-hook nil
12085 "Hook for functions that get a default item for todo.
12086 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12087 nil or a string to be used for the todo mark." )
12089 (defvar org-agenda-headline-snapshot-before-repeat)
12091 (defun org-current-effective-time ()
12092 "Return current time adjusted for `org-extend-today-until' variable."
12093 (let* ((ct (org-current-time))
12094 (dct (decode-time ct))
12095 (ct1
12096 (cond
12097 (org-use-last-clock-out-time-as-effective-time
12098 (or (org-clock-get-last-clock-out-time) ct))
12099 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12100 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12101 (t ct))))
12102 ct1))
12104 (defun org-todo-yesterday (&optional arg)
12105 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12106 (interactive "P")
12107 (if (eq major-mode 'org-agenda-mode)
12108 (apply 'org-agenda-todo-yesterday arg)
12109 (let* ((hour (third (decode-time
12110 (org-current-time))))
12111 (org-extend-today-until (1+ hour)))
12112 (org-todo arg))))
12114 (defvar org-block-entry-blocking ""
12115 "First entry preventing the TODO state change.")
12117 (defun org-todo (&optional arg)
12118 "Change the TODO state of an item.
12119 The state of an item is given by a keyword at the start of the heading,
12120 like
12121 *** TODO Write paper
12122 *** DONE Call mom
12124 The different keywords are specified in the variable `org-todo-keywords'.
12125 By default the available states are \"TODO\" and \"DONE\".
12126 So for this example: when the item starts with TODO, it is changed to DONE.
12127 When it starts with DONE, the DONE is removed. And when neither TODO nor
12128 DONE are present, add TODO at the beginning of the heading.
12130 With \\[universal-argument] prefix arg, use completion to determine the new \
12131 state.
12132 With numeric prefix arg, switch to that state.
12133 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12134 keywords (nextset).
12135 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12136 With a numeric prefix arg of 0, inhibit note taking for the change.
12138 For calling through lisp, arg is also interpreted in the following way:
12139 'none -> empty state
12140 \"\"(empty string) -> switch to empty state
12141 'done -> switch to DONE
12142 'nextset -> switch to the next set of keywords
12143 'previousset -> switch to the previous set of keywords
12144 \"WAITING\" -> switch to the specified keyword, but only if it
12145 really is a member of `org-todo-keywords'."
12146 (interactive "P")
12147 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12148 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12149 'region-start-level 'region))
12150 org-loop-over-headlines-in-active-region)
12151 (org-map-entries
12152 `(org-todo ,arg)
12153 org-loop-over-headlines-in-active-region
12154 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12155 (if (equal arg '(16)) (setq arg 'nextset))
12156 (let ((org-blocker-hook org-blocker-hook)
12157 commentp
12158 case-fold-search)
12159 (when (equal arg '(64))
12160 (setq arg nil org-blocker-hook nil))
12161 (when (and org-blocker-hook
12162 (or org-inhibit-blocking
12163 (org-entry-get nil "NOBLOCKING")))
12164 (setq org-blocker-hook nil))
12165 (save-excursion
12166 (catch 'exit
12167 (org-back-to-heading t)
12168 (when (looking-at (concat "^\\*+ " org-comment-string))
12169 (org-toggle-comment)
12170 (setq commentp t))
12171 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12172 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12173 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12174 (let* ((match-data (match-data))
12175 (startpos (point-at-bol))
12176 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12177 (org-log-done org-log-done)
12178 (org-log-repeat org-log-repeat)
12179 (org-todo-log-states org-todo-log-states)
12180 (org-inhibit-logging
12181 (if (equal arg 0)
12182 (progn (setq arg nil) 'note) org-inhibit-logging))
12183 (this (match-string 1))
12184 (hl-pos (match-beginning 0))
12185 (head (org-get-todo-sequence-head this))
12186 (ass (assoc head org-todo-kwd-alist))
12187 (interpret (nth 1 ass))
12188 (done-word (nth 3 ass))
12189 (final-done-word (nth 4 ass))
12190 (org-last-state (or this ""))
12191 (completion-ignore-case t)
12192 (member (member this org-todo-keywords-1))
12193 (tail (cdr member))
12194 (org-state (cond
12195 ((and org-todo-key-trigger
12196 (or (and (equal arg '(4))
12197 (eq org-use-fast-todo-selection 'prefix))
12198 (and (not arg) org-use-fast-todo-selection
12199 (not (eq org-use-fast-todo-selection
12200 'prefix)))))
12201 ;; Use fast selection
12202 (org-fast-todo-selection))
12203 ((and (equal arg '(4))
12204 (or (not org-use-fast-todo-selection)
12205 (not org-todo-key-trigger)))
12206 ;; Read a state with completion
12207 (org-icompleting-read
12208 "State: " (mapcar 'list org-todo-keywords-1)
12209 nil t))
12210 ((eq arg 'right)
12211 (if this
12212 (if tail (car tail) nil)
12213 (car org-todo-keywords-1)))
12214 ((eq arg 'left)
12215 (if (equal member org-todo-keywords-1)
12217 (if this
12218 (nth (- (length org-todo-keywords-1)
12219 (length tail) 2)
12220 org-todo-keywords-1)
12221 (org-last org-todo-keywords-1))))
12222 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12223 (setq arg nil))) ; hack to fall back to cycling
12224 (arg
12225 ;; user or caller requests a specific state
12226 (cond
12227 ((equal arg "") nil)
12228 ((eq arg 'none) nil)
12229 ((eq arg 'done) (or done-word (car org-done-keywords)))
12230 ((eq arg 'nextset)
12231 (or (car (cdr (member head org-todo-heads)))
12232 (car org-todo-heads)))
12233 ((eq arg 'previousset)
12234 (let ((org-todo-heads (reverse org-todo-heads)))
12235 (or (car (cdr (member head org-todo-heads)))
12236 (car org-todo-heads))))
12237 ((car (member arg org-todo-keywords-1)))
12238 ((stringp arg)
12239 (user-error "State `%s' not valid in this file" arg))
12240 ((nth (1- (prefix-numeric-value arg))
12241 org-todo-keywords-1))))
12242 ((null member) (or head (car org-todo-keywords-1)))
12243 ((equal this final-done-word) nil) ;; -> make empty
12244 ((null tail) nil) ;; -> first entry
12245 ((memq interpret '(type priority))
12246 (if (eq this-command last-command)
12247 (car tail)
12248 (if (> (length tail) 0)
12249 (or done-word (car org-done-keywords))
12250 nil)))
12252 (car tail))))
12253 (org-state (or
12254 (run-hook-with-args-until-success
12255 'org-todo-get-default-hook org-state org-last-state)
12256 org-state))
12257 (next (if org-state (concat " " org-state " ") " "))
12258 (change-plist (list :type 'todo-state-change :from this :to org-state
12259 :position startpos))
12260 dolog now-done-p)
12261 (when org-blocker-hook
12262 (setq org-last-todo-state-is-todo
12263 (not (member this org-done-keywords)))
12264 (unless (save-excursion
12265 (save-match-data
12266 (org-with-wide-buffer
12267 (run-hook-with-args-until-failure
12268 'org-blocker-hook change-plist))))
12269 (if (org-called-interactively-p 'interactive)
12270 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12271 this org-state org-block-entry-blocking)
12272 ;; fail silently
12273 (message "TODO state change from %s to %s blocked (by \"%s\")"
12274 this org-state org-block-entry-blocking)
12275 (throw 'exit nil))))
12276 (store-match-data match-data)
12277 (replace-match next t t)
12278 (unless (pos-visible-in-window-p hl-pos)
12279 (message "TODO state changed to %s" (org-trim next)))
12280 (unless head
12281 (setq head (org-get-todo-sequence-head org-state)
12282 ass (assoc head org-todo-kwd-alist)
12283 interpret (nth 1 ass)
12284 done-word (nth 3 ass)
12285 final-done-word (nth 4 ass)))
12286 (when (memq arg '(nextset previousset))
12287 (message "Keyword-Set %d/%d: %s"
12288 (- (length org-todo-sets) -1
12289 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12290 (length org-todo-sets)
12291 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12292 (setq org-last-todo-state-is-todo
12293 (not (member org-state org-done-keywords)))
12294 (setq now-done-p (and (member org-state org-done-keywords)
12295 (not (member this org-done-keywords))))
12296 (and logging (org-local-logging logging))
12297 (when (and (or org-todo-log-states org-log-done)
12298 (not (eq org-inhibit-logging t))
12299 (not (memq arg '(nextset previousset))))
12300 ;; we need to look at recording a time and note
12301 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12302 (nth 2 (assoc this org-todo-log-states))))
12303 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12304 (setq dolog 'time))
12305 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12306 (and org-state
12307 (member org-state org-not-done-keywords)
12308 (not (member this org-not-done-keywords))))
12309 ;; This is now a todo state and was not one before
12310 ;; If there was a CLOSED time stamp, get rid of it.
12311 (org-add-planning-info nil nil 'closed))
12312 (when (and now-done-p org-log-done)
12313 ;; It is now done, and it was not done before
12314 (org-add-planning-info 'closed (org-current-effective-time))
12315 (if (and (not dolog) (eq 'note org-log-done))
12316 (org-add-log-setup 'done org-state this 'findpos 'note)))
12317 (when (and org-state dolog)
12318 ;; This is a non-nil state, and we need to log it
12319 (org-add-log-setup 'state org-state this 'findpos dolog)))
12320 ;; Fixup tag positioning
12321 (org-todo-trigger-tag-changes org-state)
12322 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12323 (when org-provide-todo-statistics
12324 (org-update-parent-todo-statistics))
12325 (run-hooks 'org-after-todo-state-change-hook)
12326 (if (and arg (not (member org-state org-done-keywords)))
12327 (setq head (org-get-todo-sequence-head org-state)))
12328 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12329 ;; Do we need to trigger a repeat?
12330 (when now-done-p
12331 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12332 ;; This is for the agenda, take a snapshot of the headline.
12333 (save-match-data
12334 (setq org-agenda-headline-snapshot-before-repeat
12335 (org-get-heading))))
12336 (org-auto-repeat-maybe org-state))
12337 ;; Fixup cursor location if close to the keyword
12338 (if (and (outline-on-heading-p)
12339 (not (bolp))
12340 (save-excursion (beginning-of-line 1)
12341 (looking-at org-todo-line-regexp))
12342 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12343 (progn
12344 (goto-char (or (match-end 2) (match-end 1)))
12345 (and (looking-at " ") (just-one-space))))
12346 (when org-trigger-hook
12347 (save-excursion
12348 (run-hook-with-args 'org-trigger-hook change-plist)))
12349 (when commentp (org-toggle-comment))))))))
12351 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12352 "Block turning an entry into a TODO, using the hierarchy.
12353 This checks whether the current task should be blocked from state
12354 changes. Such blocking occurs when:
12356 1. The task has children which are not all in a completed state.
12358 2. A task has a parent with the property :ORDERED:, and there
12359 are siblings prior to the current task with incomplete
12360 status.
12362 3. The parent of the task is blocked because it has siblings that should
12363 be done first, or is child of a block grandparent TODO entry."
12365 (if (not org-enforce-todo-dependencies)
12366 t ; if locally turned off don't block
12367 (catch 'dont-block
12368 ;; If this is not a todo state change, or if this entry is already DONE,
12369 ;; do not block
12370 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12371 (member (plist-get change-plist :from)
12372 (cons 'done org-done-keywords))
12373 (member (plist-get change-plist :to)
12374 (cons 'todo org-not-done-keywords))
12375 (not (plist-get change-plist :to)))
12376 (throw 'dont-block t))
12377 ;; If this task has children, and any are undone, it's blocked
12378 (save-excursion
12379 (org-back-to-heading t)
12380 (let ((this-level (funcall outline-level)))
12381 (outline-next-heading)
12382 (let ((child-level (funcall outline-level)))
12383 (while (and (not (eobp))
12384 (> child-level this-level))
12385 ;; this todo has children, check whether they are all
12386 ;; completed
12387 (if (and (not (org-entry-is-done-p))
12388 (org-entry-is-todo-p))
12389 (progn (setq org-block-entry-blocking (org-get-heading))
12390 (throw 'dont-block nil)))
12391 (outline-next-heading)
12392 (setq child-level (funcall outline-level))))))
12393 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12394 ;; any previous siblings are undone, it's blocked
12395 (save-excursion
12396 (org-back-to-heading t)
12397 (let* ((pos (point))
12398 (parent-pos (and (org-up-heading-safe) (point))))
12399 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12400 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12401 (forward-line 1)
12402 (re-search-forward org-not-done-heading-regexp pos t))
12403 (setq org-block-entry-blocking (match-string 0))
12404 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12405 ;; Search further up the hierarchy, to see if an ancestor is blocked
12406 (while t
12407 (goto-char parent-pos)
12408 (if (not (looking-at org-not-done-heading-regexp))
12409 (throw 'dont-block t)) ; do not block, parent is not a TODO
12410 (setq pos (point))
12411 (setq parent-pos (and (org-up-heading-safe) (point)))
12412 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12413 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12414 (forward-line 1)
12415 (re-search-forward org-not-done-heading-regexp pos t)
12416 (setq org-block-entry-blocking (org-get-heading)))
12417 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12419 (defcustom org-track-ordered-property-with-tag nil
12420 "Should the ORDERED property also be shown as a tag?
12421 The ORDERED property decides if an entry should require subtasks to be
12422 completed in sequence. Since a property is not very visible, setting
12423 this option means that toggling the ORDERED property with the command
12424 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12425 not relevant for the behavior, but it makes things more visible.
12427 Note that toggling the tag with tags commands will not change the property
12428 and therefore not influence behavior!
12430 This can be t, meaning the tag ORDERED should be used, It can also be a
12431 string to select a different tag for this task."
12432 :group 'org-todo
12433 :type '(choice
12434 (const :tag "No tracking" nil)
12435 (const :tag "Track with ORDERED tag" t)
12436 (string :tag "Use other tag")))
12438 (defun org-toggle-ordered-property ()
12439 "Toggle the ORDERED property of the current entry.
12440 For better visibility, you can track the value of this property with a tag.
12441 See variable `org-track-ordered-property-with-tag'."
12442 (interactive)
12443 (let* ((t1 org-track-ordered-property-with-tag)
12444 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12445 (save-excursion
12446 (org-back-to-heading)
12447 (if (org-entry-get nil "ORDERED")
12448 (progn
12449 (org-delete-property "ORDERED" "PROPERTIES")
12450 (and tag (org-toggle-tag tag 'off))
12451 (message "Subtasks can be completed in arbitrary order"))
12452 (org-entry-put nil "ORDERED" "t")
12453 (and tag (org-toggle-tag tag 'on))
12454 (message "Subtasks must be completed in sequence")))))
12456 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12457 (defun org-block-todo-from-checkboxes (change-plist)
12458 "Block turning an entry into a TODO, using checkboxes.
12459 This checks whether the current task should be blocked from state
12460 changes because there are unchecked boxes in this entry."
12461 (if (not org-enforce-todo-checkbox-dependencies)
12462 t ; if locally turned off don't block
12463 (catch 'dont-block
12464 ;; If this is not a todo state change, or if this entry is already DONE,
12465 ;; do not block
12466 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12467 (member (plist-get change-plist :from)
12468 (cons 'done org-done-keywords))
12469 (member (plist-get change-plist :to)
12470 (cons 'todo org-not-done-keywords))
12471 (not (plist-get change-plist :to)))
12472 (throw 'dont-block t))
12473 ;; If this task has checkboxes that are not checked, it's blocked
12474 (save-excursion
12475 (org-back-to-heading t)
12476 (let ((beg (point)) end)
12477 (outline-next-heading)
12478 (setq end (point))
12479 (goto-char beg)
12480 (if (org-list-search-forward
12481 (concat (org-item-beginning-re)
12482 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12483 "\\[[- ]\\]")
12484 end t)
12485 (progn
12486 (if (boundp 'org-blocked-by-checkboxes)
12487 (setq org-blocked-by-checkboxes t))
12488 (throw 'dont-block nil)))))
12489 t))) ; do not block
12491 (defun org-entry-blocked-p ()
12492 "Is the current entry blocked?"
12493 (org-with-silent-modifications
12494 (if (org-entry-get nil "NOBLOCKING")
12495 nil ;; Never block this entry
12496 (not (run-hook-with-args-until-failure
12497 'org-blocker-hook
12498 (list :type 'todo-state-change
12499 :position (point)
12500 :from 'todo
12501 :to 'done))))))
12503 (defun org-update-statistics-cookies (all)
12504 "Update the statistics cookie, either from TODO or from checkboxes.
12505 This should be called with the cursor in a line with a statistics cookie."
12506 (interactive "P")
12507 (if all
12508 (progn
12509 (org-update-checkbox-count 'all)
12510 (org-map-entries 'org-update-parent-todo-statistics))
12511 (if (not (org-at-heading-p))
12512 (org-update-checkbox-count)
12513 (let ((pos (point-marker))
12514 end l1 l2)
12515 (ignore-errors (org-back-to-heading t))
12516 (if (not (org-at-heading-p))
12517 (org-update-checkbox-count)
12518 (setq l1 (org-outline-level))
12519 (setq end (save-excursion
12520 (outline-next-heading)
12521 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12522 (point)))
12523 (if (and (save-excursion
12524 (re-search-forward
12525 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12526 (not (save-excursion (re-search-forward
12527 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12528 (org-update-checkbox-count)
12529 (if (and l2 (> l2 l1))
12530 (progn
12531 (goto-char end)
12532 (org-update-parent-todo-statistics))
12533 (goto-char pos)
12534 (beginning-of-line 1)
12535 (while (re-search-forward
12536 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12537 (point-at-eol) t)
12538 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12539 (goto-char pos)
12540 (move-marker pos nil)))))
12542 (defvar org-entry-property-inherited-from) ;; defined below
12543 (defun org-update-parent-todo-statistics ()
12544 "Update any statistics cookie in the parent of the current headline.
12545 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12546 the entire subtree and this will travel up the hierarchy and update
12547 statistics everywhere."
12548 (let* ((prop (save-excursion (org-up-heading-safe)
12549 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12550 (recursive (or (not org-hierarchical-todo-statistics)
12551 (and prop (string-match "\\<recursive\\>" prop))))
12552 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12554 (first t)
12555 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12556 level ltoggle l1 new ndel
12557 (cnt-all 0) (cnt-done 0) is-percent kwd
12558 checkbox-beg ov ovs ove cookie-present)
12559 (catch 'exit
12560 (save-excursion
12561 (beginning-of-line 1)
12562 (setq ltoggle (funcall outline-level))
12563 ;; Three situations are to consider:
12565 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12566 ;; to the top-level ancestor on the headline;
12568 ;; 2. If parent has "recursive" property, repeat up to the
12569 ;; headline setting that property, taking inheritance into
12570 ;; account;
12572 ;; 3. Else, move up to direct parent and proceed only once.
12573 (while (and (setq level (org-up-heading-safe))
12574 (or recursive first)
12575 (>= (point) lim))
12576 (setq first nil cookie-present nil)
12577 (unless (and level
12578 (not (string-match
12579 "\\<checkbox\\>"
12580 (downcase (or (org-entry-get nil "COOKIE_DATA")
12581 "")))))
12582 (throw 'exit nil))
12583 (while (re-search-forward box-re (point-at-eol) t)
12584 (setq cnt-all 0 cnt-done 0 cookie-present t)
12585 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12586 (save-match-data
12587 (unless (outline-next-heading) (throw 'exit nil))
12588 (while (and (looking-at org-complex-heading-regexp)
12589 (> (setq l1 (length (match-string 1))) level))
12590 (setq kwd (and (or recursive (= l1 ltoggle))
12591 (match-string 2)))
12592 (if (or (eq org-provide-todo-statistics 'all-headlines)
12593 (and (listp org-provide-todo-statistics)
12594 (or (member kwd org-provide-todo-statistics)
12595 (member kwd org-done-keywords))))
12596 (setq cnt-all (1+ cnt-all))
12597 (if (eq org-provide-todo-statistics t)
12598 (and kwd (setq cnt-all (1+ cnt-all)))))
12599 (and (member kwd org-done-keywords)
12600 (setq cnt-done (1+ cnt-done)))
12601 (outline-next-heading)))
12602 (setq new
12603 (if is-percent
12604 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12605 (format "[%d/%d]" cnt-done cnt-all))
12606 ndel (- (match-end 0) checkbox-beg))
12607 ;; handle overlays when updating cookie from column view
12608 (when (setq ov (car (overlays-at checkbox-beg)))
12609 (setq ovs (overlay-start ov) ove (overlay-end ov))
12610 (delete-overlay ov))
12611 (goto-char checkbox-beg)
12612 (insert new)
12613 (delete-region (point) (+ (point) ndel))
12614 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12615 (when ov (move-overlay ov ovs ove)))
12616 (when cookie-present
12617 (run-hook-with-args 'org-after-todo-statistics-hook
12618 cnt-done (- cnt-all cnt-done))))))
12619 (run-hooks 'org-todo-statistics-hook)))
12621 (defvar org-after-todo-statistics-hook nil
12622 "Hook that is called after a TODO statistics cookie has been updated.
12623 Each function is called with two arguments: the number of not-done entries
12624 and the number of done entries.
12626 For example, the following function, when added to this hook, will switch
12627 an entry to DONE when all children are done, and back to TODO when new
12628 entries are set to a TODO status. Note that this hook is only called
12629 when there is a statistics cookie in the headline!
12631 (defun org-summary-todo (n-done n-not-done)
12632 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12633 (let (org-log-done org-log-states) ; turn off logging
12634 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12637 (defvar org-todo-statistics-hook nil
12638 "Hook that is run whenever Org thinks TODO statistics should be updated.
12639 This hook runs even if there is no statistics cookie present, in which case
12640 `org-after-todo-statistics-hook' would not run.")
12642 (defun org-todo-trigger-tag-changes (state)
12643 "Apply the changes defined in `org-todo-state-tags-triggers'."
12644 (let ((l org-todo-state-tags-triggers)
12645 changes)
12646 (when (or (not state) (equal state ""))
12647 (setq changes (append changes (cdr (assoc "" l)))))
12648 (when (and (stringp state) (> (length state) 0))
12649 (setq changes (append changes (cdr (assoc state l)))))
12650 (when (member state org-not-done-keywords)
12651 (setq changes (append changes (cdr (assoc 'todo l)))))
12652 (when (member state org-done-keywords)
12653 (setq changes (append changes (cdr (assoc 'done l)))))
12654 (dolist (c changes)
12655 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12657 (defun org-local-logging (value)
12658 "Get logging settings from a property VALUE."
12659 (let* (words w a)
12660 ;; directly set the variables, they are already local.
12661 (setq org-log-done nil
12662 org-log-repeat nil
12663 org-todo-log-states nil)
12664 (setq words (org-split-string value))
12665 (while (setq w (pop words))
12666 (cond
12667 ((setq a (assoc w org-startup-options))
12668 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12669 (set (nth 1 a) (nth 2 a))))
12670 ((setq a (org-extract-log-state-settings w))
12671 (and (member (car a) org-todo-keywords-1)
12672 (push a org-todo-log-states)))))))
12674 (defun org-get-todo-sequence-head (kwd)
12675 "Return the head of the TODO sequence to which KWD belongs.
12676 If KWD is not set, check if there is a text property remembering the
12677 right sequence."
12678 (let (p)
12679 (cond
12680 ((not kwd)
12681 (or (get-text-property (point-at-bol) 'org-todo-head)
12682 (progn
12683 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12684 nil (point-at-eol)))
12685 (get-text-property p 'org-todo-head))))
12686 ((not (member kwd org-todo-keywords-1))
12687 (car org-todo-keywords-1))
12688 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12690 (defun org-fast-todo-selection ()
12691 "Fast TODO keyword selection with single keys.
12692 Returns the new TODO keyword, or nil if no state change should occur."
12693 (let* ((fulltable org-todo-key-alist)
12694 (done-keywords org-done-keywords) ;; needed for the faces.
12695 (maxlen (apply 'max (mapcar
12696 (lambda (x)
12697 (if (stringp (car x)) (string-width (car x)) 0))
12698 fulltable)))
12699 (expert nil)
12700 (fwidth (+ maxlen 3 1 3))
12701 (ncol (/ (- (window-width) 4) fwidth))
12702 tg cnt e c tbl
12703 groups ingroup)
12704 (save-excursion
12705 (save-window-excursion
12706 (if expert
12707 (set-buffer (get-buffer-create " *Org todo*"))
12708 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12709 (erase-buffer)
12710 (org-set-local 'org-done-keywords done-keywords)
12711 (setq tbl fulltable cnt 0)
12712 (while (setq e (pop tbl))
12713 (cond
12714 ((equal e '(:startgroup))
12715 (push '() groups) (setq ingroup t)
12716 (when (not (= cnt 0))
12717 (setq cnt 0)
12718 (insert "\n"))
12719 (insert "{ "))
12720 ((equal e '(:endgroup))
12721 (setq ingroup nil cnt 0)
12722 (insert "}\n"))
12723 ((equal e '(:newline))
12724 (when (not (= cnt 0))
12725 (setq cnt 0)
12726 (insert "\n")
12727 (setq e (car tbl))
12728 (while (equal (car tbl) '(:newline))
12729 (insert "\n")
12730 (setq tbl (cdr tbl)))))
12732 (setq tg (car e) c (cdr e))
12733 (if ingroup (push tg (car groups)))
12734 (setq tg (org-add-props tg nil 'face
12735 (org-get-todo-face tg)))
12736 (if (and (= cnt 0) (not ingroup)) (insert " "))
12737 (insert "[" c "] " tg (make-string
12738 (- fwidth 4 (length tg)) ?\ ))
12739 (when (= (setq cnt (1+ cnt)) ncol)
12740 (insert "\n")
12741 (if ingroup (insert " "))
12742 (setq cnt 0)))))
12743 (insert "\n")
12744 (goto-char (point-min))
12745 (if (not expert) (org-fit-window-to-buffer))
12746 (message "[a-z..]:Set [SPC]:clear")
12747 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12748 (cond
12749 ((or (= c ?\C-g)
12750 (and (= c ?q) (not (rassoc c fulltable))))
12751 (setq quit-flag t))
12752 ((= c ?\ ) nil)
12753 ((setq e (rassoc c fulltable) tg (car e))
12755 (t (setq quit-flag t)))))))
12757 (defun org-entry-is-todo-p ()
12758 (member (org-get-todo-state) org-not-done-keywords))
12760 (defun org-entry-is-done-p ()
12761 (member (org-get-todo-state) org-done-keywords))
12763 (defun org-get-todo-state ()
12764 "Return the TODO keyword of the current subtree."
12765 (save-excursion
12766 (org-back-to-heading t)
12767 (and (looking-at org-todo-line-regexp)
12768 (match-end 2)
12769 (match-string 2))))
12771 (defun org-at-date-range-p (&optional inactive-ok)
12772 "Is the cursor inside a date range?"
12773 (interactive)
12774 (save-excursion
12775 (catch 'exit
12776 (let ((pos (point)))
12777 (skip-chars-backward "^[<\r\n")
12778 (skip-chars-backward "<[")
12779 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12780 (>= (match-end 0) pos)
12781 (throw 'exit t))
12782 (skip-chars-backward "^<[\r\n")
12783 (skip-chars-backward "<[")
12784 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12785 (>= (match-end 0) pos)
12786 (throw 'exit t)))
12787 nil)))
12789 (defun org-get-repeat (&optional tagline)
12790 "Check if there is a deadline/schedule with repeater in this entry."
12791 (save-match-data
12792 (save-excursion
12793 (org-back-to-heading t)
12794 (and (re-search-forward (if tagline
12795 (concat tagline "\\s-*" org-repeat-re)
12796 org-repeat-re)
12797 (org-entry-end-position) t)
12798 (match-string-no-properties 1)))))
12800 (defvar org-last-changed-timestamp)
12801 (defvar org-last-inserted-timestamp)
12802 (defvar org-log-post-message)
12803 (defvar org-log-note-purpose)
12804 (defvar org-log-note-how)
12805 (defvar org-log-note-extra)
12806 (defun org-auto-repeat-maybe (done-word)
12807 "Check if the current headline contains a repeated deadline/schedule.
12808 If yes, set TODO state back to what it was and change the base date
12809 of repeating deadline/scheduled time stamps to new date.
12810 This function is run automatically after each state change to a DONE state."
12811 ;; last-state is dynamically scoped into this function
12812 (let* ((repeat (org-get-repeat))
12813 (aa (assoc org-last-state org-todo-kwd-alist))
12814 (interpret (nth 1 aa))
12815 (head (nth 2 aa))
12816 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12817 (msg "Entry repeats: ")
12818 (org-log-done nil)
12819 (org-todo-log-states nil)
12820 re type n what ts time to-state)
12821 (when repeat
12822 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12823 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12824 org-todo-repeat-to-state))
12825 (unless (and to-state (member to-state org-todo-keywords-1))
12826 (setq to-state (if (eq interpret 'type) org-last-state head)))
12827 (org-todo to-state)
12828 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12829 (org-entry-put nil "LAST_REPEAT" (format-time-string
12830 (org-time-stamp-format t t))))
12831 (when org-log-repeat
12832 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12833 (memq 'org-add-log-note post-command-hook))
12834 ;; OK, we are already setup for some record
12835 (if (eq org-log-repeat 'note)
12836 ;; make sure we take a note, not only a time stamp
12837 (setq org-log-note-how 'note))
12838 ;; Set up for taking a record
12839 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12840 org-last-state
12841 'findpos org-log-repeat)))
12842 (org-back-to-heading t)
12843 (org-add-planning-info nil nil 'closed)
12844 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12845 org-deadline-time-regexp "\\)\\|\\("
12846 org-ts-regexp "\\)"))
12847 (while (re-search-forward
12848 re (save-excursion (outline-next-heading) (point)) t)
12849 (setq type (if (match-end 1) org-scheduled-string
12850 (if (match-end 3) org-deadline-string "Plain:"))
12851 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12852 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12853 (setq n (string-to-number (match-string 2 ts))
12854 what (match-string 3 ts))
12855 (if (equal what "w") (setq n (* n 7) what "d"))
12856 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12857 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12858 ;; Preparation, see if we need to modify the start date for the change
12859 (when (match-end 1)
12860 (setq time (save-match-data (org-time-string-to-time ts)))
12861 (cond
12862 ((equal (match-string 1 ts) ".")
12863 ;; Shift starting date to today
12864 (org-timestamp-change
12865 (- (org-today) (time-to-days time))
12866 'day))
12867 ((equal (match-string 1 ts) "+")
12868 (let ((nshiftmax 10) (nshift 0))
12869 (while (or (= nshift 0)
12870 (<= (time-to-days time)
12871 (time-to-days (current-time))))
12872 (when (= (incf nshift) nshiftmax)
12873 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12874 (error "Abort")))
12875 (org-timestamp-change n (cdr (assoc what whata)))
12876 (org-at-timestamp-p t)
12877 (setq ts (match-string 1))
12878 (setq time (save-match-data (org-time-string-to-time ts)))))
12879 (org-timestamp-change (- n) (cdr (assoc what whata)))
12880 ;; rematch, so that we have everything in place for the real shift
12881 (org-at-timestamp-p t)
12882 (setq ts (match-string 1))
12883 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12884 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12885 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12886 (setq org-log-post-message msg)
12887 (message "%s" msg))))
12889 (defun org-show-todo-tree (arg)
12890 "Make a compact tree which shows all headlines marked with TODO.
12891 The tree will show the lines where the regexp matches, and all higher
12892 headlines above the match.
12893 With a \\[universal-argument] prefix, prompt for a regexp to match.
12894 With a numeric prefix N, construct a sparse tree for the Nth element
12895 of `org-todo-keywords-1'."
12896 (interactive "P")
12897 (let ((case-fold-search nil)
12898 (kwd-re
12899 (cond ((null arg) org-not-done-regexp)
12900 ((equal arg '(4))
12901 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12902 (mapcar 'list org-todo-keywords-1))))
12903 (concat "\\("
12904 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12905 "\\)\\>")))
12906 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12907 (regexp-quote (nth (1- (prefix-numeric-value arg))
12908 org-todo-keywords-1)))
12909 (t (user-error "Invalid prefix argument: %s" arg)))))
12910 (message "%d TODO entries found"
12911 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12913 (defun org-deadline (arg &optional time)
12914 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12915 With one universal prefix argument, remove any deadline from the item.
12916 With two universal prefix arguments, prompt for a warning delay.
12917 With argument TIME, set the deadline at the corresponding date. TIME
12918 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12919 (interactive "P")
12920 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12921 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12922 'region-start-level 'region))
12923 org-loop-over-headlines-in-active-region)
12924 (org-map-entries
12925 `(org-deadline ',arg ,time)
12926 org-loop-over-headlines-in-active-region
12927 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12928 (let* ((old-date (org-entry-get nil "DEADLINE"))
12929 (old-date-time (if old-date (org-time-string-to-time old-date)))
12930 (repeater (and old-date
12931 (string-match
12932 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12933 old-date)
12934 (match-string 1 old-date))))
12935 (cond
12936 ((equal arg '(4))
12937 (when (and old-date org-log-redeadline)
12938 (org-add-log-setup 'deldeadline nil old-date 'findpos
12939 org-log-redeadline))
12940 (org-remove-timestamp-with-keyword org-deadline-string)
12941 (message "Item no longer has a deadline."))
12942 ((equal arg '(16))
12943 (save-excursion
12944 (org-back-to-heading t)
12945 (if (re-search-forward
12946 org-deadline-time-regexp
12947 (save-excursion (outline-next-heading) (point)) t)
12948 (let* ((rpl0 (match-string 1))
12949 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12950 (replace-match
12951 (concat org-deadline-string
12952 " <" rpl
12953 (format " -%dd"
12954 (abs
12955 (- (time-to-days
12956 (save-match-data
12957 (org-read-date nil t nil "Warn starting from" old-date-time)))
12958 (time-to-days old-date-time))))
12959 ">") t t))
12960 (user-error "No deadline information to update"))))
12962 (org-add-planning-info 'deadline time 'closed)
12963 (when (and old-date org-log-redeadline
12964 (not (equal old-date
12965 (substring org-last-inserted-timestamp 1 -1))))
12966 (org-add-log-setup 'redeadline nil old-date 'findpos
12967 org-log-redeadline))
12968 (when repeater
12969 (save-excursion
12970 (org-back-to-heading t)
12971 (when (re-search-forward (concat org-deadline-string " "
12972 org-last-inserted-timestamp)
12973 (save-excursion
12974 (outline-next-heading) (point)) t)
12975 (goto-char (1- (match-end 0)))
12976 (insert " " repeater)
12977 (setq org-last-inserted-timestamp
12978 (concat (substring org-last-inserted-timestamp 0 -1)
12979 " " repeater
12980 (substring org-last-inserted-timestamp -1))))))
12981 (message "Deadline on %s" org-last-inserted-timestamp))))))
12983 (defun org-schedule (arg &optional time)
12984 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12985 With one universal prefix argument, remove any scheduling date from the item.
12986 With two universal prefix arguments, prompt for a delay cookie.
12987 With argument TIME, scheduled at the corresponding date. TIME can
12988 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12989 (interactive "P")
12990 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12991 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12992 'region-start-level 'region))
12993 org-loop-over-headlines-in-active-region)
12994 (org-map-entries
12995 `(org-schedule ',arg ,time)
12996 org-loop-over-headlines-in-active-region
12997 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12998 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12999 (old-date-time (if old-date (org-time-string-to-time old-date)))
13000 (repeater (and old-date
13001 (string-match
13002 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13003 old-date)
13004 (match-string 1 old-date))))
13005 (cond
13006 ((equal arg '(4))
13007 (progn
13008 (when (and old-date org-log-reschedule)
13009 (org-add-log-setup 'delschedule nil old-date 'findpos
13010 org-log-reschedule))
13011 (org-remove-timestamp-with-keyword org-scheduled-string)
13012 (message "Item is no longer scheduled.")))
13013 ((equal arg '(16))
13014 (save-excursion
13015 (org-back-to-heading t)
13016 (if (re-search-forward
13017 org-scheduled-time-regexp
13018 (save-excursion (outline-next-heading) (point)) t)
13019 (let* ((rpl0 (match-string 1))
13020 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13021 (replace-match
13022 (concat org-scheduled-string
13023 " <" rpl
13024 (format " -%dd"
13025 (abs
13026 (- (time-to-days
13027 (save-match-data
13028 (org-read-date nil t nil "Delay until" old-date-time)))
13029 (time-to-days old-date-time))))
13030 ">") t t))
13031 (user-error "No scheduled information to update"))))
13033 (org-add-planning-info 'scheduled time 'closed)
13034 (when (and old-date org-log-reschedule
13035 (not (equal old-date
13036 (substring org-last-inserted-timestamp 1 -1))))
13037 (org-add-log-setup 'reschedule nil old-date 'findpos
13038 org-log-reschedule))
13039 (when repeater
13040 (save-excursion
13041 (org-back-to-heading t)
13042 (when (re-search-forward (concat org-scheduled-string " "
13043 org-last-inserted-timestamp)
13044 (save-excursion
13045 (outline-next-heading) (point)) t)
13046 (goto-char (1- (match-end 0)))
13047 (insert " " repeater)
13048 (setq org-last-inserted-timestamp
13049 (concat (substring org-last-inserted-timestamp 0 -1)
13050 " " repeater
13051 (substring org-last-inserted-timestamp -1))))))
13052 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13054 (defun org-get-scheduled-time (pom &optional inherit)
13055 "Get the scheduled time as a time tuple, of a format suitable
13056 for calling org-schedule with, or if there is no scheduling,
13057 returns nil."
13058 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13059 (when time
13060 (apply 'encode-time (org-parse-time-string time)))))
13062 (defun org-get-deadline-time (pom &optional inherit)
13063 "Get the deadline as a time tuple, of a format suitable for
13064 calling org-deadline with, or if there is no scheduling, returns
13065 nil."
13066 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13067 (when time
13068 (apply 'encode-time (org-parse-time-string time)))))
13070 (defun org-remove-timestamp-with-keyword (keyword)
13071 "Remove all time stamps with KEYWORD in the current entry."
13072 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13073 beg)
13074 (save-excursion
13075 (org-back-to-heading t)
13076 (setq beg (point))
13077 (outline-next-heading)
13078 (while (re-search-backward re beg t)
13079 (replace-match "")
13080 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13081 (equal (char-before) ?\ ))
13082 (backward-delete-char 1)
13083 (if (string-match "^[ \t]*$" (buffer-substring
13084 (point-at-bol) (point-at-eol)))
13085 (delete-region (point-at-bol)
13086 (min (point-max) (1+ (point-at-eol))))))))))
13088 (defvar org-time-was-given) ; dynamically scoped parameter
13089 (defvar org-end-time-was-given) ; dynamically scoped parameter
13091 (defun org-add-planning-info (what &optional time &rest remove)
13092 "Insert new timestamp with keyword in the line directly after the headline.
13093 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13094 If non is given, the user is prompted for a date.
13095 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13096 be removed."
13097 (interactive)
13098 (let (org-time-was-given org-end-time-was-given ts
13099 end default-time default-input)
13101 (catch 'exit
13102 (when (and (memq what '(scheduled deadline))
13103 (or (not time)
13104 (and (stringp time)
13105 (string-match "^[-+]+[0-9]" time))))
13106 ;; Try to get a default date/time from existing timestamp
13107 (save-excursion
13108 (org-back-to-heading t)
13109 (setq end (save-excursion (outline-next-heading) (point)))
13110 (when (re-search-forward (if (eq what 'scheduled)
13111 org-scheduled-time-regexp
13112 org-deadline-time-regexp)
13113 end t)
13114 (setq ts (match-string 1)
13115 default-time
13116 (apply 'encode-time (org-parse-time-string ts))
13117 default-input (and ts (org-get-compact-tod ts))))))
13118 (when what
13119 (setq time
13120 (if (stringp time)
13121 ;; This is a string (relative or absolute), set proper date
13122 (apply 'encode-time
13123 (org-read-date-analyze
13124 time default-time (decode-time default-time)))
13125 ;; If necessary, get the time from the user
13126 (or time (org-read-date nil 'to-time nil nil
13127 default-time default-input)))))
13129 (when (and org-insert-labeled-timestamps-at-point
13130 (member what '(scheduled deadline)))
13131 (insert
13132 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13133 (org-insert-time-stamp time org-time-was-given
13134 nil nil nil (list org-end-time-was-given))
13135 (setq what nil))
13136 (save-excursion
13137 (save-restriction
13138 (let (col list elt ts buffer-invisibility-spec)
13139 (org-back-to-heading t)
13140 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13141 (goto-char (match-end 1))
13142 (setq col (current-column))
13143 (goto-char (match-end 0))
13144 (if (eobp) (insert "\n") (forward-char 1))
13145 (when (and (not what)
13146 (not (looking-at
13147 (concat "[ \t]*"
13148 org-keyword-time-not-clock-regexp))))
13149 ;; Nothing to add, nothing to remove...... :-)
13150 (throw 'exit nil))
13151 (if (and (not (looking-at org-outline-regexp))
13152 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13153 "[^\r\n]*"))
13154 (not (equal (match-string 1) org-clock-string)))
13155 (narrow-to-region (match-beginning 0) (match-end 0))
13156 (insert-before-markers "\n")
13157 (backward-char 1)
13158 (narrow-to-region (point) (point))
13159 (and org-adapt-indentation (org-indent-to-column col)))
13160 ;; Check if we have to remove something.
13161 (setq list (cons what remove))
13162 (while list
13163 (setq elt (pop list))
13164 (when (or (and (eq elt 'scheduled)
13165 (re-search-forward org-scheduled-time-regexp nil t))
13166 (and (eq elt 'deadline)
13167 (re-search-forward org-deadline-time-regexp nil t))
13168 (and (eq elt 'closed)
13169 (re-search-forward org-closed-time-regexp nil t)))
13170 (replace-match "")
13171 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13172 (and (looking-at "[ \t]+") (replace-match ""))
13173 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13174 (when what
13175 (insert
13176 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13177 (cond ((eq what 'scheduled) org-scheduled-string)
13178 ((eq what 'deadline) org-deadline-string)
13179 ((eq what 'closed) org-closed-string))
13180 " ")
13181 (setq ts (org-insert-time-stamp
13182 time
13183 (or org-time-was-given
13184 (and (eq what 'closed) org-log-done-with-time))
13185 (eq what 'closed)
13186 nil nil (list org-end-time-was-given)))
13187 (insert
13188 (if (not (or (bolp) (eq (char-before) ?\ )
13189 (memq (char-after) '(32 10))
13190 (eobp))) " " ""))
13191 (end-of-line 1))
13192 (goto-char (point-min))
13193 (widen)
13194 (if (and (looking-at "[ \t]*\n")
13195 (equal (char-before) ?\n))
13196 (delete-region (1- (point)) (point-at-eol)))
13197 ts))))))
13199 (defvar org-log-note-marker (make-marker))
13200 (defvar org-log-note-purpose nil)
13201 (defvar org-log-note-state nil)
13202 (defvar org-log-note-previous-state nil)
13203 (defvar org-log-note-how nil)
13204 (defvar org-log-note-extra nil)
13205 (defvar org-log-note-window-configuration nil)
13206 (defvar org-log-note-return-to (make-marker))
13207 (defvar org-log-note-effective-time nil
13208 "Remembered current time so that dynamically scoped
13209 `org-extend-today-until' affects tha timestamps in state change
13210 log")
13212 (defvar org-log-post-message nil
13213 "Message to be displayed after a log note has been stored.
13214 The auto-repeater uses this.")
13216 (defun org-add-note ()
13217 "Add a note to the current entry.
13218 This is done in the same way as adding a state change note."
13219 (interactive)
13220 (org-add-log-setup 'note nil nil 'findpos nil))
13222 (defvar org-property-end-re)
13223 (defun org-add-log-setup (&optional purpose state prev-state
13224 findpos how extra)
13225 "Set up the post command hook to take a note.
13226 If this is about to TODO state change, the new state is expected in STATE.
13227 When FINDPOS is non-nil, find the correct position for the note in
13228 the current entry. If not, assume that it can be inserted at point.
13229 HOW is an indicator what kind of note should be created.
13230 EXTRA is additional text that will be inserted into the notes buffer."
13231 (let* ((org-log-into-drawer (org-log-into-drawer))
13232 (drawer (cond ((stringp org-log-into-drawer)
13233 org-log-into-drawer)
13234 (org-log-into-drawer "LOGBOOK"))))
13235 (save-restriction
13236 (save-excursion
13237 (when findpos
13238 (org-back-to-heading t)
13239 (narrow-to-region (point) (save-excursion
13240 (outline-next-heading) (point)))
13241 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13242 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13243 "[^\r\n]*\\)?"))
13244 (goto-char (match-end 0))
13245 (cond
13246 (drawer
13247 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13248 nil t)
13249 (progn
13250 (goto-char (match-end 0))
13251 (or org-log-states-order-reversed
13252 (and (re-search-forward org-property-end-re nil t)
13253 (goto-char (1- (match-beginning 0))))))
13254 (insert "\n:" drawer ":\n:END:")
13255 (beginning-of-line 0)
13256 (org-indent-line)
13257 (beginning-of-line 2)
13258 (org-indent-line)
13259 (end-of-line 0)))
13260 ((and org-log-state-notes-insert-after-drawers
13261 (save-excursion
13262 (forward-line) (looking-at org-drawer-regexp)))
13263 (forward-line)
13264 (while (looking-at org-drawer-regexp)
13265 (goto-char (match-end 0))
13266 (re-search-forward org-property-end-re (point-max) t)
13267 (forward-line))
13268 (forward-line -1)))
13269 (unless org-log-states-order-reversed
13270 (and (= (char-after) ?\n) (forward-char 1))
13271 (org-skip-over-state-notes)
13272 (skip-chars-backward " \t\n\r")))
13273 (move-marker org-log-note-marker (point))
13274 (setq org-log-note-purpose purpose
13275 org-log-note-state state
13276 org-log-note-previous-state prev-state
13277 org-log-note-how how
13278 org-log-note-extra extra
13279 org-log-note-effective-time (org-current-effective-time))
13280 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13282 (defun org-skip-over-state-notes ()
13283 "Skip past the list of State notes in an entry."
13284 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13285 (when (ignore-errors (goto-char (org-in-item-p)))
13286 (let* ((struct (org-list-struct))
13287 (prevs (org-list-prevs-alist struct)))
13288 (while (looking-at "[ \t]*- State")
13289 (goto-char (or (org-list-get-next-item (point) struct prevs)
13290 (org-list-get-item-end (point) struct)))))))
13292 (defun org-add-log-note (&optional purpose)
13293 "Pop up a window for taking a note, and add this note later at point."
13294 (remove-hook 'post-command-hook 'org-add-log-note)
13295 (setq org-log-note-window-configuration (current-window-configuration))
13296 (delete-other-windows)
13297 (move-marker org-log-note-return-to (point))
13298 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13299 (goto-char org-log-note-marker)
13300 (org-switch-to-buffer-other-window "*Org Note*")
13301 (erase-buffer)
13302 (if (memq org-log-note-how '(time state))
13303 (let (current-prefix-arg) (org-store-log-note))
13304 (let ((org-inhibit-startup t)) (org-mode))
13305 (insert (format "# Insert note for %s.
13306 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13307 (cond
13308 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13309 ((eq org-log-note-purpose 'done) "closed todo item")
13310 ((eq org-log-note-purpose 'state)
13311 (format "state change from \"%s\" to \"%s\""
13312 (or org-log-note-previous-state "")
13313 (or org-log-note-state "")))
13314 ((eq org-log-note-purpose 'reschedule)
13315 "rescheduling")
13316 ((eq org-log-note-purpose 'delschedule)
13317 "no longer scheduled")
13318 ((eq org-log-note-purpose 'redeadline)
13319 "changing deadline")
13320 ((eq org-log-note-purpose 'deldeadline)
13321 "removing deadline")
13322 ((eq org-log-note-purpose 'refile)
13323 "refiling")
13324 ((eq org-log-note-purpose 'note)
13325 "this entry")
13326 (t (error "This should not happen")))))
13327 (if org-log-note-extra (insert org-log-note-extra))
13328 (org-set-local 'org-finish-function 'org-store-log-note)
13329 (run-hooks 'org-log-buffer-setup-hook)))
13331 (defvar org-note-abort nil) ; dynamically scoped
13332 (defun org-store-log-note ()
13333 "Finish taking a log note, and insert it to where it belongs."
13334 (let ((txt (buffer-string)))
13335 (kill-buffer (current-buffer))
13336 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13337 lines ind bul)
13338 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13339 (setq txt (replace-match "" t t txt)))
13340 (if (string-match "\\s-+\\'" txt)
13341 (setq txt (replace-match "" t t txt)))
13342 (setq lines (org-split-string txt "\n"))
13343 (when (and note (string-match "\\S-" note))
13344 (setq note
13345 (org-replace-escapes
13346 note
13347 (list (cons "%u" (user-login-name))
13348 (cons "%U" user-full-name)
13349 (cons "%t" (format-time-string
13350 (org-time-stamp-format 'long 'inactive)
13351 org-log-note-effective-time))
13352 (cons "%T" (format-time-string
13353 (org-time-stamp-format 'long nil)
13354 org-log-note-effective-time))
13355 (cons "%d" (format-time-string
13356 (org-time-stamp-format nil 'inactive)
13357 org-log-note-effective-time))
13358 (cons "%D" (format-time-string
13359 (org-time-stamp-format nil nil)
13360 org-log-note-effective-time))
13361 (cons "%s" (if org-log-note-state
13362 (concat "\"" org-log-note-state "\"")
13363 ""))
13364 (cons "%S" (if org-log-note-previous-state
13365 (concat "\"" org-log-note-previous-state "\"")
13366 "\"\"")))))
13367 (if lines (setq note (concat note " \\\\")))
13368 (push note lines))
13369 (when (or current-prefix-arg org-note-abort)
13370 (when org-log-into-drawer
13371 (org-remove-empty-drawer-at
13372 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13373 org-log-note-marker))
13374 (setq lines nil))
13375 (when lines
13376 (with-current-buffer (marker-buffer org-log-note-marker)
13377 (save-excursion
13378 (goto-char org-log-note-marker)
13379 (move-marker org-log-note-marker nil)
13380 (end-of-line 1)
13381 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13382 (setq ind (save-excursion
13383 (if (ignore-errors (goto-char (org-in-item-p)))
13384 (let ((struct (org-list-struct)))
13385 (org-list-get-ind
13386 (org-list-get-top-point struct) struct))
13387 (skip-chars-backward " \r\t\n")
13388 (cond
13389 ((and (org-at-heading-p)
13390 org-adapt-indentation)
13391 (1+ (org-current-level)))
13392 ((org-at-heading-p) 0)
13393 (t (org-get-indentation))))))
13394 (setq bul (org-list-bullet-string "-"))
13395 (org-indent-line-to ind)
13396 (insert bul (pop lines))
13397 (let ((ind-body (+ (length bul) ind)))
13398 (while lines
13399 (insert "\n")
13400 (org-indent-line-to ind-body)
13401 (insert (pop lines))))
13402 (message "Note stored")
13403 (org-back-to-heading t)
13404 (org-cycle-hide-drawers 'children))
13405 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13406 ;; from within `org-add-log-note' because `buffer-undo-list'
13407 ;; is then modified outside of `org-with-remote-undo'.
13408 (when (eq this-command 'org-agenda-todo)
13409 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13410 ;; Don't add undo information when called from `org-agenda-todo'
13411 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13412 (set-window-configuration org-log-note-window-configuration)
13413 (with-current-buffer (marker-buffer org-log-note-return-to)
13414 (goto-char org-log-note-return-to))
13415 (move-marker org-log-note-return-to nil)
13416 (and org-log-post-message (message "%s" org-log-post-message))))
13418 (defun org-remove-empty-drawer-at (drawer pos)
13419 "Remove an empty drawer DRAWER at position POS.
13420 POS may also be a marker."
13421 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13422 (save-excursion
13423 (save-restriction
13424 (widen)
13425 (goto-char pos)
13426 (if (org-in-regexp
13427 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13428 (replace-match ""))))))
13430 (defvar org-ts-type nil)
13431 (defun org-sparse-tree (&optional arg type)
13432 "Create a sparse tree, prompt for the details.
13433 This command can create sparse trees. You first need to select the type
13434 of match used to create the tree:
13436 t Show all TODO entries.
13437 T Show entries with a specific TODO keyword.
13438 m Show entries selected by a tags/property match.
13439 p Enter a property name and its value (both with completion on existing
13440 names/values) and show entries with that property.
13441 r Show entries matching a regular expression (`/' can be used as well).
13442 b Show deadlines and scheduled items before a date.
13443 a Show deadlines and scheduled items after a date.
13444 d Show deadlines due within `org-deadline-warning-days'.
13445 D Show deadlines and scheduled items between a date range."
13446 (interactive "P")
13447 (let (ans kwd value ts-type)
13448 (setq type (or type org-sparse-tree-default-date-type))
13449 (setq org-ts-type type)
13450 (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"
13451 (cond ((eq type 'all) "all timestamps")
13452 ((eq type 'scheduled) "only scheduled")
13453 ((eq type 'deadline) "only deadline")
13454 ((eq type 'active) "only active timestamps")
13455 ((eq type 'inactive) "only inactive timestamps")
13456 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13457 ((eq type 'closed) "with a closed time-stamp")
13458 (t "scheduled/deadline")))
13459 (setq ans (read-char-exclusive))
13460 (cond
13461 ((equal ans ?c)
13462 (org-sparse-tree
13463 arg (cadr (member type '(scheduled-or-deadline
13464 all scheduled deadline active inactive closed)))))
13465 ((equal ans ?d)
13466 (call-interactively 'org-check-deadlines))
13467 ((equal ans ?b)
13468 (call-interactively 'org-check-before-date))
13469 ((equal ans ?a)
13470 (call-interactively 'org-check-after-date))
13471 ((equal ans ?D)
13472 (call-interactively 'org-check-dates-range))
13473 ((equal ans ?t)
13474 (call-interactively 'org-show-todo-tree))
13475 ((equal ans ?T)
13476 (org-show-todo-tree '(4)))
13477 ((member ans '(?T ?m))
13478 (call-interactively 'org-match-sparse-tree))
13479 ((member ans '(?p ?P))
13480 (setq kwd (org-icompleting-read "Property: "
13481 (mapcar 'list (org-buffer-property-keys))))
13482 (setq value (org-icompleting-read "Value: "
13483 (mapcar 'list (org-property-values kwd))))
13484 (unless (string-match "\\`{.*}\\'" value)
13485 (setq value (concat "\"" value "\"")))
13486 (org-match-sparse-tree arg (concat kwd "=" value)))
13487 ((member ans '(?r ?R ?/))
13488 (call-interactively 'org-occur))
13489 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13491 (defvar org-occur-highlights nil
13492 "List of overlays used for occur matches.")
13493 (make-variable-buffer-local 'org-occur-highlights)
13494 (defvar org-occur-parameters nil
13495 "Parameters of the active org-occur calls.
13496 This is a list, each call to org-occur pushes as cons cell,
13497 containing the regular expression and the callback, onto the list.
13498 The list can contain several entries if `org-occur' has been called
13499 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13500 will only contain one set of parameters. When the highlights are
13501 removed (for example with `C-c C-c', or with the next edit (depending
13502 on `org-remove-highlights-with-change'), this variable is emptied
13503 as well.")
13504 (make-variable-buffer-local 'org-occur-parameters)
13506 (defun org-occur (regexp &optional keep-previous callback)
13507 "Make a compact tree which shows all matches of REGEXP.
13508 The tree will show the lines where the regexp matches, and all higher
13509 headlines above the match. It will also show the heading after the match,
13510 to make sure editing the matching entry is easy.
13511 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13512 call to `org-occur' will be kept, to allow stacking of calls to this
13513 command.
13514 If CALLBACK is non-nil, it is a function which is called to confirm
13515 that the match should indeed be shown."
13516 (interactive "sRegexp: \nP")
13517 (when (equal regexp "")
13518 (user-error "Regexp cannot be empty"))
13519 (unless keep-previous
13520 (org-remove-occur-highlights nil nil t))
13521 (push (cons regexp callback) org-occur-parameters)
13522 (let ((cnt 0))
13523 (save-excursion
13524 (goto-char (point-min))
13525 (if (or (not keep-previous) ; do not want to keep
13526 (not org-occur-highlights)) ; no previous matches
13527 ;; hide everything
13528 (org-overview))
13529 (while (re-search-forward regexp nil t)
13530 (when (or (not callback)
13531 (save-match-data (funcall callback)))
13532 (setq cnt (1+ cnt))
13533 (when org-highlight-sparse-tree-matches
13534 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13535 (org-show-context 'occur-tree))))
13536 (when org-remove-highlights-with-change
13537 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13538 nil 'local))
13539 (unless org-sparse-tree-open-archived-trees
13540 (org-hide-archived-subtrees (point-min) (point-max)))
13541 (run-hooks 'org-occur-hook)
13542 (if (org-called-interactively-p 'interactive)
13543 (message "%d match(es) for regexp %s" cnt regexp))
13544 cnt))
13546 (defun org-occur-next-match (&optional n reset)
13547 "Function for `next-error-function' to find sparse tree matches.
13548 N is the number of matches to move, when negative move backwards.
13549 RESET is entirely ignored - this function always goes back to the
13550 starting point when no match is found."
13551 (let* ((limit (if (< n 0) (point-min) (point-max)))
13552 (search-func (if (< n 0)
13553 'previous-single-char-property-change
13554 'next-single-char-property-change))
13555 (n (abs n))
13556 (pos (point))
13558 (catch 'exit
13559 (while (setq p1 (funcall search-func (point) 'org-type))
13560 (when (equal p1 limit)
13561 (goto-char pos)
13562 (error "No more matches"))
13563 (when (equal (get-char-property p1 'org-type) 'org-occur)
13564 (setq n (1- n))
13565 (when (= n 0)
13566 (goto-char p1)
13567 (throw 'exit (point))))
13568 (goto-char p1))
13569 (goto-char p1)
13570 (error "No more matches"))))
13572 (defun org-show-context (&optional key)
13573 "Make sure point and context are visible.
13574 How much context is shown depends upon the variables
13575 `org-show-hierarchy-above', `org-show-following-heading',
13576 `org-show-entry-below' and `org-show-siblings'."
13577 (let ((heading-p (org-at-heading-p t))
13578 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13579 (following-p (org-get-alist-option org-show-following-heading key))
13580 (entry-p (org-get-alist-option org-show-entry-below key))
13581 (siblings-p (org-get-alist-option org-show-siblings key)))
13582 ;; Show heading or entry text
13583 (if (and heading-p (not entry-p))
13584 (org-flag-heading nil) ; only show the heading
13585 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13586 (org-show-hidden-entry))) ; show entire entry
13587 (when following-p
13588 ;; Show next sibling, or heading below text
13589 (save-excursion
13590 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13591 (org-flag-heading nil))))
13592 (when siblings-p (org-show-siblings))
13593 (when hierarchy-p
13594 ;; show all higher headings, possibly with siblings
13595 (save-excursion
13596 (while (and (condition-case nil
13597 (progn (org-up-heading-all 1) t)
13598 (error nil))
13599 (not (bobp)))
13600 (org-flag-heading nil)
13601 (when siblings-p (org-show-siblings)))))
13602 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13604 (defvar org-reveal-start-hook nil
13605 "Hook run before revealing a location.")
13607 (defun org-reveal (&optional siblings)
13608 "Show current entry, hierarchy above it, and the following headline.
13609 This can be used to show a consistent set of context around locations
13610 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13611 not t for the search context.
13613 With optional argument SIBLINGS, on each level of the hierarchy all
13614 siblings are shown. This repairs the tree structure to what it would
13615 look like when opened with hierarchical calls to `org-cycle'.
13616 With double optional argument \\[universal-argument] \\[universal-argument], \
13617 go to the parent and show the
13618 entire tree."
13619 (interactive "P")
13620 (run-hooks 'org-reveal-start-hook)
13621 (let ((org-show-hierarchy-above t)
13622 (org-show-following-heading t)
13623 (org-show-siblings (if siblings t org-show-siblings)))
13624 (org-show-context nil))
13625 (when (equal siblings '(16))
13626 (save-excursion
13627 (when (org-up-heading-safe)
13628 (org-show-subtree)
13629 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13631 (defun org-highlight-new-match (beg end)
13632 "Highlight from BEG to END and mark the highlight is an occur headline."
13633 (let ((ov (make-overlay beg end)))
13634 (overlay-put ov 'face 'secondary-selection)
13635 (overlay-put ov 'org-type 'org-occur)
13636 (push ov org-occur-highlights)))
13638 (defun org-remove-occur-highlights (&optional beg end noremove)
13639 "Remove the occur highlights from the buffer.
13640 BEG and END are ignored. If NOREMOVE is nil, remove this function
13641 from the `before-change-functions' in the current buffer."
13642 (interactive)
13643 (unless org-inhibit-highlight-removal
13644 (mapc 'delete-overlay org-occur-highlights)
13645 (setq org-occur-highlights nil)
13646 (setq org-occur-parameters nil)
13647 (unless noremove
13648 (remove-hook 'before-change-functions
13649 'org-remove-occur-highlights 'local))))
13651 ;;;; Priorities
13653 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13654 "Regular expression matching the priority indicator.")
13656 (defvar org-remove-priority-next-time nil)
13658 (defun org-priority-up ()
13659 "Increase the priority of the current item."
13660 (interactive)
13661 (org-priority 'up))
13663 (defun org-priority-down ()
13664 "Decrease the priority of the current item."
13665 (interactive)
13666 (org-priority 'down))
13668 (defun org-priority (&optional action show)
13669 "Change the priority of an item.
13670 ACTION can be `set', `up', `down', or a character."
13671 (interactive "P")
13672 (if (equal action '(4))
13673 (org-show-priority)
13674 (unless org-enable-priority-commands
13675 (user-error "Priority commands are disabled"))
13676 (setq action (or action 'set))
13677 (let (current new news have remove)
13678 (save-excursion
13679 (org-back-to-heading t)
13680 (if (looking-at org-priority-regexp)
13681 (setq current (string-to-char (match-string 2))
13682 have t))
13683 (cond
13684 ((eq action 'remove)
13685 (setq remove t new ?\ ))
13686 ((or (eq action 'set)
13687 (if (featurep 'xemacs) (characterp action) (integerp action)))
13688 (if (not (eq action 'set))
13689 (setq new action)
13690 (message "Priority %c-%c, SPC to remove: "
13691 org-highest-priority org-lowest-priority)
13692 (save-match-data
13693 (setq new (read-char-exclusive))))
13694 (if (and (= (upcase org-highest-priority) org-highest-priority)
13695 (= (upcase org-lowest-priority) org-lowest-priority))
13696 (setq new (upcase new)))
13697 (cond ((equal new ?\ ) (setq remove t))
13698 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13699 (user-error "Priority must be between `%c' and `%c'"
13700 org-highest-priority org-lowest-priority))))
13701 ((eq action 'up)
13702 (setq new (if have
13703 (1- current) ; normal cycling
13704 ;; last priority was empty
13705 (if (eq last-command this-command)
13706 org-lowest-priority ; wrap around empty to lowest
13707 ;; default
13708 (if org-priority-start-cycle-with-default
13709 org-default-priority
13710 (1- org-default-priority))))))
13711 ((eq action 'down)
13712 (setq new (if have
13713 (1+ current) ; normal cycling
13714 ;; last priority was empty
13715 (if (eq last-command this-command)
13716 org-highest-priority ; wrap around empty to highest
13717 ;; default
13718 (if org-priority-start-cycle-with-default
13719 org-default-priority
13720 (1+ org-default-priority))))))
13721 (t (user-error "Invalid action")))
13722 (if (or (< (upcase new) org-highest-priority)
13723 (> (upcase new) org-lowest-priority))
13724 (if (and (memq action '(up down))
13725 (not have) (not (eq last-command this-command)))
13726 ;; `new' is from default priority
13727 (error
13728 "The default can not be set, see `org-default-priority' why")
13729 ;; normal cycling: `new' is beyond highest/lowest priority
13730 ;; and is wrapped around to the empty priority
13731 (setq remove t)))
13732 (setq news (format "%c" new))
13733 (if have
13734 (if remove
13735 (replace-match "" t t nil 1)
13736 (replace-match news t t nil 2))
13737 (if remove
13738 (user-error "No priority cookie found in line")
13739 (let ((case-fold-search nil))
13740 (looking-at org-todo-line-regexp))
13741 (if (match-end 2)
13742 (progn
13743 (goto-char (match-end 2))
13744 (insert " [#" news "]"))
13745 (goto-char (match-beginning 3))
13746 (insert "[#" news "] "))))
13747 (org-preserve-lc (org-set-tags nil 'align)))
13748 (if remove
13749 (message "Priority removed")
13750 (message "Priority of current item set to %s" news)))))
13752 (defun org-show-priority ()
13753 "Show the priority of the current item.
13754 This priority is composed of the main priority given with the [#A] cookies,
13755 and by additional input from the age of a schedules or deadline entry."
13756 (interactive)
13757 (let ((pri (if (eq major-mode 'org-agenda-mode)
13758 (org-get-at-bol 'priority)
13759 (save-excursion
13760 (save-match-data
13761 (beginning-of-line)
13762 (and (looking-at org-heading-regexp)
13763 (org-get-priority (match-string 0))))))))
13764 (message "Priority is %d" (if pri pri -1000))))
13766 (defun org-get-priority (s)
13767 "Find priority cookie and return priority."
13768 (save-match-data
13769 (if (functionp org-get-priority-function)
13770 (funcall org-get-priority-function)
13771 (if (not (string-match org-priority-regexp s))
13772 (* 1000 (- org-lowest-priority org-default-priority))
13773 (* 1000 (- org-lowest-priority
13774 (string-to-char (match-string 2 s))))))))
13776 ;;;; Tags
13778 (defvar org-agenda-archives-mode)
13779 (defvar org-map-continue-from nil
13780 "Position from where mapping should continue.
13781 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13783 (defvar org-scanner-tags nil
13784 "The current tag list while the tags scanner is running.")
13785 (defvar org-trust-scanner-tags nil
13786 "Should `org-get-tags-at' use the tags for the scanner.
13787 This is for internal dynamical scoping only.
13788 When this is non-nil, the function `org-get-tags-at' will return the value
13789 of `org-scanner-tags' instead of building the list by itself. This
13790 can lead to large speed-ups when the tags scanner is used in a file with
13791 many entries, and when the list of tags is retrieved, for example to
13792 obtain a list of properties. Building the tags list for each entry in such
13793 a file becomes an N^2 operation - but with this variable set, it scales
13794 as N.")
13796 (defun org-scan-tags (action matcher todo-only &optional start-level)
13797 "Sca headline tags with inheritance and produce output ACTION.
13799 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13800 or `agenda' to produce an entry list for an agenda view. It can also be
13801 a Lisp form or a function that should be called at each matched headline, in
13802 this case the return value is a list of all return values from these calls.
13804 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13805 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13806 only lines with a not-done TODO keyword are included in the output.
13807 This should be the same variable that was scoped into
13808 and set by `org-make-tags-matcher' when it constructed MATCHER.
13810 START-LEVEL can be a string with asterisks, reducing the scope to
13811 headlines matching this string."
13812 (require 'org-agenda)
13813 (let* ((re (concat "^"
13814 (if start-level
13815 ;; Get the correct level to match
13816 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13817 org-outline-regexp)
13818 " *\\(\\<\\("
13819 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13820 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13821 (props (list 'face 'default
13822 'done-face 'org-agenda-done
13823 'undone-face 'default
13824 'mouse-face 'highlight
13825 'org-not-done-regexp org-not-done-regexp
13826 'org-todo-regexp org-todo-regexp
13827 'org-complex-heading-regexp org-complex-heading-regexp
13828 'help-echo
13829 (format "mouse-2 or RET jump to org file %s"
13830 (abbreviate-file-name
13831 (or (buffer-file-name (buffer-base-buffer))
13832 (buffer-name (buffer-base-buffer)))))))
13833 (org-map-continue-from nil)
13834 lspos tags tags-list
13835 (tags-alist (list (cons 0 org-file-tags)))
13836 (llast 0) rtn rtn1 level category i txt
13837 todo marker entry priority)
13838 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13839 (setq action (list 'lambda nil action)))
13840 (save-excursion
13841 (goto-char (point-min))
13842 (when (eq action 'sparse-tree)
13843 (org-overview)
13844 (org-remove-occur-highlights))
13845 (while (let (case-fold-search)
13846 (re-search-forward re nil t))
13847 (setq org-map-continue-from nil)
13848 (catch :skip
13849 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13850 tags (if (match-end 4) (org-match-string-no-properties 4)))
13851 (goto-char (setq lspos (match-beginning 0)))
13852 (setq level (org-reduced-level (org-outline-level))
13853 category (org-get-category))
13854 (setq i llast llast level)
13855 ;; remove tag lists from same and sublevels
13856 (while (>= i level)
13857 (when (setq entry (assoc i tags-alist))
13858 (setq tags-alist (delete entry tags-alist)))
13859 (setq i (1- i)))
13860 ;; add the next tags
13861 (when tags
13862 (setq tags (org-split-string tags ":")
13863 tags-alist
13864 (cons (cons level tags) tags-alist)))
13865 ;; compile tags for current headline
13866 (setq tags-list
13867 (if org-use-tag-inheritance
13868 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13869 tags)
13870 org-scanner-tags tags-list)
13871 (when org-use-tag-inheritance
13872 (setcdr (car tags-alist)
13873 (mapcar (lambda (x)
13874 (setq x (copy-sequence x))
13875 (org-add-prop-inherited x))
13876 (cdar tags-alist))))
13877 (when (and tags org-use-tag-inheritance
13878 (or (not (eq t org-use-tag-inheritance))
13879 org-tags-exclude-from-inheritance))
13880 ;; selective inheritance, remove uninherited ones
13881 (setcdr (car tags-alist)
13882 (org-remove-uninherited-tags (cdar tags-alist))))
13883 (when (and
13885 ;; eval matcher only when the todo condition is OK
13886 (and (or (not todo-only) (member todo org-not-done-keywords))
13887 (let ((case-fold-search t) (org-trust-scanner-tags t))
13888 (eval matcher)))
13890 ;; Call the skipper, but return t if it does not skip,
13891 ;; so that the `and' form continues evaluating
13892 (progn
13893 (unless (eq action 'sparse-tree) (org-agenda-skip))
13896 ;; Check if timestamps are deselecting this entry
13897 (or (not todo-only)
13898 (and (member todo org-not-done-keywords)
13899 (or (not org-agenda-tags-todo-honor-ignore-options)
13900 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13902 ;; select this headline
13903 (cond
13904 ((eq action 'sparse-tree)
13905 (and org-highlight-sparse-tree-matches
13906 (org-get-heading) (match-end 0)
13907 (org-highlight-new-match
13908 (match-beginning 1) (match-end 1)))
13909 (org-show-context 'tags-tree))
13910 ((eq action 'agenda)
13911 (setq txt (org-agenda-format-item
13913 (concat
13914 (if (eq org-tags-match-list-sublevels 'indented)
13915 (make-string (1- level) ?.) "")
13916 (org-get-heading))
13917 level category
13918 tags-list)
13919 priority (org-get-priority txt))
13920 (goto-char lspos)
13921 (setq marker (org-agenda-new-marker))
13922 (org-add-props txt props
13923 'org-marker marker 'org-hd-marker marker 'org-category category
13924 'todo-state todo
13925 'priority priority 'type "tagsmatch")
13926 (push txt rtn))
13927 ((functionp action)
13928 (setq org-map-continue-from nil)
13929 (save-excursion
13930 (setq rtn1 (funcall action))
13931 (push rtn1 rtn)))
13932 (t (user-error "Invalid action")))
13934 ;; if we are to skip sublevels, jump to end of subtree
13935 (unless org-tags-match-list-sublevels
13936 (org-end-of-subtree t)
13937 (backward-char 1))))
13938 ;; Get the correct position from where to continue
13939 (if org-map-continue-from
13940 (goto-char org-map-continue-from)
13941 (and (= (point) lspos) (end-of-line 1)))))
13942 (when (and (eq action 'sparse-tree)
13943 (not org-sparse-tree-open-archived-trees))
13944 (org-hide-archived-subtrees (point-min) (point-max)))
13945 (nreverse rtn)))
13947 (defun org-remove-uninherited-tags (tags)
13948 "Remove all tags that are not inherited from the list TAGS."
13949 (cond
13950 ((eq org-use-tag-inheritance t)
13951 (if org-tags-exclude-from-inheritance
13952 (org-delete-all org-tags-exclude-from-inheritance tags)
13953 tags))
13954 ((not org-use-tag-inheritance) nil)
13955 ((stringp org-use-tag-inheritance)
13956 (delq nil (mapcar
13957 (lambda (x)
13958 (if (and (string-match org-use-tag-inheritance x)
13959 (not (member x org-tags-exclude-from-inheritance)))
13960 x nil))
13961 tags)))
13962 ((listp org-use-tag-inheritance)
13963 (delq nil (mapcar
13964 (lambda (x)
13965 (if (member x org-use-tag-inheritance) x nil))
13966 tags)))))
13968 (defun org-match-sparse-tree (&optional todo-only match)
13969 "Create a sparse tree according to tags string MATCH.
13970 MATCH can contain positive and negative selection of tags, like
13971 \"+WORK+URGENT-WITHBOSS\".
13972 If optional argument TODO-ONLY is non-nil, only select lines that are
13973 also TODO lines."
13974 (interactive "P")
13975 (org-agenda-prepare-buffers (list (current-buffer)))
13976 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13978 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13980 (defvar org-cached-props nil)
13981 (defun org-cached-entry-get (pom property)
13982 (if (or (eq t org-use-property-inheritance)
13983 (and (stringp org-use-property-inheritance)
13984 (string-match org-use-property-inheritance property))
13985 (and (listp org-use-property-inheritance)
13986 (member property org-use-property-inheritance)))
13987 ;; Caching is not possible, check it directly
13988 (org-entry-get pom property 'inherit)
13989 ;; Get all properties, so that we can do complicated checks easily
13990 (cdr (assoc property (or org-cached-props
13991 (setq org-cached-props
13992 (org-entry-properties pom)))))))
13994 (defun org-global-tags-completion-table (&optional files)
13995 "Return the list of all tags in all agenda buffer/files.
13996 Optional FILES argument is a list of files which can be used
13997 instead of the agenda files."
13998 (save-excursion
13999 (org-uniquify
14000 (delq nil
14001 (apply 'append
14002 (mapcar
14003 (lambda (file)
14004 (set-buffer (find-file-noselect file))
14005 (append (org-get-buffer-tags)
14006 (mapcar (lambda (x) (if (stringp (car-safe x))
14007 (list (car-safe x)) nil))
14008 org-tag-alist)))
14009 (if (and files (car files))
14010 files
14011 (org-agenda-files))))))))
14013 (defun org-make-tags-matcher (match)
14014 "Create the TAGS/TODO matcher form for the selection string MATCH.
14016 The variable `todo-only' is scoped dynamically into this function.
14017 It will be set to t if the matcher restricts matching to TODO entries,
14018 otherwise will not be touched.
14020 Returns a cons of the selection string MATCH and the constructed
14021 lisp form implementing the matcher. The matcher is to be evaluated
14022 at an Org entry, with point on the headline, and returns t if the
14023 entry matches the selection string MATCH. The returned lisp form
14024 references two variables with information about the entry, which
14025 must be bound around the form's evaluation: todo, the TODO keyword
14026 at the entry (or nil of none); and tags-list, the list of all tags
14027 at the entry including inherited ones. Additionally, the category
14028 of the entry (if any) must be specified as the text property
14029 'org-category on the headline.
14031 See also `org-scan-tags'.
14033 (declare (special todo-only))
14034 (unless (boundp 'todo-only)
14035 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14036 (unless match
14037 ;; Get a new match request, with completion against the global
14038 ;; tags table and the local tags in current buffer
14039 (let ((org-last-tags-completion-table
14040 (org-uniquify
14041 (delq nil (append (org-get-buffer-tags)
14042 (org-global-tags-completion-table))))))
14043 (setq match (org-completing-read-no-i
14044 "Match: " 'org-tags-completion-function nil nil nil
14045 'org-tags-history))))
14047 ;; Parse the string and create a lisp form
14048 (let ((match0 match)
14049 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14050 minus tag mm
14051 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14052 orterms term orlist re-p str-p level-p level-op time-p
14053 prop-p pn pv po gv rest (start 0) (ss 0))
14054 ;; Expand group tags
14055 (setq match (org-tags-expand match))
14057 ;; Check if there is a TODO part of this match, which would be the
14058 ;; part after a "/". TO make sure that this slash is not part of
14059 ;; a property value to be matched against, we also check that there
14060 ;; is no " after that slash.
14061 ;; First, find the last slash
14062 (while (string-match "/+" match ss)
14063 (setq start (match-beginning 0) ss (match-end 0)))
14064 (if (and (string-match "/+" match start)
14065 (not (save-match-data (string-match "\"" match start))))
14066 ;; match contains also a todo-matching request
14067 (progn
14068 (setq tagsmatch (substring match 0 (match-beginning 0))
14069 todomatch (substring match (match-end 0)))
14070 (if (string-match "^!" todomatch)
14071 (setq todo-only t todomatch (substring todomatch 1)))
14072 (if (string-match "^\\s-*$" todomatch)
14073 (setq todomatch nil)))
14074 ;; only matching tags
14075 (setq tagsmatch match todomatch nil))
14077 ;; Make the tags matcher
14078 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14079 (setq tagsmatcher t)
14080 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14081 (while (setq term (pop orterms))
14082 (while (and (equal (substring term -1) "\\") orterms)
14083 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14084 (while (string-match re term)
14085 (setq rest (substring term (match-end 0))
14086 minus (and (match-end 1)
14087 (equal (match-string 1 term) "-"))
14088 tag (save-match-data (replace-regexp-in-string
14089 "\\\\-" "-"
14090 (match-string 2 term)))
14091 re-p (equal (string-to-char tag) ?{)
14092 level-p (match-end 4)
14093 prop-p (match-end 5)
14094 mm (cond
14095 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14096 (level-p
14097 (setq level-op (org-op-to-function (match-string 3 term)))
14098 `(,level-op level ,(string-to-number
14099 (match-string 4 term))))
14100 (prop-p
14101 (setq pn (match-string 5 term)
14102 po (match-string 6 term)
14103 pv (match-string 7 term)
14104 re-p (equal (string-to-char pv) ?{)
14105 str-p (equal (string-to-char pv) ?\")
14106 time-p (save-match-data
14107 (string-match "^\"[[<].*[]>]\"$" pv))
14108 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14109 (if time-p (setq pv (org-matcher-time pv)))
14110 (setq po (org-op-to-function po (if time-p 'time str-p)))
14111 (cond
14112 ((equal pn "CATEGORY")
14113 (setq gv '(get-text-property (point) 'org-category)))
14114 ((equal pn "TODO")
14115 (setq gv 'todo))
14117 (setq gv `(org-cached-entry-get nil ,pn))))
14118 (if re-p
14119 (if (eq po 'org<>)
14120 `(not (string-match ,pv (or ,gv "")))
14121 `(string-match ,pv (or ,gv "")))
14122 (if str-p
14123 `(,po (or ,gv "") ,pv)
14124 `(,po (string-to-number (or ,gv ""))
14125 ,(string-to-number pv) ))))
14126 (t `(member ,tag tags-list)))
14127 mm (if minus (list 'not mm) mm)
14128 term rest)
14129 (push mm tagsmatcher))
14130 (push (if (> (length tagsmatcher) 1)
14131 (cons 'and tagsmatcher)
14132 (car tagsmatcher))
14133 orlist)
14134 (setq tagsmatcher nil))
14135 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14136 (setq tagsmatcher
14137 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14138 ;; Make the todo matcher
14139 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14140 (setq todomatcher t)
14141 (setq orterms (org-split-string todomatch "|") orlist nil)
14142 (while (setq term (pop orterms))
14143 (while (string-match re term)
14144 (setq minus (and (match-end 1)
14145 (equal (match-string 1 term) "-"))
14146 kwd (match-string 2 term)
14147 re-p (equal (string-to-char kwd) ?{)
14148 term (substring term (match-end 0))
14149 mm (if re-p
14150 `(string-match ,(substring kwd 1 -1) todo)
14151 (list 'equal 'todo kwd))
14152 mm (if minus (list 'not mm) mm))
14153 (push mm todomatcher))
14154 (push (if (> (length todomatcher) 1)
14155 (cons 'and todomatcher)
14156 (car todomatcher))
14157 orlist)
14158 (setq todomatcher nil))
14159 (setq todomatcher (if (> (length orlist) 1)
14160 (cons 'or orlist) (car orlist))))
14162 ;; Return the string and lisp forms of the matcher
14163 (setq matcher (if todomatcher
14164 (list 'and tagsmatcher todomatcher)
14165 tagsmatcher))
14166 (when todo-only
14167 (setq matcher (list 'and '(member todo org-not-done-keywords)
14168 matcher)))
14169 (cons match0 matcher)))
14171 (defun org-tags-expand (match &optional single-as-list downcased)
14172 "Expand group tags in MATCH.
14174 This replaces every group tag in MATCH with a regexp tag search.
14175 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14176 will be replaced like this:
14178 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14179 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14180 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14182 Replacing by a regexp preserves the structure of the match.
14183 E.g., this expansion
14185 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14187 will match anything tagged with \"Lab\" and \"Home\", or tagged
14188 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14190 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14191 assumed to be a single group tag, and the function will return
14192 the list of tags in this group.
14194 When DOWNCASE is non-nil, expand downcased TAGS."
14195 (if org-group-tags
14196 (let* ((case-fold-search t)
14197 (stable org-mode-syntax-table)
14198 (tal (or org-tag-groups-alist-for-agenda
14199 org-tag-groups-alist))
14200 (tal (if downcased
14201 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14202 (tml (mapcar 'car tal))
14203 (rtnmatch match) rpl)
14204 ;; @ and _ are allowed as word-components in tags
14205 (modify-syntax-entry ?@ "w" stable)
14206 (modify-syntax-entry ?_ "w" stable)
14207 (while (and tml
14208 (with-syntax-table stable
14209 (string-match
14210 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14211 (regexp-opt tml) "\\>\\)") rtnmatch)))
14212 (let* ((dir (match-string 1 rtnmatch))
14213 (tag (match-string 2 rtnmatch))
14214 (tag (if downcased (downcase tag) tag)))
14215 (setq tml (delete tag tml))
14216 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14217 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14218 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14219 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14220 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14221 (if single-as-list
14222 (or (reverse rpl) (list rtnmatch))
14223 rtnmatch))
14224 (if single-as-list (list (if downcased (downcase match) match))
14225 match)))
14227 (defun org-op-to-function (op &optional stringp)
14228 "Turn an operator into the appropriate function."
14229 (setq op
14230 (cond
14231 ((equal op "<" ) '(< string< org-time<))
14232 ((equal op ">" ) '(> org-string> org-time>))
14233 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14234 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14235 ((member op '("=" "==")) '(= string= org-time=))
14236 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14237 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14239 (defun org<> (a b) (not (= a b)))
14240 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14241 (defun org-string>= (a b) (not (string< a b)))
14242 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14243 (defun org-string<> (a b) (not (string= a b)))
14244 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14245 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14246 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= 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) (org<> a b)))
14250 (defun org-2ft (s)
14251 "Convert S to a floating point time.
14252 If S is already a number, just return it. If it is a string, parse
14253 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14254 (cond
14255 ((numberp s) s)
14256 ((stringp s)
14257 (condition-case nil
14258 (float-time (apply 'encode-time (org-parse-time-string s)))
14259 (error 0.)))
14260 (t 0.)))
14262 (defun org-time-today ()
14263 "Time in seconds today at 0:00.
14264 Returns the float number of seconds since the beginning of the
14265 epoch to the beginning of today (00:00)."
14266 (float-time (apply 'encode-time
14267 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14269 (defun org-matcher-time (s)
14270 "Interpret a time comparison value."
14271 (save-match-data
14272 (cond
14273 ((string= s "<now>") (float-time))
14274 ((string= s "<today>") (org-time-today))
14275 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14276 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14277 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14278 (+ (org-time-today)
14279 (* (string-to-number (match-string 1 s))
14280 (cdr (assoc (match-string 2 s)
14281 '(("d" . 86400.0) ("w" . 604800.0)
14282 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14283 (t (org-2ft s)))))
14285 (defun org-match-any-p (re list)
14286 "Does re match any element of list?"
14287 (setq list (mapcar (lambda (x) (string-match re x)) list))
14288 (delq nil list))
14290 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14291 (defvar org-tags-overlay (make-overlay 1 1))
14292 (org-detach-overlay org-tags-overlay)
14294 (defun org-get-local-tags-at (&optional pos)
14295 "Get a list of tags defined in the current headline."
14296 (org-get-tags-at pos 'local))
14298 (defun org-get-local-tags ()
14299 "Get a list of tags defined in the current headline."
14300 (org-get-tags-at nil 'local))
14302 (defun org-get-tags-at (&optional pos local)
14303 "Get a list of all headline tags applicable at POS.
14304 POS defaults to point. If tags are inherited, the list contains
14305 the targets in the same sequence as the headlines appear, i.e.
14306 the tags of the current headline come last.
14307 When LOCAL is non-nil, only return tags from the current headline,
14308 ignore inherited ones."
14309 (interactive)
14310 (if (and org-trust-scanner-tags
14311 (or (not pos) (equal pos (point)))
14312 (not local))
14313 org-scanner-tags
14314 (let (tags ltags lastpos parent)
14315 (save-excursion
14316 (save-restriction
14317 (widen)
14318 (goto-char (or pos (point)))
14319 (save-match-data
14320 (catch 'done
14321 (condition-case nil
14322 (progn
14323 (org-back-to-heading t)
14324 (while (not (equal lastpos (point)))
14325 (setq lastpos (point))
14326 (when (looking-at
14327 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14328 (setq ltags (org-split-string
14329 (org-match-string-no-properties 1) ":"))
14330 (when parent
14331 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14332 (setq tags (append
14333 (if parent
14334 (org-remove-uninherited-tags ltags)
14335 ltags)
14336 tags)))
14337 (or org-use-tag-inheritance (throw 'done t))
14338 (if local (throw 'done t))
14339 (or (org-up-heading-safe) (error nil))
14340 (setq parent t)))
14341 (error nil)))))
14342 (if local
14343 tags
14344 (reverse (delete-dups
14345 (reverse (append
14346 (org-remove-uninherited-tags
14347 org-file-tags) tags)))))))))
14349 (defun org-add-prop-inherited (s)
14350 (add-text-properties 0 (length s) '(inherited t) s)
14353 (defun org-toggle-tag (tag &optional onoff)
14354 "Toggle the tag TAG for the current line.
14355 If ONOFF is `on' or `off', don't toggle but set to this state."
14356 (let (res current)
14357 (save-excursion
14358 (org-back-to-heading t)
14359 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14360 (point-at-eol) t)
14361 (progn
14362 (setq current (match-string 1))
14363 (replace-match ""))
14364 (setq current ""))
14365 (setq current (nreverse (org-split-string current ":")))
14366 (cond
14367 ((eq onoff 'on)
14368 (setq res t)
14369 (or (member tag current) (push tag current)))
14370 ((eq onoff 'off)
14371 (or (not (member tag current)) (setq current (delete tag current))))
14372 (t (if (member tag current)
14373 (setq current (delete tag current))
14374 (setq res t)
14375 (push tag current))))
14376 (end-of-line 1)
14377 (if current
14378 (progn
14379 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14380 (org-set-tags nil t))
14381 (delete-horizontal-space))
14382 (run-hooks 'org-after-tags-change-hook))
14383 res))
14385 (defun org-align-tags-here (to-col)
14386 ;; Assumes that this is a headline
14387 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14388 (beginning-of-line 1)
14389 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14390 (< pos (match-beginning 2)))
14391 (progn
14392 (setq tags-l (- (match-end 2) (match-beginning 2)))
14393 (goto-char (match-beginning 1))
14394 (insert " ")
14395 (delete-region (point) (1+ (match-beginning 2)))
14396 (setq ncol (max (current-column)
14397 (1+ col)
14398 (if (> to-col 0)
14399 to-col
14400 (- (abs to-col) tags-l))))
14401 (setq p (point))
14402 (insert (make-string (- ncol (current-column)) ?\ ))
14403 (setq ncol (current-column))
14404 (when indent-tabs-mode (tabify p (point-at-eol)))
14405 (org-move-to-column (min ncol col) t nil t))
14406 (goto-char pos))))
14408 (defun org-set-tags-command (&optional arg just-align)
14409 "Call the set-tags command for the current entry."
14410 (interactive "P")
14411 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14412 (org-set-tags arg just-align)
14413 (save-excursion
14414 (unless (and (org-region-active-p)
14415 org-loop-over-headlines-in-active-region)
14416 (org-back-to-heading t))
14417 (org-set-tags arg just-align))))
14419 (defun org-set-tags-to (data)
14420 "Set the tags of the current entry to DATA, replacing the current tags.
14421 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14422 If DATA is nil or the empty string, any tags will be removed."
14423 (interactive "sTags: ")
14424 (setq data
14425 (cond
14426 ((eq data nil) "")
14427 ((equal data "") "")
14428 ((stringp data)
14429 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14430 ":"))
14431 ((listp data)
14432 (concat ":" (mapconcat 'identity data ":") ":"))))
14433 (when data
14434 (save-excursion
14435 (org-back-to-heading t)
14436 (when (looking-at org-complex-heading-regexp)
14437 (if (match-end 5)
14438 (progn
14439 (goto-char (match-beginning 5))
14440 (insert data)
14441 (delete-region (point) (point-at-eol))
14442 (org-set-tags nil 'align))
14443 (goto-char (point-at-eol))
14444 (insert " " data)
14445 (org-set-tags nil 'align)))
14446 (beginning-of-line 1)
14447 (if (looking-at ".*?\\([ \t]+\\)$")
14448 (delete-region (match-beginning 1) (match-end 1))))))
14450 (defun org-align-all-tags ()
14451 "Align the tags i all headings."
14452 (interactive)
14453 (save-excursion
14454 (or (ignore-errors (org-back-to-heading t))
14455 (outline-next-heading))
14456 (if (org-at-heading-p)
14457 (org-set-tags t)
14458 (message "No headings"))))
14460 (defvar org-indent-indentation-per-level)
14461 (defun org-set-tags (&optional arg just-align)
14462 "Set the tags for the current headline.
14463 With prefix ARG, realign all tags in headings in the current buffer."
14464 (interactive "P")
14465 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14466 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14467 'region-start-level 'region))
14468 org-loop-over-headlines-in-active-region)
14469 (org-map-entries
14470 ;; We don't use ARG and JUST-ALIGN here these args are not
14471 ;; useful when looping over headlines
14472 `(org-set-tags)
14473 org-loop-over-headlines-in-active-region
14474 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14475 (let* ((re org-outline-regexp-bol)
14476 (current (unless arg (org-get-tags-string)))
14477 (col (current-column))
14478 (org-setting-tags t)
14479 table current-tags inherited-tags ; computed below when needed
14480 tags p0 c0 c1 rpl di tc level)
14481 (if arg
14482 (save-excursion
14483 (goto-char (point-min))
14484 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14485 (while (re-search-forward re nil t)
14486 (org-set-tags nil t)
14487 (end-of-line 1)))
14488 (message "All tags realigned to column %d" org-tags-column))
14489 (if just-align
14490 (setq tags current)
14491 ;; Get a new set of tags from the user
14492 (save-excursion
14493 (setq table (append org-tag-persistent-alist
14494 (or org-tag-alist (org-get-buffer-tags))
14495 (and
14496 org-complete-tags-always-offer-all-agenda-tags
14497 (org-global-tags-completion-table
14498 (org-agenda-files))))
14499 org-last-tags-completion-table table
14500 current-tags (org-split-string current ":")
14501 inherited-tags (nreverse
14502 (nthcdr (length current-tags)
14503 (nreverse (org-get-tags-at))))
14504 tags
14505 (if (or (eq t org-use-fast-tag-selection)
14506 (and org-use-fast-tag-selection
14507 (delq nil (mapcar 'cdr table))))
14508 (org-fast-tag-selection
14509 current-tags inherited-tags table
14510 (if org-fast-tag-selection-include-todo
14511 org-todo-key-alist))
14512 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14513 (org-trim
14514 (org-icompleting-read "Tags: "
14515 'org-tags-completion-function
14516 nil nil current 'org-tags-history))))))
14517 (while (string-match "[-+&]+" tags)
14518 ;; No boolean logic, just a list
14519 (setq tags (replace-match ":" t t tags))))
14521 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14523 (if org-tags-sort-function
14524 (setq tags (mapconcat 'identity
14525 (sort (org-split-string
14526 tags (org-re "[^[:alnum:]_@#%]+"))
14527 org-tags-sort-function) ":")))
14529 (if (string-match "\\`[\t ]*\\'" tags)
14530 (setq tags "")
14531 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14532 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14534 ;; Insert new tags at the correct column
14535 (beginning-of-line 1)
14536 (setq level (or (and (looking-at org-outline-regexp)
14537 (- (match-end 0) (point) 1))
14539 (cond
14540 ((and (equal current "") (equal tags "")))
14541 ((re-search-forward
14542 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14543 (point-at-eol) t)
14544 (if (equal tags "")
14545 (setq rpl "")
14546 (goto-char (match-beginning 0))
14547 (setq c0 (current-column)
14548 ;; compute offset for the case of org-indent-mode active
14549 di (if org-indent-mode
14550 (* (1- org-indent-indentation-per-level) (1- level))
14552 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14553 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14554 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14555 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14556 (replace-match rpl t t)
14557 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14558 tags)
14559 (t (error "Tags alignment failed")))
14560 (org-move-to-column col nil nil t)
14561 (unless just-align
14562 (run-hooks 'org-after-tags-change-hook))))))
14564 (defun org-change-tag-in-region (beg end tag off)
14565 "Add or remove TAG for each entry in the region.
14566 This works in the agenda, and also in an org-mode buffer."
14567 (interactive
14568 (list (region-beginning) (region-end)
14569 (let ((org-last-tags-completion-table
14570 (if (derived-mode-p 'org-mode)
14571 (org-uniquify
14572 (delq nil (append (org-get-buffer-tags)
14573 (org-global-tags-completion-table))))
14574 (org-global-tags-completion-table))))
14575 (org-icompleting-read
14576 "Tag: " 'org-tags-completion-function nil nil nil
14577 'org-tags-history))
14578 (progn
14579 (message "[s]et or [r]emove? ")
14580 (equal (read-char-exclusive) ?r))))
14581 (if (fboundp 'deactivate-mark) (deactivate-mark))
14582 (let ((agendap (equal major-mode 'org-agenda-mode))
14583 l1 l2 m buf pos newhead (cnt 0))
14584 (goto-char end)
14585 (setq l2 (1- (org-current-line)))
14586 (goto-char beg)
14587 (setq l1 (org-current-line))
14588 (loop for l from l1 to l2 do
14589 (org-goto-line l)
14590 (setq m (get-text-property (point) 'org-hd-marker))
14591 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14592 (and agendap m))
14593 (setq buf (if agendap (marker-buffer m) (current-buffer))
14594 pos (if agendap m (point)))
14595 (with-current-buffer buf
14596 (save-excursion
14597 (save-restriction
14598 (goto-char pos)
14599 (setq cnt (1+ cnt))
14600 (org-toggle-tag tag (if off 'off 'on))
14601 (setq newhead (org-get-heading)))))
14602 (and agendap (org-agenda-change-all-lines newhead m))))
14603 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14605 (defun org-tags-completion-function (string predicate &optional flag)
14606 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14607 (confirm (lambda (x) (stringp (car x)))))
14608 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14609 (setq s1 (match-string 1 string)
14610 s2 (match-string 2 string))
14611 (setq s1 "" s2 string))
14612 (cond
14613 ((eq flag nil)
14614 ;; try completion
14615 (setq rtn (try-completion s2 ctable confirm))
14616 (if (stringp rtn)
14617 (setq rtn
14618 (concat s1 s2 (substring rtn (length s2))
14619 (if (and org-add-colon-after-tag-completion
14620 (assoc rtn ctable))
14621 ":" ""))))
14622 rtn)
14623 ((eq flag t)
14624 ;; all-completions
14625 (all-completions s2 ctable confirm))
14626 ((eq flag 'lambda)
14627 ;; exact match?
14628 (assoc s2 ctable)))))
14630 (defun org-fast-tag-insert (kwd tags face &optional end)
14631 "Insert KDW, and the TAGS, the latter with face FACE.
14632 Also insert END."
14633 (insert (format "%-12s" (concat kwd ":"))
14634 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14635 (or end "")))
14637 (defun org-fast-tag-show-exit (flag)
14638 (save-excursion
14639 (org-goto-line 3)
14640 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14641 (replace-match ""))
14642 (when flag
14643 (end-of-line 1)
14644 (org-move-to-column (- (window-width) 19) t)
14645 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14647 (defun org-set-current-tags-overlay (current prefix)
14648 "Add an overlay to CURRENT tag with PREFIX."
14649 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14650 (if (featurep 'xemacs)
14651 (org-overlay-display org-tags-overlay (concat prefix s)
14652 'secondary-selection)
14653 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14654 (org-overlay-display org-tags-overlay (concat prefix s)))))
14656 (defvar org-last-tag-selection-key nil)
14657 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14658 "Fast tag selection with single keys.
14659 CURRENT is the current list of tags in the headline, INHERITED is the
14660 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14661 possibly with grouping information. TODO-TABLE is a similar table with
14662 TODO keywords, should these have keys assigned to them.
14663 If the keys are nil, a-z are automatically assigned.
14664 Returns the new tags string, or nil to not change the current settings."
14665 (let* ((fulltable (append table todo-table))
14666 (maxlen (apply 'max (mapcar
14667 (lambda (x)
14668 (if (stringp (car x)) (string-width (car x)) 0))
14669 fulltable)))
14670 (buf (current-buffer))
14671 (expert (eq org-fast-tag-selection-single-key 'expert))
14672 (buffer-tags nil)
14673 (fwidth (+ maxlen 3 1 3))
14674 (ncol (/ (- (window-width) 4) fwidth))
14675 (i-face 'org-done)
14676 (c-face 'org-todo)
14677 tg cnt e c char c1 c2 ntable tbl rtn
14678 ov-start ov-end ov-prefix
14679 (exit-after-next org-fast-tag-selection-single-key)
14680 (done-keywords org-done-keywords)
14681 groups ingroup)
14682 (save-excursion
14683 (beginning-of-line 1)
14684 (if (looking-at
14685 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14686 (setq ov-start (match-beginning 1)
14687 ov-end (match-end 1)
14688 ov-prefix "")
14689 (setq ov-start (1- (point-at-eol))
14690 ov-end (1+ ov-start))
14691 (skip-chars-forward "^\n\r")
14692 (setq ov-prefix
14693 (concat
14694 (buffer-substring (1- (point)) (point))
14695 (if (> (current-column) org-tags-column)
14697 (make-string (- org-tags-column (current-column)) ?\ ))))))
14698 (move-overlay org-tags-overlay ov-start ov-end)
14699 (save-window-excursion
14700 (if expert
14701 (set-buffer (get-buffer-create " *Org tags*"))
14702 (delete-other-windows)
14703 (split-window-vertically)
14704 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14705 (erase-buffer)
14706 (org-set-local 'org-done-keywords done-keywords)
14707 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14708 (org-fast-tag-insert "Current" current c-face "\n\n")
14709 (org-fast-tag-show-exit exit-after-next)
14710 (org-set-current-tags-overlay current ov-prefix)
14711 (setq tbl fulltable char ?a cnt 0)
14712 (while (setq e (pop tbl))
14713 (cond
14714 ((equal (car e) :startgroup)
14715 (push '() groups) (setq ingroup t)
14716 (when (not (= cnt 0))
14717 (setq cnt 0)
14718 (insert "\n"))
14719 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14720 ((equal (car e) :endgroup)
14721 (setq ingroup nil cnt 0)
14722 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14723 ((equal e '(:newline))
14724 (when (not (= cnt 0))
14725 (setq cnt 0)
14726 (insert "\n")
14727 (setq e (car tbl))
14728 (while (equal (car tbl) '(:newline))
14729 (insert "\n")
14730 (setq tbl (cdr tbl)))))
14731 ((equal e '(:grouptags)) nil)
14733 (setq tg (copy-sequence (car e)) c2 nil)
14734 (if (cdr e)
14735 (setq c (cdr e))
14736 ;; automatically assign a character.
14737 (setq c1 (string-to-char
14738 (downcase (substring
14739 tg (if (= (string-to-char tg) ?@) 1 0)))))
14740 (if (or (rassoc c1 ntable) (rassoc c1 table))
14741 (while (or (rassoc char ntable) (rassoc char table))
14742 (setq char (1+ char)))
14743 (setq c2 c1))
14744 (setq c (or c2 char)))
14745 (if ingroup (push tg (car groups)))
14746 (setq tg (org-add-props tg nil 'face
14747 (cond
14748 ((not (assoc tg table))
14749 (org-get-todo-face tg))
14750 ((member tg current) c-face)
14751 ((member tg inherited) i-face))))
14752 (if (equal (caar tbl) :grouptags)
14753 (org-add-props tg nil 'face 'org-tag-group))
14754 (if (and (= cnt 0) (not ingroup)) (insert " "))
14755 (insert "[" c "] " tg (make-string
14756 (- fwidth 4 (length tg)) ?\ ))
14757 (push (cons tg c) ntable)
14758 (when (= (setq cnt (1+ cnt)) ncol)
14759 (insert "\n")
14760 (if ingroup (insert " "))
14761 (setq cnt 0)))))
14762 (setq ntable (nreverse ntable))
14763 (insert "\n")
14764 (goto-char (point-min))
14765 (if (not expert) (org-fit-window-to-buffer))
14766 (setq rtn
14767 (catch 'exit
14768 (while t
14769 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14770 (if (not groups) "no " "")
14771 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14772 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14773 (setq org-last-tag-selection-key c)
14774 (cond
14775 ((= c ?\r) (throw 'exit t))
14776 ((= c ?!)
14777 (setq groups (not groups))
14778 (goto-char (point-min))
14779 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14780 ((= c ?\C-c)
14781 (if (not expert)
14782 (org-fast-tag-show-exit
14783 (setq exit-after-next (not exit-after-next)))
14784 (setq expert nil)
14785 (delete-other-windows)
14786 (set-window-buffer (split-window-vertically) " *Org tags*")
14787 (org-switch-to-buffer-other-window " *Org tags*")
14788 (org-fit-window-to-buffer)))
14789 ((or (= c ?\C-g)
14790 (and (= c ?q) (not (rassoc c ntable))))
14791 (org-detach-overlay org-tags-overlay)
14792 (setq quit-flag t))
14793 ((= c ?\ )
14794 (setq current nil)
14795 (if exit-after-next (setq exit-after-next 'now)))
14796 ((= c ?\t)
14797 (condition-case nil
14798 (setq tg (org-icompleting-read
14799 "Tag: "
14800 (or buffer-tags
14801 (with-current-buffer buf
14802 (org-get-buffer-tags)))))
14803 (quit (setq tg "")))
14804 (when (string-match "\\S-" tg)
14805 (add-to-list 'buffer-tags (list tg))
14806 (if (member tg current)
14807 (setq current (delete tg current))
14808 (push tg current)))
14809 (if exit-after-next (setq exit-after-next 'now)))
14810 ((setq e (rassoc c todo-table) tg (car e))
14811 (with-current-buffer buf
14812 (save-excursion (org-todo tg)))
14813 (if exit-after-next (setq exit-after-next 'now)))
14814 ((setq e (rassoc c ntable) tg (car e))
14815 (if (member tg current)
14816 (setq current (delete tg current))
14817 (loop for g in groups do
14818 (if (member tg g)
14819 (mapc (lambda (x)
14820 (setq current (delete x current)))
14821 g)))
14822 (push tg current))
14823 (if exit-after-next (setq exit-after-next 'now))))
14825 ;; Create a sorted list
14826 (setq current
14827 (sort current
14828 (lambda (a b)
14829 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14830 (if (eq exit-after-next 'now) (throw 'exit t))
14831 (goto-char (point-min))
14832 (beginning-of-line 2)
14833 (delete-region (point) (point-at-eol))
14834 (org-fast-tag-insert "Current" current c-face)
14835 (org-set-current-tags-overlay current ov-prefix)
14836 (while (re-search-forward
14837 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14838 (setq tg (match-string 1))
14839 (add-text-properties
14840 (match-beginning 1) (match-end 1)
14841 (list 'face
14842 (cond
14843 ((member tg current) c-face)
14844 ((member tg inherited) i-face)
14845 (t (get-text-property (match-beginning 1) 'face))))))
14846 (goto-char (point-min)))))
14847 (org-detach-overlay org-tags-overlay)
14848 (if rtn
14849 (mapconcat 'identity current ":")
14850 nil))))
14852 (defun org-get-tags-string ()
14853 "Get the TAGS string in the current headline."
14854 (unless (org-at-heading-p t)
14855 (user-error "Not on a heading"))
14856 (save-excursion
14857 (beginning-of-line 1)
14858 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14859 (org-match-string-no-properties 1)
14860 "")))
14862 (defun org-get-tags ()
14863 "Get the list of tags specified in the current headline."
14864 (org-split-string (org-get-tags-string) ":"))
14866 (defun org-get-buffer-tags ()
14867 "Get a table of all tags used in the buffer, for completion."
14868 (let (tags)
14869 (save-excursion
14870 (goto-char (point-min))
14871 (while (re-search-forward
14872 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14873 (when (equal (char-after (point-at-bol 0)) ?*)
14874 (mapc (lambda (x) (add-to-list 'tags x))
14875 (org-split-string (org-match-string-no-properties 1) ":")))))
14876 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14877 (mapcar 'list tags)))
14879 ;;;; The mapping API
14881 (defun org-map-entries (func &optional match scope &rest skip)
14882 "Call FUNC at each headline selected by MATCH in SCOPE.
14884 FUNC is a function or a lisp form. The function will be called without
14885 arguments, with the cursor positioned at the beginning of the headline.
14886 The return values of all calls to the function will be collected and
14887 returned as a list.
14889 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14890 does not need to preserve point. After evaluation, the cursor will be
14891 moved to the end of the line (presumably of the headline of the
14892 processed entry) and search continues from there. Under some
14893 circumstances, this may not produce the wanted results. For example,
14894 if you have removed (e.g. archived) the current (sub)tree it could
14895 mean that the next entry will be skipped entirely. In such cases, you
14896 can specify the position from where search should continue by making
14897 FUNC set the variable `org-map-continue-from' to the desired buffer
14898 position.
14900 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14901 Only headlines that are matched by this query will be considered during
14902 the iteration. When MATCH is nil or t, all headlines will be
14903 visited by the iteration.
14905 SCOPE determines the scope of this command. It can be any of:
14907 nil The current buffer, respecting the restriction if any
14908 tree The subtree started with the entry at point
14909 region The entries within the active region, if any
14910 region-start-level
14911 The entries within the active region, but only those at
14912 the same level than the first one.
14913 file The current buffer, without restriction
14914 file-with-archives
14915 The current buffer, and any archives associated with it
14916 agenda All agenda files
14917 agenda-with-archives
14918 All agenda files with any archive files associated with them
14919 \(file1 file2 ...)
14920 If this is a list, all files in the list will be scanned
14922 The remaining args are treated as settings for the skipping facilities of
14923 the scanner. The following items can be given here:
14925 archive skip trees with the archive tag
14926 comment skip trees with the COMMENT keyword
14927 function or Emacs Lisp form:
14928 will be used as value for `org-agenda-skip-function', so
14929 whenever the function returns a position, FUNC will not be
14930 called for that entry and search will continue from the
14931 position returned
14933 If your function needs to retrieve the tags including inherited tags
14934 at the *current* entry, you can use the value of the variable
14935 `org-scanner-tags' which will be much faster than getting the value
14936 with `org-get-tags-at'. If your function gets properties with
14937 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14938 to t around the call to `org-entry-properties' to get the same speedup.
14939 Note that if your function moves around to retrieve tags and properties at
14940 a *different* entry, you cannot use these techniques."
14941 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14942 (not (org-region-active-p)))
14943 (let* ((org-agenda-archives-mode nil) ; just to make sure
14944 (org-agenda-skip-archived-trees (memq 'archive skip))
14945 (org-agenda-skip-comment-trees (memq 'comment skip))
14946 (org-agenda-skip-function
14947 (car (org-delete-all '(comment archive) skip)))
14948 (org-tags-match-list-sublevels t)
14949 (start-level (eq scope 'region-start-level))
14950 matcher file res
14951 org-todo-keywords-for-agenda
14952 org-done-keywords-for-agenda
14953 org-todo-keyword-alist-for-agenda
14954 org-drawers-for-agenda
14955 org-tag-alist-for-agenda
14956 todo-only)
14958 (cond
14959 ((eq match t) (setq matcher t))
14960 ((eq match nil) (setq matcher t))
14961 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14963 (save-window-excursion
14964 (save-restriction
14965 (cond ((eq scope 'tree)
14966 (org-back-to-heading t)
14967 (org-narrow-to-subtree)
14968 (setq scope nil))
14969 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14970 (org-region-active-p))
14971 ;; If needed, set start-level to a string like "2"
14972 (when start-level
14973 (save-excursion
14974 (goto-char (region-beginning))
14975 (unless (org-at-heading-p) (outline-next-heading))
14976 (setq start-level (org-current-level))))
14977 (narrow-to-region (region-beginning)
14978 (save-excursion
14979 (goto-char (region-end))
14980 (unless (and (bolp) (org-at-heading-p))
14981 (outline-next-heading))
14982 (point)))
14983 (setq scope nil)))
14985 (if (not scope)
14986 (progn
14987 (org-agenda-prepare-buffers
14988 (list (buffer-file-name (current-buffer))))
14989 (setq res (org-scan-tags func matcher todo-only start-level)))
14990 ;; Get the right scope
14991 (cond
14992 ((and scope (listp scope) (symbolp (car scope)))
14993 (setq scope (eval scope)))
14994 ((eq scope 'agenda)
14995 (setq scope (org-agenda-files t)))
14996 ((eq scope 'agenda-with-archives)
14997 (setq scope (org-agenda-files t))
14998 (setq scope (org-add-archive-files scope)))
14999 ((eq scope 'file)
15000 (setq scope (list (buffer-file-name))))
15001 ((eq scope 'file-with-archives)
15002 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15003 (org-agenda-prepare-buffers scope)
15004 (while (setq file (pop scope))
15005 (with-current-buffer (org-find-base-buffer-visiting file)
15006 (save-excursion
15007 (save-restriction
15008 (widen)
15009 (goto-char (point-min))
15010 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15011 res)))
15013 ;;;; Properties
15015 ;;; Setting and retrieving properties
15017 (defconst org-special-properties
15018 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15019 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15020 "The special properties valid in Org-mode.
15022 These are properties that are not defined in the property drawer,
15023 but in some other way.")
15025 (defconst org-default-properties
15026 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15027 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15028 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15029 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15030 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15031 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15032 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15033 "Some properties that are used by Org-mode for various purposes.
15034 Being in this list makes sure that they are offered for completion.")
15036 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15037 "Regular expression matching the first line of a property drawer.")
15039 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15040 "Regular expression matching the last line of a property drawer.")
15042 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15043 "Regular expression matching the first line of a property drawer.")
15045 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15046 "Regular expression matching the first line of a property drawer.")
15048 (defconst org-property-drawer-re
15049 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15050 org-property-end-re "\\)\n?")
15051 "Matches an entire property drawer.")
15053 (defconst org-clock-drawer-re
15054 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15055 org-property-end-re "\\)\n?")
15056 "Matches an entire clock drawer.")
15058 (defun org-property-action ()
15059 "Do an action on properties."
15060 (interactive)
15061 (let (c)
15062 (org-at-property-p)
15063 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15064 (setq c (read-char-exclusive))
15065 (cond
15066 ((equal c ?s)
15067 (call-interactively 'org-set-property))
15068 ((equal c ?d)
15069 (call-interactively 'org-delete-property))
15070 ((equal c ?D)
15071 (call-interactively 'org-delete-property-globally))
15072 ((equal c ?c)
15073 (call-interactively 'org-compute-property-at-point))
15074 (t (user-error "No such property action %c" c)))))
15076 (defun org-inc-effort ()
15077 "Increment the value of the effort property in the current entry."
15078 (interactive)
15079 (org-set-effort nil t))
15081 (defvar org-clock-effort) ;; Defined in org-clock.el
15082 (defvar org-clock-current-task) ;; Defined in org-clock.el
15083 (defun org-set-effort (&optional value increment)
15084 "Set the effort property of the current entry.
15085 With numerical prefix arg, use the nth allowed value, 0 stands for the
15086 10th allowed value.
15088 When INCREMENT is non-nil, set the property to the next allowed value."
15089 (interactive "P")
15090 (if (equal value 0) (setq value 10))
15091 (let* ((completion-ignore-case t)
15092 (prop org-effort-property)
15093 (cur (org-entry-get nil prop))
15094 (allowed (org-property-get-allowed-values nil prop 'table))
15095 (existing (mapcar 'list (org-property-values prop)))
15096 (heading (nth 4 (org-heading-components)))
15098 (val (cond
15099 ((stringp value) value)
15100 ((and allowed (integerp value))
15101 (or (car (nth (1- value) allowed))
15102 (car (org-last allowed))))
15103 ((and allowed increment)
15104 (or (caadr (member (list cur) allowed))
15105 (user-error "Allowed effort values are not set")))
15106 (allowed
15107 (message "Select 1-9,0, [RET%s]: %s"
15108 (if cur (concat "=" cur) "")
15109 (mapconcat 'car allowed " "))
15110 (setq rpl (read-char-exclusive))
15111 (if (equal rpl ?\r)
15113 (setq rpl (- rpl ?0))
15114 (if (equal rpl 0) (setq rpl 10))
15115 (if (and (> rpl 0) (<= rpl (length allowed)))
15116 (car (nth (1- rpl) allowed))
15117 (org-completing-read "Effort: " allowed nil))))
15119 (let (org-completion-use-ido org-completion-use-iswitchb)
15120 (org-completing-read
15121 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15122 (concat "[" cur "]") "")
15123 ": ")
15124 existing nil nil "" nil cur))))))
15125 (unless (equal (org-entry-get nil prop) val)
15126 (org-entry-put nil prop val))
15127 (save-excursion
15128 (org-back-to-heading t)
15129 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15130 (when (string= heading org-clock-current-task)
15131 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15132 (org-clock-update-mode-line))
15133 (message "%s is now %s" prop val)))
15135 (defun org-at-property-p ()
15136 "Is cursor inside a property drawer?"
15137 (save-excursion
15138 (when (equal 'node-property (car (org-element-at-point)))
15139 (beginning-of-line 1)
15140 (looking-at org-property-re))))
15142 (defun org-get-property-block (&optional beg end force)
15143 "Return the (beg . end) range of the body of the property drawer.
15144 BEG and END are the beginning and end of the current subtree, or of
15145 the part before the first headline. If they are not given, they will
15146 be found. If the drawer does not exist and FORCE is non-nil, create
15147 the drawer."
15148 (catch 'exit
15149 (save-excursion
15150 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15151 (progn (org-back-to-heading t) (point))))
15152 (end (or end (and (not (outline-next-heading)) (point-max))
15153 (point))))
15154 (goto-char beg)
15155 (if (re-search-forward org-property-start-re end t)
15156 (setq beg (1+ (match-end 0)))
15157 (if force
15158 (save-excursion
15159 (org-insert-property-drawer)
15160 (setq end (progn (outline-next-heading) (point))))
15161 (throw 'exit nil))
15162 (goto-char beg)
15163 (if (re-search-forward org-property-start-re end t)
15164 (setq beg (1+ (match-end 0)))))
15165 (if (re-search-forward org-property-end-re end t)
15166 (setq end (match-beginning 0))
15167 (or force (throw 'exit nil))
15168 (goto-char beg)
15169 (setq end beg)
15170 (org-indent-line)
15171 (insert ":END:\n"))
15172 (cons beg end)))))
15174 (defun org-entry-properties (&optional pom which specific)
15175 "Get all properties of the entry at point-or-marker POM.
15176 This includes the TODO keyword, the tags, time strings for deadline,
15177 scheduled, and clocking, and any additional properties defined in the
15178 entry. The return value is an alist, keys may occur multiple times
15179 if the property key was used several times.
15180 POM may also be nil, in which case the current entry is used.
15181 If WHICH is nil or `all', get all properties. If WHICH is
15182 `special' or `standard', only get that subclass. If WHICH
15183 is a string only get exactly this property. SPECIFIC can be a string, the
15184 specific property we are interested in. Specifying it can speed
15185 things up because then unnecessary parsing is avoided."
15186 (setq which (or which 'all))
15187 (org-with-wide-buffer
15188 (org-with-point-at pom
15189 (let ((clockstr (substring org-clock-string 0 -1))
15190 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15191 (case-fold-search nil)
15192 beg end range props sum-props key key1 value string clocksum clocksumt)
15193 (when (and (derived-mode-p 'org-mode)
15194 (ignore-errors (org-back-to-heading t)))
15195 (setq beg (point))
15196 (setq sum-props (get-text-property (point) 'org-summaries))
15197 (setq clocksum (get-text-property (point) :org-clock-minutes)
15198 clocksumt (get-text-property (point) :org-clock-minutes-today))
15199 (outline-next-heading)
15200 (setq end (point))
15201 (when (memq which '(all special))
15202 ;; Get the special properties, like TODO and tags
15203 (goto-char beg)
15204 (when (and (or (not specific) (string= specific "TODO"))
15205 (looking-at org-todo-line-regexp) (match-end 2))
15206 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15207 (when (and (or (not specific) (string= specific "PRIORITY"))
15208 (looking-at org-priority-regexp))
15209 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15210 (when (or (not specific) (string= specific "FILE"))
15211 (push (cons "FILE" buffer-file-name) props))
15212 (when (and (or (not specific) (string= specific "TAGS"))
15213 (setq value (org-get-tags-string))
15214 (string-match "\\S-" value))
15215 (push (cons "TAGS" value) props))
15216 (when (and (or (not specific) (string= specific "ALLTAGS"))
15217 (setq value (org-get-tags-at)))
15218 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15219 ":"))
15220 props))
15221 (when (or (not specific) (string= specific "BLOCKED"))
15222 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15223 (when (or (not specific)
15224 (member specific
15225 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15226 "TIMESTAMP" "TIMESTAMP_IA")))
15227 (catch 'match
15228 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15229 (setq key (if (match-end 1)
15230 (substring (org-match-string-no-properties 1)
15231 0 -1))
15232 string (if (equal key clockstr)
15233 (org-trim
15234 (buffer-substring-no-properties
15235 (match-beginning 3) (goto-char
15236 (point-at-eol))))
15237 (substring (org-match-string-no-properties 3)
15238 1 -1)))
15239 ;; Get the correct property name from the key. This is
15240 ;; necessary if the user has configured time keywords.
15241 (setq key1 (concat key ":"))
15242 (cond
15243 ((not key)
15244 (setq key
15245 (if (= (char-after (match-beginning 3)) ?\[)
15246 "TIMESTAMP_IA" "TIMESTAMP")))
15247 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15248 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15249 ((equal key1 org-closed-string) (setq key "CLOSED"))
15250 ((equal key1 org-clock-string) (setq key "CLOCK")))
15251 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15252 (progn
15253 (push (cons key string) props)
15254 ;; no need to search further if match is found
15255 (throw 'match t))
15256 (when (or (equal key "CLOCK") (not (assoc key props)))
15257 (push (cons key string) props)))))))
15259 (when (memq which '(all standard))
15260 ;; Get the standard properties, like :PROP: ...
15261 (setq range (org-get-property-block beg end))
15262 (when range
15263 (goto-char (car range))
15264 (while (re-search-forward org-property-re
15265 (cdr range) t)
15266 (setq key (org-match-string-no-properties 2)
15267 value (org-trim (or (org-match-string-no-properties 3) "")))
15268 (unless (member key excluded)
15269 (push (cons key (or value "")) props)))))
15270 (if clocksum
15271 (push (cons "CLOCKSUM"
15272 (org-columns-number-to-string (/ (float clocksum) 60.)
15273 'add_times))
15274 props))
15275 (if clocksumt
15276 (push (cons "CLOCKSUM_T"
15277 (org-columns-number-to-string (/ (float clocksumt) 60.)
15278 'add_times))
15279 props))
15280 (unless (assoc "CATEGORY" props)
15281 (push (cons "CATEGORY" (org-get-category)) props))
15282 (append sum-props (nreverse props)))))))
15284 (defun org-entry-get (pom property &optional inherit literal-nil)
15285 "Get value of PROPERTY for entry or content at point-or-marker POM.
15286 If INHERIT is non-nil and the entry does not have the property,
15287 then also check higher levels of the hierarchy.
15288 If INHERIT is the symbol `selective', use inheritance only if the setting
15289 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15290 If the property is present but empty, the return value is the empty string.
15291 If the property is not present at all, nil is returned.
15293 Return the value as a string.
15295 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15296 do not interpret it as the list atom nil. This is used for inheritance
15297 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15298 (org-with-point-at pom
15299 (if (and inherit (if (eq inherit 'selective)
15300 (org-property-inherit-p property)
15302 (org-entry-get-with-inheritance property literal-nil)
15303 (if (member property org-special-properties)
15304 ;; We need a special property. Use `org-entry-properties'
15305 ;; to retrieve it, but specify the wanted property
15306 (cdr (assoc property (org-entry-properties nil 'special property)))
15307 (org-with-wide-buffer
15308 (let ((range (org-get-property-block)))
15309 (when (and range (not (eq (car range) (cdr range))))
15310 (let* ((props
15311 (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 If the value is `nil', it is converted to the empty string.
15462 If it is not a string, an error is raised."
15463 (cond ((null value) (setq value ""))
15464 ((not (stringp value))
15465 (error "Properties values should be strings.")))
15466 (org-with-point-at pom
15467 (org-back-to-heading t)
15468 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15469 range)
15470 (cond
15471 ((equal property "TODO")
15472 (when (and (string-match "\\S-" value)
15473 (not (member value org-todo-keywords-1)))
15474 (user-error "\"%s\" is not a valid TODO state" value))
15475 (if (or (not value)
15476 (not (string-match "\\S-" value)))
15477 (setq value 'none))
15478 (org-todo value)
15479 (org-set-tags nil 'align))
15480 ((equal property "PRIORITY")
15481 (org-priority (if (and value (string-match "\\S-" value))
15482 (string-to-char value) ?\ ))
15483 (org-set-tags nil 'align))
15484 ((equal property "CLOCKSUM")
15485 (if (not (re-search-forward
15486 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15487 (error "Cannot find a clock log")
15488 (goto-char (- (match-end 1) 2))
15489 (cond
15490 ((eq value 'earlier) (org-timestamp-down))
15491 ((eq value 'later) (org-timestamp-up)))
15492 (org-clock-sum-current-item)))
15493 ((equal property "SCHEDULED")
15494 (if (re-search-forward org-scheduled-time-regexp end t)
15495 (cond
15496 ((eq value 'earlier) (org-timestamp-change -1 'day))
15497 ((eq value 'later) (org-timestamp-change 1 'day))
15498 (t (call-interactively 'org-schedule)))
15499 (call-interactively 'org-schedule)))
15500 ((equal property "DEADLINE")
15501 (if (re-search-forward org-deadline-time-regexp end t)
15502 (cond
15503 ((eq value 'earlier) (org-timestamp-change -1 'day))
15504 ((eq value 'later) (org-timestamp-change 1 'day))
15505 (t (call-interactively 'org-deadline)))
15506 (call-interactively 'org-deadline)))
15507 ((member property org-special-properties)
15508 (error "The %s property can not yet be set with `org-entry-put'"
15509 property))
15510 (t ; a non-special property
15511 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15512 (setq range (org-get-property-block beg end 'force))
15513 (goto-char (car range))
15514 (if (re-search-forward
15515 (org-re-property property) (cdr range) t)
15516 (progn
15517 (delete-region (match-beginning 0) (match-end 0))
15518 (goto-char (match-beginning 0)))
15519 (goto-char (cdr range))
15520 (insert "\n")
15521 (backward-char 1)
15522 (org-indent-line))
15523 (insert ":" property ":")
15524 (and value (insert " " value))
15525 (org-indent-line)))))
15526 (run-hook-with-args 'org-property-changed-functions property value)))
15528 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15529 "Get all property keys in the current buffer.
15530 With INCLUDE-SPECIALS, also list the special properties that reflect things
15531 like tags and TODO state.
15532 With INCLUDE-DEFAULTS, also include properties that has special meaning
15533 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15534 and others.
15535 With INCLUDE-COLUMNS, also include property names given in COLUMN
15536 formats in the current buffer."
15537 (let (rtn range cfmt s p)
15538 (save-excursion
15539 (save-restriction
15540 (widen)
15541 (goto-char (point-min))
15542 (while (re-search-forward org-property-start-re nil t)
15543 (setq range (org-get-property-block))
15544 (goto-char (car range))
15545 (while (re-search-forward org-property-re
15546 (cdr range) t)
15547 (add-to-list 'rtn (org-match-string-no-properties 2)))
15548 (outline-next-heading))))
15550 (when include-specials
15551 (setq rtn (append org-special-properties rtn)))
15553 (when include-defaults
15554 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15555 (add-to-list 'rtn org-effort-property))
15557 (when include-columns
15558 (save-excursion
15559 (save-restriction
15560 (widen)
15561 (goto-char (point-min))
15562 (while (re-search-forward
15563 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15564 nil t)
15565 (setq cfmt (match-string 2) s 0)
15566 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15567 cfmt s)
15568 (setq s (match-end 0)
15569 p (match-string 1 cfmt))
15570 (unless (or (equal p "ITEM")
15571 (member p org-special-properties))
15572 (add-to-list 'rtn (match-string 1 cfmt))))))))
15574 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15576 (defun org-property-values (key)
15577 "Return a list of all values of property KEY in the current buffer."
15578 (save-excursion
15579 (save-restriction
15580 (widen)
15581 (goto-char (point-min))
15582 (let ((re (org-re-property key))
15583 values)
15584 (while (re-search-forward re nil t)
15585 (add-to-list 'values (org-trim (match-string 3))))
15586 (delete "" values)))))
15588 (defun org-insert-property-drawer ()
15589 "Insert a property drawer into the current entry."
15590 (org-back-to-heading t)
15591 (looking-at org-outline-regexp)
15592 (let ((indent (if org-adapt-indentation
15593 (- (match-end 0) (match-beginning 0))
15595 (beg (point))
15596 (re (concat "^[ \t]*" org-keyword-time-regexp))
15597 end hiddenp)
15598 (outline-next-heading)
15599 (setq end (point))
15600 (goto-char beg)
15601 (while (re-search-forward re end t))
15602 (setq hiddenp (outline-invisible-p))
15603 (end-of-line 1)
15604 (and (equal (char-after) ?\n) (forward-char 1))
15605 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15606 (if (member (match-string 1) '("CLOCK:" ":END:"))
15607 ;; just skip this line
15608 (beginning-of-line 2)
15609 ;; Drawer start, find the end
15610 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15611 (beginning-of-line 1)))
15612 (org-skip-over-state-notes)
15613 (skip-chars-backward " \t\n\r")
15614 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15615 (forward-char 1))
15616 (goto-char (point-at-eol))
15617 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15618 (beginning-of-line 0)
15619 (org-indent-to-column indent)
15620 (beginning-of-line 2)
15621 (org-indent-to-column indent)
15622 (beginning-of-line 0)
15623 (if hiddenp
15624 (save-excursion
15625 (org-back-to-heading t)
15626 (hide-entry))
15627 (org-flag-drawer t))))
15629 (defun org-insert-drawer (&optional arg drawer)
15630 "Insert a drawer at point.
15632 Optional argument DRAWER, when non-nil, is a string representing
15633 drawer's name. Otherwise, the user is prompted for a name.
15635 If a region is active, insert the drawer around that region
15636 instead.
15638 Point is left between drawer's boundaries."
15639 (interactive "P")
15640 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15641 "LOGBOOK"))
15642 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15643 ;; internally by Org. They are meant to be inserted
15644 ;; automatically.
15645 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15646 ;; Remove system drawers from list. Note: For some reason,
15647 ;; `org-completing-read' ignores the predicate while
15648 ;; `completing-read' handles it fine.
15649 (drawer (if arg "PROPERTIES"
15650 (or drawer
15651 (completing-read
15652 "Drawer: " org-drawers
15653 (lambda (d) (not (member d system-drawers))))))))
15654 (cond
15655 ;; With C-u, fall back on `org-insert-property-drawer'
15656 (arg (org-insert-property-drawer))
15657 ;; With an active region, insert a drawer at point.
15658 ((not (org-region-active-p))
15659 (progn
15660 (unless (bolp) (insert "\n"))
15661 (insert (format ":%s:\n\n:END:\n" drawer))
15662 (forward-line -2)))
15663 ;; Otherwise, insert the drawer at point
15665 (let ((rbeg (region-beginning))
15666 (rend (copy-marker (region-end))))
15667 (unwind-protect
15668 (progn
15669 (goto-char rbeg)
15670 (beginning-of-line)
15671 (when (save-excursion
15672 (re-search-forward org-outline-regexp-bol rend t))
15673 (user-error "Drawers cannot contain headlines"))
15674 ;; Position point at the beginning of the first
15675 ;; non-blank line in region. Insert drawer's opening
15676 ;; there, then indent it.
15677 (org-skip-whitespace)
15678 (beginning-of-line)
15679 (insert ":" drawer ":\n")
15680 (forward-line -1)
15681 (indent-for-tab-command)
15682 ;; Move point to the beginning of the first blank line
15683 ;; after the last non-blank line in region. Insert
15684 ;; drawer's closing, then indent it.
15685 (goto-char rend)
15686 (skip-chars-backward " \r\t\n")
15687 (insert "\n:END:")
15688 (deactivate-mark t)
15689 (indent-for-tab-command)
15690 (unless (eolp) (insert "\n")))
15691 ;; Clear marker, whatever the outcome of insertion is.
15692 (set-marker rend nil)))))))
15694 (defvar org-property-set-functions-alist nil
15695 "Property set function alist.
15696 Each entry should have the following format:
15698 (PROPERTY . READ-FUNCTION)
15700 The read function will be called with the same argument as
15701 `org-completing-read'.")
15703 (defun org-set-property-function (property)
15704 "Get the function that should be used to set PROPERTY.
15705 This is computed according to `org-property-set-functions-alist'."
15706 (or (cdr (assoc property org-property-set-functions-alist))
15707 'org-completing-read))
15709 (defun org-read-property-value (property)
15710 "Read PROPERTY value from user."
15711 (let* ((completion-ignore-case t)
15712 (allowed (org-property-get-allowed-values nil property 'table))
15713 (cur (org-entry-get nil property))
15714 (prompt (concat property " value"
15715 (if (and cur (string-match "\\S-" cur))
15716 (concat " [" cur "]") "") ": "))
15717 (set-function (org-set-property-function property))
15718 (val (if allowed
15719 (funcall set-function prompt allowed nil
15720 (not (get-text-property 0 'org-unrestricted
15721 (caar allowed))))
15722 (let (org-completion-use-ido org-completion-use-iswitchb)
15723 (funcall set-function prompt
15724 (mapcar 'list (org-property-values property))
15725 nil nil "" nil cur)))))
15726 (if (equal val "")
15728 val)))
15730 (defvar org-last-set-property nil)
15731 (defvar org-last-set-property-value nil)
15732 (defun org-read-property-name ()
15733 "Read a property name."
15734 (let* ((completion-ignore-case t)
15735 (keys (org-buffer-property-keys nil t t))
15736 (default-prop (or (save-excursion
15737 (save-match-data
15738 (beginning-of-line)
15739 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15740 (null (string= (match-string 1) "END"))
15741 (match-string 1))))
15742 org-last-set-property))
15743 (property (org-icompleting-read
15744 (concat "Property"
15745 (if default-prop (concat " [" default-prop "]") "")
15746 ": ")
15747 (mapcar 'list keys)
15748 nil nil nil nil
15749 default-prop)))
15750 (if (member property keys)
15751 property
15752 (or (cdr (assoc (downcase property)
15753 (mapcar (lambda (x) (cons (downcase x) x))
15754 keys)))
15755 property))))
15757 (defun org-set-property-and-value (use-last)
15758 "Allow to set [PROPERTY]: [value] direction from prompt.
15759 When use-default, don't even ask, just use the last
15760 \"[PROPERTY]: [value]\" string from the history."
15761 (interactive "P")
15762 (let* ((completion-ignore-case t)
15763 (pv (or (and use-last org-last-set-property-value)
15764 (org-completing-read
15765 "Enter a \"[Property]: [value]\" pair: "
15766 nil nil nil nil nil
15767 org-last-set-property-value)))
15768 prop val)
15769 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15770 (setq prop (match-string 1 pv)
15771 val (match-string 2 pv))
15772 (org-set-property prop val))))
15774 (defun org-set-property (property value)
15775 "In the current entry, set PROPERTY to VALUE.
15776 When called interactively, this will prompt for a property name, offering
15777 completion on existing and default properties. And then it will prompt
15778 for a value, offering completion either on allowed values (via an inherited
15779 xxx_ALL property) or on existing values in other instances of this property
15780 in the current file."
15781 (interactive (list nil nil))
15782 (let* ((property (or property (org-read-property-name)))
15783 (value (or value (org-read-property-value property)))
15784 (fn (cdr (assoc property org-properties-postprocess-alist))))
15785 (setq org-last-set-property property)
15786 (setq org-last-set-property-value (concat property ": " value))
15787 ;; Possibly postprocess the inserted value:
15788 (when fn (setq value (funcall fn value)))
15789 (unless (equal (org-entry-get nil property) value)
15790 (org-entry-put nil property value))))
15792 (defun org-delete-property (property &optional delete-empty-drawer)
15793 "In the current entry, delete PROPERTY.
15794 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15795 an empty drawer to delete."
15796 (interactive
15797 (let* ((completion-ignore-case t)
15798 (prop (org-icompleting-read "Property: "
15799 (org-entry-properties nil 'standard))))
15800 (list prop)))
15801 (message "Property %s %s" property
15802 (if (org-entry-delete nil property delete-empty-drawer)
15803 "deleted"
15804 "was not present in the entry")))
15806 (defun org-delete-property-globally (property)
15807 "Remove PROPERTY globally, from all entries."
15808 (interactive
15809 (let* ((completion-ignore-case t)
15810 (prop (org-icompleting-read
15811 "Globally remove property: "
15812 (mapcar 'list (org-buffer-property-keys)))))
15813 (list prop)))
15814 (save-excursion
15815 (save-restriction
15816 (widen)
15817 (goto-char (point-min))
15818 (let ((cnt 0))
15819 (while (re-search-forward
15820 (org-re-property property)
15821 nil t)
15822 (setq cnt (1+ cnt))
15823 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15824 (message "Property \"%s\" removed from %d entries" property cnt)))))
15826 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15828 (defun org-compute-property-at-point ()
15829 "Compute the property at point.
15830 This looks for an enclosing column format, extracts the operator and
15831 then applies it to the property in the column format's scope."
15832 (interactive)
15833 (unless (org-at-property-p)
15834 (user-error "Not at a property"))
15835 (let ((prop (org-match-string-no-properties 2)))
15836 (org-columns-get-format-and-top-level)
15837 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15838 (user-error "No operator defined for property %s" prop))
15839 (org-columns-compute prop)))
15841 (defvar org-property-allowed-value-functions nil
15842 "Hook for functions supplying allowed values for a specific property.
15843 The functions must take a single argument, the name of the property, and
15844 return a flat list of allowed values. If \":ETC\" is one of
15845 the values, this means that these values are intended as defaults for
15846 completion, but that other values should be allowed too.
15847 The functions must return nil if they are not responsible for this
15848 property.")
15850 (defun org-property-get-allowed-values (pom property &optional table)
15851 "Get allowed values for the property PROPERTY.
15852 When TABLE is non-nil, return an alist that can directly be used for
15853 completion."
15854 (let (vals)
15855 (cond
15856 ((equal property "TODO")
15857 (setq vals (org-with-point-at pom
15858 (append org-todo-keywords-1 '("")))))
15859 ((equal property "PRIORITY")
15860 (let ((n org-lowest-priority))
15861 (while (>= n org-highest-priority)
15862 (push (char-to-string n) vals)
15863 (setq n (1- n)))))
15864 ((member property org-special-properties))
15865 ((setq vals (run-hook-with-args-until-success
15866 'org-property-allowed-value-functions property)))
15868 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15869 (when (and vals (string-match "\\S-" vals))
15870 (setq vals (car (read-from-string (concat "(" vals ")"))))
15871 (setq vals (mapcar (lambda (x)
15872 (cond ((stringp x) x)
15873 ((numberp x) (number-to-string x))
15874 ((symbolp x) (symbol-name x))
15875 (t "???")))
15876 vals)))))
15877 (when (member ":ETC" vals)
15878 (setq vals (remove ":ETC" vals))
15879 (org-add-props (car vals) '(org-unrestricted t)))
15880 (if table (mapcar 'list vals) vals)))
15882 (defun org-property-previous-allowed-value (&optional previous)
15883 "Switch to the next allowed value for this property."
15884 (interactive)
15885 (org-property-next-allowed-value t))
15887 (defun org-property-next-allowed-value (&optional previous)
15888 "Switch to the next allowed value for this property."
15889 (interactive)
15890 (unless (org-at-property-p)
15891 (user-error "Not at a property"))
15892 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15893 (key (match-string 2))
15894 (value (match-string 3))
15895 (allowed (or (org-property-get-allowed-values (point) key)
15896 (and (member value '("[ ]" "[-]" "[X]"))
15897 '("[ ]" "[X]"))))
15898 (heading (save-match-data (nth 4 (org-heading-components))))
15899 nval)
15900 (unless allowed
15901 (user-error "Allowed values for this property have not been defined"))
15902 (if previous (setq allowed (reverse allowed)))
15903 (if (member value allowed)
15904 (setq nval (car (cdr (member value allowed)))))
15905 (setq nval (or nval (car allowed)))
15906 (if (equal nval value)
15907 (user-error "Only one allowed value for this property"))
15908 (org-at-property-p)
15909 (replace-match (concat " :" key ": " nval) t t)
15910 (org-indent-line)
15911 (beginning-of-line 1)
15912 (skip-chars-forward " \t")
15913 (when (equal prop org-effort-property)
15914 (save-excursion
15915 (org-back-to-heading t)
15916 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15917 (when (string= org-clock-current-task heading)
15918 (setq org-clock-effort nval)
15919 (org-clock-update-mode-line)))
15920 (run-hook-with-args 'org-property-changed-functions key nval)))
15922 (defun org-find-olp (path &optional this-buffer)
15923 "Return a marker pointing to the entry at outline path OLP.
15924 If anything goes wrong, throw an error.
15925 You can wrap this call to catch the error like this:
15927 (condition-case msg
15928 (org-mobile-locate-entry (match-string 4))
15929 (error (nth 1 msg)))
15931 The return value will then be either a string with the error message,
15932 or a marker if everything is OK.
15934 If THIS-BUFFER is set, the outline path does not contain a file,
15935 only headings."
15936 (let* ((file (if this-buffer buffer-file-name (pop path)))
15937 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15938 (level 1)
15939 (lmin 1)
15940 (lmax 1)
15941 limit re end found pos heading cnt flevel)
15942 (unless buffer (error "File not found :%s" file))
15943 (with-current-buffer buffer
15944 (save-excursion
15945 (save-restriction
15946 (widen)
15947 (setq limit (point-max))
15948 (goto-char (point-min))
15949 (while (setq heading (pop path))
15950 (setq re (format org-complex-heading-regexp-format
15951 (regexp-quote heading)))
15952 (setq cnt 0 pos (point))
15953 (while (re-search-forward re end t)
15954 (setq level (- (match-end 1) (match-beginning 1)))
15955 (if (and (>= level lmin) (<= level lmax))
15956 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15957 (when (= cnt 0) (error "Heading not found on level %d: %s"
15958 lmax heading))
15959 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15960 lmax heading))
15961 (goto-char found)
15962 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15963 (setq end (save-excursion (org-end-of-subtree t t))))
15964 (when (org-at-heading-p)
15965 (point-marker)))))))
15967 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15968 "Find node HEADING in BUFFER.
15969 Return a marker to the heading if it was found, or nil if not.
15970 If POS-ONLY is set, return just the position instead of a marker.
15972 The heading text must match exact, but it may have a TODO keyword,
15973 a priority cookie and tags in the standard locations."
15974 (with-current-buffer (or buffer (current-buffer))
15975 (save-excursion
15976 (save-restriction
15977 (widen)
15978 (goto-char (point-min))
15979 (let (case-fold-search)
15980 (if (re-search-forward
15981 (format org-complex-heading-regexp-format
15982 (regexp-quote heading)) nil t)
15983 (if pos-only
15984 (match-beginning 0)
15985 (move-marker (make-marker) (match-beginning 0)))))))))
15987 (defun org-find-exact-heading-in-directory (heading &optional dir)
15988 "Find Org node headline HEADING in all .org files in directory DIR.
15989 When the target headline is found, return a marker to this location."
15990 (let ((files (directory-files (or dir default-directory)
15991 nil "\\`[^.#].*\\.org\\'"))
15992 file visiting m buffer)
15993 (catch 'found
15994 (while (setq file (pop files))
15995 (message "trying %s" file)
15996 (setq visiting (org-find-base-buffer-visiting file))
15997 (setq buffer (or visiting (find-file-noselect file)))
15998 (setq m (org-find-exact-headline-in-buffer
15999 heading buffer))
16000 (when (and (not m) (not visiting)) (kill-buffer buffer))
16001 (and m (throw 'found m))))))
16003 (defun org-find-entry-with-id (ident)
16004 "Locate the entry that contains the ID property with exact value IDENT.
16005 IDENT can be a string, a symbol or a number, this function will search for
16006 the string representation of it.
16007 Return the position where this entry starts, or nil if there is no such entry."
16008 (interactive "sID: ")
16009 (let ((id (cond
16010 ((stringp ident) ident)
16011 ((symbol-name ident) (symbol-name ident))
16012 ((numberp ident) (number-to-string ident))
16013 (t (error "IDENT %s must be a string, symbol or number" ident))))
16014 (case-fold-search nil))
16015 (save-excursion
16016 (save-restriction
16017 (widen)
16018 (goto-char (point-min))
16019 (when (re-search-forward
16020 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16021 nil t)
16022 (org-back-to-heading t)
16023 (point))))))
16025 ;;;; Timestamps
16027 (defvar org-last-changed-timestamp nil)
16028 (defvar org-last-inserted-timestamp nil
16029 "The last time stamp inserted with `org-insert-time-stamp'.")
16030 (defvar org-ts-what) ; dynamically scoped parameter
16032 (defun org-time-stamp (arg &optional inactive)
16033 "Prompt for a date/time and insert a time stamp.
16034 If the user specifies a time like HH:MM or if this command is
16035 called with at least one prefix argument, the time stamp contains
16036 the date and the time. Otherwise, only the date is be included.
16038 All parts of a date not specified by the user is filled in from
16039 the current date/time. So if you just press return without
16040 typing anything, the time stamp will represent the current
16041 date/time.
16043 If there is already a timestamp at the cursor, it will be
16044 modified.
16046 With two universal prefix arguments, insert an active timestamp
16047 with the current time without prompting the user.
16049 When called from lisp, the timestamp is inactive if INACTIVE is
16050 non-nil."
16051 (interactive "P")
16052 (let* ((ts nil)
16053 (default-time
16054 ;; Default time is either today, or, when entering a range,
16055 ;; the range start.
16056 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16057 (save-excursion
16058 (re-search-backward
16059 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16060 (- (point) 20) t)))
16061 (apply 'encode-time (org-parse-time-string (match-string 1)))
16062 (current-time)))
16063 (default-input (and ts (org-get-compact-tod ts)))
16064 (repeater (save-excursion
16065 (save-match-data
16066 (beginning-of-line)
16067 (when (re-search-forward
16068 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16069 (save-excursion (progn (end-of-line) (point))) t)
16070 (match-string 0)))))
16071 org-time-was-given org-end-time-was-given time)
16072 (cond
16073 ((and (org-at-timestamp-p t)
16074 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16075 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16076 (insert "--")
16077 (setq time (let ((this-command this-command))
16078 (org-read-date arg 'totime nil nil
16079 default-time default-input inactive)))
16080 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16081 ((org-at-timestamp-p t)
16082 (setq time (let ((this-command this-command))
16083 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16084 (when (org-at-timestamp-p t) ; just to get the match data
16085 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16086 (replace-match "")
16087 (setq org-last-changed-timestamp
16088 (org-insert-time-stamp
16089 time (or org-time-was-given arg)
16090 inactive nil nil (list org-end-time-was-given)))
16091 (when repeater (goto-char (1- (point))) (insert " " repeater)
16092 (setq org-last-changed-timestamp
16093 (concat (substring org-last-inserted-timestamp 0 -1)
16094 " " repeater ">"))))
16095 (message "Timestamp updated"))
16096 ((equal arg '(16))
16097 (org-insert-time-stamp (current-time) t inactive))
16099 (setq time (let ((this-command this-command))
16100 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16101 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16102 nil nil (list org-end-time-was-given))))))
16104 ;; FIXME: can we use this for something else, like computing time differences?
16105 (defun org-get-compact-tod (s)
16106 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16107 (let* ((t1 (match-string 1 s))
16108 (h1 (string-to-number (match-string 2 s)))
16109 (m1 (string-to-number (match-string 3 s)))
16110 (t2 (and (match-end 4) (match-string 5 s)))
16111 (h2 (and t2 (string-to-number (match-string 6 s))))
16112 (m2 (and t2 (string-to-number (match-string 7 s))))
16113 dh dm)
16114 (if (not t2)
16116 (setq dh (- h2 h1) dm (- m2 m1))
16117 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16118 (concat t1 "+" (number-to-string dh)
16119 (and (/= 0 dm) (format ":%02d" dm)))))))
16121 (defun org-time-stamp-inactive (&optional arg)
16122 "Insert an inactive time stamp.
16123 An inactive time stamp is enclosed in square brackets instead of angle
16124 brackets. It is inactive in the sense that it does not trigger agenda entries,
16125 does not link to the calendar and cannot be changed with the S-cursor keys.
16126 So these are more for recording a certain time/date."
16127 (interactive "P")
16128 (org-time-stamp arg 'inactive))
16130 (defvar org-date-ovl (make-overlay 1 1))
16131 (overlay-put org-date-ovl 'face 'org-date-selected)
16132 (org-detach-overlay org-date-ovl)
16134 (defvar org-ans1) ; dynamically scoped parameter
16135 (defvar org-ans2) ; dynamically scoped parameter
16137 (defvar org-plain-time-of-day-regexp) ; defined below
16139 (defvar org-overriding-default-time nil) ; dynamically scoped
16140 (defvar org-read-date-overlay nil)
16141 (defvar org-dcst nil) ; dynamically scoped
16142 (defvar org-read-date-history nil)
16143 (defvar org-read-date-final-answer nil)
16144 (defvar org-read-date-analyze-futurep nil)
16145 (defvar org-read-date-analyze-forced-year nil)
16146 (defvar org-read-date-inactive)
16148 (defvar org-read-date-minibuffer-local-map
16149 (let* ((org-replace-disputed-keys nil)
16150 (map (make-sparse-keymap)))
16151 (set-keymap-parent map minibuffer-local-map)
16152 (org-defkey map (kbd ".")
16153 (lambda () (interactive)
16154 ;; Are we at the beginning of the prompt?
16155 (if (looking-back "^[^:]+: ")
16156 (org-eval-in-calendar '(calendar-goto-today))
16157 (insert "."))))
16158 (org-defkey map (kbd "C-.")
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-goto-today))))
16161 (org-defkey map [(meta shift left)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-backward-month 1))))
16164 (org-defkey map [(meta shift right)]
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(calendar-forward-month 1))))
16167 (org-defkey map [(meta shift up)]
16168 (lambda () (interactive)
16169 (org-eval-in-calendar '(calendar-backward-year 1))))
16170 (org-defkey map [(meta shift down)]
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(calendar-forward-year 1))))
16173 (org-defkey map [?\e (shift left)]
16174 (lambda () (interactive)
16175 (org-eval-in-calendar '(calendar-backward-month 1))))
16176 (org-defkey map [?\e (shift right)]
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(calendar-forward-month 1))))
16179 (org-defkey map [?\e (shift up)]
16180 (lambda () (interactive)
16181 (org-eval-in-calendar '(calendar-backward-year 1))))
16182 (org-defkey map [?\e (shift down)]
16183 (lambda () (interactive)
16184 (org-eval-in-calendar '(calendar-forward-year 1))))
16185 (org-defkey map [(shift up)]
16186 (lambda () (interactive)
16187 (org-eval-in-calendar '(calendar-backward-week 1))))
16188 (org-defkey map [(shift down)]
16189 (lambda () (interactive)
16190 (org-eval-in-calendar '(calendar-forward-week 1))))
16191 (org-defkey map [(shift left)]
16192 (lambda () (interactive)
16193 (org-eval-in-calendar '(calendar-backward-day 1))))
16194 (org-defkey map [(shift right)]
16195 (lambda () (interactive)
16196 (org-eval-in-calendar '(calendar-forward-day 1))))
16197 (org-defkey map "!"
16198 (lambda () (interactive)
16199 (org-eval-in-calendar '(diary-view-entries))
16200 (message "")))
16201 (org-defkey map ">"
16202 (lambda () (interactive)
16203 (org-eval-in-calendar '(scroll-calendar-left 1))))
16204 (org-defkey map "<"
16205 (lambda () (interactive)
16206 (org-eval-in-calendar '(scroll-calendar-right 1))))
16207 (org-defkey map "\C-v"
16208 (lambda () (interactive)
16209 (org-eval-in-calendar
16210 '(calendar-scroll-left-three-months 1))))
16211 (org-defkey map "\M-v"
16212 (lambda () (interactive)
16213 (org-eval-in-calendar
16214 '(calendar-scroll-right-three-months 1))))
16215 map)
16216 "Keymap for minibuffer commands when using `org-read-date'.")
16218 (defvar org-def)
16219 (defvar org-defdecode)
16220 (defvar org-with-time)
16222 (defun org-read-date (&optional org-with-time to-time from-string prompt
16223 default-time default-input inactive)
16224 "Read a date, possibly a time, and make things smooth for the user.
16225 The prompt will suggest to enter an ISO date, but you can also enter anything
16226 which will at least partially be understood by `parse-time-string'.
16227 Unrecognized parts of the date will default to the current day, month, year,
16228 hour and minute. If this command is called to replace a timestamp at point,
16229 or to enter the second timestamp of a range, the default time is taken
16230 from the existing stamp. Furthermore, the command prefers the future,
16231 so if you are giving a date where the year is not given, and the day-month
16232 combination is already past in the current year, it will assume you
16233 mean next year. For details, see the manual. A few examples:
16235 3-2-5 --> 2003-02-05
16236 feb 15 --> currentyear-02-15
16237 2/15 --> currentyear-02-15
16238 sep 12 9 --> 2009-09-12
16239 12:45 --> today 12:45
16240 22 sept 0:34 --> currentyear-09-22 0:34
16241 12 --> currentyear-currentmonth-12
16242 Fri --> nearest Friday after today
16243 -Tue --> last Tuesday
16244 etc.
16246 Furthermore you can specify a relative date by giving, as the *first* thing
16247 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16248 change in days weeks, months, years.
16249 With a single plus or minus, the date is relative to today. With a double
16250 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16251 +4d --> four days from today
16252 +4 --> same as above
16253 +2w --> two weeks from today
16254 ++5 --> five days from default date
16256 The function understands only English month and weekday abbreviations.
16258 While prompting, a calendar is popped up - you can also select the
16259 date with the mouse (button 1). The calendar shows a period of three
16260 months. To scroll it to other months, use the keys `>' and `<'.
16261 If you don't like the calendar, turn it off with
16262 \(setq org-read-date-popup-calendar nil)
16264 With optional argument TO-TIME, the date will immediately be converted
16265 to an internal time.
16266 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16267 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16268 still enter a time, and this function will inform the calling routine
16269 about this change. The calling routine may then choose to change the
16270 format used to insert the time stamp into the buffer to include the time.
16271 With optional argument FROM-STRING, read from this string instead from
16272 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16273 the time/date that is used for everything that is not specified by the
16274 user."
16275 (require 'parse-time)
16276 (let* ((org-time-stamp-rounding-minutes
16277 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16278 (org-dcst org-display-custom-times)
16279 (ct (org-current-time))
16280 (org-def (or org-overriding-default-time default-time ct))
16281 (org-defdecode (decode-time org-def))
16282 (dummy (progn
16283 (when (< (nth 2 org-defdecode) org-extend-today-until)
16284 (setcar (nthcdr 2 org-defdecode) -1)
16285 (setcar (nthcdr 1 org-defdecode) 59)
16286 (setq org-def (apply 'encode-time org-defdecode)
16287 org-defdecode (decode-time org-def)))))
16288 (mouse-autoselect-window nil) ; Don't let the mouse jump
16289 (calendar-frame-setup nil)
16290 (calendar-setup nil)
16291 (calendar-move-hook nil)
16292 (calendar-view-diary-initially-flag nil)
16293 (calendar-view-holidays-initially-flag nil)
16294 (timestr (format-time-string
16295 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16296 (prompt (concat (if prompt (concat prompt " ") "")
16297 (format "Date+time [%s]: " timestr)))
16298 ans (org-ans0 "") org-ans1 org-ans2 final)
16300 (cond
16301 (from-string (setq ans from-string))
16302 (org-read-date-popup-calendar
16303 (save-excursion
16304 (save-window-excursion
16305 (calendar)
16306 (org-eval-in-calendar '(setq cursor-type nil) t)
16307 (unwind-protect
16308 (progn
16309 (calendar-forward-day (- (time-to-days org-def)
16310 (calendar-absolute-from-gregorian
16311 (calendar-current-date))))
16312 (org-eval-in-calendar nil t)
16313 (let* ((old-map (current-local-map))
16314 (map (copy-keymap calendar-mode-map))
16315 (minibuffer-local-map
16316 (copy-keymap org-read-date-minibuffer-local-map)))
16317 (org-defkey map (kbd "RET") 'org-calendar-select)
16318 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16319 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16320 (unwind-protect
16321 (progn
16322 (use-local-map map)
16323 (setq org-read-date-inactive inactive)
16324 (add-hook 'post-command-hook 'org-read-date-display)
16325 (setq org-ans0 (read-string prompt default-input
16326 'org-read-date-history nil))
16327 ;; org-ans0: from prompt
16328 ;; org-ans1: from mouse click
16329 ;; org-ans2: from calendar motion
16330 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16331 (remove-hook 'post-command-hook 'org-read-date-display)
16332 (use-local-map old-map)
16333 (when org-read-date-overlay
16334 (delete-overlay org-read-date-overlay)
16335 (setq org-read-date-overlay nil)))))
16336 (bury-buffer "*Calendar*")))))
16338 (t ; Naked prompt only
16339 (unwind-protect
16340 (setq ans (read-string prompt default-input
16341 'org-read-date-history timestr))
16342 (when org-read-date-overlay
16343 (delete-overlay org-read-date-overlay)
16344 (setq org-read-date-overlay nil)))))
16346 (setq final (org-read-date-analyze ans org-def org-defdecode))
16348 (when org-read-date-analyze-forced-year
16349 (message "Year was forced into %s"
16350 (if org-read-date-force-compatible-dates
16351 "compatible range (1970-2037)"
16352 "range representable on this machine"))
16353 (ding))
16355 ;; One round trip to get rid of 34th of August and stuff like that....
16356 (setq final (decode-time (apply 'encode-time final)))
16358 (setq org-read-date-final-answer ans)
16360 (if to-time
16361 (apply 'encode-time final)
16362 (if (and (boundp 'org-time-was-given) org-time-was-given)
16363 (format "%04d-%02d-%02d %02d:%02d"
16364 (nth 5 final) (nth 4 final) (nth 3 final)
16365 (nth 2 final) (nth 1 final))
16366 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16368 (defun org-read-date-display ()
16369 "Display the current date prompt interpretation in the minibuffer."
16370 (when org-read-date-display-live
16371 (when org-read-date-overlay
16372 (delete-overlay org-read-date-overlay))
16373 (when (minibufferp (current-buffer))
16374 (save-excursion
16375 (end-of-line 1)
16376 (while (not (equal (buffer-substring
16377 (max (point-min) (- (point) 4)) (point))
16378 " "))
16379 (insert " ")))
16380 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16381 " " (or org-ans1 org-ans2)))
16382 (org-end-time-was-given nil)
16383 (f (org-read-date-analyze ans org-def org-defdecode))
16384 (fmts (if org-dcst
16385 org-time-stamp-custom-formats
16386 org-time-stamp-formats))
16387 (fmt (if (or org-with-time
16388 (and (boundp 'org-time-was-given) org-time-was-given))
16389 (cdr fmts)
16390 (car fmts)))
16391 (txt (format-time-string fmt (apply 'encode-time f)))
16392 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16393 (txt (concat "=> " txt)))
16394 (when (and org-end-time-was-given
16395 (string-match org-plain-time-of-day-regexp txt))
16396 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16397 org-end-time-was-given
16398 (substring txt (match-end 0)))))
16399 (when org-read-date-analyze-futurep
16400 (setq txt (concat txt " (=>F)")))
16401 (setq org-read-date-overlay
16402 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16403 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16405 (defun org-read-date-analyze (ans org-def org-defdecode)
16406 "Analyze the combined answer of the date prompt."
16407 ;; FIXME: cleanup and comment
16408 (let ((nowdecode (decode-time (current-time)))
16409 delta deltan deltaw deltadef year month day
16410 hour minute second wday pm h2 m2 tl wday1
16411 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16412 (setq org-read-date-analyze-futurep nil
16413 org-read-date-analyze-forced-year nil)
16414 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16415 (setq ans "+0"))
16417 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16418 (setq ans (replace-match "" t t ans)
16419 deltan (car delta)
16420 deltaw (nth 1 delta)
16421 deltadef (nth 2 delta)))
16423 ;; Check if there is an iso week date in there. If yes, store the
16424 ;; info and postpone interpreting it until the rest of the parsing
16425 ;; is done.
16426 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16427 (setq iso-year (if (match-end 1)
16428 (org-small-year-to-year
16429 (string-to-number (match-string 1 ans))))
16430 iso-weekday (if (match-end 3)
16431 (string-to-number (match-string 3 ans)))
16432 iso-week (string-to-number (match-string 2 ans)))
16433 (setq ans (replace-match "" t t ans)))
16435 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16436 (when (string-match
16437 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16438 (setq year (if (match-end 2)
16439 (string-to-number (match-string 2 ans))
16440 (progn (setq kill-year t)
16441 (string-to-number (format-time-string "%Y"))))
16442 month (string-to-number (match-string 3 ans))
16443 day (string-to-number (match-string 4 ans)))
16444 (if (< year 100) (setq year (+ 2000 year)))
16445 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16446 t nil ans)))
16448 ;; Help matching dotted european dates
16449 (when (string-match
16450 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16451 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16452 (setq kill-year t)
16453 (string-to-number (format-time-string "%Y")))
16454 day (string-to-number (match-string 1 ans))
16455 month (string-to-number (match-string 2 ans))
16456 ans (replace-match (format "%04d-%02d-%02d" year month day)
16457 t nil ans)))
16459 ;; Help matching american dates, like 5/30 or 5/30/7
16460 (when (string-match
16461 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16462 (setq year (if (match-end 4)
16463 (string-to-number (match-string 4 ans))
16464 (progn (setq kill-year t)
16465 (string-to-number (format-time-string "%Y"))))
16466 month (string-to-number (match-string 1 ans))
16467 day (string-to-number (match-string 2 ans)))
16468 (if (< year 100) (setq year (+ 2000 year)))
16469 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16470 t nil ans)))
16471 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16472 ;; If there is a time with am/pm, and *no* time without it, we convert
16473 ;; so that matching will be successful.
16474 (loop for i from 1 to 2 do ; twice, for end time as well
16475 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16476 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16477 (setq hour (string-to-number (match-string 1 ans))
16478 minute (if (match-end 3)
16479 (string-to-number (match-string 3 ans))
16481 pm (equal ?p
16482 (string-to-char (downcase (match-string 4 ans)))))
16483 (if (and (= hour 12) (not pm))
16484 (setq hour 0)
16485 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16486 (setq ans (replace-match (format "%02d:%02d" hour minute)
16487 t t ans))))
16489 ;; Check if a time range is given as a duration
16490 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16491 (setq hour (string-to-number (match-string 1 ans))
16492 h2 (+ hour (string-to-number (match-string 3 ans)))
16493 minute (string-to-number (match-string 2 ans))
16494 m2 (+ minute (if (match-end 5) (string-to-number
16495 (match-string 5 ans))0)))
16496 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16497 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16498 t t ans)))
16500 ;; Check if there is a time range
16501 (when (boundp 'org-end-time-was-given)
16502 (setq org-time-was-given nil)
16503 (when (and (string-match org-plain-time-of-day-regexp ans)
16504 (match-end 8))
16505 (setq org-end-time-was-given (match-string 8 ans))
16506 (setq ans (concat (substring ans 0 (match-beginning 7))
16507 (substring ans (match-end 7))))))
16509 (setq tl (parse-time-string ans)
16510 day (or (nth 3 tl) (nth 3 org-defdecode))
16511 month (or (nth 4 tl)
16512 (if (and org-read-date-prefer-future
16513 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16514 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16515 (nth 4 org-defdecode)))
16516 year (or (and (not kill-year) (nth 5 tl))
16517 (if (and org-read-date-prefer-future
16518 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16519 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16520 (nth 5 org-defdecode)))
16521 hour (or (nth 2 tl) (nth 2 org-defdecode))
16522 minute (or (nth 1 tl) (nth 1 org-defdecode))
16523 second (or (nth 0 tl) 0)
16524 wday (nth 6 tl))
16526 (when (and (eq org-read-date-prefer-future 'time)
16527 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16528 (equal day (nth 3 nowdecode))
16529 (equal month (nth 4 nowdecode))
16530 (equal year (nth 5 nowdecode))
16531 (nth 2 tl)
16532 (or (< (nth 2 tl) (nth 2 nowdecode))
16533 (and (= (nth 2 tl) (nth 2 nowdecode))
16534 (nth 1 tl)
16535 (< (nth 1 tl) (nth 1 nowdecode)))))
16536 (setq day (1+ day)
16537 futurep t))
16539 ;; Special date definitions below
16540 (cond
16541 (iso-week
16542 ;; There was an iso week
16543 (require 'cal-iso)
16544 (setq futurep nil)
16545 (setq year (or iso-year year)
16546 day (or iso-weekday wday 1)
16547 wday nil ; to make sure that the trigger below does not match
16548 iso-date (calendar-gregorian-from-absolute
16549 (calendar-absolute-from-iso
16550 (list iso-week day year))))
16551 ; FIXME: Should we also push ISO weeks into the future?
16552 ; (when (and org-read-date-prefer-future
16553 ; (not iso-year)
16554 ; (< (calendar-absolute-from-gregorian iso-date)
16555 ; (time-to-days (current-time))))
16556 ; (setq year (1+ year)
16557 ; iso-date (calendar-gregorian-from-absolute
16558 ; (calendar-absolute-from-iso
16559 ; (list iso-week day year)))))
16560 (setq month (car iso-date)
16561 year (nth 2 iso-date)
16562 day (nth 1 iso-date)))
16563 (deltan
16564 (setq futurep nil)
16565 (unless deltadef
16566 (let ((now (decode-time (current-time))))
16567 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16568 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16569 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16570 ((equal deltaw "m") (setq month (+ month deltan)))
16571 ((equal deltaw "y") (setq year (+ year deltan)))))
16572 ((and wday (not (nth 3 tl)))
16573 ;; Weekday was given, but no day, so pick that day in the week
16574 ;; on or after the derived date.
16575 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16576 (unless (equal wday wday1)
16577 (setq day (+ day (% (- wday wday1 -7) 7))))))
16578 (if (and (boundp 'org-time-was-given)
16579 (nth 2 tl))
16580 (setq org-time-was-given t))
16581 (if (< year 100) (setq year (+ 2000 year)))
16582 ;; Check of the date is representable
16583 (if org-read-date-force-compatible-dates
16584 (progn
16585 (if (< year 1970)
16586 (setq year 1970 org-read-date-analyze-forced-year t))
16587 (if (> year 2037)
16588 (setq year 2037 org-read-date-analyze-forced-year t)))
16589 (condition-case nil
16590 (ignore (encode-time second minute hour day month year))
16591 (error
16592 (setq year (nth 5 org-defdecode))
16593 (setq org-read-date-analyze-forced-year t))))
16594 (setq org-read-date-analyze-futurep futurep)
16595 (list second minute hour day month year)))
16597 (defvar parse-time-weekdays)
16598 (defun org-read-date-get-relative (s today default)
16599 "Check string S for special relative date string.
16600 TODAY and DEFAULT are internal times, for today and for a default.
16601 Return shift list (N what def-flag)
16602 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16603 N is the number of WHATs to shift.
16604 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16605 the DEFAULT date rather than TODAY."
16606 (require 'parse-time)
16607 (when (and
16608 (string-match
16609 (concat
16610 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16611 "\\([0-9]+\\)?"
16612 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16613 "\\([ \t]\\|$\\)") s)
16614 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16615 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16616 (string-to-char (substring (match-string 1 s) -1))
16617 ?+))
16618 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16619 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16620 (what (if (match-end 3) (match-string 3 s) "d"))
16621 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16622 (date (if rel default today))
16623 (wday (nth 6 (decode-time date)))
16624 delta)
16625 (if wday1
16626 (progn
16627 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16628 (if (= delta 0) (setq delta 7))
16629 (if (= dir ?-)
16630 (progn
16631 (setq delta (- delta 7))
16632 (if (= delta 0) (setq delta -7))))
16633 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16634 (list delta "d" rel))
16635 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16637 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16638 "Turn a user-specified date into the internal representation.
16639 The internal representation needed by the calendar is (month day year).
16640 This is a wrapper to handle the brain-dead convention in calendar that
16641 user function argument order change dependent on argument order."
16642 (if (boundp 'calendar-date-style)
16643 (cond
16644 ((eq calendar-date-style 'american)
16645 (list arg1 arg2 arg3))
16646 ((eq calendar-date-style 'european)
16647 (list arg2 arg1 arg3))
16648 ((eq calendar-date-style 'iso)
16649 (list arg2 arg3 arg1)))
16650 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16651 (if (org-bound-and-true-p european-calendar-style)
16652 (list arg2 arg1 arg3)
16653 (list arg1 arg2 arg3)))))
16655 (defun org-eval-in-calendar (form &optional keepdate)
16656 "Eval FORM in the calendar window and return to current window.
16657 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16658 otherwise stick to the current value of `org-ans2'."
16659 (let ((sf (selected-frame))
16660 (sw (selected-window)))
16661 (select-window (get-buffer-window "*Calendar*" t))
16662 (eval form)
16663 (when (and (not keepdate) (calendar-cursor-to-date))
16664 (let* ((date (calendar-cursor-to-date))
16665 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16666 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16667 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16668 (select-window sw)
16669 (org-select-frame-set-input-focus sf)))
16671 (defun org-calendar-select ()
16672 "Return to `org-read-date' with the date currently selected.
16673 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16674 (interactive)
16675 (when (calendar-cursor-to-date)
16676 (let* ((date (calendar-cursor-to-date))
16677 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16678 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16679 (if (active-minibuffer-window) (exit-minibuffer))))
16681 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16682 "Insert a date stamp for the date given by the internal TIME.
16683 WITH-HM means use the stamp format that includes the time of the day.
16684 INACTIVE means use square brackets instead of angular ones, so that the
16685 stamp will not contribute to the agenda.
16686 PRE and POST are optional strings to be inserted before and after the
16687 stamp.
16688 The command returns the inserted time stamp."
16689 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16690 stamp)
16691 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16692 (insert-before-markers (or pre ""))
16693 (when (listp extra)
16694 (setq extra (car extra))
16695 (if (and (stringp extra)
16696 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16697 (setq extra (format "-%02d:%02d"
16698 (string-to-number (match-string 1 extra))
16699 (string-to-number (match-string 2 extra))))
16700 (setq extra nil)))
16701 (when extra
16702 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16703 (insert-before-markers (setq stamp (format-time-string fmt time)))
16704 (insert-before-markers (or post ""))
16705 (setq org-last-inserted-timestamp stamp)))
16707 (defun org-toggle-time-stamp-overlays ()
16708 "Toggle the use of custom time stamp formats."
16709 (interactive)
16710 (setq org-display-custom-times (not org-display-custom-times))
16711 (unless org-display-custom-times
16712 (let ((p (point-min)) (bmp (buffer-modified-p)))
16713 (while (setq p (next-single-property-change p 'display))
16714 (if (and (get-text-property p 'display)
16715 (eq (get-text-property p 'face) 'org-date))
16716 (remove-text-properties
16717 p (setq p (next-single-property-change p 'display))
16718 '(display t))))
16719 (set-buffer-modified-p bmp)))
16720 (if (featurep 'xemacs)
16721 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16722 (org-restart-font-lock)
16723 (setq org-table-may-need-update t)
16724 (if org-display-custom-times
16725 (message "Time stamps are overlaid with custom format")
16726 (message "Time stamp overlays removed")))
16728 (defun org-display-custom-time (beg end)
16729 "Overlay modified time stamp format over timestamp between BEG and END."
16730 (let* ((ts (buffer-substring beg end))
16731 t1 w1 with-hm tf time str w2 (off 0))
16732 (save-match-data
16733 (setq t1 (org-parse-time-string ts t))
16734 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16735 (setq off (- (match-end 0) (match-beginning 0)))))
16736 (setq end (- end off))
16737 (setq w1 (- end beg)
16738 with-hm (and (nth 1 t1) (nth 2 t1))
16739 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16740 time (org-fix-decoded-time t1)
16741 str (org-add-props
16742 (format-time-string
16743 (substring tf 1 -1) (apply 'encode-time time))
16744 nil 'mouse-face 'highlight)
16745 w2 (length str))
16746 (if (not (= w2 w1))
16747 (add-text-properties (1+ beg) (+ 2 beg)
16748 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16749 (if (featurep 'xemacs)
16750 (progn
16751 (put-text-property beg end 'invisible t)
16752 (put-text-property beg end 'end-glyph (make-glyph str)))
16753 (put-text-property beg end 'display str))))
16755 (defun org-translate-time (string)
16756 "Translate all timestamps in STRING to custom format.
16757 But do this only if the variable `org-display-custom-times' is set."
16758 (when org-display-custom-times
16759 (save-match-data
16760 (let* ((start 0)
16761 (re org-ts-regexp-both)
16762 t1 with-hm inactive tf time str beg end)
16763 (while (setq start (string-match re string start))
16764 (setq beg (match-beginning 0)
16765 end (match-end 0)
16766 t1 (save-match-data
16767 (org-parse-time-string (substring string beg end) t))
16768 with-hm (and (nth 1 t1) (nth 2 t1))
16769 inactive (equal (substring string beg (1+ beg)) "[")
16770 tf (funcall (if with-hm 'cdr 'car)
16771 org-time-stamp-custom-formats)
16772 time (org-fix-decoded-time t1)
16773 str (format-time-string
16774 (concat
16775 (if inactive "[" "<") (substring tf 1 -1)
16776 (if inactive "]" ">"))
16777 (apply 'encode-time time))
16778 string (replace-match str t t string)
16779 start (+ start (length str)))))))
16780 string)
16782 (defun org-fix-decoded-time (time)
16783 "Set 0 instead of nil for the first 6 elements of time.
16784 Don't touch the rest."
16785 (let ((n 0))
16786 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16788 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16790 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16791 "Difference between TIMESTAMP-STRING and now in days.
16792 If SECONDS is non-nil, return the difference in seconds."
16793 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16794 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16795 (funcall fdiff (current-time)))))
16797 (defun org-deadline-close (timestamp-string &optional ndays)
16798 "Is the time in TIMESTAMP-STRING close to the current date?"
16799 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16800 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16801 (not (org-entry-is-done-p))))
16803 (defun org-get-wdays (ts &optional delay zero-delay)
16804 "Get the deadline lead time appropriate for timestring TS.
16805 When DELAY is non-nil, get the delay time for scheduled items
16806 instead of the deadline lead time. When ZERO-DELAY is non-nil
16807 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16808 don't try to find the delay cookie in the scheduled timestamp."
16809 (let ((tv (if delay org-scheduled-delay-days
16810 org-deadline-warning-days)))
16811 (cond
16812 ((or (and delay (< tv 0))
16813 (and delay zero-delay (<= tv 0))
16814 (and (not delay) (<= tv 0)))
16815 ;; Enforce this value no matter what
16816 (- tv))
16817 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16818 ;; lead time is specified.
16819 (floor (* (string-to-number (match-string 1 ts))
16820 (cdr (assoc (match-string 2 ts)
16821 '(("d" . 1) ("w" . 7)
16822 ("m" . 30.4) ("y" . 365.25)
16823 ("h" . 0.041667)))))))
16824 ;; go for the default.
16825 (t tv))))
16827 (defun org-calendar-select-mouse (ev)
16828 "Return to `org-read-date' with the date currently selected.
16829 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16830 (interactive "e")
16831 (mouse-set-point ev)
16832 (when (calendar-cursor-to-date)
16833 (let* ((date (calendar-cursor-to-date))
16834 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16835 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16836 (if (active-minibuffer-window) (exit-minibuffer))))
16838 (defun org-check-deadlines (ndays)
16839 "Check if there are any deadlines due or past due.
16840 A deadline is considered due if it happens within `org-deadline-warning-days'
16841 days from today's date. If the deadline appears in an entry marked DONE,
16842 it is not shown. The prefix arg NDAYS can be used to test that many
16843 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16844 (interactive "P")
16845 (let* ((org-warn-days
16846 (cond
16847 ((equal ndays '(4)) 100000)
16848 (ndays (prefix-numeric-value ndays))
16849 (t (abs org-deadline-warning-days))))
16850 (case-fold-search nil)
16851 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16852 (callback
16853 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16855 (message "%d deadlines past-due or due within %d days"
16856 (org-occur regexp nil callback)
16857 org-warn-days)))
16859 (defsubst org-re-timestamp (type)
16860 "Return a regexp for timestamp TYPE.
16861 Allowed values for TYPE are:
16863 all: all timestamps
16864 active: only active timestamps (<...>)
16865 inactive: only inactive timestamps ([...])
16866 scheduled: only scheduled timestamps
16867 deadline: only deadline timestamps
16868 closed: only closed time-stamps
16870 When TYPE is nil, fall back on returning a regexp that matches
16871 both scheduled and deadline timestamps."
16872 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16873 ((eq type 'active) org-ts-regexp)
16874 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16875 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16876 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16877 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16878 ((eq type 'scheduled-or-deadline)
16879 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16881 (defun org-check-before-date (date)
16882 "Check if there are deadlines or scheduled entries before DATE."
16883 (interactive (list (org-read-date)))
16884 (let ((case-fold-search nil)
16885 (regexp (org-re-timestamp org-ts-type))
16886 (callback
16887 (lambda () (time-less-p
16888 (org-time-string-to-time (match-string 1))
16889 (org-time-string-to-time date)))))
16890 (message "%d entries before %s"
16891 (org-occur regexp nil callback) date)))
16893 (defun org-check-after-date (date)
16894 "Check if there are deadlines or scheduled entries after DATE."
16895 (interactive (list (org-read-date)))
16896 (let ((case-fold-search nil)
16897 (regexp (org-re-timestamp org-ts-type))
16898 (callback
16899 (lambda () (not
16900 (time-less-p
16901 (org-time-string-to-time (match-string 1))
16902 (org-time-string-to-time date))))))
16903 (message "%d entries after %s"
16904 (org-occur regexp nil callback) date)))
16906 (defun org-check-dates-range (start-date end-date)
16907 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16908 (interactive (list (org-read-date nil nil nil "Range starts")
16909 (org-read-date nil nil nil "Range end")))
16910 (let ((case-fold-search nil)
16911 (regexp (org-re-timestamp org-ts-type))
16912 (callback
16913 (lambda ()
16914 (let ((match (match-string 1)))
16915 (and
16916 (not (time-less-p
16917 (org-time-string-to-time match)
16918 (org-time-string-to-time start-date)))
16919 (time-less-p
16920 (org-time-string-to-time match)
16921 (org-time-string-to-time end-date)))))))
16922 (message "%d entries between %s and %s"
16923 (org-occur regexp nil callback) start-date end-date)))
16925 (defun org-evaluate-time-range (&optional to-buffer)
16926 "Evaluate a time range by computing the difference between start and end.
16927 Normally the result is just printed in the echo area, but with prefix arg
16928 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16929 If the time range is actually in a table, the result is inserted into the
16930 next column.
16931 For time difference computation, a year is assumed to be exactly 365
16932 days in order to avoid rounding problems."
16933 (interactive "P")
16935 (org-clock-update-time-maybe)
16936 (save-excursion
16937 (unless (org-at-date-range-p t)
16938 (goto-char (point-at-bol))
16939 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16940 (if (not (org-at-date-range-p t))
16941 (user-error "Not at a time-stamp range, and none found in current line")))
16942 (let* ((ts1 (match-string 1))
16943 (ts2 (match-string 2))
16944 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16945 (match-end (match-end 0))
16946 (time1 (org-time-string-to-time ts1))
16947 (time2 (org-time-string-to-time ts2))
16948 (t1 (org-float-time time1))
16949 (t2 (org-float-time time2))
16950 (diff (abs (- t2 t1)))
16951 (negative (< (- t2 t1) 0))
16952 ;; (ys (floor (* 365 24 60 60)))
16953 (ds (* 24 60 60))
16954 (hs (* 60 60))
16955 (fy "%dy %dd %02d:%02d")
16956 (fy1 "%dy %dd")
16957 (fd "%dd %02d:%02d")
16958 (fd1 "%dd")
16959 (fh "%02d:%02d")
16960 y d h m align)
16961 (if havetime
16962 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16964 d (floor (/ diff ds)) diff (mod diff ds)
16965 h (floor (/ diff hs)) diff (mod diff hs)
16966 m (floor (/ diff 60)))
16967 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16969 d (floor (+ (/ diff ds) 0.5))
16970 h 0 m 0))
16971 (if (not to-buffer)
16972 (message "%s" (org-make-tdiff-string y d h m))
16973 (if (org-at-table-p)
16974 (progn
16975 (goto-char match-end)
16976 (setq align t)
16977 (and (looking-at " *|") (goto-char (match-end 0))))
16978 (goto-char match-end))
16979 (if (looking-at
16980 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16981 (replace-match ""))
16982 (if negative (insert " -"))
16983 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16984 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16985 (insert " " (format fh h m))))
16986 (if align (org-table-align))
16987 (message "Time difference inserted")))))
16989 (defun org-make-tdiff-string (y d h m)
16990 (let ((fmt "")
16991 (l nil))
16992 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16993 l (push y l)))
16994 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16995 l (push d l)))
16996 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16997 l (push h l)))
16998 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16999 l (push m l)))
17000 (apply 'format fmt (nreverse l))))
17002 (defun org-time-string-to-time (s &optional buffer pos)
17003 "Convert a timestamp string into internal time."
17004 (condition-case errdata
17005 (apply 'encode-time (org-parse-time-string s))
17006 (error (error "Bad timestamp `%s'%s\nError was: %s"
17007 s (if (not (and buffer pos))
17009 (format " at %d in buffer `%s'" pos buffer))
17010 (cdr errdata)))))
17012 (defun org-time-string-to-seconds (s)
17013 "Convert a timestamp string to a number of seconds."
17014 (org-float-time (org-time-string-to-time s)))
17016 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17017 "Convert a time stamp to an absolute day number.
17018 If there is a specifier for a cyclic time stamp, get the closest
17019 date to DAYNR.
17020 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17021 The variable `date' is bound by the calendar when this is called."
17022 (cond
17023 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17024 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17025 daynr
17026 (+ daynr 1000)))
17027 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17028 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17029 (time-to-days (current-time))) (match-string 0 s)
17030 prefer show-all))
17031 (t (time-to-days
17032 (condition-case errdata
17033 (apply 'encode-time (org-parse-time-string s))
17034 (error (error "Bad timestamp `%s'%s\nError was: %s"
17035 s (if (not (and buffer pos))
17037 (format " at %d in buffer `%s'" pos buffer))
17038 (cdr errdata))))))))
17040 (defun org-days-to-iso-week (days)
17041 "Return the iso week number."
17042 (require 'cal-iso)
17043 (car (calendar-iso-from-absolute days)))
17045 (defun org-small-year-to-year (year)
17046 "Convert 2-digit years into 4-digit years.
17047 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17048 The year 2000 cannot be abbreviated. Any year larger than 99
17049 is returned unchanged."
17050 (if (< year 38)
17051 (setq year (+ 2000 year))
17052 (if (< year 100)
17053 (setq year (+ 1900 year))))
17054 year)
17056 (defun org-time-from-absolute (d)
17057 "Return the time corresponding to date D.
17058 D may be an absolute day number, or a calendar-type list (month day year)."
17059 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17060 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17062 (defun org-calendar-holiday ()
17063 "List of holidays, for Diary display in Org-mode."
17064 (require 'holidays)
17065 (let ((hl (funcall
17066 (if (fboundp 'calendar-check-holidays)
17067 'calendar-check-holidays 'check-calendar-holidays) date)))
17068 (if hl (mapconcat 'identity hl "; "))))
17070 (defun org-diary-sexp-entry (sexp entry date)
17071 "Process a SEXP diary ENTRY for DATE."
17072 (require 'diary-lib)
17073 (let ((result (if calendar-debug-sexp
17074 (let ((stack-trace-on-error t))
17075 (eval (car (read-from-string sexp))))
17076 (condition-case nil
17077 (eval (car (read-from-string sexp)))
17078 (error
17079 (beep)
17080 (message "Bad sexp at line %d in %s: %s"
17081 (org-current-line)
17082 (buffer-file-name) sexp)
17083 (sleep-for 2))))))
17084 (cond ((stringp result) (split-string result "; "))
17085 ((and (consp result)
17086 (not (consp (cdr result)))
17087 (stringp (cdr result))) (cdr result))
17088 ((and (consp result)
17089 (stringp (car result))) result)
17090 (result entry))))
17092 (defun org-diary-to-ical-string (frombuf)
17093 "Get iCalendar entries from diary entries in buffer FROMBUF.
17094 This uses the icalendar.el library."
17095 (let* ((tmpdir (if (featurep 'xemacs)
17096 (temp-directory)
17097 temporary-file-directory))
17098 (tmpfile (make-temp-name
17099 (expand-file-name "orgics" tmpdir)))
17100 buf rtn b e)
17101 (with-current-buffer frombuf
17102 (icalendar-export-region (point-min) (point-max) tmpfile)
17103 (setq buf (find-buffer-visiting tmpfile))
17104 (set-buffer buf)
17105 (goto-char (point-min))
17106 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17107 (setq b (match-beginning 0)))
17108 (goto-char (point-max))
17109 (if (re-search-backward "^END:VEVENT" nil t)
17110 (setq e (match-end 0)))
17111 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17112 (kill-buffer buf)
17113 (delete-file tmpfile)
17114 rtn))
17116 (defun org-closest-date (start current change prefer show-all)
17117 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17118 When PREFER is `past', return a date that is either CURRENT or past.
17119 When PREFER is `future', return a date that is either CURRENT or future.
17120 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17121 ;; Make the proper lists from the dates
17122 (catch 'exit
17123 (let ((a1 '(("h" . hour)
17124 ("d" . day)
17125 ("w" . week)
17126 ("m" . month)
17127 ("y" . year)))
17128 (shour (nth 2 (org-parse-time-string start)))
17129 dn dw sday cday n1 n2 n0
17130 d m y y1 y2 date1 date2 nmonths nm ny m2)
17132 (setq start (org-date-to-gregorian start)
17133 current (org-date-to-gregorian
17134 (if show-all
17135 current
17136 (time-to-days (current-time))))
17137 sday (calendar-absolute-from-gregorian start)
17138 cday (calendar-absolute-from-gregorian current))
17140 (if (<= cday sday) (throw 'exit sday))
17142 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17143 (setq dn (string-to-number (match-string 1 change))
17144 dw (cdr (assoc (match-string 2 change) a1)))
17145 (user-error "Invalid change specifier: %s" change))
17146 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17147 (cond
17148 ((eq dw 'hour)
17149 (let ((missing-hours
17150 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17151 dn)))
17152 (setq n1 (if (zerop missing-hours) cday
17153 (- cday (1+ (floor (/ missing-hours 24)))))
17154 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17155 ((eq dw 'day)
17156 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17157 n2 (+ n1 dn)))
17158 ((eq dw 'year)
17159 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17160 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17161 (setq date1 (list m d y1)
17162 n1 (calendar-absolute-from-gregorian date1)
17163 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17164 n2 (calendar-absolute-from-gregorian date2)))
17165 ((eq dw 'month)
17166 ;; approx number of month between the two dates
17167 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17168 ;; How often does dn fit in there?
17169 (setq d (nth 1 start) m (car start) y (nth 2 start)
17170 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17171 m (+ m nm)
17172 ny (floor (/ m 12))
17173 y (+ y ny)
17174 m (- m (* ny 12)))
17175 (while (> m 12) (setq m (- m 12) y (1+ y)))
17176 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17177 (setq m2 (+ m dn) y2 y)
17178 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17179 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17180 (while (<= n2 cday)
17181 (setq n1 n2 m m2 y y2)
17182 (setq m2 (+ m dn) y2 y)
17183 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17184 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17185 ;; Make sure n1 is the earlier date
17186 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17187 (if show-all
17188 (cond
17189 ((eq prefer 'past) (if (= cday n2) n2 n1))
17190 ((eq prefer 'future) (if (= cday n1) n1 n2))
17191 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17192 (cond
17193 ((eq prefer 'past) (if (= cday n2) n2 n1))
17194 ((eq prefer 'future) (if (= cday n1) n1 n2))
17195 (t (if (= cday n1) n1 n2)))))))
17197 (defun org-date-to-gregorian (date)
17198 "Turn any specification of DATE into a Gregorian date for the calendar."
17199 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17200 ((and (listp date) (= (length date) 3)) date)
17201 ((stringp date)
17202 (setq date (org-parse-time-string date))
17203 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17204 ((listp date)
17205 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17207 (defun org-parse-time-string (s &optional nodefault)
17208 "Parse the standard Org-mode time string.
17209 This should be a lot faster than the normal `parse-time-string'.
17210 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17211 hour and minute fields will be nil if not given."
17212 (cond ((string-match org-ts-regexp0 s)
17213 (list 0
17214 (if (or (match-beginning 8) (not nodefault))
17215 (string-to-number (or (match-string 8 s) "0")))
17216 (if (or (match-beginning 7) (not nodefault))
17217 (string-to-number (or (match-string 7 s) "0")))
17218 (string-to-number (match-string 4 s))
17219 (string-to-number (match-string 3 s))
17220 (string-to-number (match-string 2 s))
17221 nil nil nil))
17222 ((string-match "^<[^>]+>$" s)
17223 (decode-time (seconds-to-time (org-matcher-time s))))
17224 (t (error "Not a standard Org-mode time string: %s" s))))
17226 (defun org-timestamp-up (&optional arg)
17227 "Increase the date item at the cursor by one.
17228 If the cursor is on the year, change the year. If it is on the month,
17229 the day or the time, change that.
17230 With prefix ARG, change by that many units."
17231 (interactive "p")
17232 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17234 (defun org-timestamp-down (&optional arg)
17235 "Decrease the date item at the cursor by one.
17236 If the cursor is on the year, change the year. If it is on the month,
17237 the day or the time, change that.
17238 With prefix ARG, change by that many units."
17239 (interactive "p")
17240 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17242 (defun org-timestamp-up-day (&optional arg)
17243 "Increase the date in the time stamp by one day.
17244 With prefix ARG, change that many days."
17245 (interactive "p")
17246 (if (and (not (org-at-timestamp-p t))
17247 (org-at-heading-p))
17248 (org-todo 'up)
17249 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17251 (defun org-timestamp-down-day (&optional arg)
17252 "Decrease the date in the time stamp by one day.
17253 With prefix ARG, change that many days."
17254 (interactive "p")
17255 (if (and (not (org-at-timestamp-p t))
17256 (org-at-heading-p))
17257 (org-todo 'down)
17258 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17260 (defun org-at-timestamp-p (&optional inactive-ok)
17261 "Determine if the cursor is in or at a timestamp."
17262 (interactive)
17263 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17264 (pos (point))
17265 (ans (or (looking-at tsr)
17266 (save-excursion
17267 (skip-chars-backward "^[<\n\r\t")
17268 (if (> (point) (point-min)) (backward-char 1))
17269 (and (looking-at tsr)
17270 (> (- (match-end 0) pos) -1))))))
17271 (and ans
17272 (boundp 'org-ts-what)
17273 (setq org-ts-what
17274 (cond
17275 ((= pos (match-beginning 0)) 'bracket)
17276 ;; Point is considered to be "on the bracket" whether
17277 ;; it's really on it or right after it.
17278 ((= pos (1- (match-end 0))) 'bracket)
17279 ((= pos (match-end 0)) 'after)
17280 ((org-pos-in-match-range pos 2) 'year)
17281 ((org-pos-in-match-range pos 3) 'month)
17282 ((org-pos-in-match-range pos 7) 'hour)
17283 ((org-pos-in-match-range pos 8) 'minute)
17284 ((or (org-pos-in-match-range pos 4)
17285 (org-pos-in-match-range pos 5)) 'day)
17286 ((and (> pos (or (match-end 8) (match-end 5)))
17287 (< pos (match-end 0)))
17288 (- pos (or (match-end 8) (match-end 5))))
17289 (t 'day))))
17290 ans))
17292 (defun org-toggle-timestamp-type ()
17293 "Toggle the type (<active> or [inactive]) of a time stamp."
17294 (interactive)
17295 (when (org-at-timestamp-p t)
17296 (let ((beg (match-beginning 0)) (end (match-end 0))
17297 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17298 (save-excursion
17299 (goto-char beg)
17300 (while (re-search-forward "[][<>]" end t)
17301 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17302 t t)))
17303 (message "Timestamp is now %sactive"
17304 (if (equal (char-after beg) ?<) "" "in")))))
17306 (defun org-at-clock-log-p nil
17307 "Is the cursor on the clock log line?"
17308 (save-excursion
17309 (move-beginning-of-line 1)
17310 (looking-at "^[ \t]*CLOCK:")))
17312 (defvar org-clock-history) ; defined in org-clock.el
17313 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17314 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17315 "Change the date in the time stamp at point.
17316 The date will be changed by N times WHAT. WHAT can be `day', `month',
17317 `year', `minute', `second'. If WHAT is not given, the cursor position
17318 in the timestamp determines what will be changed.
17319 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17320 (let ((origin (point)) origin-cat
17321 with-hm inactive
17322 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17323 org-ts-what
17324 extra rem
17325 ts time time0 fixnext clrgx)
17326 (if (not (org-at-timestamp-p t))
17327 (user-error "Not at a timestamp"))
17328 (if (and (not what) (eq org-ts-what 'bracket))
17329 (org-toggle-timestamp-type)
17330 ;; Point isn't on brackets. Remember the part of the time-stamp
17331 ;; the point was in. Indeed, size of time-stamps may change,
17332 ;; but point must be kept in the same category nonetheless.
17333 (setq origin-cat org-ts-what)
17334 (if (and (not what) (not (eq org-ts-what 'day))
17335 org-display-custom-times
17336 (get-text-property (point) 'display)
17337 (not (get-text-property (1- (point)) 'display)))
17338 (setq org-ts-what 'day))
17339 (setq org-ts-what (or what org-ts-what)
17340 inactive (= (char-after (match-beginning 0)) ?\[)
17341 ts (match-string 0))
17342 (replace-match "")
17343 (when (string-match
17344 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17346 (setq extra (match-string 1 ts))
17347 (if suppress-tmp-delay
17348 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17349 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17350 (setq with-hm t))
17351 (setq time0 (org-parse-time-string ts))
17352 (when (and updown
17353 (eq org-ts-what 'minute)
17354 (not current-prefix-arg))
17355 ;; This looks like s-up and s-down. Change by one rounding step.
17356 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17357 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17358 (setcar (cdr time0) (+ (nth 1 time0)
17359 (if (> n 0) (- rem) (- dm rem))))))
17360 (setq time
17361 (encode-time (or (car time0) 0)
17362 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17363 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17364 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17365 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17366 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17367 (nthcdr 6 time0)))
17368 (when (and (member org-ts-what '(hour minute))
17369 extra
17370 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17371 (setq extra (org-modify-ts-extra
17372 extra
17373 (if (eq org-ts-what 'hour) 2 5)
17374 n dm)))
17375 (when (integerp org-ts-what)
17376 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17377 (if (eq what 'calendar)
17378 (let ((cal-date (org-get-date-from-calendar)))
17379 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17380 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17381 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17382 (setcar time0 (or (car time0) 0))
17383 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17384 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17385 (setq time (apply 'encode-time time0))))
17386 ;; Insert the new time-stamp, and ensure point stays in the same
17387 ;; category as before (i.e. not after the last position in that
17388 ;; category).
17389 (let ((pos (point)))
17390 ;; Stay before inserted string. `save-excursion' is of no use.
17391 (setq org-last-changed-timestamp
17392 (org-insert-time-stamp time with-hm inactive nil nil extra))
17393 (goto-char pos))
17394 (save-match-data
17395 (looking-at org-ts-regexp3)
17396 (goto-char (cond
17397 ;; `day' category ends before `hour' if any, or at
17398 ;; the end of the day name.
17399 ((eq origin-cat 'day)
17400 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17401 ((eq origin-cat 'hour) (min (match-end 7) origin))
17402 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17403 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17404 ;; `year' and `month' have both fixed size: point
17405 ;; couldn't have moved into another part.
17406 (t origin))))
17407 ;; Update clock if on a CLOCK line.
17408 (org-clock-update-time-maybe)
17409 ;; Maybe adjust the closest clock in `org-clock-history'
17410 (when org-clock-adjust-closest
17411 (if (not (and (org-at-clock-log-p)
17412 (< 1 (length (delq nil (mapcar 'marker-position
17413 org-clock-history))))))
17414 (message "No clock to adjust")
17415 (cond ((save-excursion ; fix previous clock?
17416 (re-search-backward org-ts-regexp0 nil t)
17417 (org-looking-back (concat org-clock-string " \\[")))
17418 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17419 ((save-excursion ; fix next clock?
17420 (re-search-backward org-ts-regexp0 nil t)
17421 (looking-at (concat org-ts-regexp0 "\\] =>")))
17422 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17423 (save-window-excursion
17424 ;; Find closest clock to point, adjust the previous/next one in history
17425 (let* ((p (save-excursion (org-back-to-heading t)))
17426 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17427 (clfixnth
17428 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17429 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17430 (if (not clfixpos)
17431 (message "No clock to adjust")
17432 (save-excursion
17433 (org-goto-marker-or-bmk clfixpos)
17434 (org-show-subtree)
17435 (when (re-search-forward clrgx nil t)
17436 (goto-char (match-beginning 1))
17437 (let (org-clock-adjust-closest)
17438 (org-timestamp-change n org-ts-what updown))
17439 (message "Clock adjusted in %s for heading: %s"
17440 (file-name-nondirectory (buffer-file-name))
17441 (org-get-heading t t)))))))))
17442 ;; Try to recenter the calendar window, if any.
17443 (if (and org-calendar-follow-timestamp-change
17444 (get-buffer-window "*Calendar*" t)
17445 (memq org-ts-what '(day month year)))
17446 (org-recenter-calendar (time-to-days time))))))
17448 (defun org-modify-ts-extra (s pos n dm)
17449 "Change the different parts of the lead-time and repeat fields in timestamp."
17450 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17451 ng h m new rem)
17452 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17453 (cond
17454 ((or (org-pos-in-match-range pos 2)
17455 (org-pos-in-match-range pos 3))
17456 (setq m (string-to-number (match-string 3 s))
17457 h (string-to-number (match-string 2 s)))
17458 (if (org-pos-in-match-range pos 2)
17459 (setq h (+ h n))
17460 (setq n (* dm (org-no-warnings (signum n))))
17461 (when (not (= 0 (setq rem (% m dm))))
17462 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17463 (setq m (+ m n)))
17464 (if (< m 0) (setq m (+ m 60) h (1- h)))
17465 (if (> m 59) (setq m (- m 60) h (1+ h)))
17466 (setq h (min 24 (max 0 h)))
17467 (setq ng 1 new (format "-%02d:%02d" h m)))
17468 ((org-pos-in-match-range pos 6)
17469 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17470 ((org-pos-in-match-range pos 5)
17471 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17473 ((org-pos-in-match-range pos 9)
17474 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17475 ((org-pos-in-match-range pos 8)
17476 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17478 (when ng
17479 (setq s (concat
17480 (substring s 0 (match-beginning ng))
17482 (substring s (match-end ng))))))
17485 (defun org-recenter-calendar (date)
17486 "If the calendar is visible, recenter it to DATE."
17487 (let ((cwin (get-buffer-window "*Calendar*" t)))
17488 (when cwin
17489 (let ((calendar-move-hook nil))
17490 (with-selected-window cwin
17491 (calendar-goto-date (if (listp date) date
17492 (calendar-gregorian-from-absolute date))))))))
17494 (defun org-goto-calendar (&optional arg)
17495 "Go to the Emacs calendar at the current date.
17496 If there is a time stamp in the current line, go to that date.
17497 A prefix ARG can be used to force the current date."
17498 (interactive "P")
17499 (let ((tsr org-ts-regexp) diff
17500 (calendar-move-hook nil)
17501 (calendar-view-holidays-initially-flag nil)
17502 (calendar-view-diary-initially-flag nil))
17503 (if (or (org-at-timestamp-p)
17504 (save-excursion
17505 (beginning-of-line 1)
17506 (looking-at (concat ".*" tsr))))
17507 (let ((d1 (time-to-days (current-time)))
17508 (d2 (time-to-days
17509 (org-time-string-to-time (match-string 1)))))
17510 (setq diff (- d2 d1))))
17511 (calendar)
17512 (calendar-goto-today)
17513 (if (and diff (not arg)) (calendar-forward-day diff))))
17515 (defun org-get-date-from-calendar ()
17516 "Return a list (month day year) of date at point in calendar."
17517 (with-current-buffer "*Calendar*"
17518 (save-match-data
17519 (calendar-cursor-to-date))))
17521 (defun org-date-from-calendar ()
17522 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17523 If there is already a time stamp at the cursor position, update it."
17524 (interactive)
17525 (if (org-at-timestamp-p t)
17526 (org-timestamp-change 0 'calendar)
17527 (let ((cal-date (org-get-date-from-calendar)))
17528 (org-insert-time-stamp
17529 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17531 (defcustom org-effort-durations
17532 `(("h" . 60)
17533 ("d" . ,(* 60 8))
17534 ("w" . ,(* 60 8 5))
17535 ("m" . ,(* 60 8 5 4))
17536 ("y" . ,(* 60 8 5 40)))
17537 "Conversion factor to minutes for an effort modifier.
17539 Each entry has the form (MODIFIER . MINUTES).
17541 In an effort string, a number followed by MODIFIER is multiplied
17542 by the specified number of MINUTES to obtain an effort in
17543 minutes.
17545 For example, if the value of this variable is ((\"hours\" . 60)), then an
17546 effort string \"2hours\" is equivalent to 120 minutes."
17547 :group 'org-agenda
17548 :version "24.1"
17549 :type '(alist :key-type (string :tag "Modifier")
17550 :value-type (number :tag "Minutes")))
17552 (defun org-minutes-to-clocksum-string (m)
17553 "Format number of minutes as a clocksum string.
17554 The format is determined by `org-time-clocksum-format',
17555 `org-time-clocksum-use-fractional' and
17556 `org-time-clocksum-fractional-format' and
17557 `org-time-clocksum-use-effort-durations'."
17558 (let ((clocksum "")
17559 (m (round m)) ; Don't allow fractions of minutes
17560 h d w mo y fmt n)
17561 (setq h (if org-time-clocksum-use-effort-durations
17562 (cdr (assoc "h" org-effort-durations)) 60)
17563 d (if org-time-clocksum-use-effort-durations
17564 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17565 w (if org-time-clocksum-use-effort-durations
17566 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17567 mo (if org-time-clocksum-use-effort-durations
17568 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17569 y (if org-time-clocksum-use-effort-durations
17570 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17571 ;; fractional format
17572 (if org-time-clocksum-use-fractional
17573 (cond
17574 ;; single format string
17575 ((stringp org-time-clocksum-fractional-format)
17576 (format org-time-clocksum-fractional-format (/ m (float h))))
17577 ;; choice of fractional formats for different time units
17578 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17579 (> (/ (truncate m) (* y d h)) 0))
17580 (format fmt (/ m (* y d (float h)))))
17581 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17582 (> (/ (truncate m) (* mo d h)) 0))
17583 (format fmt (/ m (* mo d (float h)))))
17584 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17585 (> (/ (truncate m) (* w d h)) 0))
17586 (format fmt (/ m (* w d (float h)))))
17587 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17588 (> (/ (truncate m) (* d h)) 0))
17589 (format fmt (/ m (* d (float h)))))
17590 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17591 (> (/ (truncate m) h) 0))
17592 (format fmt (/ m (float h))))
17593 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17594 (format fmt m))
17595 ;; fall back to smallest time unit with a format
17596 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17597 (format fmt (/ m (float h))))
17598 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17599 (format fmt (/ m (* d (float h)))))
17600 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17601 (format fmt (/ m (* w d (float h)))))
17602 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17603 (format fmt (/ m (* mo d (float h)))))
17604 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17605 (format fmt (/ m (* y d (float h))))))
17606 ;; standard (non-fractional) format, with single format string
17607 (if (stringp org-time-clocksum-format)
17608 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17609 ;; separate formats components
17610 (and (setq fmt (plist-get org-time-clocksum-format :years))
17611 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17612 (plist-get org-time-clocksum-format :require-years))
17613 (setq clocksum (concat clocksum (format fmt n))
17614 m (- m (* n y d h))))
17615 (and (setq fmt (plist-get org-time-clocksum-format :months))
17616 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17617 (plist-get org-time-clocksum-format :require-months))
17618 (setq clocksum (concat clocksum (format fmt n))
17619 m (- m (* n mo d h))))
17620 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17621 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17622 (plist-get org-time-clocksum-format :require-weeks))
17623 (setq clocksum (concat clocksum (format fmt n))
17624 m (- m (* n w d h))))
17625 (and (setq fmt (plist-get org-time-clocksum-format :days))
17626 (or (> (setq n (/ (truncate m) (* d h))) 0)
17627 (plist-get org-time-clocksum-format :require-days))
17628 (setq clocksum (concat clocksum (format fmt n))
17629 m (- m (* n d h))))
17630 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17631 (or (> (setq n (/ (truncate m) h)) 0)
17632 (plist-get org-time-clocksum-format :require-hours))
17633 (setq clocksum (concat clocksum (format fmt n))
17634 m (- m (* n h))))
17635 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17636 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17637 (setq clocksum (concat clocksum (format fmt m))))
17638 ;; return formatted time duration
17639 clocksum))))
17641 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17642 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17643 "Org mode version 8.0")
17645 (defun org-hours-to-clocksum-string (n)
17646 (org-minutes-to-clocksum-string (* n 60)))
17648 (defun org-hh:mm-string-to-minutes (s)
17649 "Convert a string H:MM to a number of minutes.
17650 If the string is just a number, interpret it as minutes.
17651 In fact, the first hh:mm or number in the string will be taken,
17652 there can be extra stuff in the string.
17653 If no number is found, the return value is 0."
17654 (cond
17655 ((integerp s) s)
17656 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17657 (+ (* (string-to-number (match-string 1 s)) 60)
17658 (string-to-number (match-string 2 s))))
17659 ((string-match "\\([0-9]+\\)" s)
17660 (string-to-number (match-string 1 s)))
17661 (t 0)))
17663 (defcustom org-image-actual-width t
17664 "Should we use the actual width of images when inlining them?
17666 When set to `t', always use the image width.
17668 When set to a number, use imagemagick (when available) to set
17669 the image's width to this value.
17671 When set to a number in a list, try to get the width from any
17672 #+ATTR.* keyword if it matches a width specification like
17674 #+ATTR_HTML: :width 300px
17676 and fall back on that number if none is found.
17678 When set to nil, try to get the width from an #+ATTR.* keyword
17679 and fall back on the original width if none is found.
17681 This requires Emacs >= 24.1, build with imagemagick support."
17682 :group 'org-appearance
17683 :version "24.4"
17684 :package-version '(Org . "8.0")
17685 :type '(choice
17686 (const :tag "Use the image width" t)
17687 (integer :tag "Use a number of pixels")
17688 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17689 (const :tag "Use #+ATTR* or don't resize" nil)))
17691 (defcustom org-agenda-inhibit-startup nil
17692 "Inhibit startup when preparing agenda buffers.
17693 When this variable is `t' (the default), the initialization of
17694 the Org agenda buffers is inhibited: e.g. the visibility state
17695 is not set, the tables are not re-aligned, etc."
17696 :type 'boolean
17697 :version "24.3"
17698 :group 'org-agenda)
17700 (defcustom org-agenda-ignore-drawer-properties nil
17701 "Avoid updating text properties when building the agenda.
17702 Properties are used to prepare buffers for effort estimates, appointments,
17703 and subtree-local categories.
17704 If you don't use these in the agenda, you can add them to this list and
17705 agenda building will be a bit faster.
17706 The value is a list, with zero or more of the symbols `effort', `appt',
17707 or `category'."
17708 :type '(set :greedy t
17709 (const effort)
17710 (const appt)
17711 (const category))
17712 :version "24.3"
17713 :group 'org-agenda)
17715 (defun org-duration-string-to-minutes (s &optional output-to-string)
17716 "Convert a duration string S to minutes.
17718 A bare number is interpreted as minutes, modifiers can be set by
17719 customizing `org-effort-durations' (which see).
17721 Entries containing a colon are interpreted as H:MM by
17722 `org-hh:mm-string-to-minutes'."
17723 (let ((result 0)
17724 (re (concat "\\([0-9.]+\\) *\\("
17725 (regexp-opt (mapcar 'car org-effort-durations))
17726 "\\)")))
17727 (while (string-match re s)
17728 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17729 (string-to-number (match-string 1 s))))
17730 (setq s (replace-match "" nil t s)))
17731 (setq result (floor result))
17732 (incf result (org-hh:mm-string-to-minutes s))
17733 (if output-to-string (number-to-string result) result)))
17735 ;;;; Files
17737 (defun org-save-all-org-buffers ()
17738 "Save all Org-mode buffers without user confirmation."
17739 (interactive)
17740 (message "Saving all Org-mode buffers...")
17741 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17742 (when (featurep 'org-id) (org-id-locations-save))
17743 (message "Saving all Org-mode buffers... done"))
17745 (defun org-revert-all-org-buffers ()
17746 "Revert all Org-mode buffers.
17747 Prompt for confirmation when there are unsaved changes.
17748 Be sure you know what you are doing before letting this function
17749 overwrite your changes.
17751 This function is useful in a setup where one tracks org files
17752 with a version control system, to revert on one machine after pulling
17753 changes from another. I believe the procedure must be like this:
17755 1. M-x org-save-all-org-buffers
17756 2. Pull changes from the other machine, resolve conflicts
17757 3. M-x org-revert-all-org-buffers"
17758 (interactive)
17759 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17760 (user-error "Abort"))
17761 (save-excursion
17762 (save-window-excursion
17763 (mapc
17764 (lambda (b)
17765 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17766 (with-current-buffer b buffer-file-name))
17767 (org-pop-to-buffer-same-window b)
17768 (revert-buffer t 'no-confirm)))
17769 (buffer-list))
17770 (when (and (featurep 'org-id) org-id-track-globally)
17771 (org-id-locations-load)))))
17773 ;;;; Agenda files
17775 ;;;###autoload
17776 (defun org-switchb (&optional arg)
17777 "Switch between Org buffers.
17778 With one prefix argument, restrict available buffers to files.
17779 With two prefix arguments, restrict available buffers to agenda files.
17781 Defaults to `iswitchb' for buffer name completion.
17782 Set `org-completion-use-ido' to make it use ido instead."
17783 (interactive "P")
17784 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17785 ((equal arg '(16)) (org-buffer-list 'agenda))
17786 (t (org-buffer-list))))
17787 (org-completion-use-iswitchb org-completion-use-iswitchb)
17788 (org-completion-use-ido org-completion-use-ido))
17789 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17790 (setq org-completion-use-iswitchb t))
17791 (org-pop-to-buffer-same-window
17792 (org-icompleting-read "Org buffer: "
17793 (mapcar 'list (mapcar 'buffer-name blist))
17794 nil t))))
17796 ;;; Define some older names previously used for this functionality
17797 ;;;###autoload
17798 (defalias 'org-ido-switchb 'org-switchb)
17799 ;;;###autoload
17800 (defalias 'org-iswitchb 'org-switchb)
17802 (defun org-buffer-list (&optional predicate exclude-tmp)
17803 "Return a list of Org buffers.
17804 PREDICATE can be `export', `files' or `agenda'.
17806 export restrict the list to Export buffers.
17807 files restrict the list to buffers visiting Org files.
17808 agenda restrict the list to buffers visiting agenda files.
17810 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17811 (let* ((bfn nil)
17812 (agenda-files (and (eq predicate 'agenda)
17813 (mapcar 'file-truename (org-agenda-files t))))
17814 (filter
17815 (cond
17816 ((eq predicate 'files)
17817 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17818 ((eq predicate 'export)
17819 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17820 ((eq predicate 'agenda)
17821 (lambda (b)
17822 (with-current-buffer b
17823 (and (derived-mode-p 'org-mode)
17824 (setq bfn (buffer-file-name b))
17825 (member (file-truename bfn) agenda-files)))))
17826 (t (lambda (b) (with-current-buffer b
17827 (or (derived-mode-p 'org-mode)
17828 (string-match "\*Org .*Export"
17829 (buffer-name b)))))))))
17830 (delq nil
17831 (mapcar
17832 (lambda(b)
17833 (if (and (funcall filter b)
17834 (or (not exclude-tmp)
17835 (not (string-match "tmp" (buffer-name b)))))
17837 nil))
17838 (buffer-list)))))
17840 (defun org-agenda-files (&optional unrestricted archives)
17841 "Get the list of agenda files.
17842 Optional UNRESTRICTED means return the full list even if a restriction
17843 is currently in place.
17844 When ARCHIVES is t, include all archive files that are really being
17845 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17846 `org-agenda-archives-mode' is t."
17847 (let ((files
17848 (cond
17849 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17850 ((stringp org-agenda-files) (org-read-agenda-file-list))
17851 ((listp org-agenda-files) org-agenda-files)
17852 (t (error "Invalid value of `org-agenda-files'")))))
17853 (setq files (apply 'append
17854 (mapcar (lambda (f)
17855 (if (file-directory-p f)
17856 (directory-files
17857 f t org-agenda-file-regexp)
17858 (list f)))
17859 files)))
17860 (when org-agenda-skip-unavailable-files
17861 (setq files (delq nil
17862 (mapcar (function
17863 (lambda (file)
17864 (and (file-readable-p file) file)))
17865 files))))
17866 (when (or (eq archives t)
17867 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17868 (setq files (org-add-archive-files files)))
17869 files))
17871 (defun org-agenda-file-p (&optional file)
17872 "Return non-nil, if FILE is an agenda file.
17873 If FILE is omitted, use the file associated with the current
17874 buffer."
17875 (member (or file (buffer-file-name))
17876 (org-agenda-files t)))
17878 (defun org-edit-agenda-file-list ()
17879 "Edit the list of agenda files.
17880 Depending on setup, this either uses customize to edit the variable
17881 `org-agenda-files', or it visits the file that is holding the list. In the
17882 latter case, the buffer is set up in a way that saving it automatically kills
17883 the buffer and restores the previous window configuration."
17884 (interactive)
17885 (if (stringp org-agenda-files)
17886 (let ((cw (current-window-configuration)))
17887 (find-file org-agenda-files)
17888 (org-set-local 'org-window-configuration cw)
17889 (org-add-hook 'after-save-hook
17890 (lambda ()
17891 (set-window-configuration
17892 (prog1 org-window-configuration
17893 (kill-buffer (current-buffer))))
17894 (org-install-agenda-files-menu)
17895 (message "New agenda file list installed"))
17896 nil 'local)
17897 (message "%s" (substitute-command-keys
17898 "Edit list and finish with \\[save-buffer]")))
17899 (customize-variable 'org-agenda-files)))
17901 (defun org-store-new-agenda-file-list (list)
17902 "Set new value for the agenda file list and save it correctly."
17903 (if (stringp org-agenda-files)
17904 (let ((fe (org-read-agenda-file-list t)) b u)
17905 (while (setq b (find-buffer-visiting org-agenda-files))
17906 (kill-buffer b))
17907 (with-temp-file org-agenda-files
17908 (insert
17909 (mapconcat
17910 (lambda (f) ;; Keep un-expanded entries.
17911 (if (setq u (assoc f fe))
17912 (cdr u)
17914 list "\n")
17915 "\n")))
17916 (let ((org-mode-hook nil) (org-inhibit-startup t)
17917 (org-insert-mode-line-in-empty-file nil))
17918 (setq org-agenda-files list)
17919 (customize-save-variable 'org-agenda-files org-agenda-files))))
17921 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17922 "Read the list of agenda files from a file.
17923 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17924 filenames, used by `org-store-new-agenda-file-list' to write back
17925 un-expanded file names."
17926 (when (file-directory-p org-agenda-files)
17927 (error "`org-agenda-files' cannot be a single directory"))
17928 (when (stringp org-agenda-files)
17929 (with-temp-buffer
17930 (insert-file-contents org-agenda-files)
17931 (mapcar
17932 (lambda (f)
17933 (let ((e (expand-file-name (substitute-in-file-name f)
17934 org-directory)))
17935 (if pair-with-expansion
17936 (cons e f)
17937 e)))
17938 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17940 ;;;###autoload
17941 (defun org-cycle-agenda-files ()
17942 "Cycle through the files in `org-agenda-files'.
17943 If the current buffer visits an agenda file, find the next one in the list.
17944 If the current buffer does not, find the first agenda file."
17945 (interactive)
17946 (let* ((fs (org-agenda-files t))
17947 (files (append fs (list (car fs))))
17948 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17949 file)
17950 (unless files (user-error "No agenda files"))
17951 (catch 'exit
17952 (while (setq file (pop files))
17953 (if (equal (file-truename file) tcf)
17954 (when (car files)
17955 (find-file (car files))
17956 (throw 'exit t))))
17957 (find-file (car fs)))
17958 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17960 (defun org-agenda-file-to-front (&optional to-end)
17961 "Move/add the current file to the top of the agenda file list.
17962 If the file is not present in the list, it is added to the front. If it is
17963 present, it is moved there. With optional argument TO-END, add/move to the
17964 end of the list."
17965 (interactive "P")
17966 (let ((org-agenda-skip-unavailable-files nil)
17967 (file-alist (mapcar (lambda (x)
17968 (cons (file-truename x) x))
17969 (org-agenda-files t)))
17970 (ctf (file-truename
17971 (or buffer-file-name
17972 (user-error "Please save the current buffer to a file"))))
17973 x had)
17974 (setq x (assoc ctf file-alist) had x)
17976 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17977 (if to-end
17978 (setq file-alist (append (delq x file-alist) (list x)))
17979 (setq file-alist (cons x (delq x file-alist))))
17980 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17981 (org-install-agenda-files-menu)
17982 (message "File %s to %s of agenda file list"
17983 (if had "moved" "added") (if to-end "end" "front"))))
17985 (defun org-remove-file (&optional file)
17986 "Remove current file from the list of files in variable `org-agenda-files'.
17987 These are the files which are being checked for agenda entries.
17988 Optional argument FILE means use this file instead of the current."
17989 (interactive)
17990 (let* ((org-agenda-skip-unavailable-files nil)
17991 (file (or file buffer-file-name
17992 (user-error "Current buffer does not visit a file")))
17993 (true-file (file-truename file))
17994 (afile (abbreviate-file-name file))
17995 (files (delq nil (mapcar
17996 (lambda (x)
17997 (if (equal true-file
17998 (file-truename x))
17999 nil x))
18000 (org-agenda-files t)))))
18001 (if (not (= (length files) (length (org-agenda-files t))))
18002 (progn
18003 (org-store-new-agenda-file-list files)
18004 (org-install-agenda-files-menu)
18005 (message "Removed file: %s" afile))
18006 (message "File was not in list: %s (not removed)" afile))))
18008 (defun org-file-menu-entry (file)
18009 (vector file (list 'find-file file) t))
18011 (defun org-check-agenda-file (file)
18012 "Make sure FILE exists. If not, ask user what to do."
18013 (when (not (file-exists-p file))
18014 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18015 (abbreviate-file-name file))
18016 (let ((r (downcase (read-char-exclusive))))
18017 (cond
18018 ((equal r ?r)
18019 (org-remove-file file)
18020 (throw 'nextfile t))
18021 (t (error "Abort"))))))
18023 (defun org-get-agenda-file-buffer (file)
18024 "Get a buffer visiting FILE. If the buffer needs to be created, add
18025 it to the list of buffers which might be released later."
18026 (let ((buf (org-find-base-buffer-visiting file)))
18027 (if buf
18028 buf ; just return it
18029 ;; Make a new buffer and remember it
18030 (setq buf (find-file-noselect file))
18031 (if buf (push buf org-agenda-new-buffers))
18032 buf)))
18034 (defun org-release-buffers (blist)
18035 "Release all buffers in list, asking the user for confirmation when needed.
18036 When a buffer is unmodified, it is just killed. When modified, it is saved
18037 \(if the user agrees) and then killed."
18038 (let (buf file)
18039 (while (setq buf (pop blist))
18040 (setq file (buffer-file-name buf))
18041 (when (and (buffer-modified-p buf)
18042 file
18043 (y-or-n-p (format "Save file %s? " file)))
18044 (with-current-buffer buf (save-buffer)))
18045 (kill-buffer buf))))
18047 (defun org-agenda-prepare-buffers (files)
18048 "Create buffers for all agenda files, protect archived trees and comments."
18049 (interactive)
18050 (let ((pa '(:org-archived t))
18051 (pc '(:org-comment t))
18052 (pall '(:org-archived t :org-comment t))
18053 (inhibit-read-only t)
18054 (org-inhibit-startup org-agenda-inhibit-startup)
18055 (rea (concat ":" org-archive-tag ":"))
18056 file re pos)
18057 (setq org-tag-alist-for-agenda nil
18058 org-tag-groups-alist-for-agenda nil)
18059 (save-window-excursion
18060 (save-restriction
18061 (while (setq file (pop files))
18062 (catch 'nextfile
18063 (if (bufferp file)
18064 (set-buffer file)
18065 (org-check-agenda-file file)
18066 (set-buffer (org-get-agenda-file-buffer file)))
18067 (widen)
18068 (org-set-regexps-and-options-for-tags)
18069 (setq pos (point))
18070 (goto-char (point-min))
18071 (let ((case-fold-search t))
18072 (when (search-forward "#+setupfile" nil t)
18073 ;; Don't set all regexps and options systematically as
18074 ;; this is only run for setting agenda tags from setup
18075 ;; file
18076 (org-set-regexps-and-options)))
18077 (or (memq 'category org-agenda-ignore-drawer-properties)
18078 (org-refresh-category-properties))
18079 (or (memq 'effort org-agenda-ignore-drawer-properties)
18080 (org-refresh-properties org-effort-property 'org-effort))
18081 (or (memq 'appt org-agenda-ignore-drawer-properties)
18082 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18083 (setq org-todo-keywords-for-agenda
18084 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18085 (setq org-done-keywords-for-agenda
18086 (append org-done-keywords-for-agenda org-done-keywords))
18087 (setq org-todo-keyword-alist-for-agenda
18088 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18089 (setq org-drawers-for-agenda
18090 (append org-drawers-for-agenda org-drawers))
18091 (setq org-tag-alist-for-agenda
18092 (org-uniquify
18093 (append org-tag-alist-for-agenda
18094 org-tag-alist
18095 org-tag-persistent-alist)))
18096 (if org-group-tags
18097 (setq org-tag-groups-alist-for-agenda
18098 (org-uniquify-alist
18099 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18100 (org-with-silent-modifications
18101 (save-excursion
18102 (remove-text-properties (point-min) (point-max) pall)
18103 (when org-agenda-skip-archived-trees
18104 (goto-char (point-min))
18105 (while (re-search-forward rea nil t)
18106 (if (org-at-heading-p t)
18107 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18108 (goto-char (point-min))
18109 (setq re (format org-heading-keyword-regexp-format
18110 org-comment-string))
18111 (while (re-search-forward re nil t)
18112 (add-text-properties
18113 (match-beginning 0) (org-end-of-subtree t) pc))))
18114 (goto-char pos)))))
18115 (setq org-todo-keywords-for-agenda
18116 (org-uniquify org-todo-keywords-for-agenda))
18117 (setq org-todo-keyword-alist-for-agenda
18118 (org-uniquify org-todo-keyword-alist-for-agenda))))
18121 ;;;; CDLaTeX minor mode
18123 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18124 "Keymap for the minor `org-cdlatex-mode'.")
18126 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18127 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18128 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18129 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18130 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18132 (defvar org-cdlatex-texmathp-advice-is-done nil
18133 "Flag remembering if we have applied the advice to texmathp already.")
18135 (define-minor-mode org-cdlatex-mode
18136 "Toggle the minor `org-cdlatex-mode'.
18137 This mode supports entering LaTeX environment and math in LaTeX fragments
18138 in Org-mode.
18139 \\{org-cdlatex-mode-map}"
18140 nil " OCDL" nil
18141 (when org-cdlatex-mode
18142 (require 'cdlatex)
18143 (run-hooks 'cdlatex-mode-hook)
18144 (cdlatex-compute-tables))
18145 (unless org-cdlatex-texmathp-advice-is-done
18146 (setq org-cdlatex-texmathp-advice-is-done t)
18147 (defadvice texmathp (around org-math-always-on activate)
18148 "Always return t in org-mode buffers.
18149 This is because we want to insert math symbols without dollars even outside
18150 the LaTeX math segments. If Orgmode thinks that point is actually inside
18151 an embedded LaTeX fragment, let texmathp do its job.
18152 \\[org-cdlatex-mode-map]"
18153 (interactive)
18154 (let (p)
18155 (cond
18156 ((not (derived-mode-p 'org-mode)) ad-do-it)
18157 ((eq this-command 'cdlatex-math-symbol)
18158 (setq ad-return-value t
18159 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18161 (let ((p (org-inside-LaTeX-fragment-p)))
18162 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18163 (setq ad-return-value t
18164 texmathp-why '("Org-mode embedded math" . 0))
18165 (if p ad-do-it)))))))))
18167 (defun turn-on-org-cdlatex ()
18168 "Unconditionally turn on `org-cdlatex-mode'."
18169 (org-cdlatex-mode 1))
18171 (defun org-try-cdlatex-tab ()
18172 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18173 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18174 - inside a LaTeX fragment, or
18175 - after the first word in a line, where an abbreviation expansion could
18176 insert a LaTeX environment."
18177 (when org-cdlatex-mode
18178 (cond
18179 ;; Before any word on the line: No expansion possible.
18180 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18181 ;; Just after first word on the line: Expand it. Make sure it
18182 ;; cannot happen on headlines, though.
18183 ((save-excursion
18184 (skip-chars-backward "a-zA-Z0-9*")
18185 (skip-chars-backward " \t")
18186 (and (bolp) (not (org-at-heading-p))))
18187 (cdlatex-tab) t)
18188 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18190 (defun org-cdlatex-underscore-caret (&optional arg)
18191 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18192 Revert to the normal definition outside of these fragments."
18193 (interactive "P")
18194 (if (org-inside-LaTeX-fragment-p)
18195 (call-interactively 'cdlatex-sub-superscript)
18196 (let (org-cdlatex-mode)
18197 (call-interactively (key-binding (vector last-input-event))))))
18199 (defun org-cdlatex-math-modify (&optional arg)
18200 "Execute `cdlatex-math-modify' in LaTeX fragments.
18201 Revert to the normal definition outside of these fragments."
18202 (interactive "P")
18203 (if (org-inside-LaTeX-fragment-p)
18204 (call-interactively 'cdlatex-math-modify)
18205 (let (org-cdlatex-mode)
18206 (call-interactively (key-binding (vector last-input-event))))))
18210 ;;;; LaTeX fragments
18212 (defvar org-latex-regexps
18213 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18214 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18215 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18216 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18217 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18218 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18219 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18220 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18221 "Regular expressions for matching embedded LaTeX.")
18223 (defun org-inside-LaTeX-fragment-p ()
18224 "Test if point is inside a LaTeX fragment.
18225 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18226 sequence appearing also before point.
18227 Even though the matchers for math are configurable, this function assumes
18228 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18229 delimiters are skipped when they have been removed by customization.
18230 The return value is nil, or a cons cell with the delimiter and the
18231 position of this delimiter.
18233 This function does a reasonably good job, but can locally be fooled by
18234 for example currency specifications. For example it will assume being in
18235 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18236 fragments that are properly closed, but during editing, we have to live
18237 with the uncertainty caused by missing closing delimiters. This function
18238 looks only before point, not after."
18239 (catch 'exit
18240 (let ((pos (point))
18241 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18242 (lim (progn
18243 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18244 (point)))
18245 dd-on str (start 0) m re)
18246 (goto-char pos)
18247 (when dodollar
18248 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18249 re (nth 1 (assoc "$" org-latex-regexps)))
18250 (while (string-match re str start)
18251 (cond
18252 ((= (match-end 0) (length str))
18253 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18254 ((= (match-end 0) (- (length str) 5))
18255 (throw 'exit nil))
18256 (t (setq start (match-end 0))))))
18257 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18258 (goto-char pos)
18259 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18260 (and (match-beginning 2) (throw 'exit nil))
18261 ;; count $$
18262 (while (re-search-backward "\\$\\$" lim t)
18263 (setq dd-on (not dd-on)))
18264 (goto-char pos)
18265 (if dd-on (cons "$$" m))))))
18267 (defun org-inside-latex-macro-p ()
18268 "Is point inside a LaTeX macro or its arguments?"
18269 (save-match-data
18270 (org-in-regexp
18271 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18273 (defvar org-latex-fragment-image-overlays nil
18274 "List of overlays carrying the images of latex fragments.")
18275 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18277 (defun org-remove-latex-fragment-image-overlays ()
18278 "Remove all overlays with LaTeX fragment images in current buffer."
18279 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18280 (setq org-latex-fragment-image-overlays nil))
18282 (defun org-preview-latex-fragment (&optional subtree)
18283 "Preview the LaTeX fragment at point, or all locally or globally.
18284 If the cursor is in a LaTeX fragment, create the image and overlay
18285 it over the source code. If there is no fragment at point, display
18286 all fragments in the current text, from one headline to the next. With
18287 prefix SUBTREE, display all fragments in the current subtree. With a
18288 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18289 the cursor is before the first headline,
18290 display all fragments in the buffer.
18291 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18292 (interactive "P")
18293 (unless buffer-file-name
18294 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18295 (when (display-graphic-p)
18296 (org-remove-latex-fragment-image-overlays)
18297 (save-excursion
18298 (save-restriction
18299 (let (beg end at msg)
18300 (cond
18301 ((or (equal subtree '(16))
18302 (not (save-excursion
18303 (re-search-backward org-outline-regexp-bol nil t))))
18304 (setq beg (point-min) end (point-max)
18305 msg "Creating images for buffer...%s"))
18306 ((equal subtree '(4))
18307 (org-back-to-heading)
18308 (setq beg (point) end (org-end-of-subtree t)
18309 msg "Creating images for subtree...%s"))
18311 (if (setq at (org-inside-LaTeX-fragment-p))
18312 (goto-char (max (point-min) (- (cdr at) 2)))
18313 (org-back-to-heading))
18314 (setq beg (point) end (progn (outline-next-heading) (point))
18315 msg (if at "Creating image...%s"
18316 "Creating images for entry...%s"))))
18317 (message msg "")
18318 (narrow-to-region beg end)
18319 (goto-char beg)
18320 (org-format-latex
18321 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18322 (file-name-nondirectory
18323 buffer-file-name)))
18324 default-directory 'overlays msg at 'forbuffer
18325 org-latex-create-formula-image-program)
18326 (message msg "done. Use `C-c C-c' to remove images."))))))
18328 (defun org-format-latex (prefix &optional dir overlays msg at
18329 forbuffer processing-type)
18330 "Replace LaTeX fragments with links to an image, and produce images.
18331 Some of the options can be changed using the variable
18332 `org-format-latex-options'."
18333 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18334 (let* ((prefixnodir (file-name-nondirectory prefix))
18335 (absprefix (expand-file-name prefix dir))
18336 (todir (file-name-directory absprefix))
18337 (opt org-format-latex-options)
18338 (optnew org-format-latex-options)
18339 (matchers (plist-get opt :matchers))
18340 (re-list org-latex-regexps)
18341 (cnt 0) txt hash link beg end re e checkdir
18342 string
18343 m n block-type block linkfile movefile ov)
18344 ;; Check the different regular expressions
18345 (while (setq e (pop re-list))
18346 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18347 block (if block-type "\n\n" ""))
18348 (when (member m matchers)
18349 (goto-char (point-min))
18350 (while (re-search-forward re nil t)
18351 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18352 (or (not overlays)
18353 (not (eq (get-char-property (match-beginning n)
18354 'org-overlay-type)
18355 'org-latex-overlay))))
18356 (cond
18357 ((eq processing-type 'verbatim))
18358 ((eq processing-type 'mathjax)
18359 ;; Prepare for MathJax processing.
18360 (setq string (match-string n))
18361 (when (member m '("$" "$1"))
18362 (save-excursion
18363 (delete-region (match-beginning n) (match-end n))
18364 (goto-char (match-beginning n))
18365 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18366 ((or (eq processing-type 'dvipng)
18367 (eq processing-type 'imagemagick))
18368 ;; Process to an image.
18369 (setq txt (match-string n)
18370 beg (match-beginning n) end (match-end n)
18371 cnt (1+ cnt))
18372 (let ((face (face-at-point))
18373 (fg (plist-get opt :foreground))
18374 (bg (plist-get opt :background))
18375 ;; Ensure full list is printed.
18376 print-length print-level)
18377 (when forbuffer
18378 ;; Get the colors from the face at point.
18379 (goto-char beg)
18380 (when (eq fg 'auto)
18381 (setq fg (face-attribute face :foreground nil 'default)))
18382 (when (eq bg 'auto)
18383 (setq bg (face-attribute face :background nil 'default)))
18384 (setq optnew (copy-sequence opt))
18385 (plist-put optnew :foreground fg)
18386 (plist-put optnew :background bg))
18387 (setq hash (sha1 (prin1-to-string
18388 (list org-format-latex-header
18389 org-latex-default-packages-alist
18390 org-latex-packages-alist
18391 org-format-latex-options
18392 forbuffer txt fg bg)))
18393 linkfile (format "%s_%s.png" prefix hash)
18394 movefile (format "%s_%s.png" absprefix hash)))
18395 (setq link (concat block "[[file:" linkfile "]]" block))
18396 (if msg (message msg cnt))
18397 (goto-char beg)
18398 (unless checkdir ; Ensure the directory exists.
18399 (setq checkdir t)
18400 (or (file-directory-p todir) (make-directory todir t)))
18401 (unless (file-exists-p movefile)
18402 (org-create-formula-image
18403 txt movefile optnew forbuffer processing-type))
18404 (if overlays
18405 (progn
18406 (mapc (lambda (o)
18407 (if (eq (overlay-get o 'org-overlay-type)
18408 'org-latex-overlay)
18409 (delete-overlay o)))
18410 (overlays-in beg end))
18411 (setq ov (make-overlay beg end))
18412 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18413 (if (featurep 'xemacs)
18414 (progn
18415 (overlay-put ov 'invisible t)
18416 (overlay-put
18417 ov 'end-glyph
18418 (make-glyph (vector 'png :file movefile))))
18419 (overlay-put
18420 ov 'display
18421 (list 'image :type 'png :file movefile :ascent 'center)))
18422 (push ov org-latex-fragment-image-overlays)
18423 (goto-char end))
18424 (delete-region beg end)
18425 (insert (org-add-props link
18426 (list 'org-latex-src
18427 (replace-regexp-in-string
18428 "\"" "" txt)
18429 'org-latex-src-embed-type
18430 (if block-type 'paragraph 'character))))))
18431 ((eq processing-type 'mathml)
18432 ;; Process to MathML
18433 (unless (save-match-data (org-format-latex-mathml-available-p))
18434 (user-error "LaTeX to MathML converter not configured"))
18435 (setq txt (match-string n)
18436 beg (match-beginning n) end (match-end n)
18437 cnt (1+ cnt))
18438 (if msg (message msg cnt))
18439 (goto-char beg)
18440 (delete-region beg end)
18441 (insert (org-format-latex-as-mathml
18442 txt block-type prefix dir)))
18444 (error "Unknown conversion type %s for LaTeX fragments"
18445 processing-type)))))))))
18447 (defun org-create-math-formula (latex-frag &optional mathml-file)
18448 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18449 Use `org-latex-to-mathml-convert-command'. If the conversion is
18450 sucessful, return the portion between \"<math...> </math>\"
18451 elements otherwise return nil. When MATHML-FILE is specified,
18452 write the results in to that file. When invoked as an
18453 interactive command, prompt for LATEX-FRAG, with initial value
18454 set to the current active region and echo the results for user
18455 inspection."
18456 (interactive (list (let ((frag (when (org-region-active-p)
18457 (buffer-substring-no-properties
18458 (region-beginning) (region-end)))))
18459 (read-string "LaTeX Fragment: " frag nil frag))))
18460 (unless latex-frag (error "Invalid LaTeX fragment"))
18461 (let* ((tmp-in-file (file-relative-name
18462 (make-temp-name (expand-file-name "ltxmathml-in"))))
18463 (ignore (write-region latex-frag nil tmp-in-file))
18464 (tmp-out-file (file-relative-name
18465 (make-temp-name (expand-file-name "ltxmathml-out"))))
18466 (cmd (format-spec
18467 org-latex-to-mathml-convert-command
18468 `((?j . ,(shell-quote-argument
18469 (expand-file-name org-latex-to-mathml-jar-file)))
18470 (?I . ,(shell-quote-argument tmp-in-file))
18471 (?o . ,(shell-quote-argument tmp-out-file)))))
18472 mathml shell-command-output)
18473 (when (org-called-interactively-p 'any)
18474 (unless (org-format-latex-mathml-available-p)
18475 (user-error "LaTeX to MathML converter not configured")))
18476 (message "Running %s" cmd)
18477 (setq shell-command-output (shell-command-to-string cmd))
18478 (setq mathml
18479 (when (file-readable-p tmp-out-file)
18480 (with-current-buffer (find-file-noselect tmp-out-file t)
18481 (goto-char (point-min))
18482 (when (re-search-forward
18483 (concat
18484 (regexp-quote
18485 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18486 "\\(.\\|\n\\)*"
18487 (regexp-quote "</math>")) nil t)
18488 (prog1 (match-string 0) (kill-buffer))))))
18489 (cond
18490 (mathml
18491 (setq mathml
18492 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18493 (when mathml-file
18494 (write-region mathml nil mathml-file))
18495 (when (org-called-interactively-p 'any)
18496 (message mathml)))
18497 ((message "LaTeX to MathML conversion failed")
18498 (message shell-command-output)))
18499 (delete-file tmp-in-file)
18500 (when (file-exists-p tmp-out-file)
18501 (delete-file tmp-out-file))
18502 mathml))
18504 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18505 prefix &optional dir)
18506 "Use `org-create-math-formula' but check local cache first."
18507 (let* ((absprefix (expand-file-name prefix dir))
18508 (print-length nil) (print-level nil)
18509 (formula-id (concat
18510 "formula-"
18511 (sha1
18512 (prin1-to-string
18513 (list latex-frag
18514 org-latex-to-mathml-convert-command)))))
18515 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18516 (formula-cache-dir (file-name-directory formula-cache)))
18518 (unless (file-directory-p formula-cache-dir)
18519 (make-directory formula-cache-dir t))
18521 (unless (file-exists-p formula-cache)
18522 (org-create-math-formula latex-frag formula-cache))
18524 (if (file-exists-p formula-cache)
18525 ;; Successful conversion. Return the link to MathML file.
18526 (org-add-props
18527 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18528 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18529 'org-latex-src-embed-type (if latex-frag-type
18530 'paragraph 'character)))
18531 ;; Failed conversion. Return the LaTeX fragment verbatim
18532 latex-frag)))
18534 (defun org-create-formula-image (string tofile options buffer &optional type)
18535 "Create an image from LaTeX source using dvipng or convert.
18536 This function calls either `org-create-formula-image-with-dvipng'
18537 or `org-create-formula-image-with-imagemagick' depending on the
18538 value of `org-latex-create-formula-image-program' or on the value
18539 of the optional TYPE variable.
18541 Note: ultimately these two function should be combined as they
18542 share a good deal of logic."
18543 (org-check-external-command
18544 "latex" "needed to convert LaTeX fragments to images")
18545 (funcall
18546 (case (or type org-latex-create-formula-image-program)
18547 ('dvipng
18548 (org-check-external-command
18549 "dvipng" "needed to convert LaTeX fragments to images")
18550 #'org-create-formula-image-with-dvipng)
18551 ('imagemagick
18552 (org-check-external-command
18553 "convert" "you need to install imagemagick")
18554 #'org-create-formula-image-with-imagemagick)
18555 (t (error
18556 "Invalid value of `org-latex-create-formula-image-program'")))
18557 string tofile options buffer))
18559 (declare-function org-export-get-backend "ox" (name))
18560 (declare-function org-export--get-global-options "ox" (&optional backend))
18561 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18562 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18563 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18564 (defun org-create-formula--latex-header ()
18565 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18566 (let ((info (org-combine-plists (org-export--get-global-options
18567 (org-export-get-backend 'latex))
18568 (org-export--get-inbuffer-options
18569 (org-export-get-backend 'latex)))))
18570 (org-latex-guess-babel-language
18571 (org-latex-guess-inputenc
18572 (org-splice-latex-header
18573 org-format-latex-header
18574 org-latex-default-packages-alist
18575 org-latex-packages-alist t
18576 (plist-get info :latex-header)))
18577 info)))
18579 ;; This function borrows from Ganesh Swami's latex2png.el
18580 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18581 "This calls dvipng."
18582 (require 'ox-latex)
18583 (let* ((tmpdir (if (featurep 'xemacs)
18584 (temp-directory)
18585 temporary-file-directory))
18586 (texfilebase (make-temp-name
18587 (expand-file-name "orgtex" tmpdir)))
18588 (texfile (concat texfilebase ".tex"))
18589 (dvifile (concat texfilebase ".dvi"))
18590 (pngfile (concat texfilebase ".png"))
18591 (fnh (if (featurep 'xemacs)
18592 (font-height (face-font 'default))
18593 (face-attribute 'default :height nil)))
18594 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18595 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18596 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18597 "Black"))
18598 (bg (or (plist-get options (if buffer :background :html-background))
18599 "Transparent")))
18600 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18601 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18602 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18603 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18604 (let ((latex-header (org-create-formula--latex-header)))
18605 (with-temp-file texfile
18606 (insert latex-header)
18607 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18608 (let ((dir default-directory))
18609 (condition-case nil
18610 (progn
18611 (cd tmpdir)
18612 (call-process "latex" nil nil nil texfile))
18613 (error nil))
18614 (cd dir))
18615 (if (not (file-exists-p dvifile))
18616 (progn (message "Failed to create dvi file from %s" texfile) nil)
18617 (condition-case nil
18618 (if (featurep 'xemacs)
18619 (call-process "dvipng" nil nil nil
18620 "-fg" fg "-bg" bg
18621 "-T" "tight"
18622 "-o" pngfile
18623 dvifile)
18624 (call-process "dvipng" nil nil nil
18625 "-fg" fg "-bg" bg
18626 "-D" dpi
18627 ;;"-x" scale "-y" scale
18628 "-T" "tight"
18629 "-o" pngfile
18630 dvifile))
18631 (error nil))
18632 (if (not (file-exists-p pngfile))
18633 (if org-format-latex-signal-error
18634 (error "Failed to create png file from %s" texfile)
18635 (message "Failed to create png file from %s" texfile)
18636 nil)
18637 ;; Use the requested file name and clean up
18638 (copy-file pngfile tofile 'replace)
18639 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18640 (if (file-exists-p (concat texfilebase e))
18641 (delete-file (concat texfilebase e))))
18642 pngfile))))
18644 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18645 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18646 "This calls convert, which is included into imagemagick."
18647 (require 'ox-latex)
18648 (let* ((tmpdir (if (featurep 'xemacs)
18649 (temp-directory)
18650 temporary-file-directory))
18651 (texfilebase (make-temp-name
18652 (expand-file-name "orgtex" tmpdir)))
18653 (texfile (concat texfilebase ".tex"))
18654 (pdffile (concat texfilebase ".pdf"))
18655 (pngfile (concat texfilebase ".png"))
18656 (fnh (if (featurep 'xemacs)
18657 (font-height (face-font 'default))
18658 (face-attribute 'default :height nil)))
18659 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18660 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18661 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18662 "black"))
18663 (bg (or (plist-get options (if buffer :background :html-background))
18664 "white")))
18665 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18666 (setq fg (org-latex-color-format fg)))
18667 (if (eq bg 'default) (setq bg (org-latex-color :background))
18668 (setq bg (org-latex-color-format
18669 (if (string= bg "Transparent") "white" bg))))
18670 (let ((latex-header (org-create-formula--latex-header)))
18671 (with-temp-file texfile
18672 (insert latex-header)
18673 (insert "\n\\begin{document}\n"
18674 "\\definecolor{fg}{rgb}{" fg "}\n"
18675 "\\definecolor{bg}{rgb}{" bg "}\n"
18676 "\n\\pagecolor{bg}\n"
18677 "\n{\\color{fg}\n"
18678 string
18679 "\n}\n"
18680 "\n\\end{document}\n")))
18681 (org-latex-compile texfile t)
18682 (if (not (file-exists-p pdffile))
18683 (progn (message "Failed to create pdf file from %s" texfile) nil)
18684 (condition-case nil
18685 (if (featurep 'xemacs)
18686 (call-process "convert" nil nil nil
18687 "-density" "96"
18688 "-trim"
18689 "-antialias"
18690 pdffile
18691 "-quality" "100"
18692 ;; "-sharpen" "0x1.0"
18693 pngfile)
18694 (call-process "convert" nil nil nil
18695 "-density" dpi
18696 "-trim"
18697 "-antialias"
18698 pdffile
18699 "-quality" "100"
18700 ;; "-sharpen" "0x1.0"
18701 pngfile))
18702 (error nil))
18703 (if (not (file-exists-p pngfile))
18704 (if org-format-latex-signal-error
18705 (error "Failed to create png file from %s" texfile)
18706 (message "Failed to create png file from %s" texfile)
18707 nil)
18708 ;; Use the requested file name and clean up
18709 (copy-file pngfile tofile 'replace)
18710 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18711 (if (file-exists-p (concat texfilebase e))
18712 (delete-file (concat texfilebase e))))
18713 pngfile))))
18715 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18716 "Fill a LaTeX header template TPL.
18717 In the template, the following place holders will be recognized:
18719 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18720 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18721 [PACKAGES] \\usepackage statements for PKG
18722 [NO-PACKAGES] do not include PKG
18723 [EXTRA] the string EXTRA
18724 [NO-EXTRA] do not include EXTRA
18726 For backward compatibility, if both the positive and the negative place
18727 holder is missing, the positive one (without the \"NO-\") will be
18728 assumed to be present at the end of the template.
18729 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18730 EXTRA is a string.
18731 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18732 (let (rpl (end ""))
18733 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18734 (setq rpl (if (or (match-end 1) (not def-pkg))
18735 "" (org-latex-packages-to-string def-pkg snippets-p t))
18736 tpl (replace-match rpl t t tpl))
18737 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18739 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18740 (setq rpl (if (or (match-end 1) (not pkg))
18741 "" (org-latex-packages-to-string pkg snippets-p t))
18742 tpl (replace-match rpl t t tpl))
18743 (if pkg (setq end
18744 (concat end "\n"
18745 (org-latex-packages-to-string pkg snippets-p)))))
18747 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18748 (setq rpl (if (or (match-end 1) (not extra))
18749 "" (concat extra "\n"))
18750 tpl (replace-match rpl t t tpl))
18751 (if (and extra (string-match "\\S-" extra))
18752 (setq end (concat end "\n" extra))))
18754 (if (string-match "\\S-" end)
18755 (concat tpl "\n" end)
18756 tpl)))
18758 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18759 "Turn an alist of packages into a string with the \\usepackage macros."
18760 (setq pkg (mapconcat (lambda(p)
18761 (cond
18762 ((stringp p) p)
18763 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18764 (format "%% Package %s omitted" (cadr p)))
18765 ((equal "" (car p))
18766 (format "\\usepackage{%s}" (cadr p)))
18768 (format "\\usepackage[%s]{%s}"
18769 (car p) (cadr p)))))
18771 "\n"))
18772 (if newline (concat pkg "\n") pkg))
18774 (defun org-dvipng-color (attr)
18775 "Return a RGB color specification for dvipng."
18776 (apply 'format "rgb %s %s %s"
18777 (mapcar 'org-normalize-color
18778 (if (featurep 'xemacs)
18779 (color-rgb-components
18780 (face-property 'default
18781 (cond ((eq attr :foreground) 'foreground)
18782 ((eq attr :background) 'background))))
18783 (color-values (face-attribute 'default attr nil))))))
18785 (defun org-dvipng-color-format (color-name)
18786 "Convert COLOR-NAME to a RGB color value for dvipng."
18787 (apply 'format "rgb %s %s %s"
18788 (mapcar 'org-normalize-color
18789 (color-values color-name))))
18791 (defun org-latex-color (attr)
18792 "Return a RGB color for the LaTeX color package."
18793 (apply 'format "%s,%s,%s"
18794 (mapcar 'org-normalize-color
18795 (if (featurep 'xemacs)
18796 (color-rgb-components
18797 (face-property 'default
18798 (cond ((eq attr :foreground) 'foreground)
18799 ((eq attr :background) 'background))))
18800 (color-values (face-attribute 'default attr nil))))))
18802 (defun org-latex-color-format (color-name)
18803 "Convert COLOR-NAME to a RGB color value."
18804 (apply 'format "%s,%s,%s"
18805 (mapcar 'org-normalize-color
18806 (color-values color-name))))
18808 (defun org-normalize-color (value)
18809 "Return string to be used as color value for an RGB component."
18810 (format "%g" (/ value 65535.0)))
18814 ;; Image display
18816 (defvar org-inline-image-overlays nil)
18817 (make-variable-buffer-local 'org-inline-image-overlays)
18819 (defun org-toggle-inline-images (&optional include-linked)
18820 "Toggle the display of inline images.
18821 INCLUDE-LINKED is passed to `org-display-inline-images'."
18822 (interactive "P")
18823 (if org-inline-image-overlays
18824 (progn
18825 (org-remove-inline-images)
18826 (message "Inline image display turned off"))
18827 (org-display-inline-images include-linked)
18828 (if (and (org-called-interactively-p)
18829 org-inline-image-overlays)
18830 (message "%d images displayed inline"
18831 (length org-inline-image-overlays))
18832 (message "No images to display inline"))))
18834 (defun org-redisplay-inline-images ()
18835 "Refresh the display of inline images."
18836 (interactive)
18837 (if (not org-inline-image-overlays)
18838 (org-toggle-inline-images)
18839 (org-toggle-inline-images)
18840 (org-toggle-inline-images)))
18842 (defun org-display-inline-images (&optional include-linked refresh beg end)
18843 "Display inline images.
18844 Normally only links without a description part are inlined, because this
18845 is how it will work for export. When INCLUDE-LINKED is set, also links
18846 with a description part will be inlined. This can be nice for a quick
18847 look at those images, but it does not reflect what exported files will look
18848 like.
18849 When REFRESH is set, refresh existing images between BEG and END.
18850 This will create new image displays only if necessary.
18851 BEG and END default to the buffer boundaries."
18852 (interactive "P")
18853 (when (display-graphic-p)
18854 (unless refresh
18855 (org-remove-inline-images)
18856 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18857 (save-excursion
18858 (save-restriction
18859 (widen)
18860 (setq beg (or beg (point-min)) end (or end (point-max)))
18861 (goto-char beg)
18862 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18863 (substring (org-image-file-name-regexp) 0 -2)
18864 "\\)\\]" (if include-linked "" "\\]")))
18865 (case-fold-search t)
18866 old file ov img type attrwidth width)
18867 (while (re-search-forward re end t)
18868 (setq old (get-char-property-and-overlay (match-beginning 1)
18869 'org-image-overlay)
18870 file (expand-file-name
18871 (concat (or (match-string 3) "") (match-string 4))))
18872 (when (image-type-available-p 'imagemagick)
18873 (setq attrwidth (if (or (listp org-image-actual-width)
18874 (null org-image-actual-width))
18875 (save-excursion
18876 (save-match-data
18877 (when (re-search-backward
18878 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18879 (save-excursion
18880 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18881 (string-to-number (match-string 1))))))
18882 width (cond ((eq org-image-actual-width t) nil)
18883 ((null org-image-actual-width) attrwidth)
18884 ((numberp org-image-actual-width)
18885 org-image-actual-width)
18886 ((listp org-image-actual-width)
18887 (or attrwidth (car org-image-actual-width))))
18888 type (if width 'imagemagick)))
18889 (when (file-exists-p file)
18890 (if (and (car-safe old) refresh)
18891 (image-refresh (overlay-get (cdr old) 'display))
18892 (setq img (save-match-data (create-image file type nil :width width)))
18893 (when img
18894 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18895 (overlay-put ov 'display img)
18896 (overlay-put ov 'face 'default)
18897 (overlay-put ov 'org-image-overlay t)
18898 (overlay-put ov 'modification-hooks
18899 (list 'org-display-inline-remove-overlay))
18900 (push ov org-inline-image-overlays))))))))))
18902 (define-obsolete-function-alias
18903 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18905 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18906 "Remove inline-display overlay if a corresponding region is modified."
18907 (let ((inhibit-modification-hooks t))
18908 (when (and ov after)
18909 (delete ov org-inline-image-overlays)
18910 (delete-overlay ov))))
18912 (defun org-remove-inline-images ()
18913 "Remove inline display of images."
18914 (interactive)
18915 (mapc 'delete-overlay org-inline-image-overlays)
18916 (setq org-inline-image-overlays nil))
18918 ;;;; Key bindings
18920 ;; Outline functions from `outline-mode-prefix-map'
18921 ;; that can be remapped in Org:
18922 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18923 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18924 (define-key org-mode-map [remap outline-forward-same-level]
18925 'org-forward-heading-same-level)
18926 (define-key org-mode-map [remap outline-backward-same-level]
18927 'org-backward-heading-same-level)
18928 (define-key org-mode-map [remap show-branches]
18929 'org-kill-note-or-show-branches)
18930 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18931 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18932 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18934 ;; Outline functions from `outline-mode-prefix-map' that can not
18935 ;; be remapped in Org:
18937 ;; - the column "key binding" shows whether the Outline function is still
18938 ;; available in Org mode on the same key that it has been bound to in
18939 ;; Outline mode:
18940 ;; - "overridden": key used for a different functionality in Org mode
18941 ;; - else: key still bound to the same Outline function in Org mode
18943 ;; | Outline function | key binding | Org replacement |
18944 ;; |------------------------------------+-------------+-----------------------|
18945 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18946 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18947 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18948 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18949 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18950 ;; | `show-entry' | overridden | no replacement |
18951 ;; | `show-children' | `C-c C-i' | visibility cycling |
18952 ;; | `show-branches' | `C-c C-k' | still same function |
18953 ;; | `show-subtree' | overridden | visibility cycling |
18954 ;; | `show-all' | overridden | no replacement |
18955 ;; | `hide-subtree' | overridden | visibility cycling |
18956 ;; | `hide-body' | overridden | no replacement |
18957 ;; | `hide-entry' | overridden | visibility cycling |
18958 ;; | `hide-leaves' | overridden | no replacement |
18959 ;; | `hide-sublevels' | overridden | no replacement |
18960 ;; | `hide-other' | overridden | no replacement |
18962 ;; Make `C-c C-x' a prefix key
18963 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18965 ;; TAB key with modifiers
18966 (org-defkey org-mode-map "\C-i" 'org-cycle)
18967 (org-defkey org-mode-map [(tab)] 'org-cycle)
18968 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18969 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18970 ;; The following line is necessary under Suse GNU/Linux
18971 (unless (featurep 'xemacs)
18972 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18973 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18974 (define-key org-mode-map [backtab] 'org-shifttab)
18976 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18977 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18978 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18980 ;; Cursor keys with modifiers
18981 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18982 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18983 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18984 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18986 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18987 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18988 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18989 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18991 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18992 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18993 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18994 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18996 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18997 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18998 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18999 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19001 ;; Babel keys
19002 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19003 (mapc (lambda (pair)
19004 (define-key org-babel-map (car pair) (cdr pair)))
19005 org-babel-key-bindings)
19007 ;;; Extra keys for tty access.
19008 ;; We only set them when really needed because otherwise the
19009 ;; menus don't show the simple keys
19011 (when (or org-use-extra-keys
19012 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19013 (not window-system))
19014 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19015 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19016 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19017 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19018 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19019 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19020 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19021 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19022 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19023 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19024 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19025 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19026 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19027 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19028 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19029 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19030 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19031 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19032 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19033 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19034 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19035 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19036 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19037 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19038 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19039 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19040 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19041 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19043 ;; All the other keys
19045 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19046 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19047 (if (boundp 'narrow-map)
19048 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19049 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19050 (if (boundp 'narrow-map)
19051 (org-defkey narrow-map "b" 'org-narrow-to-block)
19052 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19053 (if (boundp 'narrow-map)
19054 (org-defkey narrow-map "e" 'org-narrow-to-element)
19055 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19056 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19057 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19058 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19059 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19060 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19061 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19062 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19063 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19064 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19065 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19066 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19067 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19068 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19069 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19070 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19071 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19072 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19073 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19074 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19075 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19076 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19077 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19078 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19079 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19080 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19081 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19082 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19083 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19084 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19085 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19086 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19087 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19088 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19089 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19090 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19091 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19092 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19093 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19094 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19095 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19096 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19097 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19098 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19099 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19100 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19101 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19102 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19103 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19104 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19105 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19106 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19107 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19108 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19109 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19110 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19111 (org-defkey org-mode-map "\C-c^" 'org-sort)
19112 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19113 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19114 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19115 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19116 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19117 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19118 (org-defkey org-mode-map "\C-m" 'org-return)
19119 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19120 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19121 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19122 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19123 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19124 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19125 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19126 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19127 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19128 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19129 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19130 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19131 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19132 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19133 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19134 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19135 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19136 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19137 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19138 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19139 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19140 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19141 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19143 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19144 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19145 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19147 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19148 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19149 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19150 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19151 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19152 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19153 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19154 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19155 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19156 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19157 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19158 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19159 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19160 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19161 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19162 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19163 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19164 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19165 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19166 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19167 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19168 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19169 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19171 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19172 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19173 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19174 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19175 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19177 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19179 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19181 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19182 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19184 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19187 (when (featurep 'xemacs)
19188 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19191 (defconst org-speed-commands-default
19193 ("Outline Navigation")
19194 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19195 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19196 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19197 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19198 ("F" . org-next-block)
19199 ("B" . org-previous-block)
19200 ("u" . (org-speed-move-safe 'outline-up-heading))
19201 ("j" . org-goto)
19202 ("g" . (org-refile t))
19203 ("Outline Visibility")
19204 ("c" . org-cycle)
19205 ("C" . org-shifttab)
19206 (" " . org-display-outline-path)
19207 ("s" . org-narrow-to-subtree)
19208 ("=" . org-columns)
19209 ("Outline Structure Editing")
19210 ("U" . org-shiftmetaup)
19211 ("D" . org-shiftmetadown)
19212 ("r" . org-metaright)
19213 ("l" . org-metaleft)
19214 ("R" . org-shiftmetaright)
19215 ("L" . org-shiftmetaleft)
19216 ("i" . (progn (forward-char 1) (call-interactively
19217 'org-insert-heading-respect-content)))
19218 ("^" . org-sort)
19219 ("w" . org-refile)
19220 ("a" . org-archive-subtree-default-with-confirmation)
19221 ("@" . org-mark-subtree)
19222 ("#" . org-toggle-comment)
19223 ("Clock Commands")
19224 ("I" . org-clock-in)
19225 ("O" . org-clock-out)
19226 ("Meta Data Editing")
19227 ("t" . org-todo)
19228 ("," . (org-priority))
19229 ("0" . (org-priority ?\ ))
19230 ("1" . (org-priority ?A))
19231 ("2" . (org-priority ?B))
19232 ("3" . (org-priority ?C))
19233 (":" . org-set-tags-command)
19234 ("e" . org-set-effort)
19235 ("E" . org-inc-effort)
19236 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19237 (org-entry-put (point) "APPT_WARNTIME" m)))
19238 ("Agenda Views etc")
19239 ("v" . org-agenda)
19240 ("/" . org-sparse-tree)
19241 ("Misc")
19242 ("o" . org-open-at-point)
19243 ("?" . org-speed-command-help)
19244 ("<" . (org-agenda-set-restriction-lock 'subtree))
19245 (">" . (org-agenda-remove-restriction-lock))
19247 "The default speed commands.")
19249 (defun org-print-speed-command (e)
19250 (if (> (length (car e)) 1)
19251 (progn
19252 (princ "\n")
19253 (princ (car e))
19254 (princ "\n")
19255 (princ (make-string (length (car e)) ?-))
19256 (princ "\n"))
19257 (princ (car e))
19258 (princ " ")
19259 (if (symbolp (cdr e))
19260 (princ (symbol-name (cdr e)))
19261 (prin1 (cdr e)))
19262 (princ "\n")))
19264 (defun org-speed-command-help ()
19265 "Show the available speed commands."
19266 (interactive)
19267 (if (not org-use-speed-commands)
19268 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19269 (with-output-to-temp-buffer "*Help*"
19270 (princ "User-defined Speed commands\n===========================\n")
19271 (mapc 'org-print-speed-command org-speed-commands-user)
19272 (princ "\n")
19273 (princ "Built-in Speed commands\n=======================\n")
19274 (mapc 'org-print-speed-command org-speed-commands-default))
19275 (with-current-buffer "*Help*"
19276 (setq truncate-lines t))))
19278 (defun org-speed-move-safe (cmd)
19279 "Execute CMD, but make sure that the cursor always ends up in a headline.
19280 If not, return to the original position and throw an error."
19281 (interactive)
19282 (let ((pos (point)))
19283 (call-interactively cmd)
19284 (unless (and (bolp) (org-at-heading-p))
19285 (goto-char pos)
19286 (error "Boundary reached while executing %s" cmd))))
19288 (defvar org-self-insert-command-undo-counter 0)
19290 (defvar org-table-auto-blank-field) ; defined in org-table.el
19291 (defvar org-speed-command nil)
19293 (define-obsolete-function-alias
19294 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19296 (defun org-speed-command-activate (keys)
19297 "Hook for activating single-letter speed commands.
19298 `org-speed-commands-default' specifies a minimal command set.
19299 Use `org-speed-commands-user' for further customization."
19300 (when (or (and (bolp) (looking-at org-outline-regexp))
19301 (and (functionp org-use-speed-commands)
19302 (funcall org-use-speed-commands)))
19303 (cdr (assoc keys (append org-speed-commands-user
19304 org-speed-commands-default)))))
19306 (define-obsolete-function-alias
19307 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19309 (defun org-babel-speed-command-activate (keys)
19310 "Hook for activating single-letter code block commands."
19311 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19312 (cdr (assoc keys org-babel-key-bindings))))
19314 (defcustom org-speed-command-hook
19315 '(org-speed-command-default-hook org-babel-speed-command-hook)
19316 "Hook for activating speed commands at strategic locations.
19317 Hook functions are called in sequence until a valid handler is
19318 found.
19320 Each hook takes a single argument, a user-pressed command key
19321 which is also a `self-insert-command' from the global map.
19323 Within the hook, examine the cursor position and the command key
19324 and return nil or a valid handler as appropriate. Handler could
19325 be one of an interactive command, a function, or a form.
19327 Set `org-use-speed-commands' to non-nil value to enable this
19328 hook. The default setting is `org-speed-command-activate'."
19329 :group 'org-structure
19330 :version "24.1"
19331 :type 'hook)
19333 (defun org-self-insert-command (N)
19334 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19335 If the cursor is in a table looking at whitespace, the whitespace is
19336 overwritten, and the table is not marked as requiring realignment."
19337 (interactive "p")
19338 (org-check-before-invisible-edit 'insert)
19339 (cond
19340 ((and org-use-speed-commands
19341 (setq org-speed-command
19342 (run-hook-with-args-until-success
19343 'org-speed-command-hook (this-command-keys))))
19344 (cond
19345 ((commandp org-speed-command)
19346 (setq this-command org-speed-command)
19347 (call-interactively org-speed-command))
19348 ((functionp org-speed-command)
19349 (funcall org-speed-command))
19350 ((and org-speed-command (listp org-speed-command))
19351 (eval org-speed-command))
19352 (t (let (org-use-speed-commands)
19353 (call-interactively 'org-self-insert-command)))))
19354 ((and
19355 (org-table-p)
19356 (progn
19357 ;; check if we blank the field, and if that triggers align
19358 (and (featurep 'org-table) org-table-auto-blank-field
19359 (member last-command
19360 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19361 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19362 ;; got extra space, this field does not determine column width
19363 (let (org-table-may-need-update) (org-table-blank-field))
19364 ;; no extra space, this field may determine column width
19365 (org-table-blank-field)))
19367 (eq N 1)
19368 (looking-at "[^|\n]* |"))
19369 (let (org-table-may-need-update)
19370 (goto-char (1- (match-end 0)))
19371 (backward-delete-char 1)
19372 (goto-char (match-beginning 0))
19373 (self-insert-command N)))
19375 (setq org-table-may-need-update t)
19376 (self-insert-command N)
19377 (org-fix-tags-on-the-fly)
19378 (if org-self-insert-cluster-for-undo
19379 (if (not (eq last-command 'org-self-insert-command))
19380 (setq org-self-insert-command-undo-counter 1)
19381 (if (>= org-self-insert-command-undo-counter 20)
19382 (setq org-self-insert-command-undo-counter 1)
19383 (and (> org-self-insert-command-undo-counter 0)
19384 buffer-undo-list (listp buffer-undo-list)
19385 (not (cadr buffer-undo-list)) ; remove nil entry
19386 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19387 (setq org-self-insert-command-undo-counter
19388 (1+ org-self-insert-command-undo-counter))))))))
19390 (defun org-check-before-invisible-edit (kind)
19391 "Check is editing if kind KIND would be dangerous with invisible text around.
19392 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19393 ;; First, try to get out of here as quickly as possible, to reduce overhead
19394 (if (and org-catch-invisible-edits
19395 (or (not (boundp 'visible-mode)) (not visible-mode))
19396 (or (get-char-property (point) 'invisible)
19397 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19398 ;; OK, we need to take a closer look
19399 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19400 (invisible-before-point (if (bobp) nil (get-char-property
19401 (1- (point)) 'invisible)))
19402 (border-and-ok-direction
19404 ;; Check if we are acting predictably before invisible text
19405 (and invisible-at-point (not invisible-before-point)
19406 (memq kind '(insert delete-backward)))
19407 ;; Check if we are acting predictably after invisible text
19408 ;; This works not well, and I have turned it off. It seems
19409 ;; better to always show and stop after invisible text.
19410 ;; (and (not invisible-at-point) invisible-before-point
19411 ;; (memq kind '(insert delete)))
19413 (when (or (memq invisible-at-point '(outline org-hide-block t))
19414 (memq invisible-before-point '(outline org-hide-block t)))
19415 (if (eq org-catch-invisible-edits 'error)
19416 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19417 (if (and org-custom-properties-overlays
19418 (y-or-n-p "Display invisible properties in this buffer? "))
19419 (org-toggle-custom-properties-visibility)
19420 ;; Make the area visible
19421 (save-excursion
19422 (if invisible-before-point
19423 (goto-char (previous-single-char-property-change
19424 (point) 'invisible)))
19425 (org-cycle))
19426 (cond
19427 ((eq org-catch-invisible-edits 'show)
19428 ;; That's it, we do the edit after showing
19429 (message
19430 "Unfolding invisible region around point before editing")
19431 (sit-for 1))
19432 ((and (eq org-catch-invisible-edits 'smart)
19433 border-and-ok-direction)
19434 (message "Unfolding invisible region around point before editing"))
19436 ;; Don't do the edit, make the user repeat it in full visibility
19437 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19439 (defun org-fix-tags-on-the-fly ()
19440 (when (and (equal (char-after (point-at-bol)) ?*)
19441 (org-at-heading-p))
19442 (org-align-tags-here org-tags-column)))
19444 (defun org-delete-backward-char (N)
19445 "Like `delete-backward-char', insert whitespace at field end in tables.
19446 When deleting backwards, in tables this function will insert whitespace in
19447 front of the next \"|\" separator, to keep the table aligned. The table will
19448 still be marked for re-alignment if the field did fill the entire column,
19449 because, in this case the deletion might narrow the column."
19450 (interactive "p")
19451 (save-match-data
19452 (org-check-before-invisible-edit 'delete-backward)
19453 (if (and (org-table-p)
19454 (eq N 1)
19455 (string-match "|" (buffer-substring (point-at-bol) (point)))
19456 (looking-at ".*?|"))
19457 (let ((pos (point))
19458 (noalign (looking-at "[^|\n\r]* |"))
19459 (c org-table-may-need-update))
19460 (backward-delete-char N)
19461 (if (not overwrite-mode)
19462 (progn
19463 (skip-chars-forward "^|")
19464 (insert " ")
19465 (goto-char (1- pos))))
19466 ;; noalign: if there were two spaces at the end, this field
19467 ;; does not determine the width of the column.
19468 (if noalign (setq org-table-may-need-update c)))
19469 (backward-delete-char N)
19470 (org-fix-tags-on-the-fly))))
19472 (defun org-delete-char (N)
19473 "Like `delete-char', but insert whitespace at field end in tables.
19474 When deleting characters, in tables this function will insert whitespace in
19475 front of the next \"|\" separator, to keep the table aligned. The table will
19476 still be marked for re-alignment if the field did fill the entire column,
19477 because, in this case the deletion might narrow the column."
19478 (interactive "p")
19479 (save-match-data
19480 (org-check-before-invisible-edit 'delete)
19481 (if (and (org-table-p)
19482 (not (bolp))
19483 (not (= (char-after) ?|))
19484 (eq N 1))
19485 (if (looking-at ".*?|")
19486 (let ((pos (point))
19487 (noalign (looking-at "[^|\n\r]* |"))
19488 (c org-table-may-need-update))
19489 (replace-match
19490 (concat (substring (match-string 0) 1 -1) " |") nil t)
19491 (goto-char pos)
19492 ;; noalign: if there were two spaces at the end, this field
19493 ;; does not determine the width of the column.
19494 (if noalign (setq org-table-may-need-update c)))
19495 (delete-char N))
19496 (delete-char N)
19497 (org-fix-tags-on-the-fly))))
19499 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19500 (put 'org-self-insert-command 'delete-selection
19501 (lambda ()
19502 (not (run-hook-with-args-until-success
19503 'self-insert-uses-region-functions))))
19504 (put 'orgtbl-self-insert-command 'delete-selection
19505 (lambda ()
19506 (not (run-hook-with-args-until-success
19507 'self-insert-uses-region-functions))))
19508 (put 'org-delete-char 'delete-selection 'supersede)
19509 (put 'org-delete-backward-char 'delete-selection 'supersede)
19510 (put 'org-yank 'delete-selection 'yank)
19512 ;; Make `flyspell-mode' delay after some commands
19513 (put 'org-self-insert-command 'flyspell-delayed t)
19514 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19515 (put 'org-delete-char 'flyspell-delayed t)
19516 (put 'org-delete-backward-char 'flyspell-delayed t)
19518 ;; Make pabbrev-mode expand after org-mode commands
19519 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19520 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19522 (defun org-remap (map &rest commands)
19523 "In MAP, remap the functions given in COMMANDS.
19524 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19525 (let (new old)
19526 (while commands
19527 (setq old (pop commands) new (pop commands))
19528 (if (fboundp 'command-remapping)
19529 (org-defkey map (vector 'remap old) new)
19530 (substitute-key-definition old new map global-map)))))
19532 (defun org-transpose-words ()
19533 "Transpose words for Org.
19534 This uses the `org-mode-transpose-word-syntax-table' syntax
19535 table, which interprets characters in `org-emphasis-alist' as
19536 word constituents."
19537 (interactive)
19538 (with-syntax-table org-mode-transpose-word-syntax-table
19539 (call-interactively 'transpose-words)))
19540 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19542 (when (eq org-enable-table-editor 'optimized)
19543 ;; If the user wants maximum table support, we need to hijack
19544 ;; some standard editing functions
19545 (org-remap org-mode-map
19546 'self-insert-command 'org-self-insert-command
19547 'delete-char 'org-delete-char
19548 'delete-backward-char 'org-delete-backward-char)
19549 (org-defkey org-mode-map "|" 'org-force-self-insert))
19551 (defvar org-ctrl-c-ctrl-c-hook nil
19552 "Hook for functions attaching themselves to `C-c C-c'.
19554 This can be used to add additional functionality to the C-c C-c
19555 key which executes context-dependent commands. This hook is run
19556 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19557 run after the last test.
19559 Each function will be called with no arguments. The function
19560 must check if the context is appropriate for it to act. If yes,
19561 it should do its thing and then return a non-nil value. If the
19562 context is wrong, just do nothing and return nil.")
19564 (defvar org-ctrl-c-ctrl-c-final-hook nil
19565 "Hook for functions attaching themselves to `C-c C-c'.
19567 This can be used to add additional functionality to the C-c C-c
19568 key which executes context-dependent commands. This hook is run
19569 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19570 before the first test.
19572 Each function will be called with no arguments. The function
19573 must check if the context is appropriate for it to act. If yes,
19574 it should do its thing and then return a non-nil value. If the
19575 context is wrong, just do nothing and return nil.")
19577 (defvar org-tab-first-hook nil
19578 "Hook for functions to attach themselves to TAB.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.
19580 This hook runs as the first action when TAB is pressed, even before
19581 `org-cycle' messes around with the `outline-regexp' to cater for
19582 inline tasks and plain list item folding.
19583 If any function in this hook returns t, any other actions that
19584 would have been caused by TAB (such as table field motion or visibility
19585 cycling) will not occur.")
19587 (defvar org-tab-after-check-for-table-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 the cursor is not in a
19591 table, but before checking if the cursor is in a headline or if global cycling
19592 should be done.
19593 If any function in this hook returns t, not other actions like visibility
19594 cycling will be done.")
19596 (defvar org-tab-after-check-for-cycling-hook nil
19597 "Hook for functions to attach themselves to TAB.
19598 See `org-ctrl-c-ctrl-c-hook' for more information.
19599 This hook runs after it has been established that not table field motion and
19600 not visibility should be done because of current context. This is probably
19601 the place where a package like yasnippets can hook in.")
19603 (defvar org-tab-before-tab-emulation-hook nil
19604 "Hook for functions to attach themselves to TAB.
19605 See `org-ctrl-c-ctrl-c-hook' for more information.
19606 This hook runs after every other options for TAB have been exhausted, but
19607 before indentation and \t insertion takes place.")
19609 (defvar org-metaleft-hook nil
19610 "Hook for functions attaching themselves to `M-left'.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19612 (defvar org-metaright-hook nil
19613 "Hook for functions attaching themselves to `M-right'.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.")
19615 (defvar org-metaup-hook nil
19616 "Hook for functions attaching themselves to `M-up'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-metadown-hook nil
19619 "Hook for functions attaching themselves to `M-down'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-shiftmetaleft-hook nil
19622 "Hook for functions attaching themselves to `M-S-left'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-shiftmetaright-hook nil
19625 "Hook for functions attaching themselves to `M-S-right'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftmetaup-hook nil
19628 "Hook for functions attaching themselves to `M-S-up'.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.")
19630 (defvar org-shiftmetadown-hook nil
19631 "Hook for functions attaching themselves to `M-S-down'.
19632 See `org-ctrl-c-ctrl-c-hook' for more information.")
19633 (defvar org-metareturn-hook nil
19634 "Hook for functions attaching themselves to `M-RET'.
19635 See `org-ctrl-c-ctrl-c-hook' for more information.")
19636 (defvar org-shiftup-hook nil
19637 "Hook for functions attaching themselves to `S-up'.
19638 See `org-ctrl-c-ctrl-c-hook' for more information.")
19639 (defvar org-shiftup-final-hook nil
19640 "Hook for functions attaching themselves to `S-up'.
19641 This one runs after all other options except shift-select have been excluded.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.")
19643 (defvar org-shiftdown-hook nil
19644 "Hook for functions attaching themselves to `S-down'.
19645 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defvar org-shiftdown-final-hook nil
19647 "Hook for functions attaching themselves to `S-down'.
19648 This one runs after all other options except shift-select have been excluded.
19649 See `org-ctrl-c-ctrl-c-hook' for more information.")
19650 (defvar org-shiftleft-hook nil
19651 "Hook for functions attaching themselves to `S-left'.
19652 See `org-ctrl-c-ctrl-c-hook' for more information.")
19653 (defvar org-shiftleft-final-hook nil
19654 "Hook for functions attaching themselves to `S-left'.
19655 This one runs after all other options except shift-select have been excluded.
19656 See `org-ctrl-c-ctrl-c-hook' for more information.")
19657 (defvar org-shiftright-hook nil
19658 "Hook for functions attaching themselves to `S-right'.
19659 See `org-ctrl-c-ctrl-c-hook' for more information.")
19660 (defvar org-shiftright-final-hook nil
19661 "Hook for functions attaching themselves to `S-right'.
19662 This one runs after all other options except shift-select have been excluded.
19663 See `org-ctrl-c-ctrl-c-hook' for more information.")
19665 (defun org-modifier-cursor-error ()
19666 "Throw an error, a modified cursor command was applied in wrong context."
19667 (user-error "This command is active in special context like tables, headlines or items"))
19669 (defun org-shiftselect-error ()
19670 "Throw an error because Shift-Cursor command was applied in wrong context."
19671 (if (and (boundp 'shift-select-mode) shift-select-mode)
19672 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19673 (user-error "This command works only in special context like headlines or timestamps")))
19675 (defun org-call-for-shift-select (cmd)
19676 (let ((this-command-keys-shift-translated t))
19677 (call-interactively cmd)))
19679 (defun org-shifttab (&optional arg)
19680 "Global visibility cycling or move to previous table field.
19681 Call `org-table-previous-field' within a table.
19682 When ARG is nil, cycle globally through visibility states.
19683 When ARG is a numeric prefix, show contents of this level."
19684 (interactive "P")
19685 (cond
19686 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19687 ((integerp arg)
19688 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19689 (message "Content view to level: %d" arg)
19690 (org-content (prefix-numeric-value arg2))
19691 (org-cycle-show-empty-lines t)
19692 (setq org-cycle-global-status 'overview)))
19693 (t (call-interactively 'org-global-cycle))))
19695 (defun org-shiftmetaleft ()
19696 "Promote subtree or delete table column.
19697 Calls `org-promote-subtree', `org-outdent-item-tree', or
19698 `org-table-delete-column', depending on context. See the
19699 individual commands for more information."
19700 (interactive)
19701 (cond
19702 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19703 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19704 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19705 ((if (not (org-region-active-p)) (org-at-item-p)
19706 (save-excursion (goto-char (region-beginning))
19707 (org-at-item-p)))
19708 (call-interactively 'org-outdent-item-tree))
19709 (t (org-modifier-cursor-error))))
19711 (defun org-shiftmetaright ()
19712 "Demote subtree or insert table column.
19713 Calls `org-demote-subtree', `org-indent-item-tree', or
19714 `org-table-insert-column', depending on context. See the
19715 individual commands for more information."
19716 (interactive)
19717 (cond
19718 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19719 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19720 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19721 ((if (not (org-region-active-p)) (org-at-item-p)
19722 (save-excursion (goto-char (region-beginning))
19723 (org-at-item-p)))
19724 (call-interactively 'org-indent-item-tree))
19725 (t (org-modifier-cursor-error))))
19727 (defun org-shiftmetaup (&optional arg)
19728 "Move subtree up or kill table row.
19729 Calls `org-move-subtree-up' or `org-table-kill-row' or
19730 `org-move-item-up' or `org-timestamp-up', depending on context.
19731 See the individual commands for more information."
19732 (interactive "P")
19733 (cond
19734 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19735 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19736 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19737 ((org-at-item-p) (call-interactively 'org-move-item-up))
19738 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19739 (call-interactively 'org-timestamp-up)))
19740 (t (call-interactively 'org-drag-line-backward))))
19742 (defun org-shiftmetadown (&optional arg)
19743 "Move subtree down or insert table row.
19744 Calls `org-move-subtree-down' or `org-table-insert-row' or
19745 `org-move-item-down' or `org-timestamp-up', depending on context.
19746 See the individual commands for more information."
19747 (interactive "P")
19748 (cond
19749 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19750 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19751 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19752 ((org-at-item-p) (call-interactively 'org-move-item-down))
19753 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19754 (call-interactively 'org-timestamp-down)))
19755 (t (call-interactively 'org-drag-line-forward))))
19757 (defsubst org-hidden-tree-error ()
19758 (user-error
19759 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19761 (defun org-metaleft (&optional arg)
19762 "Promote heading or move table column to left.
19763 Calls `org-do-promote' or `org-table-move-column', depending on context.
19764 With no specific context, calls the Emacs default `backward-word'.
19765 See the individual commands for more information."
19766 (interactive "P")
19767 (cond
19768 ((run-hook-with-args-until-success 'org-metaleft-hook))
19769 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19770 ((org-with-limited-levels
19771 (or (org-at-heading-p)
19772 (and (org-region-active-p)
19773 (save-excursion
19774 (goto-char (region-beginning))
19775 (org-at-heading-p)))))
19776 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19777 (call-interactively 'org-do-promote))
19778 ;; At an inline task.
19779 ((org-at-heading-p)
19780 (call-interactively 'org-inlinetask-promote))
19781 ((or (org-at-item-p)
19782 (and (org-region-active-p)
19783 (save-excursion
19784 (goto-char (region-beginning))
19785 (org-at-item-p))))
19786 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19787 (call-interactively 'org-outdent-item))
19788 (t (call-interactively 'backward-word))))
19790 (defun org-metaright (&optional arg)
19791 "Demote a subtree, a list item or move table column to right.
19792 In front of a drawer or a block keyword, indent it correctly.
19793 With no specific context, calls the Emacs default `forward-word'.
19794 See the individual commands for more information."
19795 (interactive "P")
19796 (cond
19797 ((run-hook-with-args-until-success 'org-metaright-hook))
19798 ((org-at-table-p) (call-interactively 'org-table-move-column))
19799 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19800 ((org-at-block-p) (call-interactively 'org-indent-block))
19801 ((org-with-limited-levels
19802 (or (org-at-heading-p)
19803 (and (org-region-active-p)
19804 (save-excursion
19805 (goto-char (region-beginning))
19806 (org-at-heading-p)))))
19807 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19808 (call-interactively 'org-do-demote))
19809 ;; At an inline task.
19810 ((org-at-heading-p)
19811 (call-interactively 'org-inlinetask-demote))
19812 ((or (org-at-item-p)
19813 (and (org-region-active-p)
19814 (save-excursion
19815 (goto-char (region-beginning))
19816 (org-at-item-p))))
19817 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19818 (call-interactively 'org-indent-item))
19819 (t (call-interactively 'forward-word))))
19821 (defun org-check-for-hidden (what)
19822 "Check if there are hidden headlines/items in the current visual line.
19823 WHAT can be either `headlines' or `items'. If the current line is
19824 an outline or item heading and it has a folded subtree below it,
19825 this function returns t, nil otherwise."
19826 (let ((re (cond
19827 ((eq what 'headlines) org-outline-regexp-bol)
19828 ((eq what 'items) (org-item-beginning-re))
19829 (t (error "This should not happen"))))
19830 beg end)
19831 (save-excursion
19832 (catch 'exit
19833 (unless (org-region-active-p)
19834 (setq beg (point-at-bol))
19835 (beginning-of-line 2)
19836 (while (and (not (eobp)) ;; this is like `next-line'
19837 (get-char-property (1- (point)) 'invisible))
19838 (beginning-of-line 2))
19839 (setq end (point))
19840 (goto-char beg)
19841 (goto-char (point-at-eol))
19842 (setq end (max end (point)))
19843 (while (re-search-forward re end t)
19844 (if (get-char-property (match-beginning 0) 'invisible)
19845 (throw 'exit t))))
19846 nil))))
19848 (defun org-metaup (&optional arg)
19849 "Move subtree up or move table row up.
19850 Calls `org-move-subtree-up' or `org-table-move-row' or
19851 `org-move-item-up', depending on context. See the individual commands
19852 for more information."
19853 (interactive "P")
19854 (cond
19855 ((run-hook-with-args-until-success 'org-metaup-hook))
19856 ((org-region-active-p)
19857 (let* ((a (min (region-beginning) (region-end)))
19858 (b (1- (max (region-beginning) (region-end))))
19859 (c (save-excursion (goto-char a)
19860 (move-beginning-of-line 0)))
19861 (d (save-excursion (goto-char a)
19862 (move-end-of-line 0) (point))))
19863 (transpose-regions a b c d)
19864 (goto-char c)))
19865 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19866 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19867 ((org-at-item-p) (call-interactively 'org-move-item-up))
19868 (t (org-drag-element-backward))))
19870 (defun org-metadown (&optional arg)
19871 "Move subtree down or move table row down.
19872 Calls `org-move-subtree-down' or `org-table-move-row' or
19873 `org-move-item-down', depending on context. See the individual
19874 commands for more information."
19875 (interactive "P")
19876 (cond
19877 ((run-hook-with-args-until-success 'org-metadown-hook))
19878 ((org-region-active-p)
19879 (let* ((a (min (region-beginning) (region-end)))
19880 (b (max (region-beginning) (region-end)))
19881 (c (save-excursion (goto-char b)
19882 (move-beginning-of-line 1)))
19883 (d (save-excursion (goto-char b)
19884 (move-end-of-line 1) (1+ (point)))))
19885 (transpose-regions a b c d)
19886 (goto-char d)))
19887 ((org-at-table-p) (call-interactively 'org-table-move-row))
19888 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19889 ((org-at-item-p) (call-interactively 'org-move-item-down))
19890 (t (org-drag-element-forward))))
19892 (defun org-shiftup (&optional arg)
19893 "Increase item in timestamp or increase priority of current headline.
19894 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19895 depending on context. See the individual commands for more information."
19896 (interactive "P")
19897 (cond
19898 ((run-hook-with-args-until-success 'org-shiftup-hook))
19899 ((and org-support-shift-select (org-region-active-p))
19900 (org-call-for-shift-select 'previous-line))
19901 ((org-at-timestamp-p t)
19902 (call-interactively (if org-edit-timestamp-down-means-later
19903 'org-timestamp-down 'org-timestamp-up)))
19904 ((and (not (eq org-support-shift-select 'always))
19905 org-enable-priority-commands
19906 (org-at-heading-p))
19907 (call-interactively 'org-priority-up))
19908 ((and (not org-support-shift-select) (org-at-item-p))
19909 (call-interactively 'org-previous-item))
19910 ((org-clocktable-try-shift 'up arg))
19911 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19912 (org-support-shift-select
19913 (org-call-for-shift-select 'previous-line))
19914 (t (org-shiftselect-error))))
19916 (defun org-shiftdown (&optional arg)
19917 "Decrease item in timestamp or decrease priority of current headline.
19918 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19919 depending on context. See the individual commands for more information."
19920 (interactive "P")
19921 (cond
19922 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19923 ((and org-support-shift-select (org-region-active-p))
19924 (org-call-for-shift-select 'next-line))
19925 ((org-at-timestamp-p t)
19926 (call-interactively (if org-edit-timestamp-down-means-later
19927 'org-timestamp-up 'org-timestamp-down)))
19928 ((and (not (eq org-support-shift-select 'always))
19929 org-enable-priority-commands
19930 (org-at-heading-p))
19931 (call-interactively 'org-priority-down))
19932 ((and (not org-support-shift-select) (org-at-item-p))
19933 (call-interactively 'org-next-item))
19934 ((org-clocktable-try-shift 'down arg))
19935 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19936 (org-support-shift-select
19937 (org-call-for-shift-select 'next-line))
19938 (t (org-shiftselect-error))))
19940 (defun org-shiftright (&optional arg)
19941 "Cycle the thing at point or in the current line, depending on context.
19942 Depending on context, this does one of the following:
19944 - switch a timestamp at point one day into the future
19945 - on a headline, switch to the next TODO keyword.
19946 - on an item, switch entire list to the next bullet type
19947 - on a property line, switch to the next allowed value
19948 - on a clocktable definition line, move time block into the future"
19949 (interactive "P")
19950 (cond
19951 ((run-hook-with-args-until-success 'org-shiftright-hook))
19952 ((and org-support-shift-select (org-region-active-p))
19953 (org-call-for-shift-select 'forward-char))
19954 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19955 ((and (not (eq org-support-shift-select 'always))
19956 (org-at-heading-p))
19957 (let ((org-inhibit-logging
19958 (not org-treat-S-cursor-todo-selection-as-state-change))
19959 (org-inhibit-blocking
19960 (not org-treat-S-cursor-todo-selection-as-state-change)))
19961 (org-call-with-arg 'org-todo 'right)))
19962 ((or (and org-support-shift-select
19963 (not (eq org-support-shift-select 'always))
19964 (org-at-item-bullet-p))
19965 (and (not org-support-shift-select) (org-at-item-p)))
19966 (org-call-with-arg 'org-cycle-list-bullet nil))
19967 ((and (not (eq org-support-shift-select 'always))
19968 (org-at-property-p))
19969 (call-interactively 'org-property-next-allowed-value))
19970 ((org-clocktable-try-shift 'right arg))
19971 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19972 (org-support-shift-select
19973 (org-call-for-shift-select 'forward-char))
19974 (t (org-shiftselect-error))))
19976 (defun org-shiftleft (&optional arg)
19977 "Cycle the thing at point or in the current line, depending on context.
19978 Depending on context, this does one of the following:
19980 - switch a timestamp at point one day into the past
19981 - on a headline, switch to the previous TODO keyword.
19982 - on an item, switch entire list to the previous bullet type
19983 - on a property line, switch to the previous allowed value
19984 - on a clocktable definition line, move time block into the past"
19985 (interactive "P")
19986 (cond
19987 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19988 ((and org-support-shift-select (org-region-active-p))
19989 (org-call-for-shift-select 'backward-char))
19990 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19991 ((and (not (eq org-support-shift-select 'always))
19992 (org-at-heading-p))
19993 (let ((org-inhibit-logging
19994 (not org-treat-S-cursor-todo-selection-as-state-change))
19995 (org-inhibit-blocking
19996 (not org-treat-S-cursor-todo-selection-as-state-change)))
19997 (org-call-with-arg 'org-todo 'left)))
19998 ((or (and org-support-shift-select
19999 (not (eq org-support-shift-select 'always))
20000 (org-at-item-bullet-p))
20001 (and (not org-support-shift-select) (org-at-item-p)))
20002 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20003 ((and (not (eq org-support-shift-select 'always))
20004 (org-at-property-p))
20005 (call-interactively 'org-property-previous-allowed-value))
20006 ((org-clocktable-try-shift 'left arg))
20007 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20008 (org-support-shift-select
20009 (org-call-for-shift-select 'backward-char))
20010 (t (org-shiftselect-error))))
20012 (defun org-shiftcontrolright ()
20013 "Switch to next TODO set."
20014 (interactive)
20015 (cond
20016 ((and org-support-shift-select (org-region-active-p))
20017 (org-call-for-shift-select 'forward-word))
20018 ((and (not (eq org-support-shift-select 'always))
20019 (org-at-heading-p))
20020 (org-call-with-arg 'org-todo 'nextset))
20021 (org-support-shift-select
20022 (org-call-for-shift-select 'forward-word))
20023 (t (org-shiftselect-error))))
20025 (defun org-shiftcontrolleft ()
20026 "Switch to previous TODO set."
20027 (interactive)
20028 (cond
20029 ((and org-support-shift-select (org-region-active-p))
20030 (org-call-for-shift-select 'backward-word))
20031 ((and (not (eq org-support-shift-select 'always))
20032 (org-at-heading-p))
20033 (org-call-with-arg 'org-todo 'previousset))
20034 (org-support-shift-select
20035 (org-call-for-shift-select 'backward-word))
20036 (t (org-shiftselect-error))))
20038 (defun org-shiftcontrolup (&optional n)
20039 "Change timestamps synchronously up in CLOCK log lines.
20040 Optional argument N tells to change by that many units."
20041 (interactive "P")
20042 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20043 (let (org-support-shift-select)
20044 (org-clock-timestamps-up n))
20045 (user-error "Not at a clock log")))
20047 (defun org-shiftcontroldown (&optional n)
20048 "Change timestamps synchronously down in CLOCK log lines.
20049 Optional argument N tells to change by that many units."
20050 (interactive "P")
20051 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20052 (let (org-support-shift-select)
20053 (org-clock-timestamps-down n))
20054 (user-error "Not at a clock log")))
20056 (defun org-ctrl-c-ret ()
20057 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20058 (interactive)
20059 (cond
20060 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20061 (t (call-interactively 'org-insert-heading))))
20063 (defun org-find-visible ()
20064 (let ((s (point)))
20065 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20066 (get-char-property s 'invisible)))
20068 (defun org-find-invisible ()
20069 (let ((s (point)))
20070 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20071 (not (get-char-property s 'invisible))))
20074 (defun org-copy-visible (beg end)
20075 "Copy the visible parts of the region."
20076 (interactive "r")
20077 (let (snippets s)
20078 (save-excursion
20079 (save-restriction
20080 (narrow-to-region beg end)
20081 (setq s (goto-char (point-min)))
20082 (while (not (= (point) (point-max)))
20083 (goto-char (org-find-invisible))
20084 (push (buffer-substring s (point)) snippets)
20085 (setq s (goto-char (org-find-visible))))))
20086 (kill-new (apply 'concat (nreverse snippets)))))
20088 (defun org-copy-special ()
20089 "Copy region in table or copy current subtree.
20090 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20091 See the individual commands for more information."
20092 (interactive)
20093 (call-interactively
20094 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20096 (defun org-cut-special ()
20097 "Cut region in table or cut current subtree.
20098 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20099 See the individual commands for more information."
20100 (interactive)
20101 (call-interactively
20102 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20104 (defun org-paste-special (arg)
20105 "Paste rectangular region into table, or past subtree relative to level.
20106 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20107 See the individual commands for more information."
20108 (interactive "P")
20109 (if (org-at-table-p)
20110 (org-table-paste-rectangle)
20111 (org-paste-subtree arg)))
20113 (defsubst org-in-fixed-width-region-p ()
20114 "Is point in a fixed-width region?"
20115 (save-match-data
20116 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20118 (defun org-edit-special (&optional arg)
20119 "Call a special editor for the element at point.
20120 When at a table, call the formula editor with `org-table-edit-formulas'.
20121 When in a source code block, call `org-edit-src-code'.
20122 When in a fixed-width region, call `org-edit-fixed-width-region'.
20123 When at an #+INCLUDE keyword, visit the included file.
20124 On a link, call `ffap' to visit the link at point.
20125 Otherwise, return a user error."
20126 (interactive "P")
20127 (let ((element (org-element-at-point)))
20128 (assert (not buffer-read-only) nil
20129 "Buffer is read-only: %s" (buffer-name))
20130 (case (org-element-type element)
20131 (src-block
20132 (if (not arg) (org-edit-src-code)
20133 (let* ((info (org-babel-get-src-block-info))
20134 (lang (nth 0 info))
20135 (params (nth 2 info))
20136 (session (cdr (assq :session params))))
20137 (if (not session) (org-edit-src-code)
20138 ;; At a src-block with a session and function called with
20139 ;; an ARG: switch to the buffer related to the inferior
20140 ;; process.
20141 (switch-to-buffer
20142 (funcall (intern (concat "org-babel-prep-session:" lang))
20143 session params))))))
20144 (keyword
20145 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20146 (find-file
20147 (org-remove-double-quotes
20148 (car (org-split-string (org-element-property :value element)))))
20149 (user-error "No special environment to edit here")))
20150 (table
20151 (if (eq (org-element-property :type element) 'table.el)
20152 (org-edit-src-code)
20153 (call-interactively 'org-table-edit-formulas)))
20154 ;; Only Org tables contain `table-row' type elements.
20155 (table-row (call-interactively 'org-table-edit-formulas))
20156 ((example-block export-block) (org-edit-src-code))
20157 (fixed-width (org-edit-fixed-width-region))
20158 (otherwise
20159 ;; No notable element at point. Though, we may be at a link,
20160 ;; which is an object. Thus, scan deeper.
20161 (if (eq (org-element-type (org-element-context element)) 'link)
20162 (call-interactively 'ffap)
20163 (user-error "No special environment to edit here"))))))
20165 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20166 (defun org-ctrl-c-ctrl-c (&optional arg)
20167 "Set tags in headline, or update according to changed information at point.
20169 This command does many different things, depending on context:
20171 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20172 this is what we do.
20174 - If the cursor is on a statistics cookie, update it.
20176 - If the cursor is in a headline, prompt for tags and insert them
20177 into the current line, aligned to `org-tags-column'. When called
20178 with prefix arg, realign all tags in the current buffer.
20180 - If the cursor is in one of the special #+KEYWORD lines, this
20181 triggers scanning the buffer for these lines and updating the
20182 information.
20184 - If the cursor is inside a table, realign the table. This command
20185 works even if the automatic table editor has been turned off.
20187 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20188 the entire table.
20190 - If the cursor is at a footnote reference or definition, jump to
20191 the corresponding definition or references, respectively.
20193 - If the cursor is a the beginning of a dynamic block, update it.
20195 - If the current buffer is a capture buffer, close note and file it.
20197 - If the cursor is on a <<<target>>>, update radio targets and
20198 corresponding links in this buffer.
20200 - If the cursor is on a numbered item in a plain list, renumber the
20201 ordered list.
20203 - If the cursor is on a checkbox, toggle it.
20205 - If the cursor is on a code block, evaluate it. The variable
20206 `org-confirm-babel-evaluate' can be used to control prompting
20207 before code block evaluation, by default every code block
20208 evaluation requires confirmation. Code block evaluation can be
20209 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20210 (interactive "P")
20211 (cond
20212 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20213 org-occur-highlights
20214 org-latex-fragment-image-overlays)
20215 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20216 (org-remove-occur-highlights)
20217 (org-remove-latex-fragment-image-overlays)
20218 (message "Temporary highlights/overlays removed from current buffer"))
20219 ((and (local-variable-p 'org-finish-function (current-buffer))
20220 (fboundp org-finish-function))
20221 (funcall org-finish-function))
20222 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20224 (let* ((context (org-element-context)) (type (org-element-type context)))
20225 ;; Test if point is within a blank line.
20226 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20227 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20228 (user-error "C-c C-c can do nothing useful at this location"))
20229 (case type
20230 ;; When at a link, act according to the parent instead.
20231 (link (setq context (org-element-property :parent context))
20232 (setq type (org-element-type context)))
20233 ;; Unsupported object types: check parent element instead.
20234 ((bold code entity export-snippet inline-babel-call inline-src-block
20235 italic latex-fragment line-break macro strike-through subscript
20236 superscript underline verbatim)
20237 (while (and (setq context (org-element-property :parent context))
20238 (not (memq (setq type (org-element-type context))
20239 '(paragraph verse-block)))))))
20240 ;; For convenience: at the first line of a paragraph on the
20241 ;; same line as an item, apply function on that item instead.
20242 (when (eq type 'paragraph)
20243 (let ((parent (org-element-property :parent context)))
20244 (when (and (eq (org-element-type parent) 'item)
20245 (= (point-at-bol) (org-element-property :begin parent)))
20246 (setq context parent type 'item))))
20247 ;; Act according to type of element or object at point.
20248 (case type
20249 (clock (org-clock-update-time-maybe))
20250 (dynamic-block
20251 (save-excursion
20252 (goto-char (org-element-property :post-affiliated context))
20253 (org-update-dblock)))
20254 (footnote-definition
20255 (goto-char (org-element-property :post-affiliated context))
20256 (call-interactively 'org-footnote-action))
20257 (footnote-reference (call-interactively 'org-footnote-action))
20258 ((headline inlinetask)
20259 (save-excursion (goto-char (org-element-property :begin context))
20260 (call-interactively 'org-set-tags)))
20261 (item
20262 ;; At an item: a double C-u set checkbox to "[-]"
20263 ;; unconditionally, whereas a single one will toggle its
20264 ;; presence. Without an universal argument, if the item
20265 ;; has a checkbox, toggle it. Otherwise repair the list.
20266 (let* ((box (org-element-property :checkbox context))
20267 (struct (org-element-property :structure context))
20268 (old-struct (copy-tree struct))
20269 (parents (org-list-parents-alist struct))
20270 (prevs (org-list-prevs-alist struct))
20271 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20272 (org-list-set-checkbox
20273 (org-element-property :begin context) struct
20274 (cond ((equal arg '(16)) "[-]")
20275 ((and (not box) (equal arg '(4))) "[ ]")
20276 ((or (not box) (equal arg '(4))) nil)
20277 ((eq box 'on) "[ ]")
20278 (t "[X]")))
20279 ;; Mimic `org-list-write-struct' but with grabbing
20280 ;; a return value from `org-list-struct-fix-box'.
20281 (org-list-struct-fix-ind struct parents 2)
20282 (org-list-struct-fix-item-end struct)
20283 (org-list-struct-fix-bul struct prevs)
20284 (org-list-struct-fix-ind struct parents)
20285 (let ((block-item
20286 (org-list-struct-fix-box struct parents prevs orderedp)))
20287 (if (and box (equal struct old-struct))
20288 (if (equal arg '(16))
20289 (message "Checkboxes already reset")
20290 (user-error "Cannot toggle this checkbox: %s"
20291 (if (eq box 'on)
20292 "all subitems checked"
20293 "unchecked subitems")))
20294 (org-list-struct-apply-struct struct old-struct)
20295 (org-update-checkbox-count-maybe))
20296 (when block-item
20297 (message "Checkboxes were removed due to empty box at line %d"
20298 (org-current-line block-item))))))
20299 (keyword
20300 (let ((org-inhibit-startup-visibility-stuff t)
20301 (org-startup-align-all-tables nil))
20302 (when (boundp 'org-table-coordinate-overlays)
20303 (mapc 'delete-overlay org-table-coordinate-overlays)
20304 (setq org-table-coordinate-overlays nil))
20305 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20306 (message "Local setup has been refreshed"))
20307 (plain-list
20308 ;; At a plain list, with a double C-u argument, set
20309 ;; checkboxes of each item to "[-]", whereas a single one
20310 ;; will toggle their presence according to the state of the
20311 ;; first item in the list. Without an argument, repair the
20312 ;; list.
20313 (let* ((begin (org-element-property :contents-begin context))
20314 (beginm (move-marker (make-marker) begin))
20315 (struct (org-element-property :structure context))
20316 (old-struct (copy-tree struct))
20317 (first-box (save-excursion
20318 (goto-char begin)
20319 (looking-at org-list-full-item-re)
20320 (match-string-no-properties 3)))
20321 (new-box (cond ((equal arg '(16)) "[-]")
20322 ((equal arg '(4)) (unless first-box "[ ]"))
20323 ((equal first-box "[X]") "[ ]")
20324 (t "[X]"))))
20325 (cond
20326 (arg
20327 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20328 (org-list-get-all-items
20329 begin struct (org-list-prevs-alist struct))))
20330 ((and first-box (eq (point) begin))
20331 ;; For convenience, when point is at bol on the first
20332 ;; item of the list and no argument is provided, simply
20333 ;; toggle checkbox of that item, if any.
20334 (org-list-set-checkbox begin struct new-box)))
20335 (org-list-write-struct
20336 struct (org-list-parents-alist struct) old-struct)
20337 (org-update-checkbox-count-maybe)
20338 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20339 ((property-drawer node-property)
20340 (call-interactively 'org-property-action))
20341 ((radio-target target)
20342 (call-interactively 'org-update-radio-target-regexp))
20343 (statistics-cookie
20344 (call-interactively 'org-update-statistics-cookies))
20345 ((table table-cell table-row)
20346 ;; At a table, recalculate every field and align it. Also
20347 ;; send the table if necessary. If the table has
20348 ;; a `table.el' type, just give up. At a table row or
20349 ;; cell, maybe recalculate line but always align table.
20350 (if (eq (org-element-property :type context) 'table.el)
20351 (message "Use C-c ' to edit table.el tables")
20352 (let ((org-enable-table-editor t))
20353 (if (or (eq type 'table)
20354 ;; Check if point is at a TBLFM line.
20355 (and (eq type 'table-row)
20356 (= (point) (org-element-property :end context))))
20357 (save-excursion
20358 (if (org-at-TBLFM-p)
20359 (progn (require 'org-table)
20360 (org-table-calc-current-TBLFM))
20361 (goto-char (org-element-property :contents-begin context))
20362 (org-call-with-arg 'org-table-recalculate (or arg t))
20363 (orgtbl-send-table 'maybe)))
20364 (org-table-maybe-eval-formula)
20365 (cond (arg (call-interactively 'org-table-recalculate))
20366 ((org-table-maybe-recalculate-line))
20367 (t (org-table-align)))))))
20368 (timestamp (org-timestamp-change 0 'day))
20369 (otherwise
20370 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20371 (user-error
20372 "C-c C-c can do nothing useful at this location")))))))))
20374 (defun org-mode-restart ()
20375 "Restart Org-mode, to scan again for special lines.
20376 Also updates the keyword regular expressions."
20377 (interactive)
20378 (org-mode)
20379 (message "Org-mode restarted"))
20381 (defun org-kill-note-or-show-branches ()
20382 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20383 (interactive)
20384 (if (not org-finish-function)
20385 (progn
20386 (hide-subtree)
20387 (call-interactively 'show-branches))
20388 (let ((org-note-abort t))
20389 (funcall org-finish-function))))
20391 (defun org-open-line (n)
20392 "Insert a new row in tables, call `open-line' elsewhere.
20393 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20394 (interactive "*p")
20395 (cond
20396 ((not org-special-ctrl-o)
20397 (open-line n))
20398 ((org-at-table-p)
20399 (org-table-insert-row))
20401 (open-line n))))
20403 (defun org-return (&optional indent)
20404 "Goto next table row or insert a newline.
20405 Calls `org-table-next-row' or `newline', depending on context.
20406 See the individual commands for more information."
20407 (interactive)
20408 (let (org-ts-what)
20409 (cond
20410 ((or (bobp) (org-in-src-block-p))
20411 (if indent (newline-and-indent) (newline)))
20412 ((org-at-table-p)
20413 (org-table-justify-field-maybe)
20414 (call-interactively 'org-table-next-row))
20415 ;; when `newline-and-indent' is called within a list, make sure
20416 ;; text moved stays inside the item.
20417 ((and (org-in-item-p) indent)
20418 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20419 (progn
20420 (save-match-data (newline))
20421 (org-indent-line-to (length (match-string 0))))
20422 (let ((ind (org-get-indentation)))
20423 (newline)
20424 (if (org-looking-back org-list-end-re)
20425 (org-indent-line)
20426 (org-indent-line-to ind)))))
20427 ((and org-return-follows-link
20428 (org-at-timestamp-p t)
20429 (not (eq org-ts-what 'after)))
20430 (org-follow-timestamp-link))
20431 ((and org-return-follows-link
20432 (let ((tprop (get-text-property (point) 'face)))
20433 (or (eq tprop 'org-link)
20434 (and (listp tprop) (memq 'org-link tprop)))))
20435 (call-interactively 'org-open-at-point))
20436 ((and (org-at-heading-p)
20437 (looking-at
20438 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20439 (org-show-entry)
20440 (end-of-line 1)
20441 (newline))
20442 (t (if indent (newline-and-indent) (newline))))))
20444 (defun org-return-indent ()
20445 "Goto next table row or insert a newline and indent.
20446 Calls `org-table-next-row' or `newline-and-indent', depending on
20447 context. See the individual commands for more information."
20448 (interactive)
20449 (org-return t))
20451 (defun org-ctrl-c-star ()
20452 "Compute table, or change heading status of lines.
20453 Calls `org-table-recalculate' or `org-toggle-heading',
20454 depending on context."
20455 (interactive)
20456 (cond
20457 ((org-at-table-p)
20458 (call-interactively 'org-table-recalculate))
20460 ;; Convert all lines in region to list items
20461 (call-interactively 'org-toggle-heading))))
20463 (defun org-ctrl-c-minus ()
20464 "Insert separator line in table or modify bullet status of line.
20465 Also turns a plain line or a region of lines into list items.
20466 Calls `org-table-insert-hline', `org-toggle-item', or
20467 `org-cycle-list-bullet', depending on context."
20468 (interactive)
20469 (cond
20470 ((org-at-table-p)
20471 (call-interactively 'org-table-insert-hline))
20472 ((org-region-active-p)
20473 (call-interactively 'org-toggle-item))
20474 ((org-in-item-p)
20475 (call-interactively 'org-cycle-list-bullet))
20477 (call-interactively 'org-toggle-item))))
20479 (defun org-toggle-item (arg)
20480 "Convert headings or normal lines to items, items to normal lines.
20481 If there is no active region, only the current line is considered.
20483 If the first non blank line in the region is a headline, convert
20484 all headlines to items, shifting text accordingly.
20486 If it is an item, convert all items to normal lines.
20488 If it is normal text, change region into a list of items.
20489 With a prefix argument ARG, change the region in a single item."
20490 (interactive "P")
20491 (let ((shift-text
20492 (function
20493 ;; Shift text in current section to IND, from point to END.
20494 ;; The function leaves point to END line.
20495 (lambda (ind end)
20496 (let ((min-i 1000) (end (copy-marker end)))
20497 ;; First determine the minimum indentation (MIN-I) of
20498 ;; the text.
20499 (save-excursion
20500 (catch 'exit
20501 (while (< (point) end)
20502 (let ((i (org-get-indentation)))
20503 (cond
20504 ;; Skip blank lines and inline tasks.
20505 ((looking-at "^[ \t]*$"))
20506 ((looking-at org-outline-regexp-bol))
20507 ;; We can't find less than 0 indentation.
20508 ((zerop i) (throw 'exit (setq min-i 0)))
20509 ((< i min-i) (setq min-i i))))
20510 (forward-line))))
20511 ;; Then indent each line so that a line indented to
20512 ;; MIN-I becomes indented to IND. Ignore blank lines
20513 ;; and inline tasks in the process.
20514 (let ((delta (- ind min-i)))
20515 (while (< (point) end)
20516 (unless (or (looking-at "^[ \t]*$")
20517 (looking-at org-outline-regexp-bol))
20518 (org-indent-line-to (+ (org-get-indentation) delta)))
20519 (forward-line)))))))
20520 (skip-blanks
20521 (function
20522 ;; Return beginning of first non-blank line, starting from
20523 ;; line at POS.
20524 (lambda (pos)
20525 (save-excursion
20526 (goto-char pos)
20527 (skip-chars-forward " \r\t\n")
20528 (point-at-bol)))))
20529 beg end)
20530 ;; Determine boundaries of changes.
20531 (if (org-region-active-p)
20532 (setq beg (funcall skip-blanks (region-beginning))
20533 end (copy-marker (region-end)))
20534 (setq beg (funcall skip-blanks (point-at-bol))
20535 end (copy-marker (point-at-eol))))
20536 ;; Depending on the starting line, choose an action on the text
20537 ;; between BEG and END.
20538 (org-with-limited-levels
20539 (save-excursion
20540 (goto-char beg)
20541 (cond
20542 ;; Case 1. Start at an item: de-itemize. Note that it only
20543 ;; happens when a region is active: `org-ctrl-c-minus'
20544 ;; would call `org-cycle-list-bullet' otherwise.
20545 ((org-at-item-p)
20546 (while (< (point) end)
20547 (when (org-at-item-p)
20548 (skip-chars-forward " \t")
20549 (delete-region (point) (match-end 0)))
20550 (forward-line)))
20551 ;; Case 2. Start at an heading: convert to items.
20552 ((org-at-heading-p)
20553 (let* ((bul (org-list-bullet-string "-"))
20554 (bul-len (length bul))
20555 ;; Indentation of the first heading. It should be
20556 ;; relative to the indentation of its parent, if any.
20557 (start-ind (save-excursion
20558 (cond
20559 ((not org-adapt-indentation) 0)
20560 ((not (outline-previous-heading)) 0)
20561 (t (length (match-string 0))))))
20562 ;; Level of first heading. Further headings will be
20563 ;; compared to it to determine hierarchy in the list.
20564 (ref-level (org-reduced-level (org-outline-level))))
20565 (while (< (point) end)
20566 (let* ((level (org-reduced-level (org-outline-level)))
20567 (delta (max 0 (- level ref-level))))
20568 ;; If current headline is less indented than the first
20569 ;; one, set it as reference, in order to preserve
20570 ;; subtrees.
20571 (when (< level ref-level) (setq ref-level level))
20572 (replace-match bul t t)
20573 (org-indent-line-to (+ start-ind (* delta bul-len)))
20574 ;; Ensure all text down to END (or SECTION-END) belongs
20575 ;; to the newly created item.
20576 (let ((section-end (save-excursion
20577 (or (outline-next-heading) (point)))))
20578 (forward-line)
20579 (funcall shift-text
20580 (+ start-ind (* (1+ delta) bul-len))
20581 (min end section-end)))))))
20582 ;; Case 3. Normal line with ARG: make the first line of region
20583 ;; an item, and shift indentation of others lines to
20584 ;; set them as item's body.
20585 (arg (let* ((bul (org-list-bullet-string "-"))
20586 (bul-len (length bul))
20587 (ref-ind (org-get-indentation)))
20588 (skip-chars-forward " \t")
20589 (insert bul)
20590 (forward-line)
20591 (while (< (point) end)
20592 ;; Ensure that lines less indented than first one
20593 ;; still get included in item body.
20594 (funcall shift-text
20595 (+ ref-ind bul-len)
20596 (min end (save-excursion (or (outline-next-heading)
20597 (point)))))
20598 (forward-line))))
20599 ;; Case 4. Normal line without ARG: turn each non-item line
20600 ;; into an item.
20602 (while (< (point) end)
20603 (unless (or (org-at-heading-p) (org-at-item-p))
20604 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20605 (replace-match
20606 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20607 (forward-line))))))))
20609 (defun org-toggle-heading (&optional nstars)
20610 "Convert headings to normal text, or items or text to headings.
20611 If there is no active region, only convert the current line.
20613 With a \\[universal-argument] prefix, convert the whole list at
20614 point into heading.
20616 In a region:
20618 - If the first non blank line is a headline, remove the stars
20619 from all headlines in the region.
20621 - If it is a normal line, turn each and every normal line (i.e.,
20622 not an heading or an item) in the region into headings. If you
20623 want to convert only the first line of this region, use one
20624 universal prefix argument.
20626 - If it is a plain list item, turn all plain list items into headings.
20628 When converting a line into a heading, the number of stars is chosen
20629 such that the lines become children of the current entry. However,
20630 when a numeric prefix argument is given, its value determines the
20631 number of stars to add."
20632 (interactive "P")
20633 (let ((skip-blanks
20634 (function
20635 ;; Return beginning of first non-blank line, starting from
20636 ;; line at POS.
20637 (lambda (pos)
20638 (save-excursion
20639 (goto-char pos)
20640 (while (org-at-comment-p) (forward-line))
20641 (skip-chars-forward " \r\t\n")
20642 (point-at-bol)))))
20643 beg end toggled)
20644 ;; Determine boundaries of changes. If a universal prefix has
20645 ;; been given, put the list in a region. If region ends at a bol,
20646 ;; do not consider the last line to be in the region.
20648 (when (and current-prefix-arg (org-at-item-p))
20649 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20650 (org-mark-element))
20652 (if (org-region-active-p)
20653 (setq beg (funcall skip-blanks (region-beginning))
20654 end (copy-marker (save-excursion
20655 (goto-char (region-end))
20656 (if (bolp) (point) (point-at-eol)))))
20657 (setq beg (funcall skip-blanks (point-at-bol))
20658 end (copy-marker (point-at-eol))))
20659 ;; Ensure inline tasks don't count as headings.
20660 (org-with-limited-levels
20661 (save-excursion
20662 (goto-char beg)
20663 (cond
20664 ;; Case 1. Started at an heading: de-star headings.
20665 ((org-at-heading-p)
20666 (while (< (point) end)
20667 (when (org-at-heading-p t)
20668 (looking-at org-outline-regexp) (replace-match "")
20669 (setq toggled t))
20670 (forward-line)))
20671 ;; Case 2. Started at an item: change items into headlines.
20672 ;; One star will be added by `org-list-to-subtree'.
20673 ((org-at-item-p)
20674 (let* ((stars (make-string
20675 ;; subtract the star that will be added again by
20676 ;; `org-list-to-subtree'
20677 (if (numberp nstars) (1- nstars)
20678 (or (org-current-level) 0))
20679 ?*))
20680 (add-stars
20681 (cond (nstars "") ; stars from prefix only
20682 ((equal stars "") "") ; before first heading
20683 (org-odd-levels-only "*") ; inside heading, odd
20684 (t "")))) ; inside heading, oddeven
20685 (while (< (point) end)
20686 (when (org-at-item-p)
20687 ;; Pay attention to cases when region ends before list.
20688 (let* ((struct (org-list-struct))
20689 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20690 (save-restriction
20691 (narrow-to-region (point) list-end)
20692 (insert
20693 (org-list-to-subtree
20694 (org-list-parse-list t)
20695 '(:istart (concat stars add-stars (funcall get-stars depth))
20696 :icount (concat stars add-stars (funcall get-stars depth)))))))
20697 (setq toggled t))
20698 (forward-line))))
20699 ;; Case 3. Started at normal text: make every line an heading,
20700 ;; skipping headlines and items.
20701 (t (let* ((stars
20702 (make-string
20703 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20704 (add-stars
20705 (cond (nstars "") ; stars from prefix only
20706 ((equal stars "") "*") ; before first heading
20707 (org-odd-levels-only "**") ; inside heading, odd
20708 (t "*"))) ; inside heading, oddeven
20709 (rpl (concat stars add-stars " "))
20710 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20711 (while (< (point) (if (equal nstars '(4)) lend end))
20712 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20713 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20714 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20715 (forward-line)))))))
20716 (unless toggled (message "Cannot toggle heading from here"))))
20718 (defun org-meta-return (&optional arg)
20719 "Insert a new heading or wrap a region in a table.
20720 Calls `org-insert-heading' or `org-table-wrap-region', depending
20721 on context. See the individual commands for more information."
20722 (interactive "P")
20723 (org-check-before-invisible-edit 'insert)
20724 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20725 (let* ((element (org-element-at-point))
20726 (type (org-element-type element)))
20727 (when (eq type 'table-row)
20728 (setq element (org-element-property :parent element))
20729 (setq type 'table))
20730 (if (and (eq type 'table)
20731 (eq (org-element-property :type element) 'org)
20732 (>= (point) (org-element-property :contents-begin element))
20733 (< (point) (org-element-property :contents-end element)))
20734 (call-interactively 'org-table-wrap-region)
20735 (call-interactively 'org-insert-heading)))))
20737 ;;; Menu entries
20739 (defsubst org-in-subtree-not-table-p ()
20740 "Are we in a subtree and not in a table?"
20741 (and (not (org-before-first-heading-p))
20742 (not (org-at-table-p))))
20744 ;; Define the Org-mode menus
20745 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20746 '("Tbl"
20747 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20748 ["Next Field" org-cycle (org-at-table-p)]
20749 ["Previous Field" org-shifttab (org-at-table-p)]
20750 ["Next Row" org-return (org-at-table-p)]
20751 "--"
20752 ["Blank Field" org-table-blank-field (org-at-table-p)]
20753 ["Edit Field" org-table-edit-field (org-at-table-p)]
20754 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20755 "--"
20756 ("Column"
20757 ["Move Column Left" org-metaleft (org-at-table-p)]
20758 ["Move Column Right" org-metaright (org-at-table-p)]
20759 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20760 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20761 ("Row"
20762 ["Move Row Up" org-metaup (org-at-table-p)]
20763 ["Move Row Down" org-metadown (org-at-table-p)]
20764 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20765 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20766 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20767 "--"
20768 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20769 ("Rectangle"
20770 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20771 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20772 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20773 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20774 "--"
20775 ("Calculate"
20776 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20777 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20778 ["Edit Formulas" org-edit-special (org-at-table-p)]
20779 "--"
20780 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20781 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20782 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20783 "--"
20784 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20785 "--"
20786 ["Sum Column/Rectangle" org-table-sum
20787 (or (org-at-table-p) (org-region-active-p))]
20788 ["Which Column?" org-table-current-column (org-at-table-p)])
20789 ["Debug Formulas"
20790 org-table-toggle-formula-debugger
20791 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20792 ["Show Col/Row Numbers"
20793 org-table-toggle-coordinate-overlays
20794 :style toggle
20795 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20796 "--"
20797 ["Create" org-table-create (and (not (org-at-table-p))
20798 org-enable-table-editor)]
20799 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20800 ["Import from File" org-table-import (not (org-at-table-p))]
20801 ["Export to File" org-table-export (org-at-table-p)]
20802 "--"
20803 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20805 (easy-menu-define org-org-menu org-mode-map "Org menu"
20806 '("Org"
20807 ("Show/Hide"
20808 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20809 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20810 ["Sparse Tree..." org-sparse-tree t]
20811 ["Reveal Context" org-reveal t]
20812 ["Show All" show-all t]
20813 "--"
20814 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20815 "--"
20816 ["New Heading" org-insert-heading t]
20817 ("Navigate Headings"
20818 ["Up" outline-up-heading t]
20819 ["Next" outline-next-visible-heading t]
20820 ["Previous" outline-previous-visible-heading t]
20821 ["Next Same Level" outline-forward-same-level t]
20822 ["Previous Same Level" outline-backward-same-level t]
20823 "--"
20824 ["Jump" org-goto t])
20825 ("Edit Structure"
20826 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20827 "--"
20828 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20829 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20830 "--"
20831 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20832 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20833 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20834 "--"
20835 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20836 "--"
20837 ["Copy visible text" org-copy-visible t]
20838 "--"
20839 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20840 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20841 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20842 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20843 "--"
20844 ["Sort Region/Children" org-sort t]
20845 "--"
20846 ["Convert to odd levels" org-convert-to-odd-levels t]
20847 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20848 ("Editing"
20849 ["Emphasis..." org-emphasize t]
20850 ["Edit Source Example" org-edit-special t]
20851 "--"
20852 ["Footnote new/jump" org-footnote-action t]
20853 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20854 ("Archive"
20855 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20856 "--"
20857 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20858 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20859 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20861 "--"
20862 ("Hyperlinks"
20863 ["Store Link (Global)" org-store-link t]
20864 ["Find existing link to here" org-occur-link-in-agenda-files t]
20865 ["Insert Link" org-insert-link t]
20866 ["Follow Link" org-open-at-point t]
20867 "--"
20868 ["Next link" org-next-link t]
20869 ["Previous link" org-previous-link t]
20870 "--"
20871 ["Descriptive Links"
20872 org-toggle-link-display
20873 :style radio
20874 :selected org-descriptive-links
20876 ["Literal Links"
20877 org-toggle-link-display
20878 :style radio
20879 :selected (not org-descriptive-links)])
20880 "--"
20881 ("TODO Lists"
20882 ["TODO/DONE/-" org-todo t]
20883 ("Select keyword"
20884 ["Next keyword" org-shiftright (org-at-heading-p)]
20885 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20886 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20887 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20888 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20889 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20890 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20891 "--"
20892 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20893 :selected org-enforce-todo-dependencies :style toggle :active t]
20894 "Settings for tree at point"
20895 ["Do Children sequentially" org-toggle-ordered-property :style radio
20896 :selected (org-entry-get nil "ORDERED")
20897 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20898 ["Do Children parallel" org-toggle-ordered-property :style radio
20899 :selected (not (org-entry-get nil "ORDERED"))
20900 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20901 "--"
20902 ["Set Priority" org-priority t]
20903 ["Priority Up" org-shiftup t]
20904 ["Priority Down" org-shiftdown t]
20905 "--"
20906 ["Get news from all feeds" org-feed-update-all t]
20907 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20908 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20909 ("TAGS and Properties"
20910 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20911 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20912 "--"
20913 ["Set property" org-set-property (not (org-before-first-heading-p))]
20914 ["Column view of properties" org-columns t]
20915 ["Insert Column View DBlock" org-insert-columns-dblock t])
20916 ("Dates and Scheduling"
20917 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20918 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20919 ("Change Date"
20920 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20921 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20922 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20923 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20924 ["Compute Time Range" org-evaluate-time-range t]
20925 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20926 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20927 "--"
20928 ["Custom time format" org-toggle-time-stamp-overlays
20929 :style radio :selected org-display-custom-times]
20930 "--"
20931 ["Goto Calendar" org-goto-calendar t]
20932 ["Date from Calendar" org-date-from-calendar t]
20933 "--"
20934 ["Start/Restart Timer" org-timer-start t]
20935 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20936 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20937 ["Insert Timer String" org-timer t]
20938 ["Insert Timer Item" org-timer-item t])
20939 ("Logging work"
20940 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20941 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20942 ["Clock out" org-clock-out t]
20943 ["Clock cancel" org-clock-cancel t]
20944 "--"
20945 ["Mark as default task" org-clock-mark-default-task t]
20946 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20947 ["Goto running clock" org-clock-goto t]
20948 "--"
20949 ["Display times" org-clock-display t]
20950 ["Create clock table" org-clock-report t]
20951 "--"
20952 ["Record DONE time"
20953 (progn (setq org-log-done (not org-log-done))
20954 (message "Switching to %s will %s record a timestamp"
20955 (car org-done-keywords)
20956 (if org-log-done "automatically" "not")))
20957 :style toggle :selected org-log-done])
20958 "--"
20959 ["Agenda Command..." org-agenda t]
20960 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20961 ("File List for Agenda")
20962 ("Special views current file"
20963 ["TODO Tree" org-show-todo-tree t]
20964 ["Check Deadlines" org-check-deadlines t]
20965 ["Timeline" org-timeline t]
20966 ["Tags/Property tree" org-match-sparse-tree t])
20967 "--"
20968 ["Export/Publish..." org-export-dispatch t]
20969 ("LaTeX"
20970 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20971 :selected org-cdlatex-mode]
20972 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20973 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20974 ["Modify math symbol" org-cdlatex-math-modify
20975 (org-inside-LaTeX-fragment-p)]
20976 ["Insert citation" org-reftex-citation t]
20977 "--"
20978 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20979 "--"
20980 ("MobileOrg"
20981 ["Push Files and Views" org-mobile-push t]
20982 ["Get Captured and Flagged" org-mobile-pull t]
20983 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20984 "--"
20985 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20986 "--"
20987 ("Documentation"
20988 ["Show Version" org-version t]
20989 ["Info Documentation" org-info t])
20990 ("Customize"
20991 ["Browse Org Group" org-customize t]
20992 "--"
20993 ["Expand This Menu" org-create-customize-menu
20994 (fboundp 'customize-menu-create)])
20995 ["Send bug report" org-submit-bug-report t]
20996 "--"
20997 ("Refresh/Reload"
20998 ["Refresh setup current buffer" org-mode-restart t]
20999 ["Reload Org (after update)" org-reload t]
21000 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21003 (defun org-info (&optional node)
21004 "Read documentation for Org-mode in the info system.
21005 With optional NODE, go directly to that node."
21006 (interactive)
21007 (info (format "(org)%s" (or node ""))))
21009 ;;;###autoload
21010 (defun org-submit-bug-report ()
21011 "Submit a bug report on Org-mode via mail.
21013 Don't hesitate to report any problems or inaccurate documentation.
21015 If you don't have setup sending mail from (X)Emacs, please copy the
21016 output buffer into your mail program, as it gives us important
21017 information about your Org-mode version and configuration."
21018 (interactive)
21019 (require 'reporter)
21020 (org-load-modules-maybe)
21021 (org-require-autoloaded-modules)
21022 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21023 (reporter-submit-bug-report
21024 "emacs-orgmode@gnu.org"
21025 (org-version nil 'full)
21026 (let (list)
21027 (save-window-excursion
21028 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21029 (delete-other-windows)
21030 (erase-buffer)
21031 (insert "You are about to submit a bug report to the Org-mode mailing list.
21033 We would like to add your full Org-mode and Outline configuration to the
21034 bug report. This greatly simplifies the work of the maintainer and
21035 other experts on the mailing list.
21037 HOWEVER, some variables you have customized may contain private
21038 information. The names of customers, colleagues, or friends, might
21039 appear in the form of file names, tags, todo states, or search strings.
21040 If you answer yes to the prompt, you might want to check and remove
21041 such private information before sending the email.")
21042 (add-text-properties (point-min) (point-max) '(face org-warning))
21043 (when (yes-or-no-p "Include your Org-mode configuration ")
21044 (mapatoms
21045 (lambda (v)
21046 (and (boundp v)
21047 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21048 (or (and (symbol-value v)
21049 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21050 (and
21051 (get v 'custom-type) (get v 'standard-value)
21052 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21053 (push v list)))))
21054 (kill-buffer (get-buffer "*Warn about privacy*"))
21055 list))
21056 nil nil
21057 "Remember to cover the basics, that is, what you expected to happen and
21058 what in fact did happen. You don't know how to make a good report? See
21060 http://orgmode.org/manual/Feedback.html#Feedback
21062 Your bug report will be posted to the Org-mode mailing list.
21063 ------------------------------------------------------------------------")
21064 (save-excursion
21065 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21066 (replace-match "\\1Bug: \\3 [\\2]")))))
21069 (defun org-install-agenda-files-menu ()
21070 (let ((bl (buffer-list)))
21071 (save-excursion
21072 (while bl
21073 (set-buffer (pop bl))
21074 (if (derived-mode-p 'org-mode) (setq bl nil)))
21075 (when (derived-mode-p 'org-mode)
21076 (easy-menu-change
21077 '("Org") "File List for Agenda"
21078 (append
21079 (list
21080 ["Edit File List" (org-edit-agenda-file-list) t]
21081 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21082 ["Remove Current File from List" org-remove-file t]
21083 ["Cycle through agenda files" org-cycle-agenda-files t]
21084 ["Occur in all agenda files" org-occur-in-agenda-files t]
21085 "--")
21086 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21088 ;;;; Documentation
21090 (defun org-require-autoloaded-modules ()
21091 (interactive)
21092 (mapc 'require
21093 '(org-agenda org-archive org-attach org-clock org-colview org-id
21094 org-table org-timer)))
21096 ;;;###autoload
21097 (defun org-reload (&optional uncompiled)
21098 "Reload all org lisp files.
21099 With prefix arg UNCOMPILED, load the uncompiled versions."
21100 (interactive "P")
21101 (require 'loadhist)
21102 (let* ((org-dir (org-find-library-dir "org"))
21103 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21104 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21105 (remove-re (mapconcat 'identity
21106 (mapcar (lambda (f) (concat "^" f "$"))
21107 (list (if (featurep 'xemacs)
21108 "org-colview"
21109 "org-colview-xemacs")
21110 "org" "org-loaddefs" "org-version"))
21111 "\\|"))
21112 (feats (delete-dups
21113 (mapcar 'file-name-sans-extension
21114 (mapcar 'file-name-nondirectory
21115 (delq nil
21116 (mapcar 'feature-file
21117 features))))))
21118 (lfeat (append
21119 (sort
21120 (setq feats
21121 (delq nil (mapcar
21122 (lambda (f)
21123 (if (and (string-match feature-re f)
21124 (not (string-match remove-re f)))
21125 f nil))
21126 feats)))
21127 'string-lessp)
21128 (list "org-version" "org")))
21129 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21130 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21131 load-uncore load-misses)
21132 (setq load-misses
21133 (delq 't
21134 (mapcar (lambda (f)
21135 (or (org-load-noerror-mustsuffix (concat org-dir f))
21136 (and (string= org-dir contrib-dir)
21137 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21138 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21139 (add-to-list 'load-uncore f 'append)
21142 lfeat)))
21143 (if load-uncore
21144 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21145 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21146 (if load-misses
21147 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21148 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21149 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21151 ;;;###autoload
21152 (defun org-customize ()
21153 "Call the customize function with org as argument."
21154 (interactive)
21155 (org-load-modules-maybe)
21156 (org-require-autoloaded-modules)
21157 (customize-browse 'org))
21159 (defun org-create-customize-menu ()
21160 "Create a full customization menu for Org-mode, insert it into the menu."
21161 (interactive)
21162 (org-load-modules-maybe)
21163 (org-require-autoloaded-modules)
21164 (if (fboundp 'customize-menu-create)
21165 (progn
21166 (easy-menu-change
21167 '("Org") "Customize"
21168 `(["Browse Org group" org-customize t]
21169 "--"
21170 ,(customize-menu-create 'org)
21171 ["Set" Custom-set t]
21172 ["Save" Custom-save t]
21173 ["Reset to Current" Custom-reset-current t]
21174 ["Reset to Saved" Custom-reset-saved t]
21175 ["Reset to Standard Settings" Custom-reset-standard t]))
21176 (message "\"Org\"-menu now contains full customization menu"))
21177 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21179 ;;;; Miscellaneous stuff
21181 ;;; Generally useful functions
21183 (defun org-get-at-bol (property)
21184 "Get text property PROPERTY at beginning of line."
21185 (get-text-property (point-at-bol) property))
21187 (defun org-find-text-property-in-string (prop s)
21188 "Return the first non-nil value of property PROP in string S."
21189 (or (get-text-property 0 prop s)
21190 (get-text-property (or (next-single-property-change 0 prop s) 0)
21191 prop s)))
21193 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21194 "Display the given MESSAGE as a warning."
21195 (if (fboundp 'display-warning)
21196 (display-warning 'org message
21197 (if (featurep 'xemacs) 'warning :warning))
21198 (let ((buf (get-buffer-create "*Org warnings*")))
21199 (with-current-buffer buf
21200 (goto-char (point-max))
21201 (insert "Warning (Org): " message)
21202 (unless (bolp)
21203 (newline)))
21204 (display-buffer buf)
21205 (sit-for 0))))
21207 (defun org-eval (form)
21208 "Eval FORM and return result."
21209 (condition-case error
21210 (eval form)
21211 (error (format "%%![Error: %s]" error))))
21213 (defun org-in-clocktable-p ()
21214 "Check if the cursor is in a clocktable."
21215 (let ((pos (point)) start)
21216 (save-excursion
21217 (end-of-line 1)
21218 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21219 (setq start (match-beginning 0))
21220 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21221 (>= (match-end 0) pos)
21222 start))))
21224 (defun org-in-commented-line ()
21225 "Is point in a line starting with `#'?"
21226 (equal (char-after (point-at-bol)) ?#))
21228 (defun org-in-indented-comment-line ()
21229 "Is point in a line starting with `#' after some white space?"
21230 (save-excursion
21231 (save-match-data
21232 (goto-char (point-at-bol))
21233 (looking-at "[ \t]*#"))))
21235 (defun org-in-verbatim-emphasis ()
21236 (save-match-data
21237 (and (org-in-regexp org-emph-re 2)
21238 (>= (point) (match-beginning 3))
21239 (<= (point) (match-end 4))
21240 (member (match-string 3) '("=" "~")))))
21242 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21243 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21244 (if (and marker (marker-buffer marker)
21245 (buffer-live-p (marker-buffer marker)))
21246 (progn
21247 (org-pop-to-buffer-same-window (marker-buffer marker))
21248 (if (or (> marker (point-max)) (< marker (point-min)))
21249 (widen))
21250 (goto-char marker)
21251 (org-show-context 'org-goto))
21252 (if bookmark
21253 (bookmark-jump bookmark)
21254 (error "Cannot find location"))))
21256 (defun org-quote-csv-field (s)
21257 "Quote field for inclusion in CSV material."
21258 (if (string-match "[\",]" s)
21259 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21262 (defun org-force-self-insert (N)
21263 "Needed to enforce self-insert under remapping."
21264 (interactive "p")
21265 (self-insert-command N))
21267 (defun org-string-width (s)
21268 "Compute width of string, ignoring invisible characters.
21269 This ignores character with invisibility property `org-link', and also
21270 characters with property `org-cwidth', because these will become invisible
21271 upon the next fontification round."
21272 (let (b l)
21273 (when (or (eq t buffer-invisibility-spec)
21274 (assq 'org-link buffer-invisibility-spec))
21275 (while (setq b (text-property-any 0 (length s)
21276 'invisible 'org-link s))
21277 (setq s (concat (substring s 0 b)
21278 (substring s (or (next-single-property-change
21279 b 'invisible s) (length s)))))))
21280 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21281 (setq s (concat (substring s 0 b)
21282 (substring s (or (next-single-property-change
21283 b 'org-cwidth s) (length s))))))
21284 (setq l (string-width s) b -1)
21285 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21286 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21289 (defun org-shorten-string (s maxlength)
21290 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21291 If the string is shorter or has length MAXLENGTH, just return the
21292 original string. If it is longer, the functions finds a space in the
21293 string, breaks this string off at that locations and adds three dots
21294 as ellipsis. Including the ellipsis, the string will not be longer
21295 than MAXLENGTH. If finding a good breaking point in the string does
21296 not work, the string is just chopped off in the middle of a word
21297 if necessary."
21298 (if (<= (length s) maxlength)
21300 (let* ((n (max (- maxlength 4) 1))
21301 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21302 (if (string-match re s)
21303 (concat (match-string 1 s) "...")
21304 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21306 (defun org-get-indentation (&optional line)
21307 "Get the indentation of the current line, interpreting tabs.
21308 When LINE is given, assume it represents a line and compute its indentation."
21309 (if line
21310 (if (string-match "^ *" (org-remove-tabs line))
21311 (match-end 0))
21312 (save-excursion
21313 (beginning-of-line 1)
21314 (skip-chars-forward " \t")
21315 (current-column))))
21317 (defun org-get-string-indentation (s)
21318 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21319 (let ((n -1) (i 0) (w tab-width) c)
21320 (catch 'exit
21321 (while (< (setq n (1+ n)) (length s))
21322 (setq c (aref s n))
21323 (cond ((= c ?\ ) (setq i (1+ i)))
21324 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21325 (t (throw 'exit t)))))
21328 (defun org-remove-tabs (s &optional width)
21329 "Replace tabulators in S with spaces.
21330 Assumes that s is a single line, starting in column 0."
21331 (setq width (or width tab-width))
21332 (while (string-match "\t" s)
21333 (setq s (replace-match
21334 (make-string
21335 (- (* width (/ (+ (match-beginning 0) width) width))
21336 (match-beginning 0)) ?\ )
21337 t t s)))
21340 (defun org-fix-indentation (line ind)
21341 "Fix indentation in LINE.
21342 IND is a cons cell with target and minimum indentation.
21343 If the current indentation in LINE is smaller than the minimum,
21344 leave it alone. If it is larger than ind, set it to the target."
21345 (let* ((l (org-remove-tabs line))
21346 (i (org-get-indentation l))
21347 (i1 (car ind)) (i2 (cdr ind)))
21348 (if (>= i i2) (setq l (substring line i2)))
21349 (if (> i1 0)
21350 (concat (make-string i1 ?\ ) l)
21351 l)))
21353 (defun org-remove-indentation (code &optional n)
21354 "Remove the maximum common indentation from the lines in CODE.
21355 N may optionally be the number of spaces to remove."
21356 (with-temp-buffer
21357 (insert code)
21358 (org-do-remove-indentation n)
21359 (buffer-string)))
21361 (defun org-do-remove-indentation (&optional n)
21362 "Remove the maximum common indentation from the buffer."
21363 (untabify (point-min) (point-max))
21364 (let ((min 10000) re)
21365 (if n
21366 (setq min n)
21367 (goto-char (point-min))
21368 (while (re-search-forward "^ *[^ \n]" nil t)
21369 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21370 (unless (or (= min 0) (= min 10000))
21371 (setq re (format "^ \\{%d\\}" min))
21372 (goto-char (point-min))
21373 (while (re-search-forward re nil t)
21374 (replace-match "")
21375 (end-of-line 1))
21376 min)))
21378 (defun org-fill-template (template alist)
21379 "Find each %key of ALIST in TEMPLATE and replace it."
21380 (let ((case-fold-search nil)
21381 entry key value)
21382 (setq alist (sort (copy-sequence alist)
21383 (lambda (a b) (< (length (car a)) (length (car b))))))
21384 (while (setq entry (pop alist))
21385 (setq template
21386 (replace-regexp-in-string
21387 (concat "%" (regexp-quote (car entry)))
21388 (or (cdr entry) "") template t t)))
21389 template))
21391 (defun org-base-buffer (buffer)
21392 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21393 (if (not buffer)
21394 buffer
21395 (or (buffer-base-buffer buffer)
21396 buffer)))
21398 (defun org-trim (s)
21399 "Remove whitespace at beginning and end of string."
21400 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21401 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21404 (defun org-wrap (string &optional width lines)
21405 "Wrap string to either a number of lines, or a width in characters.
21406 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21407 that costs. If there is a word longer than WIDTH, the text is actually
21408 wrapped to the length of that word.
21409 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21410 many lines, whatever width that takes.
21411 The return value is a list of lines, without newlines at the end."
21412 (let* ((words (org-split-string string "[ \t\n]+"))
21413 (maxword (apply 'max (mapcar 'org-string-width words)))
21414 w ll)
21415 (cond (width
21416 (org-do-wrap words (max maxword width)))
21417 (lines
21418 (setq w maxword)
21419 (setq ll (org-do-wrap words maxword))
21420 (if (<= (length ll) lines)
21422 (setq ll words)
21423 (while (> (length ll) lines)
21424 (setq w (1+ w))
21425 (setq ll (org-do-wrap words w)))
21426 ll))
21427 (t (error "Cannot wrap this")))))
21429 (defun org-do-wrap (words width)
21430 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21431 (let (lines line)
21432 (while words
21433 (setq line (pop words))
21434 (while (and words (< (+ (length line) (length (car words))) width))
21435 (setq line (concat line " " (pop words))))
21436 (setq lines (push line lines)))
21437 (nreverse lines)))
21439 (defun org-split-string (string &optional separators)
21440 "Splits STRING into substrings at SEPARATORS.
21441 No empty strings are returned if there are matches at the beginning
21442 and end of string."
21443 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21444 (start 0)
21445 notfirst
21446 (list nil))
21447 (while (and (string-match rexp string
21448 (if (and notfirst
21449 (= start (match-beginning 0))
21450 (< start (length string)))
21451 (1+ start) start))
21452 (< (match-beginning 0) (length string)))
21453 (setq notfirst t)
21454 (or (eq (match-beginning 0) 0)
21455 (and (eq (match-beginning 0) (match-end 0))
21456 (eq (match-beginning 0) start))
21457 (setq list
21458 (cons (substring string start (match-beginning 0))
21459 list)))
21460 (setq start (match-end 0)))
21461 (or (eq start (length string))
21462 (setq list
21463 (cons (substring string start)
21464 list)))
21465 (nreverse list)))
21467 (defun org-quote-vert (s)
21468 "Replace \"|\" with \"\\vert\"."
21469 (while (string-match "|" s)
21470 (setq s (replace-match "\\vert" t t s)))
21473 (defun org-uuidgen-p (s)
21474 "Is S an ID created by UUIDGEN?"
21475 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21477 (defun org-in-src-block-p (&optional inside)
21478 "Whether point is in a code source block.
21479 When INSIDE is non-nil, don't consider we are within a src block
21480 when point is at #+BEGIN_SRC or #+END_SRC."
21481 (let ((case-fold-search t) ov)
21482 (or (and (setq ov (overlays-at (point)))
21483 (memq 'org-block-background
21484 (overlay-properties (car ov))))
21485 (and (not inside)
21486 (save-match-data
21487 (save-excursion
21488 (beginning-of-line)
21489 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21491 (defun org-context ()
21492 "Return a list of contexts of the current cursor position.
21493 If several contexts apply, all are returned.
21494 Each context entry is a list with a symbol naming the context, and
21495 two positions indicating start and end of the context. Possible
21496 contexts are:
21498 :headline anywhere in a headline
21499 :headline-stars on the leading stars in a headline
21500 :todo-keyword on a TODO keyword (including DONE) in a headline
21501 :tags on the TAGS in a headline
21502 :priority on the priority cookie in a headline
21503 :item on the first line of a plain list item
21504 :item-bullet on the bullet/number of a plain list item
21505 :checkbox on the checkbox in a plain list item
21506 :table in an org-mode table
21507 :table-special on a special filed in a table
21508 :table-table in a table.el table
21509 :clocktable in a clocktable
21510 :src-block in a source block
21511 :link on a hyperlink
21512 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21513 :target on a <<target>>
21514 :radio-target on a <<<radio-target>>>
21515 :latex-fragment on a LaTeX fragment
21516 :latex-preview on a LaTeX fragment with overlaid preview image
21518 This function expects the position to be visible because it uses font-lock
21519 faces as a help to recognize the following contexts: :table-special, :link,
21520 and :keyword."
21521 (let* ((f (get-text-property (point) 'face))
21522 (faces (if (listp f) f (list f)))
21523 (case-fold-search t)
21524 (p (point)) clist o)
21525 ;; First the large context
21526 (cond
21527 ((org-at-heading-p t)
21528 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21529 (when (progn
21530 (beginning-of-line 1)
21531 (looking-at org-todo-line-tags-regexp))
21532 (push (org-point-in-group p 1 :headline-stars) clist)
21533 (push (org-point-in-group p 2 :todo-keyword) clist)
21534 (push (org-point-in-group p 4 :tags) clist))
21535 (goto-char p)
21536 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21537 (if (looking-at "\\[#[A-Z0-9]\\]")
21538 (push (org-point-in-group p 0 :priority) clist)))
21540 ((org-at-item-p)
21541 (push (org-point-in-group p 2 :item-bullet) clist)
21542 (push (list :item (point-at-bol)
21543 (save-excursion (org-end-of-item) (point)))
21544 clist)
21545 (and (org-at-item-checkbox-p)
21546 (push (org-point-in-group p 0 :checkbox) clist)))
21548 ((org-at-table-p)
21549 (push (list :table (org-table-begin) (org-table-end)) clist)
21550 (if (memq 'org-formula faces)
21551 (push (list :table-special
21552 (previous-single-property-change p 'face)
21553 (next-single-property-change p 'face)) clist)))
21554 ((org-at-table-p 'any)
21555 (push (list :table-table) clist)))
21556 (goto-char p)
21558 (let ((case-fold-search t))
21559 ;; New the "medium" contexts: clocktables, source blocks
21560 (cond ((org-in-clocktable-p)
21561 (push (list :clocktable
21562 (and (or (looking-at "#\\+BEGIN: clocktable")
21563 (search-backward "#+BEGIN: clocktable" nil t))
21564 (match-beginning 0))
21565 (and (re-search-forward "#\\+END:?" nil t)
21566 (match-end 0))) clist))
21567 ((org-in-src-block-p)
21568 (push (list :src-block
21569 (and (or (looking-at "#\\+BEGIN_SRC")
21570 (search-backward "#+BEGIN_SRC" nil t))
21571 (match-beginning 0))
21572 (and (search-forward "#+END_SRC" nil t)
21573 (match-beginning 0))) clist))))
21574 (goto-char p)
21576 ;; Now the small context
21577 (cond
21578 ((org-at-timestamp-p)
21579 (push (org-point-in-group p 0 :timestamp) clist))
21580 ((memq 'org-link faces)
21581 (push (list :link
21582 (previous-single-property-change p 'face)
21583 (next-single-property-change p 'face)) clist))
21584 ((memq 'org-special-keyword faces)
21585 (push (list :keyword
21586 (previous-single-property-change p 'face)
21587 (next-single-property-change p 'face)) clist))
21588 ((org-at-target-p)
21589 (push (org-point-in-group p 0 :target) clist)
21590 (goto-char (1- (match-beginning 0)))
21591 (if (looking-at org-radio-target-regexp)
21592 (push (org-point-in-group p 0 :radio-target) clist))
21593 (goto-char p))
21594 ((setq o (car (delq nil
21595 (mapcar
21596 (lambda (x)
21597 (if (memq x org-latex-fragment-image-overlays) x))
21598 (overlays-at (point))))))
21599 (push (list :latex-fragment
21600 (overlay-start o) (overlay-end o)) clist)
21601 (push (list :latex-preview
21602 (overlay-start o) (overlay-end o)) clist))
21603 ((org-inside-LaTeX-fragment-p)
21604 ;; FIXME: positions wrong.
21605 (push (list :latex-fragment (point) (point)) clist)))
21607 (setq clist (nreverse (delq nil clist)))
21608 clist))
21610 ;; FIXME: Compare with at-regexp-p Do we need both?
21611 (defun org-in-regexp (re &optional nlines visually)
21612 "Check if point is inside a match of regexp.
21613 Normally only the current line is checked, but you can include NLINES extra
21614 lines both before and after point into the search.
21615 If VISUALLY is set, require that the cursor is not after the match but
21616 really on, so that the block visually is on the match."
21617 (catch 'exit
21618 (let ((pos (point))
21619 (eol (point-at-eol (+ 1 (or nlines 0))))
21620 (inc (if visually 1 0)))
21621 (save-excursion
21622 (beginning-of-line (- 1 (or nlines 0)))
21623 (while (re-search-forward re eol t)
21624 (if (and (<= (match-beginning 0) pos)
21625 (>= (+ inc (match-end 0)) pos))
21626 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21628 (defun org-at-regexp-p (regexp)
21629 "Is point inside a match of REGEXP in the current line?"
21630 (catch 'exit
21631 (save-excursion
21632 (let ((pos (point)) (end (point-at-eol)))
21633 (beginning-of-line 1)
21634 (while (re-search-forward regexp end t)
21635 (if (and (<= (match-beginning 0) pos)
21636 (>= (match-end 0) pos))
21637 (throw 'exit t)))
21638 nil))))
21640 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21641 "Non-nil when point is between matches of START-RE and END-RE.
21643 Also return a non-nil value when point is on one of the matches.
21645 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21646 buffer positions. Default values are the positions of headlines
21647 surrounding the point.
21649 The functions returns a cons cell whose car (resp. cdr) is the
21650 position before START-RE (resp. after END-RE)."
21651 (save-match-data
21652 (let ((pos (point))
21653 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21654 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21655 beg end)
21656 (save-excursion
21657 ;; Point is on a block when on START-RE or if START-RE can be
21658 ;; found before it...
21659 (and (or (org-at-regexp-p start-re)
21660 (re-search-backward start-re limit-up t))
21661 (setq beg (match-beginning 0))
21662 ;; ... and END-RE after it...
21663 (goto-char (match-end 0))
21664 (re-search-forward end-re limit-down t)
21665 (> (setq end (match-end 0)) pos)
21666 ;; ... without another START-RE in-between.
21667 (goto-char (match-beginning 0))
21668 (not (re-search-backward start-re (1+ beg) t))
21669 ;; Return value.
21670 (cons beg end))))))
21672 (defun org-in-block-p (names)
21673 "Non-nil when point belongs to a block whose name belongs to NAMES.
21675 NAMES is a list of strings containing names of blocks.
21677 Return first block name matched, or nil. Beware that in case of
21678 nested blocks, the returned name may not belong to the closest
21679 block from point."
21680 (save-match-data
21681 (catch 'exit
21682 (let ((case-fold-search t)
21683 (lim-up (save-excursion (outline-previous-heading)))
21684 (lim-down (save-excursion (outline-next-heading))))
21685 (mapc (lambda (name)
21686 (let ((n (regexp-quote name)))
21687 (when (org-between-regexps-p
21688 (concat "^[ \t]*#\\+begin_" n)
21689 (concat "^[ \t]*#\\+end_" n)
21690 lim-up lim-down)
21691 (throw 'exit n))))
21692 names))
21693 nil)))
21695 (defun org-in-drawer-p ()
21696 "Is point within a drawer?"
21697 (save-match-data
21698 (let ((case-fold-search t)
21699 (lim-up (save-excursion (outline-previous-heading)))
21700 (lim-down (save-excursion (outline-next-heading))))
21701 (org-between-regexps-p
21702 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21703 "^[ \t]*:end:.*$"
21704 lim-up lim-down))))
21706 (defun org-occur-in-agenda-files (regexp &optional nlines)
21707 "Call `multi-occur' with buffers for all agenda files."
21708 (interactive "sOrg-files matching: \np")
21709 (let* ((files (org-agenda-files))
21710 (tnames (mapcar 'file-truename files))
21711 (extra org-agenda-text-search-extra-files)
21713 (when (eq (car extra) 'agenda-archives)
21714 (setq extra (cdr extra))
21715 (setq files (org-add-archive-files files)))
21716 (while (setq f (pop extra))
21717 (unless (member (file-truename f) tnames)
21718 (add-to-list 'files f 'append)
21719 (add-to-list 'tnames (file-truename f) 'append)))
21720 (multi-occur
21721 (mapcar (lambda (x)
21722 (with-current-buffer
21723 (or (get-file-buffer x) (find-file-noselect x))
21724 (widen)
21725 (current-buffer)))
21726 files)
21727 regexp)))
21729 (if (boundp 'occur-mode-find-occurrence-hook)
21730 ;; Emacs 23
21731 (add-hook 'occur-mode-find-occurrence-hook
21732 (lambda ()
21733 (when (derived-mode-p 'org-mode)
21734 (org-reveal))))
21735 ;; Emacs 22
21736 (defadvice occur-mode-goto-occurrence
21737 (after org-occur-reveal activate)
21738 (and (derived-mode-p 'org-mode) (org-reveal)))
21739 (defadvice occur-mode-goto-occurrence-other-window
21740 (after org-occur-reveal activate)
21741 (and (derived-mode-p 'org-mode) (org-reveal)))
21742 (defadvice occur-mode-display-occurrence
21743 (after org-occur-reveal activate)
21744 (when (derived-mode-p 'org-mode)
21745 (let ((pos (occur-mode-find-occurrence)))
21746 (with-current-buffer (marker-buffer pos)
21747 (save-excursion
21748 (goto-char pos)
21749 (org-reveal)))))))
21751 (defun org-occur-link-in-agenda-files ()
21752 "Create a link and search for it in the agendas.
21753 The link is not stored in `org-stored-links', it is just created
21754 for the search purpose."
21755 (interactive)
21756 (let ((link (condition-case nil
21757 (org-store-link nil)
21758 (error "Unable to create a link to here"))))
21759 (org-occur-in-agenda-files (regexp-quote link))))
21761 (defun org-reverse-string (string)
21762 "Return the reverse of STRING."
21763 (apply 'string (reverse (string-to-list string))))
21765 (defsubst org-uniquify (list)
21766 "Non-destructively remove duplicate elements from LIST."
21767 (let ((res (copy-sequence list))) (delete-dups res)))
21769 (defun org-uniquify-alist (alist)
21770 "Merge elements of ALIST with the same key.
21772 For example, in this alist:
21774 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21775 => '((a 1 3) (b 2))
21777 merge (a 1) and (a 3) into (a 1 3).
21779 The function returns the new ALIST."
21780 (let (rtn)
21781 (mapc
21782 (lambda (e)
21783 (let (n)
21784 (if (not (assoc (car e) rtn))
21785 (push e rtn)
21786 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21787 (setq rtn (assq-delete-all (car e) rtn))
21788 (push n rtn))))
21789 alist)
21790 rtn))
21792 (defun org-delete-all (elts list)
21793 "Remove all elements in ELTS from LIST."
21794 (while elts
21795 (setq list (delete (pop elts) list)))
21796 list)
21798 (defun org-count (cl-item cl-seq)
21799 "Count the number of occurrences of ITEM in SEQ.
21800 Taken from `count' in cl-seq.el with all keyword arguments removed."
21801 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21802 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21803 (while (< cl-start cl-end)
21804 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21805 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21806 (setq cl-start (1+ cl-start)))
21807 cl-count))
21809 (defun org-remove-if (predicate seq)
21810 "Remove everything from SEQ that fulfills PREDICATE."
21811 (let (res e)
21812 (while seq
21813 (setq e (pop seq))
21814 (if (not (funcall predicate e)) (push e res)))
21815 (nreverse res)))
21817 (defun org-remove-if-not (predicate seq)
21818 "Remove everything from SEQ that does not fulfill PREDICATE."
21819 (let (res e)
21820 (while seq
21821 (setq e (pop seq))
21822 (if (funcall predicate e) (push e res)))
21823 (nreverse res)))
21825 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21826 "Reduce two-argument FUNCTION across SEQ.
21827 Taken from `reduce' in cl-seq.el with all keyword arguments but
21828 \":initial-value\" removed."
21829 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21830 (cadr (memq :initial-value cl-keys)))
21831 (cl-seq (pop cl-seq))
21832 (t (funcall cl-func)))))
21833 (while cl-seq
21834 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21835 cl-accum))
21837 (defun org-every (pred seq)
21838 "Return true if PREDICATE is true of every element of SEQ.
21839 Adapted from `every' in cl.el."
21840 (catch 'org-every
21841 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21844 (defun org-some (pred seq)
21845 "Return true if PREDICATE is true of any element of SEQ.
21846 Adapted from `some' in cl.el."
21847 (catch 'org-some
21848 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21849 nil))
21851 (defun org-back-over-empty-lines ()
21852 "Move backwards over whitespace, to the beginning of the first empty line.
21853 Returns the number of empty lines passed."
21854 (let ((pos (point)))
21855 (if (cdr (assoc 'heading org-blank-before-new-entry))
21856 (skip-chars-backward " \t\n\r")
21857 (unless (eobp)
21858 (forward-line -1)))
21859 (beginning-of-line 2)
21860 (goto-char (min (point) pos))
21861 (count-lines (point) pos)))
21863 (defun org-skip-whitespace ()
21864 (skip-chars-forward " \t\n\r"))
21866 (defun org-point-in-group (point group &optional context)
21867 "Check if POINT is in match-group GROUP.
21868 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21869 match. If the match group does not exist or point is not inside it,
21870 return nil."
21871 (and (match-beginning group)
21872 (>= point (match-beginning group))
21873 (<= point (match-end group))
21874 (if context
21875 (list context (match-beginning group) (match-end group))
21876 t)))
21878 (defun org-switch-to-buffer-other-window (&rest args)
21879 "Switch to buffer in a second window on the current frame.
21880 In particular, do not allow pop-up frames.
21881 Returns the newly created buffer."
21882 (org-no-popups
21883 (apply 'switch-to-buffer-other-window args)))
21885 (defun org-combine-plists (&rest plists)
21886 "Create a single property list from all plists in PLISTS.
21887 The process starts by copying the first list, and then setting properties
21888 from the other lists. Settings in the last list are the most significant
21889 ones and overrule settings in the other lists."
21890 (let ((rtn (copy-sequence (pop plists)))
21891 p v ls)
21892 (while plists
21893 (setq ls (pop plists))
21894 (while ls
21895 (setq p (pop ls) v (pop ls))
21896 (setq rtn (plist-put rtn p v))))
21897 rtn))
21899 (defun org-replace-escapes (string table)
21900 "Replace %-escapes in STRING with values in TABLE.
21901 TABLE is an association list with keys like \"%a\" and string values.
21902 The sequences in STRING may contain normal field width and padding information,
21903 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21904 so values can contain further %-escapes if they are define later in TABLE."
21905 (let ((tbl (copy-alist table))
21906 (case-fold-search nil)
21907 (pchg 0)
21908 e re rpl)
21909 (while (setq e (pop tbl))
21910 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21911 (when (and (cdr e) (string-match re (cdr e)))
21912 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21913 (safe "SREF"))
21914 (add-text-properties 0 3 (list 'sref sref) safe)
21915 (setcdr e (replace-match safe t t (cdr e)))))
21916 (while (string-match re string)
21917 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21918 (cdr e)))
21919 (setq string (replace-match rpl t t string))))
21920 (while (setq pchg (next-property-change pchg string))
21921 (let ((sref (get-text-property pchg 'sref string)))
21922 (when (and sref (string-match "SREF" string pchg))
21923 (setq string (replace-match sref t t string)))))
21924 string))
21926 (defun org-sublist (list start end)
21927 "Return a section of LIST, from START to END.
21928 Counting starts at 1."
21929 (let (rtn (c start))
21930 (setq list (nthcdr (1- start) list))
21931 (while (and list (<= c end))
21932 (push (pop list) rtn)
21933 (setq c (1+ c)))
21934 (nreverse rtn)))
21936 (defun org-find-base-buffer-visiting (file)
21937 "Like `find-buffer-visiting' but always return the base buffer and
21938 not an indirect buffer."
21939 (let ((buf (or (get-file-buffer file)
21940 (find-buffer-visiting file))))
21941 (if buf
21942 (or (buffer-base-buffer buf) buf)
21943 nil)))
21945 (defun org-image-file-name-regexp (&optional extensions)
21946 "Return regexp matching the file names of images.
21947 If EXTENSIONS is given, only match these."
21948 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21949 (image-file-name-regexp)
21950 (let ((image-file-name-extensions
21951 (or extensions
21952 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21953 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21954 (concat "\\."
21955 (regexp-opt (nconc (mapcar 'upcase
21956 image-file-name-extensions)
21957 image-file-name-extensions)
21959 "\\'"))))
21961 (defun org-file-image-p (file &optional extensions)
21962 "Return non-nil if FILE is an image."
21963 (save-match-data
21964 (string-match (org-image-file-name-regexp extensions) file)))
21966 (defun org-get-cursor-date (&optional with-time)
21967 "Return the date at cursor in as a time.
21968 This works in the calendar and in the agenda, anywhere else it just
21969 returns the current time.
21970 If WITH-TIME is non-nil, returns the time of the event at point (in
21971 the agenda) or the current time of the day."
21972 (let (date day defd tp tm hod mod)
21973 (when with-time
21974 (setq tp (get-text-property (point) 'time))
21975 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21976 (setq hod (string-to-number (match-string 1 tp))
21977 mod (string-to-number (match-string 2 tp))))
21978 (or tp (setq hod (nth 2 (decode-time (current-time)))
21979 mod (nth 1 (decode-time (current-time))))))
21980 (cond
21981 ((eq major-mode 'calendar-mode)
21982 (setq date (calendar-cursor-to-date)
21983 defd (encode-time 0 (or mod 0) (or hod 0)
21984 (nth 1 date) (nth 0 date) (nth 2 date))))
21985 ((eq major-mode 'org-agenda-mode)
21986 (setq day (get-text-property (point) 'day))
21987 (if day
21988 (setq date (calendar-gregorian-from-absolute day)
21989 defd (encode-time 0 (or mod 0) (or hod 0)
21990 (nth 1 date) (nth 0 date) (nth 2 date))))))
21991 (or defd (current-time))))
21993 (defun org-mark-subtree (&optional up)
21994 "Mark the current subtree.
21995 This puts point at the start of the current subtree, and mark at
21996 the end. If a numeric prefix UP is given, move up into the
21997 hierarchy of headlines by UP levels before marking the subtree."
21998 (interactive "P")
21999 (org-with-limited-levels
22000 (cond ((org-at-heading-p) (beginning-of-line))
22001 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22002 (t (outline-previous-visible-heading 1))))
22003 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22004 (if (org-called-interactively-p 'any)
22005 (call-interactively 'org-mark-element)
22006 (org-mark-element)))
22009 ;;; Indentation
22011 (defun org-indent-line ()
22012 "Indent line depending on context."
22013 (interactive)
22014 (let* ((pos (point))
22015 (itemp (org-at-item-p))
22016 (case-fold-search t)
22017 (org-drawer-regexp (or org-drawer-regexp "\000"))
22018 (inline-task-p (and (featurep 'org-inlinetask)
22019 (org-inlinetask-in-task-p)))
22020 (inline-re (and inline-task-p
22021 (org-inlinetask-outline-regexp)))
22022 column)
22023 (if (and orgstruct-is-++ (eq pos (point)))
22024 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22025 (indent-according-to-mode))
22026 (beginning-of-line 1)
22027 (cond
22028 ;; Headings
22029 ((looking-at org-outline-regexp) (setq column 0))
22030 ;; Footnote definition
22031 ((looking-at org-footnote-definition-re) (setq column 0))
22032 ;; Literal examples
22033 ((looking-at "[ \t]*:\\( \\|$\\)")
22034 (setq column (org-get-indentation))) ; do nothing
22035 ;; Lists
22036 ((ignore-errors (goto-char (org-in-item-p)))
22037 (setq column (if itemp
22038 (org-get-indentation)
22039 (org-list-item-body-column (point))))
22040 (goto-char pos))
22041 ;; Drawers
22042 ((and (looking-at "[ \t]*:END:")
22043 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22044 (save-excursion
22045 (goto-char (1- (match-beginning 1)))
22046 (setq column (current-column))))
22047 ;; Special blocks
22048 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22049 (save-excursion
22050 (re-search-backward
22051 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22052 (setq column (org-get-indentation (match-string 0))))
22053 ((and (not (looking-at "[ \t]*#\\+begin_"))
22054 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22055 (save-excursion
22056 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22057 (setq column
22058 (cond ((equal (downcase (match-string 1)) "src")
22059 ;; src blocks: let `org-edit-src-exit' handle them
22060 (org-get-indentation))
22061 ((equal (downcase (match-string 1)) "example")
22062 (max (org-get-indentation)
22063 (org-get-indentation (match-string 0))))
22065 (org-get-indentation (match-string 0))))))
22066 ;; This line has nothing special, look at the previous relevant
22067 ;; line to compute indentation
22069 (beginning-of-line 0)
22070 (while (and (not (bobp))
22071 (not (looking-at org-table-line-regexp))
22072 (not (looking-at org-drawer-regexp))
22073 ;; When point started in an inline task, do not move
22074 ;; above task starting line.
22075 (not (and inline-task-p (looking-at inline-re)))
22076 ;; Skip drawers, blocks, empty lines, verbatim,
22077 ;; comments, tables, footnotes definitions, lists,
22078 ;; inline tasks.
22079 (or (and (looking-at "[ \t]*:END:")
22080 (re-search-backward org-drawer-regexp nil t))
22081 (and (looking-at "[ \t]*#\\+end_")
22082 (re-search-backward "[ \t]*#\\+begin_"nil t))
22083 (looking-at "[ \t]*[\n:#|]")
22084 (looking-at org-footnote-definition-re)
22085 (and (not inline-task-p)
22086 (featurep 'org-inlinetask)
22087 (org-inlinetask-in-task-p)
22088 (or (org-inlinetask-goto-beginning) t))))
22089 (beginning-of-line 0))
22090 (cond
22091 ;; There was a list item above.
22092 ((ignore-errors (goto-char (org-in-item-p)))
22093 (goto-char (org-list-get-top-point (org-list-struct)))
22094 (setq column (org-get-indentation)))
22095 ;; There was an heading above.
22096 ((looking-at "\\*+[ \t]+")
22097 (if (not org-adapt-indentation)
22098 (setq column 0)
22099 (goto-char (match-end 0))
22100 (setq column (current-column))))
22101 ;; A drawer had started and is unfinished
22102 ((looking-at org-drawer-regexp)
22103 (goto-char (1- (match-beginning 1)))
22104 (setq column (current-column)))
22105 ;; Else, nothing noticeable found: get indentation and go on.
22106 (t (setq column (org-get-indentation))))))
22107 ;; Now apply indentation and move cursor accordingly
22108 (goto-char pos)
22109 (if (<= (current-column) (current-indentation))
22110 (org-indent-line-to column)
22111 (save-excursion (org-indent-line-to column)))
22112 ;; Special polishing for properties, see `org-property-format'
22113 (setq column (current-column))
22114 (beginning-of-line 1)
22115 (if (looking-at org-property-re)
22116 (replace-match (concat (match-string 4)
22117 (format org-property-format
22118 (match-string 1) (match-string 3)))
22119 t t))
22120 (org-move-to-column column))))
22122 (defun org-indent-drawer ()
22123 "Indent the drawer at point."
22124 (interactive)
22125 (let ((p (point))
22126 (e (and (save-excursion (re-search-forward ":END:" nil t))
22127 (match-end 0)))
22128 (folded
22129 (save-excursion
22130 (end-of-line)
22131 (when (overlays-at (point))
22132 (member 'invisible (overlay-properties
22133 (car (overlays-at (point)))))))))
22134 (when folded (org-cycle))
22135 (indent-for-tab-command)
22136 (while (and (move-beginning-of-line 2) (< (point) e))
22137 (indent-for-tab-command))
22138 (goto-char p)
22139 (when folded (org-cycle)))
22140 (message "Drawer at point indented"))
22142 (defun org-indent-block ()
22143 "Indent the block at point."
22144 (interactive)
22145 (let ((p (point))
22146 (case-fold-search t)
22147 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22148 (match-end 0)))
22149 (folded
22150 (save-excursion
22151 (end-of-line)
22152 (when (overlays-at (point))
22153 (member 'invisible (overlay-properties
22154 (car (overlays-at (point)))))))))
22155 (when folded (org-cycle))
22156 (indent-for-tab-command)
22157 (while (and (move-beginning-of-line 2) (< (point) e))
22158 (indent-for-tab-command))
22159 (goto-char p)
22160 (when folded (org-cycle)))
22161 (message "Block at point indented"))
22163 (defun org-indent-region (start end)
22164 "Indent region."
22165 (interactive "r")
22166 (save-excursion
22167 (let ((line-end (org-current-line end)))
22168 (goto-char start)
22169 (while (< (org-current-line) line-end)
22170 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22171 (t (call-interactively 'org-indent-line)))
22172 (move-beginning-of-line 2)))))
22175 ;;; Filling
22177 ;; We use our own fill-paragraph and auto-fill functions.
22179 ;; `org-fill-paragraph' relies on adaptive filling and context
22180 ;; checking. Appropriate `fill-prefix' is computed with
22181 ;; `org-adaptive-fill-function'.
22183 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22184 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22185 ;; `org-adaptive-fill-function' value. Internally,
22186 ;; `org-comment-line-break-function' breaks the line.
22188 ;; `org-setup-filling' installs filling and auto-filling related
22189 ;; variables during `org-mode' initialization.
22191 (defvar org-element-paragraph-separate) ; org-element.el
22192 (defun org-setup-filling ()
22193 (require 'org-element)
22194 ;; Prevent auto-fill from inserting unwanted new items.
22195 (when (boundp 'fill-nobreak-predicate)
22196 (org-set-local
22197 'fill-nobreak-predicate
22198 (org-uniquify
22199 (append fill-nobreak-predicate
22200 '(org-fill-line-break-nobreak-p
22201 org-fill-paragraph-with-timestamp-nobreak-p)))))
22202 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22203 (org-set-local 'paragraph-start paragraph-ending)
22204 (org-set-local 'paragraph-separate paragraph-ending))
22205 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22206 (org-set-local 'auto-fill-inhibit-regexp nil)
22207 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22208 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22209 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22211 (defun org-fill-line-break-nobreak-p ()
22212 "Non-nil when a new line at point would create an Org line break."
22213 (save-excursion
22214 (skip-chars-backward "[ \t]")
22215 (skip-chars-backward "\\\\")
22216 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22218 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22219 "Non-nil when a new line at point would split a timestamp."
22220 (and (org-at-timestamp-p t)
22221 (not (looking-at org-ts-regexp-both))))
22223 (declare-function message-in-body-p "message" ())
22224 (defvar orgtbl-line-start-regexp) ; From org-table.el
22225 (defun org-adaptive-fill-function ()
22226 "Compute a fill prefix for the current line.
22227 Return fill prefix, as a string, or nil if current line isn't
22228 meant to be filled. For convenience, if `adaptive-fill-regexp'
22229 matches in paragraphs or comments, use it."
22230 (catch 'exit
22231 (when (derived-mode-p 'message-mode)
22232 (save-excursion
22233 (beginning-of-line)
22234 (cond ((or (not (message-in-body-p))
22235 (looking-at orgtbl-line-start-regexp))
22236 (throw 'exit nil))
22237 ((looking-at message-cite-prefix-regexp)
22238 (throw 'exit (match-string-no-properties 0)))
22239 ((looking-at org-outline-regexp)
22240 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22241 (org-with-wide-buffer
22242 (let* ((p (line-beginning-position))
22243 (element (save-excursion
22244 (beginning-of-line)
22245 (or (ignore-errors (org-element-at-point))
22246 (user-error "An element cannot be parsed line %d"
22247 (line-number-at-pos (point))))))
22248 (type (org-element-type element))
22249 (post-affiliated (org-element-property :post-affiliated element)))
22250 (unless (and post-affiliated (< p post-affiliated))
22251 (case type
22252 (comment
22253 (save-excursion
22254 (beginning-of-line)
22255 (looking-at "[ \t]*")
22256 (concat (match-string 0) "# ")))
22257 (footnote-definition "")
22258 ((item plain-list)
22259 (make-string (org-list-item-body-column
22260 (or post-affiliated
22261 (org-element-property :begin element)))
22262 ? ))
22263 (paragraph
22264 ;; Fill prefix is usually the same as the current line,
22265 ;; unless the paragraph is at the beginning of an item.
22266 (let ((parent (org-element-property :parent element)))
22267 (save-excursion
22268 (beginning-of-line)
22269 (cond ((eq (org-element-type parent) 'item)
22270 (make-string (org-list-item-body-column
22271 (org-element-property :begin parent))
22272 ? ))
22273 ((and adaptive-fill-regexp
22274 ;; Locally disable
22275 ;; `adaptive-fill-function' to let
22276 ;; `fill-context-prefix' handle
22277 ;; `adaptive-fill-regexp' variable.
22278 (let (adaptive-fill-function)
22279 (fill-context-prefix
22280 post-affiliated
22281 (org-element-property :end element)))))
22282 ((looking-at "[ \t]+") (match-string 0))
22283 (t "")))))
22284 (comment-block
22285 ;; Only fill contents if P is within block boundaries.
22286 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22287 (forward-line)
22288 (point)))
22289 (cend (save-excursion
22290 (goto-char (org-element-property :end element))
22291 (skip-chars-backward " \r\t\n")
22292 (line-beginning-position))))
22293 (when (and (>= p cbeg) (< p cend))
22294 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22295 (match-string 0)
22296 ""))))))))))
22298 (declare-function message-goto-body "message" ())
22299 (defvar message-cite-prefix-regexp) ; From message.el
22300 (defun org-fill-paragraph (&optional justify)
22301 "Fill element at point, when applicable.
22303 This function only applies to comment blocks, comments, example
22304 blocks and paragraphs. Also, as a special case, re-align table
22305 when point is at one.
22307 If JUSTIFY is non-nil (interactively, with prefix argument),
22308 justify as well. If `sentence-end-double-space' is non-nil, then
22309 period followed by one space does not end a sentence, so don't
22310 break a line there. The variable `fill-column' controls the
22311 width for filling.
22313 For convenience, when point is at a plain list, an item or
22314 a footnote definition, try to fill the first paragraph within."
22315 (interactive)
22316 (if (and (derived-mode-p 'message-mode)
22317 (or (not (message-in-body-p))
22318 (save-excursion (move-beginning-of-line 1)
22319 (looking-at message-cite-prefix-regexp))))
22320 ;; First ensure filling is correct in message-mode.
22321 (let ((fill-paragraph-function
22322 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22323 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22324 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22325 (paragraph-separate
22326 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22327 (fill-paragraph nil))
22328 (with-syntax-table org-mode-transpose-word-syntax-table
22329 ;; Move to end of line in order to get the first paragraph
22330 ;; within a plain list or a footnote definition.
22331 (let ((element (save-excursion
22332 (end-of-line)
22333 (or (ignore-errors (org-element-at-point))
22334 (user-error "An element cannot be parsed line %d"
22335 (line-number-at-pos (point)))))))
22336 ;; First check if point is in a blank line at the beginning of
22337 ;; the buffer. In that case, ignore filling.
22338 (case (org-element-type element)
22339 ;; Use major mode filling function is src blocks.
22340 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22341 ;; Align Org tables, leave table.el tables as-is.
22342 (table-row (org-table-align) t)
22343 (table
22344 (when (eq (org-element-property :type element) 'org)
22345 (save-excursion
22346 (goto-char (org-element-property :post-affiliated element))
22347 (org-table-align)))
22349 (paragraph
22350 ;; Paragraphs may contain `line-break' type objects.
22351 (let ((beg (max (point-min)
22352 (org-element-property :contents-begin element)))
22353 (end (min (point-max)
22354 (org-element-property :contents-end element))))
22355 ;; Do nothing if point is at an affiliated keyword.
22356 (if (< (line-end-position) beg) t
22357 (when (derived-mode-p 'message-mode)
22358 ;; In `message-mode', do not fill following citation
22359 ;; in current paragraph nor text before message body.
22360 (let ((body-start (save-excursion (message-goto-body))))
22361 (when body-start (setq beg (max body-start beg))))
22362 (when (save-excursion
22363 (re-search-forward
22364 (concat "^" message-cite-prefix-regexp) end t))
22365 (setq end (match-beginning 0))))
22366 ;; Fill paragraph, taking line breaks into account.
22367 ;; For that, slice the paragraph using line breaks as
22368 ;; separators, and fill the parts in reverse order to
22369 ;; avoid messing with markers.
22370 (save-excursion
22371 (goto-char end)
22372 (mapc
22373 (lambda (pos)
22374 (fill-region-as-paragraph pos (point) justify)
22375 (goto-char pos))
22376 ;; Find the list of ending positions for line breaks
22377 ;; in the current paragraph. Add paragraph
22378 ;; beginning to include first slice.
22379 (nreverse
22380 (cons beg
22381 (org-element-map
22382 (org-element--parse-objects
22383 beg end nil (org-element-restriction 'paragraph))
22384 'line-break
22385 (lambda (lb) (org-element-property :end lb)))))))
22386 t)))
22387 ;; Contents of `comment-block' type elements should be
22388 ;; filled as plain text, but only if point is within block
22389 ;; markers.
22390 (comment-block
22391 (let* ((case-fold-search t)
22392 (beg (save-excursion
22393 (goto-char (org-element-property :begin element))
22394 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22395 (forward-line)
22396 (point)))
22397 (end (save-excursion
22398 (goto-char (org-element-property :end element))
22399 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22400 (line-beginning-position))))
22401 (if (or (< (point) beg) (> (point) end)) t
22402 (fill-region-as-paragraph
22403 (save-excursion (end-of-line)
22404 (re-search-backward "^[ \t]*$" beg 'move)
22405 (line-beginning-position))
22406 (save-excursion (beginning-of-line)
22407 (re-search-forward "^[ \t]*$" end 'move)
22408 (line-beginning-position))
22409 justify))))
22410 ;; Fill comments.
22411 (comment
22412 (let ((begin (org-element-property :post-affiliated element))
22413 (end (org-element-property :end element)))
22414 (when (and (>= (point) begin) (<= (point) end))
22415 (let ((begin (save-excursion
22416 (end-of-line)
22417 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22418 (progn (forward-line) (point))
22419 begin)))
22420 (end (save-excursion
22421 (end-of-line)
22422 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22423 (1- (line-beginning-position))
22424 (skip-chars-backward " \r\t\n")
22425 (line-end-position)))))
22426 ;; Do not fill comments when at a blank line.
22427 (when (> end begin)
22428 (let ((fill-prefix
22429 (save-excursion
22430 (beginning-of-line)
22431 (looking-at "[ \t]*#")
22432 (let ((comment-prefix (match-string 0)))
22433 (goto-char (match-end 0))
22434 (if (looking-at adaptive-fill-regexp)
22435 (concat comment-prefix (match-string 0))
22436 (concat comment-prefix " "))))))
22437 (save-excursion
22438 (fill-region-as-paragraph begin end justify))))))
22440 ;; Ignore every other element.
22441 (otherwise t))))))
22443 (defun org-auto-fill-function ()
22444 "Auto-fill function."
22445 ;; Check if auto-filling is meaningful.
22446 (let ((fc (current-fill-column)))
22447 (when (and fc (> (current-column) fc))
22448 (let* ((fill-prefix (org-adaptive-fill-function))
22449 ;; Enforce empty fill prefix, if required. Otherwise, it
22450 ;; will be computed again.
22451 (adaptive-fill-mode (not (equal fill-prefix ""))))
22452 (when fill-prefix (do-auto-fill))))))
22454 (defun org-comment-line-break-function (&optional soft)
22455 "Break line at point and indent, continuing comment if within one.
22456 The inserted newline is marked hard if variable
22457 `use-hard-newlines' is true, unless optional argument SOFT is
22458 non-nil."
22459 (if soft (insert-and-inherit ?\n) (newline 1))
22460 (save-excursion (forward-char -1) (delete-horizontal-space))
22461 (delete-horizontal-space)
22462 (indent-to-left-margin)
22463 (insert-before-markers-and-inherit fill-prefix))
22466 ;;; Comments
22468 ;; Org comments syntax is quite complex. It requires the entire line
22469 ;; to be just a comment. Also, even with the right syntax at the
22470 ;; beginning of line, some some elements (i.e. verse-block or
22471 ;; example-block) don't accept comments. Usual Emacs comment commands
22472 ;; cannot cope with those requirements. Therefore, Org replaces them.
22474 ;; Org still relies on `comment-dwim', but cannot trust
22475 ;; `comment-only-p'. So, `comment-region-function' and
22476 ;; `uncomment-region-function' both point
22477 ;; to`org-comment-or-uncomment-region'. Eventually,
22478 ;; `org-insert-comment' takes care of insertion of comments at the
22479 ;; beginning of line.
22481 ;; `org-setup-comments-handling' install comments related variables
22482 ;; during `org-mode' initialization.
22484 (defun org-setup-comments-handling ()
22485 (interactive)
22486 (org-set-local 'comment-use-syntax nil)
22487 (org-set-local 'comment-start "# ")
22488 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22489 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22490 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22491 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22493 (defun org-insert-comment ()
22494 "Insert an empty comment above current line.
22495 If the line is empty, insert comment at its beginning."
22496 (beginning-of-line)
22497 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22498 (org-indent-line)
22499 (insert "# "))
22501 (defvar comment-empty-lines) ; From newcomment.el.
22502 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22503 "Comment or uncomment each non-blank line in the region.
22504 Uncomment each non-blank line between BEG and END if it only
22505 contains commented lines. Otherwise, comment them."
22506 (save-restriction
22507 ;; Restrict region
22508 (narrow-to-region (save-excursion (goto-char beg)
22509 (skip-chars-forward " \r\t\n" end)
22510 (line-beginning-position))
22511 (save-excursion (goto-char end)
22512 (skip-chars-backward " \r\t\n" beg)
22513 (line-end-position)))
22514 (let ((uncommentp
22515 ;; UNCOMMENTP is non-nil when every non blank line between
22516 ;; BEG and END is a comment.
22517 (save-excursion
22518 (goto-char (point-min))
22519 (while (and (not (eobp))
22520 (let ((element (org-element-at-point)))
22521 (and (eq (org-element-type element) 'comment)
22522 (goto-char (min (point-max)
22523 (org-element-property
22524 :end element)))))))
22525 (eobp))))
22526 (if uncommentp
22527 ;; Only blank lines and comments in region: uncomment it.
22528 (save-excursion
22529 (goto-char (point-min))
22530 (while (not (eobp))
22531 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22532 (replace-match "" nil nil nil 1))
22533 (forward-line)))
22534 ;; Comment each line in region.
22535 (let ((min-indent (point-max)))
22536 ;; First find the minimum indentation across all lines.
22537 (save-excursion
22538 (goto-char (point-min))
22539 (while (and (not (eobp)) (not (zerop min-indent)))
22540 (unless (looking-at "[ \t]*$")
22541 (setq min-indent (min min-indent (current-indentation))))
22542 (forward-line)))
22543 ;; Then loop over all lines.
22544 (save-excursion
22545 (goto-char (point-min))
22546 (while (not (eobp))
22547 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22548 ;; Don't get fooled by invisible text (e.g. link path)
22549 ;; when moving to column MIN-INDENT.
22550 (let ((buffer-invisibility-spec nil))
22551 (org-move-to-column min-indent t))
22552 (insert comment-start))
22553 (forward-line))))))))
22556 ;;; Planning
22558 ;; This section contains tools to operate on timestamp objects, as
22559 ;; returned by, e.g. `org-element-context'.
22561 (defun org-timestamp-has-time-p (timestamp)
22562 "Non-nil when TIMESTAMP has a time specified."
22563 (org-element-property :hour-start timestamp))
22565 (defun org-timestamp-format (timestamp format &optional end utc)
22566 "Format a TIMESTAMP element into a string.
22568 FORMAT is a format specifier to be passed to
22569 `format-time-string'.
22571 When optional argument END is non-nil, use end of date-range or
22572 time-range, if possible.
22574 When optional argument UTC is non-nil, time will be expressed as
22575 Universal Time."
22576 (format-time-string
22577 format
22578 (apply 'encode-time
22579 (cons 0
22580 (mapcar
22581 (lambda (prop) (or (org-element-property prop timestamp) 0))
22582 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22583 '(:minute-start :hour-start :day-start :month-start
22584 :year-start)))))
22585 utc))
22587 (defun org-timestamp-split-range (timestamp &optional end)
22588 "Extract a timestamp object from a date or time range.
22590 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22591 the end of the range. Otherwise, extract its start.
22593 Return a new timestamp object sharing the same parent as
22594 TIMESTAMP."
22595 (let ((type (org-element-property :type timestamp)))
22596 (if (memq type '(active inactive diary)) timestamp
22597 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22598 ;; Set new type.
22599 (org-element-put-property
22600 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22601 ;; Copy start properties over end properties if END is
22602 ;; non-nil. Otherwise, copy end properties over `start' ones.
22603 (let ((p-alist '((:minute-start . :minute-end)
22604 (:hour-start . :hour-end)
22605 (:day-start . :day-end)
22606 (:month-start . :month-end)
22607 (:year-start . :year-end))))
22608 (dolist (p-cell p-alist)
22609 (org-element-put-property
22610 split-ts
22611 (funcall (if end 'car 'cdr) p-cell)
22612 (org-element-property
22613 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22614 ;; Eventually refresh `:raw-value'.
22615 (org-element-put-property split-ts :raw-value nil)
22616 (org-element-put-property
22617 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22619 (defun org-timestamp-translate (timestamp &optional boundary)
22620 "Apply `org-translate-time' on a TIMESTAMP object.
22621 When optional argument BOUNDARY is non-nil, it is either the
22622 symbol `start' or `end'. In this case, only translate the
22623 starting or ending part of TIMESTAMP if it is a date or time
22624 range. Otherwise, translate both parts."
22625 (if (and (not boundary)
22626 (memq (org-element-property :type timestamp)
22627 '(active-range inactive-range)))
22628 (concat
22629 (org-translate-time
22630 (org-element-property :raw-value
22631 (org-timestamp-split-range timestamp)))
22632 "--"
22633 (org-translate-time
22634 (org-element-property :raw-value
22635 (org-timestamp-split-range timestamp t))))
22636 (org-translate-time
22637 (org-element-property
22638 :raw-value
22639 (if (not boundary) timestamp
22640 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22644 ;;; Other stuff.
22646 (defun org-toggle-fixed-width-section (arg)
22647 "Toggle the fixed-width export.
22648 If there is no active region, the QUOTE keyword at the current headline is
22649 inserted or removed. When present, it causes the text between this headline
22650 and the next to be exported as fixed-width text, and unmodified.
22651 If there is an active region, this command adds or removes a colon as the
22652 first character of this line. If the first character of a line is a colon,
22653 this line is also exported in fixed-width font."
22654 (interactive "P")
22655 (let* ((cc 0)
22656 (regionp (org-region-active-p))
22657 (beg (if regionp (region-beginning) (point)))
22658 (end (if regionp (region-end)))
22659 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22660 (case-fold-search nil)
22661 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22662 off)
22663 (if regionp
22664 (save-excursion
22665 (goto-char beg)
22666 (setq cc (current-column))
22667 (beginning-of-line 1)
22668 (setq off (looking-at re))
22669 (while (> nlines 0)
22670 (setq nlines (1- nlines))
22671 (beginning-of-line 1)
22672 (cond
22673 (arg
22674 (org-move-to-column cc t)
22675 (insert ": \n")
22676 (forward-line -1))
22677 ((and off (looking-at re))
22678 (replace-match "" t t nil 1))
22679 ((not off) (org-move-to-column cc t) (insert ": ")))
22680 (forward-line 1)))
22681 (save-excursion
22682 (org-back-to-heading)
22683 (cond
22684 ((looking-at (format org-heading-keyword-regexp-format
22685 org-quote-string))
22686 (goto-char (match-end 1))
22687 (looking-at (concat " +" org-quote-string))
22688 (replace-match "" t t)
22689 (when (eolp) (insert " ")))
22690 ((looking-at org-outline-regexp)
22691 (goto-char (match-end 0))
22692 (insert org-quote-string " ")))))))
22694 (defun org-reftex-citation ()
22695 "Use reftex-citation to insert a citation into the buffer.
22696 This looks for a line like
22698 #+BIBLIOGRAPHY: foo plain option:-d
22700 and derives from it that foo.bib is the bibliography file relevant
22701 for this document. It then installs the necessary environment for RefTeX
22702 to work in this buffer and calls `reftex-citation' to insert a citation
22703 into the buffer.
22705 Export of such citations to both LaTeX and HTML is handled by the contributed
22706 package ox-bibtex by Taru Karttunen."
22707 (interactive)
22708 (let ((reftex-docstruct-symbol 'rds)
22709 (reftex-cite-format "\\cite{%l}")
22710 rds bib)
22711 (save-excursion
22712 (save-restriction
22713 (widen)
22714 (let ((case-fold-search t)
22715 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22716 (if (not (save-excursion
22717 (or (re-search-forward re nil t)
22718 (re-search-backward re nil t))))
22719 (error "No bibliography defined in file")
22720 (setq bib (concat (match-string 1) ".bib")
22721 rds (list (list 'bib bib)))))))
22722 (call-interactively 'reftex-citation)))
22724 ;;;; Functions extending outline functionality
22726 (defun org-beginning-of-line (&optional arg)
22727 "Go to the beginning of the current line. If that is invisible, continue
22728 to a visible line beginning. This makes the function of C-a more intuitive.
22729 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22730 first attempt, and only move to after the tags when the cursor is already
22731 beyond the end of the headline."
22732 (interactive "P")
22733 (let ((pos (point))
22734 (special (if (consp org-special-ctrl-a/e)
22735 (car org-special-ctrl-a/e)
22736 org-special-ctrl-a/e))
22737 deactivate-mark refpos)
22738 (if (org-bound-and-true-p visual-line-mode)
22739 (beginning-of-visual-line 1)
22740 (beginning-of-line 1))
22741 (if (and arg (fboundp 'move-beginning-of-line))
22742 (call-interactively 'move-beginning-of-line)
22743 (if (bobp)
22745 (backward-char 1)
22746 (if (org-truely-invisible-p)
22747 (while (and (not (bobp)) (org-truely-invisible-p))
22748 (backward-char 1)
22749 (beginning-of-line 1))
22750 (forward-char 1))))
22751 (when special
22752 (cond
22753 ((and (looking-at org-complex-heading-regexp)
22754 (= (char-after (match-end 1)) ?\ ))
22755 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22756 (point-at-eol)))
22757 (goto-char
22758 (if (eq special t)
22759 (cond ((> pos refpos) refpos)
22760 ((= pos (point)) refpos)
22761 (t (point)))
22762 (cond ((> pos (point)) (point))
22763 ((not (eq last-command this-command)) (point))
22764 (t refpos)))))
22765 ((org-at-item-p)
22766 ;; Being at an item and not looking at an the item means point
22767 ;; was previously moved to beginning of a visual line, which
22768 ;; doesn't contain the item. Therefore, do nothing special,
22769 ;; just stay here.
22770 (when (looking-at org-list-full-item-re)
22771 ;; Set special position at first white space character after
22772 ;; bullet, and check-box, if any.
22773 (let ((after-bullet
22774 (let ((box (match-end 3)))
22775 (if (not box) (match-end 1)
22776 (let ((after (char-after box)))
22777 (if (and after (= after ? )) (1+ box) box))))))
22778 ;; Special case: Move point to special position when
22779 ;; currently after it or at beginning of line.
22780 (if (eq special t)
22781 (when (or (> pos after-bullet) (= (point) pos))
22782 (goto-char after-bullet))
22783 ;; Reversed case: Move point to special position when
22784 ;; point was already at beginning of line and command is
22785 ;; repeated.
22786 (when (and (= (point) pos) (eq last-command this-command))
22787 (goto-char after-bullet))))))))
22788 (org-no-warnings
22789 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22790 (setq disable-point-adjustment
22791 (or (not (invisible-p (point)))
22792 (not (invisible-p (max (point-min) (1- (point))))))))
22794 (defun org-end-of-line (&optional arg)
22795 "Go to the end of the line.
22796 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22797 tags on the first attempt, and only move to after the tags when
22798 the cursor is already beyond the end of the headline."
22799 (interactive "P")
22800 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22801 org-special-ctrl-a/e))
22802 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22803 'end-of-visual-line)
22804 ((fboundp 'move-end-of-line) 'move-end-of-line)
22805 (t 'end-of-line)))
22806 deactivate-mark)
22807 (if (or (not special) arg) (call-interactively move-fun)
22808 (let* ((element (save-excursion (beginning-of-line)
22809 (org-element-at-point)))
22810 (type (org-element-type element)))
22811 (cond
22812 ((memq type '(headline inlinetask))
22813 (let ((pos (point)))
22814 (beginning-of-line 1)
22815 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22816 (if (eq special t)
22817 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22818 (goto-char (match-beginning 1))
22819 (goto-char (match-end 0)))
22820 (if (or (< pos (match-end 0))
22821 (not (eq this-command last-command)))
22822 (goto-char (match-end 0))
22823 (goto-char (match-beginning 1))))
22824 (call-interactively move-fun))))
22825 ((org-element-property :hiddenp element)
22826 ;; If element is hidden, `move-end-of-line' would put point
22827 ;; after it. Use `end-of-line' to stay on current line.
22828 (call-interactively 'end-of-line))
22829 (t (call-interactively move-fun)))))
22830 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22831 (setq disable-point-adjustment
22832 (or (not (invisible-p (point)))
22833 (not (invisible-p (max (point-min) (1- (point))))))))
22835 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22836 (define-key org-mode-map "\C-e" 'org-end-of-line)
22838 (defun org-backward-sentence (&optional arg)
22839 "Go to beginning of sentence, or beginning of table field.
22840 This will call `backward-sentence' or `org-table-beginning-of-field',
22841 depending on context."
22842 (interactive "P")
22843 (cond
22844 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22845 (t (call-interactively 'backward-sentence))))
22847 (defun org-forward-sentence (&optional arg)
22848 "Go to end of sentence, or end of table field.
22849 This will call `forward-sentence' or `org-table-end-of-field',
22850 depending on context."
22851 (interactive "P")
22852 (cond
22853 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22854 (t (call-interactively 'forward-sentence))))
22856 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22857 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22859 (defun org-kill-line (&optional arg)
22860 "Kill line, to tags or end of line."
22861 (interactive "P")
22862 (cond
22863 ((or (not org-special-ctrl-k)
22864 (bolp)
22865 (not (org-at-heading-p)))
22866 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22867 org-ctrl-k-protect-subtree)
22868 (if (or (eq org-ctrl-k-protect-subtree 'error)
22869 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22870 (user-error "C-k aborted as it would kill a hidden subtree")))
22871 (call-interactively
22872 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22873 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22874 (kill-region (point) (match-beginning 1))
22875 (org-set-tags nil t))
22876 (t (kill-region (point) (point-at-eol)))))
22878 (define-key org-mode-map "\C-k" 'org-kill-line)
22880 (defun org-yank (&optional arg)
22881 "Yank. If the kill is a subtree, treat it specially.
22882 This command will look at the current kill and check if is a single
22883 subtree, or a series of subtrees[1]. If it passes the test, and if the
22884 cursor is at the beginning of a line or after the stars of a currently
22885 empty headline, then the yank is handled specially. How exactly depends
22886 on the value of the following variables, both set by default.
22888 org-yank-folded-subtrees
22889 When set, the subtree(s) will be folded after insertion, but only
22890 if doing so would now swallow text after the yanked text.
22892 org-yank-adjusted-subtrees
22893 When set, the subtree will be promoted or demoted in order to
22894 fit into the local outline tree structure, which means that the level
22895 will be adjusted so that it becomes the smaller one of the two
22896 *visible* surrounding headings.
22898 Any prefix to this command will cause `yank' to be called directly with
22899 no special treatment. In particular, a simple \\[universal-argument] prefix \
22900 will just
22901 plainly yank the text as it is.
22903 \[1] The test checks if the first non-white line is a heading
22904 and if there are no other headings with fewer stars."
22905 (interactive "P")
22906 (org-yank-generic 'yank arg))
22908 (defun org-yank-generic (command arg)
22909 "Perform some yank-like command.
22911 This function implements the behavior described in the `org-yank'
22912 documentation. However, it has been generalized to work for any
22913 interactive command with similar behavior."
22915 ;; pretend to be command COMMAND
22916 (setq this-command command)
22918 (if arg
22919 (call-interactively command)
22921 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22922 (and (org-kill-is-subtree-p)
22923 (or (bolp)
22924 (and (looking-at "[ \t]*$")
22925 (string-match
22926 "\\`\\*+\\'"
22927 (buffer-substring (point-at-bol) (point)))))))
22928 swallowp)
22929 (cond
22930 ((and subtreep org-yank-folded-subtrees)
22931 (let ((beg (point))
22932 end)
22933 (if (and subtreep org-yank-adjusted-subtrees)
22934 (org-paste-subtree nil nil 'for-yank)
22935 (call-interactively command))
22937 (setq end (point))
22938 (goto-char beg)
22939 (when (and (bolp) subtreep
22940 (not (setq swallowp
22941 (org-yank-folding-would-swallow-text beg end))))
22942 (org-with-limited-levels
22943 (or (looking-at org-outline-regexp)
22944 (re-search-forward org-outline-regexp-bol end t))
22945 (while (and (< (point) end) (looking-at org-outline-regexp))
22946 (hide-subtree)
22947 (org-cycle-show-empty-lines 'folded)
22948 (condition-case nil
22949 (outline-forward-same-level 1)
22950 (error (goto-char end))))))
22951 (when swallowp
22952 (message
22953 "Inserted text not folded because that would swallow text"))
22955 (goto-char end)
22956 (skip-chars-forward " \t\n\r")
22957 (beginning-of-line 1)
22958 (push-mark beg 'nomsg)))
22959 ((and subtreep org-yank-adjusted-subtrees)
22960 (let ((beg (point-at-bol)))
22961 (org-paste-subtree nil nil 'for-yank)
22962 (push-mark beg 'nomsg)))
22964 (call-interactively command))))))
22966 (defun org-yank-folding-would-swallow-text (beg end)
22967 "Would hide-subtree at BEG swallow any text after END?"
22968 (let (level)
22969 (org-with-limited-levels
22970 (save-excursion
22971 (goto-char beg)
22972 (when (or (looking-at org-outline-regexp)
22973 (re-search-forward org-outline-regexp-bol end t))
22974 (setq level (org-outline-level)))
22975 (goto-char end)
22976 (skip-chars-forward " \t\r\n\v\f")
22977 (if (or (eobp)
22978 (and (bolp) (looking-at org-outline-regexp)
22979 (<= (org-outline-level) level)))
22980 nil ; Nothing would be swallowed
22981 t))))) ; something would swallow
22983 (define-key org-mode-map "\C-y" 'org-yank)
22985 (defun org-truely-invisible-p ()
22986 "Check if point is at a character currently not visible.
22987 This version does not only check the character property, but also
22988 `visible-mode'."
22989 ;; Early versions of noutline don't have `outline-invisible-p'.
22990 (if (org-bound-and-true-p visible-mode)
22992 (outline-invisible-p)))
22994 (defun org-invisible-p2 ()
22995 "Check if point is at a character currently not visible."
22996 (save-excursion
22997 (if (and (eolp) (not (bobp))) (backward-char 1))
22998 ;; Early versions of noutline don't have `outline-invisible-p'.
22999 (outline-invisible-p)))
23001 (defun org-back-to-heading (&optional invisible-ok)
23002 "Call `outline-back-to-heading', but provide a better error message."
23003 (condition-case nil
23004 (outline-back-to-heading invisible-ok)
23005 (error (error "Before first headline at position %d in buffer %s"
23006 (point) (current-buffer)))))
23008 (defun org-before-first-heading-p ()
23009 "Before first heading?"
23010 (save-excursion
23011 (end-of-line)
23012 (null (re-search-backward org-outline-regexp-bol nil t))))
23014 (defun org-at-heading-p (&optional ignored)
23015 (outline-on-heading-p t))
23016 ;; Compatibility alias with Org versions < 7.8.03
23017 (defalias 'org-on-heading-p 'org-at-heading-p)
23019 (defun org-at-comment-p nil
23020 "Is cursor in a line starting with a # character?"
23021 (save-excursion
23022 (beginning-of-line)
23023 (looking-at "^#")))
23025 (defun org-at-drawer-p nil
23026 "Is cursor at a drawer keyword?"
23027 (save-excursion
23028 (move-beginning-of-line 1)
23029 (looking-at org-drawer-regexp)))
23031 (defun org-at-block-p nil
23032 "Is cursor at a block keyword?"
23033 (save-excursion
23034 (move-beginning-of-line 1)
23035 (looking-at org-block-regexp)))
23037 (defun org-point-at-end-of-empty-headline ()
23038 "If point is at the end of an empty headline, return t, else nil.
23039 If the heading only contains a TODO keyword, it is still still considered
23040 empty."
23041 (and (looking-at "[ \t]*$")
23042 (when org-todo-line-regexp
23043 (save-excursion
23044 (beginning-of-line 1)
23045 (let ((case-fold-search nil))
23046 (looking-at org-todo-line-regexp)
23047 (string= (match-string 3) ""))))))
23049 (defun org-at-heading-or-item-p ()
23050 (or (org-at-heading-p) (org-at-item-p)))
23052 (defun org-at-target-p ()
23053 (or (org-in-regexp org-radio-target-regexp)
23054 (org-in-regexp org-target-regexp)))
23055 ;; Compatibility alias with Org versions < 7.8.03
23056 (defalias 'org-on-target-p 'org-at-target-p)
23058 (defun org-up-heading-all (arg)
23059 "Move to the heading line of which the present line is a subheading.
23060 This function considers both visible and invisible heading lines.
23061 With argument, move up ARG levels."
23062 (if (fboundp 'outline-up-heading-all)
23063 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23064 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23066 (defun org-up-heading-safe ()
23067 "Move to the heading line of which the present line is a subheading.
23068 This version will not throw an error. It will return the level of the
23069 headline found, or nil if no higher level is found.
23071 Also, this function will be a lot faster than `outline-up-heading',
23072 because it relies on stars being the outline starters. This can really
23073 make a significant difference in outlines with very many siblings."
23074 (let (start-level re)
23075 (org-back-to-heading t)
23076 (setq start-level (funcall outline-level))
23077 (if (equal start-level 1)
23079 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23080 (if (re-search-backward re nil t)
23081 (funcall outline-level)))))
23083 (defun org-first-sibling-p ()
23084 "Is this heading the first child of its parents?"
23085 (interactive)
23086 (let ((re org-outline-regexp-bol)
23087 level l)
23088 (unless (org-at-heading-p t)
23089 (user-error "Not at a heading"))
23090 (setq level (funcall outline-level))
23091 (save-excursion
23092 (if (not (re-search-backward re nil t))
23094 (setq l (funcall outline-level))
23095 (< l level)))))
23097 (defun org-goto-sibling (&optional previous)
23098 "Goto the next sibling, even if it is invisible.
23099 When PREVIOUS is set, go to the previous sibling instead. Returns t
23100 when a sibling was found. When none is found, return nil and don't
23101 move point."
23102 (let ((fun (if previous 're-search-backward 're-search-forward))
23103 (pos (point))
23104 (re org-outline-regexp-bol)
23105 level l)
23106 (when (condition-case nil (org-back-to-heading t) (error nil))
23107 (setq level (funcall outline-level))
23108 (catch 'exit
23109 (or previous (forward-char 1))
23110 (while (funcall fun re nil t)
23111 (setq l (funcall outline-level))
23112 (when (< l level) (goto-char pos) (throw 'exit nil))
23113 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23114 (goto-char pos)
23115 nil))))
23117 (defun org-show-siblings ()
23118 "Show all siblings of the current headline."
23119 (save-excursion
23120 (while (org-goto-sibling) (org-flag-heading nil)))
23121 (save-excursion
23122 (while (org-goto-sibling 'previous)
23123 (org-flag-heading nil))))
23125 (defun org-goto-first-child ()
23126 "Goto the first child, even if it is invisible.
23127 Return t when a child was found. Otherwise don't move point and
23128 return nil."
23129 (let (level (pos (point)) (re org-outline-regexp-bol))
23130 (when (condition-case nil (org-back-to-heading t) (error nil))
23131 (setq level (outline-level))
23132 (forward-char 1)
23133 (if (and (re-search-forward re nil t) (> (outline-level) level))
23134 (progn (goto-char (match-beginning 0)) t)
23135 (goto-char pos) nil))))
23137 (defun org-show-hidden-entry ()
23138 "Show an entry where even the heading is hidden."
23139 (save-excursion
23140 (org-show-entry)))
23142 (defun org-flag-heading (flag &optional entry)
23143 "Flag the current heading. FLAG non-nil means make invisible.
23144 When ENTRY is non-nil, show the entire entry."
23145 (save-excursion
23146 (org-back-to-heading t)
23147 ;; Check if we should show the entire entry
23148 (if entry
23149 (progn
23150 (org-show-entry)
23151 (save-excursion
23152 (and (outline-next-heading)
23153 (org-flag-heading nil))))
23154 (outline-flag-region (max (point-min) (1- (point)))
23155 (save-excursion (outline-end-of-heading) (point))
23156 flag))))
23158 (defun org-get-next-sibling ()
23159 "Move to next heading of the same level, and return point.
23160 If there is no such heading, return nil.
23161 This is like outline-next-sibling, but invisible headings are ok."
23162 (let ((level (funcall outline-level)))
23163 (outline-next-heading)
23164 (while (and (not (eobp)) (> (funcall outline-level) level))
23165 (outline-next-heading))
23166 (if (or (eobp) (< (funcall outline-level) level))
23168 (point))))
23170 (defun org-get-last-sibling ()
23171 "Move to previous heading of the same level, and return point.
23172 If there is no such heading, return nil."
23173 (let ((opoint (point))
23174 (level (funcall outline-level)))
23175 (outline-previous-heading)
23176 (when (and (/= (point) opoint) (outline-on-heading-p t))
23177 (while (and (> (funcall outline-level) level)
23178 (not (bobp)))
23179 (outline-previous-heading))
23180 (if (< (funcall outline-level) level)
23182 (point)))))
23184 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23185 "Goto to the end of a subtree."
23186 ;; This contains an exact copy of the original function, but it uses
23187 ;; `org-back-to-heading', to make it work also in invisible
23188 ;; trees. And is uses an invisible-ok argument.
23189 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23190 ;; Furthermore, when used inside Org, finding the end of a large subtree
23191 ;; with many children and grandchildren etc, this can be much faster
23192 ;; than the outline version.
23193 (org-back-to-heading invisible-ok)
23194 (let ((first t)
23195 (level (funcall outline-level)))
23196 (if (and (derived-mode-p 'org-mode) (< level 1000))
23197 ;; A true heading (not a plain list item), in Org-mode
23198 ;; This means we can easily find the end by looking
23199 ;; only for the right number of stars. Using a regexp to do
23200 ;; this is so much faster than using a Lisp loop.
23201 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23202 (forward-char 1)
23203 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23204 ;; something else, do it the slow way
23205 (while (and (not (eobp))
23206 (or first (> (funcall outline-level) level)))
23207 (setq first nil)
23208 (outline-next-heading)))
23209 (unless to-heading
23210 (if (memq (preceding-char) '(?\n ?\^M))
23211 (progn
23212 ;; Go to end of line before heading
23213 (forward-char -1)
23214 (if (memq (preceding-char) '(?\n ?\^M))
23215 ;; leave blank line before heading
23216 (forward-char -1))))))
23217 (point))
23219 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23220 "Use Org version in org-mode, for dramatic speed-up."
23221 (if (derived-mode-p 'org-mode)
23222 (progn
23223 (org-end-of-subtree nil t)
23224 (unless (eobp) (backward-char 1)))
23225 ad-do-it))
23227 (defun org-end-of-meta-data-and-drawers ()
23228 "Jump to the first text after meta data and drawers in the current entry.
23229 This will move over empty lines, lines with planning time stamps,
23230 clocking lines, and drawers."
23231 (org-back-to-heading t)
23232 (let ((end (save-excursion (outline-next-heading) (point)))
23233 (re (concat "\\(" org-drawer-regexp "\\)"
23234 "\\|" "[ \t]*" org-keyword-time-regexp)))
23235 (forward-line 1)
23236 (while (re-search-forward re end t)
23237 (if (not (match-end 1))
23238 ;; empty or planning line
23239 (forward-line 1)
23240 ;; a drawer, find the end
23241 (re-search-forward "^[ \t]*:END:" end 'move)
23242 (forward-line 1)))
23243 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23244 (point)))
23246 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23247 "Move forward to the ARG'th subheading at same level as this one.
23248 Stop at the first and last subheadings of a superior heading.
23249 Normally this only looks at visible headings, but when INVISIBLE-OK is
23250 non-nil it will also look at invisible ones."
23251 (interactive "p")
23252 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23253 (if (and arg (< arg 0))
23254 (goto-char (point-min))
23255 (outline-next-heading))
23256 (org-at-heading-p)
23257 (let ((level (- (match-end 0) (match-beginning 0) 1))
23258 (f (if (and arg (< arg 0))
23259 're-search-backward
23260 're-search-forward))
23261 (count (if arg (abs arg) 1))
23262 (result (point)))
23263 (while (and (prog1 (> count 0)
23264 (forward-char (if (and arg (< arg 0)) -1 1)))
23265 (funcall f org-outline-regexp-bol nil 'move))
23266 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23267 (cond ((< l level) (setq count 0))
23268 ((and (= l level)
23269 (or invisible-ok
23270 (progn
23271 (goto-char (line-beginning-position))
23272 (not (outline-invisible-p)))))
23273 (setq count (1- count))
23274 (when (eq l level)
23275 (setq result (point)))))))
23276 (goto-char result))
23277 (beginning-of-line 1)))
23279 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23280 "Move backward to the ARG'th subheading at same level as this one.
23281 Stop at the first and last subheadings of a superior heading."
23282 (interactive "p")
23283 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23285 (defun org-next-block (arg &optional backward block-regexp)
23286 "Jump to the next block.
23287 With a prefix argument ARG, jump forward ARG many source blocks.
23288 When BACKWARD is non-nil, jump to the previous block.
23289 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23290 (interactive "p")
23291 (let ((re (or block-regexp org-block-regexp))
23292 (re-search-fn (or (and backward 're-search-backward)
23293 're-search-forward)))
23294 (if (looking-at re) (forward-char 1))
23295 (condition-case nil
23296 (funcall re-search-fn re nil nil arg)
23297 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23298 (goto-char (match-beginning 0)) (org-show-context)))
23300 (defun org-previous-block (arg &optional block-regexp)
23301 "Jump to the previous block.
23302 With a prefix argument ARG, jump backward ARG many source blocks.
23303 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23304 (interactive "p")
23305 (org-next-block arg t block-regexp))
23307 (defun org-forward-paragraph ()
23308 "Move forward to beginning of next paragraph or equivalent.
23310 The function moves point to the beginning of the next visible
23311 structural element, which can be a paragraph, a table, a list
23312 item, etc. It also provides some special moves for convenience:
23314 - On an affiliated keyword, jump to the beginning of the
23315 relative element.
23316 - On an item or a footnote definition, move to the second
23317 element inside, if any.
23318 - On a table or a property drawer, jump after it.
23319 - On a verse or source block, stop after blank lines."
23320 (interactive)
23321 (when (eobp) (user-error "Cannot move further down"))
23322 (let* ((deactivate-mark nil)
23323 (element (org-element-at-point))
23324 (type (org-element-type element))
23325 (post-affiliated (org-element-property :post-affiliated element))
23326 (contents-begin (org-element-property :contents-begin element))
23327 (contents-end (org-element-property :contents-end element))
23328 (end (let ((end (org-element-property :end element)) (parent element))
23329 (while (and (setq parent (org-element-property :parent parent))
23330 (= (org-element-property :contents-end parent) end))
23331 (setq end (org-element-property :end parent)))
23332 end)))
23333 (cond ((not element)
23334 (skip-chars-forward " \r\t\n")
23335 (or (eobp) (beginning-of-line)))
23336 ;; On affiliated keywords, move to element's beginning.
23337 ((and post-affiliated (< (point) post-affiliated))
23338 (goto-char post-affiliated))
23339 ;; At a table row, move to the end of the table. Similarly,
23340 ;; at a node property, move to the end of the property
23341 ;; drawer.
23342 ((memq type '(node-property table-row))
23343 (goto-char (org-element-property
23344 :end (org-element-property :parent element))))
23345 ((memq type '(property-drawer table)) (goto-char end))
23346 ;; Consider blank lines as separators in verse and source
23347 ;; blocks to ease editing.
23348 ((memq type '(src-block verse-block))
23349 (when (eq type 'src-block)
23350 (setq contents-end
23351 (save-excursion (goto-char end)
23352 (skip-chars-backward " \r\t\n")
23353 (line-beginning-position))))
23354 (beginning-of-line)
23355 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23356 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23357 (goto-char end)
23358 (skip-chars-forward " \r\t\n")
23359 (if (= (point) contents-end) (goto-char end)
23360 (beginning-of-line))))
23361 ;; With no contents, just skip element.
23362 ((not contents-begin) (goto-char end))
23363 ;; If contents are invisible, skip the element altogether.
23364 ((outline-invisible-p (line-end-position))
23365 (case type
23366 (headline
23367 (org-with-limited-levels (outline-next-visible-heading 1)))
23368 ;; At a plain list, make sure we move to the next item
23369 ;; instead of skipping the whole list.
23370 (plain-list (forward-char)
23371 (org-forward-paragraph))
23372 (otherwise (goto-char end))))
23373 ((>= (point) contents-end) (goto-char end))
23374 ((>= (point) contents-begin)
23375 ;; This can only happen on paragraphs and plain lists.
23376 (case type
23377 (paragraph (goto-char end))
23378 ;; At a plain list, try to move to second element in
23379 ;; first item, if possible.
23380 (plain-list (end-of-line)
23381 (org-forward-paragraph))))
23382 ;; When contents start on the middle of a line (e.g. in
23383 ;; items and footnote definitions), try to reach first
23384 ;; element starting after current line.
23385 ((> (line-end-position) contents-begin)
23386 (end-of-line)
23387 (org-forward-paragraph))
23388 (t (goto-char contents-begin)))))
23390 (defun org-backward-paragraph ()
23391 "Move backward to start of previous paragraph or equivalent.
23393 The function moves point to the beginning of the current
23394 structural element, which can be a paragraph, a table, a list
23395 item, etc., or to the beginning of the previous visible one if
23396 point is already there. It also provides some special moves for
23397 convenience:
23399 - On an affiliated keyword, jump to the first one.
23400 - On a table or a property drawer, move to its beginning.
23401 - On a verse or source block, stop before blank lines."
23402 (interactive)
23403 (when (bobp) (user-error "Cannot move further up"))
23404 (let* ((deactivate-mark nil)
23405 (element (org-element-at-point))
23406 (type (org-element-type element))
23407 (contents-begin (org-element-property :contents-begin element))
23408 (contents-end (org-element-property :contents-end element))
23409 (post-affiliated (org-element-property :post-affiliated element))
23410 (begin (org-element-property :begin element)))
23411 (cond
23412 ((not element) (goto-char (point-min)))
23413 ((= (point) begin)
23414 (backward-char)
23415 (org-backward-paragraph))
23416 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23417 ((memq type '(node-property table-row))
23418 (goto-char (org-element-property
23419 :post-affiliated (org-element-property :parent element))))
23420 ((memq type '(property-drawer table)) (goto-char begin))
23421 ((memq type '(src-block verse-block))
23422 (when (eq type 'src-block)
23423 (setq contents-begin
23424 (save-excursion (goto-char begin) (forward-line) (point))))
23425 (if (= (point) contents-begin) (goto-char post-affiliated)
23426 ;; Inside a verse block, see blank lines as paragraph
23427 ;; separators.
23428 (let ((origin (point)))
23429 (skip-chars-backward " \r\t\n" contents-begin)
23430 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23431 (skip-chars-forward " \r\t\n" origin)
23432 (if (= (point) origin) (goto-char contents-begin)
23433 (beginning-of-line))))))
23434 ((not contents-begin) (goto-char (or post-affiliated begin)))
23435 ((eq type 'paragraph)
23436 (goto-char contents-begin)
23437 ;; When at first paragraph in an item or a footnote definition,
23438 ;; move directly to beginning of line.
23439 (let ((parent-contents
23440 (org-element-property
23441 :contents-begin (org-element-property :parent element))))
23442 (when (and parent-contents (= parent-contents contents-begin))
23443 (beginning-of-line))))
23444 ;; At the end of a greater element, move to the beginning of the
23445 ;; last element within.
23446 ((>= (point) contents-end)
23447 (goto-char (1- contents-end))
23448 (org-backward-paragraph))
23449 (t (goto-char (or post-affiliated begin))))
23450 ;; Ensure we never leave point invisible.
23451 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23453 (defun org-forward-element ()
23454 "Move forward by one element.
23455 Move to the next element at the same level, when possible."
23456 (interactive)
23457 (cond ((eobp) (user-error "Cannot move further down"))
23458 ((org-with-limited-levels (org-at-heading-p))
23459 (let ((origin (point)))
23460 (goto-char (org-end-of-subtree nil t))
23461 (unless (org-with-limited-levels (org-at-heading-p))
23462 (goto-char origin)
23463 (user-error "Cannot move further down"))))
23465 (let* ((elem (org-element-at-point))
23466 (end (org-element-property :end elem))
23467 (parent (org-element-property :parent elem)))
23468 (cond ((and parent (= (org-element-property :contents-end parent) end))
23469 (goto-char (org-element-property :end parent)))
23470 ((integer-or-marker-p end) (goto-char end))
23471 (t (message "No element at point")))))))
23473 (defun org-backward-element ()
23474 "Move backward by one element.
23475 Move to the previous element at the same level, when possible."
23476 (interactive)
23477 (cond ((bobp) (user-error "Cannot move further up"))
23478 ((org-with-limited-levels (org-at-heading-p))
23479 ;; At a headline, move to the previous one, if any, or stay
23480 ;; here.
23481 (let ((origin (point)))
23482 (org-with-limited-levels (org-backward-heading-same-level 1))
23483 ;; When current headline has no sibling above, move to its
23484 ;; parent.
23485 (when (= (point) origin)
23486 (or (org-with-limited-levels (org-up-heading-safe))
23487 (progn (goto-char origin)
23488 (user-error "Cannot move further up"))))))
23490 (let* ((trail (org-element-at-point 'keep-trail))
23491 (elem (car trail))
23492 (prev-elem (nth 1 trail))
23493 (beg (org-element-property :begin elem)))
23494 (cond
23495 ;; Move to beginning of current element if point isn't
23496 ;; there already.
23497 ((null beg) (message "No element at point"))
23498 ((/= (point) beg) (goto-char beg))
23499 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23500 ((org-before-first-heading-p) (goto-char (point-min)))
23501 (t (org-back-to-heading)))))))
23503 (defun org-up-element ()
23504 "Move to upper element."
23505 (interactive)
23506 (if (org-with-limited-levels (org-at-heading-p))
23507 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23508 (let* ((elem (org-element-at-point))
23509 (parent (org-element-property :parent elem)))
23510 (if parent (goto-char (org-element-property :begin parent))
23511 (if (org-with-limited-levels (org-before-first-heading-p))
23512 (user-error "No surrounding element")
23513 (org-with-limited-levels (org-back-to-heading)))))))
23515 (defvar org-element-greater-elements)
23516 (defun org-down-element ()
23517 "Move to inner element."
23518 (interactive)
23519 (let ((element (org-element-at-point)))
23520 (cond
23521 ((memq (org-element-type element) '(plain-list table))
23522 (goto-char (org-element-property :contents-begin element))
23523 (forward-char))
23524 ((memq (org-element-type element) org-element-greater-elements)
23525 ;; If contents are hidden, first disclose them.
23526 (when (org-element-property :hiddenp element) (org-cycle))
23527 (goto-char (or (org-element-property :contents-begin element)
23528 (user-error "No content for this element"))))
23529 (t (user-error "No inner element")))))
23531 (defun org-drag-element-backward ()
23532 "Move backward element at point."
23533 (interactive)
23534 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23535 (let* ((trail (org-element-at-point 'keep-trail))
23536 (elem (car trail))
23537 (prev-elem (nth 1 trail)))
23538 ;; Error out if no previous element or previous element is
23539 ;; a parent of the current one.
23540 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23541 (user-error "Cannot drag element backward")
23542 (let ((pos (point)))
23543 (org-element-swap-A-B prev-elem elem)
23544 (goto-char (+ (org-element-property :begin prev-elem)
23545 (- pos (org-element-property :begin elem)))))))))
23547 (defun org-drag-element-forward ()
23548 "Move forward element at point."
23549 (interactive)
23550 (let* ((pos (point))
23551 (elem (org-element-at-point)))
23552 (when (= (point-max) (org-element-property :end elem))
23553 (user-error "Cannot drag element forward"))
23554 (goto-char (org-element-property :end elem))
23555 (let ((next-elem (org-element-at-point)))
23556 (when (or (org-element-nested-p elem next-elem)
23557 (and (eq (org-element-type next-elem) 'headline)
23558 (not (eq (org-element-type elem) 'headline))))
23559 (goto-char pos)
23560 (user-error "Cannot drag element forward"))
23561 ;; Compute new position of point: it's shifted by NEXT-ELEM
23562 ;; body's length (without final blanks) and by the length of
23563 ;; blanks between ELEM and NEXT-ELEM.
23564 (let ((size-next (- (save-excursion
23565 (goto-char (org-element-property :end next-elem))
23566 (skip-chars-backward " \r\t\n")
23567 (forward-line)
23568 ;; Small correction if buffer doesn't end
23569 ;; with a newline character.
23570 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23571 (org-element-property :begin next-elem)))
23572 (size-blank (- (org-element-property :end elem)
23573 (save-excursion
23574 (goto-char (org-element-property :end elem))
23575 (skip-chars-backward " \r\t\n")
23576 (forward-line)
23577 (point)))))
23578 (org-element-swap-A-B elem next-elem)
23579 (goto-char (+ pos size-next size-blank))))))
23581 (defun org-drag-line-forward (arg)
23582 "Drag the line at point ARG lines forward."
23583 (interactive "p")
23584 (dotimes (n (abs arg))
23585 (let ((c (current-column)))
23586 (if (< 0 arg)
23587 (progn
23588 (beginning-of-line 2)
23589 (transpose-lines 1)
23590 (beginning-of-line 0))
23591 (transpose-lines 1)
23592 (beginning-of-line -1))
23593 (org-move-to-column c))))
23595 (defun org-drag-line-backward (arg)
23596 "Drag the line at point ARG lines backward."
23597 (interactive "p")
23598 (org-drag-line-forward (- arg)))
23600 (defun org-mark-element ()
23601 "Put point at beginning of this element, mark at end.
23603 Interactively, if this command is repeated or (in Transient Mark
23604 mode) if the mark is active, it marks the next element after the
23605 ones already marked."
23606 (interactive)
23607 (let (deactivate-mark)
23608 (if (and (org-called-interactively-p 'any)
23609 (or (and (eq last-command this-command) (mark t))
23610 (and transient-mark-mode mark-active)))
23611 (set-mark
23612 (save-excursion
23613 (goto-char (mark))
23614 (goto-char (org-element-property :end (org-element-at-point)))))
23615 (let ((element (org-element-at-point)))
23616 (end-of-line)
23617 (push-mark (org-element-property :end element) t t)
23618 (goto-char (org-element-property :begin element))))))
23620 (defun org-narrow-to-element ()
23621 "Narrow buffer to current element."
23622 (interactive)
23623 (let ((elem (org-element-at-point)))
23624 (cond
23625 ((eq (car elem) 'headline)
23626 (narrow-to-region
23627 (org-element-property :begin elem)
23628 (org-element-property :end elem)))
23629 ((memq (car elem) org-element-greater-elements)
23630 (narrow-to-region
23631 (org-element-property :contents-begin elem)
23632 (org-element-property :contents-end elem)))
23634 (narrow-to-region
23635 (org-element-property :begin elem)
23636 (org-element-property :end elem))))))
23638 (defun org-transpose-element ()
23639 "Transpose current and previous elements, keeping blank lines between.
23640 Point is moved after both elements."
23641 (interactive)
23642 (org-skip-whitespace)
23643 (let ((end (org-element-property :end (org-element-at-point))))
23644 (org-drag-element-backward)
23645 (goto-char end)))
23647 (defun org-unindent-buffer ()
23648 "Un-indent the visible part of the buffer.
23649 Relative indentation (between items, inside blocks, etc.) isn't
23650 modified."
23651 (interactive)
23652 (unless (eq major-mode 'org-mode)
23653 (user-error "Cannot un-indent a buffer not in Org mode"))
23654 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23655 unindent-tree ; For byte-compiler.
23656 (unindent-tree
23657 (function
23658 (lambda (contents)
23659 (mapc
23660 (lambda (element)
23661 (if (memq (org-element-type element) '(headline section))
23662 (funcall unindent-tree (org-element-contents element))
23663 (save-excursion
23664 (save-restriction
23665 (narrow-to-region
23666 (org-element-property :begin element)
23667 (org-element-property :end element))
23668 (org-do-remove-indentation)))))
23669 (reverse contents))))))
23670 (funcall unindent-tree (org-element-contents parse-tree))))
23672 (defun org-show-subtree ()
23673 "Show everything after this heading at deeper levels."
23674 (interactive)
23675 (outline-flag-region
23676 (point)
23677 (save-excursion
23678 (org-end-of-subtree t t))
23679 nil))
23681 (defun org-show-entry ()
23682 "Show the body directly following this heading.
23683 Show the heading too, if it is currently invisible."
23684 (interactive)
23685 (save-excursion
23686 (condition-case nil
23687 (progn
23688 (org-back-to-heading t)
23689 (outline-flag-region
23690 (max (point-min) (1- (point)))
23691 (save-excursion
23692 (if (re-search-forward
23693 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23694 (match-beginning 1)
23695 (point-max)))
23696 nil)
23697 (org-cycle-hide-drawers 'children))
23698 (error nil))))
23700 (defun org-make-options-regexp (kwds &optional extra)
23701 "Make a regular expression for keyword lines."
23702 (concat
23703 "^#\\+\\("
23704 (mapconcat 'regexp-quote kwds "\\|")
23705 (if extra (concat "\\|" extra))
23706 "\\):[ \t]*\\(.*\\)"))
23708 ;; Make isearch reveal the necessary context
23709 (defun org-isearch-end ()
23710 "Reveal context after isearch exits."
23711 (when isearch-success ; only if search was successful
23712 (if (featurep 'xemacs)
23713 ;; Under XEmacs, the hook is run in the correct place,
23714 ;; we directly show the context.
23715 (org-show-context 'isearch)
23716 ;; In Emacs the hook runs *before* restoring the overlays.
23717 ;; So we have to use a one-time post-command-hook to do this.
23718 ;; (Emacs 22 has a special variable, see function `org-mode')
23719 (unless (and (boundp 'isearch-mode-end-hook-quit)
23720 isearch-mode-end-hook-quit)
23721 ;; Only when the isearch was not quitted.
23722 (org-add-hook 'post-command-hook 'org-isearch-post-command
23723 'append 'local)))
23724 (org-fix-ellipsis-at-bol)))
23726 (defun org-isearch-post-command ()
23727 "Remove self from hook, and show context."
23728 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23729 (org-show-context 'isearch))
23732 ;;;; Integration with and fixes for other packages
23734 ;;; Imenu support
23736 (defvar org-imenu-markers nil
23737 "All markers currently used by Imenu.")
23738 (make-variable-buffer-local 'org-imenu-markers)
23740 (defun org-imenu-new-marker (&optional pos)
23741 "Return a new marker for use by Imenu, and remember the marker."
23742 (let ((m (make-marker)))
23743 (move-marker m (or pos (point)))
23744 (push m org-imenu-markers)
23747 (defun org-imenu-get-tree ()
23748 "Produce the index for Imenu."
23749 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23750 (setq org-imenu-markers nil)
23751 (let* ((n org-imenu-depth)
23752 (re (concat "^" (org-get-limited-outline-regexp)))
23753 (subs (make-vector (1+ n) nil))
23754 (last-level 0)
23755 m level head0 head)
23756 (save-excursion
23757 (save-restriction
23758 (widen)
23759 (goto-char (point-max))
23760 (while (re-search-backward re nil t)
23761 (setq level (org-reduced-level (funcall outline-level)))
23762 (when (and (<= level n)
23763 (looking-at org-complex-heading-regexp)
23764 (setq head0 (org-match-string-no-properties 4)))
23765 (setq head (org-link-display-format head0)
23766 m (org-imenu-new-marker))
23767 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23768 (if (>= level last-level)
23769 (push (cons head m) (aref subs level))
23770 (push (cons head (aref subs (1+ level))) (aref subs level))
23771 (loop for i from (1+ level) to n do (aset subs i nil)))
23772 (setq last-level level)))))
23773 (aref subs 1)))
23775 (eval-after-load "imenu"
23776 '(progn
23777 (add-hook 'imenu-after-jump-hook
23778 (lambda ()
23779 (if (derived-mode-p 'org-mode)
23780 (org-show-context 'org-goto))))))
23782 (defun org-link-display-format (link)
23783 "Replace a link with its the description.
23784 If there is no description, use the link target."
23785 (save-match-data
23786 (if (string-match org-bracket-link-analytic-regexp link)
23787 (replace-match (if (match-end 5)
23788 (match-string 5 link)
23789 (concat (match-string 1 link)
23790 (match-string 3 link)))
23791 nil t link)
23792 link)))
23794 (defun org-toggle-link-display ()
23795 "Toggle the literal or descriptive display of links."
23796 (interactive)
23797 (if org-descriptive-links
23798 (progn (org-remove-from-invisibility-spec '(org-link))
23799 (org-restart-font-lock)
23800 (setq org-descriptive-links nil))
23801 (progn (add-to-invisibility-spec '(org-link))
23802 (org-restart-font-lock)
23803 (setq org-descriptive-links t))))
23805 ;; Speedbar support
23807 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23808 "Overlay marking the agenda restriction line in speedbar.")
23809 (overlay-put org-speedbar-restriction-lock-overlay
23810 'face 'org-agenda-restriction-lock)
23811 (overlay-put org-speedbar-restriction-lock-overlay
23812 'help-echo "Agendas are currently limited to this item.")
23813 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23815 (defun org-speedbar-set-agenda-restriction ()
23816 "Restrict future agenda commands to the location at point in speedbar.
23817 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23818 (interactive)
23819 (require 'org-agenda)
23820 (let (p m tp np dir txt)
23821 (cond
23822 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23823 'org-imenu t))
23824 (setq m (get-text-property p 'org-imenu-marker))
23825 (with-current-buffer (marker-buffer m)
23826 (goto-char m)
23827 (org-agenda-set-restriction-lock 'subtree)))
23828 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23829 'speedbar-function 'speedbar-find-file))
23830 (setq tp (previous-single-property-change
23831 (1+ p) 'speedbar-function)
23832 np (next-single-property-change
23833 tp 'speedbar-function)
23834 dir (speedbar-line-directory)
23835 txt (buffer-substring-no-properties (or tp (point-min))
23836 (or np (point-max))))
23837 (with-current-buffer (find-file-noselect
23838 (let ((default-directory dir))
23839 (expand-file-name txt)))
23840 (unless (derived-mode-p 'org-mode)
23841 (user-error "Cannot restrict to non-Org-mode file"))
23842 (org-agenda-set-restriction-lock 'file)))
23843 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23844 (move-overlay org-speedbar-restriction-lock-overlay
23845 (point-at-bol) (point-at-eol))
23846 (setq current-prefix-arg nil)
23847 (org-agenda-maybe-redo)))
23849 (defvar speedbar-file-key-map)
23850 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23851 (eval-after-load "speedbar"
23852 '(progn
23853 (speedbar-add-supported-extension ".org")
23854 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23855 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23856 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23857 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23858 (add-hook 'speedbar-visiting-tag-hook
23859 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23861 ;;; Fixes and Hacks for problems with other packages
23863 ;; Make flyspell not check words in links, to not mess up our keymap
23864 (defvar org-element-affiliated-keywords) ; From org-element.el
23865 (defvar org-element-block-name-alist) ; From org-element.el
23866 (defun org-mode-flyspell-verify ()
23867 "Don't let flyspell put overlays at active buttons, or on
23868 {todo,all-time,additional-option-like}-keywords."
23869 (require 'org-element) ; For `org-element-affiliated-keywords'
23870 (let ((pos (max (1- (point)) (point-min)))
23871 (word (thing-at-point 'word)))
23872 (and (not (get-text-property pos 'keymap))
23873 (not (get-text-property pos 'org-no-flyspell))
23874 (not (member word org-todo-keywords-1))
23875 (not (member word org-all-time-keywords))
23876 (not (member word org-options-keywords))
23877 (not (member word (mapcar 'car org-startup-options)))
23878 (not (member-ignore-case word org-element-affiliated-keywords))
23879 (not (member-ignore-case word (org-get-export-keywords)))
23880 (not (member-ignore-case
23881 word (mapcar 'car org-element-block-name-alist)))
23882 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23883 (not (org-in-src-block-p)))))
23885 (defun org-remove-flyspell-overlays-in (beg end)
23886 "Remove flyspell overlays in region."
23887 (and (org-bound-and-true-p flyspell-mode)
23888 (fboundp 'flyspell-delete-region-overlays)
23889 (flyspell-delete-region-overlays beg end))
23890 (add-text-properties beg end '(org-no-flyspell t)))
23892 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23893 (eval-after-load "bookmark"
23894 '(if (boundp 'bookmark-after-jump-hook)
23895 ;; We can use the hook
23896 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23897 ;; Hook not available, use advice
23898 (defadvice bookmark-jump (after org-make-visible activate)
23899 "Make the position visible."
23900 (org-bookmark-jump-unhide))))
23902 ;; Make sure saveplace shows the location if it was hidden
23903 (eval-after-load "saveplace"
23904 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23905 "Make the position visible."
23906 (org-bookmark-jump-unhide)))
23908 ;; Make sure ecb shows the location if it was hidden
23909 (eval-after-load "ecb"
23910 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23911 "Make hierarchy visible when jumping into location from ECB tree buffer."
23912 (if (derived-mode-p 'org-mode)
23913 (org-show-context))))
23915 (defun org-bookmark-jump-unhide ()
23916 "Unhide the current position, to show the bookmark location."
23917 (and (derived-mode-p 'org-mode)
23918 (or (outline-invisible-p)
23919 (save-excursion (goto-char (max (point-min) (1- (point))))
23920 (outline-invisible-p)))
23921 (org-show-context 'bookmark-jump)))
23923 ;; Make session.el ignore our circular variable
23924 (defvar session-globals-exclude)
23925 (eval-after-load "session"
23926 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23928 ;;;; Finish up
23930 (provide 'org)
23932 (run-hooks 'org-load-hook)
23934 ;;; org.el ends here