8da6f7d68499db903c1e1f2629cf25e44bee63c1
[org-mode.git] / lisp / org.el
blob8da6f7d68499db903c1e1f2629cf25e44bee63c1
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
420 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
421 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
422 (const :tag "C mew: Links to Mew folders/messages" org-mew)
423 (const :tag "C mtags: Support for muse-like tags" org-mtags)
424 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
425 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
426 (const :tag "C registry: A registry for Org-mode links" org-registry)
427 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
428 (const :tag "C secretary: Team management with org-mode" org-secretary)
429 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
430 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
431 (const :tag "C track: Keep up with Org-mode development" org-track)
432 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
433 (const :tag "C vm: Links to VM folders/messages" org-vm)
434 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
435 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
436 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
438 (defvar org-export--registered-backends) ; From ox.el.
439 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
440 (declare-function org-export-backend-name "ox" (backend))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VAL stands for the new
455 value of the variable, after updating it:
457 \(progn
458 \(setq org-export--registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(let ((name (org-export-backend-name backend)))
462 \(or (memq name val)
463 \(catch 'parentp
464 \(dolist (b val)
465 \(and (org-export-derived-backend-p b name)
466 \(throw 'parentp t)))))))
467 org-export--registered-backends))
468 \(let ((new-list (mapcar 'org-export-backend-name
469 org-export--registered-backends)))
470 \(dolist (backend val)
471 \(cond
472 \((not (load (format \"ox-%s\" backend) t t))
473 \(message \"Problems while trying to load export back-end `%s'\"
474 backend))
475 \((not (memq backend new-list)) (push backend new-list))))
476 \(set-default 'org-export-backends new-list)))
478 Adding a back-end to this list will also pull the back-end it
479 depends on, if any."
480 :group 'org
481 :group 'org-export
482 :version "24.4"
483 :package-version '(Org . "8.0")
484 :initialize 'custom-initialize-set
485 :set (lambda (var val)
486 (if (not (featurep 'ox)) (set-default var val)
487 ;; Any back-end not required anymore (not present in VAL and not
488 ;; a parent of any back-end in the new value) is removed from the
489 ;; list of registered back-ends.
490 (setq org-export--registered-backends
491 (org-remove-if-not
492 (lambda (backend)
493 (let ((name (org-export-backend-name backend)))
494 (or (memq name val)
495 (catch 'parentp
496 (dolist (b val)
497 (and (org-export-derived-backend-p b name)
498 (throw 'parentp t)))))))
499 org-export--registered-backends))
500 ;; Now build NEW-LIST of both new back-ends and required
501 ;; parents.
502 (let ((new-list (mapcar 'org-export-backend-name
503 org-export--registered-backends)))
504 (dolist (backend val)
505 (cond
506 ((not (load (format "ox-%s" backend) t t))
507 (message "Problems while trying to load export back-end `%s'"
508 backend))
509 ((not (memq backend new-list)) (push backend new-list))))
510 ;; Set VAR to that list with fixed dependencies.
511 (set-default var new-list))))
512 :type '(set :greedy t
513 (const :tag " ascii Export buffer to ASCII format" ascii)
514 (const :tag " beamer Export buffer to Beamer presentation" beamer)
515 (const :tag " html Export buffer to HTML format" html)
516 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
517 (const :tag " latex Export buffer to LaTeX format" latex)
518 (const :tag " man Export buffer to MAN format" man)
519 (const :tag " md Export buffer to Markdown format" md)
520 (const :tag " odt Export buffer to ODT format" odt)
521 (const :tag " org Export buffer to Org format" org)
522 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
523 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
524 (const :tag "C deck Export buffer to deck.js presentations" deck)
525 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
526 (const :tag "C groff Export buffer to Groff format" groff)
527 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
528 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
529 (const :tag "C s5 Export buffer to s5 presentations" s5)
530 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
532 (eval-after-load 'ox
533 '(mapc
534 (lambda (backend)
535 (condition-case nil (require (intern (format "ox-%s" backend)))
536 (error (message "Problems while trying to load export back-end `%s'"
537 backend))))
538 org-export-backends))
540 (defcustom org-support-shift-select nil
541 "Non-nil means make shift-cursor commands select text when possible.
543 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
544 start selecting a region, or enlarge regions started in this way.
545 In Org-mode, in special contexts, these same keys are used for
546 other purposes, important enough to compete with shift selection.
547 Org tries to balance these needs by supporting `shift-select-mode'
548 outside these special contexts, under control of this variable.
550 The default of this variable is nil, to avoid confusing behavior. Shifted
551 cursor keys will then execute Org commands in the following contexts:
552 - on a headline, changing TODO state (left/right) and priority (up/down)
553 - on a time stamp, changing the time
554 - in a plain list item, changing the bullet type
555 - in a property definition line, switching between allowed values
556 - in the BEGIN line of a clock table (changing the time block).
557 Outside these contexts, the commands will throw an error.
559 When this variable is t and the cursor is not in a special
560 context, Org-mode will support shift-selection for making and
561 enlarging regions. To make this more effective, the bullet
562 cycling will no longer happen anywhere in an item line, but only
563 if the cursor is exactly on the bullet.
565 If you set this variable to the symbol `always', then the keys
566 will not be special in headlines, property lines, and item lines,
567 to make shift selection work there as well. If this is what you
568 want, you can use the following alternative commands: `C-c C-t'
569 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
570 can be used to switch TODO sets, `C-c -' to cycle item bullet
571 types, and properties can be edited by hand or in column view.
573 However, when the cursor is on a timestamp, shift-cursor commands
574 will still edit the time stamp - this is just too good to give up.
576 XEmacs user should have this variable set to nil, because
577 `shift-select-mode' is in Emacs 23 or later only."
578 :group 'org
579 :type '(choice
580 (const :tag "Never" nil)
581 (const :tag "When outside special context" t)
582 (const :tag "Everywhere except timestamps" always)))
584 (defcustom org-loop-over-headlines-in-active-region nil
585 "Shall some commands act upon headlines in the active region?
587 When set to `t', some commands will be performed in all headlines
588 within the active region.
590 When set to `start-level', some commands will be performed in all
591 headlines within the active region, provided that these headlines
592 are of the same level than the first one.
594 When set to a string, those commands will be performed on the
595 matching headlines within the active region. Such string must be
596 a tags/property/todo match as it is used in the agenda tags view.
598 The list of commands is: `org-schedule', `org-deadline',
599 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
600 `org-archive-to-archive-sibling'. The archiving commands skip
601 already archived entries."
602 :type '(choice (const :tag "Don't loop" nil)
603 (const :tag "All headlines in active region" t)
604 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
605 (string :tag "Tags/Property/Todo matcher"))
606 :version "24.1"
607 :group 'org-todo
608 :group 'org-archive)
610 (defgroup org-startup nil
611 "Options concerning startup of Org-mode."
612 :tag "Org Startup"
613 :group 'org)
615 (defcustom org-startup-folded t
616 "Non-nil means entering Org-mode will switch to OVERVIEW.
617 This can also be configured on a per-file basis by adding one of
618 the following lines anywhere in the buffer:
620 #+STARTUP: fold (or `overview', this is equivalent)
621 #+STARTUP: nofold (or `showall', this is equivalent)
622 #+STARTUP: content
623 #+STARTUP: showeverything
625 By default, this option is ignored when Org opens agenda files
626 for the first time. If you want the agenda to honor the startup
627 option, set `org-agenda-inhibit-startup' to nil."
628 :group 'org-startup
629 :type '(choice
630 (const :tag "nofold: show all" nil)
631 (const :tag "fold: overview" t)
632 (const :tag "content: all headlines" content)
633 (const :tag "show everything, even drawers" showeverything)))
635 (defcustom org-startup-truncated t
636 "Non-nil means entering Org-mode will set `truncate-lines'.
637 This is useful since some lines containing links can be very long and
638 uninteresting. Also tables look terrible when wrapped."
639 :group 'org-startup
640 :type 'boolean)
642 (defcustom org-startup-indented nil
643 "Non-nil means turn on `org-indent-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: indent
648 #+STARTUP: noindent"
649 :group 'org-structure
650 :type '(choice
651 (const :tag "Not" nil)
652 (const :tag "Globally (slow on startup in large files)" t)))
654 (defcustom org-use-sub-superscripts t
655 "Non-nil means interpret \"_\" and \"^\" for display.
656 When this option is turned on, you can use TeX-like syntax for sub- and
657 superscripts. Several characters after \"_\" or \"^\" will be
658 considered as a single item - so grouping with {} is normally not
659 needed. For example, the following things will be parsed as single
660 sub- or superscripts.
662 10^24 or 10^tau several digits will be considered 1 item.
663 10^-12 or 10^-tau a leading sign with digits or a word
664 x^2-y^3 will be read as x^2 - y^3, because items are
665 terminated by almost any nonword/nondigit char.
666 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
668 Still, ambiguity is possible - so when in doubt use {} to enclose
669 the sub/superscript. If you set this variable to the symbol
670 `{}', the braces are *required* in order to trigger
671 interpretations as sub/superscript. This can be helpful in
672 documents that need \"_\" frequently in plain text."
673 :group 'org-startup
674 :version "24.1"
675 :type '(choice
676 (const :tag "Always interpret" t)
677 (const :tag "Only with braces" {})
678 (const :tag "Never interpret" nil)))
680 (defcustom org-startup-with-beamer-mode nil
681 "Non-nil means turn on `org-beamer-mode' on startup.
682 This can also be configured on a per-file basis by adding one of
683 the following lines anywhere in the buffer:
685 #+STARTUP: beamer"
686 :group 'org-startup
687 :version "24.1"
688 :type 'boolean)
690 (defcustom org-startup-align-all-tables nil
691 "Non-nil means align all tables when visiting a file.
692 This is useful when the column width in tables is forced with <N> cookies
693 in table fields. Such tables will look correct only after the first re-align.
694 This can also be configured on a per-file basis by adding one of
695 the following lines anywhere in the buffer:
696 #+STARTUP: align
697 #+STARTUP: noalign"
698 :group 'org-startup
699 :type 'boolean)
701 (defcustom org-startup-with-inline-images nil
702 "Non-nil means show inline images when loading a new Org file.
703 This can also be configured on a per-file basis by adding one of
704 the following lines anywhere in the buffer:
705 #+STARTUP: inlineimages
706 #+STARTUP: noinlineimages"
707 :group 'org-startup
708 :version "24.1"
709 :type 'boolean)
711 (defcustom org-startup-with-latex-preview nil
712 "Non-nil means preview LaTeX fragments when loading a new Org file.
714 This can also be configured on a per-file basis by adding one of
715 the followinglines anywhere in the buffer:
716 #+STARTUP: latexpreview
717 #+STARTUP: nolatexpreview"
718 :group 'org-startup
719 :version "24.4"
720 :package-version '(Org . "8.0")
721 :type 'boolean)
723 (defcustom org-insert-mode-line-in-empty-file nil
724 "Non-nil means insert the first line setting Org-mode in empty files.
725 When the function `org-mode' is called interactively in an empty file, this
726 normally means that the file name does not automatically trigger Org-mode.
727 To ensure that the file will always be in Org-mode in the future, a
728 line enforcing Org-mode will be inserted into the buffer, if this option
729 has been set."
730 :group 'org-startup
731 :type 'boolean)
733 (defcustom org-replace-disputed-keys nil
734 "Non-nil means use alternative key bindings for some keys.
735 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
736 These keys are also used by other packages like shift-selection-mode'
737 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
738 If you want to use Org-mode together with one of these other modes,
739 or more generally if you would like to move some Org-mode commands to
740 other keys, set this variable and configure the keys with the variable
741 `org-disputed-keys'.
743 This option is only relevant at load-time of Org-mode, and must be set
744 *before* org.el is loaded. Changing it requires a restart of Emacs to
745 become effective."
746 :group 'org-startup
747 :type 'boolean)
749 (defcustom org-use-extra-keys nil
750 "Non-nil means use extra key sequence definitions for certain commands.
751 This happens automatically if you run XEmacs or if `window-system'
752 is nil. This variable lets you do the same manually. You must
753 set it before loading org.
755 Example: on Carbon Emacs 22 running graphically, with an external
756 keyboard on a Powerbook, the default way of setting M-left might
757 not work for either Alt or ESC. Setting this variable will make
758 it work for ESC."
759 :group 'org-startup
760 :type 'boolean)
762 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
764 (defcustom org-disputed-keys
765 '(([(shift up)] . [(meta p)])
766 ([(shift down)] . [(meta n)])
767 ([(shift left)] . [(meta -)])
768 ([(shift right)] . [(meta +)])
769 ([(control shift right)] . [(meta shift +)])
770 ([(control shift left)] . [(meta shift -)]))
771 "Keys for which Org-mode and other modes compete.
772 This is an alist, cars are the default keys, second element specifies
773 the alternative to use when `org-replace-disputed-keys' is t.
775 Keys can be specified in any syntax supported by `define-key'.
776 The value of this option takes effect only at Org-mode's startup,
777 therefore you'll have to restart Emacs to apply it after changing."
778 :group 'org-startup
779 :type 'alist)
781 (defun org-key (key)
782 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
783 Or return the original if not disputed.
784 Also apply the translations defined in `org-xemacs-key-equivalents'."
785 (when org-replace-disputed-keys
786 (let* ((nkey (key-description key))
787 (x (org-find-if (lambda (x)
788 (equal (key-description (car x)) nkey))
789 org-disputed-keys)))
790 (setq key (if x (cdr x) key))))
791 (when (featurep 'xemacs)
792 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
793 key)
795 (defun org-find-if (predicate seq)
796 (catch 'exit
797 (while seq
798 (if (funcall predicate (car seq))
799 (throw 'exit (car seq))
800 (pop seq)))))
802 (defun org-defkey (keymap key def)
803 "Define a key, possibly translated, as returned by `org-key'."
804 (define-key keymap (org-key key) def))
806 (defcustom org-ellipsis nil
807 "The ellipsis to use in the Org-mode outline.
808 When nil, just use the standard three dots. When a string, use that instead,
809 When a face, use the standard 3 dots, but with the specified face.
810 The change affects only Org-mode (which will then use its own display table).
811 Changing this requires executing `M-x org-mode' in a buffer to become
812 effective."
813 :group 'org-startup
814 :type '(choice (const :tag "Default" nil)
815 (face :tag "Face" :value org-warning)
816 (string :tag "String" :value "...#")))
818 (defvar org-display-table nil
819 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
821 (defgroup org-keywords nil
822 "Keywords in Org-mode."
823 :tag "Org Keywords"
824 :group 'org)
826 (defcustom org-deadline-string "DEADLINE:"
827 "String to mark deadline entries.
828 A deadline is this string, followed by a time stamp. Should be a word,
829 terminated by a colon. You can insert a schedule keyword and
830 a timestamp with \\[org-deadline].
831 Changes become only effective after restarting Emacs."
832 :group 'org-keywords
833 :type 'string)
835 (defcustom org-scheduled-string "SCHEDULED:"
836 "String to mark scheduled TODO entries.
837 A schedule is this string, followed by a time stamp. Should be a word,
838 terminated by a colon. You can insert a schedule keyword and
839 a timestamp with \\[org-schedule].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
844 (defcustom org-closed-string "CLOSED:"
845 "String used as the prefix for timestamps logging closing a TODO entry."
846 :group 'org-keywords
847 :type 'string)
849 (defcustom org-clock-string "CLOCK:"
850 "String used as prefix for timestamps clocking work hours on an item."
851 :group 'org-keywords
852 :type 'string)
854 (defcustom org-closed-keep-when-no-todo nil
855 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
856 :group 'org-todo
857 :group 'org-keywords
858 :version "24.4"
859 :package-version '(Org . "8.0")
860 :type 'boolean)
862 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
863 org-scheduled-string "\\|"
864 org-deadline-string "\\|"
865 org-closed-string "\\|"
866 org-clock-string "\\)")
867 "Matches a line with planning or clock info.")
869 (defcustom org-comment-string "COMMENT"
870 "Entries starting with this keyword will never be exported.
871 An entry can be toggled between COMMENT and normal with
872 \\[org-toggle-comment].
873 Changes become only effective after restarting Emacs."
874 :group 'org-keywords
875 :type 'string)
877 (defcustom org-quote-string "QUOTE"
878 "Entries starting with this keyword will be exported in fixed-width font.
879 Quoting applies only to the text in the entry following the headline, and does
880 not extend beyond the next headline, even if that is lower level.
881 An entry can be toggled between QUOTE and normal with
882 \\[org-toggle-fixed-width-section]."
883 :group 'org-keywords
884 :type 'string)
886 (defconst org-repeat-re
887 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
888 "Regular expression for specifying repeated events.
889 After a match, group 1 contains the repeat expression.")
891 (defgroup org-structure nil
892 "Options concerning the general structure of Org-mode files."
893 :tag "Org Structure"
894 :group 'org)
896 (defgroup org-reveal-location nil
897 "Options about how to make context of a location visible."
898 :tag "Org Reveal Location"
899 :group 'org-structure)
901 (defconst org-context-choice
902 '(choice
903 (const :tag "Always" t)
904 (const :tag "Never" nil)
905 (repeat :greedy t :tag "Individual contexts"
906 (cons
907 (choice :tag "Context"
908 (const agenda)
909 (const org-goto)
910 (const occur-tree)
911 (const tags-tree)
912 (const link-search)
913 (const mark-goto)
914 (const bookmark-jump)
915 (const isearch)
916 (const default))
917 (boolean))))
918 "Contexts for the reveal options.")
920 (defcustom org-show-hierarchy-above '((default . t))
921 "Non-nil means show full hierarchy when revealing a location.
922 Org-mode often shows locations in an org-mode file which might have
923 been invisible before. When this is set, the hierarchy of headings
924 above the exposed location is shown.
925 Turning this off for example for sparse trees makes them very compact.
926 Instead of t, this can also be an alist specifying this option for different
927 contexts. Valid contexts are
928 agenda when exposing an entry from the agenda
929 org-goto when using the command `org-goto' on key C-c C-j
930 occur-tree when using the command `org-occur' on key C-c /
931 tags-tree when constructing a sparse tree based on tags matches
932 link-search when exposing search matches associated with a link
933 mark-goto when exposing the jump goal of a mark
934 bookmark-jump when exposing a bookmark location
935 isearch when exiting from an incremental search
936 default default for all contexts not set explicitly"
937 :group 'org-reveal-location
938 :type org-context-choice)
940 (defcustom org-show-following-heading '((default . nil))
941 "Non-nil means show following heading when revealing a location.
942 Org-mode often shows locations in an org-mode file which might have
943 been invisible before. When this is set, the heading following the
944 match is shown.
945 Turning this off for example for sparse trees makes them very compact,
946 but makes it harder to edit the location of the match. In such a case,
947 use the command \\[org-reveal] to show more context.
948 Instead of t, this can also be an alist specifying this option for different
949 contexts. See `org-show-hierarchy-above' for valid contexts."
950 :group 'org-reveal-location
951 :type org-context-choice)
953 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
954 "Non-nil means show all sibling heading when revealing a location.
955 Org-mode often shows locations in an org-mode file which might have
956 been invisible before. When this is set, the sibling of the current entry
957 heading are all made visible. If `org-show-hierarchy-above' is t,
958 the same happens on each level of the hierarchy above the current entry.
960 By default this is on for the isearch context, off for all other contexts.
961 Turning this off for example for sparse trees makes them very compact,
962 but makes it harder to edit the location of the match. In such a case,
963 use the command \\[org-reveal] to show more context.
964 Instead of t, this can also be an alist specifying this option for different
965 contexts. See `org-show-hierarchy-above' for valid contexts."
966 :group 'org-reveal-location
967 :type org-context-choice
968 :version "24.4"
969 :package-version '(Org . "8.0"))
971 (defcustom org-show-entry-below '((default . nil))
972 "Non-nil means show the entry below a headline when revealing a location.
973 Org-mode often shows locations in an org-mode file which might have
974 been invisible before. When this is set, the text below the headline that is
975 exposed is also shown.
977 By default this is off for all contexts.
978 Instead of t, this can also be an alist specifying this option for different
979 contexts. See `org-show-hierarchy-above' for valid contexts."
980 :group 'org-reveal-location
981 :type org-context-choice)
983 (defcustom org-indirect-buffer-display 'other-window
984 "How should indirect tree buffers be displayed?
985 This applies to indirect buffers created with the commands
986 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
987 Valid values are:
988 current-window Display in the current window
989 other-window Just display in another window.
990 dedicated-frame Create one new frame, and re-use it each time.
991 new-frame Make a new frame each time. Note that in this case
992 previously-made indirect buffers are kept, and you need to
993 kill these buffers yourself."
994 :group 'org-structure
995 :group 'org-agenda-windows
996 :type '(choice
997 (const :tag "In current window" current-window)
998 (const :tag "In current frame, other window" other-window)
999 (const :tag "Each time a new frame" new-frame)
1000 (const :tag "One dedicated frame" dedicated-frame)))
1002 (defcustom org-use-speed-commands nil
1003 "Non-nil means activate single letter commands at beginning of a headline.
1004 This may also be a function to test for appropriate locations where speed
1005 commands should be active."
1006 :group 'org-structure
1007 :type '(choice
1008 (const :tag "Never" nil)
1009 (const :tag "At beginning of headline stars" t)
1010 (function)))
1012 (defcustom org-speed-commands-user nil
1013 "Alist of additional speed commands.
1014 This list will be checked before `org-speed-commands-default'
1015 when the variable `org-use-speed-commands' is non-nil
1016 and when the cursor is at the beginning of a headline.
1017 The car if each entry is a string with a single letter, which must
1018 be assigned to `self-insert-command' in the global map.
1019 The cdr is either a command to be called interactively, a function
1020 to be called, or a form to be evaluated.
1021 An entry that is just a list with a single string will be interpreted
1022 as a descriptive headline that will be added when listing the speed
1023 commands in the Help buffer using the `?' speed command."
1024 :group 'org-structure
1025 :type '(repeat :value ("k" . ignore)
1026 (choice :value ("k" . ignore)
1027 (list :tag "Descriptive Headline" (string :tag "Headline"))
1028 (cons :tag "Letter and Command"
1029 (string :tag "Command letter")
1030 (choice
1031 (function)
1032 (sexp))))))
1034 (defcustom org-bookmark-names-plist
1035 '(:last-capture "org-capture-last-stored"
1036 :last-refile "org-refile-last-stored"
1037 :last-capture-marker "org-capture-last-stored-marker")
1038 "Names for bookmarks automatically set by some Org commands.
1039 This can provide strings as names for a number of bookmakrs Org sets
1040 automatically. The following keys are currently implemented:
1041 :last-capture
1042 :last-capture-marker
1043 :last-refile
1044 When a key does not show up in the property list, the corresponding bookmark
1045 is not set."
1046 :group 'org-structure
1047 :type 'plist)
1049 (defgroup org-cycle nil
1050 "Options concerning visibility cycling in Org-mode."
1051 :tag "Org Cycle"
1052 :group 'org-structure)
1054 (defcustom org-cycle-skip-children-state-if-no-children t
1055 "Non-nil means skip CHILDREN state in entries that don't have any."
1056 :group 'org-cycle
1057 :type 'boolean)
1059 (defcustom org-cycle-max-level nil
1060 "Maximum level which should still be subject to visibility cycling.
1061 Levels higher than this will, for cycling, be treated as text, not a headline.
1062 When `org-odd-levels-only' is set, a value of N in this variable actually
1063 means 2N-1 stars as the limiting headline.
1064 When nil, cycle all levels.
1065 Note that the limiting level of cycling is also influenced by
1066 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1067 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1068 than its value."
1069 :group 'org-cycle
1070 :type '(choice
1071 (const :tag "No limit" nil)
1072 (integer :tag "Maximum level")))
1074 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1075 "Names of drawers. Drawers are not opened by cycling on the headline above.
1076 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1077 this:
1078 :DRAWERNAME:
1079 .....
1080 :END:
1081 The drawer \"PROPERTIES\" is special for capturing properties through
1082 the property API.
1084 Drawers can be defined on the per-file basis with a line like:
1086 #+DRAWERS: HIDDEN STATE PROPERTIES"
1087 :group 'org-structure
1088 :group 'org-cycle
1089 :type '(repeat (string :tag "Drawer Name")))
1091 (defcustom org-hide-block-startup nil
1092 "Non-nil means entering Org-mode will fold all blocks.
1093 This can also be set in on a per-file basis with
1095 #+STARTUP: hideblocks
1096 #+STARTUP: showblocks"
1097 :group 'org-startup
1098 :group 'org-cycle
1099 :type 'boolean)
1101 (defcustom org-cycle-global-at-bob nil
1102 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1103 This makes it possible to do global cycling without having to use S-TAB or
1104 \\[universal-argument] TAB. For this special case to work, the first line
1105 of the buffer must not be a headline -- it may be empty or some other text.
1106 When used in this way, `org-cycle-hook' is disabled temporarily to make
1107 sure the cursor stays at the beginning of the buffer. When this option is
1108 nil, don't do anything special at the beginning of the buffer."
1109 :group 'org-cycle
1110 :type 'boolean)
1112 (defcustom org-cycle-level-after-item/entry-creation t
1113 "Non-nil means cycle entry level or item indentation in new empty entries.
1115 When the cursor is at the end of an empty headline, i.e., with only stars
1116 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1117 and then all possible ancestor states, before returning to the original state.
1118 This makes data entry extremely fast: M-RET to create a new headline,
1119 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1121 When the cursor is at the end of an empty plain list item, one TAB will
1122 make it a subitem, two or more tabs will back up to make this an item
1123 higher up in the item hierarchy."
1124 :group 'org-cycle
1125 :type 'boolean)
1127 (defcustom org-cycle-emulate-tab t
1128 "Where should `org-cycle' emulate TAB.
1129 nil Never
1130 white Only in completely white lines
1131 whitestart Only at the beginning of lines, before the first non-white char
1132 t Everywhere except in headlines
1133 exc-hl-bol Everywhere except at the start of a headline
1134 If TAB is used in a place where it does not emulate TAB, the current subtree
1135 visibility is cycled."
1136 :group 'org-cycle
1137 :type '(choice (const :tag "Never" nil)
1138 (const :tag "Only in completely white lines" white)
1139 (const :tag "Before first char in a line" whitestart)
1140 (const :tag "Everywhere except in headlines" t)
1141 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1143 (defcustom org-cycle-separator-lines 2
1144 "Number of empty lines needed to keep an empty line between collapsed trees.
1145 If you leave an empty line between the end of a subtree and the following
1146 headline, this empty line is hidden when the subtree is folded.
1147 Org-mode will leave (exactly) one empty line visible if the number of
1148 empty lines is equal or larger to the number given in this variable.
1149 So the default 2 means at least 2 empty lines after the end of a subtree
1150 are needed to produce free space between a collapsed subtree and the
1151 following headline.
1153 If the number is negative, and the number of empty lines is at least -N,
1154 all empty lines are shown.
1156 Special case: when 0, never leave empty lines in collapsed view."
1157 :group 'org-cycle
1158 :type 'integer)
1159 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1161 (defcustom org-pre-cycle-hook nil
1162 "Hook that is run before visibility cycling is happening.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that will be set right after running this hook. The
1165 argument is a symbol. Before a global state change, it can have the values
1166 `overview', `content', or `all'. Before a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1172 org-cycle-hide-drawers
1173 org-cycle-hide-inline-tasks
1174 org-cycle-show-empty-lines
1175 org-optimize-window-after-visibility-change)
1176 "Hook that is run after `org-cycle' has changed the buffer visibility.
1177 The function(s) in this hook must accept a single argument which indicates
1178 the new state that was set by the most recent `org-cycle' command. The
1179 argument is a symbol. After a global state change, it can have the values
1180 `overview', `contents', or `all'. After a local state change, it can have
1181 the values `folded', `children', or `subtree'."
1182 :group 'org-cycle
1183 :type 'hook)
1185 (defgroup org-edit-structure nil
1186 "Options concerning structure editing in Org-mode."
1187 :tag "Org Edit Structure"
1188 :group 'org-structure)
1190 (defcustom org-odd-levels-only nil
1191 "Non-nil means skip even levels and only use odd levels for the outline.
1192 This has the effect that two stars are being added/taken away in
1193 promotion/demotion commands. It also influences how levels are
1194 handled by the exporters.
1195 Changing it requires restart of `font-lock-mode' to become effective
1196 for fontification also in regions already fontified.
1197 You may also set this on a per-file basis by adding one of the following
1198 lines to the buffer:
1200 #+STARTUP: odd
1201 #+STARTUP: oddeven"
1202 :group 'org-edit-structure
1203 :group 'org-appearance
1204 :type 'boolean)
1206 (defcustom org-adapt-indentation t
1207 "Non-nil means adapt indentation to outline node level.
1209 When this variable is set, Org assumes that you write outlines by
1210 indenting text in each node to align with the headline (after the stars).
1211 The following issues are influenced by this variable:
1213 - When this is set and the *entire* text in an entry is indented, the
1214 indentation is increased by one space in a demotion command, and
1215 decreased by one in a promotion command. If any line in the entry
1216 body starts with text at column 0, indentation is not changed at all.
1218 - Property drawers and planning information is inserted indented when
1219 this variable s set. When nil, they will not be indented.
1221 - TAB indents a line relative to context. The lines below a headline
1222 will be indented when this variable is set.
1224 Note that this is all about true indentation, by adding and removing
1225 space characters. See also `org-indent.el' which does level-dependent
1226 indentation in a virtual way, i.e. at display time in Emacs."
1227 :group 'org-edit-structure
1228 :type 'boolean)
1230 (defcustom org-special-ctrl-a/e nil
1231 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1233 When t, `C-a' will bring back the cursor to the beginning of the
1234 headline text, i.e. after the stars and after a possible TODO
1235 keyword. In an item, this will be the position after bullet and
1236 check-box, if any. When the cursor is already at that position,
1237 another `C-a' will bring it to the beginning of the line.
1239 `C-e' will jump to the end of the headline, ignoring the presence
1240 of tags in the headline. A second `C-e' will then jump to the
1241 true end of the line, after any tags. This also means that, when
1242 this variable is non-nil, `C-e' also will never jump beyond the
1243 end of the heading of a folded section, i.e. not after the
1244 ellipses.
1246 When set to the symbol `reversed', the first `C-a' or `C-e' works
1247 normally, going to the true line boundary first. Only a directly
1248 following, identical keypress will bring the cursor to the
1249 special positions.
1251 This may also be a cons cell where the behavior for `C-a' and
1252 `C-e' is set separately."
1253 :group 'org-edit-structure
1254 :type '(choice
1255 (const :tag "off" nil)
1256 (const :tag "on: after stars/bullet and before tags first" t)
1257 (const :tag "reversed: true line boundary first" reversed)
1258 (cons :tag "Set C-a and C-e separately"
1259 (choice :tag "Special C-a"
1260 (const :tag "off" nil)
1261 (const :tag "on: after stars/bullet first" t)
1262 (const :tag "reversed: before stars/bullet first" reversed))
1263 (choice :tag "Special C-e"
1264 (const :tag "off" nil)
1265 (const :tag "on: before tags first" t)
1266 (const :tag "reversed: after tags first" reversed)))))
1267 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1269 (defcustom org-special-ctrl-k nil
1270 "Non-nil means `C-k' will behave specially in headlines.
1271 When nil, `C-k' will call the default `kill-line' command.
1272 When t, the following will happen while the cursor is in the headline:
1274 - When the cursor is at the beginning of a headline, kill the entire
1275 line and possible the folded subtree below the line.
1276 - When in the middle of the headline text, kill the headline up to the tags.
1277 - When after the headline text, kill the tags."
1278 :group 'org-edit-structure
1279 :type 'boolean)
1281 (defcustom org-ctrl-k-protect-subtree nil
1282 "Non-nil means, do not delete a hidden subtree with C-k.
1283 When set to the symbol `error', simply throw an error when C-k is
1284 used to kill (part-of) a headline that has hidden text behind it.
1285 Any other non-nil value will result in a query to the user, if it is
1286 OK to kill that hidden subtree. When nil, kill without remorse."
1287 :group 'org-edit-structure
1288 :version "24.1"
1289 :type '(choice
1290 (const :tag "Do not protect hidden subtrees" nil)
1291 (const :tag "Protect hidden subtrees with a security query" t)
1292 (const :tag "Never kill a hidden subtree with C-k" error)))
1294 (defcustom org-special-ctrl-o t
1295 "Non-nil means, make `C-o' insert a row in tables."
1296 :group 'org-edit-structure
1297 :type 'boolean)
1299 (defcustom org-catch-invisible-edits nil
1300 "Check if in invisible region before inserting or deleting a character.
1301 Valid values are:
1303 nil Do not check, so just do invisible edits.
1304 error Throw an error and do nothing.
1305 show Make point visible, and do the requested edit.
1306 show-and-error Make point visible, then throw an error and abort the edit.
1307 smart Make point visible, and do insertion/deletion if it is
1308 adjacent to visible text and the change feels predictable.
1309 Never delete a previously invisible character or add in the
1310 middle or right after an invisible region. Basically, this
1311 allows insertion and backward-delete right before ellipses.
1312 FIXME: maybe in this case we should not even show?"
1313 :group 'org-edit-structure
1314 :version "24.1"
1315 :type '(choice
1316 (const :tag "Do not check" nil)
1317 (const :tag "Throw error when trying to edit" error)
1318 (const :tag "Unhide, but do not do the edit" show-and-error)
1319 (const :tag "Show invisible part and do the edit" show)
1320 (const :tag "Be smart and do the right thing" smart)))
1322 (defcustom org-yank-folded-subtrees t
1323 "Non-nil means when yanking subtrees, fold them.
1324 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1325 it starts with a heading and all other headings in it are either children
1326 or siblings, then fold all the subtrees. However, do this only if no
1327 text after the yank would be swallowed into a folded tree by this action."
1328 :group 'org-edit-structure
1329 :type 'boolean)
1331 (defcustom org-yank-adjusted-subtrees nil
1332 "Non-nil means when yanking subtrees, adjust the level.
1333 With this setting, `org-paste-subtree' is used to insert the subtree, see
1334 this function for details."
1335 :group 'org-edit-structure
1336 :type 'boolean)
1338 (defcustom org-M-RET-may-split-line '((default . t))
1339 "Non-nil means M-RET will split the line at the cursor position.
1340 When nil, it will go to the end of the line before making a
1341 new line.
1342 You may also set this option in a different way for different
1343 contexts. Valid contexts are:
1345 headline when creating a new headline
1346 item when creating a new item
1347 table in a table field
1348 default the value to be used for all contexts not explicitly
1349 customized"
1350 :group 'org-structure
1351 :group 'org-table
1352 :type '(choice
1353 (const :tag "Always" t)
1354 (const :tag "Never" nil)
1355 (repeat :greedy t :tag "Individual contexts"
1356 (cons
1357 (choice :tag "Context"
1358 (const headline)
1359 (const item)
1360 (const table)
1361 (const default))
1362 (boolean)))))
1365 (defcustom org-insert-heading-respect-content nil
1366 "Non-nil means insert new headings after the current subtree.
1367 When nil, the new heading is created directly after the current line.
1368 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1369 this variable on for the duration of the command."
1370 :group 'org-structure
1371 :type 'boolean)
1373 (defcustom org-blank-before-new-entry '((heading . auto)
1374 (plain-list-item . auto))
1375 "Should `org-insert-heading' leave a blank line before new heading/item?
1376 The value is an alist, with `heading' and `plain-list-item' as CAR,
1377 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1378 which case Org will look at the surrounding headings/items and try to
1379 make an intelligent decision whether to insert a blank line or not.
1381 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1382 the setting here is ignored and no empty line is inserted to avoid breaking
1383 the list structure."
1384 :group 'org-edit-structure
1385 :type '(list
1386 (cons (const heading)
1387 (choice (const :tag "Never" nil)
1388 (const :tag "Always" t)
1389 (const :tag "Auto" auto)))
1390 (cons (const plain-list-item)
1391 (choice (const :tag "Never" nil)
1392 (const :tag "Always" t)
1393 (const :tag "Auto" auto)))))
1395 (defcustom org-insert-heading-hook nil
1396 "Hook being run after inserting a new heading."
1397 :group 'org-edit-structure
1398 :type 'hook)
1400 (defcustom org-enable-fixed-width-editor t
1401 "Non-nil means lines starting with \":\" are treated as fixed-width.
1402 This currently only means they are never auto-wrapped.
1403 When nil, such lines will be treated like ordinary lines.
1404 See also the QUOTE keyword."
1405 :group 'org-edit-structure
1406 :type 'boolean)
1408 (defcustom org-goto-auto-isearch t
1409 "Non-nil means typing characters in `org-goto' starts incremental search.
1410 When nil, you can use these keybindings to navigate the buffer:
1412 q Quit the org-goto interface
1413 n Go to the next visible heading
1414 p Go to the previous visible heading
1415 f Go one heading forward on same level
1416 b Go one heading backward on same level
1417 u Go one heading up"
1418 :group 'org-edit-structure
1419 :type 'boolean)
1421 (defgroup org-sparse-trees nil
1422 "Options concerning sparse trees in Org-mode."
1423 :tag "Org Sparse Trees"
1424 :group 'org-structure)
1426 (defcustom org-highlight-sparse-tree-matches t
1427 "Non-nil means highlight all matches that define a sparse tree.
1428 The highlights will automatically disappear the next time the buffer is
1429 changed by an edit command."
1430 :group 'org-sparse-trees
1431 :type 'boolean)
1433 (defcustom org-remove-highlights-with-change t
1434 "Non-nil means any change to the buffer will remove temporary highlights.
1435 Such highlights are created by `org-occur' and `org-clock-display'.
1436 When nil, `C-c C-c needs to be used to get rid of the highlights.
1437 The highlights created by `org-preview-latex-fragment' always need
1438 `C-c C-c' to be removed."
1439 :group 'org-sparse-trees
1440 :group 'org-time
1441 :type 'boolean)
1444 (defcustom org-occur-hook '(org-first-headline-recenter)
1445 "Hook that is run after `org-occur' has constructed a sparse tree.
1446 This can be used to recenter the window to show as much of the structure
1447 as possible."
1448 :group 'org-sparse-trees
1449 :type 'hook)
1451 (defgroup org-imenu-and-speedbar nil
1452 "Options concerning imenu and speedbar in Org-mode."
1453 :tag "Org Imenu and Speedbar"
1454 :group 'org-structure)
1456 (defcustom org-imenu-depth 2
1457 "The maximum level for Imenu access to Org-mode headlines.
1458 This also applied for speedbar access."
1459 :group 'org-imenu-and-speedbar
1460 :type 'integer)
1462 (defgroup org-table nil
1463 "Options concerning tables in Org-mode."
1464 :tag "Org Table"
1465 :group 'org)
1467 (defcustom org-enable-table-editor 'optimized
1468 "Non-nil means lines starting with \"|\" are handled by the table editor.
1469 When nil, such lines will be treated like ordinary lines.
1471 When equal to the symbol `optimized', the table editor will be optimized to
1472 do the following:
1473 - Automatic overwrite mode in front of whitespace in table fields.
1474 This makes the structure of the table stay in tact as long as the edited
1475 field does not exceed the column width.
1476 - Minimize the number of realigns. Normally, the table is aligned each time
1477 TAB or RET are pressed to move to another field. With optimization this
1478 happens only if changes to a field might have changed the column width.
1479 Optimization requires replacing the functions `self-insert-command',
1480 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1481 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1482 very good at guessing when a re-align will be necessary, but you can always
1483 force one with \\[org-ctrl-c-ctrl-c].
1485 If you would like to use the optimized version in Org-mode, but the
1486 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1488 This variable can be used to turn on and off the table editor during a session,
1489 but in order to toggle optimization, a restart is required.
1491 See also the variable `org-table-auto-blank-field'."
1492 :group 'org-table
1493 :type '(choice
1494 (const :tag "off" nil)
1495 (const :tag "on" t)
1496 (const :tag "on, optimized" optimized)))
1498 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1499 (version<= emacs-version "24.1"))
1500 "Non-nil means cluster self-insert commands for undo when possible.
1501 If this is set, then, like in the Emacs command loop, 20 consecutive
1502 characters will be undone together.
1503 This is configurable, because there is some impact on typing performance."
1504 :group 'org-table
1505 :type 'boolean)
1507 (defcustom org-table-tab-recognizes-table.el t
1508 "Non-nil means TAB will automatically notice a table.el table.
1509 When it sees such a table, it moves point into it and - if necessary -
1510 calls `table-recognize-table'."
1511 :group 'org-table-editing
1512 :type 'boolean)
1514 (defgroup org-link nil
1515 "Options concerning links in Org-mode."
1516 :tag "Org Link"
1517 :group 'org)
1519 (defvar org-link-abbrev-alist-local nil
1520 "Buffer-local version of `org-link-abbrev-alist', which see.
1521 The value of this is taken from the #+LINK lines.")
1522 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1524 (defcustom org-link-abbrev-alist nil
1525 "Alist of link abbreviations.
1526 The car of each element is a string, to be replaced at the start of a link.
1527 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1528 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1530 [[linkkey:tag][description]]
1532 The 'linkkey' must be a word word, starting with a letter, followed
1533 by letters, numbers, '-' or '_'.
1535 If REPLACE is a string, the tag will simply be appended to create the link.
1536 If the string contains \"%s\", the tag will be inserted there. If the string
1537 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1538 at that point (see the function `url-hexify-string'). If the string contains
1539 the specifier \"%(my-function)\", then the custom function `my-function' will
1540 be invoked: this function takes the tag as its only argument and must return
1541 a string.
1543 REPLACE may also be a function that will be called with the tag as the
1544 only argument to create the link, which should be returned as a string.
1546 See the manual for examples."
1547 :group 'org-link
1548 :type '(repeat
1549 (cons
1550 (string :tag "Protocol")
1551 (choice
1552 (string :tag "Format")
1553 (function)))))
1555 (defcustom org-descriptive-links t
1556 "Non-nil means Org will display descriptive links.
1557 E.g. [[http://orgmode.org][Org website]] will be displayed as
1558 \"Org Website\", hiding the link itself and just displaying its
1559 description. When set to `nil', Org will display the full links
1560 literally.
1562 You can interactively set the value of this variable by calling
1563 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1564 :group 'org-link
1565 :type 'boolean)
1567 (defcustom org-link-file-path-type 'adaptive
1568 "How the path name in file links should be stored.
1569 Valid values are:
1571 relative Relative to the current directory, i.e. the directory of the file
1572 into which the link is being inserted.
1573 absolute Absolute path, if possible with ~ for home directory.
1574 noabbrev Absolute path, no abbreviation of home directory.
1575 adaptive Use relative path for files in the current directory and sub-
1576 directories of it. For other files, use an absolute path."
1577 :group 'org-link
1578 :type '(choice
1579 (const relative)
1580 (const absolute)
1581 (const noabbrev)
1582 (const adaptive)))
1584 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1585 "Types of links that should be activated in Org-mode files.
1586 This is a list of symbols, each leading to the activation of a certain link
1587 type. In principle, it does not hurt to turn on most link types - there may
1588 be a small gain when turning off unused link types. The types are:
1590 bracket The recommended [[link][description]] or [[link]] links with hiding.
1591 angle Links in angular brackets that may contain whitespace like
1592 <bbdb:Carsten Dominik>.
1593 plain Plain links in normal text, no whitespace, like http://google.com.
1594 radio Text that is matched by a radio target, see manual for details.
1595 tag Tag settings in a headline (link to tag search).
1596 date Time stamps (link to calendar).
1597 footnote Footnote labels.
1599 Changing this variable requires a restart of Emacs to become effective."
1600 :group 'org-link
1601 :type '(set :greedy t
1602 (const :tag "Double bracket links" bracket)
1603 (const :tag "Angular bracket links" angle)
1604 (const :tag "Plain text links" plain)
1605 (const :tag "Radio target matches" radio)
1606 (const :tag "Tags" tag)
1607 (const :tag "Timestamps" date)
1608 (const :tag "Footnotes" footnote)))
1610 (defcustom org-make-link-description-function nil
1611 "Function to use for generating link descriptions from links.
1612 When nil, the link location will be used. This function must take
1613 two parameters: the first one is the link, the second one is the
1614 description generated by `org-insert-link'. The function should
1615 return the description to use."
1616 :group 'org-link
1617 :type '(choice (const nil) (function)))
1619 (defgroup org-link-store nil
1620 "Options concerning storing links in Org-mode."
1621 :tag "Org Store Link"
1622 :group 'org-link)
1624 (defcustom org-url-hexify-p t
1625 "When non-nil, hexify URL when creating a link."
1626 :type 'boolean
1627 :version "24.3"
1628 :group 'org-link-store)
1630 (defcustom org-email-link-description-format "Email %c: %.30s"
1631 "Format of the description part of a link to an email or usenet message.
1632 The following %-escapes will be replaced by corresponding information:
1634 %F full \"From\" field
1635 %f name, taken from \"From\" field, address if no name
1636 %T full \"To\" field
1637 %t first name in \"To\" field, address if no name
1638 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1639 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1640 %s subject
1641 %d date
1642 %m message-id.
1644 You may use normal field width specification between the % and the letter.
1645 This is for example useful to limit the length of the subject.
1647 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1648 :group 'org-link-store
1649 :type 'string)
1651 (defcustom org-from-is-user-regexp
1652 (let (r1 r2)
1653 (when (and user-mail-address (not (string= user-mail-address "")))
1654 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1655 (when (and user-full-name (not (string= user-full-name "")))
1656 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1657 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1658 "Regexp matched against the \"From:\" header of an email or usenet message.
1659 It should match if the message is from the user him/herself."
1660 :group 'org-link-store
1661 :type 'regexp)
1663 (defcustom org-context-in-file-links t
1664 "Non-nil means file links from `org-store-link' contain context.
1665 A search string will be added to the file name with :: as separator and
1666 used to find the context when the link is activated by the command
1667 `org-open-at-point'. When this option is t, the entire active region
1668 will be placed in the search string of the file link. If set to a
1669 positive integer, only the first n lines of context will be stored.
1671 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1672 negates this setting for the duration of the command."
1673 :group 'org-link-store
1674 :type '(choice boolean integer))
1676 (defcustom org-keep-stored-link-after-insertion nil
1677 "Non-nil means keep link in list for entire session.
1679 The command `org-store-link' adds a link pointing to the current
1680 location to an internal list. These links accumulate during a session.
1681 The command `org-insert-link' can be used to insert links into any
1682 Org-mode file (offering completion for all stored links). When this
1683 option is nil, every link which has been inserted once using \\[org-insert-link]
1684 will be removed from the list, to make completing the unused links
1685 more efficient."
1686 :group 'org-link-store
1687 :type 'boolean)
1689 (defgroup org-link-follow nil
1690 "Options concerning following links in Org-mode."
1691 :tag "Org Follow Link"
1692 :group 'org-link)
1694 (defcustom org-link-translation-function nil
1695 "Function to translate links with different syntax to Org syntax.
1696 This can be used to translate links created for example by the Planner
1697 or emacs-wiki packages to Org syntax.
1698 The function must accept two parameters, a TYPE containing the link
1699 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1700 which is everything after the link protocol. It should return a cons
1701 with possibly modified values of type and path.
1702 Org contains a function for this, so if you set this variable to
1703 `org-translate-link-from-planner', you should be able follow many
1704 links created by planner."
1705 :group 'org-link-follow
1706 :type '(choice (const nil) (function)))
1708 (defcustom org-follow-link-hook nil
1709 "Hook that is run after a link has been followed."
1710 :group 'org-link-follow
1711 :type 'hook)
1713 (defcustom org-tab-follows-link nil
1714 "Non-nil means on links TAB will follow the link.
1715 Needs to be set before org.el is loaded.
1716 This really should not be used, it does not make sense, and the
1717 implementation is bad."
1718 :group 'org-link-follow
1719 :type 'boolean)
1721 (defcustom org-return-follows-link nil
1722 "Non-nil means on links RET will follow the link.
1723 In tables, the special behavior of RET has precedence."
1724 :group 'org-link-follow
1725 :type 'boolean)
1727 (defcustom org-mouse-1-follows-link
1728 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1729 "Non-nil means mouse-1 on a link will follow the link.
1730 A longer mouse click will still set point. Does not work on XEmacs.
1731 Needs to be set before org.el is loaded."
1732 :group 'org-link-follow
1733 :type 'boolean)
1735 (defcustom org-mark-ring-length 4
1736 "Number of different positions to be recorded in the ring.
1737 Changing this requires a restart of Emacs to work correctly."
1738 :group 'org-link-follow
1739 :type 'integer)
1741 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1742 "Non-nil means internal links in Org files must exactly match a headline.
1743 When nil, the link search tries to match a phrase with all words
1744 in the search text."
1745 :group 'org-link-follow
1746 :version "24.1"
1747 :type '(choice
1748 (const :tag "Use fuzzy text search" nil)
1749 (const :tag "Match only exact headline" t)
1750 (const :tag "Match exact headline or query to create it"
1751 query-to-create)))
1753 (defcustom org-link-frame-setup
1754 '((vm . vm-visit-folder-other-frame)
1755 (vm-imap . vm-visit-imap-folder-other-frame)
1756 (gnus . org-gnus-no-new-news)
1757 (file . find-file-other-window)
1758 (wl . wl-other-frame))
1759 "Setup the frame configuration for following links.
1760 When following a link with Emacs, it may often be useful to display
1761 this link in another window or frame. This variable can be used to
1762 set this up for the different types of links.
1763 For VM, use any of
1764 `vm-visit-folder'
1765 `vm-visit-folder-other-window'
1766 `vm-visit-folder-other-frame'
1767 For Gnus, use any of
1768 `gnus'
1769 `gnus-other-frame'
1770 `org-gnus-no-new-news'
1771 For FILE, use any of
1772 `find-file'
1773 `find-file-other-window'
1774 `find-file-other-frame'
1775 For Wanderlust use any of
1776 `wl'
1777 `wl-other-frame'
1778 For the calendar, use the variable `calendar-setup'.
1779 For BBDB, it is currently only possible to display the matches in
1780 another window."
1781 :group 'org-link-follow
1782 :type '(list
1783 (cons (const vm)
1784 (choice
1785 (const vm-visit-folder)
1786 (const vm-visit-folder-other-window)
1787 (const vm-visit-folder-other-frame)))
1788 (cons (const vm-imap)
1789 (choice
1790 (const vm-visit-imap-folder)
1791 (const vm-visit-imap-folder-other-window)
1792 (const vm-visit-imap-folder-other-frame)))
1793 (cons (const gnus)
1794 (choice
1795 (const gnus)
1796 (const gnus-other-frame)
1797 (const org-gnus-no-new-news)))
1798 (cons (const file)
1799 (choice
1800 (const find-file)
1801 (const find-file-other-window)
1802 (const find-file-other-frame)))
1803 (cons (const wl)
1804 (choice
1805 (const wl)
1806 (const wl-other-frame)))))
1808 (defcustom org-display-internal-link-with-indirect-buffer nil
1809 "Non-nil means use indirect buffer to display infile links.
1810 Activating internal links (from one location in a file to another location
1811 in the same file) normally just jumps to the location. When the link is
1812 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1813 is displayed in
1814 another window. When this option is set, the other window actually displays
1815 an indirect buffer clone of the current buffer, to avoid any visibility
1816 changes to the current buffer."
1817 :group 'org-link-follow
1818 :type 'boolean)
1820 (defcustom org-open-non-existing-files nil
1821 "Non-nil means `org-open-file' will open non-existing files.
1822 When nil, an error will be generated.
1823 This variable applies only to external applications because they
1824 might choke on non-existing files. If the link is to a file that
1825 will be opened in Emacs, the variable is ignored."
1826 :group 'org-link-follow
1827 :type 'boolean)
1829 (defcustom org-open-directory-means-index-dot-org nil
1830 "Non-nil means a link to a directory really means to index.org.
1831 When nil, following a directory link will run dired or open a finder/explorer
1832 window on that directory."
1833 :group 'org-link-follow
1834 :type 'boolean)
1836 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1837 "Function and arguments to call for following mailto links.
1838 This is a list with the first element being a Lisp function, and the
1839 remaining elements being arguments to the function. In string arguments,
1840 %a will be replaced by the address, and %s will be replaced by the subject
1841 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1842 :group 'org-link-follow
1843 :type '(choice
1844 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1845 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1846 (const :tag "message-mail" (message-mail "%a" "%s"))
1847 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1849 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1850 "Non-nil means ask for confirmation before executing shell links.
1851 Shell links can be dangerous: just think about a link
1853 [[shell:rm -rf ~/*][Google Search]]
1855 This link would show up in your Org-mode document as \"Google Search\",
1856 but really it would remove your entire home directory.
1857 Therefore we advise against setting this variable to nil.
1858 Just change it to `y-or-n-p' if you want to confirm with a
1859 single keystroke rather than having to type \"yes\"."
1860 :group 'org-link-follow
1861 :type '(choice
1862 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1863 (const :tag "with y-or-n (faster)" y-or-n-p)
1864 (const :tag "no confirmation (dangerous)" nil)))
1865 (put 'org-confirm-shell-link-function
1866 'safe-local-variable
1867 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1869 (defcustom org-confirm-shell-link-not-regexp ""
1870 "A regexp to skip confirmation for shell links."
1871 :group 'org-link-follow
1872 :version "24.1"
1873 :type 'regexp)
1875 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1876 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1877 Elisp links can be dangerous: just think about a link
1879 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1881 This link would show up in your Org-mode document as \"Google Search\",
1882 but really it would remove your entire home directory.
1883 Therefore we advise against setting this variable to nil.
1884 Just change it to `y-or-n-p' if you want to confirm with a
1885 single keystroke rather than having to type \"yes\"."
1886 :group 'org-link-follow
1887 :type '(choice
1888 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1889 (const :tag "with y-or-n (faster)" y-or-n-p)
1890 (const :tag "no confirmation (dangerous)" nil)))
1891 (put 'org-confirm-shell-link-function
1892 'safe-local-variable
1893 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1895 (defcustom org-confirm-elisp-link-not-regexp ""
1896 "A regexp to skip confirmation for Elisp links."
1897 :group 'org-link-follow
1898 :version "24.1"
1899 :type 'regexp)
1901 (defconst org-file-apps-defaults-gnu
1902 '((remote . emacs)
1903 (system . mailcap)
1904 (t . mailcap))
1905 "Default file applications on a UNIX or GNU/Linux system.
1906 See `org-file-apps'.")
1908 (defconst org-file-apps-defaults-macosx
1909 '((remote . emacs)
1910 (t . "open %s")
1911 (system . "open %s")
1912 ("ps.gz" . "gv %s")
1913 ("eps.gz" . "gv %s")
1914 ("dvi" . "xdvi %s")
1915 ("fig" . "xfig %s"))
1916 "Default file applications on a MacOS X system.
1917 The system \"open\" is known as a default, but we use X11 applications
1918 for some files for which the OS does not have a good default.
1919 See `org-file-apps'.")
1921 (defconst org-file-apps-defaults-windowsnt
1922 (list
1923 '(remote . emacs)
1924 (cons t
1925 (list (if (featurep 'xemacs)
1926 'mswindows-shell-execute
1927 'w32-shell-execute)
1928 "open" 'file))
1929 (cons 'system
1930 (list (if (featurep 'xemacs)
1931 'mswindows-shell-execute
1932 'w32-shell-execute)
1933 "open" 'file)))
1934 "Default file applications on a Windows NT system.
1935 The system \"open\" is used for most files.
1936 See `org-file-apps'.")
1938 (defcustom org-file-apps
1939 '((auto-mode . emacs)
1940 ("\\.mm\\'" . default)
1941 ("\\.x?html?\\'" . default)
1942 ("\\.pdf\\'" . default))
1943 "External applications for opening `file:path' items in a document.
1944 Org-mode uses system defaults for different file types, but
1945 you can use this variable to set the application for a given file
1946 extension. The entries in this list are cons cells where the car identifies
1947 files and the cdr the corresponding command. Possible values for the
1948 file identifier are
1949 \"string\" A string as a file identifier can be interpreted in different
1950 ways, depending on its contents:
1952 - Alphanumeric characters only:
1953 Match links with this file extension.
1954 Example: (\"pdf\" . \"evince %s\")
1955 to open PDFs with evince.
1957 - Regular expression: Match links where the
1958 filename matches the regexp. If you want to
1959 use groups here, use shy groups.
1961 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1962 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1963 to open *.html and *.xhtml with firefox.
1965 - Regular expression which contains (non-shy) groups:
1966 Match links where the whole link, including \"::\", and
1967 anything after that, matches the regexp.
1968 In a custom command string, %1, %2, etc. are replaced with
1969 the parts of the link that were matched by the groups.
1970 For backwards compatibility, if a command string is given
1971 that does not use any of the group matches, this case is
1972 handled identically to the second one (i.e. match against
1973 file name only).
1974 In a custom lisp form, you can access the group matches with
1975 (match-string n link).
1977 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1978 to open [[file:document.pdf::5]] with evince at page 5.
1980 `directory' Matches a directory
1981 `remote' Matches a remote file, accessible through tramp or efs.
1982 Remote files most likely should be visited through Emacs
1983 because external applications cannot handle such paths.
1984 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1985 so all files Emacs knows how to handle. Using this with
1986 command `emacs' will open most files in Emacs. Beware that this
1987 will also open html files inside Emacs, unless you add
1988 (\"html\" . default) to the list as well.
1989 t Default for files not matched by any of the other options.
1990 `system' The system command to open files, like `open' on Windows
1991 and Mac OS X, and mailcap under GNU/Linux. This is the command
1992 that will be selected if you call `C-c C-o' with a double
1993 \\[universal-argument] \\[universal-argument] prefix.
1995 Possible values for the command are:
1996 `emacs' The file will be visited by the current Emacs process.
1997 `default' Use the default application for this file type, which is the
1998 association for t in the list, most likely in the system-specific
1999 part.
2000 This can be used to overrule an unwanted setting in the
2001 system-specific variable.
2002 `system' Use the system command for opening files, like \"open\".
2003 This command is specified by the entry whose car is `system'.
2004 Most likely, the system-specific version of this variable
2005 does define this command, but you can overrule/replace it
2006 here.
2007 string A command to be executed by a shell; %s will be replaced
2008 by the path to the file.
2009 sexp A Lisp form which will be evaluated. The file path will
2010 be available in the Lisp variable `file'.
2011 For more examples, see the system specific constants
2012 `org-file-apps-defaults-macosx'
2013 `org-file-apps-defaults-windowsnt'
2014 `org-file-apps-defaults-gnu'."
2015 :group 'org-link-follow
2016 :type '(repeat
2017 (cons (choice :value ""
2018 (string :tag "Extension")
2019 (const :tag "System command to open files" system)
2020 (const :tag "Default for unrecognized files" t)
2021 (const :tag "Remote file" remote)
2022 (const :tag "Links to a directory" directory)
2023 (const :tag "Any files that have Emacs modes"
2024 auto-mode))
2025 (choice :value ""
2026 (const :tag "Visit with Emacs" emacs)
2027 (const :tag "Use default" default)
2028 (const :tag "Use the system command" system)
2029 (string :tag "Command")
2030 (sexp :tag "Lisp form")))))
2032 (defcustom org-doi-server-url "http://dx.doi.org/"
2033 "The URL of the DOI server."
2034 :type 'string
2035 :version "24.3"
2036 :group 'org-link-follow)
2038 (defgroup org-refile nil
2039 "Options concerning refiling entries in Org-mode."
2040 :tag "Org Refile"
2041 :group 'org)
2043 (defcustom org-directory "~/org"
2044 "Directory with org files.
2045 This is just a default location to look for Org files. There is no need
2046 at all to put your files into this directory. It is only used in the
2047 following situations:
2049 1. When a capture template specifies a target file that is not an
2050 absolute path. The path will then be interpreted relative to
2051 `org-directory'
2052 2. When a capture note is filed away in an interactive way (when exiting the
2053 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2054 with `org-directory' as the default path."
2055 :group 'org-refile
2056 :group 'org-remember
2057 :group 'org-capture
2058 :type 'directory)
2060 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2061 "Default target for storing notes.
2062 Used as a fall back file for org-remember.el and org-capture.el, for
2063 templates that do not specify a target file."
2064 :group 'org-refile
2065 :group 'org-remember
2066 :group 'org-capture
2067 :type '(choice
2068 (const :tag "Default from remember-data-file" nil)
2069 file))
2071 (defcustom org-goto-interface 'outline
2072 "The default interface to be used for `org-goto'.
2073 Allowed values are:
2074 outline The interface shows an outline of the relevant file
2075 and the correct heading is found by moving through
2076 the outline or by searching with incremental search.
2077 outline-path-completion Headlines in the current buffer are offered via
2078 completion. This is the interface also used by
2079 the refile command."
2080 :group 'org-refile
2081 :type '(choice
2082 (const :tag "Outline" outline)
2083 (const :tag "Outline-path-completion" outline-path-completion)))
2085 (defcustom org-goto-max-level 5
2086 "Maximum target level when running `org-goto' with refile interface."
2087 :group 'org-refile
2088 :type 'integer)
2090 (defcustom org-reverse-note-order nil
2091 "Non-nil means store new notes at the beginning of a file or entry.
2092 When nil, new notes will be filed to the end of a file or entry.
2093 This can also be a list with cons cells of regular expressions that
2094 are matched against file names, and values."
2095 :group 'org-remember
2096 :group 'org-capture
2097 :group 'org-refile
2098 :type '(choice
2099 (const :tag "Reverse always" t)
2100 (const :tag "Reverse never" nil)
2101 (repeat :tag "By file name regexp"
2102 (cons regexp boolean))))
2104 (defcustom org-log-refile nil
2105 "Information to record when a task is refiled.
2107 Possible values are:
2109 nil Don't add anything
2110 time Add a time stamp to the task
2111 note Prompt for a note and add it with template `org-log-note-headings'
2113 This option can also be set with on a per-file-basis with
2115 #+STARTUP: nologrefile
2116 #+STARTUP: logrefile
2117 #+STARTUP: lognoterefile
2119 You can have local logging settings for a subtree by setting the LOGGING
2120 property to one or more of these keywords.
2122 When bulk-refiling from the agenda, the value `note' is forbidden and
2123 will temporarily be changed to `time'."
2124 :group 'org-refile
2125 :group 'org-progress
2126 :version "24.1"
2127 :type '(choice
2128 (const :tag "No logging" nil)
2129 (const :tag "Record timestamp" time)
2130 (const :tag "Record timestamp with note." note)))
2132 (defcustom org-refile-targets nil
2133 "Targets for refiling entries with \\[org-refile].
2134 This is a list of cons cells. Each cell contains:
2135 - a specification of the files to be considered, either a list of files,
2136 or a symbol whose function or variable value will be used to retrieve
2137 a file name or a list of file names. If you use `org-agenda-files' for
2138 that, all agenda files will be scanned for targets. Nil means consider
2139 headings in the current buffer.
2140 - A specification of how to find candidate refile targets. This may be
2141 any of:
2142 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2143 This tag has to be present in all target headlines, inheritance will
2144 not be considered.
2145 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2146 todo keyword.
2147 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2148 headlines that are refiling targets.
2149 - a cons cell (:level . N). Any headline of level N is considered a target.
2150 Note that, when `org-odd-levels-only' is set, level corresponds to
2151 order in hierarchy, not to the number of stars.
2152 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2153 Note that, when `org-odd-levels-only' is set, level corresponds to
2154 order in hierarchy, not to the number of stars.
2156 Each element of this list generates a set of possible targets.
2157 The union of these sets is presented (with completion) to
2158 the user by `org-refile'.
2160 You can set the variable `org-refile-target-verify-function' to a function
2161 to verify each headline found by the simple criteria above.
2163 When this variable is nil, all top-level headlines in the current buffer
2164 are used, equivalent to the value `((nil . (:level . 1))'."
2165 :group 'org-refile
2166 :type '(repeat
2167 (cons
2168 (choice :value org-agenda-files
2169 (const :tag "All agenda files" org-agenda-files)
2170 (const :tag "Current buffer" nil)
2171 (function) (variable) (file))
2172 (choice :tag "Identify target headline by"
2173 (cons :tag "Specific tag" (const :value :tag) (string))
2174 (cons :tag "TODO keyword" (const :value :todo) (string))
2175 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2176 (cons :tag "Level number" (const :value :level) (integer))
2177 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2179 (defcustom org-refile-target-verify-function nil
2180 "Function to verify if the headline at point should be a refile target.
2181 The function will be called without arguments, with point at the
2182 beginning of the headline. It should return t and leave point
2183 where it is if the headline is a valid target for refiling.
2185 If the target should not be selected, the function must return nil.
2186 In addition to this, it may move point to a place from where the search
2187 should be continued. For example, the function may decide that the entire
2188 subtree of the current entry should be excluded and move point to the end
2189 of the subtree."
2190 :group 'org-refile
2191 :type '(choice
2192 (const nil)
2193 (function)))
2195 (defcustom org-refile-use-cache nil
2196 "Non-nil means cache refile targets to speed up the process.
2197 The cache for a particular file will be updated automatically when
2198 the buffer has been killed, or when any of the marker used for flagging
2199 refile targets no longer points at a live buffer.
2200 If you have added new entries to a buffer that might themselves be targets,
2201 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2202 find that easier, `C-u C-u C-u C-c C-w'."
2203 :group 'org-refile
2204 :version "24.1"
2205 :type 'boolean)
2207 (defcustom org-refile-use-outline-path nil
2208 "Non-nil means provide refile targets as paths.
2209 So a level 3 headline will be available as level1/level2/level3.
2211 When the value is `file', also include the file name (without directory)
2212 into the path. In this case, you can also stop the completion after
2213 the file name, to get entries inserted as top level in the file.
2215 When `full-file-path', include the full file path."
2216 :group 'org-refile
2217 :type '(choice
2218 (const :tag "Not" nil)
2219 (const :tag "Yes" t)
2220 (const :tag "Start with file name" file)
2221 (const :tag "Start with full file path" full-file-path)))
2223 (defcustom org-outline-path-complete-in-steps t
2224 "Non-nil means complete the outline path in hierarchical steps.
2225 When Org-mode uses the refile interface to select an outline path
2226 \(see variable `org-refile-use-outline-path'), the completion of
2227 the path can be done is a single go, or if can be done in steps down
2228 the headline hierarchy. Going in steps is probably the best if you
2229 do not use a special completion package like `ido' or `icicles'.
2230 However, when using these packages, going in one step can be very
2231 fast, while still showing the whole path to the entry."
2232 :group 'org-refile
2233 :type 'boolean)
2235 (defcustom org-refile-allow-creating-parent-nodes nil
2236 "Non-nil means allow to create new nodes as refile targets.
2237 New nodes are then created by adding \"/new node name\" to the completion
2238 of an existing node. When the value of this variable is `confirm',
2239 new node creation must be confirmed by the user (recommended)
2240 When nil, the completion must match an existing entry.
2242 Note that, if the new heading is not seen by the criteria
2243 listed in `org-refile-targets', multiple instances of the same
2244 heading would be created by trying again to file under the new
2245 heading."
2246 :group 'org-refile
2247 :type '(choice
2248 (const :tag "Never" nil)
2249 (const :tag "Always" t)
2250 (const :tag "Prompt for confirmation" confirm)))
2252 (defcustom org-refile-active-region-within-subtree nil
2253 "Non-nil means also refile active region within a subtree.
2255 By default `org-refile' doesn't allow refiling regions if they
2256 don't contain a set of subtrees, but it might be convenient to
2257 do so sometimes: in that case, the first line of the region is
2258 converted to a headline before refiling."
2259 :group 'org-refile
2260 :version "24.1"
2261 :type 'boolean)
2263 (defgroup org-todo nil
2264 "Options concerning TODO items in Org-mode."
2265 :tag "Org TODO"
2266 :group 'org)
2268 (defgroup org-progress nil
2269 "Options concerning Progress logging in Org-mode."
2270 :tag "Org Progress"
2271 :group 'org-time)
2273 (defvar org-todo-interpretation-widgets
2274 '((:tag "Sequence (cycling hits every state)" sequence)
2275 (:tag "Type (cycling directly to DONE)" type))
2276 "The available interpretation symbols for customizing `org-todo-keywords'.
2277 Interested libraries should add to this list.")
2279 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2280 "List of TODO entry keyword sequences and their interpretation.
2281 \\<org-mode-map>This is a list of sequences.
2283 Each sequence starts with a symbol, either `sequence' or `type',
2284 indicating if the keywords should be interpreted as a sequence of
2285 action steps, or as different types of TODO items. The first
2286 keywords are states requiring action - these states will select a headline
2287 for inclusion into the global TODO list Org-mode produces. If one of
2288 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2289 signify that no further action is necessary. If \"|\" is not found,
2290 the last keyword is treated as the only DONE state of the sequence.
2292 The command \\[org-todo] cycles an entry through these states, and one
2293 additional state where no keyword is present. For details about this
2294 cycling, see the manual.
2296 TODO keywords and interpretation can also be set on a per-file basis with
2297 the special #+SEQ_TODO and #+TYP_TODO lines.
2299 Each keyword can optionally specify a character for fast state selection
2300 \(in combination with the variable `org-use-fast-todo-selection')
2301 and specifiers for state change logging, using the same syntax that
2302 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2303 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2304 indicates to record a time stamp each time this state is selected.
2306 Each keyword may also specify if a timestamp or a note should be
2307 recorded when entering or leaving the state, by adding additional
2308 characters in the parenthesis after the keyword. This looks like this:
2309 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2310 record only the time of the state change. With X and Y being either
2311 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2312 Y when leaving the state if and only if the *target* state does not
2313 define X. You may omit any of the fast-selection key or X or /Y,
2314 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2316 For backward compatibility, this variable may also be just a list
2317 of keywords. In this case the interpretation (sequence or type) will be
2318 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2319 :group 'org-todo
2320 :group 'org-keywords
2321 :type '(choice
2322 (repeat :tag "Old syntax, just keywords"
2323 (string :tag "Keyword"))
2324 (repeat :tag "New syntax"
2325 (cons
2326 (choice
2327 :tag "Interpretation"
2328 ;;Quick and dirty way to see
2329 ;;`org-todo-interpretations'. This takes the
2330 ;;place of item arguments
2331 :convert-widget
2332 (lambda (widget)
2333 (widget-put widget
2334 :args (mapcar
2335 #'(lambda (x)
2336 (widget-convert
2337 (cons 'const x)))
2338 org-todo-interpretation-widgets))
2339 widget))
2340 (repeat
2341 (string :tag "Keyword"))))))
2343 (defvar org-todo-keywords-1 nil
2344 "All TODO and DONE keywords active in a buffer.")
2345 (make-variable-buffer-local 'org-todo-keywords-1)
2346 (defvar org-todo-keywords-for-agenda nil)
2347 (defvar org-done-keywords-for-agenda nil)
2348 (defvar org-drawers-for-agenda nil)
2349 (defvar org-todo-keyword-alist-for-agenda nil)
2350 (defvar org-tag-alist-for-agenda nil
2351 "Alist of all tags from all agenda files.")
2352 (defvar org-tag-groups-alist-for-agenda nil
2353 "Alist of all groups tags from all current agenda files.")
2354 (defvar org-tag-groups-alist nil)
2355 (make-variable-buffer-local 'org-tag-groups-alist)
2356 (defvar org-agenda-contributing-files nil)
2357 (defvar org-not-done-keywords nil)
2358 (make-variable-buffer-local 'org-not-done-keywords)
2359 (defvar org-done-keywords nil)
2360 (make-variable-buffer-local 'org-done-keywords)
2361 (defvar org-todo-heads nil)
2362 (make-variable-buffer-local 'org-todo-heads)
2363 (defvar org-todo-sets nil)
2364 (make-variable-buffer-local 'org-todo-sets)
2365 (defvar org-todo-log-states nil)
2366 (make-variable-buffer-local 'org-todo-log-states)
2367 (defvar org-todo-kwd-alist nil)
2368 (make-variable-buffer-local 'org-todo-kwd-alist)
2369 (defvar org-todo-key-alist nil)
2370 (make-variable-buffer-local 'org-todo-key-alist)
2371 (defvar org-todo-key-trigger nil)
2372 (make-variable-buffer-local 'org-todo-key-trigger)
2374 (defcustom org-todo-interpretation 'sequence
2375 "Controls how TODO keywords are interpreted.
2376 This variable is in principle obsolete and is only used for
2377 backward compatibility, if the interpretation of todo keywords is
2378 not given already in `org-todo-keywords'. See that variable for
2379 more information."
2380 :group 'org-todo
2381 :group 'org-keywords
2382 :type '(choice (const sequence)
2383 (const type)))
2385 (defcustom org-use-fast-todo-selection t
2386 "Non-nil means use the fast todo selection scheme with C-c C-t.
2387 This variable describes if and under what circumstances the cycling
2388 mechanism for TODO keywords will be replaced by a single-key, direct
2389 selection scheme.
2391 When nil, fast selection is never used.
2393 When the symbol `prefix', it will be used when `org-todo' is called
2394 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2395 `C-u t' in an agenda buffer.
2397 When t, fast selection is used by default. In this case, the prefix
2398 argument forces cycling instead.
2400 In all cases, the special interface is only used if access keys have
2401 actually been assigned by the user, i.e. if keywords in the configuration
2402 are followed by a letter in parenthesis, like TODO(t)."
2403 :group 'org-todo
2404 :type '(choice
2405 (const :tag "Never" nil)
2406 (const :tag "By default" t)
2407 (const :tag "Only with C-u C-c C-t" prefix)))
2409 (defcustom org-provide-todo-statistics t
2410 "Non-nil means update todo statistics after insert and toggle.
2411 ALL-HEADLINES means update todo statistics by including headlines
2412 with no TODO keyword as well, counting them as not done.
2413 A list of TODO keywords means the same, but skip keywords that are
2414 not in this list.
2416 When this is set, todo statistics is updated in the parent of the
2417 current entry each time a todo state is changed."
2418 :group 'org-todo
2419 :type '(choice
2420 (const :tag "Yes, only for TODO entries" t)
2421 (const :tag "Yes, including all entries" 'all-headlines)
2422 (repeat :tag "Yes, for TODOs in this list"
2423 (string :tag "TODO keyword"))
2424 (other :tag "No TODO statistics" nil)))
2426 (defcustom org-hierarchical-todo-statistics t
2427 "Non-nil means TODO statistics covers just direct children.
2428 When nil, all entries in the subtree are considered.
2429 This has only an effect if `org-provide-todo-statistics' is set.
2430 To set this to nil for only a single subtree, use a COOKIE_DATA
2431 property and include the word \"recursive\" into the value."
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-after-todo-state-change-hook nil
2436 "Hook which is run after the state of a TODO item was changed.
2437 The new state (a string with a TODO keyword, or nil) is available in the
2438 Lisp variable `org-state'."
2439 :group 'org-todo
2440 :type 'hook)
2442 (defvar org-blocker-hook nil
2443 "Hook for functions that are allowed to block a state change.
2445 Functions in this hook should not modify the buffer.
2446 Each function gets as its single argument a property list,
2447 see `org-trigger-hook' for more information about this list.
2449 If any of the functions in this hook returns nil, the state change
2450 is blocked.")
2452 (defvar org-trigger-hook nil
2453 "Hook for functions that are triggered by a state change.
2455 Each function gets as its single argument a property list with at
2456 least the following elements:
2458 (:type type-of-change :position pos-at-entry-start
2459 :from old-state :to new-state)
2461 Depending on the type, more properties may be present.
2463 This mechanism is currently implemented for:
2465 TODO state changes
2466 ------------------
2467 :type todo-state-change
2468 :from previous state (keyword as a string), or nil, or a symbol
2469 'todo' or 'done', to indicate the general type of state.
2470 :to new state, like in :from")
2472 (defcustom org-enforce-todo-dependencies nil
2473 "Non-nil means undone TODO entries will block switching the parent to DONE.
2474 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2475 be blocked if any prior sibling is not yet done.
2476 Finally, if the parent is blocked because of ordered siblings of its own,
2477 the child will also be blocked."
2478 :set (lambda (var val)
2479 (set var val)
2480 (if val
2481 (add-hook 'org-blocker-hook
2482 'org-block-todo-from-children-or-siblings-or-parent)
2483 (remove-hook 'org-blocker-hook
2484 'org-block-todo-from-children-or-siblings-or-parent)))
2485 :group 'org-todo
2486 :type 'boolean)
2488 (defcustom org-enforce-todo-checkbox-dependencies nil
2489 "Non-nil means unchecked boxes will block switching the parent to DONE.
2490 When this is nil, checkboxes have no influence on switching TODO states.
2491 When non-nil, you first need to check off all check boxes before the TODO
2492 entry can be switched to DONE.
2493 This variable needs to be set before org.el is loaded, and you need to
2494 restart Emacs after a change to make the change effective. The only way
2495 to change is while Emacs is running is through the customize interface."
2496 :set (lambda (var val)
2497 (set var val)
2498 (if val
2499 (add-hook 'org-blocker-hook
2500 'org-block-todo-from-checkboxes)
2501 (remove-hook 'org-blocker-hook
2502 'org-block-todo-from-checkboxes)))
2503 :group 'org-todo
2504 :type 'boolean)
2506 (defcustom org-treat-insert-todo-heading-as-state-change nil
2507 "Non-nil means inserting a TODO heading is treated as state change.
2508 So when the command \\[org-insert-todo-heading] is used, state change
2509 logging will apply if appropriate. When nil, the new TODO item will
2510 be inserted directly, and no logging will take place."
2511 :group 'org-todo
2512 :type 'boolean)
2514 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2515 "Non-nil means switching TODO states with S-cursor counts as state change.
2516 This is the default behavior. However, setting this to nil allows a
2517 convenient way to select a TODO state and bypass any logging associated
2518 with that."
2519 :group 'org-todo
2520 :type 'boolean)
2522 (defcustom org-todo-state-tags-triggers nil
2523 "Tag changes that should be triggered by TODO state changes.
2524 This is a list. Each entry is
2526 (state-change (tag . flag) .......)
2528 State-change can be a string with a state, and empty string to indicate the
2529 state that has no TODO keyword, or it can be one of the symbols `todo'
2530 or `done', meaning any not-done or done state, respectively."
2531 :group 'org-todo
2532 :group 'org-tags
2533 :type '(repeat
2534 (cons (choice :tag "When changing to"
2535 (const :tag "Not-done state" todo)
2536 (const :tag "Done state" done)
2537 (string :tag "State"))
2538 (repeat
2539 (cons :tag "Tag action"
2540 (string :tag "Tag")
2541 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2543 (defcustom org-log-done nil
2544 "Information to record when a task moves to the DONE state.
2546 Possible values are:
2548 nil Don't add anything, just change the keyword
2549 time Add a time stamp to the task
2550 note Prompt for a note and add it with template `org-log-note-headings'
2552 This option can also be set with on a per-file-basis with
2554 #+STARTUP: nologdone
2555 #+STARTUP: logdone
2556 #+STARTUP: lognotedone
2558 You can have local logging settings for a subtree by setting the LOGGING
2559 property to one or more of these keywords."
2560 :group 'org-todo
2561 :group 'org-progress
2562 :type '(choice
2563 (const :tag "No logging" nil)
2564 (const :tag "Record CLOSED timestamp" time)
2565 (const :tag "Record CLOSED timestamp with note." note)))
2567 ;; Normalize old uses of org-log-done.
2568 (cond
2569 ((eq org-log-done t) (setq org-log-done 'time))
2570 ((and (listp org-log-done) (memq 'done org-log-done))
2571 (setq org-log-done 'note)))
2573 (defcustom org-log-reschedule nil
2574 "Information to record when the scheduling date of a tasks is modified.
2576 Possible values are:
2578 nil Don't add anything, just change the date
2579 time Add a time stamp to the task
2580 note Prompt for a note and add it with template `org-log-note-headings'
2582 This option can also be set with on a per-file-basis with
2584 #+STARTUP: nologreschedule
2585 #+STARTUP: logreschedule
2586 #+STARTUP: lognotereschedule"
2587 :group 'org-todo
2588 :group 'org-progress
2589 :type '(choice
2590 (const :tag "No logging" nil)
2591 (const :tag "Record timestamp" time)
2592 (const :tag "Record timestamp with note." note)))
2594 (defcustom org-log-redeadline nil
2595 "Information to record when the deadline date of a tasks is modified.
2597 Possible values are:
2599 nil Don't add anything, just change the date
2600 time Add a time stamp to the task
2601 note Prompt for a note and add it with template `org-log-note-headings'
2603 This option can also be set with on a per-file-basis with
2605 #+STARTUP: nologredeadline
2606 #+STARTUP: logredeadline
2607 #+STARTUP: lognoteredeadline
2609 You can have local logging settings for a subtree by setting the LOGGING
2610 property to one or more of these keywords."
2611 :group 'org-todo
2612 :group 'org-progress
2613 :type '(choice
2614 (const :tag "No logging" nil)
2615 (const :tag "Record timestamp" time)
2616 (const :tag "Record timestamp with note." note)))
2618 (defcustom org-log-note-clock-out nil
2619 "Non-nil means record a note when clocking out of an item.
2620 This can also be configured on a per-file basis by adding one of
2621 the following lines anywhere in the buffer:
2623 #+STARTUP: lognoteclock-out
2624 #+STARTUP: nolognoteclock-out"
2625 :group 'org-todo
2626 :group 'org-progress
2627 :type 'boolean)
2629 (defcustom org-log-done-with-time t
2630 "Non-nil means the CLOSED time stamp will contain date and time.
2631 When nil, only the date will be recorded."
2632 :group 'org-progress
2633 :type 'boolean)
2635 (defcustom org-log-note-headings
2636 '((done . "CLOSING NOTE %t")
2637 (state . "State %-12s from %-12S %t")
2638 (note . "Note taken on %t")
2639 (reschedule . "Rescheduled from %S on %t")
2640 (delschedule . "Not scheduled, was %S on %t")
2641 (redeadline . "New deadline from %S on %t")
2642 (deldeadline . "Removed deadline, was %S on %t")
2643 (refile . "Refiled on %t")
2644 (clock-out . ""))
2645 "Headings for notes added to entries.
2646 The value is an alist, with the car being a symbol indicating the note
2647 context, and the cdr is the heading to be used. The heading may also be the
2648 empty string.
2649 %t in the heading will be replaced by a time stamp.
2650 %T will be an active time stamp instead the default inactive one
2651 %d will be replaced by a short-format time stamp.
2652 %D will be replaced by an active short-format time stamp.
2653 %s will be replaced by the new TODO state, in double quotes.
2654 %S will be replaced by the old TODO state, in double quotes.
2655 %u will be replaced by the user name.
2656 %U will be replaced by the full user name.
2658 In fact, it is not a good idea to change the `state' entry, because
2659 agenda log mode depends on the format of these entries."
2660 :group 'org-todo
2661 :group 'org-progress
2662 :type '(list :greedy t
2663 (cons (const :tag "Heading when closing an item" done) string)
2664 (cons (const :tag
2665 "Heading when changing todo state (todo sequence only)"
2666 state) string)
2667 (cons (const :tag "Heading when just taking a note" note) string)
2668 (cons (const :tag "Heading when clocking out" clock-out) string)
2669 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2670 (cons (const :tag "Heading when rescheduling" reschedule) string)
2671 (cons (const :tag "Heading when changing deadline" redeadline) string)
2672 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2673 (cons (const :tag "Heading when refiling" refile) string)))
2675 (unless (assq 'note org-log-note-headings)
2676 (push '(note . "%t") org-log-note-headings))
2678 (defcustom org-log-into-drawer nil
2679 "Non-nil means insert state change notes and time stamps into a drawer.
2680 When nil, state changes notes will be inserted after the headline and
2681 any scheduling and clock lines, but not inside a drawer.
2683 The value of this variable should be the name of the drawer to use.
2684 LOGBOOK is proposed as the default drawer for this purpose, you can
2685 also set this to a string to define the drawer of your choice.
2687 A value of t is also allowed, representing \"LOGBOOK\".
2689 A value of t or nil can also be set with on a per-file-basis with
2691 #+STARTUP: logdrawer
2692 #+STARTUP: nologdrawer
2694 If this variable is set, `org-log-state-notes-insert-after-drawers'
2695 will be ignored.
2697 You can set the property LOG_INTO_DRAWER to overrule this setting for
2698 a subtree."
2699 :group 'org-todo
2700 :group 'org-progress
2701 :type '(choice
2702 (const :tag "Not into a drawer" nil)
2703 (const :tag "LOGBOOK" t)
2704 (string :tag "Other")))
2706 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2708 (defun org-log-into-drawer ()
2709 "Return the value of `org-log-into-drawer', but let properties overrule.
2710 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2711 used instead of the default value."
2712 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2713 (cond
2714 ((not p) org-log-into-drawer)
2715 ((equal p "nil") nil)
2716 ((equal p "t") "LOGBOOK")
2717 (t p))))
2719 (defcustom org-log-state-notes-insert-after-drawers nil
2720 "Non-nil means insert state change notes after any drawers in entry.
2721 Only the drawers that *immediately* follow the headline and the
2722 deadline/scheduled line are skipped.
2723 When nil, insert notes right after the heading and perhaps the line
2724 with deadline/scheduling if present.
2726 This variable will have no effect if `org-log-into-drawer' is
2727 set."
2728 :group 'org-todo
2729 :group 'org-progress
2730 :type 'boolean)
2732 (defcustom org-log-states-order-reversed t
2733 "Non-nil means the latest state note will be directly after heading.
2734 When nil, the state change notes will be ordered according to time.
2736 This option can also be set with on a per-file-basis with
2738 #+STARTUP: logstatesreversed
2739 #+STARTUP: nologstatesreversed"
2740 :group 'org-todo
2741 :group 'org-progress
2742 :type 'boolean)
2744 (defcustom org-todo-repeat-to-state nil
2745 "The TODO state to which a repeater should return the repeating task.
2746 By default this is the first task in a TODO sequence, or the previous state
2747 in a TODO_TYP set. But you can specify another task here.
2748 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2749 :group 'org-todo
2750 :version "24.1"
2751 :type '(choice (const :tag "Head of sequence" nil)
2752 (string :tag "Specific state")))
2754 (defcustom org-log-repeat 'time
2755 "Non-nil means record moving through the DONE state when triggering repeat.
2756 An auto-repeating task is immediately switched back to TODO when
2757 marked DONE. If you are not logging state changes (by adding \"@\"
2758 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2759 record a closing note, there will be no record of the task moving
2760 through DONE. This variable forces taking a note anyway.
2762 nil Don't force a record
2763 time Record a time stamp
2764 note Prompt for a note and add it with template `org-log-note-headings'
2766 This option can also be set with on a per-file-basis with
2768 #+STARTUP: nologrepeat
2769 #+STARTUP: logrepeat
2770 #+STARTUP: lognoterepeat
2772 You can have local logging settings for a subtree by setting the LOGGING
2773 property to one or more of these keywords."
2774 :group 'org-todo
2775 :group 'org-progress
2776 :type '(choice
2777 (const :tag "Don't force a record" nil)
2778 (const :tag "Force recording the DONE state" time)
2779 (const :tag "Force recording a note with the DONE state" note)))
2782 (defgroup org-priorities nil
2783 "Priorities in Org-mode."
2784 :tag "Org Priorities"
2785 :group 'org-todo)
2787 (defcustom org-enable-priority-commands t
2788 "Non-nil means priority commands are active.
2789 When nil, these commands will be disabled, so that you never accidentally
2790 set a priority."
2791 :group 'org-priorities
2792 :type 'boolean)
2794 (defcustom org-highest-priority ?A
2795 "The highest priority of TODO items. A character like ?A, ?B etc.
2796 Must have a smaller ASCII number than `org-lowest-priority'."
2797 :group 'org-priorities
2798 :type 'character)
2800 (defcustom org-lowest-priority ?C
2801 "The lowest priority of TODO items. A character like ?A, ?B etc.
2802 Must have a larger ASCII number than `org-highest-priority'."
2803 :group 'org-priorities
2804 :type 'character)
2806 (defcustom org-default-priority ?B
2807 "The default priority of TODO items.
2808 This is the priority an item gets if no explicit priority is given.
2809 When starting to cycle on an empty priority the first step in the cycle
2810 depends on `org-priority-start-cycle-with-default'. The resulting first
2811 step priority must not exceed the range from `org-highest-priority' to
2812 `org-lowest-priority' which means that `org-default-priority' has to be
2813 in this range exclusive or inclusive the range boundaries. Else the
2814 first step refuses to set the default and the second will fall back
2815 to (depending on the command used) the highest or lowest priority."
2816 :group 'org-priorities
2817 :type 'character)
2819 (defcustom org-priority-start-cycle-with-default t
2820 "Non-nil means start with default priority when starting to cycle.
2821 When this is nil, the first step in the cycle will be (depending on the
2822 command used) one higher or lower than the default priority.
2823 See also `org-default-priority'."
2824 :group 'org-priorities
2825 :type 'boolean)
2827 (defcustom org-get-priority-function nil
2828 "Function to extract the priority from a string.
2829 The string is normally the headline. If this is nil Org computes the
2830 priority from the priority cookie like [#A] in the headline. It returns
2831 an integer, increasing by 1000 for each priority level.
2832 The user can set a different function here, which should take a string
2833 as an argument and return the numeric priority."
2834 :group 'org-priorities
2835 :version "24.1"
2836 :type '(choice
2837 (const nil)
2838 (function)))
2840 (defgroup org-time nil
2841 "Options concerning time stamps and deadlines in Org-mode."
2842 :tag "Org Time"
2843 :group 'org)
2845 (defcustom org-insert-labeled-timestamps-at-point nil
2846 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2847 When nil, these labeled time stamps are forces into the second line of an
2848 entry, just after the headline. When scheduling from the global TODO list,
2849 the time stamp will always be forced into the second line."
2850 :group 'org-time
2851 :type 'boolean)
2853 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2854 "Formats for `format-time-string' which are used for time stamps.
2855 It is not recommended to change this constant.")
2857 (defcustom org-time-stamp-rounding-minutes '(0 5)
2858 "Number of minutes to round time stamps to.
2859 These are two values, the first applies when first creating a time stamp.
2860 The second applies when changing it with the commands `S-up' and `S-down'.
2861 When changing the time stamp, this means that it will change in steps
2862 of N minutes, as given by the second value.
2864 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2865 numbers should be factors of 60, so for example 5, 10, 15.
2867 When this is larger than 1, you can still force an exact time stamp by using
2868 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2869 and by using a prefix arg to `S-up/down' to specify the exact number
2870 of minutes to shift."
2871 :group 'org-time
2872 :get #'(lambda (var) ; Make sure both elements are there
2873 (if (integerp (default-value var))
2874 (list (default-value var) 5)
2875 (default-value var)))
2876 :type '(list
2877 (integer :tag "when inserting times")
2878 (integer :tag "when modifying times")))
2880 ;; Normalize old customizations of this variable.
2881 (when (integerp org-time-stamp-rounding-minutes)
2882 (setq org-time-stamp-rounding-minutes
2883 (list org-time-stamp-rounding-minutes
2884 org-time-stamp-rounding-minutes)))
2886 (defcustom org-display-custom-times nil
2887 "Non-nil means overlay custom formats over all time stamps.
2888 The formats are defined through the variable `org-time-stamp-custom-formats'.
2889 To turn this on on a per-file basis, insert anywhere in the file:
2890 #+STARTUP: customtime"
2891 :group 'org-time
2892 :set 'set-default
2893 :type 'sexp)
2894 (make-variable-buffer-local 'org-display-custom-times)
2896 (defcustom org-time-stamp-custom-formats
2897 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2898 "Custom formats for time stamps. See `format-time-string' for the syntax.
2899 These are overlaid over the default ISO format if the variable
2900 `org-display-custom-times' is set. Time like %H:%M should be at the
2901 end of the second format. The custom formats are also honored by export
2902 commands, if custom time display is turned on at the time of export."
2903 :group 'org-time
2904 :type 'sexp)
2906 (defun org-time-stamp-format (&optional long inactive)
2907 "Get the right format for a time string."
2908 (let ((f (if long (cdr org-time-stamp-formats)
2909 (car org-time-stamp-formats))))
2910 (if inactive
2911 (concat "[" (substring f 1 -1) "]")
2912 f)))
2914 (defcustom org-time-clocksum-format
2915 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2916 "The format string used when creating CLOCKSUM lines.
2917 This is also used when Org mode generates a time duration.
2919 The value can be a single format string containing two
2920 %-sequences, which will be filled with the number of hours and
2921 minutes in that order.
2923 Alternatively, the value can be a plist associating any of the
2924 keys :years, :months, :weeks, :days, :hours or :minutes with
2925 format strings. The time duration is formatted using only the
2926 time components that are needed and concatenating the results.
2927 If a time unit in absent, it falls back to the next smallest
2928 unit.
2930 The keys :require-years, :require-months, :require-days,
2931 :require-weeks, :require-hours, :require-minutes are also
2932 meaningful. A non-nil value for these keys indicates that the
2933 corresponding time component should always be included, even if
2934 its value is 0.
2937 For example,
2939 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2940 :require-minutes t)
2942 means durations longer than a day will be expressed in days,
2943 hours and minutes, and durations less than a day will always be
2944 expressed in hours and minutes (even for durations less than an
2945 hour).
2947 The value
2949 \(:days \"%dd\" :minutes \"%dm\")
2951 means durations longer than a day will be expressed in days and
2952 minutes, and durations less than a day will be expressed entirely
2953 in minutes (even for durations longer than an hour)."
2954 :group 'org-time
2955 :group 'org-clock
2956 :version "24.4"
2957 :package-version '(Org . "8.0")
2958 :type '(choice (string :tag "Format string")
2959 (set :tag "Plist"
2960 (group :inline t (const :tag "Years" :years)
2961 (string :tag "Format string"))
2962 (group :inline t
2963 (const :tag "Always show years" :require-years)
2964 (const t))
2965 (group :inline t (const :tag "Months" :months)
2966 (string :tag "Format string"))
2967 (group :inline t
2968 (const :tag "Always show months" :require-months)
2969 (const t))
2970 (group :inline t (const :tag "Weeks" :weeks)
2971 (string :tag "Format string"))
2972 (group :inline t
2973 (const :tag "Always show weeks" :require-weeks)
2974 (const t))
2975 (group :inline t (const :tag "Days" :days)
2976 (string :tag "Format string"))
2977 (group :inline t
2978 (const :tag "Always show days" :require-days)
2979 (const t))
2980 (group :inline t (const :tag "Hours" :hours)
2981 (string :tag "Format string"))
2982 (group :inline t
2983 (const :tag "Always show hours" :require-hours)
2984 (const t))
2985 (group :inline t (const :tag "Minutes" :minutes)
2986 (string :tag "Format string"))
2987 (group :inline t
2988 (const :tag "Always show minutes" :require-minutes)
2989 (const t)))))
2991 (defcustom org-time-clocksum-use-fractional nil
2992 "When non-nil, \\[org-clock-display] uses fractional times.
2993 See `org-time-clocksum-format' for more on time clock formats."
2994 :group 'org-time
2995 :group 'org-clock
2996 :version "24.3"
2997 :type 'boolean)
2999 (defcustom org-time-clocksum-use-effort-durations nil
3000 "When non-nil, \\[org-clock-display] uses effort durations.
3001 E.g. by default, one day is considered to be a 8 hours effort,
3002 so a task that has been clocked for 16 hours will be displayed
3003 as during 2 days in the clock display or in the clocktable.
3005 See `org-effort-durations' on how to set effort durations
3006 and `org-time-clocksum-format' for more on time clock formats."
3007 :group 'org-time
3008 :group 'org-clock
3009 :version "24.4"
3010 :package-version '(Org . "8.0")
3011 :type 'boolean)
3013 (defcustom org-time-clocksum-fractional-format "%.2f"
3014 "The format string used when creating CLOCKSUM lines,
3015 or when Org mode generates a time duration, if
3016 `org-time-clocksum-use-fractional' is enabled.
3018 The value can be a single format string containing one
3019 %-sequence, which will be filled with the number of hours as
3020 a float.
3022 Alternatively, the value can be a plist associating any of the
3023 keys :years, :months, :weeks, :days, :hours or :minutes with
3024 a format string. The time duration is formatted using the
3025 largest time unit which gives a non-zero integer part. If all
3026 specified formats have zero integer part, the smallest time unit
3027 is used."
3028 :group 'org-time
3029 :type '(choice (string :tag "Format string")
3030 (set (group :inline t (const :tag "Years" :years)
3031 (string :tag "Format string"))
3032 (group :inline t (const :tag "Months" :months)
3033 (string :tag "Format string"))
3034 (group :inline t (const :tag "Weeks" :weeks)
3035 (string :tag "Format string"))
3036 (group :inline t (const :tag "Days" :days)
3037 (string :tag "Format string"))
3038 (group :inline t (const :tag "Hours" :hours)
3039 (string :tag "Format string"))
3040 (group :inline t (const :tag "Minutes" :minutes)
3041 (string :tag "Format string")))))
3043 (defcustom org-deadline-warning-days 14
3044 "Number of days before expiration during which a deadline becomes active.
3045 This variable governs the display in sparse trees and in the agenda.
3046 When 0 or negative, it means use this number (the absolute value of it)
3047 even if a deadline has a different individual lead time specified.
3049 Custom commands can set this variable in the options section."
3050 :group 'org-time
3051 :group 'org-agenda-daily/weekly
3052 :type 'integer)
3054 (defcustom org-scheduled-delay-days 0
3055 "Number of days before a scheduled item becomes active.
3056 This variable governs the display in sparse trees and in the agenda.
3057 The default value (i.e. 0) means: don't delay scheduled item.
3058 When negative, it means use this number (the absolute value of it)
3059 even if a scheduled item has a different individual delay time
3060 specified.
3062 Custom commands can set this variable in the options section."
3063 :group 'org-time
3064 :group 'org-agenda-daily/weekly
3065 :version "24.4"
3066 :package-version '(Org . "8.0")
3067 :type 'integer)
3069 (defcustom org-read-date-prefer-future t
3070 "Non-nil means assume future for incomplete date input from user.
3071 This affects the following situations:
3072 1. The user gives a month but not a year.
3073 For example, if it is April and you enter \"feb 2\", this will be read
3074 as Feb 2, *next* year. \"May 5\", however, will be this year.
3075 2. The user gives a day, but no month.
3076 For example, if today is the 15th, and you enter \"3\", Org-mode will
3077 read this as the third of *next* month. However, if you enter \"17\",
3078 it will be considered as *this* month.
3080 If you set this variable to the symbol `time', then also the following
3081 will work:
3083 3. If the user gives a time.
3084 If the time is before now, it will be interpreted as tomorrow.
3086 Currently none of this works for ISO week specifications.
3088 When this option is nil, the current day, month and year will always be
3089 used as defaults.
3091 See also `org-agenda-jump-prefer-future'."
3092 :group 'org-time
3093 :type '(choice
3094 (const :tag "Never" nil)
3095 (const :tag "Check month and day" t)
3096 (const :tag "Check month, day, and time" time)))
3098 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3099 "Should the agenda jump command prefer the future for incomplete dates?
3100 The default is to do the same as configured in `org-read-date-prefer-future'.
3101 But you can also set a deviating value here.
3102 This may t or nil, or the symbol `org-read-date-prefer-future'."
3103 :group 'org-agenda
3104 :group 'org-time
3105 :version "24.1"
3106 :type '(choice
3107 (const :tag "Use org-read-date-prefer-future"
3108 org-read-date-prefer-future)
3109 (const :tag "Never" nil)
3110 (const :tag "Always" t)))
3112 (defcustom org-read-date-force-compatible-dates t
3113 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3115 Depending on the system Emacs is running on, certain dates cannot
3116 be represented with the type used internally to represent time.
3117 Dates between 1970-1-1 and 2038-1-1 can always be represented
3118 correctly. Some systems allow for earlier dates, some for later,
3119 some for both. One way to find out it to insert any date into an
3120 Org buffer, putting the cursor on the year and hitting S-up and
3121 S-down to test the range.
3123 When this variable is set to t, the date/time prompt will not let
3124 you specify dates outside the 1970-2037 range, so it is certain that
3125 these dates will work in whatever version of Emacs you are
3126 running, and also that you can move a file from one Emacs implementation
3127 to another. WHenever Org is forcing the year for you, it will display
3128 a message and beep.
3130 When this variable is nil, Org will check if the date is
3131 representable in the specific Emacs implementation you are using.
3132 If not, it will force a year, usually the current year, and beep
3133 to remind you. Currently this setting is not recommended because
3134 the likelihood that you will open your Org files in an Emacs that
3135 has limited date range is not negligible.
3137 A workaround for this problem is to use diary sexp dates for time
3138 stamps outside of this range."
3139 :group 'org-time
3140 :version "24.1"
3141 :type 'boolean)
3143 (defcustom org-read-date-display-live t
3144 "Non-nil means display current interpretation of date prompt live.
3145 This display will be in an overlay, in the minibuffer."
3146 :group 'org-time
3147 :type 'boolean)
3149 (defcustom org-read-date-popup-calendar t
3150 "Non-nil means pop up a calendar when prompting for a date.
3151 In the calendar, the date can be selected with mouse-1. However, the
3152 minibuffer will also be active, and you can simply enter the date as well.
3153 When nil, only the minibuffer will be available."
3154 :group 'org-time
3155 :type 'boolean)
3156 (org-defvaralias 'org-popup-calendar-for-date-prompt
3157 'org-read-date-popup-calendar)
3159 (make-obsolete-variable
3160 'org-read-date-minibuffer-setup-hook
3161 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3162 (defcustom org-read-date-minibuffer-setup-hook nil
3163 "Hook to be used to set up keys for the date/time interface.
3164 Add key definitions to `minibuffer-local-map', which will be a
3165 temporary copy.
3167 WARNING: This option is obsolete, you should use
3168 `org-read-date-minibuffer-local-map' to set up keys."
3169 :group 'org-time
3170 :type 'hook)
3172 (defcustom org-extend-today-until 0
3173 "The hour when your day really ends. Must be an integer.
3174 This has influence for the following applications:
3175 - When switching the agenda to \"today\". It it is still earlier than
3176 the time given here, the day recognized as TODAY is actually yesterday.
3177 - When a date is read from the user and it is still before the time given
3178 here, the current date and time will be assumed to be yesterday, 23:59.
3179 Also, timestamps inserted in capture templates follow this rule.
3181 IMPORTANT: This is a feature whose implementation is and likely will
3182 remain incomplete. Really, it is only here because past midnight seems to
3183 be the favorite working time of John Wiegley :-)"
3184 :group 'org-time
3185 :type 'integer)
3187 (defcustom org-use-effective-time nil
3188 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3189 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3190 \"effective time\" of any timestamps between midnight and 8am will be
3191 23:59 of the previous day."
3192 :group 'org-time
3193 :version "24.1"
3194 :type 'boolean)
3196 (defcustom org-use-last-clock-out-time-as-effective-time nil
3197 "When non-nil, use the last clock out time for `org-todo'.
3198 Note that this option has precedence over the combined use of
3199 `org-use-effective-time' and `org-extend-today-until'."
3200 :group 'org-time
3201 :version "24.4"
3202 :package-version '(Org . "8.0")
3203 :type 'boolean)
3205 (defcustom org-edit-timestamp-down-means-later nil
3206 "Non-nil means S-down will increase the time in a time stamp.
3207 When nil, S-up will increase."
3208 :group 'org-time
3209 :type 'boolean)
3211 (defcustom org-calendar-follow-timestamp-change t
3212 "Non-nil means make the calendar window follow timestamp changes.
3213 When a timestamp is modified and the calendar window is visible, it will be
3214 moved to the new date."
3215 :group 'org-time
3216 :type 'boolean)
3218 (defgroup org-tags nil
3219 "Options concerning tags in Org-mode."
3220 :tag "Org Tags"
3221 :group 'org)
3223 (defcustom org-tag-alist nil
3224 "List of tags allowed in Org-mode files.
3225 When this list is nil, Org-mode will base TAG input on what is already in the
3226 buffer.
3227 The value of this variable is an alist, the car of each entry must be a
3228 keyword as a string, the cdr may be a character that is used to select
3229 that tag through the fast-tag-selection interface.
3230 See the manual for details."
3231 :group 'org-tags
3232 :type '(repeat
3233 (choice
3234 (cons (string :tag "Tag name")
3235 (character :tag "Access char"))
3236 (list :tag "Start radio group"
3237 (const :startgroup)
3238 (option (string :tag "Group description")))
3239 (list :tag "Group tags delimiter"
3240 (const :grouptags))
3241 (list :tag "End radio group"
3242 (const :endgroup)
3243 (option (string :tag "Group description")))
3244 (const :tag "New line" (:newline)))))
3246 (defcustom org-tag-persistent-alist nil
3247 "List of tags that will always appear in all Org-mode files.
3248 This is in addition to any in buffer settings or customizations
3249 of `org-tag-alist'.
3250 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3251 The value of this variable is an alist, the car of each entry must be a
3252 keyword as a string, the cdr may be a character that is used to select
3253 that tag through the fast-tag-selection interface.
3254 See the manual for details.
3255 To disable these tags on a per-file basis, insert anywhere in the file:
3256 #+STARTUP: noptag"
3257 :group 'org-tags
3258 :type '(repeat
3259 (choice
3260 (cons (string :tag "Tag name")
3261 (character :tag "Access char"))
3262 (const :tag "Start radio group" (:startgroup))
3263 (const :tag "Group tags delimiter" (:grouptags))
3264 (const :tag "End radio group" (:endgroup))
3265 (const :tag "New line" (:newline)))))
3267 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3268 "If non-nil, always offer completion for all tags of all agenda files.
3269 Instead of customizing this variable directly, you might want to
3270 set it locally for capture buffers, because there no list of
3271 tags in that file can be created dynamically (there are none).
3273 (add-hook 'org-capture-mode-hook
3274 (lambda ()
3275 (set (make-local-variable
3276 'org-complete-tags-always-offer-all-agenda-tags)
3277 t)))"
3278 :group 'org-tags
3279 :version "24.1"
3280 :type 'boolean)
3282 (defvar org-file-tags nil
3283 "List of tags that can be inherited by all entries in the file.
3284 The tags will be inherited if the variable `org-use-tag-inheritance'
3285 says they should be.
3286 This variable is populated from #+FILETAGS lines.")
3288 (defcustom org-use-fast-tag-selection 'auto
3289 "Non-nil means use fast tag selection scheme.
3290 This is a special interface to select and deselect tags with single keys.
3291 When nil, fast selection is never used.
3292 When the symbol `auto', fast selection is used if and only if selection
3293 characters for tags have been configured, either through the variable
3294 `org-tag-alist' or through a #+TAGS line in the buffer.
3295 When t, fast selection is always used and selection keys are assigned
3296 automatically if necessary."
3297 :group 'org-tags
3298 :type '(choice
3299 (const :tag "Always" t)
3300 (const :tag "Never" nil)
3301 (const :tag "When selection characters are configured" auto)))
3303 (defcustom org-fast-tag-selection-single-key nil
3304 "Non-nil means fast tag selection exits after first change.
3305 When nil, you have to press RET to exit it.
3306 During fast tag selection, you can toggle this flag with `C-c'.
3307 This variable can also have the value `expert'. In this case, the window
3308 displaying the tags menu is not even shown, until you press C-c again."
3309 :group 'org-tags
3310 :type '(choice
3311 (const :tag "No" nil)
3312 (const :tag "Yes" t)
3313 (const :tag "Expert" expert)))
3315 (defvar org-fast-tag-selection-include-todo nil
3316 "Non-nil means fast tags selection interface will also offer TODO states.
3317 This is an undocumented feature, you should not rely on it.")
3319 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3320 "The column to which tags should be indented in a headline.
3321 If this number is positive, it specifies the column. If it is negative,
3322 it means that the tags should be flushright to that column. For example,
3323 -80 works well for a normal 80 character screen.
3324 When 0, place tags directly after headline text, with only one space in
3325 between."
3326 :group 'org-tags
3327 :type 'integer)
3329 (defcustom org-auto-align-tags t
3330 "Non-nil keeps tags aligned when modifying headlines.
3331 Some operations (i.e. demoting) change the length of a headline and
3332 therefore shift the tags around. With this option turned on, after
3333 each such operation the tags are again aligned to `org-tags-column'."
3334 :group 'org-tags
3335 :type 'boolean)
3337 (defcustom org-use-tag-inheritance t
3338 "Non-nil means tags in levels apply also for sublevels.
3339 When nil, only the tags directly given in a specific line apply there.
3340 This may also be a list of tags that should be inherited, or a regexp that
3341 matches tags that should be inherited. Additional control is possible
3342 with the variable `org-tags-exclude-from-inheritance' which gives an
3343 explicit list of tags to be excluded from inheritance, even if the value of
3344 `org-use-tag-inheritance' would select it for inheritance.
3346 If this option is t, a match early-on in a tree can lead to a large
3347 number of matches in the subtree when constructing the agenda or creating
3348 a sparse tree. If you only want to see the first match in a tree during
3349 a search, check out the variable `org-tags-match-list-sublevels'."
3350 :group 'org-tags
3351 :type '(choice
3352 (const :tag "Not" nil)
3353 (const :tag "Always" t)
3354 (repeat :tag "Specific tags" (string :tag "Tag"))
3355 (regexp :tag "Tags matched by regexp")))
3357 (defcustom org-tags-exclude-from-inheritance nil
3358 "List of tags that should never be inherited.
3359 This is a way to exclude a few tags from inheritance. For way to do
3360 the opposite, to actively allow inheritance for selected tags,
3361 see the variable `org-use-tag-inheritance'."
3362 :group 'org-tags
3363 :type '(repeat (string :tag "Tag")))
3365 (defun org-tag-inherit-p (tag)
3366 "Check if TAG is one that should be inherited."
3367 (cond
3368 ((member tag org-tags-exclude-from-inheritance) nil)
3369 ((eq org-use-tag-inheritance t) t)
3370 ((not org-use-tag-inheritance) nil)
3371 ((stringp org-use-tag-inheritance)
3372 (string-match org-use-tag-inheritance tag))
3373 ((listp org-use-tag-inheritance)
3374 (member tag org-use-tag-inheritance))
3375 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3377 (defcustom org-tags-match-list-sublevels t
3378 "Non-nil means list also sublevels of headlines matching a search.
3379 This variable applies to tags/property searches, and also to stuck
3380 projects because this search is based on a tags match as well.
3382 When set to the symbol `indented', sublevels are indented with
3383 leading dots.
3385 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3386 the sublevels of a headline matching a tag search often also match
3387 the same search. Listing all of them can create very long lists.
3388 Setting this variable to nil causes subtrees of a match to be skipped.
3390 This variable is semi-obsolete and probably should always be true. It
3391 is better to limit inheritance to certain tags using the variables
3392 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3393 :group 'org-tags
3394 :type '(choice
3395 (const :tag "No, don't list them" nil)
3396 (const :tag "Yes, do list them" t)
3397 (const :tag "List them, indented with leading dots" indented)))
3399 (defcustom org-tags-sort-function nil
3400 "When set, tags are sorted using this function as a comparator."
3401 :group 'org-tags
3402 :type '(choice
3403 (const :tag "No sorting" nil)
3404 (const :tag "Alphabetical" string<)
3405 (const :tag "Reverse alphabetical" string>)
3406 (function :tag "Custom function" nil)))
3408 (defvar org-tags-history nil
3409 "History of minibuffer reads for tags.")
3410 (defvar org-last-tags-completion-table nil
3411 "The last used completion table for tags.")
3412 (defvar org-after-tags-change-hook nil
3413 "Hook that is run after the tags in a line have changed.")
3415 (defgroup org-properties nil
3416 "Options concerning properties in Org-mode."
3417 :tag "Org Properties"
3418 :group 'org)
3420 (defcustom org-property-format "%-10s %s"
3421 "How property key/value pairs should be formatted by `indent-line'.
3422 When `indent-line' hits a property definition, it will format the line
3423 according to this format, mainly to make sure that the values are
3424 lined-up with respect to each other."
3425 :group 'org-properties
3426 :type 'string)
3428 (defcustom org-properties-postprocess-alist nil
3429 "Alist of properties and functions to adjust inserted values.
3430 Elements of this alist must be of the form
3432 ([string] [function])
3434 where [string] must be a property name and [function] must be a
3435 lambda expression: this lambda expression must take one argument,
3436 the value to adjust, and return the new value as a string.
3438 For example, this element will allow the property \"Remaining\"
3439 to be updated wrt the relation between the \"Effort\" property
3440 and the clock summary:
3442 ((\"Remaining\" (lambda(value)
3443 (let ((clocksum (org-clock-sum-current-item))
3444 (effort (org-duration-string-to-minutes
3445 (org-entry-get (point) \"Effort\"))))
3446 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3447 :group 'org-properties
3448 :version "24.1"
3449 :type '(alist :key-type (string :tag "Property")
3450 :value-type (function :tag "Function")))
3452 (defcustom org-use-property-inheritance nil
3453 "Non-nil means properties apply also for sublevels.
3455 This setting is chiefly used during property searches. Turning it on can
3456 cause significant overhead when doing a search, which is why it is not
3457 on by default.
3459 When nil, only the properties directly given in the current entry count.
3460 When t, every property is inherited. The value may also be a list of
3461 properties that should have inheritance, or a regular expression matching
3462 properties that should be inherited.
3464 However, note that some special properties use inheritance under special
3465 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3466 and the properties ending in \"_ALL\" when they are used as descriptor
3467 for valid values of a property.
3469 Note for programmers:
3470 When querying an entry with `org-entry-get', you can control if inheritance
3471 should be used. By default, `org-entry-get' looks only at the local
3472 properties. You can request inheritance by setting the inherit argument
3473 to t (to force inheritance) or to `selective' (to respect the setting
3474 in this variable)."
3475 :group 'org-properties
3476 :type '(choice
3477 (const :tag "Not" nil)
3478 (const :tag "Always" t)
3479 (repeat :tag "Specific properties" (string :tag "Property"))
3480 (regexp :tag "Properties matched by regexp")))
3482 (defun org-property-inherit-p (property)
3483 "Check if PROPERTY is one that should be inherited."
3484 (cond
3485 ((eq org-use-property-inheritance t) t)
3486 ((not org-use-property-inheritance) nil)
3487 ((stringp org-use-property-inheritance)
3488 (string-match org-use-property-inheritance property))
3489 ((listp org-use-property-inheritance)
3490 (member property org-use-property-inheritance))
3491 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3493 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3494 "The default column format, if no other format has been defined.
3495 This variable can be set on the per-file basis by inserting a line
3497 #+COLUMNS: %25ITEM ....."
3498 :group 'org-properties
3499 :type 'string)
3501 (defcustom org-columns-ellipses ".."
3502 "The ellipses to be used when a field in column view is truncated.
3503 When this is the empty string, as many characters as possible are shown,
3504 but then there will be no visual indication that the field has been truncated.
3505 When this is a string of length N, the last N characters of a truncated
3506 field are replaced by this string. If the column is narrower than the
3507 ellipses string, only part of the ellipses string will be shown."
3508 :group 'org-properties
3509 :type 'string)
3511 (defcustom org-columns-modify-value-for-display-function nil
3512 "Function that modifies values for display in column view.
3513 For example, it can be used to cut out a certain part from a time stamp.
3514 The function must take 2 arguments:
3516 column-title The title of the column (*not* the property name)
3517 value The value that should be modified.
3519 The function should return the value that should be displayed,
3520 or nil if the normal value should be used."
3521 :group 'org-properties
3522 :type '(choice (const nil) (function)))
3524 (defcustom org-effort-property "Effort"
3525 "The property that is being used to keep track of effort estimates.
3526 Effort estimates given in this property need to have the format H:MM."
3527 :group 'org-properties
3528 :group 'org-progress
3529 :type '(string :tag "Property"))
3531 (defconst org-global-properties-fixed
3532 '(("VISIBILITY_ALL" . "folded children content all")
3533 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3534 "List of property/value pairs that can be inherited by any entry.
3536 These are fixed values, for the preset properties. The user variable
3537 that can be used to add to this list is `org-global-properties'.
3539 The entries in this list are cons cells where the car is a property
3540 name and cdr is a string with the value. If the value represents
3541 multiple items like an \"_ALL\" property, separate the items by
3542 spaces.")
3544 (defcustom org-global-properties nil
3545 "List of property/value pairs that can be inherited by any entry.
3547 This list will be combined with the constant `org-global-properties-fixed'.
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.
3552 You can set buffer-local values for the same purpose in the variable
3553 `org-file-properties' this by adding lines like
3555 #+PROPERTY: NAME VALUE"
3556 :group 'org-properties
3557 :type '(repeat
3558 (cons (string :tag "Property")
3559 (string :tag "Value"))))
3561 (defvar org-file-properties nil
3562 "List of property/value pairs that can be inherited by any entry.
3563 Valid for the current buffer.
3564 This variable is populated from #+PROPERTY lines.")
3565 (make-variable-buffer-local 'org-file-properties)
3567 (defgroup org-agenda nil
3568 "Options concerning agenda views in Org-mode."
3569 :tag "Org Agenda"
3570 :group 'org)
3572 (defvar org-category nil
3573 "Variable used by org files to set a category for agenda display.
3574 Such files should use a file variable to set it, for example
3576 # -*- mode: org; org-category: \"ELisp\"
3578 or contain a special line
3580 #+CATEGORY: ELisp
3582 If the file does not specify a category, then file's base name
3583 is used instead.")
3584 (make-variable-buffer-local 'org-category)
3585 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3587 (defcustom org-agenda-files nil
3588 "The files to be used for agenda display.
3589 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3590 \\[org-remove-file]. You can also use customize to edit the list.
3592 If an entry is a directory, all files in that directory that are matched by
3593 `org-agenda-file-regexp' will be part of the file list.
3595 If the value of the variable is not a list but a single file name, then
3596 the list of agenda files is actually stored and maintained in that file, one
3597 agenda file per line. In this file paths can be given relative to
3598 `org-directory'. Tilde expansion and environment variable substitution
3599 are also made."
3600 :group 'org-agenda
3601 :type '(choice
3602 (repeat :tag "List of files and directories" file)
3603 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3605 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3606 "Regular expression to match files for `org-agenda-files'.
3607 If any element in the list in that variable contains a directory instead
3608 of a normal file, all files in that directory that are matched by this
3609 regular expression will be included."
3610 :group 'org-agenda
3611 :type 'regexp)
3613 (defcustom org-agenda-text-search-extra-files nil
3614 "List of extra files to be searched by text search commands.
3615 These files will be searched in addition to the agenda files by the
3616 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3617 Note that these files will only be searched for text search commands,
3618 not for the other agenda views like todo lists, tag searches or the weekly
3619 agenda. This variable is intended to list notes and possibly archive files
3620 that should also be searched by these two commands.
3621 In fact, if the first element in the list is the symbol `agenda-archives',
3622 then all archive files of all agenda files will be added to the search
3623 scope."
3624 :group 'org-agenda
3625 :type '(set :greedy t
3626 (const :tag "Agenda Archives" agenda-archives)
3627 (repeat :inline t (file))))
3629 (org-defvaralias 'org-agenda-multi-occur-extra-files
3630 'org-agenda-text-search-extra-files)
3632 (defcustom org-agenda-skip-unavailable-files nil
3633 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3634 A nil value means to remove them, after a query, from the list."
3635 :group 'org-agenda
3636 :type 'boolean)
3638 (defcustom org-calendar-to-agenda-key [?c]
3639 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3640 The command `org-calendar-goto-agenda' will be bound to this key. The
3641 default is the character `c' because then `c' can be used to switch back and
3642 forth between agenda and calendar."
3643 :group 'org-agenda
3644 :type 'sexp)
3646 (defcustom org-calendar-insert-diary-entry-key [?i]
3647 "The key to be installed in `calendar-mode-map' for adding diary entries.
3648 This option is irrelevant until `org-agenda-diary-file' has been configured
3649 to point to an Org-mode file. When that is the case, the command
3650 `org-agenda-diary-entry' will be bound to the key given here, by default
3651 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3652 if you want to continue doing this, you need to change this to a different
3653 key."
3654 :group 'org-agenda
3655 :type 'sexp)
3657 (defcustom org-agenda-diary-file 'diary-file
3658 "File to which to add new entries with the `i' key in agenda and calendar.
3659 When this is the symbol `diary-file', the functionality in the Emacs
3660 calendar will be used to add entries to the `diary-file'. But when this
3661 points to a file, `org-agenda-diary-entry' will be used instead."
3662 :group 'org-agenda
3663 :type '(choice
3664 (const :tag "The standard Emacs diary file" diary-file)
3665 (file :tag "Special Org file diary entries")))
3667 (eval-after-load "calendar"
3668 '(progn
3669 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3670 'org-calendar-goto-agenda)
3671 (add-hook 'calendar-mode-hook
3672 (lambda ()
3673 (unless (eq org-agenda-diary-file 'diary-file)
3674 (define-key calendar-mode-map
3675 org-calendar-insert-diary-entry-key
3676 'org-agenda-diary-entry))))))
3678 (defgroup org-latex nil
3679 "Options for embedding LaTeX code into Org-mode."
3680 :tag "Org LaTeX"
3681 :group 'org)
3683 (defcustom org-format-latex-options
3684 '(:foreground default :background default :scale 1.0
3685 :html-foreground "Black" :html-background "Transparent"
3686 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3687 "Options for creating images from LaTeX fragments.
3688 This is a property list with the following properties:
3689 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3690 `default' means use the foreground of the default face.
3691 `auto' means use the foreground from the text face.
3692 :background the background color, or \"Transparent\".
3693 `default' means use the background of the default face.
3694 `auto' means use the background from the text face.
3695 :scale a scaling factor for the size of the images, to get more pixels
3696 :html-foreground, :html-background, :html-scale
3697 the same numbers for HTML export.
3698 :matchers a list indicating which matchers should be used to
3699 find LaTeX fragments. Valid members of this list are:
3700 \"begin\" find environments
3701 \"$1\" find single characters surrounded by $.$
3702 \"$\" find math expressions surrounded by $...$
3703 \"$$\" find math expressions surrounded by $$....$$
3704 \"\\(\" find math expressions surrounded by \\(...\\)
3705 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3706 :group 'org-latex
3707 :type 'plist)
3709 (defcustom org-format-latex-signal-error t
3710 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3711 When nil, just push out a message."
3712 :group 'org-latex
3713 :version "24.1"
3714 :type 'boolean)
3716 (defcustom org-latex-to-mathml-jar-file nil
3717 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3718 Use this to specify additional executable file say a jar file.
3720 When using MathToWeb as the converter, specify the full-path to
3721 your mathtoweb.jar file."
3722 :group 'org-latex
3723 :version "24.1"
3724 :type '(choice
3725 (const :tag "None" nil)
3726 (file :tag "JAR file" :must-match t)))
3728 (defcustom org-latex-to-mathml-convert-command nil
3729 "Command to convert LaTeX fragments to MathML.
3730 Replace format-specifiers in the command as noted below and use
3731 `shell-command' to convert LaTeX to MathML.
3732 %j: Executable file in fully expanded form as specified by
3733 `org-latex-to-mathml-jar-file'.
3734 %I: Input LaTeX file in fully expanded form
3735 %o: Output MathML file
3736 This command is used by `org-create-math-formula'.
3738 When using MathToWeb as the converter, set this to
3739 \"java -jar %j -unicode -force -df %o %I\"."
3740 :group 'org-latex
3741 :version "24.1"
3742 :type '(choice
3743 (const :tag "None" nil)
3744 (string :tag "\nShell command")))
3746 (defcustom org-latex-create-formula-image-program 'dvipng
3747 "Program to convert LaTeX fragments with.
3749 dvipng Process the LaTeX fragments to dvi file, then convert
3750 dvi files to png files using dvipng.
3751 This will also include processing of non-math environments.
3752 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3753 to convert pdf files to png files"
3754 :group 'org-latex
3755 :version "24.1"
3756 :type '(choice
3757 (const :tag "dvipng" dvipng)
3758 (const :tag "imagemagick" imagemagick)))
3760 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3761 "Path to store latex preview images.
3762 A relative path here creates many directories relative to the
3763 processed org files paths. An absolute path puts all preview
3764 images at the same place."
3765 :group 'org-latex
3766 :version "24.3"
3767 :type 'string)
3769 (defun org-format-latex-mathml-available-p ()
3770 "Return t if `org-latex-to-mathml-convert-command' is usable."
3771 (save-match-data
3772 (when (and (boundp 'org-latex-to-mathml-convert-command)
3773 org-latex-to-mathml-convert-command)
3774 (let ((executable (car (split-string
3775 org-latex-to-mathml-convert-command))))
3776 (when (executable-find executable)
3777 (if (string-match
3778 "%j" org-latex-to-mathml-convert-command)
3779 (file-readable-p org-latex-to-mathml-jar-file)
3780 t))))))
3782 (defcustom org-format-latex-header "\\documentclass{article}
3783 \\usepackage[usenames]{color}
3784 \[PACKAGES]
3785 \[DEFAULT-PACKAGES]
3786 \\pagestyle{empty} % do not remove
3787 % The settings below are copied from fullpage.sty
3788 \\setlength{\\textwidth}{\\paperwidth}
3789 \\addtolength{\\textwidth}{-3cm}
3790 \\setlength{\\oddsidemargin}{1.5cm}
3791 \\addtolength{\\oddsidemargin}{-2.54cm}
3792 \\setlength{\\evensidemargin}{\\oddsidemargin}
3793 \\setlength{\\textheight}{\\paperheight}
3794 \\addtolength{\\textheight}{-\\headheight}
3795 \\addtolength{\\textheight}{-\\headsep}
3796 \\addtolength{\\textheight}{-\\footskip}
3797 \\addtolength{\\textheight}{-3cm}
3798 \\setlength{\\topmargin}{1.5cm}
3799 \\addtolength{\\topmargin}{-2.54cm}"
3800 "The document header used for processing LaTeX fragments.
3801 It is imperative that this header make sure that no page number
3802 appears on the page. The package defined in the variables
3803 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3804 will either replace the placeholder \"[PACKAGES]\" in this
3805 header, or they will be appended."
3806 :group 'org-latex
3807 :type 'string)
3809 (defun org-set-packages-alist (var val)
3810 "Set the packages alist and make sure it has 3 elements per entry."
3811 (set var (mapcar (lambda (x)
3812 (if (and (consp x) (= (length x) 2))
3813 (list (car x) (nth 1 x) t)
3815 val)))
3817 (defun org-get-packages-alist (var)
3818 "Get the packages alist and make sure it has 3 elements per entry."
3819 (mapcar (lambda (x)
3820 (if (and (consp x) (= (length x) 2))
3821 (list (car x) (nth 1 x) t)
3823 (default-value var)))
3825 (defcustom org-latex-default-packages-alist
3826 '(("AUTO" "inputenc" t)
3827 ("T1" "fontenc" t)
3828 ("" "fixltx2e" nil)
3829 ("" "graphicx" t)
3830 ("" "longtable" nil)
3831 ("" "float" nil)
3832 ("" "wrapfig" nil)
3833 ("" "rotating" nil)
3834 ("normalem" "ulem" t)
3835 ("" "amsmath" t)
3836 ("" "textcomp" t)
3837 ("" "marvosym" t)
3838 ("" "wasysym" t)
3839 ("" "amssymb" t)
3840 ("" "hyperref" nil)
3841 "\\tolerance=1000")
3842 "Alist of default packages to be inserted in the header.
3844 Change this only if one of the packages here causes an
3845 incompatibility with another package you are using.
3847 The packages in this list are needed by one part or another of
3848 Org mode to function properly:
3850 - inputenc, fontenc: for basic font and character selection
3851 - fixltx2e: Important patches of LaTeX itself
3852 - graphicx: for including images
3853 - longtable: For multipage tables
3854 - float, wrapfig: for figure placement
3855 - rotating: for sideways figures and tables
3856 - ulem: for underline and strike-through
3857 - amsmath: for subscript and superscript and math environments
3858 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3859 for interpreting the entities in `org-entities'. You can skip
3860 some of these packages if you don't use any of their symbols.
3861 - hyperref: for cross references
3863 Therefore you should not modify this variable unless you know
3864 what you are doing. The one reason to change it anyway is that
3865 you might be loading some other package that conflicts with one
3866 of the default packages. Each cell is of the format
3867 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3868 the package also needs to be included when compiling LaTeX
3869 snippets into images for inclusion into non-LaTeX output."
3870 :group 'org-latex
3871 :group 'org-export-latex
3872 :set 'org-set-packages-alist
3873 :get 'org-get-packages-alist
3874 :version "24.1"
3875 :type '(repeat
3876 (choice
3877 (list :tag "options/package pair"
3878 (string :tag "options")
3879 (string :tag "package")
3880 (boolean :tag "Snippet"))
3881 (string :tag "A line of LaTeX"))))
3883 (defcustom org-latex-packages-alist nil
3884 "Alist of packages to be inserted in every LaTeX header.
3886 These will be inserted after `org-latex-default-packages-alist'.
3887 Each cell is of the format:
3889 \(\"options\" \"package\" snippet-flag)
3891 SNIPPET-FLAG, when t, indicates that this package is also needed
3892 when turning LaTeX snippets into images for inclusion into
3893 non-LaTeX output.
3895 Make sure that you only list packages here which:
3897 - you want in every file
3898 - do not conflict with the setup in `org-format-latex-header'.
3899 - do not conflict with the default packages in
3900 `org-latex-default-packages-alist'."
3901 :group 'org-latex
3902 :group 'org-export-latex
3903 :set 'org-set-packages-alist
3904 :get 'org-get-packages-alist
3905 :type '(repeat
3906 (choice
3907 (list :tag "options/package pair"
3908 (string :tag "options")
3909 (string :tag "package")
3910 (boolean :tag "Snippet"))
3911 (string :tag "A line of LaTeX"))))
3913 (defgroup org-appearance nil
3914 "Settings for Org-mode appearance."
3915 :tag "Org Appearance"
3916 :group 'org)
3918 (defcustom org-level-color-stars-only nil
3919 "Non-nil means fontify only the stars in each headline.
3920 When nil, the entire headline is fontified.
3921 Changing it requires restart of `font-lock-mode' to become effective
3922 also in regions already fontified."
3923 :group 'org-appearance
3924 :type 'boolean)
3926 (defcustom org-hide-leading-stars nil
3927 "Non-nil means hide the first N-1 stars in a headline.
3928 This works by using the face `org-hide' for these stars. This
3929 face is white for a light background, and black for a dark
3930 background. You may have to customize the face `org-hide' to
3931 make this work.
3932 Changing it requires restart of `font-lock-mode' to become effective
3933 also in regions already fontified.
3934 You may also set this on a per-file basis by adding one of the following
3935 lines to the buffer:
3937 #+STARTUP: hidestars
3938 #+STARTUP: showstars"
3939 :group 'org-appearance
3940 :type 'boolean)
3942 (defcustom org-hidden-keywords nil
3943 "List of symbols corresponding to keywords to be hidden the org buffer.
3944 For example, a value '(title) for this list will make the document's title
3945 appear in the buffer without the initial #+TITLE: keyword."
3946 :group 'org-appearance
3947 :version "24.1"
3948 :type '(set (const :tag "#+AUTHOR" author)
3949 (const :tag "#+DATE" date)
3950 (const :tag "#+EMAIL" email)
3951 (const :tag "#+TITLE" title)))
3953 (defcustom org-custom-properties nil
3954 "List of properties (as strings) with a special meaning.
3955 The default use of these custom properties is to let the user
3956 hide them with `org-toggle-custom-properties-visibility'."
3957 :group 'org-properties
3958 :group 'org-appearance
3959 :version "24.3"
3960 :type '(repeat (string :tag "Property Name")))
3962 (defcustom org-fontify-done-headline nil
3963 "Non-nil means change the face of a headline if it is marked DONE.
3964 Normally, only the TODO/DONE keyword indicates the state of a headline.
3965 When this is non-nil, the headline after the keyword is set to the
3966 `org-headline-done' as an additional indication."
3967 :group 'org-appearance
3968 :type 'boolean)
3970 (defcustom org-fontify-emphasized-text t
3971 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3972 Changing this variable requires a restart of Emacs to take effect."
3973 :group 'org-appearance
3974 :type 'boolean)
3976 (defcustom org-fontify-whole-heading-line nil
3977 "Non-nil means fontify the whole line for headings.
3978 This is useful when setting a background color for the
3979 org-level-* faces."
3980 :group 'org-appearance
3981 :type 'boolean)
3983 (defcustom org-highlight-latex-and-related nil
3984 "Non-nil means highlight LaTeX related syntax in the buffer.
3985 When non nil, the value should be a list containing any of the
3986 following symbols:
3987 `latex' Highlight LaTeX snippets and environments.
3988 `script' Highlight subscript and superscript.
3989 `entities' Highlight entities."
3990 :group 'org-appearance
3991 :version "24.4"
3992 :package-version '(Org . "8.0")
3993 :type '(choice
3994 (const :tag "No highlighting" nil)
3995 (set :greedy t :tag "Highlight"
3996 (const :tag "LaTeX snippets and environments" latex)
3997 (const :tag "Subscript and superscript" script)
3998 (const :tag "Entities" entities))))
4000 (defcustom org-hide-emphasis-markers nil
4001 "Non-nil mean font-lock should hide the emphasis marker characters."
4002 :group 'org-appearance
4003 :type 'boolean)
4005 (defcustom org-pretty-entities nil
4006 "Non-nil means show entities as UTF8 characters.
4007 When nil, the \\name form remains in the buffer."
4008 :group 'org-appearance
4009 :version "24.1"
4010 :type 'boolean)
4012 (defcustom org-pretty-entities-include-sub-superscripts t
4013 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4014 :group 'org-appearance
4015 :version "24.1"
4016 :type 'boolean)
4018 (defvar org-emph-re nil
4019 "Regular expression for matching emphasis.
4020 After a match, the match groups contain these elements:
4021 0 The match of the full regular expression, including the characters
4022 before and after the proper match
4023 1 The character before the proper match, or empty at beginning of line
4024 2 The proper match, including the leading and trailing markers
4025 3 The leading marker like * or /, indicating the type of highlighting
4026 4 The text between the emphasis markers, not including the markers
4027 5 The character after the match, empty at the end of a line")
4028 (defvar org-verbatim-re nil
4029 "Regular expression for matching verbatim text.")
4030 (defvar org-emphasis-regexp-components) ; defined just below
4031 (defvar org-emphasis-alist) ; defined just below
4032 (defun org-set-emph-re (var val)
4033 "Set variable and compute the emphasis regular expression."
4034 (set var val)
4035 (when (and (boundp 'org-emphasis-alist)
4036 (boundp 'org-emphasis-regexp-components)
4037 org-emphasis-alist org-emphasis-regexp-components)
4038 (let* ((e org-emphasis-regexp-components)
4039 (pre (car e))
4040 (post (nth 1 e))
4041 (border (nth 2 e))
4042 (body (nth 3 e))
4043 (nl (nth 4 e))
4044 (body1 (concat body "*?"))
4045 (markers (mapconcat 'car org-emphasis-alist ""))
4046 (vmarkers (mapconcat
4047 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4048 org-emphasis-alist "")))
4049 ;; make sure special characters appear at the right position in the class
4050 (if (string-match "\\^" markers)
4051 (setq markers (concat (replace-match "" t t markers) "^")))
4052 (if (string-match "-" markers)
4053 (setq markers (concat (replace-match "" t t markers) "-")))
4054 (if (string-match "\\^" vmarkers)
4055 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4056 (if (string-match "-" vmarkers)
4057 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4058 (if (> nl 0)
4059 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4060 (int-to-string nl) "\\}")))
4061 ;; Make the regexp
4062 (setq org-emph-re
4063 (concat "\\([" pre "]\\|^\\)"
4064 "\\("
4065 "\\([" markers "]\\)"
4066 "\\("
4067 "[^" border "]\\|"
4068 "[^" border "]"
4069 body1
4070 "[^" border "]"
4071 "\\)"
4072 "\\3\\)"
4073 "\\([" post "]\\|$\\)"))
4074 (setq org-verbatim-re
4075 (concat "\\([" pre "]\\|^\\)"
4076 "\\("
4077 "\\([" vmarkers "]\\)"
4078 "\\("
4079 "[^" border "]\\|"
4080 "[^" border "]"
4081 body1
4082 "[^" border "]"
4083 "\\)"
4084 "\\3\\)"
4085 "\\([" post "]\\|$\\)")))))
4087 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4088 ;; set this option proved cumbersome. See this message/thread:
4089 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4090 (defvar org-emphasis-regexp-components
4091 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4092 "Components used to build the regular expression for emphasis.
4093 This is a list with five entries. Terminology: In an emphasis string
4094 like \" *strong word* \", we call the initial space PREMATCH, the final
4095 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4096 and \"trong wor\" is the body. The different components in this variable
4097 specify what is allowed/forbidden in each part:
4099 pre Chars allowed as prematch. Beginning of line will be allowed too.
4100 post Chars allowed as postmatch. End of line will be allowed too.
4101 border The chars *forbidden* as border characters.
4102 body-regexp A regexp like \".\" to match a body character. Don't use
4103 non-shy groups here, and don't allow newline here.
4104 newline The maximum number of newlines allowed in an emphasis exp.
4106 You need to reload Org or to restart Emacs after customizing this.")
4108 (defcustom org-emphasis-alist
4109 `(("*" bold)
4110 ("/" italic)
4111 ("_" underline)
4112 ("=" org-code verbatim)
4113 ("~" org-verbatim verbatim)
4114 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4115 "Alist of characters and faces to emphasize text.
4116 Text starting and ending with a special character will be emphasized,
4117 for example *bold*, _underlined_ and /italic/. This variable sets the
4118 marker characters and the face to be used by font-lock for highlighting
4119 in Org-mode Emacs buffers.
4121 You need to reload Org or to restart Emacs after customizing this."
4122 :group 'org-appearance
4123 :set 'org-set-emph-re
4124 :version "24.4"
4125 :package-version '(Org . "8.0")
4126 :type '(repeat
4127 (list
4128 (string :tag "Marker character")
4129 (choice
4130 (face :tag "Font-lock-face")
4131 (plist :tag "Face property list"))
4132 (option (const verbatim)))))
4134 (defvar org-protecting-blocks
4135 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4136 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4137 This is needed for font-lock setup.")
4139 ;;; Miscellaneous options
4141 (defgroup org-completion nil
4142 "Completion in Org-mode."
4143 :tag "Org Completion"
4144 :group 'org)
4146 (defcustom org-completion-use-ido nil
4147 "Non-nil means use ido completion wherever possible.
4148 Note that `ido-mode' must be active for this variable to be relevant.
4149 If you decide to turn this variable on, you might well want to turn off
4150 `org-outline-path-complete-in-steps'.
4151 See also `org-completion-use-iswitchb'."
4152 :group 'org-completion
4153 :type 'boolean)
4155 (defcustom org-completion-use-iswitchb nil
4156 "Non-nil means use iswitchb completion wherever possible.
4157 Note that `iswitchb-mode' must be active for this variable to be relevant.
4158 If you decide to turn this variable on, you might well want to turn off
4159 `org-outline-path-complete-in-steps'.
4160 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4161 :group 'org-completion
4162 :type 'boolean)
4164 (defcustom org-completion-fallback-command 'hippie-expand
4165 "The expansion command called by \\[pcomplete] in normal context.
4166 Normal means, no org-mode-specific context."
4167 :group 'org-completion
4168 :type 'function)
4170 ;;; Functions and variables from their packages
4171 ;; Declared here to avoid compiler warnings
4173 ;; XEmacs only
4174 (defvar outline-mode-menu-heading)
4175 (defvar outline-mode-menu-show)
4176 (defvar outline-mode-menu-hide)
4177 (defvar zmacs-regions) ; XEmacs regions
4179 ;; Emacs only
4180 (defvar mark-active)
4182 ;; Various packages
4183 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4184 (declare-function calendar-forward-day "cal-move" (arg))
4185 (declare-function calendar-goto-date "cal-move" (date))
4186 (declare-function calendar-goto-today "cal-move" ())
4187 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4188 (defvar calc-embedded-close-formula)
4189 (defvar calc-embedded-open-formula)
4190 (declare-function cdlatex-tab "ext:cdlatex" ())
4191 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4192 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4193 (defvar font-lock-unfontify-region-function)
4194 (declare-function iswitchb-read-buffer "iswitchb"
4195 (prompt &optional default require-match start matches-set))
4196 (defvar iswitchb-temp-buflist)
4197 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4198 (defvar org-agenda-tags-todo-honor-ignore-options)
4199 (declare-function org-agenda-skip "org-agenda" ())
4200 (declare-function
4201 org-agenda-format-item "org-agenda"
4202 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4203 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4204 (declare-function org-agenda-change-all-lines "org-agenda"
4205 (newhead hdmarker &optional fixface just-this))
4206 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4207 (declare-function org-agenda-maybe-redo "org-agenda" ())
4208 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4209 (beg end))
4210 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4211 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4212 "org-agenda" (&optional end))
4213 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4214 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4215 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4216 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4217 (declare-function org-indent-mode "org-indent" (&optional arg))
4218 (declare-function parse-time-string "parse-time" (string))
4219 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4220 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4221 (defvar remember-data-file)
4222 (defvar texmathp-why)
4223 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4224 (declare-function table--at-cell-p "table" (position &optional object at-column))
4226 (defvar org-latex-regexps)
4228 ;;; Autoload and prepare some org modules
4230 ;; Some table stuff that needs to be defined here, because it is used
4231 ;; by the functions setting up org-mode or checking for table context.
4233 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4234 "Detect an org-type or table-type table.")
4235 (defconst org-table-line-regexp "^[ \t]*|"
4236 "Detect an org-type table line.")
4237 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4238 "Detect an org-type table line.")
4239 (defconst org-table-hline-regexp "^[ \t]*|-"
4240 "Detect an org-type table hline.")
4241 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4242 "Detect a table-type table hline.")
4243 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4244 "Detect the first line outside a table when searching from within it.
4245 This works for both table types.")
4247 ;; Autoload the functions in org-table.el that are needed by functions here.
4249 (eval-and-compile
4250 (org-autoload "org-table"
4251 '(org-table-begin org-table-blank-field org-table-end)))
4253 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4254 "Detect a #+TBLFM line.")
4256 ;;;###autoload
4257 (defun turn-on-orgtbl ()
4258 "Unconditionally turn on `orgtbl-mode'."
4259 (require 'org-table)
4260 (orgtbl-mode 1))
4262 (defun org-at-table-p (&optional table-type)
4263 "Return t if the cursor is inside an org-type table.
4264 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4265 (if org-enable-table-editor
4266 (save-excursion
4267 (beginning-of-line 1)
4268 (looking-at (if table-type org-table-any-line-regexp
4269 org-table-line-regexp)))
4270 nil))
4271 (defsubst org-table-p () (org-at-table-p))
4273 (defun org-at-table.el-p ()
4274 "Return t if and only if we are at a table.el table."
4275 (and (org-at-table-p 'any)
4276 (save-excursion
4277 (goto-char (org-table-begin 'any))
4278 (looking-at org-table1-hline-regexp))))
4280 (defun org-table-recognize-table.el ()
4281 "If there is a table.el table nearby, recognize it and move into it."
4282 (if org-table-tab-recognizes-table.el
4283 (if (org-at-table.el-p)
4284 (progn
4285 (beginning-of-line 1)
4286 (if (looking-at org-table-dataline-regexp)
4288 (if (looking-at org-table1-hline-regexp)
4289 (progn
4290 (beginning-of-line 2)
4291 (if (looking-at org-table-any-border-regexp)
4292 (beginning-of-line -1)))))
4293 (if (re-search-forward "|" (org-table-end t) t)
4294 (progn
4295 (require 'table)
4296 (if (table--at-cell-p (point))
4298 (message "recognizing table.el table...")
4299 (table-recognize-table)
4300 (message "recognizing table.el table...done")))
4301 (error "This should not happen"))
4303 nil)
4304 nil))
4306 (defun org-at-table-hline-p ()
4307 "Return t if the cursor is inside a hline in a table."
4308 (if org-enable-table-editor
4309 (save-excursion
4310 (beginning-of-line 1)
4311 (looking-at org-table-hline-regexp))
4312 nil))
4314 (defun org-table-map-tables (function &optional quietly)
4315 "Apply FUNCTION to the start of all tables in the buffer."
4316 (save-excursion
4317 (save-restriction
4318 (widen)
4319 (goto-char (point-min))
4320 (while (re-search-forward org-table-any-line-regexp nil t)
4321 (unless quietly
4322 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4323 (beginning-of-line 1)
4324 (when (and (looking-at org-table-line-regexp)
4325 ;; Exclude tables in src/example/verbatim/clocktable blocks
4326 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4327 (save-excursion (funcall function))
4328 (or (looking-at org-table-line-regexp)
4329 (forward-char 1)))
4330 (re-search-forward org-table-any-border-regexp nil 1))))
4331 (unless quietly (message "Mapping tables: done")))
4333 ;; Declare and autoload functions from org-agenda.el
4335 (eval-and-compile
4336 (org-autoload "org-agenda"
4337 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4339 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4340 (declare-function org-clock-update-mode-line "org-clock" ())
4341 (declare-function org-resolve-clocks "org-clock"
4342 (&optional also-non-dangling-p prompt last-valid))
4344 (defun org-at-TBLFM-p (&optional pos)
4345 "Return t when point (or POS) is in #+TBLFM line."
4346 (save-excursion
4347 (let ((pos pos)))
4348 (goto-char (or pos (point)))
4349 (beginning-of-line 1)
4350 (looking-at org-TBLFM-regexp)))
4352 (defvar org-clock-start-time)
4353 (defvar org-clock-marker (make-marker)
4354 "Marker recording the last clock-in.")
4355 (defvar org-clock-hd-marker (make-marker)
4356 "Marker recording the last clock-in, but the headline position.")
4357 (defvar org-clock-heading ""
4358 "The heading of the current clock entry.")
4359 (defun org-clock-is-active ()
4360 "Return the buffer where the clock is currently running.
4361 Return nil if no clock is running."
4362 (marker-buffer org-clock-marker))
4364 (eval-and-compile
4365 (org-autoload "org-clock" '(org-clock-remove-overlays
4366 org-clock-update-time-maybe
4367 org-clocktable-shift)))
4369 (defun org-check-running-clock ()
4370 "Check if the current buffer contains the running clock.
4371 If yes, offer to stop it and to save the buffer with the changes."
4372 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4373 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4374 (buffer-name))))
4375 (org-clock-out)
4376 (when (y-or-n-p "Save changed buffer?")
4377 (save-buffer))))
4379 (defun org-clocktable-try-shift (dir n)
4380 "Check if this line starts a clock table, if yes, shift the time block."
4381 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4382 (org-clocktable-shift dir n)))
4384 ;;;###autoload
4385 (defun org-clock-persistence-insinuate ()
4386 "Set up hooks for clock persistence."
4387 (require 'org-clock)
4388 (add-hook 'org-mode-hook 'org-clock-load)
4389 (add-hook 'kill-emacs-hook 'org-clock-save))
4391 ;; Define the variable already here, to make sure we have it.
4392 (defvar org-indent-mode nil
4393 "Non-nil if Org-Indent mode is enabled.
4394 Use the command `org-indent-mode' to change this variable.")
4396 ;; Autoload archiving code
4397 ;; The stuff that is needed for cycling and tags has to be defined here.
4399 (defgroup org-archive nil
4400 "Options concerning archiving in Org-mode."
4401 :tag "Org Archive"
4402 :group 'org-structure)
4404 (defcustom org-archive-location "%s_archive::"
4405 "The location where subtrees should be archived.
4407 The value of this variable is a string, consisting of two parts,
4408 separated by a double-colon. The first part is a filename and
4409 the second part is a headline.
4411 When the filename is omitted, archiving happens in the same file.
4412 %s in the filename will be replaced by the current file
4413 name (without the directory part). Archiving to a different file
4414 is useful to keep archived entries from contributing to the
4415 Org-mode Agenda.
4417 The archived entries will be filed as subtrees of the specified
4418 headline. When the headline is omitted, the subtrees are simply
4419 filed away at the end of the file, as top-level entries. Also in
4420 the heading you can use %s to represent the file name, this can be
4421 useful when using the same archive for a number of different files.
4423 Here are a few examples:
4424 \"%s_archive::\"
4425 If the current file is Projects.org, archive in file
4426 Projects.org_archive, as top-level trees. This is the default.
4428 \"::* Archived Tasks\"
4429 Archive in the current file, under the top-level headline
4430 \"* Archived Tasks\".
4432 \"~/org/archive.org::\"
4433 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4435 \"~/org/archive.org::* From %s\"
4436 Archive in file ~/org/archive.org (absolute path), under headlines
4437 \"From FILENAME\" where file name is the current file name.
4439 \"~/org/datetree.org::datetree/* Finished Tasks\"
4440 The \"datetree/\" string is special, signifying to archive
4441 items to the datetree. Items are placed in either the CLOSED
4442 date of the item, or the current date if there is no CLOSED date.
4443 The heading will be a subentry to the current date. There doesn't
4444 need to be a heading, but there always needs to be a slash after
4445 datetree. For example, to store archived items directly in the
4446 datetree, use \"~/org/datetree.org::datetree/\".
4448 \"basement::** Finished Tasks\"
4449 Archive in file ./basement (relative path), as level 3 trees
4450 below the level 2 heading \"** Finished Tasks\".
4452 You may set this option on a per-file basis by adding to the buffer a
4453 line like
4455 #+ARCHIVE: basement::** Finished Tasks
4457 You may also define it locally for a subtree by setting an ARCHIVE property
4458 in the entry. If such a property is found in an entry, or anywhere up
4459 the hierarchy, it will be used."
4460 :group 'org-archive
4461 :type 'string)
4463 (defcustom org-archive-tag "ARCHIVE"
4464 "The tag that marks a subtree as archived.
4465 An archived subtree does not open during visibility cycling, and does
4466 not contribute to the agenda listings.
4467 After changing this, font-lock must be restarted in the relevant buffers to
4468 get the proper fontification."
4469 :group 'org-archive
4470 :group 'org-keywords
4471 :type 'string)
4473 (defcustom org-agenda-skip-archived-trees t
4474 "Non-nil means the agenda will skip any items located in archived trees.
4475 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4476 variable is no longer recommended, you should leave it at the value t.
4477 Instead, use the key `v' to cycle the archives-mode in the agenda."
4478 :group 'org-archive
4479 :group 'org-agenda-skip
4480 :type 'boolean)
4482 (defcustom org-columns-skip-archived-trees t
4483 "Non-nil means ignore archived trees when creating column view."
4484 :group 'org-archive
4485 :group 'org-properties
4486 :type 'boolean)
4488 (defcustom org-cycle-open-archived-trees nil
4489 "Non-nil means `org-cycle' will open archived trees.
4490 An archived tree is a tree marked with the tag ARCHIVE.
4491 When nil, archived trees will stay folded. You can still open them with
4492 normal outline commands like `show-all', but not with the cycling commands."
4493 :group 'org-archive
4494 :group 'org-cycle
4495 :type 'boolean)
4497 (defcustom org-sparse-tree-open-archived-trees nil
4498 "Non-nil means sparse tree construction shows matches in archived trees.
4499 When nil, matches in these trees are highlighted, but the trees are kept in
4500 collapsed state."
4501 :group 'org-archive
4502 :group 'org-sparse-trees
4503 :type 'boolean)
4505 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4506 "The default date type when building a sparse tree.
4507 When this is nil, a date is a scheduled or a deadline timestamp.
4508 Otherwise, these types are allowed:
4510 all: all timestamps
4511 active: only active timestamps (<...>)
4512 inactive: only inactive timestamps (<...)
4513 scheduled: only scheduled timestamps
4514 deadline: only deadline timestamps"
4515 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4516 (const :tag "All timestamps" all)
4517 (const :tag "Only active timestamps" active)
4518 (const :tag "Only inactive timestamps" inactive)
4519 (const :tag "Only scheduled timestamps" scheduled)
4520 (const :tag "Only deadline timestamps" deadline)
4521 (const :tag "Only closed timestamps" closed))
4522 :version "24.3"
4523 :group 'org-sparse-trees)
4525 (defun org-cycle-hide-archived-subtrees (state)
4526 "Re-hide all archived subtrees after a visibility state change."
4527 (when (and (not org-cycle-open-archived-trees)
4528 (not (memq state '(overview folded))))
4529 (save-excursion
4530 (let* ((globalp (memq state '(contents all)))
4531 (beg (if globalp (point-min) (point)))
4532 (end (if globalp (point-max) (org-end-of-subtree t))))
4533 (org-hide-archived-subtrees beg end)
4534 (goto-char beg)
4535 (if (looking-at (concat ".*:" org-archive-tag ":"))
4536 (message "%s" (substitute-command-keys
4537 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4539 (defun org-force-cycle-archived ()
4540 "Cycle subtree even if it is archived."
4541 (interactive)
4542 (setq this-command 'org-cycle)
4543 (let ((org-cycle-open-archived-trees t))
4544 (call-interactively 'org-cycle)))
4546 (defun org-hide-archived-subtrees (beg end)
4547 "Re-hide all archived subtrees after a visibility state change."
4548 (save-excursion
4549 (let* ((re (concat ":" org-archive-tag ":")))
4550 (goto-char beg)
4551 (while (re-search-forward re end t)
4552 (when (org-at-heading-p)
4553 (org-flag-subtree t)
4554 (org-end-of-subtree t))))))
4556 (declare-function outline-end-of-heading "outline" ())
4557 (declare-function outline-flag-region "outline" (from to flag))
4558 (defun org-flag-subtree (flag)
4559 (save-excursion
4560 (org-back-to-heading t)
4561 (outline-end-of-heading)
4562 (outline-flag-region (point)
4563 (progn (org-end-of-subtree t) (point))
4564 flag)))
4566 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4568 (eval-and-compile
4569 (org-autoload "org-archive"
4570 '(org-add-archive-files)))
4572 ;; Autoload Column View Code
4574 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4575 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4576 (declare-function org-columns-compute "org-colview" (property))
4578 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4579 '(org-columns-number-to-string
4580 org-columns-get-format-and-top-level
4581 org-columns-compute
4582 org-columns-remove-overlays))
4584 ;; Autoload ID code
4586 (declare-function org-id-store-link "org-id")
4587 (declare-function org-id-locations-load "org-id")
4588 (declare-function org-id-locations-save "org-id")
4589 (defvar org-id-track-globally)
4590 (org-autoload "org-id"
4591 '(org-id-new
4592 org-id-copy
4593 org-id-get-with-outline-path-completion
4594 org-id-get-with-outline-drilling))
4596 ;;; Variables for pre-computed regular expressions, all buffer local
4598 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4599 "Matches first line of a hidden block.")
4600 (make-variable-buffer-local 'org-drawer-regexp)
4601 (defvar org-todo-regexp nil
4602 "Matches any of the TODO state keywords.")
4603 (make-variable-buffer-local 'org-todo-regexp)
4604 (defvar org-not-done-regexp nil
4605 "Matches any of the TODO state keywords except the last one.")
4606 (make-variable-buffer-local 'org-not-done-regexp)
4607 (defvar org-not-done-heading-regexp nil
4608 "Matches a TODO headline that is not done.")
4609 (make-variable-buffer-local 'org-not-done-regexp)
4610 (defvar org-todo-line-regexp nil
4611 "Matches a headline and puts TODO state into group 2 if present.")
4612 (make-variable-buffer-local 'org-todo-line-regexp)
4613 (defvar org-complex-heading-regexp nil
4614 "Matches a headline and puts everything into groups:
4615 group 1: the stars
4616 group 2: The todo keyword, maybe
4617 group 3: Priority cookie
4618 group 4: True headline
4619 group 5: Tags")
4620 (make-variable-buffer-local 'org-complex-heading-regexp)
4621 (defvar org-complex-heading-regexp-format nil
4622 "Printf format to make regexp to match an exact headline.
4623 This regexp will match the headline of any node which has the
4624 exact headline text that is put into the format, but may have any
4625 TODO state, priority and tags.")
4626 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4627 (defvar org-todo-line-tags-regexp nil
4628 "Matches a headline and puts TODO state into group 2 if present.
4629 Also put tags into group 4 if tags are present.")
4630 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4631 (defvar org-ds-keyword-length 12
4632 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4633 (make-variable-buffer-local 'org-ds-keyword-length)
4634 (defvar org-deadline-regexp nil
4635 "Matches the DEADLINE keyword.")
4636 (make-variable-buffer-local 'org-deadline-regexp)
4637 (defvar org-deadline-time-regexp nil
4638 "Matches the DEADLINE keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-deadline-time-regexp)
4640 (defvar org-deadline-time-hour-regexp nil
4641 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4642 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4643 (defvar org-deadline-line-regexp nil
4644 "Matches the DEADLINE keyword and the rest of the line.")
4645 (make-variable-buffer-local 'org-deadline-line-regexp)
4646 (defvar org-scheduled-regexp nil
4647 "Matches the SCHEDULED keyword.")
4648 (make-variable-buffer-local 'org-scheduled-regexp)
4649 (defvar org-scheduled-time-regexp nil
4650 "Matches the SCHEDULED keyword together with a time stamp.")
4651 (make-variable-buffer-local 'org-scheduled-time-regexp)
4652 (defvar org-scheduled-time-hour-regexp nil
4653 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4654 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4655 (defvar org-closed-time-regexp nil
4656 "Matches the CLOSED keyword together with a time stamp.")
4657 (make-variable-buffer-local 'org-closed-time-regexp)
4659 (defvar org-keyword-time-regexp nil
4660 "Matches any of the 4 keywords, together with the time stamp.")
4661 (make-variable-buffer-local 'org-keyword-time-regexp)
4662 (defvar org-keyword-time-not-clock-regexp nil
4663 "Matches any of the 3 keywords, together with the time stamp.")
4664 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4665 (defvar org-maybe-keyword-time-regexp nil
4666 "Matches a timestamp, possibly preceded by a keyword.")
4667 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4668 (defvar org-all-time-keywords nil
4669 "List of time keywords.")
4670 (make-variable-buffer-local 'org-all-time-keywords)
4672 (defconst org-plain-time-of-day-regexp
4673 (concat
4674 "\\(\\<[012]?[0-9]"
4675 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4676 "\\(--?"
4677 "\\(\\<[012]?[0-9]"
4678 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4679 "\\)?")
4680 "Regular expression to match a plain time or time range.
4681 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4682 groups carry important information:
4683 0 the full match
4684 1 the first time, range or not
4685 8 the second time, if it is a range.")
4687 (defconst org-plain-time-extension-regexp
4688 (concat
4689 "\\(\\<[012]?[0-9]"
4690 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4691 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4692 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4693 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4694 groups carry important information:
4695 0 the full match
4696 7 hours of duration
4697 9 minutes of duration")
4699 (defconst org-stamp-time-of-day-regexp
4700 (concat
4701 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4702 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4703 "\\(--?"
4704 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4705 "Regular expression to match a timestamp time or time range.
4706 After a match, the following groups carry important information:
4707 0 the full match
4708 1 date plus weekday, for back referencing to make sure both times are on the same day
4709 2 the first time, range or not
4710 4 the second time, if it is a range.")
4712 (defconst org-startup-options
4713 '(("fold" org-startup-folded t)
4714 ("overview" org-startup-folded t)
4715 ("nofold" org-startup-folded nil)
4716 ("showall" org-startup-folded nil)
4717 ("showeverything" org-startup-folded showeverything)
4718 ("content" org-startup-folded content)
4719 ("indent" org-startup-indented t)
4720 ("noindent" org-startup-indented nil)
4721 ("hidestars" org-hide-leading-stars t)
4722 ("showstars" org-hide-leading-stars nil)
4723 ("odd" org-odd-levels-only t)
4724 ("oddeven" org-odd-levels-only nil)
4725 ("align" org-startup-align-all-tables t)
4726 ("noalign" org-startup-align-all-tables nil)
4727 ("inlineimages" org-startup-with-inline-images t)
4728 ("noinlineimages" org-startup-with-inline-images nil)
4729 ("latexpreview" org-startup-with-latex-preview t)
4730 ("nolatexpreview" org-startup-with-latex-preview nil)
4731 ("customtime" org-display-custom-times t)
4732 ("logdone" org-log-done time)
4733 ("lognotedone" org-log-done note)
4734 ("nologdone" org-log-done nil)
4735 ("lognoteclock-out" org-log-note-clock-out t)
4736 ("nolognoteclock-out" org-log-note-clock-out nil)
4737 ("logrepeat" org-log-repeat state)
4738 ("lognoterepeat" org-log-repeat note)
4739 ("logdrawer" org-log-into-drawer t)
4740 ("nologdrawer" org-log-into-drawer nil)
4741 ("logstatesreversed" org-log-states-order-reversed t)
4742 ("nologstatesreversed" org-log-states-order-reversed nil)
4743 ("nologrepeat" org-log-repeat nil)
4744 ("logreschedule" org-log-reschedule time)
4745 ("lognotereschedule" org-log-reschedule note)
4746 ("nologreschedule" org-log-reschedule nil)
4747 ("logredeadline" org-log-redeadline time)
4748 ("lognoteredeadline" org-log-redeadline note)
4749 ("nologredeadline" org-log-redeadline nil)
4750 ("logrefile" org-log-refile time)
4751 ("lognoterefile" org-log-refile note)
4752 ("nologrefile" org-log-refile nil)
4753 ("fninline" org-footnote-define-inline t)
4754 ("nofninline" org-footnote-define-inline nil)
4755 ("fnlocal" org-footnote-section nil)
4756 ("fnauto" org-footnote-auto-label t)
4757 ("fnprompt" org-footnote-auto-label nil)
4758 ("fnconfirm" org-footnote-auto-label confirm)
4759 ("fnplain" org-footnote-auto-label plain)
4760 ("fnadjust" org-footnote-auto-adjust t)
4761 ("nofnadjust" org-footnote-auto-adjust nil)
4762 ("constcgs" constants-unit-system cgs)
4763 ("constSI" constants-unit-system SI)
4764 ("noptag" org-tag-persistent-alist nil)
4765 ("hideblocks" org-hide-block-startup t)
4766 ("nohideblocks" org-hide-block-startup nil)
4767 ("beamer" org-startup-with-beamer-mode t)
4768 ("entitiespretty" org-pretty-entities t)
4769 ("entitiesplain" org-pretty-entities nil))
4770 "Variable associated with STARTUP options for org-mode.
4771 Each element is a list of three items: the startup options (as written
4772 in the #+STARTUP line), the corresponding variable, and the value to set
4773 this variable to if the option is found. An optional forth element PUSH
4774 means to push this value onto the list in the variable.")
4776 (defun org-update-property-plist (key val props)
4777 "Update PROPS with KEY and VAL."
4778 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4779 (key (if appending (substring key 0 (- (length key) 1)) key))
4780 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4781 (previous (cdr (assoc key props))))
4782 (if appending
4783 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4784 (cons (cons key val) remainder))))
4786 (defconst org-block-regexp
4787 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4788 "Regular expression for hiding blocks.")
4789 (defconst org-heading-keyword-regexp-format
4790 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4791 "Printf format for a regexp matching a headline with some keyword.
4792 This regexp will match the headline of any node which has the
4793 exact keyword that is put into the format. The keyword isn't in
4794 any group by default, but the stars and the body are.")
4795 (defconst org-heading-keyword-maybe-regexp-format
4796 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4797 "Printf format for a regexp matching a headline, possibly with some keyword.
4798 This regexp can match any headline with the specified keyword, or
4799 without a keyword. The keyword isn't in any group by default,
4800 but the stars and the body are.")
4802 (defcustom org-group-tags t
4803 "When non-nil (the default), use group tags.
4804 This can be turned on/off through `org-toggle-tags-groups'."
4805 :group 'org-tags
4806 :group 'org-startup
4807 :type 'boolean)
4809 (defun org-toggle-tags-groups ()
4810 "Toggle support for group tags.
4811 Support for group tags is controlled by the option
4812 `org-group-tags', which is non-nil by default."
4813 (interactive)
4814 (setq org-group-tags (not org-group-tags))
4815 (cond ((and (derived-mode-p 'org-agenda-mode)
4816 org-group-tags)
4817 (org-agenda-redo))
4818 ((derived-mode-p 'org-mode)
4819 (let ((org-inhibit-startup t)) (org-mode))))
4820 (message "Groups tags support has been turned %s"
4821 (if org-group-tags "on" "off")))
4823 (defun org-set-regexps-and-options-for-tags ()
4824 "Precompute variables used for tags."
4825 (when (derived-mode-p 'org-mode)
4826 (org-set-local 'org-file-tags nil)
4827 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4828 (splitre "[ \t]+")
4829 (start 0)
4830 tags ftags key value)
4831 (save-excursion
4832 (save-restriction
4833 (widen)
4834 (goto-char (point-min))
4835 (while (re-search-forward re nil t)
4836 (setq key (upcase (org-match-string-no-properties 1))
4837 value (org-match-string-no-properties 2))
4838 (if (stringp value) (setq value (org-trim value)))
4839 (cond
4840 ((equal key "TAGS")
4841 (setq tags (append tags (if tags '("\\n") nil)
4842 (org-split-string value splitre))))
4843 ((equal key "FILETAGS")
4844 (when (string-match "\\S-" value)
4845 (setq ftags
4846 (append
4847 ftags
4848 (apply 'append
4849 (mapcar (lambda (x) (org-split-string x ":"))
4850 (org-split-string value)))))))))))
4851 ;; Process the file tags.
4852 (and ftags (org-set-local 'org-file-tags
4853 (mapcar 'org-add-prop-inherited ftags)))
4854 (org-set-local 'org-tag-groups-alist nil)
4855 ;; Process the tags.
4856 (when (and (not tags) org-tag-alist)
4857 (setq tags
4858 (mapcar
4859 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4860 ((eq (car tg) :endgroup) "}")
4861 ((eq (car tg) :grouptags) ":")
4862 ((eq (car tg) :newline) "\n")
4863 (t (concat (car tg)
4864 (if (characterp (cdr tg))
4865 (format "(%s)" (char-to-string (cdr tg))) "")))))
4866 org-tag-alist)))
4867 (let (e tgs g)
4868 (while (setq e (pop tags))
4869 (cond
4870 ((equal e "{")
4871 (progn (push '(:startgroup) tgs)
4872 (when (equal (nth 1 tags) ":")
4873 (push (list (replace-regexp-in-string
4874 "(.+)$" "" (nth 0 tags)))
4875 org-tag-groups-alist)
4876 (setq g 0))))
4877 ((equal e ":") (push '(:grouptags) tgs))
4878 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4879 ((equal e "\\n") (push '(:newline) tgs))
4880 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4881 (push (cons (match-string 1 e)
4882 (string-to-char (match-string 2 e))) tgs)
4883 (if (and g (> g 0))
4884 (setcar org-tag-groups-alist
4885 (append (car org-tag-groups-alist)
4886 (list (match-string 1 e)))))
4887 (if g (setq g (1+ g))))
4888 (t (push (list e) tgs)
4889 (if (and g (> g 0))
4890 (setcar org-tag-groups-alist
4891 (append (car org-tag-groups-alist) (list e))))
4892 (if g (setq g (1+ g))))))
4893 (org-set-local 'org-tag-alist nil)
4894 (while (setq e (pop tgs))
4895 (or (and (stringp (car e))
4896 (assoc (car e) org-tag-alist))
4897 (push e org-tag-alist)))
4898 ;; Return a list with tag variables
4899 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4901 (defvar org-ota nil)
4902 (defun org-set-regexps-and-options ()
4903 "Precompute regular expressions used in the current buffer."
4904 (when (derived-mode-p 'org-mode)
4905 (org-set-local 'org-todo-kwd-alist nil)
4906 (org-set-local 'org-todo-key-alist nil)
4907 (org-set-local 'org-todo-key-trigger nil)
4908 (org-set-local 'org-todo-keywords-1 nil)
4909 (org-set-local 'org-done-keywords nil)
4910 (org-set-local 'org-todo-heads nil)
4911 (org-set-local 'org-todo-sets nil)
4912 (org-set-local 'org-todo-log-states nil)
4913 (org-set-local 'org-file-properties nil)
4914 (let ((re (org-make-options-regexp
4915 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4916 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4917 "SETUPFILE" "OPTIONS")
4918 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4919 (splitre "[ \t]+")
4920 (scripts org-use-sub-superscripts)
4921 kwds kws0 kwsa key log value cat arch const links hw dws
4922 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4923 (start 0))
4924 (save-excursion
4925 (save-restriction
4926 (widen)
4927 (goto-char (point-min))
4928 (while
4929 (or (and
4930 ext-setup-or-nil
4931 (not org-ota)
4932 (let (ret)
4933 (with-temp-buffer
4934 (insert ext-setup-or-nil)
4935 (let ((major-mode 'org-mode) org-ota)
4936 (setq ret (save-match-data
4937 (org-set-regexps-and-options-for-tags)))))
4938 ;; Append setupfile tags to existing tags
4939 (setq org-ota t)
4940 (setq org-file-tags
4941 (delq nil (append org-file-tags (nth 0 ret)))
4942 org-tag-alist
4943 (delq nil (append org-tag-alist (nth 1 ret)))
4944 org-tag-groups-alist
4945 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4946 (and ext-setup-or-nil
4947 (string-match re ext-setup-or-nil start)
4948 (setq start (match-end 0)))
4949 (and (setq ext-setup-or-nil nil start 0)
4950 (re-search-forward re nil t)))
4951 (setq key (upcase (match-string 1 ext-setup-or-nil))
4952 value (org-match-string-no-properties 2 ext-setup-or-nil))
4953 (if (stringp value) (setq value (org-trim value)))
4954 (cond
4955 ((equal key "CATEGORY")
4956 (setq cat value))
4957 ((member key '("SEQ_TODO" "TODO"))
4958 (push (cons 'sequence (org-split-string value splitre)) kwds))
4959 ((equal key "TYP_TODO")
4960 (push (cons 'type (org-split-string value splitre)) kwds))
4961 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4962 ;; general TODO-like setup
4963 (push (cons (intern (downcase (match-string 1 key)))
4964 (org-split-string value splitre)) kwds))
4965 ((equal key "COLUMNS")
4966 (org-set-local 'org-columns-default-format value))
4967 ((equal key "LINK")
4968 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4969 (push (cons (match-string 1 value)
4970 (org-trim (match-string 2 value)))
4971 links)))
4972 ((equal key "PRIORITIES")
4973 (setq prio (org-split-string value " +")))
4974 ((equal key "PROPERTY")
4975 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4976 (setq props (org-update-property-plist (match-string 1 value)
4977 (match-string 2 value)
4978 props))))
4979 ((equal key "DRAWERS")
4980 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4981 ((equal key "CONSTANTS")
4982 (org-table-set-constants))
4983 ((equal key "STARTUP")
4984 (let ((opts (org-split-string value splitre))
4985 l var val)
4986 (while (setq l (pop opts))
4987 (when (setq l (assoc l org-startup-options))
4988 (setq var (nth 1 l) val (nth 2 l))
4989 (if (not (nth 3 l))
4990 (set (make-local-variable var) val)
4991 (if (not (listp (symbol-value var)))
4992 (set (make-local-variable var) nil))
4993 (set (make-local-variable var) (symbol-value var))
4994 (add-to-list var val))))))
4995 ((equal key "ARCHIVE")
4996 (setq arch value)
4997 (remove-text-properties 0 (length arch)
4998 '(face t fontified t) arch))
4999 ((equal key "OPTIONS")
5000 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5001 (setq scripts (read (match-string 2 value)))))
5002 ((and (equal key "SETUPFILE")
5003 ;; Prevent checking in Gnus messages
5004 (not buffer-read-only))
5005 (setq setup-contents (org-file-contents
5006 (expand-file-name
5007 (org-remove-double-quotes value))
5008 'noerror))
5009 (if (not ext-setup-or-nil)
5010 (setq ext-setup-or-nil setup-contents start 0)
5011 (setq ext-setup-or-nil
5012 (concat (substring ext-setup-or-nil 0 start)
5013 "\n" setup-contents "\n"
5014 (substring ext-setup-or-nil start)))))))
5015 ;; search for property blocks
5016 (goto-char (point-min))
5017 (while (re-search-forward org-block-regexp nil t)
5018 (when (equal "PROPERTY" (upcase (match-string 1)))
5019 (setq value (replace-regexp-in-string
5020 "[\n\r]" " " (match-string 4)))
5021 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5022 (setq props (org-update-property-plist (match-string 1 value)
5023 (match-string 2 value)
5024 props)))))))
5025 (org-set-local 'org-use-sub-superscripts scripts)
5026 (when cat
5027 (org-set-local 'org-category (intern cat))
5028 (push (cons "CATEGORY" cat) props))
5029 (when prio
5030 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5031 (setq prio (mapcar 'string-to-char prio))
5032 (org-set-local 'org-highest-priority (nth 0 prio))
5033 (org-set-local 'org-lowest-priority (nth 1 prio))
5034 (org-set-local 'org-default-priority (nth 2 prio)))
5035 (and props (org-set-local 'org-file-properties (nreverse props)))
5036 (and drawers (org-set-local 'org-drawers drawers))
5037 (and arch (org-set-local 'org-archive-location arch))
5038 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5039 ;; Process the TODO keywords
5040 (unless kwds
5041 ;; Use the global values as if they had been given locally.
5042 (setq kwds (default-value 'org-todo-keywords))
5043 (if (stringp (car kwds))
5044 (setq kwds (list (cons org-todo-interpretation
5045 (default-value 'org-todo-keywords)))))
5046 (setq kwds (reverse kwds)))
5047 (setq kwds (nreverse kwds))
5048 (let (inter kws kw)
5049 (while (setq kws (pop kwds))
5050 (let ((kws (or
5051 (run-hook-with-args-until-success
5052 'org-todo-setup-filter-hook kws)
5053 kws)))
5054 (setq inter (pop kws) sep (member "|" kws)
5055 kws0 (delete "|" (copy-sequence kws))
5056 kwsa nil
5057 kws1 (mapcar
5058 (lambda (x)
5059 ;; 1 2
5060 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5061 (progn
5062 (setq kw (match-string 1 x)
5063 key (and (match-end 2) (match-string 2 x))
5064 log (org-extract-log-state-settings x))
5065 (push (cons kw (and key (string-to-char key))) kwsa)
5066 (and log (push log org-todo-log-states))
5068 (error "Invalid TODO keyword %s" x)))
5069 kws0)
5070 kwsa (if kwsa (append '((:startgroup))
5071 (nreverse kwsa)
5072 '((:endgroup))))
5073 hw (car kws1)
5074 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5075 tail (list inter hw (car dws) (org-last dws))))
5076 (add-to-list 'org-todo-heads hw 'append)
5077 (push kws1 org-todo-sets)
5078 (setq org-done-keywords (append org-done-keywords dws nil))
5079 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5080 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5081 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5082 (setq org-todo-sets (nreverse org-todo-sets)
5083 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5084 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5085 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5086 ;; Compute the regular expressions and other local variables.
5087 ;; Using `org-outline-regexp-bol' would complicate them much,
5088 ;; because of the fixed white space at the end of that string.
5089 (if (not org-done-keywords)
5090 (setq org-done-keywords (and org-todo-keywords-1
5091 (list (org-last org-todo-keywords-1)))))
5092 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5093 (length org-scheduled-string)
5094 (length org-clock-string)
5095 (length org-closed-string)))
5096 org-drawer-regexp
5097 (concat "^[ \t]*:\\("
5098 (mapconcat 'regexp-quote org-drawers "\\|")
5099 "\\):[ \t]*$")
5100 org-not-done-keywords
5101 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5102 org-todo-regexp
5103 (concat "\\("
5104 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5105 "\\)")
5106 org-not-done-regexp
5107 (concat "\\("
5108 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5109 "\\)")
5110 org-not-done-heading-regexp
5111 (format org-heading-keyword-regexp-format org-not-done-regexp)
5112 org-todo-line-regexp
5113 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5114 org-complex-heading-regexp
5115 (concat "^\\(\\*+\\)"
5116 "\\(?: +" org-todo-regexp "\\)?"
5117 "\\(?: +\\(\\[#.\\]\\)\\)?"
5118 "\\(?: +\\(.*?\\)\\)??"
5119 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5120 "[ \t]*$")
5121 org-complex-heading-regexp-format
5122 (concat "^\\(\\*+\\)"
5123 "\\(?: +" org-todo-regexp "\\)?"
5124 "\\(?: +\\(\\[#.\\]\\)\\)?"
5125 "\\(?: +"
5126 ;; Stats cookies can be stuck to body.
5127 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5128 "\\(%s\\)"
5129 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5130 "\\)"
5131 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5132 "[ \t]*$")
5133 org-todo-line-tags-regexp
5134 (concat "^\\(\\*+\\)"
5135 "\\(?: +" org-todo-regexp "\\)?"
5136 "\\(?: +\\(.*?\\)\\)??"
5137 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5138 "[ \t]*$")
5139 org-deadline-regexp (concat "\\<" org-deadline-string)
5140 org-deadline-time-regexp
5141 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5142 org-deadline-time-hour-regexp
5143 (concat "\\<" org-deadline-string
5144 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5145 org-deadline-line-regexp
5146 (concat "\\<\\(" org-deadline-string "\\).*")
5147 org-scheduled-regexp
5148 (concat "\\<" org-scheduled-string)
5149 org-scheduled-time-regexp
5150 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5151 org-scheduled-time-hour-regexp
5152 (concat "\\<" org-scheduled-string
5153 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5154 org-closed-time-regexp
5155 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5156 org-keyword-time-regexp
5157 (concat "\\<\\(" org-scheduled-string
5158 "\\|" org-deadline-string
5159 "\\|" org-closed-string
5160 "\\|" org-clock-string "\\)"
5161 " *[[<]\\([^]>]+\\)[]>]")
5162 org-keyword-time-not-clock-regexp
5163 (concat "\\<\\(" org-scheduled-string
5164 "\\|" org-deadline-string
5165 "\\|" org-closed-string
5166 "\\)"
5167 " *[[<]\\([^]>]+\\)[]>]")
5168 org-maybe-keyword-time-regexp
5169 (concat "\\(\\<\\(" org-scheduled-string
5170 "\\|" org-deadline-string
5171 "\\|" org-closed-string
5172 "\\|" org-clock-string "\\)\\)?"
5173 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5174 org-all-time-keywords
5175 (mapcar (lambda (w) (substring w 0 -1))
5176 (list org-scheduled-string org-deadline-string
5177 org-clock-string org-closed-string)))
5178 (setq org-ota nil)
5179 (org-compute-latex-and-related-regexp))))
5181 (defun org-file-contents (file &optional noerror)
5182 "Return the contents of FILE, as a string."
5183 (if (or (not file)
5184 (not (file-readable-p file)))
5185 (if noerror
5186 (message "Cannot read file \"%s\"" file)
5187 (error "Cannot read file \"%s\"" file))
5188 (with-temp-buffer
5189 (insert-file-contents file)
5190 (buffer-string))))
5192 (defun org-extract-log-state-settings (x)
5193 "Extract the log state setting from a TODO keyword string.
5194 This will extract info from a string like \"WAIT(w@/!)\"."
5195 (let (kw key log1 log2)
5196 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5197 (setq kw (match-string 1 x)
5198 key (and (match-end 2) (match-string 2 x))
5199 log1 (and (match-end 3) (match-string 3 x))
5200 log2 (and (match-end 4) (match-string 4 x)))
5201 (and (or log1 log2)
5202 (list kw
5203 (and log1 (if (equal log1 "!") 'time 'note))
5204 (and log2 (if (equal log2 "!") 'time 'note)))))))
5206 (defun org-remove-keyword-keys (list)
5207 "Remove a pair of parenthesis at the end of each string in LIST."
5208 (mapcar (lambda (x)
5209 (if (string-match "(.*)$" x)
5210 (substring x 0 (match-beginning 0))
5212 list))
5214 (defun org-assign-fast-keys (alist)
5215 "Assign fast keys to a keyword-key alist.
5216 Respect keys that are already there."
5217 (let (new e (alt ?0))
5218 (while (setq e (pop alist))
5219 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5220 (cdr e)) ;; Key already assigned.
5221 (push e new)
5222 (let ((clist (string-to-list (downcase (car e))))
5223 (used (append new alist)))
5224 (when (= (car clist) ?@)
5225 (pop clist))
5226 (while (and clist (rassoc (car clist) used))
5227 (pop clist))
5228 (unless clist
5229 (while (rassoc alt used)
5230 (incf alt)))
5231 (push (cons (car e) (or (car clist) alt)) new))))
5232 (nreverse new)))
5234 ;;; Some variables used in various places
5236 (defvar org-window-configuration nil
5237 "Used in various places to store a window configuration.")
5238 (defvar org-selected-window nil
5239 "Used in various places to store a window configuration.")
5240 (defvar org-finish-function nil
5241 "Function to be called when `C-c C-c' is used.
5242 This is for getting out of special buffers like capture.")
5245 ;; FIXME: Occasionally check by commenting these, to make sure
5246 ;; no other functions uses these, forgetting to let-bind them.
5247 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5248 (defvar org-last-state)
5249 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5251 ;; Defined somewhere in this file, but used before definition.
5252 (defvar org-entities) ;; defined in org-entities.el
5253 (defvar org-struct-menu)
5254 (defvar org-org-menu)
5255 (defvar org-tbl-menu)
5257 ;;;; Define the Org-mode
5259 ;; We use a before-change function to check if a table might need
5260 ;; an update.
5261 (defvar org-table-may-need-update t
5262 "Indicates that a table might need an update.
5263 This variable is set by `org-before-change-function'.
5264 `org-table-align' sets it back to nil.")
5265 (defun org-before-change-function (beg end)
5266 "Every change indicates that a table might need an update."
5267 (setq org-table-may-need-update t))
5268 (defvar org-mode-map)
5269 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5270 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5271 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5272 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5273 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5274 (defvar org-table-buffer-is-an nil)
5276 (defvar bidi-paragraph-direction)
5277 (defvar buffer-face-mode-face)
5279 (require 'outline)
5280 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5281 (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"))
5282 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5284 ;; Other stuff we need.
5285 (require 'time-date)
5286 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5287 (require 'easymenu)
5288 (require 'overlay)
5290 ;; (require 'org-macs) moved higher up in the file before it is first used
5291 (require 'org-entities)
5292 ;; (require 'org-compat) moved higher up in the file before it is first used
5293 (require 'org-faces)
5294 (require 'org-list)
5295 (require 'org-pcomplete)
5296 (require 'org-src)
5297 (require 'org-footnote)
5298 (require 'org-macro)
5300 ;; babel
5301 (require 'ob)
5303 ;;;###autoload
5304 (define-derived-mode org-mode outline-mode "Org"
5305 "Outline-based notes management and organizer, alias
5306 \"Carsten's outline-mode for keeping track of everything.\"
5308 Org-mode develops organizational tasks around a NOTES file which
5309 contains information about projects as plain text. Org-mode is
5310 implemented on top of outline-mode, which is ideal to keep the content
5311 of large files well structured. It supports ToDo items, deadlines and
5312 time stamps, which magically appear in the diary listing of the Emacs
5313 calendar. Tables are easily created with a built-in table editor.
5314 Plain text URL-like links connect to websites, emails (VM), Usenet
5315 messages (Gnus), BBDB entries, and any files related to the project.
5316 For printing and sharing of notes, an Org-mode file (or a part of it)
5317 can be exported as a structured ASCII or HTML file.
5319 The following commands are available:
5321 \\{org-mode-map}"
5323 ;; Get rid of Outline menus, they are not needed
5324 ;; Need to do this here because define-derived-mode sets up
5325 ;; the keymap so late. Still, it is a waste to call this each time
5326 ;; we switch another buffer into org-mode.
5327 (if (featurep 'xemacs)
5328 (when (boundp 'outline-mode-menu-heading)
5329 ;; Assume this is Greg's port, it uses easymenu
5330 (easy-menu-remove outline-mode-menu-heading)
5331 (easy-menu-remove outline-mode-menu-show)
5332 (easy-menu-remove outline-mode-menu-hide))
5333 (define-key org-mode-map [menu-bar headings] 'undefined)
5334 (define-key org-mode-map [menu-bar hide] 'undefined)
5335 (define-key org-mode-map [menu-bar show] 'undefined))
5337 (org-load-modules-maybe)
5338 (easy-menu-add org-org-menu)
5339 (easy-menu-add org-tbl-menu)
5340 (org-install-agenda-files-menu)
5341 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5342 (add-to-invisibility-spec '(org-cwidth))
5343 (add-to-invisibility-spec '(org-hide-block . t))
5344 (when (featurep 'xemacs)
5345 (org-set-local 'line-move-ignore-invisible t))
5346 (org-set-local 'outline-regexp org-outline-regexp)
5347 (org-set-local 'outline-level 'org-outline-level)
5348 (setq bidi-paragraph-direction 'left-to-right)
5349 (when (and org-ellipsis
5350 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5351 (fboundp 'make-glyph-code))
5352 (unless org-display-table
5353 (setq org-display-table (make-display-table)))
5354 (set-display-table-slot
5355 org-display-table 4
5356 (vconcat (mapcar
5357 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5358 org-ellipsis)))
5359 (if (stringp org-ellipsis) org-ellipsis "..."))))
5360 (setq buffer-display-table org-display-table))
5361 (org-set-regexps-and-options-for-tags)
5362 (org-set-regexps-and-options)
5363 (org-set-font-lock-defaults)
5364 (when (and org-tag-faces (not org-tags-special-faces-re))
5365 ;; tag faces set outside customize.... force initialization.
5366 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5367 ;; Calc embedded
5368 (org-set-local 'calc-embedded-open-mode "# ")
5369 ;; Modify a few syntax entries
5370 (modify-syntax-entry ?@ "w")
5371 (modify-syntax-entry ?\" "\"")
5372 (if org-startup-truncated (setq truncate-lines t))
5373 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5374 (org-set-local 'font-lock-unfontify-region-function
5375 'org-unfontify-region)
5376 ;; Activate before-change-function
5377 (org-set-local 'org-table-may-need-update t)
5378 (org-add-hook 'before-change-functions 'org-before-change-function nil
5379 'local)
5380 ;; Check for running clock before killing a buffer
5381 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5382 ;; Initialize macros templates.
5383 (org-macro-initialize-templates)
5384 ;; Initialize radio targets.
5385 (org-update-radio-target-regexp)
5386 ;; Indentation.
5387 (org-set-local 'indent-line-function 'org-indent-line)
5388 (org-set-local 'indent-region-function 'org-indent-region)
5389 ;; Filling and auto-filling.
5390 (org-setup-filling)
5391 ;; Comments.
5392 (org-setup-comments-handling)
5393 ;; Beginning/end of defun
5394 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5395 (org-set-local 'end-of-defun-function 'org-forward-element)
5396 ;; Next error for sparse trees
5397 (org-set-local 'next-error-function 'org-occur-next-match)
5398 ;; Make sure dependence stuff works reliably, even for users who set it
5399 ;; too late :-(
5400 (if org-enforce-todo-dependencies
5401 (add-hook 'org-blocker-hook
5402 'org-block-todo-from-children-or-siblings-or-parent)
5403 (remove-hook 'org-blocker-hook
5404 'org-block-todo-from-children-or-siblings-or-parent))
5405 (if org-enforce-todo-checkbox-dependencies
5406 (add-hook 'org-blocker-hook
5407 'org-block-todo-from-checkboxes)
5408 (remove-hook 'org-blocker-hook
5409 'org-block-todo-from-checkboxes))
5411 ;; Align options lines
5412 (org-set-local
5413 'align-mode-rules-list
5414 '((org-in-buffer-settings
5415 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5416 (modes . '(org-mode)))))
5418 ;; Imenu
5419 (org-set-local 'imenu-create-index-function
5420 'org-imenu-get-tree)
5422 ;; Make isearch reveal context
5423 (if (or (featurep 'xemacs)
5424 (not (boundp 'outline-isearch-open-invisible-function)))
5425 ;; Emacs 21 and XEmacs make use of the hook
5426 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5427 ;; Emacs 22 deals with this through a special variable
5428 (org-set-local 'outline-isearch-open-invisible-function
5429 (lambda (&rest ignore) (org-show-context 'isearch)))
5430 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5432 ;; Setup the pcomplete hooks
5433 (set (make-local-variable 'pcomplete-command-completion-function)
5434 'org-pcomplete-initial)
5435 (set (make-local-variable 'pcomplete-command-name-function)
5436 'org-command-at-point)
5437 (set (make-local-variable 'pcomplete-default-completion-function)
5438 'ignore)
5439 (set (make-local-variable 'pcomplete-parse-arguments-function)
5440 'org-parse-arguments)
5441 (set (make-local-variable 'pcomplete-termination-string) "")
5442 (when (>= emacs-major-version 23)
5443 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5445 ;; If empty file that did not turn on org-mode automatically, make it to.
5446 (if (and org-insert-mode-line-in-empty-file
5447 (org-called-interactively-p 'any)
5448 (= (point-min) (point-max)))
5449 (insert "# -*- mode: org -*-\n\n"))
5450 (unless org-inhibit-startup
5451 (org-unmodified
5452 (and org-startup-with-beamer-mode (org-beamer-mode))
5453 (when org-startup-align-all-tables
5454 (org-table-map-tables 'org-table-align 'quietly))
5455 (when org-startup-with-inline-images
5456 (org-display-inline-images))
5457 (when org-startup-with-latex-preview
5458 (org-preview-latex-fragment))
5459 (unless org-inhibit-startup-visibility-stuff
5460 (org-set-startup-visibility))))
5461 ;; Try to set org-hide correctly
5462 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5464 ;; Update `customize-package-emacs-version-alist'
5465 (add-to-list 'customize-package-emacs-version-alist
5466 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5467 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5468 ("8.0" . "24.4")))
5470 (defvar org-mode-transpose-word-syntax-table
5471 (let ((st (make-syntax-table)))
5472 (mapc (lambda(c) (modify-syntax-entry
5473 (string-to-char (car c)) "w p" st))
5474 org-emphasis-alist)
5475 st))
5477 (when (fboundp 'abbrev-table-put)
5478 (abbrev-table-put org-mode-abbrev-table
5479 :parents (list text-mode-abbrev-table)))
5481 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5483 (defsubst org-fix-ellipsis-at-bol ()
5484 (save-excursion (goto-char (window-start)) (recenter 0)))
5486 (defun org-find-invisible-foreground ()
5487 (let ((candidates (remove
5488 "unspecified-bg"
5489 (nconc
5490 (list (face-background 'default)
5491 (face-background 'org-default))
5492 (mapcar
5493 (lambda (alist)
5494 (when (boundp alist)
5495 (cdr (assoc 'background-color (symbol-value alist)))))
5496 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5497 (list (face-foreground 'org-hide))))))
5498 (car (remove nil candidates))))
5500 (defun org-current-time (&optional rounding-minutes past)
5501 "Current time, possibly rounded to ROUNDING-MINUTES.
5502 When ROUNDING-MINUTES is not an integer, fall back on the car of
5503 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5504 the rounding returns a past time."
5505 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5506 (car org-time-stamp-rounding-minutes)))
5507 (time (decode-time)) res)
5508 (if (< r 1)
5509 (current-time)
5510 (setq res
5511 (apply 'encode-time
5512 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5513 (nthcdr 2 time))))
5514 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5515 (seconds-to-time (- (org-float-time res) (* r 60)))
5516 res))))
5518 (defun org-today ()
5519 "Return today date, considering `org-extend-today-until'."
5520 (time-to-days
5521 (time-subtract (current-time)
5522 (list 0 (* 3600 org-extend-today-until) 0))))
5524 ;;;; Font-Lock stuff, including the activators
5526 (defvar org-mouse-map (make-sparse-keymap))
5527 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5528 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5529 (when org-mouse-1-follows-link
5530 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5531 (when org-tab-follows-link
5532 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5533 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5535 (require 'font-lock)
5537 (defconst org-non-link-chars "]\t\n\r<>")
5538 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5539 "shell" "elisp" "doi" "message"))
5540 (defvar org-link-types-re nil
5541 "Matches a link that has a url-like prefix like \"http:\"")
5542 (defvar org-link-re-with-space nil
5543 "Matches a link with spaces, optional angular brackets around it.")
5544 (defvar org-link-re-with-space2 nil
5545 "Matches a link with spaces, optional angular brackets around it.")
5546 (defvar org-link-re-with-space3 nil
5547 "Matches a link with spaces, only for internal part in bracket links.")
5548 (defvar org-angle-link-re nil
5549 "Matches link with angular brackets, spaces are allowed.")
5550 (defvar org-plain-link-re nil
5551 "Matches plain link, without spaces.")
5552 (defvar org-bracket-link-regexp nil
5553 "Matches a link in double brackets.")
5554 (defvar org-bracket-link-analytic-regexp nil
5555 "Regular expression used to analyze links.
5556 Here is what the match groups contain after a match:
5557 1: http:
5558 2: http
5559 3: path
5560 4: [desc]
5561 5: desc")
5562 (defvar org-bracket-link-analytic-regexp++ nil
5563 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5564 (defvar org-any-link-re nil
5565 "Regular expression matching any link.")
5567 (defconst org-match-sexp-depth 3
5568 "Number of stacked braces for sub/superscript matching.")
5570 (defun org-create-multibrace-regexp (left right n)
5571 "Create a regular expression which will match a balanced sexp.
5572 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5573 as single character strings.
5574 The regexp returned will match the entire expression including the
5575 delimiters. It will also define a single group which contains the
5576 match except for the outermost delimiters. The maximum depth of
5577 stacked delimiters is N. Escaping delimiters is not possible."
5578 (let* ((nothing (concat "[^" left right "]*?"))
5579 (or "\\|")
5580 (re nothing)
5581 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5582 (while (> n 1)
5583 (setq n (1- n)
5584 re (concat re or next)
5585 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5586 (concat left "\\(" re "\\)" right)))
5588 (defvar org-match-substring-regexp
5589 (concat
5590 "\\(\\S-\\)\\([_^]\\)\\("
5591 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5592 "\\|"
5593 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5594 "\\|"
5595 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5596 "The regular expression matching a sub- or superscript.")
5598 (defvar org-match-substring-with-braces-regexp
5599 (concat
5600 "\\(\\S-\\)\\([_^]\\)\\("
5601 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5602 "\\)")
5603 "The regular expression matching a sub- or superscript, forcing braces.")
5605 (defun org-make-link-regexps ()
5606 "Update the link regular expressions.
5607 This should be called after the variable `org-link-types' has changed."
5608 (setq org-link-types-re
5609 (concat
5610 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5611 org-link-re-with-space
5612 (concat
5613 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5614 "\\([^" org-non-link-chars " ]"
5615 "[^" org-non-link-chars "]*"
5616 "[^" org-non-link-chars " ]\\)>?")
5617 org-link-re-with-space2
5618 (concat
5619 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5620 "\\([^" org-non-link-chars " ]"
5621 "[^\t\n\r]*"
5622 "[^" org-non-link-chars " ]\\)>?")
5623 org-link-re-with-space3
5624 (concat
5625 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5626 "\\([^" org-non-link-chars " ]"
5627 "[^\t\n\r]*\\)")
5628 org-angle-link-re
5629 (concat
5630 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5631 "\\([^" org-non-link-chars " ]"
5632 "[^" org-non-link-chars "]*"
5633 "\\)>")
5634 org-plain-link-re
5635 (concat
5636 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5637 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5638 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5639 org-bracket-link-regexp
5640 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5641 org-bracket-link-analytic-regexp
5642 (concat
5643 "\\[\\["
5644 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5645 "\\([^]]+\\)"
5646 "\\]"
5647 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5648 "\\]")
5649 org-bracket-link-analytic-regexp++
5650 (concat
5651 "\\[\\["
5652 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5653 "\\([^]]+\\)"
5654 "\\]"
5655 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5656 "\\]")
5657 org-any-link-re
5658 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5659 org-angle-link-re "\\)\\|\\("
5660 org-plain-link-re "\\)")))
5662 (org-make-link-regexps)
5664 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5665 "Regular expression for fast time stamp matching.")
5666 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5667 "Regular expression for fast time stamp matching.")
5668 (defconst org-ts-regexp0
5669 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5670 "Regular expression matching time strings for analysis.
5671 This one does not require the space after the date, so it can be used
5672 on a string that terminates immediately after the date.")
5673 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5674 "Regular expression matching time strings for analysis.")
5675 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5676 "Regular expression matching time stamps, with groups.")
5677 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5678 "Regular expression matching time stamps (also [..]), with groups.")
5679 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5680 "Regular expression matching a time stamp range.")
5681 (defconst org-tr-regexp-both
5682 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5683 "Regular expression matching a time stamp range.")
5684 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5685 org-ts-regexp "\\)?")
5686 "Regular expression matching a time stamp or time stamp range.")
5687 (defconst org-tsr-regexp-both
5688 (concat org-ts-regexp-both "\\(--?-?"
5689 org-ts-regexp-both "\\)?")
5690 "Regular expression matching a time stamp or time stamp range.
5691 The time stamps may be either active or inactive.")
5693 (defvar org-emph-face nil)
5695 (defun org-do-emphasis-faces (limit)
5696 "Run through the buffer and add overlays to emphasized strings."
5697 (let (rtn a)
5698 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5699 (if (not (= (char-after (match-beginning 3))
5700 (char-after (match-beginning 4))))
5701 (progn
5702 (setq rtn t)
5703 (setq a (assoc (match-string 3) org-emphasis-alist))
5704 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5705 'face
5706 (nth 1 a))
5707 (and (nth 4 a)
5708 (org-remove-flyspell-overlays-in
5709 (match-beginning 0) (match-end 0)))
5710 (add-text-properties (match-beginning 2) (match-end 2)
5711 '(font-lock-multiline t org-emphasis t))
5712 (when org-hide-emphasis-markers
5713 (add-text-properties (match-end 4) (match-beginning 5)
5714 '(invisible org-link))
5715 (add-text-properties (match-beginning 3) (match-end 3)
5716 '(invisible org-link)))))
5717 (backward-char 1))
5718 rtn))
5720 (defun org-emphasize (&optional char)
5721 "Insert or change an emphasis, i.e. a font like bold or italic.
5722 If there is an active region, change that region to a new emphasis.
5723 If there is no region, just insert the marker characters and position
5724 the cursor between them.
5725 CHAR should be the marker character. If it is a space, it means to
5726 remove the emphasis of the selected region.
5727 If CHAR is not given (for example in an interactive call) it will be
5728 prompted for."
5729 (interactive)
5730 (let ((erc org-emphasis-regexp-components)
5731 (prompt "")
5732 (string "") beg end move c s)
5733 (if (org-region-active-p)
5734 (setq beg (region-beginning) end (region-end)
5735 string (buffer-substring beg end))
5736 (setq move t))
5738 (unless char
5739 (message "Emphasis marker or tag: [%s]"
5740 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5741 (setq char (read-char-exclusive)))
5742 (if (equal char ?\ )
5743 (setq s "" move nil)
5744 (unless (assoc (char-to-string char) org-emphasis-alist)
5745 (user-error "No such emphasis marker: \"%c\"" char))
5746 (setq s (char-to-string char)))
5747 (while (and (> (length string) 1)
5748 (equal (substring string 0 1) (substring string -1))
5749 (assoc (substring string 0 1) org-emphasis-alist))
5750 (setq string (substring string 1 -1)))
5751 (setq string (concat s string s))
5752 (if beg (delete-region beg end))
5753 (unless (or (bolp)
5754 (string-match (concat "[" (nth 0 erc) "\n]")
5755 (char-to-string (char-before (point)))))
5756 (insert " "))
5757 (unless (or (eobp)
5758 (string-match (concat "[" (nth 1 erc) "\n]")
5759 (char-to-string (char-after (point)))))
5760 (insert " ") (backward-char 1))
5761 (insert string)
5762 (and move (backward-char 1))))
5764 (defconst org-nonsticky-props
5765 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5767 (defsubst org-rear-nonsticky-at (pos)
5768 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5770 (defun org-activate-plain-links (limit)
5771 "Run through the buffer and add overlays to links."
5772 (let (f hl)
5773 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5774 (not (org-in-src-block-p)))
5775 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5776 (setq f (get-text-property (match-beginning 0) 'face))
5777 (setq hl (org-match-string-no-properties 0))
5778 (if (or (eq f 'org-tag)
5779 (and (listp f) (memq 'org-tag f)))
5781 (add-text-properties (match-beginning 0) (match-end 0)
5782 (list 'mouse-face 'highlight
5783 'face 'org-link
5784 'htmlize-link `(:uri ,hl)
5785 'keymap org-mouse-map))
5786 (org-rear-nonsticky-at (match-end 0)))
5787 t)))
5789 (defun org-activate-code (limit)
5790 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5791 (progn
5792 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5793 (remove-text-properties (match-beginning 0) (match-end 0)
5794 '(display t invisible t intangible t))
5795 t)))
5797 (defcustom org-src-fontify-natively nil
5798 "When non-nil, fontify code in code blocks."
5799 :type 'boolean
5800 :version "24.1"
5801 :group 'org-appearance
5802 :group 'org-babel)
5804 (defcustom org-allow-promoting-top-level-subtree nil
5805 "When non-nil, allow promoting a top level subtree.
5806 The leading star of the top level headline will be replaced
5807 by a #."
5808 :type 'boolean
5809 :version "24.1"
5810 :group 'org-appearance)
5812 (defun org-fontify-meta-lines-and-blocks (limit)
5813 (condition-case nil
5814 (org-fontify-meta-lines-and-blocks-1 limit)
5815 (error (message "org-mode fontification error"))))
5817 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5818 "Fontify #+ lines and blocks."
5819 (let ((case-fold-search t))
5820 (if (re-search-forward
5821 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5822 limit t)
5823 (let ((beg (match-beginning 0))
5824 (block-start (match-end 0))
5825 (block-end nil)
5826 (lang (match-string 7))
5827 (beg1 (line-beginning-position 2))
5828 (dc1 (downcase (match-string 2)))
5829 (dc3 (downcase (match-string 3)))
5830 end end1 quoting block-type ovl)
5831 (cond
5832 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5833 ;; a single line of backend-specific content
5834 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5835 (remove-text-properties (match-beginning 0) (match-end 0)
5836 '(display t invisible t intangible t))
5837 (add-text-properties (match-beginning 1) (match-end 3)
5838 '(font-lock-fontified t face org-meta-line))
5839 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5840 '(font-lock-fontified t face org-block))
5841 ; for backend-specific code
5843 ((and (match-end 4) (equal dc3 "+begin"))
5844 ;; Truly a block
5845 (setq block-type (downcase (match-string 5))
5846 quoting (member block-type org-protecting-blocks))
5847 (when (re-search-forward
5848 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5849 nil t) ;; on purpose, we look further than LIMIT
5850 (setq end (min (point-max) (match-end 0))
5851 end1 (min (point-max) (1- (match-beginning 0))))
5852 (setq block-end (match-beginning 0))
5853 (when quoting
5854 (remove-text-properties beg end
5855 '(display t invisible t intangible t)))
5856 (add-text-properties
5857 beg end
5858 '(font-lock-fontified t font-lock-multiline t))
5859 (add-text-properties beg beg1 '(face org-meta-line))
5860 (add-text-properties end1 (min (point-max) (1+ end))
5861 '(face org-meta-line)) ; for end_src
5862 (cond
5863 ((and lang (not (string= lang "")) org-src-fontify-natively)
5864 (org-src-font-lock-fontify-block lang block-start block-end)
5865 ;; remove old background overlays
5866 (mapc (lambda (ov)
5867 (if (eq (overlay-get ov 'face) 'org-block-background)
5868 (delete-overlay ov)))
5869 (overlays-at (/ (+ beg1 block-end) 2)))
5870 ;; add a background overlay
5871 (setq ovl (make-overlay beg1 block-end))
5872 (overlay-put ovl 'face 'org-block-background)
5873 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5874 (quoting
5875 (add-text-properties beg1 (min (point-max) (1+ end1))
5876 '(face org-block))) ; end of source block
5877 ((not org-fontify-quote-and-verse-blocks))
5878 ((string= block-type "quote")
5879 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5880 ((string= block-type "verse")
5881 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5882 (add-text-properties beg beg1 '(face org-block-begin-line))
5883 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5884 '(face org-block-end-line))
5886 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5887 (add-text-properties
5888 beg (match-end 3)
5889 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5890 '(font-lock-fontified t invisible t)
5891 '(font-lock-fontified t face org-document-info-keyword)))
5892 (add-text-properties
5893 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5894 (if (string-equal dc1 "+title:")
5895 '(font-lock-fontified t face org-document-title)
5896 '(font-lock-fontified t face org-document-info))))
5897 ((or (equal dc1 "+results")
5898 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5899 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5900 "+call:" "+header:" "+headers:" "+name:"))
5901 (and (match-end 4) (equal dc3 "+attr")))
5902 (add-text-properties
5903 beg (match-end 0)
5904 '(font-lock-fontified t face org-meta-line))
5906 ((member dc3 '(" " ""))
5907 (add-text-properties
5908 beg (match-end 0)
5909 '(font-lock-fontified t face font-lock-comment-face)))
5910 ((not (member (char-after beg) '(?\ ?\t)))
5911 ;; just any other in-buffer setting, but not indented
5912 (add-text-properties
5913 beg (match-end 0)
5914 '(font-lock-fontified t face org-meta-line))
5916 (t nil))))))
5918 (defun org-activate-angle-links (limit)
5919 "Run through the buffer and add overlays to links."
5920 (if (and (re-search-forward org-angle-link-re limit t)
5921 (not (org-in-src-block-p)))
5922 (progn
5923 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5924 (add-text-properties (match-beginning 0) (match-end 0)
5925 (list 'mouse-face 'highlight
5926 'keymap org-mouse-map))
5927 (org-rear-nonsticky-at (match-end 0))
5928 t)))
5930 (defun org-activate-footnote-links (limit)
5931 "Run through the buffer and add overlays to footnotes."
5932 (let ((fn (org-footnote-next-reference-or-definition limit)))
5933 (when fn
5934 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5935 (org-remove-flyspell-overlays-in beg end)
5936 (add-text-properties beg end
5937 (list 'mouse-face 'highlight
5938 'keymap org-mouse-map
5939 'help-echo
5940 (if (= (point-at-bol) beg)
5941 "Footnote definition"
5942 "Footnote reference")
5943 'font-lock-fontified t
5944 'font-lock-multiline t
5945 'face 'org-footnote))))))
5947 (defun org-activate-bracket-links (limit)
5948 "Run through the buffer and add overlays to bracketed links."
5949 (if (and (re-search-forward org-bracket-link-regexp limit t)
5950 (not (org-in-src-block-p)))
5951 (let* ((hl (org-match-string-no-properties 1))
5952 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5953 (ip (org-maybe-intangible
5954 (list 'invisible 'org-link
5955 'keymap org-mouse-map 'mouse-face 'highlight
5956 'font-lock-multiline t 'help-echo help
5957 'htmlize-link `(:uri ,hl))))
5958 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5959 'font-lock-multiline t 'help-echo help
5960 'htmlize-link `(:uri ,hl))))
5961 ;; We need to remove the invisible property here. Table narrowing
5962 ;; may have made some of this invisible.
5963 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5964 (remove-text-properties (match-beginning 0) (match-end 0)
5965 '(invisible nil))
5966 (if (match-end 3)
5967 (progn
5968 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5969 (org-rear-nonsticky-at (match-beginning 3))
5970 (add-text-properties (match-beginning 3) (match-end 3) vp)
5971 (org-rear-nonsticky-at (match-end 3))
5972 (add-text-properties (match-end 3) (match-end 0) ip)
5973 (org-rear-nonsticky-at (match-end 0)))
5974 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5975 (org-rear-nonsticky-at (match-beginning 1))
5976 (add-text-properties (match-beginning 1) (match-end 1) vp)
5977 (org-rear-nonsticky-at (match-end 1))
5978 (add-text-properties (match-end 1) (match-end 0) ip)
5979 (org-rear-nonsticky-at (match-end 0)))
5980 t)))
5982 (defun org-activate-dates (limit)
5983 "Run through the buffer and add overlays to dates."
5984 (if (and (re-search-forward org-tsr-regexp-both limit t)
5985 (not (equal (char-before (match-beginning 0)) 91)))
5986 (progn
5987 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (add-text-properties (match-beginning 0) (match-end 0)
5989 (list 'mouse-face 'highlight
5990 'keymap org-mouse-map))
5991 (org-rear-nonsticky-at (match-end 0))
5992 (when org-display-custom-times
5993 (if (match-end 3)
5994 (org-display-custom-time (match-beginning 3) (match-end 3)))
5995 (org-display-custom-time (match-beginning 1) (match-end 1)))
5996 t)))
5998 (defvar org-target-link-regexp nil
5999 "Regular expression matching radio targets in plain text.")
6000 (make-variable-buffer-local 'org-target-link-regexp)
6001 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6002 "Regular expression matching a link target.")
6003 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6004 "Regular expression matching a radio target.")
6005 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6006 "Regular expression matching any target.")
6008 (defun org-activate-target-links (limit)
6009 "Run through the buffer and add overlays to target matches."
6010 (when org-target-link-regexp
6011 (let ((case-fold-search t))
6012 (if (re-search-forward org-target-link-regexp limit t)
6013 (progn
6014 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6015 (add-text-properties (match-beginning 0) (match-end 0)
6016 (list 'mouse-face 'highlight
6017 'keymap org-mouse-map
6018 'help-echo "Radio target link"
6019 'org-linked-text t))
6020 (org-rear-nonsticky-at (match-end 0))
6021 t)))))
6023 (defun org-update-radio-target-regexp ()
6024 "Find all radio targets in this file and update the regular expression."
6025 (interactive)
6026 (when (memq 'radio org-activate-links)
6027 (setq org-target-link-regexp
6028 (org-make-target-link-regexp (org-all-targets 'radio)))
6029 (org-restart-font-lock)))
6031 (defun org-hide-wide-columns (limit)
6032 (let (s e)
6033 (setq s (text-property-any (point) (or limit (point-max))
6034 'org-cwidth t))
6035 (when s
6036 (setq e (next-single-property-change s 'org-cwidth))
6037 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6038 (goto-char e)
6039 t)))
6041 (defvar org-latex-and-related-regexp nil
6042 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6043 (defvar org-match-substring-regexp)
6044 (defvar org-match-substring-with-braces-regexp)
6046 (defun org-compute-latex-and-related-regexp ()
6047 "Compute regular expression for LaTeX, entities and sub/superscript.
6048 Result depends on variable `org-highlight-latex-and-related'."
6049 (org-set-local
6050 'org-latex-and-related-regexp
6051 (let* ((re-sub
6052 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6053 ((eq org-use-sub-superscripts '{})
6054 (list org-match-substring-with-braces-regexp))
6055 (org-use-sub-superscripts (list org-match-substring-regexp))))
6056 (re-latex
6057 (when (memq 'latex org-highlight-latex-and-related)
6058 (let ((matchers (plist-get org-format-latex-options :matchers)))
6059 (delq nil
6060 (mapcar (lambda (x)
6061 (and (member (car x) matchers) (nth 1 x)))
6062 org-latex-regexps)))))
6063 (re-entities
6064 (when (memq 'entities org-highlight-latex-and-related)
6065 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6066 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6068 (defun org-do-latex-and-related (limit)
6069 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6070 LIMIT bounds the search for syntax to highlight. Stop at first
6071 highlighted object, if any. Return t if some highlighting was
6072 done, nil otherwise."
6073 (when (org-string-nw-p org-latex-and-related-regexp)
6074 (catch 'found
6075 (while (re-search-forward org-latex-and-related-regexp limit t)
6076 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6077 'face))
6078 '(org-code org-verbatim underline))
6079 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6080 '(?_ ?^))
6082 0)))
6083 (font-lock-prepend-text-property
6084 (+ offset (match-beginning 0)) (match-end 0)
6085 'face 'org-latex-and-related)
6086 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6087 '(font-lock-multiline t)))
6088 (throw 'found t)))
6089 nil)))
6091 (defun org-restart-font-lock ()
6092 "Restart `font-lock-mode', to force refontification."
6093 (when (and (boundp 'font-lock-mode) font-lock-mode)
6094 (font-lock-mode -1)
6095 (font-lock-mode 1)))
6097 (defun org-all-targets (&optional radio)
6098 "Return a list of all targets in this file.
6099 When optional argument RADIO is non-nil, only find radio
6100 targets."
6101 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6102 (save-excursion
6103 (goto-char (point-min))
6104 (while (re-search-forward re nil t)
6105 ;; Make sure point is really within the object.
6106 (backward-char)
6107 (let ((obj (org-element-context)))
6108 (when (memq (org-element-type obj) '(radio-target target))
6109 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6110 rtn)))
6112 (defun org-make-target-link-regexp (targets)
6113 "Make regular expression matching all strings in TARGETS.
6114 The regular expression finds the targets also if there is a line break
6115 between words."
6116 (and targets
6117 (concat
6118 "\\<\\("
6119 (mapconcat
6120 (lambda (x)
6121 (setq x (regexp-quote x))
6122 (while (string-match " +" x)
6123 (setq x (replace-match "\\s-+" t t x)))
6125 targets
6126 "\\|")
6127 "\\)\\>")))
6129 (defun org-activate-tags (limit)
6130 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6131 (progn
6132 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6133 (add-text-properties (match-beginning 1) (match-end 1)
6134 (list 'mouse-face 'highlight
6135 'keymap org-mouse-map))
6136 (org-rear-nonsticky-at (match-end 1))
6137 t)))
6139 (defun org-outline-level ()
6140 "Compute the outline level of the heading at point.
6141 If this is called at a normal headline, the level is the number of stars.
6142 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6143 (save-excursion
6144 (if (not (condition-case nil
6145 (org-back-to-heading t)
6146 (error nil)))
6148 (looking-at org-outline-regexp)
6149 (1- (- (match-end 0) (match-beginning 0))))))
6151 (defvar org-font-lock-keywords nil)
6153 (defsubst org-re-property (property &optional literal)
6154 "Return a regexp matching a PROPERTY line.
6155 Match group 3 will be set to the value if it exists."
6156 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6157 (if literal property (regexp-quote property))
6158 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6160 (defconst org-property-re
6161 (org-re-property ".*?" 'literal)
6162 "Regular expression matching a property line.
6163 There are four matching groups:
6164 1: :PROPKEY: including the leading and trailing colon,
6165 2: PROPKEY without the leading and trailing colon,
6166 3: PROPVAL without leading or trailing spaces,
6167 4: the indentation of the current line,
6168 5: trailing whitespace.")
6170 (defvar org-font-lock-hook nil
6171 "Functions to be called for special font lock stuff.")
6173 (defvar org-font-lock-set-keywords-hook nil
6174 "Functions that can manipulate `org-font-lock-extra-keywords'.
6175 This is called after `org-font-lock-extra-keywords' is defined, but before
6176 it is installed to be used by font lock. This can be useful if something
6177 needs to be inserted at a specific position in the font-lock sequence.")
6179 (defun org-font-lock-hook (limit)
6180 "Run `org-font-lock-hook' within LIMIT."
6181 (run-hook-with-args 'org-font-lock-hook limit))
6183 (defun org-set-font-lock-defaults ()
6184 "Set font lock defaults for the current buffer."
6185 (let* ((em org-fontify-emphasized-text)
6186 (lk org-activate-links)
6187 (org-font-lock-extra-keywords
6188 (list
6189 ;; Call the hook
6190 '(org-font-lock-hook)
6191 ;; Headlines
6192 `(,(if org-fontify-whole-heading-line
6193 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6194 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6195 (1 (org-get-level-face 1))
6196 (2 (org-get-level-face 2))
6197 (3 (org-get-level-face 3)))
6198 ;; Table lines
6199 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6200 (1 'org-table t))
6201 ;; Table internals
6202 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6203 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6204 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6205 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6206 ;; Drawers
6207 (list org-drawer-regexp '(0 'org-special-keyword t))
6208 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6209 ;; Properties
6210 (list org-property-re
6211 '(1 'org-special-keyword t)
6212 '(3 'org-property-value t))
6213 ;; Links
6214 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6215 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6216 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6217 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6218 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6219 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6220 (if (memq 'footnote lk) '(org-activate-footnote-links))
6221 ;; Targets.
6222 (list org-any-target-regexp '(0 'org-target t))
6223 ;; Diary sexps.
6224 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6225 ;; Macro
6226 '("{{{.+}}}" (0 'org-macro t))
6227 '(org-hide-wide-columns (0 nil append))
6228 ;; TODO keyword
6229 (list (format org-heading-keyword-regexp-format
6230 org-todo-regexp)
6231 '(2 (org-get-todo-face 2) t))
6232 ;; DONE
6233 (if org-fontify-done-headline
6234 (list (format org-heading-keyword-regexp-format
6235 (concat
6236 "\\(?:"
6237 (mapconcat 'regexp-quote org-done-keywords "\\|")
6238 "\\)"))
6239 '(2 'org-headline-done t))
6240 nil)
6241 ;; Priorities
6242 '(org-font-lock-add-priority-faces)
6243 ;; Tags
6244 '(org-font-lock-add-tag-faces)
6245 ;; Tags groups
6246 (if (and org-group-tags org-tag-groups-alist)
6247 (list (concat org-outline-regexp-bol ".+\\(:"
6248 (regexp-opt (mapcar 'car org-tag-groups-alist))
6249 ":\\).*$")
6250 '(1 'org-tag-group prepend)))
6251 ;; Special keywords
6252 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6253 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6254 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6255 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6256 ;; Emphasis
6257 (if em
6258 (if (featurep 'xemacs)
6259 '(org-do-emphasis-faces (0 nil append))
6260 '(org-do-emphasis-faces)))
6261 ;; Checkboxes
6262 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6263 1 'org-checkbox prepend)
6264 (if (cdr (assq 'checkbox org-list-automatic-rules))
6265 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6266 (0 (org-get-checkbox-statistics-face) t)))
6267 ;; Description list items
6268 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6269 1 'org-list-dt prepend)
6270 ;; ARCHIVEd headings
6271 (list (concat
6272 org-outline-regexp-bol
6273 "\\(.*:" org-archive-tag ":.*\\)")
6274 '(1 'org-archived prepend))
6275 ;; Specials
6276 '(org-do-latex-and-related)
6277 '(org-fontify-entities)
6278 '(org-raise-scripts)
6279 ;; Code
6280 '(org-activate-code (1 'org-code t))
6281 ;; COMMENT
6282 (list (format org-heading-keyword-regexp-format
6283 (concat "\\("
6284 org-comment-string "\\|" org-quote-string
6285 "\\)"))
6286 '(2 'org-special-keyword t))
6287 ;; Blocks and meta lines
6288 '(org-fontify-meta-lines-and-blocks))))
6289 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6290 (run-hooks 'org-font-lock-set-keywords-hook)
6291 ;; Now set the full font-lock-keywords
6292 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6293 (org-set-local 'font-lock-defaults
6294 '(org-font-lock-keywords t nil nil backward-paragraph))
6295 (kill-local-variable 'font-lock-keywords) nil))
6297 (defun org-toggle-pretty-entities ()
6298 "Toggle the composition display of entities as UTF8 characters."
6299 (interactive)
6300 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6301 (org-restart-font-lock)
6302 (if org-pretty-entities
6303 (message "Entities are now displayed as UTF8 characters")
6304 (save-restriction
6305 (widen)
6306 (org-decompose-region (point-min) (point-max))
6307 (message "Entities are now displayed as plain text"))))
6309 (defvar org-custom-properties-overlays nil
6310 "List of overlays used for custom properties.")
6311 (make-variable-buffer-local 'org-custom-properties-overlays)
6313 (defun org-toggle-custom-properties-visibility ()
6314 "Display or hide properties in `org-custom-properties'."
6315 (interactive)
6316 (if org-custom-properties-overlays
6317 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6318 (setq org-custom-properties-overlays nil))
6319 (unless (not org-custom-properties)
6320 (save-excursion
6321 (save-restriction
6322 (widen)
6323 (goto-char (point-min))
6324 (while (re-search-forward org-property-re nil t)
6325 (mapc (lambda(p)
6326 (when (equal p (substring (match-string 1) 1 -1))
6327 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6328 (overlay-put o 'invisible t)
6329 (overlay-put o 'org-custom-property t)
6330 (push o org-custom-properties-overlays))))
6331 org-custom-properties)))))))
6333 (defun org-fontify-entities (limit)
6334 "Find an entity to fontify."
6335 (let (ee)
6336 (when org-pretty-entities
6337 (catch 'match
6338 (while (re-search-forward
6339 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6340 limit t)
6341 (if (and (not (org-in-indented-comment-line))
6342 (setq ee (org-entity-get (match-string 1)))
6343 (= (length (nth 6 ee)) 1))
6344 (let*
6345 ((end (if (equal (match-string 2) "{}")
6346 (match-end 2)
6347 (match-end 1))))
6348 (add-text-properties
6349 (match-beginning 0) end
6350 (list 'font-lock-fontified t))
6351 (compose-region (match-beginning 0) end
6352 (nth 6 ee) nil)
6353 (backward-char 1)
6354 (throw 'match t))))
6355 nil))))
6357 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6358 "Fontify string S like in Org-mode."
6359 (with-temp-buffer
6360 (insert s)
6361 (let ((org-odd-levels-only odd-levels))
6362 (org-mode)
6363 (font-lock-fontify-buffer)
6364 (buffer-string))))
6366 (defvar org-m nil)
6367 (defvar org-l nil)
6368 (defvar org-f nil)
6369 (defun org-get-level-face (n)
6370 "Get the right face for match N in font-lock matching of headlines."
6371 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6372 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6373 (if org-cycle-level-faces
6374 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6375 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6376 (cond
6377 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6378 ((eq n 2) org-f)
6379 (t (if org-level-color-stars-only nil org-f))))
6382 (defun org-get-todo-face (kwd)
6383 "Get the right face for a TODO keyword KWD.
6384 If KWD is a number, get the corresponding match group."
6385 (if (numberp kwd) (setq kwd (match-string kwd)))
6386 (or (org-face-from-face-or-color
6387 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6388 (and (member kwd org-done-keywords) 'org-done)
6389 'org-todo))
6391 (defun org-face-from-face-or-color (context inherit face-or-color)
6392 "Create a face list that inherits INHERIT, but sets the foreground color.
6393 When FACE-OR-COLOR is not a string, just return it."
6394 (if (stringp face-or-color)
6395 (list :inherit inherit
6396 (cdr (assoc context org-faces-easy-properties))
6397 face-or-color)
6398 face-or-color))
6400 (defun org-font-lock-add-tag-faces (limit)
6401 "Add the special tag faces."
6402 (when (and org-tag-faces org-tags-special-faces-re)
6403 (while (re-search-forward org-tags-special-faces-re limit t)
6404 (add-text-properties (match-beginning 1) (match-end 1)
6405 (list 'face (org-get-tag-face 1)
6406 'font-lock-fontified t))
6407 (backward-char 1))))
6409 (defun org-font-lock-add-priority-faces (limit)
6410 "Add the special priority faces."
6411 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6412 (when (save-match-data (org-at-heading-p))
6413 (add-text-properties
6414 (match-beginning 0) (match-end 0)
6415 (list 'face (or (org-face-from-face-or-color
6416 'priority 'org-priority
6417 (cdr (assoc (char-after (match-beginning 1))
6418 org-priority-faces)))
6419 'org-priority)
6420 'font-lock-fontified t)))))
6422 (defun org-get-tag-face (kwd)
6423 "Get the right face for a TODO keyword KWD.
6424 If KWD is a number, get the corresponding match group."
6425 (if (numberp kwd) (setq kwd (match-string kwd)))
6426 (or (org-face-from-face-or-color
6427 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6428 'org-tag))
6430 (defun org-unfontify-region (beg end &optional maybe_loudly)
6431 "Remove fontification and activation overlays from links."
6432 (font-lock-default-unfontify-region beg end)
6433 (let* ((buffer-undo-list t)
6434 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6435 (inhibit-modification-hooks t)
6436 deactivate-mark buffer-file-name buffer-file-truename)
6437 (org-decompose-region beg end)
6438 (remove-text-properties beg end
6439 '(mouse-face t keymap t org-linked-text t
6440 invisible t intangible t
6441 org-no-flyspell t org-emphasis t))
6442 (org-remove-font-lock-display-properties beg end)))
6444 (defconst org-script-display '(((raise -0.3) (height 0.7))
6445 ((raise 0.3) (height 0.7))
6446 ((raise -0.5))
6447 ((raise 0.5)))
6448 "Display properties for showing superscripts and subscripts.")
6450 (defun org-remove-font-lock-display-properties (beg end)
6451 "Remove specific display properties that have been added by font lock.
6452 The will remove the raise properties that are used to show superscripts
6453 and subscripts."
6454 (let (next prop)
6455 (while (< beg end)
6456 (setq next (next-single-property-change beg 'display nil end)
6457 prop (get-text-property beg 'display))
6458 (if (member prop org-script-display)
6459 (put-text-property beg next 'display nil))
6460 (setq beg next))))
6462 (defun org-raise-scripts (limit)
6463 "Add raise properties to sub/superscripts."
6464 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6465 (if (re-search-forward
6466 (if (eq org-use-sub-superscripts t)
6467 org-match-substring-regexp
6468 org-match-substring-with-braces-regexp)
6469 limit t)
6470 (let* ((pos (point)) table-p comment-p
6471 (mpos (match-beginning 3))
6472 (emph-p (get-text-property mpos 'org-emphasis))
6473 (link-p (get-text-property mpos 'mouse-face))
6474 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6475 (goto-char (point-at-bol))
6476 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6477 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6478 (goto-char pos)
6479 ;; Handle a_b^c
6480 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6481 (if (or comment-p emph-p link-p keyw-p)
6483 (put-text-property (match-beginning 3) (match-end 0)
6484 'display
6485 (if (equal (char-after (match-beginning 2)) ?^)
6486 (nth (if table-p 3 1) org-script-display)
6487 (nth (if table-p 2 0) org-script-display)))
6488 (add-text-properties (match-beginning 2) (match-end 2)
6489 (list 'invisible t
6490 'org-dwidth t 'org-dwidth-n 1))
6491 (if (and (eq (char-after (match-beginning 3)) ?{)
6492 (eq (char-before (match-end 3)) ?}))
6493 (progn
6494 (add-text-properties
6495 (match-beginning 3) (1+ (match-beginning 3))
6496 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6497 (add-text-properties
6498 (1- (match-end 3)) (match-end 3)
6499 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6500 t)))))
6502 ;;;; Visibility cycling, including org-goto and indirect buffer
6504 ;;; Cycling
6506 (defvar org-cycle-global-status nil)
6507 (make-variable-buffer-local 'org-cycle-global-status)
6508 (put 'org-cycle-global-status 'org-state t)
6509 (defvar org-cycle-subtree-status nil)
6510 (make-variable-buffer-local 'org-cycle-subtree-status)
6511 (put 'org-cycle-subtree-status 'org-state t)
6513 (defvar org-inlinetask-min-level)
6515 (defun org-unlogged-message (&rest args)
6516 "Display a message, but avoid logging it in the *Messages* buffer."
6517 (let ((message-log-max nil))
6518 (apply 'message args)))
6520 ;;;###autoload
6521 (defun org-cycle (&optional arg)
6522 "TAB-action and visibility cycling for Org-mode.
6524 This is the command invoked in Org-mode by the TAB key. Its main purpose
6525 is outline visibility cycling, but it also invokes other actions
6526 in special contexts.
6528 - When this function is called with a prefix argument, rotate the entire
6529 buffer through 3 states (global cycling)
6530 1. OVERVIEW: Show only top-level headlines.
6531 2. CONTENTS: Show all headlines of all levels, but no body text.
6532 3. SHOW ALL: Show everything.
6533 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6534 determined by the variable `org-startup-folded', and by any VISIBILITY
6535 properties in the buffer.
6536 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6537 including any drawers.
6539 - When inside a table, re-align the table and move to the next field.
6541 - When point is at the beginning of a headline, rotate the subtree started
6542 by this line through 3 different states (local cycling)
6543 1. FOLDED: Only the main headline is shown.
6544 2. CHILDREN: The main headline and the direct children are shown.
6545 From this state, you can move to one of the children
6546 and zoom in further.
6547 3. SUBTREE: Show the entire subtree, including body text.
6548 If there is no subtree, switch directly from CHILDREN to FOLDED.
6550 - When point is at the beginning of an empty headline and the variable
6551 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6552 of the headline by demoting and promoting it to likely levels. This
6553 speeds up creation document structure by pressing TAB once or several
6554 times right after creating a new headline.
6556 - When there is a numeric prefix, go up to a heading with level ARG, do
6557 a `show-subtree' and return to the previous cursor position. If ARG
6558 is negative, go up that many levels.
6560 - When point is not at the beginning of a headline, execute the global
6561 binding for TAB, which is re-indenting the line. See the option
6562 `org-cycle-emulate-tab' for details.
6564 - Special case: if point is at the beginning of the buffer and there is
6565 no headline in line 1, this function will act as if called with prefix arg
6566 (C-u TAB, same as S-TAB) also when called without prefix arg.
6567 But only if also the variable `org-cycle-global-at-bob' is t."
6568 (interactive "P")
6569 (org-load-modules-maybe)
6570 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6571 (and org-cycle-level-after-item/entry-creation
6572 (or (org-cycle-level)
6573 (org-cycle-item-indentation))))
6574 (let* ((limit-level
6575 (or org-cycle-max-level
6576 (and (boundp 'org-inlinetask-min-level)
6577 org-inlinetask-min-level
6578 (1- org-inlinetask-min-level))))
6579 (nstars (and limit-level
6580 (if org-odd-levels-only
6581 (and limit-level (1- (* limit-level 2)))
6582 limit-level)))
6583 (org-outline-regexp
6584 (if (not (derived-mode-p 'org-mode))
6585 outline-regexp
6586 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6587 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6588 (not (looking-at org-outline-regexp))))
6589 (org-cycle-hook
6590 (if bob-special
6591 (delq 'org-optimize-window-after-visibility-change
6592 (copy-sequence org-cycle-hook))
6593 org-cycle-hook))
6594 (pos (point)))
6596 (if (or bob-special (equal arg '(4)))
6597 ;; special case: use global cycling
6598 (setq arg t))
6600 (cond
6602 ((equal arg '(16))
6603 (setq last-command 'dummy)
6604 (org-set-startup-visibility)
6605 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6607 ((equal arg '(64))
6608 (show-all)
6609 (org-unlogged-message "Entire buffer visible, including drawers"))
6611 ;; Table: enter it or move to the next field.
6612 ((org-at-table-p 'any)
6613 (if (org-at-table.el-p)
6614 (message "Use C-c ' to edit table.el tables")
6615 (if arg (org-table-edit-field t)
6616 (org-table-justify-field-maybe)
6617 (call-interactively 'org-table-next-field))))
6619 ((run-hook-with-args-until-success
6620 'org-tab-after-check-for-table-hook))
6622 ;; Global cycling: delegate to `org-cycle-internal-global'.
6623 ((eq arg t) (org-cycle-internal-global))
6625 ;; Drawers: delegate to `org-flag-drawer'.
6626 ((and org-drawers org-drawer-regexp
6627 (save-excursion
6628 (beginning-of-line 1)
6629 (looking-at org-drawer-regexp)))
6630 (org-flag-drawer ; toggle block visibility
6631 (not (get-char-property (match-end 0) 'invisible))))
6633 ;; Show-subtree, ARG levels up from here.
6634 ((integerp arg)
6635 (save-excursion
6636 (org-back-to-heading)
6637 (outline-up-heading (if (< arg 0) (- arg)
6638 (- (funcall outline-level) arg)))
6639 (org-show-subtree)))
6641 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6642 ((and (featurep 'org-inlinetask)
6643 (org-inlinetask-at-task-p)
6644 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6645 (org-inlinetask-toggle-visibility))
6647 ((org-try-cdlatex-tab))
6649 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6650 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6651 (save-excursion (beginning-of-line 1)
6652 (looking-at org-outline-regexp)))
6653 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6654 (org-cycle-internal-local))
6656 ;; From there: TAB emulation and template completion.
6657 (buffer-read-only (org-back-to-heading))
6659 ((run-hook-with-args-until-success
6660 'org-tab-after-check-for-cycling-hook))
6662 ((org-try-structure-completion))
6664 ((run-hook-with-args-until-success
6665 'org-tab-before-tab-emulation-hook))
6667 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6668 (or (not (bolp))
6669 (not (looking-at org-outline-regexp))))
6670 (call-interactively (global-key-binding "\t")))
6672 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6673 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6674 (or (and (eq org-cycle-emulate-tab 'white)
6675 (= (match-end 0) (point-at-eol)))
6676 (and (eq org-cycle-emulate-tab 'whitestart)
6677 (>= (match-end 0) pos))))
6679 (eq org-cycle-emulate-tab t))
6680 (call-interactively (global-key-binding "\t")))
6682 (t (save-excursion
6683 (org-back-to-heading)
6684 (org-cycle)))))))
6686 (defun org-cycle-internal-global ()
6687 "Do the global cycling action."
6688 ;; Hack to avoid display of messages for .org attachments in Gnus
6689 (let ((ga (string-match "\\*fontification" (buffer-name))))
6690 (cond
6691 ((and (eq last-command this-command)
6692 (eq org-cycle-global-status 'overview))
6693 ;; We just created the overview - now do table of contents
6694 ;; This can be slow in very large buffers, so indicate action
6695 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6696 (unless ga (org-unlogged-message "CONTENTS..."))
6697 (org-content)
6698 (unless ga (org-unlogged-message "CONTENTS...done"))
6699 (setq org-cycle-global-status 'contents)
6700 (run-hook-with-args 'org-cycle-hook 'contents))
6702 ((and (eq last-command this-command)
6703 (eq org-cycle-global-status 'contents))
6704 ;; We just showed the table of contents - now show everything
6705 (run-hook-with-args 'org-pre-cycle-hook 'all)
6706 (show-all)
6707 (unless ga (org-unlogged-message "SHOW ALL"))
6708 (setq org-cycle-global-status 'all)
6709 (run-hook-with-args 'org-cycle-hook 'all))
6712 ;; Default action: go to overview
6713 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6714 (org-overview)
6715 (unless ga (org-unlogged-message "OVERVIEW"))
6716 (setq org-cycle-global-status 'overview)
6717 (run-hook-with-args 'org-cycle-hook 'overview)))))
6719 (defun org-cycle-internal-local ()
6720 "Do the local cycling action."
6721 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6722 ;; First, determine end of headline (EOH), end of subtree or item
6723 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6724 (save-excursion
6725 (if (org-at-item-p)
6726 (progn
6727 (beginning-of-line)
6728 (setq struct (org-list-struct))
6729 (setq eoh (point-at-eol))
6730 (setq eos (org-list-get-item-end-before-blank (point) struct))
6731 (setq has-children (org-list-has-child-p (point) struct)))
6732 (org-back-to-heading)
6733 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6734 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6735 (setq has-children
6736 (or (save-excursion
6737 (let ((level (funcall outline-level)))
6738 (outline-next-heading)
6739 (and (org-at-heading-p t)
6740 (> (funcall outline-level) level))))
6741 (save-excursion
6742 (org-list-search-forward (org-item-beginning-re) eos t)))))
6743 ;; Determine end invisible part of buffer (EOL)
6744 (beginning-of-line 2)
6745 ;; XEmacs doesn't have `next-single-char-property-change'
6746 (if (featurep 'xemacs)
6747 (while (and (not (eobp)) ;; this is like `next-line'
6748 (get-char-property (1- (point)) 'invisible))
6749 (beginning-of-line 2))
6750 (while (and (not (eobp)) ;; this is like `next-line'
6751 (get-char-property (1- (point)) 'invisible))
6752 (goto-char (next-single-char-property-change (point) 'invisible))
6753 (and (eolp) (beginning-of-line 2))))
6754 (setq eol (point)))
6755 ;; Find out what to do next and set `this-command'
6756 (cond
6757 ((= eos eoh)
6758 ;; Nothing is hidden behind this heading
6759 (unless (org-before-first-heading-p)
6760 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6761 (org-unlogged-message "EMPTY ENTRY")
6762 (setq org-cycle-subtree-status nil)
6763 (save-excursion
6764 (goto-char eos)
6765 (outline-next-heading)
6766 (if (outline-invisible-p) (org-flag-heading nil))))
6767 ((and (or (>= eol eos)
6768 (not (string-match "\\S-" (buffer-substring eol eos))))
6769 (or has-children
6770 (not (setq children-skipped
6771 org-cycle-skip-children-state-if-no-children))))
6772 ;; Entire subtree is hidden in one line: children view
6773 (unless (org-before-first-heading-p)
6774 (run-hook-with-args 'org-pre-cycle-hook 'children))
6775 (if (org-at-item-p)
6776 (org-list-set-item-visibility (point-at-bol) struct 'children)
6777 (org-show-entry)
6778 (org-with-limited-levels (show-children))
6779 ;; FIXME: This slows down the func way too much.
6780 ;; How keep drawers hidden in subtree anyway?
6781 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6782 ;; (org-cycle-hide-drawers 'subtree))
6784 ;; Fold every list in subtree to top-level items.
6785 (when (eq org-cycle-include-plain-lists 'integrate)
6786 (save-excursion
6787 (org-back-to-heading)
6788 (while (org-list-search-forward (org-item-beginning-re) eos t)
6789 (beginning-of-line 1)
6790 (let* ((struct (org-list-struct))
6791 (prevs (org-list-prevs-alist struct))
6792 (end (org-list-get-bottom-point struct)))
6793 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6794 (org-list-get-all-items (point) struct prevs))
6795 (goto-char (if (< end eos) end eos)))))))
6796 (org-unlogged-message "CHILDREN")
6797 (save-excursion
6798 (goto-char eos)
6799 (outline-next-heading)
6800 (if (outline-invisible-p) (org-flag-heading nil)))
6801 (setq org-cycle-subtree-status 'children)
6802 (unless (org-before-first-heading-p)
6803 (run-hook-with-args 'org-cycle-hook 'children)))
6804 ((or children-skipped
6805 (and (eq last-command this-command)
6806 (eq org-cycle-subtree-status 'children)))
6807 ;; We just showed the children, or no children are there,
6808 ;; now show everything.
6809 (unless (org-before-first-heading-p)
6810 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6811 (outline-flag-region eoh eos nil)
6812 (org-unlogged-message
6813 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6814 (setq org-cycle-subtree-status 'subtree)
6815 (unless (org-before-first-heading-p)
6816 (run-hook-with-args 'org-cycle-hook 'subtree)))
6818 ;; Default action: hide the subtree.
6819 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6820 (outline-flag-region eoh eos t)
6821 (org-unlogged-message "FOLDED")
6822 (setq org-cycle-subtree-status 'folded)
6823 (unless (org-before-first-heading-p)
6824 (run-hook-with-args 'org-cycle-hook 'folded))))))
6826 ;;;###autoload
6827 (defun org-global-cycle (&optional arg)
6828 "Cycle the global visibility. For details see `org-cycle'.
6829 With \\[universal-argument] prefix arg, switch to startup visibility.
6830 With a numeric prefix, show all headlines up to that level."
6831 (interactive "P")
6832 (let ((org-cycle-include-plain-lists
6833 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6834 (cond
6835 ((integerp arg)
6836 (show-all)
6837 (hide-sublevels arg)
6838 (setq org-cycle-global-status 'contents))
6839 ((equal arg '(4))
6840 (org-set-startup-visibility)
6841 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6843 (org-cycle '(4))))))
6845 (defun org-set-startup-visibility ()
6846 "Set the visibility required by startup options and properties."
6847 (cond
6848 ((eq org-startup-folded t)
6849 (org-cycle '(4)))
6850 ((eq org-startup-folded 'content)
6851 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6852 (org-cycle '(4)) (org-cycle '(4)))))
6853 (unless (eq org-startup-folded 'showeverything)
6854 (if org-hide-block-startup (org-hide-block-all))
6855 (org-set-visibility-according-to-property 'no-cleanup)
6856 (org-cycle-hide-archived-subtrees 'all)
6857 (org-cycle-hide-drawers 'all)
6858 (org-cycle-show-empty-lines t)))
6860 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6861 "Switch subtree visibilities according to :VISIBILITY: property."
6862 (interactive)
6863 (let (org-show-entry-below state)
6864 (save-excursion
6865 (goto-char (point-min))
6866 (while (re-search-forward
6867 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6868 nil t)
6869 (setq state (match-string 1))
6870 (save-excursion
6871 (org-back-to-heading t)
6872 (hide-subtree)
6873 (org-reveal)
6874 (cond
6875 ((equal state '("fold" "folded"))
6876 (hide-subtree))
6877 ((equal state "children")
6878 (org-show-hidden-entry)
6879 (show-children))
6880 ((equal state "content")
6881 (save-excursion
6882 (save-restriction
6883 (org-narrow-to-subtree)
6884 (org-content))))
6885 ((member state '("all" "showall"))
6886 (show-subtree)))))
6887 (unless no-cleanup
6888 (org-cycle-hide-archived-subtrees 'all)
6889 (org-cycle-hide-drawers 'all)
6890 (org-cycle-show-empty-lines 'all)))))
6892 ;; This function uses outline-regexp instead of the more fundamental
6893 ;; org-outline-regexp so that org-cycle-global works outside of Org
6894 ;; buffers, where outline-regexp is needed.
6895 (defun org-overview ()
6896 "Switch to overview mode, showing only top-level headlines.
6897 Really, this shows all headlines with level equal or greater than the level
6898 of the first headline in the buffer. This is important, because if the
6899 first headline is not level one, then (hide-sublevels 1) gives confusing
6900 results."
6901 (interactive)
6902 (let ((pos (point))
6903 (level (save-excursion
6904 (goto-char (point-min))
6905 (if (re-search-forward (concat "^" outline-regexp) nil t)
6906 (progn
6907 (goto-char (match-beginning 0))
6908 (funcall outline-level))))))
6909 (and level (hide-sublevels level))
6910 (recenter '(4))
6911 (goto-char pos)))
6913 (defun org-content (&optional arg)
6914 "Show all headlines in the buffer, like a table of contents.
6915 With numerical argument N, show content up to level N."
6916 (interactive "P")
6917 (save-excursion
6918 ;; Visit all headings and show their offspring
6919 (and (integerp arg) (org-overview))
6920 (goto-char (point-max))
6921 (catch 'exit
6922 (while (and (progn (condition-case nil
6923 (outline-previous-visible-heading 1)
6924 (error (goto-char (point-min))))
6926 (looking-at org-outline-regexp))
6927 (if (integerp arg)
6928 (show-children (1- arg))
6929 (show-branches))
6930 (if (bobp) (throw 'exit nil))))))
6933 (defun org-optimize-window-after-visibility-change (state)
6934 "Adjust the window after a change in outline visibility.
6935 This function is the default value of the hook `org-cycle-hook'."
6936 (when (get-buffer-window (current-buffer))
6937 (cond
6938 ((eq state 'content) nil)
6939 ((eq state 'all) nil)
6940 ((eq state 'folded) nil)
6941 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6942 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6944 (defun org-remove-empty-overlays-at (pos)
6945 "Remove outline overlays that do not contain non-white stuff."
6946 (mapc
6947 (lambda (o)
6948 (and (eq 'outline (overlay-get o 'invisible))
6949 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6950 (overlay-end o))))
6951 (delete-overlay o)))
6952 (overlays-at pos)))
6954 (defun org-clean-visibility-after-subtree-move ()
6955 "Fix visibility issues after moving a subtree."
6956 ;; First, find a reasonable region to look at:
6957 ;; Start two siblings above, end three below
6958 (let* ((beg (save-excursion
6959 (and (org-get-last-sibling)
6960 (org-get-last-sibling))
6961 (point)))
6962 (end (save-excursion
6963 (and (org-get-next-sibling)
6964 (org-get-next-sibling)
6965 (org-get-next-sibling))
6966 (if (org-at-heading-p)
6967 (point-at-eol)
6968 (point))))
6969 (level (looking-at "\\*+"))
6970 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6971 (save-excursion
6972 (save-restriction
6973 (narrow-to-region beg end)
6974 (when re
6975 ;; Properly fold already folded siblings
6976 (goto-char (point-min))
6977 (while (re-search-forward re nil t)
6978 (if (and (not (outline-invisible-p))
6979 (save-excursion
6980 (goto-char (point-at-eol)) (outline-invisible-p)))
6981 (hide-entry))))
6982 (org-cycle-show-empty-lines 'overview)
6983 (org-cycle-hide-drawers 'overview)))))
6985 (defun org-cycle-show-empty-lines (state)
6986 "Show empty lines above all visible headlines.
6987 The region to be covered depends on STATE when called through
6988 `org-cycle-hook'. Lisp program can use t for STATE to get the
6989 entire buffer covered. Note that an empty line is only shown if there
6990 are at least `org-cycle-separator-lines' empty lines before the headline."
6991 (when (not (= org-cycle-separator-lines 0))
6992 (save-excursion
6993 (let* ((n (abs org-cycle-separator-lines))
6994 (re (cond
6995 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6996 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6997 (t (let ((ns (number-to-string (- n 2))))
6998 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6999 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7000 beg end b e)
7001 (cond
7002 ((memq state '(overview contents t))
7003 (setq beg (point-min) end (point-max)))
7004 ((memq state '(children folded))
7005 (setq beg (point) end (progn (org-end-of-subtree t t)
7006 (beginning-of-line 2)
7007 (point)))))
7008 (when beg
7009 (goto-char beg)
7010 (while (re-search-forward re end t)
7011 (unless (get-char-property (match-end 1) 'invisible)
7012 (setq e (match-end 1))
7013 (if (< org-cycle-separator-lines 0)
7014 (setq b (save-excursion
7015 (goto-char (match-beginning 0))
7016 (org-back-over-empty-lines)
7017 (if (save-excursion
7018 (goto-char (max (point-min) (1- (point))))
7019 (org-at-heading-p))
7020 (1- (point))
7021 (point))))
7022 (setq b (match-beginning 1)))
7023 (outline-flag-region b e nil)))))))
7024 ;; Never hide empty lines at the end of the file.
7025 (save-excursion
7026 (goto-char (point-max))
7027 (outline-previous-heading)
7028 (outline-end-of-heading)
7029 (if (and (looking-at "[ \t\n]+")
7030 (= (match-end 0) (point-max)))
7031 (outline-flag-region (point) (match-end 0) nil))))
7033 (defun org-show-empty-lines-in-parent ()
7034 "Move to the parent and re-show empty lines before visible headlines."
7035 (save-excursion
7036 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7037 (org-cycle-show-empty-lines context))))
7039 (defun org-files-list ()
7040 "Return `org-agenda-files' list, plus all open org-mode files.
7041 This is useful for operations that need to scan all of a user's
7042 open and agenda-wise Org files."
7043 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7044 (dolist (buf (buffer-list))
7045 (with-current-buffer buf
7046 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7047 (let ((file (expand-file-name (buffer-file-name))))
7048 (unless (member file files)
7049 (push file files))))))
7050 files))
7052 (defsubst org-entry-beginning-position ()
7053 "Return the beginning position of the current entry."
7054 (save-excursion (outline-back-to-heading t) (point)))
7056 (defsubst org-entry-end-position ()
7057 "Return the end position of the current entry."
7058 (save-excursion (outline-next-heading) (point)))
7060 (defun org-cycle-hide-drawers (state)
7061 "Re-hide all drawers after a visibility state change."
7062 (when (and (derived-mode-p 'org-mode)
7063 (not (memq state '(overview folded contents))))
7064 (save-excursion
7065 (let* ((globalp (memq state '(contents all)))
7066 (beg (if globalp (point-min) (point)))
7067 (end (if globalp (point-max)
7068 (if (eq state 'children)
7069 (save-excursion (outline-next-heading) (point))
7070 (org-end-of-subtree t)))))
7071 (goto-char beg)
7072 (while (re-search-forward org-drawer-regexp end t)
7073 (org-flag-drawer t))))))
7075 (defun org-cycle-hide-inline-tasks (state)
7076 "Re-hide inline task when switching to 'contents visibility state."
7077 (when (and (eq state 'contents)
7078 (boundp 'org-inlinetask-min-level)
7079 org-inlinetask-min-level)
7080 (hide-sublevels (1- org-inlinetask-min-level))))
7082 (defun org-flag-drawer (flag)
7083 "When FLAG is non-nil, hide the drawer we are within.
7084 Otherwise make it visible."
7085 (save-excursion
7086 (beginning-of-line 1)
7087 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7088 (let ((b (match-end 0)))
7089 (if (re-search-forward
7090 "^[ \t]*:END:"
7091 (save-excursion (outline-next-heading) (point)) t)
7092 (outline-flag-region b (point-at-eol) flag)
7093 (user-error ":END: line missing at position %s" b))))))
7095 (defun org-subtree-end-visible-p ()
7096 "Is the end of the current subtree visible?"
7097 (pos-visible-in-window-p
7098 (save-excursion (org-end-of-subtree t) (point))))
7100 (defun org-first-headline-recenter (&optional N)
7101 "Move cursor to the first headline and recenter the headline.
7102 Optional argument N means put the headline into the Nth line of the window."
7103 (goto-char (point-min))
7104 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7105 (beginning-of-line)
7106 (recenter (prefix-numeric-value N))))
7108 ;;; Saving and restoring visibility
7110 (defun org-outline-overlay-data (&optional use-markers)
7111 "Return a list of the locations of all outline overlays.
7112 These are overlays with the `invisible' property value `outline'.
7113 The return value is a list of cons cells, with start and stop
7114 positions for each overlay.
7115 If USE-MARKERS is set, return the positions as markers."
7116 (let (beg end)
7117 (save-excursion
7118 (save-restriction
7119 (widen)
7120 (delq nil
7121 (mapcar (lambda (o)
7122 (when (eq (overlay-get o 'invisible) 'outline)
7123 (setq beg (overlay-start o)
7124 end (overlay-end o))
7125 (and beg end (> end beg)
7126 (if use-markers
7127 (cons (move-marker (make-marker) beg)
7128 (move-marker (make-marker) end))
7129 (cons beg end)))))
7130 (overlays-in (point-min) (point-max))))))))
7132 (defun org-set-outline-overlay-data (data)
7133 "Create visibility overlays for all positions in DATA.
7134 DATA should have been made by `org-outline-overlay-data'."
7135 (let (o)
7136 (save-excursion
7137 (save-restriction
7138 (widen)
7139 (show-all)
7140 (mapc (lambda (c)
7141 (outline-flag-region (car c) (cdr c) t))
7142 data)))))
7144 ;;; Folding of blocks
7146 (defvar org-hide-block-overlays nil
7147 "Overlays hiding blocks.")
7148 (make-variable-buffer-local 'org-hide-block-overlays)
7150 (defun org-block-map (function &optional start end)
7151 "Call FUNCTION at the head of all source blocks in the current buffer.
7152 Optional arguments START and END can be used to limit the range."
7153 (let ((start (or start (point-min)))
7154 (end (or end (point-max))))
7155 (save-excursion
7156 (goto-char start)
7157 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7158 (save-excursion
7159 (save-match-data
7160 (goto-char (match-beginning 0))
7161 (funcall function)))))))
7163 (defun org-hide-block-toggle-all ()
7164 "Toggle the visibility of all blocks in the current buffer."
7165 (org-block-map #'org-hide-block-toggle))
7167 (defun org-hide-block-all ()
7168 "Fold all blocks in the current buffer."
7169 (interactive)
7170 (org-show-block-all)
7171 (org-block-map #'org-hide-block-toggle-maybe))
7173 (defun org-show-block-all ()
7174 "Unfold all blocks in the current buffer."
7175 (interactive)
7176 (mapc 'delete-overlay org-hide-block-overlays)
7177 (setq org-hide-block-overlays nil))
7179 (defun org-hide-block-toggle-maybe ()
7180 "Toggle visibility of block at point."
7181 (interactive)
7182 (let ((case-fold-search t))
7183 (if (save-excursion
7184 (beginning-of-line 1)
7185 (looking-at org-block-regexp))
7186 (progn (org-hide-block-toggle)
7187 t) ;; to signal that we took action
7188 nil))) ;; to signal that we did not
7190 (defun org-hide-block-toggle (&optional force)
7191 "Toggle the visibility of the current block."
7192 (interactive)
7193 (save-excursion
7194 (beginning-of-line)
7195 (if (re-search-forward org-block-regexp nil t)
7196 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7197 (end (match-end 0)) ;; end of entire body
7199 (if (memq t (mapcar (lambda (overlay)
7200 (eq (overlay-get overlay 'invisible)
7201 'org-hide-block))
7202 (overlays-at start)))
7203 (if (or (not force) (eq force 'off))
7204 (mapc (lambda (ov)
7205 (when (member ov org-hide-block-overlays)
7206 (setq org-hide-block-overlays
7207 (delq ov org-hide-block-overlays)))
7208 (when (eq (overlay-get ov 'invisible)
7209 'org-hide-block)
7210 (delete-overlay ov)))
7211 (overlays-at start)))
7212 (setq ov (make-overlay start end))
7213 (overlay-put ov 'invisible 'org-hide-block)
7214 ;; make the block accessible to isearch
7215 (overlay-put
7216 ov 'isearch-open-invisible
7217 (lambda (ov)
7218 (when (member ov org-hide-block-overlays)
7219 (setq org-hide-block-overlays
7220 (delq ov org-hide-block-overlays)))
7221 (when (eq (overlay-get ov 'invisible)
7222 'org-hide-block)
7223 (delete-overlay ov))))
7224 (push ov org-hide-block-overlays)))
7225 (user-error "Not looking at a source block"))))
7227 ;; org-tab-after-check-for-cycling-hook
7228 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7229 ;; Remove overlays when changing major mode
7230 (add-hook 'org-mode-hook
7231 (lambda () (org-add-hook 'change-major-mode-hook
7232 'org-show-block-all 'append 'local)))
7234 ;;; Org-goto
7236 (defvar org-goto-window-configuration nil)
7237 (defvar org-goto-marker nil)
7238 (defvar org-goto-map)
7239 (defun org-goto-map ()
7240 "Set the keymap `org-goto'."
7241 (setq org-goto-map
7242 (let ((map (make-sparse-keymap)))
7243 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7244 mouse-drag-region universal-argument org-occur))
7245 cmd)
7246 (while (setq cmd (pop cmds))
7247 (substitute-key-definition cmd cmd map global-map)))
7248 (suppress-keymap map)
7249 (org-defkey map "\C-m" 'org-goto-ret)
7250 (org-defkey map [(return)] 'org-goto-ret)
7251 (org-defkey map [(left)] 'org-goto-left)
7252 (org-defkey map [(right)] 'org-goto-right)
7253 (org-defkey map [(control ?g)] 'org-goto-quit)
7254 (org-defkey map "\C-i" 'org-cycle)
7255 (org-defkey map [(tab)] 'org-cycle)
7256 (org-defkey map [(down)] 'outline-next-visible-heading)
7257 (org-defkey map [(up)] 'outline-previous-visible-heading)
7258 (if org-goto-auto-isearch
7259 (if (fboundp 'define-key-after)
7260 (define-key-after map [t] 'org-goto-local-auto-isearch)
7261 nil)
7262 (org-defkey map "q" 'org-goto-quit)
7263 (org-defkey map "n" 'outline-next-visible-heading)
7264 (org-defkey map "p" 'outline-previous-visible-heading)
7265 (org-defkey map "f" 'outline-forward-same-level)
7266 (org-defkey map "b" 'outline-backward-same-level)
7267 (org-defkey map "u" 'outline-up-heading))
7268 (org-defkey map "/" 'org-occur)
7269 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7270 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7271 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7272 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7273 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7274 map)))
7276 (defconst org-goto-help
7277 "Browse buffer copy, to find location or copy text.%s
7278 RET=jump to location C-g=quit and return to previous location
7279 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7281 (defvar org-goto-start-pos) ; dynamically scoped parameter
7283 (defun org-goto (&optional alternative-interface)
7284 "Look up a different location in the current file, keeping current visibility.
7286 When you want look-up or go to a different location in a
7287 document, the fastest way is often to fold the entire buffer and
7288 then dive into the tree. This method has the disadvantage, that
7289 the previous location will be folded, which may not be what you
7290 want.
7292 This command works around this by showing a copy of the current
7293 buffer in an indirect buffer, in overview mode. You can dive
7294 into the tree in that copy, use org-occur and incremental search
7295 to find a location. When pressing RET or `Q', the command
7296 returns to the original buffer in which the visibility is still
7297 unchanged. After RET it will also jump to the location selected
7298 in the indirect buffer and expose the headline hierarchy above.
7300 With a prefix argument, use the alternative interface: e.g. if
7301 `org-goto-interface' is 'outline use 'outline-path-completion."
7302 (interactive "P")
7303 (org-goto-map)
7304 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7305 (org-refile-use-outline-path t)
7306 (org-refile-target-verify-function nil)
7307 (interface
7308 (if (not alternative-interface)
7309 org-goto-interface
7310 (if (eq org-goto-interface 'outline)
7311 'outline-path-completion
7312 'outline)))
7313 (org-goto-start-pos (point))
7314 (selected-point
7315 (if (eq interface 'outline)
7316 (car (org-get-location (current-buffer) org-goto-help))
7317 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7318 (org-refile-check-position pa)
7319 (nth 3 pa)))))
7320 (if selected-point
7321 (progn
7322 (org-mark-ring-push org-goto-start-pos)
7323 (goto-char selected-point)
7324 (if (or (outline-invisible-p) (org-invisible-p2))
7325 (org-show-context 'org-goto)))
7326 (message "Quit"))))
7328 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7329 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7330 (defvar org-goto-local-auto-isearch-map) ; defined below
7332 (defun org-get-location (buf help)
7333 "Let the user select a location in the Org-mode buffer BUF.
7334 This function uses a recursive edit. It returns the selected position
7335 or nil."
7336 (org-no-popups
7337 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7338 (isearch-hide-immediately nil)
7339 (isearch-search-fun-function
7340 (lambda () 'org-goto-local-search-headings))
7341 (org-goto-selected-point org-goto-exit-command))
7342 (save-excursion
7343 (save-window-excursion
7344 (delete-other-windows)
7345 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7346 (org-pop-to-buffer-same-window
7347 (condition-case nil
7348 (make-indirect-buffer (current-buffer) "*org-goto*")
7349 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7350 (with-output-to-temp-buffer "*Org Help*"
7351 (princ (format help (if org-goto-auto-isearch
7352 " Just type for auto-isearch."
7353 " n/p/f/b/u to navigate, q to quit."))))
7354 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7355 (setq buffer-read-only nil)
7356 (let ((org-startup-truncated t)
7357 (org-startup-folded nil)
7358 (org-startup-align-all-tables nil))
7359 (org-mode)
7360 (org-overview))
7361 (setq buffer-read-only t)
7362 (if (and (boundp 'org-goto-start-pos)
7363 (integer-or-marker-p org-goto-start-pos))
7364 (let ((org-show-hierarchy-above t)
7365 (org-show-siblings t)
7366 (org-show-following-heading t))
7367 (goto-char org-goto-start-pos)
7368 (and (outline-invisible-p) (org-show-context)))
7369 (goto-char (point-min)))
7370 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7371 (message "Select location and press RET")
7372 (use-local-map org-goto-map)
7373 (recursive-edit)))
7374 (kill-buffer "*org-goto*")
7375 (cons org-goto-selected-point org-goto-exit-command))))
7377 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7378 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7379 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7380 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7382 (defun org-goto-local-search-headings (string bound noerror)
7383 "Search and make sure that any matches are in headlines."
7384 (catch 'return
7385 (while (if isearch-forward
7386 (search-forward string bound noerror)
7387 (search-backward string bound noerror))
7388 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7389 (and (member :headline context)
7390 (not (member :tags context))))
7391 (throw 'return (point))))))
7393 (defun org-goto-local-auto-isearch ()
7394 "Start isearch."
7395 (interactive)
7396 (goto-char (point-min))
7397 (let ((keys (this-command-keys)))
7398 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7399 (isearch-mode t)
7400 (isearch-process-search-char (string-to-char keys)))))
7402 (defun org-goto-ret (&optional arg)
7403 "Finish `org-goto' by going to the new location."
7404 (interactive "P")
7405 (setq org-goto-selected-point (point)
7406 org-goto-exit-command 'return)
7407 (throw 'exit nil))
7409 (defun org-goto-left ()
7410 "Finish `org-goto' by going to the new location."
7411 (interactive)
7412 (if (org-at-heading-p)
7413 (progn
7414 (beginning-of-line 1)
7415 (setq org-goto-selected-point (point)
7416 org-goto-exit-command 'left)
7417 (throw 'exit nil))
7418 (user-error "Not on a heading")))
7420 (defun org-goto-right ()
7421 "Finish `org-goto' by going to the new location."
7422 (interactive)
7423 (if (org-at-heading-p)
7424 (progn
7425 (setq org-goto-selected-point (point)
7426 org-goto-exit-command 'right)
7427 (throw 'exit nil))
7428 (user-error "Not on a heading")))
7430 (defun org-goto-quit ()
7431 "Finish `org-goto' without cursor motion."
7432 (interactive)
7433 (setq org-goto-selected-point nil)
7434 (setq org-goto-exit-command 'quit)
7435 (throw 'exit nil))
7437 ;;; Indirect buffer display of subtrees
7439 (defvar org-indirect-dedicated-frame nil
7440 "This is the frame being used for indirect tree display.")
7441 (defvar org-last-indirect-buffer nil)
7443 (defun org-tree-to-indirect-buffer (&optional arg)
7444 "Create indirect buffer and narrow it to current subtree.
7445 With a numerical prefix ARG, go up to this level and then take that tree.
7446 If ARG is negative, go up that many levels.
7448 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7449 indirect buffer previously made with this command, to avoid proliferation of
7450 indirect buffers. However, when you call the command with a \
7451 \\[universal-argument] prefix, or
7452 when `org-indirect-buffer-display' is `new-frame', the last buffer
7453 is kept so that you can work with several indirect buffers at the same time.
7454 If `org-indirect-buffer-display' is `dedicated-frame', the \
7455 \\[universal-argument] prefix also
7456 requests that a new frame be made for the new buffer, so that the dedicated
7457 frame is not changed."
7458 (interactive "P")
7459 (let ((cbuf (current-buffer))
7460 (cwin (selected-window))
7461 (pos (point))
7462 beg end level heading ibuf)
7463 (save-excursion
7464 (org-back-to-heading t)
7465 (when (numberp arg)
7466 (setq level (org-outline-level))
7467 (if (< arg 0) (setq arg (+ level arg)))
7468 (while (> (setq level (org-outline-level)) arg)
7469 (org-up-heading-safe)))
7470 (setq beg (point)
7471 heading (org-get-heading))
7472 (org-end-of-subtree t t)
7473 (if (org-at-heading-p) (backward-char 1))
7474 (setq end (point)))
7475 (if (and (buffer-live-p org-last-indirect-buffer)
7476 (not (eq org-indirect-buffer-display 'new-frame))
7477 (not arg))
7478 (kill-buffer org-last-indirect-buffer))
7479 (setq ibuf (org-get-indirect-buffer cbuf)
7480 org-last-indirect-buffer ibuf)
7481 (cond
7482 ((or (eq org-indirect-buffer-display 'new-frame)
7483 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7484 (select-frame (make-frame))
7485 (delete-other-windows)
7486 (org-pop-to-buffer-same-window ibuf)
7487 (org-set-frame-title heading))
7488 ((eq org-indirect-buffer-display 'dedicated-frame)
7489 (raise-frame
7490 (select-frame (or (and org-indirect-dedicated-frame
7491 (frame-live-p org-indirect-dedicated-frame)
7492 org-indirect-dedicated-frame)
7493 (setq org-indirect-dedicated-frame (make-frame)))))
7494 (delete-other-windows)
7495 (org-pop-to-buffer-same-window ibuf)
7496 (org-set-frame-title (concat "Indirect: " heading)))
7497 ((eq org-indirect-buffer-display 'current-window)
7498 (org-pop-to-buffer-same-window ibuf))
7499 ((eq org-indirect-buffer-display 'other-window)
7500 (pop-to-buffer ibuf))
7501 (t (error "Invalid value")))
7502 (if (featurep 'xemacs)
7503 (save-excursion (org-mode) (turn-on-font-lock)))
7504 (narrow-to-region beg end)
7505 (show-all)
7506 (goto-char pos)
7507 (run-hook-with-args 'org-cycle-hook 'all)
7508 (and (window-live-p cwin) (select-window cwin))))
7510 (defun org-get-indirect-buffer (&optional buffer)
7511 (setq buffer (or buffer (current-buffer)))
7512 (let ((n 1) (base (buffer-name buffer)) bname)
7513 (while (buffer-live-p
7514 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7515 (setq n (1+ n)))
7516 (condition-case nil
7517 (make-indirect-buffer buffer bname 'clone)
7518 (error (make-indirect-buffer buffer bname)))))
7520 (defun org-set-frame-title (title)
7521 "Set the title of the current frame to the string TITLE."
7522 ;; FIXME: how to name a single frame in XEmacs???
7523 (unless (featurep 'xemacs)
7524 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7526 ;;;; Structure editing
7528 ;;; Inserting headlines
7530 (defun org-previous-line-empty-p (&optional next)
7531 "Is the previous line a blank line?
7532 When NEXT is non-nil, check the next line instead."
7533 (save-excursion
7534 (and (not (bobp))
7535 (or (beginning-of-line (if next 2 0)) t)
7536 (save-match-data
7537 (looking-at "[ \t]*$")))))
7539 (defun org-insert-heading (&optional arg invisible-ok)
7540 "Insert a new heading or item with same depth at point.
7541 If point is in a plain list and ARG is nil, create a new list item.
7542 With one universal prefix argument, insert a heading even in lists.
7543 With two universal prefix arguments, insert the heading at the end
7544 of the parent subtree.
7546 If point is at the beginning of a headline, insert a sibling before
7547 the current headline. If point is not at the beginning, split the line
7548 and create a new headline with the text in the current line after point
7549 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7551 If point is at the beginning of a normal line, turn this line into
7552 a heading.
7554 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7555 This is important for non-interactive uses of the command."
7556 (interactive "P")
7557 (if (org-called-interactively-p 'any) (org-reveal))
7558 (let ((itemp (org-in-item-p))
7559 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7560 (respect-content (or org-insert-heading-respect-content
7561 (equal arg '(16))))
7562 (initial-content "")
7563 (adjust-empty-lines t))
7565 (cond
7567 ((or (= (buffer-size) 0)
7568 (and (not (save-excursion
7569 (and (ignore-errors (org-back-to-heading invisible-ok))
7570 (org-at-heading-p))))
7571 (or arg (not itemp))))
7572 ;; At beginning of buffer or so high up that only a heading
7573 ;; makes sense.
7574 (insert
7575 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7576 (if (org-in-src-block-p) ",* " "* "))
7577 (run-hooks 'org-insert-heading-hook))
7579 ((and itemp (not (equal arg '(4))))
7580 ;; Insert an item
7581 (org-insert-item))
7584 ;; Insert a heading
7585 (save-restriction
7586 (widen)
7587 (let* ((level nil)
7588 (on-heading (org-at-heading-p))
7589 (empty-line-p (if on-heading
7590 (org-previous-line-empty-p)
7591 ;; We will decide later
7592 nil))
7593 ;; Get a level string to fall back on
7594 (fix-level
7595 (save-excursion
7596 (org-back-to-heading t)
7597 (if (org-previous-line-empty-p) (setq empty-line-p t))
7598 (looking-at org-outline-regexp)
7599 (make-string (1- (length (match-string 0))) ?*)))
7600 (stars
7601 (save-excursion
7602 (condition-case nil
7603 (progn
7604 (org-back-to-heading invisible-ok)
7605 (when (and (not on-heading)
7606 (featurep 'org-inlinetask)
7607 (integerp org-inlinetask-min-level)
7608 (>= (length (match-string 0))
7609 org-inlinetask-min-level))
7610 ;; Find a heading level before the inline task
7611 (while (and (setq level (org-up-heading-safe))
7612 (>= level org-inlinetask-min-level)))
7613 (if (org-at-heading-p)
7614 (org-back-to-heading invisible-ok)
7615 (error "This should not happen")))
7616 (unless (and (save-excursion
7617 (save-match-data
7618 (org-backward-heading-same-level
7619 1 invisible-ok))
7620 (= (point) (match-beginning 0)))
7621 (not (org-previous-line-empty-p t)))
7622 (setq empty-line-p (or empty-line-p
7623 (org-previous-line-empty-p))))
7624 (match-string 0))
7625 (error (or fix-level "* ")))))
7626 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7627 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7628 pos hide-previous previous-pos)
7630 ;; If we insert after content, move there and clean up whitespace
7631 (when respect-content
7632 (org-end-of-subtree nil t)
7633 (skip-chars-backward " \r\n")
7634 (and (looking-at "[ \t]+") (replace-match ""))
7635 (unless (eobp) (forward-char 1))
7636 (when (looking-at "^\\*")
7637 (unless (bobp) (backward-char 1))
7638 (insert "\n")))
7640 ;; If we are splitting, grab the text that should be moved to the new headline
7641 (when may-split
7642 (if (org-on-heading-p)
7643 ;; This is a heading, we split intelligently (keeping tags)
7644 (let ((pos (point)))
7645 (goto-char (point-at-bol))
7646 (unless (looking-at org-complex-heading-regexp)
7647 (error "This should not happen"))
7648 (when (and (match-beginning 4)
7649 (> pos (match-beginning 4))
7650 (< pos (match-end 4)))
7651 (setq initial-content (buffer-substring pos (match-end 4)))
7652 (goto-char pos)
7653 (delete-region (point) (match-end 4))
7654 (if (looking-at "[ \t]*$")
7655 (replace-match "")
7656 (insert (make-string (length initial-content) ?\ )))
7657 (setq initial-content (org-trim initial-content)))
7658 (goto-char pos))
7659 ;; a normal line
7660 (unless (bolp)
7661 (setq initial-content (buffer-substring (point) (point-at-eol)))
7662 (delete-region (point) (point-at-eol))
7663 (setq initial-content (org-trim initial-content)))))
7665 ;; If we are at the beginning of the line, insert before it. Else after
7666 (cond
7667 ((and (bolp) (looking-at "[ \t]*$")))
7668 ((and (bolp) (not (looking-at "[ \t]*$")))
7669 (open-line 1))
7671 (goto-char (point-at-eol))
7672 (insert "\n")))
7674 ;; Insert the new heading
7675 (insert stars)
7676 (just-one-space)
7677 (insert initial-content)
7678 (when adjust-empty-lines
7679 (if (or (not blank)
7680 (and blank (not (org-previous-line-empty-p))))
7681 (org-N-empty-lines-before-current (if blank 1 0))))
7682 (run-hooks 'org-insert-heading-hook)))))))
7684 (defun org-N-empty-lines-before-current (N)
7685 "Make the number of empty lines before current exactly N.
7686 So this will delete or add empty lines."
7687 (save-excursion
7688 (goto-char (point-at-bol))
7689 (if (looking-back "\\s-+" nil 'greedy)
7690 (replace-match ""))
7691 (or (bobp) (insert "\n"))
7692 (while (> N 0)
7693 (insert "\n")
7694 (setq N (1- N)))))
7696 (defun org-get-heading (&optional no-tags no-todo)
7697 "Return the heading of the current entry, without the stars.
7698 When NO-TAGS is non-nil, don't include tags.
7699 When NO-TODO is non-nil, don't include TODO keywords."
7700 (save-excursion
7701 (org-back-to-heading t)
7702 (cond
7703 ((and no-tags no-todo)
7704 (looking-at org-complex-heading-regexp)
7705 (match-string 4))
7706 (no-tags
7707 (looking-at (concat org-outline-regexp
7708 "\\(.*?\\)"
7709 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7710 (match-string 1))
7711 (no-todo
7712 (looking-at org-todo-line-regexp)
7713 (match-string 3))
7714 (t (looking-at org-heading-regexp)
7715 (match-string 2)))))
7717 (defvar orgstruct-mode) ; defined below
7719 (defun org-heading-components ()
7720 "Return the components of the current heading.
7721 This is a list with the following elements:
7722 - the level as an integer
7723 - the reduced level, different if `org-odd-levels-only' is set.
7724 - the TODO keyword, or nil
7725 - the priority character, like ?A, or nil if no priority is given
7726 - the headline text itself, or the tags string if no headline text
7727 - the tags string, or nil."
7728 (save-excursion
7729 (org-back-to-heading t)
7730 (if (let (case-fold-search)
7731 (looking-at
7732 (if orgstruct-mode
7733 org-heading-regexp
7734 org-complex-heading-regexp)))
7735 (if orgstruct-mode
7736 (list (length (match-string 1))
7737 (org-reduced-level (length (match-string 1)))
7740 (match-string 2)
7741 nil)
7742 (list (length (match-string 1))
7743 (org-reduced-level (length (match-string 1)))
7744 (org-match-string-no-properties 2)
7745 (and (match-end 3) (aref (match-string 3) 2))
7746 (org-match-string-no-properties 4)
7747 (org-match-string-no-properties 5))))))
7749 (defun org-get-entry ()
7750 "Get the entry text, after heading, entire subtree."
7751 (save-excursion
7752 (org-back-to-heading t)
7753 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7755 (defun org-insert-heading-after-current ()
7756 "Insert a new heading with same level as current, after current subtree."
7757 (interactive)
7758 (org-back-to-heading)
7759 (org-insert-heading)
7760 (org-move-subtree-down)
7761 (end-of-line 1))
7763 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7764 "Insert heading with `org-insert-heading-respect-content' set to t."
7765 (interactive "P")
7766 (let ((org-insert-heading-respect-content t))
7767 (org-insert-heading '(4) invisible-ok)))
7769 (defun org-insert-todo-heading-respect-content (&optional force-state)
7770 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7771 (interactive "P")
7772 (let ((org-insert-heading-respect-content t))
7773 (org-insert-todo-heading force-state '(4))))
7775 (defun org-insert-todo-heading (arg &optional force-heading)
7776 "Insert a new heading with the same level and TODO state as current heading.
7777 If the heading has no TODO state, or if the state is DONE, use the first
7778 state (TODO by default). Also one prefix arg, force first state. With two
7779 prefix args, force inserting at the end of the parent subtree."
7780 (interactive "P")
7781 (when (or force-heading (not (org-insert-item 'checkbox)))
7782 (org-insert-heading (or (and (equal arg '(16)) '(16))
7783 force-heading))
7784 (save-excursion
7785 (org-back-to-heading)
7786 (outline-previous-heading)
7787 (looking-at org-todo-line-regexp))
7788 (let*
7789 ((new-mark-x
7790 (if (or arg
7791 (not (match-beginning 2))
7792 (member (match-string 2) org-done-keywords))
7793 (car org-todo-keywords-1)
7794 (match-string 2)))
7795 (new-mark
7797 (run-hook-with-args-until-success
7798 'org-todo-get-default-hook new-mark-x nil)
7799 new-mark-x)))
7800 (beginning-of-line 1)
7801 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7802 (if org-treat-insert-todo-heading-as-state-change
7803 (org-todo new-mark)
7804 (insert new-mark " "))))
7805 (when org-provide-todo-statistics
7806 (org-update-parent-todo-statistics))))
7808 (defun org-insert-subheading (arg)
7809 "Insert a new subheading and demote it.
7810 Works for outline headings and for plain lists alike."
7811 (interactive "P")
7812 (org-insert-heading arg)
7813 (cond
7814 ((org-at-heading-p) (org-do-demote))
7815 ((org-at-item-p) (org-indent-item))))
7817 (defun org-insert-todo-subheading (arg)
7818 "Insert a new subheading with TODO keyword or checkbox and demote it.
7819 Works for outline headings and for plain lists alike."
7820 (interactive "P")
7821 (org-insert-todo-heading arg)
7822 (cond
7823 ((org-at-heading-p) (org-do-demote))
7824 ((org-at-item-p) (org-indent-item))))
7826 ;;; Promotion and Demotion
7828 (defvar org-after-demote-entry-hook nil
7829 "Hook run after an entry has been demoted.
7830 The cursor will be at the beginning of the entry.
7831 When a subtree is being demoted, the hook will be called for each node.")
7833 (defvar org-after-promote-entry-hook nil
7834 "Hook run after an entry has been promoted.
7835 The cursor will be at the beginning of the entry.
7836 When a subtree is being promoted, the hook will be called for each node.")
7838 (defun org-promote-subtree ()
7839 "Promote the entire subtree.
7840 See also `org-promote'."
7841 (interactive)
7842 (save-excursion
7843 (org-with-limited-levels (org-map-tree 'org-promote)))
7844 (org-fix-position-after-promote))
7846 (defun org-demote-subtree ()
7847 "Demote the entire subtree. See `org-demote'.
7848 See also `org-promote'."
7849 (interactive)
7850 (save-excursion
7851 (org-with-limited-levels (org-map-tree 'org-demote)))
7852 (org-fix-position-after-promote))
7855 (defun org-do-promote ()
7856 "Promote the current heading higher up the tree.
7857 If the region is active in `transient-mark-mode', promote all headings
7858 in the region."
7859 (interactive)
7860 (save-excursion
7861 (if (org-region-active-p)
7862 (org-map-region 'org-promote (region-beginning) (region-end))
7863 (org-promote)))
7864 (org-fix-position-after-promote))
7866 (defun org-do-demote ()
7867 "Demote the current heading lower down the tree.
7868 If the region is active in `transient-mark-mode', demote all headings
7869 in the region."
7870 (interactive)
7871 (save-excursion
7872 (if (org-region-active-p)
7873 (org-map-region 'org-demote (region-beginning) (region-end))
7874 (org-demote)))
7875 (org-fix-position-after-promote))
7877 (defun org-fix-position-after-promote ()
7878 "Make sure that after pro/demotion cursor position is right."
7879 (let ((pos (point)))
7880 (when (save-excursion
7881 (beginning-of-line 1)
7882 (looking-at org-todo-line-regexp)
7883 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7884 (cond ((eobp) (insert " "))
7885 ((eolp) (insert " "))
7886 ((equal (char-after) ?\ ) (forward-char 1))))))
7888 (defun org-current-level ()
7889 "Return the level of the current entry, or nil if before the first headline.
7890 The level is the number of stars at the beginning of the headline."
7891 (save-excursion
7892 (org-with-limited-levels
7893 (if (ignore-errors (org-back-to-heading t))
7894 (funcall outline-level)))))
7896 (defun org-get-previous-line-level ()
7897 "Return the outline depth of the last headline before the current line.
7898 Returns 0 for the first headline in the buffer, and nil if before the
7899 first headline."
7900 (let ((current-level (org-current-level))
7901 (prev-level (when (> (line-number-at-pos) 1)
7902 (save-excursion
7903 (beginning-of-line 0)
7904 (org-current-level)))))
7905 (cond ((null current-level) nil) ; Before first headline
7906 ((null prev-level) 0) ; At first headline
7907 (prev-level))))
7909 (defun org-reduced-level (l)
7910 "Compute the effective level of a heading.
7911 This takes into account the setting of `org-odd-levels-only'."
7912 (cond
7913 ((zerop l) 0)
7914 (org-odd-levels-only (1+ (floor (/ l 2))))
7915 (t l)))
7917 (defun org-level-increment ()
7918 "Return the number of stars that will be added or removed at a
7919 time to headlines when structure editing, based on the value of
7920 `org-odd-levels-only'."
7921 (if org-odd-levels-only 2 1))
7923 (defun org-get-valid-level (level &optional change)
7924 "Rectify a level change under the influence of `org-odd-levels-only'
7925 LEVEL is a current level, CHANGE is by how much the level should be
7926 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7927 even level numbers will become the next higher odd number."
7928 (if org-odd-levels-only
7929 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7930 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7931 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7932 (max 1 (+ level (or change 0)))))
7934 (if (boundp 'define-obsolete-function-alias)
7935 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7936 (define-obsolete-function-alias 'org-get-legal-level
7937 'org-get-valid-level)
7938 (define-obsolete-function-alias 'org-get-legal-level
7939 'org-get-valid-level "23.1")))
7941 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7942 ;; ̀org-with-limited-levels'
7943 (defun org-promote ()
7944 "Promote the current heading higher up the tree.
7945 If the region is active in `transient-mark-mode', promote all headings
7946 in the region."
7947 (org-back-to-heading t)
7948 (let* ((level (save-match-data (funcall outline-level)))
7949 (after-change-functions (remove 'flyspell-after-change-function
7950 after-change-functions))
7951 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7952 (diff (abs (- level (length up-head) -1))))
7953 (cond ((and (= level 1) org-called-with-limited-levels
7954 org-allow-promoting-top-level-subtree)
7955 (replace-match "# " nil t))
7956 ((= level 1)
7957 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7958 (t (replace-match up-head nil t)))
7959 ;; Fixup tag positioning
7960 (unless (= level 1)
7961 (and org-auto-align-tags (org-set-tags nil t))
7962 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7963 (run-hooks 'org-after-promote-entry-hook)))
7965 (defun org-demote ()
7966 "Demote the current heading lower down the tree.
7967 If the region is active in `transient-mark-mode', demote all headings
7968 in the region."
7969 (org-back-to-heading t)
7970 (let* ((level (save-match-data (funcall outline-level)))
7971 (after-change-functions (remove 'flyspell-after-change-function
7972 after-change-functions))
7973 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7974 (diff (abs (- level (length down-head) -1))))
7975 (replace-match down-head nil t)
7976 ;; Fixup tag positioning
7977 (and org-auto-align-tags (org-set-tags nil t))
7978 (if org-adapt-indentation (org-fixup-indentation diff))
7979 (run-hooks 'org-after-demote-entry-hook)))
7981 (defun org-cycle-level ()
7982 "Cycle the level of an empty headline through possible states.
7983 This goes first to child, then to parent, level, then up the hierarchy.
7984 After top level, it switches back to sibling level."
7985 (interactive)
7986 (let ((org-adapt-indentation nil))
7987 (when (org-point-at-end-of-empty-headline)
7988 (setq this-command 'org-cycle-level) ; Only needed for caching
7989 (let ((cur-level (org-current-level))
7990 (prev-level (org-get-previous-line-level)))
7991 (cond
7992 ;; If first headline in file, promote to top-level.
7993 ((= prev-level 0)
7994 (loop repeat (/ (- cur-level 1) (org-level-increment))
7995 do (org-do-promote)))
7996 ;; If same level as prev, demote one.
7997 ((= prev-level cur-level)
7998 (org-do-demote))
7999 ;; If parent is top-level, promote to top level if not already.
8000 ((= prev-level 1)
8001 (loop repeat (/ (- cur-level 1) (org-level-increment))
8002 do (org-do-promote)))
8003 ;; If top-level, return to prev-level.
8004 ((= cur-level 1)
8005 (loop repeat (/ (- prev-level 1) (org-level-increment))
8006 do (org-do-demote)))
8007 ;; If less than prev-level, promote one.
8008 ((< cur-level prev-level)
8009 (org-do-promote))
8010 ;; If deeper than prev-level, promote until higher than
8011 ;; prev-level.
8012 ((> cur-level prev-level)
8013 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8014 do (org-do-promote))))
8015 t))))
8017 (defun org-map-tree (fun)
8018 "Call FUN for every heading underneath the current one."
8019 (org-back-to-heading)
8020 (let ((level (funcall outline-level)))
8021 (save-excursion
8022 (funcall fun)
8023 (while (and (progn
8024 (outline-next-heading)
8025 (> (funcall outline-level) level))
8026 (not (eobp)))
8027 (funcall fun)))))
8029 (defun org-map-region (fun beg end)
8030 "Call FUN for every heading between BEG and END."
8031 (let ((org-ignore-region t))
8032 (save-excursion
8033 (setq end (copy-marker end))
8034 (goto-char beg)
8035 (if (and (re-search-forward org-outline-regexp-bol nil t)
8036 (< (point) end))
8037 (funcall fun))
8038 (while (and (progn
8039 (outline-next-heading)
8040 (< (point) end))
8041 (not (eobp)))
8042 (funcall fun)))))
8044 (defvar org-property-end-re) ; silence byte-compiler
8045 (defun org-fixup-indentation (diff)
8046 "Change the indentation in the current entry by DIFF.
8047 However, if any line in the current entry has no indentation, or if it
8048 would end up with no indentation after the change, nothing at all is done."
8049 (save-excursion
8050 (let ((end (save-excursion (outline-next-heading)
8051 (point-marker)))
8052 (prohibit (if (> diff 0)
8053 "^\\S-"
8054 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8055 col)
8056 (unless (save-excursion (end-of-line 1)
8057 (re-search-forward prohibit end t))
8058 (while (and (< (point) end)
8059 (re-search-forward "^[ \t]+" end t))
8060 (goto-char (match-end 0))
8061 (setq col (current-column))
8062 (if (< diff 0) (replace-match ""))
8063 (org-indent-to-column (+ diff col))))
8064 (move-marker end nil))))
8066 (defun org-convert-to-odd-levels ()
8067 "Convert an org-mode file with all levels allowed to one with odd levels.
8068 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8069 level 5 etc."
8070 (interactive)
8071 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8072 (let ((outline-level 'org-outline-level)
8073 (org-odd-levels-only nil) n)
8074 (save-excursion
8075 (goto-char (point-min))
8076 (while (re-search-forward "^\\*\\*+ " nil t)
8077 (setq n (- (length (match-string 0)) 2))
8078 (while (>= (setq n (1- n)) 0)
8079 (org-demote))
8080 (end-of-line 1))))))
8082 (defun org-convert-to-oddeven-levels ()
8083 "Convert an org-mode file with only odd levels to one with odd/even levels.
8084 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8085 file contains a section with an even level, conversion would
8086 destroy the structure of the file. An error is signaled in this
8087 case."
8088 (interactive)
8089 (goto-char (point-min))
8090 ;; First check if there are no even levels
8091 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8092 (org-show-context t)
8093 (error "Not all levels are odd in this file. Conversion not possible"))
8094 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8095 (let ((outline-regexp org-outline-regexp)
8096 (outline-level 'org-outline-level)
8097 (org-odd-levels-only nil) n)
8098 (save-excursion
8099 (goto-char (point-min))
8100 (while (re-search-forward "^\\*\\*+ " nil t)
8101 (setq n (/ (1- (length (match-string 0))) 2))
8102 (while (>= (setq n (1- n)) 0)
8103 (org-promote))
8104 (end-of-line 1))))))
8106 (defun org-tr-level (n)
8107 "Make N odd if required."
8108 (if org-odd-levels-only (1+ (/ n 2)) n))
8110 ;;; Vertical tree motion, cutting and pasting of subtrees
8112 (defun org-move-subtree-up (&optional arg)
8113 "Move the current subtree up past ARG headlines of the same level."
8114 (interactive "p")
8115 (org-move-subtree-down (- (prefix-numeric-value arg))))
8117 (defun org-move-subtree-down (&optional arg)
8118 "Move the current subtree down past ARG headlines of the same level."
8119 (interactive "p")
8120 (setq arg (prefix-numeric-value arg))
8121 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8122 'org-get-last-sibling))
8123 (ins-point (make-marker))
8124 (cnt (abs arg))
8125 (col (current-column))
8126 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8127 ;; Select the tree
8128 (org-back-to-heading)
8129 (setq beg0 (point))
8130 (save-excursion
8131 (setq ne-beg (org-back-over-empty-lines))
8132 (setq beg (point)))
8133 (save-match-data
8134 (save-excursion (outline-end-of-heading)
8135 (setq folded (outline-invisible-p)))
8136 (outline-end-of-subtree))
8137 (outline-next-heading)
8138 (setq ne-end (org-back-over-empty-lines))
8139 (setq end (point))
8140 (goto-char beg0)
8141 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8142 ;; include less whitespace
8143 (save-excursion
8144 (goto-char beg)
8145 (forward-line (- ne-beg ne-end))
8146 (setq beg (point))))
8147 ;; Find insertion point, with error handling
8148 (while (> cnt 0)
8149 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8150 (progn (goto-char beg0)
8151 (user-error "Cannot move past superior level or buffer limit")))
8152 (setq cnt (1- cnt)))
8153 (if (> arg 0)
8154 ;; Moving forward - still need to move over subtree
8155 (progn (org-end-of-subtree t t)
8156 (save-excursion
8157 (org-back-over-empty-lines)
8158 (or (bolp) (newline)))))
8159 (setq ne-ins (org-back-over-empty-lines))
8160 (move-marker ins-point (point))
8161 (setq txt (buffer-substring beg end))
8162 (org-save-markers-in-region beg end)
8163 (delete-region beg end)
8164 (org-remove-empty-overlays-at beg)
8165 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8166 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8167 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8168 (let ((bbb (point)))
8169 (insert-before-markers txt)
8170 (org-reinstall-markers-in-region bbb)
8171 (move-marker ins-point bbb))
8172 (or (bolp) (insert "\n"))
8173 (setq ins-end (point))
8174 (goto-char ins-point)
8175 (org-skip-whitespace)
8176 (when (and (< arg 0)
8177 (org-first-sibling-p)
8178 (> ne-ins ne-beg))
8179 ;; Move whitespace back to beginning
8180 (save-excursion
8181 (goto-char ins-end)
8182 (let ((kill-whole-line t))
8183 (kill-line (- ne-ins ne-beg)) (point)))
8184 (insert (make-string (- ne-ins ne-beg) ?\n)))
8185 (move-marker ins-point nil)
8186 (if folded
8187 (hide-subtree)
8188 (org-show-entry)
8189 (show-children)
8190 (org-cycle-hide-drawers 'children))
8191 (org-clean-visibility-after-subtree-move)
8192 ;; move back to the initial column we were at
8193 (move-to-column col)))
8195 (defvar org-subtree-clip ""
8196 "Clipboard for cut and paste of subtrees.
8197 This is actually only a copy of the kill, because we use the normal kill
8198 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8200 (defvar org-subtree-clip-folded nil
8201 "Was the last copied subtree folded?
8202 This is used to fold the tree back after pasting.")
8204 (defun org-cut-subtree (&optional n)
8205 "Cut the current subtree into the clipboard.
8206 With prefix arg N, cut this many sequential subtrees.
8207 This is a short-hand for marking the subtree and then cutting it."
8208 (interactive "p")
8209 (org-copy-subtree n 'cut))
8211 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8212 "Copy the current subtree it in the clipboard.
8213 With prefix arg N, copy this many sequential subtrees.
8214 This is a short-hand for marking the subtree and then copying it.
8215 If CUT is non-nil, actually cut the subtree.
8216 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8217 of some markers in the region, even if CUT is non-nil. This is
8218 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8219 (interactive "p")
8220 (let (beg end folded (beg0 (point)))
8221 (if (org-called-interactively-p 'any)
8222 (org-back-to-heading nil) ; take what looks like a subtree
8223 (org-back-to-heading t)) ; take what is really there
8224 (setq beg (point))
8225 (skip-chars-forward " \t\r\n")
8226 (save-match-data
8227 (if nosubtrees
8228 (outline-next-heading)
8229 (save-excursion (outline-end-of-heading)
8230 (setq folded (outline-invisible-p)))
8231 (condition-case nil
8232 (org-forward-heading-same-level (1- n) t)
8233 (error nil))
8234 (org-end-of-subtree t t)))
8235 (setq end (point))
8236 (goto-char beg0)
8237 (when (> end beg)
8238 (setq org-subtree-clip-folded folded)
8239 (when (or cut force-store-markers)
8240 (org-save-markers-in-region beg end))
8241 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8242 (setq org-subtree-clip (current-kill 0))
8243 (message "%s: Subtree(s) with %d characters"
8244 (if cut "Cut" "Copied")
8245 (length org-subtree-clip)))))
8247 (defun org-paste-subtree (&optional level tree for-yank)
8248 "Paste the clipboard as a subtree, with modification of headline level.
8249 The entire subtree is promoted or demoted in order to match a new headline
8250 level.
8252 If the cursor is at the beginning of a headline, the same level as
8253 that headline is used to paste the tree.
8255 If not, the new level is derived from the *visible* headings
8256 before and after the insertion point, and taken to be the inferior headline
8257 level of the two. So if the previous visible heading is level 3 and the
8258 next is level 4 (or vice versa), level 4 will be used for insertion.
8259 This makes sure that the subtree remains an independent subtree and does
8260 not swallow low level entries.
8262 You can also force a different level, either by using a numeric prefix
8263 argument, or by inserting the heading marker by hand. For example, if the
8264 cursor is after \"*****\", then the tree will be shifted to level 5.
8266 If optional TREE is given, use this text instead of the kill ring.
8268 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8269 move back over whitespace before inserting, and move point to the end of
8270 the inserted text when done."
8271 (interactive "P")
8272 (setq tree (or tree (and kill-ring (current-kill 0))))
8273 (unless (org-kill-is-subtree-p tree)
8274 (user-error "%s"
8275 (substitute-command-keys
8276 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8277 (org-with-limited-levels
8278 (let* ((visp (not (outline-invisible-p)))
8279 (txt tree)
8280 (^re_ "\\(\\*+\\)[ \t]*")
8281 (old-level (if (string-match org-outline-regexp-bol txt)
8282 (- (match-end 0) (match-beginning 0) 1)
8283 -1))
8284 (force-level (cond (level (prefix-numeric-value level))
8285 ((and (looking-at "[ \t]*$")
8286 (string-match
8287 "^\\*+$" (buffer-substring
8288 (point-at-bol) (point))))
8289 (- (match-end 1) (match-beginning 1)))
8290 ((and (bolp)
8291 (looking-at org-outline-regexp))
8292 (- (match-end 0) (point) 1))))
8293 (previous-level (save-excursion
8294 (condition-case nil
8295 (progn
8296 (outline-previous-visible-heading 1)
8297 (if (looking-at ^re_)
8298 (- (match-end 0) (match-beginning 0) 1)
8300 (error 1))))
8301 (next-level (save-excursion
8302 (condition-case nil
8303 (progn
8304 (or (looking-at org-outline-regexp)
8305 (outline-next-visible-heading 1))
8306 (if (looking-at ^re_)
8307 (- (match-end 0) (match-beginning 0) 1)
8309 (error 1))))
8310 (new-level (or force-level (max previous-level next-level)))
8311 (shift (if (or (= old-level -1)
8312 (= new-level -1)
8313 (= old-level new-level))
8315 (- new-level old-level)))
8316 (delta (if (> shift 0) -1 1))
8317 (func (if (> shift 0) 'org-demote 'org-promote))
8318 (org-odd-levels-only nil)
8319 beg end newend)
8320 ;; Remove the forced level indicator
8321 (if force-level
8322 (delete-region (point-at-bol) (point)))
8323 ;; Paste
8324 (beginning-of-line (if (bolp) 1 2))
8325 (setq beg (point))
8326 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8327 (insert-before-markers txt)
8328 (unless (string-match "\n\\'" txt) (insert "\n"))
8329 (setq newend (point))
8330 (org-reinstall-markers-in-region beg)
8331 (setq end (point))
8332 (goto-char beg)
8333 (skip-chars-forward " \t\n\r")
8334 (setq beg (point))
8335 (if (and (outline-invisible-p) visp)
8336 (save-excursion (outline-show-heading)))
8337 ;; Shift if necessary
8338 (unless (= shift 0)
8339 (save-restriction
8340 (narrow-to-region beg end)
8341 (while (not (= shift 0))
8342 (org-map-region func (point-min) (point-max))
8343 (setq shift (+ delta shift)))
8344 (goto-char (point-min))
8345 (setq newend (point-max))))
8346 (when (or (org-called-interactively-p 'interactive) for-yank)
8347 (message "Clipboard pasted as level %d subtree" new-level))
8348 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8349 kill-ring
8350 (eq org-subtree-clip (current-kill 0))
8351 org-subtree-clip-folded)
8352 ;; The tree was folded before it was killed/copied
8353 (hide-subtree))
8354 (and for-yank (goto-char newend)))))
8356 (defun org-kill-is-subtree-p (&optional txt)
8357 "Check if the current kill is an outline subtree, or a set of trees.
8358 Returns nil if kill does not start with a headline, or if the first
8359 headline level is not the largest headline level in the tree.
8360 So this will actually accept several entries of equal levels as well,
8361 which is OK for `org-paste-subtree'.
8362 If optional TXT is given, check this string instead of the current kill."
8363 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8364 (re (org-get-limited-outline-regexp))
8365 (^re (concat "^" re))
8366 (start-level (and kill
8367 (string-match
8368 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8369 kill)
8370 (- (match-end 2) (match-beginning 2) 1)))
8371 (start (1+ (or (match-beginning 2) -1))))
8372 (if (not start-level)
8373 (progn
8374 nil) ;; does not even start with a heading
8375 (catch 'exit
8376 (while (setq start (string-match ^re kill (1+ start)))
8377 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8378 (throw 'exit nil)))
8379 t))))
8381 (defvar org-markers-to-move nil
8382 "Markers that should be moved with a cut-and-paste operation.
8383 Those markers are stored together with their positions relative to
8384 the start of the region.")
8386 (defun org-save-markers-in-region (beg end)
8387 "Check markers in region.
8388 If these markers are between BEG and END, record their position relative
8389 to BEG, so that after moving the block of text, we can put the markers back
8390 into place.
8391 This function gets called just before an entry or tree gets cut from the
8392 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8393 called immediately, to move the markers with the entries."
8394 (setq org-markers-to-move nil)
8395 (when (featurep 'org-clock)
8396 (org-clock-save-markers-for-cut-and-paste beg end))
8397 (when (featurep 'org-agenda)
8398 (org-agenda-save-markers-for-cut-and-paste beg end)))
8400 (defun org-check-and-save-marker (marker beg end)
8401 "Check if MARKER is between BEG and END.
8402 If yes, remember the marker and the distance to BEG."
8403 (when (and (marker-buffer marker)
8404 (equal (marker-buffer marker) (current-buffer)))
8405 (if (and (>= marker beg) (< marker end))
8406 (push (cons marker (- marker beg)) org-markers-to-move))))
8408 (defun org-reinstall-markers-in-region (beg)
8409 "Move all remembered markers to their position relative to BEG."
8410 (mapc (lambda (x)
8411 (move-marker (car x) (+ beg (cdr x))))
8412 org-markers-to-move)
8413 (setq org-markers-to-move nil))
8415 (defun org-narrow-to-subtree ()
8416 "Narrow buffer to the current subtree."
8417 (interactive)
8418 (save-excursion
8419 (save-match-data
8420 (org-with-limited-levels
8421 (narrow-to-region
8422 (progn (org-back-to-heading t) (point))
8423 (progn (org-end-of-subtree t t)
8424 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8425 (point)))))))
8427 (defun org-narrow-to-block ()
8428 "Narrow buffer to the current block."
8429 (interactive)
8430 (let* ((case-fold-search t)
8431 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8432 "^[ \t]*#\\+end_.*")))
8433 (if blockp
8434 (narrow-to-region (car blockp) (cdr blockp))
8435 (user-error "Not in a block"))))
8437 (eval-when-compile
8438 (defvar org-property-drawer-re))
8440 (defvar org-property-start-re) ;; defined below
8441 (defun org-clone-subtree-with-time-shift (n &optional shift)
8442 "Clone the task (subtree) at point N times.
8443 The clones will be inserted as siblings.
8445 In interactive use, the user will be prompted for the number of
8446 clones to be produced. If the entry has a timestamp, the user
8447 will also be prompted for a time shift, which may be a repeater
8448 as used in time stamps, for example `+3d'. To disable this,
8449 you can call the function with a universal prefix argument.
8451 When a valid repeater is given and the entry contains any time
8452 stamps, the clones will become a sequence in time, with time
8453 stamps in the subtree shifted for each clone produced. If SHIFT
8454 is nil or the empty string, time stamps will be left alone. The
8455 ID property of the original subtree is removed.
8457 If the original subtree did contain time stamps with a repeater,
8458 the following will happen:
8459 - the repeater will be removed in each clone
8460 - an additional clone will be produced, with the current, unshifted
8461 date(s) in the entry.
8462 - the original entry will be placed *after* all the clones, with
8463 repeater intact.
8464 - the start days in the repeater in the original entry will be shifted
8465 to past the last clone.
8466 In this way you can spell out a number of instances of a repeating task,
8467 and still retain the repeater to cover future instances of the task."
8468 (interactive "nNumber of clones to produce: ")
8469 (let ((shift
8470 (or shift
8471 (if (and (not (equal current-prefix-arg '(4)))
8472 (save-excursion
8473 (re-search-forward org-ts-regexp-both
8474 (save-excursion
8475 (org-end-of-subtree t)
8476 (point)) t)))
8477 (read-from-minibuffer
8478 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8479 ""))) ;; No time shift
8480 (n-no-remove -1)
8481 (drawer-re org-drawer-regexp)
8482 beg end template task idprop
8483 shift-n shift-what doshift nmin nmax)
8484 (if (not (and (integerp n) (> n 0)))
8485 (error "Invalid number of replications %s" n))
8486 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8487 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8488 shift)))
8489 (error "Invalid shift specification %s" shift))
8490 (when doshift
8491 (setq shift-n (string-to-number (match-string 1 shift))
8492 shift-what (cdr (assoc (match-string 2 shift)
8493 '(("d" . day) ("w" . week)
8494 ("m" . month) ("y" . year))))))
8495 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8496 (setq nmin 1 nmax n)
8497 (org-back-to-heading t)
8498 (setq beg (point))
8499 (setq idprop (org-entry-get nil "ID"))
8500 (org-end-of-subtree t t)
8501 (or (bolp) (insert "\n"))
8502 (setq end (point))
8503 (setq template (buffer-substring beg end))
8504 (when (and doshift
8505 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8506 (delete-region beg end)
8507 (setq end beg)
8508 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8509 (goto-char end)
8510 (loop for n from nmin to nmax do
8511 ;; prepare clone
8512 (with-temp-buffer
8513 (insert template)
8514 (org-mode)
8515 (goto-char (point-min))
8516 (org-show-subtree)
8517 (and idprop (if org-clone-delete-id
8518 (org-entry-delete nil "ID")
8519 (org-id-get-create t)))
8520 (unless (= n 0)
8521 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8522 (kill-whole-line))
8523 (goto-char (point-min))
8524 (while (re-search-forward drawer-re nil t)
8525 (mapc (lambda (d)
8526 (org-remove-empty-drawer-at d (point))) org-drawers)))
8527 (goto-char (point-min))
8528 (when doshift
8529 (while (re-search-forward org-ts-regexp-both nil t)
8530 (org-timestamp-change (* n shift-n) shift-what))
8531 (unless (= n n-no-remove)
8532 (goto-char (point-min))
8533 (while (re-search-forward org-ts-regexp nil t)
8534 (save-excursion
8535 (goto-char (match-beginning 0))
8536 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8537 (delete-region (match-beginning 1) (match-end 1)))))))
8538 (setq task (buffer-string)))
8539 (insert task))
8540 (goto-char beg)))
8542 ;;; Outline Sorting
8544 (defun org-sort (with-case)
8545 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8546 Optional argument WITH-CASE means sort case-sensitively."
8547 (interactive "P")
8548 (cond
8549 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8550 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8552 (org-call-with-arg 'org-sort-entries with-case))))
8554 (defun org-sort-remove-invisible (s)
8555 "Remove invisible links from string S."
8556 (remove-text-properties 0 (length s) org-rm-props s)
8557 (while (string-match org-bracket-link-regexp s)
8558 (setq s (replace-match (if (match-end 2)
8559 (match-string 3 s)
8560 (match-string 1 s)) t t s)))
8561 (let ((st (format " %s " s)))
8562 (while (string-match org-emph-re st)
8563 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8564 (setq s (substring st 1 -1)))
8567 (defvar org-priority-regexp) ; defined later in the file
8569 (defvar org-after-sorting-entries-or-items-hook nil
8570 "Hook that is run after a bunch of entries or items have been sorted.
8571 When children are sorted, the cursor is in the parent line when this
8572 hook gets called. When a region or a plain list is sorted, the cursor
8573 will be in the first entry of the sorted region/list.")
8575 (defun org-sort-entries
8576 (&optional with-case sorting-type getkey-func compare-func property)
8577 "Sort entries on a certain level of an outline tree.
8578 If there is an active region, the entries in the region are sorted.
8579 Else, if the cursor is before the first entry, sort the top-level items.
8580 Else, the children of the entry at point are sorted.
8582 Sorting can be alphabetically, numerically, by date/time as given by
8583 a time stamp, by a property, by priority order, or by a custom function.
8585 The command prompts for the sorting type unless it has been given to the
8586 function through the SORTING-TYPE argument, which needs to be a character,
8587 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8588 precise meaning of each character:
8590 n Numerically, by converting the beginning of the entry/item to a number.
8591 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8592 o By order of TODO keywords.
8593 t By date/time, either the first active time stamp in the entry, or, if
8594 none exist, by the first inactive one.
8595 s By the scheduled date/time.
8596 d By deadline date/time.
8597 c By creation time, which is assumed to be the first inactive time stamp
8598 at the beginning of a line.
8599 p By priority according to the cookie.
8600 r By the value of a property.
8602 Capital letters will reverse the sort order.
8604 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8605 called with point at the beginning of the record. It must return either
8606 a string or a number that should serve as the sorting key for that record.
8608 Comparing entries ignores case by default. However, with an optional argument
8609 WITH-CASE, the sorting considers case as well.
8611 Sorting is done against the visible part of the headlines, it ignores hidden
8612 links."
8613 (interactive "P")
8614 (let ((case-func (if with-case 'identity 'downcase))
8615 (cmstr
8616 ;; The clock marker is lost when using `sort-subr', let's
8617 ;; store the clocking string.
8618 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8619 (save-excursion
8620 (goto-char org-clock-marker)
8621 (looking-back "^.*") (match-string-no-properties 0))))
8622 start beg end stars re re2
8623 txt what tmp)
8624 ;; Find beginning and end of region to sort
8625 (cond
8626 ((org-region-active-p)
8627 ;; we will sort the region
8628 (setq end (region-end)
8629 what "region")
8630 (goto-char (region-beginning))
8631 (if (not (org-at-heading-p)) (outline-next-heading))
8632 (setq start (point)))
8633 ((or (org-at-heading-p)
8634 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8635 ;; we will sort the children of the current headline
8636 (org-back-to-heading)
8637 (setq start (point)
8638 end (progn (org-end-of-subtree t t)
8639 (or (bolp) (insert "\n"))
8640 (org-back-over-empty-lines)
8641 (point))
8642 what "children")
8643 (goto-char start)
8644 (show-subtree)
8645 (outline-next-heading))
8647 ;; we will sort the top-level entries in this file
8648 (goto-char (point-min))
8649 (or (org-at-heading-p) (outline-next-heading))
8650 (setq start (point))
8651 (goto-char (point-max))
8652 (beginning-of-line 1)
8653 (when (looking-at ".*?\\S-")
8654 ;; File ends in a non-white line
8655 (end-of-line 1)
8656 (insert "\n"))
8657 (setq end (point-max))
8658 (setq what "top-level")
8659 (goto-char start)
8660 (show-all)))
8662 (setq beg (point))
8663 (if (>= beg end) (user-error "Nothing to sort"))
8665 (looking-at "\\(\\*+\\)")
8666 (setq stars (match-string 1)
8667 re (concat "^" (regexp-quote stars) " +")
8668 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8669 txt (buffer-substring beg end))
8670 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8671 (if (and (not (equal stars "*")) (string-match re2 txt))
8672 (user-error "Region to sort contains a level above the first entry"))
8674 (unless sorting-type
8675 (message
8676 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8677 [t]ime [s]cheduled [d]eadline [c]reated
8678 A/N/P/R/O/F/T/S/D/C means reversed:"
8679 what)
8680 (setq sorting-type (read-char-exclusive))
8682 (unless getkey-func
8683 (and (= (downcase sorting-type) ?f)
8684 (setq getkey-func
8685 (org-icompleting-read "Sort using function: "
8686 obarray 'fboundp t nil nil))
8687 (setq getkey-func (intern getkey-func))))
8689 (and (= (downcase sorting-type) ?r)
8690 (not property)
8691 (setq property
8692 (org-icompleting-read "Property: "
8693 (mapcar 'list (org-buffer-property-keys t))
8694 nil t))))
8696 (message "Sorting entries...")
8698 (save-restriction
8699 (narrow-to-region start end)
8700 (let ((dcst (downcase sorting-type))
8701 (case-fold-search nil)
8702 (now (current-time)))
8703 (sort-subr
8704 (/= dcst sorting-type)
8705 ;; This function moves to the beginning character of the "record" to
8706 ;; be sorted.
8707 (lambda nil
8708 (if (re-search-forward re nil t)
8709 (goto-char (match-beginning 0))
8710 (goto-char (point-max))))
8711 ;; This function moves to the last character of the "record" being
8712 ;; sorted.
8713 (lambda nil
8714 (save-match-data
8715 (condition-case nil
8716 (outline-forward-same-level 1)
8717 (error
8718 (goto-char (point-max))))))
8719 ;; This function returns the value that gets sorted against.
8720 (lambda nil
8721 (cond
8722 ((= dcst ?n)
8723 (if (looking-at org-complex-heading-regexp)
8724 (string-to-number (org-sort-remove-invisible (match-string 4)))
8725 nil))
8726 ((= dcst ?a)
8727 (if (looking-at org-complex-heading-regexp)
8728 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8729 nil))
8730 ((= dcst ?t)
8731 (let ((end (save-excursion (outline-next-heading) (point))))
8732 (if (or (re-search-forward org-ts-regexp end t)
8733 (re-search-forward org-ts-regexp-both end t))
8734 (org-time-string-to-seconds (match-string 0))
8735 (org-float-time now))))
8736 ((= dcst ?c)
8737 (let ((end (save-excursion (outline-next-heading) (point))))
8738 (if (re-search-forward
8739 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8740 end t)
8741 (org-time-string-to-seconds (match-string 0))
8742 (org-float-time now))))
8743 ((= dcst ?s)
8744 (let ((end (save-excursion (outline-next-heading) (point))))
8745 (if (re-search-forward org-scheduled-time-regexp end t)
8746 (org-time-string-to-seconds (match-string 1))
8747 (org-float-time now))))
8748 ((= dcst ?d)
8749 (let ((end (save-excursion (outline-next-heading) (point))))
8750 (if (re-search-forward org-deadline-time-regexp end t)
8751 (org-time-string-to-seconds (match-string 1))
8752 (org-float-time now))))
8753 ((= dcst ?p)
8754 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8755 (string-to-char (match-string 2))
8756 org-default-priority))
8757 ((= dcst ?r)
8758 (or (org-entry-get nil property) ""))
8759 ((= dcst ?o)
8760 (if (looking-at org-complex-heading-regexp)
8761 (- 9999 (length (member (match-string 2)
8762 org-todo-keywords-1)))))
8763 ((= dcst ?f)
8764 (if getkey-func
8765 (progn
8766 (setq tmp (funcall getkey-func))
8767 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8768 tmp)
8769 (error "Invalid key function `%s'" getkey-func)))
8770 (t (error "Invalid sorting type `%c'" sorting-type))))
8772 (cond
8773 ((= dcst ?a) 'string<)
8774 ((= dcst ?f) compare-func)
8775 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8776 (run-hooks 'org-after-sorting-entries-or-items-hook)
8777 ;; Reset the clock marker if needed
8778 (when cmstr
8779 (save-excursion
8780 (goto-char start)
8781 (search-forward cmstr nil t)
8782 (move-marker org-clock-marker (point))))
8783 (message "Sorting entries...done")))
8785 (defun org-do-sort (table what &optional with-case sorting-type)
8786 "Sort TABLE of WHAT according to SORTING-TYPE.
8787 The user will be prompted for the SORTING-TYPE if the call to this
8788 function does not specify it. WHAT is only for the prompt, to indicate
8789 what is being sorted. The sorting key will be extracted from
8790 the car of the elements of the table.
8791 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8792 (unless sorting-type
8793 (message
8794 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8795 what)
8796 (setq sorting-type (read-char-exclusive)))
8797 (let ((dcst (downcase sorting-type))
8798 extractfun comparefun)
8799 ;; Define the appropriate functions
8800 (cond
8801 ((= dcst ?n)
8802 (setq extractfun 'string-to-number
8803 comparefun (if (= dcst sorting-type) '< '>)))
8804 ((= dcst ?a)
8805 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8806 (lambda(x) (downcase (org-sort-remove-invisible x))))
8807 comparefun (if (= dcst sorting-type)
8808 'string<
8809 (lambda (a b) (and (not (string< a b))
8810 (not (string= a b)))))))
8811 ((= dcst ?t)
8812 (setq extractfun
8813 (lambda (x)
8814 (if (or (string-match org-ts-regexp x)
8815 (string-match org-ts-regexp-both x))
8816 (org-float-time
8817 (org-time-string-to-time (match-string 0 x)))
8819 comparefun (if (= dcst sorting-type) '< '>)))
8820 (t (error "Invalid sorting type `%c'" sorting-type)))
8822 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8823 table)
8824 (lambda (a b) (funcall comparefun (car a) (car b))))))
8827 ;;; The orgstruct minor mode
8829 ;; Define a minor mode which can be used in other modes in order to
8830 ;; integrate the org-mode structure editing commands.
8832 ;; This is really a hack, because the org-mode structure commands use
8833 ;; keys which normally belong to the major mode. Here is how it
8834 ;; works: The minor mode defines all the keys necessary to operate the
8835 ;; structure commands, but wraps the commands into a function which
8836 ;; tests if the cursor is currently at a headline or a plain list
8837 ;; item. If that is the case, the structure command is used,
8838 ;; temporarily setting many Org-mode variables like regular
8839 ;; expressions for filling etc. However, when any of those keys is
8840 ;; used at a different location, function uses `key-binding' to look
8841 ;; up if the key has an associated command in another currently active
8842 ;; keymap (minor modes, major mode, global), and executes that
8843 ;; command. There might be problems if any of the keys is otherwise
8844 ;; used as a prefix key.
8846 (defcustom orgstruct-heading-prefix-regexp nil
8847 "Regexp that matches the custom prefix of Org headlines in
8848 orgstruct(++)-mode."
8849 :group 'org
8850 :version "24.4"
8851 :package-version '(Org . "8.0")
8852 :type 'string)
8853 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8855 (defcustom orgstruct-setup-hook nil
8856 "Hook run after orgstruct-mode-map is filled."
8857 :group 'org
8858 :version "24.4"
8859 :package-version '(Org . "8.0")
8860 :type 'hook)
8862 (defvar orgstruct-initialized nil)
8864 (defvar org-local-vars nil
8865 "List of local variables, for use by `orgstruct-mode'.")
8867 ;;;###autoload
8868 (define-minor-mode orgstruct-mode
8869 "Toggle the minor mode `orgstruct-mode'.
8870 This mode is for using Org-mode structure commands in other
8871 modes. The following keys behave as if Org-mode were active, if
8872 the cursor is on a headline, or on a plain list item (both as
8873 defined by Org-mode)."
8874 nil " OrgStruct" (make-sparse-keymap)
8875 (funcall (if orgstruct-mode
8876 'add-to-invisibility-spec
8877 'remove-from-invisibility-spec)
8878 '(outline . t))
8879 (when orgstruct-mode
8880 (org-load-modules-maybe)
8881 (unless orgstruct-initialized
8882 (orgstruct-setup)
8883 (setq orgstruct-initialized t))))
8885 ;;;###autoload
8886 (defun turn-on-orgstruct ()
8887 "Unconditionally turn on `orgstruct-mode'."
8888 (orgstruct-mode 1))
8890 (defvar org-fb-vars nil)
8891 (make-variable-buffer-local 'org-fb-vars)
8892 (defun orgstruct++-mode (&optional arg)
8893 "Toggle `orgstruct-mode', the enhanced version of it.
8894 In addition to setting orgstruct-mode, this also exports all
8895 indentation and autofilling variables from org-mode into the
8896 buffer. It will also recognize item context in multiline items."
8897 (interactive "P")
8898 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8899 (if (< arg 1)
8900 (progn (orgstruct-mode -1)
8901 (mapc (lambda(v)
8902 (org-set-local (car v)
8903 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8904 org-fb-vars))
8905 (orgstruct-mode 1)
8906 (setq org-fb-vars nil)
8907 (unless org-local-vars
8908 (setq org-local-vars (org-get-local-variables)))
8909 (let (var val)
8910 (mapc
8911 (lambda (x)
8912 (when (string-match
8913 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8914 (symbol-name (car x)))
8915 (setq var (car x) val (nth 1 x))
8916 (push (list var `(quote ,(eval var))) org-fb-vars)
8917 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8918 org-local-vars)
8919 (org-set-local 'orgstruct-is-++ t))))
8921 (defvar orgstruct-is-++ nil
8922 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8923 (make-variable-buffer-local 'orgstruct-is-++)
8925 ;;;###autoload
8926 (defun turn-on-orgstruct++ ()
8927 "Unconditionally turn on `orgstruct++-mode'."
8928 (orgstruct++-mode 1))
8930 (defun orgstruct-error ()
8931 "Error when there is no default binding for a structure key."
8932 (interactive)
8933 (funcall (if (fboundp 'user-error)
8934 'user-error
8935 'error)
8936 "This key has no function outside structure elements"))
8938 (defun orgstruct-setup ()
8939 "Setup orgstruct keymap."
8940 (dolist (cell '((org-demote . t)
8941 (org-metaleft . t)
8942 (org-metaright . t)
8943 (org-promote . t)
8944 (org-shiftmetaleft . t)
8945 (org-shiftmetaright . t)
8946 org-backward-element
8947 org-backward-heading-same-level
8948 org-ctrl-c-ret
8949 org-ctrl-c-minus
8950 org-ctrl-c-star
8951 org-cycle
8952 org-forward-heading-same-level
8953 org-insert-heading
8954 org-insert-heading-respect-content
8955 org-kill-note-or-show-branches
8956 org-mark-subtree
8957 org-meta-return
8958 org-metadown
8959 org-metaup
8960 org-narrow-to-subtree
8961 org-promote-subtree
8962 org-reveal
8963 org-shiftdown
8964 org-shiftleft
8965 org-shiftmetadown
8966 org-shiftmetaup
8967 org-shiftright
8968 org-shifttab
8969 org-shifttab
8970 org-shiftup
8971 org-show-subtree
8972 org-sort
8973 org-up-element
8974 outline-demote
8975 outline-next-visible-heading
8976 outline-previous-visible-heading
8977 outline-promote
8978 outline-up-heading
8979 show-children))
8980 (let ((f (or (car-safe cell) cell))
8981 (disable-when-heading-prefix (cdr-safe cell)))
8982 (when (fboundp f)
8983 (let ((new-bindings))
8984 (dolist (binding (nconc (where-is-internal f org-mode-map)
8985 (where-is-internal f outline-mode-map)))
8986 (push binding new-bindings)
8987 ;; TODO use local-function-key-map
8988 (dolist (rep '(("<tab>" . "TAB")
8989 ("<return>" . "RET")
8990 ("<escape>" . "ESC")
8991 ("<delete>" . "DEL")))
8992 (setq binding (read-kbd-macro
8993 (let ((case-fold-search))
8994 (replace-regexp-in-string
8995 (regexp-quote (cdr rep))
8996 (car rep)
8997 (key-description binding)))))
8998 (pushnew binding new-bindings :test 'equal)))
8999 (dolist (binding new-bindings)
9000 (let ((key (lookup-key orgstruct-mode-map binding)))
9001 (when (or (not key) (numberp key))
9002 (condition-case nil
9003 (org-defkey orgstruct-mode-map
9004 binding
9005 (orgstruct-make-binding f binding disable-when-heading-prefix))
9006 (error nil)))))))))
9007 (run-hooks 'orgstruct-setup-hook))
9009 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9010 "Create a function for binding in the structure minor mode.
9011 FUN is the command to call inside a table. KEY is the key that
9012 should be checked in for a command to execute outside of tables.
9013 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9014 if `orgstruct-heading-prefix-regexp' is non-nil."
9015 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9016 (let ((nname name)
9017 (i 0))
9018 (while (fboundp (intern nname))
9019 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9020 (setq name (intern nname)))
9021 (eval
9022 (let ((bindings '((org-heading-regexp
9023 (concat "^"
9024 orgstruct-heading-prefix-regexp
9025 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9026 (org-outline-regexp
9027 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9028 (org-outline-regexp-bol
9029 (concat "^" org-outline-regexp))
9030 (outline-regexp org-outline-regexp)
9031 (outline-heading-end-regexp "\n")
9032 (outline-level 'org-outline-level)
9033 (outline-heading-alist))))
9034 `(defun ,name (arg)
9035 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9036 "Outside of structure, run the binding of `"
9037 (key-description key) "'."
9038 (when disable-when-heading-prefix
9039 (concat
9040 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9041 "back to the default binding due to limitations of Org's implementation of\n"
9042 "`" (symbol-name fun) "'.")))
9043 (interactive "p")
9044 (let* ((disable
9045 ,(when disable-when-heading-prefix
9046 '(and orgstruct-heading-prefix-regexp
9047 (not (string= orgstruct-heading-prefix-regexp "")))))
9048 (fallback
9049 (or disable
9050 (not
9051 (let* ,bindings
9052 (org-context-p 'headline 'item
9053 ,(when (memq fun
9054 '(org-insert-heading
9055 org-insert-heading-respect-content
9056 org-meta-return))
9057 '(when orgstruct-is-++
9058 'item-body))))))))
9059 (if fallback
9060 (let* ((orgstruct-mode)
9061 (binding
9062 (loop with key = ,key
9063 for rep in
9064 '(nil
9065 ("<\\([^>]*\\)tab>" . "\\1TAB")
9066 ("<\\([^>]*\\)return>" . "\\1RET")
9067 ("<\\([^>]*\\)escape>" . "\\1ESC")
9068 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9070 (when rep
9071 (setq key (read-kbd-macro
9072 (let ((case-fold-search))
9073 (replace-regexp-in-string
9074 (car rep)
9075 (cdr rep)
9076 (key-description key))))))
9077 thereis (key-binding key))))
9078 (if (keymapp binding)
9079 (set-temporary-overlay-map binding)
9080 (let ((func (or binding
9081 (unless disable
9082 'orgstruct-error))))
9083 (when func
9084 (call-interactively func)))))
9085 (org-run-like-in-org-mode
9086 (lambda ()
9087 (interactive)
9088 (let* ,bindings
9089 (call-interactively ',fun)))))))))
9090 name))
9092 (defun org-contextualize-keys (alist contexts)
9093 "Return valid elements in ALIST depending on CONTEXTS.
9095 `org-agenda-custom-commands' or `org-capture-templates' are the
9096 values used for ALIST, and `org-agenda-custom-commands-contexts'
9097 or `org-capture-templates-contexts' are the associated contexts
9098 definitions."
9099 (let ((contexts
9100 ;; normalize contexts
9101 (mapcar
9102 (lambda(c) (cond ((listp (cadr c))
9103 (list (car c) (car c) (cadr c)))
9104 ((string= "" (cadr c))
9105 (list (car c) (car c) (caddr c)))
9106 (t c))) contexts))
9107 (a alist) c r s)
9108 ;; loop over all commands or templates
9109 (while (setq c (pop a))
9110 (let (vrules repl)
9111 (cond
9112 ((not (assoc (car c) contexts))
9113 (push c r))
9114 ((and (assoc (car c) contexts)
9115 (setq vrules (org-contextualize-validate-key
9116 (car c) contexts)))
9117 (mapc (lambda (vr)
9118 (when (not (equal (car vr) (cadr vr)))
9119 (setq repl vr))) vrules)
9120 (if (not repl) (push c r)
9121 (push (cadr repl) s)
9122 (push
9123 (cons (car c)
9124 (cdr (or (assoc (cadr repl) alist)
9125 (error "Undefined key `%s' as contextual replacement for `%s'"
9126 (cadr repl) (car c)))))
9127 r))))))
9128 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9129 (delq
9131 (delete-dups
9132 (mapcar (lambda (x)
9133 (let ((tpl (car x)))
9134 (when (not (delq
9136 (mapcar (lambda(y)
9137 (equal y tpl)) s))) x)))
9138 (reverse r))))))
9140 (defun org-contextualize-validate-key (key contexts)
9141 "Check CONTEXTS for agenda or capture KEY."
9142 (let (r rr res)
9143 (while (setq r (pop contexts))
9144 (mapc
9145 (lambda (rr)
9146 (when
9147 (and (equal key (car r))
9148 (if (functionp rr) (funcall rr)
9149 (or (and (eq (car rr) 'in-file)
9150 (buffer-file-name)
9151 (string-match (cdr rr) (buffer-file-name)))
9152 (and (eq (car rr) 'in-mode)
9153 (string-match (cdr rr) (symbol-name major-mode)))
9154 (and (eq (car rr) 'in-buffer)
9155 (string-match (cdr rr) (buffer-name)))
9156 (when (and (eq (car rr) 'not-in-file)
9157 (buffer-file-name))
9158 (not (string-match (cdr rr) (buffer-file-name))))
9159 (when (eq (car rr) 'not-in-mode)
9160 (not (string-match (cdr rr) (symbol-name major-mode))))
9161 (when (eq (car rr) 'not-in-buffer)
9162 (not (string-match (cdr rr) (buffer-name)))))))
9163 (push r res)))
9164 (car (last r))))
9165 (delete-dups (delq nil res))))
9167 (defun org-context-p (&rest contexts)
9168 "Check if local context is any of CONTEXTS.
9169 Possible values in the list of contexts are `table', `headline', and `item'."
9170 (let ((pos (point)))
9171 (goto-char (point-at-bol))
9172 (prog1 (or (and (memq 'table contexts)
9173 (looking-at "[ \t]*|"))
9174 (and (memq 'headline contexts)
9175 (looking-at org-outline-regexp))
9176 (and (memq 'item contexts)
9177 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9178 (and (memq 'item-body contexts)
9179 (org-in-item-p)))
9180 (goto-char pos))))
9182 (defun org-get-local-variables ()
9183 "Return a list of all local variables in an Org mode buffer."
9184 (let (varlist)
9185 (with-current-buffer (get-buffer-create "*Org tmp*")
9186 (erase-buffer)
9187 (org-mode)
9188 (setq varlist (buffer-local-variables)))
9189 (kill-buffer "*Org tmp*")
9190 (delq nil
9191 (mapcar
9192 (lambda (x)
9193 (setq x
9194 (if (symbolp x)
9195 (list x)
9196 (list (car x) (cdr x))))
9197 (if (and (not (get (car x) 'org-state))
9198 (string-match
9199 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9200 (symbol-name (car x))))
9201 x nil))
9202 varlist))))
9204 (defun org-clone-local-variables (from-buffer &optional regexp)
9205 "Clone local variables from FROM-BUFFER.
9206 Optional argument REGEXP selects variables to clone."
9207 (mapc
9208 (lambda (pair)
9209 (and (symbolp (car pair))
9210 (or (null regexp)
9211 (string-match regexp (symbol-name (car pair))))
9212 (set (make-local-variable (car pair))
9213 (cdr pair))))
9214 (buffer-local-variables from-buffer)))
9216 ;;;###autoload
9217 (defun org-run-like-in-org-mode (cmd)
9218 "Run a command, pretending that the current buffer is in Org-mode.
9219 This will temporarily bind local variables that are typically bound in
9220 Org-mode to the values they have in Org-mode, and then interactively
9221 call CMD."
9222 (org-load-modules-maybe)
9223 (unless org-local-vars
9224 (setq org-local-vars (org-get-local-variables)))
9225 (let (binds)
9226 (dolist (var org-local-vars)
9227 (when (or (not (boundp (car var)))
9228 (eq (symbol-value (car var))
9229 (default-value (car var))))
9230 (push (list (car var) `(quote ,(cadr var))) binds)))
9231 (eval `(let ,binds
9232 (call-interactively (quote ,cmd))))))
9234 ;;;; Archiving
9236 (defun org-get-category (&optional pos force-refresh)
9237 "Get the category applying to position POS."
9238 (save-match-data
9239 (if force-refresh (org-refresh-category-properties))
9240 (let ((pos (or pos (point))))
9241 (or (get-text-property pos 'org-category)
9242 (progn (org-refresh-category-properties)
9243 (get-text-property pos 'org-category))))))
9245 (defun org-refresh-category-properties ()
9246 "Refresh category text properties in the buffer."
9247 (let ((case-fold-search t)
9248 (inhibit-read-only t)
9249 (def-cat (cond
9250 ((null org-category)
9251 (if buffer-file-name
9252 (file-name-sans-extension
9253 (file-name-nondirectory buffer-file-name))
9254 "???"))
9255 ((symbolp org-category) (symbol-name org-category))
9256 (t org-category)))
9257 beg end cat pos optionp)
9258 (org-with-silent-modifications
9259 (save-excursion
9260 (save-restriction
9261 (widen)
9262 (goto-char (point-min))
9263 (put-text-property (point) (point-max) 'org-category def-cat)
9264 (while (re-search-forward
9265 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9266 (setq pos (match-end 0)
9267 optionp (equal (char-after (match-beginning 0)) ?#)
9268 cat (org-trim (match-string 2)))
9269 (if optionp
9270 (setq beg (point-at-bol) end (point-max))
9271 (org-back-to-heading t)
9272 (setq beg (point) end (org-end-of-subtree t t)))
9273 (put-text-property beg end 'org-category cat)
9274 (put-text-property beg end 'org-category-position beg)
9275 (goto-char pos)))))))
9277 (defun org-refresh-properties (dprop tprop)
9278 "Refresh buffer text properties.
9279 DPROP is the drawer property and TPROP is the corresponding text
9280 property to set."
9281 (let ((case-fold-search t)
9282 (inhibit-read-only t) p)
9283 (org-with-silent-modifications
9284 (save-excursion
9285 (save-restriction
9286 (widen)
9287 (goto-char (point-min))
9288 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9289 (setq p (org-match-string-no-properties 1))
9290 (save-excursion
9291 (org-back-to-heading t)
9292 (put-text-property
9293 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9296 ;;;; Link Stuff
9298 ;;; Link abbreviations
9300 (defun org-link-expand-abbrev (link)
9301 "Apply replacements as defined in `org-link-abbrev-alist'."
9302 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9303 (let* ((key (match-string 1 link))
9304 (as (or (assoc key org-link-abbrev-alist-local)
9305 (assoc key org-link-abbrev-alist)))
9306 (tag (and (match-end 2) (match-string 3 link)))
9307 rpl)
9308 (if (not as)
9309 link
9310 (setq rpl (cdr as))
9311 (cond
9312 ((symbolp rpl) (funcall rpl tag))
9313 ((string-match "%(\\([^)]+\\))" rpl)
9314 (replace-match
9315 (save-match-data
9316 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9317 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9318 ((string-match "%h" rpl)
9319 (replace-match (url-hexify-string (or tag "")) t t rpl))
9320 (t (concat rpl tag)))))
9321 link))
9323 ;;; Storing and inserting links
9325 (defvar org-insert-link-history nil
9326 "Minibuffer history for links inserted with `org-insert-link'.")
9328 (defvar org-stored-links nil
9329 "Contains the links stored with `org-store-link'.")
9331 (defvar org-store-link-plist nil
9332 "Plist with info about the most recently link created with `org-store-link'.")
9334 (defvar org-link-protocols nil
9335 "Link protocols added to Org-mode using `org-add-link-type'.")
9337 (defvar org-store-link-functions nil
9338 "List of functions that are called to create and store a link.
9339 Each function will be called in turn until one returns a non-nil
9340 value. Each function should check if it is responsible for creating
9341 this link (for example by looking at the major mode).
9342 If not, it must exit and return nil.
9343 If yes, it should return a non-nil value after a calling
9344 `org-store-link-props' with a list of properties and values.
9345 Special properties are:
9347 :type The link prefix, like \"http\". This must be given.
9348 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9349 This is obligatory as well.
9350 :description Optional default description for the second pair
9351 of brackets in an Org-mode link. The user can still change
9352 this when inserting this link into an Org-mode buffer.
9354 In addition to these, any additional properties can be specified
9355 and then used in capture templates.")
9357 (defun org-add-link-type (type &optional follow export)
9358 "Add TYPE to the list of `org-link-types'.
9359 Re-compute all regular expressions depending on `org-link-types'
9361 FOLLOW and EXPORT are two functions.
9363 FOLLOW should take the link path as the single argument and do whatever
9364 is necessary to follow the link, for example find a file or display
9365 a mail message.
9367 EXPORT should format the link path for export to one of the export formats.
9368 It should be a function accepting three arguments:
9370 path the path of the link, the text after the prefix (like \"http:\")
9371 desc the description of the link, if any, or a description added by
9372 org-export-normalize-links if there is none
9373 format the export format, a symbol like `html' or `latex' or `ascii'..
9375 The function may use the FORMAT information to return different values
9376 depending on the format. The return value will be put literally into
9377 the exported file. If the return value is nil, this means Org should
9378 do what it normally does with links which do not have EXPORT defined.
9380 Org-mode has a built-in default for exporting links. If you are happy with
9381 this default, there is no need to define an export function for the link
9382 type. For a simple example of an export function, see `org-bbdb.el'."
9383 (add-to-list 'org-link-types type t)
9384 (org-make-link-regexps)
9385 (if (assoc type org-link-protocols)
9386 (setcdr (assoc type org-link-protocols) (list follow export))
9387 (push (list type follow export) org-link-protocols)))
9389 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9390 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9392 ;;;###autoload
9393 (defun org-store-link (arg)
9394 "\\<org-mode-map>Store an org-link to the current location.
9395 This link is added to `org-stored-links' and can later be inserted
9396 into an org-buffer with \\[org-insert-link].
9398 For some link types, a prefix arg is interpreted.
9399 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9400 For file links, arg negates `org-context-in-file-links'.
9402 A double prefix arg force skipping storing functions that are not
9403 part of Org's core.
9405 A triple prefix arg force storing a link for each line in the
9406 active region."
9407 (interactive "P")
9408 (org-load-modules-maybe)
9409 (if (and (equal arg '(64)) (org-region-active-p))
9410 (save-excursion
9411 (let ((end (region-end)))
9412 (goto-char (region-beginning))
9413 (set-mark (point))
9414 (while (< (point-at-eol) end)
9415 (move-end-of-line 1) (activate-mark)
9416 (let (current-prefix-arg)
9417 (call-interactively 'org-store-link))
9418 (move-beginning-of-line 2)
9419 (set-mark (point)))))
9420 (org-with-limited-levels
9421 (setq org-store-link-plist nil)
9422 (let (link cpltxt desc description search
9423 txt custom-id agenda-link sfuns sfunsn)
9424 (cond
9426 ;; Store a link using an external link type
9427 ((and (not (equal arg '(16)))
9428 (setq sfuns
9429 (delq
9430 nil (mapcar (lambda (f)
9431 (let (fs) (if (funcall f) (push f fs))))
9432 org-store-link-functions))
9433 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9434 (or (and (cdr sfuns)
9435 (funcall (intern
9436 (completing-read
9437 "Which function for creating the link? "
9438 sfunsn t (car sfunsn)))))
9439 (funcall (caar sfuns)))
9440 (setq link (plist-get org-store-link-plist :link)
9441 desc (or (plist-get org-store-link-plist
9442 :description) link))))
9444 ;; Store a link from a source code buffer
9445 ((org-src-edit-buffer-p)
9446 (let (label gc)
9447 (while (or (not label)
9448 (save-excursion
9449 (save-restriction
9450 (widen)
9451 (goto-char (point-min))
9452 (re-search-forward
9453 (regexp-quote (format org-coderef-label-format label))
9454 nil t))))
9455 (when label (message "Label exists already") (sit-for 2))
9456 (setq label (read-string "Code line label: " label)))
9457 (end-of-line 1)
9458 (setq link (format org-coderef-label-format label))
9459 (setq gc (- 79 (length link)))
9460 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9461 (insert link)
9462 (setq link (concat "(" label ")") desc nil)))
9464 ;; We are in the agenda, link to referenced location
9465 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9466 (let ((m (or (get-text-property (point) 'org-hd-marker)
9467 (get-text-property (point) 'org-marker))))
9468 (when m
9469 (org-with-point-at m
9470 (setq agenda-link
9471 (if (org-called-interactively-p 'any)
9472 (call-interactively 'org-store-link)
9473 (org-store-link nil)))))))
9475 ((eq major-mode 'calendar-mode)
9476 (let ((cd (calendar-cursor-to-date)))
9477 (setq link
9478 (format-time-string
9479 (car org-time-stamp-formats)
9480 (apply 'encode-time
9481 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9482 nil nil nil))))
9483 (org-store-link-props :type "calendar" :date cd)))
9485 ((eq major-mode 'help-mode)
9486 (setq link (concat "help:" (save-excursion
9487 (goto-char (point-min))
9488 (looking-at "^[^ ]+")
9489 (match-string 0))))
9490 (org-store-link-props :type "help"))
9492 ((eq major-mode 'w3-mode)
9493 (setq cpltxt (if (and (buffer-name)
9494 (not (string-match "Untitled" (buffer-name))))
9495 (buffer-name)
9496 (url-view-url t))
9497 link (url-view-url t))
9498 (org-store-link-props :type "w3" :url (url-view-url t)))
9500 ((eq major-mode 'image-mode)
9501 (setq cpltxt (concat "file:"
9502 (abbreviate-file-name buffer-file-name))
9503 link cpltxt)
9504 (org-store-link-props :type "image" :file buffer-file-name))
9506 ;; In dired, store a link to the file of the current line
9507 ((eq major-mode 'dired-mode)
9508 (let ((file (dired-get-filename nil t)))
9509 (setq file (if file
9510 (abbreviate-file-name
9511 (expand-file-name (dired-get-filename nil t)))
9512 ;; otherwise, no file so use current directory.
9513 default-directory))
9514 (setq cpltxt (concat "file:" file)
9515 link cpltxt)))
9517 ((setq search (run-hook-with-args-until-success
9518 'org-create-file-search-functions))
9519 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9520 "::" search))
9521 (setq cpltxt (or description link)))
9523 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9524 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9525 (cond
9526 ;; Store a link using the target at point
9527 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9528 (setq cpltxt
9529 (concat "file:"
9530 (abbreviate-file-name
9531 (buffer-file-name (buffer-base-buffer)))
9532 "::" (match-string 1))
9533 link cpltxt))
9534 ((and (featurep 'org-id)
9535 (or (eq org-id-link-to-org-use-id t)
9536 (and (org-called-interactively-p 'any)
9537 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9538 (and (eq org-id-link-to-org-use-id
9539 'create-if-interactive-and-no-custom-id)
9540 (not custom-id))))
9541 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9542 ;; Store a link using the ID at point
9543 (setq link (condition-case nil
9544 (prog1 (org-id-store-link)
9545 (setq desc (plist-get org-store-link-plist
9546 :description)))
9547 (error
9548 ;; Probably before first headline, link only to file
9549 (concat "file:"
9550 (abbreviate-file-name
9551 (buffer-file-name (buffer-base-buffer))))))))
9553 ;; Just link to current headline
9554 (setq cpltxt (concat "file:"
9555 (abbreviate-file-name
9556 (buffer-file-name (buffer-base-buffer)))))
9557 ;; Add a context search string
9558 (when (org-xor org-context-in-file-links arg)
9559 (let* ((ee (org-element-at-point))
9560 (et (org-element-type ee))
9561 (ev (plist-get (cadr ee) :value))
9562 (ek (plist-get (cadr ee) :key))
9563 (eok (and (stringp ek) (string-match "name" ek))))
9564 (setq txt (cond
9565 ((org-at-heading-p) nil)
9566 ((and (eq et 'keyword) eok) ev)
9567 ((org-region-active-p)
9568 (buffer-substring (region-beginning) (region-end)))))
9569 (when (or (null txt) (string-match "\\S-" txt))
9570 (setq cpltxt
9571 (concat cpltxt "::"
9572 (condition-case nil
9573 (org-make-org-heading-search-string txt)
9574 (error "")))
9575 desc (or (and (eq et 'keyword) eok ev)
9576 (nth 4 (ignore-errors (org-heading-components)))
9577 "NONE")))))
9578 (if (string-match "::\\'" cpltxt)
9579 (setq cpltxt (substring cpltxt 0 -2)))
9580 (setq link cpltxt))))
9582 ((buffer-file-name (buffer-base-buffer))
9583 ;; Just link to this file here.
9584 (setq cpltxt (concat "file:"
9585 (abbreviate-file-name
9586 (buffer-file-name (buffer-base-buffer)))))
9587 ;; Add a context string.
9588 (when (org-xor org-context-in-file-links arg)
9589 (setq txt (if (org-region-active-p)
9590 (buffer-substring (region-beginning) (region-end))
9591 (buffer-substring (point-at-bol) (point-at-eol))))
9592 ;; Only use search option if there is some text.
9593 (when (string-match "\\S-" txt)
9594 (setq cpltxt
9595 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9596 desc "NONE")))
9597 (setq link cpltxt))
9599 ((org-called-interactively-p 'interactive)
9600 (user-error "No method for storing a link from this buffer"))
9602 (t (setq link nil)))
9604 ;; We're done setting link and desc, clean up
9605 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9606 (setq link (or link cpltxt)
9607 desc (or desc cpltxt))
9608 (cond ((equal desc "NONE") (setq desc nil))
9609 ((string-match org-bracket-link-analytic-regexp desc)
9610 (let ((d0 (match-string 3 desc))
9611 (p0 (match-string 5 desc)))
9612 (setq desc
9613 (replace-regexp-in-string
9614 org-bracket-link-regexp
9615 (concat (or p0 d0)
9616 (if (equal (length (match-string 0 desc))
9617 (length desc)) "*" "")) desc)))))
9619 ;; Return the link
9620 (if (not (and (or (org-called-interactively-p 'any)
9621 executing-kbd-macro) link))
9622 (or agenda-link (and link (org-make-link-string link desc)))
9623 (push (list link desc) org-stored-links)
9624 (message "Stored: %s" (or desc link))
9625 (when custom-id
9626 (setq link (concat "file:" (abbreviate-file-name
9627 (buffer-file-name)) "::#" custom-id))
9628 (push (list link desc) org-stored-links)))))))
9630 (defun org-store-link-props (&rest plist)
9631 "Store link properties, extract names and addresses."
9632 (let (x adr)
9633 (when (setq x (plist-get plist :from))
9634 (setq adr (mail-extract-address-components x))
9635 (setq plist (plist-put plist :fromname (car adr)))
9636 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9637 (when (setq x (plist-get plist :to))
9638 (setq adr (mail-extract-address-components x))
9639 (setq plist (plist-put plist :toname (car adr)))
9640 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9641 (let ((from (plist-get plist :from))
9642 (to (plist-get plist :to)))
9643 (when (and from to org-from-is-user-regexp)
9644 (setq plist
9645 (plist-put plist :fromto
9646 (if (string-match org-from-is-user-regexp from)
9647 (concat "to %t")
9648 (concat "from %f"))))))
9649 (setq org-store-link-plist plist))
9651 (defun org-add-link-props (&rest plist)
9652 "Add these properties to the link property list."
9653 (let (key value)
9654 (while plist
9655 (setq key (pop plist) value (pop plist))
9656 (setq org-store-link-plist
9657 (plist-put org-store-link-plist key value)))))
9659 (defun org-email-link-description (&optional fmt)
9660 "Return the description part of an email link.
9661 This takes information from `org-store-link-plist' and formats it
9662 according to FMT (default from `org-email-link-description-format')."
9663 (setq fmt (or fmt org-email-link-description-format))
9664 (let* ((p org-store-link-plist)
9665 (to (plist-get p :toaddress))
9666 (from (plist-get p :fromaddress))
9667 (table
9668 (list
9669 (cons "%c" (plist-get p :fromto))
9670 (cons "%F" (plist-get p :from))
9671 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9672 (cons "%T" (plist-get p :to))
9673 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9674 (cons "%s" (plist-get p :subject))
9675 (cons "%d" (plist-get p :date))
9676 (cons "%m" (plist-get p :message-id)))))
9677 (when (string-match "%c" fmt)
9678 ;; Check if the user wrote this message
9679 (if (and org-from-is-user-regexp from to
9680 (save-match-data (string-match org-from-is-user-regexp from)))
9681 (setq fmt (replace-match "to %t" t t fmt))
9682 (setq fmt (replace-match "from %f" t t fmt))))
9683 (org-replace-escapes fmt table)))
9685 (defun org-make-org-heading-search-string (&optional string)
9686 "Make search string for the current headline or STRING."
9687 (let ((s (or string
9688 (and (derived-mode-p 'org-mode)
9689 (save-excursion
9690 (org-back-to-heading t)
9691 (org-element-property :raw-value (org-element-at-point))))))
9692 (lines org-context-in-file-links))
9693 (or string (setq s (concat "*" s))) ; Add * for headlines
9694 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9695 (when (and string (integerp lines) (> lines 0))
9696 (let ((slines (org-split-string s "\n")))
9697 (when (< lines (length slines))
9698 (setq s (mapconcat
9699 'identity
9700 (reverse (nthcdr (- (length slines) lines)
9701 (reverse slines))) "\n")))))
9702 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9704 (defun org-make-link-string (link &optional description)
9705 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9706 (unless (string-match "\\S-" link)
9707 (error "Empty link"))
9708 (when (and description
9709 (stringp description)
9710 (not (string-match "\\S-" description)))
9711 (setq description nil))
9712 (when (stringp description)
9713 ;; Remove brackets from the description, they are fatal.
9714 (while (string-match "\\[" description)
9715 (setq description (replace-match "{" t t description)))
9716 (while (string-match "\\]" description)
9717 (setq description (replace-match "}" t t description))))
9718 (when (equal link description)
9719 ;; No description needed, it is identical
9720 (setq description nil))
9721 (when (and (not description)
9722 (not (string-match (org-image-file-name-regexp) link))
9723 (not (equal link (org-link-escape link))))
9724 (setq description (org-extract-attributes link)))
9725 (setq link
9726 (cond ((string-match (org-image-file-name-regexp) link) link)
9727 ((string-match org-link-types-re link)
9728 (concat (match-string 1 link)
9729 (org-link-escape (substring link (match-end 1)))))
9730 (t (org-link-escape link))))
9731 (concat "[[" link "]"
9732 (if description (concat "[" description "]") "")
9733 "]"))
9735 (defconst org-link-escape-chars
9736 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9737 "List of characters that should be escaped in link.
9738 This is the list that is used for internal purposes.")
9740 (defconst org-link-escape-chars-browser
9741 '(?\ ?\")
9742 "List of escapes for characters that are problematic in links.
9743 This is the list that is used before handing over to the browser.")
9745 (defun org-link-escape (text &optional table merge)
9746 "Return percent escaped representation of TEXT.
9747 TEXT is a string with the text to escape.
9748 Optional argument TABLE is a list with characters that should be
9749 escaped. When nil, `org-link-escape-chars' is used.
9750 If optional argument MERGE is set, merge TABLE into
9751 `org-link-escape-chars'."
9752 (cond
9753 ((and table merge)
9754 (mapc (lambda (defchr)
9755 (unless (member defchr table)
9756 (setq table (cons defchr table)))) org-link-escape-chars))
9757 ((null table)
9758 (setq table org-link-escape-chars)))
9759 (mapconcat
9760 (lambda (char)
9761 (if (or (member char table)
9762 (and (or (< char 32) (= char 37) (> char 126))
9763 org-url-hexify-p))
9764 (mapconcat (lambda (sequence-element)
9765 (format "%%%.2X" sequence-element))
9766 (or (encode-coding-char char 'utf-8)
9767 (error "Unable to percent escape character: %s"
9768 (char-to-string char))) "")
9769 (char-to-string char))) text ""))
9771 (defun org-link-unescape (str)
9772 "Unhex hexified Unicode strings as returned from the JavaScript function
9773 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9774 (unless (and (null str) (string= "" str))
9775 (let ((pos 0) (case-fold-search t) unhexed)
9776 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9777 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9778 (setq str (replace-match unhexed t t str))
9779 (setq pos (+ pos (length unhexed))))))
9780 str)
9782 (defun org-link-unescape-compound (hex)
9783 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9784 Note: this function also decodes single byte encodings like
9785 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9786 (save-match-data
9787 (let* ((bytes (cdr (split-string hex "%")))
9788 (ret "")
9789 (eat 0)
9790 (sum 0))
9791 (while bytes
9792 (let* ((val (string-to-number (pop bytes) 16))
9793 (shift-xor
9794 (if (= 0 eat)
9795 (cond
9796 ((>= val 252) (cons 6 252))
9797 ((>= val 248) (cons 5 248))
9798 ((>= val 240) (cons 4 240))
9799 ((>= val 224) (cons 3 224))
9800 ((>= val 192) (cons 2 192))
9801 (t (cons 0 0)))
9802 (cons 6 128))))
9803 (if (>= val 192) (setq eat (car shift-xor)))
9804 (setq val (logxor val (cdr shift-xor)))
9805 (setq sum (+ (lsh sum (car shift-xor)) val))
9806 (if (> eat 0) (setq eat (- eat 1)))
9807 (cond
9808 ((= 0 eat) ;multi byte
9809 (setq ret (concat ret (org-char-to-string sum)))
9810 (setq sum 0))
9811 ((not bytes) ; single byte(s)
9812 (setq ret (org-link-unescape-single-byte-sequence hex))))
9813 )) ;; end (while bytes
9814 ret )))
9816 (defun org-link-unescape-single-byte-sequence (hex)
9817 "Unhexify hex-encoded single byte character sequences."
9818 (mapconcat (lambda (byte)
9819 (char-to-string (string-to-number byte 16)))
9820 (cdr (split-string hex "%")) ""))
9822 (defun org-xor (a b)
9823 "Exclusive or."
9824 (if a (not b) b))
9826 (defun org-fixup-message-id-for-http (s)
9827 "Replace special characters in a message id, so it can be used in an http query."
9828 (when (string-match "%" s)
9829 (setq s (mapconcat (lambda (c)
9830 (if (eq c ?%)
9831 "%25"
9832 (char-to-string c)))
9833 s "")))
9834 (while (string-match "<" s)
9835 (setq s (replace-match "%3C" t t s)))
9836 (while (string-match ">" s)
9837 (setq s (replace-match "%3E" t t s)))
9838 (while (string-match "@" s)
9839 (setq s (replace-match "%40" t t s)))
9842 (defun org-link-prettify (link)
9843 "Return a human-readable representation of LINK.
9844 The car of LINK must be a raw link the cdr of LINK must be either
9845 a link description or nil."
9846 (let ((desc (or (cadr link) "<no description>")))
9847 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9848 "<" (car link) ">")))
9850 ;;;###autoload
9851 (defun org-insert-link-global ()
9852 "Insert a link like Org-mode does.
9853 This command can be called in any mode to insert a link in Org-mode syntax."
9854 (interactive)
9855 (org-load-modules-maybe)
9856 (org-run-like-in-org-mode 'org-insert-link))
9858 (defun org-insert-all-links (&optional keep)
9859 "Insert all links in `org-stored-links'."
9860 (interactive "P")
9861 (let ((links (copy-sequence org-stored-links)) l)
9862 (while (setq l (if keep (pop links) (pop org-stored-links)))
9863 (insert "- ")
9864 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9865 (insert "\n"))))
9867 (defun org-link-fontify-links-to-this-file ()
9868 "Fontify links to the current file in `org-stored-links'."
9869 (let ((f (buffer-file-name)) a b)
9870 (setq a (mapcar (lambda(l)
9871 (let ((ll (car l)))
9872 (when (and (string-match "^file:\\(.+\\)::" ll)
9873 (equal f (expand-file-name (match-string 1 ll))))
9874 ll)))
9875 org-stored-links))
9876 (when (featurep 'org-id)
9877 (setq b (mapcar (lambda(l)
9878 (let ((ll (car l)))
9879 (when (and (string-match "^id:\\(.+\\)$" ll)
9880 (equal f (expand-file-name
9881 (or (org-id-find-id-file
9882 (match-string 1 ll)) ""))))
9883 ll)))
9884 org-stored-links)))
9885 (mapcar (lambda(l)
9886 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9887 (delq nil (append a b)))))
9889 (defvar org-link-links-in-this-file nil)
9890 (defun org-insert-link (&optional complete-file link-location default-description)
9891 "Insert a link. At the prompt, enter the link.
9893 Completion can be used to insert any of the link protocol prefixes like
9894 http or ftp in use.
9896 The history can be used to select a link previously stored with
9897 `org-store-link'. When the empty string is entered (i.e. if you just
9898 press RET at the prompt), the link defaults to the most recently
9899 stored link. As SPC triggers completion in the minibuffer, you need to
9900 use M-SPC or C-q SPC to force the insertion of a space character.
9902 You will also be prompted for a description, and if one is given, it will
9903 be displayed in the buffer instead of the link.
9905 If there is already a link at point, this command will allow you to edit link
9906 and description parts.
9908 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9909 be selected using completion. The path to the file will be relative to the
9910 current directory if the file is in the current directory or a subdirectory.
9911 Otherwise, the link will be the absolute path as completed in the minibuffer
9912 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9913 option `org-link-file-path-type'.
9915 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9916 the current directory or below.
9918 With three \\[universal-argument] prefixes, negate the meaning of
9919 `org-keep-stored-link-after-insertion'.
9921 If `org-make-link-description-function' is non-nil, this function will be
9922 called with the link target, and the result will be the default
9923 link description.
9925 If the LINK-LOCATION parameter is non-nil, this value will be
9926 used as the link location instead of reading one interactively.
9928 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9929 be used as the default description."
9930 (interactive "P")
9931 (let* ((wcf (current-window-configuration))
9932 (origbuf (current-buffer))
9933 (region (if (org-region-active-p)
9934 (buffer-substring (region-beginning) (region-end))))
9935 (remove (and region (list (region-beginning) (region-end))))
9936 (desc region)
9937 tmphist ; byte-compile incorrectly complains about this
9938 (link link-location)
9939 (abbrevs org-link-abbrev-alist-local)
9940 entry file all-prefixes auto-desc)
9941 (cond
9942 (link-location) ; specified by arg, just use it.
9943 ((org-in-regexp org-bracket-link-regexp 1)
9944 ;; We do have a link at point, and we are going to edit it.
9945 (setq remove (list (match-beginning 0) (match-end 0)))
9946 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9947 (setq link (read-string "Link: "
9948 (org-link-unescape
9949 (org-match-string-no-properties 1)))))
9950 ((or (org-in-regexp org-angle-link-re)
9951 (org-in-regexp org-plain-link-re))
9952 ;; Convert to bracket link
9953 (setq remove (list (match-beginning 0) (match-end 0))
9954 link (read-string "Link: "
9955 (org-remove-angle-brackets (match-string 0)))))
9956 ((member complete-file '((4) (16)))
9957 ;; Completing read for file names.
9958 (setq link (org-file-complete-link complete-file)))
9960 ;; Read link, with completion for stored links.
9961 (org-link-fontify-links-to-this-file)
9962 (org-switch-to-buffer-other-window "*Org Links*")
9963 (with-current-buffer "*Org Links*"
9964 (erase-buffer)
9965 (insert "Insert a link.
9966 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9967 (when org-stored-links
9968 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9969 (insert (mapconcat 'org-link-prettify
9970 (reverse org-stored-links) "\n")))
9971 (goto-char (point-min)))
9972 (let ((cw (selected-window)))
9973 (select-window (get-buffer-window "*Org Links*" 'visible))
9974 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9975 (unless (pos-visible-in-window-p (point-max))
9976 (org-fit-window-to-buffer))
9977 (and (window-live-p cw) (select-window cw)))
9978 ;; Fake a link history, containing the stored links.
9979 (setq tmphist (append (mapcar 'car org-stored-links)
9980 org-insert-link-history))
9981 (setq all-prefixes (append (mapcar 'car abbrevs)
9982 (mapcar 'car org-link-abbrev-alist)
9983 org-link-types))
9984 (unwind-protect
9985 (progn
9986 (setq link
9987 (org-completing-read
9988 "Link: "
9989 (append
9990 (mapcar (lambda (x) (concat x ":"))
9991 all-prefixes)
9992 (mapcar 'car org-stored-links))
9993 nil nil nil
9994 'tmphist
9995 (caar org-stored-links)))
9996 (if (not (string-match "\\S-" link))
9997 (user-error "No link selected"))
9998 (mapc (lambda(l)
9999 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10000 org-stored-links)
10001 (if (or (member link all-prefixes)
10002 (and (equal ":" (substring link -1))
10003 (member (substring link 0 -1) all-prefixes)
10004 (setq link (substring link 0 -1))))
10005 (setq link (with-current-buffer origbuf
10006 (org-link-try-special-completion link)))))
10007 (set-window-configuration wcf)
10008 (kill-buffer "*Org Links*"))
10009 (setq entry (assoc link org-stored-links))
10010 (or entry (push link org-insert-link-history))
10011 (setq desc (or desc (nth 1 entry)))))
10013 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10014 (not org-keep-stored-link-after-insertion))
10015 (setq org-stored-links (delq (assoc link org-stored-links)
10016 org-stored-links)))
10018 (if (string-match org-plain-link-re link)
10019 ;; URL-like link, normalize the use of angular brackets.
10020 (setq link (org-remove-angle-brackets link)))
10022 ;; Check if we are linking to the current file with a search
10023 ;; option If yes, simplify the link by using only the search
10024 ;; option.
10025 (when (and buffer-file-name
10026 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10027 (let* ((path (match-string 1 link))
10028 (case-fold-search nil)
10029 (search (match-string 2 link)))
10030 (save-match-data
10031 (if (equal (file-truename buffer-file-name) (file-truename path))
10032 ;; We are linking to this same file, with a search option
10033 (setq link search)))))
10035 ;; Check if we can/should use a relative path. If yes, simplify the link
10036 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10037 (let* ((type (match-string 1 link))
10038 (path (match-string 2 link))
10039 (origpath path)
10040 (case-fold-search nil))
10041 (cond
10042 ((or (eq org-link-file-path-type 'absolute)
10043 (equal complete-file '(16)))
10044 (setq path (abbreviate-file-name (expand-file-name path))))
10045 ((eq org-link-file-path-type 'noabbrev)
10046 (setq path (expand-file-name path)))
10047 ((eq org-link-file-path-type 'relative)
10048 (setq path (file-relative-name path)))
10050 (save-match-data
10051 (if (string-match (concat "^" (regexp-quote
10052 (expand-file-name
10053 (file-name-as-directory
10054 default-directory))))
10055 (expand-file-name path))
10056 ;; We are linking a file with relative path name.
10057 (setq path (substring (expand-file-name path)
10058 (match-end 0)))
10059 (setq path (abbreviate-file-name (expand-file-name path)))))))
10060 (setq link (concat type path))
10061 (if (equal desc origpath)
10062 (setq desc path))))
10064 (if org-make-link-description-function
10065 (setq desc
10066 (or (condition-case nil
10067 (funcall org-make-link-description-function link desc)
10068 (error (progn (message "Can't get link description from `%s'"
10069 (symbol-name org-make-link-description-function))
10070 (sit-for 2) nil)))
10071 (read-string "Description: " default-description)))
10072 (if default-description (setq desc default-description)
10073 (setq desc (or (and auto-desc desc)
10074 (read-string "Description: " desc)))))
10076 (unless (string-match "\\S-" desc) (setq desc nil))
10077 (if remove (apply 'delete-region remove))
10078 (insert (org-make-link-string link desc))))
10080 (defun org-link-try-special-completion (type)
10081 "If there is completion support for link type TYPE, offer it."
10082 (let ((fun (intern (concat "org-" type "-complete-link"))))
10083 (if (functionp fun)
10084 (funcall fun)
10085 (read-string "Link (no completion support): " (concat type ":")))))
10087 (defun org-file-complete-link (&optional arg)
10088 "Create a file link using completion."
10089 (let (file link)
10090 (setq file (org-iread-file-name "File: "))
10091 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10092 (pwd1 (file-name-as-directory (abbreviate-file-name
10093 (expand-file-name ".")))))
10094 (cond
10095 ((equal arg '(16))
10096 (setq link (concat
10097 "file:"
10098 (abbreviate-file-name (expand-file-name file)))))
10099 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10100 (setq link (concat "file:" (match-string 1 file))))
10101 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10102 (expand-file-name file))
10103 (setq link (concat
10104 "file:" (match-string 1 (expand-file-name file)))))
10105 (t (setq link (concat "file:" file)))))
10106 link))
10108 (defun org-iread-file-name (&rest args)
10109 "Read-file-name using `ido-mode' speedup if available.
10110 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10111 See `read-file-name' for a description of parameters."
10112 (org-without-partial-completion
10113 (if (and org-completion-use-ido
10114 (fboundp 'ido-read-file-name)
10115 (boundp 'ido-mode) ido-mode
10116 (listp (second args)))
10117 (let ((ido-enter-matching-directory nil))
10118 (apply 'ido-read-file-name args))
10119 (apply 'read-file-name args))))
10121 (defun org-completing-read (&rest args)
10122 "Completing-read with SPACE being a normal character."
10123 (let ((enable-recursive-minibuffers t)
10124 (minibuffer-local-completion-map
10125 (copy-keymap minibuffer-local-completion-map)))
10126 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10127 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10128 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10129 (apply 'org-icompleting-read args)))
10131 (defun org-completing-read-no-i (&rest args)
10132 (let (org-completion-use-ido org-completion-use-iswitchb)
10133 (apply 'org-completing-read args)))
10135 (defun org-iswitchb-completing-read (prompt choices &rest args)
10136 "Use iswitch as a completing-read replacement to choose from choices.
10137 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10138 from."
10139 (let* ((iswitchb-use-virtual-buffers nil)
10140 (iswitchb-make-buflist-hook
10141 (lambda ()
10142 (setq iswitchb-temp-buflist choices))))
10143 (iswitchb-read-buffer prompt)))
10145 (defun org-icompleting-read (&rest args)
10146 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10147 (org-without-partial-completion
10148 (if (and org-completion-use-ido
10149 (fboundp 'ido-completing-read)
10150 (boundp 'ido-mode) ido-mode
10151 (listp (second args)))
10152 (let ((ido-enter-matching-directory nil))
10153 (apply 'ido-completing-read (concat (car args))
10154 (if (consp (car (nth 1 args)))
10155 (mapcar 'car (nth 1 args))
10156 (nth 1 args))
10157 (cddr args)))
10158 (if (and org-completion-use-iswitchb
10159 (boundp 'iswitchb-mode) iswitchb-mode
10160 (listp (second args)))
10161 (apply 'org-iswitchb-completing-read (concat (car args))
10162 (if (consp (car (nth 1 args)))
10163 (mapcar 'car (nth 1 args))
10164 (nth 1 args))
10165 (cddr args))
10166 (apply 'completing-read args)))))
10168 (defun org-extract-attributes (s)
10169 "Extract the attributes cookie from a string and set as text property."
10170 (let (a attr (start 0) key value)
10171 (save-match-data
10172 (when (string-match "{{\\([^}]+\\)}}$" s)
10173 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10174 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10175 (setq key (match-string 1 a) value (match-string 2 a)
10176 start (match-end 0)
10177 attr (plist-put attr (intern key) value))))
10178 (org-add-props s nil 'org-attr attr))
10181 ;;; Opening/following a link
10183 (defvar org-link-search-failed nil)
10185 (defvar org-open-link-functions nil
10186 "Hook for functions finding a plain text link.
10187 These functions must take a single argument, the link content.
10188 They will be called for links that look like [[link text][description]]
10189 when LINK TEXT does not have a protocol like \"http:\" and does not look
10190 like a filename (e.g. \"./blue.png\").
10192 These functions will be called *before* Org attempts to resolve the
10193 link by doing text searches in the current buffer - so if you want a
10194 link \"[[target]]\" to still find \"<<target>>\", your function should
10195 handle this as a special case.
10197 When the function does handle the link, it must return a non-nil value.
10198 If it decides that it is not responsible for this link, it must return
10199 nil to indicate that that Org-mode can continue with other options
10200 like exact and fuzzy text search.")
10202 (defun org-next-link (&optional search-backward)
10203 "Move forward to the next link.
10204 If the link is in hidden text, expose it."
10205 (interactive "P")
10206 (when (and org-link-search-failed (eq this-command last-command))
10207 (goto-char (point-min))
10208 (message "Link search wrapped back to beginning of buffer"))
10209 (setq org-link-search-failed nil)
10210 (let* ((pos (point))
10211 (ct (org-context))
10212 (a (assoc :link ct))
10213 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10214 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10215 ((looking-at org-any-link-re)
10216 ;; Don't stay stuck at link without an org-link face
10217 (forward-char (if search-backward -1 1))))
10218 (if (funcall srch-fun org-any-link-re nil t)
10219 (progn
10220 (goto-char (match-beginning 0))
10221 (if (outline-invisible-p) (org-show-context)))
10222 (goto-char pos)
10223 (setq org-link-search-failed t)
10224 (message "No further link found"))))
10226 (defun org-previous-link ()
10227 "Move backward to the previous link.
10228 If the link is in hidden text, expose it."
10229 (interactive)
10230 (funcall 'org-next-link t))
10232 (defun org-translate-link (s)
10233 "Translate a link string if a translation function has been defined."
10234 (if (and org-link-translation-function
10235 (fboundp org-link-translation-function)
10236 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10237 (progn
10238 (setq s (funcall org-link-translation-function
10239 (match-string 1 s) (match-string 2 s)))
10240 (concat (car s) ":" (cdr s)))
10243 (defun org-translate-link-from-planner (type path)
10244 "Translate a link from Emacs Planner syntax so that Org can follow it.
10245 This is still an experimental function, your mileage may vary."
10246 (cond
10247 ((member type '("http" "https" "news" "ftp"))
10248 ;; standard Internet links are the same.
10249 nil)
10250 ((and (equal type "irc") (string-match "^//" path))
10251 ;; Planner has two / at the beginning of an irc link, we have 1.
10252 ;; We should have zero, actually....
10253 (setq path (substring path 1)))
10254 ((and (equal type "lisp") (string-match "^/" path))
10255 ;; Planner has a slash, we do not.
10256 (setq type "elisp" path (substring path 1)))
10257 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10258 ;; A typical message link. Planner has the id after the final slash,
10259 ;; we separate it with a hash mark
10260 (setq path (concat (match-string 1 path) "#"
10261 (org-remove-angle-brackets (match-string 2 path))))))
10262 (cons type path))
10264 (defun org-find-file-at-mouse (ev)
10265 "Open file link or URL at mouse."
10266 (interactive "e")
10267 (mouse-set-point ev)
10268 (org-open-at-point 'in-emacs))
10270 (defun org-open-at-mouse (ev)
10271 "Open file link or URL at mouse.
10272 See the docstring of `org-open-file' for details."
10273 (interactive "e")
10274 (mouse-set-point ev)
10275 (if (eq major-mode 'org-agenda-mode)
10276 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10277 (org-open-at-point))
10279 (defvar org-window-config-before-follow-link nil
10280 "The window configuration before following a link.
10281 This is saved in case the need arises to restore it.")
10283 (defvar org-open-link-marker (make-marker)
10284 "Marker pointing to the location where `org-open-at-point; was called.")
10286 ;;;###autoload
10287 (defun org-open-at-point-global ()
10288 "Follow a link like Org-mode does.
10289 This command can be called in any mode to follow a link that has
10290 Org-mode syntax."
10291 (interactive)
10292 (org-run-like-in-org-mode 'org-open-at-point))
10294 ;;;###autoload
10295 (defun org-open-link-from-string (s &optional arg reference-buffer)
10296 "Open a link in the string S, as if it was in Org-mode."
10297 (interactive "sLink: \nP")
10298 (let ((reference-buffer (or reference-buffer (current-buffer))))
10299 (with-temp-buffer
10300 (let ((org-inhibit-startup (not reference-buffer)))
10301 (org-mode)
10302 (insert s)
10303 (goto-char (point-min))
10304 (when reference-buffer
10305 (setq org-link-abbrev-alist-local
10306 (with-current-buffer reference-buffer
10307 org-link-abbrev-alist-local)))
10308 (org-open-at-point arg reference-buffer)))))
10310 (defvar org-open-at-point-functions nil
10311 "Hook that is run when following a link at point.
10313 Functions in this hook must return t if they identify and follow
10314 a link at point. If they don't find anything interesting at point,
10315 they must return nil.")
10317 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10318 (defun org-open-at-point (&optional arg reference-buffer)
10319 "Open link at or after point.
10320 If there is no link at point, this function will search forward up to
10321 the end of the current line.
10322 Normally, files will be opened by an appropriate application. If the
10323 optional prefix argument ARG is non-nil, Emacs will visit the file.
10324 With a double prefix argument, try to open outside of Emacs, in the
10325 application the system uses for this file type."
10326 (interactive "P")
10327 ;; if in a code block, then open the block's results
10328 (unless (call-interactively #'org-babel-open-src-block-result)
10329 (org-load-modules-maybe)
10330 (move-marker org-open-link-marker (point))
10331 (setq org-window-config-before-follow-link (current-window-configuration))
10332 (org-remove-occur-highlights nil nil t)
10333 (cond
10334 ((and (org-at-heading-p)
10335 (not (org-at-timestamp-p t))
10336 (not (org-in-regexp
10337 (concat org-plain-link-re "\\|"
10338 org-bracket-link-regexp "\\|"
10339 org-angle-link-re "\\|"
10340 "[ \t]:[^ \t\n]+:[ \t]*$")))
10341 (not (get-text-property (point) 'org-linked-text)))
10342 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10343 (lk0 (car lkall))
10344 (lk (if (stringp lk0) (list lk0) lk0))
10345 (lkend (cdr lkall)))
10346 (mapcar (lambda(l)
10347 (search-forward l nil lkend)
10348 (goto-char (match-beginning 0))
10349 (org-open-at-point))
10350 lk))
10351 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10352 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10353 ((and (org-at-timestamp-p t)
10354 (not (org-in-regexp org-bracket-link-regexp)))
10355 (org-follow-timestamp-link))
10356 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10357 (not (org-in-regexp org-any-link-re)))
10358 (org-footnote-action))
10360 (let (type path link line search (pos (point)))
10361 (catch 'match
10362 (save-excursion
10363 (skip-chars-forward "^]\n\r")
10364 (when (org-in-regexp org-bracket-link-regexp 1)
10365 (setq link (org-extract-attributes
10366 (org-link-unescape (org-match-string-no-properties 1))))
10367 (while (string-match " *\n *" link)
10368 (setq link (replace-match " " t t link)))
10369 (setq link (org-link-expand-abbrev link))
10370 (cond
10371 ((or (file-name-absolute-p link)
10372 (string-match "^\\.\\.?/" link))
10373 (setq type "file" path link))
10374 ((string-match org-link-re-with-space3 link)
10375 (setq type (match-string 1 link) path (match-string 2 link)))
10376 ((string-match "^help:+\\(.+\\)" link)
10377 (setq type "help" path (match-string 1 link)))
10378 (t (setq type "thisfile" path link)))
10379 (throw 'match t)))
10381 (when (get-text-property (point) 'org-linked-text)
10382 (setq type "thisfile"
10383 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10384 (1+ (point)) (point))
10385 path (buffer-substring
10386 (or (previous-single-property-change pos 'org-linked-text)
10387 (point-min))
10388 (or (next-single-property-change pos 'org-linked-text)
10389 (point-max)))
10390 ;; Ensure we will search for a <<<radio>>> link, not
10391 ;; a simple reference like <<ref>>
10392 path (concat "<" path))
10393 (throw 'match t))
10395 (save-excursion
10396 (when (or (org-in-regexp org-angle-link-re)
10397 (let ((match (org-in-regexp org-plain-link-re)))
10398 ;; Check a plain link is not within a bracket link
10399 (and match
10400 (save-excursion
10401 (progn
10402 (goto-char (car match))
10403 (not (org-in-regexp org-bracket-link-regexp))))))
10404 (let ((line_ending (save-excursion (end-of-line) (point))))
10405 ;; We are in a line before a plain or bracket link
10406 (or (re-search-forward org-plain-link-re line_ending t)
10407 (re-search-forward org-bracket-link-regexp line_ending t))))
10408 (setq type (match-string 1)
10409 path (org-link-unescape (match-string 2)))
10410 (throw 'match t)))
10411 (save-excursion
10412 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10413 (setq type "tags"
10414 path (match-string 1))
10415 (while (string-match ":" path)
10416 (setq path (replace-match "+" t t path)))
10417 (throw 'match t)))
10418 (when (org-in-regexp "<\\([^><\n]+\\)>")
10419 (setq type "tree-match"
10420 path (match-string 1))
10421 (throw 'match t)))
10422 (unless path
10423 (user-error "No link found"))
10425 ;; switch back to reference buffer
10426 ;; needed when if called in a temporary buffer through
10427 ;; org-open-link-from-string
10428 (with-current-buffer (or reference-buffer (current-buffer))
10430 ;; Remove any trailing spaces in path
10431 (if (string-match " +\\'" path)
10432 (setq path (replace-match "" t t path)))
10433 (if (and org-link-translation-function
10434 (fboundp org-link-translation-function))
10435 ;; Check if we need to translate the link
10436 (let ((tmp (funcall org-link-translation-function type path)))
10437 (setq type (car tmp) path (cdr tmp))))
10439 (cond
10441 ((assoc type org-link-protocols)
10442 (funcall (nth 1 (assoc type org-link-protocols)) path))
10444 ((equal type "help")
10445 (let ((f-or-v (intern path)))
10446 (cond ((fboundp f-or-v)
10447 (describe-function f-or-v))
10448 ((boundp f-or-v)
10449 (describe-variable f-or-v))
10450 (t (error "Not a known function or variable")))))
10452 ((equal type "mailto")
10453 (let ((cmd (car org-link-mailto-program))
10454 (args (cdr org-link-mailto-program)) args1
10455 (address path) (subject "") a)
10456 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10457 (setq address (match-string 1 path)
10458 subject (org-link-escape (match-string 2 path))))
10459 (while args
10460 (cond
10461 ((not (stringp (car args))) (push (pop args) args1))
10462 (t (setq a (pop args))
10463 (if (string-match "%a" a)
10464 (setq a (replace-match address t t a)))
10465 (if (string-match "%s" a)
10466 (setq a (replace-match subject t t a)))
10467 (push a args1))))
10468 (apply cmd (nreverse args1))))
10470 ((member type '("http" "https" "ftp" "news"))
10471 (browse-url
10472 (concat type ":"
10473 (if (org-string-match-p
10474 (concat "[[:nonascii:]"
10475 org-link-escape-chars-browser "]")
10476 path)
10477 (org-link-escape path org-link-escape-chars-browser)
10478 path))))
10480 ((string= type "doi")
10481 (browse-url
10482 (concat org-doi-server-url
10483 (if (org-string-match-p
10484 (concat "[[:nonascii:]"
10485 org-link-escape-chars-browser "]")
10486 path)
10487 (org-link-escape path org-link-escape-chars-browser)
10488 path))))
10490 ((member type '("message"))
10491 (browse-url (concat type ":" path)))
10493 ((string= type "tags")
10494 (org-tags-view arg path))
10496 ((string= type "tree-match")
10497 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10499 ((string= type "file")
10500 (if (string-match "::\\([0-9]+\\)\\'" path)
10501 (setq line (string-to-number (match-string 1 path))
10502 path (substring path 0 (match-beginning 0)))
10503 (if (string-match "::\\(.+\\)\\'" path)
10504 (setq search (match-string 1 path)
10505 path (substring path 0 (match-beginning 0)))))
10506 (if (string-match "[*?{]" (file-name-nondirectory path))
10507 (dired path)
10508 (org-open-file path arg line search)))
10510 ((string= type "shell")
10511 (let ((buf (generate-new-buffer "*Org Shell Output"))
10512 (cmd path))
10513 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10514 (string-match org-confirm-shell-link-not-regexp cmd))
10515 (not org-confirm-shell-link-function)
10516 (funcall org-confirm-shell-link-function
10517 (format "Execute \"%s\" in shell? "
10518 (org-add-props cmd nil
10519 'face 'org-warning))))
10520 (progn
10521 (message "Executing %s" cmd)
10522 (shell-command cmd buf)
10523 (if (featurep 'midnight)
10524 (setq clean-buffer-list-kill-buffer-names
10525 (cons buf clean-buffer-list-kill-buffer-names))))
10526 (error "Abort"))))
10528 ((string= type "elisp")
10529 (let ((cmd path))
10530 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10531 (string-match org-confirm-elisp-link-not-regexp cmd))
10532 (not org-confirm-elisp-link-function)
10533 (funcall org-confirm-elisp-link-function
10534 (format "Execute \"%s\" as elisp? "
10535 (org-add-props cmd nil
10536 'face 'org-warning))))
10537 (message "%s => %s" cmd
10538 (if (equal (string-to-char cmd) ?\()
10539 (eval (read cmd))
10540 (call-interactively (read cmd))))
10541 (error "Abort"))))
10543 ((and (string= type "thisfile")
10544 (or (run-hook-with-args-until-success
10545 'org-open-link-functions path)
10546 (and (string-match "^id:" link)
10547 (or (featurep 'org-id) (require 'org-id))
10548 (progn
10549 (funcall (nth 1 (assoc "id" org-link-protocols))
10550 (substring path 3))
10551 t)))))
10553 ((string= type "thisfile")
10554 (if arg
10555 (switch-to-buffer-other-window
10556 (org-get-buffer-for-internal-link (current-buffer)))
10557 (org-mark-ring-push))
10558 (let ((cmd `(org-link-search
10559 ,path
10560 ,(cond ((equal arg '(4)) ''occur)
10561 ((equal arg '(16)) ''org-occur))
10562 ,pos)))
10563 (condition-case nil (let ((org-link-search-inhibit-query t))
10564 (eval cmd))
10565 (error (progn (widen) (eval cmd))))))
10567 (t (browse-url-at-point)))))))
10568 (move-marker org-open-link-marker nil)
10569 (run-hook-with-args 'org-follow-link-hook)))
10571 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10572 "Offer links in the current entry and return the selected link.
10573 If there is only one link, return it.
10574 If NTH is an integer, return the NTH link found.
10575 If ZERO is a string, check also this string for a link, and if
10576 there is one, return it."
10577 (with-current-buffer buffer
10578 (save-excursion
10579 (save-restriction
10580 (widen)
10581 (goto-char marker)
10582 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10583 "\\(" org-angle-link-re "\\)\\|"
10584 "\\(" org-plain-link-re "\\)"))
10585 (cnt ?0)
10586 (in-emacs (if (integerp nth) nil nth))
10587 have-zero end links link c)
10588 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10589 (push (match-string 0 zero) links)
10590 (setq cnt (1- cnt) have-zero t))
10591 (save-excursion
10592 (org-back-to-heading t)
10593 (setq end (save-excursion (outline-next-heading) (point)))
10594 (while (re-search-forward re end t)
10595 (push (match-string 0) links))
10596 (setq links (org-uniquify (reverse links))))
10597 (cond
10598 ((null links)
10599 (message "No links"))
10600 ((equal (length links) 1)
10601 (setq link (car links)))
10602 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10603 (setq link (nth (if have-zero nth (1- nth)) links)))
10604 (t ; we have to select a link
10605 (save-excursion
10606 (save-window-excursion
10607 (delete-other-windows)
10608 (with-output-to-temp-buffer "*Select Link*"
10609 (mapc (lambda (l)
10610 (if (not (string-match org-bracket-link-regexp l))
10611 (princ (format "[%c] %s\n" (incf cnt)
10612 (org-remove-angle-brackets l)))
10613 (if (match-end 3)
10614 (princ (format "[%c] %s (%s)\n" (incf cnt)
10615 (match-string 3 l) (match-string 1 l)))
10616 (princ (format "[%c] %s\n" (incf cnt)
10617 (match-string 1 l))))))
10618 links))
10619 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10620 (message "Select link to open, RET to open all:")
10621 (setq c (read-char-exclusive))
10622 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10623 (when (equal c ?q) (error "Abort"))
10624 (if (equal c ?\C-m)
10625 (setq link links)
10626 (setq nth (- c ?0))
10627 (if have-zero (setq nth (1+ nth)))
10628 (unless (and (integerp nth) (>= (length links) nth))
10629 (user-error "Invalid link selection"))
10630 (setq link (nth (1- nth) links)))))
10631 (cons link end))))))
10633 ;; Add special file links that specify the way of opening
10635 (org-add-link-type "file+sys" 'org-open-file-with-system)
10636 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10637 (defun org-open-file-with-system (path)
10638 "Open file at PATH using the system way of opening it."
10639 (org-open-file path 'system))
10640 (defun org-open-file-with-emacs (path)
10641 "Open file at PATH in Emacs."
10642 (org-open-file path 'emacs))
10645 ;;; File search
10647 (defvar org-create-file-search-functions nil
10648 "List of functions to construct the right search string for a file link.
10649 These functions are called in turn with point at the location to
10650 which the link should point.
10652 A function in the hook should first test if it would like to
10653 handle this file type, for example by checking the `major-mode'
10654 or the file extension. If it decides not to handle this file, it
10655 should just return nil to give other functions a chance. If it
10656 does handle the file, it must return the search string to be used
10657 when following the link. The search string will be part of the
10658 file link, given after a double colon, and `org-open-at-point'
10659 will automatically search for it. If special measures must be
10660 taken to make the search successful, another function should be
10661 added to the companion hook `org-execute-file-search-functions',
10662 which see.
10664 A function in this hook may also use `setq' to set the variable
10665 `description' to provide a suggestion for the descriptive text to
10666 be used for this link when it gets inserted into an Org-mode
10667 buffer with \\[org-insert-link].")
10669 (defvar org-execute-file-search-functions nil
10670 "List of functions to execute a file search triggered by a link.
10672 Functions added to this hook must accept a single argument, the
10673 search string that was part of the file link, the part after the
10674 double colon. The function must first check if it would like to
10675 handle this search, for example by checking the `major-mode' or
10676 the file extension. If it decides not to handle this search, it
10677 should just return nil to give other functions a chance. If it
10678 does handle the search, it must return a non-nil value to keep
10679 other functions from trying.
10681 Each function can access the current prefix argument through the
10682 variable `current-prefix-arg'. Note that a single prefix is used
10683 to force opening a link in Emacs, so it may be good to only use a
10684 numeric or double prefix to guide the search function.
10686 In case this is needed, a function in this hook can also restore
10687 the window configuration before `org-open-at-point' was called using:
10689 (set-window-configuration org-window-config-before-follow-link)")
10691 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10692 (defun org-link-search (s &optional type avoid-pos stealth)
10693 "Search for a link search option.
10694 If S is surrounded by forward slashes, it is interpreted as a
10695 regular expression. In org-mode files, this will create an `org-occur'
10696 sparse tree. In ordinary files, `occur' will be used to list matches.
10697 If the current buffer is in `dired-mode', grep will be used to search
10698 in all files. If AVOID-POS is given, ignore matches near that position.
10700 When optional argument STEALTH is non-nil, do not modify
10701 visibility around point, thus ignoring
10702 `org-show-hierarchy-above', `org-show-following-heading' and
10703 `org-show-siblings' variables."
10704 (let ((case-fold-search t)
10705 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10706 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10707 (append '(("") (" ") ("\t") ("\n"))
10708 org-emphasis-alist)
10709 "\\|") "\\)"))
10710 (pos (point))
10711 (pre nil) (post nil)
10712 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10713 (cond
10714 ;; First check if there are any special search functions
10715 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10716 ;; Now try the builtin stuff
10717 ((and (equal (string-to-char s0) ?#)
10718 (> (length s0) 1)
10719 (save-excursion
10720 (goto-char (point-min))
10721 (and
10722 (re-search-forward
10723 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10724 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10725 (setq type 'dedicated
10726 pos (match-beginning 0))))
10727 ;; There is an exact target for this
10728 (goto-char pos)
10729 (org-back-to-heading t)))
10730 ((save-excursion
10731 (goto-char (point-min))
10732 (and
10733 (re-search-forward
10734 (concat "<<" (regexp-quote s0) ">>") nil t)
10735 (setq type 'dedicated
10736 pos (match-beginning 0))))
10737 ;; There is an exact target for this
10738 (goto-char pos))
10739 ((save-excursion
10740 (goto-char (point-min))
10741 (and
10742 (re-search-forward
10743 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10744 (setq type 'dedicated pos (match-beginning 0))))
10745 ;; Found an element with a matching #+name affiliated keyword.
10746 (goto-char pos))
10747 ((and (string-match "^(\\(.*\\))$" s0)
10748 (save-excursion
10749 (goto-char (point-min))
10750 (and
10751 (re-search-forward
10752 (concat "[^[]" (regexp-quote
10753 (format org-coderef-label-format
10754 (match-string 1 s0))))
10755 nil t)
10756 (setq type 'dedicated
10757 pos (1+ (match-beginning 0))))))
10758 ;; There is a coderef target for this
10759 (goto-char pos))
10760 ((string-match "^/\\(.*\\)/$" s)
10761 ;; A regular expression
10762 (cond
10763 ((derived-mode-p 'org-mode)
10764 (org-occur (match-string 1 s)))
10765 (t (org-do-occur (match-string 1 s)))))
10766 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10767 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10768 (goto-char (point-min))
10769 (cond
10770 ((let (case-fold-search)
10771 (re-search-forward (format org-complex-heading-regexp-format
10772 (regexp-quote s))
10773 nil t))
10774 ;; OK, found a match
10775 (setq type 'dedicated)
10776 (goto-char (match-beginning 0)))
10777 ((and (not org-link-search-inhibit-query)
10778 (eq org-link-search-must-match-exact-headline 'query-to-create)
10779 (y-or-n-p "No match - create this as a new heading? "))
10780 (goto-char (point-max))
10781 (or (bolp) (newline))
10782 (insert "* " s "\n")
10783 (beginning-of-line 0))
10785 (goto-char pos)
10786 (error "No match"))))
10788 ;; A normal search string
10789 (when (equal (string-to-char s) ?*)
10790 ;; Anchor on headlines, post may include tags.
10791 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10792 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10793 s (substring s 1)))
10794 (remove-text-properties
10795 0 (length s)
10796 '(face nil mouse-face nil keymap nil fontified nil) s)
10797 ;; Make a series of regular expressions to find a match
10798 (setq words (org-split-string s "[ \n\r\t]+")
10800 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10801 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10802 "\\)" markers)
10803 re2a_ (concat "\\(" (mapconcat 'downcase words
10804 "[ \t\r\n]+") "\\)[ \t\r\n]")
10805 re2a (concat "[ \t\r\n]" re2a_)
10806 re4_ (concat "\\(" (mapconcat 'downcase words
10807 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10808 re4 (concat "[^a-zA-Z_]" re4_)
10810 re1 (concat pre re2 post)
10811 re3 (concat pre (if pre re4_ re4) post)
10812 re5 (concat pre ".*" re4)
10813 re2 (concat pre re2)
10814 re2a (concat pre (if pre re2a_ re2a))
10815 re4 (concat pre (if pre re4_ re4))
10816 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10817 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10818 re5 "\\)"))
10819 (cond
10820 ((eq type 'org-occur) (org-occur reall))
10821 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10822 (t (goto-char (point-min))
10823 (setq type 'fuzzy)
10824 (if (or (and (org-search-not-self 1 re0 nil t)
10825 (setq type 'dedicated))
10826 (org-search-not-self 1 re1 nil t)
10827 (org-search-not-self 1 re2 nil t)
10828 (org-search-not-self 1 re2a nil t)
10829 (org-search-not-self 1 re3 nil t)
10830 (org-search-not-self 1 re4 nil t)
10831 (org-search-not-self 1 re5 nil t))
10832 (goto-char (match-beginning 1))
10833 (goto-char pos)
10834 (error "No match"))))))
10835 (and (derived-mode-p 'org-mode)
10836 (not stealth)
10837 (org-show-context 'link-search))
10838 type))
10840 (defun org-search-not-self (group &rest args)
10841 "Execute `re-search-forward', but only accept matches that do not
10842 enclose the position of `org-open-link-marker'."
10843 (let ((m org-open-link-marker))
10844 (catch 'exit
10845 (while (apply 're-search-forward args)
10846 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10847 (goto-char (match-end group))
10848 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10849 (> (match-beginning 0) (marker-position m))
10850 (< (match-end 0) (marker-position m)))
10851 (save-match-data
10852 (or (not (org-in-regexp
10853 org-bracket-link-analytic-regexp 1))
10854 (not (match-end 4)) ; no description
10855 (and (<= (match-beginning 4) (point))
10856 (>= (match-end 4) (point))))))
10857 (throw 'exit (point))))))))
10859 (defun org-get-buffer-for-internal-link (buffer)
10860 "Return a buffer to be used for displaying the link target of internal links."
10861 (cond
10862 ((not org-display-internal-link-with-indirect-buffer)
10863 buffer)
10864 ((string-match "(Clone)$" (buffer-name buffer))
10865 (message "Buffer is already a clone, not making another one")
10866 ;; we also do not modify visibility in this case
10867 buffer)
10868 (t ; make a new indirect buffer for displaying the link
10869 (let* ((bn (buffer-name buffer))
10870 (ibn (concat bn "(Clone)"))
10871 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10872 (with-current-buffer ib (org-overview))
10873 ib))))
10875 (defun org-do-occur (regexp &optional cleanup)
10876 "Call the Emacs command `occur'.
10877 If CLEANUP is non-nil, remove the printout of the regular expression
10878 in the *Occur* buffer. This is useful if the regex is long and not useful
10879 to read."
10880 (occur regexp)
10881 (when cleanup
10882 (let ((cwin (selected-window)) win beg end)
10883 (when (setq win (get-buffer-window "*Occur*"))
10884 (select-window win))
10885 (goto-char (point-min))
10886 (when (re-search-forward "match[a-z]+" nil t)
10887 (setq beg (match-end 0))
10888 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10889 (setq end (1- (match-beginning 0)))))
10890 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10891 (goto-char (point-min))
10892 (select-window cwin))))
10894 ;;; The mark ring for links jumps
10896 (defvar org-mark-ring nil
10897 "Mark ring for positions before jumps in Org-mode.")
10898 (defvar org-mark-ring-last-goto nil
10899 "Last position in the mark ring used to go back.")
10900 ;; Fill and close the ring
10901 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10902 (loop for i from 1 to org-mark-ring-length do
10903 (push (make-marker) org-mark-ring))
10904 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10905 org-mark-ring)
10907 (defun org-mark-ring-push (&optional pos buffer)
10908 "Put the current position or POS into the mark ring and rotate it."
10909 (interactive)
10910 (setq pos (or pos (point)))
10911 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10912 (move-marker (car org-mark-ring)
10913 (or pos (point))
10914 (or buffer (current-buffer)))
10915 (message "%s"
10916 (substitute-command-keys
10917 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10919 (defun org-mark-ring-goto (&optional n)
10920 "Jump to the previous position in the mark ring.
10921 With prefix arg N, jump back that many stored positions. When
10922 called several times in succession, walk through the entire ring.
10923 Org-mode commands jumping to a different position in the current file,
10924 or to another Org-mode file, automatically push the old position
10925 onto the ring."
10926 (interactive "p")
10927 (let (p m)
10928 (if (eq last-command this-command)
10929 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10930 (setq p org-mark-ring))
10931 (setq org-mark-ring-last-goto p)
10932 (setq m (car p))
10933 (org-pop-to-buffer-same-window (marker-buffer m))
10934 (goto-char m)
10935 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10937 (defun org-remove-angle-brackets (s)
10938 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10939 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10941 (defun org-add-angle-brackets (s)
10942 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10943 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10945 (defun org-remove-double-quotes (s)
10946 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10947 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10950 ;;; Following specific links
10952 (defun org-follow-timestamp-link ()
10953 "Open an agenda view for the time-stamp date/range at point."
10954 (cond
10955 ((org-at-date-range-p t)
10956 (let ((org-agenda-start-on-weekday)
10957 (t1 (match-string 1))
10958 (t2 (match-string 2)) tt1 tt2)
10959 (setq tt1 (time-to-days (org-time-string-to-time t1))
10960 tt2 (time-to-days (org-time-string-to-time t2)))
10961 (let ((org-agenda-buffer-tmp-name
10962 (format "*Org Agenda(a:%s)"
10963 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10964 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10965 ((org-at-timestamp-p t)
10966 (let ((org-agenda-buffer-tmp-name
10967 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10968 (org-agenda-list nil (time-to-days (org-time-string-to-time
10969 (substring (match-string 1) 0 10)))
10970 1)))
10971 (t (error "This should not happen"))))
10974 ;;; Following file links
10975 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10976 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10977 (declare-function mailcap-mime-info
10978 "mailcap" (string &optional request no-decode))
10979 (defvar org-wait nil)
10980 (defun org-open-file (path &optional in-emacs line search)
10981 "Open the file at PATH.
10982 First, this expands any special file name abbreviations. Then the
10983 configuration variable `org-file-apps' is checked if it contains an
10984 entry for this file type, and if yes, the corresponding command is launched.
10986 If no application is found, Emacs simply visits the file.
10988 With optional prefix argument IN-EMACS, Emacs will visit the file.
10989 With a double \\[universal-argument] \\[universal-argument] \
10990 prefix arg, Org tries to avoid opening in Emacs
10991 and to use an external application to visit the file.
10993 Optional LINE specifies a line to go to, optional SEARCH a string
10994 to search for. If LINE or SEARCH is given, the file will be
10995 opened in Emacs, unless an entry from org-file-apps that makes
10996 use of groups in a regexp matches.
10998 If you want to change the way frames are used when following a
10999 link, please customize `org-link-frame-setup'.
11001 If the file does not exist, an error is thrown."
11002 (let* ((file (if (equal path "")
11003 buffer-file-name
11004 (substitute-in-file-name (expand-file-name path))))
11005 (file-apps (append org-file-apps (org-default-apps)))
11006 (apps (org-remove-if
11007 'org-file-apps-entry-match-against-dlink-p file-apps))
11008 (apps-dlink (org-remove-if-not
11009 'org-file-apps-entry-match-against-dlink-p file-apps))
11010 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11011 (dirp (if remp nil (file-directory-p file)))
11012 (file (if (and dirp org-open-directory-means-index-dot-org)
11013 (concat (file-name-as-directory file) "index.org")
11014 file))
11015 (a-m-a-p (assq 'auto-mode apps))
11016 (dfile (downcase file))
11017 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11018 (link (cond ((and (eq line nil)
11019 (eq search nil))
11020 file)
11021 (line
11022 (concat file "::" (number-to-string line)))
11023 (search
11024 (concat file "::" search))))
11025 (dlink (downcase link))
11026 (old-buffer (current-buffer))
11027 (old-pos (point))
11028 (old-mode major-mode)
11029 ext cmd link-match-data)
11030 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11031 (setq ext (match-string 1 dfile))
11032 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11033 (setq ext (match-string 1 dfile))))
11034 (cond
11035 ((member in-emacs '((16) system))
11036 (setq cmd (cdr (assoc 'system apps))))
11037 (in-emacs (setq cmd 'emacs))
11039 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11040 (and dirp (cdr (assoc 'directory apps)))
11041 ; first, try matching against apps-dlink
11042 ; if we get a match here, store the match data for later
11043 (let ((match (assoc-default dlink apps-dlink
11044 'string-match)))
11045 (if match
11046 (progn (setq link-match-data (match-data))
11047 match)
11048 (progn (setq in-emacs (or in-emacs line search))
11049 nil))) ; if we have no match in apps-dlink,
11050 ; always open the file in emacs if line or search
11051 ; is given (for backwards compatibility)
11052 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11053 'string-match)
11054 (cdr (assoc ext apps))
11055 (cdr (assoc t apps))))))
11056 (when (eq cmd 'system)
11057 (setq cmd (cdr (assoc 'system apps))))
11058 (when (eq cmd 'default)
11059 (setq cmd (cdr (assoc t apps))))
11060 (when (eq cmd 'mailcap)
11061 (require 'mailcap)
11062 (mailcap-parse-mailcaps)
11063 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11064 (command (mailcap-mime-info mime-type)))
11065 (if (stringp command)
11066 (setq cmd command)
11067 (setq cmd 'emacs))))
11068 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11069 (not (file-exists-p file))
11070 (not org-open-non-existing-files))
11071 (user-error "No such file: %s" file))
11072 (cond
11073 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11074 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11075 (while (string-match "['\"]%s['\"]" cmd)
11076 (setq cmd (replace-match "%s" t t cmd)))
11077 (while (string-match "%s" cmd)
11078 (setq cmd (replace-match
11079 (save-match-data
11080 (shell-quote-argument
11081 (convert-standard-filename file)))
11082 t t cmd)))
11084 ;; Replace "%1", "%2" etc. in command with group matches from regex
11085 (save-match-data
11086 (let ((match-index 1)
11087 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11088 (set-match-data link-match-data)
11089 (while (<= match-index number-of-groups)
11090 (let ((regex (concat "%" (number-to-string match-index)))
11091 (replace-with (match-string match-index dlink)))
11092 (while (string-match regex cmd)
11093 (setq cmd (replace-match replace-with t t cmd))))
11094 (setq match-index (+ match-index 1)))))
11096 (save-window-excursion
11097 (message "Running %s...done" cmd)
11098 (start-process-shell-command cmd nil cmd)
11099 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11100 ((or (stringp cmd)
11101 (eq cmd 'emacs))
11102 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11103 (widen)
11104 (if line (org-goto-line line)
11105 (if search (org-link-search search))))
11106 ((consp cmd)
11107 (let ((file (convert-standard-filename file)))
11108 (save-match-data
11109 (set-match-data link-match-data)
11110 (eval cmd))))
11111 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11112 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11113 (or (not (equal old-buffer (current-buffer)))
11114 (not (equal old-pos (point))))
11115 (org-mark-ring-push old-pos old-buffer))))
11117 (defun org-file-apps-entry-match-against-dlink-p (entry)
11118 "This function returns non-nil if `entry' uses a regular
11119 expression which should be matched against the whole link by
11120 org-open-file.
11122 It assumes that is the case when the entry uses a regular
11123 expression which has at least one grouping construct and the
11124 action is either a lisp form or a command string containing
11125 '%1', i.e. using at least one subexpression match as a
11126 parameter."
11127 (let ((selector (car entry))
11128 (action (cdr entry)))
11129 (if (stringp selector)
11130 (and (> (regexp-opt-depth selector) 0)
11131 (or (and (stringp action)
11132 (string-match "%[0-9]" action))
11133 (consp action)))
11134 nil)))
11136 (defun org-default-apps ()
11137 "Return the default applications for this operating system."
11138 (cond
11139 ((eq system-type 'darwin)
11140 org-file-apps-defaults-macosx)
11141 ((eq system-type 'windows-nt)
11142 org-file-apps-defaults-windowsnt)
11143 (t org-file-apps-defaults-gnu)))
11145 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11146 "Convert extensions to regular expressions in the cars of LIST.
11147 Also, weed out any non-string entries, because the return value is used
11148 only for regexp matching.
11149 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11150 point to the symbol `emacs', indicating that the file should
11151 be opened in Emacs."
11152 (append
11153 (delq nil
11154 (mapcar (lambda (x)
11155 (if (not (stringp (car x)))
11157 (if (string-match "\\W" (car x))
11159 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11160 list))
11161 (if add-auto-mode
11162 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11164 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11165 (defun org-file-remote-p (file)
11166 "Test whether FILE specifies a location on a remote system.
11167 Return non-nil if the location is indeed remote.
11169 For example, the filename \"/user@host:/foo\" specifies a location
11170 on the system \"/user@host:\"."
11171 (cond ((fboundp 'file-remote-p)
11172 (file-remote-p file))
11173 ((fboundp 'tramp-handle-file-remote-p)
11174 (tramp-handle-file-remote-p file))
11175 ((and (boundp 'ange-ftp-name-format)
11176 (string-match (car ange-ftp-name-format) file))
11177 t)))
11180 ;;;; Refiling
11182 (defun org-get-org-file ()
11183 "Read a filename, with default directory `org-directory'."
11184 (let ((default (or org-default-notes-file remember-data-file)))
11185 (read-file-name (format "File name [%s]: " default)
11186 (file-name-as-directory org-directory)
11187 default)))
11189 (defun org-notes-order-reversed-p ()
11190 "Check if the current file should receive notes in reversed order."
11191 (cond
11192 ((not org-reverse-note-order) nil)
11193 ((eq t org-reverse-note-order) t)
11194 ((not (listp org-reverse-note-order)) nil)
11195 (t (catch 'exit
11196 (let ((all org-reverse-note-order)
11197 entry)
11198 (while (setq entry (pop all))
11199 (if (string-match (car entry) buffer-file-name)
11200 (throw 'exit (cdr entry))))
11201 nil)))))
11203 (defvar org-refile-target-table nil
11204 "The list of refile targets, created by `org-refile'.")
11206 (defvar org-agenda-new-buffers nil
11207 "Buffers created to visit agenda files.")
11209 (defvar org-refile-cache nil
11210 "Cache for refile targets.")
11212 (defvar org-refile-markers nil
11213 "All the markers used for caching refile locations.")
11215 (defun org-refile-marker (pos)
11216 "Get a new refile marker, but only if caching is in use."
11217 (if (not org-refile-use-cache)
11219 (let ((m (make-marker)))
11220 (move-marker m pos)
11221 (push m org-refile-markers)
11222 m)))
11224 (defun org-refile-cache-clear ()
11225 "Clear the refile cache and disable all the markers."
11226 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11227 (setq org-refile-markers nil)
11228 (setq org-refile-cache nil)
11229 (message "Refile cache has been cleared"))
11231 (defun org-refile-cache-check-set (set)
11232 "Check if all the markers in the cache still have live buffers."
11233 (let (marker)
11234 (catch 'exit
11235 (while (and set (setq marker (nth 3 (pop set))))
11236 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11237 (when (and marker (null (marker-buffer marker)))
11238 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11239 (sit-for 3)
11240 (throw 'exit nil)))
11241 t)))
11243 (defun org-refile-cache-put (set &rest identifiers)
11244 "Push the refile targets SET into the cache, under IDENTIFIERS."
11245 (let* ((key (sha1 (prin1-to-string identifiers)))
11246 (entry (assoc key org-refile-cache)))
11247 (if entry
11248 (setcdr entry set)
11249 (push (cons key set) org-refile-cache))))
11251 (defun org-refile-cache-get (&rest identifiers)
11252 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11253 (cond
11254 ((not org-refile-cache) nil)
11255 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11257 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11258 org-refile-cache))))
11259 (and set (org-refile-cache-check-set set) set)))))
11261 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11262 "Produce a table with refile targets."
11263 (let ((case-fold-search nil)
11264 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11265 (entries (or org-refile-targets '((nil . (:level . 1)))))
11266 targets tgs txt re files f desc descre fast-path-p level pos0)
11267 (message "Getting targets...")
11268 (with-current-buffer (or default-buffer (current-buffer))
11269 (while (setq entry (pop entries))
11270 (setq files (car entry) desc (cdr entry))
11271 (setq fast-path-p nil)
11272 (cond
11273 ((null files) (setq files (list (current-buffer))))
11274 ((eq files 'org-agenda-files)
11275 (setq files (org-agenda-files 'unrestricted)))
11276 ((and (symbolp files) (fboundp files))
11277 (setq files (funcall files)))
11278 ((and (symbolp files) (boundp files))
11279 (setq files (symbol-value files))))
11280 (if (stringp files) (setq files (list files)))
11281 (cond
11282 ((eq (car desc) :tag)
11283 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11284 ((eq (car desc) :todo)
11285 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11286 ((eq (car desc) :regexp)
11287 (setq descre (cdr desc)))
11288 ((eq (car desc) :level)
11289 (setq descre (concat "^\\*\\{" (number-to-string
11290 (if org-odd-levels-only
11291 (1- (* 2 (cdr desc)))
11292 (cdr desc)))
11293 "\\}[ \t]")))
11294 ((eq (car desc) :maxlevel)
11295 (setq fast-path-p t)
11296 (setq descre (concat "^\\*\\{1," (number-to-string
11297 (if org-odd-levels-only
11298 (1- (* 2 (cdr desc)))
11299 (cdr desc)))
11300 "\\}[ \t]")))
11301 (t (error "Bad refiling target description %s" desc)))
11302 (while (setq f (pop files))
11303 (with-current-buffer
11304 (if (bufferp f) f (org-get-agenda-file-buffer f))
11306 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11307 (progn
11308 (if (bufferp f) (setq f (buffer-file-name
11309 (buffer-base-buffer f))))
11310 (setq f (and f (expand-file-name f)))
11311 (if (eq org-refile-use-outline-path 'file)
11312 (push (list (file-name-nondirectory f) f nil nil) tgs))
11313 (save-excursion
11314 (save-restriction
11315 (widen)
11316 (goto-char (point-min))
11317 (while (re-search-forward descre nil t)
11318 (goto-char (setq pos0 (point-at-bol)))
11319 (catch 'next
11320 (when org-refile-target-verify-function
11321 (save-match-data
11322 (or (funcall org-refile-target-verify-function)
11323 (throw 'next t))))
11324 (when (and (looking-at org-complex-heading-regexp)
11325 (not (member (match-string 4) excluded-entries))
11326 (match-string 4))
11327 (setq level (org-reduced-level
11328 (- (match-end 1) (match-beginning 1)))
11329 txt (org-link-display-format (match-string 4))
11330 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11331 re (format org-complex-heading-regexp-format
11332 (regexp-quote (match-string 4))))
11333 (when org-refile-use-outline-path
11334 (setq txt (mapconcat
11335 'org-protect-slash
11336 (append
11337 (if (eq org-refile-use-outline-path
11338 'file)
11339 (list (file-name-nondirectory
11340 (buffer-file-name
11341 (buffer-base-buffer))))
11342 (if (eq org-refile-use-outline-path
11343 'full-file-path)
11344 (list (buffer-file-name
11345 (buffer-base-buffer)))))
11346 (org-get-outline-path fast-path-p
11347 level txt)
11348 (list txt))
11349 "/")))
11350 (push (list txt f re (org-refile-marker (point)))
11351 tgs)))
11352 (when (= (point) pos0)
11353 ;; verification function has not moved point
11354 (goto-char (point-at-eol))))))))
11355 (when org-refile-use-cache
11356 (org-refile-cache-put tgs (buffer-file-name) descre))
11357 (setq targets (append tgs targets))))))
11358 (message "Getting targets...done")
11359 (nreverse targets)))
11361 (defun org-protect-slash (s)
11362 (while (string-match "/" s)
11363 (setq s (replace-match "\\" t t s)))
11366 (defvar org-olpa (make-vector 20 nil))
11368 (defun org-get-outline-path (&optional fastp level heading)
11369 "Return the outline path to the current entry, as a list.
11371 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11372 routine which makes outline path derivations for an entire file,
11373 avoiding backtracing. Refile target collection makes use of that."
11374 (if fastp
11375 (progn
11376 (if (> level 19)
11377 (error "Outline path failure, more than 19 levels"))
11378 (loop for i from level upto 19 do
11379 (aset org-olpa i nil))
11380 (prog1
11381 (delq nil (append org-olpa nil))
11382 (aset org-olpa level heading)))
11383 (let (rtn case-fold-search)
11384 (save-excursion
11385 (save-restriction
11386 (widen)
11387 (while (org-up-heading-safe)
11388 (when (looking-at org-complex-heading-regexp)
11389 (push (org-trim
11390 (replace-regexp-in-string
11391 ;; Remove statistical/checkboxes cookies
11392 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11393 (org-match-string-no-properties 4)))
11394 rtn)))
11395 rtn)))))
11397 (defun org-format-outline-path (path &optional width prefix separator)
11398 "Format the outline path PATH for display.
11399 WIDTH is the maximum number of characters that is available.
11400 PREFIX is a prefix to be included in the returned string,
11401 such as the file name.
11402 SEPARATOR is inserted between the different parts of the path,
11403 the default is \"/\"."
11404 (setq width (or width 79))
11405 (if prefix (setq width (- width (length prefix))))
11406 (if (not path)
11407 (or prefix "")
11408 (let* ((nsteps (length path))
11409 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11410 (maxwidth (if (<= total-width width)
11411 10000 ;; everything fits
11412 ;; we need to shorten the level headings
11413 (/ (- width nsteps) nsteps)))
11414 (org-odd-levels-only nil)
11415 (n 0)
11416 (total (1+ (length prefix))))
11417 (setq maxwidth (max maxwidth 10))
11418 (concat prefix
11419 (if prefix (or separator "/"))
11420 (mapconcat
11421 (lambda (h)
11422 (setq n (1+ n))
11423 (if (and (= n nsteps) (< maxwidth 10000))
11424 (setq maxwidth (- total-width total)))
11425 (if (< (length h) maxwidth)
11426 (progn (setq total (+ total (length h) 1)) h)
11427 (setq h (substring h 0 (- maxwidth 2))
11428 total (+ total maxwidth 1))
11429 (if (string-match "[ \t]+\\'" h)
11430 (setq h (substring h 0 (match-beginning 0))))
11431 (setq h (concat h "..")))
11432 (org-add-props h nil 'face
11433 (nth (% (1- n) org-n-level-faces)
11434 org-level-faces))
11436 path (or separator "/"))))))
11438 (defun org-display-outline-path (&optional file current separator just-return-string)
11439 "Display the current outline path in the echo area.
11441 If FILE is non-nil, prepend the output with the file name.
11442 If CURRENT is non-nil, append the current heading to the output.
11443 SEPARATOR is passed through to `org-format-outline-path'. It separates
11444 the different parts of the path and defaults to \"/\".
11445 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11446 (interactive "P")
11447 (let* (case-fold-search
11448 (bfn (buffer-file-name (buffer-base-buffer)))
11449 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11450 res)
11451 (if current (setq path (append path
11452 (save-excursion
11453 (org-back-to-heading t)
11454 (if (looking-at org-complex-heading-regexp)
11455 (list (match-string 4)))))))
11456 (setq res
11457 (org-format-outline-path
11458 path
11459 (1- (frame-width))
11460 (and file bfn (concat (file-name-nondirectory bfn) separator))
11461 separator))
11462 (if just-return-string
11463 (org-no-properties res)
11464 (org-unlogged-message "%s" res))))
11466 (defvar org-refile-history nil
11467 "History for refiling operations.")
11469 (defvar org-after-refile-insert-hook nil
11470 "Hook run after `org-refile' has inserted its stuff at the new location.
11471 Note that this is still *before* the stuff will be removed from
11472 the *old* location.")
11474 (defvar org-capture-last-stored-marker)
11475 (defvar org-refile-keep nil
11476 "Non-nil means `org-refile' will copy instead of refile.")
11478 (defun org-copy ()
11479 "Like `org-refile', but copy."
11480 (interactive)
11481 (let ((org-refile-keep t))
11482 (funcall 'org-refile nil nil nil "Copy")))
11484 (defun org-refile (&optional goto default-buffer rfloc msg)
11485 "Move the entry or entries at point to another heading.
11486 The list of target headings is compiled using the information in
11487 `org-refile-targets', which see.
11489 At the target location, the entry is filed as a subitem of the target
11490 heading. Depending on `org-reverse-note-order', the new subitem will
11491 either be the first or the last subitem.
11493 If there is an active region, all entries in that region will be moved.
11494 However, the region must fulfill the requirement that the first heading
11495 is the first one sets the top-level of the moved text - at most siblings
11496 below it are allowed.
11498 With prefix arg GOTO, the command will only visit the target location
11499 and not actually move anything.
11501 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11502 go to the location where the last refiling operation has put the subtree.
11504 With a numeric prefix argument of `2', refile to the running clock.
11506 With a numeric prefix argument of `3', emulate `org-refile-keep'
11507 being set to `t' and copy to the target location, don't move it.
11508 Beware that keeping refiled entries may result in duplicated ID
11509 properties.
11511 RFLOC can be a refile location obtained in a different way.
11513 MSG is a string to replace \"Refile\" in the default prompt with
11514 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11516 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11518 If you are using target caching (see `org-refile-use-cache'),
11519 you have to clear the target cache in order to find new targets.
11520 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11521 prefix argument (`C-u C-u C-u C-c C-w')."
11523 (interactive "P")
11524 (if (member goto '(0 (64)))
11525 (org-refile-cache-clear)
11526 (let* ((actionmsg (or msg "Refile"))
11527 (cbuf (current-buffer))
11528 (regionp (org-region-active-p))
11529 (region-start (and regionp (region-beginning)))
11530 (region-end (and regionp (region-end)))
11531 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11532 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11533 pos it nbuf file re level reversed)
11534 (setq last-command nil)
11535 (when regionp
11536 (goto-char region-start)
11537 (or (bolp) (goto-char (point-at-bol)))
11538 (setq region-start (point))
11539 (unless (or (org-kill-is-subtree-p
11540 (buffer-substring region-start region-end))
11541 (prog1 org-refile-active-region-within-subtree
11542 (let ((s (point-at-eol)))
11543 (org-toggle-heading)
11544 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11545 (user-error "The region is not a (sequence of) subtree(s)")))
11546 (if (equal goto '(16))
11547 (org-refile-goto-last-stored)
11548 (when (or
11549 (and (equal goto 2)
11550 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11551 (prog1
11552 (setq it (list (or org-clock-heading "running clock")
11553 (buffer-file-name
11554 (marker-buffer org-clock-hd-marker))
11556 (marker-position org-clock-hd-marker)))
11557 (setq goto nil)))
11558 (setq it (or rfloc
11559 (let (heading-text)
11560 (save-excursion
11561 (unless goto
11562 (org-back-to-heading t)
11563 (setq heading-text
11564 (nth 4 (org-heading-components))))
11566 (org-refile-get-location
11567 (cond (goto "Goto")
11568 (regionp (concat actionmsg " region to"))
11569 (t (concat actionmsg " subtree \""
11570 heading-text "\" to")))
11571 default-buffer
11572 (and (not (equal '(4) goto))
11573 org-refile-allow-creating-parent-nodes)
11574 goto))))))
11575 (setq file (nth 1 it)
11576 re (nth 2 it)
11577 pos (nth 3 it))
11578 (if (and (not goto)
11580 (equal (buffer-file-name) file)
11581 (if regionp
11582 (and (>= pos region-start)
11583 (<= pos region-end))
11584 (and (>= pos (point))
11585 (< pos (save-excursion
11586 (org-end-of-subtree t t))))))
11587 (error "Cannot refile to position inside the tree or region"))
11589 (setq nbuf (or (find-buffer-visiting file)
11590 (find-file-noselect file)))
11591 (if (and goto (not (equal goto 3)))
11592 (progn
11593 (org-pop-to-buffer-same-window nbuf)
11594 (goto-char pos)
11595 (org-show-context 'org-goto))
11596 (if regionp
11597 (progn
11598 (org-kill-new (buffer-substring region-start region-end))
11599 (org-save-markers-in-region region-start region-end))
11600 (org-copy-subtree 1 nil t))
11601 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11602 (find-file-noselect file)))
11603 (setq reversed (org-notes-order-reversed-p))
11604 (save-excursion
11605 (save-restriction
11606 (widen)
11607 (if pos
11608 (progn
11609 (goto-char pos)
11610 (looking-at org-outline-regexp)
11611 (setq level (org-get-valid-level (funcall outline-level) 1))
11612 (goto-char
11613 (if reversed
11614 (or (outline-next-heading) (point-max))
11615 (or (save-excursion (org-get-next-sibling))
11616 (org-end-of-subtree t t)
11617 (point-max)))))
11618 (setq level 1)
11619 (if (not reversed)
11620 (goto-char (point-max))
11621 (goto-char (point-min))
11622 (or (outline-next-heading) (goto-char (point-max)))))
11623 (if (not (bolp)) (newline))
11624 (org-paste-subtree level)
11625 (when org-log-refile
11626 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11627 (unless (eq org-log-refile 'note)
11628 (save-excursion (org-add-log-note))))
11629 (and org-auto-align-tags
11630 (let ((org-loop-over-headlines-in-active-region nil))
11631 (org-set-tags nil t)))
11632 (let ((bookmark-name (plist-get org-bookmark-names-plist
11633 :last-refile)))
11634 (when bookmark-name
11635 (with-demoted-errors
11636 (bookmark-set bookmark-name))))
11637 ;; If we are refiling for capture, make sure that the
11638 ;; last-capture pointers point here
11639 (when (org-bound-and-true-p org-refile-for-capture)
11640 (let ((bookmark-name (plist-get org-bookmark-names-plist
11641 :last-capture-marker)))
11642 (when bookmark-name
11643 (with-demoted-errors
11644 (bookmark-set bookmark-name))))
11645 (move-marker org-capture-last-stored-marker (point)))
11646 (if (fboundp 'deactivate-mark) (deactivate-mark))
11647 (run-hooks 'org-after-refile-insert-hook))))
11648 (unless org-refile-keep
11649 (if regionp
11650 (delete-region (point) (+ (point) (- region-end region-start)))
11651 (delete-region
11652 (and (org-back-to-heading t) (point))
11653 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11654 (when (featurep 'org-inlinetask)
11655 (org-inlinetask-remove-END-maybe))
11656 (setq org-markers-to-move nil)
11657 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11659 (defun org-refile-goto-last-stored ()
11660 "Go to the location where the last refile was stored."
11661 (interactive)
11662 (bookmark-jump "org-refile-last-stored")
11663 (message "This is the location of the last refile"))
11665 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11666 no-exclude)
11667 "Prompt the user for a refile location, using PROMPT.
11668 PROMPT should not be suffixed with a colon and a space, because
11669 this function appends the default value from
11670 `org-refile-history' automatically, if that is not empty.
11671 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11672 this is used for the GOTO interface."
11673 (let ((org-refile-targets org-refile-targets)
11674 (org-refile-use-outline-path org-refile-use-outline-path)
11675 excluded-entries)
11676 (when (and (derived-mode-p 'org-mode)
11677 (not org-refile-use-cache)
11678 (not no-exclude))
11679 (org-map-tree
11680 (lambda()
11681 (setq excluded-entries
11682 (append excluded-entries (list (org-get-heading t t)))))))
11683 (setq org-refile-target-table
11684 (org-refile-get-targets default-buffer excluded-entries)))
11685 (unless org-refile-target-table
11686 (user-error "No refile targets"))
11687 (let* ((cbuf (current-buffer))
11688 (partial-completion-mode nil)
11689 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11690 (cfunc (if (and org-refile-use-outline-path
11691 org-outline-path-complete-in-steps)
11692 'org-olpath-completing-read
11693 'org-icompleting-read))
11694 (extra (if org-refile-use-outline-path "/" ""))
11695 (cbnex (concat (buffer-name) extra))
11696 (filename (and cfn (expand-file-name cfn)))
11697 (tbl (mapcar
11698 (lambda (x)
11699 (if (and (not (member org-refile-use-outline-path
11700 '(file full-file-path)))
11701 (not (equal filename (nth 1 x))))
11702 (cons (concat (car x) extra " ("
11703 (file-name-nondirectory (nth 1 x)) ")")
11704 (cdr x))
11705 (cons (concat (car x) extra) (cdr x))))
11706 org-refile-target-table))
11707 (completion-ignore-case t)
11708 cdef
11709 (prompt (concat prompt
11710 (or (and (car org-refile-history)
11711 (concat " (default " (car org-refile-history) ")"))
11712 (and (assoc cbnex tbl) (setq cdef cbnex)
11713 (concat " (default " cbnex ")"))) ": "))
11714 pa answ parent-target child parent old-hist)
11715 (setq old-hist org-refile-history)
11716 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11717 nil 'org-refile-history (or cdef (car org-refile-history))))
11718 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11719 (org-refile-check-position pa)
11720 (if pa
11721 (progn
11722 (when (or (not org-refile-history)
11723 (not (eq old-hist org-refile-history))
11724 (not (equal (car pa) (car org-refile-history))))
11725 (setq org-refile-history
11726 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11727 org-refile-history
11728 (cdr org-refile-history))))
11729 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11730 (pop org-refile-history)))
11732 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11733 (progn
11734 (setq parent (match-string 1 answ)
11735 child (match-string 2 answ))
11736 (setq parent-target (or (assoc parent tbl)
11737 (assoc (concat parent "/") tbl)))
11738 (when (and parent-target
11739 (or (eq new-nodes t)
11740 (and (eq new-nodes 'confirm)
11741 (y-or-n-p (format "Create new node \"%s\"? "
11742 child)))))
11743 (org-refile-new-child parent-target child)))
11744 (user-error "Invalid target location")))))
11746 (declare-function org-string-nw-p "org-macs" (s))
11747 (defun org-refile-check-position (refile-pointer)
11748 "Check if the refile pointer matches the headline to which it points."
11749 (let* ((file (nth 1 refile-pointer))
11750 (re (nth 2 refile-pointer))
11751 (pos (nth 3 refile-pointer))
11752 buffer)
11753 (if (and (not (markerp pos)) (not file))
11754 (user-error "Please save the buffer to a file before refiling")
11755 (when (org-string-nw-p re)
11756 (setq buffer (if (markerp pos)
11757 (marker-buffer pos)
11758 (or (find-buffer-visiting file)
11759 (find-file-noselect file))))
11760 (with-current-buffer buffer
11761 (save-excursion
11762 (save-restriction
11763 (widen)
11764 (goto-char pos)
11765 (beginning-of-line 1)
11766 (unless (org-looking-at-p re)
11767 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11769 (defun org-refile-new-child (parent-target child)
11770 "Use refile target PARENT-TARGET to add new CHILD below it."
11771 (unless parent-target
11772 (error "Cannot find parent for new node"))
11773 (let ((file (nth 1 parent-target))
11774 (pos (nth 3 parent-target))
11775 level)
11776 (with-current-buffer (or (find-buffer-visiting file)
11777 (find-file-noselect file))
11778 (save-excursion
11779 (save-restriction
11780 (widen)
11781 (if pos
11782 (goto-char pos)
11783 (goto-char (point-max))
11784 (if (not (bolp)) (newline)))
11785 (when (looking-at org-outline-regexp)
11786 (setq level (funcall outline-level))
11787 (org-end-of-subtree t t))
11788 (org-back-over-empty-lines)
11789 (insert "\n" (make-string
11790 (if pos (org-get-valid-level level 1) 1) ?*)
11791 " " child "\n")
11792 (beginning-of-line 0)
11793 (list (concat (car parent-target) "/" child) file "" (point)))))))
11795 (defun org-olpath-completing-read (prompt collection &rest args)
11796 "Read an outline path like a file name."
11797 (let ((thetable collection)
11798 (org-completion-use-ido nil) ; does not work with ido.
11799 (org-completion-use-iswitchb nil)) ; or iswitchb
11800 (apply
11801 'org-icompleting-read prompt
11802 (lambda (string predicate &optional flag)
11803 (let (rtn r f (l (length string)))
11804 (cond
11805 ((eq flag nil)
11806 ;; try completion
11807 (try-completion string thetable))
11808 ((eq flag t)
11809 ;; all-completions
11810 (setq rtn (all-completions string thetable predicate))
11811 (mapcar
11812 (lambda (x)
11813 (setq r (substring x l))
11814 (if (string-match " ([^)]*)$" x)
11815 (setq f (match-string 0 x))
11816 (setq f ""))
11817 (if (string-match "/" r)
11818 (concat string (substring r 0 (match-end 0)) f)
11820 rtn))
11821 ((eq flag 'lambda)
11822 ;; exact match?
11823 (assoc string thetable)))))
11824 args)))
11826 ;;;; Dynamic blocks
11828 (defun org-find-dblock (name)
11829 "Find the first dynamic block with name NAME in the buffer.
11830 If not found, stay at current position and return nil."
11831 (let ((case-fold-search t) pos)
11832 (save-excursion
11833 (goto-char (point-min))
11834 (setq pos (and (re-search-forward
11835 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11836 (match-beginning 0))))
11837 (if pos (goto-char pos))
11838 pos))
11840 (defconst org-dblock-start-re
11841 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11842 "Matches the start line of a dynamic block, with parameters.")
11844 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11845 "Matches the end of a dynamic block.")
11847 (defun org-create-dblock (plist)
11848 "Create a dynamic block section, with parameters taken from PLIST.
11849 PLIST must contain a :name entry which is used as name of the block."
11850 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11851 (end-of-line 1)
11852 (newline))
11853 (let ((col (current-column))
11854 (name (plist-get plist :name)))
11855 (insert "#+BEGIN: " name)
11856 (while plist
11857 (if (eq (car plist) :name)
11858 (setq plist (cddr plist))
11859 (insert " " (prin1-to-string (pop plist)))))
11860 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11861 (beginning-of-line -2)))
11863 (defun org-prepare-dblock ()
11864 "Prepare dynamic block for refresh.
11865 This empties the block, puts the cursor at the insert position and returns
11866 the property list including an extra property :name with the block name."
11867 (unless (looking-at org-dblock-start-re)
11868 (user-error "Not at a dynamic block"))
11869 (let* ((begdel (1+ (match-end 0)))
11870 (name (org-no-properties (match-string 1)))
11871 (params (append (list :name name)
11872 (read (concat "(" (match-string 3) ")")))))
11873 (save-excursion
11874 (beginning-of-line 1)
11875 (skip-chars-forward " \t")
11876 (setq params (plist-put params :indentation-column (current-column))))
11877 (unless (re-search-forward org-dblock-end-re nil t)
11878 (error "Dynamic block not terminated"))
11879 (setq params
11880 (append params
11881 (list :content (buffer-substring
11882 begdel (match-beginning 0)))))
11883 (delete-region begdel (match-beginning 0))
11884 (goto-char begdel)
11885 (open-line 1)
11886 params))
11888 (defun org-map-dblocks (&optional command)
11889 "Apply COMMAND to all dynamic blocks in the current buffer.
11890 If COMMAND is not given, use `org-update-dblock'."
11891 (let ((cmd (or command 'org-update-dblock)))
11892 (save-excursion
11893 (goto-char (point-min))
11894 (while (re-search-forward org-dblock-start-re nil t)
11895 (goto-char (match-beginning 0))
11896 (save-excursion
11897 (condition-case nil
11898 (funcall cmd)
11899 (error (message "Error during update of dynamic block"))))
11900 (unless (re-search-forward org-dblock-end-re nil t)
11901 (error "Dynamic block not terminated"))))))
11903 (defun org-dblock-update (&optional arg)
11904 "User command for updating dynamic blocks.
11905 Update the dynamic block at point. With prefix ARG, update all dynamic
11906 blocks in the buffer."
11907 (interactive "P")
11908 (if arg
11909 (org-update-all-dblocks)
11910 (or (looking-at org-dblock-start-re)
11911 (org-beginning-of-dblock))
11912 (org-update-dblock)))
11914 (defun org-update-dblock ()
11915 "Update the dynamic block at point.
11916 This means to empty the block, parse for parameters and then call
11917 the correct writing function."
11918 (interactive)
11919 (save-window-excursion
11920 (let* ((pos (point))
11921 (line (org-current-line))
11922 (params (org-prepare-dblock))
11923 (name (plist-get params :name))
11924 (indent (plist-get params :indentation-column))
11925 (cmd (intern (concat "org-dblock-write:" name))))
11926 (message "Updating dynamic block `%s' at line %d..." name line)
11927 (funcall cmd params)
11928 (message "Updating dynamic block `%s' at line %d...done" name line)
11929 (goto-char pos)
11930 (when (and indent (> indent 0))
11931 (setq indent (make-string indent ?\ ))
11932 (save-excursion
11933 (org-beginning-of-dblock)
11934 (forward-line 1)
11935 (while (not (looking-at org-dblock-end-re))
11936 (insert indent)
11937 (beginning-of-line 2))
11938 (when (looking-at org-dblock-end-re)
11939 (and (looking-at "[ \t]+")
11940 (replace-match ""))
11941 (insert indent)))))))
11943 (defun org-beginning-of-dblock ()
11944 "Find the beginning of the dynamic block at point.
11945 Error if there is no such block at point."
11946 (let ((pos (point))
11947 beg)
11948 (end-of-line 1)
11949 (if (and (re-search-backward org-dblock-start-re nil t)
11950 (setq beg (match-beginning 0))
11951 (re-search-forward org-dblock-end-re nil t)
11952 (> (match-end 0) pos))
11953 (goto-char beg)
11954 (goto-char pos)
11955 (error "Not in a dynamic block"))))
11957 (defun org-update-all-dblocks ()
11958 "Update all dynamic blocks in the buffer.
11959 This function can be used in a hook."
11960 (interactive)
11961 (when (derived-mode-p 'org-mode)
11962 (org-map-dblocks 'org-update-dblock)))
11965 ;;;; Completion
11967 (declare-function org-export-backend-name "org-export" (cl-x))
11968 (declare-function org-export-backend-options "org-export" (cl-x))
11969 (defun org-get-export-keywords ()
11970 "Return a list of all currently understood export keywords.
11971 Export keywords include options, block names, attributes and
11972 keywords relative to each registered export back-end."
11973 (let (keywords)
11974 (dolist (backend
11975 (org-bound-and-true-p org-export--registered-backends)
11976 (delq nil keywords))
11977 ;; Back-end name (for keywords, like #+LATEX:)
11978 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11979 (dolist (option-entry (org-export-backend-options backend))
11980 ;; Back-end options.
11981 (push (nth 1 option-entry) keywords)))))
11983 (defconst org-options-keywords
11984 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11985 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11986 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11987 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11988 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11990 (defcustom org-structure-template-alist
11991 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11992 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11993 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11994 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11995 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11996 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11997 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11998 "<literal style=\"latex\">\n?\n</literal>")
11999 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12000 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12001 "<literal style=\"html\">\n?\n</literal>")
12002 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12003 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12004 ("A" "#+ASCII: " "")
12005 ("i" "#+INDEX: ?" "#+INDEX: ?")
12006 ("I" "#+INCLUDE: %file ?"
12007 "<include file=%file markup=\"?\">"))
12008 "Structure completion elements.
12009 This is a list of abbreviation keys and values. The value gets inserted
12010 if you type `<' followed by the key and then press the completion key,
12011 usually `M-TAB'. %file will be replaced by a file name after prompting
12012 for the file using completion. The cursor will be placed at the position
12013 of the `?` in the template.
12014 There are two templates for each key, the first uses the original Org syntax,
12015 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12016 the default when the /org-mtags.el/ module has been loaded. See also the
12017 variable `org-mtags-prefer-muse-templates'."
12018 :group 'org-completion
12019 :type '(repeat
12020 (list
12021 (string :tag "Key")
12022 (string :tag "Template")
12023 (string :tag "Muse Template"))))
12025 (defun org-try-structure-completion ()
12026 "Try to complete a structure template before point.
12027 This looks for strings like \"<e\" on an otherwise empty line and
12028 expands them."
12029 (let ((l (buffer-substring (point-at-bol) (point)))
12031 (when (and (looking-at "[ \t]*$")
12032 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12033 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12034 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12035 (match-beginning 1)) a)
12036 t)))
12038 (defun org-complete-expand-structure-template (start cell)
12039 "Expand a structure template."
12040 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12041 (rpl (nth (if musep 2 1) cell))
12042 (ind ""))
12043 (delete-region start (point))
12044 (when (string-match "\\`#\\+" rpl)
12045 (cond
12046 ((bolp))
12047 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12048 (setq ind (buffer-substring (point-at-bol) (point))))
12049 (t (newline))))
12050 (setq start (point))
12051 (if (string-match "%file" rpl)
12052 (setq rpl (replace-match
12053 (concat
12054 "\""
12055 (save-match-data
12056 (abbreviate-file-name (read-file-name "Include file: ")))
12057 "\"")
12058 t t rpl)))
12059 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12060 (concat "\n" ind)))
12061 (insert rpl)
12062 (if (re-search-backward "\\?" start t) (delete-char 1))))
12064 ;;;; TODO, DEADLINE, Comments
12066 (defun org-toggle-comment ()
12067 "Change the COMMENT state of an entry."
12068 (interactive)
12069 (save-excursion
12070 (org-back-to-heading)
12071 (let (case-fold-search)
12072 (cond
12073 ((looking-at (format org-heading-keyword-regexp-format
12074 org-comment-string))
12075 (goto-char (match-end 1))
12076 (looking-at (concat " +" org-comment-string))
12077 (replace-match "" t t)
12078 (when (eolp) (insert " ")))
12079 ((looking-at org-outline-regexp)
12080 (goto-char (match-end 0))
12081 (insert org-comment-string " "))))))
12083 (defvar org-last-todo-state-is-todo nil
12084 "This is non-nil when the last TODO state change led to a TODO state.
12085 If the last change removed the TODO tag or switched to DONE, then
12086 this is nil.")
12088 (defvar org-setting-tags nil) ; dynamically skipped
12090 (defvar org-todo-setup-filter-hook nil
12091 "Hook for functions that pre-filter todo specs.
12092 Each function takes a todo spec and returns either nil or the spec
12093 transformed into canonical form." )
12095 (defvar org-todo-get-default-hook nil
12096 "Hook for functions that get a default item for todo.
12097 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12098 nil or a string to be used for the todo mark." )
12100 (defvar org-agenda-headline-snapshot-before-repeat)
12102 (defun org-current-effective-time ()
12103 "Return current time adjusted for `org-extend-today-until' variable."
12104 (let* ((ct (org-current-time))
12105 (dct (decode-time ct))
12106 (ct1
12107 (cond
12108 (org-use-last-clock-out-time-as-effective-time
12109 (or (org-clock-get-last-clock-out-time) ct))
12110 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12111 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12112 (t ct))))
12113 ct1))
12115 (defun org-todo-yesterday (&optional arg)
12116 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12117 (interactive "P")
12118 (if (eq major-mode 'org-agenda-mode)
12119 (apply 'org-agenda-todo-yesterday arg)
12120 (let* ((hour (third (decode-time
12121 (org-current-time))))
12122 (org-extend-today-until (1+ hour)))
12123 (org-todo arg))))
12125 (defvar org-block-entry-blocking ""
12126 "First entry preventing the TODO state change.")
12128 (defun org-todo (&optional arg)
12129 "Change the TODO state of an item.
12130 The state of an item is given by a keyword at the start of the heading,
12131 like
12132 *** TODO Write paper
12133 *** DONE Call mom
12135 The different keywords are specified in the variable `org-todo-keywords'.
12136 By default the available states are \"TODO\" and \"DONE\".
12137 So for this example: when the item starts with TODO, it is changed to DONE.
12138 When it starts with DONE, the DONE is removed. And when neither TODO nor
12139 DONE are present, add TODO at the beginning of the heading.
12141 With \\[universal-argument] prefix arg, use completion to determine the new \
12142 state.
12143 With numeric prefix arg, switch to that state.
12144 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12145 keywords (nextset).
12146 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12147 With a numeric prefix arg of 0, inhibit note taking for the change.
12149 For calling through lisp, arg is also interpreted in the following way:
12150 'none -> empty state
12151 \"\"(empty string) -> switch to empty state
12152 'done -> switch to DONE
12153 'nextset -> switch to the next set of keywords
12154 'previousset -> switch to the previous set of keywords
12155 \"WAITING\" -> switch to the specified keyword, but only if it
12156 really is a member of `org-todo-keywords'."
12157 (interactive "P")
12158 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12159 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12160 'region-start-level 'region))
12161 org-loop-over-headlines-in-active-region)
12162 (org-map-entries
12163 `(org-todo ,arg)
12164 org-loop-over-headlines-in-active-region
12165 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12166 (if (equal arg '(16)) (setq arg 'nextset))
12167 (let ((org-blocker-hook org-blocker-hook)
12168 commentp
12169 case-fold-search)
12170 (when (equal arg '(64))
12171 (setq arg nil org-blocker-hook nil))
12172 (when (and org-blocker-hook
12173 (or org-inhibit-blocking
12174 (org-entry-get nil "NOBLOCKING")))
12175 (setq org-blocker-hook nil))
12176 (save-excursion
12177 (catch 'exit
12178 (org-back-to-heading t)
12179 (when (looking-at (concat "^\\*+ " org-comment-string))
12180 (org-toggle-comment)
12181 (setq commentp t))
12182 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12183 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12184 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12185 (let* ((match-data (match-data))
12186 (startpos (point-at-bol))
12187 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12188 (org-log-done org-log-done)
12189 (org-log-repeat org-log-repeat)
12190 (org-todo-log-states org-todo-log-states)
12191 (org-inhibit-logging
12192 (if (equal arg 0)
12193 (progn (setq arg nil) 'note) org-inhibit-logging))
12194 (this (match-string 1))
12195 (hl-pos (match-beginning 0))
12196 (head (org-get-todo-sequence-head this))
12197 (ass (assoc head org-todo-kwd-alist))
12198 (interpret (nth 1 ass))
12199 (done-word (nth 3 ass))
12200 (final-done-word (nth 4 ass))
12201 (org-last-state (or this ""))
12202 (completion-ignore-case t)
12203 (member (member this org-todo-keywords-1))
12204 (tail (cdr member))
12205 (org-state (cond
12206 ((and org-todo-key-trigger
12207 (or (and (equal arg '(4))
12208 (eq org-use-fast-todo-selection 'prefix))
12209 (and (not arg) org-use-fast-todo-selection
12210 (not (eq org-use-fast-todo-selection
12211 'prefix)))))
12212 ;; Use fast selection
12213 (org-fast-todo-selection))
12214 ((and (equal arg '(4))
12215 (or (not org-use-fast-todo-selection)
12216 (not org-todo-key-trigger)))
12217 ;; Read a state with completion
12218 (org-icompleting-read
12219 "State: " (mapcar 'list org-todo-keywords-1)
12220 nil t))
12221 ((eq arg 'right)
12222 (if this
12223 (if tail (car tail) nil)
12224 (car org-todo-keywords-1)))
12225 ((eq arg 'left)
12226 (if (equal member org-todo-keywords-1)
12228 (if this
12229 (nth (- (length org-todo-keywords-1)
12230 (length tail) 2)
12231 org-todo-keywords-1)
12232 (org-last org-todo-keywords-1))))
12233 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12234 (setq arg nil))) ; hack to fall back to cycling
12235 (arg
12236 ;; user or caller requests a specific state
12237 (cond
12238 ((equal arg "") nil)
12239 ((eq arg 'none) nil)
12240 ((eq arg 'done) (or done-word (car org-done-keywords)))
12241 ((eq arg 'nextset)
12242 (or (car (cdr (member head org-todo-heads)))
12243 (car org-todo-heads)))
12244 ((eq arg 'previousset)
12245 (let ((org-todo-heads (reverse org-todo-heads)))
12246 (or (car (cdr (member head org-todo-heads)))
12247 (car org-todo-heads))))
12248 ((car (member arg org-todo-keywords-1)))
12249 ((stringp arg)
12250 (user-error "State `%s' not valid in this file" arg))
12251 ((nth (1- (prefix-numeric-value arg))
12252 org-todo-keywords-1))))
12253 ((null member) (or head (car org-todo-keywords-1)))
12254 ((equal this final-done-word) nil) ;; -> make empty
12255 ((null tail) nil) ;; -> first entry
12256 ((memq interpret '(type priority))
12257 (if (eq this-command last-command)
12258 (car tail)
12259 (if (> (length tail) 0)
12260 (or done-word (car org-done-keywords))
12261 nil)))
12263 (car tail))))
12264 (org-state (or
12265 (run-hook-with-args-until-success
12266 'org-todo-get-default-hook org-state org-last-state)
12267 org-state))
12268 (next (if org-state (concat " " org-state " ") " "))
12269 (change-plist (list :type 'todo-state-change :from this :to org-state
12270 :position startpos))
12271 dolog now-done-p)
12272 (when org-blocker-hook
12273 (setq org-last-todo-state-is-todo
12274 (not (member this org-done-keywords)))
12275 (unless (save-excursion
12276 (save-match-data
12277 (org-with-wide-buffer
12278 (run-hook-with-args-until-failure
12279 'org-blocker-hook change-plist))))
12280 (if (org-called-interactively-p 'interactive)
12281 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12282 this org-state org-block-entry-blocking)
12283 ;; fail silently
12284 (message "TODO state change from %s to %s blocked (by \"%s\")"
12285 this org-state org-block-entry-blocking)
12286 (throw 'exit nil))))
12287 (store-match-data match-data)
12288 (replace-match next t t)
12289 (unless (pos-visible-in-window-p hl-pos)
12290 (message "TODO state changed to %s" (org-trim next)))
12291 (unless head
12292 (setq head (org-get-todo-sequence-head org-state)
12293 ass (assoc head org-todo-kwd-alist)
12294 interpret (nth 1 ass)
12295 done-word (nth 3 ass)
12296 final-done-word (nth 4 ass)))
12297 (when (memq arg '(nextset previousset))
12298 (message "Keyword-Set %d/%d: %s"
12299 (- (length org-todo-sets) -1
12300 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12301 (length org-todo-sets)
12302 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12303 (setq org-last-todo-state-is-todo
12304 (not (member org-state org-done-keywords)))
12305 (setq now-done-p (and (member org-state org-done-keywords)
12306 (not (member this org-done-keywords))))
12307 (and logging (org-local-logging logging))
12308 (when (and (or org-todo-log-states org-log-done)
12309 (not (eq org-inhibit-logging t))
12310 (not (memq arg '(nextset previousset))))
12311 ;; we need to look at recording a time and note
12312 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12313 (nth 2 (assoc this org-todo-log-states))))
12314 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12315 (setq dolog 'time))
12316 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12317 (and org-state
12318 (member org-state org-not-done-keywords)
12319 (not (member this org-not-done-keywords))))
12320 ;; This is now a todo state and was not one before
12321 ;; If there was a CLOSED time stamp, get rid of it.
12322 (org-add-planning-info nil nil 'closed))
12323 (when (and now-done-p org-log-done)
12324 ;; It is now done, and it was not done before
12325 (org-add-planning-info 'closed (org-current-effective-time))
12326 (if (and (not dolog) (eq 'note org-log-done))
12327 (org-add-log-setup 'done org-state this 'findpos 'note)))
12328 (when (and org-state dolog)
12329 ;; This is a non-nil state, and we need to log it
12330 (org-add-log-setup 'state org-state this 'findpos dolog)))
12331 ;; Fixup tag positioning
12332 (org-todo-trigger-tag-changes org-state)
12333 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12334 (when org-provide-todo-statistics
12335 (org-update-parent-todo-statistics))
12336 (run-hooks 'org-after-todo-state-change-hook)
12337 (if (and arg (not (member org-state org-done-keywords)))
12338 (setq head (org-get-todo-sequence-head org-state)))
12339 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12340 ;; Do we need to trigger a repeat?
12341 (when now-done-p
12342 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12343 ;; This is for the agenda, take a snapshot of the headline.
12344 (save-match-data
12345 (setq org-agenda-headline-snapshot-before-repeat
12346 (org-get-heading))))
12347 (org-auto-repeat-maybe org-state))
12348 ;; Fixup cursor location if close to the keyword
12349 (if (and (outline-on-heading-p)
12350 (not (bolp))
12351 (save-excursion (beginning-of-line 1)
12352 (looking-at org-todo-line-regexp))
12353 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12354 (progn
12355 (goto-char (or (match-end 2) (match-end 1)))
12356 (and (looking-at " ") (just-one-space))))
12357 (when org-trigger-hook
12358 (save-excursion
12359 (run-hook-with-args 'org-trigger-hook change-plist)))
12360 (when commentp (org-toggle-comment))))))))
12362 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12363 "Block turning an entry into a TODO, using the hierarchy.
12364 This checks whether the current task should be blocked from state
12365 changes. Such blocking occurs when:
12367 1. The task has children which are not all in a completed state.
12369 2. A task has a parent with the property :ORDERED:, and there
12370 are siblings prior to the current task with incomplete
12371 status.
12373 3. The parent of the task is blocked because it has siblings that should
12374 be done first, or is child of a block grandparent TODO entry."
12376 (if (not org-enforce-todo-dependencies)
12377 t ; if locally turned off don't block
12378 (catch 'dont-block
12379 ;; If this is not a todo state change, or if this entry is already DONE,
12380 ;; do not block
12381 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12382 (member (plist-get change-plist :from)
12383 (cons 'done org-done-keywords))
12384 (member (plist-get change-plist :to)
12385 (cons 'todo org-not-done-keywords))
12386 (not (plist-get change-plist :to)))
12387 (throw 'dont-block t))
12388 ;; If this task has children, and any are undone, it's blocked
12389 (save-excursion
12390 (org-back-to-heading t)
12391 (let ((this-level (funcall outline-level)))
12392 (outline-next-heading)
12393 (let ((child-level (funcall outline-level)))
12394 (while (and (not (eobp))
12395 (> child-level this-level))
12396 ;; this todo has children, check whether they are all
12397 ;; completed
12398 (if (and (not (org-entry-is-done-p))
12399 (org-entry-is-todo-p))
12400 (progn (setq org-block-entry-blocking (org-get-heading))
12401 (throw 'dont-block nil)))
12402 (outline-next-heading)
12403 (setq child-level (funcall outline-level))))))
12404 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12405 ;; any previous siblings are undone, it's blocked
12406 (save-excursion
12407 (org-back-to-heading t)
12408 (let* ((pos (point))
12409 (parent-pos (and (org-up-heading-safe) (point))))
12410 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12411 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12412 (forward-line 1)
12413 (re-search-forward org-not-done-heading-regexp pos t))
12414 (setq org-block-entry-blocking (match-string 0))
12415 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12416 ;; Search further up the hierarchy, to see if an ancestor is blocked
12417 (while t
12418 (goto-char parent-pos)
12419 (if (not (looking-at org-not-done-heading-regexp))
12420 (throw 'dont-block t)) ; do not block, parent is not a TODO
12421 (setq pos (point))
12422 (setq parent-pos (and (org-up-heading-safe) (point)))
12423 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12424 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12425 (forward-line 1)
12426 (re-search-forward org-not-done-heading-regexp pos t)
12427 (setq org-block-entry-blocking (org-get-heading)))
12428 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12430 (defcustom org-track-ordered-property-with-tag nil
12431 "Should the ORDERED property also be shown as a tag?
12432 The ORDERED property decides if an entry should require subtasks to be
12433 completed in sequence. Since a property is not very visible, setting
12434 this option means that toggling the ORDERED property with the command
12435 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12436 not relevant for the behavior, but it makes things more visible.
12438 Note that toggling the tag with tags commands will not change the property
12439 and therefore not influence behavior!
12441 This can be t, meaning the tag ORDERED should be used, It can also be a
12442 string to select a different tag for this task."
12443 :group 'org-todo
12444 :type '(choice
12445 (const :tag "No tracking" nil)
12446 (const :tag "Track with ORDERED tag" t)
12447 (string :tag "Use other tag")))
12449 (defun org-toggle-ordered-property ()
12450 "Toggle the ORDERED property of the current entry.
12451 For better visibility, you can track the value of this property with a tag.
12452 See variable `org-track-ordered-property-with-tag'."
12453 (interactive)
12454 (let* ((t1 org-track-ordered-property-with-tag)
12455 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12456 (save-excursion
12457 (org-back-to-heading)
12458 (if (org-entry-get nil "ORDERED")
12459 (progn
12460 (org-delete-property "ORDERED" "PROPERTIES")
12461 (and tag (org-toggle-tag tag 'off))
12462 (message "Subtasks can be completed in arbitrary order"))
12463 (org-entry-put nil "ORDERED" "t")
12464 (and tag (org-toggle-tag tag 'on))
12465 (message "Subtasks must be completed in sequence")))))
12467 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12468 (defun org-block-todo-from-checkboxes (change-plist)
12469 "Block turning an entry into a TODO, using checkboxes.
12470 This checks whether the current task should be blocked from state
12471 changes because there are unchecked boxes in this entry."
12472 (if (not org-enforce-todo-checkbox-dependencies)
12473 t ; if locally turned off don't block
12474 (catch 'dont-block
12475 ;; If this is not a todo state change, or if this entry is already DONE,
12476 ;; do not block
12477 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12478 (member (plist-get change-plist :from)
12479 (cons 'done org-done-keywords))
12480 (member (plist-get change-plist :to)
12481 (cons 'todo org-not-done-keywords))
12482 (not (plist-get change-plist :to)))
12483 (throw 'dont-block t))
12484 ;; If this task has checkboxes that are not checked, it's blocked
12485 (save-excursion
12486 (org-back-to-heading t)
12487 (let ((beg (point)) end)
12488 (outline-next-heading)
12489 (setq end (point))
12490 (goto-char beg)
12491 (if (org-list-search-forward
12492 (concat (org-item-beginning-re)
12493 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12494 "\\[[- ]\\]")
12495 end t)
12496 (progn
12497 (if (boundp 'org-blocked-by-checkboxes)
12498 (setq org-blocked-by-checkboxes t))
12499 (throw 'dont-block nil)))))
12500 t))) ; do not block
12502 (defun org-entry-blocked-p ()
12503 "Is the current entry blocked?"
12504 (org-with-silent-modifications
12505 (if (org-entry-get nil "NOBLOCKING")
12506 nil ;; Never block this entry
12507 (not (run-hook-with-args-until-failure
12508 'org-blocker-hook
12509 (list :type 'todo-state-change
12510 :position (point)
12511 :from 'todo
12512 :to 'done))))))
12514 (defun org-update-statistics-cookies (all)
12515 "Update the statistics cookie, either from TODO or from checkboxes.
12516 This should be called with the cursor in a line with a statistics cookie."
12517 (interactive "P")
12518 (if all
12519 (progn
12520 (org-update-checkbox-count 'all)
12521 (org-map-entries 'org-update-parent-todo-statistics))
12522 (if (not (org-at-heading-p))
12523 (org-update-checkbox-count)
12524 (let ((pos (point-marker))
12525 end l1 l2)
12526 (ignore-errors (org-back-to-heading t))
12527 (if (not (org-at-heading-p))
12528 (org-update-checkbox-count)
12529 (setq l1 (org-outline-level))
12530 (setq end (save-excursion
12531 (outline-next-heading)
12532 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12533 (point)))
12534 (if (and (save-excursion
12535 (re-search-forward
12536 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12537 (not (save-excursion (re-search-forward
12538 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12539 (org-update-checkbox-count)
12540 (if (and l2 (> l2 l1))
12541 (progn
12542 (goto-char end)
12543 (org-update-parent-todo-statistics))
12544 (goto-char pos)
12545 (beginning-of-line 1)
12546 (while (re-search-forward
12547 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12548 (point-at-eol) t)
12549 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12550 (goto-char pos)
12551 (move-marker pos nil)))))
12553 (defvar org-entry-property-inherited-from) ;; defined below
12554 (defun org-update-parent-todo-statistics ()
12555 "Update any statistics cookie in the parent of the current headline.
12556 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12557 the entire subtree and this will travel up the hierarchy and update
12558 statistics everywhere."
12559 (let* ((prop (save-excursion (org-up-heading-safe)
12560 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12561 (recursive (or (not org-hierarchical-todo-statistics)
12562 (and prop (string-match "\\<recursive\\>" prop))))
12563 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12565 (first t)
12566 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12567 level ltoggle l1 new ndel
12568 (cnt-all 0) (cnt-done 0) is-percent kwd
12569 checkbox-beg ov ovs ove cookie-present)
12570 (catch 'exit
12571 (save-excursion
12572 (beginning-of-line 1)
12573 (setq ltoggle (funcall outline-level))
12574 ;; Three situations are to consider:
12576 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12577 ;; to the top-level ancestor on the headline;
12579 ;; 2. If parent has "recursive" property, repeat up to the
12580 ;; headline setting that property, taking inheritance into
12581 ;; account;
12583 ;; 3. Else, move up to direct parent and proceed only once.
12584 (while (and (setq level (org-up-heading-safe))
12585 (or recursive first)
12586 (>= (point) lim))
12587 (setq first nil cookie-present nil)
12588 (unless (and level
12589 (not (string-match
12590 "\\<checkbox\\>"
12591 (downcase (or (org-entry-get nil "COOKIE_DATA")
12592 "")))))
12593 (throw 'exit nil))
12594 (while (re-search-forward box-re (point-at-eol) t)
12595 (setq cnt-all 0 cnt-done 0 cookie-present t)
12596 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12597 (save-match-data
12598 (unless (outline-next-heading) (throw 'exit nil))
12599 (while (and (looking-at org-complex-heading-regexp)
12600 (> (setq l1 (length (match-string 1))) level))
12601 (setq kwd (and (or recursive (= l1 ltoggle))
12602 (match-string 2)))
12603 (if (or (eq org-provide-todo-statistics 'all-headlines)
12604 (and (listp org-provide-todo-statistics)
12605 (or (member kwd org-provide-todo-statistics)
12606 (member kwd org-done-keywords))))
12607 (setq cnt-all (1+ cnt-all))
12608 (if (eq org-provide-todo-statistics t)
12609 (and kwd (setq cnt-all (1+ cnt-all)))))
12610 (and (member kwd org-done-keywords)
12611 (setq cnt-done (1+ cnt-done)))
12612 (outline-next-heading)))
12613 (setq new
12614 (if is-percent
12615 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12616 (format "[%d/%d]" cnt-done cnt-all))
12617 ndel (- (match-end 0) checkbox-beg))
12618 ;; handle overlays when updating cookie from column view
12619 (when (setq ov (car (overlays-at checkbox-beg)))
12620 (setq ovs (overlay-start ov) ove (overlay-end ov))
12621 (delete-overlay ov))
12622 (goto-char checkbox-beg)
12623 (insert new)
12624 (delete-region (point) (+ (point) ndel))
12625 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12626 (when ov (move-overlay ov ovs ove)))
12627 (when cookie-present
12628 (run-hook-with-args 'org-after-todo-statistics-hook
12629 cnt-done (- cnt-all cnt-done))))))
12630 (run-hooks 'org-todo-statistics-hook)))
12632 (defvar org-after-todo-statistics-hook nil
12633 "Hook that is called after a TODO statistics cookie has been updated.
12634 Each function is called with two arguments: the number of not-done entries
12635 and the number of done entries.
12637 For example, the following function, when added to this hook, will switch
12638 an entry to DONE when all children are done, and back to TODO when new
12639 entries are set to a TODO status. Note that this hook is only called
12640 when there is a statistics cookie in the headline!
12642 (defun org-summary-todo (n-done n-not-done)
12643 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12644 (let (org-log-done org-log-states) ; turn off logging
12645 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12648 (defvar org-todo-statistics-hook nil
12649 "Hook that is run whenever Org thinks TODO statistics should be updated.
12650 This hook runs even if there is no statistics cookie present, in which case
12651 `org-after-todo-statistics-hook' would not run.")
12653 (defun org-todo-trigger-tag-changes (state)
12654 "Apply the changes defined in `org-todo-state-tags-triggers'."
12655 (let ((l org-todo-state-tags-triggers)
12656 changes)
12657 (when (or (not state) (equal state ""))
12658 (setq changes (append changes (cdr (assoc "" l)))))
12659 (when (and (stringp state) (> (length state) 0))
12660 (setq changes (append changes (cdr (assoc state l)))))
12661 (when (member state org-not-done-keywords)
12662 (setq changes (append changes (cdr (assoc 'todo l)))))
12663 (when (member state org-done-keywords)
12664 (setq changes (append changes (cdr (assoc 'done l)))))
12665 (dolist (c changes)
12666 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12668 (defun org-local-logging (value)
12669 "Get logging settings from a property VALUE."
12670 (let* (words w a)
12671 ;; directly set the variables, they are already local.
12672 (setq org-log-done nil
12673 org-log-repeat nil
12674 org-todo-log-states nil)
12675 (setq words (org-split-string value))
12676 (while (setq w (pop words))
12677 (cond
12678 ((setq a (assoc w org-startup-options))
12679 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12680 (set (nth 1 a) (nth 2 a))))
12681 ((setq a (org-extract-log-state-settings w))
12682 (and (member (car a) org-todo-keywords-1)
12683 (push a org-todo-log-states)))))))
12685 (defun org-get-todo-sequence-head (kwd)
12686 "Return the head of the TODO sequence to which KWD belongs.
12687 If KWD is not set, check if there is a text property remembering the
12688 right sequence."
12689 (let (p)
12690 (cond
12691 ((not kwd)
12692 (or (get-text-property (point-at-bol) 'org-todo-head)
12693 (progn
12694 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12695 nil (point-at-eol)))
12696 (get-text-property p 'org-todo-head))))
12697 ((not (member kwd org-todo-keywords-1))
12698 (car org-todo-keywords-1))
12699 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12701 (defun org-fast-todo-selection ()
12702 "Fast TODO keyword selection with single keys.
12703 Returns the new TODO keyword, or nil if no state change should occur."
12704 (let* ((fulltable org-todo-key-alist)
12705 (done-keywords org-done-keywords) ;; needed for the faces.
12706 (maxlen (apply 'max (mapcar
12707 (lambda (x)
12708 (if (stringp (car x)) (string-width (car x)) 0))
12709 fulltable)))
12710 (expert nil)
12711 (fwidth (+ maxlen 3 1 3))
12712 (ncol (/ (- (window-width) 4) fwidth))
12713 tg cnt e c tbl
12714 groups ingroup)
12715 (save-excursion
12716 (save-window-excursion
12717 (if expert
12718 (set-buffer (get-buffer-create " *Org todo*"))
12719 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12720 (erase-buffer)
12721 (org-set-local 'org-done-keywords done-keywords)
12722 (setq tbl fulltable cnt 0)
12723 (while (setq e (pop tbl))
12724 (cond
12725 ((equal e '(:startgroup))
12726 (push '() groups) (setq ingroup t)
12727 (when (not (= cnt 0))
12728 (setq cnt 0)
12729 (insert "\n"))
12730 (insert "{ "))
12731 ((equal e '(:endgroup))
12732 (setq ingroup nil cnt 0)
12733 (insert "}\n"))
12734 ((equal e '(:newline))
12735 (when (not (= cnt 0))
12736 (setq cnt 0)
12737 (insert "\n")
12738 (setq e (car tbl))
12739 (while (equal (car tbl) '(:newline))
12740 (insert "\n")
12741 (setq tbl (cdr tbl)))))
12743 (setq tg (car e) c (cdr e))
12744 (if ingroup (push tg (car groups)))
12745 (setq tg (org-add-props tg nil 'face
12746 (org-get-todo-face tg)))
12747 (if (and (= cnt 0) (not ingroup)) (insert " "))
12748 (insert "[" c "] " tg (make-string
12749 (- fwidth 4 (length tg)) ?\ ))
12750 (when (= (setq cnt (1+ cnt)) ncol)
12751 (insert "\n")
12752 (if ingroup (insert " "))
12753 (setq cnt 0)))))
12754 (insert "\n")
12755 (goto-char (point-min))
12756 (if (not expert) (org-fit-window-to-buffer))
12757 (message "[a-z..]:Set [SPC]:clear")
12758 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12759 (cond
12760 ((or (= c ?\C-g)
12761 (and (= c ?q) (not (rassoc c fulltable))))
12762 (setq quit-flag t))
12763 ((= c ?\ ) nil)
12764 ((setq e (rassoc c fulltable) tg (car e))
12766 (t (setq quit-flag t)))))))
12768 (defun org-entry-is-todo-p ()
12769 (member (org-get-todo-state) org-not-done-keywords))
12771 (defun org-entry-is-done-p ()
12772 (member (org-get-todo-state) org-done-keywords))
12774 (defun org-get-todo-state ()
12775 "Return the TODO keyword of the current subtree."
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (and (looking-at org-todo-line-regexp)
12779 (match-end 2)
12780 (match-string 2))))
12782 (defun org-at-date-range-p (&optional inactive-ok)
12783 "Is the cursor inside a date range?"
12784 (interactive)
12785 (save-excursion
12786 (catch 'exit
12787 (let ((pos (point)))
12788 (skip-chars-backward "^[<\r\n")
12789 (skip-chars-backward "<[")
12790 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12791 (>= (match-end 0) pos)
12792 (throw 'exit t))
12793 (skip-chars-backward "^<[\r\n")
12794 (skip-chars-backward "<[")
12795 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12796 (>= (match-end 0) pos)
12797 (throw 'exit t)))
12798 nil)))
12800 (defun org-get-repeat (&optional tagline)
12801 "Check if there is a deadline/schedule with repeater in this entry."
12802 (save-match-data
12803 (save-excursion
12804 (org-back-to-heading t)
12805 (and (re-search-forward (if tagline
12806 (concat tagline "\\s-*" org-repeat-re)
12807 org-repeat-re)
12808 (org-entry-end-position) t)
12809 (match-string-no-properties 1)))))
12811 (defvar org-last-changed-timestamp)
12812 (defvar org-last-inserted-timestamp)
12813 (defvar org-log-post-message)
12814 (defvar org-log-note-purpose)
12815 (defvar org-log-note-how)
12816 (defvar org-log-note-extra)
12817 (defun org-auto-repeat-maybe (done-word)
12818 "Check if the current headline contains a repeated deadline/schedule.
12819 If yes, set TODO state back to what it was and change the base date
12820 of repeating deadline/scheduled time stamps to new date.
12821 This function is run automatically after each state change to a DONE state."
12822 ;; last-state is dynamically scoped into this function
12823 (let* ((repeat (org-get-repeat))
12824 (aa (assoc org-last-state org-todo-kwd-alist))
12825 (interpret (nth 1 aa))
12826 (head (nth 2 aa))
12827 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12828 (msg "Entry repeats: ")
12829 (org-log-done nil)
12830 (org-todo-log-states nil)
12831 re type n what ts time to-state)
12832 (when repeat
12833 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12834 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12835 org-todo-repeat-to-state))
12836 (unless (and to-state (member to-state org-todo-keywords-1))
12837 (setq to-state (if (eq interpret 'type) org-last-state head)))
12838 (org-todo to-state)
12839 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12840 (org-entry-put nil "LAST_REPEAT" (format-time-string
12841 (org-time-stamp-format t t))))
12842 (when org-log-repeat
12843 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12844 (memq 'org-add-log-note post-command-hook))
12845 ;; OK, we are already setup for some record
12846 (if (eq org-log-repeat 'note)
12847 ;; make sure we take a note, not only a time stamp
12848 (setq org-log-note-how 'note))
12849 ;; Set up for taking a record
12850 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12851 org-last-state
12852 'findpos org-log-repeat)))
12853 (org-back-to-heading t)
12854 (org-add-planning-info nil nil 'closed)
12855 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12856 org-deadline-time-regexp "\\)\\|\\("
12857 org-ts-regexp "\\)"))
12858 (while (re-search-forward
12859 re (save-excursion (outline-next-heading) (point)) t)
12860 (setq type (if (match-end 1) org-scheduled-string
12861 (if (match-end 3) org-deadline-string "Plain:"))
12862 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12863 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12864 (setq n (string-to-number (match-string 2 ts))
12865 what (match-string 3 ts))
12866 (if (equal what "w") (setq n (* n 7) what "d"))
12867 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12868 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12869 ;; Preparation, see if we need to modify the start date for the change
12870 (when (match-end 1)
12871 (setq time (save-match-data (org-time-string-to-time ts)))
12872 (cond
12873 ((equal (match-string 1 ts) ".")
12874 ;; Shift starting date to today
12875 (org-timestamp-change
12876 (- (org-today) (time-to-days time))
12877 'day))
12878 ((equal (match-string 1 ts) "+")
12879 (let ((nshiftmax 10) (nshift 0))
12880 (while (or (= nshift 0)
12881 (<= (time-to-days time)
12882 (time-to-days (current-time))))
12883 (when (= (incf nshift) nshiftmax)
12884 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12885 (error "Abort")))
12886 (org-timestamp-change n (cdr (assoc what whata)))
12887 (org-at-timestamp-p t)
12888 (setq ts (match-string 1))
12889 (setq time (save-match-data (org-time-string-to-time ts)))))
12890 (org-timestamp-change (- n) (cdr (assoc what whata)))
12891 ;; rematch, so that we have everything in place for the real shift
12892 (org-at-timestamp-p t)
12893 (setq ts (match-string 1))
12894 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12895 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12896 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12897 (setq org-log-post-message msg)
12898 (message "%s" msg))))
12900 (defun org-show-todo-tree (arg)
12901 "Make a compact tree which shows all headlines marked with TODO.
12902 The tree will show the lines where the regexp matches, and all higher
12903 headlines above the match.
12904 With a \\[universal-argument] prefix, prompt for a regexp to match.
12905 With a numeric prefix N, construct a sparse tree for the Nth element
12906 of `org-todo-keywords-1'."
12907 (interactive "P")
12908 (let ((case-fold-search nil)
12909 (kwd-re
12910 (cond ((null arg) org-not-done-regexp)
12911 ((equal arg '(4))
12912 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12913 (mapcar 'list org-todo-keywords-1))))
12914 (concat "\\("
12915 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12916 "\\)\\>")))
12917 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12918 (regexp-quote (nth (1- (prefix-numeric-value arg))
12919 org-todo-keywords-1)))
12920 (t (user-error "Invalid prefix argument: %s" arg)))))
12921 (message "%d TODO entries found"
12922 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12924 (defun org-deadline (arg &optional time)
12925 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12926 With one universal prefix argument, remove any deadline from the item.
12927 With two universal prefix arguments, prompt for a warning delay.
12928 With argument TIME, set the deadline at the corresponding date. TIME
12929 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12930 (interactive "P")
12931 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12932 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12933 'region-start-level 'region))
12934 org-loop-over-headlines-in-active-region)
12935 (org-map-entries
12936 `(org-deadline ',arg ,time)
12937 org-loop-over-headlines-in-active-region
12938 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12939 (let* ((old-date (org-entry-get nil "DEADLINE"))
12940 (old-date-time (if old-date (org-time-string-to-time old-date)))
12941 (repeater (and old-date
12942 (string-match
12943 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12944 old-date)
12945 (match-string 1 old-date))))
12946 (cond
12947 ((equal arg '(4))
12948 (when (and old-date org-log-redeadline)
12949 (org-add-log-setup 'deldeadline nil old-date 'findpos
12950 org-log-redeadline))
12951 (org-remove-timestamp-with-keyword org-deadline-string)
12952 (message "Item no longer has a deadline."))
12953 ((equal arg '(16))
12954 (save-excursion
12955 (if (re-search-forward
12956 org-deadline-time-regexp
12957 (save-excursion (outline-next-heading) (point)) t)
12958 (let* ((rpl0 (match-string 1))
12959 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12960 (replace-match
12961 (concat org-deadline-string
12962 " <" rpl
12963 (format " -%dd"
12964 (abs
12965 (- (time-to-days
12966 (save-match-data
12967 (org-read-date nil t nil "Warn starting from" old-date-time)))
12968 (time-to-days old-date-time))))
12969 ">") t t))
12970 (user-error "No deadline information to update"))))
12972 (org-add-planning-info 'deadline time 'closed)
12973 (when (and old-date org-log-redeadline
12974 (not (equal old-date
12975 (substring org-last-inserted-timestamp 1 -1))))
12976 (org-add-log-setup 'redeadline nil old-date 'findpos
12977 org-log-redeadline))
12978 (when repeater
12979 (save-excursion
12980 (org-back-to-heading t)
12981 (when (re-search-forward (concat org-deadline-string " "
12982 org-last-inserted-timestamp)
12983 (save-excursion
12984 (outline-next-heading) (point)) t)
12985 (goto-char (1- (match-end 0)))
12986 (insert " " repeater)
12987 (setq org-last-inserted-timestamp
12988 (concat (substring org-last-inserted-timestamp 0 -1)
12989 " " repeater
12990 (substring org-last-inserted-timestamp -1))))))
12991 (message "Deadline on %s" org-last-inserted-timestamp))))))
12993 (defun org-schedule (arg &optional time)
12994 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12995 With one universal prefix argument, remove any scheduling date from the item.
12996 With two universal prefix arguments, prompt for a delay cookie.
12997 With argument TIME, scheduled at the corresponding date. TIME can
12998 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12999 (interactive "P")
13000 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13001 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13002 'region-start-level 'region))
13003 org-loop-over-headlines-in-active-region)
13004 (org-map-entries
13005 `(org-schedule ',arg ,time)
13006 org-loop-over-headlines-in-active-region
13007 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13008 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13009 (old-date-time (if old-date (org-time-string-to-time old-date)))
13010 (repeater (and old-date
13011 (string-match
13012 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13013 old-date)
13014 (match-string 1 old-date))))
13015 (cond
13016 ((equal arg '(4))
13017 (progn
13018 (when (and old-date org-log-reschedule)
13019 (org-add-log-setup 'delschedule nil old-date 'findpos
13020 org-log-reschedule))
13021 (org-remove-timestamp-with-keyword org-scheduled-string)
13022 (message "Item is no longer scheduled.")))
13023 ((equal arg '(16))
13024 (save-excursion
13025 (if (re-search-forward
13026 org-scheduled-time-regexp
13027 (save-excursion (outline-next-heading) (point)) t)
13028 (let* ((rpl0 (match-string 1))
13029 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13030 (replace-match
13031 (concat org-scheduled-string
13032 " <" rpl
13033 (format " -%dd"
13034 (abs
13035 (- (time-to-days
13036 (save-match-data
13037 (org-read-date nil t nil "Delay until" old-date-time)))
13038 (time-to-days old-date-time))))
13039 ">") t t))
13040 (user-error "No scheduled information to update"))))
13042 (org-add-planning-info 'scheduled time 'closed)
13043 (when (and old-date org-log-reschedule
13044 (not (equal old-date
13045 (substring org-last-inserted-timestamp 1 -1))))
13046 (org-add-log-setup 'reschedule nil old-date 'findpos
13047 org-log-reschedule))
13048 (when repeater
13049 (save-excursion
13050 (org-back-to-heading t)
13051 (when (re-search-forward (concat org-scheduled-string " "
13052 org-last-inserted-timestamp)
13053 (save-excursion
13054 (outline-next-heading) (point)) t)
13055 (goto-char (1- (match-end 0)))
13056 (insert " " repeater)
13057 (setq org-last-inserted-timestamp
13058 (concat (substring org-last-inserted-timestamp 0 -1)
13059 " " repeater
13060 (substring org-last-inserted-timestamp -1))))))
13061 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13063 (defun org-get-scheduled-time (pom &optional inherit)
13064 "Get the scheduled time as a time tuple, of a format suitable
13065 for calling org-schedule with, or if there is no scheduling,
13066 returns nil."
13067 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13068 (when time
13069 (apply 'encode-time (org-parse-time-string time)))))
13071 (defun org-get-deadline-time (pom &optional inherit)
13072 "Get the deadline as a time tuple, of a format suitable for
13073 calling org-deadline with, or if there is no scheduling, returns
13074 nil."
13075 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13076 (when time
13077 (apply 'encode-time (org-parse-time-string time)))))
13079 (defun org-remove-timestamp-with-keyword (keyword)
13080 "Remove all time stamps with KEYWORD in the current entry."
13081 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13082 beg)
13083 (save-excursion
13084 (org-back-to-heading t)
13085 (setq beg (point))
13086 (outline-next-heading)
13087 (while (re-search-backward re beg t)
13088 (replace-match "")
13089 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13090 (equal (char-before) ?\ ))
13091 (backward-delete-char 1)
13092 (if (string-match "^[ \t]*$" (buffer-substring
13093 (point-at-bol) (point-at-eol)))
13094 (delete-region (point-at-bol)
13095 (min (point-max) (1+ (point-at-eol))))))))))
13097 (defun org-add-planning-info (what &optional time &rest remove)
13098 "Insert new timestamp with keyword in the line directly after the headline.
13099 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13100 If non is given, the user is prompted for a date.
13101 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13102 be removed."
13103 (interactive)
13104 (let (org-time-was-given org-end-time-was-given ts
13105 end default-time default-input)
13107 (catch 'exit
13108 (when (and (memq what '(scheduled deadline))
13109 (or (not time)
13110 (and (stringp time)
13111 (string-match "^[-+]+[0-9]" time))))
13112 ;; Try to get a default date/time from existing timestamp
13113 (save-excursion
13114 (org-back-to-heading t)
13115 (setq end (save-excursion (outline-next-heading) (point)))
13116 (when (re-search-forward (if (eq what 'scheduled)
13117 org-scheduled-time-regexp
13118 org-deadline-time-regexp)
13119 end t)
13120 (setq ts (match-string 1)
13121 default-time
13122 (apply 'encode-time (org-parse-time-string ts))
13123 default-input (and ts (org-get-compact-tod ts))))))
13124 (when what
13125 (setq time
13126 (if (stringp time)
13127 ;; This is a string (relative or absolute), set proper date
13128 (apply 'encode-time
13129 (org-read-date-analyze
13130 time default-time (decode-time default-time)))
13131 ;; If necessary, get the time from the user
13132 (or time (org-read-date nil 'to-time nil nil
13133 default-time default-input)))))
13135 (when (and org-insert-labeled-timestamps-at-point
13136 (member what '(scheduled deadline)))
13137 (insert
13138 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13139 (org-insert-time-stamp time org-time-was-given
13140 nil nil nil (list org-end-time-was-given))
13141 (setq what nil))
13142 (save-excursion
13143 (save-restriction
13144 (let (col list elt ts buffer-invisibility-spec)
13145 (org-back-to-heading t)
13146 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13147 (goto-char (match-end 1))
13148 (setq col (current-column))
13149 (goto-char (match-end 0))
13150 (if (eobp) (insert "\n") (forward-char 1))
13151 (when (and (not what)
13152 (not (looking-at
13153 (concat "[ \t]*"
13154 org-keyword-time-not-clock-regexp))))
13155 ;; Nothing to add, nothing to remove...... :-)
13156 (throw 'exit nil))
13157 (if (and (not (looking-at org-outline-regexp))
13158 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13159 "[^\r\n]*"))
13160 (not (equal (match-string 1) org-clock-string)))
13161 (narrow-to-region (match-beginning 0) (match-end 0))
13162 (insert-before-markers "\n")
13163 (backward-char 1)
13164 (narrow-to-region (point) (point))
13165 (and org-adapt-indentation (org-indent-to-column col)))
13166 ;; Check if we have to remove something.
13167 (setq list (cons what remove))
13168 (while list
13169 (setq elt (pop list))
13170 (when (or (and (eq elt 'scheduled)
13171 (re-search-forward org-scheduled-time-regexp nil t))
13172 (and (eq elt 'deadline)
13173 (re-search-forward org-deadline-time-regexp nil t))
13174 (and (eq elt 'closed)
13175 (re-search-forward org-closed-time-regexp nil t)))
13176 (replace-match "")
13177 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13178 (and (looking-at "[ \t]+") (replace-match ""))
13179 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13180 (when what
13181 (insert
13182 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13183 (cond ((eq what 'scheduled) org-scheduled-string)
13184 ((eq what 'deadline) org-deadline-string)
13185 ((eq what 'closed) org-closed-string))
13186 " ")
13187 (setq ts (org-insert-time-stamp
13188 time
13189 (or org-time-was-given
13190 (and (eq what 'closed) org-log-done-with-time))
13191 (eq what 'closed)
13192 nil nil (list org-end-time-was-given)))
13193 (insert
13194 (if (not (or (bolp) (eq (char-before) ?\ )
13195 (memq (char-after) '(32 10))
13196 (eobp))) " " ""))
13197 (end-of-line 1))
13198 (goto-char (point-min))
13199 (widen)
13200 (if (and (looking-at "[ \t]*\n")
13201 (equal (char-before) ?\n))
13202 (delete-region (1- (point)) (point-at-eol)))
13203 ts))))))
13205 (defvar org-log-note-marker (make-marker))
13206 (defvar org-log-note-purpose nil)
13207 (defvar org-log-note-state nil)
13208 (defvar org-log-note-previous-state nil)
13209 (defvar org-log-note-how nil)
13210 (defvar org-log-note-extra nil)
13211 (defvar org-log-note-window-configuration nil)
13212 (defvar org-log-note-return-to (make-marker))
13213 (defvar org-log-note-effective-time nil
13214 "Remembered current time so that dynamically scoped
13215 `org-extend-today-until' affects tha timestamps in state change
13216 log")
13218 (defvar org-log-post-message nil
13219 "Message to be displayed after a log note has been stored.
13220 The auto-repeater uses this.")
13222 (defun org-add-note ()
13223 "Add a note to the current entry.
13224 This is done in the same way as adding a state change note."
13225 (interactive)
13226 (org-add-log-setup 'note nil nil 'findpos nil))
13228 (defvar org-property-end-re)
13229 (defun org-add-log-setup (&optional purpose state prev-state
13230 findpos how extra)
13231 "Set up the post command hook to take a note.
13232 If this is about to TODO state change, the new state is expected in STATE.
13233 When FINDPOS is non-nil, find the correct position for the note in
13234 the current entry. If not, assume that it can be inserted at point.
13235 HOW is an indicator what kind of note should be created.
13236 EXTRA is additional text that will be inserted into the notes buffer."
13237 (let* ((org-log-into-drawer (org-log-into-drawer))
13238 (drawer (cond ((stringp org-log-into-drawer)
13239 org-log-into-drawer)
13240 (org-log-into-drawer "LOGBOOK"))))
13241 (save-restriction
13242 (save-excursion
13243 (when findpos
13244 (org-back-to-heading t)
13245 (narrow-to-region (point) (save-excursion
13246 (outline-next-heading) (point)))
13247 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13248 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13249 "[^\r\n]*\\)?"))
13250 (goto-char (match-end 0))
13251 (cond
13252 (drawer
13253 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13254 nil t)
13255 (progn
13256 (goto-char (match-end 0))
13257 (or org-log-states-order-reversed
13258 (and (re-search-forward org-property-end-re nil t)
13259 (goto-char (1- (match-beginning 0))))))
13260 (insert "\n:" drawer ":\n:END:")
13261 (beginning-of-line 0)
13262 (org-indent-line)
13263 (beginning-of-line 2)
13264 (org-indent-line)
13265 (end-of-line 0)))
13266 ((and org-log-state-notes-insert-after-drawers
13267 (save-excursion
13268 (forward-line) (looking-at org-drawer-regexp)))
13269 (forward-line)
13270 (while (looking-at org-drawer-regexp)
13271 (goto-char (match-end 0))
13272 (re-search-forward org-property-end-re (point-max) t)
13273 (forward-line))
13274 (forward-line -1)))
13275 (unless org-log-states-order-reversed
13276 (and (= (char-after) ?\n) (forward-char 1))
13277 (org-skip-over-state-notes)
13278 (skip-chars-backward " \t\n\r")))
13279 (move-marker org-log-note-marker (point))
13280 (setq org-log-note-purpose purpose
13281 org-log-note-state state
13282 org-log-note-previous-state prev-state
13283 org-log-note-how how
13284 org-log-note-extra extra
13285 org-log-note-effective-time (org-current-effective-time))
13286 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13288 (defun org-skip-over-state-notes ()
13289 "Skip past the list of State notes in an entry."
13290 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13291 (when (ignore-errors (goto-char (org-in-item-p)))
13292 (let* ((struct (org-list-struct))
13293 (prevs (org-list-prevs-alist struct)))
13294 (while (looking-at "[ \t]*- State")
13295 (goto-char (or (org-list-get-next-item (point) struct prevs)
13296 (org-list-get-item-end (point) struct)))))))
13298 (defun org-add-log-note (&optional purpose)
13299 "Pop up a window for taking a note, and add this note later at point."
13300 (remove-hook 'post-command-hook 'org-add-log-note)
13301 (setq org-log-note-window-configuration (current-window-configuration))
13302 (delete-other-windows)
13303 (move-marker org-log-note-return-to (point))
13304 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13305 (goto-char org-log-note-marker)
13306 (org-switch-to-buffer-other-window "*Org Note*")
13307 (erase-buffer)
13308 (if (memq org-log-note-how '(time state))
13309 (let (current-prefix-arg) (org-store-log-note))
13310 (let ((org-inhibit-startup t)) (org-mode))
13311 (insert (format "# Insert note for %s.
13312 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13313 (cond
13314 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13315 ((eq org-log-note-purpose 'done) "closed todo item")
13316 ((eq org-log-note-purpose 'state)
13317 (format "state change from \"%s\" to \"%s\""
13318 (or org-log-note-previous-state "")
13319 (or org-log-note-state "")))
13320 ((eq org-log-note-purpose 'reschedule)
13321 "rescheduling")
13322 ((eq org-log-note-purpose 'delschedule)
13323 "no longer scheduled")
13324 ((eq org-log-note-purpose 'redeadline)
13325 "changing deadline")
13326 ((eq org-log-note-purpose 'deldeadline)
13327 "removing deadline")
13328 ((eq org-log-note-purpose 'refile)
13329 "refiling")
13330 ((eq org-log-note-purpose 'note)
13331 "this entry")
13332 (t (error "This should not happen")))))
13333 (if org-log-note-extra (insert org-log-note-extra))
13334 (org-set-local 'org-finish-function 'org-store-log-note)
13335 (run-hooks 'org-log-buffer-setup-hook)))
13337 (defvar org-note-abort nil) ; dynamically scoped
13338 (defun org-store-log-note ()
13339 "Finish taking a log note, and insert it to where it belongs."
13340 (let ((txt (buffer-string)))
13341 (kill-buffer (current-buffer))
13342 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13343 lines ind bul)
13344 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13345 (setq txt (replace-match "" t t txt)))
13346 (if (string-match "\\s-+\\'" txt)
13347 (setq txt (replace-match "" t t txt)))
13348 (setq lines (org-split-string txt "\n"))
13349 (when (and note (string-match "\\S-" note))
13350 (setq note
13351 (org-replace-escapes
13352 note
13353 (list (cons "%u" (user-login-name))
13354 (cons "%U" user-full-name)
13355 (cons "%t" (format-time-string
13356 (org-time-stamp-format 'long 'inactive)
13357 org-log-note-effective-time))
13358 (cons "%T" (format-time-string
13359 (org-time-stamp-format 'long nil)
13360 org-log-note-effective-time))
13361 (cons "%d" (format-time-string
13362 (org-time-stamp-format nil 'inactive)
13363 org-log-note-effective-time))
13364 (cons "%D" (format-time-string
13365 (org-time-stamp-format nil nil)
13366 org-log-note-effective-time))
13367 (cons "%s" (if org-log-note-state
13368 (concat "\"" org-log-note-state "\"")
13369 ""))
13370 (cons "%S" (if org-log-note-previous-state
13371 (concat "\"" org-log-note-previous-state "\"")
13372 "\"\"")))))
13373 (if lines (setq note (concat note " \\\\")))
13374 (push note lines))
13375 (when (or current-prefix-arg org-note-abort)
13376 (when org-log-into-drawer
13377 (org-remove-empty-drawer-at
13378 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13379 org-log-note-marker))
13380 (setq lines nil))
13381 (when lines
13382 (with-current-buffer (marker-buffer org-log-note-marker)
13383 (save-excursion
13384 (goto-char org-log-note-marker)
13385 (move-marker org-log-note-marker nil)
13386 (end-of-line 1)
13387 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13388 (setq ind (save-excursion
13389 (if (ignore-errors (goto-char (org-in-item-p)))
13390 (let ((struct (org-list-struct)))
13391 (org-list-get-ind
13392 (org-list-get-top-point struct) struct))
13393 (skip-chars-backward " \r\t\n")
13394 (cond
13395 ((and (org-at-heading-p)
13396 org-adapt-indentation)
13397 (1+ (org-current-level)))
13398 ((org-at-heading-p) 0)
13399 (t (org-get-indentation))))))
13400 (setq bul (org-list-bullet-string "-"))
13401 (org-indent-line-to ind)
13402 (insert bul (pop lines))
13403 (let ((ind-body (+ (length bul) ind)))
13404 (while lines
13405 (insert "\n")
13406 (org-indent-line-to ind-body)
13407 (insert (pop lines))))
13408 (message "Note stored")
13409 (org-back-to-heading t)
13410 (org-cycle-hide-drawers 'children))
13411 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13412 ;; from within `org-add-log-note' because `buffer-undo-list'
13413 ;; is then modified outside of `org-with-remote-undo'.
13414 (when (eq this-command 'org-agenda-todo)
13415 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13416 ;; Don't add undo information when called from `org-agenda-todo'
13417 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13418 (set-window-configuration org-log-note-window-configuration)
13419 (with-current-buffer (marker-buffer org-log-note-return-to)
13420 (goto-char org-log-note-return-to))
13421 (move-marker org-log-note-return-to nil)
13422 (and org-log-post-message (message "%s" org-log-post-message))))
13424 (defun org-remove-empty-drawer-at (drawer pos)
13425 "Remove an empty drawer DRAWER at position POS.
13426 POS may also be a marker."
13427 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13428 (save-excursion
13429 (save-restriction
13430 (widen)
13431 (goto-char pos)
13432 (if (org-in-regexp
13433 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13434 (replace-match ""))))))
13436 (defvar org-ts-type nil)
13437 (defun org-sparse-tree (&optional arg type)
13438 "Create a sparse tree, prompt for the details.
13439 This command can create sparse trees. You first need to select the type
13440 of match used to create the tree:
13442 t Show all TODO entries.
13443 T Show entries with a specific TODO keyword.
13444 m Show entries selected by a tags/property match.
13445 p Enter a property name and its value (both with completion on existing
13446 names/values) and show entries with that property.
13447 r Show entries matching a regular expression (`/' can be used as well).
13448 b Show deadlines and scheduled items before a date.
13449 a Show deadlines and scheduled items after a date.
13450 d Show deadlines due within `org-deadline-warning-days'.
13451 D Show deadlines and scheduled items between a date range."
13452 (interactive "P")
13453 (let (ans kwd value ts-type)
13454 (setq type (or type org-sparse-tree-default-date-type))
13455 (setq org-ts-type type)
13456 (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"
13457 (cond ((eq type 'all) "all timestamps")
13458 ((eq type 'scheduled) "only scheduled")
13459 ((eq type 'deadline) "only deadline")
13460 ((eq type 'active) "only active timestamps")
13461 ((eq type 'inactive) "only inactive timestamps")
13462 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13463 ((eq type 'closed) "with a closed time-stamp")
13464 (t "scheduled/deadline")))
13465 (setq ans (read-char-exclusive))
13466 (cond
13467 ((equal ans ?c)
13468 (org-sparse-tree
13469 arg (cadr (member type '(scheduled-or-deadline
13470 all scheduled deadline active inactive closed)))))
13471 ((equal ans ?d)
13472 (call-interactively 'org-check-deadlines))
13473 ((equal ans ?b)
13474 (call-interactively 'org-check-before-date))
13475 ((equal ans ?a)
13476 (call-interactively 'org-check-after-date))
13477 ((equal ans ?D)
13478 (call-interactively 'org-check-dates-range))
13479 ((equal ans ?t)
13480 (call-interactively 'org-show-todo-tree))
13481 ((equal ans ?T)
13482 (org-show-todo-tree '(4)))
13483 ((member ans '(?T ?m))
13484 (call-interactively 'org-match-sparse-tree))
13485 ((member ans '(?p ?P))
13486 (setq kwd (org-icompleting-read "Property: "
13487 (mapcar 'list (org-buffer-property-keys))))
13488 (setq value (org-icompleting-read "Value: "
13489 (mapcar 'list (org-property-values kwd))))
13490 (unless (string-match "\\`{.*}\\'" value)
13491 (setq value (concat "\"" value "\"")))
13492 (org-match-sparse-tree arg (concat kwd "=" value)))
13493 ((member ans '(?r ?R ?/))
13494 (call-interactively 'org-occur))
13495 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13497 (defvar org-occur-highlights nil
13498 "List of overlays used for occur matches.")
13499 (make-variable-buffer-local 'org-occur-highlights)
13500 (defvar org-occur-parameters nil
13501 "Parameters of the active org-occur calls.
13502 This is a list, each call to org-occur pushes as cons cell,
13503 containing the regular expression and the callback, onto the list.
13504 The list can contain several entries if `org-occur' has been called
13505 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13506 will only contain one set of parameters. When the highlights are
13507 removed (for example with `C-c C-c', or with the next edit (depending
13508 on `org-remove-highlights-with-change'), this variable is emptied
13509 as well.")
13510 (make-variable-buffer-local 'org-occur-parameters)
13512 (defun org-occur (regexp &optional keep-previous callback)
13513 "Make a compact tree which shows all matches of REGEXP.
13514 The tree will show the lines where the regexp matches, and all higher
13515 headlines above the match. It will also show the heading after the match,
13516 to make sure editing the matching entry is easy.
13517 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13518 call to `org-occur' will be kept, to allow stacking of calls to this
13519 command.
13520 If CALLBACK is non-nil, it is a function which is called to confirm
13521 that the match should indeed be shown."
13522 (interactive "sRegexp: \nP")
13523 (when (equal regexp "")
13524 (user-error "Regexp cannot be empty"))
13525 (unless keep-previous
13526 (org-remove-occur-highlights nil nil t))
13527 (push (cons regexp callback) org-occur-parameters)
13528 (let ((cnt 0))
13529 (save-excursion
13530 (goto-char (point-min))
13531 (if (or (not keep-previous) ; do not want to keep
13532 (not org-occur-highlights)) ; no previous matches
13533 ;; hide everything
13534 (org-overview))
13535 (while (re-search-forward regexp nil t)
13536 (when (or (not callback)
13537 (save-match-data (funcall callback)))
13538 (setq cnt (1+ cnt))
13539 (when org-highlight-sparse-tree-matches
13540 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13541 (org-show-context 'occur-tree))))
13542 (when org-remove-highlights-with-change
13543 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13544 nil 'local))
13545 (unless org-sparse-tree-open-archived-trees
13546 (org-hide-archived-subtrees (point-min) (point-max)))
13547 (run-hooks 'org-occur-hook)
13548 (if (org-called-interactively-p 'interactive)
13549 (message "%d match(es) for regexp %s" cnt regexp))
13550 cnt))
13552 (defun org-occur-next-match (&optional n reset)
13553 "Function for `next-error-function' to find sparse tree matches.
13554 N is the number of matches to move, when negative move backwards.
13555 RESET is entirely ignored - this function always goes back to the
13556 starting point when no match is found."
13557 (let* ((limit (if (< n 0) (point-min) (point-max)))
13558 (search-func (if (< n 0)
13559 'previous-single-char-property-change
13560 'next-single-char-property-change))
13561 (n (abs n))
13562 (pos (point))
13564 (catch 'exit
13565 (while (setq p1 (funcall search-func (point) 'org-type))
13566 (when (equal p1 limit)
13567 (goto-char pos)
13568 (error "No more matches"))
13569 (when (equal (get-char-property p1 'org-type) 'org-occur)
13570 (setq n (1- n))
13571 (when (= n 0)
13572 (goto-char p1)
13573 (throw 'exit (point))))
13574 (goto-char p1))
13575 (goto-char p1)
13576 (error "No more matches"))))
13578 (defun org-show-context (&optional key)
13579 "Make sure point and context are visible.
13580 How much context is shown depends upon the variables
13581 `org-show-hierarchy-above', `org-show-following-heading',
13582 `org-show-entry-below' and `org-show-siblings'."
13583 (let ((heading-p (org-at-heading-p t))
13584 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13585 (following-p (org-get-alist-option org-show-following-heading key))
13586 (entry-p (org-get-alist-option org-show-entry-below key))
13587 (siblings-p (org-get-alist-option org-show-siblings key)))
13588 ;; Show heading or entry text
13589 (if (and heading-p (not entry-p))
13590 (org-flag-heading nil) ; only show the heading
13591 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13592 (org-show-hidden-entry))) ; show entire entry
13593 (when following-p
13594 ;; Show next sibling, or heading below text
13595 (save-excursion
13596 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13597 (org-flag-heading nil))))
13598 (when siblings-p (org-show-siblings))
13599 (when hierarchy-p
13600 ;; show all higher headings, possibly with siblings
13601 (save-excursion
13602 (while (and (condition-case nil
13603 (progn (org-up-heading-all 1) t)
13604 (error nil))
13605 (not (bobp)))
13606 (org-flag-heading nil)
13607 (when siblings-p (org-show-siblings)))))
13608 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13610 (defvar org-reveal-start-hook nil
13611 "Hook run before revealing a location.")
13613 (defun org-reveal (&optional siblings)
13614 "Show current entry, hierarchy above it, and the following headline.
13615 This can be used to show a consistent set of context around locations
13616 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13617 not t for the search context.
13619 With optional argument SIBLINGS, on each level of the hierarchy all
13620 siblings are shown. This repairs the tree structure to what it would
13621 look like when opened with hierarchical calls to `org-cycle'.
13622 With double optional argument \\[universal-argument] \\[universal-argument], \
13623 go to the parent and show the
13624 entire tree."
13625 (interactive "P")
13626 (run-hooks 'org-reveal-start-hook)
13627 (let ((org-show-hierarchy-above t)
13628 (org-show-following-heading t)
13629 (org-show-siblings (if siblings t org-show-siblings)))
13630 (org-show-context nil))
13631 (when (equal siblings '(16))
13632 (save-excursion
13633 (when (org-up-heading-safe)
13634 (org-show-subtree)
13635 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13637 (defun org-highlight-new-match (beg end)
13638 "Highlight from BEG to END and mark the highlight is an occur headline."
13639 (let ((ov (make-overlay beg end)))
13640 (overlay-put ov 'face 'secondary-selection)
13641 (overlay-put ov 'org-type 'org-occur)
13642 (push ov org-occur-highlights)))
13644 (defun org-remove-occur-highlights (&optional beg end noremove)
13645 "Remove the occur highlights from the buffer.
13646 BEG and END are ignored. If NOREMOVE is nil, remove this function
13647 from the `before-change-functions' in the current buffer."
13648 (interactive)
13649 (unless org-inhibit-highlight-removal
13650 (mapc 'delete-overlay org-occur-highlights)
13651 (setq org-occur-highlights nil)
13652 (setq org-occur-parameters nil)
13653 (unless noremove
13654 (remove-hook 'before-change-functions
13655 'org-remove-occur-highlights 'local))))
13657 ;;;; Priorities
13659 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13660 "Regular expression matching the priority indicator.")
13662 (defvar org-remove-priority-next-time nil)
13664 (defun org-priority-up ()
13665 "Increase the priority of the current item."
13666 (interactive)
13667 (org-priority 'up))
13669 (defun org-priority-down ()
13670 "Decrease the priority of the current item."
13671 (interactive)
13672 (org-priority 'down))
13674 (defun org-priority (&optional action show)
13675 "Change the priority of an item.
13676 ACTION can be `set', `up', `down', or a character."
13677 (interactive "P")
13678 (if (equal action '(4))
13679 (org-show-priority)
13680 (unless org-enable-priority-commands
13681 (user-error "Priority commands are disabled"))
13682 (setq action (or action 'set))
13683 (let (current new news have remove)
13684 (save-excursion
13685 (org-back-to-heading t)
13686 (if (looking-at org-priority-regexp)
13687 (setq current (string-to-char (match-string 2))
13688 have t))
13689 (cond
13690 ((eq action 'remove)
13691 (setq remove t new ?\ ))
13692 ((or (eq action 'set)
13693 (if (featurep 'xemacs) (characterp action) (integerp action)))
13694 (if (not (eq action 'set))
13695 (setq new action)
13696 (message "Priority %c-%c, SPC to remove: "
13697 org-highest-priority org-lowest-priority)
13698 (save-match-data
13699 (setq new (read-char-exclusive))))
13700 (if (and (= (upcase org-highest-priority) org-highest-priority)
13701 (= (upcase org-lowest-priority) org-lowest-priority))
13702 (setq new (upcase new)))
13703 (cond ((equal new ?\ ) (setq remove t))
13704 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13705 (user-error "Priority must be between `%c' and `%c'"
13706 org-highest-priority org-lowest-priority))))
13707 ((eq action 'up)
13708 (setq new (if have
13709 (1- current) ; normal cycling
13710 ;; last priority was empty
13711 (if (eq last-command this-command)
13712 org-lowest-priority ; wrap around empty to lowest
13713 ;; default
13714 (if org-priority-start-cycle-with-default
13715 org-default-priority
13716 (1- org-default-priority))))))
13717 ((eq action 'down)
13718 (setq new (if have
13719 (1+ current) ; normal cycling
13720 ;; last priority was empty
13721 (if (eq last-command this-command)
13722 org-highest-priority ; wrap around empty to highest
13723 ;; default
13724 (if org-priority-start-cycle-with-default
13725 org-default-priority
13726 (1+ org-default-priority))))))
13727 (t (user-error "Invalid action")))
13728 (if (or (< (upcase new) org-highest-priority)
13729 (> (upcase new) org-lowest-priority))
13730 (if (and (memq action '(up down))
13731 (not have) (not (eq last-command this-command)))
13732 ;; `new' is from default priority
13733 (error
13734 "The default can not be set, see `org-default-priority' why")
13735 ;; normal cycling: `new' is beyond highest/lowest priority
13736 ;; and is wrapped around to the empty priority
13737 (setq remove t)))
13738 (setq news (format "%c" new))
13739 (if have
13740 (if remove
13741 (replace-match "" t t nil 1)
13742 (replace-match news t t nil 2))
13743 (if remove
13744 (user-error "No priority cookie found in line")
13745 (let ((case-fold-search nil))
13746 (looking-at org-todo-line-regexp))
13747 (if (match-end 2)
13748 (progn
13749 (goto-char (match-end 2))
13750 (insert " [#" news "]"))
13751 (goto-char (match-beginning 3))
13752 (insert "[#" news "] "))))
13753 (org-preserve-lc (org-set-tags nil 'align)))
13754 (if remove
13755 (message "Priority removed")
13756 (message "Priority of current item set to %s" news)))))
13758 (defun org-show-priority ()
13759 "Show the priority of the current item.
13760 This priority is composed of the main priority given with the [#A] cookies,
13761 and by additional input from the age of a schedules or deadline entry."
13762 (interactive)
13763 (let ((pri (if (eq major-mode 'org-agenda-mode)
13764 (org-get-at-bol 'priority)
13765 (save-excursion
13766 (save-match-data
13767 (beginning-of-line)
13768 (and (looking-at org-heading-regexp)
13769 (org-get-priority (match-string 0))))))))
13770 (message "Priority is %d" (if pri pri -1000))))
13772 (defun org-get-priority (s)
13773 "Find priority cookie and return priority."
13774 (save-match-data
13775 (if (functionp org-get-priority-function)
13776 (funcall org-get-priority-function)
13777 (if (not (string-match org-priority-regexp s))
13778 (* 1000 (- org-lowest-priority org-default-priority))
13779 (* 1000 (- org-lowest-priority
13780 (string-to-char (match-string 2 s))))))))
13782 ;;;; Tags
13784 (defvar org-agenda-archives-mode)
13785 (defvar org-map-continue-from nil
13786 "Position from where mapping should continue.
13787 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13789 (defvar org-scanner-tags nil
13790 "The current tag list while the tags scanner is running.")
13791 (defvar org-trust-scanner-tags nil
13792 "Should `org-get-tags-at' use the tags for the scanner.
13793 This is for internal dynamical scoping only.
13794 When this is non-nil, the function `org-get-tags-at' will return the value
13795 of `org-scanner-tags' instead of building the list by itself. This
13796 can lead to large speed-ups when the tags scanner is used in a file with
13797 many entries, and when the list of tags is retrieved, for example to
13798 obtain a list of properties. Building the tags list for each entry in such
13799 a file becomes an N^2 operation - but with this variable set, it scales
13800 as N.")
13802 (defun org-scan-tags (action matcher todo-only &optional start-level)
13803 "Sca headline tags with inheritance and produce output ACTION.
13805 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13806 or `agenda' to produce an entry list for an agenda view. It can also be
13807 a Lisp form or a function that should be called at each matched headline, in
13808 this case the return value is a list of all return values from these calls.
13810 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13811 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13812 only lines with a not-done TODO keyword are included in the output.
13813 This should be the same variable that was scoped into
13814 and set by `org-make-tags-matcher' when it constructed MATCHER.
13816 START-LEVEL can be a string with asterisks, reducing the scope to
13817 headlines matching this string."
13818 (require 'org-agenda)
13819 (let* ((re (concat "^"
13820 (if start-level
13821 ;; Get the correct level to match
13822 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13823 org-outline-regexp)
13824 " *\\(\\<\\("
13825 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13826 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13827 (props (list 'face 'default
13828 'done-face 'org-agenda-done
13829 'undone-face 'default
13830 'mouse-face 'highlight
13831 'org-not-done-regexp org-not-done-regexp
13832 'org-todo-regexp org-todo-regexp
13833 'org-complex-heading-regexp org-complex-heading-regexp
13834 'help-echo
13835 (format "mouse-2 or RET jump to org file %s"
13836 (abbreviate-file-name
13837 (or (buffer-file-name (buffer-base-buffer))
13838 (buffer-name (buffer-base-buffer)))))))
13839 (org-map-continue-from nil)
13840 lspos tags tags-list
13841 (tags-alist (list (cons 0 org-file-tags)))
13842 (llast 0) rtn rtn1 level category i txt
13843 todo marker entry priority)
13844 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13845 (setq action (list 'lambda nil action)))
13846 (save-excursion
13847 (goto-char (point-min))
13848 (when (eq action 'sparse-tree)
13849 (org-overview)
13850 (org-remove-occur-highlights))
13851 (while (let (case-fold-search)
13852 (re-search-forward re nil t))
13853 (setq org-map-continue-from nil)
13854 (catch :skip
13855 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13856 tags (if (match-end 4) (org-match-string-no-properties 4)))
13857 (goto-char (setq lspos (match-beginning 0)))
13858 (setq level (org-reduced-level (org-outline-level))
13859 category (org-get-category))
13860 (setq i llast llast level)
13861 ;; remove tag lists from same and sublevels
13862 (while (>= i level)
13863 (when (setq entry (assoc i tags-alist))
13864 (setq tags-alist (delete entry tags-alist)))
13865 (setq i (1- i)))
13866 ;; add the next tags
13867 (when tags
13868 (setq tags (org-split-string tags ":")
13869 tags-alist
13870 (cons (cons level tags) tags-alist)))
13871 ;; compile tags for current headline
13872 (setq tags-list
13873 (if org-use-tag-inheritance
13874 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13875 tags)
13876 org-scanner-tags tags-list)
13877 (when org-use-tag-inheritance
13878 (setcdr (car tags-alist)
13879 (mapcar (lambda (x)
13880 (setq x (copy-sequence x))
13881 (org-add-prop-inherited x))
13882 (cdar tags-alist))))
13883 (when (and tags org-use-tag-inheritance
13884 (or (not (eq t org-use-tag-inheritance))
13885 org-tags-exclude-from-inheritance))
13886 ;; selective inheritance, remove uninherited ones
13887 (setcdr (car tags-alist)
13888 (org-remove-uninherited-tags (cdar tags-alist))))
13889 (when (and
13891 ;; eval matcher only when the todo condition is OK
13892 (and (or (not todo-only) (member todo org-not-done-keywords))
13893 (let ((case-fold-search t) (org-trust-scanner-tags t))
13894 (eval matcher)))
13896 ;; Call the skipper, but return t if it does not skip,
13897 ;; so that the `and' form continues evaluating
13898 (progn
13899 (unless (eq action 'sparse-tree) (org-agenda-skip))
13902 ;; Check if timestamps are deselecting this entry
13903 (or (not todo-only)
13904 (and (member todo org-not-done-keywords)
13905 (or (not org-agenda-tags-todo-honor-ignore-options)
13906 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13908 ;; select this headline
13909 (cond
13910 ((eq action 'sparse-tree)
13911 (and org-highlight-sparse-tree-matches
13912 (org-get-heading) (match-end 0)
13913 (org-highlight-new-match
13914 (match-beginning 1) (match-end 1)))
13915 (org-show-context 'tags-tree))
13916 ((eq action 'agenda)
13917 (setq txt (org-agenda-format-item
13919 (concat
13920 (if (eq org-tags-match-list-sublevels 'indented)
13921 (make-string (1- level) ?.) "")
13922 (org-get-heading))
13923 level category
13924 tags-list)
13925 priority (org-get-priority txt))
13926 (goto-char lspos)
13927 (setq marker (org-agenda-new-marker))
13928 (org-add-props txt props
13929 'org-marker marker 'org-hd-marker marker 'org-category category
13930 'todo-state todo
13931 'priority priority 'type "tagsmatch")
13932 (push txt rtn))
13933 ((functionp action)
13934 (setq org-map-continue-from nil)
13935 (save-excursion
13936 (setq rtn1 (funcall action))
13937 (push rtn1 rtn)))
13938 (t (user-error "Invalid action")))
13940 ;; if we are to skip sublevels, jump to end of subtree
13941 (unless org-tags-match-list-sublevels
13942 (org-end-of-subtree t)
13943 (backward-char 1))))
13944 ;; Get the correct position from where to continue
13945 (if org-map-continue-from
13946 (goto-char org-map-continue-from)
13947 (and (= (point) lspos) (end-of-line 1)))))
13948 (when (and (eq action 'sparse-tree)
13949 (not org-sparse-tree-open-archived-trees))
13950 (org-hide-archived-subtrees (point-min) (point-max)))
13951 (nreverse rtn)))
13953 (defun org-remove-uninherited-tags (tags)
13954 "Remove all tags that are not inherited from the list TAGS."
13955 (cond
13956 ((eq org-use-tag-inheritance t)
13957 (if org-tags-exclude-from-inheritance
13958 (org-delete-all org-tags-exclude-from-inheritance tags)
13959 tags))
13960 ((not org-use-tag-inheritance) nil)
13961 ((stringp org-use-tag-inheritance)
13962 (delq nil (mapcar
13963 (lambda (x)
13964 (if (and (string-match org-use-tag-inheritance x)
13965 (not (member x org-tags-exclude-from-inheritance)))
13966 x nil))
13967 tags)))
13968 ((listp org-use-tag-inheritance)
13969 (delq nil (mapcar
13970 (lambda (x)
13971 (if (member x org-use-tag-inheritance) x nil))
13972 tags)))))
13974 (defun org-match-sparse-tree (&optional todo-only match)
13975 "Create a sparse tree according to tags string MATCH.
13976 MATCH can contain positive and negative selection of tags, like
13977 \"+WORK+URGENT-WITHBOSS\".
13978 If optional argument TODO-ONLY is non-nil, only select lines that are
13979 also TODO lines."
13980 (interactive "P")
13981 (org-agenda-prepare-buffers (list (current-buffer)))
13982 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13984 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13986 (defvar org-cached-props nil)
13987 (defun org-cached-entry-get (pom property)
13988 (if (or (eq t org-use-property-inheritance)
13989 (and (stringp org-use-property-inheritance)
13990 (string-match org-use-property-inheritance property))
13991 (and (listp org-use-property-inheritance)
13992 (member property org-use-property-inheritance)))
13993 ;; Caching is not possible, check it directly
13994 (org-entry-get pom property 'inherit)
13995 ;; Get all properties, so that we can do complicated checks easily
13996 (cdr (assoc property (or org-cached-props
13997 (setq org-cached-props
13998 (org-entry-properties pom)))))))
14000 (defun org-global-tags-completion-table (&optional files)
14001 "Return the list of all tags in all agenda buffer/files.
14002 Optional FILES argument is a list of files which can be used
14003 instead of the agenda files."
14004 (save-excursion
14005 (org-uniquify
14006 (delq nil
14007 (apply 'append
14008 (mapcar
14009 (lambda (file)
14010 (set-buffer (find-file-noselect file))
14011 (append (org-get-buffer-tags)
14012 (mapcar (lambda (x) (if (stringp (car-safe x))
14013 (list (car-safe x)) nil))
14014 org-tag-alist)))
14015 (if (and files (car files))
14016 files
14017 (org-agenda-files))))))))
14019 (defun org-make-tags-matcher (match)
14020 "Create the TAGS/TODO matcher form for the selection string MATCH.
14022 The variable `todo-only' is scoped dynamically into this function.
14023 It will be set to t if the matcher restricts matching to TODO entries,
14024 otherwise will not be touched.
14026 Returns a cons of the selection string MATCH and the constructed
14027 lisp form implementing the matcher. The matcher is to be evaluated
14028 at an Org entry, with point on the headline, and returns t if the
14029 entry matches the selection string MATCH. The returned lisp form
14030 references two variables with information about the entry, which
14031 must be bound around the form's evaluation: todo, the TODO keyword
14032 at the entry (or nil of none); and tags-list, the list of all tags
14033 at the entry including inherited ones. Additionally, the category
14034 of the entry (if any) must be specified as the text property
14035 'org-category on the headline.
14037 See also `org-scan-tags'.
14039 (declare (special todo-only))
14040 (unless (boundp 'todo-only)
14041 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14042 (unless match
14043 ;; Get a new match request, with completion against the global
14044 ;; tags table and the local tags in current buffer
14045 (let ((org-last-tags-completion-table
14046 (org-uniquify
14047 (delq nil (append (org-get-buffer-tags)
14048 (org-global-tags-completion-table))))))
14049 (setq match (org-completing-read-no-i
14050 "Match: " 'org-tags-completion-function nil nil nil
14051 'org-tags-history))))
14053 ;; Parse the string and create a lisp form
14054 (let ((match0 match)
14055 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14056 minus tag mm
14057 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14058 orterms term orlist re-p str-p level-p level-op time-p
14059 prop-p pn pv po gv rest (start 0) (ss 0))
14060 ;; Expand group tags
14061 (setq match (org-tags-expand match))
14063 ;; Check if there is a TODO part of this match, which would be the
14064 ;; part after a "/". TO make sure that this slash is not part of
14065 ;; a property value to be matched against, we also check that there
14066 ;; is no " after that slash.
14067 ;; First, find the last slash
14068 (while (string-match "/+" match ss)
14069 (setq start (match-beginning 0) ss (match-end 0)))
14070 (if (and (string-match "/+" match start)
14071 (not (save-match-data (string-match "\"" match start))))
14072 ;; match contains also a todo-matching request
14073 (progn
14074 (setq tagsmatch (substring match 0 (match-beginning 0))
14075 todomatch (substring match (match-end 0)))
14076 (if (string-match "^!" todomatch)
14077 (setq todo-only t todomatch (substring todomatch 1)))
14078 (if (string-match "^\\s-*$" todomatch)
14079 (setq todomatch nil)))
14080 ;; only matching tags
14081 (setq tagsmatch match todomatch nil))
14083 ;; Make the tags matcher
14084 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14085 (setq tagsmatcher t)
14086 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14087 (while (setq term (pop orterms))
14088 (while (and (equal (substring term -1) "\\") orterms)
14089 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14090 (while (string-match re term)
14091 (setq rest (substring term (match-end 0))
14092 minus (and (match-end 1)
14093 (equal (match-string 1 term) "-"))
14094 tag (save-match-data (replace-regexp-in-string
14095 "\\\\-" "-"
14096 (match-string 2 term)))
14097 re-p (equal (string-to-char tag) ?{)
14098 level-p (match-end 4)
14099 prop-p (match-end 5)
14100 mm (cond
14101 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14102 (level-p
14103 (setq level-op (org-op-to-function (match-string 3 term)))
14104 `(,level-op level ,(string-to-number
14105 (match-string 4 term))))
14106 (prop-p
14107 (setq pn (match-string 5 term)
14108 po (match-string 6 term)
14109 pv (match-string 7 term)
14110 re-p (equal (string-to-char pv) ?{)
14111 str-p (equal (string-to-char pv) ?\")
14112 time-p (save-match-data
14113 (string-match "^\"[[<].*[]>]\"$" pv))
14114 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14115 (if time-p (setq pv (org-matcher-time pv)))
14116 (setq po (org-op-to-function po (if time-p 'time str-p)))
14117 (cond
14118 ((equal pn "CATEGORY")
14119 (setq gv '(get-text-property (point) 'org-category)))
14120 ((equal pn "TODO")
14121 (setq gv 'todo))
14123 (setq gv `(org-cached-entry-get nil ,pn))))
14124 (if re-p
14125 (if (eq po 'org<>)
14126 `(not (string-match ,pv (or ,gv "")))
14127 `(string-match ,pv (or ,gv "")))
14128 (if str-p
14129 `(,po (or ,gv "") ,pv)
14130 `(,po (string-to-number (or ,gv ""))
14131 ,(string-to-number pv) ))))
14132 (t `(member ,tag tags-list)))
14133 mm (if minus (list 'not mm) mm)
14134 term rest)
14135 (push mm tagsmatcher))
14136 (push (if (> (length tagsmatcher) 1)
14137 (cons 'and tagsmatcher)
14138 (car tagsmatcher))
14139 orlist)
14140 (setq tagsmatcher nil))
14141 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14142 (setq tagsmatcher
14143 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14144 ;; Make the todo matcher
14145 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14146 (setq todomatcher t)
14147 (setq orterms (org-split-string todomatch "|") orlist nil)
14148 (while (setq term (pop orterms))
14149 (while (string-match re term)
14150 (setq minus (and (match-end 1)
14151 (equal (match-string 1 term) "-"))
14152 kwd (match-string 2 term)
14153 re-p (equal (string-to-char kwd) ?{)
14154 term (substring term (match-end 0))
14155 mm (if re-p
14156 `(string-match ,(substring kwd 1 -1) todo)
14157 (list 'equal 'todo kwd))
14158 mm (if minus (list 'not mm) mm))
14159 (push mm todomatcher))
14160 (push (if (> (length todomatcher) 1)
14161 (cons 'and todomatcher)
14162 (car todomatcher))
14163 orlist)
14164 (setq todomatcher nil))
14165 (setq todomatcher (if (> (length orlist) 1)
14166 (cons 'or orlist) (car orlist))))
14168 ;; Return the string and lisp forms of the matcher
14169 (setq matcher (if todomatcher
14170 (list 'and tagsmatcher todomatcher)
14171 tagsmatcher))
14172 (when todo-only
14173 (setq matcher (list 'and '(member todo org-not-done-keywords)
14174 matcher)))
14175 (cons match0 matcher)))
14177 (defun org-tags-expand (match &optional single-as-list downcased)
14178 "Expand group tags in MATCH.
14180 This replaces every group tag in MATCH with a regexp tag search.
14181 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14182 will be replaced like this:
14184 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14185 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14186 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14188 Replacing by a regexp preserves the structure of the match.
14189 E.g., this expansion
14191 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14193 will match anything tagged with \"Lab\" and \"Home\", or tagged
14194 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14196 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14197 assumed to be a single group tag, and the function will return
14198 the list of tags in this group.
14200 When DOWNCASE is non-nil, expand downcased TAGS."
14201 (if org-group-tags
14202 (let* ((case-fold-search t)
14203 (stable org-mode-syntax-table)
14204 (tal (or org-tag-groups-alist-for-agenda
14205 org-tag-groups-alist))
14206 (tal (if downcased
14207 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14208 (tml (mapcar 'car tal))
14209 (rtnmatch match) rpl)
14210 ;; @ and _ are allowed as word-components in tags
14211 (modify-syntax-entry ?@ "w" stable)
14212 (modify-syntax-entry ?_ "w" stable)
14213 (while (and tml
14214 (with-syntax-table stable
14215 (string-match
14216 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14217 (regexp-opt tml) "\\>\\)") rtnmatch)))
14218 (let* ((dir (match-string 1 rtnmatch))
14219 (tag (match-string 2 rtnmatch))
14220 (tag (if downcased (downcase tag) tag)))
14221 (setq tml (delete tag tml))
14222 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14223 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14224 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14225 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14226 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14227 (if single-as-list
14228 (or (reverse rpl) (list rtnmatch))
14229 rtnmatch))
14230 (if single-as-list (list (if downcased (downcase match) match))
14231 match)))
14233 (defun org-op-to-function (op &optional stringp)
14234 "Turn an operator into the appropriate function."
14235 (setq op
14236 (cond
14237 ((equal op "<" ) '(< string< org-time<))
14238 ((equal op ">" ) '(> org-string> org-time>))
14239 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14240 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14241 ((member op '("=" "==")) '(= string= org-time=))
14242 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14243 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14245 (defun org<> (a b) (not (= a b)))
14246 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14247 (defun org-string>= (a b) (not (string< a b)))
14248 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14249 (defun org-string<> (a b) (not (string= a b)))
14250 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14251 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14252 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14253 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14254 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14255 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14256 (defun org-2ft (s)
14257 "Convert S to a floating point time.
14258 If S is already a number, just return it. If it is a string, parse
14259 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14260 (cond
14261 ((numberp s) s)
14262 ((stringp s)
14263 (condition-case nil
14264 (float-time (apply 'encode-time (org-parse-time-string s)))
14265 (error 0.)))
14266 (t 0.)))
14268 (defun org-time-today ()
14269 "Time in seconds today at 0:00.
14270 Returns the float number of seconds since the beginning of the
14271 epoch to the beginning of today (00:00)."
14272 (float-time (apply 'encode-time
14273 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14275 (defun org-matcher-time (s)
14276 "Interpret a time comparison value."
14277 (save-match-data
14278 (cond
14279 ((string= s "<now>") (float-time))
14280 ((string= s "<today>") (org-time-today))
14281 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14282 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14283 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14284 (+ (org-time-today)
14285 (* (string-to-number (match-string 1 s))
14286 (cdr (assoc (match-string 2 s)
14287 '(("d" . 86400.0) ("w" . 604800.0)
14288 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14289 (t (org-2ft s)))))
14291 (defun org-match-any-p (re list)
14292 "Does re match any element of list?"
14293 (setq list (mapcar (lambda (x) (string-match re x)) list))
14294 (delq nil list))
14296 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14297 (defvar org-tags-overlay (make-overlay 1 1))
14298 (org-detach-overlay org-tags-overlay)
14300 (defun org-get-local-tags-at (&optional pos)
14301 "Get a list of tags defined in the current headline."
14302 (org-get-tags-at pos 'local))
14304 (defun org-get-local-tags ()
14305 "Get a list of tags defined in the current headline."
14306 (org-get-tags-at nil 'local))
14308 (defun org-get-tags-at (&optional pos local)
14309 "Get a list of all headline tags applicable at POS.
14310 POS defaults to point. If tags are inherited, the list contains
14311 the targets in the same sequence as the headlines appear, i.e.
14312 the tags of the current headline come last.
14313 When LOCAL is non-nil, only return tags from the current headline,
14314 ignore inherited ones."
14315 (interactive)
14316 (if (and org-trust-scanner-tags
14317 (or (not pos) (equal pos (point)))
14318 (not local))
14319 org-scanner-tags
14320 (let (tags ltags lastpos parent)
14321 (save-excursion
14322 (save-restriction
14323 (widen)
14324 (goto-char (or pos (point)))
14325 (save-match-data
14326 (catch 'done
14327 (condition-case nil
14328 (progn
14329 (org-back-to-heading t)
14330 (while (not (equal lastpos (point)))
14331 (setq lastpos (point))
14332 (when (looking-at
14333 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14334 (setq ltags (org-split-string
14335 (org-match-string-no-properties 1) ":"))
14336 (when parent
14337 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14338 (setq tags (append
14339 (if parent
14340 (org-remove-uninherited-tags ltags)
14341 ltags)
14342 tags)))
14343 (or org-use-tag-inheritance (throw 'done t))
14344 (if local (throw 'done t))
14345 (or (org-up-heading-safe) (error nil))
14346 (setq parent t)))
14347 (error nil)))))
14348 (if local
14349 tags
14350 (reverse (delete-dups
14351 (reverse (append
14352 (org-remove-uninherited-tags
14353 org-file-tags) tags)))))))))
14355 (defun org-add-prop-inherited (s)
14356 (add-text-properties 0 (length s) '(inherited t) s)
14359 (defun org-toggle-tag (tag &optional onoff)
14360 "Toggle the tag TAG for the current line.
14361 If ONOFF is `on' or `off', don't toggle but set to this state."
14362 (let (res current)
14363 (save-excursion
14364 (org-back-to-heading t)
14365 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14366 (point-at-eol) t)
14367 (progn
14368 (setq current (match-string 1))
14369 (replace-match ""))
14370 (setq current ""))
14371 (setq current (nreverse (org-split-string current ":")))
14372 (cond
14373 ((eq onoff 'on)
14374 (setq res t)
14375 (or (member tag current) (push tag current)))
14376 ((eq onoff 'off)
14377 (or (not (member tag current)) (setq current (delete tag current))))
14378 (t (if (member tag current)
14379 (setq current (delete tag current))
14380 (setq res t)
14381 (push tag current))))
14382 (end-of-line 1)
14383 (if current
14384 (progn
14385 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14386 (org-set-tags nil t))
14387 (delete-horizontal-space))
14388 (run-hooks 'org-after-tags-change-hook))
14389 res))
14391 (defun org-align-tags-here (to-col)
14392 ;; Assumes that this is a headline
14393 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14394 (beginning-of-line 1)
14395 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14396 (< pos (match-beginning 2)))
14397 (progn
14398 (setq tags-l (- (match-end 2) (match-beginning 2)))
14399 (goto-char (match-beginning 1))
14400 (insert " ")
14401 (delete-region (point) (1+ (match-beginning 2)))
14402 (setq ncol (max (current-column)
14403 (1+ col)
14404 (if (> to-col 0)
14405 to-col
14406 (- (abs to-col) tags-l))))
14407 (setq p (point))
14408 (insert (make-string (- ncol (current-column)) ?\ ))
14409 (setq ncol (current-column))
14410 (when indent-tabs-mode (tabify p (point-at-eol)))
14411 (org-move-to-column (min ncol col) t))
14412 (goto-char pos))))
14414 (defun org-set-tags-command (&optional arg just-align)
14415 "Call the set-tags command for the current entry."
14416 (interactive "P")
14417 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14418 (org-set-tags arg just-align)
14419 (save-excursion
14420 (unless (and (org-region-active-p)
14421 org-loop-over-headlines-in-active-region)
14422 (org-back-to-heading t))
14423 (org-set-tags arg just-align))))
14425 (defun org-set-tags-to (data)
14426 "Set the tags of the current entry to DATA, replacing the current tags.
14427 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14428 If DATA is nil or the empty string, any tags will be removed."
14429 (interactive "sTags: ")
14430 (setq data
14431 (cond
14432 ((eq data nil) "")
14433 ((equal data "") "")
14434 ((stringp data)
14435 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14436 ":"))
14437 ((listp data)
14438 (concat ":" (mapconcat 'identity data ":") ":"))))
14439 (when data
14440 (save-excursion
14441 (org-back-to-heading t)
14442 (when (looking-at org-complex-heading-regexp)
14443 (if (match-end 5)
14444 (progn
14445 (goto-char (match-beginning 5))
14446 (insert data)
14447 (delete-region (point) (point-at-eol))
14448 (org-set-tags nil 'align))
14449 (goto-char (point-at-eol))
14450 (insert " " data)
14451 (org-set-tags nil 'align)))
14452 (beginning-of-line 1)
14453 (if (looking-at ".*?\\([ \t]+\\)$")
14454 (delete-region (match-beginning 1) (match-end 1))))))
14456 (defun org-align-all-tags ()
14457 "Align the tags i all headings."
14458 (interactive)
14459 (save-excursion
14460 (or (ignore-errors (org-back-to-heading t))
14461 (outline-next-heading))
14462 (if (org-at-heading-p)
14463 (org-set-tags t)
14464 (message "No headings"))))
14466 (defvar org-indent-indentation-per-level)
14467 (defun org-set-tags (&optional arg just-align)
14468 "Set the tags for the current headline.
14469 With prefix ARG, realign all tags in headings in the current buffer."
14470 (interactive "P")
14471 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14472 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14473 'region-start-level 'region))
14474 org-loop-over-headlines-in-active-region)
14475 (org-map-entries
14476 ;; We don't use ARG and JUST-ALIGN here these args are not
14477 ;; useful when looping over headlines
14478 `(org-set-tags)
14479 org-loop-over-headlines-in-active-region
14480 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14481 (let* ((re org-outline-regexp-bol)
14482 (current (unless arg (org-get-tags-string)))
14483 (col (current-column))
14484 (org-setting-tags t)
14485 table current-tags inherited-tags ; computed below when needed
14486 tags p0 c0 c1 rpl di tc level)
14487 (if arg
14488 (save-excursion
14489 (goto-char (point-min))
14490 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14491 (while (re-search-forward re nil t)
14492 (org-set-tags nil t)
14493 (end-of-line 1)))
14494 (message "All tags realigned to column %d" org-tags-column))
14495 (if just-align
14496 (setq tags current)
14497 ;; Get a new set of tags from the user
14498 (save-excursion
14499 (setq table (append org-tag-persistent-alist
14500 (or org-tag-alist (org-get-buffer-tags))
14501 (and
14502 org-complete-tags-always-offer-all-agenda-tags
14503 (org-global-tags-completion-table
14504 (org-agenda-files))))
14505 org-last-tags-completion-table table
14506 current-tags (org-split-string current ":")
14507 inherited-tags (nreverse
14508 (nthcdr (length current-tags)
14509 (nreverse (org-get-tags-at))))
14510 tags
14511 (if (or (eq t org-use-fast-tag-selection)
14512 (and org-use-fast-tag-selection
14513 (delq nil (mapcar 'cdr table))))
14514 (org-fast-tag-selection
14515 current-tags inherited-tags table
14516 (if org-fast-tag-selection-include-todo
14517 org-todo-key-alist))
14518 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14519 (org-trim
14520 (org-icompleting-read "Tags: "
14521 'org-tags-completion-function
14522 nil nil current 'org-tags-history))))))
14523 (while (string-match "[-+&]+" tags)
14524 ;; No boolean logic, just a list
14525 (setq tags (replace-match ":" t t tags))))
14527 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14529 (if org-tags-sort-function
14530 (setq tags (mapconcat 'identity
14531 (sort (org-split-string
14532 tags (org-re "[^[:alnum:]_@#%]+"))
14533 org-tags-sort-function) ":")))
14535 (if (string-match "\\`[\t ]*\\'" tags)
14536 (setq tags "")
14537 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14538 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14540 ;; Insert new tags at the correct column
14541 (beginning-of-line 1)
14542 (setq level (or (and (looking-at org-outline-regexp)
14543 (- (match-end 0) (point) 1))
14545 (cond
14546 ((and (equal current "") (equal tags "")))
14547 ((re-search-forward
14548 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14549 (point-at-eol) t)
14550 (if (equal tags "")
14551 (setq rpl "")
14552 (goto-char (match-beginning 0))
14553 (setq c0 (current-column)
14554 ;; compute offset for the case of org-indent-mode active
14555 di (if org-indent-mode
14556 (* (1- org-indent-indentation-per-level) (1- level))
14558 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14559 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14560 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14561 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14562 (replace-match rpl t t)
14563 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14564 tags)
14565 (t (error "Tags alignment failed")))
14566 (org-move-to-column col)
14567 (unless just-align
14568 (run-hooks 'org-after-tags-change-hook))))))
14570 (defun org-change-tag-in-region (beg end tag off)
14571 "Add or remove TAG for each entry in the region.
14572 This works in the agenda, and also in an org-mode buffer."
14573 (interactive
14574 (list (region-beginning) (region-end)
14575 (let ((org-last-tags-completion-table
14576 (if (derived-mode-p 'org-mode)
14577 (org-uniquify
14578 (delq nil (append (org-get-buffer-tags)
14579 (org-global-tags-completion-table))))
14580 (org-global-tags-completion-table))))
14581 (org-icompleting-read
14582 "Tag: " 'org-tags-completion-function nil nil nil
14583 'org-tags-history))
14584 (progn
14585 (message "[s]et or [r]emove? ")
14586 (equal (read-char-exclusive) ?r))))
14587 (if (fboundp 'deactivate-mark) (deactivate-mark))
14588 (let ((agendap (equal major-mode 'org-agenda-mode))
14589 l1 l2 m buf pos newhead (cnt 0))
14590 (goto-char end)
14591 (setq l2 (1- (org-current-line)))
14592 (goto-char beg)
14593 (setq l1 (org-current-line))
14594 (loop for l from l1 to l2 do
14595 (org-goto-line l)
14596 (setq m (get-text-property (point) 'org-hd-marker))
14597 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14598 (and agendap m))
14599 (setq buf (if agendap (marker-buffer m) (current-buffer))
14600 pos (if agendap m (point)))
14601 (with-current-buffer buf
14602 (save-excursion
14603 (save-restriction
14604 (goto-char pos)
14605 (setq cnt (1+ cnt))
14606 (org-toggle-tag tag (if off 'off 'on))
14607 (setq newhead (org-get-heading)))))
14608 (and agendap (org-agenda-change-all-lines newhead m))))
14609 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14611 (defun org-tags-completion-function (string predicate &optional flag)
14612 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14613 (confirm (lambda (x) (stringp (car x)))))
14614 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14615 (setq s1 (match-string 1 string)
14616 s2 (match-string 2 string))
14617 (setq s1 "" s2 string))
14618 (cond
14619 ((eq flag nil)
14620 ;; try completion
14621 (setq rtn (try-completion s2 ctable confirm))
14622 (if (stringp rtn)
14623 (setq rtn
14624 (concat s1 s2 (substring rtn (length s2))
14625 (if (and org-add-colon-after-tag-completion
14626 (assoc rtn ctable))
14627 ":" ""))))
14628 rtn)
14629 ((eq flag t)
14630 ;; all-completions
14631 (all-completions s2 ctable confirm))
14632 ((eq flag 'lambda)
14633 ;; exact match?
14634 (assoc s2 ctable)))))
14636 (defun org-fast-tag-insert (kwd tags face &optional end)
14637 "Insert KDW, and the TAGS, the latter with face FACE.
14638 Also insert END."
14639 (insert (format "%-12s" (concat kwd ":"))
14640 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14641 (or end "")))
14643 (defun org-fast-tag-show-exit (flag)
14644 (save-excursion
14645 (org-goto-line 3)
14646 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14647 (replace-match ""))
14648 (when flag
14649 (end-of-line 1)
14650 (org-move-to-column (- (window-width) 19) t)
14651 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14653 (defun org-set-current-tags-overlay (current prefix)
14654 "Add an overlay to CURRENT tag with PREFIX."
14655 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14656 (if (featurep 'xemacs)
14657 (org-overlay-display org-tags-overlay (concat prefix s)
14658 'secondary-selection)
14659 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14660 (org-overlay-display org-tags-overlay (concat prefix s)))))
14662 (defvar org-last-tag-selection-key nil)
14663 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14664 "Fast tag selection with single keys.
14665 CURRENT is the current list of tags in the headline, INHERITED is the
14666 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14667 possibly with grouping information. TODO-TABLE is a similar table with
14668 TODO keywords, should these have keys assigned to them.
14669 If the keys are nil, a-z are automatically assigned.
14670 Returns the new tags string, or nil to not change the current settings."
14671 (let* ((fulltable (append table todo-table))
14672 (maxlen (apply 'max (mapcar
14673 (lambda (x)
14674 (if (stringp (car x)) (string-width (car x)) 0))
14675 fulltable)))
14676 (buf (current-buffer))
14677 (expert (eq org-fast-tag-selection-single-key 'expert))
14678 (buffer-tags nil)
14679 (fwidth (+ maxlen 3 1 3))
14680 (ncol (/ (- (window-width) 4) fwidth))
14681 (i-face 'org-done)
14682 (c-face 'org-todo)
14683 tg cnt e c char c1 c2 ntable tbl rtn
14684 ov-start ov-end ov-prefix
14685 (exit-after-next org-fast-tag-selection-single-key)
14686 (done-keywords org-done-keywords)
14687 groups ingroup)
14688 (save-excursion
14689 (beginning-of-line 1)
14690 (if (looking-at
14691 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14692 (setq ov-start (match-beginning 1)
14693 ov-end (match-end 1)
14694 ov-prefix "")
14695 (setq ov-start (1- (point-at-eol))
14696 ov-end (1+ ov-start))
14697 (skip-chars-forward "^\n\r")
14698 (setq ov-prefix
14699 (concat
14700 (buffer-substring (1- (point)) (point))
14701 (if (> (current-column) org-tags-column)
14703 (make-string (- org-tags-column (current-column)) ?\ ))))))
14704 (move-overlay org-tags-overlay ov-start ov-end)
14705 (save-window-excursion
14706 (if expert
14707 (set-buffer (get-buffer-create " *Org tags*"))
14708 (delete-other-windows)
14709 (split-window-vertically)
14710 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14711 (erase-buffer)
14712 (org-set-local 'org-done-keywords done-keywords)
14713 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14714 (org-fast-tag-insert "Current" current c-face "\n\n")
14715 (org-fast-tag-show-exit exit-after-next)
14716 (org-set-current-tags-overlay current ov-prefix)
14717 (setq tbl fulltable char ?a cnt 0)
14718 (while (setq e (pop tbl))
14719 (cond
14720 ((equal (car e) :startgroup)
14721 (push '() groups) (setq ingroup t)
14722 (when (not (= cnt 0))
14723 (setq cnt 0)
14724 (insert "\n"))
14725 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14726 ((equal (car e) :endgroup)
14727 (setq ingroup nil cnt 0)
14728 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14729 ((equal e '(:newline))
14730 (when (not (= cnt 0))
14731 (setq cnt 0)
14732 (insert "\n")
14733 (setq e (car tbl))
14734 (while (equal (car tbl) '(:newline))
14735 (insert "\n")
14736 (setq tbl (cdr tbl)))))
14737 ((equal e '(:grouptags)) nil)
14739 (setq tg (copy-sequence (car e)) c2 nil)
14740 (if (cdr e)
14741 (setq c (cdr e))
14742 ;; automatically assign a character.
14743 (setq c1 (string-to-char
14744 (downcase (substring
14745 tg (if (= (string-to-char tg) ?@) 1 0)))))
14746 (if (or (rassoc c1 ntable) (rassoc c1 table))
14747 (while (or (rassoc char ntable) (rassoc char table))
14748 (setq char (1+ char)))
14749 (setq c2 c1))
14750 (setq c (or c2 char)))
14751 (if ingroup (push tg (car groups)))
14752 (setq tg (org-add-props tg nil 'face
14753 (cond
14754 ((not (assoc tg table))
14755 (org-get-todo-face tg))
14756 ((member tg current) c-face)
14757 ((member tg inherited) i-face))))
14758 (if (equal (caar tbl) :grouptags)
14759 (org-add-props tg nil 'face 'org-tag-group))
14760 (if (and (= cnt 0) (not ingroup)) (insert " "))
14761 (insert "[" c "] " tg (make-string
14762 (- fwidth 4 (length tg)) ?\ ))
14763 (push (cons tg c) ntable)
14764 (when (= (setq cnt (1+ cnt)) ncol)
14765 (insert "\n")
14766 (if ingroup (insert " "))
14767 (setq cnt 0)))))
14768 (setq ntable (nreverse ntable))
14769 (insert "\n")
14770 (goto-char (point-min))
14771 (if (not expert) (org-fit-window-to-buffer))
14772 (setq rtn
14773 (catch 'exit
14774 (while t
14775 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14776 (if (not groups) "no " "")
14777 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14778 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14779 (setq org-last-tag-selection-key c)
14780 (cond
14781 ((= c ?\r) (throw 'exit t))
14782 ((= c ?!)
14783 (setq groups (not groups))
14784 (goto-char (point-min))
14785 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14786 ((= c ?\C-c)
14787 (if (not expert)
14788 (org-fast-tag-show-exit
14789 (setq exit-after-next (not exit-after-next)))
14790 (setq expert nil)
14791 (delete-other-windows)
14792 (set-window-buffer (split-window-vertically) " *Org tags*")
14793 (org-switch-to-buffer-other-window " *Org tags*")
14794 (org-fit-window-to-buffer)))
14795 ((or (= c ?\C-g)
14796 (and (= c ?q) (not (rassoc c ntable))))
14797 (org-detach-overlay org-tags-overlay)
14798 (setq quit-flag t))
14799 ((= c ?\ )
14800 (setq current nil)
14801 (if exit-after-next (setq exit-after-next 'now)))
14802 ((= c ?\t)
14803 (condition-case nil
14804 (setq tg (org-icompleting-read
14805 "Tag: "
14806 (or buffer-tags
14807 (with-current-buffer buf
14808 (org-get-buffer-tags)))))
14809 (quit (setq tg "")))
14810 (when (string-match "\\S-" tg)
14811 (add-to-list 'buffer-tags (list tg))
14812 (if (member tg current)
14813 (setq current (delete tg current))
14814 (push tg current)))
14815 (if exit-after-next (setq exit-after-next 'now)))
14816 ((setq e (rassoc c todo-table) tg (car e))
14817 (with-current-buffer buf
14818 (save-excursion (org-todo tg)))
14819 (if exit-after-next (setq exit-after-next 'now)))
14820 ((setq e (rassoc c ntable) tg (car e))
14821 (if (member tg current)
14822 (setq current (delete tg current))
14823 (loop for g in groups do
14824 (if (member tg g)
14825 (mapc (lambda (x)
14826 (setq current (delete x current)))
14827 g)))
14828 (push tg current))
14829 (if exit-after-next (setq exit-after-next 'now))))
14831 ;; Create a sorted list
14832 (setq current
14833 (sort current
14834 (lambda (a b)
14835 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14836 (if (eq exit-after-next 'now) (throw 'exit t))
14837 (goto-char (point-min))
14838 (beginning-of-line 2)
14839 (delete-region (point) (point-at-eol))
14840 (org-fast-tag-insert "Current" current c-face)
14841 (org-set-current-tags-overlay current ov-prefix)
14842 (while (re-search-forward
14843 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14844 (setq tg (match-string 1))
14845 (add-text-properties
14846 (match-beginning 1) (match-end 1)
14847 (list 'face
14848 (cond
14849 ((member tg current) c-face)
14850 ((member tg inherited) i-face)
14851 (t (get-text-property (match-beginning 1) 'face))))))
14852 (goto-char (point-min)))))
14853 (org-detach-overlay org-tags-overlay)
14854 (if rtn
14855 (mapconcat 'identity current ":")
14856 nil))))
14858 (defun org-get-tags-string ()
14859 "Get the TAGS string in the current headline."
14860 (unless (org-at-heading-p t)
14861 (user-error "Not on a heading"))
14862 (save-excursion
14863 (beginning-of-line 1)
14864 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14865 (org-match-string-no-properties 1)
14866 "")))
14868 (defun org-get-tags ()
14869 "Get the list of tags specified in the current headline."
14870 (org-split-string (org-get-tags-string) ":"))
14872 (defun org-get-buffer-tags ()
14873 "Get a table of all tags used in the buffer, for completion."
14874 (let (tags)
14875 (save-excursion
14876 (goto-char (point-min))
14877 (while (re-search-forward
14878 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14879 (when (equal (char-after (point-at-bol 0)) ?*)
14880 (mapc (lambda (x) (add-to-list 'tags x))
14881 (org-split-string (org-match-string-no-properties 1) ":")))))
14882 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14883 (mapcar 'list tags)))
14885 ;;;; The mapping API
14887 (defun org-map-entries (func &optional match scope &rest skip)
14888 "Call FUNC at each headline selected by MATCH in SCOPE.
14890 FUNC is a function or a lisp form. The function will be called without
14891 arguments, with the cursor positioned at the beginning of the headline.
14892 The return values of all calls to the function will be collected and
14893 returned as a list.
14895 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14896 does not need to preserve point. After evaluation, the cursor will be
14897 moved to the end of the line (presumably of the headline of the
14898 processed entry) and search continues from there. Under some
14899 circumstances, this may not produce the wanted results. For example,
14900 if you have removed (e.g. archived) the current (sub)tree it could
14901 mean that the next entry will be skipped entirely. In such cases, you
14902 can specify the position from where search should continue by making
14903 FUNC set the variable `org-map-continue-from' to the desired buffer
14904 position.
14906 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14907 Only headlines that are matched by this query will be considered during
14908 the iteration. When MATCH is nil or t, all headlines will be
14909 visited by the iteration.
14911 SCOPE determines the scope of this command. It can be any of:
14913 nil The current buffer, respecting the restriction if any
14914 tree The subtree started with the entry at point
14915 region The entries within the active region, if any
14916 region-start-level
14917 The entries within the active region, but only those at
14918 the same level than the first one.
14919 file The current buffer, without restriction
14920 file-with-archives
14921 The current buffer, and any archives associated with it
14922 agenda All agenda files
14923 agenda-with-archives
14924 All agenda files with any archive files associated with them
14925 \(file1 file2 ...)
14926 If this is a list, all files in the list will be scanned
14928 The remaining args are treated as settings for the skipping facilities of
14929 the scanner. The following items can be given here:
14931 archive skip trees with the archive tag
14932 comment skip trees with the COMMENT keyword
14933 function or Emacs Lisp form:
14934 will be used as value for `org-agenda-skip-function', so
14935 whenever the function returns a position, FUNC will not be
14936 called for that entry and search will continue from the
14937 position returned
14939 If your function needs to retrieve the tags including inherited tags
14940 at the *current* entry, you can use the value of the variable
14941 `org-scanner-tags' which will be much faster than getting the value
14942 with `org-get-tags-at'. If your function gets properties with
14943 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14944 to t around the call to `org-entry-properties' to get the same speedup.
14945 Note that if your function moves around to retrieve tags and properties at
14946 a *different* entry, you cannot use these techniques."
14947 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14948 (not (org-region-active-p)))
14949 (let* ((org-agenda-archives-mode nil) ; just to make sure
14950 (org-agenda-skip-archived-trees (memq 'archive skip))
14951 (org-agenda-skip-comment-trees (memq 'comment skip))
14952 (org-agenda-skip-function
14953 (car (org-delete-all '(comment archive) skip)))
14954 (org-tags-match-list-sublevels t)
14955 (start-level (eq scope 'region-start-level))
14956 matcher file res
14957 org-todo-keywords-for-agenda
14958 org-done-keywords-for-agenda
14959 org-todo-keyword-alist-for-agenda
14960 org-drawers-for-agenda
14961 org-tag-alist-for-agenda
14962 todo-only)
14964 (cond
14965 ((eq match t) (setq matcher t))
14966 ((eq match nil) (setq matcher t))
14967 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14969 (save-window-excursion
14970 (save-restriction
14971 (cond ((eq scope 'tree)
14972 (org-back-to-heading t)
14973 (org-narrow-to-subtree)
14974 (setq scope nil))
14975 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14976 (org-region-active-p))
14977 ;; If needed, set start-level to a string like "2"
14978 (when start-level
14979 (save-excursion
14980 (goto-char (region-beginning))
14981 (unless (org-at-heading-p) (outline-next-heading))
14982 (setq start-level (org-current-level))))
14983 (narrow-to-region (region-beginning)
14984 (save-excursion
14985 (goto-char (region-end))
14986 (unless (and (bolp) (org-at-heading-p))
14987 (outline-next-heading))
14988 (point)))
14989 (setq scope nil)))
14991 (if (not scope)
14992 (progn
14993 (org-agenda-prepare-buffers
14994 (list (buffer-file-name (current-buffer))))
14995 (setq res (org-scan-tags func matcher todo-only start-level)))
14996 ;; Get the right scope
14997 (cond
14998 ((and scope (listp scope) (symbolp (car scope)))
14999 (setq scope (eval scope)))
15000 ((eq scope 'agenda)
15001 (setq scope (org-agenda-files t)))
15002 ((eq scope 'agenda-with-archives)
15003 (setq scope (org-agenda-files t))
15004 (setq scope (org-add-archive-files scope)))
15005 ((eq scope 'file)
15006 (setq scope (list (buffer-file-name))))
15007 ((eq scope 'file-with-archives)
15008 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15009 (org-agenda-prepare-buffers scope)
15010 (while (setq file (pop scope))
15011 (with-current-buffer (org-find-base-buffer-visiting file)
15012 (save-excursion
15013 (save-restriction
15014 (widen)
15015 (goto-char (point-min))
15016 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15017 res)))
15019 ;;;; Properties
15021 ;;; Setting and retrieving properties
15023 (defconst org-special-properties
15024 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15025 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15026 "The special properties valid in Org-mode.
15028 These are properties that are not defined in the property drawer,
15029 but in some other way.")
15031 (defconst org-default-properties
15032 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15033 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15034 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15035 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15036 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15037 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15038 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15039 "Some properties that are used by Org-mode for various purposes.
15040 Being in this list makes sure that they are offered for completion.")
15042 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15043 "Regular expression matching the first line of a property drawer.")
15045 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15046 "Regular expression matching the last line of a property drawer.")
15048 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15049 "Regular expression matching the first line of a property drawer.")
15051 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15052 "Regular expression matching the first line of a property drawer.")
15054 (defconst org-property-drawer-re
15055 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15056 org-property-end-re "\\)\n?")
15057 "Matches an entire property drawer.")
15059 (defconst org-clock-drawer-re
15060 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15061 org-property-end-re "\\)\n?")
15062 "Matches an entire clock drawer.")
15064 (defun org-property-action ()
15065 "Do an action on properties."
15066 (interactive)
15067 (let (c)
15068 (org-at-property-p)
15069 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15070 (setq c (read-char-exclusive))
15071 (cond
15072 ((equal c ?s)
15073 (call-interactively 'org-set-property))
15074 ((equal c ?d)
15075 (call-interactively 'org-delete-property))
15076 ((equal c ?D)
15077 (call-interactively 'org-delete-property-globally))
15078 ((equal c ?c)
15079 (call-interactively 'org-compute-property-at-point))
15080 (t (user-error "No such property action %c" c)))))
15082 (defun org-inc-effort ()
15083 "Increment the value of the effort property in the current entry."
15084 (interactive)
15085 (org-set-effort nil t))
15087 (defvar org-clock-effort) ;; Defined in org-clock.el
15088 (defvar org-clock-current-task) ;; Defined in org-clock.el
15089 (defun org-set-effort (&optional value increment)
15090 "Set the effort property of the current entry.
15091 With numerical prefix arg, use the nth allowed value, 0 stands for the
15092 10th allowed value.
15094 When INCREMENT is non-nil, set the property to the next allowed value."
15095 (interactive "P")
15096 (if (equal value 0) (setq value 10))
15097 (let* ((completion-ignore-case t)
15098 (prop org-effort-property)
15099 (cur (org-entry-get nil prop))
15100 (allowed (org-property-get-allowed-values nil prop 'table))
15101 (existing (mapcar 'list (org-property-values prop)))
15102 (heading (nth 4 (org-heading-components)))
15104 (val (cond
15105 ((stringp value) value)
15106 ((and allowed (integerp value))
15107 (or (car (nth (1- value) allowed))
15108 (car (org-last allowed))))
15109 ((and allowed increment)
15110 (or (caadr (member (list cur) allowed))
15111 (user-error "Allowed effort values are not set")))
15112 (allowed
15113 (message "Select 1-9,0, [RET%s]: %s"
15114 (if cur (concat "=" cur) "")
15115 (mapconcat 'car allowed " "))
15116 (setq rpl (read-char-exclusive))
15117 (if (equal rpl ?\r)
15119 (setq rpl (- rpl ?0))
15120 (if (equal rpl 0) (setq rpl 10))
15121 (if (and (> rpl 0) (<= rpl (length allowed)))
15122 (car (nth (1- rpl) allowed))
15123 (org-completing-read "Effort: " allowed nil))))
15125 (let (org-completion-use-ido org-completion-use-iswitchb)
15126 (org-completing-read
15127 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15128 (concat "[" cur "]") "")
15129 ": ")
15130 existing nil nil "" nil cur))))))
15131 (unless (equal (org-entry-get nil prop) val)
15132 (org-entry-put nil prop val))
15133 (save-excursion
15134 (org-back-to-heading t)
15135 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15136 (when (string= heading org-clock-current-task)
15137 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15138 (org-clock-update-mode-line))
15139 (message "%s is now %s" prop val)))
15141 (defun org-at-property-p ()
15142 "Is cursor inside a property drawer?"
15143 (save-excursion
15144 (when (equal 'node-property (car (org-element-at-point)))
15145 (beginning-of-line 1)
15146 (looking-at org-property-re))))
15148 (defun org-get-property-block (&optional beg end force)
15149 "Return the (beg . end) range of the body of the property drawer.
15150 BEG and END are the beginning and end of the current subtree, or of
15151 the part before the first headline. If they are not given, they will
15152 be found. If the drawer does not exist and FORCE is non-nil, create
15153 the drawer."
15154 (catch 'exit
15155 (save-excursion
15156 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15157 (progn (org-back-to-heading t) (point))))
15158 (end (or end (and (not (outline-next-heading)) (point-max))
15159 (point))))
15160 (goto-char beg)
15161 (if (re-search-forward org-property-start-re end t)
15162 (setq beg (1+ (match-end 0)))
15163 (if force
15164 (save-excursion
15165 (org-insert-property-drawer)
15166 (setq end (progn (outline-next-heading) (point))))
15167 (throw 'exit nil))
15168 (goto-char beg)
15169 (if (re-search-forward org-property-start-re end t)
15170 (setq beg (1+ (match-end 0)))))
15171 (if (re-search-forward org-property-end-re end t)
15172 (setq end (match-beginning 0))
15173 (or force (throw 'exit nil))
15174 (goto-char beg)
15175 (setq end beg)
15176 (org-indent-line)
15177 (insert ":END:\n"))
15178 (cons beg end)))))
15180 (defun org-entry-properties (&optional pom which specific)
15181 "Get all properties of the entry at point-or-marker POM.
15182 This includes the TODO keyword, the tags, time strings for deadline,
15183 scheduled, and clocking, and any additional properties defined in the
15184 entry. The return value is an alist, keys may occur multiple times
15185 if the property key was used several times.
15186 POM may also be nil, in which case the current entry is used.
15187 If WHICH is nil or `all', get all properties. If WHICH is
15188 `special' or `standard', only get that subclass. If WHICH
15189 is a string only get exactly this property. SPECIFIC can be a string, the
15190 specific property we are interested in. Specifying it can speed
15191 things up because then unnecessary parsing is avoided."
15192 (setq which (or which 'all))
15193 (org-with-point-at pom
15194 (let ((clockstr (substring org-clock-string 0 -1))
15195 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15196 (case-fold-search nil)
15197 beg end range props sum-props key key1 value string clocksum clocksumt)
15198 (save-excursion
15199 (when (condition-case nil
15200 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15201 (error nil))
15202 (setq beg (point))
15203 (setq sum-props (get-text-property (point) 'org-summaries))
15204 (setq clocksum (get-text-property (point) :org-clock-minutes)
15205 clocksumt (get-text-property (point) :org-clock-minutes-today))
15206 (outline-next-heading)
15207 (setq end (point))
15208 (when (memq which '(all special))
15209 ;; Get the special properties, like TODO and tags
15210 (goto-char beg)
15211 (when (and (or (not specific) (string= specific "TODO"))
15212 (looking-at org-todo-line-regexp) (match-end 2))
15213 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15214 (when (and (or (not specific) (string= specific "PRIORITY"))
15215 (looking-at org-priority-regexp))
15216 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15217 (when (or (not specific) (string= specific "FILE"))
15218 (push (cons "FILE" buffer-file-name) props))
15219 (when (and (or (not specific) (string= specific "TAGS"))
15220 (setq value (org-get-tags-string))
15221 (string-match "\\S-" value))
15222 (push (cons "TAGS" value) props))
15223 (when (and (or (not specific) (string= specific "ALLTAGS"))
15224 (setq value (org-get-tags-at)))
15225 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15226 ":"))
15227 props))
15228 (when (or (not specific) (string= specific "BLOCKED"))
15229 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15230 (when (or (not specific)
15231 (member specific
15232 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15233 "TIMESTAMP" "TIMESTAMP_IA")))
15234 (catch 'match
15235 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15236 (setq key (if (match-end 1)
15237 (substring (org-match-string-no-properties 1)
15238 0 -1))
15239 string (if (equal key clockstr)
15240 (org-trim
15241 (buffer-substring-no-properties
15242 (match-beginning 3) (goto-char
15243 (point-at-eol))))
15244 (substring (org-match-string-no-properties 3)
15245 1 -1)))
15246 ;; Get the correct property name from the key. This is
15247 ;; necessary if the user has configured time keywords.
15248 (setq key1 (concat key ":"))
15249 (cond
15250 ((not key)
15251 (setq key
15252 (if (= (char-after (match-beginning 3)) ?\[)
15253 "TIMESTAMP_IA" "TIMESTAMP")))
15254 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15255 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15256 ((equal key1 org-closed-string) (setq key "CLOSED"))
15257 ((equal key1 org-clock-string) (setq key "CLOCK")))
15258 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15259 (progn
15260 (push (cons key string) props)
15261 ;; no need to search further if match is found
15262 (throw 'match t))
15263 (when (or (equal key "CLOCK") (not (assoc key props)))
15264 (push (cons key string) props)))))))
15266 (when (memq which '(all standard))
15267 ;; Get the standard properties, like :PROP: ...
15268 (setq range (org-get-property-block beg end))
15269 (when range
15270 (goto-char (car range))
15271 (while (re-search-forward org-property-re
15272 (cdr range) t)
15273 (setq key (org-match-string-no-properties 2)
15274 value (org-trim (or (org-match-string-no-properties 3) "")))
15275 (unless (member key excluded)
15276 (push (cons key (or value "")) props)))))
15277 (if clocksum
15278 (push (cons "CLOCKSUM"
15279 (org-columns-number-to-string (/ (float clocksum) 60.)
15280 'add_times))
15281 props))
15282 (if clocksumt
15283 (push (cons "CLOCKSUM_T"
15284 (org-columns-number-to-string (/ (float clocksumt) 60.)
15285 'add_times))
15286 props))
15287 (unless (assoc "CATEGORY" props)
15288 (push (cons "CATEGORY" (org-get-category)) props))
15289 (append sum-props (nreverse props)))))))
15291 (defun org-entry-get (pom property &optional inherit literal-nil)
15292 "Get value of PROPERTY for entry or content at point-or-marker POM.
15293 If INHERIT is non-nil and the entry does not have the property,
15294 then also check higher levels of the hierarchy.
15295 If INHERIT is the symbol `selective', use inheritance only if the setting
15296 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15297 If the property is present but empty, the return value is the empty string.
15298 If the property is not present at all, nil is returned.
15300 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15301 do not interpret it as the list atom nil. This is used for inheritance
15302 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15303 (org-with-point-at pom
15304 (if (and inherit (if (eq inherit 'selective)
15305 (org-property-inherit-p property)
15307 (org-entry-get-with-inheritance property literal-nil)
15308 (if (member property org-special-properties)
15309 ;; We need a special property. Use `org-entry-properties' to
15310 ;; retrieve it, but specify the wanted property
15311 (cdr (assoc property (org-entry-properties nil 'special property)))
15312 (let ((range (org-get-property-block)))
15313 (when (and range (not (eq (car range) (cdr range))))
15314 (let* ((props (list (or (assoc property org-file-properties)
15315 (assoc property org-global-properties)
15316 (assoc property org-global-properties-fixed))))
15317 (ap (lambda (key)
15318 (when (re-search-forward
15319 (org-re-property key) (cdr range) t)
15320 (setq props
15321 (org-update-property-plist
15323 (if (match-end 3)
15324 (org-match-string-no-properties 3) "")
15325 props)))))
15326 val)
15327 (goto-char (car range))
15328 (funcall ap property)
15329 (goto-char (car range))
15330 (while (funcall ap (concat property "+")))
15331 (setq val (cdr (assoc property props)))
15332 (when val (if literal-nil val (org-not-nil val))))))))))
15334 (defun org-property-or-variable-value (var &optional inherit)
15335 "Check if there is a property fixing the value of VAR.
15336 If yes, return this value. If not, return the current value of the variable."
15337 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15338 (if (and prop (stringp prop) (string-match "\\S-" prop))
15339 (read prop)
15340 (symbol-value var))))
15342 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15343 "Delete the property PROPERTY from entry at point-or-marker POM.
15344 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15345 an empty drawer to delete."
15346 (org-with-point-at pom
15347 (if (member property org-special-properties)
15348 nil ; cannot delete these properties.
15349 (let ((range (org-get-property-block)))
15350 (if (and range
15351 (goto-char (car range))
15352 (re-search-forward
15353 (org-re-property property)
15354 (cdr range) t))
15355 (progn
15356 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15357 (and delete-empty-drawer
15358 (org-remove-empty-drawer-at
15359 delete-empty-drawer (car range)))
15361 nil)))))
15363 ;; Multi-values properties are properties that contain multiple values
15364 ;; These values are assumed to be single words, separated by whitespace.
15365 (defun org-entry-add-to-multivalued-property (pom property value)
15366 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15367 (let* ((old (org-entry-get pom property))
15368 (values (and old (org-split-string old "[ \t]"))))
15369 (setq value (org-entry-protect-space value))
15370 (unless (member value values)
15371 (setq values (append values (list value)))
15372 (org-entry-put pom property
15373 (mapconcat 'identity values " ")))))
15375 (defun org-entry-remove-from-multivalued-property (pom property value)
15376 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15377 (let* ((old (org-entry-get pom property))
15378 (values (and old (org-split-string old "[ \t]"))))
15379 (setq value (org-entry-protect-space value))
15380 (when (member value values)
15381 (setq values (delete value values))
15382 (org-entry-put pom property
15383 (mapconcat 'identity values " ")))))
15385 (defun org-entry-member-in-multivalued-property (pom property value)
15386 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15387 (let* ((old (org-entry-get pom property))
15388 (values (and old (org-split-string old "[ \t]"))))
15389 (setq value (org-entry-protect-space value))
15390 (member value values)))
15392 (defun org-entry-get-multivalued-property (pom property)
15393 "Return a list of values in a multivalued property."
15394 (let* ((value (org-entry-get pom property))
15395 (values (and value (org-split-string value "[ \t]"))))
15396 (mapcar 'org-entry-restore-space values)))
15398 (defun org-entry-put-multivalued-property (pom property &rest values)
15399 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15400 VALUES should be a list of strings. Spaces will be protected."
15401 (org-entry-put pom property
15402 (mapconcat 'org-entry-protect-space values " "))
15403 (let* ((value (org-entry-get pom property))
15404 (values (and value (org-split-string value "[ \t]"))))
15405 (mapcar 'org-entry-restore-space values)))
15407 (defun org-entry-protect-space (s)
15408 "Protect spaces and newline in string S."
15409 (while (string-match " " s)
15410 (setq s (replace-match "%20" t t s)))
15411 (while (string-match "\n" s)
15412 (setq s (replace-match "%0A" t t s)))
15415 (defun org-entry-restore-space (s)
15416 "Restore spaces and newline in string S."
15417 (while (string-match "%20" s)
15418 (setq s (replace-match " " t t s)))
15419 (while (string-match "%0A" s)
15420 (setq s (replace-match "\n" t t s)))
15423 (defvar org-entry-property-inherited-from (make-marker)
15424 "Marker pointing to the entry from where a property was inherited.
15425 Each call to `org-entry-get-with-inheritance' will set this marker to the
15426 location of the entry where the inheritance search matched. If there was
15427 no match, the marker will point nowhere.
15428 Note that also `org-entry-get' calls this function, if the INHERIT flag
15429 is set.")
15431 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15432 "Get PROPERTY of entry or content at point, search higher levels if needed.
15433 The search will stop at the first ancestor which has the property defined.
15434 If the value found is \"nil\", return nil to show that the property
15435 should be considered as undefined (this is the meaning of nil here).
15436 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15437 (move-marker org-entry-property-inherited-from nil)
15438 (let (tmp)
15439 (save-excursion
15440 (save-restriction
15441 (widen)
15442 (catch 'ex
15443 (while t
15444 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15445 (or (ignore-errors (org-back-to-heading t))
15446 (goto-char (point-min)))
15447 (move-marker org-entry-property-inherited-from (point))
15448 (throw 'ex tmp))
15449 (or (ignore-errors (org-up-heading-safe))
15450 (throw 'ex nil))))))
15451 (setq tmp (or tmp
15452 (cdr (assoc property org-file-properties))
15453 (cdr (assoc property org-global-properties))
15454 (cdr (assoc property org-global-properties-fixed))))
15455 (if literal-nil tmp (org-not-nil tmp))))
15457 (defvar org-property-changed-functions nil
15458 "Hook called when the value of a property has changed.
15459 Each hook function should accept two arguments, the name of the property
15460 and the new value.")
15462 (defun org-entry-put (pom property value)
15463 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15464 (org-with-point-at pom
15465 (org-back-to-heading t)
15466 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15467 range)
15468 (cond
15469 ((equal property "TODO")
15470 (when (and (stringp value) (string-match "\\S-" value)
15471 (not (member value org-todo-keywords-1)))
15472 (user-error "\"%s\" is not a valid TODO state" value))
15473 (if (or (not value)
15474 (not (string-match "\\S-" value)))
15475 (setq value 'none))
15476 (org-todo value)
15477 (org-set-tags nil 'align))
15478 ((equal property "PRIORITY")
15479 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15480 (string-to-char value) ?\ ))
15481 (org-set-tags nil 'align))
15482 ((equal property "CLOCKSUM")
15483 (if (not (re-search-forward
15484 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15485 (error "Cannot find a clock log")
15486 (goto-char (- (match-end 1) 2))
15487 (cond
15488 ((eq value 'earlier) (org-timestamp-down))
15489 ((eq value 'later) (org-timestamp-up)))
15490 (org-clock-sum-current-item)))
15491 ((equal property "SCHEDULED")
15492 (if (re-search-forward org-scheduled-time-regexp end t)
15493 (cond
15494 ((eq value 'earlier) (org-timestamp-change -1 'day))
15495 ((eq value 'later) (org-timestamp-change 1 'day))
15496 (t (call-interactively 'org-schedule)))
15497 (call-interactively 'org-schedule)))
15498 ((equal property "DEADLINE")
15499 (if (re-search-forward org-deadline-time-regexp end t)
15500 (cond
15501 ((eq value 'earlier) (org-timestamp-change -1 'day))
15502 ((eq value 'later) (org-timestamp-change 1 'day))
15503 (t (call-interactively 'org-deadline)))
15504 (call-interactively 'org-deadline)))
15505 ((member property org-special-properties)
15506 (error "The %s property can not yet be set with `org-entry-put'"
15507 property))
15508 (t ; a non-special property
15509 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15510 (setq range (org-get-property-block beg end 'force))
15511 (goto-char (car range))
15512 (if (re-search-forward
15513 (org-re-property property) (cdr range) t)
15514 (progn
15515 (delete-region (match-beginning 0) (match-end 0))
15516 (goto-char (match-beginning 0)))
15517 (goto-char (cdr range))
15518 (insert "\n")
15519 (backward-char 1)
15520 (org-indent-line))
15521 (insert ":" property ":")
15522 (and value (insert " " value))
15523 (org-indent-line)))))
15524 (run-hook-with-args 'org-property-changed-functions property value)))
15526 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15527 "Get all property keys in the current buffer.
15528 With INCLUDE-SPECIALS, also list the special properties that reflect things
15529 like tags and TODO state.
15530 With INCLUDE-DEFAULTS, also include properties that has special meaning
15531 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15532 and others.
15533 With INCLUDE-COLUMNS, also include property names given in COLUMN
15534 formats in the current buffer."
15535 (let (rtn range cfmt s p)
15536 (save-excursion
15537 (save-restriction
15538 (widen)
15539 (goto-char (point-min))
15540 (while (re-search-forward org-property-start-re nil t)
15541 (setq range (org-get-property-block))
15542 (goto-char (car range))
15543 (while (re-search-forward org-property-re
15544 (cdr range) t)
15545 (add-to-list 'rtn (org-match-string-no-properties 2)))
15546 (outline-next-heading))))
15548 (when include-specials
15549 (setq rtn (append org-special-properties rtn)))
15551 (when include-defaults
15552 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15553 (add-to-list 'rtn org-effort-property))
15555 (when include-columns
15556 (save-excursion
15557 (save-restriction
15558 (widen)
15559 (goto-char (point-min))
15560 (while (re-search-forward
15561 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15562 nil t)
15563 (setq cfmt (match-string 2) s 0)
15564 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15565 cfmt s)
15566 (setq s (match-end 0)
15567 p (match-string 1 cfmt))
15568 (unless (or (equal p "ITEM")
15569 (member p org-special-properties))
15570 (add-to-list 'rtn (match-string 1 cfmt))))))))
15572 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15574 (defun org-property-values (key)
15575 "Return a list of all values of property KEY in the current buffer."
15576 (save-excursion
15577 (save-restriction
15578 (widen)
15579 (goto-char (point-min))
15580 (let ((re (org-re-property key))
15581 values)
15582 (while (re-search-forward re nil t)
15583 (add-to-list 'values (org-trim (match-string 3))))
15584 (delete "" values)))))
15586 (defun org-insert-property-drawer ()
15587 "Insert a property drawer into the current entry."
15588 (org-back-to-heading t)
15589 (looking-at org-outline-regexp)
15590 (let ((indent (if org-adapt-indentation
15591 (- (match-end 0) (match-beginning 0))
15593 (beg (point))
15594 (re (concat "^[ \t]*" org-keyword-time-regexp))
15595 end hiddenp)
15596 (outline-next-heading)
15597 (setq end (point))
15598 (goto-char beg)
15599 (while (re-search-forward re end t))
15600 (setq hiddenp (outline-invisible-p))
15601 (end-of-line 1)
15602 (and (equal (char-after) ?\n) (forward-char 1))
15603 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15604 (if (member (match-string 1) '("CLOCK:" ":END:"))
15605 ;; just skip this line
15606 (beginning-of-line 2)
15607 ;; Drawer start, find the end
15608 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15609 (beginning-of-line 1)))
15610 (org-skip-over-state-notes)
15611 (skip-chars-backward " \t\n\r")
15612 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15613 (forward-char 1))
15614 (goto-char (point-at-eol))
15615 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15616 (beginning-of-line 0)
15617 (org-indent-to-column indent)
15618 (beginning-of-line 2)
15619 (org-indent-to-column indent)
15620 (beginning-of-line 0)
15621 (if hiddenp
15622 (save-excursion
15623 (org-back-to-heading t)
15624 (hide-entry))
15625 (org-flag-drawer t))))
15627 (defun org-insert-drawer (&optional arg drawer)
15628 "Insert a drawer at point.
15630 Optional argument DRAWER, when non-nil, is a string representing
15631 drawer's name. Otherwise, the user is prompted for a name.
15633 If a region is active, insert the drawer around that region
15634 instead.
15636 Point is left between drawer's boundaries."
15637 (interactive "P")
15638 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15639 "LOGBOOK"))
15640 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15641 ;; internally by Org. They are meant to be inserted
15642 ;; automatically.
15643 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15644 ;; Remove system drawers from list. Note: For some reason,
15645 ;; `org-completing-read' ignores the predicate while
15646 ;; `completing-read' handles it fine.
15647 (drawer (if arg "PROPERTIES"
15648 (or drawer
15649 (completing-read
15650 "Drawer: " org-drawers
15651 (lambda (d) (not (member d system-drawers))))))))
15652 (cond
15653 ;; With C-u, fall back on `org-insert-property-drawer'
15654 (arg (org-insert-property-drawer))
15655 ;; With an active region, insert a drawer at point.
15656 ((not (org-region-active-p))
15657 (progn
15658 (unless (bolp) (insert "\n"))
15659 (insert (format ":%s:\n\n:END:\n" drawer))
15660 (forward-line -2)))
15661 ;; Otherwise, insert the drawer at point
15663 (let ((rbeg (region-beginning))
15664 (rend (copy-marker (region-end))))
15665 (unwind-protect
15666 (progn
15667 (goto-char rbeg)
15668 (beginning-of-line)
15669 (when (save-excursion
15670 (re-search-forward org-outline-regexp-bol rend t))
15671 (user-error "Drawers cannot contain headlines"))
15672 ;; Position point at the beginning of the first
15673 ;; non-blank line in region. Insert drawer's opening
15674 ;; there, then indent it.
15675 (org-skip-whitespace)
15676 (beginning-of-line)
15677 (insert ":" drawer ":\n")
15678 (forward-line -1)
15679 (indent-for-tab-command)
15680 ;; Move point to the beginning of the first blank line
15681 ;; after the last non-blank line in region. Insert
15682 ;; drawer's closing, then indent it.
15683 (goto-char rend)
15684 (skip-chars-backward " \r\t\n")
15685 (insert "\n:END:")
15686 (deactivate-mark t)
15687 (indent-for-tab-command)
15688 (unless (eolp) (insert "\n")))
15689 ;; Clear marker, whatever the outcome of insertion is.
15690 (set-marker rend nil)))))))
15692 (defvar org-property-set-functions-alist nil
15693 "Property set function alist.
15694 Each entry should have the following format:
15696 (PROPERTY . READ-FUNCTION)
15698 The read function will be called with the same argument as
15699 `org-completing-read'.")
15701 (defun org-set-property-function (property)
15702 "Get the function that should be used to set PROPERTY.
15703 This is computed according to `org-property-set-functions-alist'."
15704 (or (cdr (assoc property org-property-set-functions-alist))
15705 'org-completing-read))
15707 (defun org-read-property-value (property)
15708 "Read PROPERTY value from user."
15709 (let* ((completion-ignore-case t)
15710 (allowed (org-property-get-allowed-values nil property 'table))
15711 (cur (org-entry-get nil property))
15712 (prompt (concat property " value"
15713 (if (and cur (string-match "\\S-" cur))
15714 (concat " [" cur "]") "") ": "))
15715 (set-function (org-set-property-function property))
15716 (val (if allowed
15717 (funcall set-function prompt allowed nil
15718 (not (get-text-property 0 'org-unrestricted
15719 (caar allowed))))
15720 (let (org-completion-use-ido org-completion-use-iswitchb)
15721 (funcall set-function prompt
15722 (mapcar 'list (org-property-values property))
15723 nil nil "" nil cur)))))
15724 (if (equal val "")
15726 val)))
15728 (defvar org-last-set-property nil)
15729 (defvar org-last-set-property-value nil)
15730 (defun org-read-property-name ()
15731 "Read a property name."
15732 (let* ((completion-ignore-case t)
15733 (keys (org-buffer-property-keys nil t t))
15734 (default-prop (or (save-excursion
15735 (save-match-data
15736 (beginning-of-line)
15737 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15738 (null (string= (match-string 1) "END"))
15739 (match-string 1))))
15740 org-last-set-property))
15741 (property (org-icompleting-read
15742 (concat "Property"
15743 (if default-prop (concat " [" default-prop "]") "")
15744 ": ")
15745 (mapcar 'list keys)
15746 nil nil nil nil
15747 default-prop)))
15748 (if (member property keys)
15749 property
15750 (or (cdr (assoc (downcase property)
15751 (mapcar (lambda (x) (cons (downcase x) x))
15752 keys)))
15753 property))))
15755 (defun org-set-property-and-value (use-last)
15756 "Allow to set [PROPERTY]: [value] direction from prompt.
15757 When use-default, don't even ask, just use the last
15758 \"[PROPERTY]: [value]\" string from the history."
15759 (interactive "P")
15760 (let* ((completion-ignore-case t)
15761 (pv (or (and use-last org-last-set-property-value)
15762 (org-completing-read
15763 "Enter a \"[Property]: [value]\" pair: "
15764 nil nil nil nil nil
15765 org-last-set-property-value)))
15766 prop val)
15767 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15768 (setq prop (match-string 1 pv)
15769 val (match-string 2 pv))
15770 (org-set-property prop val))))
15772 (defun org-set-property (property value)
15773 "In the current entry, set PROPERTY to VALUE.
15774 When called interactively, this will prompt for a property name, offering
15775 completion on existing and default properties. And then it will prompt
15776 for a value, offering completion either on allowed values (via an inherited
15777 xxx_ALL property) or on existing values in other instances of this property
15778 in the current file."
15779 (interactive (list nil nil))
15780 (let* ((property (or property (org-read-property-name)))
15781 (value (or value (org-read-property-value property)))
15782 (fn (cdr (assoc property org-properties-postprocess-alist))))
15783 (setq org-last-set-property property)
15784 (setq org-last-set-property-value (concat property ": " value))
15785 ;; Possibly postprocess the inserted value:
15786 (when fn (setq value (funcall fn value)))
15787 (unless (equal (org-entry-get nil property) value)
15788 (org-entry-put nil property value))))
15790 (defun org-delete-property (property &optional delete-empty-drawer)
15791 "In the current entry, delete PROPERTY.
15792 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15793 an empty drawer to delete."
15794 (interactive
15795 (let* ((completion-ignore-case t)
15796 (prop (org-icompleting-read "Property: "
15797 (org-entry-properties nil 'standard))))
15798 (list prop)))
15799 (message "Property %s %s" property
15800 (if (org-entry-delete nil property delete-empty-drawer)
15801 "deleted"
15802 "was not present in the entry")))
15804 (defun org-delete-property-globally (property)
15805 "Remove PROPERTY globally, from all entries."
15806 (interactive
15807 (let* ((completion-ignore-case t)
15808 (prop (org-icompleting-read
15809 "Globally remove property: "
15810 (mapcar 'list (org-buffer-property-keys)))))
15811 (list prop)))
15812 (save-excursion
15813 (save-restriction
15814 (widen)
15815 (goto-char (point-min))
15816 (let ((cnt 0))
15817 (while (re-search-forward
15818 (org-re-property property)
15819 nil t)
15820 (setq cnt (1+ cnt))
15821 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15822 (message "Property \"%s\" removed from %d entries" property cnt)))))
15824 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15826 (defun org-compute-property-at-point ()
15827 "Compute the property at point.
15828 This looks for an enclosing column format, extracts the operator and
15829 then applies it to the property in the column format's scope."
15830 (interactive)
15831 (unless (org-at-property-p)
15832 (user-error "Not at a property"))
15833 (let ((prop (org-match-string-no-properties 2)))
15834 (org-columns-get-format-and-top-level)
15835 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15836 (user-error "No operator defined for property %s" prop))
15837 (org-columns-compute prop)))
15839 (defvar org-property-allowed-value-functions nil
15840 "Hook for functions supplying allowed values for a specific property.
15841 The functions must take a single argument, the name of the property, and
15842 return a flat list of allowed values. If \":ETC\" is one of
15843 the values, this means that these values are intended as defaults for
15844 completion, but that other values should be allowed too.
15845 The functions must return nil if they are not responsible for this
15846 property.")
15848 (defun org-property-get-allowed-values (pom property &optional table)
15849 "Get allowed values for the property PROPERTY.
15850 When TABLE is non-nil, return an alist that can directly be used for
15851 completion."
15852 (let (vals)
15853 (cond
15854 ((equal property "TODO")
15855 (setq vals (org-with-point-at pom
15856 (append org-todo-keywords-1 '("")))))
15857 ((equal property "PRIORITY")
15858 (let ((n org-lowest-priority))
15859 (while (>= n org-highest-priority)
15860 (push (char-to-string n) vals)
15861 (setq n (1- n)))))
15862 ((member property org-special-properties))
15863 ((setq vals (run-hook-with-args-until-success
15864 'org-property-allowed-value-functions property)))
15866 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15867 (when (and vals (string-match "\\S-" vals))
15868 (setq vals (car (read-from-string (concat "(" vals ")"))))
15869 (setq vals (mapcar (lambda (x)
15870 (cond ((stringp x) x)
15871 ((numberp x) (number-to-string x))
15872 ((symbolp x) (symbol-name x))
15873 (t "???")))
15874 vals)))))
15875 (when (member ":ETC" vals)
15876 (setq vals (remove ":ETC" vals))
15877 (org-add-props (car vals) '(org-unrestricted t)))
15878 (if table (mapcar 'list vals) vals)))
15880 (defun org-property-previous-allowed-value (&optional previous)
15881 "Switch to the next allowed value for this property."
15882 (interactive)
15883 (org-property-next-allowed-value t))
15885 (defun org-property-next-allowed-value (&optional previous)
15886 "Switch to the next allowed value for this property."
15887 (interactive)
15888 (unless (org-at-property-p)
15889 (user-error "Not at a property"))
15890 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15891 (key (match-string 2))
15892 (value (match-string 3))
15893 (allowed (or (org-property-get-allowed-values (point) key)
15894 (and (member value '("[ ]" "[-]" "[X]"))
15895 '("[ ]" "[X]"))))
15896 (heading (save-match-data (nth 4 (org-heading-components))))
15897 nval)
15898 (unless allowed
15899 (user-error "Allowed values for this property have not been defined"))
15900 (if previous (setq allowed (reverse allowed)))
15901 (if (member value allowed)
15902 (setq nval (car (cdr (member value allowed)))))
15903 (setq nval (or nval (car allowed)))
15904 (if (equal nval value)
15905 (user-error "Only one allowed value for this property"))
15906 (org-at-property-p)
15907 (replace-match (concat " :" key ": " nval) t t)
15908 (org-indent-line)
15909 (beginning-of-line 1)
15910 (skip-chars-forward " \t")
15911 (when (equal prop org-effort-property)
15912 (save-excursion
15913 (org-back-to-heading t)
15914 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15915 (when (string= org-clock-current-task heading)
15916 (setq org-clock-effort nval)
15917 (org-clock-update-mode-line)))
15918 (run-hook-with-args 'org-property-changed-functions key nval)))
15920 (defun org-find-olp (path &optional this-buffer)
15921 "Return a marker pointing to the entry at outline path OLP.
15922 If anything goes wrong, throw an error.
15923 You can wrap this call to catch the error like this:
15925 (condition-case msg
15926 (org-mobile-locate-entry (match-string 4))
15927 (error (nth 1 msg)))
15929 The return value will then be either a string with the error message,
15930 or a marker if everything is OK.
15932 If THIS-BUFFER is set, the outline path does not contain a file,
15933 only headings."
15934 (let* ((file (if this-buffer buffer-file-name (pop path)))
15935 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15936 (level 1)
15937 (lmin 1)
15938 (lmax 1)
15939 limit re end found pos heading cnt flevel)
15940 (unless buffer (error "File not found :%s" file))
15941 (with-current-buffer buffer
15942 (save-excursion
15943 (save-restriction
15944 (widen)
15945 (setq limit (point-max))
15946 (goto-char (point-min))
15947 (while (setq heading (pop path))
15948 (setq re (format org-complex-heading-regexp-format
15949 (regexp-quote heading)))
15950 (setq cnt 0 pos (point))
15951 (while (re-search-forward re end t)
15952 (setq level (- (match-end 1) (match-beginning 1)))
15953 (if (and (>= level lmin) (<= level lmax))
15954 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15955 (when (= cnt 0) (error "Heading not found on level %d: %s"
15956 lmax heading))
15957 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15958 lmax heading))
15959 (goto-char found)
15960 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15961 (setq end (save-excursion (org-end-of-subtree t t))))
15962 (when (org-at-heading-p)
15963 (point-marker)))))))
15965 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15966 "Find node HEADING in BUFFER.
15967 Return a marker to the heading if it was found, or nil if not.
15968 If POS-ONLY is set, return just the position instead of a marker.
15970 The heading text must match exact, but it may have a TODO keyword,
15971 a priority cookie and tags in the standard locations."
15972 (with-current-buffer (or buffer (current-buffer))
15973 (save-excursion
15974 (save-restriction
15975 (widen)
15976 (goto-char (point-min))
15977 (let (case-fold-search)
15978 (if (re-search-forward
15979 (format org-complex-heading-regexp-format
15980 (regexp-quote heading)) nil t)
15981 (if pos-only
15982 (match-beginning 0)
15983 (move-marker (make-marker) (match-beginning 0)))))))))
15985 (defun org-find-exact-heading-in-directory (heading &optional dir)
15986 "Find Org node headline HEADING in all .org files in directory DIR.
15987 When the target headline is found, return a marker to this location."
15988 (let ((files (directory-files (or dir default-directory)
15989 nil "\\`[^.#].*\\.org\\'"))
15990 file visiting m buffer)
15991 (catch 'found
15992 (while (setq file (pop files))
15993 (message "trying %s" file)
15994 (setq visiting (org-find-base-buffer-visiting file))
15995 (setq buffer (or visiting (find-file-noselect file)))
15996 (setq m (org-find-exact-headline-in-buffer
15997 heading buffer))
15998 (when (and (not m) (not visiting)) (kill-buffer buffer))
15999 (and m (throw 'found m))))))
16001 (defun org-find-entry-with-id (ident)
16002 "Locate the entry that contains the ID property with exact value IDENT.
16003 IDENT can be a string, a symbol or a number, this function will search for
16004 the string representation of it.
16005 Return the position where this entry starts, or nil if there is no such entry."
16006 (interactive "sID: ")
16007 (let ((id (cond
16008 ((stringp ident) ident)
16009 ((symbol-name ident) (symbol-name ident))
16010 ((numberp ident) (number-to-string ident))
16011 (t (error "IDENT %s must be a string, symbol or number" ident))))
16012 (case-fold-search nil))
16013 (save-excursion
16014 (save-restriction
16015 (widen)
16016 (goto-char (point-min))
16017 (when (re-search-forward
16018 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16019 nil t)
16020 (org-back-to-heading t)
16021 (point))))))
16023 ;;;; Timestamps
16025 (defvar org-last-changed-timestamp nil)
16026 (defvar org-last-inserted-timestamp nil
16027 "The last time stamp inserted with `org-insert-time-stamp'.")
16028 (defvar org-time-was-given) ; dynamically scoped parameter
16029 (defvar org-end-time-was-given) ; dynamically scoped parameter
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 (defun org-read-date (&optional org-with-time to-time from-string prompt
16219 default-time default-input inactive)
16220 "Read a date, possibly a time, and make things smooth for the user.
16221 The prompt will suggest to enter an ISO date, but you can also enter anything
16222 which will at least partially be understood by `parse-time-string'.
16223 Unrecognized parts of the date will default to the current day, month, year,
16224 hour and minute. If this command is called to replace a timestamp at point,
16225 or to enter the second timestamp of a range, the default time is taken
16226 from the existing stamp. Furthermore, the command prefers the future,
16227 so if you are giving a date where the year is not given, and the day-month
16228 combination is already past in the current year, it will assume you
16229 mean next year. For details, see the manual. A few examples:
16231 3-2-5 --> 2003-02-05
16232 feb 15 --> currentyear-02-15
16233 2/15 --> currentyear-02-15
16234 sep 12 9 --> 2009-09-12
16235 12:45 --> today 12:45
16236 22 sept 0:34 --> currentyear-09-22 0:34
16237 12 --> currentyear-currentmonth-12
16238 Fri --> nearest Friday after today
16239 -Tue --> last Tuesday
16240 etc.
16242 Furthermore you can specify a relative date by giving, as the *first* thing
16243 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16244 change in days weeks, months, years.
16245 With a single plus or minus, the date is relative to today. With a double
16246 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16247 +4d --> four days from today
16248 +4 --> same as above
16249 +2w --> two weeks from today
16250 ++5 --> five days from default date
16252 The function understands only English month and weekday abbreviations.
16254 While prompting, a calendar is popped up - you can also select the
16255 date with the mouse (button 1). The calendar shows a period of three
16256 months. To scroll it to other months, use the keys `>' and `<'.
16257 If you don't like the calendar, turn it off with
16258 \(setq org-read-date-popup-calendar nil)
16260 With optional argument TO-TIME, the date will immediately be converted
16261 to an internal time.
16262 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16263 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16264 still enter a time, and this function will inform the calling routine
16265 about this change. The calling routine may then choose to change the
16266 format used to insert the time stamp into the buffer to include the time.
16267 With optional argument FROM-STRING, read from this string instead from
16268 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16269 the time/date that is used for everything that is not specified by the
16270 user."
16271 (require 'parse-time)
16272 (let* ((org-time-stamp-rounding-minutes
16273 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16274 (org-dcst org-display-custom-times)
16275 (ct (org-current-time))
16276 (org-def (or org-overriding-default-time default-time ct))
16277 (org-defdecode (decode-time org-def))
16278 (dummy (progn
16279 (when (< (nth 2 org-defdecode) org-extend-today-until)
16280 (setcar (nthcdr 2 org-defdecode) -1)
16281 (setcar (nthcdr 1 org-defdecode) 59)
16282 (setq org-def (apply 'encode-time org-defdecode)
16283 org-defdecode (decode-time org-def)))))
16284 (mouse-autoselect-window nil) ; Don't let the mouse jump
16285 (calendar-frame-setup nil)
16286 (calendar-setup nil)
16287 (calendar-move-hook nil)
16288 (calendar-view-diary-initially-flag nil)
16289 (calendar-view-holidays-initially-flag nil)
16290 (timestr (format-time-string
16291 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16292 (prompt (concat (if prompt (concat prompt " ") "")
16293 (format "Date+time [%s]: " timestr)))
16294 ans (org-ans0 "") org-ans1 org-ans2 final)
16296 (cond
16297 (from-string (setq ans from-string))
16298 (org-read-date-popup-calendar
16299 (save-excursion
16300 (save-window-excursion
16301 (calendar)
16302 (org-eval-in-calendar '(setq cursor-type nil) t)
16303 (unwind-protect
16304 (progn
16305 (calendar-forward-day (- (time-to-days org-def)
16306 (calendar-absolute-from-gregorian
16307 (calendar-current-date))))
16308 (org-eval-in-calendar nil t)
16309 (let* ((old-map (current-local-map))
16310 (map (copy-keymap calendar-mode-map))
16311 (minibuffer-local-map
16312 (copy-keymap org-read-date-minibuffer-local-map)))
16313 (org-defkey map (kbd "RET") 'org-calendar-select)
16314 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16315 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16316 (unwind-protect
16317 (progn
16318 (use-local-map map)
16319 (setq org-read-date-inactive inactive)
16320 (add-hook 'post-command-hook 'org-read-date-display)
16321 (setq org-ans0 (read-string prompt default-input
16322 'org-read-date-history nil))
16323 ;; org-ans0: from prompt
16324 ;; org-ans1: from mouse click
16325 ;; org-ans2: from calendar motion
16326 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16327 (remove-hook 'post-command-hook 'org-read-date-display)
16328 (use-local-map old-map)
16329 (when org-read-date-overlay
16330 (delete-overlay org-read-date-overlay)
16331 (setq org-read-date-overlay nil)))))
16332 (bury-buffer "*Calendar*")))))
16334 (t ; Naked prompt only
16335 (unwind-protect
16336 (setq ans (read-string prompt default-input
16337 'org-read-date-history timestr))
16338 (when org-read-date-overlay
16339 (delete-overlay org-read-date-overlay)
16340 (setq org-read-date-overlay nil)))))
16342 (setq final (org-read-date-analyze ans org-def org-defdecode))
16344 (when org-read-date-analyze-forced-year
16345 (message "Year was forced into %s"
16346 (if org-read-date-force-compatible-dates
16347 "compatible range (1970-2037)"
16348 "range representable on this machine"))
16349 (ding))
16351 ;; One round trip to get rid of 34th of August and stuff like that....
16352 (setq final (decode-time (apply 'encode-time final)))
16354 (setq org-read-date-final-answer ans)
16356 (if to-time
16357 (apply 'encode-time final)
16358 (if (and (boundp 'org-time-was-given) org-time-was-given)
16359 (format "%04d-%02d-%02d %02d:%02d"
16360 (nth 5 final) (nth 4 final) (nth 3 final)
16361 (nth 2 final) (nth 1 final))
16362 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16364 (defvar org-def)
16365 (defvar org-defdecode)
16366 (defvar org-with-time)
16367 (defun org-read-date-display ()
16368 "Display the current date prompt interpretation in the minibuffer."
16369 (when org-read-date-display-live
16370 (when org-read-date-overlay
16371 (delete-overlay org-read-date-overlay))
16372 (when (minibufferp (current-buffer))
16373 (save-excursion
16374 (end-of-line 1)
16375 (while (not (equal (buffer-substring
16376 (max (point-min) (- (point) 4)) (point))
16377 " "))
16378 (insert " ")))
16379 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16380 " " (or org-ans1 org-ans2)))
16381 (org-end-time-was-given nil)
16382 (f (org-read-date-analyze ans org-def org-defdecode))
16383 (fmts (if org-dcst
16384 org-time-stamp-custom-formats
16385 org-time-stamp-formats))
16386 (fmt (if (or org-with-time
16387 (and (boundp 'org-time-was-given) org-time-was-given))
16388 (cdr fmts)
16389 (car fmts)))
16390 (txt (format-time-string fmt (apply 'encode-time f)))
16391 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16392 (txt (concat "=> " txt)))
16393 (when (and org-end-time-was-given
16394 (string-match org-plain-time-of-day-regexp txt))
16395 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16396 org-end-time-was-given
16397 (substring txt (match-end 0)))))
16398 (when org-read-date-analyze-futurep
16399 (setq txt (concat txt " (=>F)")))
16400 (setq org-read-date-overlay
16401 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16402 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16404 (defun org-read-date-analyze (ans org-def org-defdecode)
16405 "Analyze the combined answer of the date prompt."
16406 ;; FIXME: cleanup and comment
16407 (let ((nowdecode (decode-time (current-time)))
16408 delta deltan deltaw deltadef year month day
16409 hour minute second wday pm h2 m2 tl wday1
16410 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16411 (setq org-read-date-analyze-futurep nil
16412 org-read-date-analyze-forced-year nil)
16413 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16414 (setq ans "+0"))
16416 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16417 (setq ans (replace-match "" t t ans)
16418 deltan (car delta)
16419 deltaw (nth 1 delta)
16420 deltadef (nth 2 delta)))
16422 ;; Check if there is an iso week date in there. If yes, store the
16423 ;; info and postpone interpreting it until the rest of the parsing
16424 ;; is done.
16425 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16426 (setq iso-year (if (match-end 1)
16427 (org-small-year-to-year
16428 (string-to-number (match-string 1 ans))))
16429 iso-weekday (if (match-end 3)
16430 (string-to-number (match-string 3 ans)))
16431 iso-week (string-to-number (match-string 2 ans)))
16432 (setq ans (replace-match "" t t ans)))
16434 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16435 (when (string-match
16436 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16437 (setq year (if (match-end 2)
16438 (string-to-number (match-string 2 ans))
16439 (progn (setq kill-year t)
16440 (string-to-number (format-time-string "%Y"))))
16441 month (string-to-number (match-string 3 ans))
16442 day (string-to-number (match-string 4 ans)))
16443 (if (< year 100) (setq year (+ 2000 year)))
16444 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16445 t nil ans)))
16447 ;; Help matching dotted european dates
16448 (when (string-match
16449 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16450 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16451 (setq kill-year t)
16452 (string-to-number (format-time-string "%Y")))
16453 day (string-to-number (match-string 1 ans))
16454 month (string-to-number (match-string 2 ans))
16455 ans (replace-match (format "%04d-%02d-%02d" year month day)
16456 t nil ans)))
16458 ;; Help matching american dates, like 5/30 or 5/30/7
16459 (when (string-match
16460 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16461 (setq year (if (match-end 4)
16462 (string-to-number (match-string 4 ans))
16463 (progn (setq kill-year t)
16464 (string-to-number (format-time-string "%Y"))))
16465 month (string-to-number (match-string 1 ans))
16466 day (string-to-number (match-string 2 ans)))
16467 (if (< year 100) (setq year (+ 2000 year)))
16468 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16469 t nil ans)))
16470 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16471 ;; If there is a time with am/pm, and *no* time without it, we convert
16472 ;; so that matching will be successful.
16473 (loop for i from 1 to 2 do ; twice, for end time as well
16474 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16475 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16476 (setq hour (string-to-number (match-string 1 ans))
16477 minute (if (match-end 3)
16478 (string-to-number (match-string 3 ans))
16480 pm (equal ?p
16481 (string-to-char (downcase (match-string 4 ans)))))
16482 (if (and (= hour 12) (not pm))
16483 (setq hour 0)
16484 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16485 (setq ans (replace-match (format "%02d:%02d" hour minute)
16486 t t ans))))
16488 ;; Check if a time range is given as a duration
16489 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16490 (setq hour (string-to-number (match-string 1 ans))
16491 h2 (+ hour (string-to-number (match-string 3 ans)))
16492 minute (string-to-number (match-string 2 ans))
16493 m2 (+ minute (if (match-end 5) (string-to-number
16494 (match-string 5 ans))0)))
16495 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16496 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16497 t t ans)))
16499 ;; Check if there is a time range
16500 (when (boundp 'org-end-time-was-given)
16501 (setq org-time-was-given nil)
16502 (when (and (string-match org-plain-time-of-day-regexp ans)
16503 (match-end 8))
16504 (setq org-end-time-was-given (match-string 8 ans))
16505 (setq ans (concat (substring ans 0 (match-beginning 7))
16506 (substring ans (match-end 7))))))
16508 (setq tl (parse-time-string ans)
16509 day (or (nth 3 tl) (nth 3 org-defdecode))
16510 month (or (nth 4 tl)
16511 (if (and org-read-date-prefer-future
16512 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16513 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16514 (nth 4 org-defdecode)))
16515 year (or (and (not kill-year) (nth 5 tl))
16516 (if (and org-read-date-prefer-future
16517 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16518 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16519 (nth 5 org-defdecode)))
16520 hour (or (nth 2 tl) (nth 2 org-defdecode))
16521 minute (or (nth 1 tl) (nth 1 org-defdecode))
16522 second (or (nth 0 tl) 0)
16523 wday (nth 6 tl))
16525 (when (and (eq org-read-date-prefer-future 'time)
16526 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16527 (equal day (nth 3 nowdecode))
16528 (equal month (nth 4 nowdecode))
16529 (equal year (nth 5 nowdecode))
16530 (nth 2 tl)
16531 (or (< (nth 2 tl) (nth 2 nowdecode))
16532 (and (= (nth 2 tl) (nth 2 nowdecode))
16533 (nth 1 tl)
16534 (< (nth 1 tl) (nth 1 nowdecode)))))
16535 (setq day (1+ day)
16536 futurep t))
16538 ;; Special date definitions below
16539 (cond
16540 (iso-week
16541 ;; There was an iso week
16542 (require 'cal-iso)
16543 (setq futurep nil)
16544 (setq year (or iso-year year)
16545 day (or iso-weekday wday 1)
16546 wday nil ; to make sure that the trigger below does not match
16547 iso-date (calendar-gregorian-from-absolute
16548 (calendar-absolute-from-iso
16549 (list iso-week day year))))
16550 ; FIXME: Should we also push ISO weeks into the future?
16551 ; (when (and org-read-date-prefer-future
16552 ; (not iso-year)
16553 ; (< (calendar-absolute-from-gregorian iso-date)
16554 ; (time-to-days (current-time))))
16555 ; (setq year (1+ year)
16556 ; iso-date (calendar-gregorian-from-absolute
16557 ; (calendar-absolute-from-iso
16558 ; (list iso-week day year)))))
16559 (setq month (car iso-date)
16560 year (nth 2 iso-date)
16561 day (nth 1 iso-date)))
16562 (deltan
16563 (setq futurep nil)
16564 (unless deltadef
16565 (let ((now (decode-time (current-time))))
16566 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16567 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16568 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16569 ((equal deltaw "m") (setq month (+ month deltan)))
16570 ((equal deltaw "y") (setq year (+ year deltan)))))
16571 ((and wday (not (nth 3 tl)))
16572 ;; Weekday was given, but no day, so pick that day in the week
16573 ;; on or after the derived date.
16574 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16575 (unless (equal wday wday1)
16576 (setq day (+ day (% (- wday wday1 -7) 7))))))
16577 (if (and (boundp 'org-time-was-given)
16578 (nth 2 tl))
16579 (setq org-time-was-given t))
16580 (if (< year 100) (setq year (+ 2000 year)))
16581 ;; Check of the date is representable
16582 (if org-read-date-force-compatible-dates
16583 (progn
16584 (if (< year 1970)
16585 (setq year 1970 org-read-date-analyze-forced-year t))
16586 (if (> year 2037)
16587 (setq year 2037 org-read-date-analyze-forced-year t)))
16588 (condition-case nil
16589 (ignore (encode-time second minute hour day month year))
16590 (error
16591 (setq year (nth 5 org-defdecode))
16592 (setq org-read-date-analyze-forced-year t))))
16593 (setq org-read-date-analyze-futurep futurep)
16594 (list second minute hour day month year)))
16596 (defvar parse-time-weekdays)
16597 (defun org-read-date-get-relative (s today default)
16598 "Check string S for special relative date string.
16599 TODAY and DEFAULT are internal times, for today and for a default.
16600 Return shift list (N what def-flag)
16601 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16602 N is the number of WHATs to shift.
16603 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16604 the DEFAULT date rather than TODAY."
16605 (require 'parse-time)
16606 (when (and
16607 (string-match
16608 (concat
16609 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16610 "\\([0-9]+\\)?"
16611 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16612 "\\([ \t]\\|$\\)") s)
16613 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16614 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16615 (string-to-char (substring (match-string 1 s) -1))
16616 ?+))
16617 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16618 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16619 (what (if (match-end 3) (match-string 3 s) "d"))
16620 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16621 (date (if rel default today))
16622 (wday (nth 6 (decode-time date)))
16623 delta)
16624 (if wday1
16625 (progn
16626 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16627 (if (= delta 0) (setq delta 7))
16628 (if (= dir ?-)
16629 (progn
16630 (setq delta (- delta 7))
16631 (if (= delta 0) (setq delta -7))))
16632 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16633 (list delta "d" rel))
16634 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16636 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16637 "Turn a user-specified date into the internal representation.
16638 The internal representation needed by the calendar is (month day year).
16639 This is a wrapper to handle the brain-dead convention in calendar that
16640 user function argument order change dependent on argument order."
16641 (if (boundp 'calendar-date-style)
16642 (cond
16643 ((eq calendar-date-style 'american)
16644 (list arg1 arg2 arg3))
16645 ((eq calendar-date-style 'european)
16646 (list arg2 arg1 arg3))
16647 ((eq calendar-date-style 'iso)
16648 (list arg2 arg3 arg1)))
16649 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16650 (if (org-bound-and-true-p european-calendar-style)
16651 (list arg2 arg1 arg3)
16652 (list arg1 arg2 arg3)))))
16654 (defun org-eval-in-calendar (form &optional keepdate)
16655 "Eval FORM in the calendar window and return to current window.
16656 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16657 otherwise stick to the current value of `org-ans2'."
16658 (let ((sf (selected-frame))
16659 (sw (selected-window)))
16660 (select-window (get-buffer-window "*Calendar*" t))
16661 (eval form)
16662 (when (and (not keepdate) (calendar-cursor-to-date))
16663 (let* ((date (calendar-cursor-to-date))
16664 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16665 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16666 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16667 (select-window sw)
16668 (org-select-frame-set-input-focus sf)))
16670 (defun org-calendar-select ()
16671 "Return to `org-read-date' with the date currently selected.
16672 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16673 (interactive)
16674 (when (calendar-cursor-to-date)
16675 (let* ((date (calendar-cursor-to-date))
16676 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16677 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16678 (if (active-minibuffer-window) (exit-minibuffer))))
16680 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16681 "Insert a date stamp for the date given by the internal TIME.
16682 WITH-HM means use the stamp format that includes the time of the day.
16683 INACTIVE means use square brackets instead of angular ones, so that the
16684 stamp will not contribute to the agenda.
16685 PRE and POST are optional strings to be inserted before and after the
16686 stamp.
16687 The command returns the inserted time stamp."
16688 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16689 stamp)
16690 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16691 (insert-before-markers (or pre ""))
16692 (when (listp extra)
16693 (setq extra (car extra))
16694 (if (and (stringp extra)
16695 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16696 (setq extra (format "-%02d:%02d"
16697 (string-to-number (match-string 1 extra))
16698 (string-to-number (match-string 2 extra))))
16699 (setq extra nil)))
16700 (when extra
16701 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16702 (insert-before-markers (setq stamp (format-time-string fmt time)))
16703 (insert-before-markers (or post ""))
16704 (setq org-last-inserted-timestamp stamp)))
16706 (defun org-toggle-time-stamp-overlays ()
16707 "Toggle the use of custom time stamp formats."
16708 (interactive)
16709 (setq org-display-custom-times (not org-display-custom-times))
16710 (unless org-display-custom-times
16711 (let ((p (point-min)) (bmp (buffer-modified-p)))
16712 (while (setq p (next-single-property-change p 'display))
16713 (if (and (get-text-property p 'display)
16714 (eq (get-text-property p 'face) 'org-date))
16715 (remove-text-properties
16716 p (setq p (next-single-property-change p 'display))
16717 '(display t))))
16718 (set-buffer-modified-p bmp)))
16719 (if (featurep 'xemacs)
16720 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16721 (org-restart-font-lock)
16722 (setq org-table-may-need-update t)
16723 (if org-display-custom-times
16724 (message "Time stamps are overlaid with custom format")
16725 (message "Time stamp overlays removed")))
16727 (defun org-display-custom-time (beg end)
16728 "Overlay modified time stamp format over timestamp between BEG and END."
16729 (let* ((ts (buffer-substring beg end))
16730 t1 w1 with-hm tf time str w2 (off 0))
16731 (save-match-data
16732 (setq t1 (org-parse-time-string ts t))
16733 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16734 (setq off (- (match-end 0) (match-beginning 0)))))
16735 (setq end (- end off))
16736 (setq w1 (- end beg)
16737 with-hm (and (nth 1 t1) (nth 2 t1))
16738 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16739 time (org-fix-decoded-time t1)
16740 str (org-add-props
16741 (format-time-string
16742 (substring tf 1 -1) (apply 'encode-time time))
16743 nil 'mouse-face 'highlight)
16744 w2 (length str))
16745 (if (not (= w2 w1))
16746 (add-text-properties (1+ beg) (+ 2 beg)
16747 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16748 (if (featurep 'xemacs)
16749 (progn
16750 (put-text-property beg end 'invisible t)
16751 (put-text-property beg end 'end-glyph (make-glyph str)))
16752 (put-text-property beg end 'display str))))
16754 (defun org-translate-time (string)
16755 "Translate all timestamps in STRING to custom format.
16756 But do this only if the variable `org-display-custom-times' is set."
16757 (when org-display-custom-times
16758 (save-match-data
16759 (let* ((start 0)
16760 (re org-ts-regexp-both)
16761 t1 with-hm inactive tf time str beg end)
16762 (while (setq start (string-match re string start))
16763 (setq beg (match-beginning 0)
16764 end (match-end 0)
16765 t1 (save-match-data
16766 (org-parse-time-string (substring string beg end) t))
16767 with-hm (and (nth 1 t1) (nth 2 t1))
16768 inactive (equal (substring string beg (1+ beg)) "[")
16769 tf (funcall (if with-hm 'cdr 'car)
16770 org-time-stamp-custom-formats)
16771 time (org-fix-decoded-time t1)
16772 str (format-time-string
16773 (concat
16774 (if inactive "[" "<") (substring tf 1 -1)
16775 (if inactive "]" ">"))
16776 (apply 'encode-time time))
16777 string (replace-match str t t string)
16778 start (+ start (length str)))))))
16779 string)
16781 (defun org-fix-decoded-time (time)
16782 "Set 0 instead of nil for the first 6 elements of time.
16783 Don't touch the rest."
16784 (let ((n 0))
16785 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16787 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16789 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16790 "Difference between TIMESTAMP-STRING and now in days.
16791 If SECONDS is non-nil, return the difference in seconds."
16792 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16793 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16794 (funcall fdiff (current-time)))))
16796 (defun org-deadline-close (timestamp-string &optional ndays)
16797 "Is the time in TIMESTAMP-STRING close to the current date?"
16798 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16799 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16800 (not (org-entry-is-done-p))))
16802 (defun org-get-wdays (ts &optional delay zero-delay)
16803 "Get the deadline lead time appropriate for timestring TS.
16804 When DELAY is non-nil, get the delay time for scheduled items
16805 instead of the deadline lead time. When ZERO-DELAY is non-nil
16806 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16807 don't try to find the delay cookie in the scheduled timestamp."
16808 (let ((tv (if delay org-scheduled-delay-days
16809 org-deadline-warning-days)))
16810 (cond
16811 ((or (and delay (< tv 0))
16812 (and delay zero-delay (<= tv 0))
16813 (and (not delay) (<= tv 0)))
16814 ;; Enforce this value no matter what
16815 (- tv))
16816 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16817 ;; lead time is specified.
16818 (floor (* (string-to-number (match-string 1 ts))
16819 (cdr (assoc (match-string 2 ts)
16820 '(("d" . 1) ("w" . 7)
16821 ("m" . 30.4) ("y" . 365.25)
16822 ("h" . 0.041667)))))))
16823 ;; go for the default.
16824 (t tv))))
16826 (defun org-calendar-select-mouse (ev)
16827 "Return to `org-read-date' with the date currently selected.
16828 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16829 (interactive "e")
16830 (mouse-set-point ev)
16831 (when (calendar-cursor-to-date)
16832 (let* ((date (calendar-cursor-to-date))
16833 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16834 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16835 (if (active-minibuffer-window) (exit-minibuffer))))
16837 (defun org-check-deadlines (ndays)
16838 "Check if there are any deadlines due or past due.
16839 A deadline is considered due if it happens within `org-deadline-warning-days'
16840 days from today's date. If the deadline appears in an entry marked DONE,
16841 it is not shown. The prefix arg NDAYS can be used to test that many
16842 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16843 (interactive "P")
16844 (let* ((org-warn-days
16845 (cond
16846 ((equal ndays '(4)) 100000)
16847 (ndays (prefix-numeric-value ndays))
16848 (t (abs org-deadline-warning-days))))
16849 (case-fold-search nil)
16850 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16851 (callback
16852 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16854 (message "%d deadlines past-due or due within %d days"
16855 (org-occur regexp nil callback)
16856 org-warn-days)))
16858 (defsubst org-re-timestamp (type)
16859 "Return a regexp for timestamp TYPE.
16860 Allowed values for TYPE are:
16862 all: all timestamps
16863 active: only active timestamps (<...>)
16864 inactive: only inactive timestamps ([...])
16865 scheduled: only scheduled timestamps
16866 deadline: only deadline timestamps
16867 closed: only closed time-stamps
16869 When TYPE is nil, fall back on returning a regexp that matches
16870 both scheduled and deadline timestamps."
16871 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16872 ((eq type 'active) org-ts-regexp)
16873 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16874 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16875 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16876 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16877 ((eq type 'scheduled-or-deadline)
16878 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16880 (defun org-check-before-date (date)
16881 "Check if there are deadlines or scheduled entries before DATE."
16882 (interactive (list (org-read-date)))
16883 (let ((case-fold-search nil)
16884 (regexp (org-re-timestamp org-ts-type))
16885 (callback
16886 (lambda () (time-less-p
16887 (org-time-string-to-time (match-string 1))
16888 (org-time-string-to-time date)))))
16889 (message "%d entries before %s"
16890 (org-occur regexp nil callback) date)))
16892 (defun org-check-after-date (date)
16893 "Check if there are deadlines or scheduled entries after DATE."
16894 (interactive (list (org-read-date)))
16895 (let ((case-fold-search nil)
16896 (regexp (org-re-timestamp org-ts-type))
16897 (callback
16898 (lambda () (not
16899 (time-less-p
16900 (org-time-string-to-time (match-string 1))
16901 (org-time-string-to-time date))))))
16902 (message "%d entries after %s"
16903 (org-occur regexp nil callback) date)))
16905 (defun org-check-dates-range (start-date end-date)
16906 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16907 (interactive (list (org-read-date nil nil nil "Range starts")
16908 (org-read-date nil nil nil "Range end")))
16909 (let ((case-fold-search nil)
16910 (regexp (org-re-timestamp org-ts-type))
16911 (callback
16912 (lambda ()
16913 (let ((match (match-string 1)))
16914 (and
16915 (not (time-less-p
16916 (org-time-string-to-time match)
16917 (org-time-string-to-time start-date)))
16918 (time-less-p
16919 (org-time-string-to-time match)
16920 (org-time-string-to-time end-date)))))))
16921 (message "%d entries between %s and %s"
16922 (org-occur regexp nil callback) start-date end-date)))
16924 (defun org-evaluate-time-range (&optional to-buffer)
16925 "Evaluate a time range by computing the difference between start and end.
16926 Normally the result is just printed in the echo area, but with prefix arg
16927 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16928 If the time range is actually in a table, the result is inserted into the
16929 next column.
16930 For time difference computation, a year is assumed to be exactly 365
16931 days in order to avoid rounding problems."
16932 (interactive "P")
16934 (org-clock-update-time-maybe)
16935 (save-excursion
16936 (unless (org-at-date-range-p t)
16937 (goto-char (point-at-bol))
16938 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16939 (if (not (org-at-date-range-p t))
16940 (user-error "Not at a time-stamp range, and none found in current line")))
16941 (let* ((ts1 (match-string 1))
16942 (ts2 (match-string 2))
16943 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16944 (match-end (match-end 0))
16945 (time1 (org-time-string-to-time ts1))
16946 (time2 (org-time-string-to-time ts2))
16947 (t1 (org-float-time time1))
16948 (t2 (org-float-time time2))
16949 (diff (abs (- t2 t1)))
16950 (negative (< (- t2 t1) 0))
16951 ;; (ys (floor (* 365 24 60 60)))
16952 (ds (* 24 60 60))
16953 (hs (* 60 60))
16954 (fy "%dy %dd %02d:%02d")
16955 (fy1 "%dy %dd")
16956 (fd "%dd %02d:%02d")
16957 (fd1 "%dd")
16958 (fh "%02d:%02d")
16959 y d h m align)
16960 (if havetime
16961 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16963 d (floor (/ diff ds)) diff (mod diff ds)
16964 h (floor (/ diff hs)) diff (mod diff hs)
16965 m (floor (/ diff 60)))
16966 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16968 d (floor (+ (/ diff ds) 0.5))
16969 h 0 m 0))
16970 (if (not to-buffer)
16971 (message "%s" (org-make-tdiff-string y d h m))
16972 (if (org-at-table-p)
16973 (progn
16974 (goto-char match-end)
16975 (setq align t)
16976 (and (looking-at " *|") (goto-char (match-end 0))))
16977 (goto-char match-end))
16978 (if (looking-at
16979 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16980 (replace-match ""))
16981 (if negative (insert " -"))
16982 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16983 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16984 (insert " " (format fh h m))))
16985 (if align (org-table-align))
16986 (message "Time difference inserted")))))
16988 (defun org-make-tdiff-string (y d h m)
16989 (let ((fmt "")
16990 (l nil))
16991 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16992 l (push y l)))
16993 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16994 l (push d l)))
16995 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16996 l (push h l)))
16997 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16998 l (push m l)))
16999 (apply 'format fmt (nreverse l))))
17001 (defun org-time-string-to-time (s &optional buffer pos)
17002 "Convert a timestamp string into internal time."
17003 (condition-case errdata
17004 (apply 'encode-time (org-parse-time-string s))
17005 (error (error "Bad timestamp `%s'%s\nError was: %s"
17006 s (if (not (and buffer pos))
17008 (format " at %d in buffer `%s'" pos buffer))
17009 (cdr errdata)))))
17011 (defun org-time-string-to-seconds (s)
17012 "Convert a timestamp string to a number of seconds."
17013 (org-float-time (org-time-string-to-time s)))
17015 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17016 "Convert a time stamp to an absolute day number.
17017 If there is a specifier for a cyclic time stamp, get the closest
17018 date to DAYNR.
17019 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17020 The variable `date' is bound by the calendar when this is called."
17021 (cond
17022 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17023 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17024 daynr
17025 (+ daynr 1000)))
17026 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17027 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17028 (time-to-days (current-time))) (match-string 0 s)
17029 prefer show-all))
17030 (t (time-to-days
17031 (condition-case errdata
17032 (apply 'encode-time (org-parse-time-string s))
17033 (error (error "Bad timestamp `%s'%s\nError was: %s"
17034 s (if (not (and buffer pos))
17036 (format " at %d in buffer `%s'" pos buffer))
17037 (cdr errdata))))))))
17039 (defun org-days-to-iso-week (days)
17040 "Return the iso week number."
17041 (require 'cal-iso)
17042 (car (calendar-iso-from-absolute days)))
17044 (defun org-small-year-to-year (year)
17045 "Convert 2-digit years into 4-digit years.
17046 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17047 The year 2000 cannot be abbreviated. Any year larger than 99
17048 is returned unchanged."
17049 (if (< year 38)
17050 (setq year (+ 2000 year))
17051 (if (< year 100)
17052 (setq year (+ 1900 year))))
17053 year)
17055 (defun org-time-from-absolute (d)
17056 "Return the time corresponding to date D.
17057 D may be an absolute day number, or a calendar-type list (month day year)."
17058 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17059 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17061 (defun org-calendar-holiday ()
17062 "List of holidays, for Diary display in Org-mode."
17063 (require 'holidays)
17064 (let ((hl (funcall
17065 (if (fboundp 'calendar-check-holidays)
17066 'calendar-check-holidays 'check-calendar-holidays) date)))
17067 (if hl (mapconcat 'identity hl "; "))))
17069 (defun org-diary-sexp-entry (sexp entry date)
17070 "Process a SEXP diary ENTRY for DATE."
17071 (require 'diary-lib)
17072 (let ((result (if calendar-debug-sexp
17073 (let ((stack-trace-on-error t))
17074 (eval (car (read-from-string sexp))))
17075 (condition-case nil
17076 (eval (car (read-from-string sexp)))
17077 (error
17078 (beep)
17079 (message "Bad sexp at line %d in %s: %s"
17080 (org-current-line)
17081 (buffer-file-name) sexp)
17082 (sleep-for 2))))))
17083 (cond ((stringp result) (split-string result "; "))
17084 ((and (consp result)
17085 (not (consp (cdr result)))
17086 (stringp (cdr result))) (cdr result))
17087 ((and (consp result)
17088 (stringp (car result))) result)
17089 (result entry))))
17091 (defun org-diary-to-ical-string (frombuf)
17092 "Get iCalendar entries from diary entries in buffer FROMBUF.
17093 This uses the icalendar.el library."
17094 (let* ((tmpdir (if (featurep 'xemacs)
17095 (temp-directory)
17096 temporary-file-directory))
17097 (tmpfile (make-temp-name
17098 (expand-file-name "orgics" tmpdir)))
17099 buf rtn b e)
17100 (with-current-buffer frombuf
17101 (icalendar-export-region (point-min) (point-max) tmpfile)
17102 (setq buf (find-buffer-visiting tmpfile))
17103 (set-buffer buf)
17104 (goto-char (point-min))
17105 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17106 (setq b (match-beginning 0)))
17107 (goto-char (point-max))
17108 (if (re-search-backward "^END:VEVENT" nil t)
17109 (setq e (match-end 0)))
17110 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17111 (kill-buffer buf)
17112 (delete-file tmpfile)
17113 rtn))
17115 (defun org-closest-date (start current change prefer show-all)
17116 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17117 When PREFER is `past', return a date that is either CURRENT or past.
17118 When PREFER is `future', return a date that is either CURRENT or future.
17119 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17120 ;; Make the proper lists from the dates
17121 (catch 'exit
17122 (let ((a1 '(("h" . hour)
17123 ("d" . day)
17124 ("w" . week)
17125 ("m" . month)
17126 ("y" . year)))
17127 (shour (nth 2 (org-parse-time-string start)))
17128 dn dw sday cday n1 n2 n0
17129 d m y y1 y2 date1 date2 nmonths nm ny m2)
17131 (setq start (org-date-to-gregorian start)
17132 current (org-date-to-gregorian
17133 (if show-all
17134 current
17135 (time-to-days (current-time))))
17136 sday (calendar-absolute-from-gregorian start)
17137 cday (calendar-absolute-from-gregorian current))
17139 (if (<= cday sday) (throw 'exit sday))
17141 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17142 (setq dn (string-to-number (match-string 1 change))
17143 dw (cdr (assoc (match-string 2 change) a1)))
17144 (user-error "Invalid change specifier: %s" change))
17145 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17146 (cond
17147 ((eq dw 'hour)
17148 (let ((missing-hours
17149 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17150 dn)))
17151 (setq n1 (if (zerop missing-hours) cday
17152 (- cday (1+ (floor (/ missing-hours 24)))))
17153 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17154 ((eq dw 'day)
17155 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17156 n2 (+ n1 dn)))
17157 ((eq dw 'year)
17158 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17159 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17160 (setq date1 (list m d y1)
17161 n1 (calendar-absolute-from-gregorian date1)
17162 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17163 n2 (calendar-absolute-from-gregorian date2)))
17164 ((eq dw 'month)
17165 ;; approx number of month between the two dates
17166 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17167 ;; How often does dn fit in there?
17168 (setq d (nth 1 start) m (car start) y (nth 2 start)
17169 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17170 m (+ m nm)
17171 ny (floor (/ m 12))
17172 y (+ y ny)
17173 m (- m (* ny 12)))
17174 (while (> m 12) (setq m (- m 12) y (1+ y)))
17175 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17176 (setq m2 (+ m dn) y2 y)
17177 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17178 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17179 (while (<= n2 cday)
17180 (setq n1 n2 m m2 y y2)
17181 (setq m2 (+ m dn) y2 y)
17182 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17183 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17184 ;; Make sure n1 is the earlier date
17185 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17186 (if show-all
17187 (cond
17188 ((eq prefer 'past) (if (= cday n2) n2 n1))
17189 ((eq prefer 'future) (if (= cday n1) n1 n2))
17190 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17191 (cond
17192 ((eq prefer 'past) (if (= cday n2) n2 n1))
17193 ((eq prefer 'future) (if (= cday n1) n1 n2))
17194 (t (if (= cday n1) n1 n2)))))))
17196 (defun org-date-to-gregorian (date)
17197 "Turn any specification of DATE into a Gregorian date for the calendar."
17198 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17199 ((and (listp date) (= (length date) 3)) date)
17200 ((stringp date)
17201 (setq date (org-parse-time-string date))
17202 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17203 ((listp date)
17204 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17206 (defun org-parse-time-string (s &optional nodefault)
17207 "Parse the standard Org-mode time string.
17208 This should be a lot faster than the normal `parse-time-string'.
17209 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17210 hour and minute fields will be nil if not given."
17211 (cond ((string-match org-ts-regexp0 s)
17212 (list 0
17213 (if (or (match-beginning 8) (not nodefault))
17214 (string-to-number (or (match-string 8 s) "0")))
17215 (if (or (match-beginning 7) (not nodefault))
17216 (string-to-number (or (match-string 7 s) "0")))
17217 (string-to-number (match-string 4 s))
17218 (string-to-number (match-string 3 s))
17219 (string-to-number (match-string 2 s))
17220 nil nil nil))
17221 ((string-match "^<[^>]+>$" s)
17222 (decode-time (seconds-to-time (org-matcher-time s))))
17223 (t (error "Not a standard Org-mode time string: %s" s))))
17225 (defun org-timestamp-up (&optional arg)
17226 "Increase the date item at the cursor by one.
17227 If the cursor is on the year, change the year. If it is on the month,
17228 the day or the time, change that.
17229 With prefix ARG, change by that many units."
17230 (interactive "p")
17231 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17233 (defun org-timestamp-down (&optional arg)
17234 "Decrease the date item at the cursor by one.
17235 If the cursor is on the year, change the year. If it is on the month,
17236 the day or the time, change that.
17237 With prefix ARG, change by that many units."
17238 (interactive "p")
17239 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17241 (defun org-timestamp-up-day (&optional arg)
17242 "Increase the date in the time stamp by one day.
17243 With prefix ARG, change that many days."
17244 (interactive "p")
17245 (if (and (not (org-at-timestamp-p t))
17246 (org-at-heading-p))
17247 (org-todo 'up)
17248 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17250 (defun org-timestamp-down-day (&optional arg)
17251 "Decrease the date in the time stamp by one day.
17252 With prefix ARG, change that many days."
17253 (interactive "p")
17254 (if (and (not (org-at-timestamp-p t))
17255 (org-at-heading-p))
17256 (org-todo 'down)
17257 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17259 (defun org-at-timestamp-p (&optional inactive-ok)
17260 "Determine if the cursor is in or at a timestamp."
17261 (interactive)
17262 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17263 (pos (point))
17264 (ans (or (looking-at tsr)
17265 (save-excursion
17266 (skip-chars-backward "^[<\n\r\t")
17267 (if (> (point) (point-min)) (backward-char 1))
17268 (and (looking-at tsr)
17269 (> (- (match-end 0) pos) -1))))))
17270 (and ans
17271 (boundp 'org-ts-what)
17272 (setq org-ts-what
17273 (cond
17274 ((= pos (match-beginning 0)) 'bracket)
17275 ;; Point is considered to be "on the bracket" whether
17276 ;; it's really on it or right after it.
17277 ((= pos (1- (match-end 0))) 'bracket)
17278 ((= pos (match-end 0)) 'after)
17279 ((org-pos-in-match-range pos 2) 'year)
17280 ((org-pos-in-match-range pos 3) 'month)
17281 ((org-pos-in-match-range pos 7) 'hour)
17282 ((org-pos-in-match-range pos 8) 'minute)
17283 ((or (org-pos-in-match-range pos 4)
17284 (org-pos-in-match-range pos 5)) 'day)
17285 ((and (> pos (or (match-end 8) (match-end 5)))
17286 (< pos (match-end 0)))
17287 (- pos (or (match-end 8) (match-end 5))))
17288 (t 'day))))
17289 ans))
17291 (defun org-toggle-timestamp-type ()
17292 "Toggle the type (<active> or [inactive]) of a time stamp."
17293 (interactive)
17294 (when (org-at-timestamp-p t)
17295 (let ((beg (match-beginning 0)) (end (match-end 0))
17296 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17297 (save-excursion
17298 (goto-char beg)
17299 (while (re-search-forward "[][<>]" end t)
17300 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17301 t t)))
17302 (message "Timestamp is now %sactive"
17303 (if (equal (char-after beg) ?<) "" "in")))))
17305 (defun org-at-clock-log-p nil
17306 "Is the cursor on the clock log line?"
17307 (save-excursion
17308 (move-beginning-of-line 1)
17309 (looking-at "^[ \t]*CLOCK:")))
17311 (defvar org-clock-history) ; defined in org-clock.el
17312 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17313 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17314 "Change the date in the time stamp at point.
17315 The date will be changed by N times WHAT. WHAT can be `day', `month',
17316 `year', `minute', `second'. If WHAT is not given, the cursor position
17317 in the timestamp determines what will be changed.
17318 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17319 (let ((origin (point)) origin-cat
17320 with-hm inactive
17321 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17322 org-ts-what
17323 extra rem
17324 ts time time0 fixnext clrgx)
17325 (if (not (org-at-timestamp-p t))
17326 (user-error "Not at a timestamp"))
17327 (if (and (not what) (eq org-ts-what 'bracket))
17328 (org-toggle-timestamp-type)
17329 ;; Point isn't on brackets. Remember the part of the time-stamp
17330 ;; the point was in. Indeed, size of time-stamps may change,
17331 ;; but point must be kept in the same category nonetheless.
17332 (setq origin-cat org-ts-what)
17333 (if (and (not what) (not (eq org-ts-what 'day))
17334 org-display-custom-times
17335 (get-text-property (point) 'display)
17336 (not (get-text-property (1- (point)) 'display)))
17337 (setq org-ts-what 'day))
17338 (setq org-ts-what (or what org-ts-what)
17339 inactive (= (char-after (match-beginning 0)) ?\[)
17340 ts (match-string 0))
17341 (replace-match "")
17342 (when (string-match
17343 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17345 (setq extra (match-string 1 ts))
17346 (if suppress-tmp-delay
17347 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17348 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17349 (setq with-hm t))
17350 (setq time0 (org-parse-time-string ts))
17351 (when (and updown
17352 (eq org-ts-what 'minute)
17353 (not current-prefix-arg))
17354 ;; This looks like s-up and s-down. Change by one rounding step.
17355 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17356 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17357 (setcar (cdr time0) (+ (nth 1 time0)
17358 (if (> n 0) (- rem) (- dm rem))))))
17359 (setq time
17360 (encode-time (or (car time0) 0)
17361 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17362 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17363 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17364 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17365 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17366 (nthcdr 6 time0)))
17367 (when (and (member org-ts-what '(hour minute))
17368 extra
17369 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17370 (setq extra (org-modify-ts-extra
17371 extra
17372 (if (eq org-ts-what 'hour) 2 5)
17373 n dm)))
17374 (when (integerp org-ts-what)
17375 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17376 (if (eq what 'calendar)
17377 (let ((cal-date (org-get-date-from-calendar)))
17378 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17379 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17380 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17381 (setcar time0 (or (car time0) 0))
17382 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17383 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17384 (setq time (apply 'encode-time time0))))
17385 ;; Insert the new time-stamp, and ensure point stays in the same
17386 ;; category as before (i.e. not after the last position in that
17387 ;; category).
17388 (let ((pos (point)))
17389 ;; Stay before inserted string. `save-excursion' is of no use.
17390 (setq org-last-changed-timestamp
17391 (org-insert-time-stamp time with-hm inactive nil nil extra))
17392 (goto-char pos))
17393 (save-match-data
17394 (looking-at org-ts-regexp3)
17395 (goto-char (cond
17396 ;; `day' category ends before `hour' if any, or at
17397 ;; the end of the day name.
17398 ((eq origin-cat 'day)
17399 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17400 ((eq origin-cat 'hour) (min (match-end 7) origin))
17401 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17402 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17403 ;; `year' and `month' have both fixed size: point
17404 ;; couldn't have moved into another part.
17405 (t origin))))
17406 ;; Update clock if on a CLOCK line.
17407 (org-clock-update-time-maybe)
17408 ;; Maybe adjust the closest clock in `org-clock-history'
17409 (when org-clock-adjust-closest
17410 (if (not (and (org-at-clock-log-p)
17411 (< 1 (length (delq nil (mapcar 'marker-position
17412 org-clock-history))))))
17413 (message "No clock to adjust")
17414 (cond ((save-excursion ; fix previous clock?
17415 (re-search-backward org-ts-regexp0 nil t)
17416 (org-looking-back (concat org-clock-string " \\[")))
17417 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17418 ((save-excursion ; fix next clock?
17419 (re-search-backward org-ts-regexp0 nil t)
17420 (looking-at (concat org-ts-regexp0 "\\] =>")))
17421 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17422 (save-window-excursion
17423 ;; Find closest clock to point, adjust the previous/next one in history
17424 (let* ((p (save-excursion (org-back-to-heading t)))
17425 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17426 (clfixnth
17427 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17428 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17429 (if (not clfixpos)
17430 (message "No clock to adjust")
17431 (save-excursion
17432 (org-goto-marker-or-bmk clfixpos)
17433 (org-show-subtree)
17434 (when (re-search-forward clrgx nil t)
17435 (goto-char (match-beginning 1))
17436 (let (org-clock-adjust-closest)
17437 (org-timestamp-change n org-ts-what updown))
17438 (message "Clock adjusted in %s for heading: %s"
17439 (file-name-nondirectory (buffer-file-name))
17440 (org-get-heading t t)))))))))
17441 ;; Try to recenter the calendar window, if any.
17442 (if (and org-calendar-follow-timestamp-change
17443 (get-buffer-window "*Calendar*" t)
17444 (memq org-ts-what '(day month year)))
17445 (org-recenter-calendar (time-to-days time))))))
17447 (defun org-modify-ts-extra (s pos n dm)
17448 "Change the different parts of the lead-time and repeat fields in timestamp."
17449 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17450 ng h m new rem)
17451 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17452 (cond
17453 ((or (org-pos-in-match-range pos 2)
17454 (org-pos-in-match-range pos 3))
17455 (setq m (string-to-number (match-string 3 s))
17456 h (string-to-number (match-string 2 s)))
17457 (if (org-pos-in-match-range pos 2)
17458 (setq h (+ h n))
17459 (setq n (* dm (org-no-warnings (signum n))))
17460 (when (not (= 0 (setq rem (% m dm))))
17461 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17462 (setq m (+ m n)))
17463 (if (< m 0) (setq m (+ m 60) h (1- h)))
17464 (if (> m 59) (setq m (- m 60) h (1+ h)))
17465 (setq h (min 24 (max 0 h)))
17466 (setq ng 1 new (format "-%02d:%02d" h m)))
17467 ((org-pos-in-match-range pos 6)
17468 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17469 ((org-pos-in-match-range pos 5)
17470 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17472 ((org-pos-in-match-range pos 9)
17473 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17474 ((org-pos-in-match-range pos 8)
17475 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17477 (when ng
17478 (setq s (concat
17479 (substring s 0 (match-beginning ng))
17481 (substring s (match-end ng))))))
17484 (defun org-recenter-calendar (date)
17485 "If the calendar is visible, recenter it to DATE."
17486 (let ((cwin (get-buffer-window "*Calendar*" t)))
17487 (when cwin
17488 (let ((calendar-move-hook nil))
17489 (with-selected-window cwin
17490 (calendar-goto-date (if (listp date) date
17491 (calendar-gregorian-from-absolute date))))))))
17493 (defun org-goto-calendar (&optional arg)
17494 "Go to the Emacs calendar at the current date.
17495 If there is a time stamp in the current line, go to that date.
17496 A prefix ARG can be used to force the current date."
17497 (interactive "P")
17498 (let ((tsr org-ts-regexp) diff
17499 (calendar-move-hook nil)
17500 (calendar-view-holidays-initially-flag nil)
17501 (calendar-view-diary-initially-flag nil))
17502 (if (or (org-at-timestamp-p)
17503 (save-excursion
17504 (beginning-of-line 1)
17505 (looking-at (concat ".*" tsr))))
17506 (let ((d1 (time-to-days (current-time)))
17507 (d2 (time-to-days
17508 (org-time-string-to-time (match-string 1)))))
17509 (setq diff (- d2 d1))))
17510 (calendar)
17511 (calendar-goto-today)
17512 (if (and diff (not arg)) (calendar-forward-day diff))))
17514 (defun org-get-date-from-calendar ()
17515 "Return a list (month day year) of date at point in calendar."
17516 (with-current-buffer "*Calendar*"
17517 (save-match-data
17518 (calendar-cursor-to-date))))
17520 (defun org-date-from-calendar ()
17521 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17522 If there is already a time stamp at the cursor position, update it."
17523 (interactive)
17524 (if (org-at-timestamp-p t)
17525 (org-timestamp-change 0 'calendar)
17526 (let ((cal-date (org-get-date-from-calendar)))
17527 (org-insert-time-stamp
17528 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17530 (defcustom org-effort-durations
17531 `(("h" . 60)
17532 ("d" . ,(* 60 8))
17533 ("w" . ,(* 60 8 5))
17534 ("m" . ,(* 60 8 5 4))
17535 ("y" . ,(* 60 8 5 40)))
17536 "Conversion factor to minutes for an effort modifier.
17538 Each entry has the form (MODIFIER . MINUTES).
17540 In an effort string, a number followed by MODIFIER is multiplied
17541 by the specified number of MINUTES to obtain an effort in
17542 minutes.
17544 For example, if the value of this variable is ((\"hours\" . 60)), then an
17545 effort string \"2hours\" is equivalent to 120 minutes."
17546 :group 'org-agenda
17547 :version "24.1"
17548 :type '(alist :key-type (string :tag "Modifier")
17549 :value-type (number :tag "Minutes")))
17551 (defun org-minutes-to-clocksum-string (m)
17552 "Format number of minutes as a clocksum string.
17553 The format is determined by `org-time-clocksum-format',
17554 `org-time-clocksum-use-fractional' and
17555 `org-time-clocksum-fractional-format' and
17556 `org-time-clocksum-use-effort-durations'."
17557 (let ((clocksum "")
17558 (m (round m)) ; Don't allow fractions of minutes
17559 h d w mo y fmt n)
17560 (setq h (if org-time-clocksum-use-effort-durations
17561 (cdr (assoc "h" org-effort-durations)) 60)
17562 d (if org-time-clocksum-use-effort-durations
17563 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17564 w (if org-time-clocksum-use-effort-durations
17565 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17566 mo (if org-time-clocksum-use-effort-durations
17567 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17568 y (if org-time-clocksum-use-effort-durations
17569 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17570 ;; fractional format
17571 (if org-time-clocksum-use-fractional
17572 (cond
17573 ;; single format string
17574 ((stringp org-time-clocksum-fractional-format)
17575 (format org-time-clocksum-fractional-format (/ m (float h))))
17576 ;; choice of fractional formats for different time units
17577 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17578 (> (/ (truncate m) (* y d h)) 0))
17579 (format fmt (/ m (* y d (float h)))))
17580 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17581 (> (/ (truncate m) (* mo d h)) 0))
17582 (format fmt (/ m (* mo d (float h)))))
17583 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17584 (> (/ (truncate m) (* w d h)) 0))
17585 (format fmt (/ m (* w d (float h)))))
17586 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17587 (> (/ (truncate m) (* d h)) 0))
17588 (format fmt (/ m (* d (float h)))))
17589 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17590 (> (/ (truncate m) h) 0))
17591 (format fmt (/ m (float h))))
17592 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17593 (format fmt m))
17594 ;; fall back to smallest time unit with a format
17595 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17596 (format fmt (/ m (float h))))
17597 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17598 (format fmt (/ m (* d (float h)))))
17599 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17600 (format fmt (/ m (* w d (float h)))))
17601 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17602 (format fmt (/ m (* mo d (float h)))))
17603 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17604 (format fmt (/ m (* y d (float h))))))
17605 ;; standard (non-fractional) format, with single format string
17606 (if (stringp org-time-clocksum-format)
17607 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17608 ;; separate formats components
17609 (and (setq fmt (plist-get org-time-clocksum-format :years))
17610 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17611 (plist-get org-time-clocksum-format :require-years))
17612 (setq clocksum (concat clocksum (format fmt n))
17613 m (- m (* n y d h))))
17614 (and (setq fmt (plist-get org-time-clocksum-format :months))
17615 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17616 (plist-get org-time-clocksum-format :require-months))
17617 (setq clocksum (concat clocksum (format fmt n))
17618 m (- m (* n mo d h))))
17619 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17620 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17621 (plist-get org-time-clocksum-format :require-weeks))
17622 (setq clocksum (concat clocksum (format fmt n))
17623 m (- m (* n w d h))))
17624 (and (setq fmt (plist-get org-time-clocksum-format :days))
17625 (or (> (setq n (/ (truncate m) (* d h))) 0)
17626 (plist-get org-time-clocksum-format :require-days))
17627 (setq clocksum (concat clocksum (format fmt n))
17628 m (- m (* n d h))))
17629 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17630 (or (> (setq n (/ (truncate m) h)) 0)
17631 (plist-get org-time-clocksum-format :require-hours))
17632 (setq clocksum (concat clocksum (format fmt n))
17633 m (- m (* n h))))
17634 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17635 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17636 (setq clocksum (concat clocksum (format fmt m))))
17637 ;; return formatted time duration
17638 clocksum))))
17640 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17641 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17642 "Org mode version 8.0")
17644 (defun org-hours-to-clocksum-string (n)
17645 (org-minutes-to-clocksum-string (* n 60)))
17647 (defun org-hh:mm-string-to-minutes (s)
17648 "Convert a string H:MM to a number of minutes.
17649 If the string is just a number, interpret it as minutes.
17650 In fact, the first hh:mm or number in the string will be taken,
17651 there can be extra stuff in the string.
17652 If no number is found, the return value is 0."
17653 (cond
17654 ((integerp s) s)
17655 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17656 (+ (* (string-to-number (match-string 1 s)) 60)
17657 (string-to-number (match-string 2 s))))
17658 ((string-match "\\([0-9]+\\)" s)
17659 (string-to-number (match-string 1 s)))
17660 (t 0)))
17662 (defcustom org-image-actual-width t
17663 "Should we use the actual width of images when inlining them?
17665 When set to `t', always use the image width.
17667 When set to a number, use imagemagick (when available) to set
17668 the image's width to this value.
17670 When set to a number in a list, try to get the width from any
17671 #+ATTR.* keyword if it matches a width specification like
17673 #+ATTR_HTML: :width 300px
17675 and fall back on that number if none is found.
17677 When set to nil, try to get the width from an #+ATTR.* keyword
17678 and fall back on the original width if none is found.
17680 This requires Emacs >= 24.1, build with imagemagick support."
17681 :group 'org-appearance
17682 :version "24.4"
17683 :package-version '(Org . "8.0")
17684 :type '(choice
17685 (const :tag "Use the image width" t)
17686 (integer :tag "Use a number of pixels")
17687 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17688 (const :tag "Use #+ATTR* or don't resize" nil)))
17690 (defcustom org-agenda-inhibit-startup nil
17691 "Inhibit startup when preparing agenda buffers.
17692 When this variable is `t' (the default), the initialization of
17693 the Org agenda buffers is inhibited: e.g. the visibility state
17694 is not set, the tables are not re-aligned, etc."
17695 :type 'boolean
17696 :version "24.3"
17697 :group 'org-agenda)
17699 (defcustom org-agenda-ignore-drawer-properties nil
17700 "Avoid updating text properties when building the agenda.
17701 Properties are used to prepare buffers for effort estimates, appointments,
17702 and subtree-local categories.
17703 If you don't use these in the agenda, you can add them to this list and
17704 agenda building will be a bit faster.
17705 The value is a list, with zero or more of the symbols `effort', `appt',
17706 or `category'."
17707 :type '(set :greedy t
17708 (const effort)
17709 (const appt)
17710 (const category))
17711 :version "24.3"
17712 :group 'org-agenda)
17714 (defun org-duration-string-to-minutes (s &optional output-to-string)
17715 "Convert a duration string S to minutes.
17717 A bare number is interpreted as minutes, modifiers can be set by
17718 customizing `org-effort-durations' (which see).
17720 Entries containing a colon are interpreted as H:MM by
17721 `org-hh:mm-string-to-minutes'."
17722 (let ((result 0)
17723 (re (concat "\\([0-9.]+\\) *\\("
17724 (regexp-opt (mapcar 'car org-effort-durations))
17725 "\\)")))
17726 (while (string-match re s)
17727 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17728 (string-to-number (match-string 1 s))))
17729 (setq s (replace-match "" nil t s)))
17730 (setq result (floor result))
17731 (incf result (org-hh:mm-string-to-minutes s))
17732 (if output-to-string (number-to-string result) result)))
17734 ;;;; Files
17736 (defun org-save-all-org-buffers ()
17737 "Save all Org-mode buffers without user confirmation."
17738 (interactive)
17739 (message "Saving all Org-mode buffers...")
17740 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17741 (when (featurep 'org-id) (org-id-locations-save))
17742 (message "Saving all Org-mode buffers... done"))
17744 (defun org-revert-all-org-buffers ()
17745 "Revert all Org-mode buffers.
17746 Prompt for confirmation when there are unsaved changes.
17747 Be sure you know what you are doing before letting this function
17748 overwrite your changes.
17750 This function is useful in a setup where one tracks org files
17751 with a version control system, to revert on one machine after pulling
17752 changes from another. I believe the procedure must be like this:
17754 1. M-x org-save-all-org-buffers
17755 2. Pull changes from the other machine, resolve conflicts
17756 3. M-x org-revert-all-org-buffers"
17757 (interactive)
17758 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17759 (user-error "Abort"))
17760 (save-excursion
17761 (save-window-excursion
17762 (mapc
17763 (lambda (b)
17764 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17765 (with-current-buffer b buffer-file-name))
17766 (org-pop-to-buffer-same-window b)
17767 (revert-buffer t 'no-confirm)))
17768 (buffer-list))
17769 (when (and (featurep 'org-id) org-id-track-globally)
17770 (org-id-locations-load)))))
17772 ;;;; Agenda files
17774 ;;;###autoload
17775 (defun org-switchb (&optional arg)
17776 "Switch between Org buffers.
17777 With one prefix argument, restrict available buffers to files.
17778 With two prefix arguments, restrict available buffers to agenda files.
17780 Defaults to `iswitchb' for buffer name completion.
17781 Set `org-completion-use-ido' to make it use ido instead."
17782 (interactive "P")
17783 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17784 ((equal arg '(16)) (org-buffer-list 'agenda))
17785 (t (org-buffer-list))))
17786 (org-completion-use-iswitchb org-completion-use-iswitchb)
17787 (org-completion-use-ido org-completion-use-ido))
17788 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17789 (setq org-completion-use-iswitchb t))
17790 (org-pop-to-buffer-same-window
17791 (org-icompleting-read "Org buffer: "
17792 (mapcar 'list (mapcar 'buffer-name blist))
17793 nil t))))
17795 ;;; Define some older names previously used for this functionality
17796 ;;;###autoload
17797 (defalias 'org-ido-switchb 'org-switchb)
17798 ;;;###autoload
17799 (defalias 'org-iswitchb 'org-switchb)
17801 (defun org-buffer-list (&optional predicate exclude-tmp)
17802 "Return a list of Org buffers.
17803 PREDICATE can be `export', `files' or `agenda'.
17805 export restrict the list to Export buffers.
17806 files restrict the list to buffers visiting Org files.
17807 agenda restrict the list to buffers visiting agenda files.
17809 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17810 (let* ((bfn nil)
17811 (agenda-files (and (eq predicate 'agenda)
17812 (mapcar 'file-truename (org-agenda-files t))))
17813 (filter
17814 (cond
17815 ((eq predicate 'files)
17816 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17817 ((eq predicate 'export)
17818 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17819 ((eq predicate 'agenda)
17820 (lambda (b)
17821 (with-current-buffer b
17822 (and (derived-mode-p 'org-mode)
17823 (setq bfn (buffer-file-name b))
17824 (member (file-truename bfn) agenda-files)))))
17825 (t (lambda (b) (with-current-buffer b
17826 (or (derived-mode-p 'org-mode)
17827 (string-match "\*Org .*Export"
17828 (buffer-name b)))))))))
17829 (delq nil
17830 (mapcar
17831 (lambda(b)
17832 (if (and (funcall filter b)
17833 (or (not exclude-tmp)
17834 (not (string-match "tmp" (buffer-name b)))))
17836 nil))
17837 (buffer-list)))))
17839 (defun org-agenda-files (&optional unrestricted archives)
17840 "Get the list of agenda files.
17841 Optional UNRESTRICTED means return the full list even if a restriction
17842 is currently in place.
17843 When ARCHIVES is t, include all archive files that are really being
17844 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17845 `org-agenda-archives-mode' is t."
17846 (let ((files
17847 (cond
17848 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17849 ((stringp org-agenda-files) (org-read-agenda-file-list))
17850 ((listp org-agenda-files) org-agenda-files)
17851 (t (error "Invalid value of `org-agenda-files'")))))
17852 (setq files (apply 'append
17853 (mapcar (lambda (f)
17854 (if (file-directory-p f)
17855 (directory-files
17856 f t org-agenda-file-regexp)
17857 (list f)))
17858 files)))
17859 (when org-agenda-skip-unavailable-files
17860 (setq files (delq nil
17861 (mapcar (function
17862 (lambda (file)
17863 (and (file-readable-p file) file)))
17864 files))))
17865 (when (or (eq archives t)
17866 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17867 (setq files (org-add-archive-files files)))
17868 files))
17870 (defun org-agenda-file-p (&optional file)
17871 "Return non-nil, if FILE is an agenda file.
17872 If FILE is omitted, use the file associated with the current
17873 buffer."
17874 (member (or file (buffer-file-name))
17875 (org-agenda-files t)))
17877 (defun org-edit-agenda-file-list ()
17878 "Edit the list of agenda files.
17879 Depending on setup, this either uses customize to edit the variable
17880 `org-agenda-files', or it visits the file that is holding the list. In the
17881 latter case, the buffer is set up in a way that saving it automatically kills
17882 the buffer and restores the previous window configuration."
17883 (interactive)
17884 (if (stringp org-agenda-files)
17885 (let ((cw (current-window-configuration)))
17886 (find-file org-agenda-files)
17887 (org-set-local 'org-window-configuration cw)
17888 (org-add-hook 'after-save-hook
17889 (lambda ()
17890 (set-window-configuration
17891 (prog1 org-window-configuration
17892 (kill-buffer (current-buffer))))
17893 (org-install-agenda-files-menu)
17894 (message "New agenda file list installed"))
17895 nil 'local)
17896 (message "%s" (substitute-command-keys
17897 "Edit list and finish with \\[save-buffer]")))
17898 (customize-variable 'org-agenda-files)))
17900 (defun org-store-new-agenda-file-list (list)
17901 "Set new value for the agenda file list and save it correctly."
17902 (if (stringp org-agenda-files)
17903 (let ((fe (org-read-agenda-file-list t)) b u)
17904 (while (setq b (find-buffer-visiting org-agenda-files))
17905 (kill-buffer b))
17906 (with-temp-file org-agenda-files
17907 (insert
17908 (mapconcat
17909 (lambda (f) ;; Keep un-expanded entries.
17910 (if (setq u (assoc f fe))
17911 (cdr u)
17913 list "\n")
17914 "\n")))
17915 (let ((org-mode-hook nil) (org-inhibit-startup t)
17916 (org-insert-mode-line-in-empty-file nil))
17917 (setq org-agenda-files list)
17918 (customize-save-variable 'org-agenda-files org-agenda-files))))
17920 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17921 "Read the list of agenda files from a file.
17922 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17923 filenames, used by `org-store-new-agenda-file-list' to write back
17924 un-expanded file names."
17925 (when (file-directory-p org-agenda-files)
17926 (error "`org-agenda-files' cannot be a single directory"))
17927 (when (stringp org-agenda-files)
17928 (with-temp-buffer
17929 (insert-file-contents org-agenda-files)
17930 (mapcar
17931 (lambda (f)
17932 (let ((e (expand-file-name (substitute-in-file-name f)
17933 org-directory)))
17934 (if pair-with-expansion
17935 (cons e f)
17936 e)))
17937 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17939 ;;;###autoload
17940 (defun org-cycle-agenda-files ()
17941 "Cycle through the files in `org-agenda-files'.
17942 If the current buffer visits an agenda file, find the next one in the list.
17943 If the current buffer does not, find the first agenda file."
17944 (interactive)
17945 (let* ((fs (org-agenda-files t))
17946 (files (append fs (list (car fs))))
17947 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17948 file)
17949 (unless files (user-error "No agenda files"))
17950 (catch 'exit
17951 (while (setq file (pop files))
17952 (if (equal (file-truename file) tcf)
17953 (when (car files)
17954 (find-file (car files))
17955 (throw 'exit t))))
17956 (find-file (car fs)))
17957 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17959 (defun org-agenda-file-to-front (&optional to-end)
17960 "Move/add the current file to the top of the agenda file list.
17961 If the file is not present in the list, it is added to the front. If it is
17962 present, it is moved there. With optional argument TO-END, add/move to the
17963 end of the list."
17964 (interactive "P")
17965 (let ((org-agenda-skip-unavailable-files nil)
17966 (file-alist (mapcar (lambda (x)
17967 (cons (file-truename x) x))
17968 (org-agenda-files t)))
17969 (ctf (file-truename
17970 (or buffer-file-name
17971 (user-error "Please save the current buffer to a file"))))
17972 x had)
17973 (setq x (assoc ctf file-alist) had x)
17975 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17976 (if to-end
17977 (setq file-alist (append (delq x file-alist) (list x)))
17978 (setq file-alist (cons x (delq x file-alist))))
17979 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17980 (org-install-agenda-files-menu)
17981 (message "File %s to %s of agenda file list"
17982 (if had "moved" "added") (if to-end "end" "front"))))
17984 (defun org-remove-file (&optional file)
17985 "Remove current file from the list of files in variable `org-agenda-files'.
17986 These are the files which are being checked for agenda entries.
17987 Optional argument FILE means use this file instead of the current."
17988 (interactive)
17989 (let* ((org-agenda-skip-unavailable-files nil)
17990 (file (or file buffer-file-name
17991 (user-error "Current buffer does not visit a file")))
17992 (true-file (file-truename file))
17993 (afile (abbreviate-file-name file))
17994 (files (delq nil (mapcar
17995 (lambda (x)
17996 (if (equal true-file
17997 (file-truename x))
17998 nil x))
17999 (org-agenda-files t)))))
18000 (if (not (= (length files) (length (org-agenda-files t))))
18001 (progn
18002 (org-store-new-agenda-file-list files)
18003 (org-install-agenda-files-menu)
18004 (message "Removed file: %s" afile))
18005 (message "File was not in list: %s (not removed)" afile))))
18007 (defun org-file-menu-entry (file)
18008 (vector file (list 'find-file file) t))
18010 (defun org-check-agenda-file (file)
18011 "Make sure FILE exists. If not, ask user what to do."
18012 (when (not (file-exists-p file))
18013 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18014 (abbreviate-file-name file))
18015 (let ((r (downcase (read-char-exclusive))))
18016 (cond
18017 ((equal r ?r)
18018 (org-remove-file file)
18019 (throw 'nextfile t))
18020 (t (error "Abort"))))))
18022 (defun org-get-agenda-file-buffer (file)
18023 "Get a buffer visiting FILE. If the buffer needs to be created, add
18024 it to the list of buffers which might be released later."
18025 (let ((buf (org-find-base-buffer-visiting file)))
18026 (if buf
18027 buf ; just return it
18028 ;; Make a new buffer and remember it
18029 (setq buf (find-file-noselect file))
18030 (if buf (push buf org-agenda-new-buffers))
18031 buf)))
18033 (defun org-release-buffers (blist)
18034 "Release all buffers in list, asking the user for confirmation when needed.
18035 When a buffer is unmodified, it is just killed. When modified, it is saved
18036 \(if the user agrees) and then killed."
18037 (let (buf file)
18038 (while (setq buf (pop blist))
18039 (setq file (buffer-file-name buf))
18040 (when (and (buffer-modified-p buf)
18041 file
18042 (y-or-n-p (format "Save file %s? " file)))
18043 (with-current-buffer buf (save-buffer)))
18044 (kill-buffer buf))))
18046 (defun org-agenda-prepare-buffers (files)
18047 "Create buffers for all agenda files, protect archived trees and comments."
18048 (interactive)
18049 (let ((pa '(:org-archived t))
18050 (pc '(:org-comment t))
18051 (pall '(:org-archived t :org-comment t))
18052 (inhibit-read-only t)
18053 (org-inhibit-startup org-agenda-inhibit-startup)
18054 (rea (concat ":" org-archive-tag ":"))
18055 file re)
18056 (setq org-tag-alist-for-agenda nil
18057 org-tag-groups-alist-for-agenda nil)
18058 (save-excursion
18059 (save-restriction
18060 (while (setq file (pop files))
18061 (catch 'nextfile
18062 (if (bufferp file)
18063 (set-buffer file)
18064 (org-check-agenda-file file)
18065 (set-buffer (org-get-agenda-file-buffer file)))
18066 (widen)
18067 (org-set-regexps-and-options-for-tags)
18068 (goto-char (point-min))
18069 (let ((case-fold-search t))
18070 (when (search-forward "#+setupfile" nil t)
18071 ;; Don't set all regexps and options systematically as
18072 ;; this is only run for setting agenda tags from setup
18073 ;; file
18074 (org-set-regexps-and-options)))
18075 (or (memq 'category org-agenda-ignore-drawer-properties)
18076 (org-refresh-category-properties))
18077 (or (memq 'effort org-agenda-ignore-drawer-properties)
18078 (org-refresh-properties org-effort-property 'org-effort))
18079 (or (memq 'appt org-agenda-ignore-drawer-properties)
18080 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18081 (setq org-todo-keywords-for-agenda
18082 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18083 (setq org-done-keywords-for-agenda
18084 (append org-done-keywords-for-agenda org-done-keywords))
18085 (setq org-todo-keyword-alist-for-agenda
18086 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18087 (setq org-drawers-for-agenda
18088 (append org-drawers-for-agenda org-drawers))
18089 (setq org-tag-alist-for-agenda
18090 (org-uniquify
18091 (append org-tag-alist-for-agenda
18092 org-tag-alist
18093 org-tag-persistent-alist)))
18094 (if org-group-tags
18095 (setq org-tag-groups-alist-for-agenda
18096 (org-uniquify-alist
18097 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18098 (org-with-silent-modifications
18099 (save-excursion
18100 (remove-text-properties (point-min) (point-max) pall)
18101 (when org-agenda-skip-archived-trees
18102 (goto-char (point-min))
18103 (while (re-search-forward rea nil t)
18104 (if (org-at-heading-p t)
18105 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18106 (goto-char (point-min))
18107 (setq re (format org-heading-keyword-regexp-format
18108 org-comment-string))
18109 (while (re-search-forward re nil t)
18110 (add-text-properties
18111 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18112 (setq org-todo-keywords-for-agenda
18113 (org-uniquify org-todo-keywords-for-agenda))
18114 (setq org-todo-keyword-alist-for-agenda
18115 (org-uniquify org-todo-keyword-alist-for-agenda))))
18118 ;;;; CDLaTeX minor mode
18120 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18121 "Keymap for the minor `org-cdlatex-mode'.")
18123 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18124 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18125 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18126 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18127 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18129 (defvar org-cdlatex-texmathp-advice-is-done nil
18130 "Flag remembering if we have applied the advice to texmathp already.")
18132 (define-minor-mode org-cdlatex-mode
18133 "Toggle the minor `org-cdlatex-mode'.
18134 This mode supports entering LaTeX environment and math in LaTeX fragments
18135 in Org-mode.
18136 \\{org-cdlatex-mode-map}"
18137 nil " OCDL" nil
18138 (when org-cdlatex-mode
18139 (require 'cdlatex)
18140 (run-hooks 'cdlatex-mode-hook)
18141 (cdlatex-compute-tables))
18142 (unless org-cdlatex-texmathp-advice-is-done
18143 (setq org-cdlatex-texmathp-advice-is-done t)
18144 (defadvice texmathp (around org-math-always-on activate)
18145 "Always return t in org-mode buffers.
18146 This is because we want to insert math symbols without dollars even outside
18147 the LaTeX math segments. If Orgmode thinks that point is actually inside
18148 an embedded LaTeX fragment, let texmathp do its job.
18149 \\[org-cdlatex-mode-map]"
18150 (interactive)
18151 (let (p)
18152 (cond
18153 ((not (derived-mode-p 'org-mode)) ad-do-it)
18154 ((eq this-command 'cdlatex-math-symbol)
18155 (setq ad-return-value t
18156 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18158 (let ((p (org-inside-LaTeX-fragment-p)))
18159 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18160 (setq ad-return-value t
18161 texmathp-why '("Org-mode embedded math" . 0))
18162 (if p ad-do-it)))))))))
18164 (defun turn-on-org-cdlatex ()
18165 "Unconditionally turn on `org-cdlatex-mode'."
18166 (org-cdlatex-mode 1))
18168 (defun org-try-cdlatex-tab ()
18169 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18170 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18171 - inside a LaTeX fragment, or
18172 - after the first word in a line, where an abbreviation expansion could
18173 insert a LaTeX environment."
18174 (when org-cdlatex-mode
18175 (cond
18176 ;; Before any word on the line: No expansion possible.
18177 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18178 ;; Just after first word on the line: Expand it. Make sure it
18179 ;; cannot happen on headlines, though.
18180 ((save-excursion
18181 (skip-chars-backward "a-zA-Z0-9*")
18182 (skip-chars-backward " \t")
18183 (and (bolp) (not (org-at-heading-p))))
18184 (cdlatex-tab) t)
18185 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18187 (defun org-cdlatex-underscore-caret (&optional arg)
18188 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18189 Revert to the normal definition outside of these fragments."
18190 (interactive "P")
18191 (if (org-inside-LaTeX-fragment-p)
18192 (call-interactively 'cdlatex-sub-superscript)
18193 (let (org-cdlatex-mode)
18194 (call-interactively (key-binding (vector last-input-event))))))
18196 (defun org-cdlatex-math-modify (&optional arg)
18197 "Execute `cdlatex-math-modify' in LaTeX fragments.
18198 Revert to the normal definition outside of these fragments."
18199 (interactive "P")
18200 (if (org-inside-LaTeX-fragment-p)
18201 (call-interactively 'cdlatex-math-modify)
18202 (let (org-cdlatex-mode)
18203 (call-interactively (key-binding (vector last-input-event))))))
18207 ;;;; LaTeX fragments
18209 (defvar org-latex-regexps
18210 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18211 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18212 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18213 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18214 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18215 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18216 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18217 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18218 "Regular expressions for matching embedded LaTeX.")
18220 (defun org-inside-LaTeX-fragment-p ()
18221 "Test if point is inside a LaTeX fragment.
18222 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18223 sequence appearing also before point.
18224 Even though the matchers for math are configurable, this function assumes
18225 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18226 delimiters are skipped when they have been removed by customization.
18227 The return value is nil, or a cons cell with the delimiter and the
18228 position of this delimiter.
18230 This function does a reasonably good job, but can locally be fooled by
18231 for example currency specifications. For example it will assume being in
18232 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18233 fragments that are properly closed, but during editing, we have to live
18234 with the uncertainty caused by missing closing delimiters. This function
18235 looks only before point, not after."
18236 (catch 'exit
18237 (let ((pos (point))
18238 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18239 (lim (progn
18240 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18241 (point)))
18242 dd-on str (start 0) m re)
18243 (goto-char pos)
18244 (when dodollar
18245 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18246 re (nth 1 (assoc "$" org-latex-regexps)))
18247 (while (string-match re str start)
18248 (cond
18249 ((= (match-end 0) (length str))
18250 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18251 ((= (match-end 0) (- (length str) 5))
18252 (throw 'exit nil))
18253 (t (setq start (match-end 0))))))
18254 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18255 (goto-char pos)
18256 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18257 (and (match-beginning 2) (throw 'exit nil))
18258 ;; count $$
18259 (while (re-search-backward "\\$\\$" lim t)
18260 (setq dd-on (not dd-on)))
18261 (goto-char pos)
18262 (if dd-on (cons "$$" m))))))
18264 (defun org-inside-latex-macro-p ()
18265 "Is point inside a LaTeX macro or its arguments?"
18266 (save-match-data
18267 (org-in-regexp
18268 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18270 (defvar org-latex-fragment-image-overlays nil
18271 "List of overlays carrying the images of latex fragments.")
18272 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18274 (defun org-remove-latex-fragment-image-overlays ()
18275 "Remove all overlays with LaTeX fragment images in current buffer."
18276 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18277 (setq org-latex-fragment-image-overlays nil))
18279 (defun org-preview-latex-fragment (&optional subtree)
18280 "Preview the LaTeX fragment at point, or all locally or globally.
18281 If the cursor is in a LaTeX fragment, create the image and overlay
18282 it over the source code. If there is no fragment at point, display
18283 all fragments in the current text, from one headline to the next. With
18284 prefix SUBTREE, display all fragments in the current subtree. With a
18285 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18286 the cursor is before the first headline,
18287 display all fragments in the buffer.
18288 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18289 (interactive "P")
18290 (unless buffer-file-name
18291 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18292 (when (display-graphic-p)
18293 (org-remove-latex-fragment-image-overlays)
18294 (save-excursion
18295 (save-restriction
18296 (let (beg end at msg)
18297 (cond
18298 ((or (equal subtree '(16))
18299 (not (save-excursion
18300 (re-search-backward org-outline-regexp-bol nil t))))
18301 (setq beg (point-min) end (point-max)
18302 msg "Creating images for buffer...%s"))
18303 ((equal subtree '(4))
18304 (org-back-to-heading)
18305 (setq beg (point) end (org-end-of-subtree t)
18306 msg "Creating images for subtree...%s"))
18308 (if (setq at (org-inside-LaTeX-fragment-p))
18309 (goto-char (max (point-min) (- (cdr at) 2)))
18310 (org-back-to-heading))
18311 (setq beg (point) end (progn (outline-next-heading) (point))
18312 msg (if at "Creating image...%s"
18313 "Creating images for entry...%s"))))
18314 (message msg "")
18315 (narrow-to-region beg end)
18316 (goto-char beg)
18317 (org-format-latex
18318 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18319 (file-name-nondirectory
18320 buffer-file-name)))
18321 default-directory 'overlays msg at 'forbuffer
18322 org-latex-create-formula-image-program)
18323 (message msg "done. Use `C-c C-c' to remove images."))))))
18325 (defun org-format-latex (prefix &optional dir overlays msg at
18326 forbuffer processing-type)
18327 "Replace LaTeX fragments with links to an image, and produce images.
18328 Some of the options can be changed using the variable
18329 `org-format-latex-options'."
18330 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18331 (let* ((prefixnodir (file-name-nondirectory prefix))
18332 (absprefix (expand-file-name prefix dir))
18333 (todir (file-name-directory absprefix))
18334 (opt org-format-latex-options)
18335 (optnew org-format-latex-options)
18336 (matchers (plist-get opt :matchers))
18337 (re-list org-latex-regexps)
18338 (cnt 0) txt hash link beg end re e checkdir
18339 string
18340 m n block-type block linkfile movefile ov)
18341 ;; Check the different regular expressions
18342 (while (setq e (pop re-list))
18343 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18344 block (if block-type "\n\n" ""))
18345 (when (member m matchers)
18346 (goto-char (point-min))
18347 (while (re-search-forward re nil t)
18348 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18349 (or (not overlays)
18350 (not (eq (get-char-property (match-beginning n)
18351 'org-overlay-type)
18352 'org-latex-overlay))))
18353 (cond
18354 ((eq processing-type 'verbatim))
18355 ((eq processing-type 'mathjax)
18356 ;; Prepare for MathJax processing.
18357 (setq string (match-string n))
18358 (when (member m '("$" "$1"))
18359 (save-excursion
18360 (delete-region (match-beginning n) (match-end n))
18361 (goto-char (match-beginning n))
18362 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18363 ((or (eq processing-type 'dvipng)
18364 (eq processing-type 'imagemagick))
18365 ;; Process to an image.
18366 (setq txt (match-string n)
18367 beg (match-beginning n) end (match-end n)
18368 cnt (1+ cnt))
18369 (let ((face (face-at-point))
18370 (fg (plist-get opt :foreground))
18371 (bg (plist-get opt :background))
18372 ;; Ensure full list is printed.
18373 print-length print-level)
18374 (when forbuffer
18375 ;; Get the colors from the face at point.
18376 (goto-char beg)
18377 (when (eq fg 'auto)
18378 (setq fg (face-attribute face :foreground nil 'default)))
18379 (when (eq bg 'auto)
18380 (setq bg (face-attribute face :background nil 'default)))
18381 (setq optnew (copy-sequence opt))
18382 (plist-put optnew :foreground fg)
18383 (plist-put optnew :background bg))
18384 (setq hash (sha1 (prin1-to-string
18385 (list org-format-latex-header
18386 org-latex-default-packages-alist
18387 org-latex-packages-alist
18388 org-format-latex-options
18389 forbuffer txt fg bg)))
18390 linkfile (format "%s_%s.png" prefix hash)
18391 movefile (format "%s_%s.png" absprefix hash)))
18392 (setq link (concat block "[[file:" linkfile "]]" block))
18393 (if msg (message msg cnt))
18394 (goto-char beg)
18395 (unless checkdir ; Ensure the directory exists.
18396 (setq checkdir t)
18397 (or (file-directory-p todir) (make-directory todir t)))
18398 (unless (file-exists-p movefile)
18399 (org-create-formula-image
18400 txt movefile optnew forbuffer processing-type))
18401 (if overlays
18402 (progn
18403 (mapc (lambda (o)
18404 (if (eq (overlay-get o 'org-overlay-type)
18405 'org-latex-overlay)
18406 (delete-overlay o)))
18407 (overlays-in beg end))
18408 (setq ov (make-overlay beg end))
18409 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18410 (if (featurep 'xemacs)
18411 (progn
18412 (overlay-put ov 'invisible t)
18413 (overlay-put
18414 ov 'end-glyph
18415 (make-glyph (vector 'png :file movefile))))
18416 (overlay-put
18417 ov 'display
18418 (list 'image :type 'png :file movefile :ascent 'center)))
18419 (push ov org-latex-fragment-image-overlays)
18420 (goto-char end))
18421 (delete-region beg end)
18422 (insert (org-add-props link
18423 (list 'org-latex-src
18424 (replace-regexp-in-string
18425 "\"" "" txt)
18426 'org-latex-src-embed-type
18427 (if block-type 'paragraph 'character))))))
18428 ((eq processing-type 'mathml)
18429 ;; Process to MathML
18430 (unless (save-match-data (org-format-latex-mathml-available-p))
18431 (user-error "LaTeX to MathML converter not configured"))
18432 (setq txt (match-string n)
18433 beg (match-beginning n) end (match-end n)
18434 cnt (1+ cnt))
18435 (if msg (message msg cnt))
18436 (goto-char beg)
18437 (delete-region beg end)
18438 (insert (org-format-latex-as-mathml
18439 txt block-type prefix dir)))
18441 (error "Unknown conversion type %s for LaTeX fragments"
18442 processing-type)))))))))
18444 (defun org-create-math-formula (latex-frag &optional mathml-file)
18445 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18446 Use `org-latex-to-mathml-convert-command'. If the conversion is
18447 sucessful, return the portion between \"<math...> </math>\"
18448 elements otherwise return nil. When MATHML-FILE is specified,
18449 write the results in to that file. When invoked as an
18450 interactive command, prompt for LATEX-FRAG, with initial value
18451 set to the current active region and echo the results for user
18452 inspection."
18453 (interactive (list (let ((frag (when (org-region-active-p)
18454 (buffer-substring-no-properties
18455 (region-beginning) (region-end)))))
18456 (read-string "LaTeX Fragment: " frag nil frag))))
18457 (unless latex-frag (error "Invalid LaTeX fragment"))
18458 (let* ((tmp-in-file (file-relative-name
18459 (make-temp-name (expand-file-name "ltxmathml-in"))))
18460 (ignore (write-region latex-frag nil tmp-in-file))
18461 (tmp-out-file (file-relative-name
18462 (make-temp-name (expand-file-name "ltxmathml-out"))))
18463 (cmd (format-spec
18464 org-latex-to-mathml-convert-command
18465 `((?j . ,(shell-quote-argument
18466 (expand-file-name org-latex-to-mathml-jar-file)))
18467 (?I . ,(shell-quote-argument tmp-in-file))
18468 (?o . ,(shell-quote-argument tmp-out-file)))))
18469 mathml shell-command-output)
18470 (when (org-called-interactively-p 'any)
18471 (unless (org-format-latex-mathml-available-p)
18472 (user-error "LaTeX to MathML converter not configured")))
18473 (message "Running %s" cmd)
18474 (setq shell-command-output (shell-command-to-string cmd))
18475 (setq mathml
18476 (when (file-readable-p tmp-out-file)
18477 (with-current-buffer (find-file-noselect tmp-out-file t)
18478 (goto-char (point-min))
18479 (when (re-search-forward
18480 (concat
18481 (regexp-quote
18482 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18483 "\\(.\\|\n\\)*"
18484 (regexp-quote "</math>")) nil t)
18485 (prog1 (match-string 0) (kill-buffer))))))
18486 (cond
18487 (mathml
18488 (setq mathml
18489 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18490 (when mathml-file
18491 (write-region mathml nil mathml-file))
18492 (when (org-called-interactively-p 'any)
18493 (message mathml)))
18494 ((message "LaTeX to MathML conversion failed")
18495 (message shell-command-output)))
18496 (delete-file tmp-in-file)
18497 (when (file-exists-p tmp-out-file)
18498 (delete-file tmp-out-file))
18499 mathml))
18501 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18502 prefix &optional dir)
18503 "Use `org-create-math-formula' but check local cache first."
18504 (let* ((absprefix (expand-file-name prefix dir))
18505 (print-length nil) (print-level nil)
18506 (formula-id (concat
18507 "formula-"
18508 (sha1
18509 (prin1-to-string
18510 (list latex-frag
18511 org-latex-to-mathml-convert-command)))))
18512 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18513 (formula-cache-dir (file-name-directory formula-cache)))
18515 (unless (file-directory-p formula-cache-dir)
18516 (make-directory formula-cache-dir t))
18518 (unless (file-exists-p formula-cache)
18519 (org-create-math-formula latex-frag formula-cache))
18521 (if (file-exists-p formula-cache)
18522 ;; Successful conversion. Return the link to MathML file.
18523 (org-add-props
18524 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18525 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18526 'org-latex-src-embed-type (if latex-frag-type
18527 'paragraph 'character)))
18528 ;; Failed conversion. Return the LaTeX fragment verbatim
18529 latex-frag)))
18531 (defun org-create-formula-image (string tofile options buffer &optional type)
18532 "Create an image from LaTeX source using dvipng or convert.
18533 This function calls either `org-create-formula-image-with-dvipng'
18534 or `org-create-formula-image-with-imagemagick' depending on the
18535 value of `org-latex-create-formula-image-program' or on the value
18536 of the optional TYPE variable.
18538 Note: ultimately these two function should be combined as they
18539 share a good deal of logic."
18540 (org-check-external-command
18541 "latex" "needed to convert LaTeX fragments to images")
18542 (funcall
18543 (case (or type org-latex-create-formula-image-program)
18544 ('dvipng
18545 (org-check-external-command
18546 "dvipng" "needed to convert LaTeX fragments to images")
18547 #'org-create-formula-image-with-dvipng)
18548 ('imagemagick
18549 (org-check-external-command
18550 "convert" "you need to install imagemagick")
18551 #'org-create-formula-image-with-imagemagick)
18552 (t (error
18553 "Invalid value of `org-latex-create-formula-image-program'")))
18554 string tofile options buffer))
18556 (declare-function org-export-get-backend "ox" (name))
18557 (declare-function org-export--get-global-options "ox" (&optional backend))
18558 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18559 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18560 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18561 (defun org-create-formula--latex-header ()
18562 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18563 (let ((info (org-combine-plists (org-export--get-global-options
18564 (org-export-get-backend 'latex))
18565 (org-export--get-inbuffer-options
18566 (org-export-get-backend 'latex)))))
18567 (org-latex-guess-babel-language
18568 (org-latex-guess-inputenc
18569 (org-splice-latex-header
18570 org-format-latex-header
18571 org-latex-default-packages-alist
18572 org-latex-packages-alist t
18573 (plist-get info :latex-header)))
18574 info)))
18576 ;; This function borrows from Ganesh Swami's latex2png.el
18577 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18578 "This calls dvipng."
18579 (require 'ox-latex)
18580 (let* ((tmpdir (if (featurep 'xemacs)
18581 (temp-directory)
18582 temporary-file-directory))
18583 (texfilebase (make-temp-name
18584 (expand-file-name "orgtex" tmpdir)))
18585 (texfile (concat texfilebase ".tex"))
18586 (dvifile (concat texfilebase ".dvi"))
18587 (pngfile (concat texfilebase ".png"))
18588 (fnh (if (featurep 'xemacs)
18589 (font-height (face-font 'default))
18590 (face-attribute 'default :height nil)))
18591 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18592 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18593 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18594 "Black"))
18595 (bg (or (plist-get options (if buffer :background :html-background))
18596 "Transparent")))
18597 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18598 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18599 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18600 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18601 (let ((latex-header (org-create-formula--latex-header)))
18602 (with-temp-file texfile
18603 (insert latex-header)
18604 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18605 (let ((dir default-directory))
18606 (condition-case nil
18607 (progn
18608 (cd tmpdir)
18609 (call-process "latex" nil nil nil texfile))
18610 (error nil))
18611 (cd dir))
18612 (if (not (file-exists-p dvifile))
18613 (progn (message "Failed to create dvi file from %s" texfile) nil)
18614 (condition-case nil
18615 (if (featurep 'xemacs)
18616 (call-process "dvipng" nil nil nil
18617 "-fg" fg "-bg" bg
18618 "-T" "tight"
18619 "-o" pngfile
18620 dvifile)
18621 (call-process "dvipng" nil nil nil
18622 "-fg" fg "-bg" bg
18623 "-D" dpi
18624 ;;"-x" scale "-y" scale
18625 "-T" "tight"
18626 "-o" pngfile
18627 dvifile))
18628 (error nil))
18629 (if (not (file-exists-p pngfile))
18630 (if org-format-latex-signal-error
18631 (error "Failed to create png file from %s" texfile)
18632 (message "Failed to create png file from %s" texfile)
18633 nil)
18634 ;; Use the requested file name and clean up
18635 (copy-file pngfile tofile 'replace)
18636 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18637 (if (file-exists-p (concat texfilebase e))
18638 (delete-file (concat texfilebase e))))
18639 pngfile))))
18641 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18642 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18643 "This calls convert, which is included into imagemagick."
18644 (require 'ox-latex)
18645 (let* ((tmpdir (if (featurep 'xemacs)
18646 (temp-directory)
18647 temporary-file-directory))
18648 (texfilebase (make-temp-name
18649 (expand-file-name "orgtex" tmpdir)))
18650 (texfile (concat texfilebase ".tex"))
18651 (pdffile (concat texfilebase ".pdf"))
18652 (pngfile (concat texfilebase ".png"))
18653 (fnh (if (featurep 'xemacs)
18654 (font-height (face-font 'default))
18655 (face-attribute 'default :height nil)))
18656 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18657 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18658 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18659 "black"))
18660 (bg (or (plist-get options (if buffer :background :html-background))
18661 "white")))
18662 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18663 (setq fg (org-latex-color-format fg)))
18664 (if (eq bg 'default) (setq bg (org-latex-color :background))
18665 (setq bg (org-latex-color-format
18666 (if (string= bg "Transparent") "white" bg))))
18667 (let ((latex-header (org-create-formula--latex-header)))
18668 (with-temp-file texfile
18669 (insert latex-header)
18670 (insert "\n\\begin{document}\n"
18671 "\\definecolor{fg}{rgb}{" fg "}\n"
18672 "\\definecolor{bg}{rgb}{" bg "}\n"
18673 "\n\\pagecolor{bg}\n"
18674 "\n{\\color{fg}\n"
18675 string
18676 "\n}\n"
18677 "\n\\end{document}\n")))
18678 (org-latex-compile texfile t)
18679 (if (not (file-exists-p pdffile))
18680 (progn (message "Failed to create pdf file from %s" texfile) nil)
18681 (condition-case nil
18682 (if (featurep 'xemacs)
18683 (call-process "convert" nil nil nil
18684 "-density" "96"
18685 "-trim"
18686 "-antialias"
18687 pdffile
18688 "-quality" "100"
18689 ;; "-sharpen" "0x1.0"
18690 pngfile)
18691 (call-process "convert" nil nil nil
18692 "-density" dpi
18693 "-trim"
18694 "-antialias"
18695 pdffile
18696 "-quality" "100"
18697 ;; "-sharpen" "0x1.0"
18698 pngfile))
18699 (error nil))
18700 (if (not (file-exists-p pngfile))
18701 (if org-format-latex-signal-error
18702 (error "Failed to create png file from %s" texfile)
18703 (message "Failed to create png file from %s" texfile)
18704 nil)
18705 ;; Use the requested file name and clean up
18706 (copy-file pngfile tofile 'replace)
18707 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18708 (if (file-exists-p (concat texfilebase e))
18709 (delete-file (concat texfilebase e))))
18710 pngfile))))
18712 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18713 "Fill a LaTeX header template TPL.
18714 In the template, the following place holders will be recognized:
18716 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18717 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18718 [PACKAGES] \\usepackage statements for PKG
18719 [NO-PACKAGES] do not include PKG
18720 [EXTRA] the string EXTRA
18721 [NO-EXTRA] do not include EXTRA
18723 For backward compatibility, if both the positive and the negative place
18724 holder is missing, the positive one (without the \"NO-\") will be
18725 assumed to be present at the end of the template.
18726 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18727 EXTRA is a string.
18728 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18729 (let (rpl (end ""))
18730 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18731 (setq rpl (if (or (match-end 1) (not def-pkg))
18732 "" (org-latex-packages-to-string def-pkg snippets-p t))
18733 tpl (replace-match rpl t t tpl))
18734 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18736 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18737 (setq rpl (if (or (match-end 1) (not pkg))
18738 "" (org-latex-packages-to-string pkg snippets-p t))
18739 tpl (replace-match rpl t t tpl))
18740 (if pkg (setq end
18741 (concat end "\n"
18742 (org-latex-packages-to-string pkg snippets-p)))))
18744 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18745 (setq rpl (if (or (match-end 1) (not extra))
18746 "" (concat extra "\n"))
18747 tpl (replace-match rpl t t tpl))
18748 (if (and extra (string-match "\\S-" extra))
18749 (setq end (concat end "\n" extra))))
18751 (if (string-match "\\S-" end)
18752 (concat tpl "\n" end)
18753 tpl)))
18755 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18756 "Turn an alist of packages into a string with the \\usepackage macros."
18757 (setq pkg (mapconcat (lambda(p)
18758 (cond
18759 ((stringp p) p)
18760 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18761 (format "%% Package %s omitted" (cadr p)))
18762 ((equal "" (car p))
18763 (format "\\usepackage{%s}" (cadr p)))
18765 (format "\\usepackage[%s]{%s}"
18766 (car p) (cadr p)))))
18768 "\n"))
18769 (if newline (concat pkg "\n") pkg))
18771 (defun org-dvipng-color (attr)
18772 "Return a RGB color specification for dvipng."
18773 (apply 'format "rgb %s %s %s"
18774 (mapcar 'org-normalize-color
18775 (if (featurep 'xemacs)
18776 (color-rgb-components
18777 (face-property 'default
18778 (cond ((eq attr :foreground) 'foreground)
18779 ((eq attr :background) 'background))))
18780 (color-values (face-attribute 'default attr nil))))))
18782 (defun org-dvipng-color-format (color-name)
18783 "Convert COLOR-NAME to a RGB color value for dvipng."
18784 (apply 'format "rgb %s %s %s"
18785 (mapcar 'org-normalize-color
18786 (color-values color-name))))
18788 (defun org-latex-color (attr)
18789 "Return a RGB color for the LaTeX color package."
18790 (apply 'format "%s,%s,%s"
18791 (mapcar 'org-normalize-color
18792 (if (featurep 'xemacs)
18793 (color-rgb-components
18794 (face-property 'default
18795 (cond ((eq attr :foreground) 'foreground)
18796 ((eq attr :background) 'background))))
18797 (color-values (face-attribute 'default attr nil))))))
18799 (defun org-latex-color-format (color-name)
18800 "Convert COLOR-NAME to a RGB color value."
18801 (apply 'format "%s,%s,%s"
18802 (mapcar 'org-normalize-color
18803 (color-values color-name))))
18805 (defun org-normalize-color (value)
18806 "Return string to be used as color value for an RGB component."
18807 (format "%g" (/ value 65535.0)))
18811 ;; Image display
18813 (defvar org-inline-image-overlays nil)
18814 (make-variable-buffer-local 'org-inline-image-overlays)
18816 (defun org-toggle-inline-images (&optional include-linked)
18817 "Toggle the display of inline images.
18818 INCLUDE-LINKED is passed to `org-display-inline-images'."
18819 (interactive "P")
18820 (if org-inline-image-overlays
18821 (progn
18822 (org-remove-inline-images)
18823 (message "Inline image display turned off"))
18824 (org-display-inline-images include-linked)
18825 (if (and (org-called-interactively-p)
18826 org-inline-image-overlays)
18827 (message "%d images displayed inline"
18828 (length org-inline-image-overlays))
18829 (message "No images to display inline"))))
18831 (defun org-redisplay-inline-images ()
18832 "Refresh the display of inline images."
18833 (interactive)
18834 (if (not org-inline-image-overlays)
18835 (org-toggle-inline-images)
18836 (org-toggle-inline-images)
18837 (org-toggle-inline-images)))
18839 (defun org-display-inline-images (&optional include-linked refresh beg end)
18840 "Display inline images.
18841 Normally only links without a description part are inlined, because this
18842 is how it will work for export. When INCLUDE-LINKED is set, also links
18843 with a description part will be inlined. This can be nice for a quick
18844 look at those images, but it does not reflect what exported files will look
18845 like.
18846 When REFRESH is set, refresh existing images between BEG and END.
18847 This will create new image displays only if necessary.
18848 BEG and END default to the buffer boundaries."
18849 (interactive "P")
18850 (when (display-graphic-p)
18851 (unless refresh
18852 (org-remove-inline-images)
18853 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18854 (save-excursion
18855 (save-restriction
18856 (widen)
18857 (setq beg (or beg (point-min)) end (or end (point-max)))
18858 (goto-char beg)
18859 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18860 (substring (org-image-file-name-regexp) 0 -2)
18861 "\\)\\]" (if include-linked "" "\\]")))
18862 (case-fold-search t)
18863 old file ov img type attrwidth width)
18864 (while (re-search-forward re end t)
18865 (setq old (get-char-property-and-overlay (match-beginning 1)
18866 'org-image-overlay)
18867 file (expand-file-name
18868 (concat (or (match-string 3) "") (match-string 4))))
18869 (when (image-type-available-p 'imagemagick)
18870 (setq attrwidth (if (or (listp org-image-actual-width)
18871 (null org-image-actual-width))
18872 (save-excursion
18873 (save-match-data
18874 (when (re-search-backward
18875 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18876 (save-excursion
18877 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18878 (string-to-number (match-string 1))))))
18879 width (cond ((eq org-image-actual-width t) nil)
18880 ((null org-image-actual-width) attrwidth)
18881 ((numberp org-image-actual-width)
18882 org-image-actual-width)
18883 ((listp org-image-actual-width)
18884 (or attrwidth (car org-image-actual-width))))
18885 type (if width 'imagemagick)))
18886 (when (file-exists-p file)
18887 (if (and (car-safe old) refresh)
18888 (image-refresh (overlay-get (cdr old) 'display))
18889 (setq img (save-match-data (create-image file type nil :width width)))
18890 (when img
18891 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18892 (overlay-put ov 'display img)
18893 (overlay-put ov 'face 'default)
18894 (overlay-put ov 'org-image-overlay t)
18895 (overlay-put ov 'modification-hooks
18896 (list 'org-display-inline-remove-overlay))
18897 (push ov org-inline-image-overlays))))))))))
18899 (define-obsolete-function-alias
18900 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18902 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18903 "Remove inline-display overlay if a corresponding region is modified."
18904 (let ((inhibit-modification-hooks t))
18905 (when (and ov after)
18906 (delete ov org-inline-image-overlays)
18907 (delete-overlay ov))))
18909 (defun org-remove-inline-images ()
18910 "Remove inline display of images."
18911 (interactive)
18912 (mapc 'delete-overlay org-inline-image-overlays)
18913 (setq org-inline-image-overlays nil))
18915 ;;;; Key bindings
18917 ;; Outline functions from `outline-mode-prefix-map'
18918 ;; that can be remapped in Org:
18919 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18920 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18921 (define-key org-mode-map [remap outline-forward-same-level]
18922 'org-forward-heading-same-level)
18923 (define-key org-mode-map [remap outline-backward-same-level]
18924 'org-backward-heading-same-level)
18925 (define-key org-mode-map [remap show-branches]
18926 'org-kill-note-or-show-branches)
18927 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18928 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18929 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18931 ;; Outline functions from `outline-mode-prefix-map' that can not
18932 ;; be remapped in Org:
18934 ;; - the column "key binding" shows whether the Outline function is still
18935 ;; available in Org mode on the same key that it has been bound to in
18936 ;; Outline mode:
18937 ;; - "overridden": key used for a different functionality in Org mode
18938 ;; - else: key still bound to the same Outline function in Org mode
18940 ;; | Outline function | key binding | Org replacement |
18941 ;; |------------------------------------+-------------+-----------------------|
18942 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18943 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18944 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18945 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18946 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18947 ;; | `show-entry' | overridden | no replacement |
18948 ;; | `show-children' | `C-c C-i' | visibility cycling |
18949 ;; | `show-branches' | `C-c C-k' | still same function |
18950 ;; | `show-subtree' | overridden | visibility cycling |
18951 ;; | `show-all' | overridden | no replacement |
18952 ;; | `hide-subtree' | overridden | visibility cycling |
18953 ;; | `hide-body' | overridden | no replacement |
18954 ;; | `hide-entry' | overridden | visibility cycling |
18955 ;; | `hide-leaves' | overridden | no replacement |
18956 ;; | `hide-sublevels' | overridden | no replacement |
18957 ;; | `hide-other' | overridden | no replacement |
18959 ;; Make `C-c C-x' a prefix key
18960 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18962 ;; TAB key with modifiers
18963 (org-defkey org-mode-map "\C-i" 'org-cycle)
18964 (org-defkey org-mode-map [(tab)] 'org-cycle)
18965 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18966 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18967 ;; The following line is necessary under Suse GNU/Linux
18968 (unless (featurep 'xemacs)
18969 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18970 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18971 (define-key org-mode-map [backtab] 'org-shifttab)
18973 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18974 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18975 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18977 ;; Cursor keys with modifiers
18978 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18979 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18980 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18981 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18983 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18984 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18985 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18986 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18988 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18989 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18990 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18991 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18993 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18994 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18995 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18996 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18998 ;; Babel keys
18999 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19000 (mapc (lambda (pair)
19001 (define-key org-babel-map (car pair) (cdr pair)))
19002 org-babel-key-bindings)
19004 ;;; Extra keys for tty access.
19005 ;; We only set them when really needed because otherwise the
19006 ;; menus don't show the simple keys
19008 (when (or org-use-extra-keys
19009 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19010 (not window-system))
19011 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19012 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19013 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19014 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19015 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19016 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19017 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19018 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19019 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19020 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19021 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19022 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19023 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19024 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19025 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19026 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19027 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19028 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19029 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19030 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19031 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19032 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19033 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19034 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19035 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19036 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19037 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19038 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19040 ;; All the other keys
19042 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19043 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19044 (if (boundp 'narrow-map)
19045 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19046 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19047 (if (boundp 'narrow-map)
19048 (org-defkey narrow-map "b" 'org-narrow-to-block)
19049 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19050 (if (boundp 'narrow-map)
19051 (org-defkey narrow-map "e" 'org-narrow-to-element)
19052 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19053 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19054 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19055 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19056 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19057 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19058 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19059 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19060 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19061 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19062 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19063 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19064 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19065 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19066 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19067 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19068 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19069 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19070 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19071 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19072 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19073 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19074 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19075 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19076 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19077 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19078 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19079 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19080 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19081 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19082 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19083 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19084 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19085 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19086 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19087 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19088 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19089 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19090 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19091 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19092 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19093 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19094 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19095 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19096 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19097 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19098 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19099 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19100 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19101 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19102 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19103 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19104 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19105 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19106 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19107 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19108 (org-defkey org-mode-map "\C-c^" 'org-sort)
19109 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19110 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19111 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19112 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19113 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19114 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19115 (org-defkey org-mode-map "\C-m" 'org-return)
19116 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19117 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19118 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19119 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19120 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19121 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19122 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19123 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19124 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19125 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19126 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19127 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19128 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19129 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19130 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19131 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19132 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19133 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19134 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19135 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19136 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19137 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19138 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19140 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19141 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19142 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19144 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19145 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19146 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19147 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19148 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19149 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19150 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19151 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19152 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19153 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19154 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19155 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19156 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19157 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19158 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19159 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19160 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19161 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19162 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19163 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19164 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19165 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19166 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19168 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19169 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19170 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19171 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19172 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19174 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19176 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19178 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19179 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19181 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19184 (when (featurep 'xemacs)
19185 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19188 (defconst org-speed-commands-default
19190 ("Outline Navigation")
19191 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19192 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19193 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19194 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19195 ("F" . org-next-block)
19196 ("B" . org-previous-block)
19197 ("u" . (org-speed-move-safe 'outline-up-heading))
19198 ("j" . org-goto)
19199 ("g" . (org-refile t))
19200 ("Outline Visibility")
19201 ("c" . org-cycle)
19202 ("C" . org-shifttab)
19203 (" " . org-display-outline-path)
19204 ("s" . org-narrow-to-subtree)
19205 ("=" . org-columns)
19206 ("Outline Structure Editing")
19207 ("U" . org-shiftmetaup)
19208 ("D" . org-shiftmetadown)
19209 ("r" . org-metaright)
19210 ("l" . org-metaleft)
19211 ("R" . org-shiftmetaright)
19212 ("L" . org-shiftmetaleft)
19213 ("i" . (progn (forward-char 1) (call-interactively
19214 'org-insert-heading-respect-content)))
19215 ("^" . org-sort)
19216 ("w" . org-refile)
19217 ("a" . org-archive-subtree-default-with-confirmation)
19218 ("@" . org-mark-subtree)
19219 ("#" . org-toggle-comment)
19220 ("Clock Commands")
19221 ("I" . org-clock-in)
19222 ("O" . org-clock-out)
19223 ("Meta Data Editing")
19224 ("t" . org-todo)
19225 ("," . (org-priority))
19226 ("0" . (org-priority ?\ ))
19227 ("1" . (org-priority ?A))
19228 ("2" . (org-priority ?B))
19229 ("3" . (org-priority ?C))
19230 (":" . org-set-tags-command)
19231 ("e" . org-set-effort)
19232 ("E" . org-inc-effort)
19233 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19234 (org-entry-put (point) "APPT_WARNTIME" m)))
19235 ("Agenda Views etc")
19236 ("v" . org-agenda)
19237 ("/" . org-sparse-tree)
19238 ("Misc")
19239 ("o" . org-open-at-point)
19240 ("?" . org-speed-command-help)
19241 ("<" . (org-agenda-set-restriction-lock 'subtree))
19242 (">" . (org-agenda-remove-restriction-lock))
19244 "The default speed commands.")
19246 (defun org-print-speed-command (e)
19247 (if (> (length (car e)) 1)
19248 (progn
19249 (princ "\n")
19250 (princ (car e))
19251 (princ "\n")
19252 (princ (make-string (length (car e)) ?-))
19253 (princ "\n"))
19254 (princ (car e))
19255 (princ " ")
19256 (if (symbolp (cdr e))
19257 (princ (symbol-name (cdr e)))
19258 (prin1 (cdr e)))
19259 (princ "\n")))
19261 (defun org-speed-command-help ()
19262 "Show the available speed commands."
19263 (interactive)
19264 (if (not org-use-speed-commands)
19265 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19266 (with-output-to-temp-buffer "*Help*"
19267 (princ "User-defined Speed commands\n===========================\n")
19268 (mapc 'org-print-speed-command org-speed-commands-user)
19269 (princ "\n")
19270 (princ "Built-in Speed commands\n=======================\n")
19271 (mapc 'org-print-speed-command org-speed-commands-default))
19272 (with-current-buffer "*Help*"
19273 (setq truncate-lines t))))
19275 (defun org-speed-move-safe (cmd)
19276 "Execute CMD, but make sure that the cursor always ends up in a headline.
19277 If not, return to the original position and throw an error."
19278 (interactive)
19279 (let ((pos (point)))
19280 (call-interactively cmd)
19281 (unless (and (bolp) (org-at-heading-p))
19282 (goto-char pos)
19283 (error "Boundary reached while executing %s" cmd))))
19285 (defvar org-self-insert-command-undo-counter 0)
19287 (defvar org-table-auto-blank-field) ; defined in org-table.el
19288 (defvar org-speed-command nil)
19290 (define-obsolete-function-alias
19291 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19293 (defun org-speed-command-activate (keys)
19294 "Hook for activating single-letter speed commands.
19295 `org-speed-commands-default' specifies a minimal command set.
19296 Use `org-speed-commands-user' for further customization."
19297 (when (or (and (bolp) (looking-at org-outline-regexp))
19298 (and (functionp org-use-speed-commands)
19299 (funcall org-use-speed-commands)))
19300 (cdr (assoc keys (append org-speed-commands-user
19301 org-speed-commands-default)))))
19303 (define-obsolete-function-alias
19304 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19306 (defun org-babel-speed-command-activate (keys)
19307 "Hook for activating single-letter code block commands."
19308 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19309 (cdr (assoc keys org-babel-key-bindings))))
19311 (defcustom org-speed-command-hook
19312 '(org-speed-command-default-hook org-babel-speed-command-hook)
19313 "Hook for activating speed commands at strategic locations.
19314 Hook functions are called in sequence until a valid handler is
19315 found.
19317 Each hook takes a single argument, a user-pressed command key
19318 which is also a `self-insert-command' from the global map.
19320 Within the hook, examine the cursor position and the command key
19321 and return nil or a valid handler as appropriate. Handler could
19322 be one of an interactive command, a function, or a form.
19324 Set `org-use-speed-commands' to non-nil value to enable this
19325 hook. The default setting is `org-speed-command-activate'."
19326 :group 'org-structure
19327 :version "24.1"
19328 :type 'hook)
19330 (defun org-self-insert-command (N)
19331 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19332 If the cursor is in a table looking at whitespace, the whitespace is
19333 overwritten, and the table is not marked as requiring realignment."
19334 (interactive "p")
19335 (org-check-before-invisible-edit 'insert)
19336 (cond
19337 ((and org-use-speed-commands
19338 (setq org-speed-command
19339 (run-hook-with-args-until-success
19340 'org-speed-command-hook (this-command-keys))))
19341 (cond
19342 ((commandp org-speed-command)
19343 (setq this-command org-speed-command)
19344 (call-interactively org-speed-command))
19345 ((functionp org-speed-command)
19346 (funcall org-speed-command))
19347 ((and org-speed-command (listp org-speed-command))
19348 (eval org-speed-command))
19349 (t (let (org-use-speed-commands)
19350 (call-interactively 'org-self-insert-command)))))
19351 ((and
19352 (org-table-p)
19353 (progn
19354 ;; check if we blank the field, and if that triggers align
19355 (and (featurep 'org-table) org-table-auto-blank-field
19356 (member last-command
19357 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19358 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19359 ;; got extra space, this field does not determine column width
19360 (let (org-table-may-need-update) (org-table-blank-field))
19361 ;; no extra space, this field may determine column width
19362 (org-table-blank-field)))
19364 (eq N 1)
19365 (looking-at "[^|\n]* |"))
19366 (let (org-table-may-need-update)
19367 (goto-char (1- (match-end 0)))
19368 (backward-delete-char 1)
19369 (goto-char (match-beginning 0))
19370 (self-insert-command N)))
19372 (setq org-table-may-need-update t)
19373 (self-insert-command N)
19374 (org-fix-tags-on-the-fly)
19375 (if org-self-insert-cluster-for-undo
19376 (if (not (eq last-command 'org-self-insert-command))
19377 (setq org-self-insert-command-undo-counter 1)
19378 (if (>= org-self-insert-command-undo-counter 20)
19379 (setq org-self-insert-command-undo-counter 1)
19380 (and (> org-self-insert-command-undo-counter 0)
19381 buffer-undo-list (listp buffer-undo-list)
19382 (not (cadr buffer-undo-list)) ; remove nil entry
19383 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19384 (setq org-self-insert-command-undo-counter
19385 (1+ org-self-insert-command-undo-counter))))))))
19387 (defun org-check-before-invisible-edit (kind)
19388 "Check is editing if kind KIND would be dangerous with invisible text around.
19389 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19390 ;; First, try to get out of here as quickly as possible, to reduce overhead
19391 (if (and org-catch-invisible-edits
19392 (or (not (boundp 'visible-mode)) (not visible-mode))
19393 (or (get-char-property (point) 'invisible)
19394 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19395 ;; OK, we need to take a closer look
19396 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19397 (invisible-before-point (if (bobp) nil (get-char-property
19398 (1- (point)) 'invisible)))
19399 (border-and-ok-direction
19401 ;; Check if we are acting predictably before invisible text
19402 (and invisible-at-point (not invisible-before-point)
19403 (memq kind '(insert delete-backward)))
19404 ;; Check if we are acting predictably after invisible text
19405 ;; This works not well, and I have turned it off. It seems
19406 ;; better to always show and stop after invisible text.
19407 ;; (and (not invisible-at-point) invisible-before-point
19408 ;; (memq kind '(insert delete)))
19410 (when (or (memq invisible-at-point '(outline org-hide-block t))
19411 (memq invisible-before-point '(outline org-hide-block t)))
19412 (if (eq org-catch-invisible-edits 'error)
19413 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19414 (if (and org-custom-properties-overlays
19415 (y-or-n-p "Display invisible properties in this buffer? "))
19416 (org-toggle-custom-properties-visibility)
19417 ;; Make the area visible
19418 (save-excursion
19419 (if invisible-before-point
19420 (goto-char (previous-single-char-property-change
19421 (point) 'invisible)))
19422 (org-cycle))
19423 (cond
19424 ((eq org-catch-invisible-edits 'show)
19425 ;; That's it, we do the edit after showing
19426 (message
19427 "Unfolding invisible region around point before editing")
19428 (sit-for 1))
19429 ((and (eq org-catch-invisible-edits 'smart)
19430 border-and-ok-direction)
19431 (message "Unfolding invisible region around point before editing"))
19433 ;; Don't do the edit, make the user repeat it in full visibility
19434 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19436 (defun org-fix-tags-on-the-fly ()
19437 (when (and (equal (char-after (point-at-bol)) ?*)
19438 (org-at-heading-p))
19439 (org-align-tags-here org-tags-column)))
19441 (defun org-delete-backward-char (N)
19442 "Like `delete-backward-char', insert whitespace at field end in tables.
19443 When deleting backwards, in tables this function will insert whitespace in
19444 front of the next \"|\" separator, to keep the table aligned. The table will
19445 still be marked for re-alignment if the field did fill the entire column,
19446 because, in this case the deletion might narrow the column."
19447 (interactive "p")
19448 (save-match-data
19449 (org-check-before-invisible-edit 'delete-backward)
19450 (if (and (org-table-p)
19451 (eq N 1)
19452 (string-match "|" (buffer-substring (point-at-bol) (point)))
19453 (looking-at ".*?|"))
19454 (let ((pos (point))
19455 (noalign (looking-at "[^|\n\r]* |"))
19456 (c org-table-may-need-update))
19457 (backward-delete-char N)
19458 (if (not overwrite-mode)
19459 (progn
19460 (skip-chars-forward "^|")
19461 (insert " ")
19462 (goto-char (1- pos))))
19463 ;; noalign: if there were two spaces at the end, this field
19464 ;; does not determine the width of the column.
19465 (if noalign (setq org-table-may-need-update c)))
19466 (backward-delete-char N)
19467 (org-fix-tags-on-the-fly))))
19469 (defun org-delete-char (N)
19470 "Like `delete-char', but insert whitespace at field end in tables.
19471 When deleting characters, in tables this function will insert whitespace in
19472 front of the next \"|\" separator, to keep the table aligned. The table will
19473 still be marked for re-alignment if the field did fill the entire column,
19474 because, in this case the deletion might narrow the column."
19475 (interactive "p")
19476 (save-match-data
19477 (org-check-before-invisible-edit 'delete)
19478 (if (and (org-table-p)
19479 (not (bolp))
19480 (not (= (char-after) ?|))
19481 (eq N 1))
19482 (if (looking-at ".*?|")
19483 (let ((pos (point))
19484 (noalign (looking-at "[^|\n\r]* |"))
19485 (c org-table-may-need-update))
19486 (replace-match
19487 (concat (substring (match-string 0) 1 -1) " |") nil t)
19488 (goto-char pos)
19489 ;; noalign: if there were two spaces at the end, this field
19490 ;; does not determine the width of the column.
19491 (if noalign (setq org-table-may-need-update c)))
19492 (delete-char N))
19493 (delete-char N)
19494 (org-fix-tags-on-the-fly))))
19496 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19497 (put 'org-self-insert-command 'delete-selection t)
19498 (put 'orgtbl-self-insert-command 'delete-selection t)
19499 (put 'org-delete-char 'delete-selection 'supersede)
19500 (put 'org-delete-backward-char 'delete-selection 'supersede)
19501 (put 'org-yank 'delete-selection 'yank)
19503 ;; Make `flyspell-mode' delay after some commands
19504 (put 'org-self-insert-command 'flyspell-delayed t)
19505 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19506 (put 'org-delete-char 'flyspell-delayed t)
19507 (put 'org-delete-backward-char 'flyspell-delayed t)
19509 ;; Make pabbrev-mode expand after org-mode commands
19510 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19511 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19513 ;; How to do this: Measure non-white length of current string
19514 ;; If equal to column width, we should realign.
19516 (defun org-remap (map &rest commands)
19517 "In MAP, remap the functions given in COMMANDS.
19518 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19519 (let (new old)
19520 (while commands
19521 (setq old (pop commands) new (pop commands))
19522 (if (fboundp 'command-remapping)
19523 (org-defkey map (vector 'remap old) new)
19524 (substitute-key-definition old new map global-map)))))
19526 (defun org-transpose-words ()
19527 "Transpose words for Org.
19528 This uses the `org-mode-transpose-word-syntax-table' syntax
19529 table, which interprets characters in `org-emphasis-alist' as
19530 word constituants."
19531 (interactive)
19532 (with-syntax-table org-mode-transpose-word-syntax-table
19533 (call-interactively 'transpose-words)))
19534 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19536 (when (eq org-enable-table-editor 'optimized)
19537 ;; If the user wants maximum table support, we need to hijack
19538 ;; some standard editing functions
19539 (org-remap org-mode-map
19540 'self-insert-command 'org-self-insert-command
19541 'delete-char 'org-delete-char
19542 'delete-backward-char 'org-delete-backward-char)
19543 (org-defkey org-mode-map "|" 'org-force-self-insert))
19545 (defvar org-ctrl-c-ctrl-c-hook nil
19546 "Hook for functions attaching themselves to `C-c C-c'.
19548 This can be used to add additional functionality to the C-c C-c
19549 key which executes context-dependent commands. This hook is run
19550 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19551 run after the last test.
19553 Each function will be called with no arguments. The function
19554 must check if the context is appropriate for it to act. If yes,
19555 it should do its thing and then return a non-nil value. If the
19556 context is wrong, just do nothing and return nil.")
19558 (defvar org-ctrl-c-ctrl-c-final-hook nil
19559 "Hook for functions attaching themselves to `C-c C-c'.
19561 This can be used to add additional functionality to the C-c C-c
19562 key which executes context-dependent commands. This hook is run
19563 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19564 before the first test.
19566 Each function will be called with no arguments. The function
19567 must check if the context is appropriate for it to act. If yes,
19568 it should do its thing and then return a non-nil value. If the
19569 context is wrong, just do nothing and return nil.")
19571 (defvar org-tab-first-hook nil
19572 "Hook for functions to attach themselves to TAB.
19573 See `org-ctrl-c-ctrl-c-hook' for more information.
19574 This hook runs as the first action when TAB is pressed, even before
19575 `org-cycle' messes around with the `outline-regexp' to cater for
19576 inline tasks and plain list item folding.
19577 If any function in this hook returns t, any other actions that
19578 would have been caused by TAB (such as table field motion or visibility
19579 cycling) will not occur.")
19581 (defvar org-tab-after-check-for-table-hook nil
19582 "Hook for functions to attach themselves to TAB.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.
19584 This hook runs after it has been established that the cursor is not in a
19585 table, but before checking if the cursor is in a headline or if global cycling
19586 should be done.
19587 If any function in this hook returns t, not other actions like visibility
19588 cycling will be done.")
19590 (defvar org-tab-after-check-for-cycling-hook nil
19591 "Hook for functions to attach themselves to TAB.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.
19593 This hook runs after it has been established that not table field motion and
19594 not visibility should be done because of current context. This is probably
19595 the place where a package like yasnippets can hook in.")
19597 (defvar org-tab-before-tab-emulation-hook nil
19598 "Hook for functions to attach themselves to TAB.
19599 See `org-ctrl-c-ctrl-c-hook' for more information.
19600 This hook runs after every other options for TAB have been exhausted, but
19601 before indentation and \t insertion takes place.")
19603 (defvar org-metaleft-hook nil
19604 "Hook for functions attaching themselves to `M-left'.
19605 See `org-ctrl-c-ctrl-c-hook' for more information.")
19606 (defvar org-metaright-hook nil
19607 "Hook for functions attaching themselves to `M-right'.
19608 See `org-ctrl-c-ctrl-c-hook' for more information.")
19609 (defvar org-metaup-hook nil
19610 "Hook for functions attaching themselves to `M-up'.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19612 (defvar org-metadown-hook nil
19613 "Hook for functions attaching themselves to `M-down'.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.")
19615 (defvar org-shiftmetaleft-hook nil
19616 "Hook for functions attaching themselves to `M-S-left'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-shiftmetaright-hook nil
19619 "Hook for functions attaching themselves to `M-S-right'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-shiftmetaup-hook nil
19622 "Hook for functions attaching themselves to `M-S-up'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-shiftmetadown-hook nil
19625 "Hook for functions attaching themselves to `M-S-down'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-metareturn-hook nil
19628 "Hook for functions attaching themselves to `M-RET'.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.")
19630 (defvar org-shiftup-hook nil
19631 "Hook for functions attaching themselves to `S-up'.
19632 See `org-ctrl-c-ctrl-c-hook' for more information.")
19633 (defvar org-shiftup-final-hook nil
19634 "Hook for functions attaching themselves to `S-up'.
19635 This one runs after all other options except shift-select have been excluded.
19636 See `org-ctrl-c-ctrl-c-hook' for more information.")
19637 (defvar org-shiftdown-hook nil
19638 "Hook for functions attaching themselves to `S-down'.
19639 See `org-ctrl-c-ctrl-c-hook' for more information.")
19640 (defvar org-shiftdown-final-hook nil
19641 "Hook for functions attaching themselves to `S-down'.
19642 This one runs after all other options except shift-select have been excluded.
19643 See `org-ctrl-c-ctrl-c-hook' for more information.")
19644 (defvar org-shiftleft-hook nil
19645 "Hook for functions attaching themselves to `S-left'.
19646 See `org-ctrl-c-ctrl-c-hook' for more information.")
19647 (defvar org-shiftleft-final-hook nil
19648 "Hook for functions attaching themselves to `S-left'.
19649 This one runs after all other options except shift-select have been excluded.
19650 See `org-ctrl-c-ctrl-c-hook' for more information.")
19651 (defvar org-shiftright-hook nil
19652 "Hook for functions attaching themselves to `S-right'.
19653 See `org-ctrl-c-ctrl-c-hook' for more information.")
19654 (defvar org-shiftright-final-hook nil
19655 "Hook for functions attaching themselves to `S-right'.
19656 This one runs after all other options except shift-select have been excluded.
19657 See `org-ctrl-c-ctrl-c-hook' for more information.")
19659 (defun org-modifier-cursor-error ()
19660 "Throw an error, a modified cursor command was applied in wrong context."
19661 (user-error "This command is active in special context like tables, headlines or items"))
19663 (defun org-shiftselect-error ()
19664 "Throw an error because Shift-Cursor command was applied in wrong context."
19665 (if (and (boundp 'shift-select-mode) shift-select-mode)
19666 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19667 (user-error "This command works only in special context like headlines or timestamps")))
19669 (defun org-call-for-shift-select (cmd)
19670 (let ((this-command-keys-shift-translated t))
19671 (call-interactively cmd)))
19673 (defun org-shifttab (&optional arg)
19674 "Global visibility cycling or move to previous table field.
19675 Call `org-table-previous-field' within a table.
19676 When ARG is nil, cycle globally through visibility states.
19677 When ARG is a numeric prefix, show contents of this level."
19678 (interactive "P")
19679 (cond
19680 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19681 ((integerp arg)
19682 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19683 (message "Content view to level: %d" arg)
19684 (org-content (prefix-numeric-value arg2))
19685 (org-cycle-show-empty-lines t)
19686 (setq org-cycle-global-status 'overview)))
19687 (t (call-interactively 'org-global-cycle))))
19689 (defun org-shiftmetaleft ()
19690 "Promote subtree or delete table column.
19691 Calls `org-promote-subtree', `org-outdent-item-tree', or
19692 `org-table-delete-column', depending on context. See the
19693 individual commands for more information."
19694 (interactive)
19695 (cond
19696 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19697 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19698 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19699 ((if (not (org-region-active-p)) (org-at-item-p)
19700 (save-excursion (goto-char (region-beginning))
19701 (org-at-item-p)))
19702 (call-interactively 'org-outdent-item-tree))
19703 (t (org-modifier-cursor-error))))
19705 (defun org-shiftmetaright ()
19706 "Demote subtree or insert table column.
19707 Calls `org-demote-subtree', `org-indent-item-tree', or
19708 `org-table-insert-column', depending on context. See the
19709 individual commands for more information."
19710 (interactive)
19711 (cond
19712 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19713 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19714 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19715 ((if (not (org-region-active-p)) (org-at-item-p)
19716 (save-excursion (goto-char (region-beginning))
19717 (org-at-item-p)))
19718 (call-interactively 'org-indent-item-tree))
19719 (t (org-modifier-cursor-error))))
19721 (defun org-shiftmetaup (&optional arg)
19722 "Move subtree up or kill table row.
19723 Calls `org-move-subtree-up' or `org-table-kill-row' or
19724 `org-move-item-up' or `org-timestamp-up', depending on context.
19725 See the individual commands for more information."
19726 (interactive "P")
19727 (cond
19728 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19729 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19730 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19731 ((org-at-item-p) (call-interactively 'org-move-item-up))
19732 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19733 (call-interactively 'org-timestamp-up)))
19734 (t (call-interactively 'org-drag-line-backward))))
19736 (defun org-shiftmetadown (&optional arg)
19737 "Move subtree down or insert table row.
19738 Calls `org-move-subtree-down' or `org-table-insert-row' or
19739 `org-move-item-down' or `org-timestamp-up', depending on context.
19740 See the individual commands for more information."
19741 (interactive "P")
19742 (cond
19743 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19744 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19745 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19746 ((org-at-item-p) (call-interactively 'org-move-item-down))
19747 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19748 (call-interactively 'org-timestamp-down)))
19749 (t (call-interactively 'org-drag-line-forward))))
19751 (defsubst org-hidden-tree-error ()
19752 (user-error
19753 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19755 (defun org-metaleft (&optional arg)
19756 "Promote heading or move table column to left.
19757 Calls `org-do-promote' or `org-table-move-column', depending on context.
19758 With no specific context, calls the Emacs default `backward-word'.
19759 See the individual commands for more information."
19760 (interactive "P")
19761 (cond
19762 ((run-hook-with-args-until-success 'org-metaleft-hook))
19763 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19764 ((org-with-limited-levels
19765 (or (org-at-heading-p)
19766 (and (org-region-active-p)
19767 (save-excursion
19768 (goto-char (region-beginning))
19769 (org-at-heading-p)))))
19770 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19771 (call-interactively 'org-do-promote))
19772 ;; At an inline task.
19773 ((org-at-heading-p)
19774 (call-interactively 'org-inlinetask-promote))
19775 ((or (org-at-item-p)
19776 (and (org-region-active-p)
19777 (save-excursion
19778 (goto-char (region-beginning))
19779 (org-at-item-p))))
19780 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19781 (call-interactively 'org-outdent-item))
19782 (t (call-interactively 'backward-word))))
19784 (defun org-metaright (&optional arg)
19785 "Demote a subtree, a list item or move table column to right.
19786 In front of a drawer or a block keyword, indent it correctly.
19787 With no specific context, calls the Emacs default `forward-word'.
19788 See the individual commands for more information."
19789 (interactive "P")
19790 (cond
19791 ((run-hook-with-args-until-success 'org-metaright-hook))
19792 ((org-at-table-p) (call-interactively 'org-table-move-column))
19793 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19794 ((org-at-block-p) (call-interactively 'org-indent-block))
19795 ((org-with-limited-levels
19796 (or (org-at-heading-p)
19797 (and (org-region-active-p)
19798 (save-excursion
19799 (goto-char (region-beginning))
19800 (org-at-heading-p)))))
19801 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19802 (call-interactively 'org-do-demote))
19803 ;; At an inline task.
19804 ((org-at-heading-p)
19805 (call-interactively 'org-inlinetask-demote))
19806 ((or (org-at-item-p)
19807 (and (org-region-active-p)
19808 (save-excursion
19809 (goto-char (region-beginning))
19810 (org-at-item-p))))
19811 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19812 (call-interactively 'org-indent-item))
19813 (t (call-interactively 'forward-word))))
19815 (defun org-check-for-hidden (what)
19816 "Check if there are hidden headlines/items in the current visual line.
19817 WHAT can be either `headlines' or `items'. If the current line is
19818 an outline or item heading and it has a folded subtree below it,
19819 this function returns t, nil otherwise."
19820 (let ((re (cond
19821 ((eq what 'headlines) org-outline-regexp-bol)
19822 ((eq what 'items) (org-item-beginning-re))
19823 (t (error "This should not happen"))))
19824 beg end)
19825 (save-excursion
19826 (catch 'exit
19827 (unless (org-region-active-p)
19828 (setq beg (point-at-bol))
19829 (beginning-of-line 2)
19830 (while (and (not (eobp)) ;; this is like `next-line'
19831 (get-char-property (1- (point)) 'invisible))
19832 (beginning-of-line 2))
19833 (setq end (point))
19834 (goto-char beg)
19835 (goto-char (point-at-eol))
19836 (setq end (max end (point)))
19837 (while (re-search-forward re end t)
19838 (if (get-char-property (match-beginning 0) 'invisible)
19839 (throw 'exit t))))
19840 nil))))
19842 (defun org-metaup (&optional arg)
19843 "Move subtree up or move table row up.
19844 Calls `org-move-subtree-up' or `org-table-move-row' or
19845 `org-move-item-up', depending on context. See the individual commands
19846 for more information."
19847 (interactive "P")
19848 (cond
19849 ((run-hook-with-args-until-success 'org-metaup-hook))
19850 ((org-region-active-p)
19851 (let* ((a (min (region-beginning) (region-end)))
19852 (b (1- (max (region-beginning) (region-end))))
19853 (c (save-excursion (goto-char a)
19854 (move-beginning-of-line 0)))
19855 (d (save-excursion (goto-char a)
19856 (move-end-of-line 0) (point))))
19857 (transpose-regions a b c d)
19858 (goto-char c)))
19859 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19860 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19861 ((org-at-item-p) (call-interactively 'org-move-item-up))
19862 (t (org-drag-element-backward))))
19864 (defun org-metadown (&optional arg)
19865 "Move subtree down or move table row down.
19866 Calls `org-move-subtree-down' or `org-table-move-row' or
19867 `org-move-item-down', depending on context. See the individual
19868 commands for more information."
19869 (interactive "P")
19870 (cond
19871 ((run-hook-with-args-until-success 'org-metadown-hook))
19872 ((org-region-active-p)
19873 (let* ((a (min (region-beginning) (region-end)))
19874 (b (max (region-beginning) (region-end)))
19875 (c (save-excursion (goto-char b)
19876 (move-beginning-of-line 1)))
19877 (d (save-excursion (goto-char b)
19878 (move-end-of-line 1) (1+ (point)))))
19879 (transpose-regions a b c d)
19880 (goto-char d)))
19881 ((org-at-table-p) (call-interactively 'org-table-move-row))
19882 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19883 ((org-at-item-p) (call-interactively 'org-move-item-down))
19884 (t (org-drag-element-forward))))
19886 (defun org-shiftup (&optional arg)
19887 "Increase item in timestamp or increase priority of current headline.
19888 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19889 depending on context. See the individual commands for more information."
19890 (interactive "P")
19891 (cond
19892 ((run-hook-with-args-until-success 'org-shiftup-hook))
19893 ((and org-support-shift-select (org-region-active-p))
19894 (org-call-for-shift-select 'previous-line))
19895 ((org-at-timestamp-p t)
19896 (call-interactively (if org-edit-timestamp-down-means-later
19897 'org-timestamp-down 'org-timestamp-up)))
19898 ((and (not (eq org-support-shift-select 'always))
19899 org-enable-priority-commands
19900 (org-at-heading-p))
19901 (call-interactively 'org-priority-up))
19902 ((and (not org-support-shift-select) (org-at-item-p))
19903 (call-interactively 'org-previous-item))
19904 ((org-clocktable-try-shift 'up arg))
19905 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19906 (org-support-shift-select
19907 (org-call-for-shift-select 'previous-line))
19908 (t (org-shiftselect-error))))
19910 (defun org-shiftdown (&optional arg)
19911 "Decrease item in timestamp or decrease priority of current headline.
19912 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19913 depending on context. See the individual commands for more information."
19914 (interactive "P")
19915 (cond
19916 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19917 ((and org-support-shift-select (org-region-active-p))
19918 (org-call-for-shift-select 'next-line))
19919 ((org-at-timestamp-p t)
19920 (call-interactively (if org-edit-timestamp-down-means-later
19921 'org-timestamp-up 'org-timestamp-down)))
19922 ((and (not (eq org-support-shift-select 'always))
19923 org-enable-priority-commands
19924 (org-at-heading-p))
19925 (call-interactively 'org-priority-down))
19926 ((and (not org-support-shift-select) (org-at-item-p))
19927 (call-interactively 'org-next-item))
19928 ((org-clocktable-try-shift 'down arg))
19929 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19930 (org-support-shift-select
19931 (org-call-for-shift-select 'next-line))
19932 (t (org-shiftselect-error))))
19934 (defun org-shiftright (&optional arg)
19935 "Cycle the thing at point or in the current line, depending on context.
19936 Depending on context, this does one of the following:
19938 - switch a timestamp at point one day into the future
19939 - on a headline, switch to the next TODO keyword.
19940 - on an item, switch entire list to the next bullet type
19941 - on a property line, switch to the next allowed value
19942 - on a clocktable definition line, move time block into the future"
19943 (interactive "P")
19944 (cond
19945 ((run-hook-with-args-until-success 'org-shiftright-hook))
19946 ((and org-support-shift-select (org-region-active-p))
19947 (org-call-for-shift-select 'forward-char))
19948 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19949 ((and (not (eq org-support-shift-select 'always))
19950 (org-at-heading-p))
19951 (let ((org-inhibit-logging
19952 (not org-treat-S-cursor-todo-selection-as-state-change))
19953 (org-inhibit-blocking
19954 (not org-treat-S-cursor-todo-selection-as-state-change)))
19955 (org-call-with-arg 'org-todo 'right)))
19956 ((or (and org-support-shift-select
19957 (not (eq org-support-shift-select 'always))
19958 (org-at-item-bullet-p))
19959 (and (not org-support-shift-select) (org-at-item-p)))
19960 (org-call-with-arg 'org-cycle-list-bullet nil))
19961 ((and (not (eq org-support-shift-select 'always))
19962 (org-at-property-p))
19963 (call-interactively 'org-property-next-allowed-value))
19964 ((org-clocktable-try-shift 'right arg))
19965 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19966 (org-support-shift-select
19967 (org-call-for-shift-select 'forward-char))
19968 (t (org-shiftselect-error))))
19970 (defun org-shiftleft (&optional arg)
19971 "Cycle the thing at point or in the current line, depending on context.
19972 Depending on context, this does one of the following:
19974 - switch a timestamp at point one day into the past
19975 - on a headline, switch to the previous TODO keyword.
19976 - on an item, switch entire list to the previous bullet type
19977 - on a property line, switch to the previous allowed value
19978 - on a clocktable definition line, move time block into the past"
19979 (interactive "P")
19980 (cond
19981 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19982 ((and org-support-shift-select (org-region-active-p))
19983 (org-call-for-shift-select 'backward-char))
19984 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19985 ((and (not (eq org-support-shift-select 'always))
19986 (org-at-heading-p))
19987 (let ((org-inhibit-logging
19988 (not org-treat-S-cursor-todo-selection-as-state-change))
19989 (org-inhibit-blocking
19990 (not org-treat-S-cursor-todo-selection-as-state-change)))
19991 (org-call-with-arg 'org-todo 'left)))
19992 ((or (and org-support-shift-select
19993 (not (eq org-support-shift-select 'always))
19994 (org-at-item-bullet-p))
19995 (and (not org-support-shift-select) (org-at-item-p)))
19996 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19997 ((and (not (eq org-support-shift-select 'always))
19998 (org-at-property-p))
19999 (call-interactively 'org-property-previous-allowed-value))
20000 ((org-clocktable-try-shift 'left arg))
20001 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20002 (org-support-shift-select
20003 (org-call-for-shift-select 'backward-char))
20004 (t (org-shiftselect-error))))
20006 (defun org-shiftcontrolright ()
20007 "Switch to next TODO set."
20008 (interactive)
20009 (cond
20010 ((and org-support-shift-select (org-region-active-p))
20011 (org-call-for-shift-select 'forward-word))
20012 ((and (not (eq org-support-shift-select 'always))
20013 (org-at-heading-p))
20014 (org-call-with-arg 'org-todo 'nextset))
20015 (org-support-shift-select
20016 (org-call-for-shift-select 'forward-word))
20017 (t (org-shiftselect-error))))
20019 (defun org-shiftcontrolleft ()
20020 "Switch to previous TODO set."
20021 (interactive)
20022 (cond
20023 ((and org-support-shift-select (org-region-active-p))
20024 (org-call-for-shift-select 'backward-word))
20025 ((and (not (eq org-support-shift-select 'always))
20026 (org-at-heading-p))
20027 (org-call-with-arg 'org-todo 'previousset))
20028 (org-support-shift-select
20029 (org-call-for-shift-select 'backward-word))
20030 (t (org-shiftselect-error))))
20032 (defun org-shiftcontrolup (&optional n)
20033 "Change timestamps synchronously up in CLOCK log lines.
20034 Optional argument N tells to change by that many units."
20035 (interactive "P")
20036 (cond ((and (not org-support-shift-select)
20037 (org-at-clock-log-p)
20038 (org-at-timestamp-p t))
20039 (org-clock-timestamps-up n))
20040 (t (org-shiftselect-error))))
20042 (defun org-shiftcontroldown (&optional n)
20043 "Change timestamps synchronously down in CLOCK log lines.
20044 Optional argument N tells to change by that many units."
20045 (interactive "P")
20046 (cond ((and (not org-support-shift-select)
20047 (org-at-clock-log-p)
20048 (org-at-timestamp-p t))
20049 (org-clock-timestamps-down n))
20050 (t (org-shiftselect-error))))
20052 (defun org-ctrl-c-ret ()
20053 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20054 (interactive)
20055 (cond
20056 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20057 (t (call-interactively 'org-insert-heading))))
20059 (defun org-find-visible ()
20060 (let ((s (point)))
20061 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20062 (get-char-property s 'invisible)))
20064 (defun org-find-invisible ()
20065 (let ((s (point)))
20066 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20067 (not (get-char-property s 'invisible))))
20070 (defun org-copy-visible (beg end)
20071 "Copy the visible parts of the region."
20072 (interactive "r")
20073 (let (snippets s)
20074 (save-excursion
20075 (save-restriction
20076 (narrow-to-region beg end)
20077 (setq s (goto-char (point-min)))
20078 (while (not (= (point) (point-max)))
20079 (goto-char (org-find-invisible))
20080 (push (buffer-substring s (point)) snippets)
20081 (setq s (goto-char (org-find-visible))))))
20082 (kill-new (apply 'concat (nreverse snippets)))))
20084 (defun org-copy-special ()
20085 "Copy region in table or copy current subtree.
20086 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20087 See the individual commands for more information."
20088 (interactive)
20089 (call-interactively
20090 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20092 (defun org-cut-special ()
20093 "Cut region in table or cut current subtree.
20094 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20095 See the individual commands for more information."
20096 (interactive)
20097 (call-interactively
20098 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20100 (defun org-paste-special (arg)
20101 "Paste rectangular region into table, or past subtree relative to level.
20102 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20103 See the individual commands for more information."
20104 (interactive "P")
20105 (if (org-at-table-p)
20106 (org-table-paste-rectangle)
20107 (org-paste-subtree arg)))
20109 (defsubst org-in-fixed-width-region-p ()
20110 "Is point in a fixed-width region?"
20111 (save-match-data
20112 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20114 (defun org-edit-special (&optional arg)
20115 "Call a special editor for the element at point.
20116 When at a table, call the formula editor with `org-table-edit-formulas'.
20117 When in a source code block, call `org-edit-src-code'.
20118 When in a fixed-width region, call `org-edit-fixed-width-region'.
20119 When at an #+INCLUDE keyword, visit the included file.
20120 On a link, call `ffap' to visit the link at point.
20121 Otherwise, return a user error."
20122 (interactive "P")
20123 (let ((element (org-element-at-point)))
20124 (assert (not buffer-read-only) nil
20125 "Buffer is read-only: %s" (buffer-name))
20126 (case (org-element-type element)
20127 (src-block
20128 (if (not arg) (org-edit-src-code)
20129 (let* ((info (org-babel-get-src-block-info))
20130 (lang (nth 0 info))
20131 (params (nth 2 info))
20132 (session (cdr (assq :session params))))
20133 (if (not session) (org-edit-src-code)
20134 ;; At a src-block with a session and function called with
20135 ;; an ARG: switch to the buffer related to the inferior
20136 ;; process.
20137 (switch-to-buffer
20138 (funcall (intern (concat "org-babel-prep-session:" lang))
20139 session params))))))
20140 (keyword
20141 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20142 (find-file
20143 (org-remove-double-quotes
20144 (car (org-split-string (org-element-property :value element)))))
20145 (user-error "No special environment to edit here")))
20146 (table
20147 (if (eq (org-element-property :type element) 'table.el)
20148 (org-edit-src-code)
20149 (call-interactively 'org-table-edit-formulas)))
20150 ;; Only Org tables contain `table-row' type elements.
20151 (table-row (call-interactively 'org-table-edit-formulas))
20152 ((example-block export-block) (org-edit-src-code))
20153 (fixed-width (org-edit-fixed-width-region))
20154 (otherwise
20155 ;; No notable element at point. Though, we may be at a link,
20156 ;; which is an object. Thus, scan deeper.
20157 (if (eq (org-element-type (org-element-context element)) 'link)
20158 (call-interactively 'ffap)
20159 (user-error "No special environment to edit here"))))))
20161 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20162 (defun org-ctrl-c-ctrl-c (&optional arg)
20163 "Set tags in headline, or update according to changed information at point.
20165 This command does many different things, depending on context:
20167 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20168 this is what we do.
20170 - If the cursor is on a statistics cookie, update it.
20172 - If the cursor is in a headline, prompt for tags and insert them
20173 into the current line, aligned to `org-tags-column'. When called
20174 with prefix arg, realign all tags in the current buffer.
20176 - If the cursor is in one of the special #+KEYWORD lines, this
20177 triggers scanning the buffer for these lines and updating the
20178 information.
20180 - If the cursor is inside a table, realign the table. This command
20181 works even if the automatic table editor has been turned off.
20183 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20184 the entire table.
20186 - If the cursor is at a footnote reference or definition, jump to
20187 the corresponding definition or references, respectively.
20189 - If the cursor is a the beginning of a dynamic block, update it.
20191 - If the current buffer is a capture buffer, close note and file it.
20193 - If the cursor is on a <<<target>>>, update radio targets and
20194 corresponding links in this buffer.
20196 - If the cursor is on a numbered item in a plain list, renumber the
20197 ordered list.
20199 - If the cursor is on a checkbox, toggle it.
20201 - If the cursor is on a code block, evaluate it. The variable
20202 `org-confirm-babel-evaluate' can be used to control prompting
20203 before code block evaluation, by default every code block
20204 evaluation requires confirmation. Code block evaluation can be
20205 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20206 (interactive "P")
20207 (cond
20208 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20209 org-occur-highlights
20210 org-latex-fragment-image-overlays)
20211 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20212 (org-remove-occur-highlights)
20213 (org-remove-latex-fragment-image-overlays)
20214 (message "Temporary highlights/overlays removed from current buffer"))
20215 ((and (local-variable-p 'org-finish-function (current-buffer))
20216 (fboundp org-finish-function))
20217 (funcall org-finish-function))
20218 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20220 (let* ((context (org-element-context)) (type (org-element-type context)))
20221 ;; Test if point is within a blank line.
20222 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20223 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20224 (user-error "C-c C-c can do nothing useful at this location"))
20225 ;; When at a link, act according to the parent instead.
20226 (when (eq type 'link)
20227 (setq context (org-element-property :parent context))
20228 (setq type (org-element-type context)))
20229 ;; For convenience: at the first line of a paragraph on the
20230 ;; same line as an item, apply function on that item instead.
20231 (when (eq type 'paragraph)
20232 (let ((parent (org-element-property :parent context)))
20233 (when (and (eq (org-element-type parent) 'item)
20234 (= (point-at-bol) (org-element-property :begin parent)))
20235 (setq context parent type 'item))))
20236 ;; Act according to type of element or object at point.
20237 (case type
20238 (clock (org-clock-update-time-maybe))
20239 (dynamic-block
20240 (save-excursion
20241 (goto-char (org-element-property :post-affiliated context))
20242 (org-update-dblock)))
20243 (footnote-definition
20244 (goto-char (org-element-property :post-affiliated context))
20245 (call-interactively 'org-footnote-action))
20246 (footnote-reference (call-interactively 'org-footnote-action))
20247 ((headline inlinetask)
20248 (save-excursion (goto-char (org-element-property :begin context))
20249 (call-interactively 'org-set-tags)))
20250 (item
20251 ;; At an item: a double C-u set checkbox to "[-]"
20252 ;; unconditionally, whereas a single one will toggle its
20253 ;; presence. Without an universal argument, if the item
20254 ;; has a checkbox, toggle it. Otherwise repair the list.
20255 (let* ((box (org-element-property :checkbox context))
20256 (struct (org-element-property :structure context))
20257 (old-struct (copy-tree struct))
20258 (parents (org-list-parents-alist struct))
20259 (prevs (org-list-prevs-alist struct))
20260 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20261 (org-list-set-checkbox
20262 (org-element-property :begin context) struct
20263 (cond ((equal arg '(16)) "[-]")
20264 ((and (not box) (equal arg '(4))) "[ ]")
20265 ((or (not box) (equal arg '(4))) nil)
20266 ((eq box 'on) "[ ]")
20267 (t "[X]")))
20268 ;; Mimic `org-list-write-struct' but with grabbing
20269 ;; a return value from `org-list-struct-fix-box'.
20270 (org-list-struct-fix-ind struct parents 2)
20271 (org-list-struct-fix-item-end struct)
20272 (org-list-struct-fix-bul struct prevs)
20273 (org-list-struct-fix-ind struct parents)
20274 (let ((block-item
20275 (org-list-struct-fix-box struct parents prevs orderedp)))
20276 (if (and box (equal struct old-struct))
20277 (if (equal arg '(16))
20278 (message "Checkboxes already reset")
20279 (user-error "Cannot toggle this checkbox: %s"
20280 (if (eq box 'on)
20281 "all subitems checked"
20282 "unchecked subitems")))
20283 (org-list-struct-apply-struct struct old-struct)
20284 (org-update-checkbox-count-maybe))
20285 (when block-item
20286 (message "Checkboxes were removed due to empty box at line %d"
20287 (org-current-line block-item))))))
20288 (keyword
20289 (let ((org-inhibit-startup-visibility-stuff t)
20290 (org-startup-align-all-tables nil))
20291 (when (boundp 'org-table-coordinate-overlays)
20292 (mapc 'delete-overlay org-table-coordinate-overlays)
20293 (setq org-table-coordinate-overlays nil))
20294 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20295 (message "Local setup has been refreshed"))
20296 (plain-list
20297 ;; At a plain list, with a double C-u argument, set
20298 ;; checkboxes of each item to "[-]", whereas a single one
20299 ;; will toggle their presence according to the state of the
20300 ;; first item in the list. Without an argument, repair the
20301 ;; list.
20302 (let* ((begin (org-element-property :contents-begin context))
20303 (beginm (move-marker (make-marker) begin))
20304 (struct (org-element-property :structure context))
20305 (old-struct (copy-tree struct))
20306 (first-box (save-excursion
20307 (goto-char begin)
20308 (looking-at org-list-full-item-re)
20309 (match-string-no-properties 3)))
20310 (new-box (cond ((equal arg '(16)) "[-]")
20311 ((equal arg '(4)) (unless first-box "[ ]"))
20312 ((equal first-box "[X]") "[ ]")
20313 (t "[X]"))))
20314 (cond
20315 (arg
20316 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20317 (org-list-get-all-items
20318 begin struct (org-list-prevs-alist struct))))
20319 ((and first-box (eq (point) begin))
20320 ;; For convenience, when point is at bol on the first
20321 ;; item of the list and no argument is provided, simply
20322 ;; toggle checkbox of that item, if any.
20323 (org-list-set-checkbox begin struct new-box)))
20324 (org-list-write-struct
20325 struct (org-list-parents-alist struct) old-struct)
20326 (org-update-checkbox-count-maybe)
20327 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20328 ((property-drawer node-property)
20329 (call-interactively 'org-property-action))
20330 ((radio-target target)
20331 (call-interactively 'org-update-radio-target-regexp))
20332 (statistics-cookie
20333 (call-interactively 'org-update-statistics-cookies))
20334 ((table table-cell table-row)
20335 ;; At a table, recalculate every field and align it. Also
20336 ;; send the table if necessary. If the table has
20337 ;; a `table.el' type, just give up. At a table row or
20338 ;; cell, maybe recalculate line but always align table.
20339 (if (eq (org-element-property :type context) 'table.el)
20340 (message "Use C-c ' to edit table.el tables")
20341 (let ((org-enable-table-editor t))
20342 (if (or (eq type 'table)
20343 ;; Check if point is at a TBLFM line.
20344 (and (eq type 'table-row)
20345 (= (point) (org-element-property :end context))))
20346 (save-excursion
20347 (if (org-at-TBLFM-p)
20348 (progn (require 'org-table)
20349 (org-table-calc-current-TBLFM))
20350 (goto-char (org-element-property :contents-begin context))
20351 (org-call-with-arg 'org-table-recalculate (or arg t))
20352 (orgtbl-send-table 'maybe)))
20353 (org-table-maybe-eval-formula)
20354 (cond (arg (call-interactively 'org-table-recalculate))
20355 ((org-table-maybe-recalculate-line))
20356 (t (org-table-align)))))))
20357 (timestamp (org-timestamp-change 0 'day))
20358 (otherwise
20359 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20360 (user-error
20361 "C-c C-c can do nothing useful at this location")))))))))
20363 (defun org-mode-restart ()
20364 "Restart Org-mode, to scan again for special lines.
20365 Also updates the keyword regular expressions."
20366 (interactive)
20367 (org-mode)
20368 (message "Org-mode restarted"))
20370 (defun org-kill-note-or-show-branches ()
20371 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20372 (interactive)
20373 (if (not org-finish-function)
20374 (progn
20375 (hide-subtree)
20376 (call-interactively 'show-branches))
20377 (let ((org-note-abort t))
20378 (funcall org-finish-function))))
20380 (defun org-open-line (n)
20381 "Insert a new row in tables, call `open-line' elsewhere.
20382 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20383 (interactive "*p")
20384 (cond
20385 ((not org-special-ctrl-o)
20386 (open-line n))
20387 ((org-at-table-p)
20388 (org-table-insert-row))
20390 (open-line n))))
20392 (defun org-return (&optional indent)
20393 "Goto next table row or insert a newline.
20394 Calls `org-table-next-row' or `newline', depending on context.
20395 See the individual commands for more information."
20396 (interactive)
20397 (let (org-ts-what)
20398 (cond
20399 ((or (bobp) (org-in-src-block-p))
20400 (if indent (newline-and-indent) (newline)))
20401 ((org-at-table-p)
20402 (org-table-justify-field-maybe)
20403 (call-interactively 'org-table-next-row))
20404 ;; when `newline-and-indent' is called within a list, make sure
20405 ;; text moved stays inside the item.
20406 ((and (org-in-item-p) indent)
20407 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20408 (progn
20409 (save-match-data (newline))
20410 (org-indent-line-to (length (match-string 0))))
20411 (let ((ind (org-get-indentation)))
20412 (newline)
20413 (if (org-looking-back org-list-end-re)
20414 (org-indent-line)
20415 (org-indent-line-to ind)))))
20416 ((and org-return-follows-link
20417 (org-at-timestamp-p t)
20418 (not (eq org-ts-what 'after)))
20419 (org-follow-timestamp-link))
20420 ((and org-return-follows-link
20421 (let ((tprop (get-text-property (point) 'face)))
20422 (or (eq tprop 'org-link)
20423 (and (listp tprop) (memq 'org-link tprop)))))
20424 (call-interactively 'org-open-at-point))
20425 ((and (org-at-heading-p)
20426 (looking-at
20427 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20428 (org-show-entry)
20429 (end-of-line 1)
20430 (newline))
20431 (t (if indent (newline-and-indent) (newline))))))
20433 (defun org-return-indent ()
20434 "Goto next table row or insert a newline and indent.
20435 Calls `org-table-next-row' or `newline-and-indent', depending on
20436 context. See the individual commands for more information."
20437 (interactive)
20438 (org-return t))
20440 (defun org-ctrl-c-star ()
20441 "Compute table, or change heading status of lines.
20442 Calls `org-table-recalculate' or `org-toggle-heading',
20443 depending on context."
20444 (interactive)
20445 (cond
20446 ((org-at-table-p)
20447 (call-interactively 'org-table-recalculate))
20449 ;; Convert all lines in region to list items
20450 (call-interactively 'org-toggle-heading))))
20452 (defun org-ctrl-c-minus ()
20453 "Insert separator line in table or modify bullet status of line.
20454 Also turns a plain line or a region of lines into list items.
20455 Calls `org-table-insert-hline', `org-toggle-item', or
20456 `org-cycle-list-bullet', depending on context."
20457 (interactive)
20458 (cond
20459 ((org-at-table-p)
20460 (call-interactively 'org-table-insert-hline))
20461 ((org-region-active-p)
20462 (call-interactively 'org-toggle-item))
20463 ((org-in-item-p)
20464 (call-interactively 'org-cycle-list-bullet))
20466 (call-interactively 'org-toggle-item))))
20468 (defun org-toggle-item (arg)
20469 "Convert headings or normal lines to items, items to normal lines.
20470 If there is no active region, only the current line is considered.
20472 If the first non blank line in the region is a headline, convert
20473 all headlines to items, shifting text accordingly.
20475 If it is an item, convert all items to normal lines.
20477 If it is normal text, change region into a list of items.
20478 With a prefix argument ARG, change the region in a single item."
20479 (interactive "P")
20480 (let ((shift-text
20481 (function
20482 ;; Shift text in current section to IND, from point to END.
20483 ;; The function leaves point to END line.
20484 (lambda (ind end)
20485 (let ((min-i 1000) (end (copy-marker end)))
20486 ;; First determine the minimum indentation (MIN-I) of
20487 ;; the text.
20488 (save-excursion
20489 (catch 'exit
20490 (while (< (point) end)
20491 (let ((i (org-get-indentation)))
20492 (cond
20493 ;; Skip blank lines and inline tasks.
20494 ((looking-at "^[ \t]*$"))
20495 ((looking-at org-outline-regexp-bol))
20496 ;; We can't find less than 0 indentation.
20497 ((zerop i) (throw 'exit (setq min-i 0)))
20498 ((< i min-i) (setq min-i i))))
20499 (forward-line))))
20500 ;; Then indent each line so that a line indented to
20501 ;; MIN-I becomes indented to IND. Ignore blank lines
20502 ;; and inline tasks in the process.
20503 (let ((delta (- ind min-i)))
20504 (while (< (point) end)
20505 (unless (or (looking-at "^[ \t]*$")
20506 (looking-at org-outline-regexp-bol))
20507 (org-indent-line-to (+ (org-get-indentation) delta)))
20508 (forward-line)))))))
20509 (skip-blanks
20510 (function
20511 ;; Return beginning of first non-blank line, starting from
20512 ;; line at POS.
20513 (lambda (pos)
20514 (save-excursion
20515 (goto-char pos)
20516 (skip-chars-forward " \r\t\n")
20517 (point-at-bol)))))
20518 beg end)
20519 ;; Determine boundaries of changes.
20520 (if (org-region-active-p)
20521 (setq beg (funcall skip-blanks (region-beginning))
20522 end (copy-marker (region-end)))
20523 (setq beg (funcall skip-blanks (point-at-bol))
20524 end (copy-marker (point-at-eol))))
20525 ;; Depending on the starting line, choose an action on the text
20526 ;; between BEG and END.
20527 (org-with-limited-levels
20528 (save-excursion
20529 (goto-char beg)
20530 (cond
20531 ;; Case 1. Start at an item: de-itemize. Note that it only
20532 ;; happens when a region is active: `org-ctrl-c-minus'
20533 ;; would call `org-cycle-list-bullet' otherwise.
20534 ((org-at-item-p)
20535 (while (< (point) end)
20536 (when (org-at-item-p)
20537 (skip-chars-forward " \t")
20538 (delete-region (point) (match-end 0)))
20539 (forward-line)))
20540 ;; Case 2. Start at an heading: convert to items.
20541 ((org-at-heading-p)
20542 (let* ((bul (org-list-bullet-string "-"))
20543 (bul-len (length bul))
20544 ;; Indentation of the first heading. It should be
20545 ;; relative to the indentation of its parent, if any.
20546 (start-ind (save-excursion
20547 (cond
20548 ((not org-adapt-indentation) 0)
20549 ((not (outline-previous-heading)) 0)
20550 (t (length (match-string 0))))))
20551 ;; Level of first heading. Further headings will be
20552 ;; compared to it to determine hierarchy in the list.
20553 (ref-level (org-reduced-level (org-outline-level))))
20554 (while (< (point) end)
20555 (let* ((level (org-reduced-level (org-outline-level)))
20556 (delta (max 0 (- level ref-level))))
20557 ;; If current headline is less indented than the first
20558 ;; one, set it as reference, in order to preserve
20559 ;; subtrees.
20560 (when (< level ref-level) (setq ref-level level))
20561 (replace-match bul t t)
20562 (org-indent-line-to (+ start-ind (* delta bul-len)))
20563 ;; Ensure all text down to END (or SECTION-END) belongs
20564 ;; to the newly created item.
20565 (let ((section-end (save-excursion
20566 (or (outline-next-heading) (point)))))
20567 (forward-line)
20568 (funcall shift-text
20569 (+ start-ind (* (1+ delta) bul-len))
20570 (min end section-end)))))))
20571 ;; Case 3. Normal line with ARG: make the first line of region
20572 ;; an item, and shift indentation of others lines to
20573 ;; set them as item's body.
20574 (arg (let* ((bul (org-list-bullet-string "-"))
20575 (bul-len (length bul))
20576 (ref-ind (org-get-indentation)))
20577 (skip-chars-forward " \t")
20578 (insert bul)
20579 (forward-line)
20580 (while (< (point) end)
20581 ;; Ensure that lines less indented than first one
20582 ;; still get included in item body.
20583 (funcall shift-text
20584 (+ ref-ind bul-len)
20585 (min end (save-excursion (or (outline-next-heading)
20586 (point)))))
20587 (forward-line))))
20588 ;; Case 4. Normal line without ARG: turn each non-item line
20589 ;; into an item.
20591 (while (< (point) end)
20592 (unless (or (org-at-heading-p) (org-at-item-p))
20593 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20594 (replace-match
20595 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20596 (forward-line))))))))
20598 (defun org-toggle-heading (&optional nstars)
20599 "Convert headings to normal text, or items or text to headings.
20600 If there is no active region, only convert the current line.
20602 With a \\[universal-argument] prefix, convert the whole list at
20603 point into heading.
20605 In a region:
20607 - If the first non blank line is a headline, remove the stars
20608 from all headlines in the region.
20610 - If it is a normal line, turn each and every normal line (i.e.,
20611 not an heading or an item) in the region into headings. If you
20612 want to convert only the first line of this region, use one
20613 universal prefix argument.
20615 - If it is a plain list item, turn all plain list items into headings.
20617 When converting a line into a heading, the number of stars is chosen
20618 such that the lines become children of the current entry. However,
20619 when a numeric prefix argument is given, its value determines the
20620 number of stars to add."
20621 (interactive "P")
20622 (let ((skip-blanks
20623 (function
20624 ;; Return beginning of first non-blank line, starting from
20625 ;; line at POS.
20626 (lambda (pos)
20627 (save-excursion
20628 (goto-char pos)
20629 (while (org-at-comment-p) (forward-line))
20630 (skip-chars-forward " \r\t\n")
20631 (point-at-bol)))))
20632 beg end toggled)
20633 ;; Determine boundaries of changes. If a universal prefix has
20634 ;; been given, put the list in a region. If region ends at a bol,
20635 ;; do not consider the last line to be in the region.
20637 (when (and current-prefix-arg (org-at-item-p))
20638 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20639 (org-mark-element))
20641 (if (org-region-active-p)
20642 (setq beg (funcall skip-blanks (region-beginning))
20643 end (copy-marker (save-excursion
20644 (goto-char (region-end))
20645 (if (bolp) (point) (point-at-eol)))))
20646 (setq beg (funcall skip-blanks (point-at-bol))
20647 end (copy-marker (point-at-eol))))
20648 ;; Ensure inline tasks don't count as headings.
20649 (org-with-limited-levels
20650 (save-excursion
20651 (goto-char beg)
20652 (cond
20653 ;; Case 1. Started at an heading: de-star headings.
20654 ((org-at-heading-p)
20655 (while (< (point) end)
20656 (when (org-at-heading-p t)
20657 (looking-at org-outline-regexp) (replace-match "")
20658 (setq toggled t))
20659 (forward-line)))
20660 ;; Case 2. Started at an item: change items into headlines.
20661 ;; One star will be added by `org-list-to-subtree'.
20662 ((org-at-item-p)
20663 (let* ((stars (make-string
20664 ;; subtract the star that will be added again by
20665 ;; `org-list-to-subtree'
20666 (if (numberp nstars) (1- nstars)
20667 (or (org-current-level) 0))
20668 ?*))
20669 (add-stars
20670 (cond (nstars "") ; stars from prefix only
20671 ((equal stars "") "") ; before first heading
20672 (org-odd-levels-only "*") ; inside heading, odd
20673 (t "")))) ; inside heading, oddeven
20674 (while (< (point) end)
20675 (when (org-at-item-p)
20676 ;; Pay attention to cases when region ends before list.
20677 (let* ((struct (org-list-struct))
20678 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20679 (save-restriction
20680 (narrow-to-region (point) list-end)
20681 (insert
20682 (org-list-to-subtree
20683 (org-list-parse-list t)
20684 '(:istart (concat stars add-stars (funcall get-stars depth))
20685 :icount (concat stars add-stars (funcall get-stars depth)))))))
20686 (setq toggled t))
20687 (forward-line))))
20688 ;; Case 3. Started at normal text: make every line an heading,
20689 ;; skipping headlines and items.
20690 (t (let* ((stars
20691 (make-string
20692 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20693 (add-stars
20694 (cond (nstars "") ; stars from prefix only
20695 ((equal stars "") "*") ; before first heading
20696 (org-odd-levels-only "**") ; inside heading, odd
20697 (t "*"))) ; inside heading, oddeven
20698 (rpl (concat stars add-stars " "))
20699 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20700 (while (< (point) (if (equal nstars '(4)) lend end))
20701 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20702 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20703 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20704 (forward-line)))))))
20705 (unless toggled (message "Cannot toggle heading from here"))))
20707 (defun org-meta-return (&optional arg)
20708 "Insert a new heading or wrap a region in a table.
20709 Calls `org-insert-heading' or `org-table-wrap-region', depending
20710 on context. See the individual commands for more information."
20711 (interactive "P")
20712 (org-check-before-invisible-edit 'insert)
20713 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20714 (let* ((element (org-element-at-point))
20715 (type (org-element-type element)))
20716 (when (eq type 'table-row)
20717 (setq element (org-element-property :parent element))
20718 (setq type 'table))
20719 (if (and (eq type 'table)
20720 (eq (org-element-property :type element) 'org)
20721 (>= (point) (org-element-property :contents-begin element))
20722 (< (point) (org-element-property :contents-end element)))
20723 (call-interactively 'org-table-wrap-region)
20724 (call-interactively 'org-insert-heading)))))
20726 ;;; Menu entries
20728 (defsubst org-in-subtree-not-table-p ()
20729 "Are we in a subtree and not in a table?"
20730 (and (not (org-before-first-heading-p))
20731 (not (org-at-table-p))))
20733 ;; Define the Org-mode menus
20734 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20735 '("Tbl"
20736 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20737 ["Next Field" org-cycle (org-at-table-p)]
20738 ["Previous Field" org-shifttab (org-at-table-p)]
20739 ["Next Row" org-return (org-at-table-p)]
20740 "--"
20741 ["Blank Field" org-table-blank-field (org-at-table-p)]
20742 ["Edit Field" org-table-edit-field (org-at-table-p)]
20743 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20744 "--"
20745 ("Column"
20746 ["Move Column Left" org-metaleft (org-at-table-p)]
20747 ["Move Column Right" org-metaright (org-at-table-p)]
20748 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20749 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20750 ("Row"
20751 ["Move Row Up" org-metaup (org-at-table-p)]
20752 ["Move Row Down" org-metadown (org-at-table-p)]
20753 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20754 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20755 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20756 "--"
20757 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20758 ("Rectangle"
20759 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20760 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20761 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20762 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20763 "--"
20764 ("Calculate"
20765 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20766 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20767 ["Edit Formulas" org-edit-special (org-at-table-p)]
20768 "--"
20769 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20770 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20771 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20772 "--"
20773 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20774 "--"
20775 ["Sum Column/Rectangle" org-table-sum
20776 (or (org-at-table-p) (org-region-active-p))]
20777 ["Which Column?" org-table-current-column (org-at-table-p)])
20778 ["Debug Formulas"
20779 org-table-toggle-formula-debugger
20780 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20781 ["Show Col/Row Numbers"
20782 org-table-toggle-coordinate-overlays
20783 :style toggle
20784 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20785 "--"
20786 ["Create" org-table-create (and (not (org-at-table-p))
20787 org-enable-table-editor)]
20788 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20789 ["Import from File" org-table-import (not (org-at-table-p))]
20790 ["Export to File" org-table-export (org-at-table-p)]
20791 "--"
20792 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20794 (easy-menu-define org-org-menu org-mode-map "Org menu"
20795 '("Org"
20796 ("Show/Hide"
20797 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20798 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20799 ["Sparse Tree..." org-sparse-tree t]
20800 ["Reveal Context" org-reveal t]
20801 ["Show All" show-all t]
20802 "--"
20803 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20804 "--"
20805 ["New Heading" org-insert-heading t]
20806 ("Navigate Headings"
20807 ["Up" outline-up-heading t]
20808 ["Next" outline-next-visible-heading t]
20809 ["Previous" outline-previous-visible-heading t]
20810 ["Next Same Level" outline-forward-same-level t]
20811 ["Previous Same Level" outline-backward-same-level t]
20812 "--"
20813 ["Jump" org-goto t])
20814 ("Edit Structure"
20815 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20816 "--"
20817 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20818 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20819 "--"
20820 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20821 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20822 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20823 "--"
20824 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20825 "--"
20826 ["Copy visible text" org-copy-visible t]
20827 "--"
20828 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20829 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20830 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20831 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20832 "--"
20833 ["Sort Region/Children" org-sort t]
20834 "--"
20835 ["Convert to odd levels" org-convert-to-odd-levels t]
20836 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20837 ("Editing"
20838 ["Emphasis..." org-emphasize t]
20839 ["Edit Source Example" org-edit-special t]
20840 "--"
20841 ["Footnote new/jump" org-footnote-action t]
20842 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20843 ("Archive"
20844 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20845 "--"
20846 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20847 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20848 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20850 "--"
20851 ("Hyperlinks"
20852 ["Store Link (Global)" org-store-link t]
20853 ["Find existing link to here" org-occur-link-in-agenda-files t]
20854 ["Insert Link" org-insert-link t]
20855 ["Follow Link" org-open-at-point t]
20856 "--"
20857 ["Next link" org-next-link t]
20858 ["Previous link" org-previous-link t]
20859 "--"
20860 ["Descriptive Links"
20861 org-toggle-link-display
20862 :style radio
20863 :selected org-descriptive-links
20865 ["Literal Links"
20866 org-toggle-link-display
20867 :style radio
20868 :selected (not org-descriptive-links)])
20869 "--"
20870 ("TODO Lists"
20871 ["TODO/DONE/-" org-todo t]
20872 ("Select keyword"
20873 ["Next keyword" org-shiftright (org-at-heading-p)]
20874 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20875 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20876 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20877 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20878 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20879 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20880 "--"
20881 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20882 :selected org-enforce-todo-dependencies :style toggle :active t]
20883 "Settings for tree at point"
20884 ["Do Children sequentially" org-toggle-ordered-property :style radio
20885 :selected (org-entry-get nil "ORDERED")
20886 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20887 ["Do Children parallel" org-toggle-ordered-property :style radio
20888 :selected (not (org-entry-get nil "ORDERED"))
20889 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20890 "--"
20891 ["Set Priority" org-priority t]
20892 ["Priority Up" org-shiftup t]
20893 ["Priority Down" org-shiftdown t]
20894 "--"
20895 ["Get news from all feeds" org-feed-update-all t]
20896 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20897 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20898 ("TAGS and Properties"
20899 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20900 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20901 "--"
20902 ["Set property" org-set-property (not (org-before-first-heading-p))]
20903 ["Column view of properties" org-columns t]
20904 ["Insert Column View DBlock" org-insert-columns-dblock t])
20905 ("Dates and Scheduling"
20906 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20907 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20908 ("Change Date"
20909 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20910 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20911 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20912 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20913 ["Compute Time Range" org-evaluate-time-range t]
20914 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20915 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20916 "--"
20917 ["Custom time format" org-toggle-time-stamp-overlays
20918 :style radio :selected org-display-custom-times]
20919 "--"
20920 ["Goto Calendar" org-goto-calendar t]
20921 ["Date from Calendar" org-date-from-calendar t]
20922 "--"
20923 ["Start/Restart Timer" org-timer-start t]
20924 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20925 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20926 ["Insert Timer String" org-timer t]
20927 ["Insert Timer Item" org-timer-item t])
20928 ("Logging work"
20929 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20930 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20931 ["Clock out" org-clock-out t]
20932 ["Clock cancel" org-clock-cancel t]
20933 "--"
20934 ["Mark as default task" org-clock-mark-default-task t]
20935 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20936 ["Goto running clock" org-clock-goto t]
20937 "--"
20938 ["Display times" org-clock-display t]
20939 ["Create clock table" org-clock-report t]
20940 "--"
20941 ["Record DONE time"
20942 (progn (setq org-log-done (not org-log-done))
20943 (message "Switching to %s will %s record a timestamp"
20944 (car org-done-keywords)
20945 (if org-log-done "automatically" "not")))
20946 :style toggle :selected org-log-done])
20947 "--"
20948 ["Agenda Command..." org-agenda t]
20949 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20950 ("File List for Agenda")
20951 ("Special views current file"
20952 ["TODO Tree" org-show-todo-tree t]
20953 ["Check Deadlines" org-check-deadlines t]
20954 ["Timeline" org-timeline t]
20955 ["Tags/Property tree" org-match-sparse-tree t])
20956 "--"
20957 ["Export/Publish..." org-export-dispatch t]
20958 ("LaTeX"
20959 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20960 :selected org-cdlatex-mode]
20961 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20962 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20963 ["Modify math symbol" org-cdlatex-math-modify
20964 (org-inside-LaTeX-fragment-p)]
20965 ["Insert citation" org-reftex-citation t]
20966 "--"
20967 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20968 "--"
20969 ("MobileOrg"
20970 ["Push Files and Views" org-mobile-push t]
20971 ["Get Captured and Flagged" org-mobile-pull t]
20972 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20973 "--"
20974 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20975 "--"
20976 ("Documentation"
20977 ["Show Version" org-version t]
20978 ["Info Documentation" org-info t])
20979 ("Customize"
20980 ["Browse Org Group" org-customize t]
20981 "--"
20982 ["Expand This Menu" org-create-customize-menu
20983 (fboundp 'customize-menu-create)])
20984 ["Send bug report" org-submit-bug-report t]
20985 "--"
20986 ("Refresh/Reload"
20987 ["Refresh setup current buffer" org-mode-restart t]
20988 ["Reload Org (after update)" org-reload t]
20989 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20992 (defun org-info (&optional node)
20993 "Read documentation for Org-mode in the info system.
20994 With optional NODE, go directly to that node."
20995 (interactive)
20996 (info (format "(org)%s" (or node ""))))
20998 ;;;###autoload
20999 (defun org-submit-bug-report ()
21000 "Submit a bug report on Org-mode via mail.
21002 Don't hesitate to report any problems or inaccurate documentation.
21004 If you don't have setup sending mail from (X)Emacs, please copy the
21005 output buffer into your mail program, as it gives us important
21006 information about your Org-mode version and configuration."
21007 (interactive)
21008 (require 'reporter)
21009 (org-load-modules-maybe)
21010 (org-require-autoloaded-modules)
21011 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21012 (reporter-submit-bug-report
21013 "emacs-orgmode@gnu.org"
21014 (org-version nil 'full)
21015 (let (list)
21016 (save-window-excursion
21017 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21018 (delete-other-windows)
21019 (erase-buffer)
21020 (insert "You are about to submit a bug report to the Org-mode mailing list.
21022 We would like to add your full Org-mode and Outline configuration to the
21023 bug report. This greatly simplifies the work of the maintainer and
21024 other experts on the mailing list.
21026 HOWEVER, some variables you have customized may contain private
21027 information. The names of customers, colleagues, or friends, might
21028 appear in the form of file names, tags, todo states, or search strings.
21029 If you answer yes to the prompt, you might want to check and remove
21030 such private information before sending the email.")
21031 (add-text-properties (point-min) (point-max) '(face org-warning))
21032 (when (yes-or-no-p "Include your Org-mode configuration ")
21033 (mapatoms
21034 (lambda (v)
21035 (and (boundp v)
21036 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21037 (or (and (symbol-value v)
21038 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21039 (and
21040 (get v 'custom-type) (get v 'standard-value)
21041 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21042 (push v list)))))
21043 (kill-buffer (get-buffer "*Warn about privacy*"))
21044 list))
21045 nil nil
21046 "Remember to cover the basics, that is, what you expected to happen and
21047 what in fact did happen. You don't know how to make a good report? See
21049 http://orgmode.org/manual/Feedback.html#Feedback
21051 Your bug report will be posted to the Org-mode mailing list.
21052 ------------------------------------------------------------------------")
21053 (save-excursion
21054 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21055 (replace-match "\\1Bug: \\3 [\\2]")))))
21058 (defun org-install-agenda-files-menu ()
21059 (let ((bl (buffer-list)))
21060 (save-excursion
21061 (while bl
21062 (set-buffer (pop bl))
21063 (if (derived-mode-p 'org-mode) (setq bl nil)))
21064 (when (derived-mode-p 'org-mode)
21065 (easy-menu-change
21066 '("Org") "File List for Agenda"
21067 (append
21068 (list
21069 ["Edit File List" (org-edit-agenda-file-list) t]
21070 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21071 ["Remove Current File from List" org-remove-file t]
21072 ["Cycle through agenda files" org-cycle-agenda-files t]
21073 ["Occur in all agenda files" org-occur-in-agenda-files t]
21074 "--")
21075 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21077 ;;;; Documentation
21079 (defun org-require-autoloaded-modules ()
21080 (interactive)
21081 (mapc 'require
21082 '(org-agenda org-archive org-attach org-clock org-colview org-id
21083 org-remember org-table org-timer)))
21085 ;;;###autoload
21086 (defun org-reload (&optional uncompiled)
21087 "Reload all org lisp files.
21088 With prefix arg UNCOMPILED, load the uncompiled versions."
21089 (interactive "P")
21090 (require 'loadhist)
21091 (let* ((org-dir (org-find-library-dir "org"))
21092 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21093 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21094 (remove-re (mapconcat 'identity
21095 (mapcar (lambda (f) (concat "^" f "$"))
21096 (list (if (featurep 'xemacs)
21097 "org-colview"
21098 "org-colview-xemacs")
21099 "org" "org-loaddefs" "org-version"))
21100 "\\|"))
21101 (feats (delete-dups
21102 (mapcar 'file-name-sans-extension
21103 (mapcar 'file-name-nondirectory
21104 (delq nil
21105 (mapcar 'feature-file
21106 features))))))
21107 (lfeat (append
21108 (sort
21109 (setq feats
21110 (delq nil (mapcar
21111 (lambda (f)
21112 (if (and (string-match feature-re f)
21113 (not (string-match remove-re f)))
21114 f nil))
21115 feats)))
21116 'string-lessp)
21117 (list "org-version" "org")))
21118 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21119 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21120 load-uncore load-misses)
21121 (setq load-misses
21122 (delq 't
21123 (mapcar (lambda (f)
21124 (or (org-load-noerror-mustsuffix (concat org-dir f))
21125 (and (string= org-dir contrib-dir)
21126 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21127 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21128 (add-to-list 'load-uncore f 'append)
21131 lfeat)))
21132 (if load-uncore
21133 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21134 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21135 (if load-misses
21136 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21137 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21138 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21140 ;;;###autoload
21141 (defun org-customize ()
21142 "Call the customize function with org as argument."
21143 (interactive)
21144 (org-load-modules-maybe)
21145 (org-require-autoloaded-modules)
21146 (customize-browse 'org))
21148 (defun org-create-customize-menu ()
21149 "Create a full customization menu for Org-mode, insert it into the menu."
21150 (interactive)
21151 (org-load-modules-maybe)
21152 (org-require-autoloaded-modules)
21153 (if (fboundp 'customize-menu-create)
21154 (progn
21155 (easy-menu-change
21156 '("Org") "Customize"
21157 `(["Browse Org group" org-customize t]
21158 "--"
21159 ,(customize-menu-create 'org)
21160 ["Set" Custom-set t]
21161 ["Save" Custom-save t]
21162 ["Reset to Current" Custom-reset-current t]
21163 ["Reset to Saved" Custom-reset-saved t]
21164 ["Reset to Standard Settings" Custom-reset-standard t]))
21165 (message "\"Org\"-menu now contains full customization menu"))
21166 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21168 ;;;; Miscellaneous stuff
21170 ;;; Generally useful functions
21172 (defun org-get-at-bol (property)
21173 "Get text property PROPERTY at beginning of line."
21174 (get-text-property (point-at-bol) property))
21176 (defun org-find-text-property-in-string (prop s)
21177 "Return the first non-nil value of property PROP in string S."
21178 (or (get-text-property 0 prop s)
21179 (get-text-property (or (next-single-property-change 0 prop s) 0)
21180 prop s)))
21182 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21183 "Display the given MESSAGE as a warning."
21184 (if (fboundp 'display-warning)
21185 (display-warning 'org message
21186 (if (featurep 'xemacs) 'warning :warning))
21187 (let ((buf (get-buffer-create "*Org warnings*")))
21188 (with-current-buffer buf
21189 (goto-char (point-max))
21190 (insert "Warning (Org): " message)
21191 (unless (bolp)
21192 (newline)))
21193 (display-buffer buf)
21194 (sit-for 0))))
21196 (defun org-eval (form)
21197 "Eval FORM and return result."
21198 (condition-case error
21199 (eval form)
21200 (error (format "%%![Error: %s]" error))))
21202 (defun org-in-clocktable-p ()
21203 "Check if the cursor is in a clocktable."
21204 (let ((pos (point)) start)
21205 (save-excursion
21206 (end-of-line 1)
21207 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21208 (setq start (match-beginning 0))
21209 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21210 (>= (match-end 0) pos)
21211 start))))
21213 (defun org-in-commented-line ()
21214 "Is point in a line starting with `#'?"
21215 (equal (char-after (point-at-bol)) ?#))
21217 (defun org-in-indented-comment-line ()
21218 "Is point in a line starting with `#' after some white space?"
21219 (save-excursion
21220 (save-match-data
21221 (goto-char (point-at-bol))
21222 (looking-at "[ \t]*#"))))
21224 (defun org-in-verbatim-emphasis ()
21225 (save-match-data
21226 (and (org-in-regexp org-emph-re 2)
21227 (>= (point) (match-beginning 3))
21228 (<= (point) (match-end 4))
21229 (member (match-string 3) '("=" "~")))))
21231 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21232 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21233 (if (and marker (marker-buffer marker)
21234 (buffer-live-p (marker-buffer marker)))
21235 (progn
21236 (org-pop-to-buffer-same-window (marker-buffer marker))
21237 (if (or (> marker (point-max)) (< marker (point-min)))
21238 (widen))
21239 (goto-char marker)
21240 (org-show-context 'org-goto))
21241 (if bookmark
21242 (bookmark-jump bookmark)
21243 (error "Cannot find location"))))
21245 (defun org-quote-csv-field (s)
21246 "Quote field for inclusion in CSV material."
21247 (if (string-match "[\",]" s)
21248 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21251 (defun org-force-self-insert (N)
21252 "Needed to enforce self-insert under remapping."
21253 (interactive "p")
21254 (self-insert-command N))
21256 (defun org-string-width (s)
21257 "Compute width of string, ignoring invisible characters.
21258 This ignores character with invisibility property `org-link', and also
21259 characters with property `org-cwidth', because these will become invisible
21260 upon the next fontification round."
21261 (let (b l)
21262 (when (or (eq t buffer-invisibility-spec)
21263 (assq 'org-link buffer-invisibility-spec))
21264 (while (setq b (text-property-any 0 (length s)
21265 'invisible 'org-link s))
21266 (setq s (concat (substring s 0 b)
21267 (substring s (or (next-single-property-change
21268 b 'invisible s) (length s)))))))
21269 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21270 (setq s (concat (substring s 0 b)
21271 (substring s (or (next-single-property-change
21272 b 'org-cwidth s) (length s))))))
21273 (setq l (string-width s) b -1)
21274 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21275 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21278 (defun org-shorten-string (s maxlength)
21279 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21280 If the string is shorter or has length MAXLENGTH, just return the
21281 original string. If it is longer, the functions finds a space in the
21282 string, breaks this string off at that locations and adds three dots
21283 as ellipsis. Including the ellipsis, the string will not be longer
21284 than MAXLENGTH. If finding a good breaking point in the string does
21285 not work, the string is just chopped off in the middle of a word
21286 if necessary."
21287 (if (<= (length s) maxlength)
21289 (let* ((n (max (- maxlength 4) 1))
21290 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21291 (if (string-match re s)
21292 (concat (match-string 1 s) "...")
21293 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21295 (defun org-get-indentation (&optional line)
21296 "Get the indentation of the current line, interpreting tabs.
21297 When LINE is given, assume it represents a line and compute its indentation."
21298 (if line
21299 (if (string-match "^ *" (org-remove-tabs line))
21300 (match-end 0))
21301 (save-excursion
21302 (beginning-of-line 1)
21303 (skip-chars-forward " \t")
21304 (current-column))))
21306 (defun org-get-string-indentation (s)
21307 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21308 (let ((n -1) (i 0) (w tab-width) c)
21309 (catch 'exit
21310 (while (< (setq n (1+ n)) (length s))
21311 (setq c (aref s n))
21312 (cond ((= c ?\ ) (setq i (1+ i)))
21313 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21314 (t (throw 'exit t)))))
21317 (defun org-remove-tabs (s &optional width)
21318 "Replace tabulators in S with spaces.
21319 Assumes that s is a single line, starting in column 0."
21320 (setq width (or width tab-width))
21321 (while (string-match "\t" s)
21322 (setq s (replace-match
21323 (make-string
21324 (- (* width (/ (+ (match-beginning 0) width) width))
21325 (match-beginning 0)) ?\ )
21326 t t s)))
21329 (defun org-fix-indentation (line ind)
21330 "Fix indentation in LINE.
21331 IND is a cons cell with target and minimum indentation.
21332 If the current indentation in LINE is smaller than the minimum,
21333 leave it alone. If it is larger than ind, set it to the target."
21334 (let* ((l (org-remove-tabs line))
21335 (i (org-get-indentation l))
21336 (i1 (car ind)) (i2 (cdr ind)))
21337 (if (>= i i2) (setq l (substring line i2)))
21338 (if (> i1 0)
21339 (concat (make-string i1 ?\ ) l)
21340 l)))
21342 (defun org-remove-indentation (code &optional n)
21343 "Remove the maximum common indentation from the lines in CODE.
21344 N may optionally be the number of spaces to remove."
21345 (with-temp-buffer
21346 (insert code)
21347 (org-do-remove-indentation n)
21348 (buffer-string)))
21350 (defun org-do-remove-indentation (&optional n)
21351 "Remove the maximum common indentation from the buffer."
21352 (untabify (point-min) (point-max))
21353 (let ((min 10000) re)
21354 (if n
21355 (setq min n)
21356 (goto-char (point-min))
21357 (while (re-search-forward "^ *[^ \n]" nil t)
21358 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21359 (unless (or (= min 0) (= min 10000))
21360 (setq re (format "^ \\{%d\\}" min))
21361 (goto-char (point-min))
21362 (while (re-search-forward re nil t)
21363 (replace-match "")
21364 (end-of-line 1))
21365 min)))
21367 (defun org-fill-template (template alist)
21368 "Find each %key of ALIST in TEMPLATE and replace it."
21369 (let ((case-fold-search nil)
21370 entry key value)
21371 (setq alist (sort (copy-sequence alist)
21372 (lambda (a b) (< (length (car a)) (length (car b))))))
21373 (while (setq entry (pop alist))
21374 (setq template
21375 (replace-regexp-in-string
21376 (concat "%" (regexp-quote (car entry)))
21377 (or (cdr entry) "") template t t)))
21378 template))
21380 (defun org-base-buffer (buffer)
21381 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21382 (if (not buffer)
21383 buffer
21384 (or (buffer-base-buffer buffer)
21385 buffer)))
21387 (defun org-trim (s)
21388 "Remove whitespace at beginning and end of string."
21389 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21390 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21393 (defun org-wrap (string &optional width lines)
21394 "Wrap string to either a number of lines, or a width in characters.
21395 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21396 that costs. If there is a word longer than WIDTH, the text is actually
21397 wrapped to the length of that word.
21398 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21399 many lines, whatever width that takes.
21400 The return value is a list of lines, without newlines at the end."
21401 (let* ((words (org-split-string string "[ \t\n]+"))
21402 (maxword (apply 'max (mapcar 'org-string-width words)))
21403 w ll)
21404 (cond (width
21405 (org-do-wrap words (max maxword width)))
21406 (lines
21407 (setq w maxword)
21408 (setq ll (org-do-wrap words maxword))
21409 (if (<= (length ll) lines)
21411 (setq ll words)
21412 (while (> (length ll) lines)
21413 (setq w (1+ w))
21414 (setq ll (org-do-wrap words w)))
21415 ll))
21416 (t (error "Cannot wrap this")))))
21418 (defun org-do-wrap (words width)
21419 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21420 (let (lines line)
21421 (while words
21422 (setq line (pop words))
21423 (while (and words (< (+ (length line) (length (car words))) width))
21424 (setq line (concat line " " (pop words))))
21425 (setq lines (push line lines)))
21426 (nreverse lines)))
21428 (defun org-split-string (string &optional separators)
21429 "Splits STRING into substrings at SEPARATORS.
21430 No empty strings are returned if there are matches at the beginning
21431 and end of string."
21432 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21433 (start 0)
21434 notfirst
21435 (list nil))
21436 (while (and (string-match rexp string
21437 (if (and notfirst
21438 (= start (match-beginning 0))
21439 (< start (length string)))
21440 (1+ start) start))
21441 (< (match-beginning 0) (length string)))
21442 (setq notfirst t)
21443 (or (eq (match-beginning 0) 0)
21444 (and (eq (match-beginning 0) (match-end 0))
21445 (eq (match-beginning 0) start))
21446 (setq list
21447 (cons (substring string start (match-beginning 0))
21448 list)))
21449 (setq start (match-end 0)))
21450 (or (eq start (length string))
21451 (setq list
21452 (cons (substring string start)
21453 list)))
21454 (nreverse list)))
21456 (defun org-quote-vert (s)
21457 "Replace \"|\" with \"\\vert\"."
21458 (while (string-match "|" s)
21459 (setq s (replace-match "\\vert" t t s)))
21462 (defun org-uuidgen-p (s)
21463 "Is S an ID created by UUIDGEN?"
21464 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21466 (defun org-in-src-block-p (&optional inside)
21467 "Whether point is in a code source block.
21468 When INSIDE is non-nil, don't consider we are within a src block
21469 when point is at #+BEGIN_SRC or #+END_SRC."
21470 (let ((case-fold-search t) ov)
21471 (or (and (setq ov (overlays-at (point)))
21472 (memq 'org-block-background
21473 (overlay-properties (car ov))))
21474 (and (not inside)
21475 (save-match-data
21476 (save-excursion
21477 (beginning-of-line)
21478 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21480 (defun org-context ()
21481 "Return a list of contexts of the current cursor position.
21482 If several contexts apply, all are returned.
21483 Each context entry is a list with a symbol naming the context, and
21484 two positions indicating start and end of the context. Possible
21485 contexts are:
21487 :headline anywhere in a headline
21488 :headline-stars on the leading stars in a headline
21489 :todo-keyword on a TODO keyword (including DONE) in a headline
21490 :tags on the TAGS in a headline
21491 :priority on the priority cookie in a headline
21492 :item on the first line of a plain list item
21493 :item-bullet on the bullet/number of a plain list item
21494 :checkbox on the checkbox in a plain list item
21495 :table in an org-mode table
21496 :table-special on a special filed in a table
21497 :table-table in a table.el table
21498 :clocktable in a clocktable
21499 :src-block in a source block
21500 :link on a hyperlink
21501 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21502 :target on a <<target>>
21503 :radio-target on a <<<radio-target>>>
21504 :latex-fragment on a LaTeX fragment
21505 :latex-preview on a LaTeX fragment with overlaid preview image
21507 This function expects the position to be visible because it uses font-lock
21508 faces as a help to recognize the following contexts: :table-special, :link,
21509 and :keyword."
21510 (let* ((f (get-text-property (point) 'face))
21511 (faces (if (listp f) f (list f)))
21512 (case-fold-search t)
21513 (p (point)) clist o)
21514 ;; First the large context
21515 (cond
21516 ((org-at-heading-p t)
21517 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21518 (when (progn
21519 (beginning-of-line 1)
21520 (looking-at org-todo-line-tags-regexp))
21521 (push (org-point-in-group p 1 :headline-stars) clist)
21522 (push (org-point-in-group p 2 :todo-keyword) clist)
21523 (push (org-point-in-group p 4 :tags) clist))
21524 (goto-char p)
21525 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21526 (if (looking-at "\\[#[A-Z0-9]\\]")
21527 (push (org-point-in-group p 0 :priority) clist)))
21529 ((org-at-item-p)
21530 (push (org-point-in-group p 2 :item-bullet) clist)
21531 (push (list :item (point-at-bol)
21532 (save-excursion (org-end-of-item) (point)))
21533 clist)
21534 (and (org-at-item-checkbox-p)
21535 (push (org-point-in-group p 0 :checkbox) clist)))
21537 ((org-at-table-p)
21538 (push (list :table (org-table-begin) (org-table-end)) clist)
21539 (if (memq 'org-formula faces)
21540 (push (list :table-special
21541 (previous-single-property-change p 'face)
21542 (next-single-property-change p 'face)) clist)))
21543 ((org-at-table-p 'any)
21544 (push (list :table-table) clist)))
21545 (goto-char p)
21547 (let ((case-fold-search t))
21548 ;; New the "medium" contexts: clocktables, source blocks
21549 (cond ((org-in-clocktable-p)
21550 (push (list :clocktable
21551 (and (or (looking-at "#\\+BEGIN: clocktable")
21552 (search-backward "#+BEGIN: clocktable" nil t))
21553 (match-beginning 0))
21554 (and (re-search-forward "#\\+END:?" nil t)
21555 (match-end 0))) clist))
21556 ((org-in-src-block-p)
21557 (push (list :src-block
21558 (and (or (looking-at "#\\+BEGIN_SRC")
21559 (search-backward "#+BEGIN_SRC" nil t))
21560 (match-beginning 0))
21561 (and (search-forward "#+END_SRC" nil t)
21562 (match-beginning 0))) clist))))
21563 (goto-char p)
21565 ;; Now the small context
21566 (cond
21567 ((org-at-timestamp-p)
21568 (push (org-point-in-group p 0 :timestamp) clist))
21569 ((memq 'org-link faces)
21570 (push (list :link
21571 (previous-single-property-change p 'face)
21572 (next-single-property-change p 'face)) clist))
21573 ((memq 'org-special-keyword faces)
21574 (push (list :keyword
21575 (previous-single-property-change p 'face)
21576 (next-single-property-change p 'face)) clist))
21577 ((org-at-target-p)
21578 (push (org-point-in-group p 0 :target) clist)
21579 (goto-char (1- (match-beginning 0)))
21580 (if (looking-at org-radio-target-regexp)
21581 (push (org-point-in-group p 0 :radio-target) clist))
21582 (goto-char p))
21583 ((setq o (car (delq nil
21584 (mapcar
21585 (lambda (x)
21586 (if (memq x org-latex-fragment-image-overlays) x))
21587 (overlays-at (point))))))
21588 (push (list :latex-fragment
21589 (overlay-start o) (overlay-end o)) clist)
21590 (push (list :latex-preview
21591 (overlay-start o) (overlay-end o)) clist))
21592 ((org-inside-LaTeX-fragment-p)
21593 ;; FIXME: positions wrong.
21594 (push (list :latex-fragment (point) (point)) clist)))
21596 (setq clist (nreverse (delq nil clist)))
21597 clist))
21599 ;; FIXME: Compare with at-regexp-p Do we need both?
21600 (defun org-in-regexp (re &optional nlines visually)
21601 "Check if point is inside a match of regexp.
21602 Normally only the current line is checked, but you can include NLINES extra
21603 lines both before and after point into the search.
21604 If VISUALLY is set, require that the cursor is not after the match but
21605 really on, so that the block visually is on the match."
21606 (catch 'exit
21607 (let ((pos (point))
21608 (eol (point-at-eol (+ 1 (or nlines 0))))
21609 (inc (if visually 1 0)))
21610 (save-excursion
21611 (beginning-of-line (- 1 (or nlines 0)))
21612 (while (re-search-forward re eol t)
21613 (if (and (<= (match-beginning 0) pos)
21614 (>= (+ inc (match-end 0)) pos))
21615 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21617 (defun org-at-regexp-p (regexp)
21618 "Is point inside a match of REGEXP in the current line?"
21619 (catch 'exit
21620 (save-excursion
21621 (let ((pos (point)) (end (point-at-eol)))
21622 (beginning-of-line 1)
21623 (while (re-search-forward regexp end t)
21624 (if (and (<= (match-beginning 0) pos)
21625 (>= (match-end 0) pos))
21626 (throw 'exit t)))
21627 nil))))
21629 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21630 "Non-nil when point is between matches of START-RE and END-RE.
21632 Also return a non-nil value when point is on one of the matches.
21634 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21635 buffer positions. Default values are the positions of headlines
21636 surrounding the point.
21638 The functions returns a cons cell whose car (resp. cdr) is the
21639 position before START-RE (resp. after END-RE)."
21640 (save-match-data
21641 (let ((pos (point))
21642 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21643 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21644 beg end)
21645 (save-excursion
21646 ;; Point is on a block when on START-RE or if START-RE can be
21647 ;; found before it...
21648 (and (or (org-at-regexp-p start-re)
21649 (re-search-backward start-re limit-up t))
21650 (setq beg (match-beginning 0))
21651 ;; ... and END-RE after it...
21652 (goto-char (match-end 0))
21653 (re-search-forward end-re limit-down t)
21654 (> (setq end (match-end 0)) pos)
21655 ;; ... without another START-RE in-between.
21656 (goto-char (match-beginning 0))
21657 (not (re-search-backward start-re (1+ beg) t))
21658 ;; Return value.
21659 (cons beg end))))))
21661 (defun org-in-block-p (names)
21662 "Non-nil when point belongs to a block whose name belongs to NAMES.
21664 NAMES is a list of strings containing names of blocks.
21666 Return first block name matched, or nil. Beware that in case of
21667 nested blocks, the returned name may not belong to the closest
21668 block from point."
21669 (save-match-data
21670 (catch 'exit
21671 (let ((case-fold-search t)
21672 (lim-up (save-excursion (outline-previous-heading)))
21673 (lim-down (save-excursion (outline-next-heading))))
21674 (mapc (lambda (name)
21675 (let ((n (regexp-quote name)))
21676 (when (org-between-regexps-p
21677 (concat "^[ \t]*#\\+begin_" n)
21678 (concat "^[ \t]*#\\+end_" n)
21679 lim-up lim-down)
21680 (throw 'exit n))))
21681 names))
21682 nil)))
21684 (defun org-in-drawer-p ()
21685 "Is point within a drawer?"
21686 (save-match-data
21687 (let ((case-fold-search t)
21688 (lim-up (save-excursion (outline-previous-heading)))
21689 (lim-down (save-excursion (outline-next-heading))))
21690 (org-between-regexps-p
21691 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21692 "^[ \t]*:end:.*$"
21693 lim-up lim-down))))
21695 (defun org-occur-in-agenda-files (regexp &optional nlines)
21696 "Call `multi-occur' with buffers for all agenda files."
21697 (interactive "sOrg-files matching: \np")
21698 (let* ((files (org-agenda-files))
21699 (tnames (mapcar 'file-truename files))
21700 (extra org-agenda-text-search-extra-files)
21702 (when (eq (car extra) 'agenda-archives)
21703 (setq extra (cdr extra))
21704 (setq files (org-add-archive-files files)))
21705 (while (setq f (pop extra))
21706 (unless (member (file-truename f) tnames)
21707 (add-to-list 'files f 'append)
21708 (add-to-list 'tnames (file-truename f) 'append)))
21709 (multi-occur
21710 (mapcar (lambda (x)
21711 (with-current-buffer
21712 (or (get-file-buffer x) (find-file-noselect x))
21713 (widen)
21714 (current-buffer)))
21715 files)
21716 regexp)))
21718 (if (boundp 'occur-mode-find-occurrence-hook)
21719 ;; Emacs 23
21720 (add-hook 'occur-mode-find-occurrence-hook
21721 (lambda ()
21722 (when (derived-mode-p 'org-mode)
21723 (org-reveal))))
21724 ;; Emacs 22
21725 (defadvice occur-mode-goto-occurrence
21726 (after org-occur-reveal activate)
21727 (and (derived-mode-p 'org-mode) (org-reveal)))
21728 (defadvice occur-mode-goto-occurrence-other-window
21729 (after org-occur-reveal activate)
21730 (and (derived-mode-p 'org-mode) (org-reveal)))
21731 (defadvice occur-mode-display-occurrence
21732 (after org-occur-reveal activate)
21733 (when (derived-mode-p 'org-mode)
21734 (let ((pos (occur-mode-find-occurrence)))
21735 (with-current-buffer (marker-buffer pos)
21736 (save-excursion
21737 (goto-char pos)
21738 (org-reveal)))))))
21740 (defun org-occur-link-in-agenda-files ()
21741 "Create a link and search for it in the agendas.
21742 The link is not stored in `org-stored-links', it is just created
21743 for the search purpose."
21744 (interactive)
21745 (let ((link (condition-case nil
21746 (org-store-link nil)
21747 (error "Unable to create a link to here"))))
21748 (org-occur-in-agenda-files (regexp-quote link))))
21750 (defun org-reverse-string (string)
21751 "Return the reverse of STRING."
21752 (apply 'string (reverse (string-to-list string))))
21754 (defsubst org-uniquify (list)
21755 "Non-destructively remove duplicate elements from LIST."
21756 (let ((res (copy-sequence list))) (delete-dups res)))
21758 (defun org-uniquify-alist (alist)
21759 "Merge elements of ALIST with the same key.
21761 For example, in this alist:
21763 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21764 => '((a 1 3) (b 2))
21766 merge (a 1) and (a 3) into (a 1 3).
21768 The function returns the new ALIST."
21769 (let (rtn)
21770 (mapc
21771 (lambda (e)
21772 (let (n)
21773 (if (not (assoc (car e) rtn))
21774 (push e rtn)
21775 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21776 (setq rtn (assq-delete-all (car e) rtn))
21777 (push n rtn))))
21778 alist)
21779 rtn))
21781 (defun org-delete-all (elts list)
21782 "Remove all elements in ELTS from LIST."
21783 (while elts
21784 (setq list (delete (pop elts) list)))
21785 list)
21787 (defun org-count (cl-item cl-seq)
21788 "Count the number of occurrences of ITEM in SEQ.
21789 Taken from `count' in cl-seq.el with all keyword arguments removed."
21790 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21791 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21792 (while (< cl-start cl-end)
21793 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21794 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21795 (setq cl-start (1+ cl-start)))
21796 cl-count))
21798 (defun org-remove-if (predicate seq)
21799 "Remove everything from SEQ that fulfills PREDICATE."
21800 (let (res e)
21801 (while seq
21802 (setq e (pop seq))
21803 (if (not (funcall predicate e)) (push e res)))
21804 (nreverse res)))
21806 (defun org-remove-if-not (predicate seq)
21807 "Remove everything from SEQ that does not fulfill PREDICATE."
21808 (let (res e)
21809 (while seq
21810 (setq e (pop seq))
21811 (if (funcall predicate e) (push e res)))
21812 (nreverse res)))
21814 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21815 "Reduce two-argument FUNCTION across SEQ.
21816 Taken from `reduce' in cl-seq.el with all keyword arguments but
21817 \":initial-value\" removed."
21818 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21819 (cadr (memq :initial-value cl-keys)))
21820 (cl-seq (pop cl-seq))
21821 (t (funcall cl-func)))))
21822 (while cl-seq
21823 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21824 cl-accum))
21826 (defun org-every (pred seq)
21827 "Return true if PREDICATE is true of every element of SEQ.
21828 Adapted from `every' in cl.el."
21829 (catch 'org-every
21830 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21833 (defun org-some (pred seq)
21834 "Return true if PREDICATE is true of any element of SEQ.
21835 Adapted from `some' in cl.el."
21836 (catch 'org-some
21837 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21838 nil))
21840 (defun org-back-over-empty-lines ()
21841 "Move backwards over whitespace, to the beginning of the first empty line.
21842 Returns the number of empty lines passed."
21843 (let ((pos (point)))
21844 (if (cdr (assoc 'heading org-blank-before-new-entry))
21845 (skip-chars-backward " \t\n\r")
21846 (unless (eobp)
21847 (forward-line -1)))
21848 (beginning-of-line 2)
21849 (goto-char (min (point) pos))
21850 (count-lines (point) pos)))
21852 (defun org-skip-whitespace ()
21853 (skip-chars-forward " \t\n\r"))
21855 (defun org-point-in-group (point group &optional context)
21856 "Check if POINT is in match-group GROUP.
21857 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21858 match. If the match group does not exist or point is not inside it,
21859 return nil."
21860 (and (match-beginning group)
21861 (>= point (match-beginning group))
21862 (<= point (match-end group))
21863 (if context
21864 (list context (match-beginning group) (match-end group))
21865 t)))
21867 (defun org-switch-to-buffer-other-window (&rest args)
21868 "Switch to buffer in a second window on the current frame.
21869 In particular, do not allow pop-up frames.
21870 Returns the newly created buffer."
21871 (org-no-popups
21872 (apply 'switch-to-buffer-other-window args)))
21874 (defun org-combine-plists (&rest plists)
21875 "Create a single property list from all plists in PLISTS.
21876 The process starts by copying the first list, and then setting properties
21877 from the other lists. Settings in the last list are the most significant
21878 ones and overrule settings in the other lists."
21879 (let ((rtn (copy-sequence (pop plists)))
21880 p v ls)
21881 (while plists
21882 (setq ls (pop plists))
21883 (while ls
21884 (setq p (pop ls) v (pop ls))
21885 (setq rtn (plist-put rtn p v))))
21886 rtn))
21888 (defun org-replace-escapes (string table)
21889 "Replace %-escapes in STRING with values in TABLE.
21890 TABLE is an association list with keys like \"%a\" and string values.
21891 The sequences in STRING may contain normal field width and padding information,
21892 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21893 so values can contain further %-escapes if they are define later in TABLE."
21894 (let ((tbl (copy-alist table))
21895 (case-fold-search nil)
21896 (pchg 0)
21897 e re rpl)
21898 (while (setq e (pop tbl))
21899 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21900 (when (and (cdr e) (string-match re (cdr e)))
21901 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21902 (safe "SREF"))
21903 (add-text-properties 0 3 (list 'sref sref) safe)
21904 (setcdr e (replace-match safe t t (cdr e)))))
21905 (while (string-match re string)
21906 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21907 (cdr e)))
21908 (setq string (replace-match rpl t t string))))
21909 (while (setq pchg (next-property-change pchg string))
21910 (let ((sref (get-text-property pchg 'sref string)))
21911 (when (and sref (string-match "SREF" string pchg))
21912 (setq string (replace-match sref t t string)))))
21913 string))
21915 (defun org-sublist (list start end)
21916 "Return a section of LIST, from START to END.
21917 Counting starts at 1."
21918 (let (rtn (c start))
21919 (setq list (nthcdr (1- start) list))
21920 (while (and list (<= c end))
21921 (push (pop list) rtn)
21922 (setq c (1+ c)))
21923 (nreverse rtn)))
21925 (defun org-find-base-buffer-visiting (file)
21926 "Like `find-buffer-visiting' but always return the base buffer and
21927 not an indirect buffer."
21928 (let ((buf (or (get-file-buffer file)
21929 (find-buffer-visiting file))))
21930 (if buf
21931 (or (buffer-base-buffer buf) buf)
21932 nil)))
21934 (defun org-image-file-name-regexp (&optional extensions)
21935 "Return regexp matching the file names of images.
21936 If EXTENSIONS is given, only match these."
21937 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21938 (image-file-name-regexp)
21939 (let ((image-file-name-extensions
21940 (or extensions
21941 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21942 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21943 (concat "\\."
21944 (regexp-opt (nconc (mapcar 'upcase
21945 image-file-name-extensions)
21946 image-file-name-extensions)
21948 "\\'"))))
21950 (defun org-file-image-p (file &optional extensions)
21951 "Return non-nil if FILE is an image."
21952 (save-match-data
21953 (string-match (org-image-file-name-regexp extensions) file)))
21955 (defun org-get-cursor-date (&optional with-time)
21956 "Return the date at cursor in as a time.
21957 This works in the calendar and in the agenda, anywhere else it just
21958 returns the current time.
21959 If WITH-TIME is non-nil, returns the time of the event at point (in
21960 the agenda) or the current time of the day."
21961 (let (date day defd tp tm hod mod)
21962 (when with-time
21963 (setq tp (get-text-property (point) 'time))
21964 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21965 (setq hod (string-to-number (match-string 1 tp))
21966 mod (string-to-number (match-string 2 tp))))
21967 (or tp (setq hod (nth 2 (decode-time (current-time)))
21968 mod (nth 1 (decode-time (current-time))))))
21969 (cond
21970 ((eq major-mode 'calendar-mode)
21971 (setq date (calendar-cursor-to-date)
21972 defd (encode-time 0 (or mod 0) (or hod 0)
21973 (nth 1 date) (nth 0 date) (nth 2 date))))
21974 ((eq major-mode 'org-agenda-mode)
21975 (setq day (get-text-property (point) 'day))
21976 (if day
21977 (setq date (calendar-gregorian-from-absolute day)
21978 defd (encode-time 0 (or mod 0) (or hod 0)
21979 (nth 1 date) (nth 0 date) (nth 2 date))))))
21980 (or defd (current-time))))
21982 (defun org-mark-subtree (&optional up)
21983 "Mark the current subtree.
21984 This puts point at the start of the current subtree, and mark at
21985 the end. If a numeric prefix UP is given, move up into the
21986 hierarchy of headlines by UP levels before marking the subtree."
21987 (interactive "P")
21988 (org-with-limited-levels
21989 (cond ((org-at-heading-p) (beginning-of-line))
21990 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21991 (t (outline-previous-visible-heading 1))))
21992 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21993 (if (org-called-interactively-p 'any)
21994 (call-interactively 'org-mark-element)
21995 (org-mark-element)))
21998 ;;; Indentation
22000 (defun org-indent-line ()
22001 "Indent line depending on context."
22002 (interactive)
22003 (let* ((pos (point))
22004 (itemp (org-at-item-p))
22005 (case-fold-search t)
22006 (org-drawer-regexp (or org-drawer-regexp "\000"))
22007 (inline-task-p (and (featurep 'org-inlinetask)
22008 (org-inlinetask-in-task-p)))
22009 (inline-re (and inline-task-p
22010 (org-inlinetask-outline-regexp)))
22011 column)
22012 (if (and orgstruct-is-++ (eq pos (point)))
22013 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22014 (indent-according-to-mode))
22015 (beginning-of-line 1)
22016 (cond
22017 ;; Headings
22018 ((looking-at org-outline-regexp) (setq column 0))
22019 ;; Footnote definition
22020 ((looking-at org-footnote-definition-re) (setq column 0))
22021 ;; Literal examples
22022 ((looking-at "[ \t]*:\\( \\|$\\)")
22023 (setq column (org-get-indentation))) ; do nothing
22024 ;; Lists
22025 ((ignore-errors (goto-char (org-in-item-p)))
22026 (setq column (if itemp
22027 (org-get-indentation)
22028 (org-list-item-body-column (point))))
22029 (goto-char pos))
22030 ;; Drawers
22031 ((and (looking-at "[ \t]*:END:")
22032 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22033 (save-excursion
22034 (goto-char (1- (match-beginning 1)))
22035 (setq column (current-column))))
22036 ;; Special blocks
22037 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22038 (save-excursion
22039 (re-search-backward
22040 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22041 (setq column (org-get-indentation (match-string 0))))
22042 ((and (not (looking-at "[ \t]*#\\+begin_"))
22043 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22044 (save-excursion
22045 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22046 (setq column
22047 (cond ((equal (downcase (match-string 1)) "src")
22048 ;; src blocks: let `org-edit-src-exit' handle them
22049 (org-get-indentation))
22050 ((equal (downcase (match-string 1)) "example")
22051 (max (org-get-indentation)
22052 (org-get-indentation (match-string 0))))
22054 (org-get-indentation (match-string 0))))))
22055 ;; This line has nothing special, look at the previous relevant
22056 ;; line to compute indentation
22058 (beginning-of-line 0)
22059 (while (and (not (bobp))
22060 (not (looking-at org-table-line-regexp))
22061 (not (looking-at org-drawer-regexp))
22062 ;; When point started in an inline task, do not move
22063 ;; above task starting line.
22064 (not (and inline-task-p (looking-at inline-re)))
22065 ;; Skip drawers, blocks, empty lines, verbatim,
22066 ;; comments, tables, footnotes definitions, lists,
22067 ;; inline tasks.
22068 (or (and (looking-at "[ \t]*:END:")
22069 (re-search-backward org-drawer-regexp nil t))
22070 (and (looking-at "[ \t]*#\\+end_")
22071 (re-search-backward "[ \t]*#\\+begin_"nil t))
22072 (looking-at "[ \t]*[\n:#|]")
22073 (looking-at org-footnote-definition-re)
22074 (and (not inline-task-p)
22075 (featurep 'org-inlinetask)
22076 (org-inlinetask-in-task-p)
22077 (or (org-inlinetask-goto-beginning) t))))
22078 (beginning-of-line 0))
22079 (cond
22080 ;; There was a list item above.
22081 ((ignore-errors (goto-char (org-in-item-p)))
22082 (goto-char (org-list-get-top-point (org-list-struct)))
22083 (setq column (org-get-indentation)))
22084 ;; There was an heading above.
22085 ((looking-at "\\*+[ \t]+")
22086 (if (not org-adapt-indentation)
22087 (setq column 0)
22088 (goto-char (match-end 0))
22089 (setq column (current-column))))
22090 ;; A drawer had started and is unfinished
22091 ((looking-at org-drawer-regexp)
22092 (goto-char (1- (match-beginning 1)))
22093 (setq column (current-column)))
22094 ;; Else, nothing noticeable found: get indentation and go on.
22095 (t (setq column (org-get-indentation))))))
22096 ;; Now apply indentation and move cursor accordingly
22097 (goto-char pos)
22098 (if (<= (current-column) (current-indentation))
22099 (org-indent-line-to column)
22100 (save-excursion (org-indent-line-to column)))
22101 ;; Special polishing for properties, see `org-property-format'
22102 (setq column (current-column))
22103 (beginning-of-line 1)
22104 (if (looking-at org-property-re)
22105 (replace-match (concat (match-string 4)
22106 (format org-property-format
22107 (match-string 1) (match-string 3)))
22108 t t))
22109 (org-move-to-column column))))
22111 (defun org-indent-drawer ()
22112 "Indent the drawer at point."
22113 (interactive)
22114 (let ((p (point))
22115 (e (and (save-excursion (re-search-forward ":END:" nil t))
22116 (match-end 0)))
22117 (folded
22118 (save-excursion
22119 (end-of-line)
22120 (when (overlays-at (point))
22121 (member 'invisible (overlay-properties
22122 (car (overlays-at (point)))))))))
22123 (when folded (org-cycle))
22124 (indent-for-tab-command)
22125 (while (and (move-beginning-of-line 2) (< (point) e))
22126 (indent-for-tab-command))
22127 (goto-char p)
22128 (when folded (org-cycle)))
22129 (message "Drawer at point indented"))
22131 (defun org-indent-block ()
22132 "Indent the block at point."
22133 (interactive)
22134 (let ((p (point))
22135 (case-fold-search t)
22136 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22137 (match-end 0)))
22138 (folded
22139 (save-excursion
22140 (end-of-line)
22141 (when (overlays-at (point))
22142 (member 'invisible (overlay-properties
22143 (car (overlays-at (point)))))))))
22144 (when folded (org-cycle))
22145 (indent-for-tab-command)
22146 (while (and (move-beginning-of-line 2) (< (point) e))
22147 (indent-for-tab-command))
22148 (goto-char p)
22149 (when folded (org-cycle)))
22150 (message "Block at point indented"))
22152 (defun org-indent-region (start end)
22153 "Indent region."
22154 (interactive "r")
22155 (save-excursion
22156 (let ((line-end (org-current-line end)))
22157 (goto-char start)
22158 (while (< (org-current-line) line-end)
22159 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22160 (t (call-interactively 'org-indent-line)))
22161 (move-beginning-of-line 2)))))
22164 ;;; Filling
22166 ;; We use our own fill-paragraph and auto-fill functions.
22168 ;; `org-fill-paragraph' relies on adaptive filling and context
22169 ;; checking. Appropriate `fill-prefix' is computed with
22170 ;; `org-adaptive-fill-function'.
22172 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22173 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22174 ;; `org-adaptive-fill-function' value. Internally,
22175 ;; `org-comment-line-break-function' breaks the line.
22177 ;; `org-setup-filling' installs filling and auto-filling related
22178 ;; variables during `org-mode' initialization.
22180 (defvar org-element-paragraph-separate) ; org-element.el
22181 (defun org-setup-filling ()
22182 (require 'org-element)
22183 ;; Prevent auto-fill from inserting unwanted new items.
22184 (when (boundp 'fill-nobreak-predicate)
22185 (org-set-local
22186 'fill-nobreak-predicate
22187 (org-uniquify
22188 (append fill-nobreak-predicate
22189 '(org-fill-line-break-nobreak-p
22190 org-fill-paragraph-with-timestamp-nobreak-p)))))
22191 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22192 (org-set-local 'paragraph-start paragraph-ending)
22193 (org-set-local 'paragraph-separate paragraph-ending))
22194 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22195 (org-set-local 'auto-fill-inhibit-regexp nil)
22196 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22197 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22198 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22200 (defun org-fill-line-break-nobreak-p ()
22201 "Non-nil when a new line at point would create an Org line break."
22202 (save-excursion
22203 (skip-chars-backward "[ \t]")
22204 (skip-chars-backward "\\\\")
22205 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22207 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22208 "Non-nil when a new line at point would split a timestamp."
22209 (and (org-at-timestamp-p t)
22210 (not (looking-at org-ts-regexp-both))))
22212 (declare-function message-in-body-p "message" ())
22213 (defvar orgtbl-line-start-regexp) ; From org-table.el
22214 (defun org-adaptive-fill-function ()
22215 "Compute a fill prefix for the current line.
22216 Return fill prefix, as a string, or nil if current line isn't
22217 meant to be filled. For convenience, if `adaptive-fill-regexp'
22218 matches in paragraphs or comments, use it."
22219 (catch 'exit
22220 (when (derived-mode-p 'message-mode)
22221 (save-excursion
22222 (beginning-of-line)
22223 (cond ((or (not (message-in-body-p))
22224 (looking-at orgtbl-line-start-regexp))
22225 (throw 'exit nil))
22226 ((looking-at message-cite-prefix-regexp)
22227 (throw 'exit (match-string-no-properties 0)))
22228 ((looking-at org-outline-regexp)
22229 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22230 (org-with-wide-buffer
22231 (let* ((p (line-beginning-position))
22232 (element (save-excursion
22233 (beginning-of-line)
22234 (or (ignore-errors (org-element-at-point))
22235 (user-error "An element cannot be parsed line %d"
22236 (line-number-at-pos (point))))))
22237 (type (org-element-type element))
22238 (post-affiliated (org-element-property :post-affiliated element)))
22239 (unless (and post-affiliated (< p post-affiliated))
22240 (case type
22241 (comment
22242 (save-excursion
22243 (beginning-of-line)
22244 (looking-at "[ \t]*")
22245 (concat (match-string 0) "# ")))
22246 (footnote-definition "")
22247 ((item plain-list)
22248 (make-string (org-list-item-body-column
22249 (or post-affiliated
22250 (org-element-property :begin element)))
22251 ? ))
22252 (paragraph
22253 ;; Fill prefix is usually the same as the current line,
22254 ;; unless the paragraph is at the beginning of an item.
22255 (let ((parent (org-element-property :parent element)))
22256 (save-excursion
22257 (beginning-of-line)
22258 (cond ((eq (org-element-type parent) 'item)
22259 (make-string (org-list-item-body-column
22260 (org-element-property :begin parent))
22261 ? ))
22262 ((and adaptive-fill-regexp
22263 ;; Locally disable
22264 ;; `adaptive-fill-function' to let
22265 ;; `fill-context-prefix' handle
22266 ;; `adaptive-fill-regexp' variable.
22267 (let (adaptive-fill-function)
22268 (fill-context-prefix
22269 post-affiliated
22270 (org-element-property :end element)))))
22271 ((looking-at "[ \t]+") (match-string 0))
22272 (t "")))))
22273 (comment-block
22274 ;; Only fill contents if P is within block boundaries.
22275 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22276 (forward-line)
22277 (point)))
22278 (cend (save-excursion
22279 (goto-char (org-element-property :end element))
22280 (skip-chars-backward " \r\t\n")
22281 (line-beginning-position))))
22282 (when (and (>= p cbeg) (< p cend))
22283 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22284 (match-string 0)
22285 ""))))))))))
22287 (declare-function message-goto-body "message" ())
22288 (defvar message-cite-prefix-regexp) ; From message.el
22289 (defun org-fill-paragraph (&optional justify)
22290 "Fill element at point, when applicable.
22292 This function only applies to comment blocks, comments, example
22293 blocks and paragraphs. Also, as a special case, re-align table
22294 when point is at one.
22296 If JUSTIFY is non-nil (interactively, with prefix argument),
22297 justify as well. If `sentence-end-double-space' is non-nil, then
22298 period followed by one space does not end a sentence, so don't
22299 break a line there. The variable `fill-column' controls the
22300 width for filling.
22302 For convenience, when point is at a plain list, an item or
22303 a footnote definition, try to fill the first paragraph within."
22304 (interactive)
22305 (if (and (derived-mode-p 'message-mode)
22306 (or (not (message-in-body-p))
22307 (save-excursion (move-beginning-of-line 1)
22308 (looking-at message-cite-prefix-regexp))))
22309 ;; First ensure filling is correct in message-mode.
22310 (let ((fill-paragraph-function
22311 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22312 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22313 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22314 (paragraph-separate
22315 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22316 (fill-paragraph nil))
22317 (with-syntax-table org-mode-transpose-word-syntax-table
22318 ;; Move to end of line in order to get the first paragraph
22319 ;; within a plain list or a footnote definition.
22320 (let ((element (save-excursion
22321 (end-of-line)
22322 (or (ignore-errors (org-element-at-point))
22323 (user-error "An element cannot be parsed line %d"
22324 (line-number-at-pos (point)))))))
22325 ;; First check if point is in a blank line at the beginning of
22326 ;; the buffer. In that case, ignore filling.
22327 (case (org-element-type element)
22328 ;; Use major mode filling function is src blocks.
22329 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22330 ;; Align Org tables, leave table.el tables as-is.
22331 (table-row (org-table-align) t)
22332 (table
22333 (when (eq (org-element-property :type element) 'org)
22334 (save-excursion
22335 (goto-char (org-element-property :post-affiliated element))
22336 (org-table-align)))
22338 (paragraph
22339 ;; Paragraphs may contain `line-break' type objects.
22340 (let ((beg (max (point-min)
22341 (org-element-property :contents-begin element)))
22342 (end (min (point-max)
22343 (org-element-property :contents-end element))))
22344 ;; Do nothing if point is at an affiliated keyword.
22345 (if (< (line-end-position) beg) t
22346 (when (derived-mode-p 'message-mode)
22347 ;; In `message-mode', do not fill following citation
22348 ;; in current paragraph nor text before message body.
22349 (let ((body-start (save-excursion (message-goto-body))))
22350 (when body-start (setq beg (max body-start beg))))
22351 (when (save-excursion
22352 (re-search-forward
22353 (concat "^" message-cite-prefix-regexp) end t))
22354 (setq end (match-beginning 0))))
22355 ;; Fill paragraph, taking line breaks into account.
22356 ;; For that, slice the paragraph using line breaks as
22357 ;; separators, and fill the parts in reverse order to
22358 ;; avoid messing with markers.
22359 (save-excursion
22360 (goto-char end)
22361 (mapc
22362 (lambda (pos)
22363 (fill-region-as-paragraph pos (point) justify)
22364 (goto-char pos))
22365 ;; Find the list of ending positions for line breaks
22366 ;; in the current paragraph. Add paragraph
22367 ;; beginning to include first slice.
22368 (nreverse
22369 (cons beg
22370 (org-element-map
22371 (org-element--parse-objects
22372 beg end nil (org-element-restriction 'paragraph))
22373 'line-break
22374 (lambda (lb) (org-element-property :end lb)))))))
22375 t)))
22376 ;; Contents of `comment-block' type elements should be
22377 ;; filled as plain text, but only if point is within block
22378 ;; markers.
22379 (comment-block
22380 (let* ((case-fold-search t)
22381 (beg (save-excursion
22382 (goto-char (org-element-property :begin element))
22383 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22384 (forward-line)
22385 (point)))
22386 (end (save-excursion
22387 (goto-char (org-element-property :end element))
22388 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22389 (line-beginning-position))))
22390 (if (or (< (point) beg) (> (point) end)) t
22391 (fill-region-as-paragraph
22392 (save-excursion (end-of-line)
22393 (re-search-backward "^[ \t]*$" beg 'move)
22394 (line-beginning-position))
22395 (save-excursion (beginning-of-line)
22396 (re-search-forward "^[ \t]*$" end 'move)
22397 (line-beginning-position))
22398 justify))))
22399 ;; Fill comments.
22400 (comment
22401 (let ((begin (org-element-property :post-affiliated element))
22402 (end (org-element-property :end element)))
22403 (when (and (>= (point) begin) (<= (point) end))
22404 (let ((begin (save-excursion
22405 (end-of-line)
22406 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22407 (progn (forward-line) (point))
22408 begin)))
22409 (end (save-excursion
22410 (end-of-line)
22411 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22412 (1- (line-beginning-position))
22413 (skip-chars-backward " \r\t\n")
22414 (line-end-position)))))
22415 ;; Do not fill comments when at a blank line.
22416 (when (> end begin)
22417 (let ((fill-prefix
22418 (save-excursion
22419 (beginning-of-line)
22420 (looking-at "[ \t]*#")
22421 (let ((comment-prefix (match-string 0)))
22422 (goto-char (match-end 0))
22423 (if (looking-at adaptive-fill-regexp)
22424 (concat comment-prefix (match-string 0))
22425 (concat comment-prefix " "))))))
22426 (save-excursion
22427 (fill-region-as-paragraph begin end justify))))))
22429 ;; Ignore every other element.
22430 (otherwise t))))))
22432 (defun org-auto-fill-function ()
22433 "Auto-fill function."
22434 ;; Check if auto-filling is meaningful.
22435 (let ((fc (current-fill-column)))
22436 (when (and fc (> (current-column) fc))
22437 (let* ((fill-prefix (org-adaptive-fill-function))
22438 ;; Enforce empty fill prefix, if required. Otherwise, it
22439 ;; will be computed again.
22440 (adaptive-fill-mode (not (equal fill-prefix ""))))
22441 (when fill-prefix (do-auto-fill))))))
22443 (defun org-comment-line-break-function (&optional soft)
22444 "Break line at point and indent, continuing comment if within one.
22445 The inserted newline is marked hard if variable
22446 `use-hard-newlines' is true, unless optional argument SOFT is
22447 non-nil."
22448 (if soft (insert-and-inherit ?\n) (newline 1))
22449 (save-excursion (forward-char -1) (delete-horizontal-space))
22450 (delete-horizontal-space)
22451 (indent-to-left-margin)
22452 (insert-before-markers-and-inherit fill-prefix))
22455 ;;; Comments
22457 ;; Org comments syntax is quite complex. It requires the entire line
22458 ;; to be just a comment. Also, even with the right syntax at the
22459 ;; beginning of line, some some elements (i.e. verse-block or
22460 ;; example-block) don't accept comments. Usual Emacs comment commands
22461 ;; cannot cope with those requirements. Therefore, Org replaces them.
22463 ;; Org still relies on `comment-dwim', but cannot trust
22464 ;; `comment-only-p'. So, `comment-region-function' and
22465 ;; `uncomment-region-function' both point
22466 ;; to`org-comment-or-uncomment-region'. Eventually,
22467 ;; `org-insert-comment' takes care of insertion of comments at the
22468 ;; beginning of line.
22470 ;; `org-setup-comments-handling' install comments related variables
22471 ;; during `org-mode' initialization.
22473 (defun org-setup-comments-handling ()
22474 (interactive)
22475 (org-set-local 'comment-use-syntax nil)
22476 (org-set-local 'comment-start "# ")
22477 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22478 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22479 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22480 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22482 (defun org-insert-comment ()
22483 "Insert an empty comment above current line.
22484 If the line is empty, insert comment at its beginning."
22485 (beginning-of-line)
22486 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22487 (org-indent-line)
22488 (insert "# "))
22490 (defvar comment-empty-lines) ; From newcomment.el.
22491 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22492 "Comment or uncomment each non-blank line in the region.
22493 Uncomment each non-blank line between BEG and END if it only
22494 contains commented lines. Otherwise, comment them."
22495 (save-restriction
22496 ;; Restrict region
22497 (narrow-to-region (save-excursion (goto-char beg)
22498 (skip-chars-forward " \r\t\n" end)
22499 (line-beginning-position))
22500 (save-excursion (goto-char end)
22501 (skip-chars-backward " \r\t\n" beg)
22502 (line-end-position)))
22503 (let ((uncommentp
22504 ;; UNCOMMENTP is non-nil when every non blank line between
22505 ;; BEG and END is a comment.
22506 (save-excursion
22507 (goto-char (point-min))
22508 (while (and (not (eobp))
22509 (let ((element (org-element-at-point)))
22510 (and (eq (org-element-type element) 'comment)
22511 (goto-char (min (point-max)
22512 (org-element-property
22513 :end element)))))))
22514 (eobp))))
22515 (if uncommentp
22516 ;; Only blank lines and comments in region: uncomment it.
22517 (save-excursion
22518 (goto-char (point-min))
22519 (while (not (eobp))
22520 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22521 (replace-match "" nil nil nil 1))
22522 (forward-line)))
22523 ;; Comment each line in region.
22524 (let ((min-indent (point-max)))
22525 ;; First find the minimum indentation across all lines.
22526 (save-excursion
22527 (goto-char (point-min))
22528 (while (and (not (eobp)) (not (zerop min-indent)))
22529 (unless (looking-at "[ \t]*$")
22530 (setq min-indent (min min-indent (current-indentation))))
22531 (forward-line)))
22532 ;; Then loop over all lines.
22533 (save-excursion
22534 (goto-char (point-min))
22535 (while (not (eobp))
22536 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22537 ;; Don't get fooled by invisible text (e.g. link path)
22538 ;; when moving to column MIN-INDENT.
22539 (let ((buffer-invisibility-spec nil))
22540 (org-move-to-column min-indent t))
22541 (insert comment-start))
22542 (forward-line))))))))
22545 ;;; Planning
22547 ;; This section contains tools to operate on timestamp objects, as
22548 ;; returned by, e.g. `org-element-context'.
22550 (defun org-timestamp-has-time-p (timestamp)
22551 "Non-nil when TIMESTAMP has a time specified."
22552 (org-element-property :hour-start timestamp))
22554 (defun org-timestamp-format (timestamp format &optional end utc)
22555 "Format a TIMESTAMP element into a string.
22557 FORMAT is a format specifier to be passed to
22558 `format-time-string'.
22560 When optional argument END is non-nil, use end of date-range or
22561 time-range, if possible.
22563 When optional argument UTC is non-nil, time will be expressed as
22564 Universal Time."
22565 (format-time-string
22566 format
22567 (apply 'encode-time
22568 (cons 0
22569 (mapcar
22570 (lambda (prop) (or (org-element-property prop timestamp) 0))
22571 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22572 '(:minute-start :hour-start :day-start :month-start
22573 :year-start)))))
22574 utc))
22576 (defun org-timestamp-split-range (timestamp &optional end)
22577 "Extract a timestamp object from a date or time range.
22579 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22580 the end of the range. Otherwise, extract its start.
22582 Return a new timestamp object sharing the same parent as
22583 TIMESTAMP."
22584 (let ((type (org-element-property :type timestamp)))
22585 (if (memq type '(active inactive diary)) timestamp
22586 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22587 ;; Set new type.
22588 (org-element-put-property
22589 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22590 ;; Copy start properties over end properties if END is
22591 ;; non-nil. Otherwise, copy end properties over `start' ones.
22592 (let ((p-alist '((:minute-start . :minute-end)
22593 (:hour-start . :hour-end)
22594 (:day-start . :day-end)
22595 (:month-start . :month-end)
22596 (:year-start . :year-end))))
22597 (dolist (p-cell p-alist)
22598 (org-element-put-property
22599 split-ts
22600 (funcall (if end 'car 'cdr) p-cell)
22601 (org-element-property
22602 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22603 ;; Eventually refresh `:raw-value'.
22604 (org-element-put-property split-ts :raw-value nil)
22605 (org-element-put-property
22606 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22608 (defun org-timestamp-translate (timestamp &optional boundary)
22609 "Apply `org-translate-time' on a TIMESTAMP object.
22610 When optional argument BOUNDARY is non-nil, it is either the
22611 symbol `start' or `end'. In this case, only translate the
22612 starting or ending part of TIMESTAMP if it is a date or time
22613 range. Otherwise, translate both parts."
22614 (if (and (not boundary)
22615 (memq (org-element-property :type timestamp)
22616 '(active-range inactive-range)))
22617 (concat
22618 (org-translate-time
22619 (org-element-property :raw-value
22620 (org-timestamp-split-range timestamp)))
22621 "--"
22622 (org-translate-time
22623 (org-element-property :raw-value
22624 (org-timestamp-split-range timestamp t))))
22625 (org-translate-time
22626 (org-element-property
22627 :raw-value
22628 (if (not boundary) timestamp
22629 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22633 ;;; Other stuff.
22635 (defun org-toggle-fixed-width-section (arg)
22636 "Toggle the fixed-width export.
22637 If there is no active region, the QUOTE keyword at the current headline is
22638 inserted or removed. When present, it causes the text between this headline
22639 and the next to be exported as fixed-width text, and unmodified.
22640 If there is an active region, this command adds or removes a colon as the
22641 first character of this line. If the first character of a line is a colon,
22642 this line is also exported in fixed-width font."
22643 (interactive "P")
22644 (let* ((cc 0)
22645 (regionp (org-region-active-p))
22646 (beg (if regionp (region-beginning) (point)))
22647 (end (if regionp (region-end)))
22648 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22649 (case-fold-search nil)
22650 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22651 off)
22652 (if regionp
22653 (save-excursion
22654 (goto-char beg)
22655 (setq cc (current-column))
22656 (beginning-of-line 1)
22657 (setq off (looking-at re))
22658 (while (> nlines 0)
22659 (setq nlines (1- nlines))
22660 (beginning-of-line 1)
22661 (cond
22662 (arg
22663 (org-move-to-column cc t)
22664 (insert ": \n")
22665 (forward-line -1))
22666 ((and off (looking-at re))
22667 (replace-match "" t t nil 1))
22668 ((not off) (org-move-to-column cc t) (insert ": ")))
22669 (forward-line 1)))
22670 (save-excursion
22671 (org-back-to-heading)
22672 (cond
22673 ((looking-at (format org-heading-keyword-regexp-format
22674 org-quote-string))
22675 (goto-char (match-end 1))
22676 (looking-at (concat " +" org-quote-string))
22677 (replace-match "" t t)
22678 (when (eolp) (insert " ")))
22679 ((looking-at org-outline-regexp)
22680 (goto-char (match-end 0))
22681 (insert org-quote-string " ")))))))
22683 (defun org-reftex-citation ()
22684 "Use reftex-citation to insert a citation into the buffer.
22685 This looks for a line like
22687 #+BIBLIOGRAPHY: foo plain option:-d
22689 and derives from it that foo.bib is the bibliography file relevant
22690 for this document. It then installs the necessary environment for RefTeX
22691 to work in this buffer and calls `reftex-citation' to insert a citation
22692 into the buffer.
22694 Export of such citations to both LaTeX and HTML is handled by the contributed
22695 package ox-bibtex by Taru Karttunen."
22696 (interactive)
22697 (let ((reftex-docstruct-symbol 'rds)
22698 (reftex-cite-format "\\cite{%l}")
22699 rds bib)
22700 (save-excursion
22701 (save-restriction
22702 (widen)
22703 (let ((case-fold-search t)
22704 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22705 (if (not (save-excursion
22706 (or (re-search-forward re nil t)
22707 (re-search-backward re nil t))))
22708 (error "No bibliography defined in file")
22709 (setq bib (concat (match-string 1) ".bib")
22710 rds (list (list 'bib bib)))))))
22711 (call-interactively 'reftex-citation)))
22713 ;;;; Functions extending outline functionality
22715 (defun org-beginning-of-line (&optional arg)
22716 "Go to the beginning of the current line. If that is invisible, continue
22717 to a visible line beginning. This makes the function of C-a more intuitive.
22718 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22719 first attempt, and only move to after the tags when the cursor is already
22720 beyond the end of the headline."
22721 (interactive "P")
22722 (let ((pos (point))
22723 (special (if (consp org-special-ctrl-a/e)
22724 (car org-special-ctrl-a/e)
22725 org-special-ctrl-a/e))
22726 deactivate-mark refpos)
22727 (if (org-bound-and-true-p visual-line-mode)
22728 (beginning-of-visual-line 1)
22729 (beginning-of-line 1))
22730 (if (and arg (fboundp 'move-beginning-of-line))
22731 (call-interactively 'move-beginning-of-line)
22732 (if (bobp)
22734 (backward-char 1)
22735 (if (org-truely-invisible-p)
22736 (while (and (not (bobp)) (org-truely-invisible-p))
22737 (backward-char 1)
22738 (beginning-of-line 1))
22739 (forward-char 1))))
22740 (when special
22741 (cond
22742 ((and (looking-at org-complex-heading-regexp)
22743 (= (char-after (match-end 1)) ?\ ))
22744 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22745 (point-at-eol)))
22746 (goto-char
22747 (if (eq special t)
22748 (cond ((> pos refpos) refpos)
22749 ((= pos (point)) refpos)
22750 (t (point)))
22751 (cond ((> pos (point)) (point))
22752 ((not (eq last-command this-command)) (point))
22753 (t refpos)))))
22754 ((org-at-item-p)
22755 ;; Being at an item and not looking at an the item means point
22756 ;; was previously moved to beginning of a visual line, which
22757 ;; doesn't contain the item. Therefore, do nothing special,
22758 ;; just stay here.
22759 (when (looking-at org-list-full-item-re)
22760 ;; Set special position at first white space character after
22761 ;; bullet, and check-box, if any.
22762 (let ((after-bullet
22763 (let ((box (match-end 3)))
22764 (if (not box) (match-end 1)
22765 (let ((after (char-after box)))
22766 (if (and after (= after ? )) (1+ box) box))))))
22767 ;; Special case: Move point to special position when
22768 ;; currently after it or at beginning of line.
22769 (if (eq special t)
22770 (when (or (> pos after-bullet) (= (point) pos))
22771 (goto-char after-bullet))
22772 ;; Reversed case: Move point to special position when
22773 ;; point was already at beginning of line and command is
22774 ;; repeated.
22775 (when (and (= (point) pos) (eq last-command this-command))
22776 (goto-char after-bullet))))))))
22777 (org-no-warnings
22778 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22779 (setq disable-point-adjustment
22780 (or (not (invisible-p (point)))
22781 (not (invisible-p (max (point-min) (1- (point))))))))
22783 (defun org-end-of-line (&optional arg)
22784 "Go to the end of the line.
22785 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22786 tags on the first attempt, and only move to after the tags when
22787 the cursor is already beyond the end of the headline."
22788 (interactive "P")
22789 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22790 org-special-ctrl-a/e))
22791 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22792 'end-of-visual-line)
22793 ((fboundp 'move-end-of-line) 'move-end-of-line)
22794 (t 'end-of-line)))
22795 deactivate-mark)
22796 (if (or (not special) arg) (call-interactively move-fun)
22797 (let* ((element (save-excursion (beginning-of-line)
22798 (org-element-at-point)))
22799 (type (org-element-type element)))
22800 (cond
22801 ((memq type '(headline inlinetask))
22802 (let ((pos (point)))
22803 (beginning-of-line 1)
22804 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22805 (if (eq special t)
22806 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22807 (goto-char (match-beginning 1))
22808 (goto-char (match-end 0)))
22809 (if (or (< pos (match-end 0))
22810 (not (eq this-command last-command)))
22811 (goto-char (match-end 0))
22812 (goto-char (match-beginning 1))))
22813 (call-interactively move-fun))))
22814 ((org-element-property :hiddenp element)
22815 ;; If element is hidden, `move-end-of-line' would put point
22816 ;; after it. Use `end-of-line' to stay on current line.
22817 (call-interactively 'end-of-line))
22818 (t (call-interactively move-fun)))))
22819 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22820 (setq disable-point-adjustment
22821 (or (not (invisible-p (point)))
22822 (not (invisible-p (max (point-min) (1- (point))))))))
22824 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22825 (define-key org-mode-map "\C-e" 'org-end-of-line)
22827 (defun org-backward-sentence (&optional arg)
22828 "Go to beginning of sentence, or beginning of table field.
22829 This will call `backward-sentence' or `org-table-beginning-of-field',
22830 depending on context."
22831 (interactive "P")
22832 (cond
22833 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22834 (t (call-interactively 'backward-sentence))))
22836 (defun org-forward-sentence (&optional arg)
22837 "Go to end of sentence, or end of table field.
22838 This will call `forward-sentence' or `org-table-end-of-field',
22839 depending on context."
22840 (interactive "P")
22841 (cond
22842 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22843 (t (call-interactively 'forward-sentence))))
22845 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22846 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22848 (defun org-kill-line (&optional arg)
22849 "Kill line, to tags or end of line."
22850 (interactive "P")
22851 (cond
22852 ((or (not org-special-ctrl-k)
22853 (bolp)
22854 (not (org-at-heading-p)))
22855 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22856 org-ctrl-k-protect-subtree)
22857 (if (or (eq org-ctrl-k-protect-subtree 'error)
22858 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22859 (user-error "C-k aborted as it would kill a hidden subtree")))
22860 (call-interactively
22861 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22862 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22863 (kill-region (point) (match-beginning 1))
22864 (org-set-tags nil t))
22865 (t (kill-region (point) (point-at-eol)))))
22867 (define-key org-mode-map "\C-k" 'org-kill-line)
22869 (defun org-yank (&optional arg)
22870 "Yank. If the kill is a subtree, treat it specially.
22871 This command will look at the current kill and check if is a single
22872 subtree, or a series of subtrees[1]. If it passes the test, and if the
22873 cursor is at the beginning of a line or after the stars of a currently
22874 empty headline, then the yank is handled specially. How exactly depends
22875 on the value of the following variables, both set by default.
22877 org-yank-folded-subtrees
22878 When set, the subtree(s) will be folded after insertion, but only
22879 if doing so would now swallow text after the yanked text.
22881 org-yank-adjusted-subtrees
22882 When set, the subtree will be promoted or demoted in order to
22883 fit into the local outline tree structure, which means that the level
22884 will be adjusted so that it becomes the smaller one of the two
22885 *visible* surrounding headings.
22887 Any prefix to this command will cause `yank' to be called directly with
22888 no special treatment. In particular, a simple \\[universal-argument] prefix \
22889 will just
22890 plainly yank the text as it is.
22892 \[1] The test checks if the first non-white line is a heading
22893 and if there are no other headings with fewer stars."
22894 (interactive "P")
22895 (org-yank-generic 'yank arg))
22897 (defun org-yank-generic (command arg)
22898 "Perform some yank-like command.
22900 This function implements the behavior described in the `org-yank'
22901 documentation. However, it has been generalized to work for any
22902 interactive command with similar behavior."
22904 ;; pretend to be command COMMAND
22905 (setq this-command command)
22907 (if arg
22908 (call-interactively command)
22910 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22911 (and (org-kill-is-subtree-p)
22912 (or (bolp)
22913 (and (looking-at "[ \t]*$")
22914 (string-match
22915 "\\`\\*+\\'"
22916 (buffer-substring (point-at-bol) (point)))))))
22917 swallowp)
22918 (cond
22919 ((and subtreep org-yank-folded-subtrees)
22920 (let ((beg (point))
22921 end)
22922 (if (and subtreep org-yank-adjusted-subtrees)
22923 (org-paste-subtree nil nil 'for-yank)
22924 (call-interactively command))
22926 (setq end (point))
22927 (goto-char beg)
22928 (when (and (bolp) subtreep
22929 (not (setq swallowp
22930 (org-yank-folding-would-swallow-text beg end))))
22931 (org-with-limited-levels
22932 (or (looking-at org-outline-regexp)
22933 (re-search-forward org-outline-regexp-bol end t))
22934 (while (and (< (point) end) (looking-at org-outline-regexp))
22935 (hide-subtree)
22936 (org-cycle-show-empty-lines 'folded)
22937 (condition-case nil
22938 (outline-forward-same-level 1)
22939 (error (goto-char end))))))
22940 (when swallowp
22941 (message
22942 "Inserted text not folded because that would swallow text"))
22944 (goto-char end)
22945 (skip-chars-forward " \t\n\r")
22946 (beginning-of-line 1)
22947 (push-mark beg 'nomsg)))
22948 ((and subtreep org-yank-adjusted-subtrees)
22949 (let ((beg (point-at-bol)))
22950 (org-paste-subtree nil nil 'for-yank)
22951 (push-mark beg 'nomsg)))
22953 (call-interactively command))))))
22955 (defun org-yank-folding-would-swallow-text (beg end)
22956 "Would hide-subtree at BEG swallow any text after END?"
22957 (let (level)
22958 (org-with-limited-levels
22959 (save-excursion
22960 (goto-char beg)
22961 (when (or (looking-at org-outline-regexp)
22962 (re-search-forward org-outline-regexp-bol end t))
22963 (setq level (org-outline-level)))
22964 (goto-char end)
22965 (skip-chars-forward " \t\r\n\v\f")
22966 (if (or (eobp)
22967 (and (bolp) (looking-at org-outline-regexp)
22968 (<= (org-outline-level) level)))
22969 nil ; Nothing would be swallowed
22970 t))))) ; something would swallow
22972 (define-key org-mode-map "\C-y" 'org-yank)
22974 (defun org-truely-invisible-p ()
22975 "Check if point is at a character currently not visible.
22976 This version does not only check the character property, but also
22977 `visible-mode'."
22978 ;; Early versions of noutline don't have `outline-invisible-p'.
22979 (if (org-bound-and-true-p visible-mode)
22981 (outline-invisible-p)))
22983 (defun org-invisible-p2 ()
22984 "Check if point is at a character currently not visible."
22985 (save-excursion
22986 (if (and (eolp) (not (bobp))) (backward-char 1))
22987 ;; Early versions of noutline don't have `outline-invisible-p'.
22988 (outline-invisible-p)))
22990 (defun org-back-to-heading (&optional invisible-ok)
22991 "Call `outline-back-to-heading', but provide a better error message."
22992 (condition-case nil
22993 (outline-back-to-heading invisible-ok)
22994 (error (error "Before first headline at position %d in buffer %s"
22995 (point) (current-buffer)))))
22997 (defun org-before-first-heading-p ()
22998 "Before first heading?"
22999 (save-excursion
23000 (end-of-line)
23001 (null (re-search-backward org-outline-regexp-bol nil t))))
23003 (defun org-at-heading-p (&optional ignored)
23004 (outline-on-heading-p t))
23005 ;; Compatibility alias with Org versions < 7.8.03
23006 (defalias 'org-on-heading-p 'org-at-heading-p)
23008 (defun org-at-comment-p nil
23009 "Is cursor in a line starting with a # character?"
23010 (save-excursion
23011 (beginning-of-line)
23012 (looking-at "^#")))
23014 (defun org-at-drawer-p nil
23015 "Is cursor at a drawer keyword?"
23016 (save-excursion
23017 (move-beginning-of-line 1)
23018 (looking-at org-drawer-regexp)))
23020 (defun org-at-block-p nil
23021 "Is cursor at a block keyword?"
23022 (save-excursion
23023 (move-beginning-of-line 1)
23024 (looking-at org-block-regexp)))
23026 (defun org-point-at-end-of-empty-headline ()
23027 "If point is at the end of an empty headline, return t, else nil.
23028 If the heading only contains a TODO keyword, it is still still considered
23029 empty."
23030 (and (looking-at "[ \t]*$")
23031 (when org-todo-line-regexp
23032 (save-excursion
23033 (beginning-of-line 1)
23034 (let ((case-fold-search nil))
23035 (looking-at org-todo-line-regexp)
23036 (string= (match-string 3) ""))))))
23038 (defun org-at-heading-or-item-p ()
23039 (or (org-at-heading-p) (org-at-item-p)))
23041 (defun org-at-target-p ()
23042 (or (org-in-regexp org-radio-target-regexp)
23043 (org-in-regexp org-target-regexp)))
23044 ;; Compatibility alias with Org versions < 7.8.03
23045 (defalias 'org-on-target-p 'org-at-target-p)
23047 (defun org-up-heading-all (arg)
23048 "Move to the heading line of which the present line is a subheading.
23049 This function considers both visible and invisible heading lines.
23050 With argument, move up ARG levels."
23051 (if (fboundp 'outline-up-heading-all)
23052 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23053 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23055 (defun org-up-heading-safe ()
23056 "Move to the heading line of which the present line is a subheading.
23057 This version will not throw an error. It will return the level of the
23058 headline found, or nil if no higher level is found.
23060 Also, this function will be a lot faster than `outline-up-heading',
23061 because it relies on stars being the outline starters. This can really
23062 make a significant difference in outlines with very many siblings."
23063 (let (start-level re)
23064 (org-back-to-heading t)
23065 (setq start-level (funcall outline-level))
23066 (if (equal start-level 1)
23068 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23069 (if (re-search-backward re nil t)
23070 (funcall outline-level)))))
23072 (defun org-first-sibling-p ()
23073 "Is this heading the first child of its parents?"
23074 (interactive)
23075 (let ((re org-outline-regexp-bol)
23076 level l)
23077 (unless (org-at-heading-p t)
23078 (user-error "Not at a heading"))
23079 (setq level (funcall outline-level))
23080 (save-excursion
23081 (if (not (re-search-backward re nil t))
23083 (setq l (funcall outline-level))
23084 (< l level)))))
23086 (defun org-goto-sibling (&optional previous)
23087 "Goto the next sibling, even if it is invisible.
23088 When PREVIOUS is set, go to the previous sibling instead. Returns t
23089 when a sibling was found. When none is found, return nil and don't
23090 move point."
23091 (let ((fun (if previous 're-search-backward 're-search-forward))
23092 (pos (point))
23093 (re org-outline-regexp-bol)
23094 level l)
23095 (when (condition-case nil (org-back-to-heading t) (error nil))
23096 (setq level (funcall outline-level))
23097 (catch 'exit
23098 (or previous (forward-char 1))
23099 (while (funcall fun re nil t)
23100 (setq l (funcall outline-level))
23101 (when (< l level) (goto-char pos) (throw 'exit nil))
23102 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23103 (goto-char pos)
23104 nil))))
23106 (defun org-show-siblings ()
23107 "Show all siblings of the current headline."
23108 (save-excursion
23109 (while (org-goto-sibling) (org-flag-heading nil)))
23110 (save-excursion
23111 (while (org-goto-sibling 'previous)
23112 (org-flag-heading nil))))
23114 (defun org-goto-first-child ()
23115 "Goto the first child, even if it is invisible.
23116 Return t when a child was found. Otherwise don't move point and
23117 return nil."
23118 (let (level (pos (point)) (re org-outline-regexp-bol))
23119 (when (condition-case nil (org-back-to-heading t) (error nil))
23120 (setq level (outline-level))
23121 (forward-char 1)
23122 (if (and (re-search-forward re nil t) (> (outline-level) level))
23123 (progn (goto-char (match-beginning 0)) t)
23124 (goto-char pos) nil))))
23126 (defun org-show-hidden-entry ()
23127 "Show an entry where even the heading is hidden."
23128 (save-excursion
23129 (org-show-entry)))
23131 (defun org-flag-heading (flag &optional entry)
23132 "Flag the current heading. FLAG non-nil means make invisible.
23133 When ENTRY is non-nil, show the entire entry."
23134 (save-excursion
23135 (org-back-to-heading t)
23136 ;; Check if we should show the entire entry
23137 (if entry
23138 (progn
23139 (org-show-entry)
23140 (save-excursion
23141 (and (outline-next-heading)
23142 (org-flag-heading nil))))
23143 (outline-flag-region (max (point-min) (1- (point)))
23144 (save-excursion (outline-end-of-heading) (point))
23145 flag))))
23147 (defun org-get-next-sibling ()
23148 "Move to next heading of the same level, and return point.
23149 If there is no such heading, return nil.
23150 This is like outline-next-sibling, but invisible headings are ok."
23151 (let ((level (funcall outline-level)))
23152 (outline-next-heading)
23153 (while (and (not (eobp)) (> (funcall outline-level) level))
23154 (outline-next-heading))
23155 (if (or (eobp) (< (funcall outline-level) level))
23157 (point))))
23159 (defun org-get-last-sibling ()
23160 "Move to previous heading of the same level, and return point.
23161 If there is no such heading, return nil."
23162 (let ((opoint (point))
23163 (level (funcall outline-level)))
23164 (outline-previous-heading)
23165 (when (and (/= (point) opoint) (outline-on-heading-p t))
23166 (while (and (> (funcall outline-level) level)
23167 (not (bobp)))
23168 (outline-previous-heading))
23169 (if (< (funcall outline-level) level)
23171 (point)))))
23173 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23174 "Goto to the end of a subtree."
23175 ;; This contains an exact copy of the original function, but it uses
23176 ;; `org-back-to-heading', to make it work also in invisible
23177 ;; trees. And is uses an invisible-ok argument.
23178 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23179 ;; Furthermore, when used inside Org, finding the end of a large subtree
23180 ;; with many children and grandchildren etc, this can be much faster
23181 ;; than the outline version.
23182 (org-back-to-heading invisible-ok)
23183 (let ((first t)
23184 (level (funcall outline-level)))
23185 (if (and (derived-mode-p 'org-mode) (< level 1000))
23186 ;; A true heading (not a plain list item), in Org-mode
23187 ;; This means we can easily find the end by looking
23188 ;; only for the right number of stars. Using a regexp to do
23189 ;; this is so much faster than using a Lisp loop.
23190 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23191 (forward-char 1)
23192 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23193 ;; something else, do it the slow way
23194 (while (and (not (eobp))
23195 (or first (> (funcall outline-level) level)))
23196 (setq first nil)
23197 (outline-next-heading)))
23198 (unless to-heading
23199 (if (memq (preceding-char) '(?\n ?\^M))
23200 (progn
23201 ;; Go to end of line before heading
23202 (forward-char -1)
23203 (if (memq (preceding-char) '(?\n ?\^M))
23204 ;; leave blank line before heading
23205 (forward-char -1))))))
23206 (point))
23208 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23209 "Use Org version in org-mode, for dramatic speed-up."
23210 (if (derived-mode-p 'org-mode)
23211 (progn
23212 (org-end-of-subtree nil t)
23213 (unless (eobp) (backward-char 1)))
23214 ad-do-it))
23216 (defun org-end-of-meta-data-and-drawers ()
23217 "Jump to the first text after meta data and drawers in the current entry.
23218 This will move over empty lines, lines with planning time stamps,
23219 clocking lines, and drawers."
23220 (org-back-to-heading t)
23221 (let ((end (save-excursion (outline-next-heading) (point)))
23222 (re (concat "\\(" org-drawer-regexp "\\)"
23223 "\\|" "[ \t]*" org-keyword-time-regexp)))
23224 (forward-line 1)
23225 (while (re-search-forward re end t)
23226 (if (not (match-end 1))
23227 ;; empty or planning line
23228 (forward-line 1)
23229 ;; a drawer, find the end
23230 (re-search-forward "^[ \t]*:END:" end 'move)
23231 (forward-line 1)))
23232 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23233 (point)))
23235 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23236 "Move forward to the ARG'th subheading at same level as this one.
23237 Stop at the first and last subheadings of a superior heading.
23238 Normally this only looks at visible headings, but when INVISIBLE-OK is
23239 non-nil it will also look at invisible ones."
23240 (interactive "p")
23241 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23242 (if (and arg (< arg 0))
23243 (goto-char (point-min))
23244 (outline-next-heading))
23245 (org-at-heading-p)
23246 (let ((level (- (match-end 0) (match-beginning 0) 1))
23247 (f (if (and arg (< arg 0))
23248 're-search-backward
23249 're-search-forward))
23250 (count (if arg (abs arg) 1))
23251 (result (point)))
23252 (while (and (prog1 (> count 0)
23253 (forward-char (if (and arg (< arg 0)) -1 1)))
23254 (funcall f org-outline-regexp-bol nil 'move))
23255 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23256 (cond ((< l level) (setq count 0))
23257 ((and (= l level)
23258 (or invisible-ok
23259 (progn
23260 (goto-char (line-beginning-position))
23261 (not (outline-invisible-p)))))
23262 (setq count (1- count))
23263 (when (eq l level)
23264 (setq result (point)))))))
23265 (goto-char result))
23266 (beginning-of-line 1)))
23268 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23269 "Move backward to the ARG'th subheading at same level as this one.
23270 Stop at the first and last subheadings of a superior heading."
23271 (interactive "p")
23272 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23274 (defun org-next-block (arg &optional backward block-regexp)
23275 "Jump to the next block.
23276 With a prefix argument ARG, jump forward ARG many source blocks.
23277 When BACKWARD is non-nil, jump to the previous block.
23278 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23279 (interactive "p")
23280 (let ((re (or block-regexp org-block-regexp))
23281 (re-search-fn (or (and backward 're-search-backward)
23282 're-search-forward)))
23283 (if (looking-at re) (forward-char 1))
23284 (condition-case nil
23285 (funcall re-search-fn re nil nil arg)
23286 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23287 (goto-char (match-beginning 0)) (org-show-context)))
23289 (defun org-previous-block (arg &optional block-regexp)
23290 "Jump to the previous block.
23291 With a prefix argument ARG, jump backward ARG many source blocks.
23292 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23293 (interactive "p")
23294 (org-next-block arg t block-regexp))
23296 (defun org-forward-paragraph ()
23297 "Move forward to beginning of next paragraph or equivalent.
23299 The function moves point to the beginning of the next visible
23300 structural element, which can be a paragraph, a table, a list
23301 item, etc. It also provides some special moves for convenience:
23303 - On an affiliated keyword, jump to the beginning of the
23304 relative element.
23305 - On an item or a footnote definition, move to the second
23306 element inside, if any.
23307 - On a table or a property drawer, jump after it.
23308 - On a verse or source block, stop after blank lines."
23309 (interactive)
23310 (when (eobp) (user-error "Cannot move further down"))
23311 (let* ((deactivate-mark nil)
23312 (element (org-element-at-point))
23313 (type (org-element-type element))
23314 (post-affiliated (org-element-property :post-affiliated element))
23315 (contents-begin (org-element-property :contents-begin element))
23316 (contents-end (org-element-property :contents-end element))
23317 (end (let ((end (org-element-property :end element)) (parent element))
23318 (while (and (setq parent (org-element-property :parent parent))
23319 (= (org-element-property :contents-end parent) end))
23320 (setq end (org-element-property :end parent)))
23321 end)))
23322 (cond ((not element)
23323 (skip-chars-forward " \r\t\n")
23324 (or (eobp) (beginning-of-line)))
23325 ;; On affiliated keywords, move to element's beginning.
23326 ((and post-affiliated (< (point) post-affiliated))
23327 (goto-char post-affiliated))
23328 ;; At a table row, move to the end of the table. Similarly,
23329 ;; at a node property, move to the end of the property
23330 ;; drawer.
23331 ((memq type '(node-property table-row))
23332 (goto-char (org-element-property
23333 :end (org-element-property :parent element))))
23334 ((memq type '(property-drawer table)) (goto-char end))
23335 ;; Consider blank lines as separators in verse and source
23336 ;; blocks to ease editing.
23337 ((memq type '(src-block verse-block))
23338 (when (eq type 'src-block)
23339 (setq contents-end
23340 (save-excursion (goto-char end)
23341 (skip-chars-backward " \r\t\n")
23342 (line-beginning-position))))
23343 (beginning-of-line)
23344 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23345 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23346 (goto-char end)
23347 (skip-chars-forward " \r\t\n")
23348 (if (= (point) contents-end) (goto-char end)
23349 (beginning-of-line))))
23350 ;; With no contents, just skip element.
23351 ((not contents-begin) (goto-char end))
23352 ;; If contents are invisible, skip the element altogether.
23353 ((outline-invisible-p (line-end-position))
23354 (case type
23355 (headline
23356 (org-with-limited-levels (outline-next-visible-heading 1)))
23357 ;; At a plain list, make sure we move to the next item
23358 ;; instead of skipping the whole list.
23359 (plain-list (forward-char)
23360 (org-forward-paragraph))
23361 (otherwise (goto-char end))))
23362 ((>= (point) contents-end) (goto-char end))
23363 ((>= (point) contents-begin)
23364 ;; This can only happen on paragraphs and plain lists.
23365 (case type
23366 (paragraph (goto-char end))
23367 ;; At a plain list, try to move to second element in
23368 ;; first item, if possible.
23369 (plain-list (end-of-line)
23370 (org-forward-paragraph))))
23371 ;; When contents start on the middle of a line (e.g. in
23372 ;; items and footnote definitions), try to reach first
23373 ;; element starting after current line.
23374 ((> (line-end-position) contents-begin)
23375 (end-of-line)
23376 (org-forward-paragraph))
23377 (t (goto-char contents-begin)))))
23379 (defun org-backward-paragraph ()
23380 "Move backward to start of previous paragraph or equivalent.
23382 The function moves point to the beginning of the current
23383 structural element, which can be a paragraph, a table, a list
23384 item, etc., or to the beginning of the previous visible one if
23385 point is already there. It also provides some special moves for
23386 convenience:
23388 - On an affiliated keyword, jump to the first one.
23389 - On a table or a property drawer, move to its beginning.
23390 - On a verse or source block, stop before blank lines."
23391 (interactive)
23392 (when (bobp) (user-error "Cannot move further up"))
23393 (let* ((deactivate-mark nil)
23394 (element (org-element-at-point))
23395 (type (org-element-type element))
23396 (contents-begin (org-element-property :contents-begin element))
23397 (contents-end (org-element-property :contents-end element))
23398 (post-affiliated (org-element-property :post-affiliated element))
23399 (begin (org-element-property :begin element)))
23400 (cond
23401 ((not element) (goto-char (point-min)))
23402 ((= (point) begin)
23403 (backward-char)
23404 (org-backward-paragraph))
23405 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23406 ((memq type '(node-property table-row))
23407 (goto-char (org-element-property
23408 :post-affiliated (org-element-property :parent element))))
23409 ((memq type '(property-drawer table)) (goto-char begin))
23410 ((memq type '(src-block verse-block))
23411 (when (eq type 'src-block)
23412 (setq contents-begin
23413 (save-excursion (goto-char begin) (forward-line) (point))))
23414 (if (= (point) contents-begin) (goto-char post-affiliated)
23415 ;; Inside a verse block, see blank lines as paragraph
23416 ;; separators.
23417 (let ((origin (point)))
23418 (skip-chars-backward " \r\t\n" contents-begin)
23419 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23420 (skip-chars-forward " \r\t\n" origin)
23421 (if (= (point) origin) (goto-char contents-begin)
23422 (beginning-of-line))))))
23423 ((not contents-begin) (goto-char (or post-affiliated begin)))
23424 ((eq type 'paragraph)
23425 (goto-char contents-begin)
23426 ;; When at first paragraph in an item or a footnote definition,
23427 ;; move directly to beginning of line.
23428 (let ((parent-contents
23429 (org-element-property
23430 :contents-begin (org-element-property :parent element))))
23431 (when (and parent-contents (= parent-contents contents-begin))
23432 (beginning-of-line))))
23433 ;; At the end of a greater element, move to the beginning of the
23434 ;; last element within.
23435 ((>= (point) contents-end)
23436 (goto-char (1- contents-end))
23437 (org-backward-paragraph))
23438 (t (goto-char (or post-affiliated begin))))
23439 ;; Ensure we never leave point invisible.
23440 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23442 (defun org-forward-element ()
23443 "Move forward by one element.
23444 Move to the next element at the same level, when possible."
23445 (interactive)
23446 (cond ((eobp) (user-error "Cannot move further down"))
23447 ((org-with-limited-levels (org-at-heading-p))
23448 (let ((origin (point)))
23449 (goto-char (org-end-of-subtree nil t))
23450 (unless (org-with-limited-levels (org-at-heading-p))
23451 (goto-char origin)
23452 (user-error "Cannot move further down"))))
23454 (let* ((elem (org-element-at-point))
23455 (end (org-element-property :end elem))
23456 (parent (org-element-property :parent elem)))
23457 (cond ((and parent (= (org-element-property :contents-end parent) end))
23458 (goto-char (org-element-property :end parent)))
23459 ((integer-or-marker-p end) (goto-char end))
23460 (t (message "No element at point")))))))
23462 (defun org-backward-element ()
23463 "Move backward by one element.
23464 Move to the previous element at the same level, when possible."
23465 (interactive)
23466 (cond ((bobp) (user-error "Cannot move further up"))
23467 ((org-with-limited-levels (org-at-heading-p))
23468 ;; At a headline, move to the previous one, if any, or stay
23469 ;; here.
23470 (let ((origin (point)))
23471 (org-with-limited-levels (org-backward-heading-same-level 1))
23472 ;; When current headline has no sibling above, move to its
23473 ;; parent.
23474 (when (= (point) origin)
23475 (or (org-with-limited-levels (org-up-heading-safe))
23476 (progn (goto-char origin)
23477 (user-error "Cannot move further up"))))))
23479 (let* ((trail (org-element-at-point 'keep-trail))
23480 (elem (car trail))
23481 (prev-elem (nth 1 trail))
23482 (beg (org-element-property :begin elem)))
23483 (cond
23484 ;; Move to beginning of current element if point isn't
23485 ;; there already.
23486 ((null beg) (message "No element at point"))
23487 ((/= (point) beg) (goto-char beg))
23488 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23489 ((org-before-first-heading-p) (goto-char (point-min)))
23490 (t (org-back-to-heading)))))))
23492 (defun org-up-element ()
23493 "Move to upper element."
23494 (interactive)
23495 (if (org-with-limited-levels (org-at-heading-p))
23496 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23497 (let* ((elem (org-element-at-point))
23498 (parent (org-element-property :parent elem)))
23499 (if parent (goto-char (org-element-property :begin parent))
23500 (if (org-with-limited-levels (org-before-first-heading-p))
23501 (user-error "No surrounding element")
23502 (org-with-limited-levels (org-back-to-heading)))))))
23504 (defvar org-element-greater-elements)
23505 (defun org-down-element ()
23506 "Move to inner element."
23507 (interactive)
23508 (let ((element (org-element-at-point)))
23509 (cond
23510 ((memq (org-element-type element) '(plain-list table))
23511 (goto-char (org-element-property :contents-begin element))
23512 (forward-char))
23513 ((memq (org-element-type element) org-element-greater-elements)
23514 ;; If contents are hidden, first disclose them.
23515 (when (org-element-property :hiddenp element) (org-cycle))
23516 (goto-char (or (org-element-property :contents-begin element)
23517 (user-error "No content for this element"))))
23518 (t (user-error "No inner element")))))
23520 (defun org-drag-element-backward ()
23521 "Move backward element at point."
23522 (interactive)
23523 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23524 (let* ((trail (org-element-at-point 'keep-trail))
23525 (elem (car trail))
23526 (prev-elem (nth 1 trail)))
23527 ;; Error out if no previous element or previous element is
23528 ;; a parent of the current one.
23529 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23530 (user-error "Cannot drag element backward")
23531 (let ((pos (point)))
23532 (org-element-swap-A-B prev-elem elem)
23533 (goto-char (+ (org-element-property :begin prev-elem)
23534 (- pos (org-element-property :begin elem)))))))))
23536 (defun org-drag-element-forward ()
23537 "Move forward element at point."
23538 (interactive)
23539 (let* ((pos (point))
23540 (elem (org-element-at-point)))
23541 (when (= (point-max) (org-element-property :end elem))
23542 (user-error "Cannot drag element forward"))
23543 (goto-char (org-element-property :end elem))
23544 (let ((next-elem (org-element-at-point)))
23545 (when (or (org-element-nested-p elem next-elem)
23546 (and (eq (org-element-type next-elem) 'headline)
23547 (not (eq (org-element-type elem) 'headline))))
23548 (goto-char pos)
23549 (user-error "Cannot drag element forward"))
23550 ;; Compute new position of point: it's shifted by NEXT-ELEM
23551 ;; body's length (without final blanks) and by the length of
23552 ;; blanks between ELEM and NEXT-ELEM.
23553 (let ((size-next (- (save-excursion
23554 (goto-char (org-element-property :end next-elem))
23555 (skip-chars-backward " \r\t\n")
23556 (forward-line)
23557 ;; Small correction if buffer doesn't end
23558 ;; with a newline character.
23559 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23560 (org-element-property :begin next-elem)))
23561 (size-blank (- (org-element-property :end elem)
23562 (save-excursion
23563 (goto-char (org-element-property :end elem))
23564 (skip-chars-backward " \r\t\n")
23565 (forward-line)
23566 (point)))))
23567 (org-element-swap-A-B elem next-elem)
23568 (goto-char (+ pos size-next size-blank))))))
23570 (defun org-drag-line-forward (arg)
23571 "Drag the line at point ARG lines forward."
23572 (interactive "p")
23573 (dotimes (n (abs arg))
23574 (let ((c (current-column)))
23575 (if (< 0 arg)
23576 (progn
23577 (beginning-of-line 2)
23578 (transpose-lines 1)
23579 (beginning-of-line 0))
23580 (transpose-lines 1)
23581 (beginning-of-line -1))
23582 (org-move-to-column c))))
23584 (defun org-drag-line-backward (arg)
23585 "Drag the line at point ARG lines backward."
23586 (interactive "p")
23587 (org-drag-line-forward (- arg)))
23589 (defun org-mark-element ()
23590 "Put point at beginning of this element, mark at end.
23592 Interactively, if this command is repeated or (in Transient Mark
23593 mode) if the mark is active, it marks the next element after the
23594 ones already marked."
23595 (interactive)
23596 (let (deactivate-mark)
23597 (if (and (org-called-interactively-p 'any)
23598 (or (and (eq last-command this-command) (mark t))
23599 (and transient-mark-mode mark-active)))
23600 (set-mark
23601 (save-excursion
23602 (goto-char (mark))
23603 (goto-char (org-element-property :end (org-element-at-point)))))
23604 (let ((element (org-element-at-point)))
23605 (end-of-line)
23606 (push-mark (org-element-property :end element) t t)
23607 (goto-char (org-element-property :begin element))))))
23609 (defun org-narrow-to-element ()
23610 "Narrow buffer to current element."
23611 (interactive)
23612 (let ((elem (org-element-at-point)))
23613 (cond
23614 ((eq (car elem) 'headline)
23615 (narrow-to-region
23616 (org-element-property :begin elem)
23617 (org-element-property :end elem)))
23618 ((memq (car elem) org-element-greater-elements)
23619 (narrow-to-region
23620 (org-element-property :contents-begin elem)
23621 (org-element-property :contents-end elem)))
23623 (narrow-to-region
23624 (org-element-property :begin elem)
23625 (org-element-property :end elem))))))
23627 (defun org-transpose-element ()
23628 "Transpose current and previous elements, keeping blank lines between.
23629 Point is moved after both elements."
23630 (interactive)
23631 (org-skip-whitespace)
23632 (let ((end (org-element-property :end (org-element-at-point))))
23633 (org-drag-element-backward)
23634 (goto-char end)))
23636 (defun org-unindent-buffer ()
23637 "Un-indent the visible part of the buffer.
23638 Relative indentation (between items, inside blocks, etc.) isn't
23639 modified."
23640 (interactive)
23641 (unless (eq major-mode 'org-mode)
23642 (user-error "Cannot un-indent a buffer not in Org mode"))
23643 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23644 unindent-tree ; For byte-compiler.
23645 (unindent-tree
23646 (function
23647 (lambda (contents)
23648 (mapc
23649 (lambda (element)
23650 (if (memq (org-element-type element) '(headline section))
23651 (funcall unindent-tree (org-element-contents element))
23652 (save-excursion
23653 (save-restriction
23654 (narrow-to-region
23655 (org-element-property :begin element)
23656 (org-element-property :end element))
23657 (org-do-remove-indentation)))))
23658 (reverse contents))))))
23659 (funcall unindent-tree (org-element-contents parse-tree))))
23661 (defun org-show-subtree ()
23662 "Show everything after this heading at deeper levels."
23663 (interactive)
23664 (outline-flag-region
23665 (point)
23666 (save-excursion
23667 (org-end-of-subtree t t))
23668 nil))
23670 (defun org-show-entry ()
23671 "Show the body directly following this heading.
23672 Show the heading too, if it is currently invisible."
23673 (interactive)
23674 (save-excursion
23675 (condition-case nil
23676 (progn
23677 (org-back-to-heading t)
23678 (outline-flag-region
23679 (max (point-min) (1- (point)))
23680 (save-excursion
23681 (if (re-search-forward
23682 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23683 (match-beginning 1)
23684 (point-max)))
23685 nil)
23686 (org-cycle-hide-drawers 'children))
23687 (error nil))))
23689 (defun org-make-options-regexp (kwds &optional extra)
23690 "Make a regular expression for keyword lines."
23691 (concat
23692 "^#\\+\\("
23693 (mapconcat 'regexp-quote kwds "\\|")
23694 (if extra (concat "\\|" extra))
23695 "\\):[ \t]*\\(.*\\)"))
23697 ;; Make isearch reveal the necessary context
23698 (defun org-isearch-end ()
23699 "Reveal context after isearch exits."
23700 (when isearch-success ; only if search was successful
23701 (if (featurep 'xemacs)
23702 ;; Under XEmacs, the hook is run in the correct place,
23703 ;; we directly show the context.
23704 (org-show-context 'isearch)
23705 ;; In Emacs the hook runs *before* restoring the overlays.
23706 ;; So we have to use a one-time post-command-hook to do this.
23707 ;; (Emacs 22 has a special variable, see function `org-mode')
23708 (unless (and (boundp 'isearch-mode-end-hook-quit)
23709 isearch-mode-end-hook-quit)
23710 ;; Only when the isearch was not quitted.
23711 (org-add-hook 'post-command-hook 'org-isearch-post-command
23712 'append 'local)))
23713 (org-fix-ellipsis-at-bol)))
23715 (defun org-isearch-post-command ()
23716 "Remove self from hook, and show context."
23717 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23718 (org-show-context 'isearch))
23721 ;;;; Integration with and fixes for other packages
23723 ;;; Imenu support
23725 (defvar org-imenu-markers nil
23726 "All markers currently used by Imenu.")
23727 (make-variable-buffer-local 'org-imenu-markers)
23729 (defun org-imenu-new-marker (&optional pos)
23730 "Return a new marker for use by Imenu, and remember the marker."
23731 (let ((m (make-marker)))
23732 (move-marker m (or pos (point)))
23733 (push m org-imenu-markers)
23736 (defun org-imenu-get-tree ()
23737 "Produce the index for Imenu."
23738 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23739 (setq org-imenu-markers nil)
23740 (let* ((n org-imenu-depth)
23741 (re (concat "^" (org-get-limited-outline-regexp)))
23742 (subs (make-vector (1+ n) nil))
23743 (last-level 0)
23744 m level head0 head)
23745 (save-excursion
23746 (save-restriction
23747 (widen)
23748 (goto-char (point-max))
23749 (while (re-search-backward re nil t)
23750 (setq level (org-reduced-level (funcall outline-level)))
23751 (when (and (<= level n)
23752 (looking-at org-complex-heading-regexp)
23753 (setq head0 (org-match-string-no-properties 4)))
23754 (setq head (org-link-display-format head0)
23755 m (org-imenu-new-marker))
23756 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23757 (if (>= level last-level)
23758 (push (cons head m) (aref subs level))
23759 (push (cons head (aref subs (1+ level))) (aref subs level))
23760 (loop for i from (1+ level) to n do (aset subs i nil)))
23761 (setq last-level level)))))
23762 (aref subs 1)))
23764 (eval-after-load "imenu"
23765 '(progn
23766 (add-hook 'imenu-after-jump-hook
23767 (lambda ()
23768 (if (derived-mode-p 'org-mode)
23769 (org-show-context 'org-goto))))))
23771 (defun org-link-display-format (link)
23772 "Replace a link with its the description.
23773 If there is no description, use the link target."
23774 (save-match-data
23775 (if (string-match org-bracket-link-analytic-regexp link)
23776 (replace-match (if (match-end 5)
23777 (match-string 5 link)
23778 (concat (match-string 1 link)
23779 (match-string 3 link)))
23780 nil t link)
23781 link)))
23783 (defun org-toggle-link-display ()
23784 "Toggle the literal or descriptive display of links."
23785 (interactive)
23786 (if org-descriptive-links
23787 (progn (org-remove-from-invisibility-spec '(org-link))
23788 (org-restart-font-lock)
23789 (setq org-descriptive-links nil))
23790 (progn (add-to-invisibility-spec '(org-link))
23791 (org-restart-font-lock)
23792 (setq org-descriptive-links t))))
23794 ;; Speedbar support
23796 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23797 "Overlay marking the agenda restriction line in speedbar.")
23798 (overlay-put org-speedbar-restriction-lock-overlay
23799 'face 'org-agenda-restriction-lock)
23800 (overlay-put org-speedbar-restriction-lock-overlay
23801 'help-echo "Agendas are currently limited to this item.")
23802 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23804 (defun org-speedbar-set-agenda-restriction ()
23805 "Restrict future agenda commands to the location at point in speedbar.
23806 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23807 (interactive)
23808 (require 'org-agenda)
23809 (let (p m tp np dir txt)
23810 (cond
23811 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23812 'org-imenu t))
23813 (setq m (get-text-property p 'org-imenu-marker))
23814 (with-current-buffer (marker-buffer m)
23815 (goto-char m)
23816 (org-agenda-set-restriction-lock 'subtree)))
23817 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23818 'speedbar-function 'speedbar-find-file))
23819 (setq tp (previous-single-property-change
23820 (1+ p) 'speedbar-function)
23821 np (next-single-property-change
23822 tp 'speedbar-function)
23823 dir (speedbar-line-directory)
23824 txt (buffer-substring-no-properties (or tp (point-min))
23825 (or np (point-max))))
23826 (with-current-buffer (find-file-noselect
23827 (let ((default-directory dir))
23828 (expand-file-name txt)))
23829 (unless (derived-mode-p 'org-mode)
23830 (user-error "Cannot restrict to non-Org-mode file"))
23831 (org-agenda-set-restriction-lock 'file)))
23832 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23833 (move-overlay org-speedbar-restriction-lock-overlay
23834 (point-at-bol) (point-at-eol))
23835 (setq current-prefix-arg nil)
23836 (org-agenda-maybe-redo)))
23838 (defvar speedbar-file-key-map)
23839 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23840 (eval-after-load "speedbar"
23841 '(progn
23842 (speedbar-add-supported-extension ".org")
23843 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23844 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23845 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23846 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23847 (add-hook 'speedbar-visiting-tag-hook
23848 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23850 ;;; Fixes and Hacks for problems with other packages
23852 ;; Make flyspell not check words in links, to not mess up our keymap
23853 (defvar org-element-affiliated-keywords) ; From org-element.el
23854 (defvar org-element-block-name-alist) ; From org-element.el
23855 (defun org-mode-flyspell-verify ()
23856 "Don't let flyspell put overlays at active buttons, or on
23857 {todo,all-time,additional-option-like}-keywords."
23858 (require 'org-element) ; For `org-element-affiliated-keywords'
23859 (let ((pos (max (1- (point)) (point-min)))
23860 (word (thing-at-point 'word)))
23861 (and (not (get-text-property pos 'keymap))
23862 (not (get-text-property pos 'org-no-flyspell))
23863 (not (member word org-todo-keywords-1))
23864 (not (member word org-all-time-keywords))
23865 (not (member word org-options-keywords))
23866 (not (member word (mapcar 'car org-startup-options)))
23867 (not (member-ignore-case word org-element-affiliated-keywords))
23868 (not (member-ignore-case word (org-get-export-keywords)))
23869 (not (member-ignore-case
23870 word (mapcar 'car org-element-block-name-alist)))
23871 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23872 (not (org-in-src-block-p)))))
23874 (defun org-remove-flyspell-overlays-in (beg end)
23875 "Remove flyspell overlays in region."
23876 (and (org-bound-and-true-p flyspell-mode)
23877 (fboundp 'flyspell-delete-region-overlays)
23878 (flyspell-delete-region-overlays beg end))
23879 (add-text-properties beg end '(org-no-flyspell t)))
23881 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23882 (eval-after-load "bookmark"
23883 '(if (boundp 'bookmark-after-jump-hook)
23884 ;; We can use the hook
23885 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23886 ;; Hook not available, use advice
23887 (defadvice bookmark-jump (after org-make-visible activate)
23888 "Make the position visible."
23889 (org-bookmark-jump-unhide))))
23891 ;; Make sure saveplace shows the location if it was hidden
23892 (eval-after-load "saveplace"
23893 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23894 "Make the position visible."
23895 (org-bookmark-jump-unhide)))
23897 ;; Make sure ecb shows the location if it was hidden
23898 (eval-after-load "ecb"
23899 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23900 "Make hierarchy visible when jumping into location from ECB tree buffer."
23901 (if (derived-mode-p 'org-mode)
23902 (org-show-context))))
23904 (defun org-bookmark-jump-unhide ()
23905 "Unhide the current position, to show the bookmark location."
23906 (and (derived-mode-p 'org-mode)
23907 (or (outline-invisible-p)
23908 (save-excursion (goto-char (max (point-min) (1- (point))))
23909 (outline-invisible-p)))
23910 (org-show-context 'bookmark-jump)))
23912 ;; Make session.el ignore our circular variable
23913 (defvar session-globals-exclude)
23914 (eval-after-load "session"
23915 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23917 ;;;; Finish up
23919 (provide 'org)
23921 (run-hooks 'org-load-hook)
23923 ;;; org.el ends here