org-element: Implement caching for dynamic parser
[org-mode.git] / lisp / org.el
blob15323bab400d2725c64fd007a1361e7cad829189
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-cache-reset "org-element" (&optional all))
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-context "org-element" (&optional element))
146 (declare-function org-element-interpret-data "org-element"
147 (data &optional parent))
148 (declare-function org-element-map "org-element"
149 (data types fun &optional info first-match no-recursion))
150 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
151 (declare-function org-element-parse-buffer "org-element"
152 (&optional granularity visible-only))
153 (declare-function org-element-property "org-element" (property element))
154 (declare-function org-element-put-property "org-element"
155 (element property value))
156 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
157 (declare-function org-element--parse-objects "org-element"
158 (beg end acc restriction))
159 (declare-function org-element-parse-buffer "org-element"
160 (&optional granularity visible-only))
161 (declare-function org-element-restriction "org-element" (element))
162 (declare-function org-element-type "org-element" (element))
164 ;; load languages based on value of `org-babel-load-languages'
165 (defvar org-babel-load-languages)
167 ;;;###autoload
168 (defun org-babel-do-load-languages (sym value)
169 "Load the languages defined in `org-babel-load-languages'."
170 (set-default sym value)
171 (mapc (lambda (pair)
172 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
173 (if active
174 (progn
175 (require (intern (concat "ob-" lang))))
176 (progn
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-execute:" lang)))
179 (funcall 'fmakunbound
180 (intern (concat "org-babel-expand-body:" lang)))))))
181 org-babel-load-languages))
183 ;;;###autoload
184 (defun org-babel-load-file (file &optional compile)
185 "Load Emacs Lisp source code blocks in the Org-mode FILE.
186 This function exports the source code using `org-babel-tangle'
187 and then loads the resulting file using `load-file'. With prefix
188 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
189 file to byte-code before it is loaded."
190 (interactive "fFile to load: \nP")
191 (require 'ob-core)
192 (let* ((age (lambda (file)
193 (float-time
194 (time-subtract (current-time)
195 (nth 5 (or (file-attributes (file-truename file))
196 (file-attributes file)))))))
197 (base-name (file-name-sans-extension file))
198 (exported-file (concat base-name ".el")))
199 ;; tangle if the org-mode file is newer than the elisp file
200 (unless (and (file-exists-p exported-file)
201 (> (funcall age file) (funcall age exported-file)))
202 (org-babel-tangle-file file exported-file "emacs-lisp"))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite)
267 (const :tag "ebnf2ps" ebnf2ps))
268 :value-type (boolean :tag "Activate" :value t)))
270 ;;;; Customization variables
271 (defcustom org-clone-delete-id nil
272 "Remove ID property of clones of a subtree.
273 When non-nil, clones of a subtree don't inherit the ID property.
274 Otherwise they inherit the ID property with a new unique
275 identifier."
276 :type 'boolean
277 :version "24.1"
278 :group 'org-id)
280 ;;; Version
281 (org-check-version)
283 ;;;###autoload
284 (defun org-version (&optional here full message)
285 "Show the org-mode version in the echo area.
286 With prefix argument HERE, insert it at point.
287 When FULL is non-nil, use a verbose version string.
288 When MESSAGE is non-nil, display a message with the version."
289 (interactive "P")
290 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
291 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
292 (load-suffixes (list ".el"))
293 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
294 (org-trash (or
295 (and (fboundp 'org-release) (fboundp 'org-git-version))
296 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
297 (load-suffixes save-load-suffixes)
298 (org-version (org-release))
299 (git-version (org-git-version))
300 (version (format "Org-mode version %s (%s @ %s)"
301 org-version
302 git-version
303 (if org-install-dir
304 (if (string= org-dir org-install-dir)
305 org-install-dir
306 (concat "mixed installation! " org-install-dir " and " org-dir))
307 "org-loaddefs.el can not be found!")))
308 (_version (if full version org-version)))
309 (if (org-called-interactively-p 'interactive)
310 (if here
311 (insert version)
312 (message version))
313 (if message (message _version))
314 _version)))
316 (defconst org-version (org-version))
318 ;;; Compatibility constants
320 ;;; The custom variables
322 (defgroup org nil
323 "Outline-based notes management and organizer."
324 :tag "Org"
325 :group 'outlines
326 :group 'calendar)
328 (defcustom org-mode-hook nil
329 "Mode hook for Org-mode, run after the mode was turned on."
330 :group 'org
331 :type 'hook)
333 (defcustom org-load-hook nil
334 "Hook that is run after org.el has been loaded."
335 :group 'org
336 :type 'hook)
338 (defcustom org-log-buffer-setup-hook nil
339 "Hook that is run after an Org log buffer is created."
340 :group 'org
341 :version "24.1"
342 :type 'hook)
344 (defvar org-modules) ; defined below
345 (defvar org-modules-loaded nil
346 "Have the modules been loaded already?")
348 (defun org-load-modules-maybe (&optional force)
349 "Load all extensions listed in `org-modules'."
350 (when (or force (not org-modules-loaded))
351 (mapc (lambda (ext)
352 (condition-case nil (require ext)
353 (error (message "Problems while trying to load feature `%s'" ext))))
354 org-modules)
355 (setq org-modules-loaded t)))
357 (defun org-set-modules (var value)
358 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
359 (set var value)
360 (when (featurep 'org)
361 (org-load-modules-maybe 'force)
362 (org-element-cache-reset 'all)))
364 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
365 "Modules that should always be loaded together with org.el.
367 If a description starts with <C>, the file is not part of Emacs
368 and loading it will require that you have downloaded and properly
369 installed the Org mode distribution.
371 You can also use this system to load external packages (i.e. neither Org
372 core modules, nor modules from the CONTRIB directory). Just add symbols
373 to the end of the list. If the package is called org-xyz.el, then you need
374 to add the symbol `xyz', and the package must have a call to:
376 \(provide 'org-xyz)
378 For export specific modules, see also `org-export-backends'."
379 :group 'org
380 :set 'org-set-modules
381 :version "24.4"
382 :package-version '(Org . "8.0")
383 :type
384 '(set :greedy t
385 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
386 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
387 (const :tag " crypt: Encryption of subtrees" org-crypt)
388 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
389 (const :tag " docview: Links to doc-view buffers" org-docview)
390 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
391 (const :tag " habit: Track your consistency with habits" org-habit)
392 (const :tag " id: Global IDs for identifying entries" org-id)
393 (const :tag " info: Links to Info nodes" org-info)
394 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
395 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
396 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
397 (const :tag " mouse: Additional mouse support" org-mouse)
398 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
399 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
400 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
402 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
403 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
404 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
405 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
406 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
407 (const :tag "C collector: Collect properties into tables" org-collector)
408 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
409 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
410 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
411 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
412 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
413 (const :tag "C eval: Include command output as text" org-eval)
414 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
415 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
416 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
417 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
418 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
419 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
420 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
421 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
422 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
423 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
424 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
425 (const :tag "C mew: Links to Mew folders/messages" org-mew)
426 (const :tag "C mtags: Support for muse-like tags" org-mtags)
427 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
428 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
429 (const :tag "C registry: A registry for Org-mode links" org-registry)
430 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
431 (const :tag "C secretary: Team management with org-mode" org-secretary)
432 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
433 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
434 (const :tag "C track: Keep up with Org-mode development" org-track)
435 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
436 (const :tag "C vm: Links to VM folders/messages" org-vm)
437 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
438 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
439 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
441 (defvar org-export--registered-backends) ; From ox.el.
442 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
443 (declare-function org-export-backend-name "ox" (backend))
444 (defcustom org-export-backends '(ascii html icalendar latex)
445 "List of export back-ends that should be always available.
447 If a description starts with <C>, the file is not part of Emacs
448 and loading it will require that you have downloaded and properly
449 installed the Org mode distribution.
451 Unlike to `org-modules', libraries in this list will not be
452 loaded along with Org, but only once the export framework is
453 needed.
455 This variable needs to be set before org.el is loaded. If you
456 need to make a change while Emacs is running, use the customize
457 interface or run the following code, where VAL stands for the new
458 value of the variable, after updating it:
460 \(progn
461 \(setq org-export--registered-backends
462 \(org-remove-if-not
463 \(lambda (backend)
464 \(let ((name (org-export-backend-name backend)))
465 \(or (memq name val)
466 \(catch 'parentp
467 \(dolist (b val)
468 \(and (org-export-derived-backend-p b name)
469 \(throw 'parentp t)))))))
470 org-export--registered-backends))
471 \(let ((new-list (mapcar 'org-export-backend-name
472 org-export--registered-backends)))
473 \(dolist (backend val)
474 \(cond
475 \((not (load (format \"ox-%s\" backend) t t))
476 \(message \"Problems while trying to load export back-end `%s'\"
477 backend))
478 \((not (memq backend new-list)) (push backend new-list))))
479 \(set-default 'org-export-backends new-list)))
481 Adding a back-end to this list will also pull the back-end it
482 depends on, if any."
483 :group 'org
484 :group 'org-export
485 :version "24.4"
486 :package-version '(Org . "8.0")
487 :initialize 'custom-initialize-set
488 :set (lambda (var val)
489 (if (not (featurep 'ox)) (set-default var val)
490 ;; Any back-end not required anymore (not present in VAL and not
491 ;; a parent of any back-end in the new value) is removed from the
492 ;; list of registered back-ends.
493 (setq org-export--registered-backends
494 (org-remove-if-not
495 (lambda (backend)
496 (let ((name (org-export-backend-name backend)))
497 (or (memq name val)
498 (catch 'parentp
499 (dolist (b val)
500 (and (org-export-derived-backend-p b name)
501 (throw 'parentp t)))))))
502 org-export--registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'org-export-backend-name
506 org-export--registered-backends)))
507 (dolist (backend val)
508 (cond
509 ((not (load (format "ox-%s" backend) t t))
510 (message "Problems while trying to load export back-end `%s'"
511 backend))
512 ((not (memq backend new-list)) (push backend new-list))))
513 ;; Set VAR to that list with fixed dependencies.
514 (set-default var new-list))))
515 :type '(set :greedy t
516 (const :tag " ascii Export buffer to ASCII format" ascii)
517 (const :tag " beamer Export buffer to Beamer presentation" beamer)
518 (const :tag " html Export buffer to HTML format" html)
519 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
520 (const :tag " latex Export buffer to LaTeX format" latex)
521 (const :tag " man Export buffer to MAN format" man)
522 (const :tag " md Export buffer to Markdown format" md)
523 (const :tag " odt Export buffer to ODT format" odt)
524 (const :tag " org Export buffer to Org format" org)
525 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
526 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
527 (const :tag "C deck Export buffer to deck.js presentations" deck)
528 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
529 (const :tag "C groff Export buffer to Groff format" groff)
530 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
531 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
532 (const :tag "C s5 Export buffer to s5 presentations" s5)
533 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
535 (eval-after-load 'ox
536 '(mapc
537 (lambda (backend)
538 (condition-case nil (require (intern (format "ox-%s" backend)))
539 (error (message "Problems while trying to load export back-end `%s'"
540 backend))))
541 org-export-backends))
543 (defcustom org-support-shift-select nil
544 "Non-nil means make shift-cursor commands select text when possible.
546 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
547 start selecting a region, or enlarge regions started in this way.
548 In Org-mode, in special contexts, these same keys are used for
549 other purposes, important enough to compete with shift selection.
550 Org tries to balance these needs by supporting `shift-select-mode'
551 outside these special contexts, under control of this variable.
553 The default of this variable is nil, to avoid confusing behavior. Shifted
554 cursor keys will then execute Org commands in the following contexts:
555 - on a headline, changing TODO state (left/right) and priority (up/down)
556 - on a time stamp, changing the time
557 - in a plain list item, changing the bullet type
558 - in a property definition line, switching between allowed values
559 - in the BEGIN line of a clock table (changing the time block).
560 Outside these contexts, the commands will throw an error.
562 When this variable is t and the cursor is not in a special
563 context, Org-mode will support shift-selection for making and
564 enlarging regions. To make this more effective, the bullet
565 cycling will no longer happen anywhere in an item line, but only
566 if the cursor is exactly on the bullet.
568 If you set this variable to the symbol `always', then the keys
569 will not be special in headlines, property lines, and item lines,
570 to make shift selection work there as well. If this is what you
571 want, you can use the following alternative commands: `C-c C-t'
572 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
573 can be used to switch TODO sets, `C-c -' to cycle item bullet
574 types, and properties can be edited by hand or in column view.
576 However, when the cursor is on a timestamp, shift-cursor commands
577 will still edit the time stamp - this is just too good to give up.
579 XEmacs user should have this variable set to nil, because
580 `shift-select-mode' is in Emacs 23 or later only."
581 :group 'org
582 :type '(choice
583 (const :tag "Never" nil)
584 (const :tag "When outside special context" t)
585 (const :tag "Everywhere except timestamps" always)))
587 (defcustom org-loop-over-headlines-in-active-region nil
588 "Shall some commands act upon headlines in the active region?
590 When set to `t', some commands will be performed in all headlines
591 within the active region.
593 When set to `start-level', some commands will be performed in all
594 headlines within the active region, provided that these headlines
595 are of the same level than the first one.
597 When set to a string, those commands will be performed on the
598 matching headlines within the active region. Such string must be
599 a tags/property/todo match as it is used in the agenda tags view.
601 The list of commands is: `org-schedule', `org-deadline',
602 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
603 `org-archive-to-archive-sibling'. The archiving commands skip
604 already archived entries."
605 :type '(choice (const :tag "Don't loop" nil)
606 (const :tag "All headlines in active region" t)
607 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
608 (string :tag "Tags/Property/Todo matcher"))
609 :version "24.1"
610 :group 'org-todo
611 :group 'org-archive)
613 (defgroup org-startup nil
614 "Options concerning startup of Org-mode."
615 :tag "Org Startup"
616 :group 'org)
618 (defcustom org-startup-folded t
619 "Non-nil means entering Org-mode will switch to OVERVIEW.
620 This can also be configured on a per-file basis by adding one of
621 the following lines anywhere in the buffer:
623 #+STARTUP: fold (or `overview', this is equivalent)
624 #+STARTUP: nofold (or `showall', this is equivalent)
625 #+STARTUP: content
626 #+STARTUP: showeverything
628 By default, this option is ignored when Org opens agenda files
629 for the first time. If you want the agenda to honor the startup
630 option, set `org-agenda-inhibit-startup' to nil."
631 :group 'org-startup
632 :type '(choice
633 (const :tag "nofold: show all" nil)
634 (const :tag "fold: overview" t)
635 (const :tag "content: all headlines" content)
636 (const :tag "show everything, even drawers" showeverything)))
638 (defcustom org-startup-truncated t
639 "Non-nil means entering Org-mode will set `truncate-lines'.
640 This is useful since some lines containing links can be very long and
641 uninteresting. Also tables look terrible when wrapped."
642 :group 'org-startup
643 :type 'boolean)
645 (defcustom org-startup-indented nil
646 "Non-nil means turn on `org-indent-mode' on startup.
647 This can also be configured on a per-file basis by adding one of
648 the following lines anywhere in the buffer:
650 #+STARTUP: indent
651 #+STARTUP: noindent"
652 :group 'org-structure
653 :type '(choice
654 (const :tag "Not" nil)
655 (const :tag "Globally (slow on startup in large files)" t)))
657 (defcustom org-use-sub-superscripts t
658 "Non-nil means interpret \"_\" and \"^\" for display.
659 When this option is turned on, you can use TeX-like syntax for sub- and
660 superscripts. Several characters after \"_\" or \"^\" will be
661 considered as a single item - so grouping with {} is normally not
662 needed. For example, the following things will be parsed as single
663 sub- or superscripts.
665 10^24 or 10^tau several digits will be considered 1 item.
666 10^-12 or 10^-tau a leading sign with digits or a word
667 x^2-y^3 will be read as x^2 - y^3, because items are
668 terminated by almost any nonword/nondigit char.
669 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
671 Still, ambiguity is possible - so when in doubt use {} to enclose
672 the sub/superscript. If you set this variable to the symbol
673 `{}', the braces are *required* in order to trigger
674 interpretations as sub/superscript. This can be helpful in
675 documents that need \"_\" frequently in plain text."
676 :group 'org-startup
677 :version "24.1"
678 :type '(choice
679 (const :tag "Always interpret" t)
680 (const :tag "Only with braces" {})
681 (const :tag "Never interpret" nil)))
683 (defcustom org-startup-with-beamer-mode nil
684 "Non-nil means turn on `org-beamer-mode' on startup.
685 This can also be configured on a per-file basis by adding one of
686 the following lines anywhere in the buffer:
688 #+STARTUP: beamer"
689 :group 'org-startup
690 :version "24.1"
691 :type 'boolean)
693 (defcustom org-startup-align-all-tables nil
694 "Non-nil means align all tables when visiting a file.
695 This is useful when the column width in tables is forced with <N> cookies
696 in table fields. Such tables will look correct only after the first re-align.
697 This can also be configured on a per-file basis by adding one of
698 the following lines anywhere in the buffer:
699 #+STARTUP: align
700 #+STARTUP: noalign"
701 :group 'org-startup
702 :type 'boolean)
704 (defcustom org-startup-with-inline-images nil
705 "Non-nil means show inline images when loading a new Org file.
706 This can also be configured on a per-file basis by adding one of
707 the following lines anywhere in the buffer:
708 #+STARTUP: inlineimages
709 #+STARTUP: noinlineimages"
710 :group 'org-startup
711 :version "24.1"
712 :type 'boolean)
714 (defcustom org-startup-with-latex-preview nil
715 "Non-nil means preview LaTeX fragments when loading a new Org file.
717 This can also be configured on a per-file basis by adding one of
718 the followinglines anywhere in the buffer:
719 #+STARTUP: latexpreview
720 #+STARTUP: nolatexpreview"
721 :group 'org-startup
722 :version "24.4"
723 :package-version '(Org . "8.0")
724 :type 'boolean)
726 (defcustom org-insert-mode-line-in-empty-file nil
727 "Non-nil means insert the first line setting Org-mode in empty files.
728 When the function `org-mode' is called interactively in an empty file, this
729 normally means that the file name does not automatically trigger Org-mode.
730 To ensure that the file will always be in Org-mode in the future, a
731 line enforcing Org-mode will be inserted into the buffer, if this option
732 has been set."
733 :group 'org-startup
734 :type 'boolean)
736 (defcustom org-replace-disputed-keys nil
737 "Non-nil means use alternative key bindings for some keys.
738 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
739 These keys are also used by other packages like shift-selection-mode'
740 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
741 If you want to use Org-mode together with one of these other modes,
742 or more generally if you would like to move some Org-mode commands to
743 other keys, set this variable and configure the keys with the variable
744 `org-disputed-keys'.
746 This option is only relevant at load-time of Org-mode, and must be set
747 *before* org.el is loaded. Changing it requires a restart of Emacs to
748 become effective."
749 :group 'org-startup
750 :type 'boolean)
752 (defcustom org-use-extra-keys nil
753 "Non-nil means use extra key sequence definitions for certain commands.
754 This happens automatically if you run XEmacs or if `window-system'
755 is nil. This variable lets you do the same manually. You must
756 set it before loading org.
758 Example: on Carbon Emacs 22 running graphically, with an external
759 keyboard on a Powerbook, the default way of setting M-left might
760 not work for either Alt or ESC. Setting this variable will make
761 it work for ESC."
762 :group 'org-startup
763 :type 'boolean)
765 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
767 (defcustom org-disputed-keys
768 '(([(shift up)] . [(meta p)])
769 ([(shift down)] . [(meta n)])
770 ([(shift left)] . [(meta -)])
771 ([(shift right)] . [(meta +)])
772 ([(control shift right)] . [(meta shift +)])
773 ([(control shift left)] . [(meta shift -)]))
774 "Keys for which Org-mode and other modes compete.
775 This is an alist, cars are the default keys, second element specifies
776 the alternative to use when `org-replace-disputed-keys' is t.
778 Keys can be specified in any syntax supported by `define-key'.
779 The value of this option takes effect only at Org-mode's startup,
780 therefore you'll have to restart Emacs to apply it after changing."
781 :group 'org-startup
782 :type 'alist)
784 (defun org-key (key)
785 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
786 Or return the original if not disputed.
787 Also apply the translations defined in `org-xemacs-key-equivalents'."
788 (when org-replace-disputed-keys
789 (let* ((nkey (key-description key))
790 (x (org-find-if (lambda (x)
791 (equal (key-description (car x)) nkey))
792 org-disputed-keys)))
793 (setq key (if x (cdr x) key))))
794 (when (featurep 'xemacs)
795 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
796 key)
798 (defun org-find-if (predicate seq)
799 (catch 'exit
800 (while seq
801 (if (funcall predicate (car seq))
802 (throw 'exit (car seq))
803 (pop seq)))))
805 (defun org-defkey (keymap key def)
806 "Define a key, possibly translated, as returned by `org-key'."
807 (define-key keymap (org-key key) def))
809 (defcustom org-ellipsis nil
810 "The ellipsis to use in the Org-mode outline.
811 When nil, just use the standard three dots. When a string, use that instead,
812 When a face, use the standard 3 dots, but with the specified face.
813 The change affects only Org-mode (which will then use its own display table).
814 Changing this requires executing `M-x org-mode' in a buffer to become
815 effective."
816 :group 'org-startup
817 :type '(choice (const :tag "Default" nil)
818 (face :tag "Face" :value org-warning)
819 (string :tag "String" :value "...#")))
821 (defvar org-display-table nil
822 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
824 (defgroup org-keywords nil
825 "Keywords in Org-mode."
826 :tag "Org Keywords"
827 :group 'org)
829 (defcustom org-deadline-string "DEADLINE:"
830 "String to mark deadline entries.
831 A deadline is this string, followed by a time stamp. Should be a word,
832 terminated by a colon. You can insert a schedule keyword and
833 a timestamp with \\[org-deadline].
834 Changes become only effective after restarting Emacs."
835 :group 'org-keywords
836 :type 'string)
838 (defcustom org-scheduled-string "SCHEDULED:"
839 "String to mark scheduled TODO entries.
840 A schedule is this string, followed by a time stamp. Should be a word,
841 terminated by a colon. You can insert a schedule keyword and
842 a timestamp with \\[org-schedule].
843 Changes become only effective after restarting Emacs."
844 :group 'org-keywords
845 :type 'string)
847 (defcustom org-closed-string "CLOSED:"
848 "String used as the prefix for timestamps logging closing a TODO entry."
849 :group 'org-keywords
850 :type 'string)
852 (defcustom org-clock-string "CLOCK:"
853 "String used as prefix for timestamps clocking work hours on an item."
854 :group 'org-keywords
855 :type 'string)
857 (defcustom org-closed-keep-when-no-todo nil
858 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
859 :group 'org-todo
860 :group 'org-keywords
861 :version "24.4"
862 :package-version '(Org . "8.0")
863 :type 'boolean)
865 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
866 org-scheduled-string "\\|"
867 org-deadline-string "\\|"
868 org-closed-string "\\|"
869 org-clock-string "\\)")
870 "Matches a line with planning or clock info.")
872 (defcustom org-comment-string "COMMENT"
873 "Entries starting with this keyword will never be exported.
874 An entry can be toggled between COMMENT and normal with
875 \\[org-toggle-comment].
876 Changes become only effective after restarting Emacs."
877 :group 'org-keywords
878 :type 'string)
880 (defcustom org-quote-string "QUOTE"
881 "Entries starting with this keyword will be exported in fixed-width font.
882 Quoting applies only to the text in the entry following the headline, and does
883 not extend beyond the next headline, even if that is lower level.
884 An entry can be toggled between QUOTE and normal with
885 \\[org-toggle-fixed-width-section]."
886 :group 'org-keywords
887 :type 'string)
889 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
890 "Matches first line of a hidden block.
891 Group 1 contains drawer's name.")
893 (defconst org-repeat-re
894 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
895 "Regular expression for specifying repeated events.
896 After a match, group 1 contains the repeat expression.")
898 (defgroup org-structure nil
899 "Options concerning the general structure of Org-mode files."
900 :tag "Org Structure"
901 :group 'org)
903 (defgroup org-reveal-location nil
904 "Options about how to make context of a location visible."
905 :tag "Org Reveal Location"
906 :group 'org-structure)
908 (defconst org-context-choice
909 '(choice
910 (const :tag "Always" t)
911 (const :tag "Never" nil)
912 (repeat :greedy t :tag "Individual contexts"
913 (cons
914 (choice :tag "Context"
915 (const agenda)
916 (const org-goto)
917 (const occur-tree)
918 (const tags-tree)
919 (const link-search)
920 (const mark-goto)
921 (const bookmark-jump)
922 (const isearch)
923 (const default))
924 (boolean))))
925 "Contexts for the reveal options.")
927 (defcustom org-show-hierarchy-above '((default . t))
928 "Non-nil means show full hierarchy when revealing a location.
929 Org-mode often shows locations in an org-mode file which might have
930 been invisible before. When this is set, the hierarchy of headings
931 above the exposed location is shown.
932 Turning this off for example for sparse trees makes them very compact.
933 Instead of t, this can also be an alist specifying this option for different
934 contexts. Valid contexts are
935 agenda when exposing an entry from the agenda
936 org-goto when using the command `org-goto' on key C-c C-j
937 occur-tree when using the command `org-occur' on key C-c /
938 tags-tree when constructing a sparse tree based on tags matches
939 link-search when exposing search matches associated with a link
940 mark-goto when exposing the jump goal of a mark
941 bookmark-jump when exposing a bookmark location
942 isearch when exiting from an incremental search
943 default default for all contexts not set explicitly"
944 :group 'org-reveal-location
945 :type org-context-choice)
947 (defcustom org-show-following-heading '((default . nil))
948 "Non-nil means show following heading when revealing a location.
949 Org-mode often shows locations in an org-mode file which might have
950 been invisible before. When this is set, the heading following the
951 match is shown.
952 Turning this off for example for sparse trees makes them very compact,
953 but makes it harder to edit the location of the match. In such a case,
954 use the command \\[org-reveal] to show more context.
955 Instead of t, this can also be an alist specifying this option for different
956 contexts. See `org-show-hierarchy-above' for valid contexts."
957 :group 'org-reveal-location
958 :type org-context-choice)
960 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
961 "Non-nil means show all sibling heading when revealing a location.
962 Org-mode often shows locations in an org-mode file which might have
963 been invisible before. When this is set, the sibling of the current entry
964 heading are all made visible. If `org-show-hierarchy-above' is t,
965 the same happens on each level of the hierarchy above the current entry.
967 By default this is on for the isearch context, off for all other contexts.
968 Turning this off for example for sparse trees makes them very compact,
969 but makes it harder to edit the location of the match. In such a case,
970 use the command \\[org-reveal] to show more context.
971 Instead of t, this can also be an alist specifying this option for different
972 contexts. See `org-show-hierarchy-above' for valid contexts."
973 :group 'org-reveal-location
974 :type org-context-choice
975 :version "24.4"
976 :package-version '(Org . "8.0"))
978 (defcustom org-show-entry-below '((default . nil))
979 "Non-nil means show the entry below a headline when revealing a location.
980 Org-mode often shows locations in an org-mode file which might have
981 been invisible before. When this is set, the text below the headline that is
982 exposed is also shown.
984 By default this is off for all contexts.
985 Instead of t, this can also be an alist specifying this option for different
986 contexts. See `org-show-hierarchy-above' for valid contexts."
987 :group 'org-reveal-location
988 :type org-context-choice)
990 (defcustom org-indirect-buffer-display 'other-window
991 "How should indirect tree buffers be displayed?
992 This applies to indirect buffers created with the commands
993 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
994 Valid values are:
995 current-window Display in the current window
996 other-window Just display in another window.
997 dedicated-frame Create one new frame, and re-use it each time.
998 new-frame Make a new frame each time. Note that in this case
999 previously-made indirect buffers are kept, and you need to
1000 kill these buffers yourself."
1001 :group 'org-structure
1002 :group 'org-agenda-windows
1003 :type '(choice
1004 (const :tag "In current window" current-window)
1005 (const :tag "In current frame, other window" other-window)
1006 (const :tag "Each time a new frame" new-frame)
1007 (const :tag "One dedicated frame" dedicated-frame)))
1009 (defcustom org-use-speed-commands nil
1010 "Non-nil means activate single letter commands at beginning of a headline.
1011 This may also be a function to test for appropriate locations where speed
1012 commands should be active."
1013 :group 'org-structure
1014 :type '(choice
1015 (const :tag "Never" nil)
1016 (const :tag "At beginning of headline stars" t)
1017 (function)))
1019 (defcustom org-speed-commands-user nil
1020 "Alist of additional speed commands.
1021 This list will be checked before `org-speed-commands-default'
1022 when the variable `org-use-speed-commands' is non-nil
1023 and when the cursor is at the beginning of a headline.
1024 The car if each entry is a string with a single letter, which must
1025 be assigned to `self-insert-command' in the global map.
1026 The cdr is either a command to be called interactively, a function
1027 to be called, or a form to be evaluated.
1028 An entry that is just a list with a single string will be interpreted
1029 as a descriptive headline that will be added when listing the speed
1030 commands in the Help buffer using the `?' speed command."
1031 :group 'org-structure
1032 :type '(repeat :value ("k" . ignore)
1033 (choice :value ("k" . ignore)
1034 (list :tag "Descriptive Headline" (string :tag "Headline"))
1035 (cons :tag "Letter and Command"
1036 (string :tag "Command letter")
1037 (choice
1038 (function)
1039 (sexp))))))
1041 (defcustom org-bookmark-names-plist
1042 '(:last-capture "org-capture-last-stored"
1043 :last-refile "org-refile-last-stored"
1044 :last-capture-marker "org-capture-last-stored-marker")
1045 "Names for bookmarks automatically set by some Org commands.
1046 This can provide strings as names for a number of bookmakrs Org sets
1047 automatically. The following keys are currently implemented:
1048 :last-capture
1049 :last-capture-marker
1050 :last-refile
1051 When a key does not show up in the property list, the corresponding bookmark
1052 is not set."
1053 :group 'org-structure
1054 :type 'plist)
1056 (defgroup org-cycle nil
1057 "Options concerning visibility cycling in Org-mode."
1058 :tag "Org Cycle"
1059 :group 'org-structure)
1061 (defcustom org-cycle-skip-children-state-if-no-children t
1062 "Non-nil means skip CHILDREN state in entries that don't have any."
1063 :group 'org-cycle
1064 :type 'boolean)
1066 (defcustom org-cycle-max-level nil
1067 "Maximum level which should still be subject to visibility cycling.
1068 Levels higher than this will, for cycling, be treated as text, not a headline.
1069 When `org-odd-levels-only' is set, a value of N in this variable actually
1070 means 2N-1 stars as the limiting headline.
1071 When nil, cycle all levels.
1072 Note that the limiting level of cycling is also influenced by
1073 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1074 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1075 than its value."
1076 :group 'org-cycle
1077 :type '(choice
1078 (const :tag "No limit" nil)
1079 (integer :tag "Maximum level")))
1081 (defcustom org-hide-block-startup nil
1082 "Non-nil means entering Org-mode will fold all blocks.
1083 This can also be set in on a per-file basis with
1085 #+STARTUP: hideblocks
1086 #+STARTUP: showblocks"
1087 :group 'org-startup
1088 :group 'org-cycle
1089 :type 'boolean)
1091 (defcustom org-cycle-global-at-bob nil
1092 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1093 This makes it possible to do global cycling without having to use S-TAB or
1094 \\[universal-argument] TAB. For this special case to work, the first line
1095 of the buffer must not be a headline -- it may be empty or some other text.
1096 When used in this way, `org-cycle-hook' is disabled temporarily to make
1097 sure the cursor stays at the beginning of the buffer. When this option is
1098 nil, don't do anything special at the beginning of the buffer."
1099 :group 'org-cycle
1100 :type 'boolean)
1102 (defcustom org-cycle-level-after-item/entry-creation t
1103 "Non-nil means cycle entry level or item indentation in new empty entries.
1105 When the cursor is at the end of an empty headline, i.e., with only stars
1106 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1107 and then all possible ancestor states, before returning to the original state.
1108 This makes data entry extremely fast: M-RET to create a new headline,
1109 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1111 When the cursor is at the end of an empty plain list item, one TAB will
1112 make it a subitem, two or more tabs will back up to make this an item
1113 higher up in the item hierarchy."
1114 :group 'org-cycle
1115 :type 'boolean)
1117 (defcustom org-cycle-emulate-tab t
1118 "Where should `org-cycle' emulate TAB.
1119 nil Never
1120 white Only in completely white lines
1121 whitestart Only at the beginning of lines, before the first non-white char
1122 t Everywhere except in headlines
1123 exc-hl-bol Everywhere except at the start of a headline
1124 If TAB is used in a place where it does not emulate TAB, the current subtree
1125 visibility is cycled."
1126 :group 'org-cycle
1127 :type '(choice (const :tag "Never" nil)
1128 (const :tag "Only in completely white lines" white)
1129 (const :tag "Before first char in a line" whitestart)
1130 (const :tag "Everywhere except in headlines" t)
1131 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1133 (defcustom org-cycle-separator-lines 2
1134 "Number of empty lines needed to keep an empty line between collapsed trees.
1135 If you leave an empty line between the end of a subtree and the following
1136 headline, this empty line is hidden when the subtree is folded.
1137 Org-mode will leave (exactly) one empty line visible if the number of
1138 empty lines is equal or larger to the number given in this variable.
1139 So the default 2 means at least 2 empty lines after the end of a subtree
1140 are needed to produce free space between a collapsed subtree and the
1141 following headline.
1143 If the number is negative, and the number of empty lines is at least -N,
1144 all empty lines are shown.
1146 Special case: when 0, never leave empty lines in collapsed view."
1147 :group 'org-cycle
1148 :type 'integer)
1149 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1151 (defcustom org-pre-cycle-hook nil
1152 "Hook that is run before visibility cycling is happening.
1153 The function(s) in this hook must accept a single argument which indicates
1154 the new state that will be set right after running this hook. The
1155 argument is a symbol. Before a global state change, it can have the values
1156 `overview', `content', or `all'. Before a local state change, it can have
1157 the values `folded', `children', or `subtree'."
1158 :group 'org-cycle
1159 :type 'hook)
1161 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1162 org-cycle-hide-drawers
1163 org-cycle-hide-inline-tasks
1164 org-cycle-show-empty-lines
1165 org-optimize-window-after-visibility-change)
1166 "Hook that is run after `org-cycle' has changed the buffer visibility.
1167 The function(s) in this hook must accept a single argument which indicates
1168 the new state that was set by the most recent `org-cycle' command. The
1169 argument is a symbol. After a global state change, it can have the values
1170 `overview', `contents', or `all'. After a local state change, it can have
1171 the values `folded', `children', or `subtree'."
1172 :group 'org-cycle
1173 :type 'hook)
1175 (defgroup org-edit-structure nil
1176 "Options concerning structure editing in Org-mode."
1177 :tag "Org Edit Structure"
1178 :group 'org-structure)
1180 (defcustom org-odd-levels-only nil
1181 "Non-nil means skip even levels and only use odd levels for the outline.
1182 This has the effect that two stars are being added/taken away in
1183 promotion/demotion commands. It also influences how levels are
1184 handled by the exporters.
1185 Changing it requires restart of `font-lock-mode' to become effective
1186 for fontification also in regions already fontified.
1187 You may also set this on a per-file basis by adding one of the following
1188 lines to the buffer:
1190 #+STARTUP: odd
1191 #+STARTUP: oddeven"
1192 :group 'org-edit-structure
1193 :group 'org-appearance
1194 :type 'boolean)
1196 (defcustom org-adapt-indentation t
1197 "Non-nil means adapt indentation to outline node level.
1199 When this variable is set, Org assumes that you write outlines by
1200 indenting text in each node to align with the headline (after the stars).
1201 The following issues are influenced by this variable:
1203 - When this is set and the *entire* text in an entry is indented, the
1204 indentation is increased by one space in a demotion command, and
1205 decreased by one in a promotion command. If any line in the entry
1206 body starts with text at column 0, indentation is not changed at all.
1208 - Property drawers and planning information is inserted indented when
1209 this variable s set. When nil, they will not be indented.
1211 - TAB indents a line relative to context. The lines below a headline
1212 will be indented when this variable is set.
1214 Note that this is all about true indentation, by adding and removing
1215 space characters. See also `org-indent.el' which does level-dependent
1216 indentation in a virtual way, i.e. at display time in Emacs."
1217 :group 'org-edit-structure
1218 :type 'boolean)
1220 (defcustom org-special-ctrl-a/e nil
1221 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1223 When t, `C-a' will bring back the cursor to the beginning of the
1224 headline text, i.e. after the stars and after a possible TODO
1225 keyword. In an item, this will be the position after bullet and
1226 check-box, if any. When the cursor is already at that position,
1227 another `C-a' will bring it to the beginning of the line.
1229 `C-e' will jump to the end of the headline, ignoring the presence
1230 of tags in the headline. A second `C-e' will then jump to the
1231 true end of the line, after any tags. This also means that, when
1232 this variable is non-nil, `C-e' also will never jump beyond the
1233 end of the heading of a folded section, i.e. not after the
1234 ellipses.
1236 When set to the symbol `reversed', the first `C-a' or `C-e' works
1237 normally, going to the true line boundary first. Only a directly
1238 following, identical keypress will bring the cursor to the
1239 special positions.
1241 This may also be a cons cell where the behavior for `C-a' and
1242 `C-e' is set separately."
1243 :group 'org-edit-structure
1244 :type '(choice
1245 (const :tag "off" nil)
1246 (const :tag "on: after stars/bullet and before tags first" t)
1247 (const :tag "reversed: true line boundary first" reversed)
1248 (cons :tag "Set C-a and C-e separately"
1249 (choice :tag "Special C-a"
1250 (const :tag "off" nil)
1251 (const :tag "on: after stars/bullet first" t)
1252 (const :tag "reversed: before stars/bullet first" reversed))
1253 (choice :tag "Special C-e"
1254 (const :tag "off" nil)
1255 (const :tag "on: before tags first" t)
1256 (const :tag "reversed: after tags first" reversed)))))
1257 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1259 (defcustom org-special-ctrl-k nil
1260 "Non-nil means `C-k' will behave specially in headlines.
1261 When nil, `C-k' will call the default `kill-line' command.
1262 When t, the following will happen while the cursor is in the headline:
1264 - When the cursor is at the beginning of a headline, kill the entire
1265 line and possible the folded subtree below the line.
1266 - When in the middle of the headline text, kill the headline up to the tags.
1267 - When after the headline text, kill the tags."
1268 :group 'org-edit-structure
1269 :type 'boolean)
1271 (defcustom org-ctrl-k-protect-subtree nil
1272 "Non-nil means, do not delete a hidden subtree with C-k.
1273 When set to the symbol `error', simply throw an error when C-k is
1274 used to kill (part-of) a headline that has hidden text behind it.
1275 Any other non-nil value will result in a query to the user, if it is
1276 OK to kill that hidden subtree. When nil, kill without remorse."
1277 :group 'org-edit-structure
1278 :version "24.1"
1279 :type '(choice
1280 (const :tag "Do not protect hidden subtrees" nil)
1281 (const :tag "Protect hidden subtrees with a security query" t)
1282 (const :tag "Never kill a hidden subtree with C-k" error)))
1284 (defcustom org-special-ctrl-o t
1285 "Non-nil means, make `C-o' insert a row in tables."
1286 :group 'org-edit-structure
1287 :type 'boolean)
1289 (defcustom org-catch-invisible-edits nil
1290 "Check if in invisible region before inserting or deleting a character.
1291 Valid values are:
1293 nil Do not check, so just do invisible edits.
1294 error Throw an error and do nothing.
1295 show Make point visible, and do the requested edit.
1296 show-and-error Make point visible, then throw an error and abort the edit.
1297 smart Make point visible, and do insertion/deletion if it is
1298 adjacent to visible text and the change feels predictable.
1299 Never delete a previously invisible character or add in the
1300 middle or right after an invisible region. Basically, this
1301 allows insertion and backward-delete right before ellipses.
1302 FIXME: maybe in this case we should not even show?"
1303 :group 'org-edit-structure
1304 :version "24.1"
1305 :type '(choice
1306 (const :tag "Do not check" nil)
1307 (const :tag "Throw error when trying to edit" error)
1308 (const :tag "Unhide, but do not do the edit" show-and-error)
1309 (const :tag "Show invisible part and do the edit" show)
1310 (const :tag "Be smart and do the right thing" smart)))
1312 (defcustom org-yank-folded-subtrees t
1313 "Non-nil means when yanking subtrees, fold them.
1314 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1315 it starts with a heading and all other headings in it are either children
1316 or siblings, then fold all the subtrees. However, do this only if no
1317 text after the yank would be swallowed into a folded tree by this action."
1318 :group 'org-edit-structure
1319 :type 'boolean)
1321 (defcustom org-yank-adjusted-subtrees nil
1322 "Non-nil means when yanking subtrees, adjust the level.
1323 With this setting, `org-paste-subtree' is used to insert the subtree, see
1324 this function for details."
1325 :group 'org-edit-structure
1326 :type 'boolean)
1328 (defcustom org-M-RET-may-split-line '((default . t))
1329 "Non-nil means M-RET will split the line at the cursor position.
1330 When nil, it will go to the end of the line before making a
1331 new line.
1332 You may also set this option in a different way for different
1333 contexts. Valid contexts are:
1335 headline when creating a new headline
1336 item when creating a new item
1337 table in a table field
1338 default the value to be used for all contexts not explicitly
1339 customized"
1340 :group 'org-structure
1341 :group 'org-table
1342 :type '(choice
1343 (const :tag "Always" t)
1344 (const :tag "Never" nil)
1345 (repeat :greedy t :tag "Individual contexts"
1346 (cons
1347 (choice :tag "Context"
1348 (const headline)
1349 (const item)
1350 (const table)
1351 (const default))
1352 (boolean)))))
1355 (defcustom org-insert-heading-respect-content nil
1356 "Non-nil means insert new headings after the current subtree.
1357 When nil, the new heading is created directly after the current line.
1358 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1359 this variable on for the duration of the command."
1360 :group 'org-structure
1361 :type 'boolean)
1363 (defcustom org-blank-before-new-entry '((heading . auto)
1364 (plain-list-item . auto))
1365 "Should `org-insert-heading' leave a blank line before new heading/item?
1366 The value is an alist, with `heading' and `plain-list-item' as CAR,
1367 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1368 which case Org will look at the surrounding headings/items and try to
1369 make an intelligent decision whether to insert a blank line or not.
1371 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1372 the setting here is ignored and no empty line is inserted to avoid breaking
1373 the list structure."
1374 :group 'org-edit-structure
1375 :type '(list
1376 (cons (const heading)
1377 (choice (const :tag "Never" nil)
1378 (const :tag "Always" t)
1379 (const :tag "Auto" auto)))
1380 (cons (const plain-list-item)
1381 (choice (const :tag "Never" nil)
1382 (const :tag "Always" t)
1383 (const :tag "Auto" auto)))))
1385 (defcustom org-insert-heading-hook nil
1386 "Hook being run after inserting a new heading."
1387 :group 'org-edit-structure
1388 :type 'hook)
1390 (defcustom org-enable-fixed-width-editor t
1391 "Non-nil means lines starting with \":\" are treated as fixed-width.
1392 This currently only means they are never auto-wrapped.
1393 When nil, such lines will be treated like ordinary lines.
1394 See also the QUOTE keyword."
1395 :group 'org-edit-structure
1396 :type 'boolean)
1398 (defcustom org-goto-auto-isearch t
1399 "Non-nil means typing characters in `org-goto' starts incremental search.
1400 When nil, you can use these keybindings to navigate the buffer:
1402 q Quit the org-goto interface
1403 n Go to the next visible heading
1404 p Go to the previous visible heading
1405 f Go one heading forward on same level
1406 b Go one heading backward on same level
1407 u Go one heading up"
1408 :group 'org-edit-structure
1409 :type 'boolean)
1411 (defgroup org-sparse-trees nil
1412 "Options concerning sparse trees in Org-mode."
1413 :tag "Org Sparse Trees"
1414 :group 'org-structure)
1416 (defcustom org-highlight-sparse-tree-matches t
1417 "Non-nil means highlight all matches that define a sparse tree.
1418 The highlights will automatically disappear the next time the buffer is
1419 changed by an edit command."
1420 :group 'org-sparse-trees
1421 :type 'boolean)
1423 (defcustom org-remove-highlights-with-change t
1424 "Non-nil means any change to the buffer will remove temporary highlights.
1425 Such highlights are created by `org-occur' and `org-clock-display'.
1426 When nil, `C-c C-c needs to be used to get rid of the highlights.
1427 The highlights created by `org-preview-latex-fragment' always need
1428 `C-c C-c' to be removed."
1429 :group 'org-sparse-trees
1430 :group 'org-time
1431 :type 'boolean)
1434 (defcustom org-occur-hook '(org-first-headline-recenter)
1435 "Hook that is run after `org-occur' has constructed a sparse tree.
1436 This can be used to recenter the window to show as much of the structure
1437 as possible."
1438 :group 'org-sparse-trees
1439 :type 'hook)
1441 (defgroup org-imenu-and-speedbar nil
1442 "Options concerning imenu and speedbar in Org-mode."
1443 :tag "Org Imenu and Speedbar"
1444 :group 'org-structure)
1446 (defcustom org-imenu-depth 2
1447 "The maximum level for Imenu access to Org-mode headlines.
1448 This also applied for speedbar access."
1449 :group 'org-imenu-and-speedbar
1450 :type 'integer)
1452 (defgroup org-table nil
1453 "Options concerning tables in Org-mode."
1454 :tag "Org Table"
1455 :group 'org)
1457 (defcustom org-enable-table-editor 'optimized
1458 "Non-nil means lines starting with \"|\" are handled by the table editor.
1459 When nil, such lines will be treated like ordinary lines.
1461 When equal to the symbol `optimized', the table editor will be optimized to
1462 do the following:
1463 - Automatic overwrite mode in front of whitespace in table fields.
1464 This makes the structure of the table stay in tact as long as the edited
1465 field does not exceed the column width.
1466 - Minimize the number of realigns. Normally, the table is aligned each time
1467 TAB or RET are pressed to move to another field. With optimization this
1468 happens only if changes to a field might have changed the column width.
1469 Optimization requires replacing the functions `self-insert-command',
1470 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1471 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1472 very good at guessing when a re-align will be necessary, but you can always
1473 force one with \\[org-ctrl-c-ctrl-c].
1475 If you would like to use the optimized version in Org-mode, but the
1476 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1478 This variable can be used to turn on and off the table editor during a session,
1479 but in order to toggle optimization, a restart is required.
1481 See also the variable `org-table-auto-blank-field'."
1482 :group 'org-table
1483 :type '(choice
1484 (const :tag "off" nil)
1485 (const :tag "on" t)
1486 (const :tag "on, optimized" optimized)))
1488 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1489 (version<= emacs-version "24.1"))
1490 "Non-nil means cluster self-insert commands for undo when possible.
1491 If this is set, then, like in the Emacs command loop, 20 consecutive
1492 characters will be undone together.
1493 This is configurable, because there is some impact on typing performance."
1494 :group 'org-table
1495 :type 'boolean)
1497 (defcustom org-table-tab-recognizes-table.el t
1498 "Non-nil means TAB will automatically notice a table.el table.
1499 When it sees such a table, it moves point into it and - if necessary -
1500 calls `table-recognize-table'."
1501 :group 'org-table-editing
1502 :type 'boolean)
1504 (defgroup org-link nil
1505 "Options concerning links in Org-mode."
1506 :tag "Org Link"
1507 :group 'org)
1509 (defvar org-link-abbrev-alist-local nil
1510 "Buffer-local version of `org-link-abbrev-alist', which see.
1511 The value of this is taken from the #+LINK lines.")
1512 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1514 (defcustom org-link-abbrev-alist nil
1515 "Alist of link abbreviations.
1516 The car of each element is a string, to be replaced at the start of a link.
1517 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1518 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1520 [[linkkey:tag][description]]
1522 The 'linkkey' must be a word word, starting with a letter, followed
1523 by letters, numbers, '-' or '_'.
1525 If REPLACE is a string, the tag will simply be appended to create the link.
1526 If the string contains \"%s\", the tag will be inserted there. If the string
1527 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1528 at that point (see the function `url-hexify-string'). If the string contains
1529 the specifier \"%(my-function)\", then the custom function `my-function' will
1530 be invoked: this function takes the tag as its only argument and must return
1531 a string.
1533 REPLACE may also be a function that will be called with the tag as the
1534 only argument to create the link, which should be returned as a string.
1536 See the manual for examples."
1537 :group 'org-link
1538 :type '(repeat
1539 (cons
1540 (string :tag "Protocol")
1541 (choice
1542 (string :tag "Format")
1543 (function)))))
1545 (defcustom org-descriptive-links t
1546 "Non-nil means Org will display descriptive links.
1547 E.g. [[http://orgmode.org][Org website]] will be displayed as
1548 \"Org Website\", hiding the link itself and just displaying its
1549 description. When set to `nil', Org will display the full links
1550 literally.
1552 You can interactively set the value of this variable by calling
1553 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1554 :group 'org-link
1555 :type 'boolean)
1557 (defcustom org-link-file-path-type 'adaptive
1558 "How the path name in file links should be stored.
1559 Valid values are:
1561 relative Relative to the current directory, i.e. the directory of the file
1562 into which the link is being inserted.
1563 absolute Absolute path, if possible with ~ for home directory.
1564 noabbrev Absolute path, no abbreviation of home directory.
1565 adaptive Use relative path for files in the current directory and sub-
1566 directories of it. For other files, use an absolute path."
1567 :group 'org-link
1568 :type '(choice
1569 (const relative)
1570 (const absolute)
1571 (const noabbrev)
1572 (const adaptive)))
1574 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1575 "Types of links that should be activated in Org-mode files.
1576 This is a list of symbols, each leading to the activation of a certain link
1577 type. In principle, it does not hurt to turn on most link types - there may
1578 be a small gain when turning off unused link types. The types are:
1580 bracket The recommended [[link][description]] or [[link]] links with hiding.
1581 angle Links in angular brackets that may contain whitespace like
1582 <bbdb:Carsten Dominik>.
1583 plain Plain links in normal text, no whitespace, like http://google.com.
1584 radio Text that is matched by a radio target, see manual for details.
1585 tag Tag settings in a headline (link to tag search).
1586 date Time stamps (link to calendar).
1587 footnote Footnote labels.
1589 Changing this variable requires a restart of Emacs to become effective."
1590 :group 'org-link
1591 :type '(set :greedy t
1592 (const :tag "Double bracket links" bracket)
1593 (const :tag "Angular bracket links" angle)
1594 (const :tag "Plain text links" plain)
1595 (const :tag "Radio target matches" radio)
1596 (const :tag "Tags" tag)
1597 (const :tag "Timestamps" date)
1598 (const :tag "Footnotes" footnote)))
1600 (defcustom org-make-link-description-function nil
1601 "Function to use for generating link descriptions from links.
1602 When nil, the link location will be used. This function must take
1603 two parameters: the first one is the link, the second one is the
1604 description generated by `org-insert-link'. The function should
1605 return the description to use."
1606 :group 'org-link
1607 :type '(choice (const nil) (function)))
1609 (defgroup org-link-store nil
1610 "Options concerning storing links in Org-mode."
1611 :tag "Org Store Link"
1612 :group 'org-link)
1614 (defcustom org-url-hexify-p t
1615 "When non-nil, hexify URL when creating a link."
1616 :type 'boolean
1617 :version "24.3"
1618 :group 'org-link-store)
1620 (defcustom org-email-link-description-format "Email %c: %.30s"
1621 "Format of the description part of a link to an email or usenet message.
1622 The following %-escapes will be replaced by corresponding information:
1624 %F full \"From\" field
1625 %f name, taken from \"From\" field, address if no name
1626 %T full \"To\" field
1627 %t first name in \"To\" field, address if no name
1628 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1629 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1630 %s subject
1631 %d date
1632 %m message-id.
1634 You may use normal field width specification between the % and the letter.
1635 This is for example useful to limit the length of the subject.
1637 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1638 :group 'org-link-store
1639 :type 'string)
1641 (defcustom org-from-is-user-regexp
1642 (let (r1 r2)
1643 (when (and user-mail-address (not (string= user-mail-address "")))
1644 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1645 (when (and user-full-name (not (string= user-full-name "")))
1646 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1647 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1648 "Regexp matched against the \"From:\" header of an email or usenet message.
1649 It should match if the message is from the user him/herself."
1650 :group 'org-link-store
1651 :type 'regexp)
1653 (defcustom org-context-in-file-links t
1654 "Non-nil means file links from `org-store-link' contain context.
1655 A search string will be added to the file name with :: as separator and
1656 used to find the context when the link is activated by the command
1657 `org-open-at-point'. When this option is t, the entire active region
1658 will be placed in the search string of the file link. If set to a
1659 positive integer, only the first n lines of context will be stored.
1661 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1662 negates this setting for the duration of the command."
1663 :group 'org-link-store
1664 :type '(choice boolean integer))
1666 (defcustom org-keep-stored-link-after-insertion nil
1667 "Non-nil means keep link in list for entire session.
1669 The command `org-store-link' adds a link pointing to the current
1670 location to an internal list. These links accumulate during a session.
1671 The command `org-insert-link' can be used to insert links into any
1672 Org-mode file (offering completion for all stored links). When this
1673 option is nil, every link which has been inserted once using \\[org-insert-link]
1674 will be removed from the list, to make completing the unused links
1675 more efficient."
1676 :group 'org-link-store
1677 :type 'boolean)
1679 (defgroup org-link-follow nil
1680 "Options concerning following links in Org-mode."
1681 :tag "Org Follow Link"
1682 :group 'org-link)
1684 (defcustom org-link-translation-function nil
1685 "Function to translate links with different syntax to Org syntax.
1686 This can be used to translate links created for example by the Planner
1687 or emacs-wiki packages to Org syntax.
1688 The function must accept two parameters, a TYPE containing the link
1689 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1690 which is everything after the link protocol. It should return a cons
1691 with possibly modified values of type and path.
1692 Org contains a function for this, so if you set this variable to
1693 `org-translate-link-from-planner', you should be able follow many
1694 links created by planner."
1695 :group 'org-link-follow
1696 :type '(choice (const nil) (function)))
1698 (defcustom org-follow-link-hook nil
1699 "Hook that is run after a link has been followed."
1700 :group 'org-link-follow
1701 :type 'hook)
1703 (defcustom org-tab-follows-link nil
1704 "Non-nil means on links TAB will follow the link.
1705 Needs to be set before org.el is loaded.
1706 This really should not be used, it does not make sense, and the
1707 implementation is bad."
1708 :group 'org-link-follow
1709 :type 'boolean)
1711 (defcustom org-return-follows-link nil
1712 "Non-nil means on links RET will follow the link.
1713 In tables, the special behavior of RET has precedence."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-mouse-1-follows-link
1718 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1719 "Non-nil means mouse-1 on a link will follow the link.
1720 A longer mouse click will still set point. Does not work on XEmacs.
1721 Needs to be set before org.el is loaded."
1722 :group 'org-link-follow
1723 :type 'boolean)
1725 (defcustom org-mark-ring-length 4
1726 "Number of different positions to be recorded in the ring.
1727 Changing this requires a restart of Emacs to work correctly."
1728 :group 'org-link-follow
1729 :type 'integer)
1731 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1732 "Non-nil means internal links in Org files must exactly match a headline.
1733 When nil, the link search tries to match a phrase with all words
1734 in the search text."
1735 :group 'org-link-follow
1736 :version "24.1"
1737 :type '(choice
1738 (const :tag "Use fuzzy text search" nil)
1739 (const :tag "Match only exact headline" t)
1740 (const :tag "Match exact headline or query to create it"
1741 query-to-create)))
1743 (defcustom org-link-frame-setup
1744 '((vm . vm-visit-folder-other-frame)
1745 (vm-imap . vm-visit-imap-folder-other-frame)
1746 (gnus . org-gnus-no-new-news)
1747 (file . find-file-other-window)
1748 (wl . wl-other-frame))
1749 "Setup the frame configuration for following links.
1750 When following a link with Emacs, it may often be useful to display
1751 this link in another window or frame. This variable can be used to
1752 set this up for the different types of links.
1753 For VM, use any of
1754 `vm-visit-folder'
1755 `vm-visit-folder-other-window'
1756 `vm-visit-folder-other-frame'
1757 For Gnus, use any of
1758 `gnus'
1759 `gnus-other-frame'
1760 `org-gnus-no-new-news'
1761 For FILE, use any of
1762 `find-file'
1763 `find-file-other-window'
1764 `find-file-other-frame'
1765 For Wanderlust use any of
1766 `wl'
1767 `wl-other-frame'
1768 For the calendar, use the variable `calendar-setup'.
1769 For BBDB, it is currently only possible to display the matches in
1770 another window."
1771 :group 'org-link-follow
1772 :type '(list
1773 (cons (const vm)
1774 (choice
1775 (const vm-visit-folder)
1776 (const vm-visit-folder-other-window)
1777 (const vm-visit-folder-other-frame)))
1778 (cons (const vm-imap)
1779 (choice
1780 (const vm-visit-imap-folder)
1781 (const vm-visit-imap-folder-other-window)
1782 (const vm-visit-imap-folder-other-frame)))
1783 (cons (const gnus)
1784 (choice
1785 (const gnus)
1786 (const gnus-other-frame)
1787 (const org-gnus-no-new-news)))
1788 (cons (const file)
1789 (choice
1790 (const find-file)
1791 (const find-file-other-window)
1792 (const find-file-other-frame)))
1793 (cons (const wl)
1794 (choice
1795 (const wl)
1796 (const wl-other-frame)))))
1798 (defcustom org-display-internal-link-with-indirect-buffer nil
1799 "Non-nil means use indirect buffer to display infile links.
1800 Activating internal links (from one location in a file to another location
1801 in the same file) normally just jumps to the location. When the link is
1802 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1803 is displayed in
1804 another window. When this option is set, the other window actually displays
1805 an indirect buffer clone of the current buffer, to avoid any visibility
1806 changes to the current buffer."
1807 :group 'org-link-follow
1808 :type 'boolean)
1810 (defcustom org-open-non-existing-files nil
1811 "Non-nil means `org-open-file' will open non-existing files.
1812 When nil, an error will be generated.
1813 This variable applies only to external applications because they
1814 might choke on non-existing files. If the link is to a file that
1815 will be opened in Emacs, the variable is ignored."
1816 :group 'org-link-follow
1817 :type 'boolean)
1819 (defcustom org-open-directory-means-index-dot-org nil
1820 "Non-nil means a link to a directory really means to index.org.
1821 When nil, following a directory link will run dired or open a finder/explorer
1822 window on that directory."
1823 :group 'org-link-follow
1824 :type 'boolean)
1826 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1827 "Function and arguments to call for following mailto links.
1828 This is a list with the first element being a Lisp function, and the
1829 remaining elements being arguments to the function. In string arguments,
1830 %a will be replaced by the address, and %s will be replaced by the subject
1831 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1832 :group 'org-link-follow
1833 :type '(choice
1834 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1835 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1836 (const :tag "message-mail" (message-mail "%a" "%s"))
1837 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1839 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1840 "Non-nil means ask for confirmation before executing shell links.
1841 Shell links can be dangerous: just think about a link
1843 [[shell:rm -rf ~/*][Google Search]]
1845 This link would show up in your Org-mode document as \"Google Search\",
1846 but really it would remove your entire home directory.
1847 Therefore we advise against setting this variable to nil.
1848 Just change it to `y-or-n-p' if you want to confirm with a
1849 single keystroke rather than having to type \"yes\"."
1850 :group 'org-link-follow
1851 :type '(choice
1852 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1853 (const :tag "with y-or-n (faster)" y-or-n-p)
1854 (const :tag "no confirmation (dangerous)" nil)))
1855 (put 'org-confirm-shell-link-function
1856 'safe-local-variable
1857 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1859 (defcustom org-confirm-shell-link-not-regexp ""
1860 "A regexp to skip confirmation for shell links."
1861 :group 'org-link-follow
1862 :version "24.1"
1863 :type 'regexp)
1865 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1866 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1867 Elisp links can be dangerous: just think about a link
1869 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1871 This link would show up in your Org-mode document as \"Google Search\",
1872 but really it would remove your entire home directory.
1873 Therefore we advise against setting this variable to nil.
1874 Just change it to `y-or-n-p' if you want to confirm with a
1875 single keystroke rather than having to type \"yes\"."
1876 :group 'org-link-follow
1877 :type '(choice
1878 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1879 (const :tag "with y-or-n (faster)" y-or-n-p)
1880 (const :tag "no confirmation (dangerous)" nil)))
1881 (put 'org-confirm-shell-link-function
1882 'safe-local-variable
1883 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1885 (defcustom org-confirm-elisp-link-not-regexp ""
1886 "A regexp to skip confirmation for Elisp links."
1887 :group 'org-link-follow
1888 :version "24.1"
1889 :type 'regexp)
1891 (defconst org-file-apps-defaults-gnu
1892 '((remote . emacs)
1893 (system . mailcap)
1894 (t . mailcap))
1895 "Default file applications on a UNIX or GNU/Linux system.
1896 See `org-file-apps'.")
1898 (defconst org-file-apps-defaults-macosx
1899 '((remote . emacs)
1900 (t . "open %s")
1901 (system . "open %s")
1902 ("ps.gz" . "gv %s")
1903 ("eps.gz" . "gv %s")
1904 ("dvi" . "xdvi %s")
1905 ("fig" . "xfig %s"))
1906 "Default file applications on a MacOS X system.
1907 The system \"open\" is known as a default, but we use X11 applications
1908 for some files for which the OS does not have a good default.
1909 See `org-file-apps'.")
1911 (defconst org-file-apps-defaults-windowsnt
1912 (list
1913 '(remote . emacs)
1914 (cons t
1915 (list (if (featurep 'xemacs)
1916 'mswindows-shell-execute
1917 'w32-shell-execute)
1918 "open" 'file))
1919 (cons 'system
1920 (list (if (featurep 'xemacs)
1921 'mswindows-shell-execute
1922 'w32-shell-execute)
1923 "open" 'file)))
1924 "Default file applications on a Windows NT system.
1925 The system \"open\" is used for most files.
1926 See `org-file-apps'.")
1928 (defcustom org-file-apps
1929 '((auto-mode . emacs)
1930 ("\\.mm\\'" . default)
1931 ("\\.x?html?\\'" . default)
1932 ("\\.pdf\\'" . default))
1933 "External applications for opening `file:path' items in a document.
1934 Org-mode uses system defaults for different file types, but
1935 you can use this variable to set the application for a given file
1936 extension. The entries in this list are cons cells where the car identifies
1937 files and the cdr the corresponding command. Possible values for the
1938 file identifier are
1939 \"string\" A string as a file identifier can be interpreted in different
1940 ways, depending on its contents:
1942 - Alphanumeric characters only:
1943 Match links with this file extension.
1944 Example: (\"pdf\" . \"evince %s\")
1945 to open PDFs with evince.
1947 - Regular expression: Match links where the
1948 filename matches the regexp. If you want to
1949 use groups here, use shy groups.
1951 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1952 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1953 to open *.html and *.xhtml with firefox.
1955 - Regular expression which contains (non-shy) groups:
1956 Match links where the whole link, including \"::\", and
1957 anything after that, matches the regexp.
1958 In a custom command string, %1, %2, etc. are replaced with
1959 the parts of the link that were matched by the groups.
1960 For backwards compatibility, if a command string is given
1961 that does not use any of the group matches, this case is
1962 handled identically to the second one (i.e. match against
1963 file name only).
1964 In a custom lisp form, you can access the group matches with
1965 (match-string n link).
1967 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1968 to open [[file:document.pdf::5]] with evince at page 5.
1970 `directory' Matches a directory
1971 `remote' Matches a remote file, accessible through tramp or efs.
1972 Remote files most likely should be visited through Emacs
1973 because external applications cannot handle such paths.
1974 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1975 so all files Emacs knows how to handle. Using this with
1976 command `emacs' will open most files in Emacs. Beware that this
1977 will also open html files inside Emacs, unless you add
1978 (\"html\" . default) to the list as well.
1979 t Default for files not matched by any of the other options.
1980 `system' The system command to open files, like `open' on Windows
1981 and Mac OS X, and mailcap under GNU/Linux. This is the command
1982 that will be selected if you call `C-c C-o' with a double
1983 \\[universal-argument] \\[universal-argument] prefix.
1985 Possible values for the command are:
1986 `emacs' The file will be visited by the current Emacs process.
1987 `default' Use the default application for this file type, which is the
1988 association for t in the list, most likely in the system-specific
1989 part.
1990 This can be used to overrule an unwanted setting in the
1991 system-specific variable.
1992 `system' Use the system command for opening files, like \"open\".
1993 This command is specified by the entry whose car is `system'.
1994 Most likely, the system-specific version of this variable
1995 does define this command, but you can overrule/replace it
1996 here.
1997 string A command to be executed by a shell; %s will be replaced
1998 by the path to the file.
1999 sexp A Lisp form which will be evaluated. The file path will
2000 be available in the Lisp variable `file'.
2001 For more examples, see the system specific constants
2002 `org-file-apps-defaults-macosx'
2003 `org-file-apps-defaults-windowsnt'
2004 `org-file-apps-defaults-gnu'."
2005 :group 'org-link-follow
2006 :type '(repeat
2007 (cons (choice :value ""
2008 (string :tag "Extension")
2009 (const :tag "System command to open files" system)
2010 (const :tag "Default for unrecognized files" t)
2011 (const :tag "Remote file" remote)
2012 (const :tag "Links to a directory" directory)
2013 (const :tag "Any files that have Emacs modes"
2014 auto-mode))
2015 (choice :value ""
2016 (const :tag "Visit with Emacs" emacs)
2017 (const :tag "Use default" default)
2018 (const :tag "Use the system command" system)
2019 (string :tag "Command")
2020 (sexp :tag "Lisp form")))))
2022 (defcustom org-doi-server-url "http://dx.doi.org/"
2023 "The URL of the DOI server."
2024 :type 'string
2025 :version "24.3"
2026 :group 'org-link-follow)
2028 (defgroup org-refile nil
2029 "Options concerning refiling entries in Org-mode."
2030 :tag "Org Refile"
2031 :group 'org)
2033 (defcustom org-directory "~/org"
2034 "Directory with org files.
2035 This is just a default location to look for Org files. There is no need
2036 at all to put your files into this directory. It is only used in the
2037 following situations:
2039 1. When a capture template specifies a target file that is not an
2040 absolute path. The path will then be interpreted relative to
2041 `org-directory'
2042 2. When a capture note is filed away in an interactive way (when exiting the
2043 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2044 with `org-directory' as the default path."
2045 :group 'org-refile
2046 :group 'org-remember
2047 :group 'org-capture
2048 :type 'directory)
2050 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2051 "Default target for storing notes.
2052 Used as a fall back file for org-remember.el and org-capture.el, for
2053 templates that do not specify a target file."
2054 :group 'org-refile
2055 :group 'org-remember
2056 :group 'org-capture
2057 :type '(choice
2058 (const :tag "Default from remember-data-file" nil)
2059 file))
2061 (defcustom org-goto-interface 'outline
2062 "The default interface to be used for `org-goto'.
2063 Allowed values are:
2064 outline The interface shows an outline of the relevant file
2065 and the correct heading is found by moving through
2066 the outline or by searching with incremental search.
2067 outline-path-completion Headlines in the current buffer are offered via
2068 completion. This is the interface also used by
2069 the refile command."
2070 :group 'org-refile
2071 :type '(choice
2072 (const :tag "Outline" outline)
2073 (const :tag "Outline-path-completion" outline-path-completion)))
2075 (defcustom org-goto-max-level 5
2076 "Maximum target level when running `org-goto' with refile interface."
2077 :group 'org-refile
2078 :type 'integer)
2080 (defcustom org-reverse-note-order nil
2081 "Non-nil means store new notes at the beginning of a file or entry.
2082 When nil, new notes will be filed to the end of a file or entry.
2083 This can also be a list with cons cells of regular expressions that
2084 are matched against file names, and values."
2085 :group 'org-remember
2086 :group 'org-capture
2087 :group 'org-refile
2088 :type '(choice
2089 (const :tag "Reverse always" t)
2090 (const :tag "Reverse never" nil)
2091 (repeat :tag "By file name regexp"
2092 (cons regexp boolean))))
2094 (defcustom org-log-refile nil
2095 "Information to record when a task is refiled.
2097 Possible values are:
2099 nil Don't add anything
2100 time Add a time stamp to the task
2101 note Prompt for a note and add it with template `org-log-note-headings'
2103 This option can also be set with on a per-file-basis with
2105 #+STARTUP: nologrefile
2106 #+STARTUP: logrefile
2107 #+STARTUP: lognoterefile
2109 You can have local logging settings for a subtree by setting the LOGGING
2110 property to one or more of these keywords.
2112 When bulk-refiling from the agenda, the value `note' is forbidden and
2113 will temporarily be changed to `time'."
2114 :group 'org-refile
2115 :group 'org-progress
2116 :version "24.1"
2117 :type '(choice
2118 (const :tag "No logging" nil)
2119 (const :tag "Record timestamp" time)
2120 (const :tag "Record timestamp with note." note)))
2122 (defcustom org-refile-targets nil
2123 "Targets for refiling entries with \\[org-refile].
2124 This is a list of cons cells. Each cell contains:
2125 - a specification of the files to be considered, either a list of files,
2126 or a symbol whose function or variable value will be used to retrieve
2127 a file name or a list of file names. If you use `org-agenda-files' for
2128 that, all agenda files will be scanned for targets. Nil means consider
2129 headings in the current buffer.
2130 - A specification of how to find candidate refile targets. This may be
2131 any of:
2132 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2133 This tag has to be present in all target headlines, inheritance will
2134 not be considered.
2135 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2136 todo keyword.
2137 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2138 headlines that are refiling targets.
2139 - a cons cell (:level . N). Any headline of level N is considered a target.
2140 Note that, when `org-odd-levels-only' is set, level corresponds to
2141 order in hierarchy, not to the number of stars.
2142 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2143 Note that, when `org-odd-levels-only' is set, level corresponds to
2144 order in hierarchy, not to the number of stars.
2146 Each element of this list generates a set of possible targets.
2147 The union of these sets is presented (with completion) to
2148 the user by `org-refile'.
2150 You can set the variable `org-refile-target-verify-function' to a function
2151 to verify each headline found by the simple criteria above.
2153 When this variable is nil, all top-level headlines in the current buffer
2154 are used, equivalent to the value `((nil . (:level . 1))'."
2155 :group 'org-refile
2156 :type '(repeat
2157 (cons
2158 (choice :value org-agenda-files
2159 (const :tag "All agenda files" org-agenda-files)
2160 (const :tag "Current buffer" nil)
2161 (function) (variable) (file))
2162 (choice :tag "Identify target headline by"
2163 (cons :tag "Specific tag" (const :value :tag) (string))
2164 (cons :tag "TODO keyword" (const :value :todo) (string))
2165 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2166 (cons :tag "Level number" (const :value :level) (integer))
2167 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2169 (defcustom org-refile-target-verify-function nil
2170 "Function to verify if the headline at point should be a refile target.
2171 The function will be called without arguments, with point at the
2172 beginning of the headline. It should return t and leave point
2173 where it is if the headline is a valid target for refiling.
2175 If the target should not be selected, the function must return nil.
2176 In addition to this, it may move point to a place from where the search
2177 should be continued. For example, the function may decide that the entire
2178 subtree of the current entry should be excluded and move point to the end
2179 of the subtree."
2180 :group 'org-refile
2181 :type '(choice
2182 (const nil)
2183 (function)))
2185 (defcustom org-refile-use-cache nil
2186 "Non-nil means cache refile targets to speed up the process.
2187 The cache for a particular file will be updated automatically when
2188 the buffer has been killed, or when any of the marker used for flagging
2189 refile targets no longer points at a live buffer.
2190 If you have added new entries to a buffer that might themselves be targets,
2191 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2192 find that easier, `C-u C-u C-u C-c C-w'."
2193 :group 'org-refile
2194 :version "24.1"
2195 :type 'boolean)
2197 (defcustom org-refile-use-outline-path nil
2198 "Non-nil means provide refile targets as paths.
2199 So a level 3 headline will be available as level1/level2/level3.
2201 When the value is `file', also include the file name (without directory)
2202 into the path. In this case, you can also stop the completion after
2203 the file name, to get entries inserted as top level in the file.
2205 When `full-file-path', include the full file path."
2206 :group 'org-refile
2207 :type '(choice
2208 (const :tag "Not" nil)
2209 (const :tag "Yes" t)
2210 (const :tag "Start with file name" file)
2211 (const :tag "Start with full file path" full-file-path)))
2213 (defcustom org-outline-path-complete-in-steps t
2214 "Non-nil means complete the outline path in hierarchical steps.
2215 When Org-mode uses the refile interface to select an outline path
2216 \(see variable `org-refile-use-outline-path'), the completion of
2217 the path can be done is a single go, or if can be done in steps down
2218 the headline hierarchy. Going in steps is probably the best if you
2219 do not use a special completion package like `ido' or `icicles'.
2220 However, when using these packages, going in one step can be very
2221 fast, while still showing the whole path to the entry."
2222 :group 'org-refile
2223 :type 'boolean)
2225 (defcustom org-refile-allow-creating-parent-nodes nil
2226 "Non-nil means allow to create new nodes as refile targets.
2227 New nodes are then created by adding \"/new node name\" to the completion
2228 of an existing node. When the value of this variable is `confirm',
2229 new node creation must be confirmed by the user (recommended)
2230 When nil, the completion must match an existing entry.
2232 Note that, if the new heading is not seen by the criteria
2233 listed in `org-refile-targets', multiple instances of the same
2234 heading would be created by trying again to file under the new
2235 heading."
2236 :group 'org-refile
2237 :type '(choice
2238 (const :tag "Never" nil)
2239 (const :tag "Always" t)
2240 (const :tag "Prompt for confirmation" confirm)))
2242 (defcustom org-refile-active-region-within-subtree nil
2243 "Non-nil means also refile active region within a subtree.
2245 By default `org-refile' doesn't allow refiling regions if they
2246 don't contain a set of subtrees, but it might be convenient to
2247 do so sometimes: in that case, the first line of the region is
2248 converted to a headline before refiling."
2249 :group 'org-refile
2250 :version "24.1"
2251 :type 'boolean)
2253 (defgroup org-todo nil
2254 "Options concerning TODO items in Org-mode."
2255 :tag "Org TODO"
2256 :group 'org)
2258 (defgroup org-progress nil
2259 "Options concerning Progress logging in Org-mode."
2260 :tag "Org Progress"
2261 :group 'org-time)
2263 (defvar org-todo-interpretation-widgets
2264 '((:tag "Sequence (cycling hits every state)" sequence)
2265 (:tag "Type (cycling directly to DONE)" type))
2266 "The available interpretation symbols for customizing `org-todo-keywords'.
2267 Interested libraries should add to this list.")
2269 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2270 "List of TODO entry keyword sequences and their interpretation.
2271 \\<org-mode-map>This is a list of sequences.
2273 Each sequence starts with a symbol, either `sequence' or `type',
2274 indicating if the keywords should be interpreted as a sequence of
2275 action steps, or as different types of TODO items. The first
2276 keywords are states requiring action - these states will select a headline
2277 for inclusion into the global TODO list Org-mode produces. If one of
2278 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2279 signify that no further action is necessary. If \"|\" is not found,
2280 the last keyword is treated as the only DONE state of the sequence.
2282 The command \\[org-todo] cycles an entry through these states, and one
2283 additional state where no keyword is present. For details about this
2284 cycling, see the manual.
2286 TODO keywords and interpretation can also be set on a per-file basis with
2287 the special #+SEQ_TODO and #+TYP_TODO lines.
2289 Each keyword can optionally specify a character for fast state selection
2290 \(in combination with the variable `org-use-fast-todo-selection')
2291 and specifiers for state change logging, using the same syntax that
2292 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2293 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2294 indicates to record a time stamp each time this state is selected.
2296 Each keyword may also specify if a timestamp or a note should be
2297 recorded when entering or leaving the state, by adding additional
2298 characters in the parenthesis after the keyword. This looks like this:
2299 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2300 record only the time of the state change. With X and Y being either
2301 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2302 Y when leaving the state if and only if the *target* state does not
2303 define X. You may omit any of the fast-selection key or X or /Y,
2304 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2306 For backward compatibility, this variable may also be just a list
2307 of keywords. In this case the interpretation (sequence or type) will be
2308 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2309 :group 'org-todo
2310 :group 'org-keywords
2311 :type '(choice
2312 (repeat :tag "Old syntax, just keywords"
2313 (string :tag "Keyword"))
2314 (repeat :tag "New syntax"
2315 (cons
2316 (choice
2317 :tag "Interpretation"
2318 ;;Quick and dirty way to see
2319 ;;`org-todo-interpretations'. This takes the
2320 ;;place of item arguments
2321 :convert-widget
2322 (lambda (widget)
2323 (widget-put widget
2324 :args (mapcar
2325 #'(lambda (x)
2326 (widget-convert
2327 (cons 'const x)))
2328 org-todo-interpretation-widgets))
2329 widget))
2330 (repeat
2331 (string :tag "Keyword"))))))
2333 (defvar org-todo-keywords-1 nil
2334 "All TODO and DONE keywords active in a buffer.")
2335 (make-variable-buffer-local 'org-todo-keywords-1)
2336 (defvar org-todo-keywords-for-agenda nil)
2337 (defvar org-done-keywords-for-agenda nil)
2338 (defvar org-todo-keyword-alist-for-agenda nil)
2339 (defvar org-tag-alist-for-agenda nil
2340 "Alist of all tags from all agenda files.")
2341 (defvar org-tag-groups-alist-for-agenda nil
2342 "Alist of all groups tags from all current agenda files.")
2343 (defvar org-tag-groups-alist nil)
2344 (make-variable-buffer-local 'org-tag-groups-alist)
2345 (defvar org-agenda-contributing-files nil)
2346 (defvar org-not-done-keywords nil)
2347 (make-variable-buffer-local 'org-not-done-keywords)
2348 (defvar org-done-keywords nil)
2349 (make-variable-buffer-local 'org-done-keywords)
2350 (defvar org-todo-heads nil)
2351 (make-variable-buffer-local 'org-todo-heads)
2352 (defvar org-todo-sets nil)
2353 (make-variable-buffer-local 'org-todo-sets)
2354 (defvar org-todo-log-states nil)
2355 (make-variable-buffer-local 'org-todo-log-states)
2356 (defvar org-todo-kwd-alist nil)
2357 (make-variable-buffer-local 'org-todo-kwd-alist)
2358 (defvar org-todo-key-alist nil)
2359 (make-variable-buffer-local 'org-todo-key-alist)
2360 (defvar org-todo-key-trigger nil)
2361 (make-variable-buffer-local 'org-todo-key-trigger)
2363 (defcustom org-todo-interpretation 'sequence
2364 "Controls how TODO keywords are interpreted.
2365 This variable is in principle obsolete and is only used for
2366 backward compatibility, if the interpretation of todo keywords is
2367 not given already in `org-todo-keywords'. See that variable for
2368 more information."
2369 :group 'org-todo
2370 :group 'org-keywords
2371 :type '(choice (const sequence)
2372 (const type)))
2374 (defcustom org-use-fast-todo-selection t
2375 "Non-nil means use the fast todo selection scheme with C-c C-t.
2376 This variable describes if and under what circumstances the cycling
2377 mechanism for TODO keywords will be replaced by a single-key, direct
2378 selection scheme.
2380 When nil, fast selection is never used.
2382 When the symbol `prefix', it will be used when `org-todo' is called
2383 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2384 `C-u t' in an agenda buffer.
2386 When t, fast selection is used by default. In this case, the prefix
2387 argument forces cycling instead.
2389 In all cases, the special interface is only used if access keys have
2390 actually been assigned by the user, i.e. if keywords in the configuration
2391 are followed by a letter in parenthesis, like TODO(t)."
2392 :group 'org-todo
2393 :type '(choice
2394 (const :tag "Never" nil)
2395 (const :tag "By default" t)
2396 (const :tag "Only with C-u C-c C-t" prefix)))
2398 (defcustom org-provide-todo-statistics t
2399 "Non-nil means update todo statistics after insert and toggle.
2400 ALL-HEADLINES means update todo statistics by including headlines
2401 with no TODO keyword as well, counting them as not done.
2402 A list of TODO keywords means the same, but skip keywords that are
2403 not in this list.
2405 When this is set, todo statistics is updated in the parent of the
2406 current entry each time a todo state is changed."
2407 :group 'org-todo
2408 :type '(choice
2409 (const :tag "Yes, only for TODO entries" t)
2410 (const :tag "Yes, including all entries" 'all-headlines)
2411 (repeat :tag "Yes, for TODOs in this list"
2412 (string :tag "TODO keyword"))
2413 (other :tag "No TODO statistics" nil)))
2415 (defcustom org-hierarchical-todo-statistics t
2416 "Non-nil means TODO statistics covers just direct children.
2417 When nil, all entries in the subtree are considered.
2418 This has only an effect if `org-provide-todo-statistics' is set.
2419 To set this to nil for only a single subtree, use a COOKIE_DATA
2420 property and include the word \"recursive\" into the value."
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-after-todo-state-change-hook nil
2425 "Hook which is run after the state of a TODO item was changed.
2426 The new state (a string with a TODO keyword, or nil) is available in the
2427 Lisp variable `org-state'."
2428 :group 'org-todo
2429 :type 'hook)
2431 (defvar org-blocker-hook nil
2432 "Hook for functions that are allowed to block a state change.
2434 Functions in this hook should not modify the buffer.
2435 Each function gets as its single argument a property list,
2436 see `org-trigger-hook' for more information about this list.
2438 If any of the functions in this hook returns nil, the state change
2439 is blocked.")
2441 (defvar org-trigger-hook nil
2442 "Hook for functions that are triggered by a state change.
2444 Each function gets as its single argument a property list with at
2445 least the following elements:
2447 (:type type-of-change :position pos-at-entry-start
2448 :from old-state :to new-state)
2450 Depending on the type, more properties may be present.
2452 This mechanism is currently implemented for:
2454 TODO state changes
2455 ------------------
2456 :type todo-state-change
2457 :from previous state (keyword as a string), or nil, or a symbol
2458 'todo' or 'done', to indicate the general type of state.
2459 :to new state, like in :from")
2461 (defcustom org-enforce-todo-dependencies nil
2462 "Non-nil means undone TODO entries will block switching the parent to DONE.
2463 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2464 be blocked if any prior sibling is not yet done.
2465 Finally, if the parent is blocked because of ordered siblings of its own,
2466 the child will also be blocked."
2467 :set (lambda (var val)
2468 (set var val)
2469 (if val
2470 (add-hook 'org-blocker-hook
2471 'org-block-todo-from-children-or-siblings-or-parent)
2472 (remove-hook 'org-blocker-hook
2473 'org-block-todo-from-children-or-siblings-or-parent)))
2474 :group 'org-todo
2475 :type 'boolean)
2477 (defcustom org-enforce-todo-checkbox-dependencies nil
2478 "Non-nil means unchecked boxes will block switching the parent to DONE.
2479 When this is nil, checkboxes have no influence on switching TODO states.
2480 When non-nil, you first need to check off all check boxes before the TODO
2481 entry can be switched to DONE.
2482 This variable needs to be set before org.el is loaded, and you need to
2483 restart Emacs after a change to make the change effective. The only way
2484 to change is while Emacs is running is through the customize interface."
2485 :set (lambda (var val)
2486 (set var val)
2487 (if val
2488 (add-hook 'org-blocker-hook
2489 'org-block-todo-from-checkboxes)
2490 (remove-hook 'org-blocker-hook
2491 'org-block-todo-from-checkboxes)))
2492 :group 'org-todo
2493 :type 'boolean)
2495 (defcustom org-treat-insert-todo-heading-as-state-change nil
2496 "Non-nil means inserting a TODO heading is treated as state change.
2497 So when the command \\[org-insert-todo-heading] is used, state change
2498 logging will apply if appropriate. When nil, the new TODO item will
2499 be inserted directly, and no logging will take place."
2500 :group 'org-todo
2501 :type 'boolean)
2503 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2504 "Non-nil means switching TODO states with S-cursor counts as state change.
2505 This is the default behavior. However, setting this to nil allows a
2506 convenient way to select a TODO state and bypass any logging associated
2507 with that."
2508 :group 'org-todo
2509 :type 'boolean)
2511 (defcustom org-todo-state-tags-triggers nil
2512 "Tag changes that should be triggered by TODO state changes.
2513 This is a list. Each entry is
2515 (state-change (tag . flag) .......)
2517 State-change can be a string with a state, and empty string to indicate the
2518 state that has no TODO keyword, or it can be one of the symbols `todo'
2519 or `done', meaning any not-done or done state, respectively."
2520 :group 'org-todo
2521 :group 'org-tags
2522 :type '(repeat
2523 (cons (choice :tag "When changing to"
2524 (const :tag "Not-done state" todo)
2525 (const :tag "Done state" done)
2526 (string :tag "State"))
2527 (repeat
2528 (cons :tag "Tag action"
2529 (string :tag "Tag")
2530 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2532 (defcustom org-log-done nil
2533 "Information to record when a task moves to the DONE state.
2535 Possible values are:
2537 nil Don't add anything, just change the keyword
2538 time Add a time stamp to the task
2539 note Prompt for a note and add it with template `org-log-note-headings'
2541 This option can also be set with on a per-file-basis with
2543 #+STARTUP: nologdone
2544 #+STARTUP: logdone
2545 #+STARTUP: lognotedone
2547 You can have local logging settings for a subtree by setting the LOGGING
2548 property to one or more of these keywords."
2549 :group 'org-todo
2550 :group 'org-progress
2551 :type '(choice
2552 (const :tag "No logging" nil)
2553 (const :tag "Record CLOSED timestamp" time)
2554 (const :tag "Record CLOSED timestamp with note." note)))
2556 ;; Normalize old uses of org-log-done.
2557 (cond
2558 ((eq org-log-done t) (setq org-log-done 'time))
2559 ((and (listp org-log-done) (memq 'done org-log-done))
2560 (setq org-log-done 'note)))
2562 (defcustom org-log-reschedule nil
2563 "Information to record when the scheduling date of a tasks is modified.
2565 Possible values are:
2567 nil Don't add anything, just change the date
2568 time Add a time stamp to the task
2569 note Prompt for a note and add it with template `org-log-note-headings'
2571 This option can also be set with on a per-file-basis with
2573 #+STARTUP: nologreschedule
2574 #+STARTUP: logreschedule
2575 #+STARTUP: lognotereschedule"
2576 :group 'org-todo
2577 :group 'org-progress
2578 :type '(choice
2579 (const :tag "No logging" nil)
2580 (const :tag "Record timestamp" time)
2581 (const :tag "Record timestamp with note." note)))
2583 (defcustom org-log-redeadline nil
2584 "Information to record when the deadline date of a tasks is modified.
2586 Possible values are:
2588 nil Don't add anything, just change the date
2589 time Add a time stamp to the task
2590 note Prompt for a note and add it with template `org-log-note-headings'
2592 This option can also be set with on a per-file-basis with
2594 #+STARTUP: nologredeadline
2595 #+STARTUP: logredeadline
2596 #+STARTUP: lognoteredeadline
2598 You can have local logging settings for a subtree by setting the LOGGING
2599 property to one or more of these keywords."
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type '(choice
2603 (const :tag "No logging" nil)
2604 (const :tag "Record timestamp" time)
2605 (const :tag "Record timestamp with note." note)))
2607 (defcustom org-log-note-clock-out nil
2608 "Non-nil means record a note when clocking out of an item.
2609 This can also be configured on a per-file basis by adding one of
2610 the following lines anywhere in the buffer:
2612 #+STARTUP: lognoteclock-out
2613 #+STARTUP: nolognoteclock-out"
2614 :group 'org-todo
2615 :group 'org-progress
2616 :type 'boolean)
2618 (defcustom org-log-done-with-time t
2619 "Non-nil means the CLOSED time stamp will contain date and time.
2620 When nil, only the date will be recorded."
2621 :group 'org-progress
2622 :type 'boolean)
2624 (defcustom org-log-note-headings
2625 '((done . "CLOSING NOTE %t")
2626 (state . "State %-12s from %-12S %t")
2627 (note . "Note taken on %t")
2628 (reschedule . "Rescheduled from %S on %t")
2629 (delschedule . "Not scheduled, was %S on %t")
2630 (redeadline . "New deadline from %S on %t")
2631 (deldeadline . "Removed deadline, was %S on %t")
2632 (refile . "Refiled on %t")
2633 (clock-out . ""))
2634 "Headings for notes added to entries.
2635 The value is an alist, with the car being a symbol indicating the note
2636 context, and the cdr is the heading to be used. The heading may also be the
2637 empty string.
2638 %t in the heading will be replaced by a time stamp.
2639 %T will be an active time stamp instead the default inactive one
2640 %d will be replaced by a short-format time stamp.
2641 %D will be replaced by an active short-format time stamp.
2642 %s will be replaced by the new TODO state, in double quotes.
2643 %S will be replaced by the old TODO state, in double quotes.
2644 %u will be replaced by the user name.
2645 %U will be replaced by the full user name.
2647 In fact, it is not a good idea to change the `state' entry, because
2648 agenda log mode depends on the format of these entries."
2649 :group 'org-todo
2650 :group 'org-progress
2651 :type '(list :greedy t
2652 (cons (const :tag "Heading when closing an item" done) string)
2653 (cons (const :tag
2654 "Heading when changing todo state (todo sequence only)"
2655 state) string)
2656 (cons (const :tag "Heading when just taking a note" note) string)
2657 (cons (const :tag "Heading when clocking out" clock-out) string)
2658 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2659 (cons (const :tag "Heading when rescheduling" reschedule) string)
2660 (cons (const :tag "Heading when changing deadline" redeadline) string)
2661 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2662 (cons (const :tag "Heading when refiling" refile) string)))
2664 (unless (assq 'note org-log-note-headings)
2665 (push '(note . "%t") org-log-note-headings))
2667 (defcustom org-log-into-drawer nil
2668 "Non-nil means insert state change notes and time stamps into a drawer.
2669 When nil, state changes notes will be inserted after the headline and
2670 any scheduling and clock lines, but not inside a drawer.
2672 The value of this variable should be the name of the drawer to use.
2673 LOGBOOK is proposed as the default drawer for this purpose, you can
2674 also set this to a string to define the drawer of your choice.
2676 A value of t is also allowed, representing \"LOGBOOK\".
2678 A value of t or nil can also be set with on a per-file-basis with
2680 #+STARTUP: logdrawer
2681 #+STARTUP: nologdrawer
2683 If this variable is set, `org-log-state-notes-insert-after-drawers'
2684 will be ignored.
2686 You can set the property LOG_INTO_DRAWER to overrule this setting for
2687 a subtree."
2688 :group 'org-todo
2689 :group 'org-progress
2690 :type '(choice
2691 (const :tag "Not into a drawer" nil)
2692 (const :tag "LOGBOOK" t)
2693 (string :tag "Other")))
2695 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2697 (defun org-log-into-drawer ()
2698 "Return the value of `org-log-into-drawer', but let properties overrule.
2699 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2700 used instead of the default value."
2701 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2702 (cond
2703 ((not p) org-log-into-drawer)
2704 ((equal p "nil") nil)
2705 ((equal p "t") "LOGBOOK")
2706 (t p))))
2708 (defcustom org-log-state-notes-insert-after-drawers nil
2709 "Non-nil means insert state change notes after any drawers in entry.
2710 Only the drawers that *immediately* follow the headline and the
2711 deadline/scheduled line are skipped.
2712 When nil, insert notes right after the heading and perhaps the line
2713 with deadline/scheduling if present.
2715 This variable will have no effect if `org-log-into-drawer' is
2716 set."
2717 :group 'org-todo
2718 :group 'org-progress
2719 :type 'boolean)
2721 (defcustom org-log-states-order-reversed t
2722 "Non-nil means the latest state note will be directly after heading.
2723 When nil, the state change notes will be ordered according to time.
2725 This option can also be set with on a per-file-basis with
2727 #+STARTUP: logstatesreversed
2728 #+STARTUP: nologstatesreversed"
2729 :group 'org-todo
2730 :group 'org-progress
2731 :type 'boolean)
2733 (defcustom org-todo-repeat-to-state nil
2734 "The TODO state to which a repeater should return the repeating task.
2735 By default this is the first task in a TODO sequence, or the previous state
2736 in a TODO_TYP set. But you can specify another task here.
2737 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2738 :group 'org-todo
2739 :version "24.1"
2740 :type '(choice (const :tag "Head of sequence" nil)
2741 (string :tag "Specific state")))
2743 (defcustom org-log-repeat 'time
2744 "Non-nil means record moving through the DONE state when triggering repeat.
2745 An auto-repeating task is immediately switched back to TODO when
2746 marked DONE. If you are not logging state changes (by adding \"@\"
2747 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2748 record a closing note, there will be no record of the task moving
2749 through DONE. This variable forces taking a note anyway.
2751 nil Don't force a record
2752 time Record a time stamp
2753 note Prompt for a note and add it with template `org-log-note-headings'
2755 This option can also be set with on a per-file-basis with
2757 #+STARTUP: nologrepeat
2758 #+STARTUP: logrepeat
2759 #+STARTUP: lognoterepeat
2761 You can have local logging settings for a subtree by setting the LOGGING
2762 property to one or more of these keywords."
2763 :group 'org-todo
2764 :group 'org-progress
2765 :type '(choice
2766 (const :tag "Don't force a record" nil)
2767 (const :tag "Force recording the DONE state" time)
2768 (const :tag "Force recording a note with the DONE state" note)))
2771 (defgroup org-priorities nil
2772 "Priorities in Org-mode."
2773 :tag "Org Priorities"
2774 :group 'org-todo)
2776 (defcustom org-enable-priority-commands t
2777 "Non-nil means priority commands are active.
2778 When nil, these commands will be disabled, so that you never accidentally
2779 set a priority."
2780 :group 'org-priorities
2781 :type 'boolean)
2783 (defcustom org-highest-priority ?A
2784 "The highest priority of TODO items. A character like ?A, ?B etc.
2785 Must have a smaller ASCII number than `org-lowest-priority'."
2786 :group 'org-priorities
2787 :type 'character)
2789 (defcustom org-lowest-priority ?C
2790 "The lowest priority of TODO items. A character like ?A, ?B etc.
2791 Must have a larger ASCII number than `org-highest-priority'."
2792 :group 'org-priorities
2793 :type 'character)
2795 (defcustom org-default-priority ?B
2796 "The default priority of TODO items.
2797 This is the priority an item gets if no explicit priority is given.
2798 When starting to cycle on an empty priority the first step in the cycle
2799 depends on `org-priority-start-cycle-with-default'. The resulting first
2800 step priority must not exceed the range from `org-highest-priority' to
2801 `org-lowest-priority' which means that `org-default-priority' has to be
2802 in this range exclusive or inclusive the range boundaries. Else the
2803 first step refuses to set the default and the second will fall back
2804 to (depending on the command used) the highest or lowest priority."
2805 :group 'org-priorities
2806 :type 'character)
2808 (defcustom org-priority-start-cycle-with-default t
2809 "Non-nil means start with default priority when starting to cycle.
2810 When this is nil, the first step in the cycle will be (depending on the
2811 command used) one higher or lower than the default priority.
2812 See also `org-default-priority'."
2813 :group 'org-priorities
2814 :type 'boolean)
2816 (defcustom org-get-priority-function nil
2817 "Function to extract the priority from a string.
2818 The string is normally the headline. If this is nil Org computes the
2819 priority from the priority cookie like [#A] in the headline. It returns
2820 an integer, increasing by 1000 for each priority level.
2821 The user can set a different function here, which should take a string
2822 as an argument and return the numeric priority."
2823 :group 'org-priorities
2824 :version "24.1"
2825 :type '(choice
2826 (const nil)
2827 (function)))
2829 (defgroup org-time nil
2830 "Options concerning time stamps and deadlines in Org-mode."
2831 :tag "Org Time"
2832 :group 'org)
2834 (defcustom org-insert-labeled-timestamps-at-point nil
2835 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2836 When nil, these labeled time stamps are forces into the second line of an
2837 entry, just after the headline. When scheduling from the global TODO list,
2838 the time stamp will always be forced into the second line."
2839 :group 'org-time
2840 :type 'boolean)
2842 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2843 "Formats for `format-time-string' which are used for time stamps.
2844 It is not recommended to change this constant.")
2846 (defcustom org-time-stamp-rounding-minutes '(0 5)
2847 "Number of minutes to round time stamps to.
2848 These are two values, the first applies when first creating a time stamp.
2849 The second applies when changing it with the commands `S-up' and `S-down'.
2850 When changing the time stamp, this means that it will change in steps
2851 of N minutes, as given by the second value.
2853 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2854 numbers should be factors of 60, so for example 5, 10, 15.
2856 When this is larger than 1, you can still force an exact time stamp by using
2857 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2858 and by using a prefix arg to `S-up/down' to specify the exact number
2859 of minutes to shift."
2860 :group 'org-time
2861 :get #'(lambda (var) ; Make sure both elements are there
2862 (if (integerp (default-value var))
2863 (list (default-value var) 5)
2864 (default-value var)))
2865 :type '(list
2866 (integer :tag "when inserting times")
2867 (integer :tag "when modifying times")))
2869 ;; Normalize old customizations of this variable.
2870 (when (integerp org-time-stamp-rounding-minutes)
2871 (setq org-time-stamp-rounding-minutes
2872 (list org-time-stamp-rounding-minutes
2873 org-time-stamp-rounding-minutes)))
2875 (defcustom org-display-custom-times nil
2876 "Non-nil means overlay custom formats over all time stamps.
2877 The formats are defined through the variable `org-time-stamp-custom-formats'.
2878 To turn this on on a per-file basis, insert anywhere in the file:
2879 #+STARTUP: customtime"
2880 :group 'org-time
2881 :set 'set-default
2882 :type 'sexp)
2883 (make-variable-buffer-local 'org-display-custom-times)
2885 (defcustom org-time-stamp-custom-formats
2886 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2887 "Custom formats for time stamps. See `format-time-string' for the syntax.
2888 These are overlaid over the default ISO format if the variable
2889 `org-display-custom-times' is set. Time like %H:%M should be at the
2890 end of the second format. The custom formats are also honored by export
2891 commands, if custom time display is turned on at the time of export."
2892 :group 'org-time
2893 :type 'sexp)
2895 (defun org-time-stamp-format (&optional long inactive)
2896 "Get the right format for a time string."
2897 (let ((f (if long (cdr org-time-stamp-formats)
2898 (car org-time-stamp-formats))))
2899 (if inactive
2900 (concat "[" (substring f 1 -1) "]")
2901 f)))
2903 (defcustom org-time-clocksum-format
2904 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2905 "The format string used when creating CLOCKSUM lines.
2906 This is also used when Org mode generates a time duration.
2908 The value can be a single format string containing two
2909 %-sequences, which will be filled with the number of hours and
2910 minutes in that order.
2912 Alternatively, the value can be a plist associating any of the
2913 keys :years, :months, :weeks, :days, :hours or :minutes with
2914 format strings. The time duration is formatted using only the
2915 time components that are needed and concatenating the results.
2916 If a time unit in absent, it falls back to the next smallest
2917 unit.
2919 The keys :require-years, :require-months, :require-days,
2920 :require-weeks, :require-hours, :require-minutes are also
2921 meaningful. A non-nil value for these keys indicates that the
2922 corresponding time component should always be included, even if
2923 its value is 0.
2926 For example,
2928 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2929 :require-minutes t)
2931 means durations longer than a day will be expressed in days,
2932 hours and minutes, and durations less than a day will always be
2933 expressed in hours and minutes (even for durations less than an
2934 hour).
2936 The value
2938 \(:days \"%dd\" :minutes \"%dm\")
2940 means durations longer than a day will be expressed in days and
2941 minutes, and durations less than a day will be expressed entirely
2942 in minutes (even for durations longer than an hour)."
2943 :group 'org-time
2944 :group 'org-clock
2945 :version "24.4"
2946 :package-version '(Org . "8.0")
2947 :type '(choice (string :tag "Format string")
2948 (set :tag "Plist"
2949 (group :inline t (const :tag "Years" :years)
2950 (string :tag "Format string"))
2951 (group :inline t
2952 (const :tag "Always show years" :require-years)
2953 (const t))
2954 (group :inline t (const :tag "Months" :months)
2955 (string :tag "Format string"))
2956 (group :inline t
2957 (const :tag "Always show months" :require-months)
2958 (const t))
2959 (group :inline t (const :tag "Weeks" :weeks)
2960 (string :tag "Format string"))
2961 (group :inline t
2962 (const :tag "Always show weeks" :require-weeks)
2963 (const t))
2964 (group :inline t (const :tag "Days" :days)
2965 (string :tag "Format string"))
2966 (group :inline t
2967 (const :tag "Always show days" :require-days)
2968 (const t))
2969 (group :inline t (const :tag "Hours" :hours)
2970 (string :tag "Format string"))
2971 (group :inline t
2972 (const :tag "Always show hours" :require-hours)
2973 (const t))
2974 (group :inline t (const :tag "Minutes" :minutes)
2975 (string :tag "Format string"))
2976 (group :inline t
2977 (const :tag "Always show minutes" :require-minutes)
2978 (const t)))))
2980 (defcustom org-time-clocksum-use-fractional nil
2981 "When non-nil, \\[org-clock-display] uses fractional times.
2982 See `org-time-clocksum-format' for more on time clock formats."
2983 :group 'org-time
2984 :group 'org-clock
2985 :version "24.3"
2986 :type 'boolean)
2988 (defcustom org-time-clocksum-use-effort-durations nil
2989 "When non-nil, \\[org-clock-display] uses effort durations.
2990 E.g. by default, one day is considered to be a 8 hours effort,
2991 so a task that has been clocked for 16 hours will be displayed
2992 as during 2 days in the clock display or in the clocktable.
2994 See `org-effort-durations' on how to set effort durations
2995 and `org-time-clocksum-format' for more on time clock formats."
2996 :group 'org-time
2997 :group 'org-clock
2998 :version "24.4"
2999 :package-version '(Org . "8.0")
3000 :type 'boolean)
3002 (defcustom org-time-clocksum-fractional-format "%.2f"
3003 "The format string used when creating CLOCKSUM lines,
3004 or when Org mode generates a time duration, if
3005 `org-time-clocksum-use-fractional' is enabled.
3007 The value can be a single format string containing one
3008 %-sequence, which will be filled with the number of hours as
3009 a float.
3011 Alternatively, the value can be a plist associating any of the
3012 keys :years, :months, :weeks, :days, :hours or :minutes with
3013 a format string. The time duration is formatted using the
3014 largest time unit which gives a non-zero integer part. If all
3015 specified formats have zero integer part, the smallest time unit
3016 is used."
3017 :group 'org-time
3018 :type '(choice (string :tag "Format string")
3019 (set (group :inline t (const :tag "Years" :years)
3020 (string :tag "Format string"))
3021 (group :inline t (const :tag "Months" :months)
3022 (string :tag "Format string"))
3023 (group :inline t (const :tag "Weeks" :weeks)
3024 (string :tag "Format string"))
3025 (group :inline t (const :tag "Days" :days)
3026 (string :tag "Format string"))
3027 (group :inline t (const :tag "Hours" :hours)
3028 (string :tag "Format string"))
3029 (group :inline t (const :tag "Minutes" :minutes)
3030 (string :tag "Format string")))))
3032 (defcustom org-deadline-warning-days 14
3033 "Number of days before expiration during which a deadline becomes active.
3034 This variable governs the display in sparse trees and in the agenda.
3035 When 0 or negative, it means use this number (the absolute value of it)
3036 even if a deadline has a different individual lead time specified.
3038 Custom commands can set this variable in the options section."
3039 :group 'org-time
3040 :group 'org-agenda-daily/weekly
3041 :type 'integer)
3043 (defcustom org-scheduled-delay-days 0
3044 "Number of days before a scheduled item becomes active.
3045 This variable governs the display in sparse trees and in the agenda.
3046 The default value (i.e. 0) means: don't delay scheduled item.
3047 When negative, it means use this number (the absolute value of it)
3048 even if a scheduled item has a different individual delay time
3049 specified.
3051 Custom commands can set this variable in the options section."
3052 :group 'org-time
3053 :group 'org-agenda-daily/weekly
3054 :version "24.4"
3055 :package-version '(Org . "8.0")
3056 :type 'integer)
3058 (defcustom org-read-date-prefer-future t
3059 "Non-nil means assume future for incomplete date input from user.
3060 This affects the following situations:
3061 1. The user gives a month but not a year.
3062 For example, if it is April and you enter \"feb 2\", this will be read
3063 as Feb 2, *next* year. \"May 5\", however, will be this year.
3064 2. The user gives a day, but no month.
3065 For example, if today is the 15th, and you enter \"3\", Org-mode will
3066 read this as the third of *next* month. However, if you enter \"17\",
3067 it will be considered as *this* month.
3069 If you set this variable to the symbol `time', then also the following
3070 will work:
3072 3. If the user gives a time.
3073 If the time is before now, it will be interpreted as tomorrow.
3075 Currently none of this works for ISO week specifications.
3077 When this option is nil, the current day, month and year will always be
3078 used as defaults.
3080 See also `org-agenda-jump-prefer-future'."
3081 :group 'org-time
3082 :type '(choice
3083 (const :tag "Never" nil)
3084 (const :tag "Check month and day" t)
3085 (const :tag "Check month, day, and time" time)))
3087 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3088 "Should the agenda jump command prefer the future for incomplete dates?
3089 The default is to do the same as configured in `org-read-date-prefer-future'.
3090 But you can also set a deviating value here.
3091 This may t or nil, or the symbol `org-read-date-prefer-future'."
3092 :group 'org-agenda
3093 :group 'org-time
3094 :version "24.1"
3095 :type '(choice
3096 (const :tag "Use org-read-date-prefer-future"
3097 org-read-date-prefer-future)
3098 (const :tag "Never" nil)
3099 (const :tag "Always" t)))
3101 (defcustom org-read-date-force-compatible-dates t
3102 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3104 Depending on the system Emacs is running on, certain dates cannot
3105 be represented with the type used internally to represent time.
3106 Dates between 1970-1-1 and 2038-1-1 can always be represented
3107 correctly. Some systems allow for earlier dates, some for later,
3108 some for both. One way to find out it to insert any date into an
3109 Org buffer, putting the cursor on the year and hitting S-up and
3110 S-down to test the range.
3112 When this variable is set to t, the date/time prompt will not let
3113 you specify dates outside the 1970-2037 range, so it is certain that
3114 these dates will work in whatever version of Emacs you are
3115 running, and also that you can move a file from one Emacs implementation
3116 to another. WHenever Org is forcing the year for you, it will display
3117 a message and beep.
3119 When this variable is nil, Org will check if the date is
3120 representable in the specific Emacs implementation you are using.
3121 If not, it will force a year, usually the current year, and beep
3122 to remind you. Currently this setting is not recommended because
3123 the likelihood that you will open your Org files in an Emacs that
3124 has limited date range is not negligible.
3126 A workaround for this problem is to use diary sexp dates for time
3127 stamps outside of this range."
3128 :group 'org-time
3129 :version "24.1"
3130 :type 'boolean)
3132 (defcustom org-read-date-display-live t
3133 "Non-nil means display current interpretation of date prompt live.
3134 This display will be in an overlay, in the minibuffer."
3135 :group 'org-time
3136 :type 'boolean)
3138 (defcustom org-read-date-popup-calendar t
3139 "Non-nil means pop up a calendar when prompting for a date.
3140 In the calendar, the date can be selected with mouse-1. However, the
3141 minibuffer will also be active, and you can simply enter the date as well.
3142 When nil, only the minibuffer will be available."
3143 :group 'org-time
3144 :type 'boolean)
3145 (org-defvaralias 'org-popup-calendar-for-date-prompt
3146 'org-read-date-popup-calendar)
3148 (make-obsolete-variable
3149 'org-read-date-minibuffer-setup-hook
3150 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3151 (defcustom org-read-date-minibuffer-setup-hook nil
3152 "Hook to be used to set up keys for the date/time interface.
3153 Add key definitions to `minibuffer-local-map', which will be a
3154 temporary copy.
3156 WARNING: This option is obsolete, you should use
3157 `org-read-date-minibuffer-local-map' to set up keys."
3158 :group 'org-time
3159 :type 'hook)
3161 (defcustom org-extend-today-until 0
3162 "The hour when your day really ends. Must be an integer.
3163 This has influence for the following applications:
3164 - When switching the agenda to \"today\". It it is still earlier than
3165 the time given here, the day recognized as TODAY is actually yesterday.
3166 - When a date is read from the user and it is still before the time given
3167 here, the current date and time will be assumed to be yesterday, 23:59.
3168 Also, timestamps inserted in capture templates follow this rule.
3170 IMPORTANT: This is a feature whose implementation is and likely will
3171 remain incomplete. Really, it is only here because past midnight seems to
3172 be the favorite working time of John Wiegley :-)"
3173 :group 'org-time
3174 :type 'integer)
3176 (defcustom org-use-effective-time nil
3177 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3178 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3179 \"effective time\" of any timestamps between midnight and 8am will be
3180 23:59 of the previous day."
3181 :group 'org-time
3182 :version "24.1"
3183 :type 'boolean)
3185 (defcustom org-use-last-clock-out-time-as-effective-time nil
3186 "When non-nil, use the last clock out time for `org-todo'.
3187 Note that this option has precedence over the combined use of
3188 `org-use-effective-time' and `org-extend-today-until'."
3189 :group 'org-time
3190 :version "24.4"
3191 :package-version '(Org . "8.0")
3192 :type 'boolean)
3194 (defcustom org-edit-timestamp-down-means-later nil
3195 "Non-nil means S-down will increase the time in a time stamp.
3196 When nil, S-up will increase."
3197 :group 'org-time
3198 :type 'boolean)
3200 (defcustom org-calendar-follow-timestamp-change t
3201 "Non-nil means make the calendar window follow timestamp changes.
3202 When a timestamp is modified and the calendar window is visible, it will be
3203 moved to the new date."
3204 :group 'org-time
3205 :type 'boolean)
3207 (defgroup org-tags nil
3208 "Options concerning tags in Org-mode."
3209 :tag "Org Tags"
3210 :group 'org)
3212 (defcustom org-tag-alist nil
3213 "List of tags allowed in Org-mode files.
3214 When this list is nil, Org-mode will base TAG input on what is already in the
3215 buffer.
3216 The value of this variable is an alist, the car of each entry must be a
3217 keyword as a string, the cdr may be a character that is used to select
3218 that tag through the fast-tag-selection interface.
3219 See the manual for details."
3220 :group 'org-tags
3221 :type '(repeat
3222 (choice
3223 (cons (string :tag "Tag name")
3224 (character :tag "Access char"))
3225 (list :tag "Start radio group"
3226 (const :startgroup)
3227 (option (string :tag "Group description")))
3228 (list :tag "Group tags delimiter"
3229 (const :grouptags))
3230 (list :tag "End radio group"
3231 (const :endgroup)
3232 (option (string :tag "Group description")))
3233 (const :tag "New line" (:newline)))))
3235 (defcustom org-tag-persistent-alist nil
3236 "List of tags that will always appear in all Org-mode files.
3237 This is in addition to any in buffer settings or customizations
3238 of `org-tag-alist'.
3239 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3240 The value of this variable is an alist, the car of each entry must be a
3241 keyword as a string, the cdr may be a character that is used to select
3242 that tag through the fast-tag-selection interface.
3243 See the manual for details.
3244 To disable these tags on a per-file basis, insert anywhere in the file:
3245 #+STARTUP: noptag"
3246 :group 'org-tags
3247 :type '(repeat
3248 (choice
3249 (cons (string :tag "Tag name")
3250 (character :tag "Access char"))
3251 (const :tag "Start radio group" (:startgroup))
3252 (const :tag "Group tags delimiter" (:grouptags))
3253 (const :tag "End radio group" (:endgroup))
3254 (const :tag "New line" (:newline)))))
3256 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3257 "If non-nil, always offer completion for all tags of all agenda files.
3258 Instead of customizing this variable directly, you might want to
3259 set it locally for capture buffers, because there no list of
3260 tags in that file can be created dynamically (there are none).
3262 (add-hook 'org-capture-mode-hook
3263 (lambda ()
3264 (set (make-local-variable
3265 'org-complete-tags-always-offer-all-agenda-tags)
3266 t)))"
3267 :group 'org-tags
3268 :version "24.1"
3269 :type 'boolean)
3271 (defvar org-file-tags nil
3272 "List of tags that can be inherited by all entries in the file.
3273 The tags will be inherited if the variable `org-use-tag-inheritance'
3274 says they should be.
3275 This variable is populated from #+FILETAGS lines.")
3277 (defcustom org-use-fast-tag-selection 'auto
3278 "Non-nil means use fast tag selection scheme.
3279 This is a special interface to select and deselect tags with single keys.
3280 When nil, fast selection is never used.
3281 When the symbol `auto', fast selection is used if and only if selection
3282 characters for tags have been configured, either through the variable
3283 `org-tag-alist' or through a #+TAGS line in the buffer.
3284 When t, fast selection is always used and selection keys are assigned
3285 automatically if necessary."
3286 :group 'org-tags
3287 :type '(choice
3288 (const :tag "Always" t)
3289 (const :tag "Never" nil)
3290 (const :tag "When selection characters are configured" auto)))
3292 (defcustom org-fast-tag-selection-single-key nil
3293 "Non-nil means fast tag selection exits after first change.
3294 When nil, you have to press RET to exit it.
3295 During fast tag selection, you can toggle this flag with `C-c'.
3296 This variable can also have the value `expert'. In this case, the window
3297 displaying the tags menu is not even shown, until you press C-c again."
3298 :group 'org-tags
3299 :type '(choice
3300 (const :tag "No" nil)
3301 (const :tag "Yes" t)
3302 (const :tag "Expert" expert)))
3304 (defvar org-fast-tag-selection-include-todo nil
3305 "Non-nil means fast tags selection interface will also offer TODO states.
3306 This is an undocumented feature, you should not rely on it.")
3308 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3309 "The column to which tags should be indented in a headline.
3310 If this number is positive, it specifies the column. If it is negative,
3311 it means that the tags should be flushright to that column. For example,
3312 -80 works well for a normal 80 character screen.
3313 When 0, place tags directly after headline text, with only one space in
3314 between."
3315 :group 'org-tags
3316 :type 'integer)
3318 (defcustom org-auto-align-tags t
3319 "Non-nil keeps tags aligned when modifying headlines.
3320 Some operations (i.e. demoting) change the length of a headline and
3321 therefore shift the tags around. With this option turned on, after
3322 each such operation the tags are again aligned to `org-tags-column'."
3323 :group 'org-tags
3324 :type 'boolean)
3326 (defcustom org-use-tag-inheritance t
3327 "Non-nil means tags in levels apply also for sublevels.
3328 When nil, only the tags directly given in a specific line apply there.
3329 This may also be a list of tags that should be inherited, or a regexp that
3330 matches tags that should be inherited. Additional control is possible
3331 with the variable `org-tags-exclude-from-inheritance' which gives an
3332 explicit list of tags to be excluded from inheritance, even if the value of
3333 `org-use-tag-inheritance' would select it for inheritance.
3335 If this option is t, a match early-on in a tree can lead to a large
3336 number of matches in the subtree when constructing the agenda or creating
3337 a sparse tree. If you only want to see the first match in a tree during
3338 a search, check out the variable `org-tags-match-list-sublevels'."
3339 :group 'org-tags
3340 :type '(choice
3341 (const :tag "Not" nil)
3342 (const :tag "Always" t)
3343 (repeat :tag "Specific tags" (string :tag "Tag"))
3344 (regexp :tag "Tags matched by regexp")))
3346 (defcustom org-tags-exclude-from-inheritance nil
3347 "List of tags that should never be inherited.
3348 This is a way to exclude a few tags from inheritance. For way to do
3349 the opposite, to actively allow inheritance for selected tags,
3350 see the variable `org-use-tag-inheritance'."
3351 :group 'org-tags
3352 :type '(repeat (string :tag "Tag")))
3354 (defun org-tag-inherit-p (tag)
3355 "Check if TAG is one that should be inherited."
3356 (cond
3357 ((member tag org-tags-exclude-from-inheritance) nil)
3358 ((eq org-use-tag-inheritance t) t)
3359 ((not org-use-tag-inheritance) nil)
3360 ((stringp org-use-tag-inheritance)
3361 (string-match org-use-tag-inheritance tag))
3362 ((listp org-use-tag-inheritance)
3363 (member tag org-use-tag-inheritance))
3364 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3366 (defcustom org-tags-match-list-sublevels t
3367 "Non-nil means list also sublevels of headlines matching a search.
3368 This variable applies to tags/property searches, and also to stuck
3369 projects because this search is based on a tags match as well.
3371 When set to the symbol `indented', sublevels are indented with
3372 leading dots.
3374 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3375 the sublevels of a headline matching a tag search often also match
3376 the same search. Listing all of them can create very long lists.
3377 Setting this variable to nil causes subtrees of a match to be skipped.
3379 This variable is semi-obsolete and probably should always be true. It
3380 is better to limit inheritance to certain tags using the variables
3381 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3382 :group 'org-tags
3383 :type '(choice
3384 (const :tag "No, don't list them" nil)
3385 (const :tag "Yes, do list them" t)
3386 (const :tag "List them, indented with leading dots" indented)))
3388 (defcustom org-tags-sort-function nil
3389 "When set, tags are sorted using this function as a comparator."
3390 :group 'org-tags
3391 :type '(choice
3392 (const :tag "No sorting" nil)
3393 (const :tag "Alphabetical" string<)
3394 (const :tag "Reverse alphabetical" string>)
3395 (function :tag "Custom function" nil)))
3397 (defvar org-tags-history nil
3398 "History of minibuffer reads for tags.")
3399 (defvar org-last-tags-completion-table nil
3400 "The last used completion table for tags.")
3401 (defvar org-after-tags-change-hook nil
3402 "Hook that is run after the tags in a line have changed.")
3404 (defgroup org-properties nil
3405 "Options concerning properties in Org-mode."
3406 :tag "Org Properties"
3407 :group 'org)
3409 (defcustom org-property-format "%-10s %s"
3410 "How property key/value pairs should be formatted by `indent-line'.
3411 When `indent-line' hits a property definition, it will format the line
3412 according to this format, mainly to make sure that the values are
3413 lined-up with respect to each other."
3414 :group 'org-properties
3415 :type 'string)
3417 (defcustom org-properties-postprocess-alist nil
3418 "Alist of properties and functions to adjust inserted values.
3419 Elements of this alist must be of the form
3421 ([string] [function])
3423 where [string] must be a property name and [function] must be a
3424 lambda expression: this lambda expression must take one argument,
3425 the value to adjust, and return the new value as a string.
3427 For example, this element will allow the property \"Remaining\"
3428 to be updated wrt the relation between the \"Effort\" property
3429 and the clock summary:
3431 ((\"Remaining\" (lambda(value)
3432 (let ((clocksum (org-clock-sum-current-item))
3433 (effort (org-duration-string-to-minutes
3434 (org-entry-get (point) \"Effort\"))))
3435 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3436 :group 'org-properties
3437 :version "24.1"
3438 :type '(alist :key-type (string :tag "Property")
3439 :value-type (function :tag "Function")))
3441 (defcustom org-use-property-inheritance nil
3442 "Non-nil means properties apply also for sublevels.
3444 This setting is chiefly used during property searches. Turning it on can
3445 cause significant overhead when doing a search, which is why it is not
3446 on by default.
3448 When nil, only the properties directly given in the current entry count.
3449 When t, every property is inherited. The value may also be a list of
3450 properties that should have inheritance, or a regular expression matching
3451 properties that should be inherited.
3453 However, note that some special properties use inheritance under special
3454 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3455 and the properties ending in \"_ALL\" when they are used as descriptor
3456 for valid values of a property.
3458 Note for programmers:
3459 When querying an entry with `org-entry-get', you can control if inheritance
3460 should be used. By default, `org-entry-get' looks only at the local
3461 properties. You can request inheritance by setting the inherit argument
3462 to t (to force inheritance) or to `selective' (to respect the setting
3463 in this variable)."
3464 :group 'org-properties
3465 :type '(choice
3466 (const :tag "Not" nil)
3467 (const :tag "Always" t)
3468 (repeat :tag "Specific properties" (string :tag "Property"))
3469 (regexp :tag "Properties matched by regexp")))
3471 (defun org-property-inherit-p (property)
3472 "Check if PROPERTY is one that should be inherited."
3473 (cond
3474 ((eq org-use-property-inheritance t) t)
3475 ((not org-use-property-inheritance) nil)
3476 ((stringp org-use-property-inheritance)
3477 (string-match org-use-property-inheritance property))
3478 ((listp org-use-property-inheritance)
3479 (member property org-use-property-inheritance))
3480 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3482 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3483 "The default column format, if no other format has been defined.
3484 This variable can be set on the per-file basis by inserting a line
3486 #+COLUMNS: %25ITEM ....."
3487 :group 'org-properties
3488 :type 'string)
3490 (defcustom org-columns-ellipses ".."
3491 "The ellipses to be used when a field in column view is truncated.
3492 When this is the empty string, as many characters as possible are shown,
3493 but then there will be no visual indication that the field has been truncated.
3494 When this is a string of length N, the last N characters of a truncated
3495 field are replaced by this string. If the column is narrower than the
3496 ellipses string, only part of the ellipses string will be shown."
3497 :group 'org-properties
3498 :type 'string)
3500 (defcustom org-columns-modify-value-for-display-function nil
3501 "Function that modifies values for display in column view.
3502 For example, it can be used to cut out a certain part from a time stamp.
3503 The function must take 2 arguments:
3505 column-title The title of the column (*not* the property name)
3506 value The value that should be modified.
3508 The function should return the value that should be displayed,
3509 or nil if the normal value should be used."
3510 :group 'org-properties
3511 :type '(choice (const nil) (function)))
3513 (defcustom org-effort-property "Effort"
3514 "The property that is being used to keep track of effort estimates.
3515 Effort estimates given in this property need to have the format H:MM."
3516 :group 'org-properties
3517 :group 'org-progress
3518 :type '(string :tag "Property"))
3520 (defconst org-global-properties-fixed
3521 '(("VISIBILITY_ALL" . "folded children content all")
3522 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3523 "List of property/value pairs that can be inherited by any entry.
3525 These are fixed values, for the preset properties. The user variable
3526 that can be used to add to this list is `org-global-properties'.
3528 The entries in this list are cons cells where the car is a property
3529 name and cdr is a string with the value. If the value represents
3530 multiple items like an \"_ALL\" property, separate the items by
3531 spaces.")
3533 (defcustom org-global-properties nil
3534 "List of property/value pairs that can be inherited by any entry.
3536 This list will be combined with the constant `org-global-properties-fixed'.
3538 The entries in this list are cons cells where the car is a property
3539 name and cdr is a string with the value.
3541 You can set buffer-local values for the same purpose in the variable
3542 `org-file-properties' this by adding lines like
3544 #+PROPERTY: NAME VALUE"
3545 :group 'org-properties
3546 :type '(repeat
3547 (cons (string :tag "Property")
3548 (string :tag "Value"))))
3550 (defvar org-file-properties nil
3551 "List of property/value pairs that can be inherited by any entry.
3552 Valid for the current buffer.
3553 This variable is populated from #+PROPERTY lines.")
3554 (make-variable-buffer-local 'org-file-properties)
3556 (defgroup org-agenda nil
3557 "Options concerning agenda views in Org-mode."
3558 :tag "Org Agenda"
3559 :group 'org)
3561 (defvar org-category nil
3562 "Variable used by org files to set a category for agenda display.
3563 Such files should use a file variable to set it, for example
3565 # -*- mode: org; org-category: \"ELisp\"
3567 or contain a special line
3569 #+CATEGORY: ELisp
3571 If the file does not specify a category, then file's base name
3572 is used instead.")
3573 (make-variable-buffer-local 'org-category)
3574 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3576 (defcustom org-agenda-files nil
3577 "The files to be used for agenda display.
3578 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3579 \\[org-remove-file]. You can also use customize to edit the list.
3581 If an entry is a directory, all files in that directory that are matched by
3582 `org-agenda-file-regexp' will be part of the file list.
3584 If the value of the variable is not a list but a single file name, then
3585 the list of agenda files is actually stored and maintained in that file, one
3586 agenda file per line. In this file paths can be given relative to
3587 `org-directory'. Tilde expansion and environment variable substitution
3588 are also made."
3589 :group 'org-agenda
3590 :type '(choice
3591 (repeat :tag "List of files and directories" file)
3592 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3594 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3595 "Regular expression to match files for `org-agenda-files'.
3596 If any element in the list in that variable contains a directory instead
3597 of a normal file, all files in that directory that are matched by this
3598 regular expression will be included."
3599 :group 'org-agenda
3600 :type 'regexp)
3602 (defcustom org-agenda-text-search-extra-files nil
3603 "List of extra files to be searched by text search commands.
3604 These files will be searched in addition to the agenda files by the
3605 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3606 Note that these files will only be searched for text search commands,
3607 not for the other agenda views like todo lists, tag searches or the weekly
3608 agenda. This variable is intended to list notes and possibly archive files
3609 that should also be searched by these two commands.
3610 In fact, if the first element in the list is the symbol `agenda-archives',
3611 then all archive files of all agenda files will be added to the search
3612 scope."
3613 :group 'org-agenda
3614 :type '(set :greedy t
3615 (const :tag "Agenda Archives" agenda-archives)
3616 (repeat :inline t (file))))
3618 (org-defvaralias 'org-agenda-multi-occur-extra-files
3619 'org-agenda-text-search-extra-files)
3621 (defcustom org-agenda-skip-unavailable-files nil
3622 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3623 A nil value means to remove them, after a query, from the list."
3624 :group 'org-agenda
3625 :type 'boolean)
3627 (defcustom org-calendar-to-agenda-key [?c]
3628 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3629 The command `org-calendar-goto-agenda' will be bound to this key. The
3630 default is the character `c' because then `c' can be used to switch back and
3631 forth between agenda and calendar."
3632 :group 'org-agenda
3633 :type 'sexp)
3635 (defcustom org-calendar-insert-diary-entry-key [?i]
3636 "The key to be installed in `calendar-mode-map' for adding diary entries.
3637 This option is irrelevant until `org-agenda-diary-file' has been configured
3638 to point to an Org-mode file. When that is the case, the command
3639 `org-agenda-diary-entry' will be bound to the key given here, by default
3640 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3641 if you want to continue doing this, you need to change this to a different
3642 key."
3643 :group 'org-agenda
3644 :type 'sexp)
3646 (defcustom org-agenda-diary-file 'diary-file
3647 "File to which to add new entries with the `i' key in agenda and calendar.
3648 When this is the symbol `diary-file', the functionality in the Emacs
3649 calendar will be used to add entries to the `diary-file'. But when this
3650 points to a file, `org-agenda-diary-entry' will be used instead."
3651 :group 'org-agenda
3652 :type '(choice
3653 (const :tag "The standard Emacs diary file" diary-file)
3654 (file :tag "Special Org file diary entries")))
3656 (eval-after-load "calendar"
3657 '(progn
3658 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3659 'org-calendar-goto-agenda)
3660 (add-hook 'calendar-mode-hook
3661 (lambda ()
3662 (unless (eq org-agenda-diary-file 'diary-file)
3663 (define-key calendar-mode-map
3664 org-calendar-insert-diary-entry-key
3665 'org-agenda-diary-entry))))))
3667 (defgroup org-latex nil
3668 "Options for embedding LaTeX code into Org-mode."
3669 :tag "Org LaTeX"
3670 :group 'org)
3672 (defcustom org-format-latex-options
3673 '(:foreground default :background default :scale 1.0
3674 :html-foreground "Black" :html-background "Transparent"
3675 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3676 "Options for creating images from LaTeX fragments.
3677 This is a property list with the following properties:
3678 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3679 `default' means use the foreground of the default face.
3680 `auto' means use the foreground from the text face.
3681 :background the background color, or \"Transparent\".
3682 `default' means use the background of the default face.
3683 `auto' means use the background from the text face.
3684 :scale a scaling factor for the size of the images, to get more pixels
3685 :html-foreground, :html-background, :html-scale
3686 the same numbers for HTML export.
3687 :matchers a list indicating which matchers should be used to
3688 find LaTeX fragments. Valid members of this list are:
3689 \"begin\" find environments
3690 \"$1\" find single characters surrounded by $.$
3691 \"$\" find math expressions surrounded by $...$
3692 \"$$\" find math expressions surrounded by $$....$$
3693 \"\\(\" find math expressions surrounded by \\(...\\)
3694 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3695 :group 'org-latex
3696 :type 'plist)
3698 (defcustom org-format-latex-signal-error t
3699 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3700 When nil, just push out a message."
3701 :group 'org-latex
3702 :version "24.1"
3703 :type 'boolean)
3705 (defcustom org-latex-to-mathml-jar-file nil
3706 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3707 Use this to specify additional executable file say a jar file.
3709 When using MathToWeb as the converter, specify the full-path to
3710 your mathtoweb.jar file."
3711 :group 'org-latex
3712 :version "24.1"
3713 :type '(choice
3714 (const :tag "None" nil)
3715 (file :tag "JAR file" :must-match t)))
3717 (defcustom org-latex-to-mathml-convert-command nil
3718 "Command to convert LaTeX fragments to MathML.
3719 Replace format-specifiers in the command as noted below and use
3720 `shell-command' to convert LaTeX to MathML.
3721 %j: Executable file in fully expanded form as specified by
3722 `org-latex-to-mathml-jar-file'.
3723 %I: Input LaTeX file in fully expanded form
3724 %o: Output MathML file
3725 This command is used by `org-create-math-formula'.
3727 When using MathToWeb as the converter, set this to
3728 \"java -jar %j -unicode -force -df %o %I\"."
3729 :group 'org-latex
3730 :version "24.1"
3731 :type '(choice
3732 (const :tag "None" nil)
3733 (string :tag "\nShell command")))
3735 (defcustom org-latex-create-formula-image-program 'dvipng
3736 "Program to convert LaTeX fragments with.
3738 dvipng Process the LaTeX fragments to dvi file, then convert
3739 dvi files to png files using dvipng.
3740 This will also include processing of non-math environments.
3741 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3742 to convert pdf files to png files"
3743 :group 'org-latex
3744 :version "24.1"
3745 :type '(choice
3746 (const :tag "dvipng" dvipng)
3747 (const :tag "imagemagick" imagemagick)))
3749 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3750 "Path to store latex preview images.
3751 A relative path here creates many directories relative to the
3752 processed org files paths. An absolute path puts all preview
3753 images at the same place."
3754 :group 'org-latex
3755 :version "24.3"
3756 :type 'string)
3758 (defun org-format-latex-mathml-available-p ()
3759 "Return t if `org-latex-to-mathml-convert-command' is usable."
3760 (save-match-data
3761 (when (and (boundp 'org-latex-to-mathml-convert-command)
3762 org-latex-to-mathml-convert-command)
3763 (let ((executable (car (split-string
3764 org-latex-to-mathml-convert-command))))
3765 (when (executable-find executable)
3766 (if (string-match
3767 "%j" org-latex-to-mathml-convert-command)
3768 (file-readable-p org-latex-to-mathml-jar-file)
3769 t))))))
3771 (defcustom org-format-latex-header "\\documentclass{article}
3772 \\usepackage[usenames]{color}
3773 \[PACKAGES]
3774 \[DEFAULT-PACKAGES]
3775 \\pagestyle{empty} % do not remove
3776 % The settings below are copied from fullpage.sty
3777 \\setlength{\\textwidth}{\\paperwidth}
3778 \\addtolength{\\textwidth}{-3cm}
3779 \\setlength{\\oddsidemargin}{1.5cm}
3780 \\addtolength{\\oddsidemargin}{-2.54cm}
3781 \\setlength{\\evensidemargin}{\\oddsidemargin}
3782 \\setlength{\\textheight}{\\paperheight}
3783 \\addtolength{\\textheight}{-\\headheight}
3784 \\addtolength{\\textheight}{-\\headsep}
3785 \\addtolength{\\textheight}{-\\footskip}
3786 \\addtolength{\\textheight}{-3cm}
3787 \\setlength{\\topmargin}{1.5cm}
3788 \\addtolength{\\topmargin}{-2.54cm}"
3789 "The document header used for processing LaTeX fragments.
3790 It is imperative that this header make sure that no page number
3791 appears on the page. The package defined in the variables
3792 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3793 will either replace the placeholder \"[PACKAGES]\" in this
3794 header, or they will be appended."
3795 :group 'org-latex
3796 :type 'string)
3798 (defun org-set-packages-alist (var val)
3799 "Set the packages alist and make sure it has 3 elements per entry."
3800 (set var (mapcar (lambda (x)
3801 (if (and (consp x) (= (length x) 2))
3802 (list (car x) (nth 1 x) t)
3804 val)))
3806 (defun org-get-packages-alist (var)
3807 "Get the packages alist and make sure it has 3 elements per entry."
3808 (mapcar (lambda (x)
3809 (if (and (consp x) (= (length x) 2))
3810 (list (car x) (nth 1 x) t)
3812 (default-value var)))
3814 (defcustom org-latex-default-packages-alist
3815 '(("AUTO" "inputenc" t)
3816 ("T1" "fontenc" t)
3817 ("" "fixltx2e" nil)
3818 ("" "graphicx" t)
3819 ("" "longtable" nil)
3820 ("" "float" nil)
3821 ("" "wrapfig" nil)
3822 ("" "rotating" nil)
3823 ("normalem" "ulem" t)
3824 ("" "amsmath" t)
3825 ("" "textcomp" t)
3826 ("" "marvosym" t)
3827 ("" "wasysym" t)
3828 ("" "amssymb" t)
3829 ("" "hyperref" nil)
3830 "\\tolerance=1000")
3831 "Alist of default packages to be inserted in the header.
3833 Change this only if one of the packages here causes an
3834 incompatibility with another package you are using.
3836 The packages in this list are needed by one part or another of
3837 Org mode to function properly:
3839 - inputenc, fontenc: for basic font and character selection
3840 - fixltx2e: Important patches of LaTeX itself
3841 - graphicx: for including images
3842 - longtable: For multipage tables
3843 - float, wrapfig: for figure placement
3844 - rotating: for sideways figures and tables
3845 - ulem: for underline and strike-through
3846 - amsmath: for subscript and superscript and math environments
3847 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3848 for interpreting the entities in `org-entities'. You can skip
3849 some of these packages if you don't use any of their symbols.
3850 - hyperref: for cross references
3852 Therefore you should not modify this variable unless you know
3853 what you are doing. The one reason to change it anyway is that
3854 you might be loading some other package that conflicts with one
3855 of the default packages. Each cell is of the format
3856 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3857 the package also needs to be included when compiling LaTeX
3858 snippets into images for inclusion into non-LaTeX output."
3859 :group 'org-latex
3860 :group 'org-export-latex
3861 :set 'org-set-packages-alist
3862 :get 'org-get-packages-alist
3863 :version "24.1"
3864 :type '(repeat
3865 (choice
3866 (list :tag "options/package pair"
3867 (string :tag "options")
3868 (string :tag "package")
3869 (boolean :tag "Snippet"))
3870 (string :tag "A line of LaTeX"))))
3872 (defcustom org-latex-packages-alist nil
3873 "Alist of packages to be inserted in every LaTeX header.
3875 These will be inserted after `org-latex-default-packages-alist'.
3876 Each cell is of the format:
3878 \(\"options\" \"package\" snippet-flag)
3880 SNIPPET-FLAG, when t, indicates that this package is also needed
3881 when turning LaTeX snippets into images for inclusion into
3882 non-LaTeX output.
3884 Make sure that you only list packages here which:
3886 - you want in every file
3887 - do not conflict with the setup in `org-format-latex-header'.
3888 - do not conflict with the default packages in
3889 `org-latex-default-packages-alist'."
3890 :group 'org-latex
3891 :group 'org-export-latex
3892 :set 'org-set-packages-alist
3893 :get 'org-get-packages-alist
3894 :type '(repeat
3895 (choice
3896 (list :tag "options/package pair"
3897 (string :tag "options")
3898 (string :tag "package")
3899 (boolean :tag "Snippet"))
3900 (string :tag "A line of LaTeX"))))
3902 (defgroup org-appearance nil
3903 "Settings for Org-mode appearance."
3904 :tag "Org Appearance"
3905 :group 'org)
3907 (defcustom org-level-color-stars-only nil
3908 "Non-nil means fontify only the stars in each headline.
3909 When nil, the entire headline is fontified.
3910 Changing it requires restart of `font-lock-mode' to become effective
3911 also in regions already fontified."
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-hide-leading-stars nil
3916 "Non-nil means hide the first N-1 stars in a headline.
3917 This works by using the face `org-hide' for these stars. This
3918 face is white for a light background, and black for a dark
3919 background. You may have to customize the face `org-hide' to
3920 make this work.
3921 Changing it requires restart of `font-lock-mode' to become effective
3922 also in regions already fontified.
3923 You may also set this on a per-file basis by adding one of the following
3924 lines to the buffer:
3926 #+STARTUP: hidestars
3927 #+STARTUP: showstars"
3928 :group 'org-appearance
3929 :type 'boolean)
3931 (defcustom org-hidden-keywords nil
3932 "List of symbols corresponding to keywords to be hidden the org buffer.
3933 For example, a value '(title) for this list will make the document's title
3934 appear in the buffer without the initial #+TITLE: keyword."
3935 :group 'org-appearance
3936 :version "24.1"
3937 :type '(set (const :tag "#+AUTHOR" author)
3938 (const :tag "#+DATE" date)
3939 (const :tag "#+EMAIL" email)
3940 (const :tag "#+TITLE" title)))
3942 (defcustom org-custom-properties nil
3943 "List of properties (as strings) with a special meaning.
3944 The default use of these custom properties is to let the user
3945 hide them with `org-toggle-custom-properties-visibility'."
3946 :group 'org-properties
3947 :group 'org-appearance
3948 :version "24.3"
3949 :type '(repeat (string :tag "Property Name")))
3951 (defcustom org-fontify-done-headline nil
3952 "Non-nil means change the face of a headline if it is marked DONE.
3953 Normally, only the TODO/DONE keyword indicates the state of a headline.
3954 When this is non-nil, the headline after the keyword is set to the
3955 `org-headline-done' as an additional indication."
3956 :group 'org-appearance
3957 :type 'boolean)
3959 (defcustom org-fontify-emphasized-text t
3960 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3961 Changing this variable requires a restart of Emacs to take effect."
3962 :group 'org-appearance
3963 :type 'boolean)
3965 (defcustom org-fontify-whole-heading-line nil
3966 "Non-nil means fontify the whole line for headings.
3967 This is useful when setting a background color for the
3968 org-level-* faces."
3969 :group 'org-appearance
3970 :type 'boolean)
3972 (defcustom org-highlight-latex-and-related nil
3973 "Non-nil means highlight LaTeX related syntax in the buffer.
3974 When non nil, the value should be a list containing any of the
3975 following symbols:
3976 `latex' Highlight LaTeX snippets and environments.
3977 `script' Highlight subscript and superscript.
3978 `entities' Highlight entities."
3979 :group 'org-appearance
3980 :version "24.4"
3981 :package-version '(Org . "8.0")
3982 :type '(choice
3983 (const :tag "No highlighting" nil)
3984 (set :greedy t :tag "Highlight"
3985 (const :tag "LaTeX snippets and environments" latex)
3986 (const :tag "Subscript and superscript" script)
3987 (const :tag "Entities" entities))))
3989 (defcustom org-hide-emphasis-markers nil
3990 "Non-nil mean font-lock should hide the emphasis marker characters."
3991 :group 'org-appearance
3992 :type 'boolean)
3994 (defcustom org-pretty-entities nil
3995 "Non-nil means show entities as UTF8 characters.
3996 When nil, the \\name form remains in the buffer."
3997 :group 'org-appearance
3998 :version "24.1"
3999 :type 'boolean)
4001 (defcustom org-pretty-entities-include-sub-superscripts t
4002 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4003 :group 'org-appearance
4004 :version "24.1"
4005 :type 'boolean)
4007 (defvar org-emph-re nil
4008 "Regular expression for matching emphasis.
4009 After a match, the match groups contain these elements:
4010 0 The match of the full regular expression, including the characters
4011 before and after the proper match
4012 1 The character before the proper match, or empty at beginning of line
4013 2 The proper match, including the leading and trailing markers
4014 3 The leading marker like * or /, indicating the type of highlighting
4015 4 The text between the emphasis markers, not including the markers
4016 5 The character after the match, empty at the end of a line")
4017 (defvar org-verbatim-re nil
4018 "Regular expression for matching verbatim text.")
4019 (defvar org-emphasis-regexp-components) ; defined just below
4020 (defvar org-emphasis-alist) ; defined just below
4021 (defun org-set-emph-re (var val)
4022 "Set variable and compute the emphasis regular expression."
4023 (set var val)
4024 (when (and (boundp 'org-emphasis-alist)
4025 (boundp 'org-emphasis-regexp-components)
4026 org-emphasis-alist org-emphasis-regexp-components)
4027 (let* ((e org-emphasis-regexp-components)
4028 (pre (car e))
4029 (post (nth 1 e))
4030 (border (nth 2 e))
4031 (body (nth 3 e))
4032 (nl (nth 4 e))
4033 (body1 (concat body "*?"))
4034 (markers (mapconcat 'car org-emphasis-alist ""))
4035 (vmarkers (mapconcat
4036 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4037 org-emphasis-alist "")))
4038 ;; make sure special characters appear at the right position in the class
4039 (if (string-match "\\^" markers)
4040 (setq markers (concat (replace-match "" t t markers) "^")))
4041 (if (string-match "-" markers)
4042 (setq markers (concat (replace-match "" t t markers) "-")))
4043 (if (string-match "\\^" vmarkers)
4044 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4045 (if (string-match "-" vmarkers)
4046 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4047 (if (> nl 0)
4048 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4049 (int-to-string nl) "\\}")))
4050 ;; Make the regexp
4051 (setq org-emph-re
4052 (concat "\\([" pre "]\\|^\\)"
4053 "\\("
4054 "\\([" markers "]\\)"
4055 "\\("
4056 "[^" border "]\\|"
4057 "[^" border "]"
4058 body1
4059 "[^" border "]"
4060 "\\)"
4061 "\\3\\)"
4062 "\\([" post "]\\|$\\)"))
4063 (setq org-verbatim-re
4064 (concat "\\([" pre "]\\|^\\)"
4065 "\\("
4066 "\\([" vmarkers "]\\)"
4067 "\\("
4068 "[^" border "]\\|"
4069 "[^" border "]"
4070 body1
4071 "[^" border "]"
4072 "\\)"
4073 "\\3\\)"
4074 "\\([" post "]\\|$\\)")))))
4076 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4077 ;; set this option proved cumbersome. See this message/thread:
4078 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4079 (defvar org-emphasis-regexp-components
4080 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4081 "Components used to build the regular expression for emphasis.
4082 This is a list with five entries. Terminology: In an emphasis string
4083 like \" *strong word* \", we call the initial space PREMATCH, the final
4084 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4085 and \"trong wor\" is the body. The different components in this variable
4086 specify what is allowed/forbidden in each part:
4088 pre Chars allowed as prematch. Beginning of line will be allowed too.
4089 post Chars allowed as postmatch. End of line will be allowed too.
4090 border The chars *forbidden* as border characters.
4091 body-regexp A regexp like \".\" to match a body character. Don't use
4092 non-shy groups here, and don't allow newline here.
4093 newline The maximum number of newlines allowed in an emphasis exp.
4095 You need to reload Org or to restart Emacs after customizing this.")
4097 (defcustom org-emphasis-alist
4098 `(("*" bold)
4099 ("/" italic)
4100 ("_" underline)
4101 ("=" org-code verbatim)
4102 ("~" org-verbatim verbatim)
4103 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4104 "Alist of characters and faces to emphasize text.
4105 Text starting and ending with a special character will be emphasized,
4106 for example *bold*, _underlined_ and /italic/. This variable sets the
4107 marker characters and the face to be used by font-lock for highlighting
4108 in Org-mode Emacs buffers.
4110 You need to reload Org or to restart Emacs after customizing this."
4111 :group 'org-appearance
4112 :set 'org-set-emph-re
4113 :version "24.4"
4114 :package-version '(Org . "8.0")
4115 :type '(repeat
4116 (list
4117 (string :tag "Marker character")
4118 (choice
4119 (face :tag "Font-lock-face")
4120 (plist :tag "Face property list"))
4121 (option (const verbatim)))))
4123 (defvar org-protecting-blocks
4124 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4125 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4126 This is needed for font-lock setup.")
4128 ;;; Miscellaneous options
4130 (defgroup org-completion nil
4131 "Completion in Org-mode."
4132 :tag "Org Completion"
4133 :group 'org)
4135 (defcustom org-completion-use-ido nil
4136 "Non-nil means use ido completion wherever possible.
4137 Note that `ido-mode' must be active for this variable to be relevant.
4138 If you decide to turn this variable on, you might well want to turn off
4139 `org-outline-path-complete-in-steps'.
4140 See also `org-completion-use-iswitchb'."
4141 :group 'org-completion
4142 :type 'boolean)
4144 (defcustom org-completion-use-iswitchb nil
4145 "Non-nil means use iswitchb completion wherever possible.
4146 Note that `iswitchb-mode' must be active for this variable to be relevant.
4147 If you decide to turn this variable on, you might well want to turn off
4148 `org-outline-path-complete-in-steps'.
4149 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4150 :group 'org-completion
4151 :type 'boolean)
4153 (defcustom org-completion-fallback-command 'hippie-expand
4154 "The expansion command called by \\[pcomplete] in normal context.
4155 Normal means, no org-mode-specific context."
4156 :group 'org-completion
4157 :type 'function)
4159 ;;; Functions and variables from their packages
4160 ;; Declared here to avoid compiler warnings
4162 ;; XEmacs only
4163 (defvar outline-mode-menu-heading)
4164 (defvar outline-mode-menu-show)
4165 (defvar outline-mode-menu-hide)
4166 (defvar zmacs-regions) ; XEmacs regions
4168 ;; Emacs only
4169 (defvar mark-active)
4171 ;; Various packages
4172 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4173 (declare-function calendar-forward-day "cal-move" (arg))
4174 (declare-function calendar-goto-date "cal-move" (date))
4175 (declare-function calendar-goto-today "cal-move" ())
4176 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4177 (defvar calc-embedded-close-formula)
4178 (defvar calc-embedded-open-formula)
4179 (declare-function cdlatex-tab "ext:cdlatex" ())
4180 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4181 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4182 (defvar font-lock-unfontify-region-function)
4183 (declare-function iswitchb-read-buffer "iswitchb"
4184 (prompt &optional default require-match start matches-set))
4185 (defvar iswitchb-temp-buflist)
4186 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4187 (defvar org-agenda-tags-todo-honor-ignore-options)
4188 (declare-function org-agenda-skip "org-agenda" ())
4189 (declare-function
4190 org-agenda-format-item "org-agenda"
4191 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4192 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4193 (declare-function org-agenda-change-all-lines "org-agenda"
4194 (newhead hdmarker &optional fixface just-this))
4195 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4196 (declare-function org-agenda-maybe-redo "org-agenda" ())
4197 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4198 (beg end))
4199 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4200 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4201 "org-agenda" (&optional end))
4202 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4203 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4204 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4205 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4206 (declare-function org-indent-mode "org-indent" (&optional arg))
4207 (declare-function parse-time-string "parse-time" (string))
4208 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4209 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4210 (defvar remember-data-file)
4211 (defvar texmathp-why)
4212 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4213 (declare-function table--at-cell-p "table" (position &optional object at-column))
4215 (defvar org-latex-regexps)
4217 ;;; Autoload and prepare some org modules
4219 ;; Some table stuff that needs to be defined here, because it is used
4220 ;; by the functions setting up org-mode or checking for table context.
4222 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4223 "Detect an org-type or table-type table.")
4224 (defconst org-table-line-regexp "^[ \t]*|"
4225 "Detect an org-type table line.")
4226 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4227 "Detect an org-type table line.")
4228 (defconst org-table-hline-regexp "^[ \t]*|-"
4229 "Detect an org-type table hline.")
4230 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4231 "Detect a table-type table hline.")
4232 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4233 "Detect the first line outside a table when searching from within it.
4234 This works for both table types.")
4236 ;; Autoload the functions in org-table.el that are needed by functions here.
4238 (eval-and-compile
4239 (org-autoload "org-table"
4240 '(org-table-begin org-table-blank-field org-table-end)))
4242 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4243 "Detect a #+TBLFM line.")
4245 ;;;###autoload
4246 (defun turn-on-orgtbl ()
4247 "Unconditionally turn on `orgtbl-mode'."
4248 (require 'org-table)
4249 (orgtbl-mode 1))
4251 (defun org-at-table-p (&optional table-type)
4252 "Return t if the cursor is inside an org-type table.
4253 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4254 (if org-enable-table-editor
4255 (save-excursion
4256 (beginning-of-line 1)
4257 (looking-at (if table-type org-table-any-line-regexp
4258 org-table-line-regexp)))
4259 nil))
4260 (defsubst org-table-p () (org-at-table-p))
4262 (defun org-at-table.el-p ()
4263 "Return t if and only if we are at a table.el table."
4264 (and (org-at-table-p 'any)
4265 (save-excursion
4266 (goto-char (org-table-begin 'any))
4267 (looking-at org-table1-hline-regexp))))
4269 (defun org-table-recognize-table.el ()
4270 "If there is a table.el table nearby, recognize it and move into it."
4271 (if org-table-tab-recognizes-table.el
4272 (if (org-at-table.el-p)
4273 (progn
4274 (beginning-of-line 1)
4275 (if (looking-at org-table-dataline-regexp)
4277 (if (looking-at org-table1-hline-regexp)
4278 (progn
4279 (beginning-of-line 2)
4280 (if (looking-at org-table-any-border-regexp)
4281 (beginning-of-line -1)))))
4282 (if (re-search-forward "|" (org-table-end t) t)
4283 (progn
4284 (require 'table)
4285 (if (table--at-cell-p (point))
4287 (message "recognizing table.el table...")
4288 (table-recognize-table)
4289 (message "recognizing table.el table...done")))
4290 (error "This should not happen"))
4292 nil)
4293 nil))
4295 (defun org-at-table-hline-p ()
4296 "Return t if the cursor is inside a hline in a table."
4297 (if org-enable-table-editor
4298 (save-excursion
4299 (beginning-of-line 1)
4300 (looking-at org-table-hline-regexp))
4301 nil))
4303 (defun org-table-map-tables (function &optional quietly)
4304 "Apply FUNCTION to the start of all tables in the buffer."
4305 (save-excursion
4306 (save-restriction
4307 (widen)
4308 (goto-char (point-min))
4309 (while (re-search-forward org-table-any-line-regexp nil t)
4310 (unless quietly
4311 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4312 (beginning-of-line 1)
4313 (when (and (looking-at org-table-line-regexp)
4314 ;; Exclude tables in src/example/verbatim/clocktable blocks
4315 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4316 (save-excursion (funcall function))
4317 (or (looking-at org-table-line-regexp)
4318 (forward-char 1)))
4319 (re-search-forward org-table-any-border-regexp nil 1))))
4320 (unless quietly (message "Mapping tables: done")))
4322 ;; Declare and autoload functions from org-agenda.el
4324 (eval-and-compile
4325 (org-autoload "org-agenda"
4326 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4328 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4329 (declare-function org-clock-update-mode-line "org-clock" ())
4330 (declare-function org-resolve-clocks "org-clock"
4331 (&optional also-non-dangling-p prompt last-valid))
4333 (defun org-at-TBLFM-p (&optional pos)
4334 "Return t when point (or POS) is in #+TBLFM line."
4335 (save-excursion
4336 (let ((pos pos)))
4337 (goto-char (or pos (point)))
4338 (beginning-of-line 1)
4339 (looking-at org-TBLFM-regexp)))
4341 (defvar org-clock-start-time)
4342 (defvar org-clock-marker (make-marker)
4343 "Marker recording the last clock-in.")
4344 (defvar org-clock-hd-marker (make-marker)
4345 "Marker recording the last clock-in, but the headline position.")
4346 (defvar org-clock-heading ""
4347 "The heading of the current clock entry.")
4348 (defun org-clock-is-active ()
4349 "Return the buffer where the clock is currently running.
4350 Return nil if no clock is running."
4351 (marker-buffer org-clock-marker))
4353 (eval-and-compile
4354 (org-autoload "org-clock" '(org-clock-remove-overlays
4355 org-clock-update-time-maybe
4356 org-clocktable-shift)))
4358 (defun org-check-running-clock ()
4359 "Check if the current buffer contains the running clock.
4360 If yes, offer to stop it and to save the buffer with the changes."
4361 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4362 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4363 (buffer-name))))
4364 (org-clock-out)
4365 (when (y-or-n-p "Save changed buffer?")
4366 (save-buffer))))
4368 (defun org-clocktable-try-shift (dir n)
4369 "Check if this line starts a clock table, if yes, shift the time block."
4370 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4371 (org-clocktable-shift dir n)))
4373 ;;;###autoload
4374 (defun org-clock-persistence-insinuate ()
4375 "Set up hooks for clock persistence."
4376 (require 'org-clock)
4377 (add-hook 'org-mode-hook 'org-clock-load)
4378 (add-hook 'kill-emacs-hook 'org-clock-save))
4380 ;; Define the variable already here, to make sure we have it.
4381 (defvar org-indent-mode nil
4382 "Non-nil if Org-Indent mode is enabled.
4383 Use the command `org-indent-mode' to change this variable.")
4385 ;; Autoload archiving code
4386 ;; The stuff that is needed for cycling and tags has to be defined here.
4388 (defgroup org-archive nil
4389 "Options concerning archiving in Org-mode."
4390 :tag "Org Archive"
4391 :group 'org-structure)
4393 (defcustom org-archive-location "%s_archive::"
4394 "The location where subtrees should be archived.
4396 The value of this variable is a string, consisting of two parts,
4397 separated by a double-colon. The first part is a filename and
4398 the second part is a headline.
4400 When the filename is omitted, archiving happens in the same file.
4401 %s in the filename will be replaced by the current file
4402 name (without the directory part). Archiving to a different file
4403 is useful to keep archived entries from contributing to the
4404 Org-mode Agenda.
4406 The archived entries will be filed as subtrees of the specified
4407 headline. When the headline is omitted, the subtrees are simply
4408 filed away at the end of the file, as top-level entries. Also in
4409 the heading you can use %s to represent the file name, this can be
4410 useful when using the same archive for a number of different files.
4412 Here are a few examples:
4413 \"%s_archive::\"
4414 If the current file is Projects.org, archive in file
4415 Projects.org_archive, as top-level trees. This is the default.
4417 \"::* Archived Tasks\"
4418 Archive in the current file, under the top-level headline
4419 \"* Archived Tasks\".
4421 \"~/org/archive.org::\"
4422 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4424 \"~/org/archive.org::* From %s\"
4425 Archive in file ~/org/archive.org (absolute path), under headlines
4426 \"From FILENAME\" where file name is the current file name.
4428 \"~/org/datetree.org::datetree/* Finished Tasks\"
4429 The \"datetree/\" string is special, signifying to archive
4430 items to the datetree. Items are placed in either the CLOSED
4431 date of the item, or the current date if there is no CLOSED date.
4432 The heading will be a subentry to the current date. There doesn't
4433 need to be a heading, but there always needs to be a slash after
4434 datetree. For example, to store archived items directly in the
4435 datetree, use \"~/org/datetree.org::datetree/\".
4437 \"basement::** Finished Tasks\"
4438 Archive in file ./basement (relative path), as level 3 trees
4439 below the level 2 heading \"** Finished Tasks\".
4441 You may set this option on a per-file basis by adding to the buffer a
4442 line like
4444 #+ARCHIVE: basement::** Finished Tasks
4446 You may also define it locally for a subtree by setting an ARCHIVE property
4447 in the entry. If such a property is found in an entry, or anywhere up
4448 the hierarchy, it will be used."
4449 :group 'org-archive
4450 :type 'string)
4452 (defcustom org-archive-tag "ARCHIVE"
4453 "The tag that marks a subtree as archived.
4454 An archived subtree does not open during visibility cycling, and does
4455 not contribute to the agenda listings.
4456 After changing this, font-lock must be restarted in the relevant buffers to
4457 get the proper fontification."
4458 :group 'org-archive
4459 :group 'org-keywords
4460 :type 'string)
4462 (defcustom org-agenda-skip-archived-trees t
4463 "Non-nil means the agenda will skip any items located in archived trees.
4464 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4465 variable is no longer recommended, you should leave it at the value t.
4466 Instead, use the key `v' to cycle the archives-mode in the agenda."
4467 :group 'org-archive
4468 :group 'org-agenda-skip
4469 :type 'boolean)
4471 (defcustom org-columns-skip-archived-trees t
4472 "Non-nil means ignore archived trees when creating column view."
4473 :group 'org-archive
4474 :group 'org-properties
4475 :type 'boolean)
4477 (defcustom org-cycle-open-archived-trees nil
4478 "Non-nil means `org-cycle' will open archived trees.
4479 An archived tree is a tree marked with the tag ARCHIVE.
4480 When nil, archived trees will stay folded. You can still open them with
4481 normal outline commands like `show-all', but not with the cycling commands."
4482 :group 'org-archive
4483 :group 'org-cycle
4484 :type 'boolean)
4486 (defcustom org-sparse-tree-open-archived-trees nil
4487 "Non-nil means sparse tree construction shows matches in archived trees.
4488 When nil, matches in these trees are highlighted, but the trees are kept in
4489 collapsed state."
4490 :group 'org-archive
4491 :group 'org-sparse-trees
4492 :type 'boolean)
4494 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4495 "The default date type when building a sparse tree.
4496 When this is nil, a date is a scheduled or a deadline timestamp.
4497 Otherwise, these types are allowed:
4499 all: all timestamps
4500 active: only active timestamps (<...>)
4501 inactive: only inactive timestamps (<...)
4502 scheduled: only scheduled timestamps
4503 deadline: only deadline timestamps"
4504 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4505 (const :tag "All timestamps" all)
4506 (const :tag "Only active timestamps" active)
4507 (const :tag "Only inactive timestamps" inactive)
4508 (const :tag "Only scheduled timestamps" scheduled)
4509 (const :tag "Only deadline timestamps" deadline)
4510 (const :tag "Only closed timestamps" closed))
4511 :version "24.3"
4512 :group 'org-sparse-trees)
4514 (defun org-cycle-hide-archived-subtrees (state)
4515 "Re-hide all archived subtrees after a visibility state change."
4516 (when (and (not org-cycle-open-archived-trees)
4517 (not (memq state '(overview folded))))
4518 (save-excursion
4519 (let* ((globalp (memq state '(contents all)))
4520 (beg (if globalp (point-min) (point)))
4521 (end (if globalp (point-max) (org-end-of-subtree t))))
4522 (org-hide-archived-subtrees beg end)
4523 (goto-char beg)
4524 (if (looking-at (concat ".*:" org-archive-tag ":"))
4525 (message "%s" (substitute-command-keys
4526 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4528 (defun org-force-cycle-archived ()
4529 "Cycle subtree even if it is archived."
4530 (interactive)
4531 (setq this-command 'org-cycle)
4532 (let ((org-cycle-open-archived-trees t))
4533 (call-interactively 'org-cycle)))
4535 (defun org-hide-archived-subtrees (beg end)
4536 "Re-hide all archived subtrees after a visibility state change."
4537 (save-excursion
4538 (let* ((re (concat ":" org-archive-tag ":")))
4539 (goto-char beg)
4540 (while (re-search-forward re end t)
4541 (when (org-at-heading-p)
4542 (org-flag-subtree t)
4543 (org-end-of-subtree t))))))
4545 (declare-function outline-end-of-heading "outline" ())
4546 (declare-function outline-flag-region "outline" (from to flag))
4547 (defun org-flag-subtree (flag)
4548 (save-excursion
4549 (org-back-to-heading t)
4550 (outline-end-of-heading)
4551 (outline-flag-region (point)
4552 (progn (org-end-of-subtree t) (point))
4553 flag)))
4555 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4557 (eval-and-compile
4558 (org-autoload "org-archive"
4559 '(org-add-archive-files)))
4561 ;; Autoload Column View Code
4563 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4564 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4565 (declare-function org-columns-compute "org-colview" (property))
4567 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4568 '(org-columns-number-to-string
4569 org-columns-get-format-and-top-level
4570 org-columns-compute
4571 org-columns-remove-overlays))
4573 ;; Autoload ID code
4575 (declare-function org-id-store-link "org-id")
4576 (declare-function org-id-locations-load "org-id")
4577 (declare-function org-id-locations-save "org-id")
4578 (defvar org-id-track-globally)
4579 (org-autoload "org-id"
4580 '(org-id-new
4581 org-id-copy
4582 org-id-get-with-outline-path-completion
4583 org-id-get-with-outline-drilling))
4585 ;;; Variables for pre-computed regular expressions, all buffer local
4587 (defvar org-todo-regexp nil
4588 "Matches any of the TODO state keywords.")
4589 (make-variable-buffer-local 'org-todo-regexp)
4590 (defvar org-not-done-regexp nil
4591 "Matches any of the TODO state keywords except the last one.")
4592 (make-variable-buffer-local 'org-not-done-regexp)
4593 (defvar org-not-done-heading-regexp nil
4594 "Matches a TODO headline that is not done.")
4595 (make-variable-buffer-local 'org-not-done-regexp)
4596 (defvar org-todo-line-regexp nil
4597 "Matches a headline and puts TODO state into group 2 if present.")
4598 (make-variable-buffer-local 'org-todo-line-regexp)
4599 (defvar org-complex-heading-regexp nil
4600 "Matches a headline and puts everything into groups:
4601 group 1: the stars
4602 group 2: The todo keyword, maybe
4603 group 3: Priority cookie
4604 group 4: True headline
4605 group 5: Tags")
4606 (make-variable-buffer-local 'org-complex-heading-regexp)
4607 (defvar org-complex-heading-regexp-format nil
4608 "Printf format to make regexp to match an exact headline.
4609 This regexp will match the headline of any node which has the
4610 exact headline text that is put into the format, but may have any
4611 TODO state, priority and tags.")
4612 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4613 (defvar org-todo-line-tags-regexp nil
4614 "Matches a headline and puts TODO state into group 2 if present.
4615 Also put tags into group 4 if tags are present.")
4616 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4617 (defvar org-ds-keyword-length 12
4618 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4619 (make-variable-buffer-local 'org-ds-keyword-length)
4620 (defvar org-deadline-regexp nil
4621 "Matches the DEADLINE keyword.")
4622 (make-variable-buffer-local 'org-deadline-regexp)
4623 (defvar org-deadline-time-regexp nil
4624 "Matches the DEADLINE keyword together with a time stamp.")
4625 (make-variable-buffer-local 'org-deadline-time-regexp)
4626 (defvar org-deadline-time-hour-regexp nil
4627 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4628 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4629 (defvar org-deadline-line-regexp nil
4630 "Matches the DEADLINE keyword and the rest of the line.")
4631 (make-variable-buffer-local 'org-deadline-line-regexp)
4632 (defvar org-scheduled-regexp nil
4633 "Matches the SCHEDULED keyword.")
4634 (make-variable-buffer-local 'org-scheduled-regexp)
4635 (defvar org-scheduled-time-regexp nil
4636 "Matches the SCHEDULED keyword together with a time stamp.")
4637 (make-variable-buffer-local 'org-scheduled-time-regexp)
4638 (defvar org-scheduled-time-hour-regexp nil
4639 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4640 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4641 (defvar org-closed-time-regexp nil
4642 "Matches the CLOSED keyword together with a time stamp.")
4643 (make-variable-buffer-local 'org-closed-time-regexp)
4645 (defvar org-keyword-time-regexp nil
4646 "Matches any of the 4 keywords, together with the time stamp.")
4647 (make-variable-buffer-local 'org-keyword-time-regexp)
4648 (defvar org-keyword-time-not-clock-regexp nil
4649 "Matches any of the 3 keywords, together with the time stamp.")
4650 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4651 (defvar org-maybe-keyword-time-regexp nil
4652 "Matches a timestamp, possibly preceded by a keyword.")
4653 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4654 (defvar org-all-time-keywords nil
4655 "List of time keywords.")
4656 (make-variable-buffer-local 'org-all-time-keywords)
4658 (defconst org-plain-time-of-day-regexp
4659 (concat
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\(--?"
4663 "\\(\\<[012]?[0-9]"
4664 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4665 "\\)?")
4666 "Regular expression to match a plain time or time range.
4667 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4668 groups carry important information:
4669 0 the full match
4670 1 the first time, range or not
4671 8 the second time, if it is a range.")
4673 (defconst org-plain-time-extension-regexp
4674 (concat
4675 "\\(\\<[012]?[0-9]"
4676 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4677 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4678 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4679 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4680 groups carry important information:
4681 0 the full match
4682 7 hours of duration
4683 9 minutes of duration")
4685 (defconst org-stamp-time-of-day-regexp
4686 (concat
4687 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4688 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4689 "\\(--?"
4690 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4691 "Regular expression to match a timestamp time or time range.
4692 After a match, the following groups carry important information:
4693 0 the full match
4694 1 date plus weekday, for back referencing to make sure both times are on the same day
4695 2 the first time, range or not
4696 4 the second time, if it is a range.")
4698 (defconst org-startup-options
4699 '(("fold" org-startup-folded t)
4700 ("overview" org-startup-folded t)
4701 ("nofold" org-startup-folded nil)
4702 ("showall" org-startup-folded nil)
4703 ("showeverything" org-startup-folded showeverything)
4704 ("content" org-startup-folded content)
4705 ("indent" org-startup-indented t)
4706 ("noindent" org-startup-indented nil)
4707 ("hidestars" org-hide-leading-stars t)
4708 ("showstars" org-hide-leading-stars nil)
4709 ("odd" org-odd-levels-only t)
4710 ("oddeven" org-odd-levels-only nil)
4711 ("align" org-startup-align-all-tables t)
4712 ("noalign" org-startup-align-all-tables nil)
4713 ("inlineimages" org-startup-with-inline-images t)
4714 ("noinlineimages" org-startup-with-inline-images nil)
4715 ("latexpreview" org-startup-with-latex-preview t)
4716 ("nolatexpreview" org-startup-with-latex-preview nil)
4717 ("customtime" org-display-custom-times t)
4718 ("logdone" org-log-done time)
4719 ("lognotedone" org-log-done note)
4720 ("nologdone" org-log-done nil)
4721 ("lognoteclock-out" org-log-note-clock-out t)
4722 ("nolognoteclock-out" org-log-note-clock-out nil)
4723 ("logrepeat" org-log-repeat state)
4724 ("lognoterepeat" org-log-repeat note)
4725 ("logdrawer" org-log-into-drawer t)
4726 ("nologdrawer" org-log-into-drawer nil)
4727 ("logstatesreversed" org-log-states-order-reversed t)
4728 ("nologstatesreversed" org-log-states-order-reversed nil)
4729 ("nologrepeat" org-log-repeat nil)
4730 ("logreschedule" org-log-reschedule time)
4731 ("lognotereschedule" org-log-reschedule note)
4732 ("nologreschedule" org-log-reschedule nil)
4733 ("logredeadline" org-log-redeadline time)
4734 ("lognoteredeadline" org-log-redeadline note)
4735 ("nologredeadline" org-log-redeadline nil)
4736 ("logrefile" org-log-refile time)
4737 ("lognoterefile" org-log-refile note)
4738 ("nologrefile" org-log-refile nil)
4739 ("fninline" org-footnote-define-inline t)
4740 ("nofninline" org-footnote-define-inline nil)
4741 ("fnlocal" org-footnote-section nil)
4742 ("fnauto" org-footnote-auto-label t)
4743 ("fnprompt" org-footnote-auto-label nil)
4744 ("fnconfirm" org-footnote-auto-label confirm)
4745 ("fnplain" org-footnote-auto-label plain)
4746 ("fnadjust" org-footnote-auto-adjust t)
4747 ("nofnadjust" org-footnote-auto-adjust nil)
4748 ("constcgs" constants-unit-system cgs)
4749 ("constSI" constants-unit-system SI)
4750 ("noptag" org-tag-persistent-alist nil)
4751 ("hideblocks" org-hide-block-startup t)
4752 ("nohideblocks" org-hide-block-startup nil)
4753 ("beamer" org-startup-with-beamer-mode t)
4754 ("entitiespretty" org-pretty-entities t)
4755 ("entitiesplain" org-pretty-entities nil))
4756 "Variable associated with STARTUP options for org-mode.
4757 Each element is a list of three items: the startup options (as written
4758 in the #+STARTUP line), the corresponding variable, and the value to set
4759 this variable to if the option is found. An optional forth element PUSH
4760 means to push this value onto the list in the variable.")
4762 (defun org-update-property-plist (key val props)
4763 "Update PROPS with KEY and VAL."
4764 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4765 (key (if appending (substring key 0 (- (length key) 1)) key))
4766 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4767 (previous (cdr (assoc key props))))
4768 (if appending
4769 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4770 (cons (cons key val) remainder))))
4772 (defconst org-block-regexp
4773 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4774 "Regular expression for hiding blocks.")
4775 (defconst org-heading-keyword-regexp-format
4776 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4777 "Printf format for a regexp matching a headline with some keyword.
4778 This regexp will match the headline of any node which has the
4779 exact keyword that is put into the format. The keyword isn't in
4780 any group by default, but the stars and the body are.")
4781 (defconst org-heading-keyword-maybe-regexp-format
4782 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4783 "Printf format for a regexp matching a headline, possibly with some keyword.
4784 This regexp can match any headline with the specified keyword, or
4785 without a keyword. The keyword isn't in any group by default,
4786 but the stars and the body are.")
4788 (defcustom org-group-tags t
4789 "When non-nil (the default), use group tags.
4790 This can be turned on/off through `org-toggle-tags-groups'."
4791 :group 'org-tags
4792 :group 'org-startup
4793 :type 'boolean)
4795 (defun org-toggle-tags-groups ()
4796 "Toggle support for group tags.
4797 Support for group tags is controlled by the option
4798 `org-group-tags', which is non-nil by default."
4799 (interactive)
4800 (setq org-group-tags (not org-group-tags))
4801 (cond ((and (derived-mode-p 'org-agenda-mode)
4802 org-group-tags)
4803 (org-agenda-redo))
4804 ((derived-mode-p 'org-mode)
4805 (let ((org-inhibit-startup t)) (org-mode))))
4806 (message "Groups tags support has been turned %s"
4807 (if org-group-tags "on" "off")))
4809 (defun org-set-regexps-and-options-for-tags ()
4810 "Precompute variables used for tags."
4811 (when (derived-mode-p 'org-mode)
4812 (org-set-local 'org-file-tags nil)
4813 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4814 (splitre "[ \t]+")
4815 (start 0)
4816 tags ftags key value)
4817 (save-excursion
4818 (save-restriction
4819 (widen)
4820 (goto-char (point-min))
4821 (while (re-search-forward re nil t)
4822 (setq key (upcase (org-match-string-no-properties 1))
4823 value (org-match-string-no-properties 2))
4824 (if (stringp value) (setq value (org-trim value)))
4825 (cond
4826 ((equal key "TAGS")
4827 (setq tags (append tags (if tags '("\\n") nil)
4828 (org-split-string value splitre))))
4829 ((equal key "FILETAGS")
4830 (when (string-match "\\S-" value)
4831 (setq ftags
4832 (append
4833 ftags
4834 (apply 'append
4835 (mapcar (lambda (x) (org-split-string x ":"))
4836 (org-split-string value)))))))))))
4837 ;; Process the file tags.
4838 (and ftags (org-set-local 'org-file-tags
4839 (mapcar 'org-add-prop-inherited ftags)))
4840 (org-set-local 'org-tag-groups-alist nil)
4841 ;; Process the tags.
4842 (when (and (not tags) org-tag-alist)
4843 (setq tags
4844 (mapcar
4845 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4846 ((eq (car tg) :endgroup) "}")
4847 ((eq (car tg) :grouptags) ":")
4848 ((eq (car tg) :newline) "\n")
4849 (t (concat (car tg)
4850 (if (characterp (cdr tg))
4851 (format "(%s)" (char-to-string (cdr tg))) "")))))
4852 org-tag-alist)))
4853 (let (e tgs g)
4854 (while (setq e (pop tags))
4855 (cond
4856 ((equal e "{")
4857 (progn (push '(:startgroup) tgs)
4858 (when (equal (nth 1 tags) ":")
4859 (push (list (replace-regexp-in-string
4860 "(.+)$" "" (nth 0 tags)))
4861 org-tag-groups-alist)
4862 (setq g 0))))
4863 ((equal e ":") (push '(:grouptags) tgs))
4864 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4865 ((equal e "\\n") (push '(:newline) tgs))
4866 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4867 (push (cons (match-string 1 e)
4868 (string-to-char (match-string 2 e))) tgs)
4869 (if (and g (> g 0))
4870 (setcar org-tag-groups-alist
4871 (append (car org-tag-groups-alist)
4872 (list (match-string 1 e)))))
4873 (if g (setq g (1+ g))))
4874 (t (push (list e) tgs)
4875 (if (and g (> g 0))
4876 (setcar org-tag-groups-alist
4877 (append (car org-tag-groups-alist) (list e))))
4878 (if g (setq g (1+ g))))))
4879 (org-set-local 'org-tag-alist nil)
4880 (while (setq e (pop tgs))
4881 (or (and (stringp (car e))
4882 (assoc (car e) org-tag-alist))
4883 (push e org-tag-alist)))
4884 ;; Return a list with tag variables
4885 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4887 (defvar org-ota nil)
4888 (defun org-set-regexps-and-options ()
4889 "Precompute regular expressions used in the current buffer."
4890 (when (derived-mode-p 'org-mode)
4891 (org-set-local 'org-todo-kwd-alist nil)
4892 (org-set-local 'org-todo-key-alist nil)
4893 (org-set-local 'org-todo-key-trigger nil)
4894 (org-set-local 'org-todo-keywords-1 nil)
4895 (org-set-local 'org-done-keywords nil)
4896 (org-set-local 'org-todo-heads nil)
4897 (org-set-local 'org-todo-sets nil)
4898 (org-set-local 'org-todo-log-states nil)
4899 (org-set-local 'org-file-properties nil)
4900 (let ((re (org-make-options-regexp
4901 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4902 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4903 "SETUPFILE" "OPTIONS")
4904 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4905 (splitre "[ \t]+")
4906 (scripts org-use-sub-superscripts)
4907 kwds kws0 kwsa key log value cat arch const links hw dws
4908 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4909 (start 0))
4910 (save-excursion
4911 (save-restriction
4912 (widen)
4913 (goto-char (point-min))
4914 (while
4915 (or (and
4916 ext-setup-or-nil
4917 (not org-ota)
4918 (let (ret)
4919 (with-temp-buffer
4920 (insert ext-setup-or-nil)
4921 (let ((major-mode 'org-mode) org-ota)
4922 (setq ret (save-match-data
4923 (org-set-regexps-and-options-for-tags)))))
4924 ;; Append setupfile tags to existing tags
4925 (setq org-ota t)
4926 (setq org-file-tags
4927 (delq nil (append org-file-tags (nth 0 ret)))
4928 org-tag-alist
4929 (delq nil (append org-tag-alist (nth 1 ret)))
4930 org-tag-groups-alist
4931 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4932 (and ext-setup-or-nil
4933 (string-match re ext-setup-or-nil start)
4934 (setq start (match-end 0)))
4935 (and (setq ext-setup-or-nil nil start 0)
4936 (re-search-forward re nil t)))
4937 (setq key (upcase (match-string 1 ext-setup-or-nil))
4938 value (org-match-string-no-properties 2 ext-setup-or-nil))
4939 (if (stringp value) (setq value (org-trim value)))
4940 (cond
4941 ((equal key "CATEGORY")
4942 (setq cat value))
4943 ((member key '("SEQ_TODO" "TODO"))
4944 (push (cons 'sequence (org-split-string value splitre)) kwds))
4945 ((equal key "TYP_TODO")
4946 (push (cons 'type (org-split-string value splitre)) kwds))
4947 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4948 ;; general TODO-like setup
4949 (push (cons (intern (downcase (match-string 1 key)))
4950 (org-split-string value splitre)) kwds))
4951 ((equal key "COLUMNS")
4952 (org-set-local 'org-columns-default-format value))
4953 ((equal key "LINK")
4954 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4955 (push (cons (match-string 1 value)
4956 (org-trim (match-string 2 value)))
4957 links)))
4958 ((equal key "PRIORITIES")
4959 (setq prio (org-split-string value " +")))
4960 ((equal key "PROPERTY")
4961 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4962 (setq props (org-update-property-plist (match-string 1 value)
4963 (match-string 2 value)
4964 props))))
4965 ((equal key "CONSTANTS")
4966 (org-table-set-constants))
4967 ((equal key "STARTUP")
4968 (let ((opts (org-split-string value splitre))
4969 l var val)
4970 (while (setq l (pop opts))
4971 (when (setq l (assoc l org-startup-options))
4972 (setq var (nth 1 l) val (nth 2 l))
4973 (if (not (nth 3 l))
4974 (set (make-local-variable var) val)
4975 (if (not (listp (symbol-value var)))
4976 (set (make-local-variable var) nil))
4977 (set (make-local-variable var) (symbol-value var))
4978 (add-to-list var val))))))
4979 ((equal key "ARCHIVE")
4980 (setq arch value)
4981 (remove-text-properties 0 (length arch)
4982 '(face t fontified t) arch))
4983 ((equal key "OPTIONS")
4984 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4985 (setq scripts (read (match-string 2 value)))))
4986 ((and (equal key "SETUPFILE")
4987 ;; Prevent checking in Gnus messages
4988 (not buffer-read-only))
4989 (setq setup-contents (org-file-contents
4990 (expand-file-name
4991 (org-remove-double-quotes value))
4992 'noerror))
4993 (if (not ext-setup-or-nil)
4994 (setq ext-setup-or-nil setup-contents start 0)
4995 (setq ext-setup-or-nil
4996 (concat (substring ext-setup-or-nil 0 start)
4997 "\n" setup-contents "\n"
4998 (substring ext-setup-or-nil start)))))))
4999 ;; search for property blocks
5000 (goto-char (point-min))
5001 (while (re-search-forward org-block-regexp nil t)
5002 (when (equal "PROPERTY" (upcase (match-string 1)))
5003 (setq value (replace-regexp-in-string
5004 "[\n\r]" " " (match-string 4)))
5005 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5006 (setq props (org-update-property-plist (match-string 1 value)
5007 (match-string 2 value)
5008 props)))))))
5009 (org-set-local 'org-use-sub-superscripts scripts)
5010 (when cat
5011 (org-set-local 'org-category (intern cat))
5012 (push (cons "CATEGORY" cat) props))
5013 (when prio
5014 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5015 (setq prio (mapcar 'string-to-char prio))
5016 (org-set-local 'org-highest-priority (nth 0 prio))
5017 (org-set-local 'org-lowest-priority (nth 1 prio))
5018 (org-set-local 'org-default-priority (nth 2 prio)))
5019 (and props (org-set-local 'org-file-properties (nreverse props)))
5020 (and arch (org-set-local 'org-archive-location arch))
5021 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5022 ;; Process the TODO keywords
5023 (unless kwds
5024 ;; Use the global values as if they had been given locally.
5025 (setq kwds (default-value 'org-todo-keywords))
5026 (if (stringp (car kwds))
5027 (setq kwds (list (cons org-todo-interpretation
5028 (default-value 'org-todo-keywords)))))
5029 (setq kwds (reverse kwds)))
5030 (setq kwds (nreverse kwds))
5031 (let (inter kws kw)
5032 (while (setq kws (pop kwds))
5033 (let ((kws (or
5034 (run-hook-with-args-until-success
5035 'org-todo-setup-filter-hook kws)
5036 kws)))
5037 (setq inter (pop kws) sep (member "|" kws)
5038 kws0 (delete "|" (copy-sequence kws))
5039 kwsa nil
5040 kws1 (mapcar
5041 (lambda (x)
5042 ;; 1 2
5043 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5044 (progn
5045 (setq kw (match-string 1 x)
5046 key (and (match-end 2) (match-string 2 x))
5047 log (org-extract-log-state-settings x))
5048 (push (cons kw (and key (string-to-char key))) kwsa)
5049 (and log (push log org-todo-log-states))
5051 (error "Invalid TODO keyword %s" x)))
5052 kws0)
5053 kwsa (if kwsa (append '((:startgroup))
5054 (nreverse kwsa)
5055 '((:endgroup))))
5056 hw (car kws1)
5057 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5058 tail (list inter hw (car dws) (org-last dws))))
5059 (add-to-list 'org-todo-heads hw 'append)
5060 (push kws1 org-todo-sets)
5061 (setq org-done-keywords (append org-done-keywords dws nil))
5062 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5063 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5064 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5065 (setq org-todo-sets (nreverse org-todo-sets)
5066 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5067 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5068 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5069 ;; Compute the regular expressions and other local variables.
5070 ;; Using `org-outline-regexp-bol' would complicate them much,
5071 ;; because of the fixed white space at the end of that string.
5072 (if (not org-done-keywords)
5073 (setq org-done-keywords (and org-todo-keywords-1
5074 (list (org-last org-todo-keywords-1)))))
5075 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5076 (length org-scheduled-string)
5077 (length org-clock-string)
5078 (length org-closed-string)))
5079 org-not-done-keywords
5080 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5081 org-todo-regexp
5082 (concat "\\("
5083 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5084 "\\)")
5085 org-not-done-regexp
5086 (concat "\\("
5087 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5088 "\\)")
5089 org-not-done-heading-regexp
5090 (format org-heading-keyword-regexp-format org-not-done-regexp)
5091 org-todo-line-regexp
5092 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5093 org-complex-heading-regexp
5094 (concat "^\\(\\*+\\)"
5095 "\\(?: +" org-todo-regexp "\\)?"
5096 "\\(?: +\\(\\[#.\\]\\)\\)?"
5097 "\\(?: +\\(.*?\\)\\)??"
5098 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5099 "[ \t]*$")
5100 org-complex-heading-regexp-format
5101 (concat "^\\(\\*+\\)"
5102 "\\(?: +" org-todo-regexp "\\)?"
5103 "\\(?: +\\(\\[#.\\]\\)\\)?"
5104 "\\(?: +"
5105 ;; Stats cookies can be stuck to body.
5106 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5107 "\\(%s\\)"
5108 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5109 "\\)"
5110 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5111 "[ \t]*$")
5112 org-todo-line-tags-regexp
5113 (concat "^\\(\\*+\\)"
5114 "\\(?: +" org-todo-regexp "\\)?"
5115 "\\(?: +\\(.*?\\)\\)??"
5116 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5117 "[ \t]*$")
5118 org-deadline-regexp (concat "\\<" org-deadline-string)
5119 org-deadline-time-regexp
5120 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5121 org-deadline-time-hour-regexp
5122 (concat "\\<" org-deadline-string
5123 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5124 org-deadline-line-regexp
5125 (concat "\\<\\(" org-deadline-string "\\).*")
5126 org-scheduled-regexp
5127 (concat "\\<" org-scheduled-string)
5128 org-scheduled-time-regexp
5129 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5130 org-scheduled-time-hour-regexp
5131 (concat "\\<" org-scheduled-string
5132 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5133 org-closed-time-regexp
5134 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5135 org-keyword-time-regexp
5136 (concat "\\<\\(" org-scheduled-string
5137 "\\|" org-deadline-string
5138 "\\|" org-closed-string
5139 "\\|" org-clock-string "\\)"
5140 " *[[<]\\([^]>]+\\)[]>]")
5141 org-keyword-time-not-clock-regexp
5142 (concat "\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\)"
5146 " *[[<]\\([^]>]+\\)[]>]")
5147 org-maybe-keyword-time-regexp
5148 (concat "\\(\\<\\(" org-scheduled-string
5149 "\\|" org-deadline-string
5150 "\\|" org-closed-string
5151 "\\|" org-clock-string "\\)\\)?"
5152 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5153 org-all-time-keywords
5154 (mapcar (lambda (w) (substring w 0 -1))
5155 (list org-scheduled-string org-deadline-string
5156 org-clock-string org-closed-string)))
5157 (setq org-ota nil)
5158 (org-compute-latex-and-related-regexp))))
5160 (defun org-file-contents (file &optional noerror)
5161 "Return the contents of FILE, as a string."
5162 (if (or (not file)
5163 (not (file-readable-p file)))
5164 (if noerror
5165 (message "Cannot read file \"%s\"" file)
5166 (error "Cannot read file \"%s\"" file))
5167 (with-temp-buffer
5168 (insert-file-contents file)
5169 (buffer-string))))
5171 (defun org-extract-log-state-settings (x)
5172 "Extract the log state setting from a TODO keyword string.
5173 This will extract info from a string like \"WAIT(w@/!)\"."
5174 (let (kw key log1 log2)
5175 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5176 (setq kw (match-string 1 x)
5177 key (and (match-end 2) (match-string 2 x))
5178 log1 (and (match-end 3) (match-string 3 x))
5179 log2 (and (match-end 4) (match-string 4 x)))
5180 (and (or log1 log2)
5181 (list kw
5182 (and log1 (if (equal log1 "!") 'time 'note))
5183 (and log2 (if (equal log2 "!") 'time 'note)))))))
5185 (defun org-remove-keyword-keys (list)
5186 "Remove a pair of parenthesis at the end of each string in LIST."
5187 (mapcar (lambda (x)
5188 (if (string-match "(.*)$" x)
5189 (substring x 0 (match-beginning 0))
5191 list))
5193 (defun org-assign-fast-keys (alist)
5194 "Assign fast keys to a keyword-key alist.
5195 Respect keys that are already there."
5196 (let (new e (alt ?0))
5197 (while (setq e (pop alist))
5198 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5199 (cdr e)) ;; Key already assigned.
5200 (push e new)
5201 (let ((clist (string-to-list (downcase (car e))))
5202 (used (append new alist)))
5203 (when (= (car clist) ?@)
5204 (pop clist))
5205 (while (and clist (rassoc (car clist) used))
5206 (pop clist))
5207 (unless clist
5208 (while (rassoc alt used)
5209 (incf alt)))
5210 (push (cons (car e) (or (car clist) alt)) new))))
5211 (nreverse new)))
5213 ;;; Some variables used in various places
5215 (defvar org-window-configuration nil
5216 "Used in various places to store a window configuration.")
5217 (defvar org-selected-window nil
5218 "Used in various places to store a window configuration.")
5219 (defvar org-finish-function nil
5220 "Function to be called when `C-c C-c' is used.
5221 This is for getting out of special buffers like capture.")
5224 ;; FIXME: Occasionally check by commenting these, to make sure
5225 ;; no other functions uses these, forgetting to let-bind them.
5226 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5227 (defvar org-last-state)
5228 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5230 ;; Defined somewhere in this file, but used before definition.
5231 (defvar org-entities) ;; defined in org-entities.el
5232 (defvar org-struct-menu)
5233 (defvar org-org-menu)
5234 (defvar org-tbl-menu)
5236 ;;;; Define the Org-mode
5238 ;; We use a before-change function to check if a table might need
5239 ;; an update.
5240 (defvar org-table-may-need-update t
5241 "Indicates that a table might need an update.
5242 This variable is set by `org-before-change-function'.
5243 `org-table-align' sets it back to nil.")
5244 (defun org-before-change-function (beg end)
5245 "Every change indicates that a table might need an update."
5246 (setq org-table-may-need-update t))
5247 (defvar org-mode-map)
5248 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5249 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5250 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5251 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5252 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5253 (defvar org-table-buffer-is-an nil)
5255 (defvar bidi-paragraph-direction)
5256 (defvar buffer-face-mode-face)
5258 (require 'outline)
5259 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5260 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5261 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5263 ;; Other stuff we need.
5264 (require 'time-date)
5265 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5266 (require 'easymenu)
5267 (require 'overlay)
5269 ;; (require 'org-macs) moved higher up in the file before it is first used
5270 (require 'org-entities)
5271 ;; (require 'org-compat) moved higher up in the file before it is first used
5272 (require 'org-faces)
5273 (require 'org-list)
5274 (require 'org-pcomplete)
5275 (require 'org-src)
5276 (require 'org-footnote)
5277 (require 'org-macro)
5279 ;; babel
5280 (require 'ob)
5282 ;;;###autoload
5283 (define-derived-mode org-mode outline-mode "Org"
5284 "Outline-based notes management and organizer, alias
5285 \"Carsten's outline-mode for keeping track of everything.\"
5287 Org-mode develops organizational tasks around a NOTES file which
5288 contains information about projects as plain text. Org-mode is
5289 implemented on top of outline-mode, which is ideal to keep the content
5290 of large files well structured. It supports ToDo items, deadlines and
5291 time stamps, which magically appear in the diary listing of the Emacs
5292 calendar. Tables are easily created with a built-in table editor.
5293 Plain text URL-like links connect to websites, emails (VM), Usenet
5294 messages (Gnus), BBDB entries, and any files related to the project.
5295 For printing and sharing of notes, an Org-mode file (or a part of it)
5296 can be exported as a structured ASCII or HTML file.
5298 The following commands are available:
5300 \\{org-mode-map}"
5302 ;; Get rid of Outline menus, they are not needed
5303 ;; Need to do this here because define-derived-mode sets up
5304 ;; the keymap so late. Still, it is a waste to call this each time
5305 ;; we switch another buffer into org-mode.
5306 (if (featurep 'xemacs)
5307 (when (boundp 'outline-mode-menu-heading)
5308 ;; Assume this is Greg's port, it uses easymenu
5309 (easy-menu-remove outline-mode-menu-heading)
5310 (easy-menu-remove outline-mode-menu-show)
5311 (easy-menu-remove outline-mode-menu-hide))
5312 (define-key org-mode-map [menu-bar headings] 'undefined)
5313 (define-key org-mode-map [menu-bar hide] 'undefined)
5314 (define-key org-mode-map [menu-bar show] 'undefined))
5316 (org-load-modules-maybe)
5317 (easy-menu-add org-org-menu)
5318 (easy-menu-add org-tbl-menu)
5319 (org-install-agenda-files-menu)
5320 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5321 (add-to-invisibility-spec '(org-cwidth))
5322 (add-to-invisibility-spec '(org-hide-block . t))
5323 (when (featurep 'xemacs)
5324 (org-set-local 'line-move-ignore-invisible t))
5325 (org-set-local 'outline-regexp org-outline-regexp)
5326 (org-set-local 'outline-level 'org-outline-level)
5327 (setq bidi-paragraph-direction 'left-to-right)
5328 (when (and org-ellipsis
5329 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5330 (fboundp 'make-glyph-code))
5331 (unless org-display-table
5332 (setq org-display-table (make-display-table)))
5333 (set-display-table-slot
5334 org-display-table 4
5335 (vconcat (mapcar
5336 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5337 org-ellipsis)))
5338 (if (stringp org-ellipsis) org-ellipsis "..."))))
5339 (setq buffer-display-table org-display-table))
5340 (org-set-regexps-and-options-for-tags)
5341 (org-set-regexps-and-options)
5342 (org-set-font-lock-defaults)
5343 (when (and org-tag-faces (not org-tags-special-faces-re))
5344 ;; tag faces set outside customize.... force initialization.
5345 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5346 ;; Calc embedded
5347 (org-set-local 'calc-embedded-open-mode "# ")
5348 ;; Modify a few syntax entries
5349 (modify-syntax-entry ?@ "w")
5350 (modify-syntax-entry ?\" "\"")
5351 (if org-startup-truncated (setq truncate-lines t))
5352 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5353 (org-set-local 'font-lock-unfontify-region-function
5354 'org-unfontify-region)
5355 ;; Activate before-change-function
5356 (org-set-local 'org-table-may-need-update t)
5357 (org-add-hook 'before-change-functions 'org-before-change-function nil
5358 'local)
5359 ;; Check for running clock before killing a buffer
5360 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5361 ;; Initialize macros templates.
5362 (org-macro-initialize-templates)
5363 ;; Initialize radio targets.
5364 (org-update-radio-target-regexp)
5365 ;; Indentation.
5366 (org-set-local 'indent-line-function 'org-indent-line)
5367 (org-set-local 'indent-region-function 'org-indent-region)
5368 ;; Filling and auto-filling.
5369 (org-setup-filling)
5370 ;; Comments.
5371 (org-setup-comments-handling)
5372 ;; Initialize cache.
5373 (org-element-cache-reset)
5374 ;; Beginning/end of defun
5375 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5376 (org-set-local 'end-of-defun-function 'org-forward-element)
5377 ;; Next error for sparse trees
5378 (org-set-local 'next-error-function 'org-occur-next-match)
5379 ;; Make sure dependence stuff works reliably, even for users who set it
5380 ;; too late :-(
5381 (if org-enforce-todo-dependencies
5382 (add-hook 'org-blocker-hook
5383 'org-block-todo-from-children-or-siblings-or-parent)
5384 (remove-hook 'org-blocker-hook
5385 'org-block-todo-from-children-or-siblings-or-parent))
5386 (if org-enforce-todo-checkbox-dependencies
5387 (add-hook 'org-blocker-hook
5388 'org-block-todo-from-checkboxes)
5389 (remove-hook 'org-blocker-hook
5390 'org-block-todo-from-checkboxes))
5392 ;; Align options lines
5393 (org-set-local
5394 'align-mode-rules-list
5395 '((org-in-buffer-settings
5396 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5397 (modes . '(org-mode)))))
5399 ;; Imenu
5400 (org-set-local 'imenu-create-index-function
5401 'org-imenu-get-tree)
5403 ;; Make isearch reveal context
5404 (if (or (featurep 'xemacs)
5405 (not (boundp 'outline-isearch-open-invisible-function)))
5406 ;; Emacs 21 and XEmacs make use of the hook
5407 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5408 ;; Emacs 22 deals with this through a special variable
5409 (org-set-local 'outline-isearch-open-invisible-function
5410 (lambda (&rest ignore) (org-show-context 'isearch)))
5411 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5413 ;; Setup the pcomplete hooks
5414 (set (make-local-variable 'pcomplete-command-completion-function)
5415 'org-pcomplete-initial)
5416 (set (make-local-variable 'pcomplete-command-name-function)
5417 'org-command-at-point)
5418 (set (make-local-variable 'pcomplete-default-completion-function)
5419 'ignore)
5420 (set (make-local-variable 'pcomplete-parse-arguments-function)
5421 'org-parse-arguments)
5422 (set (make-local-variable 'pcomplete-termination-string) "")
5423 (when (>= emacs-major-version 23)
5424 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5426 ;; If empty file that did not turn on org-mode automatically, make it to.
5427 (if (and org-insert-mode-line-in-empty-file
5428 (org-called-interactively-p 'any)
5429 (= (point-min) (point-max)))
5430 (insert "# -*- mode: org -*-\n\n"))
5431 (unless org-inhibit-startup
5432 (org-unmodified
5433 (and org-startup-with-beamer-mode (org-beamer-mode))
5434 (when org-startup-align-all-tables
5435 (org-table-map-tables 'org-table-align 'quietly))
5436 (when org-startup-with-inline-images
5437 (org-display-inline-images))
5438 (when org-startup-with-latex-preview
5439 (org-preview-latex-fragment))
5440 (unless org-inhibit-startup-visibility-stuff
5441 (org-set-startup-visibility))))
5442 ;; Try to set org-hide correctly
5443 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5445 ;; Update `customize-package-emacs-version-alist'
5446 (add-to-list 'customize-package-emacs-version-alist
5447 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5448 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5449 ("8.0" . "24.4")))
5451 (defvar org-mode-transpose-word-syntax-table
5452 (let ((st (make-syntax-table)))
5453 (mapc (lambda(c) (modify-syntax-entry
5454 (string-to-char (car c)) "w p" st))
5455 org-emphasis-alist)
5456 st))
5458 (when (fboundp 'abbrev-table-put)
5459 (abbrev-table-put org-mode-abbrev-table
5460 :parents (list text-mode-abbrev-table)))
5462 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5464 (defsubst org-fix-ellipsis-at-bol ()
5465 (save-excursion (goto-char (window-start)) (recenter 0)))
5467 (defun org-find-invisible-foreground ()
5468 (let ((candidates (remove
5469 "unspecified-bg"
5470 (nconc
5471 (list (face-background 'default)
5472 (face-background 'org-default))
5473 (mapcar
5474 (lambda (alist)
5475 (when (boundp alist)
5476 (cdr (assoc 'background-color (symbol-value alist)))))
5477 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5478 (list (face-foreground 'org-hide))))))
5479 (car (remove nil candidates))))
5481 (defun org-current-time (&optional rounding-minutes past)
5482 "Current time, possibly rounded to ROUNDING-MINUTES.
5483 When ROUNDING-MINUTES is not an integer, fall back on the car of
5484 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5485 the rounding returns a past time."
5486 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5487 (car org-time-stamp-rounding-minutes)))
5488 (time (decode-time)) res)
5489 (if (< r 1)
5490 (current-time)
5491 (setq res
5492 (apply 'encode-time
5493 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5494 (nthcdr 2 time))))
5495 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5496 (seconds-to-time (- (org-float-time res) (* r 60)))
5497 res))))
5499 (defun org-today ()
5500 "Return today date, considering `org-extend-today-until'."
5501 (time-to-days
5502 (time-subtract (current-time)
5503 (list 0 (* 3600 org-extend-today-until) 0))))
5505 ;;;; Font-Lock stuff, including the activators
5507 (defvar org-mouse-map (make-sparse-keymap))
5508 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5509 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5510 (when org-mouse-1-follows-link
5511 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5512 (when org-tab-follows-link
5513 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5514 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5516 (require 'font-lock)
5518 (defconst org-non-link-chars "]\t\n\r<>")
5519 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5520 "shell" "elisp" "doi" "message"))
5521 (defvar org-link-types-re nil
5522 "Matches a link that has a url-like prefix like \"http:\"")
5523 (defvar org-link-re-with-space nil
5524 "Matches a link with spaces, optional angular brackets around it.")
5525 (defvar org-link-re-with-space2 nil
5526 "Matches a link with spaces, optional angular brackets around it.")
5527 (defvar org-link-re-with-space3 nil
5528 "Matches a link with spaces, only for internal part in bracket links.")
5529 (defvar org-angle-link-re nil
5530 "Matches link with angular brackets, spaces are allowed.")
5531 (defvar org-plain-link-re nil
5532 "Matches plain link, without spaces.")
5533 (defvar org-bracket-link-regexp nil
5534 "Matches a link in double brackets.")
5535 (defvar org-bracket-link-analytic-regexp nil
5536 "Regular expression used to analyze links.
5537 Here is what the match groups contain after a match:
5538 1: http:
5539 2: http
5540 3: path
5541 4: [desc]
5542 5: desc")
5543 (defvar org-bracket-link-analytic-regexp++ nil
5544 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5545 (defvar org-any-link-re nil
5546 "Regular expression matching any link.")
5548 (defconst org-match-sexp-depth 3
5549 "Number of stacked braces for sub/superscript matching.")
5551 (defun org-create-multibrace-regexp (left right n)
5552 "Create a regular expression which will match a balanced sexp.
5553 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5554 as single character strings.
5555 The regexp returned will match the entire expression including the
5556 delimiters. It will also define a single group which contains the
5557 match except for the outermost delimiters. The maximum depth of
5558 stacked delimiters is N. Escaping delimiters is not possible."
5559 (let* ((nothing (concat "[^" left right "]*?"))
5560 (or "\\|")
5561 (re nothing)
5562 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5563 (while (> n 1)
5564 (setq n (1- n)
5565 re (concat re or next)
5566 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5567 (concat left "\\(" re "\\)" right)))
5569 (defvar org-match-substring-regexp
5570 (concat
5571 "\\(\\S-\\)\\([_^]\\)\\("
5572 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5573 "\\|"
5574 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5575 "\\|"
5576 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5577 "The regular expression matching a sub- or superscript.")
5579 (defvar org-match-substring-with-braces-regexp
5580 (concat
5581 "\\(\\S-\\)\\([_^]\\)\\("
5582 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5583 "\\)")
5584 "The regular expression matching a sub- or superscript, forcing braces.")
5586 (defun org-make-link-regexps ()
5587 "Update the link regular expressions.
5588 This should be called after the variable `org-link-types' has changed."
5589 (setq org-link-types-re
5590 (concat
5591 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5592 org-link-re-with-space
5593 (concat
5594 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^" org-non-link-chars "]*"
5597 "[^" org-non-link-chars " ]\\)>?")
5598 org-link-re-with-space2
5599 (concat
5600 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 "\\([^" org-non-link-chars " ]"
5602 "[^\t\n\r]*"
5603 "[^" org-non-link-chars " ]\\)>?")
5604 org-link-re-with-space3
5605 (concat
5606 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5607 "\\([^" org-non-link-chars " ]"
5608 "[^\t\n\r]*\\)")
5609 org-angle-link-re
5610 (concat
5611 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5612 "\\([^" org-non-link-chars " ]"
5613 "[^" org-non-link-chars "]*"
5614 "\\)>")
5615 org-plain-link-re
5616 (concat
5617 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5618 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5619 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5620 org-bracket-link-regexp
5621 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5622 org-bracket-link-analytic-regexp
5623 (concat
5624 "\\[\\["
5625 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5626 "\\([^]]+\\)"
5627 "\\]"
5628 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5629 "\\]")
5630 org-bracket-link-analytic-regexp++
5631 (concat
5632 "\\[\\["
5633 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5634 "\\([^]]+\\)"
5635 "\\]"
5636 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5637 "\\]")
5638 org-any-link-re
5639 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5640 org-angle-link-re "\\)\\|\\("
5641 org-plain-link-re "\\)")))
5643 (org-make-link-regexps)
5645 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5646 "Regular expression for fast time stamp matching.")
5647 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5648 "Regular expression for fast time stamp matching.")
5649 (defconst org-ts-regexp0
5650 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5651 "Regular expression matching time strings for analysis.
5652 This one does not require the space after the date, so it can be used
5653 on a string that terminates immediately after the date.")
5654 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5655 "Regular expression matching time strings for analysis.")
5656 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5657 "Regular expression matching time stamps, with groups.")
5658 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5659 "Regular expression matching time stamps (also [..]), with groups.")
5660 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5661 "Regular expression matching a time stamp range.")
5662 (defconst org-tr-regexp-both
5663 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5664 "Regular expression matching a time stamp range.")
5665 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5666 org-ts-regexp "\\)?")
5667 "Regular expression matching a time stamp or time stamp range.")
5668 (defconst org-tsr-regexp-both
5669 (concat org-ts-regexp-both "\\(--?-?"
5670 org-ts-regexp-both "\\)?")
5671 "Regular expression matching a time stamp or time stamp range.
5672 The time stamps may be either active or inactive.")
5674 (defvar org-emph-face nil)
5676 (defun org-do-emphasis-faces (limit)
5677 "Run through the buffer and add overlays to emphasized strings."
5678 (let (rtn a)
5679 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5680 (if (not (= (char-after (match-beginning 3))
5681 (char-after (match-beginning 4))))
5682 (progn
5683 (setq rtn t)
5684 (setq a (assoc (match-string 3) org-emphasis-alist))
5685 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5686 'face
5687 (nth 1 a))
5688 (and (nth 4 a)
5689 (org-remove-flyspell-overlays-in
5690 (match-beginning 0) (match-end 0)))
5691 (add-text-properties (match-beginning 2) (match-end 2)
5692 '(font-lock-multiline t org-emphasis t))
5693 (when org-hide-emphasis-markers
5694 (add-text-properties (match-end 4) (match-beginning 5)
5695 '(invisible org-link))
5696 (add-text-properties (match-beginning 3) (match-end 3)
5697 '(invisible org-link)))))
5698 (backward-char 1))
5699 rtn))
5701 (defun org-emphasize (&optional char)
5702 "Insert or change an emphasis, i.e. a font like bold or italic.
5703 If there is an active region, change that region to a new emphasis.
5704 If there is no region, just insert the marker characters and position
5705 the cursor between them.
5706 CHAR should be the marker character. If it is a space, it means to
5707 remove the emphasis of the selected region.
5708 If CHAR is not given (for example in an interactive call) it will be
5709 prompted for."
5710 (interactive)
5711 (let ((erc org-emphasis-regexp-components)
5712 (prompt "")
5713 (string "") beg end move c s)
5714 (if (org-region-active-p)
5715 (setq beg (region-beginning) end (region-end)
5716 string (buffer-substring beg end))
5717 (setq move t))
5719 (unless char
5720 (message "Emphasis marker or tag: [%s]"
5721 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5722 (setq char (read-char-exclusive)))
5723 (if (equal char ?\ )
5724 (setq s "" move nil)
5725 (unless (assoc (char-to-string char) org-emphasis-alist)
5726 (user-error "No such emphasis marker: \"%c\"" char))
5727 (setq s (char-to-string char)))
5728 (while (and (> (length string) 1)
5729 (equal (substring string 0 1) (substring string -1))
5730 (assoc (substring string 0 1) org-emphasis-alist))
5731 (setq string (substring string 1 -1)))
5732 (setq string (concat s string s))
5733 (if beg (delete-region beg end))
5734 (unless (or (bolp)
5735 (string-match (concat "[" (nth 0 erc) "\n]")
5736 (char-to-string (char-before (point)))))
5737 (insert " "))
5738 (unless (or (eobp)
5739 (string-match (concat "[" (nth 1 erc) "\n]")
5740 (char-to-string (char-after (point)))))
5741 (insert " ") (backward-char 1))
5742 (insert string)
5743 (and move (backward-char 1))))
5745 (defconst org-nonsticky-props
5746 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5748 (defsubst org-rear-nonsticky-at (pos)
5749 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5751 (defun org-activate-plain-links (limit)
5752 "Run through the buffer and add overlays to links."
5753 (let (f hl)
5754 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5755 (not (org-in-src-block-p)))
5756 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5757 (setq f (get-text-property (match-beginning 0) 'face))
5758 (setq hl (org-match-string-no-properties 0))
5759 (if (or (eq f 'org-tag)
5760 (and (listp f) (memq 'org-tag f)))
5762 (add-text-properties (match-beginning 0) (match-end 0)
5763 (list 'mouse-face 'highlight
5764 'face 'org-link
5765 'htmlize-link `(:uri ,hl)
5766 'keymap org-mouse-map))
5767 (org-rear-nonsticky-at (match-end 0)))
5768 t)))
5770 (defun org-activate-code (limit)
5771 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5772 (progn
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (remove-text-properties (match-beginning 0) (match-end 0)
5775 '(display t invisible t intangible t))
5776 t)))
5778 (defcustom org-src-fontify-natively nil
5779 "When non-nil, fontify code in code blocks."
5780 :type 'boolean
5781 :version "24.1"
5782 :group 'org-appearance
5783 :group 'org-babel)
5785 (defcustom org-allow-promoting-top-level-subtree nil
5786 "When non-nil, allow promoting a top level subtree.
5787 The leading star of the top level headline will be replaced
5788 by a #."
5789 :type 'boolean
5790 :version "24.1"
5791 :group 'org-appearance)
5793 (defun org-fontify-meta-lines-and-blocks (limit)
5794 (condition-case nil
5795 (org-fontify-meta-lines-and-blocks-1 limit)
5796 (error (message "org-mode fontification error"))))
5798 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5799 "Fontify #+ lines and blocks."
5800 (let ((case-fold-search t))
5801 (if (re-search-forward
5802 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5803 limit t)
5804 (let ((beg (match-beginning 0))
5805 (block-start (match-end 0))
5806 (block-end nil)
5807 (lang (match-string 7))
5808 (beg1 (line-beginning-position 2))
5809 (dc1 (downcase (match-string 2)))
5810 (dc3 (downcase (match-string 3)))
5811 end end1 quoting block-type ovl)
5812 (cond
5813 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5814 ;; a single line of backend-specific content
5815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5816 (remove-text-properties (match-beginning 0) (match-end 0)
5817 '(display t invisible t intangible t))
5818 (add-text-properties (match-beginning 1) (match-end 3)
5819 '(font-lock-fontified t face org-meta-line))
5820 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5821 '(font-lock-fontified t face org-block))
5822 ; for backend-specific code
5824 ((and (match-end 4) (equal dc3 "+begin"))
5825 ;; Truly a block
5826 (setq block-type (downcase (match-string 5))
5827 quoting (member block-type org-protecting-blocks))
5828 (when (re-search-forward
5829 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5830 nil t) ;; on purpose, we look further than LIMIT
5831 (setq end (min (point-max) (match-end 0))
5832 end1 (min (point-max) (1- (match-beginning 0))))
5833 (setq block-end (match-beginning 0))
5834 (when quoting
5835 (remove-text-properties beg end
5836 '(display t invisible t intangible t)))
5837 (add-text-properties
5838 beg end
5839 '(font-lock-fontified t font-lock-multiline t))
5840 (add-text-properties beg beg1 '(face org-meta-line))
5841 (add-text-properties end1 (min (point-max) (1+ end))
5842 '(face org-meta-line)) ; for end_src
5843 (cond
5844 ((and lang (not (string= lang "")) org-src-fontify-natively)
5845 (org-src-font-lock-fontify-block lang block-start block-end)
5846 ;; remove old background overlays
5847 (mapc (lambda (ov)
5848 (if (eq (overlay-get ov 'face) 'org-block-background)
5849 (delete-overlay ov)))
5850 (overlays-at (/ (+ beg1 block-end) 2)))
5851 ;; add a background overlay
5852 (setq ovl (make-overlay beg1 block-end))
5853 (overlay-put ovl 'face 'org-block-background)
5854 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5855 (quoting
5856 (add-text-properties beg1 (min (point-max) (1+ end1))
5857 '(face org-block))) ; end of source block
5858 ((not org-fontify-quote-and-verse-blocks))
5859 ((string= block-type "quote")
5860 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5861 ((string= block-type "verse")
5862 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5863 (add-text-properties beg beg1 '(face org-block-begin-line))
5864 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5865 '(face org-block-end-line))
5867 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5868 (add-text-properties
5869 beg (match-end 3)
5870 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5871 '(font-lock-fontified t invisible t)
5872 '(font-lock-fontified t face org-document-info-keyword)))
5873 (add-text-properties
5874 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5875 (if (string-equal dc1 "+title:")
5876 '(font-lock-fontified t face org-document-title)
5877 '(font-lock-fontified t face org-document-info))))
5878 ((or (equal dc1 "+results")
5879 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5880 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5881 "+call:" "+header:" "+headers:" "+name:"))
5882 (and (match-end 4) (equal dc3 "+attr")))
5883 (add-text-properties
5884 beg (match-end 0)
5885 '(font-lock-fontified t face org-meta-line))
5887 ((member dc3 '(" " ""))
5888 (add-text-properties
5889 beg (match-end 0)
5890 '(font-lock-fontified t face font-lock-comment-face)))
5891 ((not (member (char-after beg) '(?\ ?\t)))
5892 ;; just any other in-buffer setting, but not indented
5893 (add-text-properties
5894 beg (match-end 0)
5895 '(font-lock-fontified t face org-meta-line))
5897 (t nil))))))
5899 (defun org-activate-angle-links (limit)
5900 "Run through the buffer and add overlays to links."
5901 (if (and (re-search-forward org-angle-link-re limit t)
5902 (not (org-in-src-block-p)))
5903 (progn
5904 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5905 (add-text-properties (match-beginning 0) (match-end 0)
5906 (list 'mouse-face 'highlight
5907 'keymap org-mouse-map))
5908 (org-rear-nonsticky-at (match-end 0))
5909 t)))
5911 (defun org-activate-footnote-links (limit)
5912 "Run through the buffer and add overlays to footnotes."
5913 (let ((fn (org-footnote-next-reference-or-definition limit)))
5914 (when fn
5915 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5916 (org-remove-flyspell-overlays-in beg end)
5917 (add-text-properties beg end
5918 (list 'mouse-face 'highlight
5919 'keymap org-mouse-map
5920 'help-echo
5921 (if (= (point-at-bol) beg)
5922 "Footnote definition"
5923 "Footnote reference")
5924 'font-lock-fontified t
5925 'font-lock-multiline t
5926 'face 'org-footnote))))))
5928 (defun org-activate-bracket-links (limit)
5929 "Run through the buffer and add overlays to bracketed links."
5930 (if (and (re-search-forward org-bracket-link-regexp limit t)
5931 (not (org-in-src-block-p)))
5932 (let* ((hl (org-match-string-no-properties 1))
5933 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5934 (ip (org-maybe-intangible
5935 (list 'invisible 'org-link
5936 'keymap org-mouse-map 'mouse-face 'highlight
5937 'font-lock-multiline t 'help-echo help
5938 'htmlize-link `(:uri ,hl))))
5939 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5940 'font-lock-multiline t 'help-echo help
5941 'htmlize-link `(:uri ,hl))))
5942 ;; We need to remove the invisible property here. Table narrowing
5943 ;; may have made some of this invisible.
5944 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5945 (remove-text-properties (match-beginning 0) (match-end 0)
5946 '(invisible nil))
5947 (if (match-end 3)
5948 (progn
5949 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5950 (org-rear-nonsticky-at (match-beginning 3))
5951 (add-text-properties (match-beginning 3) (match-end 3) vp)
5952 (org-rear-nonsticky-at (match-end 3))
5953 (add-text-properties (match-end 3) (match-end 0) ip)
5954 (org-rear-nonsticky-at (match-end 0)))
5955 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5956 (org-rear-nonsticky-at (match-beginning 1))
5957 (add-text-properties (match-beginning 1) (match-end 1) vp)
5958 (org-rear-nonsticky-at (match-end 1))
5959 (add-text-properties (match-end 1) (match-end 0) ip)
5960 (org-rear-nonsticky-at (match-end 0)))
5961 t)))
5963 (defun org-activate-dates (limit)
5964 "Run through the buffer and add overlays to dates."
5965 (if (and (re-search-forward org-tsr-regexp-both limit t)
5966 (not (equal (char-before (match-beginning 0)) 91)))
5967 (progn
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (add-text-properties (match-beginning 0) (match-end 0)
5970 (list 'mouse-face 'highlight
5971 'keymap org-mouse-map))
5972 (org-rear-nonsticky-at (match-end 0))
5973 (when org-display-custom-times
5974 (if (match-end 3)
5975 (org-display-custom-time (match-beginning 3) (match-end 3)))
5976 (org-display-custom-time (match-beginning 1) (match-end 1)))
5977 t)))
5979 (defvar org-target-link-regexp nil
5980 "Regular expression matching radio targets in plain text.")
5981 (make-variable-buffer-local 'org-target-link-regexp)
5982 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5983 "Regular expression matching a link target.")
5984 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5985 "Regular expression matching a radio target.")
5986 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5987 "Regular expression matching any target.")
5989 (defun org-activate-target-links (limit)
5990 "Run through the buffer and add overlays to target matches."
5991 (when org-target-link-regexp
5992 (let ((case-fold-search t))
5993 (if (re-search-forward org-target-link-regexp limit t)
5994 (progn
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (add-text-properties (match-beginning 0) (match-end 0)
5997 (list 'mouse-face 'highlight
5998 'keymap org-mouse-map
5999 'help-echo "Radio target link"
6000 'org-linked-text t))
6001 (org-rear-nonsticky-at (match-end 0))
6002 t)))))
6004 (defun org-update-radio-target-regexp ()
6005 "Find all radio targets in this file and update the regular expression."
6006 (interactive)
6007 (when (memq 'radio org-activate-links)
6008 (setq org-target-link-regexp
6009 (org-make-target-link-regexp (org-all-targets 'radio)))
6010 (org-restart-font-lock)))
6012 (defun org-hide-wide-columns (limit)
6013 (let (s e)
6014 (setq s (text-property-any (point) (or limit (point-max))
6015 'org-cwidth t))
6016 (when s
6017 (setq e (next-single-property-change s 'org-cwidth))
6018 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6019 (goto-char e)
6020 t)))
6022 (defvar org-latex-and-related-regexp nil
6023 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6024 (defvar org-match-substring-regexp)
6025 (defvar org-match-substring-with-braces-regexp)
6027 (defun org-compute-latex-and-related-regexp ()
6028 "Compute regular expression for LaTeX, entities and sub/superscript.
6029 Result depends on variable `org-highlight-latex-and-related'."
6030 (org-set-local
6031 'org-latex-and-related-regexp
6032 (let* ((re-sub
6033 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6034 ((eq org-use-sub-superscripts '{})
6035 (list org-match-substring-with-braces-regexp))
6036 (org-use-sub-superscripts (list org-match-substring-regexp))))
6037 (re-latex
6038 (when (memq 'latex org-highlight-latex-and-related)
6039 (let ((matchers (plist-get org-format-latex-options :matchers)))
6040 (delq nil
6041 (mapcar (lambda (x)
6042 (and (member (car x) matchers) (nth 1 x)))
6043 org-latex-regexps)))))
6044 (re-entities
6045 (when (memq 'entities org-highlight-latex-and-related)
6046 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6047 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6049 (defun org-do-latex-and-related (limit)
6050 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6051 LIMIT bounds the search for syntax to highlight. Stop at first
6052 highlighted object, if any. Return t if some highlighting was
6053 done, nil otherwise."
6054 (when (org-string-nw-p org-latex-and-related-regexp)
6055 (catch 'found
6056 (while (re-search-forward org-latex-and-related-regexp limit t)
6057 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6058 'face))
6059 '(org-code org-verbatim underline))
6060 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6061 '(?_ ?^))
6063 0)))
6064 (font-lock-prepend-text-property
6065 (+ offset (match-beginning 0)) (match-end 0)
6066 'face 'org-latex-and-related)
6067 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6068 '(font-lock-multiline t)))
6069 (throw 'found t)))
6070 nil)))
6072 (defun org-restart-font-lock ()
6073 "Restart `font-lock-mode', to force refontification."
6074 (when (and (boundp 'font-lock-mode) font-lock-mode)
6075 (font-lock-mode -1)
6076 (font-lock-mode 1)))
6078 (defun org-all-targets (&optional radio)
6079 "Return a list of all targets in this file.
6080 When optional argument RADIO is non-nil, only find radio
6081 targets."
6082 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6083 (save-excursion
6084 (goto-char (point-min))
6085 (while (re-search-forward re nil t)
6086 ;; Make sure point is really within the object.
6087 (backward-char)
6088 (let ((obj (org-element-context)))
6089 (when (memq (org-element-type obj) '(radio-target target))
6090 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6091 rtn)))
6093 (defun org-make-target-link-regexp (targets)
6094 "Make regular expression matching all strings in TARGETS.
6095 The regular expression finds the targets also if there is a line break
6096 between words."
6097 (and targets
6098 (concat
6099 "\\<\\("
6100 (mapconcat
6101 (lambda (x)
6102 (setq x (regexp-quote x))
6103 (while (string-match " +" x)
6104 (setq x (replace-match "\\s-+" t t x)))
6106 targets
6107 "\\|")
6108 "\\)\\>")))
6110 (defun org-activate-tags (limit)
6111 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6112 (progn
6113 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6114 (add-text-properties (match-beginning 1) (match-end 1)
6115 (list 'mouse-face 'highlight
6116 'keymap org-mouse-map))
6117 (org-rear-nonsticky-at (match-end 1))
6118 t)))
6120 (defun org-outline-level ()
6121 "Compute the outline level of the heading at point.
6122 If this is called at a normal headline, the level is the number of stars.
6123 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6124 (save-excursion
6125 (if (not (condition-case nil
6126 (org-back-to-heading t)
6127 (error nil)))
6129 (looking-at org-outline-regexp)
6130 (1- (- (match-end 0) (match-beginning 0))))))
6132 (defvar org-font-lock-keywords nil)
6134 (defsubst org-re-property (property &optional literal)
6135 "Return a regexp matching a PROPERTY line.
6136 Match group 3 will be set to the value if it exists."
6137 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6138 (if literal property (regexp-quote property))
6139 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6141 (defconst org-property-re
6142 (org-re-property ".*?" 'literal)
6143 "Regular expression matching a property line.
6144 There are four matching groups:
6145 1: :PROPKEY: including the leading and trailing colon,
6146 2: PROPKEY without the leading and trailing colon,
6147 3: PROPVAL without leading or trailing spaces,
6148 4: the indentation of the current line,
6149 5: trailing whitespace.")
6151 (defvar org-font-lock-hook nil
6152 "Functions to be called for special font lock stuff.")
6154 (defvar org-font-lock-set-keywords-hook nil
6155 "Functions that can manipulate `org-font-lock-extra-keywords'.
6156 This is called after `org-font-lock-extra-keywords' is defined, but before
6157 it is installed to be used by font lock. This can be useful if something
6158 needs to be inserted at a specific position in the font-lock sequence.")
6160 (defun org-font-lock-hook (limit)
6161 "Run `org-font-lock-hook' within LIMIT."
6162 (run-hook-with-args 'org-font-lock-hook limit))
6164 (defun org-set-font-lock-defaults ()
6165 "Set font lock defaults for the current buffer."
6166 (let* ((em org-fontify-emphasized-text)
6167 (lk org-activate-links)
6168 (org-font-lock-extra-keywords
6169 (list
6170 ;; Call the hook
6171 '(org-font-lock-hook)
6172 ;; Headlines
6173 `(,(if org-fontify-whole-heading-line
6174 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6175 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6176 (1 (org-get-level-face 1))
6177 (2 (org-get-level-face 2))
6178 (3 (org-get-level-face 3)))
6179 ;; Table lines
6180 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6181 (1 'org-table t))
6182 ;; Table internals
6183 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6184 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6185 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6186 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6187 ;; Drawers
6188 (list org-drawer-regexp '(0 'org-special-keyword t))
6189 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6190 ;; Properties
6191 (list org-property-re
6192 '(1 'org-special-keyword t)
6193 '(3 'org-property-value t))
6194 ;; Links
6195 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6196 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6197 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6198 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6199 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6200 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6201 (if (memq 'footnote lk) '(org-activate-footnote-links))
6202 ;; Targets.
6203 (list org-any-target-regexp '(0 'org-target t))
6204 ;; Diary sexps.
6205 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6206 ;; Macro
6207 '("{{{.+}}}" (0 'org-macro t))
6208 '(org-hide-wide-columns (0 nil append))
6209 ;; TODO keyword
6210 (list (format org-heading-keyword-regexp-format
6211 org-todo-regexp)
6212 '(2 (org-get-todo-face 2) t))
6213 ;; DONE
6214 (if org-fontify-done-headline
6215 (list (format org-heading-keyword-regexp-format
6216 (concat
6217 "\\(?:"
6218 (mapconcat 'regexp-quote org-done-keywords "\\|")
6219 "\\)"))
6220 '(2 'org-headline-done t))
6221 nil)
6222 ;; Priorities
6223 '(org-font-lock-add-priority-faces)
6224 ;; Tags
6225 '(org-font-lock-add-tag-faces)
6226 ;; Tags groups
6227 (if (and org-group-tags org-tag-groups-alist)
6228 (list (concat org-outline-regexp-bol ".+\\(:"
6229 (regexp-opt (mapcar 'car org-tag-groups-alist))
6230 ":\\).*$")
6231 '(1 'org-tag-group prepend)))
6232 ;; Special keywords
6233 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6234 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6235 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6236 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6237 ;; Emphasis
6238 (if em
6239 (if (featurep 'xemacs)
6240 '(org-do-emphasis-faces (0 nil append))
6241 '(org-do-emphasis-faces)))
6242 ;; Checkboxes
6243 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6244 1 'org-checkbox prepend)
6245 (if (cdr (assq 'checkbox org-list-automatic-rules))
6246 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6247 (0 (org-get-checkbox-statistics-face) t)))
6248 ;; Description list items
6249 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6250 1 'org-list-dt prepend)
6251 ;; ARCHIVEd headings
6252 (list (concat
6253 org-outline-regexp-bol
6254 "\\(.*:" org-archive-tag ":.*\\)")
6255 '(1 'org-archived prepend))
6256 ;; Specials
6257 '(org-do-latex-and-related)
6258 '(org-fontify-entities)
6259 '(org-raise-scripts)
6260 ;; Code
6261 '(org-activate-code (1 'org-code t))
6262 ;; COMMENT
6263 (list (format org-heading-keyword-regexp-format
6264 (concat "\\("
6265 org-comment-string "\\|" org-quote-string
6266 "\\)"))
6267 '(2 'org-special-keyword t))
6268 ;; Blocks and meta lines
6269 '(org-fontify-meta-lines-and-blocks))))
6270 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6271 (run-hooks 'org-font-lock-set-keywords-hook)
6272 ;; Now set the full font-lock-keywords
6273 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6274 (org-set-local 'font-lock-defaults
6275 '(org-font-lock-keywords t nil nil backward-paragraph))
6276 (kill-local-variable 'font-lock-keywords) nil))
6278 (defun org-toggle-pretty-entities ()
6279 "Toggle the composition display of entities as UTF8 characters."
6280 (interactive)
6281 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6282 (org-restart-font-lock)
6283 (if org-pretty-entities
6284 (message "Entities are now displayed as UTF8 characters")
6285 (save-restriction
6286 (widen)
6287 (org-decompose-region (point-min) (point-max))
6288 (message "Entities are now displayed as plain text"))))
6290 (defvar org-custom-properties-overlays nil
6291 "List of overlays used for custom properties.")
6292 (make-variable-buffer-local 'org-custom-properties-overlays)
6294 (defun org-toggle-custom-properties-visibility ()
6295 "Display or hide properties in `org-custom-properties'."
6296 (interactive)
6297 (if org-custom-properties-overlays
6298 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6299 (setq org-custom-properties-overlays nil))
6300 (unless (not org-custom-properties)
6301 (save-excursion
6302 (save-restriction
6303 (widen)
6304 (goto-char (point-min))
6305 (while (re-search-forward org-property-re nil t)
6306 (mapc (lambda(p)
6307 (when (equal p (substring (match-string 1) 1 -1))
6308 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6309 (overlay-put o 'invisible t)
6310 (overlay-put o 'org-custom-property t)
6311 (push o org-custom-properties-overlays))))
6312 org-custom-properties)))))))
6314 (defun org-fontify-entities (limit)
6315 "Find an entity to fontify."
6316 (let (ee)
6317 (when org-pretty-entities
6318 (catch 'match
6319 (while (re-search-forward
6320 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6321 limit t)
6322 (if (and (not (org-in-indented-comment-line))
6323 (setq ee (org-entity-get (match-string 1)))
6324 (= (length (nth 6 ee)) 1))
6325 (let*
6326 ((end (if (equal (match-string 2) "{}")
6327 (match-end 2)
6328 (match-end 1))))
6329 (add-text-properties
6330 (match-beginning 0) end
6331 (list 'font-lock-fontified t))
6332 (compose-region (match-beginning 0) end
6333 (nth 6 ee) nil)
6334 (backward-char 1)
6335 (throw 'match t))))
6336 nil))))
6338 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6339 "Fontify string S like in Org-mode."
6340 (with-temp-buffer
6341 (insert s)
6342 (let ((org-odd-levels-only odd-levels))
6343 (org-mode)
6344 (font-lock-fontify-buffer)
6345 (buffer-string))))
6347 (defvar org-m nil)
6348 (defvar org-l nil)
6349 (defvar org-f nil)
6350 (defun org-get-level-face (n)
6351 "Get the right face for match N in font-lock matching of headlines."
6352 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6353 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6354 (if org-cycle-level-faces
6355 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6356 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6357 (cond
6358 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6359 ((eq n 2) org-f)
6360 (t (if org-level-color-stars-only nil org-f))))
6363 (defun org-get-todo-face (kwd)
6364 "Get the right face for a TODO keyword KWD.
6365 If KWD is a number, get the corresponding match group."
6366 (if (numberp kwd) (setq kwd (match-string kwd)))
6367 (or (org-face-from-face-or-color
6368 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6369 (and (member kwd org-done-keywords) 'org-done)
6370 'org-todo))
6372 (defun org-face-from-face-or-color (context inherit face-or-color)
6373 "Create a face list that inherits INHERIT, but sets the foreground color.
6374 When FACE-OR-COLOR is not a string, just return it."
6375 (if (stringp face-or-color)
6376 (list :inherit inherit
6377 (cdr (assoc context org-faces-easy-properties))
6378 face-or-color)
6379 face-or-color))
6381 (defun org-font-lock-add-tag-faces (limit)
6382 "Add the special tag faces."
6383 (when (and org-tag-faces org-tags-special-faces-re)
6384 (while (re-search-forward org-tags-special-faces-re limit t)
6385 (add-text-properties (match-beginning 1) (match-end 1)
6386 (list 'face (org-get-tag-face 1)
6387 'font-lock-fontified t))
6388 (backward-char 1))))
6390 (defun org-font-lock-add-priority-faces (limit)
6391 "Add the special priority faces."
6392 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6393 (when (save-match-data (org-at-heading-p))
6394 (add-text-properties
6395 (match-beginning 0) (match-end 0)
6396 (list 'face (or (org-face-from-face-or-color
6397 'priority 'org-priority
6398 (cdr (assoc (char-after (match-beginning 1))
6399 org-priority-faces)))
6400 'org-priority)
6401 'font-lock-fontified t)))))
6403 (defun org-get-tag-face (kwd)
6404 "Get the right face for a TODO keyword KWD.
6405 If KWD is a number, get the corresponding match group."
6406 (if (numberp kwd) (setq kwd (match-string kwd)))
6407 (or (org-face-from-face-or-color
6408 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6409 'org-tag))
6411 (defun org-unfontify-region (beg end &optional maybe_loudly)
6412 "Remove fontification and activation overlays from links."
6413 (font-lock-default-unfontify-region beg end)
6414 (let* ((buffer-undo-list t)
6415 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6416 (inhibit-modification-hooks t)
6417 deactivate-mark buffer-file-name buffer-file-truename)
6418 (org-decompose-region beg end)
6419 (remove-text-properties beg end
6420 '(mouse-face t keymap t org-linked-text t
6421 invisible t intangible t
6422 org-no-flyspell t org-emphasis t))
6423 (org-remove-font-lock-display-properties beg end)))
6425 (defconst org-script-display '(((raise -0.3) (height 0.7))
6426 ((raise 0.3) (height 0.7))
6427 ((raise -0.5))
6428 ((raise 0.5)))
6429 "Display properties for showing superscripts and subscripts.")
6431 (defun org-remove-font-lock-display-properties (beg end)
6432 "Remove specific display properties that have been added by font lock.
6433 The will remove the raise properties that are used to show superscripts
6434 and subscripts."
6435 (let (next prop)
6436 (while (< beg end)
6437 (setq next (next-single-property-change beg 'display nil end)
6438 prop (get-text-property beg 'display))
6439 (if (member prop org-script-display)
6440 (put-text-property beg next 'display nil))
6441 (setq beg next))))
6443 (defun org-raise-scripts (limit)
6444 "Add raise properties to sub/superscripts."
6445 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6446 (if (re-search-forward
6447 (if (eq org-use-sub-superscripts t)
6448 org-match-substring-regexp
6449 org-match-substring-with-braces-regexp)
6450 limit t)
6451 (let* ((pos (point)) table-p comment-p
6452 (mpos (match-beginning 3))
6453 (emph-p (get-text-property mpos 'org-emphasis))
6454 (link-p (get-text-property mpos 'mouse-face))
6455 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6456 (goto-char (point-at-bol))
6457 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6458 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6459 (goto-char pos)
6460 ;; Handle a_b^c
6461 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6462 (if (or comment-p emph-p link-p keyw-p)
6464 (put-text-property (match-beginning 3) (match-end 0)
6465 'display
6466 (if (equal (char-after (match-beginning 2)) ?^)
6467 (nth (if table-p 3 1) org-script-display)
6468 (nth (if table-p 2 0) org-script-display)))
6469 (add-text-properties (match-beginning 2) (match-end 2)
6470 (list 'invisible t
6471 'org-dwidth t 'org-dwidth-n 1))
6472 (if (and (eq (char-after (match-beginning 3)) ?{)
6473 (eq (char-before (match-end 3)) ?}))
6474 (progn
6475 (add-text-properties
6476 (match-beginning 3) (1+ (match-beginning 3))
6477 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6478 (add-text-properties
6479 (1- (match-end 3)) (match-end 3)
6480 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6481 t)))))
6483 ;;;; Visibility cycling, including org-goto and indirect buffer
6485 ;;; Cycling
6487 (defvar org-cycle-global-status nil)
6488 (make-variable-buffer-local 'org-cycle-global-status)
6489 (put 'org-cycle-global-status 'org-state t)
6490 (defvar org-cycle-subtree-status nil)
6491 (make-variable-buffer-local 'org-cycle-subtree-status)
6492 (put 'org-cycle-subtree-status 'org-state t)
6494 (defvar org-inlinetask-min-level)
6496 (defun org-unlogged-message (&rest args)
6497 "Display a message, but avoid logging it in the *Messages* buffer."
6498 (let ((message-log-max nil))
6499 (apply 'message args)))
6501 ;;;###autoload
6502 (defun org-cycle (&optional arg)
6503 "TAB-action and visibility cycling for Org-mode.
6505 This is the command invoked in Org-mode by the TAB key. Its main purpose
6506 is outline visibility cycling, but it also invokes other actions
6507 in special contexts.
6509 - When this function is called with a prefix argument, rotate the entire
6510 buffer through 3 states (global cycling)
6511 1. OVERVIEW: Show only top-level headlines.
6512 2. CONTENTS: Show all headlines of all levels, but no body text.
6513 3. SHOW ALL: Show everything.
6514 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6515 determined by the variable `org-startup-folded', and by any VISIBILITY
6516 properties in the buffer.
6517 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6518 including any drawers.
6520 - When inside a table, re-align the table and move to the next field.
6522 - When point is at the beginning of a headline, rotate the subtree started
6523 by this line through 3 different states (local cycling)
6524 1. FOLDED: Only the main headline is shown.
6525 2. CHILDREN: The main headline and the direct children are shown.
6526 From this state, you can move to one of the children
6527 and zoom in further.
6528 3. SUBTREE: Show the entire subtree, including body text.
6529 If there is no subtree, switch directly from CHILDREN to FOLDED.
6531 - When point is at the beginning of an empty headline and the variable
6532 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6533 of the headline by demoting and promoting it to likely levels. This
6534 speeds up creation document structure by pressing TAB once or several
6535 times right after creating a new headline.
6537 - When there is a numeric prefix, go up to a heading with level ARG, do
6538 a `show-subtree' and return to the previous cursor position. If ARG
6539 is negative, go up that many levels.
6541 - When point is not at the beginning of a headline, execute the global
6542 binding for TAB, which is re-indenting the line. See the option
6543 `org-cycle-emulate-tab' for details.
6545 - Special case: if point is at the beginning of the buffer and there is
6546 no headline in line 1, this function will act as if called with prefix arg
6547 (C-u TAB, same as S-TAB) also when called without prefix arg.
6548 But only if also the variable `org-cycle-global-at-bob' is t."
6549 (interactive "P")
6550 (org-load-modules-maybe)
6551 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6552 (and org-cycle-level-after-item/entry-creation
6553 (or (org-cycle-level)
6554 (org-cycle-item-indentation))))
6555 (let* ((limit-level
6556 (or org-cycle-max-level
6557 (and (boundp 'org-inlinetask-min-level)
6558 org-inlinetask-min-level
6559 (1- org-inlinetask-min-level))))
6560 (nstars (and limit-level
6561 (if org-odd-levels-only
6562 (and limit-level (1- (* limit-level 2)))
6563 limit-level)))
6564 (org-outline-regexp
6565 (if (not (derived-mode-p 'org-mode))
6566 outline-regexp
6567 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6568 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6569 (not (looking-at org-outline-regexp))))
6570 (org-cycle-hook
6571 (if bob-special
6572 (delq 'org-optimize-window-after-visibility-change
6573 (copy-sequence org-cycle-hook))
6574 org-cycle-hook))
6575 (pos (point)))
6577 (if (or bob-special (equal arg '(4)))
6578 ;; special case: use global cycling
6579 (setq arg t))
6581 (cond
6583 ((equal arg '(16))
6584 (setq last-command 'dummy)
6585 (org-set-startup-visibility)
6586 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6588 ((equal arg '(64))
6589 (show-all)
6590 (org-unlogged-message "Entire buffer visible, including drawers"))
6592 ;; Table: enter it or move to the next field.
6593 ((org-at-table-p 'any)
6594 (if (org-at-table.el-p)
6595 (message "Use C-c ' to edit table.el tables")
6596 (if arg (org-table-edit-field t)
6597 (org-table-justify-field-maybe)
6598 (call-interactively 'org-table-next-field))))
6600 ((run-hook-with-args-until-success
6601 'org-tab-after-check-for-table-hook))
6603 ;; Global cycling: delegate to `org-cycle-internal-global'.
6604 ((eq arg t) (org-cycle-internal-global))
6606 ;; Drawers: delegate to `org-flag-drawer'.
6607 ((save-excursion
6608 (beginning-of-line 1)
6609 (looking-at org-drawer-regexp))
6610 (org-flag-drawer ; toggle block visibility
6611 (not (get-char-property (match-end 0) 'invisible))))
6613 ;; Show-subtree, ARG levels up from here.
6614 ((integerp arg)
6615 (save-excursion
6616 (org-back-to-heading)
6617 (outline-up-heading (if (< arg 0) (- arg)
6618 (- (funcall outline-level) arg)))
6619 (org-show-subtree)))
6621 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6622 ((and (featurep 'org-inlinetask)
6623 (org-inlinetask-at-task-p)
6624 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6625 (org-inlinetask-toggle-visibility))
6627 ((org-try-cdlatex-tab))
6629 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6630 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6631 (save-excursion (beginning-of-line 1)
6632 (looking-at org-outline-regexp)))
6633 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6634 (org-cycle-internal-local))
6636 ;; From there: TAB emulation and template completion.
6637 (buffer-read-only (org-back-to-heading))
6639 ((run-hook-with-args-until-success
6640 'org-tab-after-check-for-cycling-hook))
6642 ((org-try-structure-completion))
6644 ((run-hook-with-args-until-success
6645 'org-tab-before-tab-emulation-hook))
6647 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6648 (or (not (bolp))
6649 (not (looking-at org-outline-regexp))))
6650 (call-interactively (global-key-binding "\t")))
6652 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6653 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6654 (or (and (eq org-cycle-emulate-tab 'white)
6655 (= (match-end 0) (point-at-eol)))
6656 (and (eq org-cycle-emulate-tab 'whitestart)
6657 (>= (match-end 0) pos))))
6659 (eq org-cycle-emulate-tab t))
6660 (call-interactively (global-key-binding "\t")))
6662 (t (save-excursion
6663 (org-back-to-heading)
6664 (org-cycle)))))))
6666 (defun org-cycle-internal-global ()
6667 "Do the global cycling action."
6668 ;; Hack to avoid display of messages for .org attachments in Gnus
6669 (let ((ga (string-match "\\*fontification" (buffer-name))))
6670 (cond
6671 ((and (eq last-command this-command)
6672 (eq org-cycle-global-status 'overview))
6673 ;; We just created the overview - now do table of contents
6674 ;; This can be slow in very large buffers, so indicate action
6675 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6676 (unless ga (org-unlogged-message "CONTENTS..."))
6677 (org-content)
6678 (unless ga (org-unlogged-message "CONTENTS...done"))
6679 (setq org-cycle-global-status 'contents)
6680 (run-hook-with-args 'org-cycle-hook 'contents))
6682 ((and (eq last-command this-command)
6683 (eq org-cycle-global-status 'contents))
6684 ;; We just showed the table of contents - now show everything
6685 (run-hook-with-args 'org-pre-cycle-hook 'all)
6686 (show-all)
6687 (unless ga (org-unlogged-message "SHOW ALL"))
6688 (setq org-cycle-global-status 'all)
6689 (run-hook-with-args 'org-cycle-hook 'all))
6692 ;; Default action: go to overview
6693 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6694 (org-overview)
6695 (unless ga (org-unlogged-message "OVERVIEW"))
6696 (setq org-cycle-global-status 'overview)
6697 (run-hook-with-args 'org-cycle-hook 'overview)))))
6699 (defun org-cycle-internal-local ()
6700 "Do the local cycling action."
6701 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6702 ;; First, determine end of headline (EOH), end of subtree or item
6703 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6704 (save-excursion
6705 (if (org-at-item-p)
6706 (progn
6707 (beginning-of-line)
6708 (setq struct (org-list-struct))
6709 (setq eoh (point-at-eol))
6710 (setq eos (org-list-get-item-end-before-blank (point) struct))
6711 (setq has-children (org-list-has-child-p (point) struct)))
6712 (org-back-to-heading)
6713 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6714 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6715 (setq has-children
6716 (or (save-excursion
6717 (let ((level (funcall outline-level)))
6718 (outline-next-heading)
6719 (and (org-at-heading-p t)
6720 (> (funcall outline-level) level))))
6721 (save-excursion
6722 (org-list-search-forward (org-item-beginning-re) eos t)))))
6723 ;; Determine end invisible part of buffer (EOL)
6724 (beginning-of-line 2)
6725 ;; XEmacs doesn't have `next-single-char-property-change'
6726 (if (featurep 'xemacs)
6727 (while (and (not (eobp)) ;; this is like `next-line'
6728 (get-char-property (1- (point)) 'invisible))
6729 (beginning-of-line 2))
6730 (while (and (not (eobp)) ;; this is like `next-line'
6731 (get-char-property (1- (point)) 'invisible))
6732 (goto-char (next-single-char-property-change (point) 'invisible))
6733 (and (eolp) (beginning-of-line 2))))
6734 (setq eol (point)))
6735 ;; Find out what to do next and set `this-command'
6736 (cond
6737 ((= eos eoh)
6738 ;; Nothing is hidden behind this heading
6739 (unless (org-before-first-heading-p)
6740 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6741 (org-unlogged-message "EMPTY ENTRY")
6742 (setq org-cycle-subtree-status nil)
6743 (save-excursion
6744 (goto-char eos)
6745 (outline-next-heading)
6746 (if (outline-invisible-p) (org-flag-heading nil))))
6747 ((and (or (>= eol eos)
6748 (not (string-match "\\S-" (buffer-substring eol eos))))
6749 (or has-children
6750 (not (setq children-skipped
6751 org-cycle-skip-children-state-if-no-children))))
6752 ;; Entire subtree is hidden in one line: children view
6753 (unless (org-before-first-heading-p)
6754 (run-hook-with-args 'org-pre-cycle-hook 'children))
6755 (if (org-at-item-p)
6756 (org-list-set-item-visibility (point-at-bol) struct 'children)
6757 (org-show-entry)
6758 (org-with-limited-levels (show-children))
6759 ;; FIXME: This slows down the func way too much.
6760 ;; How keep drawers hidden in subtree anyway?
6761 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6762 ;; (org-cycle-hide-drawers 'subtree))
6764 ;; Fold every list in subtree to top-level items.
6765 (when (eq org-cycle-include-plain-lists 'integrate)
6766 (save-excursion
6767 (org-back-to-heading)
6768 (while (org-list-search-forward (org-item-beginning-re) eos t)
6769 (beginning-of-line 1)
6770 (let* ((struct (org-list-struct))
6771 (prevs (org-list-prevs-alist struct))
6772 (end (org-list-get-bottom-point struct)))
6773 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6774 (org-list-get-all-items (point) struct prevs))
6775 (goto-char (if (< end eos) end eos)))))))
6776 (org-unlogged-message "CHILDREN")
6777 (save-excursion
6778 (goto-char eos)
6779 (outline-next-heading)
6780 (if (outline-invisible-p) (org-flag-heading nil)))
6781 (setq org-cycle-subtree-status 'children)
6782 (unless (org-before-first-heading-p)
6783 (run-hook-with-args 'org-cycle-hook 'children)))
6784 ((or children-skipped
6785 (and (eq last-command this-command)
6786 (eq org-cycle-subtree-status 'children)))
6787 ;; We just showed the children, or no children are there,
6788 ;; now show everything.
6789 (unless (org-before-first-heading-p)
6790 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6791 (outline-flag-region eoh eos nil)
6792 (org-unlogged-message
6793 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6794 (setq org-cycle-subtree-status 'subtree)
6795 (unless (org-before-first-heading-p)
6796 (run-hook-with-args 'org-cycle-hook 'subtree)))
6798 ;; Default action: hide the subtree.
6799 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6800 (outline-flag-region eoh eos t)
6801 (org-unlogged-message "FOLDED")
6802 (setq org-cycle-subtree-status 'folded)
6803 (unless (org-before-first-heading-p)
6804 (run-hook-with-args 'org-cycle-hook 'folded))))))
6806 ;;;###autoload
6807 (defun org-global-cycle (&optional arg)
6808 "Cycle the global visibility. For details see `org-cycle'.
6809 With \\[universal-argument] prefix arg, switch to startup visibility.
6810 With a numeric prefix, show all headlines up to that level."
6811 (interactive "P")
6812 (let ((org-cycle-include-plain-lists
6813 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6814 (cond
6815 ((integerp arg)
6816 (show-all)
6817 (hide-sublevels arg)
6818 (setq org-cycle-global-status 'contents))
6819 ((equal arg '(4))
6820 (org-set-startup-visibility)
6821 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6823 (org-cycle '(4))))))
6825 (defun org-set-startup-visibility ()
6826 "Set the visibility required by startup options and properties."
6827 (cond
6828 ((eq org-startup-folded t)
6829 (org-cycle '(4)))
6830 ((eq org-startup-folded 'content)
6831 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6832 (org-cycle '(4)) (org-cycle '(4)))))
6833 (unless (eq org-startup-folded 'showeverything)
6834 (if org-hide-block-startup (org-hide-block-all))
6835 (org-set-visibility-according-to-property 'no-cleanup)
6836 (org-cycle-hide-archived-subtrees 'all)
6837 (org-cycle-hide-drawers 'all)
6838 (org-cycle-show-empty-lines t)))
6840 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6841 "Switch subtree visibilities according to :VISIBILITY: property."
6842 (interactive)
6843 (let (org-show-entry-below state)
6844 (save-excursion
6845 (goto-char (point-min))
6846 (while (re-search-forward
6847 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6848 nil t)
6849 (setq state (match-string 1))
6850 (save-excursion
6851 (org-back-to-heading t)
6852 (hide-subtree)
6853 (org-reveal)
6854 (cond
6855 ((equal state '("fold" "folded"))
6856 (hide-subtree))
6857 ((equal state "children")
6858 (org-show-hidden-entry)
6859 (show-children))
6860 ((equal state "content")
6861 (save-excursion
6862 (save-restriction
6863 (org-narrow-to-subtree)
6864 (org-content))))
6865 ((member state '("all" "showall"))
6866 (show-subtree)))))
6867 (unless no-cleanup
6868 (org-cycle-hide-archived-subtrees 'all)
6869 (org-cycle-hide-drawers 'all)
6870 (org-cycle-show-empty-lines 'all)))))
6872 ;; This function uses outline-regexp instead of the more fundamental
6873 ;; org-outline-regexp so that org-cycle-global works outside of Org
6874 ;; buffers, where outline-regexp is needed.
6875 (defun org-overview ()
6876 "Switch to overview mode, showing only top-level headlines.
6877 Really, this shows all headlines with level equal or greater than the level
6878 of the first headline in the buffer. This is important, because if the
6879 first headline is not level one, then (hide-sublevels 1) gives confusing
6880 results."
6881 (interactive)
6882 (let ((pos (point))
6883 (level (save-excursion
6884 (goto-char (point-min))
6885 (if (re-search-forward (concat "^" outline-regexp) nil t)
6886 (progn
6887 (goto-char (match-beginning 0))
6888 (funcall outline-level))))))
6889 (and level (hide-sublevels level))
6890 (recenter '(4))
6891 (goto-char pos)))
6893 (defun org-content (&optional arg)
6894 "Show all headlines in the buffer, like a table of contents.
6895 With numerical argument N, show content up to level N."
6896 (interactive "P")
6897 (save-excursion
6898 ;; Visit all headings and show their offspring
6899 (and (integerp arg) (org-overview))
6900 (goto-char (point-max))
6901 (catch 'exit
6902 (while (and (progn (condition-case nil
6903 (outline-previous-visible-heading 1)
6904 (error (goto-char (point-min))))
6906 (looking-at org-outline-regexp))
6907 (if (integerp arg)
6908 (show-children (1- arg))
6909 (show-branches))
6910 (if (bobp) (throw 'exit nil))))))
6913 (defun org-optimize-window-after-visibility-change (state)
6914 "Adjust the window after a change in outline visibility.
6915 This function is the default value of the hook `org-cycle-hook'."
6916 (when (get-buffer-window (current-buffer))
6917 (cond
6918 ((eq state 'content) nil)
6919 ((eq state 'all) nil)
6920 ((eq state 'folded) nil)
6921 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6922 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6924 (defun org-remove-empty-overlays-at (pos)
6925 "Remove outline overlays that do not contain non-white stuff."
6926 (mapc
6927 (lambda (o)
6928 (and (eq 'outline (overlay-get o 'invisible))
6929 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6930 (overlay-end o))))
6931 (delete-overlay o)))
6932 (overlays-at pos)))
6934 (defun org-clean-visibility-after-subtree-move ()
6935 "Fix visibility issues after moving a subtree."
6936 ;; First, find a reasonable region to look at:
6937 ;; Start two siblings above, end three below
6938 (let* ((beg (save-excursion
6939 (and (org-get-last-sibling)
6940 (org-get-last-sibling))
6941 (point)))
6942 (end (save-excursion
6943 (and (org-get-next-sibling)
6944 (org-get-next-sibling)
6945 (org-get-next-sibling))
6946 (if (org-at-heading-p)
6947 (point-at-eol)
6948 (point))))
6949 (level (looking-at "\\*+"))
6950 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6951 (save-excursion
6952 (save-restriction
6953 (narrow-to-region beg end)
6954 (when re
6955 ;; Properly fold already folded siblings
6956 (goto-char (point-min))
6957 (while (re-search-forward re nil t)
6958 (if (and (not (outline-invisible-p))
6959 (save-excursion
6960 (goto-char (point-at-eol)) (outline-invisible-p)))
6961 (hide-entry))))
6962 (org-cycle-show-empty-lines 'overview)
6963 (org-cycle-hide-drawers 'overview)))))
6965 (defun org-cycle-show-empty-lines (state)
6966 "Show empty lines above all visible headlines.
6967 The region to be covered depends on STATE when called through
6968 `org-cycle-hook'. Lisp program can use t for STATE to get the
6969 entire buffer covered. Note that an empty line is only shown if there
6970 are at least `org-cycle-separator-lines' empty lines before the headline."
6971 (when (not (= org-cycle-separator-lines 0))
6972 (save-excursion
6973 (let* ((n (abs org-cycle-separator-lines))
6974 (re (cond
6975 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6976 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6977 (t (let ((ns (number-to-string (- n 2))))
6978 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6979 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6980 beg end b e)
6981 (cond
6982 ((memq state '(overview contents t))
6983 (setq beg (point-min) end (point-max)))
6984 ((memq state '(children folded))
6985 (setq beg (point) end (progn (org-end-of-subtree t t)
6986 (beginning-of-line 2)
6987 (point)))))
6988 (when beg
6989 (goto-char beg)
6990 (while (re-search-forward re end t)
6991 (unless (get-char-property (match-end 1) 'invisible)
6992 (setq e (match-end 1))
6993 (if (< org-cycle-separator-lines 0)
6994 (setq b (save-excursion
6995 (goto-char (match-beginning 0))
6996 (org-back-over-empty-lines)
6997 (if (save-excursion
6998 (goto-char (max (point-min) (1- (point))))
6999 (org-at-heading-p))
7000 (1- (point))
7001 (point))))
7002 (setq b (match-beginning 1)))
7003 (outline-flag-region b e nil)))))))
7004 ;; Never hide empty lines at the end of the file.
7005 (save-excursion
7006 (goto-char (point-max))
7007 (outline-previous-heading)
7008 (outline-end-of-heading)
7009 (if (and (looking-at "[ \t\n]+")
7010 (= (match-end 0) (point-max)))
7011 (outline-flag-region (point) (match-end 0) nil))))
7013 (defun org-show-empty-lines-in-parent ()
7014 "Move to the parent and re-show empty lines before visible headlines."
7015 (save-excursion
7016 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7017 (org-cycle-show-empty-lines context))))
7019 (defun org-files-list ()
7020 "Return `org-agenda-files' list, plus all open org-mode files.
7021 This is useful for operations that need to scan all of a user's
7022 open and agenda-wise Org files."
7023 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7024 (dolist (buf (buffer-list))
7025 (with-current-buffer buf
7026 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7027 (let ((file (expand-file-name (buffer-file-name))))
7028 (unless (member file files)
7029 (push file files))))))
7030 files))
7032 (defsubst org-entry-beginning-position ()
7033 "Return the beginning position of the current entry."
7034 (save-excursion (outline-back-to-heading t) (point)))
7036 (defsubst org-entry-end-position ()
7037 "Return the end position of the current entry."
7038 (save-excursion (outline-next-heading) (point)))
7040 (defun org-cycle-hide-drawers (state &optional exceptions)
7041 "Re-hide all drawers after a visibility state change.
7042 When non-nil, optional argument EXCEPTIONS is a list of strings
7043 specifying which drawers should not be hidden."
7044 (when (and (derived-mode-p 'org-mode)
7045 (not (memq state '(overview folded contents))))
7046 (save-excursion
7047 (let* ((globalp (memq state '(contents all)))
7048 (beg (if globalp (point-min) (point)))
7049 (end (if globalp (point-max)
7050 (if (eq state 'children)
7051 (save-excursion (outline-next-heading) (point))
7052 (org-end-of-subtree t)))))
7053 (goto-char beg)
7054 (while (re-search-forward org-drawer-regexp end t)
7055 (unless (member-ignore-case (match-string 1) exceptions)
7056 (org-flag-drawer t)))))))
7058 (defun org-cycle-hide-inline-tasks (state)
7059 "Re-hide inline task when switching to 'contents visibility state."
7060 (when (and (eq state 'contents)
7061 (boundp 'org-inlinetask-min-level)
7062 org-inlinetask-min-level)
7063 (hide-sublevels (1- org-inlinetask-min-level))))
7065 (defun org-flag-drawer (flag &optional element)
7066 "When FLAG is non-nil, hide the drawer we are at.
7067 Otherwise make it visible. When optional argument ELEMENT is
7068 a parsed drawer, as returned by `org-element-at-point', hide or
7069 show that drawer instead."
7070 (let ((drawer (or element (org-element-at-point))))
7071 (when (memq (org-element-type drawer) '(drawer property-drawer))
7072 (save-excursion
7073 (goto-char (org-element-property :post-affiliated drawer))
7074 (outline-flag-region
7075 (line-end-position)
7076 (progn (goto-char (org-element-property :end drawer))
7077 (skip-chars-backward " \r\t\n")
7078 (line-end-position))
7079 flag)))))
7081 (defun org-subtree-end-visible-p ()
7082 "Is the end of the current subtree visible?"
7083 (pos-visible-in-window-p
7084 (save-excursion (org-end-of-subtree t) (point))))
7086 (defun org-first-headline-recenter (&optional N)
7087 "Move cursor to the first headline and recenter the headline.
7088 Optional argument N means put the headline into the Nth line of the window."
7089 (goto-char (point-min))
7090 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7091 (beginning-of-line)
7092 (recenter (prefix-numeric-value N))))
7094 ;;; Saving and restoring visibility
7096 (defun org-outline-overlay-data (&optional use-markers)
7097 "Return a list of the locations of all outline overlays.
7098 These are overlays with the `invisible' property value `outline'.
7099 The return value is a list of cons cells, with start and stop
7100 positions for each overlay.
7101 If USE-MARKERS is set, return the positions as markers."
7102 (let (beg end)
7103 (save-excursion
7104 (save-restriction
7105 (widen)
7106 (delq nil
7107 (mapcar (lambda (o)
7108 (when (eq (overlay-get o 'invisible) 'outline)
7109 (setq beg (overlay-start o)
7110 end (overlay-end o))
7111 (and beg end (> end beg)
7112 (if use-markers
7113 (cons (move-marker (make-marker) beg)
7114 (move-marker (make-marker) end))
7115 (cons beg end)))))
7116 (overlays-in (point-min) (point-max))))))))
7118 (defun org-set-outline-overlay-data (data)
7119 "Create visibility overlays for all positions in DATA.
7120 DATA should have been made by `org-outline-overlay-data'."
7121 (let (o)
7122 (save-excursion
7123 (save-restriction
7124 (widen)
7125 (show-all)
7126 (mapc (lambda (c)
7127 (outline-flag-region (car c) (cdr c) t))
7128 data)))))
7130 ;;; Folding of blocks
7132 (defvar org-hide-block-overlays nil
7133 "Overlays hiding blocks.")
7134 (make-variable-buffer-local 'org-hide-block-overlays)
7136 (defun org-block-map (function &optional start end)
7137 "Call FUNCTION at the head of all source blocks in the current buffer.
7138 Optional arguments START and END can be used to limit the range."
7139 (let ((start (or start (point-min)))
7140 (end (or end (point-max))))
7141 (save-excursion
7142 (goto-char start)
7143 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7144 (save-excursion
7145 (save-match-data
7146 (goto-char (match-beginning 0))
7147 (funcall function)))))))
7149 (defun org-hide-block-toggle-all ()
7150 "Toggle the visibility of all blocks in the current buffer."
7151 (org-block-map #'org-hide-block-toggle))
7153 (defun org-hide-block-all ()
7154 "Fold all blocks in the current buffer."
7155 (interactive)
7156 (org-show-block-all)
7157 (org-block-map #'org-hide-block-toggle-maybe))
7159 (defun org-show-block-all ()
7160 "Unfold all blocks in the current buffer."
7161 (interactive)
7162 (mapc 'delete-overlay org-hide-block-overlays)
7163 (setq org-hide-block-overlays nil))
7165 (defun org-hide-block-toggle-maybe ()
7166 "Toggle visibility of block at point."
7167 (interactive)
7168 (let ((case-fold-search t))
7169 (if (save-excursion
7170 (beginning-of-line 1)
7171 (looking-at org-block-regexp))
7172 (progn (org-hide-block-toggle)
7173 t) ;; to signal that we took action
7174 nil))) ;; to signal that we did not
7176 (defun org-hide-block-toggle (&optional force)
7177 "Toggle the visibility of the current block."
7178 (interactive)
7179 (save-excursion
7180 (beginning-of-line)
7181 (if (re-search-forward org-block-regexp nil t)
7182 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7183 (end (match-end 0)) ;; end of entire body
7185 (if (memq t (mapcar (lambda (overlay)
7186 (eq (overlay-get overlay 'invisible)
7187 'org-hide-block))
7188 (overlays-at start)))
7189 (if (or (not force) (eq force 'off))
7190 (mapc (lambda (ov)
7191 (when (member ov org-hide-block-overlays)
7192 (setq org-hide-block-overlays
7193 (delq ov org-hide-block-overlays)))
7194 (when (eq (overlay-get ov 'invisible)
7195 'org-hide-block)
7196 (delete-overlay ov)))
7197 (overlays-at start)))
7198 (setq ov (make-overlay start end))
7199 (overlay-put ov 'invisible 'org-hide-block)
7200 ;; make the block accessible to isearch
7201 (overlay-put
7202 ov 'isearch-open-invisible
7203 (lambda (ov)
7204 (when (member ov org-hide-block-overlays)
7205 (setq org-hide-block-overlays
7206 (delq ov org-hide-block-overlays)))
7207 (when (eq (overlay-get ov 'invisible)
7208 'org-hide-block)
7209 (delete-overlay ov))))
7210 (push ov org-hide-block-overlays)))
7211 (user-error "Not looking at a source block"))))
7213 ;; org-tab-after-check-for-cycling-hook
7214 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7215 ;; Remove overlays when changing major mode
7216 (add-hook 'org-mode-hook
7217 (lambda () (org-add-hook 'change-major-mode-hook
7218 'org-show-block-all 'append 'local)))
7220 ;;; Org-goto
7222 (defvar org-goto-window-configuration nil)
7223 (defvar org-goto-marker nil)
7224 (defvar org-goto-map)
7225 (defun org-goto-map ()
7226 "Set the keymap `org-goto'."
7227 (setq org-goto-map
7228 (let ((map (make-sparse-keymap)))
7229 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7230 mouse-drag-region universal-argument org-occur))
7231 cmd)
7232 (while (setq cmd (pop cmds))
7233 (substitute-key-definition cmd cmd map global-map)))
7234 (suppress-keymap map)
7235 (org-defkey map "\C-m" 'org-goto-ret)
7236 (org-defkey map [(return)] 'org-goto-ret)
7237 (org-defkey map [(left)] 'org-goto-left)
7238 (org-defkey map [(right)] 'org-goto-right)
7239 (org-defkey map [(control ?g)] 'org-goto-quit)
7240 (org-defkey map "\C-i" 'org-cycle)
7241 (org-defkey map [(tab)] 'org-cycle)
7242 (org-defkey map [(down)] 'outline-next-visible-heading)
7243 (org-defkey map [(up)] 'outline-previous-visible-heading)
7244 (if org-goto-auto-isearch
7245 (if (fboundp 'define-key-after)
7246 (define-key-after map [t] 'org-goto-local-auto-isearch)
7247 nil)
7248 (org-defkey map "q" 'org-goto-quit)
7249 (org-defkey map "n" 'outline-next-visible-heading)
7250 (org-defkey map "p" 'outline-previous-visible-heading)
7251 (org-defkey map "f" 'outline-forward-same-level)
7252 (org-defkey map "b" 'outline-backward-same-level)
7253 (org-defkey map "u" 'outline-up-heading))
7254 (org-defkey map "/" 'org-occur)
7255 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7256 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7257 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7258 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7259 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7260 map)))
7262 (defconst org-goto-help
7263 "Browse buffer copy, to find location or copy text.%s
7264 RET=jump to location C-g=quit and return to previous location
7265 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7267 (defvar org-goto-start-pos) ; dynamically scoped parameter
7269 (defun org-goto (&optional alternative-interface)
7270 "Look up a different location in the current file, keeping current visibility.
7272 When you want look-up or go to a different location in a
7273 document, the fastest way is often to fold the entire buffer and
7274 then dive into the tree. This method has the disadvantage, that
7275 the previous location will be folded, which may not be what you
7276 want.
7278 This command works around this by showing a copy of the current
7279 buffer in an indirect buffer, in overview mode. You can dive
7280 into the tree in that copy, use org-occur and incremental search
7281 to find a location. When pressing RET or `Q', the command
7282 returns to the original buffer in which the visibility is still
7283 unchanged. After RET it will also jump to the location selected
7284 in the indirect buffer and expose the headline hierarchy above.
7286 With a prefix argument, use the alternative interface: e.g. if
7287 `org-goto-interface' is 'outline use 'outline-path-completion."
7288 (interactive "P")
7289 (org-goto-map)
7290 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7291 (org-refile-use-outline-path t)
7292 (org-refile-target-verify-function nil)
7293 (interface
7294 (if (not alternative-interface)
7295 org-goto-interface
7296 (if (eq org-goto-interface 'outline)
7297 'outline-path-completion
7298 'outline)))
7299 (org-goto-start-pos (point))
7300 (selected-point
7301 (if (eq interface 'outline)
7302 (car (org-get-location (current-buffer) org-goto-help))
7303 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7304 (org-refile-check-position pa)
7305 (nth 3 pa)))))
7306 (if selected-point
7307 (progn
7308 (org-mark-ring-push org-goto-start-pos)
7309 (goto-char selected-point)
7310 (if (or (outline-invisible-p) (org-invisible-p2))
7311 (org-show-context 'org-goto)))
7312 (message "Quit"))))
7314 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7315 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7316 (defvar org-goto-local-auto-isearch-map) ; defined below
7318 (defun org-get-location (buf help)
7319 "Let the user select a location in the Org-mode buffer BUF.
7320 This function uses a recursive edit. It returns the selected position
7321 or nil."
7322 (org-no-popups
7323 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7324 (isearch-hide-immediately nil)
7325 (isearch-search-fun-function
7326 (lambda () 'org-goto-local-search-headings))
7327 (org-goto-selected-point org-goto-exit-command))
7328 (save-excursion
7329 (save-window-excursion
7330 (delete-other-windows)
7331 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7332 (org-pop-to-buffer-same-window
7333 (condition-case nil
7334 (make-indirect-buffer (current-buffer) "*org-goto*")
7335 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7336 (with-output-to-temp-buffer "*Org Help*"
7337 (princ (format help (if org-goto-auto-isearch
7338 " Just type for auto-isearch."
7339 " n/p/f/b/u to navigate, q to quit."))))
7340 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7341 (setq buffer-read-only nil)
7342 (let ((org-startup-truncated t)
7343 (org-startup-folded nil)
7344 (org-startup-align-all-tables nil))
7345 (org-mode)
7346 (org-overview))
7347 (setq buffer-read-only t)
7348 (if (and (boundp 'org-goto-start-pos)
7349 (integer-or-marker-p org-goto-start-pos))
7350 (let ((org-show-hierarchy-above t)
7351 (org-show-siblings t)
7352 (org-show-following-heading t))
7353 (goto-char org-goto-start-pos)
7354 (and (outline-invisible-p) (org-show-context)))
7355 (goto-char (point-min)))
7356 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7357 (message "Select location and press RET")
7358 (use-local-map org-goto-map)
7359 (recursive-edit)))
7360 (kill-buffer "*org-goto*")
7361 (cons org-goto-selected-point org-goto-exit-command))))
7363 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7364 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7365 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7366 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7368 (defun org-goto-local-search-headings (string bound noerror)
7369 "Search and make sure that any matches are in headlines."
7370 (catch 'return
7371 (while (if isearch-forward
7372 (search-forward string bound noerror)
7373 (search-backward string bound noerror))
7374 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7375 (and (member :headline context)
7376 (not (member :tags context))))
7377 (throw 'return (point))))))
7379 (defun org-goto-local-auto-isearch ()
7380 "Start isearch."
7381 (interactive)
7382 (goto-char (point-min))
7383 (let ((keys (this-command-keys)))
7384 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7385 (isearch-mode t)
7386 (isearch-process-search-char (string-to-char keys)))))
7388 (defun org-goto-ret (&optional arg)
7389 "Finish `org-goto' by going to the new location."
7390 (interactive "P")
7391 (setq org-goto-selected-point (point)
7392 org-goto-exit-command 'return)
7393 (throw 'exit nil))
7395 (defun org-goto-left ()
7396 "Finish `org-goto' by going to the new location."
7397 (interactive)
7398 (if (org-at-heading-p)
7399 (progn
7400 (beginning-of-line 1)
7401 (setq org-goto-selected-point (point)
7402 org-goto-exit-command 'left)
7403 (throw 'exit nil))
7404 (user-error "Not on a heading")))
7406 (defun org-goto-right ()
7407 "Finish `org-goto' by going to the new location."
7408 (interactive)
7409 (if (org-at-heading-p)
7410 (progn
7411 (setq org-goto-selected-point (point)
7412 org-goto-exit-command 'right)
7413 (throw 'exit nil))
7414 (user-error "Not on a heading")))
7416 (defun org-goto-quit ()
7417 "Finish `org-goto' without cursor motion."
7418 (interactive)
7419 (setq org-goto-selected-point nil)
7420 (setq org-goto-exit-command 'quit)
7421 (throw 'exit nil))
7423 ;;; Indirect buffer display of subtrees
7425 (defvar org-indirect-dedicated-frame nil
7426 "This is the frame being used for indirect tree display.")
7427 (defvar org-last-indirect-buffer nil)
7429 (defun org-tree-to-indirect-buffer (&optional arg)
7430 "Create indirect buffer and narrow it to current subtree.
7431 With a numerical prefix ARG, go up to this level and then take that tree.
7432 If ARG is negative, go up that many levels.
7434 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7435 indirect buffer previously made with this command, to avoid proliferation of
7436 indirect buffers. However, when you call the command with a \
7437 \\[universal-argument] prefix, or
7438 when `org-indirect-buffer-display' is `new-frame', the last buffer
7439 is kept so that you can work with several indirect buffers at the same time.
7440 If `org-indirect-buffer-display' is `dedicated-frame', the \
7441 \\[universal-argument] prefix also
7442 requests that a new frame be made for the new buffer, so that the dedicated
7443 frame is not changed."
7444 (interactive "P")
7445 (let ((cbuf (current-buffer))
7446 (cwin (selected-window))
7447 (pos (point))
7448 beg end level heading ibuf)
7449 (save-excursion
7450 (org-back-to-heading t)
7451 (when (numberp arg)
7452 (setq level (org-outline-level))
7453 (if (< arg 0) (setq arg (+ level arg)))
7454 (while (> (setq level (org-outline-level)) arg)
7455 (org-up-heading-safe)))
7456 (setq beg (point)
7457 heading (org-get-heading))
7458 (org-end-of-subtree t t)
7459 (if (org-at-heading-p) (backward-char 1))
7460 (setq end (point)))
7461 (if (and (buffer-live-p org-last-indirect-buffer)
7462 (not (eq org-indirect-buffer-display 'new-frame))
7463 (not arg))
7464 (kill-buffer org-last-indirect-buffer))
7465 (setq ibuf (org-get-indirect-buffer cbuf)
7466 org-last-indirect-buffer ibuf)
7467 (cond
7468 ((or (eq org-indirect-buffer-display 'new-frame)
7469 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7470 (select-frame (make-frame))
7471 (delete-other-windows)
7472 (org-pop-to-buffer-same-window ibuf)
7473 (org-set-frame-title heading))
7474 ((eq org-indirect-buffer-display 'dedicated-frame)
7475 (raise-frame
7476 (select-frame (or (and org-indirect-dedicated-frame
7477 (frame-live-p org-indirect-dedicated-frame)
7478 org-indirect-dedicated-frame)
7479 (setq org-indirect-dedicated-frame (make-frame)))))
7480 (delete-other-windows)
7481 (org-pop-to-buffer-same-window ibuf)
7482 (org-set-frame-title (concat "Indirect: " heading)))
7483 ((eq org-indirect-buffer-display 'current-window)
7484 (org-pop-to-buffer-same-window ibuf))
7485 ((eq org-indirect-buffer-display 'other-window)
7486 (pop-to-buffer ibuf))
7487 (t (error "Invalid value")))
7488 (if (featurep 'xemacs)
7489 (save-excursion (org-mode) (turn-on-font-lock)))
7490 (narrow-to-region beg end)
7491 (show-all)
7492 (goto-char pos)
7493 (run-hook-with-args 'org-cycle-hook 'all)
7494 (and (window-live-p cwin) (select-window cwin))))
7496 (defun org-get-indirect-buffer (&optional buffer)
7497 (setq buffer (or buffer (current-buffer)))
7498 (let ((n 1) (base (buffer-name buffer)) bname)
7499 (while (buffer-live-p
7500 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7501 (setq n (1+ n)))
7502 (condition-case nil
7503 (make-indirect-buffer buffer bname 'clone)
7504 (error (make-indirect-buffer buffer bname)))))
7506 (defun org-set-frame-title (title)
7507 "Set the title of the current frame to the string TITLE."
7508 ;; FIXME: how to name a single frame in XEmacs???
7509 (unless (featurep 'xemacs)
7510 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7512 ;;;; Structure editing
7514 ;;; Inserting headlines
7516 (defun org-previous-line-empty-p (&optional next)
7517 "Is the previous line a blank line?
7518 When NEXT is non-nil, check the next line instead."
7519 (save-excursion
7520 (and (not (bobp))
7521 (or (beginning-of-line (if next 2 0)) t)
7522 (save-match-data
7523 (looking-at "[ \t]*$")))))
7525 (defun org-insert-heading (&optional arg invisible-ok)
7526 "Insert a new heading or item with same depth at point.
7527 If point is in a plain list and ARG is nil, create a new list item.
7528 With one universal prefix argument, insert a heading even in lists.
7529 With two universal prefix arguments, insert the heading at the end
7530 of the parent subtree.
7532 If point is at the beginning of a headline, insert a sibling before
7533 the current headline. If point is not at the beginning, split the line
7534 and create a new headline with the text in the current line after point
7535 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7537 If point is at the beginning of a normal line, turn this line into
7538 a heading.
7540 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7541 This is important for non-interactive uses of the command."
7542 (interactive "P")
7543 (if (org-called-interactively-p 'any) (org-reveal))
7544 (let ((itemp (org-in-item-p))
7545 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7546 (respect-content (or org-insert-heading-respect-content
7547 (equal arg '(16))))
7548 (initial-content "")
7549 (adjust-empty-lines t))
7551 (cond
7553 ((or (= (buffer-size) 0)
7554 (and (not (save-excursion
7555 (and (ignore-errors (org-back-to-heading invisible-ok))
7556 (org-at-heading-p))))
7557 (or arg (not itemp))))
7558 ;; At beginning of buffer or so high up that only a heading
7559 ;; makes sense.
7560 (insert
7561 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7562 (if (org-in-src-block-p) ",* " "* "))
7563 (run-hooks 'org-insert-heading-hook))
7565 ((and itemp (not (equal arg '(4))))
7566 ;; Insert an item
7567 (org-insert-item))
7570 ;; Insert a heading
7571 (save-restriction
7572 (widen)
7573 (let* ((level nil)
7574 (on-heading (org-at-heading-p))
7575 (empty-line-p (if on-heading
7576 (org-previous-line-empty-p)
7577 ;; We will decide later
7578 nil))
7579 ;; Get a level string to fall back on
7580 (fix-level
7581 (save-excursion
7582 (org-back-to-heading t)
7583 (if (org-previous-line-empty-p) (setq empty-line-p t))
7584 (looking-at org-outline-regexp)
7585 (make-string (1- (length (match-string 0))) ?*)))
7586 (stars
7587 (save-excursion
7588 (condition-case nil
7589 (progn
7590 (org-back-to-heading invisible-ok)
7591 (when (and (not on-heading)
7592 (featurep 'org-inlinetask)
7593 (integerp org-inlinetask-min-level)
7594 (>= (length (match-string 0))
7595 org-inlinetask-min-level))
7596 ;; Find a heading level before the inline task
7597 (while (and (setq level (org-up-heading-safe))
7598 (>= level org-inlinetask-min-level)))
7599 (if (org-at-heading-p)
7600 (org-back-to-heading invisible-ok)
7601 (error "This should not happen")))
7602 (unless (and (save-excursion
7603 (save-match-data
7604 (org-backward-heading-same-level
7605 1 invisible-ok))
7606 (= (point) (match-beginning 0)))
7607 (not (org-previous-line-empty-p t)))
7608 (setq empty-line-p (or empty-line-p
7609 (org-previous-line-empty-p))))
7610 (match-string 0))
7611 (error (or fix-level "* ")))))
7612 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7613 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7614 pos hide-previous previous-pos)
7616 ;; If we insert after content, move there and clean up whitespace
7617 (when respect-content
7618 (org-end-of-subtree nil t)
7619 (skip-chars-backward " \r\n")
7620 (and (looking-at "[ \t]+") (replace-match ""))
7621 (unless (eobp) (forward-char 1))
7622 (when (looking-at "^\\*")
7623 (unless (bobp) (backward-char 1))
7624 (insert "\n")))
7626 ;; If we are splitting, grab the text that should be moved to the new headline
7627 (when may-split
7628 (if (org-on-heading-p)
7629 ;; This is a heading, we split intelligently (keeping tags)
7630 (let ((pos (point)))
7631 (goto-char (point-at-bol))
7632 (unless (looking-at org-complex-heading-regexp)
7633 (error "This should not happen"))
7634 (when (and (match-beginning 4)
7635 (> pos (match-beginning 4))
7636 (< pos (match-end 4)))
7637 (setq initial-content (buffer-substring pos (match-end 4)))
7638 (goto-char pos)
7639 (delete-region (point) (match-end 4))
7640 (if (looking-at "[ \t]*$")
7641 (replace-match "")
7642 (insert (make-string (length initial-content) ?\ )))
7643 (setq initial-content (org-trim initial-content)))
7644 (goto-char pos))
7645 ;; a normal line
7646 (unless (bolp)
7647 (setq initial-content (buffer-substring (point) (point-at-eol)))
7648 (delete-region (point) (point-at-eol))
7649 (setq initial-content (org-trim initial-content)))))
7651 ;; If we are at the beginning of the line, insert before it. Else after
7652 (cond
7653 ((and (bolp) (looking-at "[ \t]*$")))
7654 ((and (bolp) (not (looking-at "[ \t]*$")))
7655 (open-line 1))
7657 (goto-char (point-at-eol))
7658 (insert "\n")))
7660 ;; Insert the new heading
7661 (insert stars)
7662 (just-one-space)
7663 (insert initial-content)
7664 (when adjust-empty-lines
7665 (if (or (not blank)
7666 (and blank (not (org-previous-line-empty-p))))
7667 (org-N-empty-lines-before-current (if blank 1 0))))
7668 (run-hooks 'org-insert-heading-hook)))))))
7670 (defun org-N-empty-lines-before-current (N)
7671 "Make the number of empty lines before current exactly N.
7672 So this will delete or add empty lines."
7673 (save-excursion
7674 (goto-char (point-at-bol))
7675 (if (looking-back "\\s-+" nil 'greedy)
7676 (replace-match ""))
7677 (or (bobp) (insert "\n"))
7678 (while (> N 0)
7679 (insert "\n")
7680 (setq N (1- N)))))
7682 (defun org-get-heading (&optional no-tags no-todo)
7683 "Return the heading of the current entry, without the stars.
7684 When NO-TAGS is non-nil, don't include tags.
7685 When NO-TODO is non-nil, don't include TODO keywords."
7686 (save-excursion
7687 (org-back-to-heading t)
7688 (cond
7689 ((and no-tags no-todo)
7690 (looking-at org-complex-heading-regexp)
7691 (match-string 4))
7692 (no-tags
7693 (looking-at (concat org-outline-regexp
7694 "\\(.*?\\)"
7695 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7696 (match-string 1))
7697 (no-todo
7698 (looking-at org-todo-line-regexp)
7699 (match-string 3))
7700 (t (looking-at org-heading-regexp)
7701 (match-string 2)))))
7703 (defvar orgstruct-mode) ; defined below
7705 (defun org-heading-components ()
7706 "Return the components of the current heading.
7707 This is a list with the following elements:
7708 - the level as an integer
7709 - the reduced level, different if `org-odd-levels-only' is set.
7710 - the TODO keyword, or nil
7711 - the priority character, like ?A, or nil if no priority is given
7712 - the headline text itself, or the tags string if no headline text
7713 - the tags string, or nil."
7714 (save-excursion
7715 (org-back-to-heading t)
7716 (if (let (case-fold-search)
7717 (looking-at
7718 (if orgstruct-mode
7719 org-heading-regexp
7720 org-complex-heading-regexp)))
7721 (if orgstruct-mode
7722 (list (length (match-string 1))
7723 (org-reduced-level (length (match-string 1)))
7726 (match-string 2)
7727 nil)
7728 (list (length (match-string 1))
7729 (org-reduced-level (length (match-string 1)))
7730 (org-match-string-no-properties 2)
7731 (and (match-end 3) (aref (match-string 3) 2))
7732 (org-match-string-no-properties 4)
7733 (org-match-string-no-properties 5))))))
7735 (defun org-get-entry ()
7736 "Get the entry text, after heading, entire subtree."
7737 (save-excursion
7738 (org-back-to-heading t)
7739 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7741 (defun org-insert-heading-after-current ()
7742 "Insert a new heading with same level as current, after current subtree."
7743 (interactive)
7744 (org-back-to-heading)
7745 (org-insert-heading)
7746 (org-move-subtree-down)
7747 (end-of-line 1))
7749 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7750 "Insert heading with `org-insert-heading-respect-content' set to t."
7751 (interactive "P")
7752 (let ((org-insert-heading-respect-content t))
7753 (org-insert-heading '(4) invisible-ok)))
7755 (defun org-insert-todo-heading-respect-content (&optional force-state)
7756 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7757 (interactive "P")
7758 (let ((org-insert-heading-respect-content t))
7759 (org-insert-todo-heading force-state '(4))))
7761 (defun org-insert-todo-heading (arg &optional force-heading)
7762 "Insert a new heading with the same level and TODO state as current heading.
7763 If the heading has no TODO state, or if the state is DONE, use the first
7764 state (TODO by default). Also one prefix arg, force first state. With two
7765 prefix args, force inserting at the end of the parent subtree."
7766 (interactive "P")
7767 (when (or force-heading (not (org-insert-item 'checkbox)))
7768 (org-insert-heading (or (and (equal arg '(16)) '(16))
7769 force-heading))
7770 (save-excursion
7771 (org-back-to-heading)
7772 (outline-previous-heading)
7773 (looking-at org-todo-line-regexp))
7774 (let*
7775 ((new-mark-x
7776 (if (or arg
7777 (not (match-beginning 2))
7778 (member (match-string 2) org-done-keywords))
7779 (car org-todo-keywords-1)
7780 (match-string 2)))
7781 (new-mark
7783 (run-hook-with-args-until-success
7784 'org-todo-get-default-hook new-mark-x nil)
7785 new-mark-x)))
7786 (beginning-of-line 1)
7787 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7788 (if org-treat-insert-todo-heading-as-state-change
7789 (org-todo new-mark)
7790 (insert new-mark " "))))
7791 (when org-provide-todo-statistics
7792 (org-update-parent-todo-statistics))))
7794 (defun org-insert-subheading (arg)
7795 "Insert a new subheading and demote it.
7796 Works for outline headings and for plain lists alike."
7797 (interactive "P")
7798 (org-insert-heading arg)
7799 (cond
7800 ((org-at-heading-p) (org-do-demote))
7801 ((org-at-item-p) (org-indent-item))))
7803 (defun org-insert-todo-subheading (arg)
7804 "Insert a new subheading with TODO keyword or checkbox and demote it.
7805 Works for outline headings and for plain lists alike."
7806 (interactive "P")
7807 (org-insert-todo-heading arg)
7808 (cond
7809 ((org-at-heading-p) (org-do-demote))
7810 ((org-at-item-p) (org-indent-item))))
7812 ;;; Promotion and Demotion
7814 (defvar org-after-demote-entry-hook nil
7815 "Hook run after an entry has been demoted.
7816 The cursor will be at the beginning of the entry.
7817 When a subtree is being demoted, the hook will be called for each node.")
7819 (defvar org-after-promote-entry-hook nil
7820 "Hook run after an entry has been promoted.
7821 The cursor will be at the beginning of the entry.
7822 When a subtree is being promoted, the hook will be called for each node.")
7824 (defun org-promote-subtree ()
7825 "Promote the entire subtree.
7826 See also `org-promote'."
7827 (interactive)
7828 (save-excursion
7829 (org-with-limited-levels (org-map-tree 'org-promote)))
7830 (org-fix-position-after-promote))
7832 (defun org-demote-subtree ()
7833 "Demote the entire subtree. See `org-demote'.
7834 See also `org-promote'."
7835 (interactive)
7836 (save-excursion
7837 (org-with-limited-levels (org-map-tree 'org-demote)))
7838 (org-fix-position-after-promote))
7841 (defun org-do-promote ()
7842 "Promote the current heading higher up the tree.
7843 If the region is active in `transient-mark-mode', promote all headings
7844 in the region."
7845 (interactive)
7846 (save-excursion
7847 (if (org-region-active-p)
7848 (org-map-region 'org-promote (region-beginning) (region-end))
7849 (org-promote)))
7850 (org-fix-position-after-promote))
7852 (defun org-do-demote ()
7853 "Demote the current heading lower down the tree.
7854 If the region is active in `transient-mark-mode', demote all headings
7855 in the region."
7856 (interactive)
7857 (save-excursion
7858 (if (org-region-active-p)
7859 (org-map-region 'org-demote (region-beginning) (region-end))
7860 (org-demote)))
7861 (org-fix-position-after-promote))
7863 (defun org-fix-position-after-promote ()
7864 "Make sure that after pro/demotion cursor position is right."
7865 (let ((pos (point)))
7866 (when (save-excursion
7867 (beginning-of-line 1)
7868 (looking-at org-todo-line-regexp)
7869 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7870 (cond ((eobp) (insert " "))
7871 ((eolp) (insert " "))
7872 ((equal (char-after) ?\ ) (forward-char 1))))))
7874 (defun org-current-level ()
7875 "Return the level of the current entry, or nil if before the first headline.
7876 The level is the number of stars at the beginning of the headline."
7877 (save-excursion
7878 (org-with-limited-levels
7879 (if (ignore-errors (org-back-to-heading t))
7880 (funcall outline-level)))))
7882 (defun org-get-previous-line-level ()
7883 "Return the outline depth of the last headline before the current line.
7884 Returns 0 for the first headline in the buffer, and nil if before the
7885 first headline."
7886 (let ((current-level (org-current-level))
7887 (prev-level (when (> (line-number-at-pos) 1)
7888 (save-excursion
7889 (beginning-of-line 0)
7890 (org-current-level)))))
7891 (cond ((null current-level) nil) ; Before first headline
7892 ((null prev-level) 0) ; At first headline
7893 (prev-level))))
7895 (defun org-reduced-level (l)
7896 "Compute the effective level of a heading.
7897 This takes into account the setting of `org-odd-levels-only'."
7898 (cond
7899 ((zerop l) 0)
7900 (org-odd-levels-only (1+ (floor (/ l 2))))
7901 (t l)))
7903 (defun org-level-increment ()
7904 "Return the number of stars that will be added or removed at a
7905 time to headlines when structure editing, based on the value of
7906 `org-odd-levels-only'."
7907 (if org-odd-levels-only 2 1))
7909 (defun org-get-valid-level (level &optional change)
7910 "Rectify a level change under the influence of `org-odd-levels-only'
7911 LEVEL is a current level, CHANGE is by how much the level should be
7912 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7913 even level numbers will become the next higher odd number."
7914 (if org-odd-levels-only
7915 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7916 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7917 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7918 (max 1 (+ level (or change 0)))))
7920 (if (boundp 'define-obsolete-function-alias)
7921 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7922 (define-obsolete-function-alias 'org-get-legal-level
7923 'org-get-valid-level)
7924 (define-obsolete-function-alias 'org-get-legal-level
7925 'org-get-valid-level "23.1")))
7927 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7928 ;; ̀org-with-limited-levels'
7929 (defun org-promote ()
7930 "Promote the current heading higher up the tree.
7931 If the region is active in `transient-mark-mode', promote all headings
7932 in the region."
7933 (org-back-to-heading t)
7934 (let* ((level (save-match-data (funcall outline-level)))
7935 (after-change-functions (remove 'flyspell-after-change-function
7936 after-change-functions))
7937 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7938 (diff (abs (- level (length up-head) -1))))
7939 (cond ((and (= level 1) org-called-with-limited-levels
7940 org-allow-promoting-top-level-subtree)
7941 (replace-match "# " nil t))
7942 ((= level 1)
7943 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7944 (t (replace-match up-head nil t)))
7945 ;; Fixup tag positioning
7946 (unless (= level 1)
7947 (and org-auto-align-tags (org-set-tags nil t))
7948 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7949 (run-hooks 'org-after-promote-entry-hook)))
7951 (defun org-demote ()
7952 "Demote the current heading lower down the tree.
7953 If the region is active in `transient-mark-mode', demote all headings
7954 in the region."
7955 (org-back-to-heading t)
7956 (let* ((level (save-match-data (funcall outline-level)))
7957 (after-change-functions (remove 'flyspell-after-change-function
7958 after-change-functions))
7959 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7960 (diff (abs (- level (length down-head) -1))))
7961 (replace-match down-head nil t)
7962 ;; Fixup tag positioning
7963 (and org-auto-align-tags (org-set-tags nil t))
7964 (if org-adapt-indentation (org-fixup-indentation diff))
7965 (run-hooks 'org-after-demote-entry-hook)))
7967 (defun org-cycle-level ()
7968 "Cycle the level of an empty headline through possible states.
7969 This goes first to child, then to parent, level, then up the hierarchy.
7970 After top level, it switches back to sibling level."
7971 (interactive)
7972 (let ((org-adapt-indentation nil))
7973 (when (org-point-at-end-of-empty-headline)
7974 (setq this-command 'org-cycle-level) ; Only needed for caching
7975 (let ((cur-level (org-current-level))
7976 (prev-level (org-get-previous-line-level)))
7977 (cond
7978 ;; If first headline in file, promote to top-level.
7979 ((= prev-level 0)
7980 (loop repeat (/ (- cur-level 1) (org-level-increment))
7981 do (org-do-promote)))
7982 ;; If same level as prev, demote one.
7983 ((= prev-level cur-level)
7984 (org-do-demote))
7985 ;; If parent is top-level, promote to top level if not already.
7986 ((= prev-level 1)
7987 (loop repeat (/ (- cur-level 1) (org-level-increment))
7988 do (org-do-promote)))
7989 ;; If top-level, return to prev-level.
7990 ((= cur-level 1)
7991 (loop repeat (/ (- prev-level 1) (org-level-increment))
7992 do (org-do-demote)))
7993 ;; If less than prev-level, promote one.
7994 ((< cur-level prev-level)
7995 (org-do-promote))
7996 ;; If deeper than prev-level, promote until higher than
7997 ;; prev-level.
7998 ((> cur-level prev-level)
7999 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8000 do (org-do-promote))))
8001 t))))
8003 (defun org-map-tree (fun)
8004 "Call FUN for every heading underneath the current one."
8005 (org-back-to-heading)
8006 (let ((level (funcall outline-level)))
8007 (save-excursion
8008 (funcall fun)
8009 (while (and (progn
8010 (outline-next-heading)
8011 (> (funcall outline-level) level))
8012 (not (eobp)))
8013 (funcall fun)))))
8015 (defun org-map-region (fun beg end)
8016 "Call FUN for every heading between BEG and END."
8017 (let ((org-ignore-region t))
8018 (save-excursion
8019 (setq end (copy-marker end))
8020 (goto-char beg)
8021 (if (and (re-search-forward org-outline-regexp-bol nil t)
8022 (< (point) end))
8023 (funcall fun))
8024 (while (and (progn
8025 (outline-next-heading)
8026 (< (point) end))
8027 (not (eobp)))
8028 (funcall fun)))))
8030 (defvar org-property-end-re) ; silence byte-compiler
8031 (defun org-fixup-indentation (diff)
8032 "Change the indentation in the current entry by DIFF.
8033 However, if any line in the current entry has no indentation, or if it
8034 would end up with no indentation after the change, nothing at all is done."
8035 (save-excursion
8036 (let ((end (save-excursion (outline-next-heading)
8037 (point-marker)))
8038 (prohibit (if (> diff 0)
8039 "^\\S-"
8040 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8041 col)
8042 (unless (save-excursion (end-of-line 1)
8043 (re-search-forward prohibit end t))
8044 (while (and (< (point) end)
8045 (re-search-forward "^[ \t]+" end t))
8046 (goto-char (match-end 0))
8047 (setq col (current-column))
8048 (if (< diff 0) (replace-match ""))
8049 (org-indent-to-column (+ diff col))))
8050 (move-marker end nil))))
8052 (defun org-convert-to-odd-levels ()
8053 "Convert an org-mode file with all levels allowed to one with odd levels.
8054 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8055 level 5 etc."
8056 (interactive)
8057 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8058 (let ((outline-level 'org-outline-level)
8059 (org-odd-levels-only nil) n)
8060 (save-excursion
8061 (goto-char (point-min))
8062 (while (re-search-forward "^\\*\\*+ " nil t)
8063 (setq n (- (length (match-string 0)) 2))
8064 (while (>= (setq n (1- n)) 0)
8065 (org-demote))
8066 (end-of-line 1))))))
8068 (defun org-convert-to-oddeven-levels ()
8069 "Convert an org-mode file with only odd levels to one with odd/even levels.
8070 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8071 file contains a section with an even level, conversion would
8072 destroy the structure of the file. An error is signaled in this
8073 case."
8074 (interactive)
8075 (goto-char (point-min))
8076 ;; First check if there are no even levels
8077 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8078 (org-show-context t)
8079 (error "Not all levels are odd in this file. Conversion not possible"))
8080 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8081 (let ((outline-regexp org-outline-regexp)
8082 (outline-level 'org-outline-level)
8083 (org-odd-levels-only nil) n)
8084 (save-excursion
8085 (goto-char (point-min))
8086 (while (re-search-forward "^\\*\\*+ " nil t)
8087 (setq n (/ (1- (length (match-string 0))) 2))
8088 (while (>= (setq n (1- n)) 0)
8089 (org-promote))
8090 (end-of-line 1))))))
8092 (defun org-tr-level (n)
8093 "Make N odd if required."
8094 (if org-odd-levels-only (1+ (/ n 2)) n))
8096 ;;; Vertical tree motion, cutting and pasting of subtrees
8098 (defun org-move-subtree-up (&optional arg)
8099 "Move the current subtree up past ARG headlines of the same level."
8100 (interactive "p")
8101 (org-move-subtree-down (- (prefix-numeric-value arg))))
8103 (defun org-move-subtree-down (&optional arg)
8104 "Move the current subtree down past ARG headlines of the same level."
8105 (interactive "p")
8106 (setq arg (prefix-numeric-value arg))
8107 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8108 'org-get-last-sibling))
8109 (ins-point (make-marker))
8110 (cnt (abs arg))
8111 (col (current-column))
8112 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8113 ;; Select the tree
8114 (org-back-to-heading)
8115 (setq beg0 (point))
8116 (save-excursion
8117 (setq ne-beg (org-back-over-empty-lines))
8118 (setq beg (point)))
8119 (save-match-data
8120 (save-excursion (outline-end-of-heading)
8121 (setq folded (outline-invisible-p)))
8122 (outline-end-of-subtree))
8123 (outline-next-heading)
8124 (setq ne-end (org-back-over-empty-lines))
8125 (setq end (point))
8126 (goto-char beg0)
8127 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8128 ;; include less whitespace
8129 (save-excursion
8130 (goto-char beg)
8131 (forward-line (- ne-beg ne-end))
8132 (setq beg (point))))
8133 ;; Find insertion point, with error handling
8134 (while (> cnt 0)
8135 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8136 (progn (goto-char beg0)
8137 (user-error "Cannot move past superior level or buffer limit")))
8138 (setq cnt (1- cnt)))
8139 (if (> arg 0)
8140 ;; Moving forward - still need to move over subtree
8141 (progn (org-end-of-subtree t t)
8142 (save-excursion
8143 (org-back-over-empty-lines)
8144 (or (bolp) (newline)))))
8145 (setq ne-ins (org-back-over-empty-lines))
8146 (move-marker ins-point (point))
8147 (setq txt (buffer-substring beg end))
8148 (org-save-markers-in-region beg end)
8149 (delete-region beg end)
8150 (org-remove-empty-overlays-at beg)
8151 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8152 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8153 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8154 (let ((bbb (point)))
8155 (insert-before-markers txt)
8156 (org-reinstall-markers-in-region bbb)
8157 (move-marker ins-point bbb))
8158 (or (bolp) (insert "\n"))
8159 (setq ins-end (point))
8160 (goto-char ins-point)
8161 (org-skip-whitespace)
8162 (when (and (< arg 0)
8163 (org-first-sibling-p)
8164 (> ne-ins ne-beg))
8165 ;; Move whitespace back to beginning
8166 (save-excursion
8167 (goto-char ins-end)
8168 (let ((kill-whole-line t))
8169 (kill-line (- ne-ins ne-beg)) (point)))
8170 (insert (make-string (- ne-ins ne-beg) ?\n)))
8171 (move-marker ins-point nil)
8172 (if folded
8173 (hide-subtree)
8174 (org-show-entry)
8175 (show-children)
8176 (org-cycle-hide-drawers 'children))
8177 (org-clean-visibility-after-subtree-move)
8178 ;; move back to the initial column we were at
8179 (move-to-column col)))
8181 (defvar org-subtree-clip ""
8182 "Clipboard for cut and paste of subtrees.
8183 This is actually only a copy of the kill, because we use the normal kill
8184 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8186 (defvar org-subtree-clip-folded nil
8187 "Was the last copied subtree folded?
8188 This is used to fold the tree back after pasting.")
8190 (defun org-cut-subtree (&optional n)
8191 "Cut the current subtree into the clipboard.
8192 With prefix arg N, cut this many sequential subtrees.
8193 This is a short-hand for marking the subtree and then cutting it."
8194 (interactive "p")
8195 (org-copy-subtree n 'cut))
8197 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8198 "Copy the current subtree it in the clipboard.
8199 With prefix arg N, copy this many sequential subtrees.
8200 This is a short-hand for marking the subtree and then copying it.
8201 If CUT is non-nil, actually cut the subtree.
8202 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8203 of some markers in the region, even if CUT is non-nil. This is
8204 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8205 (interactive "p")
8206 (let (beg end folded (beg0 (point)))
8207 (if (org-called-interactively-p 'any)
8208 (org-back-to-heading nil) ; take what looks like a subtree
8209 (org-back-to-heading t)) ; take what is really there
8210 (setq beg (point))
8211 (skip-chars-forward " \t\r\n")
8212 (save-match-data
8213 (if nosubtrees
8214 (outline-next-heading)
8215 (save-excursion (outline-end-of-heading)
8216 (setq folded (outline-invisible-p)))
8217 (condition-case nil
8218 (org-forward-heading-same-level (1- n) t)
8219 (error nil))
8220 (org-end-of-subtree t t)))
8221 (setq end (point))
8222 (goto-char beg0)
8223 (when (> end beg)
8224 (setq org-subtree-clip-folded folded)
8225 (when (or cut force-store-markers)
8226 (org-save-markers-in-region beg end))
8227 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8228 (setq org-subtree-clip (current-kill 0))
8229 (message "%s: Subtree(s) with %d characters"
8230 (if cut "Cut" "Copied")
8231 (length org-subtree-clip)))))
8233 (defun org-paste-subtree (&optional level tree for-yank)
8234 "Paste the clipboard as a subtree, with modification of headline level.
8235 The entire subtree is promoted or demoted in order to match a new headline
8236 level.
8238 If the cursor is at the beginning of a headline, the same level as
8239 that headline is used to paste the tree.
8241 If not, the new level is derived from the *visible* headings
8242 before and after the insertion point, and taken to be the inferior headline
8243 level of the two. So if the previous visible heading is level 3 and the
8244 next is level 4 (or vice versa), level 4 will be used for insertion.
8245 This makes sure that the subtree remains an independent subtree and does
8246 not swallow low level entries.
8248 You can also force a different level, either by using a numeric prefix
8249 argument, or by inserting the heading marker by hand. For example, if the
8250 cursor is after \"*****\", then the tree will be shifted to level 5.
8252 If optional TREE is given, use this text instead of the kill ring.
8254 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8255 move back over whitespace before inserting, and move point to the end of
8256 the inserted text when done."
8257 (interactive "P")
8258 (setq tree (or tree (and kill-ring (current-kill 0))))
8259 (unless (org-kill-is-subtree-p tree)
8260 (user-error "%s"
8261 (substitute-command-keys
8262 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8263 (org-with-limited-levels
8264 (let* ((visp (not (outline-invisible-p)))
8265 (txt tree)
8266 (^re_ "\\(\\*+\\)[ \t]*")
8267 (old-level (if (string-match org-outline-regexp-bol txt)
8268 (- (match-end 0) (match-beginning 0) 1)
8269 -1))
8270 (force-level (cond (level (prefix-numeric-value level))
8271 ((and (looking-at "[ \t]*$")
8272 (string-match
8273 "^\\*+$" (buffer-substring
8274 (point-at-bol) (point))))
8275 (- (match-end 1) (match-beginning 1)))
8276 ((and (bolp)
8277 (looking-at org-outline-regexp))
8278 (- (match-end 0) (point) 1))))
8279 (previous-level (save-excursion
8280 (condition-case nil
8281 (progn
8282 (outline-previous-visible-heading 1)
8283 (if (looking-at ^re_)
8284 (- (match-end 0) (match-beginning 0) 1)
8286 (error 1))))
8287 (next-level (save-excursion
8288 (condition-case nil
8289 (progn
8290 (or (looking-at org-outline-regexp)
8291 (outline-next-visible-heading 1))
8292 (if (looking-at ^re_)
8293 (- (match-end 0) (match-beginning 0) 1)
8295 (error 1))))
8296 (new-level (or force-level (max previous-level next-level)))
8297 (shift (if (or (= old-level -1)
8298 (= new-level -1)
8299 (= old-level new-level))
8301 (- new-level old-level)))
8302 (delta (if (> shift 0) -1 1))
8303 (func (if (> shift 0) 'org-demote 'org-promote))
8304 (org-odd-levels-only nil)
8305 beg end newend)
8306 ;; Remove the forced level indicator
8307 (if force-level
8308 (delete-region (point-at-bol) (point)))
8309 ;; Paste
8310 (beginning-of-line (if (bolp) 1 2))
8311 (setq beg (point))
8312 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8313 (insert-before-markers txt)
8314 (unless (string-match "\n\\'" txt) (insert "\n"))
8315 (setq newend (point))
8316 (org-reinstall-markers-in-region beg)
8317 (setq end (point))
8318 (goto-char beg)
8319 (skip-chars-forward " \t\n\r")
8320 (setq beg (point))
8321 (if (and (outline-invisible-p) visp)
8322 (save-excursion (outline-show-heading)))
8323 ;; Shift if necessary
8324 (unless (= shift 0)
8325 (save-restriction
8326 (narrow-to-region beg end)
8327 (while (not (= shift 0))
8328 (org-map-region func (point-min) (point-max))
8329 (setq shift (+ delta shift)))
8330 (goto-char (point-min))
8331 (setq newend (point-max))))
8332 (when (or (org-called-interactively-p 'interactive) for-yank)
8333 (message "Clipboard pasted as level %d subtree" new-level))
8334 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8335 kill-ring
8336 (eq org-subtree-clip (current-kill 0))
8337 org-subtree-clip-folded)
8338 ;; The tree was folded before it was killed/copied
8339 (hide-subtree))
8340 (and for-yank (goto-char newend)))))
8342 (defun org-kill-is-subtree-p (&optional txt)
8343 "Check if the current kill is an outline subtree, or a set of trees.
8344 Returns nil if kill does not start with a headline, or if the first
8345 headline level is not the largest headline level in the tree.
8346 So this will actually accept several entries of equal levels as well,
8347 which is OK for `org-paste-subtree'.
8348 If optional TXT is given, check this string instead of the current kill."
8349 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8350 (re (org-get-limited-outline-regexp))
8351 (^re (concat "^" re))
8352 (start-level (and kill
8353 (string-match
8354 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8355 kill)
8356 (- (match-end 2) (match-beginning 2) 1)))
8357 (start (1+ (or (match-beginning 2) -1))))
8358 (if (not start-level)
8359 (progn
8360 nil) ;; does not even start with a heading
8361 (catch 'exit
8362 (while (setq start (string-match ^re kill (1+ start)))
8363 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8364 (throw 'exit nil)))
8365 t))))
8367 (defvar org-markers-to-move nil
8368 "Markers that should be moved with a cut-and-paste operation.
8369 Those markers are stored together with their positions relative to
8370 the start of the region.")
8372 (defun org-save-markers-in-region (beg end)
8373 "Check markers in region.
8374 If these markers are between BEG and END, record their position relative
8375 to BEG, so that after moving the block of text, we can put the markers back
8376 into place.
8377 This function gets called just before an entry or tree gets cut from the
8378 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8379 called immediately, to move the markers with the entries."
8380 (setq org-markers-to-move nil)
8381 (when (featurep 'org-clock)
8382 (org-clock-save-markers-for-cut-and-paste beg end))
8383 (when (featurep 'org-agenda)
8384 (org-agenda-save-markers-for-cut-and-paste beg end)))
8386 (defun org-check-and-save-marker (marker beg end)
8387 "Check if MARKER is between BEG and END.
8388 If yes, remember the marker and the distance to BEG."
8389 (when (and (marker-buffer marker)
8390 (equal (marker-buffer marker) (current-buffer)))
8391 (if (and (>= marker beg) (< marker end))
8392 (push (cons marker (- marker beg)) org-markers-to-move))))
8394 (defun org-reinstall-markers-in-region (beg)
8395 "Move all remembered markers to their position relative to BEG."
8396 (mapc (lambda (x)
8397 (move-marker (car x) (+ beg (cdr x))))
8398 org-markers-to-move)
8399 (setq org-markers-to-move nil))
8401 (defun org-narrow-to-subtree ()
8402 "Narrow buffer to the current subtree."
8403 (interactive)
8404 (save-excursion
8405 (save-match-data
8406 (org-with-limited-levels
8407 (narrow-to-region
8408 (progn (org-back-to-heading t) (point))
8409 (progn (org-end-of-subtree t t)
8410 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8411 (point)))))))
8413 (defun org-narrow-to-block ()
8414 "Narrow buffer to the current block."
8415 (interactive)
8416 (let* ((case-fold-search t)
8417 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8418 "^[ \t]*#\\+end_.*")))
8419 (if blockp
8420 (narrow-to-region (car blockp) (cdr blockp))
8421 (user-error "Not in a block"))))
8423 (eval-when-compile
8424 (defvar org-property-drawer-re))
8426 (defvar org-property-start-re) ;; defined below
8427 (defun org-clone-subtree-with-time-shift (n &optional shift)
8428 "Clone the task (subtree) at point N times.
8429 The clones will be inserted as siblings.
8431 In interactive use, the user will be prompted for the number of
8432 clones to be produced. If the entry has a timestamp, the user
8433 will also be prompted for a time shift, which may be a repeater
8434 as used in time stamps, for example `+3d'. To disable this,
8435 you can call the function with a universal prefix argument.
8437 When a valid repeater is given and the entry contains any time
8438 stamps, the clones will become a sequence in time, with time
8439 stamps in the subtree shifted for each clone produced. If SHIFT
8440 is nil or the empty string, time stamps will be left alone. The
8441 ID property of the original subtree is removed.
8443 If the original subtree did contain time stamps with a repeater,
8444 the following will happen:
8445 - the repeater will be removed in each clone
8446 - an additional clone will be produced, with the current, unshifted
8447 date(s) in the entry.
8448 - the original entry will be placed *after* all the clones, with
8449 repeater intact.
8450 - the start days in the repeater in the original entry will be shifted
8451 to past the last clone.
8452 In this way you can spell out a number of instances of a repeating task,
8453 and still retain the repeater to cover future instances of the task."
8454 (interactive "nNumber of clones to produce: ")
8455 (let ((shift
8456 (or shift
8457 (if (and (not (equal current-prefix-arg '(4)))
8458 (save-excursion
8459 (re-search-forward org-ts-regexp-both
8460 (save-excursion
8461 (org-end-of-subtree t)
8462 (point)) t)))
8463 (read-from-minibuffer
8464 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8465 ""))) ;; No time shift
8466 (n-no-remove -1)
8467 (drawer-re org-drawer-regexp)
8468 beg end template task idprop
8469 shift-n shift-what doshift nmin nmax)
8470 (if (not (and (integerp n) (> n 0)))
8471 (error "Invalid number of replications %s" n))
8472 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8473 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8474 shift)))
8475 (error "Invalid shift specification %s" shift))
8476 (when doshift
8477 (setq shift-n (string-to-number (match-string 1 shift))
8478 shift-what (cdr (assoc (match-string 2 shift)
8479 '(("d" . day) ("w" . week)
8480 ("m" . month) ("y" . year))))))
8481 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8482 (setq nmin 1 nmax n)
8483 (org-back-to-heading t)
8484 (setq beg (point))
8485 (setq idprop (org-entry-get nil "ID"))
8486 (org-end-of-subtree t t)
8487 (or (bolp) (insert "\n"))
8488 (setq end (point))
8489 (setq template (buffer-substring beg end))
8490 (when (and doshift
8491 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8492 (delete-region beg end)
8493 (setq end beg)
8494 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8495 (goto-char end)
8496 (loop for n from nmin to nmax do
8497 ;; prepare clone
8498 (with-temp-buffer
8499 (insert template)
8500 (org-mode)
8501 (goto-char (point-min))
8502 (org-show-subtree)
8503 (and idprop (if org-clone-delete-id
8504 (org-entry-delete nil "ID")
8505 (org-id-get-create t)))
8506 (unless (= n 0)
8507 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8508 (kill-whole-line))
8509 (goto-char (point-min))
8510 (while (re-search-forward drawer-re nil t)
8511 (org-remove-empty-drawer-at (point))))
8512 (goto-char (point-min))
8513 (when doshift
8514 (while (re-search-forward org-ts-regexp-both nil t)
8515 (org-timestamp-change (* n shift-n) shift-what))
8516 (unless (= n n-no-remove)
8517 (goto-char (point-min))
8518 (while (re-search-forward org-ts-regexp nil t)
8519 (save-excursion
8520 (goto-char (match-beginning 0))
8521 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8522 (delete-region (match-beginning 1) (match-end 1)))))))
8523 (setq task (buffer-string)))
8524 (insert task))
8525 (goto-char beg)))
8527 ;;; Outline Sorting
8529 (defun org-sort (with-case)
8530 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8531 Optional argument WITH-CASE means sort case-sensitively."
8532 (interactive "P")
8533 (cond
8534 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8535 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8537 (org-call-with-arg 'org-sort-entries with-case))))
8539 (defun org-sort-remove-invisible (s)
8540 "Remove invisible links from string S."
8541 (remove-text-properties 0 (length s) org-rm-props s)
8542 (while (string-match org-bracket-link-regexp s)
8543 (setq s (replace-match (if (match-end 2)
8544 (match-string 3 s)
8545 (match-string 1 s)) t t s)))
8546 (let ((st (format " %s " s)))
8547 (while (string-match org-emph-re st)
8548 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8549 (setq s (substring st 1 -1)))
8552 (defvar org-priority-regexp) ; defined later in the file
8554 (defvar org-after-sorting-entries-or-items-hook nil
8555 "Hook that is run after a bunch of entries or items have been sorted.
8556 When children are sorted, the cursor is in the parent line when this
8557 hook gets called. When a region or a plain list is sorted, the cursor
8558 will be in the first entry of the sorted region/list.")
8560 (defun org-sort-entries
8561 (&optional with-case sorting-type getkey-func compare-func property)
8562 "Sort entries on a certain level of an outline tree.
8563 If there is an active region, the entries in the region are sorted.
8564 Else, if the cursor is before the first entry, sort the top-level items.
8565 Else, the children of the entry at point are sorted.
8567 Sorting can be alphabetically, numerically, by date/time as given by
8568 a time stamp, by a property, by priority order, or by a custom function.
8570 The command prompts for the sorting type unless it has been given to the
8571 function through the SORTING-TYPE argument, which needs to be a character,
8572 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8573 precise meaning of each character:
8575 n Numerically, by converting the beginning of the entry/item to a number.
8576 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8577 o By order of TODO keywords.
8578 t By date/time, either the first active time stamp in the entry, or, if
8579 none exist, by the first inactive one.
8580 s By the scheduled date/time.
8581 d By deadline date/time.
8582 c By creation time, which is assumed to be the first inactive time stamp
8583 at the beginning of a line.
8584 p By priority according to the cookie.
8585 r By the value of a property.
8587 Capital letters will reverse the sort order.
8589 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8590 called with point at the beginning of the record. It must return either
8591 a string or a number that should serve as the sorting key for that record.
8593 Comparing entries ignores case by default. However, with an optional argument
8594 WITH-CASE, the sorting considers case as well.
8596 Sorting is done against the visible part of the headlines, it ignores hidden
8597 links."
8598 (interactive "P")
8599 (let ((case-func (if with-case 'identity 'downcase))
8600 (cmstr
8601 ;; The clock marker is lost when using `sort-subr', let's
8602 ;; store the clocking string.
8603 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8604 (save-excursion
8605 (goto-char org-clock-marker)
8606 (looking-back "^.*") (match-string-no-properties 0))))
8607 start beg end stars re re2
8608 txt what tmp)
8609 ;; Find beginning and end of region to sort
8610 (cond
8611 ((org-region-active-p)
8612 ;; we will sort the region
8613 (setq end (region-end)
8614 what "region")
8615 (goto-char (region-beginning))
8616 (if (not (org-at-heading-p)) (outline-next-heading))
8617 (setq start (point)))
8618 ((or (org-at-heading-p)
8619 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8620 ;; we will sort the children of the current headline
8621 (org-back-to-heading)
8622 (setq start (point)
8623 end (progn (org-end-of-subtree t t)
8624 (or (bolp) (insert "\n"))
8625 (org-back-over-empty-lines)
8626 (point))
8627 what "children")
8628 (goto-char start)
8629 (show-subtree)
8630 (outline-next-heading))
8632 ;; we will sort the top-level entries in this file
8633 (goto-char (point-min))
8634 (or (org-at-heading-p) (outline-next-heading))
8635 (setq start (point))
8636 (goto-char (point-max))
8637 (beginning-of-line 1)
8638 (when (looking-at ".*?\\S-")
8639 ;; File ends in a non-white line
8640 (end-of-line 1)
8641 (insert "\n"))
8642 (setq end (point-max))
8643 (setq what "top-level")
8644 (goto-char start)
8645 (show-all)))
8647 (setq beg (point))
8648 (if (>= beg end) (user-error "Nothing to sort"))
8650 (looking-at "\\(\\*+\\)")
8651 (setq stars (match-string 1)
8652 re (concat "^" (regexp-quote stars) " +")
8653 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8654 txt (buffer-substring beg end))
8655 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8656 (if (and (not (equal stars "*")) (string-match re2 txt))
8657 (user-error "Region to sort contains a level above the first entry"))
8659 (unless sorting-type
8660 (message
8661 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8662 [t]ime [s]cheduled [d]eadline [c]reated
8663 A/N/P/R/O/F/T/S/D/C means reversed:"
8664 what)
8665 (setq sorting-type (read-char-exclusive))
8667 (unless getkey-func
8668 (and (= (downcase sorting-type) ?f)
8669 (setq getkey-func
8670 (org-icompleting-read "Sort using function: "
8671 obarray 'fboundp t nil nil))
8672 (setq getkey-func (intern getkey-func))))
8674 (and (= (downcase sorting-type) ?r)
8675 (not property)
8676 (setq property
8677 (org-icompleting-read "Property: "
8678 (mapcar 'list (org-buffer-property-keys t))
8679 nil t))))
8681 (message "Sorting entries...")
8683 (save-restriction
8684 (narrow-to-region start end)
8685 (let ((dcst (downcase sorting-type))
8686 (case-fold-search nil)
8687 (now (current-time)))
8688 (sort-subr
8689 (/= dcst sorting-type)
8690 ;; This function moves to the beginning character of the "record" to
8691 ;; be sorted.
8692 (lambda nil
8693 (if (re-search-forward re nil t)
8694 (goto-char (match-beginning 0))
8695 (goto-char (point-max))))
8696 ;; This function moves to the last character of the "record" being
8697 ;; sorted.
8698 (lambda nil
8699 (save-match-data
8700 (condition-case nil
8701 (outline-forward-same-level 1)
8702 (error
8703 (goto-char (point-max))))))
8704 ;; This function returns the value that gets sorted against.
8705 (lambda nil
8706 (cond
8707 ((= dcst ?n)
8708 (if (looking-at org-complex-heading-regexp)
8709 (string-to-number (org-sort-remove-invisible (match-string 4)))
8710 nil))
8711 ((= dcst ?a)
8712 (if (looking-at org-complex-heading-regexp)
8713 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8714 nil))
8715 ((= dcst ?t)
8716 (let ((end (save-excursion (outline-next-heading) (point))))
8717 (if (or (re-search-forward org-ts-regexp end t)
8718 (re-search-forward org-ts-regexp-both end t))
8719 (org-time-string-to-seconds (match-string 0))
8720 (org-float-time now))))
8721 ((= dcst ?c)
8722 (let ((end (save-excursion (outline-next-heading) (point))))
8723 (if (re-search-forward
8724 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8725 end t)
8726 (org-time-string-to-seconds (match-string 0))
8727 (org-float-time now))))
8728 ((= dcst ?s)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (re-search-forward org-scheduled-time-regexp end t)
8731 (org-time-string-to-seconds (match-string 1))
8732 (org-float-time now))))
8733 ((= dcst ?d)
8734 (let ((end (save-excursion (outline-next-heading) (point))))
8735 (if (re-search-forward org-deadline-time-regexp end t)
8736 (org-time-string-to-seconds (match-string 1))
8737 (org-float-time now))))
8738 ((= dcst ?p)
8739 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8740 (string-to-char (match-string 2))
8741 org-default-priority))
8742 ((= dcst ?r)
8743 (or (org-entry-get nil property) ""))
8744 ((= dcst ?o)
8745 (if (looking-at org-complex-heading-regexp)
8746 (- 9999 (length (member (match-string 2)
8747 org-todo-keywords-1)))))
8748 ((= dcst ?f)
8749 (if getkey-func
8750 (progn
8751 (setq tmp (funcall getkey-func))
8752 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8753 tmp)
8754 (error "Invalid key function `%s'" getkey-func)))
8755 (t (error "Invalid sorting type `%c'" sorting-type))))
8757 (cond
8758 ((= dcst ?a) 'string<)
8759 ((= dcst ?f) compare-func)
8760 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8761 (run-hooks 'org-after-sorting-entries-or-items-hook)
8762 ;; Reset the clock marker if needed
8763 (when cmstr
8764 (save-excursion
8765 (goto-char start)
8766 (search-forward cmstr nil t)
8767 (move-marker org-clock-marker (point))))
8768 (message "Sorting entries...done")))
8770 (defun org-do-sort (table what &optional with-case sorting-type)
8771 "Sort TABLE of WHAT according to SORTING-TYPE.
8772 The user will be prompted for the SORTING-TYPE if the call to this
8773 function does not specify it. WHAT is only for the prompt, to indicate
8774 what is being sorted. The sorting key will be extracted from
8775 the car of the elements of the table.
8776 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8777 (unless sorting-type
8778 (message
8779 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8780 what)
8781 (setq sorting-type (read-char-exclusive)))
8782 (let ((dcst (downcase sorting-type))
8783 extractfun comparefun)
8784 ;; Define the appropriate functions
8785 (cond
8786 ((= dcst ?n)
8787 (setq extractfun 'string-to-number
8788 comparefun (if (= dcst sorting-type) '< '>)))
8789 ((= dcst ?a)
8790 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8791 (lambda(x) (downcase (org-sort-remove-invisible x))))
8792 comparefun (if (= dcst sorting-type)
8793 'string<
8794 (lambda (a b) (and (not (string< a b))
8795 (not (string= a b)))))))
8796 ((= dcst ?t)
8797 (setq extractfun
8798 (lambda (x)
8799 (if (or (string-match org-ts-regexp x)
8800 (string-match org-ts-regexp-both x))
8801 (org-float-time
8802 (org-time-string-to-time (match-string 0 x)))
8804 comparefun (if (= dcst sorting-type) '< '>)))
8805 (t (error "Invalid sorting type `%c'" sorting-type)))
8807 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8808 table)
8809 (lambda (a b) (funcall comparefun (car a) (car b))))))
8812 ;;; The orgstruct minor mode
8814 ;; Define a minor mode which can be used in other modes in order to
8815 ;; integrate the org-mode structure editing commands.
8817 ;; This is really a hack, because the org-mode structure commands use
8818 ;; keys which normally belong to the major mode. Here is how it
8819 ;; works: The minor mode defines all the keys necessary to operate the
8820 ;; structure commands, but wraps the commands into a function which
8821 ;; tests if the cursor is currently at a headline or a plain list
8822 ;; item. If that is the case, the structure command is used,
8823 ;; temporarily setting many Org-mode variables like regular
8824 ;; expressions for filling etc. However, when any of those keys is
8825 ;; used at a different location, function uses `key-binding' to look
8826 ;; up if the key has an associated command in another currently active
8827 ;; keymap (minor modes, major mode, global), and executes that
8828 ;; command. There might be problems if any of the keys is otherwise
8829 ;; used as a prefix key.
8831 (defcustom orgstruct-heading-prefix-regexp nil
8832 "Regexp that matches the custom prefix of Org headlines in
8833 orgstruct(++)-mode."
8834 :group 'org
8835 :version "24.4"
8836 :package-version '(Org . "8.0")
8837 :type 'string)
8838 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8840 (defcustom orgstruct-setup-hook nil
8841 "Hook run after orgstruct-mode-map is filled."
8842 :group 'org
8843 :version "24.4"
8844 :package-version '(Org . "8.0")
8845 :type 'hook)
8847 (defvar orgstruct-initialized nil)
8849 (defvar org-local-vars nil
8850 "List of local variables, for use by `orgstruct-mode'.")
8852 ;;;###autoload
8853 (define-minor-mode orgstruct-mode
8854 "Toggle the minor mode `orgstruct-mode'.
8855 This mode is for using Org-mode structure commands in other
8856 modes. The following keys behave as if Org-mode were active, if
8857 the cursor is on a headline, or on a plain list item (both as
8858 defined by Org-mode)."
8859 nil " OrgStruct" (make-sparse-keymap)
8860 (funcall (if orgstruct-mode
8861 'add-to-invisibility-spec
8862 'remove-from-invisibility-spec)
8863 '(outline . t))
8864 (when orgstruct-mode
8865 (org-load-modules-maybe)
8866 (unless orgstruct-initialized
8867 (orgstruct-setup)
8868 (setq orgstruct-initialized t))))
8870 ;;;###autoload
8871 (defun turn-on-orgstruct ()
8872 "Unconditionally turn on `orgstruct-mode'."
8873 (orgstruct-mode 1))
8875 (defvar org-fb-vars nil)
8876 (make-variable-buffer-local 'org-fb-vars)
8877 (defun orgstruct++-mode (&optional arg)
8878 "Toggle `orgstruct-mode', the enhanced version of it.
8879 In addition to setting orgstruct-mode, this also exports all
8880 indentation and autofilling variables from org-mode into the
8881 buffer. It will also recognize item context in multiline items."
8882 (interactive "P")
8883 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8884 (if (< arg 1)
8885 (progn (orgstruct-mode -1)
8886 (mapc (lambda(v)
8887 (org-set-local (car v)
8888 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8889 org-fb-vars))
8890 (orgstruct-mode 1)
8891 (setq org-fb-vars nil)
8892 (unless org-local-vars
8893 (setq org-local-vars (org-get-local-variables)))
8894 (let (var val)
8895 (mapc
8896 (lambda (x)
8897 (when (string-match
8898 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8899 (symbol-name (car x)))
8900 (setq var (car x) val (nth 1 x))
8901 (push (list var `(quote ,(eval var))) org-fb-vars)
8902 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8903 org-local-vars)
8904 (org-set-local 'orgstruct-is-++ t))))
8906 (defvar orgstruct-is-++ nil
8907 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8908 (make-variable-buffer-local 'orgstruct-is-++)
8910 ;;;###autoload
8911 (defun turn-on-orgstruct++ ()
8912 "Unconditionally turn on `orgstruct++-mode'."
8913 (orgstruct++-mode 1))
8915 (defun orgstruct-error ()
8916 "Error when there is no default binding for a structure key."
8917 (interactive)
8918 (funcall (if (fboundp 'user-error)
8919 'user-error
8920 'error)
8921 "This key has no function outside structure elements"))
8923 (defun orgstruct-setup ()
8924 "Setup orgstruct keymap."
8925 (dolist (cell '((org-demote . t)
8926 (org-metaleft . t)
8927 (org-metaright . t)
8928 (org-promote . t)
8929 (org-shiftmetaleft . t)
8930 (org-shiftmetaright . t)
8931 org-backward-element
8932 org-backward-heading-same-level
8933 org-ctrl-c-ret
8934 org-ctrl-c-minus
8935 org-ctrl-c-star
8936 org-cycle
8937 org-forward-heading-same-level
8938 org-insert-heading
8939 org-insert-heading-respect-content
8940 org-kill-note-or-show-branches
8941 org-mark-subtree
8942 org-meta-return
8943 org-metadown
8944 org-metaup
8945 org-narrow-to-subtree
8946 org-promote-subtree
8947 org-reveal
8948 org-shiftdown
8949 org-shiftleft
8950 org-shiftmetadown
8951 org-shiftmetaup
8952 org-shiftright
8953 org-shifttab
8954 org-shifttab
8955 org-shiftup
8956 org-show-subtree
8957 org-sort
8958 org-up-element
8959 outline-demote
8960 outline-next-visible-heading
8961 outline-previous-visible-heading
8962 outline-promote
8963 outline-up-heading
8964 show-children))
8965 (let ((f (or (car-safe cell) cell))
8966 (disable-when-heading-prefix (cdr-safe cell)))
8967 (when (fboundp f)
8968 (let ((new-bindings))
8969 (dolist (binding (nconc (where-is-internal f org-mode-map)
8970 (where-is-internal f outline-mode-map)))
8971 (push binding new-bindings)
8972 ;; TODO use local-function-key-map
8973 (dolist (rep '(("<tab>" . "TAB")
8974 ("<return>" . "RET")
8975 ("<escape>" . "ESC")
8976 ("<delete>" . "DEL")))
8977 (setq binding (read-kbd-macro
8978 (let ((case-fold-search))
8979 (replace-regexp-in-string
8980 (regexp-quote (cdr rep))
8981 (car rep)
8982 (key-description binding)))))
8983 (pushnew binding new-bindings :test 'equal)))
8984 (dolist (binding new-bindings)
8985 (let ((key (lookup-key orgstruct-mode-map binding)))
8986 (when (or (not key) (numberp key))
8987 (condition-case nil
8988 (org-defkey orgstruct-mode-map
8989 binding
8990 (orgstruct-make-binding f binding disable-when-heading-prefix))
8991 (error nil)))))))))
8992 (run-hooks 'orgstruct-setup-hook))
8994 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8995 "Create a function for binding in the structure minor mode.
8996 FUN is the command to call inside a table. KEY is the key that
8997 should be checked in for a command to execute outside of tables.
8998 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8999 if `orgstruct-heading-prefix-regexp' is non-nil."
9000 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9001 (let ((nname name)
9002 (i 0))
9003 (while (fboundp (intern nname))
9004 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9005 (setq name (intern nname)))
9006 (eval
9007 (let ((bindings '((org-heading-regexp
9008 (concat "^"
9009 orgstruct-heading-prefix-regexp
9010 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9011 (org-outline-regexp
9012 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9013 (org-outline-regexp-bol
9014 (concat "^" org-outline-regexp))
9015 (outline-regexp org-outline-regexp)
9016 (outline-heading-end-regexp "\n")
9017 (outline-level 'org-outline-level)
9018 (outline-heading-alist))))
9019 `(defun ,name (arg)
9020 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9021 "Outside of structure, run the binding of `"
9022 (key-description key) "'."
9023 (when disable-when-heading-prefix
9024 (concat
9025 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9026 "back to the default binding due to limitations of Org's implementation of\n"
9027 "`" (symbol-name fun) "'.")))
9028 (interactive "p")
9029 (let* ((disable
9030 ,(when disable-when-heading-prefix
9031 '(and orgstruct-heading-prefix-regexp
9032 (not (string= orgstruct-heading-prefix-regexp "")))))
9033 (fallback
9034 (or disable
9035 (not
9036 (let* ,bindings
9037 (org-context-p 'headline 'item
9038 ,(when (memq fun
9039 '(org-insert-heading
9040 org-insert-heading-respect-content
9041 org-meta-return))
9042 '(when orgstruct-is-++
9043 'item-body))))))))
9044 (if fallback
9045 (let* ((orgstruct-mode)
9046 (binding
9047 (loop with key = ,key
9048 for rep in
9049 '(nil
9050 ("<\\([^>]*\\)tab>" . "\\1TAB")
9051 ("<\\([^>]*\\)return>" . "\\1RET")
9052 ("<\\([^>]*\\)escape>" . "\\1ESC")
9053 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9055 (when rep
9056 (setq key (read-kbd-macro
9057 (let ((case-fold-search))
9058 (replace-regexp-in-string
9059 (car rep)
9060 (cdr rep)
9061 (key-description key))))))
9062 thereis (key-binding key))))
9063 (if (keymapp binding)
9064 (set-temporary-overlay-map binding)
9065 (let ((func (or binding
9066 (unless disable
9067 'orgstruct-error))))
9068 (when func
9069 (call-interactively func)))))
9070 (org-run-like-in-org-mode
9071 (lambda ()
9072 (interactive)
9073 (let* ,bindings
9074 (call-interactively ',fun)))))))))
9075 name))
9077 (defun org-contextualize-keys (alist contexts)
9078 "Return valid elements in ALIST depending on CONTEXTS.
9080 `org-agenda-custom-commands' or `org-capture-templates' are the
9081 values used for ALIST, and `org-agenda-custom-commands-contexts'
9082 or `org-capture-templates-contexts' are the associated contexts
9083 definitions."
9084 (let ((contexts
9085 ;; normalize contexts
9086 (mapcar
9087 (lambda(c) (cond ((listp (cadr c))
9088 (list (car c) (car c) (cadr c)))
9089 ((string= "" (cadr c))
9090 (list (car c) (car c) (caddr c)))
9091 (t c))) contexts))
9092 (a alist) c r s)
9093 ;; loop over all commands or templates
9094 (while (setq c (pop a))
9095 (let (vrules repl)
9096 (cond
9097 ((not (assoc (car c) contexts))
9098 (push c r))
9099 ((and (assoc (car c) contexts)
9100 (setq vrules (org-contextualize-validate-key
9101 (car c) contexts)))
9102 (mapc (lambda (vr)
9103 (when (not (equal (car vr) (cadr vr)))
9104 (setq repl vr))) vrules)
9105 (if (not repl) (push c r)
9106 (push (cadr repl) s)
9107 (push
9108 (cons (car c)
9109 (cdr (or (assoc (cadr repl) alist)
9110 (error "Undefined key `%s' as contextual replacement for `%s'"
9111 (cadr repl) (car c)))))
9112 r))))))
9113 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9114 (delq
9116 (delete-dups
9117 (mapcar (lambda (x)
9118 (let ((tpl (car x)))
9119 (when (not (delq
9121 (mapcar (lambda(y)
9122 (equal y tpl)) s))) x)))
9123 (reverse r))))))
9125 (defun org-contextualize-validate-key (key contexts)
9126 "Check CONTEXTS for agenda or capture KEY."
9127 (let (r rr res)
9128 (while (setq r (pop contexts))
9129 (mapc
9130 (lambda (rr)
9131 (when
9132 (and (equal key (car r))
9133 (if (functionp rr) (funcall rr)
9134 (or (and (eq (car rr) 'in-file)
9135 (buffer-file-name)
9136 (string-match (cdr rr) (buffer-file-name)))
9137 (and (eq (car rr) 'in-mode)
9138 (string-match (cdr rr) (symbol-name major-mode)))
9139 (and (eq (car rr) 'in-buffer)
9140 (string-match (cdr rr) (buffer-name)))
9141 (when (and (eq (car rr) 'not-in-file)
9142 (buffer-file-name))
9143 (not (string-match (cdr rr) (buffer-file-name))))
9144 (when (eq (car rr) 'not-in-mode)
9145 (not (string-match (cdr rr) (symbol-name major-mode))))
9146 (when (eq (car rr) 'not-in-buffer)
9147 (not (string-match (cdr rr) (buffer-name)))))))
9148 (push r res)))
9149 (car (last r))))
9150 (delete-dups (delq nil res))))
9152 (defun org-context-p (&rest contexts)
9153 "Check if local context is any of CONTEXTS.
9154 Possible values in the list of contexts are `table', `headline', and `item'."
9155 (let ((pos (point)))
9156 (goto-char (point-at-bol))
9157 (prog1 (or (and (memq 'table contexts)
9158 (looking-at "[ \t]*|"))
9159 (and (memq 'headline contexts)
9160 (looking-at org-outline-regexp))
9161 (and (memq 'item contexts)
9162 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9163 (and (memq 'item-body contexts)
9164 (org-in-item-p)))
9165 (goto-char pos))))
9167 (defun org-get-local-variables ()
9168 "Return a list of all local variables in an Org mode buffer."
9169 (let (varlist)
9170 (with-current-buffer (get-buffer-create "*Org tmp*")
9171 (erase-buffer)
9172 (org-mode)
9173 (setq varlist (buffer-local-variables)))
9174 (kill-buffer "*Org tmp*")
9175 (delq nil
9176 (mapcar
9177 (lambda (x)
9178 (setq x
9179 (if (symbolp x)
9180 (list x)
9181 (list (car x) (cdr x))))
9182 (if (and (not (get (car x) 'org-state))
9183 (string-match
9184 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9185 (symbol-name (car x))))
9186 x nil))
9187 varlist))))
9189 (defun org-clone-local-variables (from-buffer &optional regexp)
9190 "Clone local variables from FROM-BUFFER.
9191 Optional argument REGEXP selects variables to clone."
9192 (mapc
9193 (lambda (pair)
9194 (and (symbolp (car pair))
9195 (or (null regexp)
9196 (string-match regexp (symbol-name (car pair))))
9197 (set (make-local-variable (car pair))
9198 (cdr pair))))
9199 (buffer-local-variables from-buffer)))
9201 ;;;###autoload
9202 (defun org-run-like-in-org-mode (cmd)
9203 "Run a command, pretending that the current buffer is in Org-mode.
9204 This will temporarily bind local variables that are typically bound in
9205 Org-mode to the values they have in Org-mode, and then interactively
9206 call CMD."
9207 (org-load-modules-maybe)
9208 (unless org-local-vars
9209 (setq org-local-vars (org-get-local-variables)))
9210 (let (binds)
9211 (dolist (var org-local-vars)
9212 (when (or (not (boundp (car var)))
9213 (eq (symbol-value (car var))
9214 (default-value (car var))))
9215 (push (list (car var) `(quote ,(cadr var))) binds)))
9216 (eval `(let ,binds
9217 (call-interactively (quote ,cmd))))))
9219 ;;;; Archiving
9221 (defun org-get-category (&optional pos force-refresh)
9222 "Get the category applying to position POS."
9223 (save-match-data
9224 (if force-refresh (org-refresh-category-properties))
9225 (let ((pos (or pos (point))))
9226 (or (get-text-property pos 'org-category)
9227 (progn (org-refresh-category-properties)
9228 (get-text-property pos 'org-category))))))
9230 (defun org-refresh-category-properties ()
9231 "Refresh category text properties in the buffer."
9232 (let ((case-fold-search t)
9233 (inhibit-read-only t)
9234 (def-cat (cond
9235 ((null org-category)
9236 (if buffer-file-name
9237 (file-name-sans-extension
9238 (file-name-nondirectory buffer-file-name))
9239 "???"))
9240 ((symbolp org-category) (symbol-name org-category))
9241 (t org-category)))
9242 beg end cat pos optionp)
9243 (org-with-silent-modifications
9244 (save-excursion
9245 (save-restriction
9246 (widen)
9247 (goto-char (point-min))
9248 (put-text-property (point) (point-max) 'org-category def-cat)
9249 (while (re-search-forward
9250 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9251 (setq pos (match-end 0)
9252 optionp (equal (char-after (match-beginning 0)) ?#)
9253 cat (org-trim (match-string 2)))
9254 (if optionp
9255 (setq beg (point-at-bol) end (point-max))
9256 (org-back-to-heading t)
9257 (setq beg (point) end (org-end-of-subtree t t)))
9258 (put-text-property beg end 'org-category cat)
9259 (put-text-property beg end 'org-category-position beg)
9260 (goto-char pos)))))))
9262 (defun org-refresh-properties (dprop tprop)
9263 "Refresh buffer text properties.
9264 DPROP is the drawer property and TPROP is the corresponding text
9265 property to set."
9266 (let ((case-fold-search t)
9267 (inhibit-read-only t) p)
9268 (org-with-silent-modifications
9269 (save-excursion
9270 (save-restriction
9271 (widen)
9272 (goto-char (point-min))
9273 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9274 (setq p (org-match-string-no-properties 1))
9275 (save-excursion
9276 (org-back-to-heading t)
9277 (put-text-property
9278 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9281 ;;;; Link Stuff
9283 ;;; Link abbreviations
9285 (defun org-link-expand-abbrev (link)
9286 "Apply replacements as defined in `org-link-abbrev-alist'."
9287 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9288 (let* ((key (match-string 1 link))
9289 (as (or (assoc key org-link-abbrev-alist-local)
9290 (assoc key org-link-abbrev-alist)))
9291 (tag (and (match-end 2) (match-string 3 link)))
9292 rpl)
9293 (if (not as)
9294 link
9295 (setq rpl (cdr as))
9296 (cond
9297 ((symbolp rpl) (funcall rpl tag))
9298 ((string-match "%(\\([^)]+\\))" rpl)
9299 (replace-match
9300 (save-match-data
9301 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9302 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9303 ((string-match "%h" rpl)
9304 (replace-match (url-hexify-string (or tag "")) t t rpl))
9305 (t (concat rpl tag)))))
9306 link))
9308 ;;; Storing and inserting links
9310 (defvar org-insert-link-history nil
9311 "Minibuffer history for links inserted with `org-insert-link'.")
9313 (defvar org-stored-links nil
9314 "Contains the links stored with `org-store-link'.")
9316 (defvar org-store-link-plist nil
9317 "Plist with info about the most recently link created with `org-store-link'.")
9319 (defvar org-link-protocols nil
9320 "Link protocols added to Org-mode using `org-add-link-type'.")
9322 (defvar org-store-link-functions nil
9323 "List of functions that are called to create and store a link.
9324 Each function will be called in turn until one returns a non-nil
9325 value. Each function should check if it is responsible for creating
9326 this link (for example by looking at the major mode).
9327 If not, it must exit and return nil.
9328 If yes, it should return a non-nil value after a calling
9329 `org-store-link-props' with a list of properties and values.
9330 Special properties are:
9332 :type The link prefix, like \"http\". This must be given.
9333 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9334 This is obligatory as well.
9335 :description Optional default description for the second pair
9336 of brackets in an Org-mode link. The user can still change
9337 this when inserting this link into an Org-mode buffer.
9339 In addition to these, any additional properties can be specified
9340 and then used in capture templates.")
9342 (defun org-add-link-type (type &optional follow export)
9343 "Add TYPE to the list of `org-link-types'.
9344 Re-compute all regular expressions depending on `org-link-types'
9346 FOLLOW and EXPORT are two functions.
9348 FOLLOW should take the link path as the single argument and do whatever
9349 is necessary to follow the link, for example find a file or display
9350 a mail message.
9352 EXPORT should format the link path for export to one of the export formats.
9353 It should be a function accepting three arguments:
9355 path the path of the link, the text after the prefix (like \"http:\")
9356 desc the description of the link, if any, or a description added by
9357 org-export-normalize-links if there is none
9358 format the export format, a symbol like `html' or `latex' or `ascii'..
9360 The function may use the FORMAT information to return different values
9361 depending on the format. The return value will be put literally into
9362 the exported file. If the return value is nil, this means Org should
9363 do what it normally does with links which do not have EXPORT defined.
9365 Org-mode has a built-in default for exporting links. If you are happy with
9366 this default, there is no need to define an export function for the link
9367 type. For a simple example of an export function, see `org-bbdb.el'."
9368 (add-to-list 'org-link-types type t)
9369 (org-make-link-regexps)
9370 (if (assoc type org-link-protocols)
9371 (setcdr (assoc type org-link-protocols) (list follow export))
9372 (push (list type follow export) org-link-protocols)))
9374 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9375 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9377 ;;;###autoload
9378 (defun org-store-link (arg)
9379 "\\<org-mode-map>Store an org-link to the current location.
9380 This link is added to `org-stored-links' and can later be inserted
9381 into an org-buffer with \\[org-insert-link].
9383 For some link types, a prefix arg is interpreted.
9384 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9385 For file links, arg negates `org-context-in-file-links'.
9387 A double prefix arg force skipping storing functions that are not
9388 part of Org's core.
9390 A triple prefix arg force storing a link for each line in the
9391 active region."
9392 (interactive "P")
9393 (org-load-modules-maybe)
9394 (if (and (equal arg '(64)) (org-region-active-p))
9395 (save-excursion
9396 (let ((end (region-end)))
9397 (goto-char (region-beginning))
9398 (set-mark (point))
9399 (while (< (point-at-eol) end)
9400 (move-end-of-line 1) (activate-mark)
9401 (let (current-prefix-arg)
9402 (call-interactively 'org-store-link))
9403 (move-beginning-of-line 2)
9404 (set-mark (point)))))
9405 (org-with-limited-levels
9406 (setq org-store-link-plist nil)
9407 (let (link cpltxt desc description search
9408 txt custom-id agenda-link sfuns sfunsn)
9409 (cond
9411 ;; Store a link using an external link type
9412 ((and (not (equal arg '(16)))
9413 (setq sfuns
9414 (delq
9415 nil (mapcar (lambda (f)
9416 (let (fs) (if (funcall f) (push f fs))))
9417 org-store-link-functions))
9418 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9419 (or (and (cdr sfuns)
9420 (funcall (intern
9421 (completing-read
9422 "Which function for creating the link? "
9423 sfunsn t (car sfunsn)))))
9424 (funcall (caar sfuns)))
9425 (setq link (plist-get org-store-link-plist :link)
9426 desc (or (plist-get org-store-link-plist
9427 :description) link))))
9429 ;; Store a link from a source code buffer
9430 ((org-src-edit-buffer-p)
9431 (let (label gc)
9432 (while (or (not label)
9433 (save-excursion
9434 (save-restriction
9435 (widen)
9436 (goto-char (point-min))
9437 (re-search-forward
9438 (regexp-quote (format org-coderef-label-format label))
9439 nil t))))
9440 (when label (message "Label exists already") (sit-for 2))
9441 (setq label (read-string "Code line label: " label)))
9442 (end-of-line 1)
9443 (setq link (format org-coderef-label-format label))
9444 (setq gc (- 79 (length link)))
9445 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9446 (insert link)
9447 (setq link (concat "(" label ")") desc nil)))
9449 ;; We are in the agenda, link to referenced location
9450 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9451 (let ((m (or (get-text-property (point) 'org-hd-marker)
9452 (get-text-property (point) 'org-marker))))
9453 (when m
9454 (org-with-point-at m
9455 (setq agenda-link
9456 (if (org-called-interactively-p 'any)
9457 (call-interactively 'org-store-link)
9458 (org-store-link nil)))))))
9460 ((eq major-mode 'calendar-mode)
9461 (let ((cd (calendar-cursor-to-date)))
9462 (setq link
9463 (format-time-string
9464 (car org-time-stamp-formats)
9465 (apply 'encode-time
9466 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9467 nil nil nil))))
9468 (org-store-link-props :type "calendar" :date cd)))
9470 ((eq major-mode 'help-mode)
9471 (setq link (concat "help:" (save-excursion
9472 (goto-char (point-min))
9473 (looking-at "^[^ ]+")
9474 (match-string 0))))
9475 (org-store-link-props :type "help"))
9477 ((eq major-mode 'w3-mode)
9478 (setq cpltxt (if (and (buffer-name)
9479 (not (string-match "Untitled" (buffer-name))))
9480 (buffer-name)
9481 (url-view-url t))
9482 link (url-view-url t))
9483 (org-store-link-props :type "w3" :url (url-view-url t)))
9485 ((eq major-mode 'image-mode)
9486 (setq cpltxt (concat "file:"
9487 (abbreviate-file-name buffer-file-name))
9488 link cpltxt)
9489 (org-store-link-props :type "image" :file buffer-file-name))
9491 ;; In dired, store a link to the file of the current line
9492 ((eq major-mode 'dired-mode)
9493 (let ((file (dired-get-filename nil t)))
9494 (setq file (if file
9495 (abbreviate-file-name
9496 (expand-file-name (dired-get-filename nil t)))
9497 ;; otherwise, no file so use current directory.
9498 default-directory))
9499 (setq cpltxt (concat "file:" file)
9500 link cpltxt)))
9502 ((setq search (run-hook-with-args-until-success
9503 'org-create-file-search-functions))
9504 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9505 "::" search))
9506 (setq cpltxt (or description link)))
9508 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9509 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9510 (cond
9511 ;; Store a link using the target at point
9512 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9513 (setq cpltxt
9514 (concat "file:"
9515 (abbreviate-file-name
9516 (buffer-file-name (buffer-base-buffer)))
9517 "::" (match-string 1))
9518 link cpltxt))
9519 ((and (featurep 'org-id)
9520 (or (eq org-id-link-to-org-use-id t)
9521 (and (org-called-interactively-p 'any)
9522 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9523 (and (eq org-id-link-to-org-use-id
9524 'create-if-interactive-and-no-custom-id)
9525 (not custom-id))))
9526 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9527 ;; Store a link using the ID at point
9528 (setq link (condition-case nil
9529 (prog1 (org-id-store-link)
9530 (setq desc (plist-get org-store-link-plist
9531 :description)))
9532 (error
9533 ;; Probably before first headline, link only to file
9534 (concat "file:"
9535 (abbreviate-file-name
9536 (buffer-file-name (buffer-base-buffer))))))))
9538 ;; Just link to current headline
9539 (setq cpltxt (concat "file:"
9540 (abbreviate-file-name
9541 (buffer-file-name (buffer-base-buffer)))))
9542 ;; Add a context search string
9543 (when (org-xor org-context-in-file-links arg)
9544 (let* ((ee (org-element-at-point))
9545 (et (org-element-type ee))
9546 (ev (plist-get (cadr ee) :value))
9547 (ek (plist-get (cadr ee) :key))
9548 (eok (and (stringp ek) (string-match "name" ek))))
9549 (setq txt (cond
9550 ((org-at-heading-p) nil)
9551 ((and (eq et 'keyword) eok) ev)
9552 ((org-region-active-p)
9553 (buffer-substring (region-beginning) (region-end)))))
9554 (when (or (null txt) (string-match "\\S-" txt))
9555 (setq cpltxt
9556 (concat cpltxt "::"
9557 (condition-case nil
9558 (org-make-org-heading-search-string txt)
9559 (error "")))
9560 desc (or (and (eq et 'keyword) eok ev)
9561 (nth 4 (ignore-errors (org-heading-components)))
9562 "NONE")))))
9563 (if (string-match "::\\'" cpltxt)
9564 (setq cpltxt (substring cpltxt 0 -2)))
9565 (setq link cpltxt))))
9567 ((buffer-file-name (buffer-base-buffer))
9568 ;; Just link to this file here.
9569 (setq cpltxt (concat "file:"
9570 (abbreviate-file-name
9571 (buffer-file-name (buffer-base-buffer)))))
9572 ;; Add a context string.
9573 (when (org-xor org-context-in-file-links arg)
9574 (setq txt (if (org-region-active-p)
9575 (buffer-substring (region-beginning) (region-end))
9576 (buffer-substring (point-at-bol) (point-at-eol))))
9577 ;; Only use search option if there is some text.
9578 (when (string-match "\\S-" txt)
9579 (setq cpltxt
9580 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9581 desc "NONE")))
9582 (setq link cpltxt))
9584 ((org-called-interactively-p 'interactive)
9585 (user-error "No method for storing a link from this buffer"))
9587 (t (setq link nil)))
9589 ;; We're done setting link and desc, clean up
9590 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9591 (setq link (or link cpltxt)
9592 desc (or desc cpltxt))
9593 (cond ((equal desc "NONE") (setq desc nil))
9594 ((string-match org-bracket-link-analytic-regexp desc)
9595 (let ((d0 (match-string 3 desc))
9596 (p0 (match-string 5 desc)))
9597 (setq desc
9598 (replace-regexp-in-string
9599 org-bracket-link-regexp
9600 (concat (or p0 d0)
9601 (if (equal (length (match-string 0 desc))
9602 (length desc)) "*" "")) desc)))))
9604 ;; Return the link
9605 (if (not (and (or (org-called-interactively-p 'any)
9606 executing-kbd-macro) link))
9607 (or agenda-link (and link (org-make-link-string link desc)))
9608 (push (list link desc) org-stored-links)
9609 (message "Stored: %s" (or desc link))
9610 (when custom-id
9611 (setq link (concat "file:" (abbreviate-file-name
9612 (buffer-file-name)) "::#" custom-id))
9613 (push (list link desc) org-stored-links)))))))
9615 (defun org-store-link-props (&rest plist)
9616 "Store link properties, extract names and addresses."
9617 (let (x adr)
9618 (when (setq x (plist-get plist :from))
9619 (setq adr (mail-extract-address-components x))
9620 (setq plist (plist-put plist :fromname (car adr)))
9621 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9622 (when (setq x (plist-get plist :to))
9623 (setq adr (mail-extract-address-components x))
9624 (setq plist (plist-put plist :toname (car adr)))
9625 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9626 (let ((from (plist-get plist :from))
9627 (to (plist-get plist :to)))
9628 (when (and from to org-from-is-user-regexp)
9629 (setq plist
9630 (plist-put plist :fromto
9631 (if (string-match org-from-is-user-regexp from)
9632 (concat "to %t")
9633 (concat "from %f"))))))
9634 (setq org-store-link-plist plist))
9636 (defun org-add-link-props (&rest plist)
9637 "Add these properties to the link property list."
9638 (let (key value)
9639 (while plist
9640 (setq key (pop plist) value (pop plist))
9641 (setq org-store-link-plist
9642 (plist-put org-store-link-plist key value)))))
9644 (defun org-email-link-description (&optional fmt)
9645 "Return the description part of an email link.
9646 This takes information from `org-store-link-plist' and formats it
9647 according to FMT (default from `org-email-link-description-format')."
9648 (setq fmt (or fmt org-email-link-description-format))
9649 (let* ((p org-store-link-plist)
9650 (to (plist-get p :toaddress))
9651 (from (plist-get p :fromaddress))
9652 (table
9653 (list
9654 (cons "%c" (plist-get p :fromto))
9655 (cons "%F" (plist-get p :from))
9656 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9657 (cons "%T" (plist-get p :to))
9658 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9659 (cons "%s" (plist-get p :subject))
9660 (cons "%d" (plist-get p :date))
9661 (cons "%m" (plist-get p :message-id)))))
9662 (when (string-match "%c" fmt)
9663 ;; Check if the user wrote this message
9664 (if (and org-from-is-user-regexp from to
9665 (save-match-data (string-match org-from-is-user-regexp from)))
9666 (setq fmt (replace-match "to %t" t t fmt))
9667 (setq fmt (replace-match "from %f" t t fmt))))
9668 (org-replace-escapes fmt table)))
9670 (defun org-make-org-heading-search-string (&optional string)
9671 "Make search string for the current headline or STRING."
9672 (let ((s (or string
9673 (and (derived-mode-p 'org-mode)
9674 (save-excursion
9675 (org-back-to-heading t)
9676 (org-element-property :raw-value (org-element-at-point))))))
9677 (lines org-context-in-file-links))
9678 (or string (setq s (concat "*" s))) ; Add * for headlines
9679 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9680 (when (and string (integerp lines) (> lines 0))
9681 (let ((slines (org-split-string s "\n")))
9682 (when (< lines (length slines))
9683 (setq s (mapconcat
9684 'identity
9685 (reverse (nthcdr (- (length slines) lines)
9686 (reverse slines))) "\n")))))
9687 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9689 (defun org-make-link-string (link &optional description)
9690 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9691 (unless (string-match "\\S-" link)
9692 (error "Empty link"))
9693 (when (and description
9694 (stringp description)
9695 (not (string-match "\\S-" description)))
9696 (setq description nil))
9697 (when (stringp description)
9698 ;; Remove brackets from the description, they are fatal.
9699 (while (string-match "\\[" description)
9700 (setq description (replace-match "{" t t description)))
9701 (while (string-match "\\]" description)
9702 (setq description (replace-match "}" t t description))))
9703 (when (equal link description)
9704 ;; No description needed, it is identical
9705 (setq description nil))
9706 (when (and (not description)
9707 (not (string-match (org-image-file-name-regexp) link))
9708 (not (equal link (org-link-escape link))))
9709 (setq description (org-extract-attributes link)))
9710 (setq link
9711 (cond ((string-match (org-image-file-name-regexp) link) link)
9712 ((string-match org-link-types-re link)
9713 (concat (match-string 1 link)
9714 (org-link-escape (substring link (match-end 1)))))
9715 (t (org-link-escape link))))
9716 (concat "[[" link "]"
9717 (if description (concat "[" description "]") "")
9718 "]"))
9720 (defconst org-link-escape-chars
9721 ;;%20 %2B %3B %3D %5B %5D
9722 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9723 "List of characters that should be escaped in link.
9724 This is the list that is used for internal purposes.")
9726 (defconst org-link-escape-chars-browser
9727 ;;%20 %22
9728 '(?\ ?\")
9729 "List of escapes for characters that are problematic in links.
9730 This is the list that is used before handing over to the browser.")
9732 (defun org-link-escape (text &optional table merge)
9733 "Return percent escaped representation of TEXT.
9734 TEXT is a string with the text to escape.
9735 Optional argument TABLE is a list with characters that should be
9736 escaped. When nil, `org-link-escape-chars' is used.
9737 If optional argument MERGE is set, merge TABLE into
9738 `org-link-escape-chars'."
9739 (cond
9740 ((and table merge)
9741 (mapc (lambda (defchr)
9742 (unless (member defchr table)
9743 (setq table (cons defchr table)))) org-link-escape-chars))
9744 ((null table)
9745 (setq table org-link-escape-chars)))
9746 (mapconcat
9747 (lambda (char)
9748 (if (or (member char table)
9749 (and (or (< char 32) (= char ?\%) (> char 126))
9750 org-url-hexify-p))
9751 (mapconcat (lambda (sequence-element)
9752 (format "%%%.2X" sequence-element))
9753 (or (encode-coding-char char 'utf-8)
9754 (error "Unable to percent escape character: %s"
9755 (char-to-string char))) "")
9756 (char-to-string char))) text ""))
9758 (defun org-link-escape-browser (text)
9759 (if (org-string-match-p
9760 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9761 text)
9762 (org-link-escape text org-link-escape-chars-browser)
9763 text))
9765 (defun org-link-unescape (str)
9766 "Unhex hexified Unicode strings as returned from the JavaScript function
9767 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9768 (unless (and (null str) (string= "" str))
9769 (let ((pos 0) (case-fold-search t) unhexed)
9770 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9771 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9772 (setq str (replace-match unhexed t t str))
9773 (setq pos (+ pos (length unhexed))))))
9774 str)
9776 (defun org-link-unescape-compound (hex)
9777 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9778 Note: this function also decodes single byte encodings like
9779 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9780 (save-match-data
9781 (let* ((bytes (cdr (split-string hex "%")))
9782 (ret "")
9783 (eat 0)
9784 (sum 0))
9785 (while bytes
9786 (let* ((val (string-to-number (pop bytes) 16))
9787 (shift-xor
9788 (if (= 0 eat)
9789 (cond
9790 ((>= val 252) (cons 6 252))
9791 ((>= val 248) (cons 5 248))
9792 ((>= val 240) (cons 4 240))
9793 ((>= val 224) (cons 3 224))
9794 ((>= val 192) (cons 2 192))
9795 (t (cons 0 0)))
9796 (cons 6 128))))
9797 (if (>= val 192) (setq eat (car shift-xor)))
9798 (setq val (logxor val (cdr shift-xor)))
9799 (setq sum (+ (lsh sum (car shift-xor)) val))
9800 (if (> eat 0) (setq eat (- eat 1)))
9801 (cond
9802 ((= 0 eat) ;multi byte
9803 (setq ret (concat ret (org-char-to-string sum)))
9804 (setq sum 0))
9805 ((not bytes) ; single byte(s)
9806 (setq ret (org-link-unescape-single-byte-sequence hex))))
9807 )) ;; end (while bytes
9808 ret )))
9810 (defun org-link-unescape-single-byte-sequence (hex)
9811 "Unhexify hex-encoded single byte character sequences."
9812 (mapconcat (lambda (byte)
9813 (char-to-string (string-to-number byte 16)))
9814 (cdr (split-string hex "%")) ""))
9816 (defun org-xor (a b)
9817 "Exclusive or."
9818 (if a (not b) b))
9820 (defun org-fixup-message-id-for-http (s)
9821 "Replace special characters in a message id, so it can be used in an http query."
9822 (when (string-match "%" s)
9823 (setq s (mapconcat (lambda (c)
9824 (if (eq c ?%)
9825 "%25"
9826 (char-to-string c)))
9827 s "")))
9828 (while (string-match "<" s)
9829 (setq s (replace-match "%3C" t t s)))
9830 (while (string-match ">" s)
9831 (setq s (replace-match "%3E" t t s)))
9832 (while (string-match "@" s)
9833 (setq s (replace-match "%40" t t s)))
9836 (defun org-link-prettify (link)
9837 "Return a human-readable representation of LINK.
9838 The car of LINK must be a raw link the cdr of LINK must be either
9839 a link description or nil."
9840 (let ((desc (or (cadr link) "<no description>")))
9841 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9842 "<" (car link) ">")))
9844 ;;;###autoload
9845 (defun org-insert-link-global ()
9846 "Insert a link like Org-mode does.
9847 This command can be called in any mode to insert a link in Org-mode syntax."
9848 (interactive)
9849 (org-load-modules-maybe)
9850 (org-run-like-in-org-mode 'org-insert-link))
9852 (defun org-insert-all-links (&optional keep)
9853 "Insert all links in `org-stored-links'."
9854 (interactive "P")
9855 (let ((links (copy-sequence org-stored-links)) l)
9856 (while (setq l (if keep (pop links) (pop org-stored-links)))
9857 (insert "- ")
9858 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9859 (insert "\n"))))
9861 (defun org-link-fontify-links-to-this-file ()
9862 "Fontify links to the current file in `org-stored-links'."
9863 (let ((f (buffer-file-name)) a b)
9864 (setq a (mapcar (lambda(l)
9865 (let ((ll (car l)))
9866 (when (and (string-match "^file:\\(.+\\)::" ll)
9867 (equal f (expand-file-name (match-string 1 ll))))
9868 ll)))
9869 org-stored-links))
9870 (when (featurep 'org-id)
9871 (setq b (mapcar (lambda(l)
9872 (let ((ll (car l)))
9873 (when (and (string-match "^id:\\(.+\\)$" ll)
9874 (equal f (expand-file-name
9875 (or (org-id-find-id-file
9876 (match-string 1 ll)) ""))))
9877 ll)))
9878 org-stored-links)))
9879 (mapcar (lambda(l)
9880 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9881 (delq nil (append a b)))))
9883 (defvar org-link-links-in-this-file nil)
9884 (defun org-insert-link (&optional complete-file link-location default-description)
9885 "Insert a link. At the prompt, enter the link.
9887 Completion can be used to insert any of the link protocol prefixes like
9888 http or ftp in use.
9890 The history can be used to select a link previously stored with
9891 `org-store-link'. When the empty string is entered (i.e. if you just
9892 press RET at the prompt), the link defaults to the most recently
9893 stored link. As SPC triggers completion in the minibuffer, you need to
9894 use M-SPC or C-q SPC to force the insertion of a space character.
9896 You will also be prompted for a description, and if one is given, it will
9897 be displayed in the buffer instead of the link.
9899 If there is already a link at point, this command will allow you to edit link
9900 and description parts.
9902 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9903 be selected using completion. The path to the file will be relative to the
9904 current directory if the file is in the current directory or a subdirectory.
9905 Otherwise, the link will be the absolute path as completed in the minibuffer
9906 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9907 option `org-link-file-path-type'.
9909 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9910 the current directory or below.
9912 With three \\[universal-argument] prefixes, negate the meaning of
9913 `org-keep-stored-link-after-insertion'.
9915 If `org-make-link-description-function' is non-nil, this function will be
9916 called with the link target, and the result will be the default
9917 link description.
9919 If the LINK-LOCATION parameter is non-nil, this value will be
9920 used as the link location instead of reading one interactively.
9922 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9923 be used as the default description."
9924 (interactive "P")
9925 (let* ((wcf (current-window-configuration))
9926 (origbuf (current-buffer))
9927 (region (if (org-region-active-p)
9928 (buffer-substring (region-beginning) (region-end))))
9929 (remove (and region (list (region-beginning) (region-end))))
9930 (desc region)
9931 tmphist ; byte-compile incorrectly complains about this
9932 (link link-location)
9933 (abbrevs org-link-abbrev-alist-local)
9934 entry file all-prefixes auto-desc)
9935 (cond
9936 (link-location) ; specified by arg, just use it.
9937 ((org-in-regexp org-bracket-link-regexp 1)
9938 ;; We do have a link at point, and we are going to edit it.
9939 (setq remove (list (match-beginning 0) (match-end 0)))
9940 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9941 (setq link (read-string "Link: "
9942 (org-link-unescape
9943 (org-match-string-no-properties 1)))))
9944 ((or (org-in-regexp org-angle-link-re)
9945 (org-in-regexp org-plain-link-re))
9946 ;; Convert to bracket link
9947 (setq remove (list (match-beginning 0) (match-end 0))
9948 link (read-string "Link: "
9949 (org-remove-angle-brackets (match-string 0)))))
9950 ((member complete-file '((4) (16)))
9951 ;; Completing read for file names.
9952 (setq link (org-file-complete-link complete-file)))
9954 ;; Read link, with completion for stored links.
9955 (org-link-fontify-links-to-this-file)
9956 (org-switch-to-buffer-other-window "*Org Links*")
9957 (with-current-buffer "*Org Links*"
9958 (erase-buffer)
9959 (insert "Insert a link.
9960 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9961 (when org-stored-links
9962 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9963 (insert (mapconcat 'org-link-prettify
9964 (reverse org-stored-links) "\n")))
9965 (goto-char (point-min)))
9966 (let ((cw (selected-window)))
9967 (select-window (get-buffer-window "*Org Links*" 'visible))
9968 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9969 (unless (pos-visible-in-window-p (point-max))
9970 (org-fit-window-to-buffer))
9971 (and (window-live-p cw) (select-window cw)))
9972 ;; Fake a link history, containing the stored links.
9973 (setq tmphist (append (mapcar 'car org-stored-links)
9974 org-insert-link-history))
9975 (setq all-prefixes (append (mapcar 'car abbrevs)
9976 (mapcar 'car org-link-abbrev-alist)
9977 org-link-types))
9978 (unwind-protect
9979 (progn
9980 (setq link
9981 (org-completing-read
9982 "Link: "
9983 (append
9984 (mapcar (lambda (x) (concat x ":"))
9985 all-prefixes)
9986 (mapcar 'car org-stored-links))
9987 nil nil nil
9988 'tmphist
9989 (caar org-stored-links)))
9990 (if (not (string-match "\\S-" link))
9991 (user-error "No link selected"))
9992 (mapc (lambda(l)
9993 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9994 org-stored-links)
9995 (if (or (member link all-prefixes)
9996 (and (equal ":" (substring link -1))
9997 (member (substring link 0 -1) all-prefixes)
9998 (setq link (substring link 0 -1))))
9999 (setq link (with-current-buffer origbuf
10000 (org-link-try-special-completion link)))))
10001 (set-window-configuration wcf)
10002 (kill-buffer "*Org Links*"))
10003 (setq entry (assoc link org-stored-links))
10004 (or entry (push link org-insert-link-history))
10005 (setq desc (or desc (nth 1 entry)))))
10007 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10008 (not org-keep-stored-link-after-insertion))
10009 (setq org-stored-links (delq (assoc link org-stored-links)
10010 org-stored-links)))
10012 (if (string-match org-plain-link-re link)
10013 ;; URL-like link, normalize the use of angular brackets.
10014 (setq link (org-remove-angle-brackets link)))
10016 ;; Check if we are linking to the current file with a search
10017 ;; option If yes, simplify the link by using only the search
10018 ;; option.
10019 (when (and buffer-file-name
10020 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10021 (let* ((path (match-string 1 link))
10022 (case-fold-search nil)
10023 (search (match-string 2 link)))
10024 (save-match-data
10025 (if (equal (file-truename buffer-file-name) (file-truename path))
10026 ;; We are linking to this same file, with a search option
10027 (setq link search)))))
10029 ;; Check if we can/should use a relative path. If yes, simplify the link
10030 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10031 (let* ((type (match-string 1 link))
10032 (path (match-string 2 link))
10033 (origpath path)
10034 (case-fold-search nil))
10035 (cond
10036 ((or (eq org-link-file-path-type 'absolute)
10037 (equal complete-file '(16)))
10038 (setq path (abbreviate-file-name (expand-file-name path))))
10039 ((eq org-link-file-path-type 'noabbrev)
10040 (setq path (expand-file-name path)))
10041 ((eq org-link-file-path-type 'relative)
10042 (setq path (file-relative-name path)))
10044 (save-match-data
10045 (if (string-match (concat "^" (regexp-quote
10046 (expand-file-name
10047 (file-name-as-directory
10048 default-directory))))
10049 (expand-file-name path))
10050 ;; We are linking a file with relative path name.
10051 (setq path (substring (expand-file-name path)
10052 (match-end 0)))
10053 (setq path (abbreviate-file-name (expand-file-name path)))))))
10054 (setq link (concat type path))
10055 (if (equal desc origpath)
10056 (setq desc path))))
10058 (if org-make-link-description-function
10059 (setq desc
10060 (or (condition-case nil
10061 (funcall org-make-link-description-function link desc)
10062 (error (progn (message "Can't get link description from `%s'"
10063 (symbol-name org-make-link-description-function))
10064 (sit-for 2) nil)))
10065 (read-string "Description: " default-description)))
10066 (if default-description (setq desc default-description)
10067 (setq desc (or (and auto-desc desc)
10068 (read-string "Description: " desc)))))
10070 (unless (string-match "\\S-" desc) (setq desc nil))
10071 (if remove (apply 'delete-region remove))
10072 (insert (org-make-link-string link desc))))
10074 (defun org-link-try-special-completion (type)
10075 "If there is completion support for link type TYPE, offer it."
10076 (let ((fun (intern (concat "org-" type "-complete-link"))))
10077 (if (functionp fun)
10078 (funcall fun)
10079 (read-string "Link (no completion support): " (concat type ":")))))
10081 (defun org-file-complete-link (&optional arg)
10082 "Create a file link using completion."
10083 (let (file link)
10084 (setq file (org-iread-file-name "File: "))
10085 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10086 (pwd1 (file-name-as-directory (abbreviate-file-name
10087 (expand-file-name ".")))))
10088 (cond
10089 ((equal arg '(16))
10090 (setq link (concat
10091 "file:"
10092 (abbreviate-file-name (expand-file-name file)))))
10093 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10094 (setq link (concat "file:" (match-string 1 file))))
10095 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10096 (expand-file-name file))
10097 (setq link (concat
10098 "file:" (match-string 1 (expand-file-name file)))))
10099 (t (setq link (concat "file:" file)))))
10100 link))
10102 (defun org-iread-file-name (&rest args)
10103 "Read-file-name using `ido-mode' speedup if available.
10104 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10105 See `read-file-name' for a description of parameters."
10106 (org-without-partial-completion
10107 (if (and org-completion-use-ido
10108 (fboundp 'ido-read-file-name)
10109 (boundp 'ido-mode) ido-mode
10110 (listp (second args)))
10111 (let ((ido-enter-matching-directory nil))
10112 (apply 'ido-read-file-name args))
10113 (apply 'read-file-name args))))
10115 (defun org-completing-read (&rest args)
10116 "Completing-read with SPACE being a normal character."
10117 (let ((enable-recursive-minibuffers t)
10118 (minibuffer-local-completion-map
10119 (copy-keymap minibuffer-local-completion-map)))
10120 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10121 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10122 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10123 (apply 'org-icompleting-read args)))
10125 (defun org-completing-read-no-i (&rest args)
10126 (let (org-completion-use-ido org-completion-use-iswitchb)
10127 (apply 'org-completing-read args)))
10129 (defun org-iswitchb-completing-read (prompt choices &rest args)
10130 "Use iswitch as a completing-read replacement to choose from choices.
10131 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10132 from."
10133 (let* ((iswitchb-use-virtual-buffers nil)
10134 (iswitchb-make-buflist-hook
10135 (lambda ()
10136 (setq iswitchb-temp-buflist choices))))
10137 (iswitchb-read-buffer prompt)))
10139 (defun org-icompleting-read (&rest args)
10140 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10141 (org-without-partial-completion
10142 (if (and org-completion-use-ido
10143 (fboundp 'ido-completing-read)
10144 (boundp 'ido-mode) ido-mode
10145 (listp (second args)))
10146 (let ((ido-enter-matching-directory nil))
10147 (apply 'ido-completing-read (concat (car args))
10148 (if (consp (car (nth 1 args)))
10149 (mapcar 'car (nth 1 args))
10150 (nth 1 args))
10151 (cddr args)))
10152 (if (and org-completion-use-iswitchb
10153 (boundp 'iswitchb-mode) iswitchb-mode
10154 (listp (second args)))
10155 (apply 'org-iswitchb-completing-read (concat (car args))
10156 (if (consp (car (nth 1 args)))
10157 (mapcar 'car (nth 1 args))
10158 (nth 1 args))
10159 (cddr args))
10160 (apply 'completing-read args)))))
10162 (defun org-extract-attributes (s)
10163 "Extract the attributes cookie from a string and set as text property."
10164 (let (a attr (start 0) key value)
10165 (save-match-data
10166 (when (string-match "{{\\([^}]+\\)}}$" s)
10167 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10168 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10169 (setq key (match-string 1 a) value (match-string 2 a)
10170 start (match-end 0)
10171 attr (plist-put attr (intern key) value))))
10172 (org-add-props s nil 'org-attr attr))
10175 ;;; Opening/following a link
10177 (defvar org-link-search-failed nil)
10179 (defvar org-open-link-functions nil
10180 "Hook for functions finding a plain text link.
10181 These functions must take a single argument, the link content.
10182 They will be called for links that look like [[link text][description]]
10183 when LINK TEXT does not have a protocol like \"http:\" and does not look
10184 like a filename (e.g. \"./blue.png\").
10186 These functions will be called *before* Org attempts to resolve the
10187 link by doing text searches in the current buffer - so if you want a
10188 link \"[[target]]\" to still find \"<<target>>\", your function should
10189 handle this as a special case.
10191 When the function does handle the link, it must return a non-nil value.
10192 If it decides that it is not responsible for this link, it must return
10193 nil to indicate that that Org-mode can continue with other options
10194 like exact and fuzzy text search.")
10196 (defun org-next-link (&optional search-backward)
10197 "Move forward to the next link.
10198 If the link is in hidden text, expose it."
10199 (interactive "P")
10200 (when (and org-link-search-failed (eq this-command last-command))
10201 (goto-char (point-min))
10202 (message "Link search wrapped back to beginning of buffer"))
10203 (setq org-link-search-failed nil)
10204 (let* ((pos (point))
10205 (ct (org-context))
10206 (a (assoc :link ct))
10207 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10208 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10209 ((looking-at org-any-link-re)
10210 ;; Don't stay stuck at link without an org-link face
10211 (forward-char (if search-backward -1 1))))
10212 (if (funcall srch-fun org-any-link-re nil t)
10213 (progn
10214 (goto-char (match-beginning 0))
10215 (if (outline-invisible-p) (org-show-context)))
10216 (goto-char pos)
10217 (setq org-link-search-failed t)
10218 (message "No further link found"))))
10220 (defun org-previous-link ()
10221 "Move backward to the previous link.
10222 If the link is in hidden text, expose it."
10223 (interactive)
10224 (funcall 'org-next-link t))
10226 (defun org-translate-link (s)
10227 "Translate a link string if a translation function has been defined."
10228 (if (and org-link-translation-function
10229 (fboundp org-link-translation-function)
10230 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10231 (progn
10232 (setq s (funcall org-link-translation-function
10233 (match-string 1 s) (match-string 2 s)))
10234 (concat (car s) ":" (cdr s)))
10237 (defun org-translate-link-from-planner (type path)
10238 "Translate a link from Emacs Planner syntax so that Org can follow it.
10239 This is still an experimental function, your mileage may vary."
10240 (cond
10241 ((member type '("http" "https" "news" "ftp"))
10242 ;; standard Internet links are the same.
10243 nil)
10244 ((and (equal type "irc") (string-match "^//" path))
10245 ;; Planner has two / at the beginning of an irc link, we have 1.
10246 ;; We should have zero, actually....
10247 (setq path (substring path 1)))
10248 ((and (equal type "lisp") (string-match "^/" path))
10249 ;; Planner has a slash, we do not.
10250 (setq type "elisp" path (substring path 1)))
10251 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10252 ;; A typical message link. Planner has the id after the final slash,
10253 ;; we separate it with a hash mark
10254 (setq path (concat (match-string 1 path) "#"
10255 (org-remove-angle-brackets (match-string 2 path))))))
10256 (cons type path))
10258 (defun org-find-file-at-mouse (ev)
10259 "Open file link or URL at mouse."
10260 (interactive "e")
10261 (mouse-set-point ev)
10262 (org-open-at-point 'in-emacs))
10264 (defun org-open-at-mouse (ev)
10265 "Open file link or URL at mouse.
10266 See the docstring of `org-open-file' for details."
10267 (interactive "e")
10268 (mouse-set-point ev)
10269 (if (eq major-mode 'org-agenda-mode)
10270 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10271 (org-open-at-point))
10273 (defvar org-window-config-before-follow-link nil
10274 "The window configuration before following a link.
10275 This is saved in case the need arises to restore it.")
10277 (defvar org-open-link-marker (make-marker)
10278 "Marker pointing to the location where `org-open-at-point; was called.")
10280 ;;;###autoload
10281 (defun org-open-at-point-global ()
10282 "Follow a link like Org-mode does.
10283 This command can be called in any mode to follow a link that has
10284 Org-mode syntax."
10285 (interactive)
10286 (org-run-like-in-org-mode 'org-open-at-point))
10288 ;;;###autoload
10289 (defun org-open-link-from-string (s &optional arg reference-buffer)
10290 "Open a link in the string S, as if it was in Org-mode."
10291 (interactive "sLink: \nP")
10292 (let ((reference-buffer (or reference-buffer (current-buffer))))
10293 (with-temp-buffer
10294 (let ((org-inhibit-startup (not reference-buffer)))
10295 (org-mode)
10296 (insert s)
10297 (goto-char (point-min))
10298 (when reference-buffer
10299 (setq org-link-abbrev-alist-local
10300 (with-current-buffer reference-buffer
10301 org-link-abbrev-alist-local)))
10302 (org-open-at-point arg reference-buffer)))))
10304 (defvar org-open-at-point-functions nil
10305 "Hook that is run when following a link at point.
10307 Functions in this hook must return t if they identify and follow
10308 a link at point. If they don't find anything interesting at point,
10309 they must return nil.")
10311 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10312 (defun org-open-at-point (&optional arg reference-buffer)
10313 "Open link at or after point.
10314 If there is no link at point, this function will search forward up to
10315 the end of the current line.
10316 Normally, files will be opened by an appropriate application. If the
10317 optional prefix argument ARG is non-nil, Emacs will visit the file.
10318 With a double prefix argument, try to open outside of Emacs, in the
10319 application the system uses for this file type."
10320 (interactive "P")
10321 ;; if in a code block, then open the block's results
10322 (unless (call-interactively #'org-babel-open-src-block-result)
10323 (org-load-modules-maybe)
10324 (move-marker org-open-link-marker (point))
10325 (setq org-window-config-before-follow-link (current-window-configuration))
10326 (org-remove-occur-highlights nil nil t)
10327 (cond
10328 ((and (org-at-heading-p)
10329 (not (org-at-timestamp-p t))
10330 (not (org-in-regexp
10331 (concat org-plain-link-re "\\|"
10332 org-bracket-link-regexp "\\|"
10333 org-angle-link-re "\\|"
10334 "[ \t]:[^ \t\n]+:[ \t]*$")))
10335 (not (get-text-property (point) 'org-linked-text)))
10336 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10337 (lk0 (car lkall))
10338 (lk (if (stringp lk0) (list lk0) lk0))
10339 (lkend (cdr lkall)))
10340 (mapcar (lambda(l)
10341 (search-forward l nil lkend)
10342 (goto-char (match-beginning 0))
10343 (org-open-at-point))
10344 lk))
10345 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10346 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10347 ((and (org-at-timestamp-p t)
10348 (not (org-in-regexp org-bracket-link-regexp)))
10349 (org-follow-timestamp-link))
10350 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10351 (not (org-in-regexp org-any-link-re)))
10352 (org-footnote-action))
10354 (let (type path link line search (pos (point)))
10355 (catch 'match
10356 (save-excursion
10357 (skip-chars-forward "^]\n\r")
10358 (when (org-in-regexp org-bracket-link-regexp 1)
10359 (setq link (org-extract-attributes
10360 (org-link-unescape (org-match-string-no-properties 1))))
10361 (while (string-match " *\n *" link)
10362 (setq link (replace-match " " t t link)))
10363 (setq link (org-link-expand-abbrev link))
10364 (cond
10365 ((or (file-name-absolute-p link)
10366 (string-match "^\\.\\.?/" link))
10367 (setq type "file" path link))
10368 ((string-match org-link-re-with-space3 link)
10369 (setq type (match-string 1 link) path (match-string 2 link)))
10370 ((string-match "^help:+\\(.+\\)" link)
10371 (setq type "help" path (match-string 1 link)))
10372 (t (setq type "thisfile" path link)))
10373 (throw 'match t)))
10375 (when (get-text-property (point) 'org-linked-text)
10376 (setq type "thisfile"
10377 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10378 (1+ (point)) (point))
10379 path (buffer-substring
10380 (or (previous-single-property-change pos 'org-linked-text)
10381 (point-min))
10382 (or (next-single-property-change pos 'org-linked-text)
10383 (point-max)))
10384 ;; Ensure we will search for a <<<radio>>> link, not
10385 ;; a simple reference like <<ref>>
10386 path (concat "<" path))
10387 (throw 'match t))
10389 (save-excursion
10390 (when (or (org-in-regexp org-angle-link-re)
10391 (let ((match (org-in-regexp org-plain-link-re)))
10392 ;; Check a plain link is not within a bracket link
10393 (and match
10394 (save-excursion
10395 (progn
10396 (goto-char (car match))
10397 (not (org-in-regexp org-bracket-link-regexp))))))
10398 (let ((line_ending (save-excursion (end-of-line) (point))))
10399 ;; We are in a line before a plain or bracket link
10400 (or (re-search-forward org-plain-link-re line_ending t)
10401 (re-search-forward org-bracket-link-regexp line_ending t))))
10402 (setq type (match-string 1)
10403 path (org-link-unescape (match-string 2)))
10404 (throw 'match t)))
10405 (save-excursion
10406 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10407 (setq type "tags"
10408 path (match-string 1))
10409 (while (string-match ":" path)
10410 (setq path (replace-match "+" t t path)))
10411 (throw 'match t)))
10412 (when (org-in-regexp "<\\([^><\n]+\\)>")
10413 (setq type "tree-match"
10414 path (match-string 1))
10415 (throw 'match t)))
10416 (unless path
10417 (user-error "No link found"))
10419 ;; switch back to reference buffer
10420 ;; needed when if called in a temporary buffer through
10421 ;; org-open-link-from-string
10422 (with-current-buffer (or reference-buffer (current-buffer))
10424 ;; Remove any trailing spaces in path
10425 (if (string-match " +\\'" path)
10426 (setq path (replace-match "" t t path)))
10427 (if (and org-link-translation-function
10428 (fboundp org-link-translation-function))
10429 ;; Check if we need to translate the link
10430 (let ((tmp (funcall org-link-translation-function type path)))
10431 (setq type (car tmp) path (cdr tmp))))
10433 (cond
10435 ((assoc type org-link-protocols)
10436 (funcall (nth 1 (assoc type org-link-protocols)) path))
10438 ((equal type "help")
10439 (let ((f-or-v (intern path)))
10440 (cond ((fboundp f-or-v)
10441 (describe-function f-or-v))
10442 ((boundp f-or-v)
10443 (describe-variable f-or-v))
10444 (t (error "Not a known function or variable")))))
10446 ((equal type "mailto")
10447 (let ((cmd (car org-link-mailto-program))
10448 (args (cdr org-link-mailto-program)) args1
10449 (address path) (subject "") a)
10450 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10451 (setq address (match-string 1 path)
10452 subject (org-link-escape (match-string 2 path))))
10453 (while args
10454 (cond
10455 ((not (stringp (car args))) (push (pop args) args1))
10456 (t (setq a (pop args))
10457 (if (string-match "%a" a)
10458 (setq a (replace-match address t t a)))
10459 (if (string-match "%s" a)
10460 (setq a (replace-match subject t t a)))
10461 (push a args1))))
10462 (apply cmd (nreverse args1))))
10464 ((member type '("http" "https" "ftp" "news"))
10465 (browse-url (concat type ":" (org-link-escape-browser path))))
10467 ((string= type "doi")
10468 (browse-url (concat org-doi-server-url
10469 (org-link-escape-browser path))))
10471 ((member type '("message"))
10472 (browse-url (concat type ":" path)))
10474 ((string= type "tags")
10475 (org-tags-view arg path))
10477 ((string= type "tree-match")
10478 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10480 ((string= type "file")
10481 (if (string-match "::\\([0-9]+\\)\\'" path)
10482 (setq line (string-to-number (match-string 1 path))
10483 path (substring path 0 (match-beginning 0)))
10484 (if (string-match "::\\(.+\\)\\'" path)
10485 (setq search (match-string 1 path)
10486 path (substring path 0 (match-beginning 0)))))
10487 (if (string-match "[*?{]" (file-name-nondirectory path))
10488 (dired path)
10489 (org-open-file path arg line search)))
10491 ((string= type "shell")
10492 (let ((buf (generate-new-buffer "*Org Shell Output"))
10493 (cmd path))
10494 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10495 (string-match org-confirm-shell-link-not-regexp cmd))
10496 (not org-confirm-shell-link-function)
10497 (funcall org-confirm-shell-link-function
10498 (format "Execute \"%s\" in shell? "
10499 (org-add-props cmd nil
10500 'face 'org-warning))))
10501 (progn
10502 (message "Executing %s" cmd)
10503 (shell-command cmd buf)
10504 (if (featurep 'midnight)
10505 (setq clean-buffer-list-kill-buffer-names
10506 (cons buf clean-buffer-list-kill-buffer-names))))
10507 (error "Abort"))))
10509 ((string= type "elisp")
10510 (let ((cmd path))
10511 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10512 (string-match org-confirm-elisp-link-not-regexp cmd))
10513 (not org-confirm-elisp-link-function)
10514 (funcall org-confirm-elisp-link-function
10515 (format "Execute \"%s\" as elisp? "
10516 (org-add-props cmd nil
10517 'face 'org-warning))))
10518 (message "%s => %s" cmd
10519 (if (equal (string-to-char cmd) ?\()
10520 (eval (read cmd))
10521 (call-interactively (read cmd))))
10522 (error "Abort"))))
10524 ((and (string= type "thisfile")
10525 (or (run-hook-with-args-until-success
10526 'org-open-link-functions path)
10527 (and link
10528 (string-match "^id:" link)
10529 (or (featurep 'org-id) (require 'org-id))
10530 (progn
10531 (funcall (nth 1 (assoc "id" org-link-protocols))
10532 (substring path 3))
10533 t)))))
10535 ((string= type "thisfile")
10536 (if arg
10537 (switch-to-buffer-other-window
10538 (org-get-buffer-for-internal-link (current-buffer)))
10539 (org-mark-ring-push))
10540 (let ((cmd `(org-link-search
10541 ,path
10542 ,(cond ((equal arg '(4)) ''occur)
10543 ((equal arg '(16)) ''org-occur))
10544 ,pos)))
10545 (condition-case nil (let ((org-link-search-inhibit-query t))
10546 (eval cmd))
10547 (error (progn (widen) (eval cmd))))))
10549 (t (browse-url-at-point)))))))
10550 (move-marker org-open-link-marker nil)
10551 (run-hook-with-args 'org-follow-link-hook)))
10553 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10554 "Offer links in the current entry and return the selected link.
10555 If there is only one link, return it.
10556 If NTH is an integer, return the NTH link found.
10557 If ZERO is a string, check also this string for a link, and if
10558 there is one, return it."
10559 (with-current-buffer buffer
10560 (save-excursion
10561 (save-restriction
10562 (widen)
10563 (goto-char marker)
10564 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10565 "\\(" org-angle-link-re "\\)\\|"
10566 "\\(" org-plain-link-re "\\)"))
10567 (cnt ?0)
10568 (in-emacs (if (integerp nth) nil nth))
10569 have-zero end links link c)
10570 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10571 (push (match-string 0 zero) links)
10572 (setq cnt (1- cnt) have-zero t))
10573 (save-excursion
10574 (org-back-to-heading t)
10575 (setq end (save-excursion (outline-next-heading) (point)))
10576 (while (re-search-forward re end t)
10577 (push (match-string 0) links))
10578 (setq links (org-uniquify (reverse links))))
10579 (cond
10580 ((null links)
10581 (message "No links"))
10582 ((equal (length links) 1)
10583 (setq link (car links)))
10584 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10585 (setq link (nth (if have-zero nth (1- nth)) links)))
10586 (t ; we have to select a link
10587 (save-excursion
10588 (save-window-excursion
10589 (delete-other-windows)
10590 (with-output-to-temp-buffer "*Select Link*"
10591 (mapc (lambda (l)
10592 (if (not (string-match org-bracket-link-regexp l))
10593 (princ (format "[%c] %s\n" (incf cnt)
10594 (org-remove-angle-brackets l)))
10595 (if (match-end 3)
10596 (princ (format "[%c] %s (%s)\n" (incf cnt)
10597 (match-string 3 l) (match-string 1 l)))
10598 (princ (format "[%c] %s\n" (incf cnt)
10599 (match-string 1 l))))))
10600 links))
10601 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10602 (message "Select link to open, RET to open all:")
10603 (setq c (read-char-exclusive))
10604 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10605 (when (equal c ?q) (error "Abort"))
10606 (if (equal c ?\C-m)
10607 (setq link links)
10608 (setq nth (- c ?0))
10609 (if have-zero (setq nth (1+ nth)))
10610 (unless (and (integerp nth) (>= (length links) nth))
10611 (user-error "Invalid link selection"))
10612 (setq link (nth (1- nth) links)))))
10613 (cons link end))))))
10615 ;; Add special file links that specify the way of opening
10617 (org-add-link-type "file+sys" 'org-open-file-with-system)
10618 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10619 (defun org-open-file-with-system (path)
10620 "Open file at PATH using the system way of opening it."
10621 (org-open-file path 'system))
10622 (defun org-open-file-with-emacs (path)
10623 "Open file at PATH in Emacs."
10624 (org-open-file path 'emacs))
10627 ;;; File search
10629 (defvar org-create-file-search-functions nil
10630 "List of functions to construct the right search string for a file link.
10631 These functions are called in turn with point at the location to
10632 which the link should point.
10634 A function in the hook should first test if it would like to
10635 handle this file type, for example by checking the `major-mode'
10636 or the file extension. If it decides not to handle this file, it
10637 should just return nil to give other functions a chance. If it
10638 does handle the file, it must return the search string to be used
10639 when following the link. The search string will be part of the
10640 file link, given after a double colon, and `org-open-at-point'
10641 will automatically search for it. If special measures must be
10642 taken to make the search successful, another function should be
10643 added to the companion hook `org-execute-file-search-functions',
10644 which see.
10646 A function in this hook may also use `setq' to set the variable
10647 `description' to provide a suggestion for the descriptive text to
10648 be used for this link when it gets inserted into an Org-mode
10649 buffer with \\[org-insert-link].")
10651 (defvar org-execute-file-search-functions nil
10652 "List of functions to execute a file search triggered by a link.
10654 Functions added to this hook must accept a single argument, the
10655 search string that was part of the file link, the part after the
10656 double colon. The function must first check if it would like to
10657 handle this search, for example by checking the `major-mode' or
10658 the file extension. If it decides not to handle this search, it
10659 should just return nil to give other functions a chance. If it
10660 does handle the search, it must return a non-nil value to keep
10661 other functions from trying.
10663 Each function can access the current prefix argument through the
10664 variable `current-prefix-arg'. Note that a single prefix is used
10665 to force opening a link in Emacs, so it may be good to only use a
10666 numeric or double prefix to guide the search function.
10668 In case this is needed, a function in this hook can also restore
10669 the window configuration before `org-open-at-point' was called using:
10671 (set-window-configuration org-window-config-before-follow-link)")
10673 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10674 (defun org-link-search (s &optional type avoid-pos stealth)
10675 "Search for a link search option.
10676 If S is surrounded by forward slashes, it is interpreted as a
10677 regular expression. In org-mode files, this will create an `org-occur'
10678 sparse tree. In ordinary files, `occur' will be used to list matches.
10679 If the current buffer is in `dired-mode', grep will be used to search
10680 in all files. If AVOID-POS is given, ignore matches near that position.
10682 When optional argument STEALTH is non-nil, do not modify
10683 visibility around point, thus ignoring
10684 `org-show-hierarchy-above', `org-show-following-heading' and
10685 `org-show-siblings' variables."
10686 (let ((case-fold-search t)
10687 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10688 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10689 (append '(("") (" ") ("\t") ("\n"))
10690 org-emphasis-alist)
10691 "\\|") "\\)"))
10692 (pos (point))
10693 (pre nil) (post nil)
10694 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10695 (cond
10696 ;; First check if there are any special search functions
10697 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10698 ;; Now try the builtin stuff
10699 ((and (equal (string-to-char s0) ?#)
10700 (> (length s0) 1)
10701 (save-excursion
10702 (goto-char (point-min))
10703 (and
10704 (re-search-forward
10705 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10706 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10707 (setq type 'dedicated
10708 pos (match-beginning 0))))
10709 ;; There is an exact target for this
10710 (goto-char pos)
10711 (org-back-to-heading t)))
10712 ((save-excursion
10713 (goto-char (point-min))
10714 (and
10715 (re-search-forward
10716 (concat "<<" (regexp-quote s0) ">>") nil t)
10717 (setq type 'dedicated
10718 pos (match-beginning 0))))
10719 ;; There is an exact target for this
10720 (goto-char pos))
10721 ((save-excursion
10722 (goto-char (point-min))
10723 (and
10724 (re-search-forward
10725 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10726 (setq type 'dedicated pos (match-beginning 0))))
10727 ;; Found an element with a matching #+name affiliated keyword.
10728 (goto-char pos))
10729 ((and (string-match "^(\\(.*\\))$" s0)
10730 (save-excursion
10731 (goto-char (point-min))
10732 (and
10733 (re-search-forward
10734 (concat "[^[]" (regexp-quote
10735 (format org-coderef-label-format
10736 (match-string 1 s0))))
10737 nil t)
10738 (setq type 'dedicated
10739 pos (1+ (match-beginning 0))))))
10740 ;; There is a coderef target for this
10741 (goto-char pos))
10742 ((string-match "^/\\(.*\\)/$" s)
10743 ;; A regular expression
10744 (cond
10745 ((derived-mode-p 'org-mode)
10746 (org-occur (match-string 1 s)))
10747 (t (org-do-occur (match-string 1 s)))))
10748 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10749 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10750 (goto-char (point-min))
10751 (cond
10752 ((let (case-fold-search)
10753 (re-search-forward (format org-complex-heading-regexp-format
10754 (regexp-quote s))
10755 nil t))
10756 ;; OK, found a match
10757 (setq type 'dedicated)
10758 (goto-char (match-beginning 0)))
10759 ((and (not org-link-search-inhibit-query)
10760 (eq org-link-search-must-match-exact-headline 'query-to-create)
10761 (y-or-n-p "No match - create this as a new heading? "))
10762 (goto-char (point-max))
10763 (or (bolp) (newline))
10764 (insert "* " s "\n")
10765 (beginning-of-line 0))
10767 (goto-char pos)
10768 (error "No match"))))
10770 ;; A normal search string
10771 (when (equal (string-to-char s) ?*)
10772 ;; Anchor on headlines, post may include tags.
10773 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10774 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10775 s (substring s 1)))
10776 (remove-text-properties
10777 0 (length s)
10778 '(face nil mouse-face nil keymap nil fontified nil) s)
10779 ;; Make a series of regular expressions to find a match
10780 (setq words (org-split-string s "[ \n\r\t]+")
10782 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10783 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10784 "\\)" markers)
10785 re2a_ (concat "\\(" (mapconcat 'downcase words
10786 "[ \t\r\n]+") "\\)[ \t\r\n]")
10787 re2a (concat "[ \t\r\n]" re2a_)
10788 re4_ (concat "\\(" (mapconcat 'downcase words
10789 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10790 re4 (concat "[^a-zA-Z_]" re4_)
10792 re1 (concat pre re2 post)
10793 re3 (concat pre (if pre re4_ re4) post)
10794 re5 (concat pre ".*" re4)
10795 re2 (concat pre re2)
10796 re2a (concat pre (if pre re2a_ re2a))
10797 re4 (concat pre (if pre re4_ re4))
10798 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10799 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10800 re5 "\\)"))
10801 (cond
10802 ((eq type 'org-occur) (org-occur reall))
10803 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10804 (t (goto-char (point-min))
10805 (setq type 'fuzzy)
10806 (if (or (and (org-search-not-self 1 re0 nil t)
10807 (setq type 'dedicated))
10808 (org-search-not-self 1 re1 nil t)
10809 (org-search-not-self 1 re2 nil t)
10810 (org-search-not-self 1 re2a nil t)
10811 (org-search-not-self 1 re3 nil t)
10812 (org-search-not-self 1 re4 nil t)
10813 (org-search-not-self 1 re5 nil t))
10814 (goto-char (match-beginning 1))
10815 (goto-char pos)
10816 (error "No match"))))))
10817 (and (derived-mode-p 'org-mode)
10818 (not stealth)
10819 (org-show-context 'link-search))
10820 type))
10822 (defun org-search-not-self (group &rest args)
10823 "Execute `re-search-forward', but only accept matches that do not
10824 enclose the position of `org-open-link-marker'."
10825 (let ((m org-open-link-marker))
10826 (catch 'exit
10827 (while (apply 're-search-forward args)
10828 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10829 (goto-char (match-end group))
10830 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10831 (> (match-beginning 0) (marker-position m))
10832 (< (match-end 0) (marker-position m)))
10833 (save-match-data
10834 (or (not (org-in-regexp
10835 org-bracket-link-analytic-regexp 1))
10836 (not (match-end 4)) ; no description
10837 (and (<= (match-beginning 4) (point))
10838 (>= (match-end 4) (point))))))
10839 (throw 'exit (point))))))))
10841 (defun org-get-buffer-for-internal-link (buffer)
10842 "Return a buffer to be used for displaying the link target of internal links."
10843 (cond
10844 ((not org-display-internal-link-with-indirect-buffer)
10845 buffer)
10846 ((string-match "(Clone)$" (buffer-name buffer))
10847 (message "Buffer is already a clone, not making another one")
10848 ;; we also do not modify visibility in this case
10849 buffer)
10850 (t ; make a new indirect buffer for displaying the link
10851 (let* ((bn (buffer-name buffer))
10852 (ibn (concat bn "(Clone)"))
10853 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10854 (with-current-buffer ib (org-overview))
10855 ib))))
10857 (defun org-do-occur (regexp &optional cleanup)
10858 "Call the Emacs command `occur'.
10859 If CLEANUP is non-nil, remove the printout of the regular expression
10860 in the *Occur* buffer. This is useful if the regex is long and not useful
10861 to read."
10862 (occur regexp)
10863 (when cleanup
10864 (let ((cwin (selected-window)) win beg end)
10865 (when (setq win (get-buffer-window "*Occur*"))
10866 (select-window win))
10867 (goto-char (point-min))
10868 (when (re-search-forward "match[a-z]+" nil t)
10869 (setq beg (match-end 0))
10870 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10871 (setq end (1- (match-beginning 0)))))
10872 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10873 (goto-char (point-min))
10874 (select-window cwin))))
10876 ;;; The mark ring for links jumps
10878 (defvar org-mark-ring nil
10879 "Mark ring for positions before jumps in Org-mode.")
10880 (defvar org-mark-ring-last-goto nil
10881 "Last position in the mark ring used to go back.")
10882 ;; Fill and close the ring
10883 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10884 (loop for i from 1 to org-mark-ring-length do
10885 (push (make-marker) org-mark-ring))
10886 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10887 org-mark-ring)
10889 (defun org-mark-ring-push (&optional pos buffer)
10890 "Put the current position or POS into the mark ring and rotate it."
10891 (interactive)
10892 (setq pos (or pos (point)))
10893 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10894 (move-marker (car org-mark-ring)
10895 (or pos (point))
10896 (or buffer (current-buffer)))
10897 (message "%s"
10898 (substitute-command-keys
10899 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10901 (defun org-mark-ring-goto (&optional n)
10902 "Jump to the previous position in the mark ring.
10903 With prefix arg N, jump back that many stored positions. When
10904 called several times in succession, walk through the entire ring.
10905 Org-mode commands jumping to a different position in the current file,
10906 or to another Org-mode file, automatically push the old position
10907 onto the ring."
10908 (interactive "p")
10909 (let (p m)
10910 (if (eq last-command this-command)
10911 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10912 (setq p org-mark-ring))
10913 (setq org-mark-ring-last-goto p)
10914 (setq m (car p))
10915 (org-pop-to-buffer-same-window (marker-buffer m))
10916 (goto-char m)
10917 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10919 (defun org-remove-angle-brackets (s)
10920 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10921 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10923 (defun org-add-angle-brackets (s)
10924 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10925 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10927 (defun org-remove-double-quotes (s)
10928 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10929 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10932 ;;; Following specific links
10934 (defun org-follow-timestamp-link ()
10935 "Open an agenda view for the time-stamp date/range at point."
10936 (cond
10937 ((org-at-date-range-p t)
10938 (let ((org-agenda-start-on-weekday)
10939 (t1 (match-string 1))
10940 (t2 (match-string 2)) tt1 tt2)
10941 (setq tt1 (time-to-days (org-time-string-to-time t1))
10942 tt2 (time-to-days (org-time-string-to-time t2)))
10943 (let ((org-agenda-buffer-tmp-name
10944 (format "*Org Agenda(a:%s)"
10945 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10946 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10947 ((org-at-timestamp-p t)
10948 (let ((org-agenda-buffer-tmp-name
10949 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10950 (org-agenda-list nil (time-to-days (org-time-string-to-time
10951 (substring (match-string 1) 0 10)))
10952 1)))
10953 (t (error "This should not happen"))))
10956 ;;; Following file links
10957 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10958 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10959 (declare-function mailcap-mime-info
10960 "mailcap" (string &optional request no-decode))
10961 (defvar org-wait nil)
10962 (defun org-open-file (path &optional in-emacs line search)
10963 "Open the file at PATH.
10964 First, this expands any special file name abbreviations. Then the
10965 configuration variable `org-file-apps' is checked if it contains an
10966 entry for this file type, and if yes, the corresponding command is launched.
10968 If no application is found, Emacs simply visits the file.
10970 With optional prefix argument IN-EMACS, Emacs will visit the file.
10971 With a double \\[universal-argument] \\[universal-argument] \
10972 prefix arg, Org tries to avoid opening in Emacs
10973 and to use an external application to visit the file.
10975 Optional LINE specifies a line to go to, optional SEARCH a string
10976 to search for. If LINE or SEARCH is given, the file will be
10977 opened in Emacs, unless an entry from org-file-apps that makes
10978 use of groups in a regexp matches.
10980 If you want to change the way frames are used when following a
10981 link, please customize `org-link-frame-setup'.
10983 If the file does not exist, an error is thrown."
10984 (let* ((file (if (equal path "")
10985 buffer-file-name
10986 (substitute-in-file-name (expand-file-name path))))
10987 (file-apps (append org-file-apps (org-default-apps)))
10988 (apps (org-remove-if
10989 'org-file-apps-entry-match-against-dlink-p file-apps))
10990 (apps-dlink (org-remove-if-not
10991 'org-file-apps-entry-match-against-dlink-p file-apps))
10992 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10993 (dirp (if remp nil (file-directory-p file)))
10994 (file (if (and dirp org-open-directory-means-index-dot-org)
10995 (concat (file-name-as-directory file) "index.org")
10996 file))
10997 (a-m-a-p (assq 'auto-mode apps))
10998 (dfile (downcase file))
10999 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11000 (link (cond ((and (eq line nil)
11001 (eq search nil))
11002 file)
11003 (line
11004 (concat file "::" (number-to-string line)))
11005 (search
11006 (concat file "::" search))))
11007 (dlink (downcase link))
11008 (old-buffer (current-buffer))
11009 (old-pos (point))
11010 (old-mode major-mode)
11011 ext cmd link-match-data)
11012 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11013 (setq ext (match-string 1 dfile))
11014 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11015 (setq ext (match-string 1 dfile))))
11016 (cond
11017 ((member in-emacs '((16) system))
11018 (setq cmd (cdr (assoc 'system apps))))
11019 (in-emacs (setq cmd 'emacs))
11021 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11022 (and dirp (cdr (assoc 'directory apps)))
11023 ; first, try matching against apps-dlink
11024 ; if we get a match here, store the match data for later
11025 (let ((match (assoc-default dlink apps-dlink
11026 'string-match)))
11027 (if match
11028 (progn (setq link-match-data (match-data))
11029 match)
11030 (progn (setq in-emacs (or in-emacs line search))
11031 nil))) ; if we have no match in apps-dlink,
11032 ; always open the file in emacs if line or search
11033 ; is given (for backwards compatibility)
11034 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11035 'string-match)
11036 (cdr (assoc ext apps))
11037 (cdr (assoc t apps))))))
11038 (when (eq cmd 'system)
11039 (setq cmd (cdr (assoc 'system apps))))
11040 (when (eq cmd 'default)
11041 (setq cmd (cdr (assoc t apps))))
11042 (when (eq cmd 'mailcap)
11043 (require 'mailcap)
11044 (mailcap-parse-mailcaps)
11045 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11046 (command (mailcap-mime-info mime-type)))
11047 (if (stringp command)
11048 (setq cmd command)
11049 (setq cmd 'emacs))))
11050 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11051 (not (file-exists-p file))
11052 (not org-open-non-existing-files))
11053 (user-error "No such file: %s" file))
11054 (cond
11055 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11056 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11057 (while (string-match "['\"]%s['\"]" cmd)
11058 (setq cmd (replace-match "%s" t t cmd)))
11059 (while (string-match "%s" cmd)
11060 (setq cmd (replace-match
11061 (save-match-data
11062 (shell-quote-argument
11063 (convert-standard-filename file)))
11064 t t cmd)))
11066 ;; Replace "%1", "%2" etc. in command with group matches from regex
11067 (save-match-data
11068 (let ((match-index 1)
11069 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11070 (set-match-data link-match-data)
11071 (while (<= match-index number-of-groups)
11072 (let ((regex (concat "%" (number-to-string match-index)))
11073 (replace-with (match-string match-index dlink)))
11074 (while (string-match regex cmd)
11075 (setq cmd (replace-match replace-with t t cmd))))
11076 (setq match-index (+ match-index 1)))))
11078 (save-window-excursion
11079 (message "Running %s...done" cmd)
11080 (start-process-shell-command cmd nil cmd)
11081 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11082 ((or (stringp cmd)
11083 (eq cmd 'emacs))
11084 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11085 (widen)
11086 (if line (org-goto-line line)
11087 (if search (org-link-search search))))
11088 ((consp cmd)
11089 (let ((file (convert-standard-filename file)))
11090 (save-match-data
11091 (set-match-data link-match-data)
11092 (eval cmd))))
11093 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11094 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11095 (or (not (equal old-buffer (current-buffer)))
11096 (not (equal old-pos (point))))
11097 (org-mark-ring-push old-pos old-buffer))))
11099 (defun org-file-apps-entry-match-against-dlink-p (entry)
11100 "This function returns non-nil if `entry' uses a regular
11101 expression which should be matched against the whole link by
11102 org-open-file.
11104 It assumes that is the case when the entry uses a regular
11105 expression which has at least one grouping construct and the
11106 action is either a lisp form or a command string containing
11107 '%1', i.e. using at least one subexpression match as a
11108 parameter."
11109 (let ((selector (car entry))
11110 (action (cdr entry)))
11111 (if (stringp selector)
11112 (and (> (regexp-opt-depth selector) 0)
11113 (or (and (stringp action)
11114 (string-match "%[0-9]" action))
11115 (consp action)))
11116 nil)))
11118 (defun org-default-apps ()
11119 "Return the default applications for this operating system."
11120 (cond
11121 ((eq system-type 'darwin)
11122 org-file-apps-defaults-macosx)
11123 ((eq system-type 'windows-nt)
11124 org-file-apps-defaults-windowsnt)
11125 (t org-file-apps-defaults-gnu)))
11127 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11128 "Convert extensions to regular expressions in the cars of LIST.
11129 Also, weed out any non-string entries, because the return value is used
11130 only for regexp matching.
11131 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11132 point to the symbol `emacs', indicating that the file should
11133 be opened in Emacs."
11134 (append
11135 (delq nil
11136 (mapcar (lambda (x)
11137 (if (not (stringp (car x)))
11139 (if (string-match "\\W" (car x))
11141 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11142 list))
11143 (if add-auto-mode
11144 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11146 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11147 (defun org-file-remote-p (file)
11148 "Test whether FILE specifies a location on a remote system.
11149 Return non-nil if the location is indeed remote.
11151 For example, the filename \"/user@host:/foo\" specifies a location
11152 on the system \"/user@host:\"."
11153 (cond ((fboundp 'file-remote-p)
11154 (file-remote-p file))
11155 ((fboundp 'tramp-handle-file-remote-p)
11156 (tramp-handle-file-remote-p file))
11157 ((and (boundp 'ange-ftp-name-format)
11158 (string-match (car ange-ftp-name-format) file))
11159 t)))
11162 ;;;; Refiling
11164 (defun org-get-org-file ()
11165 "Read a filename, with default directory `org-directory'."
11166 (let ((default (or org-default-notes-file remember-data-file)))
11167 (read-file-name (format "File name [%s]: " default)
11168 (file-name-as-directory org-directory)
11169 default)))
11171 (defun org-notes-order-reversed-p ()
11172 "Check if the current file should receive notes in reversed order."
11173 (cond
11174 ((not org-reverse-note-order) nil)
11175 ((eq t org-reverse-note-order) t)
11176 ((not (listp org-reverse-note-order)) nil)
11177 (t (catch 'exit
11178 (let ((all org-reverse-note-order)
11179 entry)
11180 (while (setq entry (pop all))
11181 (if (string-match (car entry) buffer-file-name)
11182 (throw 'exit (cdr entry))))
11183 nil)))))
11185 (defvar org-refile-target-table nil
11186 "The list of refile targets, created by `org-refile'.")
11188 (defvar org-agenda-new-buffers nil
11189 "Buffers created to visit agenda files.")
11191 (defvar org-refile-cache nil
11192 "Cache for refile targets.")
11194 (defvar org-refile-markers nil
11195 "All the markers used for caching refile locations.")
11197 (defun org-refile-marker (pos)
11198 "Get a new refile marker, but only if caching is in use."
11199 (if (not org-refile-use-cache)
11201 (let ((m (make-marker)))
11202 (move-marker m pos)
11203 (push m org-refile-markers)
11204 m)))
11206 (defun org-refile-cache-clear ()
11207 "Clear the refile cache and disable all the markers."
11208 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11209 (setq org-refile-markers nil)
11210 (setq org-refile-cache nil)
11211 (message "Refile cache has been cleared"))
11213 (defun org-refile-cache-check-set (set)
11214 "Check if all the markers in the cache still have live buffers."
11215 (let (marker)
11216 (catch 'exit
11217 (while (and set (setq marker (nth 3 (pop set))))
11218 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11219 (when (and marker (null (marker-buffer marker)))
11220 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11221 (sit-for 3)
11222 (throw 'exit nil)))
11223 t)))
11225 (defun org-refile-cache-put (set &rest identifiers)
11226 "Push the refile targets SET into the cache, under IDENTIFIERS."
11227 (let* ((key (sha1 (prin1-to-string identifiers)))
11228 (entry (assoc key org-refile-cache)))
11229 (if entry
11230 (setcdr entry set)
11231 (push (cons key set) org-refile-cache))))
11233 (defun org-refile-cache-get (&rest identifiers)
11234 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11235 (cond
11236 ((not org-refile-cache) nil)
11237 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11239 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11240 org-refile-cache))))
11241 (and set (org-refile-cache-check-set set) set)))))
11243 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11244 "Produce a table with refile targets."
11245 (let ((case-fold-search nil)
11246 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11247 (entries (or org-refile-targets '((nil . (:level . 1)))))
11248 targets tgs txt re files f desc descre fast-path-p level pos0)
11249 (message "Getting targets...")
11250 (with-current-buffer (or default-buffer (current-buffer))
11251 (while (setq entry (pop entries))
11252 (setq files (car entry) desc (cdr entry))
11253 (setq fast-path-p nil)
11254 (cond
11255 ((null files) (setq files (list (current-buffer))))
11256 ((eq files 'org-agenda-files)
11257 (setq files (org-agenda-files 'unrestricted)))
11258 ((and (symbolp files) (fboundp files))
11259 (setq files (funcall files)))
11260 ((and (symbolp files) (boundp files))
11261 (setq files (symbol-value files))))
11262 (if (stringp files) (setq files (list files)))
11263 (cond
11264 ((eq (car desc) :tag)
11265 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11266 ((eq (car desc) :todo)
11267 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11268 ((eq (car desc) :regexp)
11269 (setq descre (cdr desc)))
11270 ((eq (car desc) :level)
11271 (setq descre (concat "^\\*\\{" (number-to-string
11272 (if org-odd-levels-only
11273 (1- (* 2 (cdr desc)))
11274 (cdr desc)))
11275 "\\}[ \t]")))
11276 ((eq (car desc) :maxlevel)
11277 (setq fast-path-p t)
11278 (setq descre (concat "^\\*\\{1," (number-to-string
11279 (if org-odd-levels-only
11280 (1- (* 2 (cdr desc)))
11281 (cdr desc)))
11282 "\\}[ \t]")))
11283 (t (error "Bad refiling target description %s" desc)))
11284 (while (setq f (pop files))
11285 (with-current-buffer
11286 (if (bufferp f) f (org-get-agenda-file-buffer f))
11288 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11289 (progn
11290 (if (bufferp f) (setq f (buffer-file-name
11291 (buffer-base-buffer f))))
11292 (setq f (and f (expand-file-name f)))
11293 (if (eq org-refile-use-outline-path 'file)
11294 (push (list (file-name-nondirectory f) f nil nil) tgs))
11295 (save-excursion
11296 (save-restriction
11297 (widen)
11298 (goto-char (point-min))
11299 (while (re-search-forward descre nil t)
11300 (goto-char (setq pos0 (point-at-bol)))
11301 (catch 'next
11302 (when org-refile-target-verify-function
11303 (save-match-data
11304 (or (funcall org-refile-target-verify-function)
11305 (throw 'next t))))
11306 (when (and (looking-at org-complex-heading-regexp)
11307 (not (member (match-string 4) excluded-entries))
11308 (match-string 4))
11309 (setq level (org-reduced-level
11310 (- (match-end 1) (match-beginning 1)))
11311 txt (org-link-display-format (match-string 4))
11312 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11313 re (format org-complex-heading-regexp-format
11314 (regexp-quote (match-string 4))))
11315 (when org-refile-use-outline-path
11316 (setq txt (mapconcat
11317 'org-protect-slash
11318 (append
11319 (if (eq org-refile-use-outline-path
11320 'file)
11321 (list (file-name-nondirectory
11322 (buffer-file-name
11323 (buffer-base-buffer))))
11324 (if (eq org-refile-use-outline-path
11325 'full-file-path)
11326 (list (buffer-file-name
11327 (buffer-base-buffer)))))
11328 (org-get-outline-path fast-path-p
11329 level txt)
11330 (list txt))
11331 "/")))
11332 (push (list txt f re (org-refile-marker (point)))
11333 tgs)))
11334 (when (= (point) pos0)
11335 ;; verification function has not moved point
11336 (goto-char (point-at-eol))))))))
11337 (when org-refile-use-cache
11338 (org-refile-cache-put tgs (buffer-file-name) descre))
11339 (setq targets (append tgs targets))))))
11340 (message "Getting targets...done")
11341 (nreverse targets)))
11343 (defun org-protect-slash (s)
11344 (while (string-match "/" s)
11345 (setq s (replace-match "\\" t t s)))
11348 (defvar org-olpa (make-vector 20 nil))
11350 (defun org-get-outline-path (&optional fastp level heading)
11351 "Return the outline path to the current entry, as a list.
11353 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11354 routine which makes outline path derivations for an entire file,
11355 avoiding backtracing. Refile target collection makes use of that."
11356 (if fastp
11357 (progn
11358 (if (> level 19)
11359 (error "Outline path failure, more than 19 levels"))
11360 (loop for i from level upto 19 do
11361 (aset org-olpa i nil))
11362 (prog1
11363 (delq nil (append org-olpa nil))
11364 (aset org-olpa level heading)))
11365 (let (rtn case-fold-search)
11366 (save-excursion
11367 (save-restriction
11368 (widen)
11369 (while (org-up-heading-safe)
11370 (when (looking-at org-complex-heading-regexp)
11371 (push (org-trim
11372 (replace-regexp-in-string
11373 ;; Remove statistical/checkboxes cookies
11374 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11375 (org-match-string-no-properties 4)))
11376 rtn)))
11377 rtn)))))
11379 (defun org-format-outline-path (path &optional width prefix separator)
11380 "Format the outline path PATH for display.
11381 WIDTH is the maximum number of characters that is available.
11382 PREFIX is a prefix to be included in the returned string,
11383 such as the file name.
11384 SEPARATOR is inserted between the different parts of the path,
11385 the default is \"/\"."
11386 (setq width (or width 79))
11387 (if prefix (setq width (- width (length prefix))))
11388 (if (not path)
11389 (or prefix "")
11390 (let* ((nsteps (length path))
11391 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11392 (maxwidth (if (<= total-width width)
11393 10000 ;; everything fits
11394 ;; we need to shorten the level headings
11395 (/ (- width nsteps) nsteps)))
11396 (org-odd-levels-only nil)
11397 (n 0)
11398 (total (1+ (length prefix))))
11399 (setq maxwidth (max maxwidth 10))
11400 (concat prefix
11401 (if prefix (or separator "/"))
11402 (mapconcat
11403 (lambda (h)
11404 (setq n (1+ n))
11405 (if (and (= n nsteps) (< maxwidth 10000))
11406 (setq maxwidth (- total-width total)))
11407 (if (< (length h) maxwidth)
11408 (progn (setq total (+ total (length h) 1)) h)
11409 (setq h (substring h 0 (- maxwidth 2))
11410 total (+ total maxwidth 1))
11411 (if (string-match "[ \t]+\\'" h)
11412 (setq h (substring h 0 (match-beginning 0))))
11413 (setq h (concat h "..")))
11414 (org-add-props h nil 'face
11415 (nth (% (1- n) org-n-level-faces)
11416 org-level-faces))
11418 path (or separator "/"))))))
11420 (defun org-display-outline-path (&optional file current separator just-return-string)
11421 "Display the current outline path in the echo area.
11423 If FILE is non-nil, prepend the output with the file name.
11424 If CURRENT is non-nil, append the current heading to the output.
11425 SEPARATOR is passed through to `org-format-outline-path'. It separates
11426 the different parts of the path and defaults to \"/\".
11427 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11428 (interactive "P")
11429 (let* (case-fold-search
11430 (bfn (buffer-file-name (buffer-base-buffer)))
11431 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11432 res)
11433 (if current (setq path (append path
11434 (save-excursion
11435 (org-back-to-heading t)
11436 (if (looking-at org-complex-heading-regexp)
11437 (list (match-string 4)))))))
11438 (setq res
11439 (org-format-outline-path
11440 path
11441 (1- (frame-width))
11442 (and file bfn (concat (file-name-nondirectory bfn) separator))
11443 separator))
11444 (if just-return-string
11445 (org-no-properties res)
11446 (org-unlogged-message "%s" res))))
11448 (defvar org-refile-history nil
11449 "History for refiling operations.")
11451 (defvar org-after-refile-insert-hook nil
11452 "Hook run after `org-refile' has inserted its stuff at the new location.
11453 Note that this is still *before* the stuff will be removed from
11454 the *old* location.")
11456 (defvar org-capture-last-stored-marker)
11457 (defvar org-refile-keep nil
11458 "Non-nil means `org-refile' will copy instead of refile.")
11460 (defun org-copy ()
11461 "Like `org-refile', but copy."
11462 (interactive)
11463 (let ((org-refile-keep t))
11464 (funcall 'org-refile nil nil nil "Copy")))
11466 (defun org-refile (&optional goto default-buffer rfloc msg)
11467 "Move the entry or entries at point to another heading.
11468 The list of target headings is compiled using the information in
11469 `org-refile-targets', which see.
11471 At the target location, the entry is filed as a subitem of the target
11472 heading. Depending on `org-reverse-note-order', the new subitem will
11473 either be the first or the last subitem.
11475 If there is an active region, all entries in that region will be moved.
11476 However, the region must fulfill the requirement that the first heading
11477 is the first one sets the top-level of the moved text - at most siblings
11478 below it are allowed.
11480 With prefix arg GOTO, the command will only visit the target location
11481 and not actually move anything.
11483 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11484 go to the location where the last refiling operation has put the subtree.
11486 With a numeric prefix argument of `2', refile to the running clock.
11488 With a numeric prefix argument of `3', emulate `org-refile-keep'
11489 being set to `t' and copy to the target location, don't move it.
11490 Beware that keeping refiled entries may result in duplicated ID
11491 properties.
11493 RFLOC can be a refile location obtained in a different way.
11495 MSG is a string to replace \"Refile\" in the default prompt with
11496 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11498 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11500 If you are using target caching (see `org-refile-use-cache'),
11501 you have to clear the target cache in order to find new targets.
11502 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11503 prefix argument (`C-u C-u C-u C-c C-w')."
11505 (interactive "P")
11506 (if (member goto '(0 (64)))
11507 (org-refile-cache-clear)
11508 (let* ((actionmsg (or msg "Refile"))
11509 (cbuf (current-buffer))
11510 (regionp (org-region-active-p))
11511 (region-start (and regionp (region-beginning)))
11512 (region-end (and regionp (region-end)))
11513 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11514 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11515 pos it nbuf file re level reversed)
11516 (setq last-command nil)
11517 (when regionp
11518 (goto-char region-start)
11519 (or (bolp) (goto-char (point-at-bol)))
11520 (setq region-start (point))
11521 (unless (or (org-kill-is-subtree-p
11522 (buffer-substring region-start region-end))
11523 (prog1 org-refile-active-region-within-subtree
11524 (let ((s (point-at-eol)))
11525 (org-toggle-heading)
11526 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11527 (user-error "The region is not a (sequence of) subtree(s)")))
11528 (if (equal goto '(16))
11529 (org-refile-goto-last-stored)
11530 (when (or
11531 (and (equal goto 2)
11532 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11533 (prog1
11534 (setq it (list (or org-clock-heading "running clock")
11535 (buffer-file-name
11536 (marker-buffer org-clock-hd-marker))
11538 (marker-position org-clock-hd-marker)))
11539 (setq goto nil)))
11540 (setq it (or rfloc
11541 (let (heading-text)
11542 (save-excursion
11543 (unless goto
11544 (org-back-to-heading t)
11545 (setq heading-text
11546 (nth 4 (org-heading-components))))
11548 (org-refile-get-location
11549 (cond (goto "Goto")
11550 (regionp (concat actionmsg " region to"))
11551 (t (concat actionmsg " subtree \""
11552 heading-text "\" to")))
11553 default-buffer
11554 (and (not (equal '(4) goto))
11555 org-refile-allow-creating-parent-nodes)
11556 goto))))))
11557 (setq file (nth 1 it)
11558 re (nth 2 it)
11559 pos (nth 3 it))
11560 (if (and (not goto)
11562 (equal (buffer-file-name) file)
11563 (if regionp
11564 (and (>= pos region-start)
11565 (<= pos region-end))
11566 (and (>= pos (point))
11567 (< pos (save-excursion
11568 (org-end-of-subtree t t))))))
11569 (error "Cannot refile to position inside the tree or region"))
11571 (setq nbuf (or (find-buffer-visiting file)
11572 (find-file-noselect file)))
11573 (if (and goto (not (equal goto 3)))
11574 (progn
11575 (org-pop-to-buffer-same-window nbuf)
11576 (goto-char pos)
11577 (org-show-context 'org-goto))
11578 (if regionp
11579 (progn
11580 (org-kill-new (buffer-substring region-start region-end))
11581 (org-save-markers-in-region region-start region-end))
11582 (org-copy-subtree 1 nil t))
11583 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11584 (find-file-noselect file)))
11585 (setq reversed (org-notes-order-reversed-p))
11586 (save-excursion
11587 (save-restriction
11588 (widen)
11589 (if pos
11590 (progn
11591 (goto-char pos)
11592 (looking-at org-outline-regexp)
11593 (setq level (org-get-valid-level (funcall outline-level) 1))
11594 (goto-char
11595 (if reversed
11596 (or (outline-next-heading) (point-max))
11597 (or (save-excursion (org-get-next-sibling))
11598 (org-end-of-subtree t t)
11599 (point-max)))))
11600 (setq level 1)
11601 (if (not reversed)
11602 (goto-char (point-max))
11603 (goto-char (point-min))
11604 (or (outline-next-heading) (goto-char (point-max)))))
11605 (if (not (bolp)) (newline))
11606 (org-paste-subtree level)
11607 (when org-log-refile
11608 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11609 (unless (eq org-log-refile 'note)
11610 (save-excursion (org-add-log-note))))
11611 (and org-auto-align-tags
11612 (let ((org-loop-over-headlines-in-active-region nil))
11613 (org-set-tags nil t)))
11614 (let ((bookmark-name (plist-get org-bookmark-names-plist
11615 :last-refile)))
11616 (when bookmark-name
11617 (with-demoted-errors
11618 (bookmark-set bookmark-name))))
11619 ;; If we are refiling for capture, make sure that the
11620 ;; last-capture pointers point here
11621 (when (org-bound-and-true-p org-refile-for-capture)
11622 (let ((bookmark-name (plist-get org-bookmark-names-plist
11623 :last-capture-marker)))
11624 (when bookmark-name
11625 (with-demoted-errors
11626 (bookmark-set bookmark-name))))
11627 (move-marker org-capture-last-stored-marker (point)))
11628 (if (fboundp 'deactivate-mark) (deactivate-mark))
11629 (run-hooks 'org-after-refile-insert-hook))))
11630 (unless org-refile-keep
11631 (if regionp
11632 (delete-region (point) (+ (point) (- region-end region-start)))
11633 (delete-region
11634 (and (org-back-to-heading t) (point))
11635 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11636 (when (featurep 'org-inlinetask)
11637 (org-inlinetask-remove-END-maybe))
11638 (setq org-markers-to-move nil)
11639 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11641 (defun org-refile-goto-last-stored ()
11642 "Go to the location where the last refile was stored."
11643 (interactive)
11644 (bookmark-jump "org-refile-last-stored")
11645 (message "This is the location of the last refile"))
11647 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11648 no-exclude)
11649 "Prompt the user for a refile location, using PROMPT.
11650 PROMPT should not be suffixed with a colon and a space, because
11651 this function appends the default value from
11652 `org-refile-history' automatically, if that is not empty.
11653 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11654 this is used for the GOTO interface."
11655 (let ((org-refile-targets org-refile-targets)
11656 (org-refile-use-outline-path org-refile-use-outline-path)
11657 excluded-entries)
11658 (when (and (derived-mode-p 'org-mode)
11659 (not org-refile-use-cache)
11660 (not no-exclude))
11661 (org-map-tree
11662 (lambda()
11663 (setq excluded-entries
11664 (append excluded-entries (list (org-get-heading t t)))))))
11665 (setq org-refile-target-table
11666 (org-refile-get-targets default-buffer excluded-entries)))
11667 (unless org-refile-target-table
11668 (user-error "No refile targets"))
11669 (let* ((cbuf (current-buffer))
11670 (partial-completion-mode nil)
11671 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11672 (cfunc (if (and org-refile-use-outline-path
11673 org-outline-path-complete-in-steps)
11674 'org-olpath-completing-read
11675 'org-icompleting-read))
11676 (extra (if org-refile-use-outline-path "/" ""))
11677 (cbnex (concat (buffer-name) extra))
11678 (filename (and cfn (expand-file-name cfn)))
11679 (tbl (mapcar
11680 (lambda (x)
11681 (if (and (not (member org-refile-use-outline-path
11682 '(file full-file-path)))
11683 (not (equal filename (nth 1 x))))
11684 (cons (concat (car x) extra " ("
11685 (file-name-nondirectory (nth 1 x)) ")")
11686 (cdr x))
11687 (cons (concat (car x) extra) (cdr x))))
11688 org-refile-target-table))
11689 (completion-ignore-case t)
11690 cdef
11691 (prompt (concat prompt
11692 (or (and (car org-refile-history)
11693 (concat " (default " (car org-refile-history) ")"))
11694 (and (assoc cbnex tbl) (setq cdef cbnex)
11695 (concat " (default " cbnex ")"))) ": "))
11696 pa answ parent-target child parent old-hist)
11697 (setq old-hist org-refile-history)
11698 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11699 nil 'org-refile-history (or cdef (car org-refile-history))))
11700 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11701 (org-refile-check-position pa)
11702 (if pa
11703 (progn
11704 (when (or (not org-refile-history)
11705 (not (eq old-hist org-refile-history))
11706 (not (equal (car pa) (car org-refile-history))))
11707 (setq org-refile-history
11708 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11709 org-refile-history
11710 (cdr org-refile-history))))
11711 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11712 (pop org-refile-history)))
11714 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11715 (progn
11716 (setq parent (match-string 1 answ)
11717 child (match-string 2 answ))
11718 (setq parent-target (or (assoc parent tbl)
11719 (assoc (concat parent "/") tbl)))
11720 (when (and parent-target
11721 (or (eq new-nodes t)
11722 (and (eq new-nodes 'confirm)
11723 (y-or-n-p (format "Create new node \"%s\"? "
11724 child)))))
11725 (org-refile-new-child parent-target child)))
11726 (user-error "Invalid target location")))))
11728 (declare-function org-string-nw-p "org-macs" (s))
11729 (defun org-refile-check-position (refile-pointer)
11730 "Check if the refile pointer matches the headline to which it points."
11731 (let* ((file (nth 1 refile-pointer))
11732 (re (nth 2 refile-pointer))
11733 (pos (nth 3 refile-pointer))
11734 buffer)
11735 (if (and (not (markerp pos)) (not file))
11736 (user-error "Please save the buffer to a file before refiling")
11737 (when (org-string-nw-p re)
11738 (setq buffer (if (markerp pos)
11739 (marker-buffer pos)
11740 (or (find-buffer-visiting file)
11741 (find-file-noselect file))))
11742 (with-current-buffer buffer
11743 (save-excursion
11744 (save-restriction
11745 (widen)
11746 (goto-char pos)
11747 (beginning-of-line 1)
11748 (unless (org-looking-at-p re)
11749 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11751 (defun org-refile-new-child (parent-target child)
11752 "Use refile target PARENT-TARGET to add new CHILD below it."
11753 (unless parent-target
11754 (error "Cannot find parent for new node"))
11755 (let ((file (nth 1 parent-target))
11756 (pos (nth 3 parent-target))
11757 level)
11758 (with-current-buffer (or (find-buffer-visiting file)
11759 (find-file-noselect file))
11760 (save-excursion
11761 (save-restriction
11762 (widen)
11763 (if pos
11764 (goto-char pos)
11765 (goto-char (point-max))
11766 (if (not (bolp)) (newline)))
11767 (when (looking-at org-outline-regexp)
11768 (setq level (funcall outline-level))
11769 (org-end-of-subtree t t))
11770 (org-back-over-empty-lines)
11771 (insert "\n" (make-string
11772 (if pos (org-get-valid-level level 1) 1) ?*)
11773 " " child "\n")
11774 (beginning-of-line 0)
11775 (list (concat (car parent-target) "/" child) file "" (point)))))))
11777 (defun org-olpath-completing-read (prompt collection &rest args)
11778 "Read an outline path like a file name."
11779 (let ((thetable collection)
11780 (org-completion-use-ido nil) ; does not work with ido.
11781 (org-completion-use-iswitchb nil)) ; or iswitchb
11782 (apply
11783 'org-icompleting-read prompt
11784 (lambda (string predicate &optional flag)
11785 (let (rtn r f (l (length string)))
11786 (cond
11787 ((eq flag nil)
11788 ;; try completion
11789 (try-completion string thetable))
11790 ((eq flag t)
11791 ;; all-completions
11792 (setq rtn (all-completions string thetable predicate))
11793 (mapcar
11794 (lambda (x)
11795 (setq r (substring x l))
11796 (if (string-match " ([^)]*)$" x)
11797 (setq f (match-string 0 x))
11798 (setq f ""))
11799 (if (string-match "/" r)
11800 (concat string (substring r 0 (match-end 0)) f)
11802 rtn))
11803 ((eq flag 'lambda)
11804 ;; exact match?
11805 (assoc string thetable)))))
11806 args)))
11808 ;;;; Dynamic blocks
11810 (defun org-find-dblock (name)
11811 "Find the first dynamic block with name NAME in the buffer.
11812 If not found, stay at current position and return nil."
11813 (let ((case-fold-search t) pos)
11814 (save-excursion
11815 (goto-char (point-min))
11816 (setq pos (and (re-search-forward
11817 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11818 (match-beginning 0))))
11819 (if pos (goto-char pos))
11820 pos))
11822 (defconst org-dblock-start-re
11823 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11824 "Matches the start line of a dynamic block, with parameters.")
11826 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11827 "Matches the end of a dynamic block.")
11829 (defun org-create-dblock (plist)
11830 "Create a dynamic block section, with parameters taken from PLIST.
11831 PLIST must contain a :name entry which is used as name of the block."
11832 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11833 (end-of-line 1)
11834 (newline))
11835 (let ((col (current-column))
11836 (name (plist-get plist :name)))
11837 (insert "#+BEGIN: " name)
11838 (while plist
11839 (if (eq (car plist) :name)
11840 (setq plist (cddr plist))
11841 (insert " " (prin1-to-string (pop plist)))))
11842 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11843 (beginning-of-line -2)))
11845 (defun org-prepare-dblock ()
11846 "Prepare dynamic block for refresh.
11847 This empties the block, puts the cursor at the insert position and returns
11848 the property list including an extra property :name with the block name."
11849 (unless (looking-at org-dblock-start-re)
11850 (user-error "Not at a dynamic block"))
11851 (let* ((begdel (1+ (match-end 0)))
11852 (name (org-no-properties (match-string 1)))
11853 (params (append (list :name name)
11854 (read (concat "(" (match-string 3) ")")))))
11855 (save-excursion
11856 (beginning-of-line 1)
11857 (skip-chars-forward " \t")
11858 (setq params (plist-put params :indentation-column (current-column))))
11859 (unless (re-search-forward org-dblock-end-re nil t)
11860 (error "Dynamic block not terminated"))
11861 (setq params
11862 (append params
11863 (list :content (buffer-substring
11864 begdel (match-beginning 0)))))
11865 (delete-region begdel (match-beginning 0))
11866 (goto-char begdel)
11867 (open-line 1)
11868 params))
11870 (defun org-map-dblocks (&optional command)
11871 "Apply COMMAND to all dynamic blocks in the current buffer.
11872 If COMMAND is not given, use `org-update-dblock'."
11873 (let ((cmd (or command 'org-update-dblock)))
11874 (save-excursion
11875 (goto-char (point-min))
11876 (while (re-search-forward org-dblock-start-re nil t)
11877 (goto-char (match-beginning 0))
11878 (save-excursion
11879 (condition-case nil
11880 (funcall cmd)
11881 (error (message "Error during update of dynamic block"))))
11882 (unless (re-search-forward org-dblock-end-re nil t)
11883 (error "Dynamic block not terminated"))))))
11885 (defun org-dblock-update (&optional arg)
11886 "User command for updating dynamic blocks.
11887 Update the dynamic block at point. With prefix ARG, update all dynamic
11888 blocks in the buffer."
11889 (interactive "P")
11890 (if arg
11891 (org-update-all-dblocks)
11892 (or (looking-at org-dblock-start-re)
11893 (org-beginning-of-dblock))
11894 (org-update-dblock)))
11896 (defun org-update-dblock ()
11897 "Update the dynamic block at point.
11898 This means to empty the block, parse for parameters and then call
11899 the correct writing function."
11900 (interactive)
11901 (save-window-excursion
11902 (let* ((pos (point))
11903 (line (org-current-line))
11904 (params (org-prepare-dblock))
11905 (name (plist-get params :name))
11906 (indent (plist-get params :indentation-column))
11907 (cmd (intern (concat "org-dblock-write:" name))))
11908 (message "Updating dynamic block `%s' at line %d..." name line)
11909 (funcall cmd params)
11910 (message "Updating dynamic block `%s' at line %d...done" name line)
11911 (goto-char pos)
11912 (when (and indent (> indent 0))
11913 (setq indent (make-string indent ?\ ))
11914 (save-excursion
11915 (org-beginning-of-dblock)
11916 (forward-line 1)
11917 (while (not (looking-at org-dblock-end-re))
11918 (insert indent)
11919 (beginning-of-line 2))
11920 (when (looking-at org-dblock-end-re)
11921 (and (looking-at "[ \t]+")
11922 (replace-match ""))
11923 (insert indent)))))))
11925 (defun org-beginning-of-dblock ()
11926 "Find the beginning of the dynamic block at point.
11927 Error if there is no such block at point."
11928 (let ((pos (point))
11929 beg)
11930 (end-of-line 1)
11931 (if (and (re-search-backward org-dblock-start-re nil t)
11932 (setq beg (match-beginning 0))
11933 (re-search-forward org-dblock-end-re nil t)
11934 (> (match-end 0) pos))
11935 (goto-char beg)
11936 (goto-char pos)
11937 (error "Not in a dynamic block"))))
11939 (defun org-update-all-dblocks ()
11940 "Update all dynamic blocks in the buffer.
11941 This function can be used in a hook."
11942 (interactive)
11943 (when (derived-mode-p 'org-mode)
11944 (org-map-dblocks 'org-update-dblock)))
11947 ;;;; Completion
11949 (declare-function org-export-backend-name "org-export" (cl-x))
11950 (declare-function org-export-backend-options "org-export" (cl-x))
11951 (defun org-get-export-keywords ()
11952 "Return a list of all currently understood export keywords.
11953 Export keywords include options, block names, attributes and
11954 keywords relative to each registered export back-end."
11955 (let (keywords)
11956 (dolist (backend
11957 (org-bound-and-true-p org-export--registered-backends)
11958 (delq nil keywords))
11959 ;; Back-end name (for keywords, like #+LATEX:)
11960 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11961 (dolist (option-entry (org-export-backend-options backend))
11962 ;; Back-end options.
11963 (push (nth 1 option-entry) keywords)))))
11965 (defconst org-options-keywords
11966 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11967 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11968 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11969 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11970 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11972 (defcustom org-structure-template-alist
11973 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11974 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11975 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11976 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11977 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11978 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11979 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11980 "<literal style=\"latex\">\n?\n</literal>")
11981 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11982 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11983 "<literal style=\"html\">\n?\n</literal>")
11984 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11985 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11986 ("A" "#+ASCII: " "")
11987 ("i" "#+INDEX: ?" "#+INDEX: ?")
11988 ("I" "#+INCLUDE: %file ?"
11989 "<include file=%file markup=\"?\">"))
11990 "Structure completion elements.
11991 This is a list of abbreviation keys and values. The value gets inserted
11992 if you type `<' followed by the key and then press the completion key,
11993 usually `M-TAB'. %file will be replaced by a file name after prompting
11994 for the file using completion. The cursor will be placed at the position
11995 of the `?` in the template.
11996 There are two templates for each key, the first uses the original Org syntax,
11997 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11998 the default when the /org-mtags.el/ module has been loaded. See also the
11999 variable `org-mtags-prefer-muse-templates'."
12000 :group 'org-completion
12001 :type '(repeat
12002 (list
12003 (string :tag "Key")
12004 (string :tag "Template")
12005 (string :tag "Muse Template"))))
12007 (defun org-try-structure-completion ()
12008 "Try to complete a structure template before point.
12009 This looks for strings like \"<e\" on an otherwise empty line and
12010 expands them."
12011 (let ((l (buffer-substring (point-at-bol) (point)))
12013 (when (and (looking-at "[ \t]*$")
12014 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12015 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12016 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12017 (match-beginning 1)) a)
12018 t)))
12020 (defun org-complete-expand-structure-template (start cell)
12021 "Expand a structure template."
12022 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12023 (rpl (nth (if musep 2 1) cell))
12024 (ind ""))
12025 (delete-region start (point))
12026 (when (string-match "\\`#\\+" rpl)
12027 (cond
12028 ((bolp))
12029 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12030 (setq ind (buffer-substring (point-at-bol) (point))))
12031 (t (newline))))
12032 (setq start (point))
12033 (if (string-match "%file" rpl)
12034 (setq rpl (replace-match
12035 (concat
12036 "\""
12037 (save-match-data
12038 (abbreviate-file-name (read-file-name "Include file: ")))
12039 "\"")
12040 t t rpl)))
12041 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12042 (concat "\n" ind)))
12043 (insert rpl)
12044 (if (re-search-backward "\\?" start t) (delete-char 1))))
12046 ;;;; TODO, DEADLINE, Comments
12048 (defun org-toggle-comment ()
12049 "Change the COMMENT state of an entry."
12050 (interactive)
12051 (save-excursion
12052 (org-back-to-heading)
12053 (let (case-fold-search)
12054 (cond
12055 ((looking-at (format org-heading-keyword-regexp-format
12056 org-comment-string))
12057 (goto-char (match-end 1))
12058 (looking-at (concat " +" org-comment-string))
12059 (replace-match "" t t)
12060 (when (eolp) (insert " ")))
12061 ((looking-at org-outline-regexp)
12062 (goto-char (match-end 0))
12063 (insert org-comment-string " "))))))
12065 (defvar org-last-todo-state-is-todo nil
12066 "This is non-nil when the last TODO state change led to a TODO state.
12067 If the last change removed the TODO tag or switched to DONE, then
12068 this is nil.")
12070 (defvar org-setting-tags nil) ; dynamically skipped
12072 (defvar org-todo-setup-filter-hook nil
12073 "Hook for functions that pre-filter todo specs.
12074 Each function takes a todo spec and returns either nil or the spec
12075 transformed into canonical form." )
12077 (defvar org-todo-get-default-hook nil
12078 "Hook for functions that get a default item for todo.
12079 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12080 nil or a string to be used for the todo mark." )
12082 (defvar org-agenda-headline-snapshot-before-repeat)
12084 (defun org-current-effective-time ()
12085 "Return current time adjusted for `org-extend-today-until' variable."
12086 (let* ((ct (org-current-time))
12087 (dct (decode-time ct))
12088 (ct1
12089 (cond
12090 (org-use-last-clock-out-time-as-effective-time
12091 (or (org-clock-get-last-clock-out-time) ct))
12092 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12093 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12094 (t ct))))
12095 ct1))
12097 (defun org-todo-yesterday (&optional arg)
12098 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12099 (interactive "P")
12100 (if (eq major-mode 'org-agenda-mode)
12101 (apply 'org-agenda-todo-yesterday arg)
12102 (let* ((hour (third (decode-time
12103 (org-current-time))))
12104 (org-extend-today-until (1+ hour)))
12105 (org-todo arg))))
12107 (defvar org-block-entry-blocking ""
12108 "First entry preventing the TODO state change.")
12110 (defun org-todo (&optional arg)
12111 "Change the TODO state of an item.
12112 The state of an item is given by a keyword at the start of the heading,
12113 like
12114 *** TODO Write paper
12115 *** DONE Call mom
12117 The different keywords are specified in the variable `org-todo-keywords'.
12118 By default the available states are \"TODO\" and \"DONE\".
12119 So for this example: when the item starts with TODO, it is changed to DONE.
12120 When it starts with DONE, the DONE is removed. And when neither TODO nor
12121 DONE are present, add TODO at the beginning of the heading.
12123 With \\[universal-argument] prefix arg, use completion to determine the new \
12124 state.
12125 With numeric prefix arg, switch to that state.
12126 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12127 keywords (nextset).
12128 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12129 With a numeric prefix arg of 0, inhibit note taking for the change.
12131 For calling through lisp, arg is also interpreted in the following way:
12132 'none -> empty state
12133 \"\"(empty string) -> switch to empty state
12134 'done -> switch to DONE
12135 'nextset -> switch to the next set of keywords
12136 'previousset -> switch to the previous set of keywords
12137 \"WAITING\" -> switch to the specified keyword, but only if it
12138 really is a member of `org-todo-keywords'."
12139 (interactive "P")
12140 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12141 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12142 'region-start-level 'region))
12143 org-loop-over-headlines-in-active-region)
12144 (org-map-entries
12145 `(org-todo ,arg)
12146 org-loop-over-headlines-in-active-region
12147 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12148 (if (equal arg '(16)) (setq arg 'nextset))
12149 (let ((org-blocker-hook org-blocker-hook)
12150 commentp
12151 case-fold-search)
12152 (when (equal arg '(64))
12153 (setq arg nil org-blocker-hook nil))
12154 (when (and org-blocker-hook
12155 (or org-inhibit-blocking
12156 (org-entry-get nil "NOBLOCKING")))
12157 (setq org-blocker-hook nil))
12158 (save-excursion
12159 (catch 'exit
12160 (org-back-to-heading t)
12161 (when (looking-at (concat "^\\*+ " org-comment-string))
12162 (org-toggle-comment)
12163 (setq commentp t))
12164 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12165 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12166 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12167 (let* ((match-data (match-data))
12168 (startpos (point-at-bol))
12169 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12170 (org-log-done org-log-done)
12171 (org-log-repeat org-log-repeat)
12172 (org-todo-log-states org-todo-log-states)
12173 (org-inhibit-logging
12174 (if (equal arg 0)
12175 (progn (setq arg nil) 'note) org-inhibit-logging))
12176 (this (match-string 1))
12177 (hl-pos (match-beginning 0))
12178 (head (org-get-todo-sequence-head this))
12179 (ass (assoc head org-todo-kwd-alist))
12180 (interpret (nth 1 ass))
12181 (done-word (nth 3 ass))
12182 (final-done-word (nth 4 ass))
12183 (org-last-state (or this ""))
12184 (completion-ignore-case t)
12185 (member (member this org-todo-keywords-1))
12186 (tail (cdr member))
12187 (org-state (cond
12188 ((and org-todo-key-trigger
12189 (or (and (equal arg '(4))
12190 (eq org-use-fast-todo-selection 'prefix))
12191 (and (not arg) org-use-fast-todo-selection
12192 (not (eq org-use-fast-todo-selection
12193 'prefix)))))
12194 ;; Use fast selection
12195 (org-fast-todo-selection))
12196 ((and (equal arg '(4))
12197 (or (not org-use-fast-todo-selection)
12198 (not org-todo-key-trigger)))
12199 ;; Read a state with completion
12200 (org-icompleting-read
12201 "State: " (mapcar 'list org-todo-keywords-1)
12202 nil t))
12203 ((eq arg 'right)
12204 (if this
12205 (if tail (car tail) nil)
12206 (car org-todo-keywords-1)))
12207 ((eq arg 'left)
12208 (if (equal member org-todo-keywords-1)
12210 (if this
12211 (nth (- (length org-todo-keywords-1)
12212 (length tail) 2)
12213 org-todo-keywords-1)
12214 (org-last org-todo-keywords-1))))
12215 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12216 (setq arg nil))) ; hack to fall back to cycling
12217 (arg
12218 ;; user or caller requests a specific state
12219 (cond
12220 ((equal arg "") nil)
12221 ((eq arg 'none) nil)
12222 ((eq arg 'done) (or done-word (car org-done-keywords)))
12223 ((eq arg 'nextset)
12224 (or (car (cdr (member head org-todo-heads)))
12225 (car org-todo-heads)))
12226 ((eq arg 'previousset)
12227 (let ((org-todo-heads (reverse org-todo-heads)))
12228 (or (car (cdr (member head org-todo-heads)))
12229 (car org-todo-heads))))
12230 ((car (member arg org-todo-keywords-1)))
12231 ((stringp arg)
12232 (user-error "State `%s' not valid in this file" arg))
12233 ((nth (1- (prefix-numeric-value arg))
12234 org-todo-keywords-1))))
12235 ((null member) (or head (car org-todo-keywords-1)))
12236 ((equal this final-done-word) nil) ;; -> make empty
12237 ((null tail) nil) ;; -> first entry
12238 ((memq interpret '(type priority))
12239 (if (eq this-command last-command)
12240 (car tail)
12241 (if (> (length tail) 0)
12242 (or done-word (car org-done-keywords))
12243 nil)))
12245 (car tail))))
12246 (org-state (or
12247 (run-hook-with-args-until-success
12248 'org-todo-get-default-hook org-state org-last-state)
12249 org-state))
12250 (next (if org-state (concat " " org-state " ") " "))
12251 (change-plist (list :type 'todo-state-change :from this :to org-state
12252 :position startpos))
12253 dolog now-done-p)
12254 (when org-blocker-hook
12255 (setq org-last-todo-state-is-todo
12256 (not (member this org-done-keywords)))
12257 (unless (save-excursion
12258 (save-match-data
12259 (org-with-wide-buffer
12260 (run-hook-with-args-until-failure
12261 'org-blocker-hook change-plist))))
12262 (if (org-called-interactively-p 'interactive)
12263 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12264 this org-state org-block-entry-blocking)
12265 ;; fail silently
12266 (message "TODO state change from %s to %s blocked (by \"%s\")"
12267 this org-state org-block-entry-blocking)
12268 (throw 'exit nil))))
12269 (store-match-data match-data)
12270 (replace-match next t t)
12271 (unless (pos-visible-in-window-p hl-pos)
12272 (message "TODO state changed to %s" (org-trim next)))
12273 (unless head
12274 (setq head (org-get-todo-sequence-head org-state)
12275 ass (assoc head org-todo-kwd-alist)
12276 interpret (nth 1 ass)
12277 done-word (nth 3 ass)
12278 final-done-word (nth 4 ass)))
12279 (when (memq arg '(nextset previousset))
12280 (message "Keyword-Set %d/%d: %s"
12281 (- (length org-todo-sets) -1
12282 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12283 (length org-todo-sets)
12284 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12285 (setq org-last-todo-state-is-todo
12286 (not (member org-state org-done-keywords)))
12287 (setq now-done-p (and (member org-state org-done-keywords)
12288 (not (member this org-done-keywords))))
12289 (and logging (org-local-logging logging))
12290 (when (and (or org-todo-log-states org-log-done)
12291 (not (eq org-inhibit-logging t))
12292 (not (memq arg '(nextset previousset))))
12293 ;; we need to look at recording a time and note
12294 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12295 (nth 2 (assoc this org-todo-log-states))))
12296 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12297 (setq dolog 'time))
12298 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12299 (and org-state
12300 (member org-state org-not-done-keywords)
12301 (not (member this org-not-done-keywords))))
12302 ;; This is now a todo state and was not one before
12303 ;; If there was a CLOSED time stamp, get rid of it.
12304 (org-add-planning-info nil nil 'closed))
12305 (when (and now-done-p org-log-done)
12306 ;; It is now done, and it was not done before
12307 (org-add-planning-info 'closed (org-current-effective-time))
12308 (if (and (not dolog) (eq 'note org-log-done))
12309 (org-add-log-setup 'done org-state this 'findpos 'note)))
12310 (when (and org-state dolog)
12311 ;; This is a non-nil state, and we need to log it
12312 (org-add-log-setup 'state org-state this 'findpos dolog)))
12313 ;; Fixup tag positioning
12314 (org-todo-trigger-tag-changes org-state)
12315 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12316 (when org-provide-todo-statistics
12317 (org-update-parent-todo-statistics))
12318 (run-hooks 'org-after-todo-state-change-hook)
12319 (if (and arg (not (member org-state org-done-keywords)))
12320 (setq head (org-get-todo-sequence-head org-state)))
12321 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12322 ;; Do we need to trigger a repeat?
12323 (when now-done-p
12324 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12325 ;; This is for the agenda, take a snapshot of the headline.
12326 (save-match-data
12327 (setq org-agenda-headline-snapshot-before-repeat
12328 (org-get-heading))))
12329 (org-auto-repeat-maybe org-state))
12330 ;; Fixup cursor location if close to the keyword
12331 (if (and (outline-on-heading-p)
12332 (not (bolp))
12333 (save-excursion (beginning-of-line 1)
12334 (looking-at org-todo-line-regexp))
12335 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12336 (progn
12337 (goto-char (or (match-end 2) (match-end 1)))
12338 (and (looking-at " ") (just-one-space))))
12339 (when org-trigger-hook
12340 (save-excursion
12341 (run-hook-with-args 'org-trigger-hook change-plist)))
12342 (when commentp (org-toggle-comment))))))))
12344 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12345 "Block turning an entry into a TODO, using the hierarchy.
12346 This checks whether the current task should be blocked from state
12347 changes. Such blocking occurs when:
12349 1. The task has children which are not all in a completed state.
12351 2. A task has a parent with the property :ORDERED:, and there
12352 are siblings prior to the current task with incomplete
12353 status.
12355 3. The parent of the task is blocked because it has siblings that should
12356 be done first, or is child of a block grandparent TODO entry."
12358 (if (not org-enforce-todo-dependencies)
12359 t ; if locally turned off don't block
12360 (catch 'dont-block
12361 ;; If this is not a todo state change, or if this entry is already DONE,
12362 ;; do not block
12363 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12364 (member (plist-get change-plist :from)
12365 (cons 'done org-done-keywords))
12366 (member (plist-get change-plist :to)
12367 (cons 'todo org-not-done-keywords))
12368 (not (plist-get change-plist :to)))
12369 (throw 'dont-block t))
12370 ;; If this task has children, and any are undone, it's blocked
12371 (save-excursion
12372 (org-back-to-heading t)
12373 (let ((this-level (funcall outline-level)))
12374 (outline-next-heading)
12375 (let ((child-level (funcall outline-level)))
12376 (while (and (not (eobp))
12377 (> child-level this-level))
12378 ;; this todo has children, check whether they are all
12379 ;; completed
12380 (if (and (not (org-entry-is-done-p))
12381 (org-entry-is-todo-p))
12382 (progn (setq org-block-entry-blocking (org-get-heading))
12383 (throw 'dont-block nil)))
12384 (outline-next-heading)
12385 (setq child-level (funcall outline-level))))))
12386 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12387 ;; any previous siblings are undone, it's blocked
12388 (save-excursion
12389 (org-back-to-heading t)
12390 (let* ((pos (point))
12391 (parent-pos (and (org-up-heading-safe) (point))))
12392 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12393 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12394 (forward-line 1)
12395 (re-search-forward org-not-done-heading-regexp pos t))
12396 (setq org-block-entry-blocking (match-string 0))
12397 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12398 ;; Search further up the hierarchy, to see if an ancestor is blocked
12399 (while t
12400 (goto-char parent-pos)
12401 (if (not (looking-at org-not-done-heading-regexp))
12402 (throw 'dont-block t)) ; do not block, parent is not a TODO
12403 (setq pos (point))
12404 (setq parent-pos (and (org-up-heading-safe) (point)))
12405 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12406 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12407 (forward-line 1)
12408 (re-search-forward org-not-done-heading-regexp pos t)
12409 (setq org-block-entry-blocking (org-get-heading)))
12410 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12412 (defcustom org-track-ordered-property-with-tag nil
12413 "Should the ORDERED property also be shown as a tag?
12414 The ORDERED property decides if an entry should require subtasks to be
12415 completed in sequence. Since a property is not very visible, setting
12416 this option means that toggling the ORDERED property with the command
12417 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12418 not relevant for the behavior, but it makes things more visible.
12420 Note that toggling the tag with tags commands will not change the property
12421 and therefore not influence behavior!
12423 This can be t, meaning the tag ORDERED should be used, It can also be a
12424 string to select a different tag for this task."
12425 :group 'org-todo
12426 :type '(choice
12427 (const :tag "No tracking" nil)
12428 (const :tag "Track with ORDERED tag" t)
12429 (string :tag "Use other tag")))
12431 (defun org-toggle-ordered-property ()
12432 "Toggle the ORDERED property of the current entry.
12433 For better visibility, you can track the value of this property with a tag.
12434 See variable `org-track-ordered-property-with-tag'."
12435 (interactive)
12436 (let* ((t1 org-track-ordered-property-with-tag)
12437 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12438 (save-excursion
12439 (org-back-to-heading)
12440 (if (org-entry-get nil "ORDERED")
12441 (progn
12442 (org-delete-property "ORDERED")
12443 (and tag (org-toggle-tag tag 'off))
12444 (message "Subtasks can be completed in arbitrary order"))
12445 (org-entry-put nil "ORDERED" "t")
12446 (and tag (org-toggle-tag tag 'on))
12447 (message "Subtasks must be completed in sequence")))))
12449 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12450 (defun org-block-todo-from-checkboxes (change-plist)
12451 "Block turning an entry into a TODO, using checkboxes.
12452 This checks whether the current task should be blocked from state
12453 changes because there are unchecked boxes in this entry."
12454 (if (not org-enforce-todo-checkbox-dependencies)
12455 t ; if locally turned off don't block
12456 (catch 'dont-block
12457 ;; If this is not a todo state change, or if this entry is already DONE,
12458 ;; do not block
12459 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12460 (member (plist-get change-plist :from)
12461 (cons 'done org-done-keywords))
12462 (member (plist-get change-plist :to)
12463 (cons 'todo org-not-done-keywords))
12464 (not (plist-get change-plist :to)))
12465 (throw 'dont-block t))
12466 ;; If this task has checkboxes that are not checked, it's blocked
12467 (save-excursion
12468 (org-back-to-heading t)
12469 (let ((beg (point)) end)
12470 (outline-next-heading)
12471 (setq end (point))
12472 (goto-char beg)
12473 (if (org-list-search-forward
12474 (concat (org-item-beginning-re)
12475 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12476 "\\[[- ]\\]")
12477 end t)
12478 (progn
12479 (if (boundp 'org-blocked-by-checkboxes)
12480 (setq org-blocked-by-checkboxes t))
12481 (throw 'dont-block nil)))))
12482 t))) ; do not block
12484 (defun org-entry-blocked-p ()
12485 "Is the current entry blocked?"
12486 (org-with-silent-modifications
12487 (if (org-entry-get nil "NOBLOCKING")
12488 nil ;; Never block this entry
12489 (not (run-hook-with-args-until-failure
12490 'org-blocker-hook
12491 (list :type 'todo-state-change
12492 :position (point)
12493 :from 'todo
12494 :to 'done))))))
12496 (defun org-update-statistics-cookies (all)
12497 "Update the statistics cookie, either from TODO or from checkboxes.
12498 This should be called with the cursor in a line with a statistics cookie."
12499 (interactive "P")
12500 (if all
12501 (progn
12502 (org-update-checkbox-count 'all)
12503 (org-map-entries 'org-update-parent-todo-statistics))
12504 (if (not (org-at-heading-p))
12505 (org-update-checkbox-count)
12506 (let ((pos (point-marker))
12507 end l1 l2)
12508 (ignore-errors (org-back-to-heading t))
12509 (if (not (org-at-heading-p))
12510 (org-update-checkbox-count)
12511 (setq l1 (org-outline-level))
12512 (setq end (save-excursion
12513 (outline-next-heading)
12514 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12515 (point)))
12516 (if (and (save-excursion
12517 (re-search-forward
12518 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12519 (not (save-excursion (re-search-forward
12520 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12521 (org-update-checkbox-count)
12522 (if (and l2 (> l2 l1))
12523 (progn
12524 (goto-char end)
12525 (org-update-parent-todo-statistics))
12526 (goto-char pos)
12527 (beginning-of-line 1)
12528 (while (re-search-forward
12529 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12530 (point-at-eol) t)
12531 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12532 (goto-char pos)
12533 (move-marker pos nil)))))
12535 (defvar org-entry-property-inherited-from) ;; defined below
12536 (defun org-update-parent-todo-statistics ()
12537 "Update any statistics cookie in the parent of the current headline.
12538 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12539 the entire subtree and this will travel up the hierarchy and update
12540 statistics everywhere."
12541 (let* ((prop (save-excursion (org-up-heading-safe)
12542 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12543 (recursive (or (not org-hierarchical-todo-statistics)
12544 (and prop (string-match "\\<recursive\\>" prop))))
12545 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12547 (first t)
12548 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12549 level ltoggle l1 new ndel
12550 (cnt-all 0) (cnt-done 0) is-percent kwd
12551 checkbox-beg ov ovs ove cookie-present)
12552 (catch 'exit
12553 (save-excursion
12554 (beginning-of-line 1)
12555 (setq ltoggle (funcall outline-level))
12556 ;; Three situations are to consider:
12558 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12559 ;; to the top-level ancestor on the headline;
12561 ;; 2. If parent has "recursive" property, repeat up to the
12562 ;; headline setting that property, taking inheritance into
12563 ;; account;
12565 ;; 3. Else, move up to direct parent and proceed only once.
12566 (while (and (setq level (org-up-heading-safe))
12567 (or recursive first)
12568 (>= (point) lim))
12569 (setq first nil cookie-present nil)
12570 (unless (and level
12571 (not (string-match
12572 "\\<checkbox\\>"
12573 (downcase (or (org-entry-get nil "COOKIE_DATA")
12574 "")))))
12575 (throw 'exit nil))
12576 (while (re-search-forward box-re (point-at-eol) t)
12577 (setq cnt-all 0 cnt-done 0 cookie-present t)
12578 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12579 (save-match-data
12580 (unless (outline-next-heading) (throw 'exit nil))
12581 (while (and (looking-at org-complex-heading-regexp)
12582 (> (setq l1 (length (match-string 1))) level))
12583 (setq kwd (and (or recursive (= l1 ltoggle))
12584 (match-string 2)))
12585 (if (or (eq org-provide-todo-statistics 'all-headlines)
12586 (and (listp org-provide-todo-statistics)
12587 (or (member kwd org-provide-todo-statistics)
12588 (member kwd org-done-keywords))))
12589 (setq cnt-all (1+ cnt-all))
12590 (if (eq org-provide-todo-statistics t)
12591 (and kwd (setq cnt-all (1+ cnt-all)))))
12592 (and (member kwd org-done-keywords)
12593 (setq cnt-done (1+ cnt-done)))
12594 (outline-next-heading)))
12595 (setq new
12596 (if is-percent
12597 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12598 (format "[%d/%d]" cnt-done cnt-all))
12599 ndel (- (match-end 0) checkbox-beg))
12600 ;; handle overlays when updating cookie from column view
12601 (when (setq ov (car (overlays-at checkbox-beg)))
12602 (setq ovs (overlay-start ov) ove (overlay-end ov))
12603 (delete-overlay ov))
12604 (goto-char checkbox-beg)
12605 (insert new)
12606 (delete-region (point) (+ (point) ndel))
12607 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12608 (when ov (move-overlay ov ovs ove)))
12609 (when cookie-present
12610 (run-hook-with-args 'org-after-todo-statistics-hook
12611 cnt-done (- cnt-all cnt-done))))))
12612 (run-hooks 'org-todo-statistics-hook)))
12614 (defvar org-after-todo-statistics-hook nil
12615 "Hook that is called after a TODO statistics cookie has been updated.
12616 Each function is called with two arguments: the number of not-done entries
12617 and the number of done entries.
12619 For example, the following function, when added to this hook, will switch
12620 an entry to DONE when all children are done, and back to TODO when new
12621 entries are set to a TODO status. Note that this hook is only called
12622 when there is a statistics cookie in the headline!
12624 (defun org-summary-todo (n-done n-not-done)
12625 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12626 (let (org-log-done org-log-states) ; turn off logging
12627 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12630 (defvar org-todo-statistics-hook nil
12631 "Hook that is run whenever Org thinks TODO statistics should be updated.
12632 This hook runs even if there is no statistics cookie present, in which case
12633 `org-after-todo-statistics-hook' would not run.")
12635 (defun org-todo-trigger-tag-changes (state)
12636 "Apply the changes defined in `org-todo-state-tags-triggers'."
12637 (let ((l org-todo-state-tags-triggers)
12638 changes)
12639 (when (or (not state) (equal state ""))
12640 (setq changes (append changes (cdr (assoc "" l)))))
12641 (when (and (stringp state) (> (length state) 0))
12642 (setq changes (append changes (cdr (assoc state l)))))
12643 (when (member state org-not-done-keywords)
12644 (setq changes (append changes (cdr (assoc 'todo l)))))
12645 (when (member state org-done-keywords)
12646 (setq changes (append changes (cdr (assoc 'done l)))))
12647 (dolist (c changes)
12648 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12650 (defun org-local-logging (value)
12651 "Get logging settings from a property VALUE."
12652 (let* (words w a)
12653 ;; directly set the variables, they are already local.
12654 (setq org-log-done nil
12655 org-log-repeat nil
12656 org-todo-log-states nil)
12657 (setq words (org-split-string value))
12658 (while (setq w (pop words))
12659 (cond
12660 ((setq a (assoc w org-startup-options))
12661 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12662 (set (nth 1 a) (nth 2 a))))
12663 ((setq a (org-extract-log-state-settings w))
12664 (and (member (car a) org-todo-keywords-1)
12665 (push a org-todo-log-states)))))))
12667 (defun org-get-todo-sequence-head (kwd)
12668 "Return the head of the TODO sequence to which KWD belongs.
12669 If KWD is not set, check if there is a text property remembering the
12670 right sequence."
12671 (let (p)
12672 (cond
12673 ((not kwd)
12674 (or (get-text-property (point-at-bol) 'org-todo-head)
12675 (progn
12676 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12677 nil (point-at-eol)))
12678 (get-text-property p 'org-todo-head))))
12679 ((not (member kwd org-todo-keywords-1))
12680 (car org-todo-keywords-1))
12681 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12683 (defun org-fast-todo-selection ()
12684 "Fast TODO keyword selection with single keys.
12685 Returns the new TODO keyword, or nil if no state change should occur."
12686 (let* ((fulltable org-todo-key-alist)
12687 (done-keywords org-done-keywords) ;; needed for the faces.
12688 (maxlen (apply 'max (mapcar
12689 (lambda (x)
12690 (if (stringp (car x)) (string-width (car x)) 0))
12691 fulltable)))
12692 (expert nil)
12693 (fwidth (+ maxlen 3 1 3))
12694 (ncol (/ (- (window-width) 4) fwidth))
12695 tg cnt e c tbl
12696 groups ingroup)
12697 (save-excursion
12698 (save-window-excursion
12699 (if expert
12700 (set-buffer (get-buffer-create " *Org todo*"))
12701 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12702 (erase-buffer)
12703 (org-set-local 'org-done-keywords done-keywords)
12704 (setq tbl fulltable cnt 0)
12705 (while (setq e (pop tbl))
12706 (cond
12707 ((equal e '(:startgroup))
12708 (push '() groups) (setq ingroup t)
12709 (when (not (= cnt 0))
12710 (setq cnt 0)
12711 (insert "\n"))
12712 (insert "{ "))
12713 ((equal e '(:endgroup))
12714 (setq ingroup nil cnt 0)
12715 (insert "}\n"))
12716 ((equal e '(:newline))
12717 (when (not (= cnt 0))
12718 (setq cnt 0)
12719 (insert "\n")
12720 (setq e (car tbl))
12721 (while (equal (car tbl) '(:newline))
12722 (insert "\n")
12723 (setq tbl (cdr tbl)))))
12725 (setq tg (car e) c (cdr e))
12726 (if ingroup (push tg (car groups)))
12727 (setq tg (org-add-props tg nil 'face
12728 (org-get-todo-face tg)))
12729 (if (and (= cnt 0) (not ingroup)) (insert " "))
12730 (insert "[" c "] " tg (make-string
12731 (- fwidth 4 (length tg)) ?\ ))
12732 (when (= (setq cnt (1+ cnt)) ncol)
12733 (insert "\n")
12734 (if ingroup (insert " "))
12735 (setq cnt 0)))))
12736 (insert "\n")
12737 (goto-char (point-min))
12738 (if (not expert) (org-fit-window-to-buffer))
12739 (message "[a-z..]:Set [SPC]:clear")
12740 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12741 (cond
12742 ((or (= c ?\C-g)
12743 (and (= c ?q) (not (rassoc c fulltable))))
12744 (setq quit-flag t))
12745 ((= c ?\ ) nil)
12746 ((setq e (rassoc c fulltable) tg (car e))
12748 (t (setq quit-flag t)))))))
12750 (defun org-entry-is-todo-p ()
12751 (member (org-get-todo-state) org-not-done-keywords))
12753 (defun org-entry-is-done-p ()
12754 (member (org-get-todo-state) org-done-keywords))
12756 (defun org-get-todo-state ()
12757 "Return the TODO keyword of the current subtree."
12758 (save-excursion
12759 (org-back-to-heading t)
12760 (and (looking-at org-todo-line-regexp)
12761 (match-end 2)
12762 (match-string 2))))
12764 (defun org-at-date-range-p (&optional inactive-ok)
12765 "Is the cursor inside a date range?"
12766 (interactive)
12767 (save-excursion
12768 (catch 'exit
12769 (let ((pos (point)))
12770 (skip-chars-backward "^[<\r\n")
12771 (skip-chars-backward "<[")
12772 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12773 (>= (match-end 0) pos)
12774 (throw 'exit t))
12775 (skip-chars-backward "^<[\r\n")
12776 (skip-chars-backward "<[")
12777 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12778 (>= (match-end 0) pos)
12779 (throw 'exit t)))
12780 nil)))
12782 (defun org-get-repeat (&optional tagline)
12783 "Check if there is a deadline/schedule with repeater in this entry."
12784 (save-match-data
12785 (save-excursion
12786 (org-back-to-heading t)
12787 (and (re-search-forward (if tagline
12788 (concat tagline "\\s-*" org-repeat-re)
12789 org-repeat-re)
12790 (org-entry-end-position) t)
12791 (match-string-no-properties 1)))))
12793 (defvar org-last-changed-timestamp)
12794 (defvar org-last-inserted-timestamp)
12795 (defvar org-log-post-message)
12796 (defvar org-log-note-purpose)
12797 (defvar org-log-note-how)
12798 (defvar org-log-note-extra)
12799 (defun org-auto-repeat-maybe (done-word)
12800 "Check if the current headline contains a repeated deadline/schedule.
12801 If yes, set TODO state back to what it was and change the base date
12802 of repeating deadline/scheduled time stamps to new date.
12803 This function is run automatically after each state change to a DONE state."
12804 ;; last-state is dynamically scoped into this function
12805 (let* ((repeat (org-get-repeat))
12806 (aa (assoc org-last-state org-todo-kwd-alist))
12807 (interpret (nth 1 aa))
12808 (head (nth 2 aa))
12809 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12810 (msg "Entry repeats: ")
12811 (org-log-done nil)
12812 (org-todo-log-states nil)
12813 re type n what ts time to-state)
12814 (when repeat
12815 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12816 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12817 org-todo-repeat-to-state))
12818 (unless (and to-state (member to-state org-todo-keywords-1))
12819 (setq to-state (if (eq interpret 'type) org-last-state head)))
12820 (org-todo to-state)
12821 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12822 (org-entry-put nil "LAST_REPEAT" (format-time-string
12823 (org-time-stamp-format t t))))
12824 (when org-log-repeat
12825 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12826 (memq 'org-add-log-note post-command-hook))
12827 ;; OK, we are already setup for some record
12828 (if (eq org-log-repeat 'note)
12829 ;; make sure we take a note, not only a time stamp
12830 (setq org-log-note-how 'note))
12831 ;; Set up for taking a record
12832 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12833 org-last-state
12834 'findpos org-log-repeat)))
12835 (org-back-to-heading t)
12836 (org-add-planning-info nil nil 'closed)
12837 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12838 org-deadline-time-regexp "\\)\\|\\("
12839 org-ts-regexp "\\)"))
12840 (while (re-search-forward
12841 re (save-excursion (outline-next-heading) (point)) t)
12842 (setq type (if (match-end 1) org-scheduled-string
12843 (if (match-end 3) org-deadline-string "Plain:"))
12844 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12845 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12846 (setq n (string-to-number (match-string 2 ts))
12847 what (match-string 3 ts))
12848 (if (equal what "w") (setq n (* n 7) what "d"))
12849 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12850 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12851 ;; Preparation, see if we need to modify the start date for the change
12852 (when (match-end 1)
12853 (setq time (save-match-data (org-time-string-to-time ts)))
12854 (cond
12855 ((equal (match-string 1 ts) ".")
12856 ;; Shift starting date to today
12857 (org-timestamp-change
12858 (- (org-today) (time-to-days time))
12859 'day))
12860 ((equal (match-string 1 ts) "+")
12861 (let ((nshiftmax 10) (nshift 0))
12862 (while (or (= nshift 0)
12863 (<= (time-to-days time)
12864 (time-to-days (current-time))))
12865 (when (= (incf nshift) nshiftmax)
12866 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12867 (error "Abort")))
12868 (org-timestamp-change n (cdr (assoc what whata)))
12869 (org-at-timestamp-p t)
12870 (setq ts (match-string 1))
12871 (setq time (save-match-data (org-time-string-to-time ts)))))
12872 (org-timestamp-change (- n) (cdr (assoc what whata)))
12873 ;; rematch, so that we have everything in place for the real shift
12874 (org-at-timestamp-p t)
12875 (setq ts (match-string 1))
12876 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12877 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12878 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12879 (setq org-log-post-message msg)
12880 (message "%s" msg))))
12882 (defun org-show-todo-tree (arg)
12883 "Make a compact tree which shows all headlines marked with TODO.
12884 The tree will show the lines where the regexp matches, and all higher
12885 headlines above the match.
12886 With a \\[universal-argument] prefix, prompt for a regexp to match.
12887 With a numeric prefix N, construct a sparse tree for the Nth element
12888 of `org-todo-keywords-1'."
12889 (interactive "P")
12890 (let ((case-fold-search nil)
12891 (kwd-re
12892 (cond ((null arg) org-not-done-regexp)
12893 ((equal arg '(4))
12894 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12895 (mapcar 'list org-todo-keywords-1))))
12896 (concat "\\("
12897 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12898 "\\)\\>")))
12899 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12900 (regexp-quote (nth (1- (prefix-numeric-value arg))
12901 org-todo-keywords-1)))
12902 (t (user-error "Invalid prefix argument: %s" arg)))))
12903 (message "%d TODO entries found"
12904 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12906 (defun org-deadline (arg &optional time)
12907 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12908 With one universal prefix argument, remove any deadline from the item.
12909 With two universal prefix arguments, prompt for a warning delay.
12910 With argument TIME, set the deadline at the corresponding date. TIME
12911 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12912 (interactive "P")
12913 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12914 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12915 'region-start-level 'region))
12916 org-loop-over-headlines-in-active-region)
12917 (org-map-entries
12918 `(org-deadline ',arg ,time)
12919 org-loop-over-headlines-in-active-region
12920 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12921 (let* ((old-date (org-entry-get nil "DEADLINE"))
12922 (old-date-time (if old-date (org-time-string-to-time old-date)))
12923 (repeater (and old-date
12924 (string-match
12925 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12926 old-date)
12927 (match-string 1 old-date))))
12928 (cond
12929 ((equal arg '(4))
12930 (when (and old-date org-log-redeadline)
12931 (org-add-log-setup 'deldeadline nil old-date 'findpos
12932 org-log-redeadline))
12933 (org-remove-timestamp-with-keyword org-deadline-string)
12934 (message "Item no longer has a deadline."))
12935 ((equal arg '(16))
12936 (save-excursion
12937 (if (re-search-forward
12938 org-deadline-time-regexp
12939 (save-excursion (outline-next-heading) (point)) t)
12940 (let* ((rpl0 (match-string 1))
12941 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12942 (replace-match
12943 (concat org-deadline-string
12944 " <" rpl
12945 (format " -%dd"
12946 (abs
12947 (- (time-to-days
12948 (save-match-data
12949 (org-read-date nil t nil "Warn starting from" old-date-time)))
12950 (time-to-days old-date-time))))
12951 ">") t t))
12952 (user-error "No deadline information to update"))))
12954 (org-add-planning-info 'deadline time 'closed)
12955 (when (and old-date org-log-redeadline
12956 (not (equal old-date
12957 (substring org-last-inserted-timestamp 1 -1))))
12958 (org-add-log-setup 'redeadline nil old-date 'findpos
12959 org-log-redeadline))
12960 (when repeater
12961 (save-excursion
12962 (org-back-to-heading t)
12963 (when (re-search-forward (concat org-deadline-string " "
12964 org-last-inserted-timestamp)
12965 (save-excursion
12966 (outline-next-heading) (point)) t)
12967 (goto-char (1- (match-end 0)))
12968 (insert " " repeater)
12969 (setq org-last-inserted-timestamp
12970 (concat (substring org-last-inserted-timestamp 0 -1)
12971 " " repeater
12972 (substring org-last-inserted-timestamp -1))))))
12973 (message "Deadline on %s" org-last-inserted-timestamp))))))
12975 (defun org-schedule (arg &optional time)
12976 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12977 With one universal prefix argument, remove any scheduling date from the item.
12978 With two universal prefix arguments, prompt for a delay cookie.
12979 With argument TIME, scheduled at the corresponding date. TIME can
12980 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12981 (interactive "P")
12982 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12983 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12984 'region-start-level 'region))
12985 org-loop-over-headlines-in-active-region)
12986 (org-map-entries
12987 `(org-schedule ',arg ,time)
12988 org-loop-over-headlines-in-active-region
12989 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12990 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12991 (old-date-time (if old-date (org-time-string-to-time old-date)))
12992 (repeater (and old-date
12993 (string-match
12994 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12995 old-date)
12996 (match-string 1 old-date))))
12997 (cond
12998 ((equal arg '(4))
12999 (progn
13000 (when (and old-date org-log-reschedule)
13001 (org-add-log-setup 'delschedule nil old-date 'findpos
13002 org-log-reschedule))
13003 (org-remove-timestamp-with-keyword org-scheduled-string)
13004 (message "Item is no longer scheduled.")))
13005 ((equal arg '(16))
13006 (save-excursion
13007 (if (re-search-forward
13008 org-scheduled-time-regexp
13009 (save-excursion (outline-next-heading) (point)) t)
13010 (let* ((rpl0 (match-string 1))
13011 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13012 (replace-match
13013 (concat org-scheduled-string
13014 " <" rpl
13015 (format " -%dd"
13016 (abs
13017 (- (time-to-days
13018 (save-match-data
13019 (org-read-date nil t nil "Delay until" old-date-time)))
13020 (time-to-days old-date-time))))
13021 ">") t t))
13022 (user-error "No scheduled information to update"))))
13024 (org-add-planning-info 'scheduled time 'closed)
13025 (when (and old-date org-log-reschedule
13026 (not (equal old-date
13027 (substring org-last-inserted-timestamp 1 -1))))
13028 (org-add-log-setup 'reschedule nil old-date 'findpos
13029 org-log-reschedule))
13030 (when repeater
13031 (save-excursion
13032 (org-back-to-heading t)
13033 (when (re-search-forward (concat org-scheduled-string " "
13034 org-last-inserted-timestamp)
13035 (save-excursion
13036 (outline-next-heading) (point)) t)
13037 (goto-char (1- (match-end 0)))
13038 (insert " " repeater)
13039 (setq org-last-inserted-timestamp
13040 (concat (substring org-last-inserted-timestamp 0 -1)
13041 " " repeater
13042 (substring org-last-inserted-timestamp -1))))))
13043 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13045 (defun org-get-scheduled-time (pom &optional inherit)
13046 "Get the scheduled time as a time tuple, of a format suitable
13047 for calling org-schedule with, or if there is no scheduling,
13048 returns nil."
13049 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13050 (when time
13051 (apply 'encode-time (org-parse-time-string time)))))
13053 (defun org-get-deadline-time (pom &optional inherit)
13054 "Get the deadline as a time tuple, of a format suitable for
13055 calling org-deadline with, or if there is no scheduling, returns
13056 nil."
13057 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13058 (when time
13059 (apply 'encode-time (org-parse-time-string time)))))
13061 (defun org-remove-timestamp-with-keyword (keyword)
13062 "Remove all time stamps with KEYWORD in the current entry."
13063 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13064 beg)
13065 (save-excursion
13066 (org-back-to-heading t)
13067 (setq beg (point))
13068 (outline-next-heading)
13069 (while (re-search-backward re beg t)
13070 (replace-match "")
13071 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13072 (equal (char-before) ?\ ))
13073 (backward-delete-char 1)
13074 (if (string-match "^[ \t]*$" (buffer-substring
13075 (point-at-bol) (point-at-eol)))
13076 (delete-region (point-at-bol)
13077 (min (point-max) (1+ (point-at-eol))))))))))
13079 (defun org-add-planning-info (what &optional time &rest remove)
13080 "Insert new timestamp with keyword in the line directly after the headline.
13081 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13082 If non is given, the user is prompted for a date.
13083 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13084 be removed."
13085 (interactive)
13086 (let (org-time-was-given org-end-time-was-given ts
13087 end default-time default-input)
13089 (catch 'exit
13090 (when (and (memq what '(scheduled deadline))
13091 (or (not time)
13092 (and (stringp time)
13093 (string-match "^[-+]+[0-9]" time))))
13094 ;; Try to get a default date/time from existing timestamp
13095 (save-excursion
13096 (org-back-to-heading t)
13097 (setq end (save-excursion (outline-next-heading) (point)))
13098 (when (re-search-forward (if (eq what 'scheduled)
13099 org-scheduled-time-regexp
13100 org-deadline-time-regexp)
13101 end t)
13102 (setq ts (match-string 1)
13103 default-time
13104 (apply 'encode-time (org-parse-time-string ts))
13105 default-input (and ts (org-get-compact-tod ts))))))
13106 (when what
13107 (setq time
13108 (if (stringp time)
13109 ;; This is a string (relative or absolute), set proper date
13110 (apply 'encode-time
13111 (org-read-date-analyze
13112 time default-time (decode-time default-time)))
13113 ;; If necessary, get the time from the user
13114 (or time (org-read-date nil 'to-time nil nil
13115 default-time default-input)))))
13117 (when (and org-insert-labeled-timestamps-at-point
13118 (member what '(scheduled deadline)))
13119 (insert
13120 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13121 (org-insert-time-stamp time org-time-was-given
13122 nil nil nil (list org-end-time-was-given))
13123 (setq what nil))
13124 (save-excursion
13125 (save-restriction
13126 (let (col list elt ts buffer-invisibility-spec)
13127 (org-back-to-heading t)
13128 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13129 (goto-char (match-end 1))
13130 (setq col (current-column))
13131 (goto-char (match-end 0))
13132 (if (eobp) (insert "\n") (forward-char 1))
13133 (when (and (not what)
13134 (not (looking-at
13135 (concat "[ \t]*"
13136 org-keyword-time-not-clock-regexp))))
13137 ;; Nothing to add, nothing to remove...... :-)
13138 (throw 'exit nil))
13139 (if (and (not (looking-at org-outline-regexp))
13140 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13141 "[^\r\n]*"))
13142 (not (equal (match-string 1) org-clock-string)))
13143 (narrow-to-region (match-beginning 0) (match-end 0))
13144 (insert-before-markers "\n")
13145 (backward-char 1)
13146 (narrow-to-region (point) (point))
13147 (and org-adapt-indentation (org-indent-to-column col)))
13148 ;; Check if we have to remove something.
13149 (setq list (cons what remove))
13150 (while list
13151 (setq elt (pop list))
13152 (when (or (and (eq elt 'scheduled)
13153 (re-search-forward org-scheduled-time-regexp nil t))
13154 (and (eq elt 'deadline)
13155 (re-search-forward org-deadline-time-regexp nil t))
13156 (and (eq elt 'closed)
13157 (re-search-forward org-closed-time-regexp nil t)))
13158 (replace-match "")
13159 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13160 (and (looking-at "[ \t]+") (replace-match ""))
13161 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13162 (when what
13163 (insert
13164 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13165 (cond ((eq what 'scheduled) org-scheduled-string)
13166 ((eq what 'deadline) org-deadline-string)
13167 ((eq what 'closed) org-closed-string))
13168 " ")
13169 (setq ts (org-insert-time-stamp
13170 time
13171 (or org-time-was-given
13172 (and (eq what 'closed) org-log-done-with-time))
13173 (eq what 'closed)
13174 nil nil (list org-end-time-was-given)))
13175 (insert
13176 (if (not (or (bolp) (eq (char-before) ?\ )
13177 (memq (char-after) '(32 10))
13178 (eobp))) " " ""))
13179 (end-of-line 1))
13180 (goto-char (point-min))
13181 (widen)
13182 (if (and (looking-at "[ \t]*\n")
13183 (equal (char-before) ?\n))
13184 (delete-region (1- (point)) (point-at-eol)))
13185 ts))))))
13187 (defvar org-log-note-marker (make-marker))
13188 (defvar org-log-note-purpose nil)
13189 (defvar org-log-note-state nil)
13190 (defvar org-log-note-previous-state nil)
13191 (defvar org-log-note-how nil)
13192 (defvar org-log-note-extra nil)
13193 (defvar org-log-note-window-configuration nil)
13194 (defvar org-log-note-return-to (make-marker))
13195 (defvar org-log-note-effective-time nil
13196 "Remembered current time so that dynamically scoped
13197 `org-extend-today-until' affects tha timestamps in state change
13198 log")
13200 (defvar org-log-post-message nil
13201 "Message to be displayed after a log note has been stored.
13202 The auto-repeater uses this.")
13204 (defun org-add-note ()
13205 "Add a note to the current entry.
13206 This is done in the same way as adding a state change note."
13207 (interactive)
13208 (org-add-log-setup 'note nil nil 'findpos nil))
13210 (defvar org-property-end-re)
13211 (defun org-add-log-setup (&optional purpose state prev-state
13212 findpos how extra)
13213 "Set up the post command hook to take a note.
13214 If this is about to TODO state change, the new state is expected in STATE.
13215 When FINDPOS is non-nil, find the correct position for the note in
13216 the current entry. If not, assume that it can be inserted at point.
13217 HOW is an indicator what kind of note should be created.
13218 EXTRA is additional text that will be inserted into the notes buffer."
13219 (let* ((org-log-into-drawer (org-log-into-drawer))
13220 (drawer (cond ((stringp org-log-into-drawer)
13221 org-log-into-drawer)
13222 (org-log-into-drawer "LOGBOOK"))))
13223 (save-restriction
13224 (save-excursion
13225 (when findpos
13226 (org-back-to-heading t)
13227 (narrow-to-region (point) (save-excursion
13228 (outline-next-heading) (point)))
13229 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13230 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13231 "[^\r\n]*\\)?"))
13232 (goto-char (match-end 0))
13233 (cond
13234 (drawer
13235 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13236 nil t)
13237 (progn
13238 (goto-char (match-end 0))
13239 (or org-log-states-order-reversed
13240 (and (re-search-forward org-property-end-re nil t)
13241 (goto-char (1- (match-beginning 0))))))
13242 (insert "\n:" drawer ":\n:END:")
13243 (beginning-of-line 0)
13244 (org-indent-line)
13245 (beginning-of-line 2)
13246 (org-indent-line)
13247 (end-of-line 0)))
13248 ((and org-log-state-notes-insert-after-drawers
13249 (save-excursion
13250 (forward-line) (looking-at org-drawer-regexp)))
13251 (forward-line)
13252 (while (looking-at org-drawer-regexp)
13253 (goto-char (match-end 0))
13254 (re-search-forward org-property-end-re (point-max) t)
13255 (forward-line))
13256 (forward-line -1)))
13257 (unless org-log-states-order-reversed
13258 (and (= (char-after) ?\n) (forward-char 1))
13259 (org-skip-over-state-notes)
13260 (skip-chars-backward " \t\n\r")))
13261 (move-marker org-log-note-marker (point))
13262 (setq org-log-note-purpose purpose
13263 org-log-note-state state
13264 org-log-note-previous-state prev-state
13265 org-log-note-how how
13266 org-log-note-extra extra
13267 org-log-note-effective-time (org-current-effective-time))
13268 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13270 (defun org-skip-over-state-notes ()
13271 "Skip past the list of State notes in an entry."
13272 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13273 (when (ignore-errors (goto-char (org-in-item-p)))
13274 (let* ((struct (org-list-struct))
13275 (prevs (org-list-prevs-alist struct)))
13276 (while (looking-at "[ \t]*- State")
13277 (goto-char (or (org-list-get-next-item (point) struct prevs)
13278 (org-list-get-item-end (point) struct)))))))
13280 (defun org-add-log-note (&optional purpose)
13281 "Pop up a window for taking a note, and add this note later at point."
13282 (remove-hook 'post-command-hook 'org-add-log-note)
13283 (setq org-log-note-window-configuration (current-window-configuration))
13284 (delete-other-windows)
13285 (move-marker org-log-note-return-to (point))
13286 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13287 (goto-char org-log-note-marker)
13288 (org-switch-to-buffer-other-window "*Org Note*")
13289 (erase-buffer)
13290 (if (memq org-log-note-how '(time state))
13291 (let (current-prefix-arg) (org-store-log-note))
13292 (let ((org-inhibit-startup t)) (org-mode))
13293 (insert (format "# Insert note for %s.
13294 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13295 (cond
13296 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13297 ((eq org-log-note-purpose 'done) "closed todo item")
13298 ((eq org-log-note-purpose 'state)
13299 (format "state change from \"%s\" to \"%s\""
13300 (or org-log-note-previous-state "")
13301 (or org-log-note-state "")))
13302 ((eq org-log-note-purpose 'reschedule)
13303 "rescheduling")
13304 ((eq org-log-note-purpose 'delschedule)
13305 "no longer scheduled")
13306 ((eq org-log-note-purpose 'redeadline)
13307 "changing deadline")
13308 ((eq org-log-note-purpose 'deldeadline)
13309 "removing deadline")
13310 ((eq org-log-note-purpose 'refile)
13311 "refiling")
13312 ((eq org-log-note-purpose 'note)
13313 "this entry")
13314 (t (error "This should not happen")))))
13315 (if org-log-note-extra (insert org-log-note-extra))
13316 (org-set-local 'org-finish-function 'org-store-log-note)
13317 (run-hooks 'org-log-buffer-setup-hook)))
13319 (defvar org-note-abort nil) ; dynamically scoped
13320 (defun org-store-log-note ()
13321 "Finish taking a log note, and insert it to where it belongs."
13322 (let ((txt (buffer-string)))
13323 (kill-buffer (current-buffer))
13324 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13325 lines ind bul)
13326 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13327 (setq txt (replace-match "" t t txt)))
13328 (if (string-match "\\s-+\\'" txt)
13329 (setq txt (replace-match "" t t txt)))
13330 (setq lines (org-split-string txt "\n"))
13331 (when (and note (string-match "\\S-" note))
13332 (setq note
13333 (org-replace-escapes
13334 note
13335 (list (cons "%u" (user-login-name))
13336 (cons "%U" user-full-name)
13337 (cons "%t" (format-time-string
13338 (org-time-stamp-format 'long 'inactive)
13339 org-log-note-effective-time))
13340 (cons "%T" (format-time-string
13341 (org-time-stamp-format 'long nil)
13342 org-log-note-effective-time))
13343 (cons "%d" (format-time-string
13344 (org-time-stamp-format nil 'inactive)
13345 org-log-note-effective-time))
13346 (cons "%D" (format-time-string
13347 (org-time-stamp-format nil nil)
13348 org-log-note-effective-time))
13349 (cons "%s" (if org-log-note-state
13350 (concat "\"" org-log-note-state "\"")
13351 ""))
13352 (cons "%S" (if org-log-note-previous-state
13353 (concat "\"" org-log-note-previous-state "\"")
13354 "\"\"")))))
13355 (if lines (setq note (concat note " \\\\")))
13356 (push note lines))
13357 (when (or current-prefix-arg org-note-abort)
13358 (when org-log-into-drawer
13359 (org-remove-empty-drawer-at org-log-note-marker))
13360 (setq lines nil))
13361 (when lines
13362 (with-current-buffer (marker-buffer org-log-note-marker)
13363 (save-excursion
13364 (goto-char org-log-note-marker)
13365 (move-marker org-log-note-marker nil)
13366 (end-of-line 1)
13367 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13368 (setq ind (save-excursion
13369 (if (ignore-errors (goto-char (org-in-item-p)))
13370 (let ((struct (org-list-struct)))
13371 (org-list-get-ind
13372 (org-list-get-top-point struct) struct))
13373 (skip-chars-backward " \r\t\n")
13374 (cond
13375 ((and (org-at-heading-p)
13376 org-adapt-indentation)
13377 (1+ (org-current-level)))
13378 ((org-at-heading-p) 0)
13379 (t (org-get-indentation))))))
13380 (setq bul (org-list-bullet-string "-"))
13381 (org-indent-line-to ind)
13382 (insert bul (pop lines))
13383 (let ((ind-body (+ (length bul) ind)))
13384 (while lines
13385 (insert "\n")
13386 (org-indent-line-to ind-body)
13387 (insert (pop lines))))
13388 (message "Note stored")
13389 (org-back-to-heading t)
13390 (org-cycle-hide-drawers 'children))
13391 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13392 ;; from within `org-add-log-note' because `buffer-undo-list'
13393 ;; is then modified outside of `org-with-remote-undo'.
13394 (when (eq this-command 'org-agenda-todo)
13395 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13396 ;; Don't add undo information when called from `org-agenda-todo'
13397 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13398 (set-window-configuration org-log-note-window-configuration)
13399 (with-current-buffer (marker-buffer org-log-note-return-to)
13400 (goto-char org-log-note-return-to))
13401 (move-marker org-log-note-return-to nil)
13402 (and org-log-post-message (message "%s" org-log-post-message))))
13404 (defun org-remove-empty-drawer-at (pos)
13405 "Remove an empty drawer at position POS.
13406 POS may also be a marker."
13407 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13408 (org-with-wide-buffer
13409 (goto-char pos)
13410 (let ((drawer (org-element-at-point)))
13411 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13412 (not (org-element-property :contents-begin drawer)))
13413 (delete-region (org-element-property :begin drawer)
13414 (progn (goto-char (org-element-property :end drawer))
13415 (skip-chars-backward " \r\t\n")
13416 (forward-line)
13417 (point))))))))
13419 (defvar org-ts-type nil)
13420 (defun org-sparse-tree (&optional arg type)
13421 "Create a sparse tree, prompt for the details.
13422 This command can create sparse trees. You first need to select the type
13423 of match used to create the tree:
13425 t Show all TODO entries.
13426 T Show entries with a specific TODO keyword.
13427 m Show entries selected by a tags/property match.
13428 p Enter a property name and its value (both with completion on existing
13429 names/values) and show entries with that property.
13430 r Show entries matching a regular expression (`/' can be used as well).
13431 b Show deadlines and scheduled items before a date.
13432 a Show deadlines and scheduled items after a date.
13433 d Show deadlines due within `org-deadline-warning-days'.
13434 D Show deadlines and scheduled items between a date range."
13435 (interactive "P")
13436 (let (ans kwd value ts-type)
13437 (setq type (or type org-sparse-tree-default-date-type))
13438 (setq org-ts-type type)
13439 (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"
13440 (cond ((eq type 'all) "all timestamps")
13441 ((eq type 'scheduled) "only scheduled")
13442 ((eq type 'deadline) "only deadline")
13443 ((eq type 'active) "only active timestamps")
13444 ((eq type 'inactive) "only inactive timestamps")
13445 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13446 ((eq type 'closed) "with a closed time-stamp")
13447 (t "scheduled/deadline")))
13448 (setq ans (read-char-exclusive))
13449 (cond
13450 ((equal ans ?c)
13451 (org-sparse-tree
13452 arg (cadr (member type '(scheduled-or-deadline
13453 all scheduled deadline active inactive closed)))))
13454 ((equal ans ?d)
13455 (call-interactively 'org-check-deadlines))
13456 ((equal ans ?b)
13457 (call-interactively 'org-check-before-date))
13458 ((equal ans ?a)
13459 (call-interactively 'org-check-after-date))
13460 ((equal ans ?D)
13461 (call-interactively 'org-check-dates-range))
13462 ((equal ans ?t)
13463 (call-interactively 'org-show-todo-tree))
13464 ((equal ans ?T)
13465 (org-show-todo-tree '(4)))
13466 ((member ans '(?T ?m))
13467 (call-interactively 'org-match-sparse-tree))
13468 ((member ans '(?p ?P))
13469 (setq kwd (org-icompleting-read "Property: "
13470 (mapcar 'list (org-buffer-property-keys))))
13471 (setq value (org-icompleting-read "Value: "
13472 (mapcar 'list (org-property-values kwd))))
13473 (unless (string-match "\\`{.*}\\'" value)
13474 (setq value (concat "\"" value "\"")))
13475 (org-match-sparse-tree arg (concat kwd "=" value)))
13476 ((member ans '(?r ?R ?/))
13477 (call-interactively 'org-occur))
13478 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13480 (defvar org-occur-highlights nil
13481 "List of overlays used for occur matches.")
13482 (make-variable-buffer-local 'org-occur-highlights)
13483 (defvar org-occur-parameters nil
13484 "Parameters of the active org-occur calls.
13485 This is a list, each call to org-occur pushes as cons cell,
13486 containing the regular expression and the callback, onto the list.
13487 The list can contain several entries if `org-occur' has been called
13488 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13489 will only contain one set of parameters. When the highlights are
13490 removed (for example with `C-c C-c', or with the next edit (depending
13491 on `org-remove-highlights-with-change'), this variable is emptied
13492 as well.")
13493 (make-variable-buffer-local 'org-occur-parameters)
13495 (defun org-occur (regexp &optional keep-previous callback)
13496 "Make a compact tree which shows all matches of REGEXP.
13497 The tree will show the lines where the regexp matches, and all higher
13498 headlines above the match. It will also show the heading after the match,
13499 to make sure editing the matching entry is easy.
13500 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13501 call to `org-occur' will be kept, to allow stacking of calls to this
13502 command.
13503 If CALLBACK is non-nil, it is a function which is called to confirm
13504 that the match should indeed be shown."
13505 (interactive "sRegexp: \nP")
13506 (when (equal regexp "")
13507 (user-error "Regexp cannot be empty"))
13508 (unless keep-previous
13509 (org-remove-occur-highlights nil nil t))
13510 (push (cons regexp callback) org-occur-parameters)
13511 (let ((cnt 0))
13512 (save-excursion
13513 (goto-char (point-min))
13514 (if (or (not keep-previous) ; do not want to keep
13515 (not org-occur-highlights)) ; no previous matches
13516 ;; hide everything
13517 (org-overview))
13518 (while (re-search-forward regexp nil t)
13519 (when (or (not callback)
13520 (save-match-data (funcall callback)))
13521 (setq cnt (1+ cnt))
13522 (when org-highlight-sparse-tree-matches
13523 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13524 (org-show-context 'occur-tree))))
13525 (when org-remove-highlights-with-change
13526 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13527 nil 'local))
13528 (unless org-sparse-tree-open-archived-trees
13529 (org-hide-archived-subtrees (point-min) (point-max)))
13530 (run-hooks 'org-occur-hook)
13531 (if (org-called-interactively-p 'interactive)
13532 (message "%d match(es) for regexp %s" cnt regexp))
13533 cnt))
13535 (defun org-occur-next-match (&optional n reset)
13536 "Function for `next-error-function' to find sparse tree matches.
13537 N is the number of matches to move, when negative move backwards.
13538 RESET is entirely ignored - this function always goes back to the
13539 starting point when no match is found."
13540 (let* ((limit (if (< n 0) (point-min) (point-max)))
13541 (search-func (if (< n 0)
13542 'previous-single-char-property-change
13543 'next-single-char-property-change))
13544 (n (abs n))
13545 (pos (point))
13547 (catch 'exit
13548 (while (setq p1 (funcall search-func (point) 'org-type))
13549 (when (equal p1 limit)
13550 (goto-char pos)
13551 (error "No more matches"))
13552 (when (equal (get-char-property p1 'org-type) 'org-occur)
13553 (setq n (1- n))
13554 (when (= n 0)
13555 (goto-char p1)
13556 (throw 'exit (point))))
13557 (goto-char p1))
13558 (goto-char p1)
13559 (error "No more matches"))))
13561 (defun org-show-context (&optional key)
13562 "Make sure point and context are visible.
13563 How much context is shown depends upon the variables
13564 `org-show-hierarchy-above', `org-show-following-heading',
13565 `org-show-entry-below' and `org-show-siblings'."
13566 (let ((heading-p (org-at-heading-p t))
13567 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13568 (following-p (org-get-alist-option org-show-following-heading key))
13569 (entry-p (org-get-alist-option org-show-entry-below key))
13570 (siblings-p (org-get-alist-option org-show-siblings key)))
13571 ;; Show heading or entry text
13572 (if (and heading-p (not entry-p))
13573 (org-flag-heading nil) ; only show the heading
13574 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13575 (org-show-hidden-entry))) ; show entire entry
13576 (when following-p
13577 ;; Show next sibling, or heading below text
13578 (save-excursion
13579 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13580 (org-flag-heading nil))))
13581 (when siblings-p (org-show-siblings))
13582 (when hierarchy-p
13583 ;; show all higher headings, possibly with siblings
13584 (save-excursion
13585 (while (and (condition-case nil
13586 (progn (org-up-heading-all 1) t)
13587 (error nil))
13588 (not (bobp)))
13589 (org-flag-heading nil)
13590 (when siblings-p (org-show-siblings)))))
13591 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13593 (defvar org-reveal-start-hook nil
13594 "Hook run before revealing a location.")
13596 (defun org-reveal (&optional siblings)
13597 "Show current entry, hierarchy above it, and the following headline.
13598 This can be used to show a consistent set of context around locations
13599 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13600 not t for the search context.
13602 With optional argument SIBLINGS, on each level of the hierarchy all
13603 siblings are shown. This repairs the tree structure to what it would
13604 look like when opened with hierarchical calls to `org-cycle'.
13605 With double optional argument \\[universal-argument] \\[universal-argument], \
13606 go to the parent and show the
13607 entire tree."
13608 (interactive "P")
13609 (run-hooks 'org-reveal-start-hook)
13610 (let ((org-show-hierarchy-above t)
13611 (org-show-following-heading t)
13612 (org-show-siblings (if siblings t org-show-siblings)))
13613 (org-show-context nil))
13614 (when (equal siblings '(16))
13615 (save-excursion
13616 (when (org-up-heading-safe)
13617 (org-show-subtree)
13618 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13620 (defun org-highlight-new-match (beg end)
13621 "Highlight from BEG to END and mark the highlight is an occur headline."
13622 (let ((ov (make-overlay beg end)))
13623 (overlay-put ov 'face 'secondary-selection)
13624 (overlay-put ov 'org-type 'org-occur)
13625 (push ov org-occur-highlights)))
13627 (defun org-remove-occur-highlights (&optional beg end noremove)
13628 "Remove the occur highlights from the buffer.
13629 BEG and END are ignored. If NOREMOVE is nil, remove this function
13630 from the `before-change-functions' in the current buffer."
13631 (interactive)
13632 (unless org-inhibit-highlight-removal
13633 (mapc 'delete-overlay org-occur-highlights)
13634 (setq org-occur-highlights nil)
13635 (setq org-occur-parameters nil)
13636 (unless noremove
13637 (remove-hook 'before-change-functions
13638 'org-remove-occur-highlights 'local))))
13640 ;;;; Priorities
13642 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13643 "Regular expression matching the priority indicator.")
13645 (defvar org-remove-priority-next-time nil)
13647 (defun org-priority-up ()
13648 "Increase the priority of the current item."
13649 (interactive)
13650 (org-priority 'up))
13652 (defun org-priority-down ()
13653 "Decrease the priority of the current item."
13654 (interactive)
13655 (org-priority 'down))
13657 (defun org-priority (&optional action show)
13658 "Change the priority of an item.
13659 ACTION can be `set', `up', `down', or a character."
13660 (interactive "P")
13661 (if (equal action '(4))
13662 (org-show-priority)
13663 (unless org-enable-priority-commands
13664 (user-error "Priority commands are disabled"))
13665 (setq action (or action 'set))
13666 (let (current new news have remove)
13667 (save-excursion
13668 (org-back-to-heading t)
13669 (if (looking-at org-priority-regexp)
13670 (setq current (string-to-char (match-string 2))
13671 have t))
13672 (cond
13673 ((eq action 'remove)
13674 (setq remove t new ?\ ))
13675 ((or (eq action 'set)
13676 (if (featurep 'xemacs) (characterp action) (integerp action)))
13677 (if (not (eq action 'set))
13678 (setq new action)
13679 (message "Priority %c-%c, SPC to remove: "
13680 org-highest-priority org-lowest-priority)
13681 (save-match-data
13682 (setq new (read-char-exclusive))))
13683 (if (and (= (upcase org-highest-priority) org-highest-priority)
13684 (= (upcase org-lowest-priority) org-lowest-priority))
13685 (setq new (upcase new)))
13686 (cond ((equal new ?\ ) (setq remove t))
13687 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13688 (user-error "Priority must be between `%c' and `%c'"
13689 org-highest-priority org-lowest-priority))))
13690 ((eq action 'up)
13691 (setq new (if have
13692 (1- current) ; normal cycling
13693 ;; last priority was empty
13694 (if (eq last-command this-command)
13695 org-lowest-priority ; wrap around empty to lowest
13696 ;; default
13697 (if org-priority-start-cycle-with-default
13698 org-default-priority
13699 (1- org-default-priority))))))
13700 ((eq action 'down)
13701 (setq new (if have
13702 (1+ current) ; normal cycling
13703 ;; last priority was empty
13704 (if (eq last-command this-command)
13705 org-highest-priority ; wrap around empty to highest
13706 ;; default
13707 (if org-priority-start-cycle-with-default
13708 org-default-priority
13709 (1+ org-default-priority))))))
13710 (t (user-error "Invalid action")))
13711 (if (or (< (upcase new) org-highest-priority)
13712 (> (upcase new) org-lowest-priority))
13713 (if (and (memq action '(up down))
13714 (not have) (not (eq last-command this-command)))
13715 ;; `new' is from default priority
13716 (error
13717 "The default can not be set, see `org-default-priority' why")
13718 ;; normal cycling: `new' is beyond highest/lowest priority
13719 ;; and is wrapped around to the empty priority
13720 (setq remove t)))
13721 (setq news (format "%c" new))
13722 (if have
13723 (if remove
13724 (replace-match "" t t nil 1)
13725 (replace-match news t t nil 2))
13726 (if remove
13727 (user-error "No priority cookie found in line")
13728 (let ((case-fold-search nil))
13729 (looking-at org-todo-line-regexp))
13730 (if (match-end 2)
13731 (progn
13732 (goto-char (match-end 2))
13733 (insert " [#" news "]"))
13734 (goto-char (match-beginning 3))
13735 (insert "[#" news "] "))))
13736 (org-preserve-lc (org-set-tags nil 'align)))
13737 (if remove
13738 (message "Priority removed")
13739 (message "Priority of current item set to %s" news)))))
13741 (defun org-show-priority ()
13742 "Show the priority of the current item.
13743 This priority is composed of the main priority given with the [#A] cookies,
13744 and by additional input from the age of a schedules or deadline entry."
13745 (interactive)
13746 (let ((pri (if (eq major-mode 'org-agenda-mode)
13747 (org-get-at-bol 'priority)
13748 (save-excursion
13749 (save-match-data
13750 (beginning-of-line)
13751 (and (looking-at org-heading-regexp)
13752 (org-get-priority (match-string 0))))))))
13753 (message "Priority is %d" (if pri pri -1000))))
13755 (defun org-get-priority (s)
13756 "Find priority cookie and return priority."
13757 (save-match-data
13758 (if (functionp org-get-priority-function)
13759 (funcall org-get-priority-function)
13760 (if (not (string-match org-priority-regexp s))
13761 (* 1000 (- org-lowest-priority org-default-priority))
13762 (* 1000 (- org-lowest-priority
13763 (string-to-char (match-string 2 s))))))))
13765 ;;;; Tags
13767 (defvar org-agenda-archives-mode)
13768 (defvar org-map-continue-from nil
13769 "Position from where mapping should continue.
13770 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13772 (defvar org-scanner-tags nil
13773 "The current tag list while the tags scanner is running.")
13774 (defvar org-trust-scanner-tags nil
13775 "Should `org-get-tags-at' use the tags for the scanner.
13776 This is for internal dynamical scoping only.
13777 When this is non-nil, the function `org-get-tags-at' will return the value
13778 of `org-scanner-tags' instead of building the list by itself. This
13779 can lead to large speed-ups when the tags scanner is used in a file with
13780 many entries, and when the list of tags is retrieved, for example to
13781 obtain a list of properties. Building the tags list for each entry in such
13782 a file becomes an N^2 operation - but with this variable set, it scales
13783 as N.")
13785 (defun org-scan-tags (action matcher todo-only &optional start-level)
13786 "Sca headline tags with inheritance and produce output ACTION.
13788 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13789 or `agenda' to produce an entry list for an agenda view. It can also be
13790 a Lisp form or a function that should be called at each matched headline, in
13791 this case the return value is a list of all return values from these calls.
13793 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13794 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13795 only lines with a not-done TODO keyword are included in the output.
13796 This should be the same variable that was scoped into
13797 and set by `org-make-tags-matcher' when it constructed MATCHER.
13799 START-LEVEL can be a string with asterisks, reducing the scope to
13800 headlines matching this string."
13801 (require 'org-agenda)
13802 (let* ((re (concat "^"
13803 (if start-level
13804 ;; Get the correct level to match
13805 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13806 org-outline-regexp)
13807 " *\\(\\<\\("
13808 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13809 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13810 (props (list 'face 'default
13811 'done-face 'org-agenda-done
13812 'undone-face 'default
13813 'mouse-face 'highlight
13814 'org-not-done-regexp org-not-done-regexp
13815 'org-todo-regexp org-todo-regexp
13816 'org-complex-heading-regexp org-complex-heading-regexp
13817 'help-echo
13818 (format "mouse-2 or RET jump to org file %s"
13819 (abbreviate-file-name
13820 (or (buffer-file-name (buffer-base-buffer))
13821 (buffer-name (buffer-base-buffer)))))))
13822 (org-map-continue-from nil)
13823 lspos tags tags-list
13824 (tags-alist (list (cons 0 org-file-tags)))
13825 (llast 0) rtn rtn1 level category i txt
13826 todo marker entry priority)
13827 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13828 (setq action (list 'lambda nil action)))
13829 (save-excursion
13830 (goto-char (point-min))
13831 (when (eq action 'sparse-tree)
13832 (org-overview)
13833 (org-remove-occur-highlights))
13834 (while (let (case-fold-search)
13835 (re-search-forward re nil t))
13836 (setq org-map-continue-from nil)
13837 (catch :skip
13838 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13839 tags (if (match-end 4) (org-match-string-no-properties 4)))
13840 (goto-char (setq lspos (match-beginning 0)))
13841 (setq level (org-reduced-level (org-outline-level))
13842 category (org-get-category))
13843 (setq i llast llast level)
13844 ;; remove tag lists from same and sublevels
13845 (while (>= i level)
13846 (when (setq entry (assoc i tags-alist))
13847 (setq tags-alist (delete entry tags-alist)))
13848 (setq i (1- i)))
13849 ;; add the next tags
13850 (when tags
13851 (setq tags (org-split-string tags ":")
13852 tags-alist
13853 (cons (cons level tags) tags-alist)))
13854 ;; compile tags for current headline
13855 (setq tags-list
13856 (if org-use-tag-inheritance
13857 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13858 tags)
13859 org-scanner-tags tags-list)
13860 (when org-use-tag-inheritance
13861 (setcdr (car tags-alist)
13862 (mapcar (lambda (x)
13863 (setq x (copy-sequence x))
13864 (org-add-prop-inherited x))
13865 (cdar tags-alist))))
13866 (when (and tags org-use-tag-inheritance
13867 (or (not (eq t org-use-tag-inheritance))
13868 org-tags-exclude-from-inheritance))
13869 ;; selective inheritance, remove uninherited ones
13870 (setcdr (car tags-alist)
13871 (org-remove-uninherited-tags (cdar tags-alist))))
13872 (when (and
13874 ;; eval matcher only when the todo condition is OK
13875 (and (or (not todo-only) (member todo org-not-done-keywords))
13876 (let ((case-fold-search t) (org-trust-scanner-tags t))
13877 (eval matcher)))
13879 ;; Call the skipper, but return t if it does not skip,
13880 ;; so that the `and' form continues evaluating
13881 (progn
13882 (unless (eq action 'sparse-tree) (org-agenda-skip))
13885 ;; Check if timestamps are deselecting this entry
13886 (or (not todo-only)
13887 (and (member todo org-not-done-keywords)
13888 (or (not org-agenda-tags-todo-honor-ignore-options)
13889 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13891 ;; select this headline
13892 (cond
13893 ((eq action 'sparse-tree)
13894 (and org-highlight-sparse-tree-matches
13895 (org-get-heading) (match-end 0)
13896 (org-highlight-new-match
13897 (match-beginning 1) (match-end 1)))
13898 (org-show-context 'tags-tree))
13899 ((eq action 'agenda)
13900 (setq txt (org-agenda-format-item
13902 (concat
13903 (if (eq org-tags-match-list-sublevels 'indented)
13904 (make-string (1- level) ?.) "")
13905 (org-get-heading))
13906 level category
13907 tags-list)
13908 priority (org-get-priority txt))
13909 (goto-char lspos)
13910 (setq marker (org-agenda-new-marker))
13911 (org-add-props txt props
13912 'org-marker marker 'org-hd-marker marker 'org-category category
13913 'todo-state todo
13914 'priority priority 'type "tagsmatch")
13915 (push txt rtn))
13916 ((functionp action)
13917 (setq org-map-continue-from nil)
13918 (save-excursion
13919 (setq rtn1 (funcall action))
13920 (push rtn1 rtn)))
13921 (t (user-error "Invalid action")))
13923 ;; if we are to skip sublevels, jump to end of subtree
13924 (unless org-tags-match-list-sublevels
13925 (org-end-of-subtree t)
13926 (backward-char 1))))
13927 ;; Get the correct position from where to continue
13928 (if org-map-continue-from
13929 (goto-char org-map-continue-from)
13930 (and (= (point) lspos) (end-of-line 1)))))
13931 (when (and (eq action 'sparse-tree)
13932 (not org-sparse-tree-open-archived-trees))
13933 (org-hide-archived-subtrees (point-min) (point-max)))
13934 (nreverse rtn)))
13936 (defun org-remove-uninherited-tags (tags)
13937 "Remove all tags that are not inherited from the list TAGS."
13938 (cond
13939 ((eq org-use-tag-inheritance t)
13940 (if org-tags-exclude-from-inheritance
13941 (org-delete-all org-tags-exclude-from-inheritance tags)
13942 tags))
13943 ((not org-use-tag-inheritance) nil)
13944 ((stringp org-use-tag-inheritance)
13945 (delq nil (mapcar
13946 (lambda (x)
13947 (if (and (string-match org-use-tag-inheritance x)
13948 (not (member x org-tags-exclude-from-inheritance)))
13949 x nil))
13950 tags)))
13951 ((listp org-use-tag-inheritance)
13952 (delq nil (mapcar
13953 (lambda (x)
13954 (if (member x org-use-tag-inheritance) x nil))
13955 tags)))))
13957 (defun org-match-sparse-tree (&optional todo-only match)
13958 "Create a sparse tree according to tags string MATCH.
13959 MATCH can contain positive and negative selection of tags, like
13960 \"+WORK+URGENT-WITHBOSS\".
13961 If optional argument TODO-ONLY is non-nil, only select lines that are
13962 also TODO lines."
13963 (interactive "P")
13964 (org-agenda-prepare-buffers (list (current-buffer)))
13965 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13967 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13969 (defvar org-cached-props nil)
13970 (defun org-cached-entry-get (pom property)
13971 (if (or (eq t org-use-property-inheritance)
13972 (and (stringp org-use-property-inheritance)
13973 (string-match org-use-property-inheritance property))
13974 (and (listp org-use-property-inheritance)
13975 (member property org-use-property-inheritance)))
13976 ;; Caching is not possible, check it directly
13977 (org-entry-get pom property 'inherit)
13978 ;; Get all properties, so that we can do complicated checks easily
13979 (cdr (assoc property (or org-cached-props
13980 (setq org-cached-props
13981 (org-entry-properties pom)))))))
13983 (defun org-global-tags-completion-table (&optional files)
13984 "Return the list of all tags in all agenda buffer/files.
13985 Optional FILES argument is a list of files which can be used
13986 instead of the agenda files."
13987 (save-excursion
13988 (org-uniquify
13989 (delq nil
13990 (apply 'append
13991 (mapcar
13992 (lambda (file)
13993 (set-buffer (find-file-noselect file))
13994 (append (org-get-buffer-tags)
13995 (mapcar (lambda (x) (if (stringp (car-safe x))
13996 (list (car-safe x)) nil))
13997 org-tag-alist)))
13998 (if (and files (car files))
13999 files
14000 (org-agenda-files))))))))
14002 (defun org-make-tags-matcher (match)
14003 "Create the TAGS/TODO matcher form for the selection string MATCH.
14005 The variable `todo-only' is scoped dynamically into this function.
14006 It will be set to t if the matcher restricts matching to TODO entries,
14007 otherwise will not be touched.
14009 Returns a cons of the selection string MATCH and the constructed
14010 lisp form implementing the matcher. The matcher is to be evaluated
14011 at an Org entry, with point on the headline, and returns t if the
14012 entry matches the selection string MATCH. The returned lisp form
14013 references two variables with information about the entry, which
14014 must be bound around the form's evaluation: todo, the TODO keyword
14015 at the entry (or nil of none); and tags-list, the list of all tags
14016 at the entry including inherited ones. Additionally, the category
14017 of the entry (if any) must be specified as the text property
14018 'org-category on the headline.
14020 See also `org-scan-tags'.
14022 (declare (special todo-only))
14023 (unless (boundp 'todo-only)
14024 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14025 (unless match
14026 ;; Get a new match request, with completion against the global
14027 ;; tags table and the local tags in current buffer
14028 (let ((org-last-tags-completion-table
14029 (org-uniquify
14030 (delq nil (append (org-get-buffer-tags)
14031 (org-global-tags-completion-table))))))
14032 (setq match (org-completing-read-no-i
14033 "Match: " 'org-tags-completion-function nil nil nil
14034 'org-tags-history))))
14036 ;; Parse the string and create a lisp form
14037 (let ((match0 match)
14038 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14039 minus tag mm
14040 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14041 orterms term orlist re-p str-p level-p level-op time-p
14042 prop-p pn pv po gv rest (start 0) (ss 0))
14043 ;; Expand group tags
14044 (setq match (org-tags-expand match))
14046 ;; Check if there is a TODO part of this match, which would be the
14047 ;; part after a "/". TO make sure that this slash is not part of
14048 ;; a property value to be matched against, we also check that there
14049 ;; is no " after that slash.
14050 ;; First, find the last slash
14051 (while (string-match "/+" match ss)
14052 (setq start (match-beginning 0) ss (match-end 0)))
14053 (if (and (string-match "/+" match start)
14054 (not (save-match-data (string-match "\"" match start))))
14055 ;; match contains also a todo-matching request
14056 (progn
14057 (setq tagsmatch (substring match 0 (match-beginning 0))
14058 todomatch (substring match (match-end 0)))
14059 (if (string-match "^!" todomatch)
14060 (setq todo-only t todomatch (substring todomatch 1)))
14061 (if (string-match "^\\s-*$" todomatch)
14062 (setq todomatch nil)))
14063 ;; only matching tags
14064 (setq tagsmatch match todomatch nil))
14066 ;; Make the tags matcher
14067 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14068 (setq tagsmatcher t)
14069 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14070 (while (setq term (pop orterms))
14071 (while (and (equal (substring term -1) "\\") orterms)
14072 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14073 (while (string-match re term)
14074 (setq rest (substring term (match-end 0))
14075 minus (and (match-end 1)
14076 (equal (match-string 1 term) "-"))
14077 tag (save-match-data (replace-regexp-in-string
14078 "\\\\-" "-"
14079 (match-string 2 term)))
14080 re-p (equal (string-to-char tag) ?{)
14081 level-p (match-end 4)
14082 prop-p (match-end 5)
14083 mm (cond
14084 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14085 (level-p
14086 (setq level-op (org-op-to-function (match-string 3 term)))
14087 `(,level-op level ,(string-to-number
14088 (match-string 4 term))))
14089 (prop-p
14090 (setq pn (match-string 5 term)
14091 po (match-string 6 term)
14092 pv (match-string 7 term)
14093 re-p (equal (string-to-char pv) ?{)
14094 str-p (equal (string-to-char pv) ?\")
14095 time-p (save-match-data
14096 (string-match "^\"[[<].*[]>]\"$" pv))
14097 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14098 (if time-p (setq pv (org-matcher-time pv)))
14099 (setq po (org-op-to-function po (if time-p 'time str-p)))
14100 (cond
14101 ((equal pn "CATEGORY")
14102 (setq gv '(get-text-property (point) 'org-category)))
14103 ((equal pn "TODO")
14104 (setq gv 'todo))
14106 (setq gv `(org-cached-entry-get nil ,pn))))
14107 (if re-p
14108 (if (eq po 'org<>)
14109 `(not (string-match ,pv (or ,gv "")))
14110 `(string-match ,pv (or ,gv "")))
14111 (if str-p
14112 `(,po (or ,gv "") ,pv)
14113 `(,po (string-to-number (or ,gv ""))
14114 ,(string-to-number pv) ))))
14115 (t `(member ,tag tags-list)))
14116 mm (if minus (list 'not mm) mm)
14117 term rest)
14118 (push mm tagsmatcher))
14119 (push (if (> (length tagsmatcher) 1)
14120 (cons 'and tagsmatcher)
14121 (car tagsmatcher))
14122 orlist)
14123 (setq tagsmatcher nil))
14124 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14125 (setq tagsmatcher
14126 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14127 ;; Make the todo matcher
14128 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14129 (setq todomatcher t)
14130 (setq orterms (org-split-string todomatch "|") orlist nil)
14131 (while (setq term (pop orterms))
14132 (while (string-match re term)
14133 (setq minus (and (match-end 1)
14134 (equal (match-string 1 term) "-"))
14135 kwd (match-string 2 term)
14136 re-p (equal (string-to-char kwd) ?{)
14137 term (substring term (match-end 0))
14138 mm (if re-p
14139 `(string-match ,(substring kwd 1 -1) todo)
14140 (list 'equal 'todo kwd))
14141 mm (if minus (list 'not mm) mm))
14142 (push mm todomatcher))
14143 (push (if (> (length todomatcher) 1)
14144 (cons 'and todomatcher)
14145 (car todomatcher))
14146 orlist)
14147 (setq todomatcher nil))
14148 (setq todomatcher (if (> (length orlist) 1)
14149 (cons 'or orlist) (car orlist))))
14151 ;; Return the string and lisp forms of the matcher
14152 (setq matcher (if todomatcher
14153 (list 'and tagsmatcher todomatcher)
14154 tagsmatcher))
14155 (when todo-only
14156 (setq matcher (list 'and '(member todo org-not-done-keywords)
14157 matcher)))
14158 (cons match0 matcher)))
14160 (defun org-tags-expand (match &optional single-as-list downcased)
14161 "Expand group tags in MATCH.
14163 This replaces every group tag in MATCH with a regexp tag search.
14164 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14165 will be replaced like this:
14167 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14168 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14169 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14171 Replacing by a regexp preserves the structure of the match.
14172 E.g., this expansion
14174 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14176 will match anything tagged with \"Lab\" and \"Home\", or tagged
14177 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14179 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14180 assumed to be a single group tag, and the function will return
14181 the list of tags in this group.
14183 When DOWNCASE is non-nil, expand downcased TAGS."
14184 (if org-group-tags
14185 (let* ((case-fold-search t)
14186 (stable org-mode-syntax-table)
14187 (tal (or org-tag-groups-alist-for-agenda
14188 org-tag-groups-alist))
14189 (tal (if downcased
14190 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14191 (tml (mapcar 'car tal))
14192 (rtnmatch match) rpl)
14193 ;; @ and _ are allowed as word-components in tags
14194 (modify-syntax-entry ?@ "w" stable)
14195 (modify-syntax-entry ?_ "w" stable)
14196 (while (and tml
14197 (with-syntax-table stable
14198 (string-match
14199 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14200 (regexp-opt tml) "\\>\\)") rtnmatch)))
14201 (let* ((dir (match-string 1 rtnmatch))
14202 (tag (match-string 2 rtnmatch))
14203 (tag (if downcased (downcase tag) tag)))
14204 (setq tml (delete tag tml))
14205 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14206 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14207 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14208 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14209 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14210 (if single-as-list
14211 (or (reverse rpl) (list rtnmatch))
14212 rtnmatch))
14213 (if single-as-list (list (if downcased (downcase match) match))
14214 match)))
14216 (defun org-op-to-function (op &optional stringp)
14217 "Turn an operator into the appropriate function."
14218 (setq op
14219 (cond
14220 ((equal op "<" ) '(< string< org-time<))
14221 ((equal op ">" ) '(> org-string> org-time>))
14222 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14223 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14224 ((member op '("=" "==")) '(= string= org-time=))
14225 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14226 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14228 (defun org<> (a b) (not (= a b)))
14229 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14230 (defun org-string>= (a b) (not (string< a b)))
14231 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14232 (defun org-string<> (a b) (not (string= a b)))
14233 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14234 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14235 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14236 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14237 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14238 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14239 (defun org-2ft (s)
14240 "Convert S to a floating point time.
14241 If S is already a number, just return it. If it is a string, parse
14242 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14243 (cond
14244 ((numberp s) s)
14245 ((stringp s)
14246 (condition-case nil
14247 (float-time (apply 'encode-time (org-parse-time-string s)))
14248 (error 0.)))
14249 (t 0.)))
14251 (defun org-time-today ()
14252 "Time in seconds today at 0:00.
14253 Returns the float number of seconds since the beginning of the
14254 epoch to the beginning of today (00:00)."
14255 (float-time (apply 'encode-time
14256 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14258 (defun org-matcher-time (s)
14259 "Interpret a time comparison value."
14260 (save-match-data
14261 (cond
14262 ((string= s "<now>") (float-time))
14263 ((string= s "<today>") (org-time-today))
14264 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14265 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14266 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14267 (+ (org-time-today)
14268 (* (string-to-number (match-string 1 s))
14269 (cdr (assoc (match-string 2 s)
14270 '(("d" . 86400.0) ("w" . 604800.0)
14271 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14272 (t (org-2ft s)))))
14274 (defun org-match-any-p (re list)
14275 "Does re match any element of list?"
14276 (setq list (mapcar (lambda (x) (string-match re x)) list))
14277 (delq nil list))
14279 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14280 (defvar org-tags-overlay (make-overlay 1 1))
14281 (org-detach-overlay org-tags-overlay)
14283 (defun org-get-local-tags-at (&optional pos)
14284 "Get a list of tags defined in the current headline."
14285 (org-get-tags-at pos 'local))
14287 (defun org-get-local-tags ()
14288 "Get a list of tags defined in the current headline."
14289 (org-get-tags-at nil 'local))
14291 (defun org-get-tags-at (&optional pos local)
14292 "Get a list of all headline tags applicable at POS.
14293 POS defaults to point. If tags are inherited, the list contains
14294 the targets in the same sequence as the headlines appear, i.e.
14295 the tags of the current headline come last.
14296 When LOCAL is non-nil, only return tags from the current headline,
14297 ignore inherited ones."
14298 (interactive)
14299 (if (and org-trust-scanner-tags
14300 (or (not pos) (equal pos (point)))
14301 (not local))
14302 org-scanner-tags
14303 (let (tags ltags lastpos parent)
14304 (save-excursion
14305 (save-restriction
14306 (widen)
14307 (goto-char (or pos (point)))
14308 (save-match-data
14309 (catch 'done
14310 (condition-case nil
14311 (progn
14312 (org-back-to-heading t)
14313 (while (not (equal lastpos (point)))
14314 (setq lastpos (point))
14315 (when (looking-at
14316 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14317 (setq ltags (org-split-string
14318 (org-match-string-no-properties 1) ":"))
14319 (when parent
14320 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14321 (setq tags (append
14322 (if parent
14323 (org-remove-uninherited-tags ltags)
14324 ltags)
14325 tags)))
14326 (or org-use-tag-inheritance (throw 'done t))
14327 (if local (throw 'done t))
14328 (or (org-up-heading-safe) (error nil))
14329 (setq parent t)))
14330 (error nil)))))
14331 (if local
14332 tags
14333 (reverse (delete-dups
14334 (reverse (append
14335 (org-remove-uninherited-tags
14336 org-file-tags) tags)))))))))
14338 (defun org-add-prop-inherited (s)
14339 (add-text-properties 0 (length s) '(inherited t) s)
14342 (defun org-toggle-tag (tag &optional onoff)
14343 "Toggle the tag TAG for the current line.
14344 If ONOFF is `on' or `off', don't toggle but set to this state."
14345 (let (res current)
14346 (save-excursion
14347 (org-back-to-heading t)
14348 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14349 (point-at-eol) t)
14350 (progn
14351 (setq current (match-string 1))
14352 (replace-match ""))
14353 (setq current ""))
14354 (setq current (nreverse (org-split-string current ":")))
14355 (cond
14356 ((eq onoff 'on)
14357 (setq res t)
14358 (or (member tag current) (push tag current)))
14359 ((eq onoff 'off)
14360 (or (not (member tag current)) (setq current (delete tag current))))
14361 (t (if (member tag current)
14362 (setq current (delete tag current))
14363 (setq res t)
14364 (push tag current))))
14365 (end-of-line 1)
14366 (if current
14367 (progn
14368 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14369 (org-set-tags nil t))
14370 (delete-horizontal-space))
14371 (run-hooks 'org-after-tags-change-hook))
14372 res))
14374 (defun org-align-tags-here (to-col)
14375 ;; Assumes that this is a headline
14376 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14377 (beginning-of-line 1)
14378 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14379 (< pos (match-beginning 2)))
14380 (progn
14381 (setq tags-l (- (match-end 2) (match-beginning 2)))
14382 (goto-char (match-beginning 1))
14383 (insert " ")
14384 (delete-region (point) (1+ (match-beginning 2)))
14385 (setq ncol (max (current-column)
14386 (1+ col)
14387 (if (> to-col 0)
14388 to-col
14389 (- (abs to-col) tags-l))))
14390 (setq p (point))
14391 (insert (make-string (- ncol (current-column)) ?\ ))
14392 (setq ncol (current-column))
14393 (when indent-tabs-mode (tabify p (point-at-eol)))
14394 (org-move-to-column (min ncol col) t))
14395 (goto-char pos))))
14397 (defun org-set-tags-command (&optional arg just-align)
14398 "Call the set-tags command for the current entry."
14399 (interactive "P")
14400 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14401 (org-set-tags arg just-align)
14402 (save-excursion
14403 (unless (and (org-region-active-p)
14404 org-loop-over-headlines-in-active-region)
14405 (org-back-to-heading t))
14406 (org-set-tags arg just-align))))
14408 (defun org-set-tags-to (data)
14409 "Set the tags of the current entry to DATA, replacing the current tags.
14410 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14411 If DATA is nil or the empty string, any tags will be removed."
14412 (interactive "sTags: ")
14413 (setq data
14414 (cond
14415 ((eq data nil) "")
14416 ((equal data "") "")
14417 ((stringp data)
14418 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14419 ":"))
14420 ((listp data)
14421 (concat ":" (mapconcat 'identity data ":") ":"))))
14422 (when data
14423 (save-excursion
14424 (org-back-to-heading t)
14425 (when (looking-at org-complex-heading-regexp)
14426 (if (match-end 5)
14427 (progn
14428 (goto-char (match-beginning 5))
14429 (insert data)
14430 (delete-region (point) (point-at-eol))
14431 (org-set-tags nil 'align))
14432 (goto-char (point-at-eol))
14433 (insert " " data)
14434 (org-set-tags nil 'align)))
14435 (beginning-of-line 1)
14436 (if (looking-at ".*?\\([ \t]+\\)$")
14437 (delete-region (match-beginning 1) (match-end 1))))))
14439 (defun org-align-all-tags ()
14440 "Align the tags i all headings."
14441 (interactive)
14442 (save-excursion
14443 (or (ignore-errors (org-back-to-heading t))
14444 (outline-next-heading))
14445 (if (org-at-heading-p)
14446 (org-set-tags t)
14447 (message "No headings"))))
14449 (defvar org-indent-indentation-per-level)
14450 (defun org-set-tags (&optional arg just-align)
14451 "Set the tags for the current headline.
14452 With prefix ARG, realign all tags in headings in the current buffer."
14453 (interactive "P")
14454 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14455 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14456 'region-start-level 'region))
14457 org-loop-over-headlines-in-active-region)
14458 (org-map-entries
14459 ;; We don't use ARG and JUST-ALIGN here these args are not
14460 ;; useful when looping over headlines
14461 `(org-set-tags)
14462 org-loop-over-headlines-in-active-region
14463 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14464 (let* ((re org-outline-regexp-bol)
14465 (current (unless arg (org-get-tags-string)))
14466 (col (current-column))
14467 (org-setting-tags t)
14468 table current-tags inherited-tags ; computed below when needed
14469 tags p0 c0 c1 rpl di tc level)
14470 (if arg
14471 (save-excursion
14472 (goto-char (point-min))
14473 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14474 (while (re-search-forward re nil t)
14475 (org-set-tags nil t)
14476 (end-of-line 1)))
14477 (message "All tags realigned to column %d" org-tags-column))
14478 (if just-align
14479 (setq tags current)
14480 ;; Get a new set of tags from the user
14481 (save-excursion
14482 (setq table (append org-tag-persistent-alist
14483 (or org-tag-alist (org-get-buffer-tags))
14484 (and
14485 org-complete-tags-always-offer-all-agenda-tags
14486 (org-global-tags-completion-table
14487 (org-agenda-files))))
14488 org-last-tags-completion-table table
14489 current-tags (org-split-string current ":")
14490 inherited-tags (nreverse
14491 (nthcdr (length current-tags)
14492 (nreverse (org-get-tags-at))))
14493 tags
14494 (if (or (eq t org-use-fast-tag-selection)
14495 (and org-use-fast-tag-selection
14496 (delq nil (mapcar 'cdr table))))
14497 (org-fast-tag-selection
14498 current-tags inherited-tags table
14499 (if org-fast-tag-selection-include-todo
14500 org-todo-key-alist))
14501 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14502 (org-trim
14503 (org-icompleting-read "Tags: "
14504 'org-tags-completion-function
14505 nil nil current 'org-tags-history))))))
14506 (while (string-match "[-+&]+" tags)
14507 ;; No boolean logic, just a list
14508 (setq tags (replace-match ":" t t tags))))
14510 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14512 (if org-tags-sort-function
14513 (setq tags (mapconcat 'identity
14514 (sort (org-split-string
14515 tags (org-re "[^[:alnum:]_@#%]+"))
14516 org-tags-sort-function) ":")))
14518 (if (string-match "\\`[\t ]*\\'" tags)
14519 (setq tags "")
14520 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14521 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14523 ;; Insert new tags at the correct column
14524 (beginning-of-line 1)
14525 (setq level (or (and (looking-at org-outline-regexp)
14526 (- (match-end 0) (point) 1))
14528 (cond
14529 ((and (equal current "") (equal tags "")))
14530 ((re-search-forward
14531 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14532 (point-at-eol) t)
14533 (if (equal tags "")
14534 (setq rpl "")
14535 (goto-char (match-beginning 0))
14536 (setq c0 (current-column)
14537 ;; compute offset for the case of org-indent-mode active
14538 di (if org-indent-mode
14539 (* (1- org-indent-indentation-per-level) (1- level))
14541 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14542 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14543 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14544 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14545 (replace-match rpl t t)
14546 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14547 tags)
14548 (t (error "Tags alignment failed")))
14549 (org-move-to-column col)
14550 (unless just-align
14551 (run-hooks 'org-after-tags-change-hook))))))
14553 (defun org-change-tag-in-region (beg end tag off)
14554 "Add or remove TAG for each entry in the region.
14555 This works in the agenda, and also in an org-mode buffer."
14556 (interactive
14557 (list (region-beginning) (region-end)
14558 (let ((org-last-tags-completion-table
14559 (if (derived-mode-p 'org-mode)
14560 (org-uniquify
14561 (delq nil (append (org-get-buffer-tags)
14562 (org-global-tags-completion-table))))
14563 (org-global-tags-completion-table))))
14564 (org-icompleting-read
14565 "Tag: " 'org-tags-completion-function nil nil nil
14566 'org-tags-history))
14567 (progn
14568 (message "[s]et or [r]emove? ")
14569 (equal (read-char-exclusive) ?r))))
14570 (if (fboundp 'deactivate-mark) (deactivate-mark))
14571 (let ((agendap (equal major-mode 'org-agenda-mode))
14572 l1 l2 m buf pos newhead (cnt 0))
14573 (goto-char end)
14574 (setq l2 (1- (org-current-line)))
14575 (goto-char beg)
14576 (setq l1 (org-current-line))
14577 (loop for l from l1 to l2 do
14578 (org-goto-line l)
14579 (setq m (get-text-property (point) 'org-hd-marker))
14580 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14581 (and agendap m))
14582 (setq buf (if agendap (marker-buffer m) (current-buffer))
14583 pos (if agendap m (point)))
14584 (with-current-buffer buf
14585 (save-excursion
14586 (save-restriction
14587 (goto-char pos)
14588 (setq cnt (1+ cnt))
14589 (org-toggle-tag tag (if off 'off 'on))
14590 (setq newhead (org-get-heading)))))
14591 (and agendap (org-agenda-change-all-lines newhead m))))
14592 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14594 (defun org-tags-completion-function (string predicate &optional flag)
14595 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14596 (confirm (lambda (x) (stringp (car x)))))
14597 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14598 (setq s1 (match-string 1 string)
14599 s2 (match-string 2 string))
14600 (setq s1 "" s2 string))
14601 (cond
14602 ((eq flag nil)
14603 ;; try completion
14604 (setq rtn (try-completion s2 ctable confirm))
14605 (if (stringp rtn)
14606 (setq rtn
14607 (concat s1 s2 (substring rtn (length s2))
14608 (if (and org-add-colon-after-tag-completion
14609 (assoc rtn ctable))
14610 ":" ""))))
14611 rtn)
14612 ((eq flag t)
14613 ;; all-completions
14614 (all-completions s2 ctable confirm))
14615 ((eq flag 'lambda)
14616 ;; exact match?
14617 (assoc s2 ctable)))))
14619 (defun org-fast-tag-insert (kwd tags face &optional end)
14620 "Insert KDW, and the TAGS, the latter with face FACE.
14621 Also insert END."
14622 (insert (format "%-12s" (concat kwd ":"))
14623 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14624 (or end "")))
14626 (defun org-fast-tag-show-exit (flag)
14627 (save-excursion
14628 (org-goto-line 3)
14629 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14630 (replace-match ""))
14631 (when flag
14632 (end-of-line 1)
14633 (org-move-to-column (- (window-width) 19) t)
14634 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14636 (defun org-set-current-tags-overlay (current prefix)
14637 "Add an overlay to CURRENT tag with PREFIX."
14638 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14639 (if (featurep 'xemacs)
14640 (org-overlay-display org-tags-overlay (concat prefix s)
14641 'secondary-selection)
14642 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14643 (org-overlay-display org-tags-overlay (concat prefix s)))))
14645 (defvar org-last-tag-selection-key nil)
14646 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14647 "Fast tag selection with single keys.
14648 CURRENT is the current list of tags in the headline, INHERITED is the
14649 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14650 possibly with grouping information. TODO-TABLE is a similar table with
14651 TODO keywords, should these have keys assigned to them.
14652 If the keys are nil, a-z are automatically assigned.
14653 Returns the new tags string, or nil to not change the current settings."
14654 (let* ((fulltable (append table todo-table))
14655 (maxlen (apply 'max (mapcar
14656 (lambda (x)
14657 (if (stringp (car x)) (string-width (car x)) 0))
14658 fulltable)))
14659 (buf (current-buffer))
14660 (expert (eq org-fast-tag-selection-single-key 'expert))
14661 (buffer-tags nil)
14662 (fwidth (+ maxlen 3 1 3))
14663 (ncol (/ (- (window-width) 4) fwidth))
14664 (i-face 'org-done)
14665 (c-face 'org-todo)
14666 tg cnt e c char c1 c2 ntable tbl rtn
14667 ov-start ov-end ov-prefix
14668 (exit-after-next org-fast-tag-selection-single-key)
14669 (done-keywords org-done-keywords)
14670 groups ingroup)
14671 (save-excursion
14672 (beginning-of-line 1)
14673 (if (looking-at
14674 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14675 (setq ov-start (match-beginning 1)
14676 ov-end (match-end 1)
14677 ov-prefix "")
14678 (setq ov-start (1- (point-at-eol))
14679 ov-end (1+ ov-start))
14680 (skip-chars-forward "^\n\r")
14681 (setq ov-prefix
14682 (concat
14683 (buffer-substring (1- (point)) (point))
14684 (if (> (current-column) org-tags-column)
14686 (make-string (- org-tags-column (current-column)) ?\ ))))))
14687 (move-overlay org-tags-overlay ov-start ov-end)
14688 (save-window-excursion
14689 (if expert
14690 (set-buffer (get-buffer-create " *Org tags*"))
14691 (delete-other-windows)
14692 (split-window-vertically)
14693 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14694 (erase-buffer)
14695 (org-set-local 'org-done-keywords done-keywords)
14696 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14697 (org-fast-tag-insert "Current" current c-face "\n\n")
14698 (org-fast-tag-show-exit exit-after-next)
14699 (org-set-current-tags-overlay current ov-prefix)
14700 (setq tbl fulltable char ?a cnt 0)
14701 (while (setq e (pop tbl))
14702 (cond
14703 ((equal (car e) :startgroup)
14704 (push '() groups) (setq ingroup t)
14705 (when (not (= cnt 0))
14706 (setq cnt 0)
14707 (insert "\n"))
14708 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14709 ((equal (car e) :endgroup)
14710 (setq ingroup nil cnt 0)
14711 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14712 ((equal e '(:newline))
14713 (when (not (= cnt 0))
14714 (setq cnt 0)
14715 (insert "\n")
14716 (setq e (car tbl))
14717 (while (equal (car tbl) '(:newline))
14718 (insert "\n")
14719 (setq tbl (cdr tbl)))))
14720 ((equal e '(:grouptags)) nil)
14722 (setq tg (copy-sequence (car e)) c2 nil)
14723 (if (cdr e)
14724 (setq c (cdr e))
14725 ;; automatically assign a character.
14726 (setq c1 (string-to-char
14727 (downcase (substring
14728 tg (if (= (string-to-char tg) ?@) 1 0)))))
14729 (if (or (rassoc c1 ntable) (rassoc c1 table))
14730 (while (or (rassoc char ntable) (rassoc char table))
14731 (setq char (1+ char)))
14732 (setq c2 c1))
14733 (setq c (or c2 char)))
14734 (if ingroup (push tg (car groups)))
14735 (setq tg (org-add-props tg nil 'face
14736 (cond
14737 ((not (assoc tg table))
14738 (org-get-todo-face tg))
14739 ((member tg current) c-face)
14740 ((member tg inherited) i-face))))
14741 (if (equal (caar tbl) :grouptags)
14742 (org-add-props tg nil 'face 'org-tag-group))
14743 (if (and (= cnt 0) (not ingroup)) (insert " "))
14744 (insert "[" c "] " tg (make-string
14745 (- fwidth 4 (length tg)) ?\ ))
14746 (push (cons tg c) ntable)
14747 (when (= (setq cnt (1+ cnt)) ncol)
14748 (insert "\n")
14749 (if ingroup (insert " "))
14750 (setq cnt 0)))))
14751 (setq ntable (nreverse ntable))
14752 (insert "\n")
14753 (goto-char (point-min))
14754 (if (not expert) (org-fit-window-to-buffer))
14755 (setq rtn
14756 (catch 'exit
14757 (while t
14758 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14759 (if (not groups) "no " "")
14760 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14761 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14762 (setq org-last-tag-selection-key c)
14763 (cond
14764 ((= c ?\r) (throw 'exit t))
14765 ((= c ?!)
14766 (setq groups (not groups))
14767 (goto-char (point-min))
14768 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14769 ((= c ?\C-c)
14770 (if (not expert)
14771 (org-fast-tag-show-exit
14772 (setq exit-after-next (not exit-after-next)))
14773 (setq expert nil)
14774 (delete-other-windows)
14775 (set-window-buffer (split-window-vertically) " *Org tags*")
14776 (org-switch-to-buffer-other-window " *Org tags*")
14777 (org-fit-window-to-buffer)))
14778 ((or (= c ?\C-g)
14779 (and (= c ?q) (not (rassoc c ntable))))
14780 (org-detach-overlay org-tags-overlay)
14781 (setq quit-flag t))
14782 ((= c ?\ )
14783 (setq current nil)
14784 (if exit-after-next (setq exit-after-next 'now)))
14785 ((= c ?\t)
14786 (condition-case nil
14787 (setq tg (org-icompleting-read
14788 "Tag: "
14789 (or buffer-tags
14790 (with-current-buffer buf
14791 (org-get-buffer-tags)))))
14792 (quit (setq tg "")))
14793 (when (string-match "\\S-" tg)
14794 (add-to-list 'buffer-tags (list tg))
14795 (if (member tg current)
14796 (setq current (delete tg current))
14797 (push tg current)))
14798 (if exit-after-next (setq exit-after-next 'now)))
14799 ((setq e (rassoc c todo-table) tg (car e))
14800 (with-current-buffer buf
14801 (save-excursion (org-todo tg)))
14802 (if exit-after-next (setq exit-after-next 'now)))
14803 ((setq e (rassoc c ntable) tg (car e))
14804 (if (member tg current)
14805 (setq current (delete tg current))
14806 (loop for g in groups do
14807 (if (member tg g)
14808 (mapc (lambda (x)
14809 (setq current (delete x current)))
14810 g)))
14811 (push tg current))
14812 (if exit-after-next (setq exit-after-next 'now))))
14814 ;; Create a sorted list
14815 (setq current
14816 (sort current
14817 (lambda (a b)
14818 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14819 (if (eq exit-after-next 'now) (throw 'exit t))
14820 (goto-char (point-min))
14821 (beginning-of-line 2)
14822 (delete-region (point) (point-at-eol))
14823 (org-fast-tag-insert "Current" current c-face)
14824 (org-set-current-tags-overlay current ov-prefix)
14825 (while (re-search-forward
14826 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14827 (setq tg (match-string 1))
14828 (add-text-properties
14829 (match-beginning 1) (match-end 1)
14830 (list 'face
14831 (cond
14832 ((member tg current) c-face)
14833 ((member tg inherited) i-face)
14834 (t (get-text-property (match-beginning 1) 'face))))))
14835 (goto-char (point-min)))))
14836 (org-detach-overlay org-tags-overlay)
14837 (if rtn
14838 (mapconcat 'identity current ":")
14839 nil))))
14841 (defun org-get-tags-string ()
14842 "Get the TAGS string in the current headline."
14843 (unless (org-at-heading-p t)
14844 (user-error "Not on a heading"))
14845 (save-excursion
14846 (beginning-of-line 1)
14847 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14848 (org-match-string-no-properties 1)
14849 "")))
14851 (defun org-get-tags ()
14852 "Get the list of tags specified in the current headline."
14853 (org-split-string (org-get-tags-string) ":"))
14855 (defun org-get-buffer-tags ()
14856 "Get a table of all tags used in the buffer, for completion."
14857 (let (tags)
14858 (save-excursion
14859 (goto-char (point-min))
14860 (while (re-search-forward
14861 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14862 (when (equal (char-after (point-at-bol 0)) ?*)
14863 (mapc (lambda (x) (add-to-list 'tags x))
14864 (org-split-string (org-match-string-no-properties 1) ":")))))
14865 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14866 (mapcar 'list tags)))
14868 ;;;; The mapping API
14870 (defun org-map-entries (func &optional match scope &rest skip)
14871 "Call FUNC at each headline selected by MATCH in SCOPE.
14873 FUNC is a function or a lisp form. The function will be called without
14874 arguments, with the cursor positioned at the beginning of the headline.
14875 The return values of all calls to the function will be collected and
14876 returned as a list.
14878 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14879 does not need to preserve point. After evaluation, the cursor will be
14880 moved to the end of the line (presumably of the headline of the
14881 processed entry) and search continues from there. Under some
14882 circumstances, this may not produce the wanted results. For example,
14883 if you have removed (e.g. archived) the current (sub)tree it could
14884 mean that the next entry will be skipped entirely. In such cases, you
14885 can specify the position from where search should continue by making
14886 FUNC set the variable `org-map-continue-from' to the desired buffer
14887 position.
14889 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14890 Only headlines that are matched by this query will be considered during
14891 the iteration. When MATCH is nil or t, all headlines will be
14892 visited by the iteration.
14894 SCOPE determines the scope of this command. It can be any of:
14896 nil The current buffer, respecting the restriction if any
14897 tree The subtree started with the entry at point
14898 region The entries within the active region, if any
14899 region-start-level
14900 The entries within the active region, but only those at
14901 the same level than the first one.
14902 file The current buffer, without restriction
14903 file-with-archives
14904 The current buffer, and any archives associated with it
14905 agenda All agenda files
14906 agenda-with-archives
14907 All agenda files with any archive files associated with them
14908 \(file1 file2 ...)
14909 If this is a list, all files in the list will be scanned
14911 The remaining args are treated as settings for the skipping facilities of
14912 the scanner. The following items can be given here:
14914 archive skip trees with the archive tag
14915 comment skip trees with the COMMENT keyword
14916 function or Emacs Lisp form:
14917 will be used as value for `org-agenda-skip-function', so
14918 whenever the function returns a position, FUNC will not be
14919 called for that entry and search will continue from the
14920 position returned
14922 If your function needs to retrieve the tags including inherited tags
14923 at the *current* entry, you can use the value of the variable
14924 `org-scanner-tags' which will be much faster than getting the value
14925 with `org-get-tags-at'. If your function gets properties with
14926 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14927 to t around the call to `org-entry-properties' to get the same speedup.
14928 Note that if your function moves around to retrieve tags and properties at
14929 a *different* entry, you cannot use these techniques."
14930 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14931 (not (org-region-active-p)))
14932 (let* ((org-agenda-archives-mode nil) ; just to make sure
14933 (org-agenda-skip-archived-trees (memq 'archive skip))
14934 (org-agenda-skip-comment-trees (memq 'comment skip))
14935 (org-agenda-skip-function
14936 (car (org-delete-all '(comment archive) skip)))
14937 (org-tags-match-list-sublevels t)
14938 (start-level (eq scope 'region-start-level))
14939 matcher file res
14940 org-todo-keywords-for-agenda
14941 org-done-keywords-for-agenda
14942 org-todo-keyword-alist-for-agenda
14943 org-tag-alist-for-agenda
14944 todo-only)
14946 (cond
14947 ((eq match t) (setq matcher t))
14948 ((eq match nil) (setq matcher t))
14949 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14951 (save-window-excursion
14952 (save-restriction
14953 (cond ((eq scope 'tree)
14954 (org-back-to-heading t)
14955 (org-narrow-to-subtree)
14956 (setq scope nil))
14957 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14958 (org-region-active-p))
14959 ;; If needed, set start-level to a string like "2"
14960 (when start-level
14961 (save-excursion
14962 (goto-char (region-beginning))
14963 (unless (org-at-heading-p) (outline-next-heading))
14964 (setq start-level (org-current-level))))
14965 (narrow-to-region (region-beginning)
14966 (save-excursion
14967 (goto-char (region-end))
14968 (unless (and (bolp) (org-at-heading-p))
14969 (outline-next-heading))
14970 (point)))
14971 (setq scope nil)))
14973 (if (not scope)
14974 (progn
14975 (org-agenda-prepare-buffers
14976 (list (buffer-file-name (current-buffer))))
14977 (setq res (org-scan-tags func matcher todo-only start-level)))
14978 ;; Get the right scope
14979 (cond
14980 ((and scope (listp scope) (symbolp (car scope)))
14981 (setq scope (eval scope)))
14982 ((eq scope 'agenda)
14983 (setq scope (org-agenda-files t)))
14984 ((eq scope 'agenda-with-archives)
14985 (setq scope (org-agenda-files t))
14986 (setq scope (org-add-archive-files scope)))
14987 ((eq scope 'file)
14988 (setq scope (list (buffer-file-name))))
14989 ((eq scope 'file-with-archives)
14990 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14991 (org-agenda-prepare-buffers scope)
14992 (while (setq file (pop scope))
14993 (with-current-buffer (org-find-base-buffer-visiting file)
14994 (save-excursion
14995 (save-restriction
14996 (widen)
14997 (goto-char (point-min))
14998 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14999 res)))
15001 ;;;; Properties
15003 ;;; Setting and retrieving properties
15005 (defconst org-special-properties
15006 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15007 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15008 "The special properties valid in Org-mode.
15010 These are properties that are not defined in the property drawer,
15011 but in some other way.")
15013 (defconst org-default-properties
15014 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15015 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15016 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15017 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15018 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15019 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15020 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15021 "Some properties that are used by Org-mode for various purposes.
15022 Being in this list makes sure that they are offered for completion.")
15024 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15025 "Regular expression matching the first line of a property drawer.")
15027 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15028 "Regular expression matching the last line of a property drawer.")
15030 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15031 "Regular expression matching the first line of a property drawer.")
15033 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15034 "Regular expression matching the first line of a property drawer.")
15036 (defconst org-property-drawer-re
15037 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
15038 org-property-end-re "\\)\n?")
15039 "Matches an entire property drawer.")
15041 (defconst org-clock-drawer-re
15042 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
15043 org-property-end-re "\\)\n?")
15044 "Matches an entire clock drawer.")
15046 (defun org-property-action ()
15047 "Do an action on properties."
15048 (interactive)
15049 (let (c)
15050 (org-at-property-p)
15051 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15052 (setq c (read-char-exclusive))
15053 (cond
15054 ((equal c ?s)
15055 (call-interactively 'org-set-property))
15056 ((equal c ?d)
15057 (call-interactively 'org-delete-property))
15058 ((equal c ?D)
15059 (call-interactively 'org-delete-property-globally))
15060 ((equal c ?c)
15061 (call-interactively 'org-compute-property-at-point))
15062 (t (user-error "No such property action %c" c)))))
15064 (defun org-inc-effort ()
15065 "Increment the value of the effort property in the current entry."
15066 (interactive)
15067 (org-set-effort nil t))
15069 (defvar org-clock-effort) ;; Defined in org-clock.el
15070 (defvar org-clock-current-task) ;; Defined in org-clock.el
15071 (defun org-set-effort (&optional value increment)
15072 "Set the effort property of the current entry.
15073 With numerical prefix arg, use the nth allowed value, 0 stands for the
15074 10th allowed value.
15076 When INCREMENT is non-nil, set the property to the next allowed value."
15077 (interactive "P")
15078 (if (equal value 0) (setq value 10))
15079 (let* ((completion-ignore-case t)
15080 (prop org-effort-property)
15081 (cur (org-entry-get nil prop))
15082 (allowed (org-property-get-allowed-values nil prop 'table))
15083 (existing (mapcar 'list (org-property-values prop)))
15084 (heading (nth 4 (org-heading-components)))
15086 (val (cond
15087 ((stringp value) value)
15088 ((and allowed (integerp value))
15089 (or (car (nth (1- value) allowed))
15090 (car (org-last allowed))))
15091 ((and allowed increment)
15092 (or (caadr (member (list cur) allowed))
15093 (user-error "Allowed effort values are not set")))
15094 (allowed
15095 (message "Select 1-9,0, [RET%s]: %s"
15096 (if cur (concat "=" cur) "")
15097 (mapconcat 'car allowed " "))
15098 (setq rpl (read-char-exclusive))
15099 (if (equal rpl ?\r)
15101 (setq rpl (- rpl ?0))
15102 (if (equal rpl 0) (setq rpl 10))
15103 (if (and (> rpl 0) (<= rpl (length allowed)))
15104 (car (nth (1- rpl) allowed))
15105 (org-completing-read "Effort: " allowed nil))))
15107 (let (org-completion-use-ido org-completion-use-iswitchb)
15108 (org-completing-read
15109 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15110 (concat "[" cur "]") "")
15111 ": ")
15112 existing nil nil "" nil cur))))))
15113 (unless (equal (org-entry-get nil prop) val)
15114 (org-entry-put nil prop val))
15115 (save-excursion
15116 (org-back-to-heading t)
15117 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15118 (when (string= heading org-clock-current-task)
15119 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15120 (org-clock-update-mode-line))
15121 (message "%s is now %s" prop val)))
15123 (defun org-at-property-p ()
15124 "Is cursor inside a property drawer?"
15125 (save-excursion
15126 (when (equal 'node-property (car (org-element-at-point)))
15127 (beginning-of-line 1)
15128 (looking-at org-property-re))))
15130 (defun org-get-property-block (&optional beg end force)
15131 "Return the (beg . end) range of the body of the property drawer.
15132 BEG and END are the beginning and end of the current subtree, or of
15133 the part before the first headline. If they are not given, they will
15134 be found. If the drawer does not exist and FORCE is non-nil, create
15135 the drawer."
15136 (catch 'exit
15137 (save-excursion
15138 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15139 (progn (org-back-to-heading t) (point))))
15140 (end (or end (and (not (outline-next-heading)) (point-max))
15141 (point))))
15142 (goto-char beg)
15143 (if (re-search-forward org-property-start-re end t)
15144 (setq beg (1+ (match-end 0)))
15145 (if force
15146 (save-excursion
15147 (org-insert-property-drawer)
15148 (setq end (progn (outline-next-heading) (point))))
15149 (throw 'exit nil))
15150 (goto-char beg)
15151 (if (re-search-forward org-property-start-re end t)
15152 (setq beg (1+ (match-end 0)))))
15153 (if (re-search-forward org-property-end-re end t)
15154 (setq end (match-beginning 0))
15155 (or force (throw 'exit nil))
15156 (goto-char beg)
15157 (setq end beg)
15158 (org-indent-line)
15159 (insert ":END:\n"))
15160 (cons beg end)))))
15162 (defun org-entry-properties (&optional pom which specific)
15163 "Get all properties of the entry at point-or-marker POM.
15164 This includes the TODO keyword, the tags, time strings for deadline,
15165 scheduled, and clocking, and any additional properties defined in the
15166 entry. The return value is an alist, keys may occur multiple times
15167 if the property key was used several times.
15168 POM may also be nil, in which case the current entry is used.
15169 If WHICH is nil or `all', get all properties. If WHICH is
15170 `special' or `standard', only get that subclass. If WHICH
15171 is a string only get exactly this property. SPECIFIC can be a string, the
15172 specific property we are interested in. Specifying it can speed
15173 things up because then unnecessary parsing is avoided."
15174 (setq which (or which 'all))
15175 (org-with-point-at pom
15176 (let ((clockstr (substring org-clock-string 0 -1))
15177 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15178 (case-fold-search nil)
15179 beg end range props sum-props key key1 value string clocksum clocksumt)
15180 (save-excursion
15181 (when (condition-case nil
15182 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15183 (error nil))
15184 (setq beg (point))
15185 (setq sum-props (get-text-property (point) 'org-summaries))
15186 (setq clocksum (get-text-property (point) :org-clock-minutes)
15187 clocksumt (get-text-property (point) :org-clock-minutes-today))
15188 (outline-next-heading)
15189 (setq end (point))
15190 (when (memq which '(all special))
15191 ;; Get the special properties, like TODO and tags
15192 (goto-char beg)
15193 (when (and (or (not specific) (string= specific "TODO"))
15194 (looking-at org-todo-line-regexp) (match-end 2))
15195 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15196 (when (and (or (not specific) (string= specific "PRIORITY"))
15197 (looking-at org-priority-regexp))
15198 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15199 (when (or (not specific) (string= specific "FILE"))
15200 (push (cons "FILE" buffer-file-name) props))
15201 (when (and (or (not specific) (string= specific "TAGS"))
15202 (setq value (org-get-tags-string))
15203 (string-match "\\S-" value))
15204 (push (cons "TAGS" value) props))
15205 (when (and (or (not specific) (string= specific "ALLTAGS"))
15206 (setq value (org-get-tags-at)))
15207 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15208 ":"))
15209 props))
15210 (when (or (not specific) (string= specific "BLOCKED"))
15211 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15212 (when (or (not specific)
15213 (member specific
15214 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15215 "TIMESTAMP" "TIMESTAMP_IA")))
15216 (catch 'match
15217 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15218 (setq key (if (match-end 1)
15219 (substring (org-match-string-no-properties 1)
15220 0 -1))
15221 string (if (equal key clockstr)
15222 (org-trim
15223 (buffer-substring-no-properties
15224 (match-beginning 3) (goto-char
15225 (point-at-eol))))
15226 (substring (org-match-string-no-properties 3)
15227 1 -1)))
15228 ;; Get the correct property name from the key. This is
15229 ;; necessary if the user has configured time keywords.
15230 (setq key1 (concat key ":"))
15231 (cond
15232 ((not key)
15233 (setq key
15234 (if (= (char-after (match-beginning 3)) ?\[)
15235 "TIMESTAMP_IA" "TIMESTAMP")))
15236 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15237 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15238 ((equal key1 org-closed-string) (setq key "CLOSED"))
15239 ((equal key1 org-clock-string) (setq key "CLOCK")))
15240 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15241 (progn
15242 (push (cons key string) props)
15243 ;; no need to search further if match is found
15244 (throw 'match t))
15245 (when (or (equal key "CLOCK") (not (assoc key props)))
15246 (push (cons key string) props)))))))
15248 (when (memq which '(all standard))
15249 ;; Get the standard properties, like :PROP: ...
15250 (setq range (org-get-property-block beg end))
15251 (when range
15252 (goto-char (car range))
15253 (while (re-search-forward org-property-re
15254 (cdr range) t)
15255 (setq key (org-match-string-no-properties 2)
15256 value (org-trim (or (org-match-string-no-properties 3) "")))
15257 (unless (member key excluded)
15258 (push (cons key (or value "")) props)))))
15259 (if clocksum
15260 (push (cons "CLOCKSUM"
15261 (org-columns-number-to-string (/ (float clocksum) 60.)
15262 'add_times))
15263 props))
15264 (if clocksumt
15265 (push (cons "CLOCKSUM_T"
15266 (org-columns-number-to-string (/ (float clocksumt) 60.)
15267 'add_times))
15268 props))
15269 (unless (assoc "CATEGORY" props)
15270 (push (cons "CATEGORY" (org-get-category)) props))
15271 (append sum-props (nreverse props)))))))
15273 (defun org-entry-get (pom property &optional inherit literal-nil)
15274 "Get value of PROPERTY for entry or content at point-or-marker POM.
15275 If INHERIT is non-nil and the entry does not have the property,
15276 then also check higher levels of the hierarchy.
15277 If INHERIT is the symbol `selective', use inheritance only if the setting
15278 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15279 If the property is present but empty, the return value is the empty string.
15280 If the property is not present at all, nil is returned.
15282 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15283 do not interpret it as the list atom nil. This is used for inheritance
15284 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15285 (org-with-point-at pom
15286 (if (and inherit (if (eq inherit 'selective)
15287 (org-property-inherit-p property)
15289 (org-entry-get-with-inheritance property literal-nil)
15290 (if (member property org-special-properties)
15291 ;; We need a special property. Use `org-entry-properties' to
15292 ;; retrieve it, but specify the wanted property
15293 (cdr (assoc property (org-entry-properties nil 'special property)))
15294 (let ((range (org-get-property-block)))
15295 (when (and range (not (eq (car range) (cdr range))))
15296 (let* ((props (list (or (assoc property org-file-properties)
15297 (assoc property org-global-properties)
15298 (assoc property org-global-properties-fixed))))
15299 (ap (lambda (key)
15300 (when (re-search-forward
15301 (org-re-property key) (cdr range) t)
15302 (setq props
15303 (org-update-property-plist
15305 (if (match-end 3)
15306 (org-match-string-no-properties 3) "")
15307 props)))))
15308 val)
15309 (goto-char (car range))
15310 (funcall ap property)
15311 (goto-char (car range))
15312 (while (funcall ap (concat property "+")))
15313 (setq val (cdr (assoc property props)))
15314 (when val (if literal-nil val (org-not-nil val))))))))))
15316 (defun org-property-or-variable-value (var &optional inherit)
15317 "Check if there is a property fixing the value of VAR.
15318 If yes, return this value. If not, return the current value of the variable."
15319 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15320 (if (and prop (stringp prop) (string-match "\\S-" prop))
15321 (read prop)
15322 (symbol-value var))))
15324 (defun org-entry-delete (pom property)
15325 "Delete the property PROPERTY from entry at point-or-marker POM."
15326 (unless (member property org-special-properties)
15327 (org-with-point-at pom
15328 (let ((range (org-get-property-block)))
15329 (if (and range
15330 (goto-char (car range))
15331 (re-search-forward
15332 (org-re-property property)
15333 (cdr range) t))
15334 (progn
15335 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15336 (org-remove-empty-drawer-at (car range))
15338 nil)))))
15340 ;; Multi-values properties are properties that contain multiple values
15341 ;; These values are assumed to be single words, separated by whitespace.
15342 (defun org-entry-add-to-multivalued-property (pom property value)
15343 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15344 (let* ((old (org-entry-get pom property))
15345 (values (and old (org-split-string old "[ \t]"))))
15346 (setq value (org-entry-protect-space value))
15347 (unless (member value values)
15348 (setq values (append values (list value)))
15349 (org-entry-put pom property
15350 (mapconcat 'identity values " ")))))
15352 (defun org-entry-remove-from-multivalued-property (pom property value)
15353 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15354 (let* ((old (org-entry-get pom property))
15355 (values (and old (org-split-string old "[ \t]"))))
15356 (setq value (org-entry-protect-space value))
15357 (when (member value values)
15358 (setq values (delete value values))
15359 (org-entry-put pom property
15360 (mapconcat 'identity values " ")))))
15362 (defun org-entry-member-in-multivalued-property (pom property value)
15363 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15364 (let* ((old (org-entry-get pom property))
15365 (values (and old (org-split-string old "[ \t]"))))
15366 (setq value (org-entry-protect-space value))
15367 (member value values)))
15369 (defun org-entry-get-multivalued-property (pom property)
15370 "Return a list of values in a multivalued property."
15371 (let* ((value (org-entry-get pom property))
15372 (values (and value (org-split-string value "[ \t]"))))
15373 (mapcar 'org-entry-restore-space values)))
15375 (defun org-entry-put-multivalued-property (pom property &rest values)
15376 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15377 VALUES should be a list of strings. Spaces will be protected."
15378 (org-entry-put pom property
15379 (mapconcat 'org-entry-protect-space values " "))
15380 (let* ((value (org-entry-get pom property))
15381 (values (and value (org-split-string value "[ \t]"))))
15382 (mapcar 'org-entry-restore-space values)))
15384 (defun org-entry-protect-space (s)
15385 "Protect spaces and newline in string S."
15386 (while (string-match " " s)
15387 (setq s (replace-match "%20" t t s)))
15388 (while (string-match "\n" s)
15389 (setq s (replace-match "%0A" t t s)))
15392 (defun org-entry-restore-space (s)
15393 "Restore spaces and newline in string S."
15394 (while (string-match "%20" s)
15395 (setq s (replace-match " " t t s)))
15396 (while (string-match "%0A" s)
15397 (setq s (replace-match "\n" t t s)))
15400 (defvar org-entry-property-inherited-from (make-marker)
15401 "Marker pointing to the entry from where a property was inherited.
15402 Each call to `org-entry-get-with-inheritance' will set this marker to the
15403 location of the entry where the inheritance search matched. If there was
15404 no match, the marker will point nowhere.
15405 Note that also `org-entry-get' calls this function, if the INHERIT flag
15406 is set.")
15408 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15409 "Get PROPERTY of entry or content at point, search higher levels if needed.
15410 The search will stop at the first ancestor which has the property defined.
15411 If the value found is \"nil\", return nil to show that the property
15412 should be considered as undefined (this is the meaning of nil here).
15413 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15414 (move-marker org-entry-property-inherited-from nil)
15415 (let (tmp)
15416 (save-excursion
15417 (save-restriction
15418 (widen)
15419 (catch 'ex
15420 (while t
15421 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15422 (or (ignore-errors (org-back-to-heading t))
15423 (goto-char (point-min)))
15424 (move-marker org-entry-property-inherited-from (point))
15425 (throw 'ex tmp))
15426 (or (ignore-errors (org-up-heading-safe))
15427 (throw 'ex nil))))))
15428 (setq tmp (or tmp
15429 (cdr (assoc property org-file-properties))
15430 (cdr (assoc property org-global-properties))
15431 (cdr (assoc property org-global-properties-fixed))))
15432 (if literal-nil tmp (org-not-nil tmp))))
15434 (defvar org-property-changed-functions nil
15435 "Hook called when the value of a property has changed.
15436 Each hook function should accept two arguments, the name of the property
15437 and the new value.")
15439 (defun org-entry-put (pom property value)
15440 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15441 (org-with-point-at pom
15442 (org-back-to-heading t)
15443 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15444 range)
15445 (cond
15446 ((equal property "TODO")
15447 (when (and (stringp value) (string-match "\\S-" value)
15448 (not (member value org-todo-keywords-1)))
15449 (user-error "\"%s\" is not a valid TODO state" value))
15450 (if (or (not value)
15451 (not (string-match "\\S-" value)))
15452 (setq value 'none))
15453 (org-todo value)
15454 (org-set-tags nil 'align))
15455 ((equal property "PRIORITY")
15456 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15457 (string-to-char value) ?\ ))
15458 (org-set-tags nil 'align))
15459 ((equal property "CLOCKSUM")
15460 (if (not (re-search-forward
15461 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15462 (error "Cannot find a clock log")
15463 (goto-char (- (match-end 1) 2))
15464 (cond
15465 ((eq value 'earlier) (org-timestamp-down))
15466 ((eq value 'later) (org-timestamp-up)))
15467 (org-clock-sum-current-item)))
15468 ((equal property "SCHEDULED")
15469 (if (re-search-forward org-scheduled-time-regexp end t)
15470 (cond
15471 ((eq value 'earlier) (org-timestamp-change -1 'day))
15472 ((eq value 'later) (org-timestamp-change 1 'day))
15473 (t (call-interactively 'org-schedule)))
15474 (call-interactively 'org-schedule)))
15475 ((equal property "DEADLINE")
15476 (if (re-search-forward org-deadline-time-regexp end t)
15477 (cond
15478 ((eq value 'earlier) (org-timestamp-change -1 'day))
15479 ((eq value 'later) (org-timestamp-change 1 'day))
15480 (t (call-interactively 'org-deadline)))
15481 (call-interactively 'org-deadline)))
15482 ((member property org-special-properties)
15483 (error "The %s property can not yet be set with `org-entry-put'"
15484 property))
15485 (t ; a non-special property
15486 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15487 (setq range (org-get-property-block beg end 'force))
15488 (goto-char (car range))
15489 (if (re-search-forward
15490 (org-re-property property) (cdr range) t)
15491 (progn
15492 (delete-region (match-beginning 0) (match-end 0))
15493 (goto-char (match-beginning 0)))
15494 (goto-char (cdr range))
15495 (insert "\n")
15496 (backward-char 1)
15497 (org-indent-line))
15498 (insert ":" property ":")
15499 (and value (insert " " value))
15500 (org-indent-line)))))
15501 (run-hook-with-args 'org-property-changed-functions property value)))
15503 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15504 "Get all property keys in the current buffer.
15505 With INCLUDE-SPECIALS, also list the special properties that reflect things
15506 like tags and TODO state.
15507 With INCLUDE-DEFAULTS, also include properties that has special meaning
15508 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15509 and others.
15510 With INCLUDE-COLUMNS, also include property names given in COLUMN
15511 formats in the current buffer."
15512 (let (rtn range cfmt s p)
15513 (save-excursion
15514 (save-restriction
15515 (widen)
15516 (goto-char (point-min))
15517 (while (re-search-forward org-property-start-re nil t)
15518 (setq range (org-get-property-block))
15519 (goto-char (car range))
15520 (while (re-search-forward org-property-re
15521 (cdr range) t)
15522 (add-to-list 'rtn (org-match-string-no-properties 2)))
15523 (outline-next-heading))))
15525 (when include-specials
15526 (setq rtn (append org-special-properties rtn)))
15528 (when include-defaults
15529 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15530 (add-to-list 'rtn org-effort-property))
15532 (when include-columns
15533 (save-excursion
15534 (save-restriction
15535 (widen)
15536 (goto-char (point-min))
15537 (while (re-search-forward
15538 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15539 nil t)
15540 (setq cfmt (match-string 2) s 0)
15541 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15542 cfmt s)
15543 (setq s (match-end 0)
15544 p (match-string 1 cfmt))
15545 (unless (or (equal p "ITEM")
15546 (member p org-special-properties))
15547 (add-to-list 'rtn (match-string 1 cfmt))))))))
15549 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15551 (defun org-property-values (key)
15552 "Return a list of all values of property KEY in the current buffer."
15553 (save-excursion
15554 (save-restriction
15555 (widen)
15556 (goto-char (point-min))
15557 (let ((re (org-re-property key))
15558 values)
15559 (while (re-search-forward re nil t)
15560 (add-to-list 'values (org-trim (match-string 3))))
15561 (delete "" values)))))
15563 (defun org-insert-property-drawer ()
15564 "Insert a property drawer into the current entry."
15565 (org-back-to-heading t)
15566 (looking-at org-outline-regexp)
15567 (let ((indent (if org-adapt-indentation
15568 (- (match-end 0) (match-beginning 0))
15570 (beg (point))
15571 (re (concat "^[ \t]*" org-keyword-time-regexp))
15572 end hiddenp)
15573 (outline-next-heading)
15574 (setq end (point))
15575 (goto-char beg)
15576 (while (re-search-forward re end t))
15577 (setq hiddenp (outline-invisible-p))
15578 (end-of-line 1)
15579 (and (equal (char-after) ?\n) (forward-char 1))
15580 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15581 (if (member (match-string 1) '("CLOCK:" ":END:"))
15582 ;; just skip this line
15583 (beginning-of-line 2)
15584 ;; Drawer start, find the end
15585 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15586 (beginning-of-line 1)))
15587 (org-skip-over-state-notes)
15588 (skip-chars-backward " \t\n\r")
15589 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15590 (forward-char 1))
15591 (goto-char (point-at-eol))
15592 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15593 (beginning-of-line 0)
15594 (org-indent-to-column indent)
15595 (beginning-of-line 2)
15596 (org-indent-to-column indent)
15597 (beginning-of-line 0)
15598 (if hiddenp
15599 (save-excursion
15600 (org-back-to-heading t)
15601 (hide-entry))
15602 (org-flag-drawer t))))
15604 (defun org-insert-drawer (&optional arg drawer)
15605 "Insert a drawer at point.
15607 Optional argument DRAWER, when non-nil, is a string representing
15608 drawer's name. Otherwise, the user is prompted for a name.
15610 If a region is active, insert the drawer around that region
15611 instead.
15613 Point is left between drawer's boundaries."
15614 (interactive "P")
15615 (let* ((drawer (if arg "PROPERTIES"
15616 (or drawer (read-from-minibuffer "Drawer: ")))))
15617 (cond
15618 ;; With C-u, fall back on `org-insert-property-drawer'
15619 (arg (org-insert-property-drawer))
15621 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15622 (user-error "Invalid drawer name"))
15623 ;; With an active region, insert a drawer at point.
15624 ((not (org-region-active-p))
15625 (progn
15626 (unless (bolp) (insert "\n"))
15627 (insert (format ":%s:\n\n:END:\n" drawer))
15628 (forward-line -2)))
15629 ;; Otherwise, insert the drawer at point
15631 (let ((rbeg (region-beginning))
15632 (rend (copy-marker (region-end))))
15633 (unwind-protect
15634 (progn
15635 (goto-char rbeg)
15636 (beginning-of-line)
15637 (when (save-excursion
15638 (re-search-forward org-outline-regexp-bol rend t))
15639 (user-error "Drawers cannot contain headlines"))
15640 ;; Position point at the beginning of the first
15641 ;; non-blank line in region. Insert drawer's opening
15642 ;; there, then indent it.
15643 (org-skip-whitespace)
15644 (beginning-of-line)
15645 (insert ":" drawer ":\n")
15646 (forward-line -1)
15647 (indent-for-tab-command)
15648 ;; Move point to the beginning of the first blank line
15649 ;; after the last non-blank line in region. Insert
15650 ;; drawer's closing, then indent it.
15651 (goto-char rend)
15652 (skip-chars-backward " \r\t\n")
15653 (insert "\n:END:")
15654 (deactivate-mark t)
15655 (indent-for-tab-command)
15656 (unless (eolp) (insert "\n")))
15657 ;; Clear marker, whatever the outcome of insertion is.
15658 (set-marker rend nil)))))))
15660 (defvar org-property-set-functions-alist nil
15661 "Property set function alist.
15662 Each entry should have the following format:
15664 (PROPERTY . READ-FUNCTION)
15666 The read function will be called with the same argument as
15667 `org-completing-read'.")
15669 (defun org-set-property-function (property)
15670 "Get the function that should be used to set PROPERTY.
15671 This is computed according to `org-property-set-functions-alist'."
15672 (or (cdr (assoc property org-property-set-functions-alist))
15673 'org-completing-read))
15675 (defun org-read-property-value (property)
15676 "Read PROPERTY value from user."
15677 (let* ((completion-ignore-case t)
15678 (allowed (org-property-get-allowed-values nil property 'table))
15679 (cur (org-entry-get nil property))
15680 (prompt (concat property " value"
15681 (if (and cur (string-match "\\S-" cur))
15682 (concat " [" cur "]") "") ": "))
15683 (set-function (org-set-property-function property))
15684 (val (if allowed
15685 (funcall set-function prompt allowed nil
15686 (not (get-text-property 0 'org-unrestricted
15687 (caar allowed))))
15688 (let (org-completion-use-ido org-completion-use-iswitchb)
15689 (funcall set-function prompt
15690 (mapcar 'list (org-property-values property))
15691 nil nil "" nil cur)))))
15692 (if (equal val "")
15694 val)))
15696 (defvar org-last-set-property nil)
15697 (defvar org-last-set-property-value nil)
15698 (defun org-read-property-name ()
15699 "Read a property name."
15700 (let* ((completion-ignore-case t)
15701 (keys (org-buffer-property-keys nil t t))
15702 (default-prop (or (save-excursion
15703 (save-match-data
15704 (beginning-of-line)
15705 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15706 (null (string= (match-string 1) "END"))
15707 (match-string 1))))
15708 org-last-set-property))
15709 (property (org-icompleting-read
15710 (concat "Property"
15711 (if default-prop (concat " [" default-prop "]") "")
15712 ": ")
15713 (mapcar 'list keys)
15714 nil nil nil nil
15715 default-prop)))
15716 (if (member property keys)
15717 property
15718 (or (cdr (assoc (downcase property)
15719 (mapcar (lambda (x) (cons (downcase x) x))
15720 keys)))
15721 property))))
15723 (defun org-set-property-and-value (use-last)
15724 "Allow to set [PROPERTY]: [value] direction from prompt.
15725 When use-default, don't even ask, just use the last
15726 \"[PROPERTY]: [value]\" string from the history."
15727 (interactive "P")
15728 (let* ((completion-ignore-case t)
15729 (pv (or (and use-last org-last-set-property-value)
15730 (org-completing-read
15731 "Enter a \"[Property]: [value]\" pair: "
15732 nil nil nil nil nil
15733 org-last-set-property-value)))
15734 prop val)
15735 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15736 (setq prop (match-string 1 pv)
15737 val (match-string 2 pv))
15738 (org-set-property prop val))))
15740 (defun org-set-property (property value)
15741 "In the current entry, set PROPERTY to VALUE.
15742 When called interactively, this will prompt for a property name, offering
15743 completion on existing and default properties. And then it will prompt
15744 for a value, offering completion either on allowed values (via an inherited
15745 xxx_ALL property) or on existing values in other instances of this property
15746 in the current file."
15747 (interactive (list nil nil))
15748 (let* ((property (or property (org-read-property-name)))
15749 (value (or value (org-read-property-value property)))
15750 (fn (cdr (assoc property org-properties-postprocess-alist))))
15751 (setq org-last-set-property property)
15752 (setq org-last-set-property-value (concat property ": " value))
15753 ;; Possibly postprocess the inserted value:
15754 (when fn (setq value (funcall fn value)))
15755 (unless (equal (org-entry-get nil property) value)
15756 (org-entry-put nil property value))))
15758 (defun org-delete-property (property)
15759 "In the current entry, delete PROPERTY."
15760 (interactive
15761 (let* ((completion-ignore-case t)
15762 (prop (org-icompleting-read "Property: "
15763 (org-entry-properties nil 'standard))))
15764 (list prop)))
15765 (message "Property %s %s" property
15766 (if (org-entry-delete nil property)
15767 "deleted"
15768 "was not present in the entry")))
15770 (defun org-delete-property-globally (property)
15771 "Remove PROPERTY globally, from all entries."
15772 (interactive
15773 (let* ((completion-ignore-case t)
15774 (prop (org-icompleting-read
15775 "Globally remove property: "
15776 (mapcar 'list (org-buffer-property-keys)))))
15777 (list prop)))
15778 (save-excursion
15779 (save-restriction
15780 (widen)
15781 (goto-char (point-min))
15782 (let ((cnt 0))
15783 (while (re-search-forward
15784 (org-re-property property)
15785 nil t)
15786 (setq cnt (1+ cnt))
15787 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15788 (message "Property \"%s\" removed from %d entries" property cnt)))))
15790 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15792 (defun org-compute-property-at-point ()
15793 "Compute the property at point.
15794 This looks for an enclosing column format, extracts the operator and
15795 then applies it to the property in the column format's scope."
15796 (interactive)
15797 (unless (org-at-property-p)
15798 (user-error "Not at a property"))
15799 (let ((prop (org-match-string-no-properties 2)))
15800 (org-columns-get-format-and-top-level)
15801 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15802 (user-error "No operator defined for property %s" prop))
15803 (org-columns-compute prop)))
15805 (defvar org-property-allowed-value-functions nil
15806 "Hook for functions supplying allowed values for a specific property.
15807 The functions must take a single argument, the name of the property, and
15808 return a flat list of allowed values. If \":ETC\" is one of
15809 the values, this means that these values are intended as defaults for
15810 completion, but that other values should be allowed too.
15811 The functions must return nil if they are not responsible for this
15812 property.")
15814 (defun org-property-get-allowed-values (pom property &optional table)
15815 "Get allowed values for the property PROPERTY.
15816 When TABLE is non-nil, return an alist that can directly be used for
15817 completion."
15818 (let (vals)
15819 (cond
15820 ((equal property "TODO")
15821 (setq vals (org-with-point-at pom
15822 (append org-todo-keywords-1 '("")))))
15823 ((equal property "PRIORITY")
15824 (let ((n org-lowest-priority))
15825 (while (>= n org-highest-priority)
15826 (push (char-to-string n) vals)
15827 (setq n (1- n)))))
15828 ((member property org-special-properties))
15829 ((setq vals (run-hook-with-args-until-success
15830 'org-property-allowed-value-functions property)))
15832 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15833 (when (and vals (string-match "\\S-" vals))
15834 (setq vals (car (read-from-string (concat "(" vals ")"))))
15835 (setq vals (mapcar (lambda (x)
15836 (cond ((stringp x) x)
15837 ((numberp x) (number-to-string x))
15838 ((symbolp x) (symbol-name x))
15839 (t "???")))
15840 vals)))))
15841 (when (member ":ETC" vals)
15842 (setq vals (remove ":ETC" vals))
15843 (org-add-props (car vals) '(org-unrestricted t)))
15844 (if table (mapcar 'list vals) vals)))
15846 (defun org-property-previous-allowed-value (&optional previous)
15847 "Switch to the next allowed value for this property."
15848 (interactive)
15849 (org-property-next-allowed-value t))
15851 (defun org-property-next-allowed-value (&optional previous)
15852 "Switch to the next allowed value for this property."
15853 (interactive)
15854 (unless (org-at-property-p)
15855 (user-error "Not at a property"))
15856 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15857 (key (match-string 2))
15858 (value (match-string 3))
15859 (allowed (or (org-property-get-allowed-values (point) key)
15860 (and (member value '("[ ]" "[-]" "[X]"))
15861 '("[ ]" "[X]"))))
15862 (heading (save-match-data (nth 4 (org-heading-components))))
15863 nval)
15864 (unless allowed
15865 (user-error "Allowed values for this property have not been defined"))
15866 (if previous (setq allowed (reverse allowed)))
15867 (if (member value allowed)
15868 (setq nval (car (cdr (member value allowed)))))
15869 (setq nval (or nval (car allowed)))
15870 (if (equal nval value)
15871 (user-error "Only one allowed value for this property"))
15872 (org-at-property-p)
15873 (replace-match (concat " :" key ": " nval) t t)
15874 (org-indent-line)
15875 (beginning-of-line 1)
15876 (skip-chars-forward " \t")
15877 (when (equal prop org-effort-property)
15878 (save-excursion
15879 (org-back-to-heading t)
15880 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15881 (when (string= org-clock-current-task heading)
15882 (setq org-clock-effort nval)
15883 (org-clock-update-mode-line)))
15884 (run-hook-with-args 'org-property-changed-functions key nval)))
15886 (defun org-find-olp (path &optional this-buffer)
15887 "Return a marker pointing to the entry at outline path OLP.
15888 If anything goes wrong, throw an error.
15889 You can wrap this call to catch the error like this:
15891 (condition-case msg
15892 (org-mobile-locate-entry (match-string 4))
15893 (error (nth 1 msg)))
15895 The return value will then be either a string with the error message,
15896 or a marker if everything is OK.
15898 If THIS-BUFFER is set, the outline path does not contain a file,
15899 only headings."
15900 (let* ((file (if this-buffer buffer-file-name (pop path)))
15901 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15902 (level 1)
15903 (lmin 1)
15904 (lmax 1)
15905 limit re end found pos heading cnt flevel)
15906 (unless buffer (error "File not found :%s" file))
15907 (with-current-buffer buffer
15908 (save-excursion
15909 (save-restriction
15910 (widen)
15911 (setq limit (point-max))
15912 (goto-char (point-min))
15913 (while (setq heading (pop path))
15914 (setq re (format org-complex-heading-regexp-format
15915 (regexp-quote heading)))
15916 (setq cnt 0 pos (point))
15917 (while (re-search-forward re end t)
15918 (setq level (- (match-end 1) (match-beginning 1)))
15919 (if (and (>= level lmin) (<= level lmax))
15920 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15921 (when (= cnt 0) (error "Heading not found on level %d: %s"
15922 lmax heading))
15923 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15924 lmax heading))
15925 (goto-char found)
15926 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15927 (setq end (save-excursion (org-end-of-subtree t t))))
15928 (when (org-at-heading-p)
15929 (point-marker)))))))
15931 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15932 "Find node HEADING in BUFFER.
15933 Return a marker to the heading if it was found, or nil if not.
15934 If POS-ONLY is set, return just the position instead of a marker.
15936 The heading text must match exact, but it may have a TODO keyword,
15937 a priority cookie and tags in the standard locations."
15938 (with-current-buffer (or buffer (current-buffer))
15939 (save-excursion
15940 (save-restriction
15941 (widen)
15942 (goto-char (point-min))
15943 (let (case-fold-search)
15944 (if (re-search-forward
15945 (format org-complex-heading-regexp-format
15946 (regexp-quote heading)) nil t)
15947 (if pos-only
15948 (match-beginning 0)
15949 (move-marker (make-marker) (match-beginning 0)))))))))
15951 (defun org-find-exact-heading-in-directory (heading &optional dir)
15952 "Find Org node headline HEADING in all .org files in directory DIR.
15953 When the target headline is found, return a marker to this location."
15954 (let ((files (directory-files (or dir default-directory)
15955 nil "\\`[^.#].*\\.org\\'"))
15956 file visiting m buffer)
15957 (catch 'found
15958 (while (setq file (pop files))
15959 (message "trying %s" file)
15960 (setq visiting (org-find-base-buffer-visiting file))
15961 (setq buffer (or visiting (find-file-noselect file)))
15962 (setq m (org-find-exact-headline-in-buffer
15963 heading buffer))
15964 (when (and (not m) (not visiting)) (kill-buffer buffer))
15965 (and m (throw 'found m))))))
15967 (defun org-find-entry-with-id (ident)
15968 "Locate the entry that contains the ID property with exact value IDENT.
15969 IDENT can be a string, a symbol or a number, this function will search for
15970 the string representation of it.
15971 Return the position where this entry starts, or nil if there is no such entry."
15972 (interactive "sID: ")
15973 (let ((id (cond
15974 ((stringp ident) ident)
15975 ((symbol-name ident) (symbol-name ident))
15976 ((numberp ident) (number-to-string ident))
15977 (t (error "IDENT %s must be a string, symbol or number" ident))))
15978 (case-fold-search nil))
15979 (save-excursion
15980 (save-restriction
15981 (widen)
15982 (goto-char (point-min))
15983 (when (re-search-forward
15984 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15985 nil t)
15986 (org-back-to-heading t)
15987 (point))))))
15989 ;;;; Timestamps
15991 (defvar org-last-changed-timestamp nil)
15992 (defvar org-last-inserted-timestamp nil
15993 "The last time stamp inserted with `org-insert-time-stamp'.")
15994 (defvar org-time-was-given) ; dynamically scoped parameter
15995 (defvar org-end-time-was-given) ; dynamically scoped parameter
15996 (defvar org-ts-what) ; dynamically scoped parameter
15998 (defun org-time-stamp (arg &optional inactive)
15999 "Prompt for a date/time and insert a time stamp.
16000 If the user specifies a time like HH:MM or if this command is
16001 called with at least one prefix argument, the time stamp contains
16002 the date and the time. Otherwise, only the date is be included.
16004 All parts of a date not specified by the user is filled in from
16005 the current date/time. So if you just press return without
16006 typing anything, the time stamp will represent the current
16007 date/time.
16009 If there is already a timestamp at the cursor, it will be
16010 modified.
16012 With two universal prefix arguments, insert an active timestamp
16013 with the current time without prompting the user.
16015 When called from lisp, the timestamp is inactive if INACTIVE is
16016 non-nil."
16017 (interactive "P")
16018 (let* ((ts nil)
16019 (default-time
16020 ;; Default time is either today, or, when entering a range,
16021 ;; the range start.
16022 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16023 (save-excursion
16024 (re-search-backward
16025 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16026 (- (point) 20) t)))
16027 (apply 'encode-time (org-parse-time-string (match-string 1)))
16028 (current-time)))
16029 (default-input (and ts (org-get-compact-tod ts)))
16030 (repeater (save-excursion
16031 (save-match-data
16032 (beginning-of-line)
16033 (when (re-search-forward
16034 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16035 (save-excursion (progn (end-of-line) (point))) t)
16036 (match-string 0)))))
16037 org-time-was-given org-end-time-was-given time)
16038 (cond
16039 ((and (org-at-timestamp-p t)
16040 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16041 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16042 (insert "--")
16043 (setq time (let ((this-command this-command))
16044 (org-read-date arg 'totime nil nil
16045 default-time default-input inactive)))
16046 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16047 ((org-at-timestamp-p t)
16048 (setq time (let ((this-command this-command))
16049 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16050 (when (org-at-timestamp-p t) ; just to get the match data
16051 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16052 (replace-match "")
16053 (setq org-last-changed-timestamp
16054 (org-insert-time-stamp
16055 time (or org-time-was-given arg)
16056 inactive nil nil (list org-end-time-was-given)))
16057 (when repeater (goto-char (1- (point))) (insert " " repeater)
16058 (setq org-last-changed-timestamp
16059 (concat (substring org-last-inserted-timestamp 0 -1)
16060 " " repeater ">"))))
16061 (message "Timestamp updated"))
16062 ((equal arg '(16))
16063 (org-insert-time-stamp (current-time) t inactive))
16065 (setq time (let ((this-command this-command))
16066 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16067 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16068 nil nil (list org-end-time-was-given))))))
16070 ;; FIXME: can we use this for something else, like computing time differences?
16071 (defun org-get-compact-tod (s)
16072 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16073 (let* ((t1 (match-string 1 s))
16074 (h1 (string-to-number (match-string 2 s)))
16075 (m1 (string-to-number (match-string 3 s)))
16076 (t2 (and (match-end 4) (match-string 5 s)))
16077 (h2 (and t2 (string-to-number (match-string 6 s))))
16078 (m2 (and t2 (string-to-number (match-string 7 s))))
16079 dh dm)
16080 (if (not t2)
16082 (setq dh (- h2 h1) dm (- m2 m1))
16083 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16084 (concat t1 "+" (number-to-string dh)
16085 (and (/= 0 dm) (format ":%02d" dm)))))))
16087 (defun org-time-stamp-inactive (&optional arg)
16088 "Insert an inactive time stamp.
16089 An inactive time stamp is enclosed in square brackets instead of angle
16090 brackets. It is inactive in the sense that it does not trigger agenda entries,
16091 does not link to the calendar and cannot be changed with the S-cursor keys.
16092 So these are more for recording a certain time/date."
16093 (interactive "P")
16094 (org-time-stamp arg 'inactive))
16096 (defvar org-date-ovl (make-overlay 1 1))
16097 (overlay-put org-date-ovl 'face 'org-date-selected)
16098 (org-detach-overlay org-date-ovl)
16100 (defvar org-ans1) ; dynamically scoped parameter
16101 (defvar org-ans2) ; dynamically scoped parameter
16103 (defvar org-plain-time-of-day-regexp) ; defined below
16105 (defvar org-overriding-default-time nil) ; dynamically scoped
16106 (defvar org-read-date-overlay nil)
16107 (defvar org-dcst nil) ; dynamically scoped
16108 (defvar org-read-date-history nil)
16109 (defvar org-read-date-final-answer nil)
16110 (defvar org-read-date-analyze-futurep nil)
16111 (defvar org-read-date-analyze-forced-year nil)
16112 (defvar org-read-date-inactive)
16114 (defvar org-read-date-minibuffer-local-map
16115 (let* ((org-replace-disputed-keys nil)
16116 (map (make-sparse-keymap)))
16117 (set-keymap-parent map minibuffer-local-map)
16118 (org-defkey map (kbd ".")
16119 (lambda () (interactive)
16120 ;; Are we at the beginning of the prompt?
16121 (if (looking-back "^[^:]+: ")
16122 (org-eval-in-calendar '(calendar-goto-today))
16123 (insert "."))))
16124 (org-defkey map (kbd "C-.")
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-goto-today))))
16127 (org-defkey map [(meta shift left)]
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-backward-month 1))))
16130 (org-defkey map [(meta shift right)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-forward-month 1))))
16133 (org-defkey map [(meta shift up)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-backward-year 1))))
16136 (org-defkey map [(meta shift down)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-forward-year 1))))
16139 (org-defkey map [?\e (shift left)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-backward-month 1))))
16142 (org-defkey map [?\e (shift right)]
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-forward-month 1))))
16145 (org-defkey map [?\e (shift up)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-backward-year 1))))
16148 (org-defkey map [?\e (shift down)]
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-forward-year 1))))
16151 (org-defkey map [(shift up)]
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-backward-week 1))))
16154 (org-defkey map [(shift down)]
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-forward-week 1))))
16157 (org-defkey map [(shift left)]
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(calendar-backward-day 1))))
16160 (org-defkey map [(shift right)]
16161 (lambda () (interactive)
16162 (org-eval-in-calendar '(calendar-forward-day 1))))
16163 (org-defkey map "!"
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(diary-view-entries))
16166 (message "")))
16167 (org-defkey map ">"
16168 (lambda () (interactive)
16169 (org-eval-in-calendar '(scroll-calendar-left 1))))
16170 (org-defkey map "<"
16171 (lambda () (interactive)
16172 (org-eval-in-calendar '(scroll-calendar-right 1))))
16173 (org-defkey map "\C-v"
16174 (lambda () (interactive)
16175 (org-eval-in-calendar
16176 '(calendar-scroll-left-three-months 1))))
16177 (org-defkey map "\M-v"
16178 (lambda () (interactive)
16179 (org-eval-in-calendar
16180 '(calendar-scroll-right-three-months 1))))
16181 map)
16182 "Keymap for minibuffer commands when using `org-read-date'.")
16184 (defun org-read-date (&optional org-with-time to-time from-string prompt
16185 default-time default-input inactive)
16186 "Read a date, possibly a time, and make things smooth for the user.
16187 The prompt will suggest to enter an ISO date, but you can also enter anything
16188 which will at least partially be understood by `parse-time-string'.
16189 Unrecognized parts of the date will default to the current day, month, year,
16190 hour and minute. If this command is called to replace a timestamp at point,
16191 or to enter the second timestamp of a range, the default time is taken
16192 from the existing stamp. Furthermore, the command prefers the future,
16193 so if you are giving a date where the year is not given, and the day-month
16194 combination is already past in the current year, it will assume you
16195 mean next year. For details, see the manual. A few examples:
16197 3-2-5 --> 2003-02-05
16198 feb 15 --> currentyear-02-15
16199 2/15 --> currentyear-02-15
16200 sep 12 9 --> 2009-09-12
16201 12:45 --> today 12:45
16202 22 sept 0:34 --> currentyear-09-22 0:34
16203 12 --> currentyear-currentmonth-12
16204 Fri --> nearest Friday after today
16205 -Tue --> last Tuesday
16206 etc.
16208 Furthermore you can specify a relative date by giving, as the *first* thing
16209 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16210 change in days weeks, months, years.
16211 With a single plus or minus, the date is relative to today. With a double
16212 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16213 +4d --> four days from today
16214 +4 --> same as above
16215 +2w --> two weeks from today
16216 ++5 --> five days from default date
16218 The function understands only English month and weekday abbreviations.
16220 While prompting, a calendar is popped up - you can also select the
16221 date with the mouse (button 1). The calendar shows a period of three
16222 months. To scroll it to other months, use the keys `>' and `<'.
16223 If you don't like the calendar, turn it off with
16224 \(setq org-read-date-popup-calendar nil)
16226 With optional argument TO-TIME, the date will immediately be converted
16227 to an internal time.
16228 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16229 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16230 still enter a time, and this function will inform the calling routine
16231 about this change. The calling routine may then choose to change the
16232 format used to insert the time stamp into the buffer to include the time.
16233 With optional argument FROM-STRING, read from this string instead from
16234 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16235 the time/date that is used for everything that is not specified by the
16236 user."
16237 (require 'parse-time)
16238 (let* ((org-time-stamp-rounding-minutes
16239 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16240 (org-dcst org-display-custom-times)
16241 (ct (org-current-time))
16242 (org-def (or org-overriding-default-time default-time ct))
16243 (org-defdecode (decode-time org-def))
16244 (dummy (progn
16245 (when (< (nth 2 org-defdecode) org-extend-today-until)
16246 (setcar (nthcdr 2 org-defdecode) -1)
16247 (setcar (nthcdr 1 org-defdecode) 59)
16248 (setq org-def (apply 'encode-time org-defdecode)
16249 org-defdecode (decode-time org-def)))))
16250 (mouse-autoselect-window nil) ; Don't let the mouse jump
16251 (calendar-frame-setup nil)
16252 (calendar-setup nil)
16253 (calendar-move-hook nil)
16254 (calendar-view-diary-initially-flag nil)
16255 (calendar-view-holidays-initially-flag nil)
16256 (timestr (format-time-string
16257 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16258 (prompt (concat (if prompt (concat prompt " ") "")
16259 (format "Date+time [%s]: " timestr)))
16260 ans (org-ans0 "") org-ans1 org-ans2 final)
16262 (cond
16263 (from-string (setq ans from-string))
16264 (org-read-date-popup-calendar
16265 (save-excursion
16266 (save-window-excursion
16267 (calendar)
16268 (org-eval-in-calendar '(setq cursor-type nil) t)
16269 (unwind-protect
16270 (progn
16271 (calendar-forward-day (- (time-to-days org-def)
16272 (calendar-absolute-from-gregorian
16273 (calendar-current-date))))
16274 (org-eval-in-calendar nil t)
16275 (let* ((old-map (current-local-map))
16276 (map (copy-keymap calendar-mode-map))
16277 (minibuffer-local-map
16278 (copy-keymap org-read-date-minibuffer-local-map)))
16279 (org-defkey map (kbd "RET") 'org-calendar-select)
16280 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16281 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16282 (unwind-protect
16283 (progn
16284 (use-local-map map)
16285 (setq org-read-date-inactive inactive)
16286 (add-hook 'post-command-hook 'org-read-date-display)
16287 (setq org-ans0 (read-string prompt default-input
16288 'org-read-date-history nil))
16289 ;; org-ans0: from prompt
16290 ;; org-ans1: from mouse click
16291 ;; org-ans2: from calendar motion
16292 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16293 (remove-hook 'post-command-hook 'org-read-date-display)
16294 (use-local-map old-map)
16295 (when org-read-date-overlay
16296 (delete-overlay org-read-date-overlay)
16297 (setq org-read-date-overlay nil)))))
16298 (bury-buffer "*Calendar*")))))
16300 (t ; Naked prompt only
16301 (unwind-protect
16302 (setq ans (read-string prompt default-input
16303 'org-read-date-history timestr))
16304 (when org-read-date-overlay
16305 (delete-overlay org-read-date-overlay)
16306 (setq org-read-date-overlay nil)))))
16308 (setq final (org-read-date-analyze ans org-def org-defdecode))
16310 (when org-read-date-analyze-forced-year
16311 (message "Year was forced into %s"
16312 (if org-read-date-force-compatible-dates
16313 "compatible range (1970-2037)"
16314 "range representable on this machine"))
16315 (ding))
16317 ;; One round trip to get rid of 34th of August and stuff like that....
16318 (setq final (decode-time (apply 'encode-time final)))
16320 (setq org-read-date-final-answer ans)
16322 (if to-time
16323 (apply 'encode-time final)
16324 (if (and (boundp 'org-time-was-given) org-time-was-given)
16325 (format "%04d-%02d-%02d %02d:%02d"
16326 (nth 5 final) (nth 4 final) (nth 3 final)
16327 (nth 2 final) (nth 1 final))
16328 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16330 (defvar org-def)
16331 (defvar org-defdecode)
16332 (defvar org-with-time)
16333 (defun org-read-date-display ()
16334 "Display the current date prompt interpretation in the minibuffer."
16335 (when org-read-date-display-live
16336 (when org-read-date-overlay
16337 (delete-overlay org-read-date-overlay))
16338 (when (minibufferp (current-buffer))
16339 (save-excursion
16340 (end-of-line 1)
16341 (while (not (equal (buffer-substring
16342 (max (point-min) (- (point) 4)) (point))
16343 " "))
16344 (insert " ")))
16345 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16346 " " (or org-ans1 org-ans2)))
16347 (org-end-time-was-given nil)
16348 (f (org-read-date-analyze ans org-def org-defdecode))
16349 (fmts (if org-dcst
16350 org-time-stamp-custom-formats
16351 org-time-stamp-formats))
16352 (fmt (if (or org-with-time
16353 (and (boundp 'org-time-was-given) org-time-was-given))
16354 (cdr fmts)
16355 (car fmts)))
16356 (txt (format-time-string fmt (apply 'encode-time f)))
16357 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16358 (txt (concat "=> " txt)))
16359 (when (and org-end-time-was-given
16360 (string-match org-plain-time-of-day-regexp txt))
16361 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16362 org-end-time-was-given
16363 (substring txt (match-end 0)))))
16364 (when org-read-date-analyze-futurep
16365 (setq txt (concat txt " (=>F)")))
16366 (setq org-read-date-overlay
16367 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16368 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16370 (defun org-read-date-analyze (ans org-def org-defdecode)
16371 "Analyze the combined answer of the date prompt."
16372 ;; FIXME: cleanup and comment
16373 (let ((nowdecode (decode-time (current-time)))
16374 delta deltan deltaw deltadef year month day
16375 hour minute second wday pm h2 m2 tl wday1
16376 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16377 (setq org-read-date-analyze-futurep nil
16378 org-read-date-analyze-forced-year nil)
16379 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16380 (setq ans "+0"))
16382 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16383 (setq ans (replace-match "" t t ans)
16384 deltan (car delta)
16385 deltaw (nth 1 delta)
16386 deltadef (nth 2 delta)))
16388 ;; Check if there is an iso week date in there. If yes, store the
16389 ;; info and postpone interpreting it until the rest of the parsing
16390 ;; is done.
16391 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16392 (setq iso-year (if (match-end 1)
16393 (org-small-year-to-year
16394 (string-to-number (match-string 1 ans))))
16395 iso-weekday (if (match-end 3)
16396 (string-to-number (match-string 3 ans)))
16397 iso-week (string-to-number (match-string 2 ans)))
16398 (setq ans (replace-match "" t t ans)))
16400 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16401 (when (string-match
16402 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16403 (setq year (if (match-end 2)
16404 (string-to-number (match-string 2 ans))
16405 (progn (setq kill-year t)
16406 (string-to-number (format-time-string "%Y"))))
16407 month (string-to-number (match-string 3 ans))
16408 day (string-to-number (match-string 4 ans)))
16409 (if (< year 100) (setq year (+ 2000 year)))
16410 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16411 t nil ans)))
16413 ;; Help matching dotted european dates
16414 (when (string-match
16415 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16416 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16417 (setq kill-year t)
16418 (string-to-number (format-time-string "%Y")))
16419 day (string-to-number (match-string 1 ans))
16420 month (string-to-number (match-string 2 ans))
16421 ans (replace-match (format "%04d-%02d-%02d" year month day)
16422 t nil ans)))
16424 ;; Help matching american dates, like 5/30 or 5/30/7
16425 (when (string-match
16426 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16427 (setq year (if (match-end 4)
16428 (string-to-number (match-string 4 ans))
16429 (progn (setq kill-year t)
16430 (string-to-number (format-time-string "%Y"))))
16431 month (string-to-number (match-string 1 ans))
16432 day (string-to-number (match-string 2 ans)))
16433 (if (< year 100) (setq year (+ 2000 year)))
16434 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16435 t nil ans)))
16436 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16437 ;; If there is a time with am/pm, and *no* time without it, we convert
16438 ;; so that matching will be successful.
16439 (loop for i from 1 to 2 do ; twice, for end time as well
16440 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16441 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16442 (setq hour (string-to-number (match-string 1 ans))
16443 minute (if (match-end 3)
16444 (string-to-number (match-string 3 ans))
16446 pm (equal ?p
16447 (string-to-char (downcase (match-string 4 ans)))))
16448 (if (and (= hour 12) (not pm))
16449 (setq hour 0)
16450 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16451 (setq ans (replace-match (format "%02d:%02d" hour minute)
16452 t t ans))))
16454 ;; Check if a time range is given as a duration
16455 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16456 (setq hour (string-to-number (match-string 1 ans))
16457 h2 (+ hour (string-to-number (match-string 3 ans)))
16458 minute (string-to-number (match-string 2 ans))
16459 m2 (+ minute (if (match-end 5) (string-to-number
16460 (match-string 5 ans))0)))
16461 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16462 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16463 t t ans)))
16465 ;; Check if there is a time range
16466 (when (boundp 'org-end-time-was-given)
16467 (setq org-time-was-given nil)
16468 (when (and (string-match org-plain-time-of-day-regexp ans)
16469 (match-end 8))
16470 (setq org-end-time-was-given (match-string 8 ans))
16471 (setq ans (concat (substring ans 0 (match-beginning 7))
16472 (substring ans (match-end 7))))))
16474 (setq tl (parse-time-string ans)
16475 day (or (nth 3 tl) (nth 3 org-defdecode))
16476 month (or (nth 4 tl)
16477 (if (and org-read-date-prefer-future
16478 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16479 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16480 (nth 4 org-defdecode)))
16481 year (or (and (not kill-year) (nth 5 tl))
16482 (if (and org-read-date-prefer-future
16483 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16484 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16485 (nth 5 org-defdecode)))
16486 hour (or (nth 2 tl) (nth 2 org-defdecode))
16487 minute (or (nth 1 tl) (nth 1 org-defdecode))
16488 second (or (nth 0 tl) 0)
16489 wday (nth 6 tl))
16491 (when (and (eq org-read-date-prefer-future 'time)
16492 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16493 (equal day (nth 3 nowdecode))
16494 (equal month (nth 4 nowdecode))
16495 (equal year (nth 5 nowdecode))
16496 (nth 2 tl)
16497 (or (< (nth 2 tl) (nth 2 nowdecode))
16498 (and (= (nth 2 tl) (nth 2 nowdecode))
16499 (nth 1 tl)
16500 (< (nth 1 tl) (nth 1 nowdecode)))))
16501 (setq day (1+ day)
16502 futurep t))
16504 ;; Special date definitions below
16505 (cond
16506 (iso-week
16507 ;; There was an iso week
16508 (require 'cal-iso)
16509 (setq futurep nil)
16510 (setq year (or iso-year year)
16511 day (or iso-weekday wday 1)
16512 wday nil ; to make sure that the trigger below does not match
16513 iso-date (calendar-gregorian-from-absolute
16514 (calendar-absolute-from-iso
16515 (list iso-week day year))))
16516 ; FIXME: Should we also push ISO weeks into the future?
16517 ; (when (and org-read-date-prefer-future
16518 ; (not iso-year)
16519 ; (< (calendar-absolute-from-gregorian iso-date)
16520 ; (time-to-days (current-time))))
16521 ; (setq year (1+ year)
16522 ; iso-date (calendar-gregorian-from-absolute
16523 ; (calendar-absolute-from-iso
16524 ; (list iso-week day year)))))
16525 (setq month (car iso-date)
16526 year (nth 2 iso-date)
16527 day (nth 1 iso-date)))
16528 (deltan
16529 (setq futurep nil)
16530 (unless deltadef
16531 (let ((now (decode-time (current-time))))
16532 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16533 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16534 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16535 ((equal deltaw "m") (setq month (+ month deltan)))
16536 ((equal deltaw "y") (setq year (+ year deltan)))))
16537 ((and wday (not (nth 3 tl)))
16538 ;; Weekday was given, but no day, so pick that day in the week
16539 ;; on or after the derived date.
16540 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16541 (unless (equal wday wday1)
16542 (setq day (+ day (% (- wday wday1 -7) 7))))))
16543 (if (and (boundp 'org-time-was-given)
16544 (nth 2 tl))
16545 (setq org-time-was-given t))
16546 (if (< year 100) (setq year (+ 2000 year)))
16547 ;; Check of the date is representable
16548 (if org-read-date-force-compatible-dates
16549 (progn
16550 (if (< year 1970)
16551 (setq year 1970 org-read-date-analyze-forced-year t))
16552 (if (> year 2037)
16553 (setq year 2037 org-read-date-analyze-forced-year t)))
16554 (condition-case nil
16555 (ignore (encode-time second minute hour day month year))
16556 (error
16557 (setq year (nth 5 org-defdecode))
16558 (setq org-read-date-analyze-forced-year t))))
16559 (setq org-read-date-analyze-futurep futurep)
16560 (list second minute hour day month year)))
16562 (defvar parse-time-weekdays)
16563 (defun org-read-date-get-relative (s today default)
16564 "Check string S for special relative date string.
16565 TODAY and DEFAULT are internal times, for today and for a default.
16566 Return shift list (N what def-flag)
16567 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16568 N is the number of WHATs to shift.
16569 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16570 the DEFAULT date rather than TODAY."
16571 (require 'parse-time)
16572 (when (and
16573 (string-match
16574 (concat
16575 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16576 "\\([0-9]+\\)?"
16577 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16578 "\\([ \t]\\|$\\)") s)
16579 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16580 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16581 (string-to-char (substring (match-string 1 s) -1))
16582 ?+))
16583 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16584 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16585 (what (if (match-end 3) (match-string 3 s) "d"))
16586 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16587 (date (if rel default today))
16588 (wday (nth 6 (decode-time date)))
16589 delta)
16590 (if wday1
16591 (progn
16592 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16593 (if (= delta 0) (setq delta 7))
16594 (if (= dir ?-)
16595 (progn
16596 (setq delta (- delta 7))
16597 (if (= delta 0) (setq delta -7))))
16598 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16599 (list delta "d" rel))
16600 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16602 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16603 "Turn a user-specified date into the internal representation.
16604 The internal representation needed by the calendar is (month day year).
16605 This is a wrapper to handle the brain-dead convention in calendar that
16606 user function argument order change dependent on argument order."
16607 (if (boundp 'calendar-date-style)
16608 (cond
16609 ((eq calendar-date-style 'american)
16610 (list arg1 arg2 arg3))
16611 ((eq calendar-date-style 'european)
16612 (list arg2 arg1 arg3))
16613 ((eq calendar-date-style 'iso)
16614 (list arg2 arg3 arg1)))
16615 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16616 (if (org-bound-and-true-p european-calendar-style)
16617 (list arg2 arg1 arg3)
16618 (list arg1 arg2 arg3)))))
16620 (defun org-eval-in-calendar (form &optional keepdate)
16621 "Eval FORM in the calendar window and return to current window.
16622 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16623 otherwise stick to the current value of `org-ans2'."
16624 (let ((sf (selected-frame))
16625 (sw (selected-window)))
16626 (select-window (get-buffer-window "*Calendar*" t))
16627 (eval form)
16628 (when (and (not keepdate) (calendar-cursor-to-date))
16629 (let* ((date (calendar-cursor-to-date))
16630 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16631 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16632 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16633 (select-window sw)
16634 (org-select-frame-set-input-focus sf)))
16636 (defun org-calendar-select ()
16637 "Return to `org-read-date' with the date currently selected.
16638 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16639 (interactive)
16640 (when (calendar-cursor-to-date)
16641 (let* ((date (calendar-cursor-to-date))
16642 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16643 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16644 (if (active-minibuffer-window) (exit-minibuffer))))
16646 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16647 "Insert a date stamp for the date given by the internal TIME.
16648 WITH-HM means use the stamp format that includes the time of the day.
16649 INACTIVE means use square brackets instead of angular ones, so that the
16650 stamp will not contribute to the agenda.
16651 PRE and POST are optional strings to be inserted before and after the
16652 stamp.
16653 The command returns the inserted time stamp."
16654 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16655 stamp)
16656 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16657 (insert-before-markers (or pre ""))
16658 (when (listp extra)
16659 (setq extra (car extra))
16660 (if (and (stringp extra)
16661 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16662 (setq extra (format "-%02d:%02d"
16663 (string-to-number (match-string 1 extra))
16664 (string-to-number (match-string 2 extra))))
16665 (setq extra nil)))
16666 (when extra
16667 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16668 (insert-before-markers (setq stamp (format-time-string fmt time)))
16669 (insert-before-markers (or post ""))
16670 (setq org-last-inserted-timestamp stamp)))
16672 (defun org-toggle-time-stamp-overlays ()
16673 "Toggle the use of custom time stamp formats."
16674 (interactive)
16675 (setq org-display-custom-times (not org-display-custom-times))
16676 (unless org-display-custom-times
16677 (let ((p (point-min)) (bmp (buffer-modified-p)))
16678 (while (setq p (next-single-property-change p 'display))
16679 (if (and (get-text-property p 'display)
16680 (eq (get-text-property p 'face) 'org-date))
16681 (remove-text-properties
16682 p (setq p (next-single-property-change p 'display))
16683 '(display t))))
16684 (set-buffer-modified-p bmp)))
16685 (if (featurep 'xemacs)
16686 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16687 (org-restart-font-lock)
16688 (setq org-table-may-need-update t)
16689 (if org-display-custom-times
16690 (message "Time stamps are overlaid with custom format")
16691 (message "Time stamp overlays removed")))
16693 (defun org-display-custom-time (beg end)
16694 "Overlay modified time stamp format over timestamp between BEG and END."
16695 (let* ((ts (buffer-substring beg end))
16696 t1 w1 with-hm tf time str w2 (off 0))
16697 (save-match-data
16698 (setq t1 (org-parse-time-string ts t))
16699 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16700 (setq off (- (match-end 0) (match-beginning 0)))))
16701 (setq end (- end off))
16702 (setq w1 (- end beg)
16703 with-hm (and (nth 1 t1) (nth 2 t1))
16704 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16705 time (org-fix-decoded-time t1)
16706 str (org-add-props
16707 (format-time-string
16708 (substring tf 1 -1) (apply 'encode-time time))
16709 nil 'mouse-face 'highlight)
16710 w2 (length str))
16711 (if (not (= w2 w1))
16712 (add-text-properties (1+ beg) (+ 2 beg)
16713 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16714 (if (featurep 'xemacs)
16715 (progn
16716 (put-text-property beg end 'invisible t)
16717 (put-text-property beg end 'end-glyph (make-glyph str)))
16718 (put-text-property beg end 'display str))))
16720 (defun org-translate-time (string)
16721 "Translate all timestamps in STRING to custom format.
16722 But do this only if the variable `org-display-custom-times' is set."
16723 (when org-display-custom-times
16724 (save-match-data
16725 (let* ((start 0)
16726 (re org-ts-regexp-both)
16727 t1 with-hm inactive tf time str beg end)
16728 (while (setq start (string-match re string start))
16729 (setq beg (match-beginning 0)
16730 end (match-end 0)
16731 t1 (save-match-data
16732 (org-parse-time-string (substring string beg end) t))
16733 with-hm (and (nth 1 t1) (nth 2 t1))
16734 inactive (equal (substring string beg (1+ beg)) "[")
16735 tf (funcall (if with-hm 'cdr 'car)
16736 org-time-stamp-custom-formats)
16737 time (org-fix-decoded-time t1)
16738 str (format-time-string
16739 (concat
16740 (if inactive "[" "<") (substring tf 1 -1)
16741 (if inactive "]" ">"))
16742 (apply 'encode-time time))
16743 string (replace-match str t t string)
16744 start (+ start (length str)))))))
16745 string)
16747 (defun org-fix-decoded-time (time)
16748 "Set 0 instead of nil for the first 6 elements of time.
16749 Don't touch the rest."
16750 (let ((n 0))
16751 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16753 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16755 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16756 "Difference between TIMESTAMP-STRING and now in days.
16757 If SECONDS is non-nil, return the difference in seconds."
16758 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16759 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16760 (funcall fdiff (current-time)))))
16762 (defun org-deadline-close (timestamp-string &optional ndays)
16763 "Is the time in TIMESTAMP-STRING close to the current date?"
16764 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16765 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16766 (not (org-entry-is-done-p))))
16768 (defun org-get-wdays (ts &optional delay zero-delay)
16769 "Get the deadline lead time appropriate for timestring TS.
16770 When DELAY is non-nil, get the delay time for scheduled items
16771 instead of the deadline lead time. When ZERO-DELAY is non-nil
16772 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16773 don't try to find the delay cookie in the scheduled timestamp."
16774 (let ((tv (if delay org-scheduled-delay-days
16775 org-deadline-warning-days)))
16776 (cond
16777 ((or (and delay (< tv 0))
16778 (and delay zero-delay (<= tv 0))
16779 (and (not delay) (<= tv 0)))
16780 ;; Enforce this value no matter what
16781 (- tv))
16782 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16783 ;; lead time is specified.
16784 (floor (* (string-to-number (match-string 1 ts))
16785 (cdr (assoc (match-string 2 ts)
16786 '(("d" . 1) ("w" . 7)
16787 ("m" . 30.4) ("y" . 365.25)
16788 ("h" . 0.041667)))))))
16789 ;; go for the default.
16790 (t tv))))
16792 (defun org-calendar-select-mouse (ev)
16793 "Return to `org-read-date' with the date currently selected.
16794 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16795 (interactive "e")
16796 (mouse-set-point ev)
16797 (when (calendar-cursor-to-date)
16798 (let* ((date (calendar-cursor-to-date))
16799 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16800 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16801 (if (active-minibuffer-window) (exit-minibuffer))))
16803 (defun org-check-deadlines (ndays)
16804 "Check if there are any deadlines due or past due.
16805 A deadline is considered due if it happens within `org-deadline-warning-days'
16806 days from today's date. If the deadline appears in an entry marked DONE,
16807 it is not shown. The prefix arg NDAYS can be used to test that many
16808 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16809 (interactive "P")
16810 (let* ((org-warn-days
16811 (cond
16812 ((equal ndays '(4)) 100000)
16813 (ndays (prefix-numeric-value ndays))
16814 (t (abs org-deadline-warning-days))))
16815 (case-fold-search nil)
16816 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16817 (callback
16818 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16820 (message "%d deadlines past-due or due within %d days"
16821 (org-occur regexp nil callback)
16822 org-warn-days)))
16824 (defsubst org-re-timestamp (type)
16825 "Return a regexp for timestamp TYPE.
16826 Allowed values for TYPE are:
16828 all: all timestamps
16829 active: only active timestamps (<...>)
16830 inactive: only inactive timestamps ([...])
16831 scheduled: only scheduled timestamps
16832 deadline: only deadline timestamps
16833 closed: only closed time-stamps
16835 When TYPE is nil, fall back on returning a regexp that matches
16836 both scheduled and deadline timestamps."
16837 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16838 ((eq type 'active) org-ts-regexp)
16839 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16840 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16841 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16842 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16843 ((eq type 'scheduled-or-deadline)
16844 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16846 (defun org-check-before-date (date)
16847 "Check if there are deadlines or scheduled entries before DATE."
16848 (interactive (list (org-read-date)))
16849 (let ((case-fold-search nil)
16850 (regexp (org-re-timestamp org-ts-type))
16851 (callback
16852 (lambda () (time-less-p
16853 (org-time-string-to-time (match-string 1))
16854 (org-time-string-to-time date)))))
16855 (message "%d entries before %s"
16856 (org-occur regexp nil callback) date)))
16858 (defun org-check-after-date (date)
16859 "Check if there are deadlines or scheduled entries after DATE."
16860 (interactive (list (org-read-date)))
16861 (let ((case-fold-search nil)
16862 (regexp (org-re-timestamp org-ts-type))
16863 (callback
16864 (lambda () (not
16865 (time-less-p
16866 (org-time-string-to-time (match-string 1))
16867 (org-time-string-to-time date))))))
16868 (message "%d entries after %s"
16869 (org-occur regexp nil callback) date)))
16871 (defun org-check-dates-range (start-date end-date)
16872 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16873 (interactive (list (org-read-date nil nil nil "Range starts")
16874 (org-read-date nil nil nil "Range end")))
16875 (let ((case-fold-search nil)
16876 (regexp (org-re-timestamp org-ts-type))
16877 (callback
16878 (lambda ()
16879 (let ((match (match-string 1)))
16880 (and
16881 (not (time-less-p
16882 (org-time-string-to-time match)
16883 (org-time-string-to-time start-date)))
16884 (time-less-p
16885 (org-time-string-to-time match)
16886 (org-time-string-to-time end-date)))))))
16887 (message "%d entries between %s and %s"
16888 (org-occur regexp nil callback) start-date end-date)))
16890 (defun org-evaluate-time-range (&optional to-buffer)
16891 "Evaluate a time range by computing the difference between start and end.
16892 Normally the result is just printed in the echo area, but with prefix arg
16893 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16894 If the time range is actually in a table, the result is inserted into the
16895 next column.
16896 For time difference computation, a year is assumed to be exactly 365
16897 days in order to avoid rounding problems."
16898 (interactive "P")
16900 (org-clock-update-time-maybe)
16901 (save-excursion
16902 (unless (org-at-date-range-p t)
16903 (goto-char (point-at-bol))
16904 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16905 (if (not (org-at-date-range-p t))
16906 (user-error "Not at a time-stamp range, and none found in current line")))
16907 (let* ((ts1 (match-string 1))
16908 (ts2 (match-string 2))
16909 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16910 (match-end (match-end 0))
16911 (time1 (org-time-string-to-time ts1))
16912 (time2 (org-time-string-to-time ts2))
16913 (t1 (org-float-time time1))
16914 (t2 (org-float-time time2))
16915 (diff (abs (- t2 t1)))
16916 (negative (< (- t2 t1) 0))
16917 ;; (ys (floor (* 365 24 60 60)))
16918 (ds (* 24 60 60))
16919 (hs (* 60 60))
16920 (fy "%dy %dd %02d:%02d")
16921 (fy1 "%dy %dd")
16922 (fd "%dd %02d:%02d")
16923 (fd1 "%dd")
16924 (fh "%02d:%02d")
16925 y d h m align)
16926 (if havetime
16927 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16929 d (floor (/ diff ds)) diff (mod diff ds)
16930 h (floor (/ diff hs)) diff (mod diff hs)
16931 m (floor (/ diff 60)))
16932 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16934 d (floor (+ (/ diff ds) 0.5))
16935 h 0 m 0))
16936 (if (not to-buffer)
16937 (message "%s" (org-make-tdiff-string y d h m))
16938 (if (org-at-table-p)
16939 (progn
16940 (goto-char match-end)
16941 (setq align t)
16942 (and (looking-at " *|") (goto-char (match-end 0))))
16943 (goto-char match-end))
16944 (if (looking-at
16945 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16946 (replace-match ""))
16947 (if negative (insert " -"))
16948 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16949 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16950 (insert " " (format fh h m))))
16951 (if align (org-table-align))
16952 (message "Time difference inserted")))))
16954 (defun org-make-tdiff-string (y d h m)
16955 (let ((fmt "")
16956 (l nil))
16957 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16958 l (push y l)))
16959 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16960 l (push d l)))
16961 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16962 l (push h l)))
16963 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16964 l (push m l)))
16965 (apply 'format fmt (nreverse l))))
16967 (defun org-time-string-to-time (s &optional buffer pos)
16968 "Convert a timestamp string into internal time."
16969 (condition-case errdata
16970 (apply 'encode-time (org-parse-time-string s))
16971 (error (error "Bad timestamp `%s'%s\nError was: %s"
16972 s (if (not (and buffer pos))
16974 (format " at %d in buffer `%s'" pos buffer))
16975 (cdr errdata)))))
16977 (defun org-time-string-to-seconds (s)
16978 "Convert a timestamp string to a number of seconds."
16979 (org-float-time (org-time-string-to-time s)))
16981 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16982 "Convert a time stamp to an absolute day number.
16983 If there is a specifier for a cyclic time stamp, get the closest
16984 date to DAYNR.
16985 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16986 The variable `date' is bound by the calendar when this is called."
16987 (cond
16988 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16989 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16990 daynr
16991 (+ daynr 1000)))
16992 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16993 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16994 (time-to-days (current-time))) (match-string 0 s)
16995 prefer show-all))
16996 (t (time-to-days
16997 (condition-case errdata
16998 (apply 'encode-time (org-parse-time-string s))
16999 (error (error "Bad timestamp `%s'%s\nError was: %s"
17000 s (if (not (and buffer pos))
17002 (format " at %d in buffer `%s'" pos buffer))
17003 (cdr errdata))))))))
17005 (defun org-days-to-iso-week (days)
17006 "Return the iso week number."
17007 (require 'cal-iso)
17008 (car (calendar-iso-from-absolute days)))
17010 (defun org-small-year-to-year (year)
17011 "Convert 2-digit years into 4-digit years.
17012 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17013 The year 2000 cannot be abbreviated. Any year larger than 99
17014 is returned unchanged."
17015 (if (< year 38)
17016 (setq year (+ 2000 year))
17017 (if (< year 100)
17018 (setq year (+ 1900 year))))
17019 year)
17021 (defun org-time-from-absolute (d)
17022 "Return the time corresponding to date D.
17023 D may be an absolute day number, or a calendar-type list (month day year)."
17024 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17025 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17027 (defun org-calendar-holiday ()
17028 "List of holidays, for Diary display in Org-mode."
17029 (require 'holidays)
17030 (let ((hl (funcall
17031 (if (fboundp 'calendar-check-holidays)
17032 'calendar-check-holidays 'check-calendar-holidays) date)))
17033 (if hl (mapconcat 'identity hl "; "))))
17035 (defun org-diary-sexp-entry (sexp entry date)
17036 "Process a SEXP diary ENTRY for DATE."
17037 (require 'diary-lib)
17038 (let ((result (if calendar-debug-sexp
17039 (let ((stack-trace-on-error t))
17040 (eval (car (read-from-string sexp))))
17041 (condition-case nil
17042 (eval (car (read-from-string sexp)))
17043 (error
17044 (beep)
17045 (message "Bad sexp at line %d in %s: %s"
17046 (org-current-line)
17047 (buffer-file-name) sexp)
17048 (sleep-for 2))))))
17049 (cond ((stringp result) (split-string result "; "))
17050 ((and (consp result)
17051 (not (consp (cdr result)))
17052 (stringp (cdr result))) (cdr result))
17053 ((and (consp result)
17054 (stringp (car result))) result)
17055 (result entry))))
17057 (defun org-diary-to-ical-string (frombuf)
17058 "Get iCalendar entries from diary entries in buffer FROMBUF.
17059 This uses the icalendar.el library."
17060 (let* ((tmpdir (if (featurep 'xemacs)
17061 (temp-directory)
17062 temporary-file-directory))
17063 (tmpfile (make-temp-name
17064 (expand-file-name "orgics" tmpdir)))
17065 buf rtn b e)
17066 (with-current-buffer frombuf
17067 (icalendar-export-region (point-min) (point-max) tmpfile)
17068 (setq buf (find-buffer-visiting tmpfile))
17069 (set-buffer buf)
17070 (goto-char (point-min))
17071 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17072 (setq b (match-beginning 0)))
17073 (goto-char (point-max))
17074 (if (re-search-backward "^END:VEVENT" nil t)
17075 (setq e (match-end 0)))
17076 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17077 (kill-buffer buf)
17078 (delete-file tmpfile)
17079 rtn))
17081 (defun org-closest-date (start current change prefer show-all)
17082 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17083 When PREFER is `past', return a date that is either CURRENT or past.
17084 When PREFER is `future', return a date that is either CURRENT or future.
17085 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17086 ;; Make the proper lists from the dates
17087 (catch 'exit
17088 (let ((a1 '(("h" . hour)
17089 ("d" . day)
17090 ("w" . week)
17091 ("m" . month)
17092 ("y" . year)))
17093 (shour (nth 2 (org-parse-time-string start)))
17094 dn dw sday cday n1 n2 n0
17095 d m y y1 y2 date1 date2 nmonths nm ny m2)
17097 (setq start (org-date-to-gregorian start)
17098 current (org-date-to-gregorian
17099 (if show-all
17100 current
17101 (time-to-days (current-time))))
17102 sday (calendar-absolute-from-gregorian start)
17103 cday (calendar-absolute-from-gregorian current))
17105 (if (<= cday sday) (throw 'exit sday))
17107 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17108 (setq dn (string-to-number (match-string 1 change))
17109 dw (cdr (assoc (match-string 2 change) a1)))
17110 (user-error "Invalid change specifier: %s" change))
17111 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17112 (cond
17113 ((eq dw 'hour)
17114 (let ((missing-hours
17115 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17116 dn)))
17117 (setq n1 (if (zerop missing-hours) cday
17118 (- cday (1+ (floor (/ missing-hours 24)))))
17119 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17120 ((eq dw 'day)
17121 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17122 n2 (+ n1 dn)))
17123 ((eq dw 'year)
17124 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17125 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17126 (setq date1 (list m d y1)
17127 n1 (calendar-absolute-from-gregorian date1)
17128 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17129 n2 (calendar-absolute-from-gregorian date2)))
17130 ((eq dw 'month)
17131 ;; approx number of month between the two dates
17132 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17133 ;; How often does dn fit in there?
17134 (setq d (nth 1 start) m (car start) y (nth 2 start)
17135 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17136 m (+ m nm)
17137 ny (floor (/ m 12))
17138 y (+ y ny)
17139 m (- m (* ny 12)))
17140 (while (> m 12) (setq m (- m 12) y (1+ y)))
17141 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17142 (setq m2 (+ m dn) y2 y)
17143 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17144 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17145 (while (<= n2 cday)
17146 (setq n1 n2 m m2 y y2)
17147 (setq m2 (+ m dn) y2 y)
17148 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17149 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17150 ;; Make sure n1 is the earlier date
17151 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17152 (if show-all
17153 (cond
17154 ((eq prefer 'past) (if (= cday n2) n2 n1))
17155 ((eq prefer 'future) (if (= cday n1) n1 n2))
17156 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17157 (cond
17158 ((eq prefer 'past) (if (= cday n2) n2 n1))
17159 ((eq prefer 'future) (if (= cday n1) n1 n2))
17160 (t (if (= cday n1) n1 n2)))))))
17162 (defun org-date-to-gregorian (date)
17163 "Turn any specification of DATE into a Gregorian date for the calendar."
17164 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17165 ((and (listp date) (= (length date) 3)) date)
17166 ((stringp date)
17167 (setq date (org-parse-time-string date))
17168 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17169 ((listp date)
17170 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17172 (defun org-parse-time-string (s &optional nodefault)
17173 "Parse the standard Org-mode time string.
17174 This should be a lot faster than the normal `parse-time-string'.
17175 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17176 hour and minute fields will be nil if not given."
17177 (cond ((string-match org-ts-regexp0 s)
17178 (list 0
17179 (if (or (match-beginning 8) (not nodefault))
17180 (string-to-number (or (match-string 8 s) "0")))
17181 (if (or (match-beginning 7) (not nodefault))
17182 (string-to-number (or (match-string 7 s) "0")))
17183 (string-to-number (match-string 4 s))
17184 (string-to-number (match-string 3 s))
17185 (string-to-number (match-string 2 s))
17186 nil nil nil))
17187 ((string-match "^<[^>]+>$" s)
17188 (decode-time (seconds-to-time (org-matcher-time s))))
17189 (t (error "Not a standard Org-mode time string: %s" s))))
17191 (defun org-timestamp-up (&optional arg)
17192 "Increase the date item at the cursor by one.
17193 If the cursor is on the year, change the year. If it is on the month,
17194 the day or the time, change that.
17195 With prefix ARG, change by that many units."
17196 (interactive "p")
17197 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17199 (defun org-timestamp-down (&optional arg)
17200 "Decrease the date item at the cursor by one.
17201 If the cursor is on the year, change the year. If it is on the month,
17202 the day or the time, change that.
17203 With prefix ARG, change by that many units."
17204 (interactive "p")
17205 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17207 (defun org-timestamp-up-day (&optional arg)
17208 "Increase the date in the time stamp by one day.
17209 With prefix ARG, change that many days."
17210 (interactive "p")
17211 (if (and (not (org-at-timestamp-p t))
17212 (org-at-heading-p))
17213 (org-todo 'up)
17214 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17216 (defun org-timestamp-down-day (&optional arg)
17217 "Decrease the date in the time stamp by one day.
17218 With prefix ARG, change that many days."
17219 (interactive "p")
17220 (if (and (not (org-at-timestamp-p t))
17221 (org-at-heading-p))
17222 (org-todo 'down)
17223 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17225 (defun org-at-timestamp-p (&optional inactive-ok)
17226 "Determine if the cursor is in or at a timestamp."
17227 (interactive)
17228 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17229 (pos (point))
17230 (ans (or (looking-at tsr)
17231 (save-excursion
17232 (skip-chars-backward "^[<\n\r\t")
17233 (if (> (point) (point-min)) (backward-char 1))
17234 (and (looking-at tsr)
17235 (> (- (match-end 0) pos) -1))))))
17236 (and ans
17237 (boundp 'org-ts-what)
17238 (setq org-ts-what
17239 (cond
17240 ((= pos (match-beginning 0)) 'bracket)
17241 ;; Point is considered to be "on the bracket" whether
17242 ;; it's really on it or right after it.
17243 ((= pos (1- (match-end 0))) 'bracket)
17244 ((= pos (match-end 0)) 'after)
17245 ((org-pos-in-match-range pos 2) 'year)
17246 ((org-pos-in-match-range pos 3) 'month)
17247 ((org-pos-in-match-range pos 7) 'hour)
17248 ((org-pos-in-match-range pos 8) 'minute)
17249 ((or (org-pos-in-match-range pos 4)
17250 (org-pos-in-match-range pos 5)) 'day)
17251 ((and (> pos (or (match-end 8) (match-end 5)))
17252 (< pos (match-end 0)))
17253 (- pos (or (match-end 8) (match-end 5))))
17254 (t 'day))))
17255 ans))
17257 (defun org-toggle-timestamp-type ()
17258 "Toggle the type (<active> or [inactive]) of a time stamp."
17259 (interactive)
17260 (when (org-at-timestamp-p t)
17261 (let ((beg (match-beginning 0)) (end (match-end 0))
17262 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17263 (save-excursion
17264 (goto-char beg)
17265 (while (re-search-forward "[][<>]" end t)
17266 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17267 t t)))
17268 (message "Timestamp is now %sactive"
17269 (if (equal (char-after beg) ?<) "" "in")))))
17271 (defun org-at-clock-log-p nil
17272 "Is the cursor on the clock log line?"
17273 (save-excursion
17274 (move-beginning-of-line 1)
17275 (looking-at "^[ \t]*CLOCK:")))
17277 (defvar org-clock-history) ; defined in org-clock.el
17278 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17279 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17280 "Change the date in the time stamp at point.
17281 The date will be changed by N times WHAT. WHAT can be `day', `month',
17282 `year', `minute', `second'. If WHAT is not given, the cursor position
17283 in the timestamp determines what will be changed.
17284 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17285 (let ((origin (point)) origin-cat
17286 with-hm inactive
17287 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17288 org-ts-what
17289 extra rem
17290 ts time time0 fixnext clrgx)
17291 (if (not (org-at-timestamp-p t))
17292 (user-error "Not at a timestamp"))
17293 (if (and (not what) (eq org-ts-what 'bracket))
17294 (org-toggle-timestamp-type)
17295 ;; Point isn't on brackets. Remember the part of the time-stamp
17296 ;; the point was in. Indeed, size of time-stamps may change,
17297 ;; but point must be kept in the same category nonetheless.
17298 (setq origin-cat org-ts-what)
17299 (if (and (not what) (not (eq org-ts-what 'day))
17300 org-display-custom-times
17301 (get-text-property (point) 'display)
17302 (not (get-text-property (1- (point)) 'display)))
17303 (setq org-ts-what 'day))
17304 (setq org-ts-what (or what org-ts-what)
17305 inactive (= (char-after (match-beginning 0)) ?\[)
17306 ts (match-string 0))
17307 (replace-match "")
17308 (when (string-match
17309 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17311 (setq extra (match-string 1 ts))
17312 (if suppress-tmp-delay
17313 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17314 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17315 (setq with-hm t))
17316 (setq time0 (org-parse-time-string ts))
17317 (when (and updown
17318 (eq org-ts-what 'minute)
17319 (not current-prefix-arg))
17320 ;; This looks like s-up and s-down. Change by one rounding step.
17321 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17322 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17323 (setcar (cdr time0) (+ (nth 1 time0)
17324 (if (> n 0) (- rem) (- dm rem))))))
17325 (setq time
17326 (encode-time (or (car time0) 0)
17327 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17328 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17329 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17330 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17331 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17332 (nthcdr 6 time0)))
17333 (when (and (member org-ts-what '(hour minute))
17334 extra
17335 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17336 (setq extra (org-modify-ts-extra
17337 extra
17338 (if (eq org-ts-what 'hour) 2 5)
17339 n dm)))
17340 (when (integerp org-ts-what)
17341 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17342 (if (eq what 'calendar)
17343 (let ((cal-date (org-get-date-from-calendar)))
17344 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17345 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17346 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17347 (setcar time0 (or (car time0) 0))
17348 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17349 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17350 (setq time (apply 'encode-time time0))))
17351 ;; Insert the new time-stamp, and ensure point stays in the same
17352 ;; category as before (i.e. not after the last position in that
17353 ;; category).
17354 (let ((pos (point)))
17355 ;; Stay before inserted string. `save-excursion' is of no use.
17356 (setq org-last-changed-timestamp
17357 (org-insert-time-stamp time with-hm inactive nil nil extra))
17358 (goto-char pos))
17359 (save-match-data
17360 (looking-at org-ts-regexp3)
17361 (goto-char (cond
17362 ;; `day' category ends before `hour' if any, or at
17363 ;; the end of the day name.
17364 ((eq origin-cat 'day)
17365 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17366 ((eq origin-cat 'hour) (min (match-end 7) origin))
17367 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17368 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17369 ;; `year' and `month' have both fixed size: point
17370 ;; couldn't have moved into another part.
17371 (t origin))))
17372 ;; Update clock if on a CLOCK line.
17373 (org-clock-update-time-maybe)
17374 ;; Maybe adjust the closest clock in `org-clock-history'
17375 (when org-clock-adjust-closest
17376 (if (not (and (org-at-clock-log-p)
17377 (< 1 (length (delq nil (mapcar 'marker-position
17378 org-clock-history))))))
17379 (message "No clock to adjust")
17380 (cond ((save-excursion ; fix previous clock?
17381 (re-search-backward org-ts-regexp0 nil t)
17382 (org-looking-back (concat org-clock-string " \\[")))
17383 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17384 ((save-excursion ; fix next clock?
17385 (re-search-backward org-ts-regexp0 nil t)
17386 (looking-at (concat org-ts-regexp0 "\\] =>")))
17387 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17388 (save-window-excursion
17389 ;; Find closest clock to point, adjust the previous/next one in history
17390 (let* ((p (save-excursion (org-back-to-heading t)))
17391 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17392 (clfixnth
17393 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17394 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17395 (if (not clfixpos)
17396 (message "No clock to adjust")
17397 (save-excursion
17398 (org-goto-marker-or-bmk clfixpos)
17399 (org-show-subtree)
17400 (when (re-search-forward clrgx nil t)
17401 (goto-char (match-beginning 1))
17402 (let (org-clock-adjust-closest)
17403 (org-timestamp-change n org-ts-what updown))
17404 (message "Clock adjusted in %s for heading: %s"
17405 (file-name-nondirectory (buffer-file-name))
17406 (org-get-heading t t)))))))))
17407 ;; Try to recenter the calendar window, if any.
17408 (if (and org-calendar-follow-timestamp-change
17409 (get-buffer-window "*Calendar*" t)
17410 (memq org-ts-what '(day month year)))
17411 (org-recenter-calendar (time-to-days time))))))
17413 (defun org-modify-ts-extra (s pos n dm)
17414 "Change the different parts of the lead-time and repeat fields in timestamp."
17415 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17416 ng h m new rem)
17417 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17418 (cond
17419 ((or (org-pos-in-match-range pos 2)
17420 (org-pos-in-match-range pos 3))
17421 (setq m (string-to-number (match-string 3 s))
17422 h (string-to-number (match-string 2 s)))
17423 (if (org-pos-in-match-range pos 2)
17424 (setq h (+ h n))
17425 (setq n (* dm (org-no-warnings (signum n))))
17426 (when (not (= 0 (setq rem (% m dm))))
17427 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17428 (setq m (+ m n)))
17429 (if (< m 0) (setq m (+ m 60) h (1- h)))
17430 (if (> m 59) (setq m (- m 60) h (1+ h)))
17431 (setq h (min 24 (max 0 h)))
17432 (setq ng 1 new (format "-%02d:%02d" h m)))
17433 ((org-pos-in-match-range pos 6)
17434 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17435 ((org-pos-in-match-range pos 5)
17436 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17438 ((org-pos-in-match-range pos 9)
17439 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17440 ((org-pos-in-match-range pos 8)
17441 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17443 (when ng
17444 (setq s (concat
17445 (substring s 0 (match-beginning ng))
17447 (substring s (match-end ng))))))
17450 (defun org-recenter-calendar (date)
17451 "If the calendar is visible, recenter it to DATE."
17452 (let ((cwin (get-buffer-window "*Calendar*" t)))
17453 (when cwin
17454 (let ((calendar-move-hook nil))
17455 (with-selected-window cwin
17456 (calendar-goto-date (if (listp date) date
17457 (calendar-gregorian-from-absolute date))))))))
17459 (defun org-goto-calendar (&optional arg)
17460 "Go to the Emacs calendar at the current date.
17461 If there is a time stamp in the current line, go to that date.
17462 A prefix ARG can be used to force the current date."
17463 (interactive "P")
17464 (let ((tsr org-ts-regexp) diff
17465 (calendar-move-hook nil)
17466 (calendar-view-holidays-initially-flag nil)
17467 (calendar-view-diary-initially-flag nil))
17468 (if (or (org-at-timestamp-p)
17469 (save-excursion
17470 (beginning-of-line 1)
17471 (looking-at (concat ".*" tsr))))
17472 (let ((d1 (time-to-days (current-time)))
17473 (d2 (time-to-days
17474 (org-time-string-to-time (match-string 1)))))
17475 (setq diff (- d2 d1))))
17476 (calendar)
17477 (calendar-goto-today)
17478 (if (and diff (not arg)) (calendar-forward-day diff))))
17480 (defun org-get-date-from-calendar ()
17481 "Return a list (month day year) of date at point in calendar."
17482 (with-current-buffer "*Calendar*"
17483 (save-match-data
17484 (calendar-cursor-to-date))))
17486 (defun org-date-from-calendar ()
17487 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17488 If there is already a time stamp at the cursor position, update it."
17489 (interactive)
17490 (if (org-at-timestamp-p t)
17491 (org-timestamp-change 0 'calendar)
17492 (let ((cal-date (org-get-date-from-calendar)))
17493 (org-insert-time-stamp
17494 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17496 (defcustom org-effort-durations
17497 `(("h" . 60)
17498 ("d" . ,(* 60 8))
17499 ("w" . ,(* 60 8 5))
17500 ("m" . ,(* 60 8 5 4))
17501 ("y" . ,(* 60 8 5 40)))
17502 "Conversion factor to minutes for an effort modifier.
17504 Each entry has the form (MODIFIER . MINUTES).
17506 In an effort string, a number followed by MODIFIER is multiplied
17507 by the specified number of MINUTES to obtain an effort in
17508 minutes.
17510 For example, if the value of this variable is ((\"hours\" . 60)), then an
17511 effort string \"2hours\" is equivalent to 120 minutes."
17512 :group 'org-agenda
17513 :version "24.1"
17514 :type '(alist :key-type (string :tag "Modifier")
17515 :value-type (number :tag "Minutes")))
17517 (defun org-minutes-to-clocksum-string (m)
17518 "Format number of minutes as a clocksum string.
17519 The format is determined by `org-time-clocksum-format',
17520 `org-time-clocksum-use-fractional' and
17521 `org-time-clocksum-fractional-format' and
17522 `org-time-clocksum-use-effort-durations'."
17523 (let ((clocksum "")
17524 (m (round m)) ; Don't allow fractions of minutes
17525 h d w mo y fmt n)
17526 (setq h (if org-time-clocksum-use-effort-durations
17527 (cdr (assoc "h" org-effort-durations)) 60)
17528 d (if org-time-clocksum-use-effort-durations
17529 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17530 w (if org-time-clocksum-use-effort-durations
17531 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17532 mo (if org-time-clocksum-use-effort-durations
17533 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17534 y (if org-time-clocksum-use-effort-durations
17535 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17536 ;; fractional format
17537 (if org-time-clocksum-use-fractional
17538 (cond
17539 ;; single format string
17540 ((stringp org-time-clocksum-fractional-format)
17541 (format org-time-clocksum-fractional-format (/ m (float h))))
17542 ;; choice of fractional formats for different time units
17543 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17544 (> (/ (truncate m) (* y d h)) 0))
17545 (format fmt (/ m (* y d (float h)))))
17546 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17547 (> (/ (truncate m) (* mo d h)) 0))
17548 (format fmt (/ m (* mo d (float h)))))
17549 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17550 (> (/ (truncate m) (* w d h)) 0))
17551 (format fmt (/ m (* w d (float h)))))
17552 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17553 (> (/ (truncate m) (* d h)) 0))
17554 (format fmt (/ m (* d (float h)))))
17555 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17556 (> (/ (truncate m) h) 0))
17557 (format fmt (/ m (float h))))
17558 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17559 (format fmt m))
17560 ;; fall back to smallest time unit with a format
17561 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17562 (format fmt (/ m (float h))))
17563 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17564 (format fmt (/ m (* d (float h)))))
17565 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17566 (format fmt (/ m (* w d (float h)))))
17567 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17568 (format fmt (/ m (* mo d (float h)))))
17569 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17570 (format fmt (/ m (* y d (float h))))))
17571 ;; standard (non-fractional) format, with single format string
17572 (if (stringp org-time-clocksum-format)
17573 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17574 ;; separate formats components
17575 (and (setq fmt (plist-get org-time-clocksum-format :years))
17576 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17577 (plist-get org-time-clocksum-format :require-years))
17578 (setq clocksum (concat clocksum (format fmt n))
17579 m (- m (* n y d h))))
17580 (and (setq fmt (plist-get org-time-clocksum-format :months))
17581 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17582 (plist-get org-time-clocksum-format :require-months))
17583 (setq clocksum (concat clocksum (format fmt n))
17584 m (- m (* n mo d h))))
17585 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17586 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17587 (plist-get org-time-clocksum-format :require-weeks))
17588 (setq clocksum (concat clocksum (format fmt n))
17589 m (- m (* n w d h))))
17590 (and (setq fmt (plist-get org-time-clocksum-format :days))
17591 (or (> (setq n (/ (truncate m) (* d h))) 0)
17592 (plist-get org-time-clocksum-format :require-days))
17593 (setq clocksum (concat clocksum (format fmt n))
17594 m (- m (* n d h))))
17595 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17596 (or (> (setq n (/ (truncate m) h)) 0)
17597 (plist-get org-time-clocksum-format :require-hours))
17598 (setq clocksum (concat clocksum (format fmt n))
17599 m (- m (* n h))))
17600 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17601 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17602 (setq clocksum (concat clocksum (format fmt m))))
17603 ;; return formatted time duration
17604 clocksum))))
17606 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17607 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17608 "Org mode version 8.0")
17610 (defun org-hours-to-clocksum-string (n)
17611 (org-minutes-to-clocksum-string (* n 60)))
17613 (defun org-hh:mm-string-to-minutes (s)
17614 "Convert a string H:MM to a number of minutes.
17615 If the string is just a number, interpret it as minutes.
17616 In fact, the first hh:mm or number in the string will be taken,
17617 there can be extra stuff in the string.
17618 If no number is found, the return value is 0."
17619 (cond
17620 ((integerp s) s)
17621 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17622 (+ (* (string-to-number (match-string 1 s)) 60)
17623 (string-to-number (match-string 2 s))))
17624 ((string-match "\\([0-9]+\\)" s)
17625 (string-to-number (match-string 1 s)))
17626 (t 0)))
17628 (defcustom org-image-actual-width t
17629 "Should we use the actual width of images when inlining them?
17631 When set to `t', always use the image width.
17633 When set to a number, use imagemagick (when available) to set
17634 the image's width to this value.
17636 When set to a number in a list, try to get the width from any
17637 #+ATTR.* keyword if it matches a width specification like
17639 #+ATTR_HTML: :width 300px
17641 and fall back on that number if none is found.
17643 When set to nil, try to get the width from an #+ATTR.* keyword
17644 and fall back on the original width if none is found.
17646 This requires Emacs >= 24.1, build with imagemagick support."
17647 :group 'org-appearance
17648 :version "24.4"
17649 :package-version '(Org . "8.0")
17650 :type '(choice
17651 (const :tag "Use the image width" t)
17652 (integer :tag "Use a number of pixels")
17653 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17654 (const :tag "Use #+ATTR* or don't resize" nil)))
17656 (defcustom org-agenda-inhibit-startup nil
17657 "Inhibit startup when preparing agenda buffers.
17658 When this variable is `t' (the default), the initialization of
17659 the Org agenda buffers is inhibited: e.g. the visibility state
17660 is not set, the tables are not re-aligned, etc."
17661 :type 'boolean
17662 :version "24.3"
17663 :group 'org-agenda)
17665 (defcustom org-agenda-ignore-drawer-properties nil
17666 "Avoid updating text properties when building the agenda.
17667 Properties are used to prepare buffers for effort estimates, appointments,
17668 and subtree-local categories.
17669 If you don't use these in the agenda, you can add them to this list and
17670 agenda building will be a bit faster.
17671 The value is a list, with zero or more of the symbols `effort', `appt',
17672 or `category'."
17673 :type '(set :greedy t
17674 (const effort)
17675 (const appt)
17676 (const category))
17677 :version "24.3"
17678 :group 'org-agenda)
17680 (defun org-duration-string-to-minutes (s &optional output-to-string)
17681 "Convert a duration string S to minutes.
17683 A bare number is interpreted as minutes, modifiers can be set by
17684 customizing `org-effort-durations' (which see).
17686 Entries containing a colon are interpreted as H:MM by
17687 `org-hh:mm-string-to-minutes'."
17688 (let ((result 0)
17689 (re (concat "\\([0-9.]+\\) *\\("
17690 (regexp-opt (mapcar 'car org-effort-durations))
17691 "\\)")))
17692 (while (string-match re s)
17693 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17694 (string-to-number (match-string 1 s))))
17695 (setq s (replace-match "" nil t s)))
17696 (setq result (floor result))
17697 (incf result (org-hh:mm-string-to-minutes s))
17698 (if output-to-string (number-to-string result) result)))
17700 ;;;; Files
17702 (defun org-save-all-org-buffers ()
17703 "Save all Org-mode buffers without user confirmation."
17704 (interactive)
17705 (message "Saving all Org-mode buffers...")
17706 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17707 (when (featurep 'org-id) (org-id-locations-save))
17708 (message "Saving all Org-mode buffers... done"))
17710 (defun org-revert-all-org-buffers ()
17711 "Revert all Org-mode buffers.
17712 Prompt for confirmation when there are unsaved changes.
17713 Be sure you know what you are doing before letting this function
17714 overwrite your changes.
17716 This function is useful in a setup where one tracks org files
17717 with a version control system, to revert on one machine after pulling
17718 changes from another. I believe the procedure must be like this:
17720 1. M-x org-save-all-org-buffers
17721 2. Pull changes from the other machine, resolve conflicts
17722 3. M-x org-revert-all-org-buffers"
17723 (interactive)
17724 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17725 (user-error "Abort"))
17726 (save-excursion
17727 (save-window-excursion
17728 (mapc
17729 (lambda (b)
17730 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17731 (with-current-buffer b buffer-file-name))
17732 (org-pop-to-buffer-same-window b)
17733 (revert-buffer t 'no-confirm)))
17734 (buffer-list))
17735 (when (and (featurep 'org-id) org-id-track-globally)
17736 (org-id-locations-load)))))
17738 ;;;; Agenda files
17740 ;;;###autoload
17741 (defun org-switchb (&optional arg)
17742 "Switch between Org buffers.
17743 With one prefix argument, restrict available buffers to files.
17744 With two prefix arguments, restrict available buffers to agenda files.
17746 Defaults to `iswitchb' for buffer name completion.
17747 Set `org-completion-use-ido' to make it use ido instead."
17748 (interactive "P")
17749 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17750 ((equal arg '(16)) (org-buffer-list 'agenda))
17751 (t (org-buffer-list))))
17752 (org-completion-use-iswitchb org-completion-use-iswitchb)
17753 (org-completion-use-ido org-completion-use-ido))
17754 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17755 (setq org-completion-use-iswitchb t))
17756 (org-pop-to-buffer-same-window
17757 (org-icompleting-read "Org buffer: "
17758 (mapcar 'list (mapcar 'buffer-name blist))
17759 nil t))))
17761 ;;; Define some older names previously used for this functionality
17762 ;;;###autoload
17763 (defalias 'org-ido-switchb 'org-switchb)
17764 ;;;###autoload
17765 (defalias 'org-iswitchb 'org-switchb)
17767 (defun org-buffer-list (&optional predicate exclude-tmp)
17768 "Return a list of Org buffers.
17769 PREDICATE can be `export', `files' or `agenda'.
17771 export restrict the list to Export buffers.
17772 files restrict the list to buffers visiting Org files.
17773 agenda restrict the list to buffers visiting agenda files.
17775 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17776 (let* ((bfn nil)
17777 (agenda-files (and (eq predicate 'agenda)
17778 (mapcar 'file-truename (org-agenda-files t))))
17779 (filter
17780 (cond
17781 ((eq predicate 'files)
17782 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17783 ((eq predicate 'export)
17784 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17785 ((eq predicate 'agenda)
17786 (lambda (b)
17787 (with-current-buffer b
17788 (and (derived-mode-p 'org-mode)
17789 (setq bfn (buffer-file-name b))
17790 (member (file-truename bfn) agenda-files)))))
17791 (t (lambda (b) (with-current-buffer b
17792 (or (derived-mode-p 'org-mode)
17793 (string-match "\*Org .*Export"
17794 (buffer-name b)))))))))
17795 (delq nil
17796 (mapcar
17797 (lambda(b)
17798 (if (and (funcall filter b)
17799 (or (not exclude-tmp)
17800 (not (string-match "tmp" (buffer-name b)))))
17802 nil))
17803 (buffer-list)))))
17805 (defun org-agenda-files (&optional unrestricted archives)
17806 "Get the list of agenda files.
17807 Optional UNRESTRICTED means return the full list even if a restriction
17808 is currently in place.
17809 When ARCHIVES is t, include all archive files that are really being
17810 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17811 `org-agenda-archives-mode' is t."
17812 (let ((files
17813 (cond
17814 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17815 ((stringp org-agenda-files) (org-read-agenda-file-list))
17816 ((listp org-agenda-files) org-agenda-files)
17817 (t (error "Invalid value of `org-agenda-files'")))))
17818 (setq files (apply 'append
17819 (mapcar (lambda (f)
17820 (if (file-directory-p f)
17821 (directory-files
17822 f t org-agenda-file-regexp)
17823 (list f)))
17824 files)))
17825 (when org-agenda-skip-unavailable-files
17826 (setq files (delq nil
17827 (mapcar (function
17828 (lambda (file)
17829 (and (file-readable-p file) file)))
17830 files))))
17831 (when (or (eq archives t)
17832 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17833 (setq files (org-add-archive-files files)))
17834 files))
17836 (defun org-agenda-file-p (&optional file)
17837 "Return non-nil, if FILE is an agenda file.
17838 If FILE is omitted, use the file associated with the current
17839 buffer."
17840 (member (or file (buffer-file-name))
17841 (org-agenda-files t)))
17843 (defun org-edit-agenda-file-list ()
17844 "Edit the list of agenda files.
17845 Depending on setup, this either uses customize to edit the variable
17846 `org-agenda-files', or it visits the file that is holding the list. In the
17847 latter case, the buffer is set up in a way that saving it automatically kills
17848 the buffer and restores the previous window configuration."
17849 (interactive)
17850 (if (stringp org-agenda-files)
17851 (let ((cw (current-window-configuration)))
17852 (find-file org-agenda-files)
17853 (org-set-local 'org-window-configuration cw)
17854 (org-add-hook 'after-save-hook
17855 (lambda ()
17856 (set-window-configuration
17857 (prog1 org-window-configuration
17858 (kill-buffer (current-buffer))))
17859 (org-install-agenda-files-menu)
17860 (message "New agenda file list installed"))
17861 nil 'local)
17862 (message "%s" (substitute-command-keys
17863 "Edit list and finish with \\[save-buffer]")))
17864 (customize-variable 'org-agenda-files)))
17866 (defun org-store-new-agenda-file-list (list)
17867 "Set new value for the agenda file list and save it correctly."
17868 (if (stringp org-agenda-files)
17869 (let ((fe (org-read-agenda-file-list t)) b u)
17870 (while (setq b (find-buffer-visiting org-agenda-files))
17871 (kill-buffer b))
17872 (with-temp-file org-agenda-files
17873 (insert
17874 (mapconcat
17875 (lambda (f) ;; Keep un-expanded entries.
17876 (if (setq u (assoc f fe))
17877 (cdr u)
17879 list "\n")
17880 "\n")))
17881 (let ((org-mode-hook nil) (org-inhibit-startup t)
17882 (org-insert-mode-line-in-empty-file nil))
17883 (setq org-agenda-files list)
17884 (customize-save-variable 'org-agenda-files org-agenda-files))))
17886 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17887 "Read the list of agenda files from a file.
17888 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17889 filenames, used by `org-store-new-agenda-file-list' to write back
17890 un-expanded file names."
17891 (when (file-directory-p org-agenda-files)
17892 (error "`org-agenda-files' cannot be a single directory"))
17893 (when (stringp org-agenda-files)
17894 (with-temp-buffer
17895 (insert-file-contents org-agenda-files)
17896 (mapcar
17897 (lambda (f)
17898 (let ((e (expand-file-name (substitute-in-file-name f)
17899 org-directory)))
17900 (if pair-with-expansion
17901 (cons e f)
17902 e)))
17903 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17905 ;;;###autoload
17906 (defun org-cycle-agenda-files ()
17907 "Cycle through the files in `org-agenda-files'.
17908 If the current buffer visits an agenda file, find the next one in the list.
17909 If the current buffer does not, find the first agenda file."
17910 (interactive)
17911 (let* ((fs (org-agenda-files t))
17912 (files (append fs (list (car fs))))
17913 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17914 file)
17915 (unless files (user-error "No agenda files"))
17916 (catch 'exit
17917 (while (setq file (pop files))
17918 (if (equal (file-truename file) tcf)
17919 (when (car files)
17920 (find-file (car files))
17921 (throw 'exit t))))
17922 (find-file (car fs)))
17923 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17925 (defun org-agenda-file-to-front (&optional to-end)
17926 "Move/add the current file to the top of the agenda file list.
17927 If the file is not present in the list, it is added to the front. If it is
17928 present, it is moved there. With optional argument TO-END, add/move to the
17929 end of the list."
17930 (interactive "P")
17931 (let ((org-agenda-skip-unavailable-files nil)
17932 (file-alist (mapcar (lambda (x)
17933 (cons (file-truename x) x))
17934 (org-agenda-files t)))
17935 (ctf (file-truename
17936 (or buffer-file-name
17937 (user-error "Please save the current buffer to a file"))))
17938 x had)
17939 (setq x (assoc ctf file-alist) had x)
17941 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17942 (if to-end
17943 (setq file-alist (append (delq x file-alist) (list x)))
17944 (setq file-alist (cons x (delq x file-alist))))
17945 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17946 (org-install-agenda-files-menu)
17947 (message "File %s to %s of agenda file list"
17948 (if had "moved" "added") (if to-end "end" "front"))))
17950 (defun org-remove-file (&optional file)
17951 "Remove current file from the list of files in variable `org-agenda-files'.
17952 These are the files which are being checked for agenda entries.
17953 Optional argument FILE means use this file instead of the current."
17954 (interactive)
17955 (let* ((org-agenda-skip-unavailable-files nil)
17956 (file (or file buffer-file-name
17957 (user-error "Current buffer does not visit a file")))
17958 (true-file (file-truename file))
17959 (afile (abbreviate-file-name file))
17960 (files (delq nil (mapcar
17961 (lambda (x)
17962 (if (equal true-file
17963 (file-truename x))
17964 nil x))
17965 (org-agenda-files t)))))
17966 (if (not (= (length files) (length (org-agenda-files t))))
17967 (progn
17968 (org-store-new-agenda-file-list files)
17969 (org-install-agenda-files-menu)
17970 (message "Removed file: %s" afile))
17971 (message "File was not in list: %s (not removed)" afile))))
17973 (defun org-file-menu-entry (file)
17974 (vector file (list 'find-file file) t))
17976 (defun org-check-agenda-file (file)
17977 "Make sure FILE exists. If not, ask user what to do."
17978 (when (not (file-exists-p file))
17979 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17980 (abbreviate-file-name file))
17981 (let ((r (downcase (read-char-exclusive))))
17982 (cond
17983 ((equal r ?r)
17984 (org-remove-file file)
17985 (throw 'nextfile t))
17986 (t (error "Abort"))))))
17988 (defun org-get-agenda-file-buffer (file)
17989 "Get a buffer visiting FILE. If the buffer needs to be created, add
17990 it to the list of buffers which might be released later."
17991 (let ((buf (org-find-base-buffer-visiting file)))
17992 (if buf
17993 buf ; just return it
17994 ;; Make a new buffer and remember it
17995 (setq buf (find-file-noselect file))
17996 (if buf (push buf org-agenda-new-buffers))
17997 buf)))
17999 (defun org-release-buffers (blist)
18000 "Release all buffers in list, asking the user for confirmation when needed.
18001 When a buffer is unmodified, it is just killed. When modified, it is saved
18002 \(if the user agrees) and then killed."
18003 (let (buf file)
18004 (while (setq buf (pop blist))
18005 (setq file (buffer-file-name buf))
18006 (when (and (buffer-modified-p buf)
18007 file
18008 (y-or-n-p (format "Save file %s? " file)))
18009 (with-current-buffer buf (save-buffer)))
18010 (kill-buffer buf))))
18012 (defun org-agenda-prepare-buffers (files)
18013 "Create buffers for all agenda files, protect archived trees and comments."
18014 (interactive)
18015 (let ((pa '(:org-archived t))
18016 (pc '(:org-comment t))
18017 (pall '(:org-archived t :org-comment t))
18018 (inhibit-read-only t)
18019 (org-inhibit-startup org-agenda-inhibit-startup)
18020 (rea (concat ":" org-archive-tag ":"))
18021 file re)
18022 (setq org-tag-alist-for-agenda nil
18023 org-tag-groups-alist-for-agenda nil)
18024 (save-excursion
18025 (save-restriction
18026 (while (setq file (pop files))
18027 (catch 'nextfile
18028 (if (bufferp file)
18029 (set-buffer file)
18030 (org-check-agenda-file file)
18031 (set-buffer (org-get-agenda-file-buffer file)))
18032 (widen)
18033 (org-set-regexps-and-options-for-tags)
18034 (goto-char (point-min))
18035 (let ((case-fold-search t))
18036 (when (search-forward "#+setupfile" nil t)
18037 ;; Don't set all regexps and options systematically as
18038 ;; this is only run for setting agenda tags from setup
18039 ;; file
18040 (org-set-regexps-and-options)))
18041 (or (memq 'category org-agenda-ignore-drawer-properties)
18042 (org-refresh-category-properties))
18043 (or (memq 'effort org-agenda-ignore-drawer-properties)
18044 (org-refresh-properties org-effort-property 'org-effort))
18045 (or (memq 'appt org-agenda-ignore-drawer-properties)
18046 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18047 (setq org-todo-keywords-for-agenda
18048 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18049 (setq org-done-keywords-for-agenda
18050 (append org-done-keywords-for-agenda org-done-keywords))
18051 (setq org-todo-keyword-alist-for-agenda
18052 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18053 (setq org-tag-alist-for-agenda
18054 (org-uniquify
18055 (append org-tag-alist-for-agenda
18056 org-tag-alist
18057 org-tag-persistent-alist)))
18058 (if org-group-tags
18059 (setq org-tag-groups-alist-for-agenda
18060 (org-uniquify-alist
18061 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18062 (org-with-silent-modifications
18063 (save-excursion
18064 (remove-text-properties (point-min) (point-max) pall)
18065 (when org-agenda-skip-archived-trees
18066 (goto-char (point-min))
18067 (while (re-search-forward rea nil t)
18068 (if (org-at-heading-p t)
18069 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18070 (goto-char (point-min))
18071 (setq re (format org-heading-keyword-regexp-format
18072 org-comment-string))
18073 (while (re-search-forward re nil t)
18074 (add-text-properties
18075 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18076 (setq org-todo-keywords-for-agenda
18077 (org-uniquify org-todo-keywords-for-agenda))
18078 (setq org-todo-keyword-alist-for-agenda
18079 (org-uniquify org-todo-keyword-alist-for-agenda))))
18082 ;;;; CDLaTeX minor mode
18084 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18085 "Keymap for the minor `org-cdlatex-mode'.")
18087 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18088 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18089 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18090 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18091 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18093 (defvar org-cdlatex-texmathp-advice-is-done nil
18094 "Flag remembering if we have applied the advice to texmathp already.")
18096 (define-minor-mode org-cdlatex-mode
18097 "Toggle the minor `org-cdlatex-mode'.
18098 This mode supports entering LaTeX environment and math in LaTeX fragments
18099 in Org-mode.
18100 \\{org-cdlatex-mode-map}"
18101 nil " OCDL" nil
18102 (when org-cdlatex-mode
18103 (require 'cdlatex)
18104 (run-hooks 'cdlatex-mode-hook)
18105 (cdlatex-compute-tables))
18106 (unless org-cdlatex-texmathp-advice-is-done
18107 (setq org-cdlatex-texmathp-advice-is-done t)
18108 (defadvice texmathp (around org-math-always-on activate)
18109 "Always return t in org-mode buffers.
18110 This is because we want to insert math symbols without dollars even outside
18111 the LaTeX math segments. If Orgmode thinks that point is actually inside
18112 an embedded LaTeX fragment, let texmathp do its job.
18113 \\[org-cdlatex-mode-map]"
18114 (interactive)
18115 (let (p)
18116 (cond
18117 ((not (derived-mode-p 'org-mode)) ad-do-it)
18118 ((eq this-command 'cdlatex-math-symbol)
18119 (setq ad-return-value t
18120 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18122 (let ((p (org-inside-LaTeX-fragment-p)))
18123 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18124 (setq ad-return-value t
18125 texmathp-why '("Org-mode embedded math" . 0))
18126 (if p ad-do-it)))))))))
18128 (defun turn-on-org-cdlatex ()
18129 "Unconditionally turn on `org-cdlatex-mode'."
18130 (org-cdlatex-mode 1))
18132 (defun org-try-cdlatex-tab ()
18133 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18134 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18135 - inside a LaTeX fragment, or
18136 - after the first word in a line, where an abbreviation expansion could
18137 insert a LaTeX environment."
18138 (when org-cdlatex-mode
18139 (cond
18140 ;; Before any word on the line: No expansion possible.
18141 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18142 ;; Just after first word on the line: Expand it. Make sure it
18143 ;; cannot happen on headlines, though.
18144 ((save-excursion
18145 (skip-chars-backward "a-zA-Z0-9*")
18146 (skip-chars-backward " \t")
18147 (and (bolp) (not (org-at-heading-p))))
18148 (cdlatex-tab) t)
18149 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18151 (defun org-cdlatex-underscore-caret (&optional arg)
18152 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18153 Revert to the normal definition outside of these fragments."
18154 (interactive "P")
18155 (if (org-inside-LaTeX-fragment-p)
18156 (call-interactively 'cdlatex-sub-superscript)
18157 (let (org-cdlatex-mode)
18158 (call-interactively (key-binding (vector last-input-event))))))
18160 (defun org-cdlatex-math-modify (&optional arg)
18161 "Execute `cdlatex-math-modify' in LaTeX fragments.
18162 Revert to the normal definition outside of these fragments."
18163 (interactive "P")
18164 (if (org-inside-LaTeX-fragment-p)
18165 (call-interactively 'cdlatex-math-modify)
18166 (let (org-cdlatex-mode)
18167 (call-interactively (key-binding (vector last-input-event))))))
18171 ;;;; LaTeX fragments
18173 (defvar org-latex-regexps
18174 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18175 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18176 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18177 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18178 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18179 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18180 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18181 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18182 "Regular expressions for matching embedded LaTeX.")
18184 (defun org-inside-LaTeX-fragment-p ()
18185 "Test if point is inside a LaTeX fragment.
18186 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18187 sequence appearing also before point.
18188 Even though the matchers for math are configurable, this function assumes
18189 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18190 delimiters are skipped when they have been removed by customization.
18191 The return value is nil, or a cons cell with the delimiter and the
18192 position of this delimiter.
18194 This function does a reasonably good job, but can locally be fooled by
18195 for example currency specifications. For example it will assume being in
18196 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18197 fragments that are properly closed, but during editing, we have to live
18198 with the uncertainty caused by missing closing delimiters. This function
18199 looks only before point, not after."
18200 (catch 'exit
18201 (let ((pos (point))
18202 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18203 (lim (progn
18204 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18205 (point)))
18206 dd-on str (start 0) m re)
18207 (goto-char pos)
18208 (when dodollar
18209 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18210 re (nth 1 (assoc "$" org-latex-regexps)))
18211 (while (string-match re str start)
18212 (cond
18213 ((= (match-end 0) (length str))
18214 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18215 ((= (match-end 0) (- (length str) 5))
18216 (throw 'exit nil))
18217 (t (setq start (match-end 0))))))
18218 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18219 (goto-char pos)
18220 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18221 (and (match-beginning 2) (throw 'exit nil))
18222 ;; count $$
18223 (while (re-search-backward "\\$\\$" lim t)
18224 (setq dd-on (not dd-on)))
18225 (goto-char pos)
18226 (if dd-on (cons "$$" m))))))
18228 (defun org-inside-latex-macro-p ()
18229 "Is point inside a LaTeX macro or its arguments?"
18230 (save-match-data
18231 (org-in-regexp
18232 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18234 (defvar org-latex-fragment-image-overlays nil
18235 "List of overlays carrying the images of latex fragments.")
18236 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18238 (defun org-remove-latex-fragment-image-overlays ()
18239 "Remove all overlays with LaTeX fragment images in current buffer."
18240 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18241 (setq org-latex-fragment-image-overlays nil))
18243 (defun org-preview-latex-fragment (&optional subtree)
18244 "Preview the LaTeX fragment at point, or all locally or globally.
18245 If the cursor is in a LaTeX fragment, create the image and overlay
18246 it over the source code. If there is no fragment at point, display
18247 all fragments in the current text, from one headline to the next. With
18248 prefix SUBTREE, display all fragments in the current subtree. With a
18249 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18250 the cursor is before the first headline,
18251 display all fragments in the buffer.
18252 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18253 (interactive "P")
18254 (unless buffer-file-name
18255 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18256 (when (display-graphic-p)
18257 (org-remove-latex-fragment-image-overlays)
18258 (save-excursion
18259 (save-restriction
18260 (let (beg end at msg)
18261 (cond
18262 ((or (equal subtree '(16))
18263 (not (save-excursion
18264 (re-search-backward org-outline-regexp-bol nil t))))
18265 (setq beg (point-min) end (point-max)
18266 msg "Creating images for buffer...%s"))
18267 ((equal subtree '(4))
18268 (org-back-to-heading)
18269 (setq beg (point) end (org-end-of-subtree t)
18270 msg "Creating images for subtree...%s"))
18272 (if (setq at (org-inside-LaTeX-fragment-p))
18273 (goto-char (max (point-min) (- (cdr at) 2)))
18274 (org-back-to-heading))
18275 (setq beg (point) end (progn (outline-next-heading) (point))
18276 msg (if at "Creating image...%s"
18277 "Creating images for entry...%s"))))
18278 (message msg "")
18279 (narrow-to-region beg end)
18280 (goto-char beg)
18281 (org-format-latex
18282 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18283 (file-name-nondirectory
18284 buffer-file-name)))
18285 default-directory 'overlays msg at 'forbuffer
18286 org-latex-create-formula-image-program)
18287 (message msg "done. Use `C-c C-c' to remove images."))))))
18289 (defun org-format-latex (prefix &optional dir overlays msg at
18290 forbuffer processing-type)
18291 "Replace LaTeX fragments with links to an image, and produce images.
18292 Some of the options can be changed using the variable
18293 `org-format-latex-options'."
18294 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18295 (let* ((prefixnodir (file-name-nondirectory prefix))
18296 (absprefix (expand-file-name prefix dir))
18297 (todir (file-name-directory absprefix))
18298 (opt org-format-latex-options)
18299 (optnew org-format-latex-options)
18300 (matchers (plist-get opt :matchers))
18301 (re-list org-latex-regexps)
18302 (cnt 0) txt hash link beg end re e checkdir
18303 string
18304 m n block-type block linkfile movefile ov)
18305 ;; Check the different regular expressions
18306 (while (setq e (pop re-list))
18307 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18308 block (if block-type "\n\n" ""))
18309 (when (member m matchers)
18310 (goto-char (point-min))
18311 (while (re-search-forward re nil t)
18312 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18313 (or (not overlays)
18314 (not (eq (get-char-property (match-beginning n)
18315 'org-overlay-type)
18316 'org-latex-overlay))))
18317 (cond
18318 ((eq processing-type 'verbatim))
18319 ((eq processing-type 'mathjax)
18320 ;; Prepare for MathJax processing.
18321 (setq string (match-string n))
18322 (when (member m '("$" "$1"))
18323 (save-excursion
18324 (delete-region (match-beginning n) (match-end n))
18325 (goto-char (match-beginning n))
18326 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18327 ((or (eq processing-type 'dvipng)
18328 (eq processing-type 'imagemagick))
18329 ;; Process to an image.
18330 (setq txt (match-string n)
18331 beg (match-beginning n) end (match-end n)
18332 cnt (1+ cnt))
18333 (let ((face (face-at-point))
18334 (fg (plist-get opt :foreground))
18335 (bg (plist-get opt :background))
18336 ;; Ensure full list is printed.
18337 print-length print-level)
18338 (when forbuffer
18339 ;; Get the colors from the face at point.
18340 (goto-char beg)
18341 (when (eq fg 'auto)
18342 (setq fg (face-attribute face :foreground nil 'default)))
18343 (when (eq bg 'auto)
18344 (setq bg (face-attribute face :background nil 'default)))
18345 (setq optnew (copy-sequence opt))
18346 (plist-put optnew :foreground fg)
18347 (plist-put optnew :background bg))
18348 (setq hash (sha1 (prin1-to-string
18349 (list org-format-latex-header
18350 org-latex-default-packages-alist
18351 org-latex-packages-alist
18352 org-format-latex-options
18353 forbuffer txt fg bg)))
18354 linkfile (format "%s_%s.png" prefix hash)
18355 movefile (format "%s_%s.png" absprefix hash)))
18356 (setq link (concat block "[[file:" linkfile "]]" block))
18357 (if msg (message msg cnt))
18358 (goto-char beg)
18359 (unless checkdir ; Ensure the directory exists.
18360 (setq checkdir t)
18361 (or (file-directory-p todir) (make-directory todir t)))
18362 (unless (file-exists-p movefile)
18363 (org-create-formula-image
18364 txt movefile optnew forbuffer processing-type))
18365 (if overlays
18366 (progn
18367 (mapc (lambda (o)
18368 (if (eq (overlay-get o 'org-overlay-type)
18369 'org-latex-overlay)
18370 (delete-overlay o)))
18371 (overlays-in beg end))
18372 (setq ov (make-overlay beg end))
18373 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18374 (if (featurep 'xemacs)
18375 (progn
18376 (overlay-put ov 'invisible t)
18377 (overlay-put
18378 ov 'end-glyph
18379 (make-glyph (vector 'png :file movefile))))
18380 (overlay-put
18381 ov 'display
18382 (list 'image :type 'png :file movefile :ascent 'center)))
18383 (push ov org-latex-fragment-image-overlays)
18384 (goto-char end))
18385 (delete-region beg end)
18386 (insert (org-add-props link
18387 (list 'org-latex-src
18388 (replace-regexp-in-string
18389 "\"" "" txt)
18390 'org-latex-src-embed-type
18391 (if block-type 'paragraph 'character))))))
18392 ((eq processing-type 'mathml)
18393 ;; Process to MathML
18394 (unless (save-match-data (org-format-latex-mathml-available-p))
18395 (user-error "LaTeX to MathML converter not configured"))
18396 (setq txt (match-string n)
18397 beg (match-beginning n) end (match-end n)
18398 cnt (1+ cnt))
18399 (if msg (message msg cnt))
18400 (goto-char beg)
18401 (delete-region beg end)
18402 (insert (org-format-latex-as-mathml
18403 txt block-type prefix dir)))
18405 (error "Unknown conversion type %s for LaTeX fragments"
18406 processing-type)))))))))
18408 (defun org-create-math-formula (latex-frag &optional mathml-file)
18409 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18410 Use `org-latex-to-mathml-convert-command'. If the conversion is
18411 sucessful, return the portion between \"<math...> </math>\"
18412 elements otherwise return nil. When MATHML-FILE is specified,
18413 write the results in to that file. When invoked as an
18414 interactive command, prompt for LATEX-FRAG, with initial value
18415 set to the current active region and echo the results for user
18416 inspection."
18417 (interactive (list (let ((frag (when (org-region-active-p)
18418 (buffer-substring-no-properties
18419 (region-beginning) (region-end)))))
18420 (read-string "LaTeX Fragment: " frag nil frag))))
18421 (unless latex-frag (error "Invalid LaTeX fragment"))
18422 (let* ((tmp-in-file (file-relative-name
18423 (make-temp-name (expand-file-name "ltxmathml-in"))))
18424 (ignore (write-region latex-frag nil tmp-in-file))
18425 (tmp-out-file (file-relative-name
18426 (make-temp-name (expand-file-name "ltxmathml-out"))))
18427 (cmd (format-spec
18428 org-latex-to-mathml-convert-command
18429 `((?j . ,(shell-quote-argument
18430 (expand-file-name org-latex-to-mathml-jar-file)))
18431 (?I . ,(shell-quote-argument tmp-in-file))
18432 (?o . ,(shell-quote-argument tmp-out-file)))))
18433 mathml shell-command-output)
18434 (when (org-called-interactively-p 'any)
18435 (unless (org-format-latex-mathml-available-p)
18436 (user-error "LaTeX to MathML converter not configured")))
18437 (message "Running %s" cmd)
18438 (setq shell-command-output (shell-command-to-string cmd))
18439 (setq mathml
18440 (when (file-readable-p tmp-out-file)
18441 (with-current-buffer (find-file-noselect tmp-out-file t)
18442 (goto-char (point-min))
18443 (when (re-search-forward
18444 (concat
18445 (regexp-quote
18446 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18447 "\\(.\\|\n\\)*"
18448 (regexp-quote "</math>")) nil t)
18449 (prog1 (match-string 0) (kill-buffer))))))
18450 (cond
18451 (mathml
18452 (setq mathml
18453 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18454 (when mathml-file
18455 (write-region mathml nil mathml-file))
18456 (when (org-called-interactively-p 'any)
18457 (message mathml)))
18458 ((message "LaTeX to MathML conversion failed")
18459 (message shell-command-output)))
18460 (delete-file tmp-in-file)
18461 (when (file-exists-p tmp-out-file)
18462 (delete-file tmp-out-file))
18463 mathml))
18465 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18466 prefix &optional dir)
18467 "Use `org-create-math-formula' but check local cache first."
18468 (let* ((absprefix (expand-file-name prefix dir))
18469 (print-length nil) (print-level nil)
18470 (formula-id (concat
18471 "formula-"
18472 (sha1
18473 (prin1-to-string
18474 (list latex-frag
18475 org-latex-to-mathml-convert-command)))))
18476 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18477 (formula-cache-dir (file-name-directory formula-cache)))
18479 (unless (file-directory-p formula-cache-dir)
18480 (make-directory formula-cache-dir t))
18482 (unless (file-exists-p formula-cache)
18483 (org-create-math-formula latex-frag formula-cache))
18485 (if (file-exists-p formula-cache)
18486 ;; Successful conversion. Return the link to MathML file.
18487 (org-add-props
18488 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18489 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18490 'org-latex-src-embed-type (if latex-frag-type
18491 'paragraph 'character)))
18492 ;; Failed conversion. Return the LaTeX fragment verbatim
18493 latex-frag)))
18495 (defun org-create-formula-image (string tofile options buffer &optional type)
18496 "Create an image from LaTeX source using dvipng or convert.
18497 This function calls either `org-create-formula-image-with-dvipng'
18498 or `org-create-formula-image-with-imagemagick' depending on the
18499 value of `org-latex-create-formula-image-program' or on the value
18500 of the optional TYPE variable.
18502 Note: ultimately these two function should be combined as they
18503 share a good deal of logic."
18504 (org-check-external-command
18505 "latex" "needed to convert LaTeX fragments to images")
18506 (funcall
18507 (case (or type org-latex-create-formula-image-program)
18508 ('dvipng
18509 (org-check-external-command
18510 "dvipng" "needed to convert LaTeX fragments to images")
18511 #'org-create-formula-image-with-dvipng)
18512 ('imagemagick
18513 (org-check-external-command
18514 "convert" "you need to install imagemagick")
18515 #'org-create-formula-image-with-imagemagick)
18516 (t (error
18517 "Invalid value of `org-latex-create-formula-image-program'")))
18518 string tofile options buffer))
18520 (declare-function org-export-get-backend "ox" (name))
18521 (declare-function org-export--get-global-options "ox" (&optional backend))
18522 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18523 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18524 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18525 (defun org-create-formula--latex-header ()
18526 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18527 (let ((info (org-combine-plists (org-export--get-global-options
18528 (org-export-get-backend 'latex))
18529 (org-export--get-inbuffer-options
18530 (org-export-get-backend 'latex)))))
18531 (org-latex-guess-babel-language
18532 (org-latex-guess-inputenc
18533 (org-splice-latex-header
18534 org-format-latex-header
18535 org-latex-default-packages-alist
18536 org-latex-packages-alist t
18537 (plist-get info :latex-header)))
18538 info)))
18540 ;; This function borrows from Ganesh Swami's latex2png.el
18541 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18542 "This calls dvipng."
18543 (require 'ox-latex)
18544 (let* ((tmpdir (if (featurep 'xemacs)
18545 (temp-directory)
18546 temporary-file-directory))
18547 (texfilebase (make-temp-name
18548 (expand-file-name "orgtex" tmpdir)))
18549 (texfile (concat texfilebase ".tex"))
18550 (dvifile (concat texfilebase ".dvi"))
18551 (pngfile (concat texfilebase ".png"))
18552 (fnh (if (featurep 'xemacs)
18553 (font-height (face-font 'default))
18554 (face-attribute 'default :height nil)))
18555 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18556 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18557 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18558 "Black"))
18559 (bg (or (plist-get options (if buffer :background :html-background))
18560 "Transparent")))
18561 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18562 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18563 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18564 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18565 (let ((latex-header (org-create-formula--latex-header)))
18566 (with-temp-file texfile
18567 (insert latex-header)
18568 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18569 (let ((dir default-directory))
18570 (condition-case nil
18571 (progn
18572 (cd tmpdir)
18573 (call-process "latex" nil nil nil texfile))
18574 (error nil))
18575 (cd dir))
18576 (if (not (file-exists-p dvifile))
18577 (progn (message "Failed to create dvi file from %s" texfile) nil)
18578 (condition-case nil
18579 (if (featurep 'xemacs)
18580 (call-process "dvipng" nil nil nil
18581 "-fg" fg "-bg" bg
18582 "-T" "tight"
18583 "-o" pngfile
18584 dvifile)
18585 (call-process "dvipng" nil nil nil
18586 "-fg" fg "-bg" bg
18587 "-D" dpi
18588 ;;"-x" scale "-y" scale
18589 "-T" "tight"
18590 "-o" pngfile
18591 dvifile))
18592 (error nil))
18593 (if (not (file-exists-p pngfile))
18594 (if org-format-latex-signal-error
18595 (error "Failed to create png file from %s" texfile)
18596 (message "Failed to create png file from %s" texfile)
18597 nil)
18598 ;; Use the requested file name and clean up
18599 (copy-file pngfile tofile 'replace)
18600 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18601 (if (file-exists-p (concat texfilebase e))
18602 (delete-file (concat texfilebase e))))
18603 pngfile))))
18605 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18606 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18607 "This calls convert, which is included into imagemagick."
18608 (require 'ox-latex)
18609 (let* ((tmpdir (if (featurep 'xemacs)
18610 (temp-directory)
18611 temporary-file-directory))
18612 (texfilebase (make-temp-name
18613 (expand-file-name "orgtex" tmpdir)))
18614 (texfile (concat texfilebase ".tex"))
18615 (pdffile (concat texfilebase ".pdf"))
18616 (pngfile (concat texfilebase ".png"))
18617 (fnh (if (featurep 'xemacs)
18618 (font-height (face-font 'default))
18619 (face-attribute 'default :height nil)))
18620 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18621 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18622 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18623 "black"))
18624 (bg (or (plist-get options (if buffer :background :html-background))
18625 "white")))
18626 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18627 (setq fg (org-latex-color-format fg)))
18628 (if (eq bg 'default) (setq bg (org-latex-color :background))
18629 (setq bg (org-latex-color-format
18630 (if (string= bg "Transparent") "white" bg))))
18631 (let ((latex-header (org-create-formula--latex-header)))
18632 (with-temp-file texfile
18633 (insert latex-header)
18634 (insert "\n\\begin{document}\n"
18635 "\\definecolor{fg}{rgb}{" fg "}\n"
18636 "\\definecolor{bg}{rgb}{" bg "}\n"
18637 "\n\\pagecolor{bg}\n"
18638 "\n{\\color{fg}\n"
18639 string
18640 "\n}\n"
18641 "\n\\end{document}\n")))
18642 (org-latex-compile texfile t)
18643 (if (not (file-exists-p pdffile))
18644 (progn (message "Failed to create pdf file from %s" texfile) nil)
18645 (condition-case nil
18646 (if (featurep 'xemacs)
18647 (call-process "convert" nil nil nil
18648 "-density" "96"
18649 "-trim"
18650 "-antialias"
18651 pdffile
18652 "-quality" "100"
18653 ;; "-sharpen" "0x1.0"
18654 pngfile)
18655 (call-process "convert" nil nil nil
18656 "-density" dpi
18657 "-trim"
18658 "-antialias"
18659 pdffile
18660 "-quality" "100"
18661 ;; "-sharpen" "0x1.0"
18662 pngfile))
18663 (error nil))
18664 (if (not (file-exists-p pngfile))
18665 (if org-format-latex-signal-error
18666 (error "Failed to create png file from %s" texfile)
18667 (message "Failed to create png file from %s" texfile)
18668 nil)
18669 ;; Use the requested file name and clean up
18670 (copy-file pngfile tofile 'replace)
18671 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18672 (if (file-exists-p (concat texfilebase e))
18673 (delete-file (concat texfilebase e))))
18674 pngfile))))
18676 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18677 "Fill a LaTeX header template TPL.
18678 In the template, the following place holders will be recognized:
18680 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18681 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18682 [PACKAGES] \\usepackage statements for PKG
18683 [NO-PACKAGES] do not include PKG
18684 [EXTRA] the string EXTRA
18685 [NO-EXTRA] do not include EXTRA
18687 For backward compatibility, if both the positive and the negative place
18688 holder is missing, the positive one (without the \"NO-\") will be
18689 assumed to be present at the end of the template.
18690 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18691 EXTRA is a string.
18692 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18693 (let (rpl (end ""))
18694 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18695 (setq rpl (if (or (match-end 1) (not def-pkg))
18696 "" (org-latex-packages-to-string def-pkg snippets-p t))
18697 tpl (replace-match rpl t t tpl))
18698 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18700 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18701 (setq rpl (if (or (match-end 1) (not pkg))
18702 "" (org-latex-packages-to-string pkg snippets-p t))
18703 tpl (replace-match rpl t t tpl))
18704 (if pkg (setq end
18705 (concat end "\n"
18706 (org-latex-packages-to-string pkg snippets-p)))))
18708 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18709 (setq rpl (if (or (match-end 1) (not extra))
18710 "" (concat extra "\n"))
18711 tpl (replace-match rpl t t tpl))
18712 (if (and extra (string-match "\\S-" extra))
18713 (setq end (concat end "\n" extra))))
18715 (if (string-match "\\S-" end)
18716 (concat tpl "\n" end)
18717 tpl)))
18719 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18720 "Turn an alist of packages into a string with the \\usepackage macros."
18721 (setq pkg (mapconcat (lambda(p)
18722 (cond
18723 ((stringp p) p)
18724 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18725 (format "%% Package %s omitted" (cadr p)))
18726 ((equal "" (car p))
18727 (format "\\usepackage{%s}" (cadr p)))
18729 (format "\\usepackage[%s]{%s}"
18730 (car p) (cadr p)))))
18732 "\n"))
18733 (if newline (concat pkg "\n") pkg))
18735 (defun org-dvipng-color (attr)
18736 "Return a RGB color specification for dvipng."
18737 (apply 'format "rgb %s %s %s"
18738 (mapcar 'org-normalize-color
18739 (if (featurep 'xemacs)
18740 (color-rgb-components
18741 (face-property 'default
18742 (cond ((eq attr :foreground) 'foreground)
18743 ((eq attr :background) 'background))))
18744 (color-values (face-attribute 'default attr nil))))))
18746 (defun org-dvipng-color-format (color-name)
18747 "Convert COLOR-NAME to a RGB color value for dvipng."
18748 (apply 'format "rgb %s %s %s"
18749 (mapcar 'org-normalize-color
18750 (color-values color-name))))
18752 (defun org-latex-color (attr)
18753 "Return a RGB color for the LaTeX color package."
18754 (apply 'format "%s,%s,%s"
18755 (mapcar 'org-normalize-color
18756 (if (featurep 'xemacs)
18757 (color-rgb-components
18758 (face-property 'default
18759 (cond ((eq attr :foreground) 'foreground)
18760 ((eq attr :background) 'background))))
18761 (color-values (face-attribute 'default attr nil))))))
18763 (defun org-latex-color-format (color-name)
18764 "Convert COLOR-NAME to a RGB color value."
18765 (apply 'format "%s,%s,%s"
18766 (mapcar 'org-normalize-color
18767 (color-values color-name))))
18769 (defun org-normalize-color (value)
18770 "Return string to be used as color value for an RGB component."
18771 (format "%g" (/ value 65535.0)))
18775 ;; Image display
18777 (defvar org-inline-image-overlays nil)
18778 (make-variable-buffer-local 'org-inline-image-overlays)
18780 (defun org-toggle-inline-images (&optional include-linked)
18781 "Toggle the display of inline images.
18782 INCLUDE-LINKED is passed to `org-display-inline-images'."
18783 (interactive "P")
18784 (if org-inline-image-overlays
18785 (progn
18786 (org-remove-inline-images)
18787 (message "Inline image display turned off"))
18788 (org-display-inline-images include-linked)
18789 (if (and (org-called-interactively-p)
18790 org-inline-image-overlays)
18791 (message "%d images displayed inline"
18792 (length org-inline-image-overlays))
18793 (message "No images to display inline"))))
18795 (defun org-redisplay-inline-images ()
18796 "Refresh the display of inline images."
18797 (interactive)
18798 (if (not org-inline-image-overlays)
18799 (org-toggle-inline-images)
18800 (org-toggle-inline-images)
18801 (org-toggle-inline-images)))
18803 (defun org-display-inline-images (&optional include-linked refresh beg end)
18804 "Display inline images.
18806 An inline image is a link which follows either of these
18807 conventions:
18809 1. Its path is a file with an extension matching return value
18810 from `image-file-name-regexp' and it has no contents.
18812 2. Its description consists in a single link of the previous
18813 type.
18815 When optional argument INCLUDE-LINKED is non-nil, also links with
18816 a text description part will be inlined. This can be nice for
18817 a quick look at those images, but it does not reflect what
18818 exported files will look like.
18820 When optional argument REFRESH is non-nil, refresh existing
18821 images between BEG and END. This will create new image displays
18822 only if necessary. BEG and END default to the buffer
18823 boundaries."
18824 (interactive "P")
18825 (when (display-graphic-p)
18826 (unless refresh
18827 (org-remove-inline-images)
18828 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18829 (org-with-wide-buffer
18830 (goto-char (or beg (point-min)))
18831 (let ((case-fold-search t)
18832 (file-extension-re (org-image-file-name-regexp)))
18833 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18834 (let ((link (save-match-data (org-element-context))))
18835 ;; Check if we're at an inline image.
18836 (when (and (equal (org-element-property :type link) "file")
18837 (or include-linked
18838 (not (org-element-property :contents-begin link)))
18839 (let ((parent (org-element-property :parent link)))
18840 (or (not (eq (org-element-type parent) 'link))
18841 (not (cdr (org-element-contents parent)))))
18842 (org-string-match-p file-extension-re
18843 (org-element-property :path link)))
18844 (let ((file (expand-file-name (org-element-property :path link))))
18845 (when (file-exists-p file)
18846 (let ((width
18847 ;; Apply `org-image-actual-width' specifications.
18848 (cond
18849 ((not (image-type-available-p 'imagemagick)) nil)
18850 ((eq org-image-actual-width t) nil)
18851 ((listp org-image-actual-width)
18853 ;; First try to find a width among
18854 ;; attributes associated to the paragraph
18855 ;; containing link.
18856 (let ((paragraph
18857 (let ((e link))
18858 (while (and (setq e (org-element-property
18859 :parent e))
18860 (not (eq (org-element-type e)
18861 'paragraph))))
18862 e)))
18863 (when paragraph
18864 (save-excursion
18865 (goto-char (org-element-property :begin paragraph))
18866 (when (save-match-data
18867 (re-search-forward
18868 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18869 (org-element-property
18870 :post-affiliated paragraph)
18872 (string-to-number (match-string 1))))))
18873 ;; Otherwise, fall-back to provided number.
18874 (car org-image-actual-width)))
18875 ((numberp org-image-actual-width)
18876 org-image-actual-width)))
18877 (old (get-char-property-and-overlay
18878 (org-element-property :begin link)
18879 'org-image-overlay)))
18880 (if (and (car-safe old) refresh)
18881 (image-refresh (overlay-get (cdr old) 'display))
18882 (let ((image (save-match-data
18883 (create-image file
18884 (and width 'imagemagick)
18886 :width width))))
18887 (when image
18888 (let* ((link
18889 ;; If inline image is the description
18890 ;; of another link, be sure to
18891 ;; consider the latter as the one to
18892 ;; apply the overlay on.
18893 (let ((parent
18894 (org-element-property :parent link)))
18895 (if (eq (org-element-type parent) 'link)
18896 parent
18897 link)))
18898 (ov (make-overlay
18899 (org-element-property :begin link)
18900 (progn
18901 (goto-char
18902 (org-element-property :end link))
18903 (skip-chars-backward " \t")
18904 (point)))))
18905 (overlay-put ov 'display image)
18906 (overlay-put ov 'face 'default)
18907 (overlay-put ov 'org-image-overlay t)
18908 (overlay-put
18909 ov 'modification-hooks
18910 (list 'org-display-inline-remove-overlay))
18911 (push ov org-inline-image-overlays)))))))))))))))
18913 (define-obsolete-function-alias
18914 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18916 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18917 "Remove inline-display overlay if a corresponding region is modified."
18918 (let ((inhibit-modification-hooks t))
18919 (when (and ov after)
18920 (delete ov org-inline-image-overlays)
18921 (delete-overlay ov))))
18923 (defun org-remove-inline-images ()
18924 "Remove inline display of images."
18925 (interactive)
18926 (mapc 'delete-overlay org-inline-image-overlays)
18927 (setq org-inline-image-overlays nil))
18929 ;;;; Key bindings
18931 ;; Outline functions from `outline-mode-prefix-map'
18932 ;; that can be remapped in Org:
18933 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18934 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18935 (define-key org-mode-map [remap outline-forward-same-level]
18936 'org-forward-heading-same-level)
18937 (define-key org-mode-map [remap outline-backward-same-level]
18938 'org-backward-heading-same-level)
18939 (define-key org-mode-map [remap show-branches]
18940 'org-kill-note-or-show-branches)
18941 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18942 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18943 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18945 ;; Outline functions from `outline-mode-prefix-map' that can not
18946 ;; be remapped in Org:
18948 ;; - the column "key binding" shows whether the Outline function is still
18949 ;; available in Org mode on the same key that it has been bound to in
18950 ;; Outline mode:
18951 ;; - "overridden": key used for a different functionality in Org mode
18952 ;; - else: key still bound to the same Outline function in Org mode
18954 ;; | Outline function | key binding | Org replacement |
18955 ;; |------------------------------------+-------------+-----------------------|
18956 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18957 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18958 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18959 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18960 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18961 ;; | `show-entry' | overridden | no replacement |
18962 ;; | `show-children' | `C-c C-i' | visibility cycling |
18963 ;; | `show-branches' | `C-c C-k' | still same function |
18964 ;; | `show-subtree' | overridden | visibility cycling |
18965 ;; | `show-all' | overridden | no replacement |
18966 ;; | `hide-subtree' | overridden | visibility cycling |
18967 ;; | `hide-body' | overridden | no replacement |
18968 ;; | `hide-entry' | overridden | visibility cycling |
18969 ;; | `hide-leaves' | overridden | no replacement |
18970 ;; | `hide-sublevels' | overridden | no replacement |
18971 ;; | `hide-other' | overridden | no replacement |
18973 ;; Make `C-c C-x' a prefix key
18974 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18976 ;; TAB key with modifiers
18977 (org-defkey org-mode-map "\C-i" 'org-cycle)
18978 (org-defkey org-mode-map [(tab)] 'org-cycle)
18979 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18980 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18981 ;; The following line is necessary under Suse GNU/Linux
18982 (unless (featurep 'xemacs)
18983 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18984 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18985 (define-key org-mode-map [backtab] 'org-shifttab)
18987 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18988 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18989 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18991 ;; Cursor keys with modifiers
18992 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18993 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18994 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18995 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18997 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18998 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18999 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19000 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19002 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19003 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19004 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19005 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19007 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19008 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19009 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19010 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19012 ;; Babel keys
19013 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19014 (mapc (lambda (pair)
19015 (define-key org-babel-map (car pair) (cdr pair)))
19016 org-babel-key-bindings)
19018 ;;; Extra keys for tty access.
19019 ;; We only set them when really needed because otherwise the
19020 ;; menus don't show the simple keys
19022 (when (or org-use-extra-keys
19023 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19024 (not window-system))
19025 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19026 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19027 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19028 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19029 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19030 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19031 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19032 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19033 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19034 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19035 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19036 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19037 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19038 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19039 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19040 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19041 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19042 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19043 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19044 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19045 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19046 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19047 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19048 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19049 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19050 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19051 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19052 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19054 ;; All the other keys
19056 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19057 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19058 (if (boundp 'narrow-map)
19059 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19060 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19061 (if (boundp 'narrow-map)
19062 (org-defkey narrow-map "b" 'org-narrow-to-block)
19063 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19064 (if (boundp 'narrow-map)
19065 (org-defkey narrow-map "e" 'org-narrow-to-element)
19066 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19067 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19068 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19069 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19070 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19071 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19072 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19073 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19074 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19075 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19076 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19077 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19078 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19079 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19080 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19081 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19082 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19083 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19084 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19085 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19086 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19087 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19088 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19089 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19090 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19091 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19092 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19093 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19094 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19095 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19096 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19097 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19098 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19099 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19100 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19101 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19102 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19103 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19104 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19105 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19106 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19107 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19108 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19109 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19110 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19111 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19112 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19113 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19114 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19115 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19116 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19117 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19118 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19119 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19120 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19121 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19122 (org-defkey org-mode-map "\C-c^" 'org-sort)
19123 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19124 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19125 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19126 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19127 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19128 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19129 (org-defkey org-mode-map "\C-m" 'org-return)
19130 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19131 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19132 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19133 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19134 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19135 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19136 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19137 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19138 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19139 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19140 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19141 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19142 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19143 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19144 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19145 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19146 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19147 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19148 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19149 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19150 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19151 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19152 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19154 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19155 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19156 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19158 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19159 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19160 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19161 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19162 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19163 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19164 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19165 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19166 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19167 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19168 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19169 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19170 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19171 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19172 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19173 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19174 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19175 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19176 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19177 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19178 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19179 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19180 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19182 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19183 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19184 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19185 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19186 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19188 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19190 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19192 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19193 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19195 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19198 (when (featurep 'xemacs)
19199 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19202 (defconst org-speed-commands-default
19204 ("Outline Navigation")
19205 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19206 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19207 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19208 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19209 ("F" . org-next-block)
19210 ("B" . org-previous-block)
19211 ("u" . (org-speed-move-safe 'outline-up-heading))
19212 ("j" . org-goto)
19213 ("g" . (org-refile t))
19214 ("Outline Visibility")
19215 ("c" . org-cycle)
19216 ("C" . org-shifttab)
19217 (" " . org-display-outline-path)
19218 ("s" . org-narrow-to-subtree)
19219 ("=" . org-columns)
19220 ("Outline Structure Editing")
19221 ("U" . org-shiftmetaup)
19222 ("D" . org-shiftmetadown)
19223 ("r" . org-metaright)
19224 ("l" . org-metaleft)
19225 ("R" . org-shiftmetaright)
19226 ("L" . org-shiftmetaleft)
19227 ("i" . (progn (forward-char 1) (call-interactively
19228 'org-insert-heading-respect-content)))
19229 ("^" . org-sort)
19230 ("w" . org-refile)
19231 ("a" . org-archive-subtree-default-with-confirmation)
19232 ("@" . org-mark-subtree)
19233 ("#" . org-toggle-comment)
19234 ("Clock Commands")
19235 ("I" . org-clock-in)
19236 ("O" . org-clock-out)
19237 ("Meta Data Editing")
19238 ("t" . org-todo)
19239 ("," . (org-priority))
19240 ("0" . (org-priority ?\ ))
19241 ("1" . (org-priority ?A))
19242 ("2" . (org-priority ?B))
19243 ("3" . (org-priority ?C))
19244 (":" . org-set-tags-command)
19245 ("e" . org-set-effort)
19246 ("E" . org-inc-effort)
19247 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19248 (org-entry-put (point) "APPT_WARNTIME" m)))
19249 ("Agenda Views etc")
19250 ("v" . org-agenda)
19251 ("/" . org-sparse-tree)
19252 ("Misc")
19253 ("o" . org-open-at-point)
19254 ("?" . org-speed-command-help)
19255 ("<" . (org-agenda-set-restriction-lock 'subtree))
19256 (">" . (org-agenda-remove-restriction-lock))
19258 "The default speed commands.")
19260 (defun org-print-speed-command (e)
19261 (if (> (length (car e)) 1)
19262 (progn
19263 (princ "\n")
19264 (princ (car e))
19265 (princ "\n")
19266 (princ (make-string (length (car e)) ?-))
19267 (princ "\n"))
19268 (princ (car e))
19269 (princ " ")
19270 (if (symbolp (cdr e))
19271 (princ (symbol-name (cdr e)))
19272 (prin1 (cdr e)))
19273 (princ "\n")))
19275 (defun org-speed-command-help ()
19276 "Show the available speed commands."
19277 (interactive)
19278 (if (not org-use-speed-commands)
19279 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19280 (with-output-to-temp-buffer "*Help*"
19281 (princ "User-defined Speed commands\n===========================\n")
19282 (mapc 'org-print-speed-command org-speed-commands-user)
19283 (princ "\n")
19284 (princ "Built-in Speed commands\n=======================\n")
19285 (mapc 'org-print-speed-command org-speed-commands-default))
19286 (with-current-buffer "*Help*"
19287 (setq truncate-lines t))))
19289 (defun org-speed-move-safe (cmd)
19290 "Execute CMD, but make sure that the cursor always ends up in a headline.
19291 If not, return to the original position and throw an error."
19292 (interactive)
19293 (let ((pos (point)))
19294 (call-interactively cmd)
19295 (unless (and (bolp) (org-at-heading-p))
19296 (goto-char pos)
19297 (error "Boundary reached while executing %s" cmd))))
19299 (defvar org-self-insert-command-undo-counter 0)
19301 (defvar org-table-auto-blank-field) ; defined in org-table.el
19302 (defvar org-speed-command nil)
19304 (define-obsolete-function-alias
19305 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19307 (defun org-speed-command-activate (keys)
19308 "Hook for activating single-letter speed commands.
19309 `org-speed-commands-default' specifies a minimal command set.
19310 Use `org-speed-commands-user' for further customization."
19311 (when (or (and (bolp) (looking-at org-outline-regexp))
19312 (and (functionp org-use-speed-commands)
19313 (funcall org-use-speed-commands)))
19314 (cdr (assoc keys (append org-speed-commands-user
19315 org-speed-commands-default)))))
19317 (define-obsolete-function-alias
19318 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19320 (defun org-babel-speed-command-activate (keys)
19321 "Hook for activating single-letter code block commands."
19322 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19323 (cdr (assoc keys org-babel-key-bindings))))
19325 (defcustom org-speed-command-hook
19326 '(org-speed-command-default-hook org-babel-speed-command-hook)
19327 "Hook for activating speed commands at strategic locations.
19328 Hook functions are called in sequence until a valid handler is
19329 found.
19331 Each hook takes a single argument, a user-pressed command key
19332 which is also a `self-insert-command' from the global map.
19334 Within the hook, examine the cursor position and the command key
19335 and return nil or a valid handler as appropriate. Handler could
19336 be one of an interactive command, a function, or a form.
19338 Set `org-use-speed-commands' to non-nil value to enable this
19339 hook. The default setting is `org-speed-command-activate'."
19340 :group 'org-structure
19341 :version "24.1"
19342 :type 'hook)
19344 (defun org-self-insert-command (N)
19345 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19346 If the cursor is in a table looking at whitespace, the whitespace is
19347 overwritten, and the table is not marked as requiring realignment."
19348 (interactive "p")
19349 (org-check-before-invisible-edit 'insert)
19350 (cond
19351 ((and org-use-speed-commands
19352 (setq org-speed-command
19353 (run-hook-with-args-until-success
19354 'org-speed-command-hook (this-command-keys))))
19355 (cond
19356 ((commandp org-speed-command)
19357 (setq this-command org-speed-command)
19358 (call-interactively org-speed-command))
19359 ((functionp org-speed-command)
19360 (funcall org-speed-command))
19361 ((and org-speed-command (listp org-speed-command))
19362 (eval org-speed-command))
19363 (t (let (org-use-speed-commands)
19364 (call-interactively 'org-self-insert-command)))))
19365 ((and
19366 (org-table-p)
19367 (progn
19368 ;; check if we blank the field, and if that triggers align
19369 (and (featurep 'org-table) org-table-auto-blank-field
19370 (member last-command
19371 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19372 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19373 ;; got extra space, this field does not determine column width
19374 (let (org-table-may-need-update) (org-table-blank-field))
19375 ;; no extra space, this field may determine column width
19376 (org-table-blank-field)))
19378 (eq N 1)
19379 (looking-at "[^|\n]* |"))
19380 (let (org-table-may-need-update)
19381 (goto-char (1- (match-end 0)))
19382 (backward-delete-char 1)
19383 (goto-char (match-beginning 0))
19384 (self-insert-command N)))
19386 (setq org-table-may-need-update t)
19387 (self-insert-command N)
19388 (org-fix-tags-on-the-fly)
19389 (if org-self-insert-cluster-for-undo
19390 (if (not (eq last-command 'org-self-insert-command))
19391 (setq org-self-insert-command-undo-counter 1)
19392 (if (>= org-self-insert-command-undo-counter 20)
19393 (setq org-self-insert-command-undo-counter 1)
19394 (and (> org-self-insert-command-undo-counter 0)
19395 buffer-undo-list (listp buffer-undo-list)
19396 (not (cadr buffer-undo-list)) ; remove nil entry
19397 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19398 (setq org-self-insert-command-undo-counter
19399 (1+ org-self-insert-command-undo-counter))))))))
19401 (defun org-check-before-invisible-edit (kind)
19402 "Check is editing if kind KIND would be dangerous with invisible text around.
19403 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19404 ;; First, try to get out of here as quickly as possible, to reduce overhead
19405 (if (and org-catch-invisible-edits
19406 (or (not (boundp 'visible-mode)) (not visible-mode))
19407 (or (get-char-property (point) 'invisible)
19408 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19409 ;; OK, we need to take a closer look
19410 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19411 (invisible-before-point (if (bobp) nil (get-char-property
19412 (1- (point)) 'invisible)))
19413 (border-and-ok-direction
19415 ;; Check if we are acting predictably before invisible text
19416 (and invisible-at-point (not invisible-before-point)
19417 (memq kind '(insert delete-backward)))
19418 ;; Check if we are acting predictably after invisible text
19419 ;; This works not well, and I have turned it off. It seems
19420 ;; better to always show and stop after invisible text.
19421 ;; (and (not invisible-at-point) invisible-before-point
19422 ;; (memq kind '(insert delete)))
19424 (when (or (memq invisible-at-point '(outline org-hide-block t))
19425 (memq invisible-before-point '(outline org-hide-block t)))
19426 (if (eq org-catch-invisible-edits 'error)
19427 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19428 (if (and org-custom-properties-overlays
19429 (y-or-n-p "Display invisible properties in this buffer? "))
19430 (org-toggle-custom-properties-visibility)
19431 ;; Make the area visible
19432 (save-excursion
19433 (if invisible-before-point
19434 (goto-char (previous-single-char-property-change
19435 (point) 'invisible)))
19436 (org-cycle))
19437 (cond
19438 ((eq org-catch-invisible-edits 'show)
19439 ;; That's it, we do the edit after showing
19440 (message
19441 "Unfolding invisible region around point before editing")
19442 (sit-for 1))
19443 ((and (eq org-catch-invisible-edits 'smart)
19444 border-and-ok-direction)
19445 (message "Unfolding invisible region around point before editing"))
19447 ;; Don't do the edit, make the user repeat it in full visibility
19448 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19450 (defun org-fix-tags-on-the-fly ()
19451 (when (and (equal (char-after (point-at-bol)) ?*)
19452 (org-at-heading-p))
19453 (org-align-tags-here org-tags-column)))
19455 (defun org-delete-backward-char (N)
19456 "Like `delete-backward-char', insert whitespace at field end in tables.
19457 When deleting backwards, in tables this function will insert whitespace in
19458 front of the next \"|\" separator, to keep the table aligned. The table will
19459 still be marked for re-alignment if the field did fill the entire column,
19460 because, in this case the deletion might narrow the column."
19461 (interactive "p")
19462 (save-match-data
19463 (org-check-before-invisible-edit 'delete-backward)
19464 (if (and (org-table-p)
19465 (eq N 1)
19466 (string-match "|" (buffer-substring (point-at-bol) (point)))
19467 (looking-at ".*?|"))
19468 (let ((pos (point))
19469 (noalign (looking-at "[^|\n\r]* |"))
19470 (c org-table-may-need-update))
19471 (backward-delete-char N)
19472 (if (not overwrite-mode)
19473 (progn
19474 (skip-chars-forward "^|")
19475 (insert " ")
19476 (goto-char (1- pos))))
19477 ;; noalign: if there were two spaces at the end, this field
19478 ;; does not determine the width of the column.
19479 (if noalign (setq org-table-may-need-update c)))
19480 (backward-delete-char N)
19481 (org-fix-tags-on-the-fly))))
19483 (defun org-delete-char (N)
19484 "Like `delete-char', but insert whitespace at field end in tables.
19485 When deleting characters, in tables this function will insert whitespace in
19486 front of the next \"|\" separator, to keep the table aligned. The table will
19487 still be marked for re-alignment if the field did fill the entire column,
19488 because, in this case the deletion might narrow the column."
19489 (interactive "p")
19490 (save-match-data
19491 (org-check-before-invisible-edit 'delete)
19492 (if (and (org-table-p)
19493 (not (bolp))
19494 (not (= (char-after) ?|))
19495 (eq N 1))
19496 (if (looking-at ".*?|")
19497 (let ((pos (point))
19498 (noalign (looking-at "[^|\n\r]* |"))
19499 (c org-table-may-need-update))
19500 (replace-match
19501 (concat (substring (match-string 0) 1 -1) " |") nil t)
19502 (goto-char pos)
19503 ;; noalign: if there were two spaces at the end, this field
19504 ;; does not determine the width of the column.
19505 (if noalign (setq org-table-may-need-update c)))
19506 (delete-char N))
19507 (delete-char N)
19508 (org-fix-tags-on-the-fly))))
19510 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19511 (put 'org-self-insert-command 'delete-selection t)
19512 (put 'orgtbl-self-insert-command 'delete-selection t)
19513 (put 'org-delete-char 'delete-selection 'supersede)
19514 (put 'org-delete-backward-char 'delete-selection 'supersede)
19515 (put 'org-yank 'delete-selection 'yank)
19517 ;; Make `flyspell-mode' delay after some commands
19518 (put 'org-self-insert-command 'flyspell-delayed t)
19519 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19520 (put 'org-delete-char 'flyspell-delayed t)
19521 (put 'org-delete-backward-char 'flyspell-delayed t)
19523 ;; Make pabbrev-mode expand after org-mode commands
19524 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19525 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19527 ;; How to do this: Measure non-white length of current string
19528 ;; If equal to column width, we should realign.
19530 (defun org-remap (map &rest commands)
19531 "In MAP, remap the functions given in COMMANDS.
19532 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19533 (let (new old)
19534 (while commands
19535 (setq old (pop commands) new (pop commands))
19536 (if (fboundp 'command-remapping)
19537 (org-defkey map (vector 'remap old) new)
19538 (substitute-key-definition old new map global-map)))))
19540 (defun org-transpose-words ()
19541 "Transpose words for Org.
19542 This uses the `org-mode-transpose-word-syntax-table' syntax
19543 table, which interprets characters in `org-emphasis-alist' as
19544 word constituants."
19545 (interactive)
19546 (with-syntax-table org-mode-transpose-word-syntax-table
19547 (call-interactively 'transpose-words)))
19548 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19550 (when (eq org-enable-table-editor 'optimized)
19551 ;; If the user wants maximum table support, we need to hijack
19552 ;; some standard editing functions
19553 (org-remap org-mode-map
19554 'self-insert-command 'org-self-insert-command
19555 'delete-char 'org-delete-char
19556 'delete-backward-char 'org-delete-backward-char)
19557 (org-defkey org-mode-map "|" 'org-force-self-insert))
19559 (defvar org-ctrl-c-ctrl-c-hook nil
19560 "Hook for functions attaching themselves to `C-c C-c'.
19562 This can be used to add additional functionality to the C-c C-c
19563 key which executes context-dependent commands. This hook is run
19564 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19565 run after the last test.
19567 Each function will be called with no arguments. The function
19568 must check if the context is appropriate for it to act. If yes,
19569 it should do its thing and then return a non-nil value. If the
19570 context is wrong, just do nothing and return nil.")
19572 (defvar org-ctrl-c-ctrl-c-final-hook nil
19573 "Hook for functions attaching themselves to `C-c C-c'.
19575 This can be used to add additional functionality to the C-c C-c
19576 key which executes context-dependent commands. This hook is run
19577 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19578 before the first test.
19580 Each function will be called with no arguments. The function
19581 must check if the context is appropriate for it to act. If yes,
19582 it should do its thing and then return a non-nil value. If the
19583 context is wrong, just do nothing and return nil.")
19585 (defvar org-tab-first-hook nil
19586 "Hook for functions to attach themselves to TAB.
19587 See `org-ctrl-c-ctrl-c-hook' for more information.
19588 This hook runs as the first action when TAB is pressed, even before
19589 `org-cycle' messes around with the `outline-regexp' to cater for
19590 inline tasks and plain list item folding.
19591 If any function in this hook returns t, any other actions that
19592 would have been caused by TAB (such as table field motion or visibility
19593 cycling) will not occur.")
19595 (defvar org-tab-after-check-for-table-hook nil
19596 "Hook for functions to attach themselves to TAB.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.
19598 This hook runs after it has been established that the cursor is not in a
19599 table, but before checking if the cursor is in a headline or if global cycling
19600 should be done.
19601 If any function in this hook returns t, not other actions like visibility
19602 cycling will be done.")
19604 (defvar org-tab-after-check-for-cycling-hook nil
19605 "Hook for functions to attach themselves to TAB.
19606 See `org-ctrl-c-ctrl-c-hook' for more information.
19607 This hook runs after it has been established that not table field motion and
19608 not visibility should be done because of current context. This is probably
19609 the place where a package like yasnippets can hook in.")
19611 (defvar org-tab-before-tab-emulation-hook nil
19612 "Hook for functions to attach themselves to TAB.
19613 See `org-ctrl-c-ctrl-c-hook' for more information.
19614 This hook runs after every other options for TAB have been exhausted, but
19615 before indentation and \t insertion takes place.")
19617 (defvar org-metaleft-hook nil
19618 "Hook for functions attaching themselves to `M-left'.
19619 See `org-ctrl-c-ctrl-c-hook' for more information.")
19620 (defvar org-metaright-hook nil
19621 "Hook for functions attaching themselves to `M-right'.
19622 See `org-ctrl-c-ctrl-c-hook' for more information.")
19623 (defvar org-metaup-hook nil
19624 "Hook for functions attaching themselves to `M-up'.
19625 See `org-ctrl-c-ctrl-c-hook' for more information.")
19626 (defvar org-metadown-hook nil
19627 "Hook for functions attaching themselves to `M-down'.
19628 See `org-ctrl-c-ctrl-c-hook' for more information.")
19629 (defvar org-shiftmetaleft-hook nil
19630 "Hook for functions attaching themselves to `M-S-left'.
19631 See `org-ctrl-c-ctrl-c-hook' for more information.")
19632 (defvar org-shiftmetaright-hook nil
19633 "Hook for functions attaching themselves to `M-S-right'.
19634 See `org-ctrl-c-ctrl-c-hook' for more information.")
19635 (defvar org-shiftmetaup-hook nil
19636 "Hook for functions attaching themselves to `M-S-up'.
19637 See `org-ctrl-c-ctrl-c-hook' for more information.")
19638 (defvar org-shiftmetadown-hook nil
19639 "Hook for functions attaching themselves to `M-S-down'.
19640 See `org-ctrl-c-ctrl-c-hook' for more information.")
19641 (defvar org-metareturn-hook nil
19642 "Hook for functions attaching themselves to `M-RET'.
19643 See `org-ctrl-c-ctrl-c-hook' for more information.")
19644 (defvar org-shiftup-hook nil
19645 "Hook for functions attaching themselves to `S-up'.
19646 See `org-ctrl-c-ctrl-c-hook' for more information.")
19647 (defvar org-shiftup-final-hook nil
19648 "Hook for functions attaching themselves to `S-up'.
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-shiftdown-hook nil
19652 "Hook for functions attaching themselves to `S-down'.
19653 See `org-ctrl-c-ctrl-c-hook' for more information.")
19654 (defvar org-shiftdown-final-hook nil
19655 "Hook for functions attaching themselves to `S-down'.
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.")
19658 (defvar org-shiftleft-hook nil
19659 "Hook for functions attaching themselves to `S-left'.
19660 See `org-ctrl-c-ctrl-c-hook' for more information.")
19661 (defvar org-shiftleft-final-hook nil
19662 "Hook for functions attaching themselves to `S-left'.
19663 This one runs after all other options except shift-select have been excluded.
19664 See `org-ctrl-c-ctrl-c-hook' for more information.")
19665 (defvar org-shiftright-hook nil
19666 "Hook for functions attaching themselves to `S-right'.
19667 See `org-ctrl-c-ctrl-c-hook' for more information.")
19668 (defvar org-shiftright-final-hook nil
19669 "Hook for functions attaching themselves to `S-right'.
19670 This one runs after all other options except shift-select have been excluded.
19671 See `org-ctrl-c-ctrl-c-hook' for more information.")
19673 (defun org-modifier-cursor-error ()
19674 "Throw an error, a modified cursor command was applied in wrong context."
19675 (user-error "This command is active in special context like tables, headlines or items"))
19677 (defun org-shiftselect-error ()
19678 "Throw an error because Shift-Cursor command was applied in wrong context."
19679 (if (and (boundp 'shift-select-mode) shift-select-mode)
19680 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19681 (user-error "This command works only in special context like headlines or timestamps")))
19683 (defun org-call-for-shift-select (cmd)
19684 (let ((this-command-keys-shift-translated t))
19685 (call-interactively cmd)))
19687 (defun org-shifttab (&optional arg)
19688 "Global visibility cycling or move to previous table field.
19689 Call `org-table-previous-field' within a table.
19690 When ARG is nil, cycle globally through visibility states.
19691 When ARG is a numeric prefix, show contents of this level."
19692 (interactive "P")
19693 (cond
19694 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19695 ((integerp arg)
19696 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19697 (message "Content view to level: %d" arg)
19698 (org-content (prefix-numeric-value arg2))
19699 (org-cycle-show-empty-lines t)
19700 (setq org-cycle-global-status 'overview)))
19701 (t (call-interactively 'org-global-cycle))))
19703 (defun org-shiftmetaleft ()
19704 "Promote subtree or delete table column.
19705 Calls `org-promote-subtree', `org-outdent-item-tree', or
19706 `org-table-delete-column', depending on context. See the
19707 individual commands for more information."
19708 (interactive)
19709 (cond
19710 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19711 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19712 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19713 ((if (not (org-region-active-p)) (org-at-item-p)
19714 (save-excursion (goto-char (region-beginning))
19715 (org-at-item-p)))
19716 (call-interactively 'org-outdent-item-tree))
19717 (t (org-modifier-cursor-error))))
19719 (defun org-shiftmetaright ()
19720 "Demote subtree or insert table column.
19721 Calls `org-demote-subtree', `org-indent-item-tree', or
19722 `org-table-insert-column', depending on context. See the
19723 individual commands for more information."
19724 (interactive)
19725 (cond
19726 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19727 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19728 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19729 ((if (not (org-region-active-p)) (org-at-item-p)
19730 (save-excursion (goto-char (region-beginning))
19731 (org-at-item-p)))
19732 (call-interactively 'org-indent-item-tree))
19733 (t (org-modifier-cursor-error))))
19735 (defun org-shiftmetaup (&optional arg)
19736 "Move subtree up or kill table row.
19737 Calls `org-move-subtree-up' or `org-table-kill-row' or
19738 `org-move-item-up' or `org-timestamp-up', depending on context.
19739 See the individual commands for more information."
19740 (interactive "P")
19741 (cond
19742 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19743 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19744 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19745 ((org-at-item-p) (call-interactively 'org-move-item-up))
19746 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19747 (call-interactively 'org-timestamp-up)))
19748 (t (call-interactively 'org-drag-line-backward))))
19750 (defun org-shiftmetadown (&optional arg)
19751 "Move subtree down or insert table row.
19752 Calls `org-move-subtree-down' or `org-table-insert-row' or
19753 `org-move-item-down' or `org-timestamp-up', depending on context.
19754 See the individual commands for more information."
19755 (interactive "P")
19756 (cond
19757 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19758 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19759 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19760 ((org-at-item-p) (call-interactively 'org-move-item-down))
19761 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19762 (call-interactively 'org-timestamp-down)))
19763 (t (call-interactively 'org-drag-line-forward))))
19765 (defsubst org-hidden-tree-error ()
19766 (user-error
19767 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19769 (defun org-metaleft (&optional arg)
19770 "Promote heading or move table column to left.
19771 Calls `org-do-promote' or `org-table-move-column', depending on context.
19772 With no specific context, calls the Emacs default `backward-word'.
19773 See the individual commands for more information."
19774 (interactive "P")
19775 (cond
19776 ((run-hook-with-args-until-success 'org-metaleft-hook))
19777 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19778 ((org-with-limited-levels
19779 (or (org-at-heading-p)
19780 (and (org-region-active-p)
19781 (save-excursion
19782 (goto-char (region-beginning))
19783 (org-at-heading-p)))))
19784 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19785 (call-interactively 'org-do-promote))
19786 ;; At an inline task.
19787 ((org-at-heading-p)
19788 (call-interactively 'org-inlinetask-promote))
19789 ((or (org-at-item-p)
19790 (and (org-region-active-p)
19791 (save-excursion
19792 (goto-char (region-beginning))
19793 (org-at-item-p))))
19794 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19795 (call-interactively 'org-outdent-item))
19796 (t (call-interactively 'backward-word))))
19798 (defun org-metaright (&optional arg)
19799 "Demote a subtree, a list item or move table column to right.
19800 In front of a drawer or a block keyword, indent it correctly.
19801 With no specific context, calls the Emacs default `forward-word'.
19802 See the individual commands for more information."
19803 (interactive "P")
19804 (cond
19805 ((run-hook-with-args-until-success 'org-metaright-hook))
19806 ((org-at-table-p) (call-interactively 'org-table-move-column))
19807 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19808 ((org-at-block-p) (call-interactively 'org-indent-block))
19809 ((org-with-limited-levels
19810 (or (org-at-heading-p)
19811 (and (org-region-active-p)
19812 (save-excursion
19813 (goto-char (region-beginning))
19814 (org-at-heading-p)))))
19815 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19816 (call-interactively 'org-do-demote))
19817 ;; At an inline task.
19818 ((org-at-heading-p)
19819 (call-interactively 'org-inlinetask-demote))
19820 ((or (org-at-item-p)
19821 (and (org-region-active-p)
19822 (save-excursion
19823 (goto-char (region-beginning))
19824 (org-at-item-p))))
19825 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19826 (call-interactively 'org-indent-item))
19827 (t (call-interactively 'forward-word))))
19829 (defun org-check-for-hidden (what)
19830 "Check if there are hidden headlines/items in the current visual line.
19831 WHAT can be either `headlines' or `items'. If the current line is
19832 an outline or item heading and it has a folded subtree below it,
19833 this function returns t, nil otherwise."
19834 (let ((re (cond
19835 ((eq what 'headlines) org-outline-regexp-bol)
19836 ((eq what 'items) (org-item-beginning-re))
19837 (t (error "This should not happen"))))
19838 beg end)
19839 (save-excursion
19840 (catch 'exit
19841 (unless (org-region-active-p)
19842 (setq beg (point-at-bol))
19843 (beginning-of-line 2)
19844 (while (and (not (eobp)) ;; this is like `next-line'
19845 (get-char-property (1- (point)) 'invisible))
19846 (beginning-of-line 2))
19847 (setq end (point))
19848 (goto-char beg)
19849 (goto-char (point-at-eol))
19850 (setq end (max end (point)))
19851 (while (re-search-forward re end t)
19852 (if (get-char-property (match-beginning 0) 'invisible)
19853 (throw 'exit t))))
19854 nil))))
19856 (defun org-metaup (&optional arg)
19857 "Move subtree up or move table row up.
19858 Calls `org-move-subtree-up' or `org-table-move-row' or
19859 `org-move-item-up', depending on context. See the individual commands
19860 for more information."
19861 (interactive "P")
19862 (cond
19863 ((run-hook-with-args-until-success 'org-metaup-hook))
19864 ((org-region-active-p)
19865 (let* ((a (min (region-beginning) (region-end)))
19866 (b (1- (max (region-beginning) (region-end))))
19867 (c (save-excursion (goto-char a)
19868 (move-beginning-of-line 0)))
19869 (d (save-excursion (goto-char a)
19870 (move-end-of-line 0) (point))))
19871 (transpose-regions a b c d)
19872 (goto-char c)))
19873 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19874 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19875 ((org-at-item-p) (call-interactively 'org-move-item-up))
19876 (t (org-drag-element-backward))))
19878 (defun org-metadown (&optional arg)
19879 "Move subtree down or move table row down.
19880 Calls `org-move-subtree-down' or `org-table-move-row' or
19881 `org-move-item-down', depending on context. See the individual
19882 commands for more information."
19883 (interactive "P")
19884 (cond
19885 ((run-hook-with-args-until-success 'org-metadown-hook))
19886 ((org-region-active-p)
19887 (let* ((a (min (region-beginning) (region-end)))
19888 (b (max (region-beginning) (region-end)))
19889 (c (save-excursion (goto-char b)
19890 (move-beginning-of-line 1)))
19891 (d (save-excursion (goto-char b)
19892 (move-end-of-line 1) (1+ (point)))))
19893 (transpose-regions a b c d)
19894 (goto-char d)))
19895 ((org-at-table-p) (call-interactively 'org-table-move-row))
19896 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19897 ((org-at-item-p) (call-interactively 'org-move-item-down))
19898 (t (org-drag-element-forward))))
19900 (defun org-shiftup (&optional arg)
19901 "Increase item in timestamp or increase priority of current headline.
19902 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19903 depending on context. See the individual commands for more information."
19904 (interactive "P")
19905 (cond
19906 ((run-hook-with-args-until-success 'org-shiftup-hook))
19907 ((and org-support-shift-select (org-region-active-p))
19908 (org-call-for-shift-select 'previous-line))
19909 ((org-at-timestamp-p t)
19910 (call-interactively (if org-edit-timestamp-down-means-later
19911 'org-timestamp-down 'org-timestamp-up)))
19912 ((and (not (eq org-support-shift-select 'always))
19913 org-enable-priority-commands
19914 (org-at-heading-p))
19915 (call-interactively 'org-priority-up))
19916 ((and (not org-support-shift-select) (org-at-item-p))
19917 (call-interactively 'org-previous-item))
19918 ((org-clocktable-try-shift 'up arg))
19919 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19920 (org-support-shift-select
19921 (org-call-for-shift-select 'previous-line))
19922 (t (org-shiftselect-error))))
19924 (defun org-shiftdown (&optional arg)
19925 "Decrease item in timestamp or decrease priority of current headline.
19926 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19927 depending on context. See the individual commands for more information."
19928 (interactive "P")
19929 (cond
19930 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19931 ((and org-support-shift-select (org-region-active-p))
19932 (org-call-for-shift-select 'next-line))
19933 ((org-at-timestamp-p t)
19934 (call-interactively (if org-edit-timestamp-down-means-later
19935 'org-timestamp-up 'org-timestamp-down)))
19936 ((and (not (eq org-support-shift-select 'always))
19937 org-enable-priority-commands
19938 (org-at-heading-p))
19939 (call-interactively 'org-priority-down))
19940 ((and (not org-support-shift-select) (org-at-item-p))
19941 (call-interactively 'org-next-item))
19942 ((org-clocktable-try-shift 'down arg))
19943 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19944 (org-support-shift-select
19945 (org-call-for-shift-select 'next-line))
19946 (t (org-shiftselect-error))))
19948 (defun org-shiftright (&optional arg)
19949 "Cycle the thing at point or in the current line, depending on context.
19950 Depending on context, this does one of the following:
19952 - switch a timestamp at point one day into the future
19953 - on a headline, switch to the next TODO keyword.
19954 - on an item, switch entire list to the next bullet type
19955 - on a property line, switch to the next allowed value
19956 - on a clocktable definition line, move time block into the future"
19957 (interactive "P")
19958 (cond
19959 ((run-hook-with-args-until-success 'org-shiftright-hook))
19960 ((and org-support-shift-select (org-region-active-p))
19961 (org-call-for-shift-select 'forward-char))
19962 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19963 ((and (not (eq org-support-shift-select 'always))
19964 (org-at-heading-p))
19965 (let ((org-inhibit-logging
19966 (not org-treat-S-cursor-todo-selection-as-state-change))
19967 (org-inhibit-blocking
19968 (not org-treat-S-cursor-todo-selection-as-state-change)))
19969 (org-call-with-arg 'org-todo 'right)))
19970 ((or (and org-support-shift-select
19971 (not (eq org-support-shift-select 'always))
19972 (org-at-item-bullet-p))
19973 (and (not org-support-shift-select) (org-at-item-p)))
19974 (org-call-with-arg 'org-cycle-list-bullet nil))
19975 ((and (not (eq org-support-shift-select 'always))
19976 (org-at-property-p))
19977 (call-interactively 'org-property-next-allowed-value))
19978 ((org-clocktable-try-shift 'right arg))
19979 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19980 (org-support-shift-select
19981 (org-call-for-shift-select 'forward-char))
19982 (t (org-shiftselect-error))))
19984 (defun org-shiftleft (&optional arg)
19985 "Cycle the thing at point or in the current line, depending on context.
19986 Depending on context, this does one of the following:
19988 - switch a timestamp at point one day into the past
19989 - on a headline, switch to the previous TODO keyword.
19990 - on an item, switch entire list to the previous bullet type
19991 - on a property line, switch to the previous allowed value
19992 - on a clocktable definition line, move time block into the past"
19993 (interactive "P")
19994 (cond
19995 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19996 ((and org-support-shift-select (org-region-active-p))
19997 (org-call-for-shift-select 'backward-char))
19998 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19999 ((and (not (eq org-support-shift-select 'always))
20000 (org-at-heading-p))
20001 (let ((org-inhibit-logging
20002 (not org-treat-S-cursor-todo-selection-as-state-change))
20003 (org-inhibit-blocking
20004 (not org-treat-S-cursor-todo-selection-as-state-change)))
20005 (org-call-with-arg 'org-todo 'left)))
20006 ((or (and org-support-shift-select
20007 (not (eq org-support-shift-select 'always))
20008 (org-at-item-bullet-p))
20009 (and (not org-support-shift-select) (org-at-item-p)))
20010 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20011 ((and (not (eq org-support-shift-select 'always))
20012 (org-at-property-p))
20013 (call-interactively 'org-property-previous-allowed-value))
20014 ((org-clocktable-try-shift 'left arg))
20015 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20016 (org-support-shift-select
20017 (org-call-for-shift-select 'backward-char))
20018 (t (org-shiftselect-error))))
20020 (defun org-shiftcontrolright ()
20021 "Switch to next TODO set."
20022 (interactive)
20023 (cond
20024 ((and org-support-shift-select (org-region-active-p))
20025 (org-call-for-shift-select 'forward-word))
20026 ((and (not (eq org-support-shift-select 'always))
20027 (org-at-heading-p))
20028 (org-call-with-arg 'org-todo 'nextset))
20029 (org-support-shift-select
20030 (org-call-for-shift-select 'forward-word))
20031 (t (org-shiftselect-error))))
20033 (defun org-shiftcontrolleft ()
20034 "Switch to previous TODO set."
20035 (interactive)
20036 (cond
20037 ((and org-support-shift-select (org-region-active-p))
20038 (org-call-for-shift-select 'backward-word))
20039 ((and (not (eq org-support-shift-select 'always))
20040 (org-at-heading-p))
20041 (org-call-with-arg 'org-todo 'previousset))
20042 (org-support-shift-select
20043 (org-call-for-shift-select 'backward-word))
20044 (t (org-shiftselect-error))))
20046 (defun org-shiftcontrolup (&optional n)
20047 "Change timestamps synchronously up in CLOCK log lines.
20048 Optional argument N tells to change by that many units."
20049 (interactive "P")
20050 (cond ((and (not org-support-shift-select)
20051 (org-at-clock-log-p)
20052 (org-at-timestamp-p t))
20053 (org-clock-timestamps-up n))
20054 (t (org-shiftselect-error))))
20056 (defun org-shiftcontroldown (&optional n)
20057 "Change timestamps synchronously down in CLOCK log lines.
20058 Optional argument N tells to change by that many units."
20059 (interactive "P")
20060 (cond ((and (not org-support-shift-select)
20061 (org-at-clock-log-p)
20062 (org-at-timestamp-p t))
20063 (org-clock-timestamps-down n))
20064 (t (org-shiftselect-error))))
20066 (defun org-ctrl-c-ret ()
20067 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20068 (interactive)
20069 (cond
20070 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20071 (t (call-interactively 'org-insert-heading))))
20073 (defun org-find-visible ()
20074 (let ((s (point)))
20075 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20076 (get-char-property s 'invisible)))
20078 (defun org-find-invisible ()
20079 (let ((s (point)))
20080 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20081 (not (get-char-property s 'invisible))))
20084 (defun org-copy-visible (beg end)
20085 "Copy the visible parts of the region."
20086 (interactive "r")
20087 (let (snippets s)
20088 (save-excursion
20089 (save-restriction
20090 (narrow-to-region beg end)
20091 (setq s (goto-char (point-min)))
20092 (while (not (= (point) (point-max)))
20093 (goto-char (org-find-invisible))
20094 (push (buffer-substring s (point)) snippets)
20095 (setq s (goto-char (org-find-visible))))))
20096 (kill-new (apply 'concat (nreverse snippets)))))
20098 (defun org-copy-special ()
20099 "Copy region in table or copy current subtree.
20100 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20101 See the individual commands for more information."
20102 (interactive)
20103 (call-interactively
20104 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20106 (defun org-cut-special ()
20107 "Cut region in table or cut current subtree.
20108 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20109 See the individual commands for more information."
20110 (interactive)
20111 (call-interactively
20112 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20114 (defun org-paste-special (arg)
20115 "Paste rectangular region into table, or past subtree relative to level.
20116 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20117 See the individual commands for more information."
20118 (interactive "P")
20119 (if (org-at-table-p)
20120 (org-table-paste-rectangle)
20121 (org-paste-subtree arg)))
20123 (defsubst org-in-fixed-width-region-p ()
20124 "Is point in a fixed-width region?"
20125 (save-match-data
20126 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20128 (defun org-edit-special (&optional arg)
20129 "Call a special editor for the element at point.
20130 When at a table, call the formula editor with `org-table-edit-formulas'.
20131 When in a source code block, call `org-edit-src-code'.
20132 When in a fixed-width region, call `org-edit-fixed-width-region'.
20133 When at an #+INCLUDE keyword, visit the included file.
20134 On a link, call `ffap' to visit the link at point.
20135 Otherwise, return a user error."
20136 (interactive "P")
20137 (let ((element (org-element-at-point)))
20138 (assert (not buffer-read-only) nil
20139 "Buffer is read-only: %s" (buffer-name))
20140 (case (org-element-type element)
20141 (src-block
20142 (if (not arg) (org-edit-src-code)
20143 (let* ((info (org-babel-get-src-block-info))
20144 (lang (nth 0 info))
20145 (params (nth 2 info))
20146 (session (cdr (assq :session params))))
20147 (if (not session) (org-edit-src-code)
20148 ;; At a src-block with a session and function called with
20149 ;; an ARG: switch to the buffer related to the inferior
20150 ;; process.
20151 (switch-to-buffer
20152 (funcall (intern (concat "org-babel-prep-session:" lang))
20153 session params))))))
20154 (keyword
20155 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20156 (find-file
20157 (org-remove-double-quotes
20158 (car (org-split-string (org-element-property :value element)))))
20159 (user-error "No special environment to edit here")))
20160 (table
20161 (if (eq (org-element-property :type element) 'table.el)
20162 (org-edit-src-code)
20163 (call-interactively 'org-table-edit-formulas)))
20164 ;; Only Org tables contain `table-row' type elements.
20165 (table-row (call-interactively 'org-table-edit-formulas))
20166 ((example-block export-block) (org-edit-src-code))
20167 (fixed-width (org-edit-fixed-width-region))
20168 (otherwise
20169 ;; No notable element at point. Though, we may be at a link,
20170 ;; which is an object. Thus, scan deeper.
20171 (if (eq (org-element-type (org-element-context element)) 'link)
20172 (call-interactively 'ffap)
20173 (user-error "No special environment to edit here"))))))
20175 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20176 (defun org-ctrl-c-ctrl-c (&optional arg)
20177 "Set tags in headline, or update according to changed information at point.
20179 This command does many different things, depending on context:
20181 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20182 this is what we do.
20184 - If the cursor is on a statistics cookie, update it.
20186 - If the cursor is in a headline, prompt for tags and insert them
20187 into the current line, aligned to `org-tags-column'. When called
20188 with prefix arg, realign all tags in the current buffer.
20190 - If the cursor is in one of the special #+KEYWORD lines, this
20191 triggers scanning the buffer for these lines and updating the
20192 information.
20194 - If the cursor is inside a table, realign the table. This command
20195 works even if the automatic table editor has been turned off.
20197 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20198 the entire table.
20200 - If the cursor is at a footnote reference or definition, jump to
20201 the corresponding definition or references, respectively.
20203 - If the cursor is a the beginning of a dynamic block, update it.
20205 - If the current buffer is a capture buffer, close note and file it.
20207 - If the cursor is on a <<<target>>>, update radio targets and
20208 corresponding links in this buffer.
20210 - If the cursor is on a numbered item in a plain list, renumber the
20211 ordered list.
20213 - If the cursor is on a checkbox, toggle it.
20215 - If the cursor is on a code block, evaluate it. The variable
20216 `org-confirm-babel-evaluate' can be used to control prompting
20217 before code block evaluation, by default every code block
20218 evaluation requires confirmation. Code block evaluation can be
20219 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20220 (interactive "P")
20221 (cond
20222 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20223 org-occur-highlights
20224 org-latex-fragment-image-overlays)
20225 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20226 (org-remove-occur-highlights)
20227 (org-remove-latex-fragment-image-overlays)
20228 (message "Temporary highlights/overlays removed from current buffer"))
20229 ((and (local-variable-p 'org-finish-function (current-buffer))
20230 (fboundp org-finish-function))
20231 (funcall org-finish-function))
20232 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20234 (let* ((context (org-element-context)) (type (org-element-type context)))
20235 ;; Test if point is within a blank line.
20236 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20237 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20238 (user-error "C-c C-c can do nothing useful at this location"))
20239 ;; When at a link, act according to the parent instead.
20240 (when (eq type 'link)
20241 (setq context (org-element-property :parent context))
20242 (setq type (org-element-type context)))
20243 ;; For convenience: at the first line of a paragraph on the
20244 ;; same line as an item, apply function on that item instead.
20245 (when (eq type 'paragraph)
20246 (let ((parent (org-element-property :parent context)))
20247 (when (and (eq (org-element-type parent) 'item)
20248 (= (point-at-bol) (org-element-property :begin parent)))
20249 (setq context parent type 'item))))
20250 ;; Act according to type of element or object at point.
20251 (case type
20252 (clock (org-clock-update-time-maybe))
20253 (dynamic-block
20254 (save-excursion
20255 (goto-char (org-element-property :post-affiliated context))
20256 (org-update-dblock)))
20257 (footnote-definition
20258 (goto-char (org-element-property :post-affiliated context))
20259 (call-interactively 'org-footnote-action))
20260 (footnote-reference (call-interactively 'org-footnote-action))
20261 ((headline inlinetask)
20262 (save-excursion (goto-char (org-element-property :begin context))
20263 (call-interactively 'org-set-tags)))
20264 (item
20265 ;; At an item: a double C-u set checkbox to "[-]"
20266 ;; unconditionally, whereas a single one will toggle its
20267 ;; presence. Without an universal argument, if the item
20268 ;; has a checkbox, toggle it. Otherwise repair the list.
20269 (let* ((box (org-element-property :checkbox context))
20270 (struct (org-element-property :structure context))
20271 (old-struct (copy-tree struct))
20272 (parents (org-list-parents-alist struct))
20273 (prevs (org-list-prevs-alist struct))
20274 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20275 (org-list-set-checkbox
20276 (org-element-property :begin context) struct
20277 (cond ((equal arg '(16)) "[-]")
20278 ((and (not box) (equal arg '(4))) "[ ]")
20279 ((or (not box) (equal arg '(4))) nil)
20280 ((eq box 'on) "[ ]")
20281 (t "[X]")))
20282 ;; Mimic `org-list-write-struct' but with grabbing
20283 ;; a return value from `org-list-struct-fix-box'.
20284 (org-list-struct-fix-ind struct parents 2)
20285 (org-list-struct-fix-item-end struct)
20286 (org-list-struct-fix-bul struct prevs)
20287 (org-list-struct-fix-ind struct parents)
20288 (let ((block-item
20289 (org-list-struct-fix-box struct parents prevs orderedp)))
20290 (if (and box (equal struct old-struct))
20291 (if (equal arg '(16))
20292 (message "Checkboxes already reset")
20293 (user-error "Cannot toggle this checkbox: %s"
20294 (if (eq box 'on)
20295 "all subitems checked"
20296 "unchecked subitems")))
20297 (org-list-struct-apply-struct struct old-struct)
20298 (org-update-checkbox-count-maybe))
20299 (when block-item
20300 (message "Checkboxes were removed due to empty box at line %d"
20301 (org-current-line block-item))))))
20302 (keyword
20303 (let ((org-inhibit-startup-visibility-stuff t)
20304 (org-startup-align-all-tables nil))
20305 (when (boundp 'org-table-coordinate-overlays)
20306 (mapc 'delete-overlay org-table-coordinate-overlays)
20307 (setq org-table-coordinate-overlays nil))
20308 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20309 (message "Local setup has been refreshed"))
20310 (plain-list
20311 ;; At a plain list, with a double C-u argument, set
20312 ;; checkboxes of each item to "[-]", whereas a single one
20313 ;; will toggle their presence according to the state of the
20314 ;; first item in the list. Without an argument, repair the
20315 ;; list.
20316 (let* ((begin (org-element-property :contents-begin context))
20317 (beginm (move-marker (make-marker) begin))
20318 (struct (org-element-property :structure context))
20319 (old-struct (copy-tree struct))
20320 (first-box (save-excursion
20321 (goto-char begin)
20322 (looking-at org-list-full-item-re)
20323 (match-string-no-properties 3)))
20324 (new-box (cond ((equal arg '(16)) "[-]")
20325 ((equal arg '(4)) (unless first-box "[ ]"))
20326 ((equal first-box "[X]") "[ ]")
20327 (t "[X]"))))
20328 (cond
20329 (arg
20330 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20331 (org-list-get-all-items
20332 begin struct (org-list-prevs-alist struct))))
20333 ((and first-box (eq (point) begin))
20334 ;; For convenience, when point is at bol on the first
20335 ;; item of the list and no argument is provided, simply
20336 ;; toggle checkbox of that item, if any.
20337 (org-list-set-checkbox begin struct new-box)))
20338 (org-list-write-struct
20339 struct (org-list-parents-alist struct) old-struct)
20340 (org-update-checkbox-count-maybe)
20341 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20342 ((property-drawer node-property)
20343 (call-interactively 'org-property-action))
20344 ((radio-target target)
20345 (call-interactively 'org-update-radio-target-regexp))
20346 (statistics-cookie
20347 (call-interactively 'org-update-statistics-cookies))
20348 ((table table-cell table-row)
20349 ;; At a table, recalculate every field and align it. Also
20350 ;; send the table if necessary. If the table has
20351 ;; a `table.el' type, just give up. At a table row or
20352 ;; cell, maybe recalculate line but always align table.
20353 (if (eq (org-element-property :type context) 'table.el)
20354 (message "Use C-c ' to edit table.el tables")
20355 (let ((org-enable-table-editor t))
20356 (if (or (eq type 'table)
20357 ;; Check if point is at a TBLFM line.
20358 (and (eq type 'table-row)
20359 (= (point) (org-element-property :end context))))
20360 (save-excursion
20361 (if (org-at-TBLFM-p)
20362 (progn (require 'org-table)
20363 (org-table-calc-current-TBLFM))
20364 (goto-char (org-element-property :contents-begin context))
20365 (org-call-with-arg 'org-table-recalculate (or arg t))
20366 (orgtbl-send-table 'maybe)))
20367 (org-table-maybe-eval-formula)
20368 (cond (arg (call-interactively 'org-table-recalculate))
20369 ((org-table-maybe-recalculate-line))
20370 (t (org-table-align)))))))
20371 (timestamp (org-timestamp-change 0 'day))
20372 (otherwise
20373 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20374 (user-error
20375 "C-c C-c can do nothing useful at this location")))))))))
20377 (defun org-mode-restart ()
20378 "Restart Org-mode, to scan again for special lines.
20379 Also updates the keyword regular expressions."
20380 (interactive)
20381 (org-mode)
20382 (message "Org-mode restarted"))
20384 (defun org-kill-note-or-show-branches ()
20385 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20386 (interactive)
20387 (if (not org-finish-function)
20388 (progn
20389 (hide-subtree)
20390 (call-interactively 'show-branches))
20391 (let ((org-note-abort t))
20392 (funcall org-finish-function))))
20394 (defun org-open-line (n)
20395 "Insert a new row in tables, call `open-line' elsewhere.
20396 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20397 (interactive "*p")
20398 (cond
20399 ((not org-special-ctrl-o)
20400 (open-line n))
20401 ((org-at-table-p)
20402 (org-table-insert-row))
20404 (open-line n))))
20406 (defun org-return (&optional indent)
20407 "Goto next table row or insert a newline.
20408 Calls `org-table-next-row' or `newline', depending on context.
20409 See the individual commands for more information."
20410 (interactive)
20411 (let (org-ts-what)
20412 (cond
20413 ((or (bobp) (org-in-src-block-p))
20414 (if indent (newline-and-indent) (newline)))
20415 ((org-at-table-p)
20416 (org-table-justify-field-maybe)
20417 (call-interactively 'org-table-next-row))
20418 ;; when `newline-and-indent' is called within a list, make sure
20419 ;; text moved stays inside the item.
20420 ((and (org-in-item-p) indent)
20421 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20422 (progn
20423 (save-match-data (newline))
20424 (org-indent-line-to (length (match-string 0))))
20425 (let ((ind (org-get-indentation)))
20426 (newline)
20427 (if (org-looking-back org-list-end-re)
20428 (org-indent-line)
20429 (org-indent-line-to ind)))))
20430 ((and org-return-follows-link
20431 (org-at-timestamp-p t)
20432 (not (eq org-ts-what 'after)))
20433 (org-follow-timestamp-link))
20434 ((and org-return-follows-link
20435 (let ((tprop (get-text-property (point) 'face)))
20436 (or (eq tprop 'org-link)
20437 (and (listp tprop) (memq 'org-link tprop)))))
20438 (call-interactively 'org-open-at-point))
20439 ((and (org-at-heading-p)
20440 (looking-at
20441 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20442 (org-show-entry)
20443 (end-of-line 1)
20444 (newline))
20445 (t (if indent (newline-and-indent) (newline))))))
20447 (defun org-return-indent ()
20448 "Goto next table row or insert a newline and indent.
20449 Calls `org-table-next-row' or `newline-and-indent', depending on
20450 context. See the individual commands for more information."
20451 (interactive)
20452 (org-return t))
20454 (defun org-ctrl-c-star ()
20455 "Compute table, or change heading status of lines.
20456 Calls `org-table-recalculate' or `org-toggle-heading',
20457 depending on context."
20458 (interactive)
20459 (cond
20460 ((org-at-table-p)
20461 (call-interactively 'org-table-recalculate))
20463 ;; Convert all lines in region to list items
20464 (call-interactively 'org-toggle-heading))))
20466 (defun org-ctrl-c-minus ()
20467 "Insert separator line in table or modify bullet status of line.
20468 Also turns a plain line or a region of lines into list items.
20469 Calls `org-table-insert-hline', `org-toggle-item', or
20470 `org-cycle-list-bullet', depending on context."
20471 (interactive)
20472 (cond
20473 ((org-at-table-p)
20474 (call-interactively 'org-table-insert-hline))
20475 ((org-region-active-p)
20476 (call-interactively 'org-toggle-item))
20477 ((org-in-item-p)
20478 (call-interactively 'org-cycle-list-bullet))
20480 (call-interactively 'org-toggle-item))))
20482 (defun org-toggle-item (arg)
20483 "Convert headings or normal lines to items, items to normal lines.
20484 If there is no active region, only the current line is considered.
20486 If the first non blank line in the region is a headline, convert
20487 all headlines to items, shifting text accordingly.
20489 If it is an item, convert all items to normal lines.
20491 If it is normal text, change region into a list of items.
20492 With a prefix argument ARG, change the region in a single item."
20493 (interactive "P")
20494 (let ((shift-text
20495 (function
20496 ;; Shift text in current section to IND, from point to END.
20497 ;; The function leaves point to END line.
20498 (lambda (ind end)
20499 (let ((min-i 1000) (end (copy-marker end)))
20500 ;; First determine the minimum indentation (MIN-I) of
20501 ;; the text.
20502 (save-excursion
20503 (catch 'exit
20504 (while (< (point) end)
20505 (let ((i (org-get-indentation)))
20506 (cond
20507 ;; Skip blank lines and inline tasks.
20508 ((looking-at "^[ \t]*$"))
20509 ((looking-at org-outline-regexp-bol))
20510 ;; We can't find less than 0 indentation.
20511 ((zerop i) (throw 'exit (setq min-i 0)))
20512 ((< i min-i) (setq min-i i))))
20513 (forward-line))))
20514 ;; Then indent each line so that a line indented to
20515 ;; MIN-I becomes indented to IND. Ignore blank lines
20516 ;; and inline tasks in the process.
20517 (let ((delta (- ind min-i)))
20518 (while (< (point) end)
20519 (unless (or (looking-at "^[ \t]*$")
20520 (looking-at org-outline-regexp-bol))
20521 (org-indent-line-to (+ (org-get-indentation) delta)))
20522 (forward-line)))))))
20523 (skip-blanks
20524 (function
20525 ;; Return beginning of first non-blank line, starting from
20526 ;; line at POS.
20527 (lambda (pos)
20528 (save-excursion
20529 (goto-char pos)
20530 (skip-chars-forward " \r\t\n")
20531 (point-at-bol)))))
20532 beg end)
20533 ;; Determine boundaries of changes.
20534 (if (org-region-active-p)
20535 (setq beg (funcall skip-blanks (region-beginning))
20536 end (copy-marker (region-end)))
20537 (setq beg (funcall skip-blanks (point-at-bol))
20538 end (copy-marker (point-at-eol))))
20539 ;; Depending on the starting line, choose an action on the text
20540 ;; between BEG and END.
20541 (org-with-limited-levels
20542 (save-excursion
20543 (goto-char beg)
20544 (cond
20545 ;; Case 1. Start at an item: de-itemize. Note that it only
20546 ;; happens when a region is active: `org-ctrl-c-minus'
20547 ;; would call `org-cycle-list-bullet' otherwise.
20548 ((org-at-item-p)
20549 (while (< (point) end)
20550 (when (org-at-item-p)
20551 (skip-chars-forward " \t")
20552 (delete-region (point) (match-end 0)))
20553 (forward-line)))
20554 ;; Case 2. Start at an heading: convert to items.
20555 ((org-at-heading-p)
20556 (let* ((bul (org-list-bullet-string "-"))
20557 (bul-len (length bul))
20558 ;; Indentation of the first heading. It should be
20559 ;; relative to the indentation of its parent, if any.
20560 (start-ind (save-excursion
20561 (cond
20562 ((not org-adapt-indentation) 0)
20563 ((not (outline-previous-heading)) 0)
20564 (t (length (match-string 0))))))
20565 ;; Level of first heading. Further headings will be
20566 ;; compared to it to determine hierarchy in the list.
20567 (ref-level (org-reduced-level (org-outline-level))))
20568 (while (< (point) end)
20569 (let* ((level (org-reduced-level (org-outline-level)))
20570 (delta (max 0 (- level ref-level))))
20571 ;; If current headline is less indented than the first
20572 ;; one, set it as reference, in order to preserve
20573 ;; subtrees.
20574 (when (< level ref-level) (setq ref-level level))
20575 (replace-match bul t t)
20576 (org-indent-line-to (+ start-ind (* delta bul-len)))
20577 ;; Ensure all text down to END (or SECTION-END) belongs
20578 ;; to the newly created item.
20579 (let ((section-end (save-excursion
20580 (or (outline-next-heading) (point)))))
20581 (forward-line)
20582 (funcall shift-text
20583 (+ start-ind (* (1+ delta) bul-len))
20584 (min end section-end)))))))
20585 ;; Case 3. Normal line with ARG: make the first line of region
20586 ;; an item, and shift indentation of others lines to
20587 ;; set them as item's body.
20588 (arg (let* ((bul (org-list-bullet-string "-"))
20589 (bul-len (length bul))
20590 (ref-ind (org-get-indentation)))
20591 (skip-chars-forward " \t")
20592 (insert bul)
20593 (forward-line)
20594 (while (< (point) end)
20595 ;; Ensure that lines less indented than first one
20596 ;; still get included in item body.
20597 (funcall shift-text
20598 (+ ref-ind bul-len)
20599 (min end (save-excursion (or (outline-next-heading)
20600 (point)))))
20601 (forward-line))))
20602 ;; Case 4. Normal line without ARG: turn each non-item line
20603 ;; into an item.
20605 (while (< (point) end)
20606 (unless (or (org-at-heading-p) (org-at-item-p))
20607 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20608 (replace-match
20609 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20610 (forward-line))))))))
20612 (defun org-toggle-heading (&optional nstars)
20613 "Convert headings to normal text, or items or text to headings.
20614 If there is no active region, only convert the current line.
20616 With a \\[universal-argument] prefix, convert the whole list at
20617 point into heading.
20619 In a region:
20621 - If the first non blank line is a headline, remove the stars
20622 from all headlines in the region.
20624 - If it is a normal line, turn each and every normal line (i.e.,
20625 not an heading or an item) in the region into headings. If you
20626 want to convert only the first line of this region, use one
20627 universal prefix argument.
20629 - If it is a plain list item, turn all plain list items into headings.
20631 When converting a line into a heading, the number of stars is chosen
20632 such that the lines become children of the current entry. However,
20633 when a numeric prefix argument is given, its value determines the
20634 number of stars to add."
20635 (interactive "P")
20636 (let ((skip-blanks
20637 (function
20638 ;; Return beginning of first non-blank line, starting from
20639 ;; line at POS.
20640 (lambda (pos)
20641 (save-excursion
20642 (goto-char pos)
20643 (while (org-at-comment-p) (forward-line))
20644 (skip-chars-forward " \r\t\n")
20645 (point-at-bol)))))
20646 beg end toggled)
20647 ;; Determine boundaries of changes. If a universal prefix has
20648 ;; been given, put the list in a region. If region ends at a bol,
20649 ;; do not consider the last line to be in the region.
20651 (when (and current-prefix-arg (org-at-item-p))
20652 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20653 (org-mark-element))
20655 (if (org-region-active-p)
20656 (setq beg (funcall skip-blanks (region-beginning))
20657 end (copy-marker (save-excursion
20658 (goto-char (region-end))
20659 (if (bolp) (point) (point-at-eol)))))
20660 (setq beg (funcall skip-blanks (point-at-bol))
20661 end (copy-marker (point-at-eol))))
20662 ;; Ensure inline tasks don't count as headings.
20663 (org-with-limited-levels
20664 (save-excursion
20665 (goto-char beg)
20666 (cond
20667 ;; Case 1. Started at an heading: de-star headings.
20668 ((org-at-heading-p)
20669 (while (< (point) end)
20670 (when (org-at-heading-p t)
20671 (looking-at org-outline-regexp) (replace-match "")
20672 (setq toggled t))
20673 (forward-line)))
20674 ;; Case 2. Started at an item: change items into headlines.
20675 ;; One star will be added by `org-list-to-subtree'.
20676 ((org-at-item-p)
20677 (let* ((stars (make-string
20678 ;; subtract the star that will be added again by
20679 ;; `org-list-to-subtree'
20680 (if (numberp nstars) (1- nstars)
20681 (or (org-current-level) 0))
20682 ?*))
20683 (add-stars
20684 (cond (nstars "") ; stars from prefix only
20685 ((equal stars "") "") ; before first heading
20686 (org-odd-levels-only "*") ; inside heading, odd
20687 (t "")))) ; inside heading, oddeven
20688 (while (< (point) end)
20689 (when (org-at-item-p)
20690 ;; Pay attention to cases when region ends before list.
20691 (let* ((struct (org-list-struct))
20692 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20693 (save-restriction
20694 (narrow-to-region (point) list-end)
20695 (insert
20696 (org-list-to-subtree
20697 (org-list-parse-list t)
20698 '(:istart (concat stars add-stars (funcall get-stars depth))
20699 :icount (concat stars add-stars (funcall get-stars depth)))))))
20700 (setq toggled t))
20701 (forward-line))))
20702 ;; Case 3. Started at normal text: make every line an heading,
20703 ;; skipping headlines and items.
20704 (t (let* ((stars
20705 (make-string
20706 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20707 (add-stars
20708 (cond (nstars "") ; stars from prefix only
20709 ((equal stars "") "*") ; before first heading
20710 (org-odd-levels-only "**") ; inside heading, odd
20711 (t "*"))) ; inside heading, oddeven
20712 (rpl (concat stars add-stars " "))
20713 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20714 (while (< (point) (if (equal nstars '(4)) lend end))
20715 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20716 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20717 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20718 (forward-line)))))))
20719 (unless toggled (message "Cannot toggle heading from here"))))
20721 (defun org-meta-return (&optional arg)
20722 "Insert a new heading or wrap a region in a table.
20723 Calls `org-insert-heading' or `org-table-wrap-region', depending
20724 on context. See the individual commands for more information."
20725 (interactive "P")
20726 (org-check-before-invisible-edit 'insert)
20727 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20728 (let* ((element (org-element-at-point))
20729 (type (org-element-type element)))
20730 (when (eq type 'table-row)
20731 (setq element (org-element-property :parent element))
20732 (setq type 'table))
20733 (if (and (eq type 'table)
20734 (eq (org-element-property :type element) 'org)
20735 (>= (point) (org-element-property :contents-begin element))
20736 (< (point) (org-element-property :contents-end element)))
20737 (call-interactively 'org-table-wrap-region)
20738 (call-interactively 'org-insert-heading)))))
20740 ;;; Menu entries
20742 (defsubst org-in-subtree-not-table-p ()
20743 "Are we in a subtree and not in a table?"
20744 (and (not (org-before-first-heading-p))
20745 (not (org-at-table-p))))
20747 ;; Define the Org-mode menus
20748 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20749 '("Tbl"
20750 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20751 ["Next Field" org-cycle (org-at-table-p)]
20752 ["Previous Field" org-shifttab (org-at-table-p)]
20753 ["Next Row" org-return (org-at-table-p)]
20754 "--"
20755 ["Blank Field" org-table-blank-field (org-at-table-p)]
20756 ["Edit Field" org-table-edit-field (org-at-table-p)]
20757 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20758 "--"
20759 ("Column"
20760 ["Move Column Left" org-metaleft (org-at-table-p)]
20761 ["Move Column Right" org-metaright (org-at-table-p)]
20762 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20763 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20764 ("Row"
20765 ["Move Row Up" org-metaup (org-at-table-p)]
20766 ["Move Row Down" org-metadown (org-at-table-p)]
20767 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20768 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20769 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20770 "--"
20771 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20772 ("Rectangle"
20773 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20774 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20775 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20776 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20777 "--"
20778 ("Calculate"
20779 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20780 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20781 ["Edit Formulas" org-edit-special (org-at-table-p)]
20782 "--"
20783 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20784 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20785 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20786 "--"
20787 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20788 "--"
20789 ["Sum Column/Rectangle" org-table-sum
20790 (or (org-at-table-p) (org-region-active-p))]
20791 ["Which Column?" org-table-current-column (org-at-table-p)])
20792 ["Debug Formulas"
20793 org-table-toggle-formula-debugger
20794 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20795 ["Show Col/Row Numbers"
20796 org-table-toggle-coordinate-overlays
20797 :style toggle
20798 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20799 "--"
20800 ["Create" org-table-create (and (not (org-at-table-p))
20801 org-enable-table-editor)]
20802 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20803 ["Import from File" org-table-import (not (org-at-table-p))]
20804 ["Export to File" org-table-export (org-at-table-p)]
20805 "--"
20806 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20808 (easy-menu-define org-org-menu org-mode-map "Org menu"
20809 '("Org"
20810 ("Show/Hide"
20811 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20812 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20813 ["Sparse Tree..." org-sparse-tree t]
20814 ["Reveal Context" org-reveal t]
20815 ["Show All" show-all t]
20816 "--"
20817 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20818 "--"
20819 ["New Heading" org-insert-heading t]
20820 ("Navigate Headings"
20821 ["Up" outline-up-heading t]
20822 ["Next" outline-next-visible-heading t]
20823 ["Previous" outline-previous-visible-heading t]
20824 ["Next Same Level" outline-forward-same-level t]
20825 ["Previous Same Level" outline-backward-same-level t]
20826 "--"
20827 ["Jump" org-goto t])
20828 ("Edit Structure"
20829 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20830 "--"
20831 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20832 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20833 "--"
20834 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20835 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20836 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20837 "--"
20838 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20839 "--"
20840 ["Copy visible text" org-copy-visible t]
20841 "--"
20842 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20843 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20844 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20845 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20846 "--"
20847 ["Sort Region/Children" org-sort t]
20848 "--"
20849 ["Convert to odd levels" org-convert-to-odd-levels t]
20850 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20851 ("Editing"
20852 ["Emphasis..." org-emphasize t]
20853 ["Edit Source Example" org-edit-special t]
20854 "--"
20855 ["Footnote new/jump" org-footnote-action t]
20856 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20857 ("Archive"
20858 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20859 "--"
20860 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20861 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20862 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20864 "--"
20865 ("Hyperlinks"
20866 ["Store Link (Global)" org-store-link t]
20867 ["Find existing link to here" org-occur-link-in-agenda-files t]
20868 ["Insert Link" org-insert-link t]
20869 ["Follow Link" org-open-at-point t]
20870 "--"
20871 ["Next link" org-next-link t]
20872 ["Previous link" org-previous-link t]
20873 "--"
20874 ["Descriptive Links"
20875 org-toggle-link-display
20876 :style radio
20877 :selected org-descriptive-links
20879 ["Literal Links"
20880 org-toggle-link-display
20881 :style radio
20882 :selected (not org-descriptive-links)])
20883 "--"
20884 ("TODO Lists"
20885 ["TODO/DONE/-" org-todo t]
20886 ("Select keyword"
20887 ["Next keyword" org-shiftright (org-at-heading-p)]
20888 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20889 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20890 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20891 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20892 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20893 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20894 "--"
20895 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20896 :selected org-enforce-todo-dependencies :style toggle :active t]
20897 "Settings for tree at point"
20898 ["Do Children sequentially" org-toggle-ordered-property :style radio
20899 :selected (org-entry-get nil "ORDERED")
20900 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20901 ["Do Children parallel" org-toggle-ordered-property :style radio
20902 :selected (not (org-entry-get nil "ORDERED"))
20903 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20904 "--"
20905 ["Set Priority" org-priority t]
20906 ["Priority Up" org-shiftup t]
20907 ["Priority Down" org-shiftdown t]
20908 "--"
20909 ["Get news from all feeds" org-feed-update-all t]
20910 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20911 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20912 ("TAGS and Properties"
20913 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20914 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20915 "--"
20916 ["Set property" org-set-property (not (org-before-first-heading-p))]
20917 ["Column view of properties" org-columns t]
20918 ["Insert Column View DBlock" org-insert-columns-dblock t])
20919 ("Dates and Scheduling"
20920 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20921 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20922 ("Change Date"
20923 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20924 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20925 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20926 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20927 ["Compute Time Range" org-evaluate-time-range t]
20928 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20929 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20930 "--"
20931 ["Custom time format" org-toggle-time-stamp-overlays
20932 :style radio :selected org-display-custom-times]
20933 "--"
20934 ["Goto Calendar" org-goto-calendar t]
20935 ["Date from Calendar" org-date-from-calendar t]
20936 "--"
20937 ["Start/Restart Timer" org-timer-start t]
20938 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20939 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20940 ["Insert Timer String" org-timer t]
20941 ["Insert Timer Item" org-timer-item t])
20942 ("Logging work"
20943 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20944 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20945 ["Clock out" org-clock-out t]
20946 ["Clock cancel" org-clock-cancel t]
20947 "--"
20948 ["Mark as default task" org-clock-mark-default-task t]
20949 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20950 ["Goto running clock" org-clock-goto t]
20951 "--"
20952 ["Display times" org-clock-display t]
20953 ["Create clock table" org-clock-report t]
20954 "--"
20955 ["Record DONE time"
20956 (progn (setq org-log-done (not org-log-done))
20957 (message "Switching to %s will %s record a timestamp"
20958 (car org-done-keywords)
20959 (if org-log-done "automatically" "not")))
20960 :style toggle :selected org-log-done])
20961 "--"
20962 ["Agenda Command..." org-agenda t]
20963 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20964 ("File List for Agenda")
20965 ("Special views current file"
20966 ["TODO Tree" org-show-todo-tree t]
20967 ["Check Deadlines" org-check-deadlines t]
20968 ["Timeline" org-timeline t]
20969 ["Tags/Property tree" org-match-sparse-tree t])
20970 "--"
20971 ["Export/Publish..." org-export-dispatch t]
20972 ("LaTeX"
20973 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20974 :selected org-cdlatex-mode]
20975 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20976 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20977 ["Modify math symbol" org-cdlatex-math-modify
20978 (org-inside-LaTeX-fragment-p)]
20979 ["Insert citation" org-reftex-citation t]
20980 "--"
20981 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20982 "--"
20983 ("MobileOrg"
20984 ["Push Files and Views" org-mobile-push t]
20985 ["Get Captured and Flagged" org-mobile-pull t]
20986 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20987 "--"
20988 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20989 "--"
20990 ("Documentation"
20991 ["Show Version" org-version t]
20992 ["Info Documentation" org-info t])
20993 ("Customize"
20994 ["Browse Org Group" org-customize t]
20995 "--"
20996 ["Expand This Menu" org-create-customize-menu
20997 (fboundp 'customize-menu-create)])
20998 ["Send bug report" org-submit-bug-report t]
20999 "--"
21000 ("Refresh/Reload"
21001 ["Refresh setup current buffer" org-mode-restart t]
21002 ["Reload Org (after update)" org-reload t]
21003 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21006 (defun org-info (&optional node)
21007 "Read documentation for Org-mode in the info system.
21008 With optional NODE, go directly to that node."
21009 (interactive)
21010 (info (format "(org)%s" (or node ""))))
21012 ;;;###autoload
21013 (defun org-submit-bug-report ()
21014 "Submit a bug report on Org-mode via mail.
21016 Don't hesitate to report any problems or inaccurate documentation.
21018 If you don't have setup sending mail from (X)Emacs, please copy the
21019 output buffer into your mail program, as it gives us important
21020 information about your Org-mode version and configuration."
21021 (interactive)
21022 (require 'reporter)
21023 (org-load-modules-maybe)
21024 (org-require-autoloaded-modules)
21025 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21026 (reporter-submit-bug-report
21027 "emacs-orgmode@gnu.org"
21028 (org-version nil 'full)
21029 (let (list)
21030 (save-window-excursion
21031 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21032 (delete-other-windows)
21033 (erase-buffer)
21034 (insert "You are about to submit a bug report to the Org-mode mailing list.
21036 We would like to add your full Org-mode and Outline configuration to the
21037 bug report. This greatly simplifies the work of the maintainer and
21038 other experts on the mailing list.
21040 HOWEVER, some variables you have customized may contain private
21041 information. The names of customers, colleagues, or friends, might
21042 appear in the form of file names, tags, todo states, or search strings.
21043 If you answer yes to the prompt, you might want to check and remove
21044 such private information before sending the email.")
21045 (add-text-properties (point-min) (point-max) '(face org-warning))
21046 (when (yes-or-no-p "Include your Org-mode configuration ")
21047 (mapatoms
21048 (lambda (v)
21049 (and (boundp v)
21050 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21051 (or (and (symbol-value v)
21052 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21053 (and
21054 (get v 'custom-type) (get v 'standard-value)
21055 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21056 (push v list)))))
21057 (kill-buffer (get-buffer "*Warn about privacy*"))
21058 list))
21059 nil nil
21060 "Remember to cover the basics, that is, what you expected to happen and
21061 what in fact did happen. You don't know how to make a good report? See
21063 http://orgmode.org/manual/Feedback.html#Feedback
21065 Your bug report will be posted to the Org-mode mailing list.
21066 ------------------------------------------------------------------------")
21067 (save-excursion
21068 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21069 (replace-match "\\1Bug: \\3 [\\2]")))))
21072 (defun org-install-agenda-files-menu ()
21073 (let ((bl (buffer-list)))
21074 (save-excursion
21075 (while bl
21076 (set-buffer (pop bl))
21077 (if (derived-mode-p 'org-mode) (setq bl nil)))
21078 (when (derived-mode-p 'org-mode)
21079 (easy-menu-change
21080 '("Org") "File List for Agenda"
21081 (append
21082 (list
21083 ["Edit File List" (org-edit-agenda-file-list) t]
21084 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21085 ["Remove Current File from List" org-remove-file t]
21086 ["Cycle through agenda files" org-cycle-agenda-files t]
21087 ["Occur in all agenda files" org-occur-in-agenda-files t]
21088 "--")
21089 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21091 ;;;; Documentation
21093 (defun org-require-autoloaded-modules ()
21094 (interactive)
21095 (mapc 'require
21096 '(org-agenda org-archive org-attach org-clock org-colview org-id
21097 org-remember org-table org-timer)))
21099 ;;;###autoload
21100 (defun org-reload (&optional uncompiled)
21101 "Reload all org lisp files.
21102 With prefix arg UNCOMPILED, load the uncompiled versions."
21103 (interactive "P")
21104 (require 'loadhist)
21105 (let* ((org-dir (org-find-library-dir "org"))
21106 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21107 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21108 (remove-re (mapconcat 'identity
21109 (mapcar (lambda (f) (concat "^" f "$"))
21110 (list (if (featurep 'xemacs)
21111 "org-colview"
21112 "org-colview-xemacs")
21113 "org" "org-loaddefs" "org-version"))
21114 "\\|"))
21115 (feats (delete-dups
21116 (mapcar 'file-name-sans-extension
21117 (mapcar 'file-name-nondirectory
21118 (delq nil
21119 (mapcar 'feature-file
21120 features))))))
21121 (lfeat (append
21122 (sort
21123 (setq feats
21124 (delq nil (mapcar
21125 (lambda (f)
21126 (if (and (string-match feature-re f)
21127 (not (string-match remove-re f)))
21128 f nil))
21129 feats)))
21130 'string-lessp)
21131 (list "org-version" "org")))
21132 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21133 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21134 load-uncore load-misses)
21135 (setq load-misses
21136 (delq 't
21137 (mapcar (lambda (f)
21138 (or (org-load-noerror-mustsuffix (concat org-dir f))
21139 (and (string= org-dir contrib-dir)
21140 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21141 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21142 (add-to-list 'load-uncore f 'append)
21145 lfeat)))
21146 (if load-uncore
21147 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21148 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21149 (if load-misses
21150 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21151 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21152 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21154 ;;;###autoload
21155 (defun org-customize ()
21156 "Call the customize function with org as argument."
21157 (interactive)
21158 (org-load-modules-maybe)
21159 (org-require-autoloaded-modules)
21160 (customize-browse 'org))
21162 (defun org-create-customize-menu ()
21163 "Create a full customization menu for Org-mode, insert it into the menu."
21164 (interactive)
21165 (org-load-modules-maybe)
21166 (org-require-autoloaded-modules)
21167 (if (fboundp 'customize-menu-create)
21168 (progn
21169 (easy-menu-change
21170 '("Org") "Customize"
21171 `(["Browse Org group" org-customize t]
21172 "--"
21173 ,(customize-menu-create 'org)
21174 ["Set" Custom-set t]
21175 ["Save" Custom-save t]
21176 ["Reset to Current" Custom-reset-current t]
21177 ["Reset to Saved" Custom-reset-saved t]
21178 ["Reset to Standard Settings" Custom-reset-standard t]))
21179 (message "\"Org\"-menu now contains full customization menu"))
21180 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21182 ;;;; Miscellaneous stuff
21184 ;;; Generally useful functions
21186 (defun org-get-at-bol (property)
21187 "Get text property PROPERTY at beginning of line."
21188 (get-text-property (point-at-bol) property))
21190 (defun org-find-text-property-in-string (prop s)
21191 "Return the first non-nil value of property PROP in string S."
21192 (or (get-text-property 0 prop s)
21193 (get-text-property (or (next-single-property-change 0 prop s) 0)
21194 prop s)))
21196 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21197 "Display the given MESSAGE as a warning."
21198 (if (fboundp 'display-warning)
21199 (display-warning 'org message
21200 (if (featurep 'xemacs) 'warning :warning))
21201 (let ((buf (get-buffer-create "*Org warnings*")))
21202 (with-current-buffer buf
21203 (goto-char (point-max))
21204 (insert "Warning (Org): " message)
21205 (unless (bolp)
21206 (newline)))
21207 (display-buffer buf)
21208 (sit-for 0))))
21210 (defun org-eval (form)
21211 "Eval FORM and return result."
21212 (condition-case error
21213 (eval form)
21214 (error (format "%%![Error: %s]" error))))
21216 (defun org-in-clocktable-p ()
21217 "Check if the cursor is in a clocktable."
21218 (let ((pos (point)) start)
21219 (save-excursion
21220 (end-of-line 1)
21221 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21222 (setq start (match-beginning 0))
21223 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21224 (>= (match-end 0) pos)
21225 start))))
21227 (defun org-in-commented-line ()
21228 "Is point in a line starting with `#'?"
21229 (equal (char-after (point-at-bol)) ?#))
21231 (defun org-in-indented-comment-line ()
21232 "Is point in a line starting with `#' after some white space?"
21233 (save-excursion
21234 (save-match-data
21235 (goto-char (point-at-bol))
21236 (looking-at "[ \t]*#"))))
21238 (defun org-in-verbatim-emphasis ()
21239 (save-match-data
21240 (and (org-in-regexp org-emph-re 2)
21241 (>= (point) (match-beginning 3))
21242 (<= (point) (match-end 4))
21243 (member (match-string 3) '("=" "~")))))
21245 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21246 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21247 (if (and marker (marker-buffer marker)
21248 (buffer-live-p (marker-buffer marker)))
21249 (progn
21250 (org-pop-to-buffer-same-window (marker-buffer marker))
21251 (if (or (> marker (point-max)) (< marker (point-min)))
21252 (widen))
21253 (goto-char marker)
21254 (org-show-context 'org-goto))
21255 (if bookmark
21256 (bookmark-jump bookmark)
21257 (error "Cannot find location"))))
21259 (defun org-quote-csv-field (s)
21260 "Quote field for inclusion in CSV material."
21261 (if (string-match "[\",]" s)
21262 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21265 (defun org-force-self-insert (N)
21266 "Needed to enforce self-insert under remapping."
21267 (interactive "p")
21268 (self-insert-command N))
21270 (defun org-string-width (s)
21271 "Compute width of string, ignoring invisible characters.
21272 This ignores character with invisibility property `org-link', and also
21273 characters with property `org-cwidth', because these will become invisible
21274 upon the next fontification round."
21275 (let (b l)
21276 (when (or (eq t buffer-invisibility-spec)
21277 (assq 'org-link buffer-invisibility-spec))
21278 (while (setq b (text-property-any 0 (length s)
21279 'invisible 'org-link s))
21280 (setq s (concat (substring s 0 b)
21281 (substring s (or (next-single-property-change
21282 b 'invisible s) (length s)))))))
21283 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21284 (setq s (concat (substring s 0 b)
21285 (substring s (or (next-single-property-change
21286 b 'org-cwidth s) (length s))))))
21287 (setq l (string-width s) b -1)
21288 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21289 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21292 (defun org-shorten-string (s maxlength)
21293 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21294 If the string is shorter or has length MAXLENGTH, just return the
21295 original string. If it is longer, the functions finds a space in the
21296 string, breaks this string off at that locations and adds three dots
21297 as ellipsis. Including the ellipsis, the string will not be longer
21298 than MAXLENGTH. If finding a good breaking point in the string does
21299 not work, the string is just chopped off in the middle of a word
21300 if necessary."
21301 (if (<= (length s) maxlength)
21303 (let* ((n (max (- maxlength 4) 1))
21304 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21305 (if (string-match re s)
21306 (concat (match-string 1 s) "...")
21307 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21309 (defun org-get-indentation (&optional line)
21310 "Get the indentation of the current line, interpreting tabs.
21311 When LINE is given, assume it represents a line and compute its indentation."
21312 (if line
21313 (if (string-match "^ *" (org-remove-tabs line))
21314 (match-end 0))
21315 (save-excursion
21316 (beginning-of-line 1)
21317 (skip-chars-forward " \t")
21318 (current-column))))
21320 (defun org-get-string-indentation (s)
21321 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21322 (let ((n -1) (i 0) (w tab-width) c)
21323 (catch 'exit
21324 (while (< (setq n (1+ n)) (length s))
21325 (setq c (aref s n))
21326 (cond ((= c ?\ ) (setq i (1+ i)))
21327 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21328 (t (throw 'exit t)))))
21331 (defun org-remove-tabs (s &optional width)
21332 "Replace tabulators in S with spaces.
21333 Assumes that s is a single line, starting in column 0."
21334 (setq width (or width tab-width))
21335 (while (string-match "\t" s)
21336 (setq s (replace-match
21337 (make-string
21338 (- (* width (/ (+ (match-beginning 0) width) width))
21339 (match-beginning 0)) ?\ )
21340 t t s)))
21343 (defun org-fix-indentation (line ind)
21344 "Fix indentation in LINE.
21345 IND is a cons cell with target and minimum indentation.
21346 If the current indentation in LINE is smaller than the minimum,
21347 leave it alone. If it is larger than ind, set it to the target."
21348 (let* ((l (org-remove-tabs line))
21349 (i (org-get-indentation l))
21350 (i1 (car ind)) (i2 (cdr ind)))
21351 (if (>= i i2) (setq l (substring line i2)))
21352 (if (> i1 0)
21353 (concat (make-string i1 ?\ ) l)
21354 l)))
21356 (defun org-remove-indentation (code &optional n)
21357 "Remove the maximum common indentation from the lines in CODE.
21358 N may optionally be the number of spaces to remove."
21359 (with-temp-buffer
21360 (insert code)
21361 (org-do-remove-indentation n)
21362 (buffer-string)))
21364 (defun org-do-remove-indentation (&optional n)
21365 "Remove the maximum common indentation from the buffer."
21366 (untabify (point-min) (point-max))
21367 (let ((min 10000) re)
21368 (if n
21369 (setq min n)
21370 (goto-char (point-min))
21371 (while (re-search-forward "^ *[^ \n]" nil t)
21372 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21373 (unless (or (= min 0) (= min 10000))
21374 (setq re (format "^ \\{%d\\}" min))
21375 (goto-char (point-min))
21376 (while (re-search-forward re nil t)
21377 (replace-match "")
21378 (end-of-line 1))
21379 min)))
21381 (defun org-fill-template (template alist)
21382 "Find each %key of ALIST in TEMPLATE and replace it."
21383 (let ((case-fold-search nil)
21384 entry key value)
21385 (setq alist (sort (copy-sequence alist)
21386 (lambda (a b) (< (length (car a)) (length (car b))))))
21387 (while (setq entry (pop alist))
21388 (setq template
21389 (replace-regexp-in-string
21390 (concat "%" (regexp-quote (car entry)))
21391 (or (cdr entry) "") template t t)))
21392 template))
21394 (defun org-base-buffer (buffer)
21395 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21396 (if (not buffer)
21397 buffer
21398 (or (buffer-base-buffer buffer)
21399 buffer)))
21401 (defun org-trim (s)
21402 "Remove whitespace at beginning and end of string."
21403 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21404 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21407 (defun org-wrap (string &optional width lines)
21408 "Wrap string to either a number of lines, or a width in characters.
21409 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21410 that costs. If there is a word longer than WIDTH, the text is actually
21411 wrapped to the length of that word.
21412 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21413 many lines, whatever width that takes.
21414 The return value is a list of lines, without newlines at the end."
21415 (let* ((words (org-split-string string "[ \t\n]+"))
21416 (maxword (apply 'max (mapcar 'org-string-width words)))
21417 w ll)
21418 (cond (width
21419 (org-do-wrap words (max maxword width)))
21420 (lines
21421 (setq w maxword)
21422 (setq ll (org-do-wrap words maxword))
21423 (if (<= (length ll) lines)
21425 (setq ll words)
21426 (while (> (length ll) lines)
21427 (setq w (1+ w))
21428 (setq ll (org-do-wrap words w)))
21429 ll))
21430 (t (error "Cannot wrap this")))))
21432 (defun org-do-wrap (words width)
21433 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21434 (let (lines line)
21435 (while words
21436 (setq line (pop words))
21437 (while (and words (< (+ (length line) (length (car words))) width))
21438 (setq line (concat line " " (pop words))))
21439 (setq lines (push line lines)))
21440 (nreverse lines)))
21442 (defun org-split-string (string &optional separators)
21443 "Splits STRING into substrings at SEPARATORS.
21444 No empty strings are returned if there are matches at the beginning
21445 and end of string."
21446 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21447 (start 0)
21448 notfirst
21449 (list nil))
21450 (while (and (string-match rexp string
21451 (if (and notfirst
21452 (= start (match-beginning 0))
21453 (< start (length string)))
21454 (1+ start) start))
21455 (< (match-beginning 0) (length string)))
21456 (setq notfirst t)
21457 (or (eq (match-beginning 0) 0)
21458 (and (eq (match-beginning 0) (match-end 0))
21459 (eq (match-beginning 0) start))
21460 (setq list
21461 (cons (substring string start (match-beginning 0))
21462 list)))
21463 (setq start (match-end 0)))
21464 (or (eq start (length string))
21465 (setq list
21466 (cons (substring string start)
21467 list)))
21468 (nreverse list)))
21470 (defun org-quote-vert (s)
21471 "Replace \"|\" with \"\\vert\"."
21472 (while (string-match "|" s)
21473 (setq s (replace-match "\\vert" t t s)))
21476 (defun org-uuidgen-p (s)
21477 "Is S an ID created by UUIDGEN?"
21478 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21480 (defun org-in-src-block-p (&optional inside)
21481 "Whether point is in a code source block.
21482 When INSIDE is non-nil, don't consider we are within a src block
21483 when point is at #+BEGIN_SRC or #+END_SRC."
21484 (let ((case-fold-search t) ov)
21485 (or (and (setq ov (overlays-at (point)))
21486 (memq 'org-block-background
21487 (overlay-properties (car ov))))
21488 (and (not inside)
21489 (save-match-data
21490 (save-excursion
21491 (beginning-of-line)
21492 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21494 (defun org-context ()
21495 "Return a list of contexts of the current cursor position.
21496 If several contexts apply, all are returned.
21497 Each context entry is a list with a symbol naming the context, and
21498 two positions indicating start and end of the context. Possible
21499 contexts are:
21501 :headline anywhere in a headline
21502 :headline-stars on the leading stars in a headline
21503 :todo-keyword on a TODO keyword (including DONE) in a headline
21504 :tags on the TAGS in a headline
21505 :priority on the priority cookie in a headline
21506 :item on the first line of a plain list item
21507 :item-bullet on the bullet/number of a plain list item
21508 :checkbox on the checkbox in a plain list item
21509 :table in an org-mode table
21510 :table-special on a special filed in a table
21511 :table-table in a table.el table
21512 :clocktable in a clocktable
21513 :src-block in a source block
21514 :link on a hyperlink
21515 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21516 :target on a <<target>>
21517 :radio-target on a <<<radio-target>>>
21518 :latex-fragment on a LaTeX fragment
21519 :latex-preview on a LaTeX fragment with overlaid preview image
21521 This function expects the position to be visible because it uses font-lock
21522 faces as a help to recognize the following contexts: :table-special, :link,
21523 and :keyword."
21524 (let* ((f (get-text-property (point) 'face))
21525 (faces (if (listp f) f (list f)))
21526 (case-fold-search t)
21527 (p (point)) clist o)
21528 ;; First the large context
21529 (cond
21530 ((org-at-heading-p t)
21531 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21532 (when (progn
21533 (beginning-of-line 1)
21534 (looking-at org-todo-line-tags-regexp))
21535 (push (org-point-in-group p 1 :headline-stars) clist)
21536 (push (org-point-in-group p 2 :todo-keyword) clist)
21537 (push (org-point-in-group p 4 :tags) clist))
21538 (goto-char p)
21539 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21540 (if (looking-at "\\[#[A-Z0-9]\\]")
21541 (push (org-point-in-group p 0 :priority) clist)))
21543 ((org-at-item-p)
21544 (push (org-point-in-group p 2 :item-bullet) clist)
21545 (push (list :item (point-at-bol)
21546 (save-excursion (org-end-of-item) (point)))
21547 clist)
21548 (and (org-at-item-checkbox-p)
21549 (push (org-point-in-group p 0 :checkbox) clist)))
21551 ((org-at-table-p)
21552 (push (list :table (org-table-begin) (org-table-end)) clist)
21553 (if (memq 'org-formula faces)
21554 (push (list :table-special
21555 (previous-single-property-change p 'face)
21556 (next-single-property-change p 'face)) clist)))
21557 ((org-at-table-p 'any)
21558 (push (list :table-table) clist)))
21559 (goto-char p)
21561 (let ((case-fold-search t))
21562 ;; New the "medium" contexts: clocktables, source blocks
21563 (cond ((org-in-clocktable-p)
21564 (push (list :clocktable
21565 (and (or (looking-at "#\\+BEGIN: clocktable")
21566 (search-backward "#+BEGIN: clocktable" nil t))
21567 (match-beginning 0))
21568 (and (re-search-forward "#\\+END:?" nil t)
21569 (match-end 0))) clist))
21570 ((org-in-src-block-p)
21571 (push (list :src-block
21572 (and (or (looking-at "#\\+BEGIN_SRC")
21573 (search-backward "#+BEGIN_SRC" nil t))
21574 (match-beginning 0))
21575 (and (search-forward "#+END_SRC" nil t)
21576 (match-beginning 0))) clist))))
21577 (goto-char p)
21579 ;; Now the small context
21580 (cond
21581 ((org-at-timestamp-p)
21582 (push (org-point-in-group p 0 :timestamp) clist))
21583 ((memq 'org-link faces)
21584 (push (list :link
21585 (previous-single-property-change p 'face)
21586 (next-single-property-change p 'face)) clist))
21587 ((memq 'org-special-keyword faces)
21588 (push (list :keyword
21589 (previous-single-property-change p 'face)
21590 (next-single-property-change p 'face)) clist))
21591 ((org-at-target-p)
21592 (push (org-point-in-group p 0 :target) clist)
21593 (goto-char (1- (match-beginning 0)))
21594 (if (looking-at org-radio-target-regexp)
21595 (push (org-point-in-group p 0 :radio-target) clist))
21596 (goto-char p))
21597 ((setq o (car (delq nil
21598 (mapcar
21599 (lambda (x)
21600 (if (memq x org-latex-fragment-image-overlays) x))
21601 (overlays-at (point))))))
21602 (push (list :latex-fragment
21603 (overlay-start o) (overlay-end o)) clist)
21604 (push (list :latex-preview
21605 (overlay-start o) (overlay-end o)) clist))
21606 ((org-inside-LaTeX-fragment-p)
21607 ;; FIXME: positions wrong.
21608 (push (list :latex-fragment (point) (point)) clist)))
21610 (setq clist (nreverse (delq nil clist)))
21611 clist))
21613 ;; FIXME: Compare with at-regexp-p Do we need both?
21614 (defun org-in-regexp (re &optional nlines visually)
21615 "Check if point is inside a match of regexp.
21616 Normally only the current line is checked, but you can include NLINES extra
21617 lines both before and after point into the search.
21618 If VISUALLY is set, require that the cursor is not after the match but
21619 really on, so that the block visually is on the match."
21620 (catch 'exit
21621 (let ((pos (point))
21622 (eol (point-at-eol (+ 1 (or nlines 0))))
21623 (inc (if visually 1 0)))
21624 (save-excursion
21625 (beginning-of-line (- 1 (or nlines 0)))
21626 (while (re-search-forward re eol t)
21627 (if (and (<= (match-beginning 0) pos)
21628 (>= (+ inc (match-end 0)) pos))
21629 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21631 (defun org-at-regexp-p (regexp)
21632 "Is point inside a match of REGEXP in the current line?"
21633 (catch 'exit
21634 (save-excursion
21635 (let ((pos (point)) (end (point-at-eol)))
21636 (beginning-of-line 1)
21637 (while (re-search-forward regexp end t)
21638 (if (and (<= (match-beginning 0) pos)
21639 (>= (match-end 0) pos))
21640 (throw 'exit t)))
21641 nil))))
21643 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21644 "Non-nil when point is between matches of START-RE and END-RE.
21646 Also return a non-nil value when point is on one of the matches.
21648 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21649 buffer positions. Default values are the positions of headlines
21650 surrounding the point.
21652 The functions returns a cons cell whose car (resp. cdr) is the
21653 position before START-RE (resp. after END-RE)."
21654 (save-match-data
21655 (let ((pos (point))
21656 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21657 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21658 beg end)
21659 (save-excursion
21660 ;; Point is on a block when on START-RE or if START-RE can be
21661 ;; found before it...
21662 (and (or (org-at-regexp-p start-re)
21663 (re-search-backward start-re limit-up t))
21664 (setq beg (match-beginning 0))
21665 ;; ... and END-RE after it...
21666 (goto-char (match-end 0))
21667 (re-search-forward end-re limit-down t)
21668 (> (setq end (match-end 0)) pos)
21669 ;; ... without another START-RE in-between.
21670 (goto-char (match-beginning 0))
21671 (not (re-search-backward start-re (1+ beg) t))
21672 ;; Return value.
21673 (cons beg end))))))
21675 (defun org-in-block-p (names)
21676 "Non-nil when point belongs to a block whose name belongs to NAMES.
21678 NAMES is a list of strings containing names of blocks.
21680 Return first block name matched, or nil. Beware that in case of
21681 nested blocks, the returned name may not belong to the closest
21682 block from point."
21683 (save-match-data
21684 (catch 'exit
21685 (let ((case-fold-search t)
21686 (lim-up (save-excursion (outline-previous-heading)))
21687 (lim-down (save-excursion (outline-next-heading))))
21688 (mapc (lambda (name)
21689 (let ((n (regexp-quote name)))
21690 (when (org-between-regexps-p
21691 (concat "^[ \t]*#\\+begin_" n)
21692 (concat "^[ \t]*#\\+end_" n)
21693 lim-up lim-down)
21694 (throw 'exit n))))
21695 names))
21696 nil)))
21698 (defun org-in-drawer-p ()
21699 "Non-nil if point is within a drawer.
21700 If point is within a drawer, return it, as parsed data."
21701 (let ((element (save-match-data (org-element-at-point))))
21702 (while (and element (not (memq (org-element-type element)
21703 '(drawer property-drawer))))
21704 (setq element (org-element-property :parent element)))
21705 element))
21707 (defun org-occur-in-agenda-files (regexp &optional nlines)
21708 "Call `multi-occur' with buffers for all agenda files."
21709 (interactive "sOrg-files matching: \np")
21710 (let* ((files (org-agenda-files))
21711 (tnames (mapcar 'file-truename files))
21712 (extra org-agenda-text-search-extra-files)
21714 (when (eq (car extra) 'agenda-archives)
21715 (setq extra (cdr extra))
21716 (setq files (org-add-archive-files files)))
21717 (while (setq f (pop extra))
21718 (unless (member (file-truename f) tnames)
21719 (add-to-list 'files f 'append)
21720 (add-to-list 'tnames (file-truename f) 'append)))
21721 (multi-occur
21722 (mapcar (lambda (x)
21723 (with-current-buffer
21724 (or (get-file-buffer x) (find-file-noselect x))
21725 (widen)
21726 (current-buffer)))
21727 files)
21728 regexp)))
21730 (if (boundp 'occur-mode-find-occurrence-hook)
21731 ;; Emacs 23
21732 (add-hook 'occur-mode-find-occurrence-hook
21733 (lambda ()
21734 (when (derived-mode-p 'org-mode)
21735 (org-reveal))))
21736 ;; Emacs 22
21737 (defadvice occur-mode-goto-occurrence
21738 (after org-occur-reveal activate)
21739 (and (derived-mode-p 'org-mode) (org-reveal)))
21740 (defadvice occur-mode-goto-occurrence-other-window
21741 (after org-occur-reveal activate)
21742 (and (derived-mode-p 'org-mode) (org-reveal)))
21743 (defadvice occur-mode-display-occurrence
21744 (after org-occur-reveal activate)
21745 (when (derived-mode-p 'org-mode)
21746 (let ((pos (occur-mode-find-occurrence)))
21747 (with-current-buffer (marker-buffer pos)
21748 (save-excursion
21749 (goto-char pos)
21750 (org-reveal)))))))
21752 (defun org-occur-link-in-agenda-files ()
21753 "Create a link and search for it in the agendas.
21754 The link is not stored in `org-stored-links', it is just created
21755 for the search purpose."
21756 (interactive)
21757 (let ((link (condition-case nil
21758 (org-store-link nil)
21759 (error "Unable to create a link to here"))))
21760 (org-occur-in-agenda-files (regexp-quote link))))
21762 (defun org-reverse-string (string)
21763 "Return the reverse of STRING."
21764 (apply 'string (reverse (string-to-list string))))
21766 (defsubst org-uniquify (list)
21767 "Non-destructively remove duplicate elements from LIST."
21768 (let ((res (copy-sequence list))) (delete-dups res)))
21770 (defun org-uniquify-alist (alist)
21771 "Merge elements of ALIST with the same key.
21773 For example, in this alist:
21775 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21776 => '((a 1 3) (b 2))
21778 merge (a 1) and (a 3) into (a 1 3).
21780 The function returns the new ALIST."
21781 (let (rtn)
21782 (mapc
21783 (lambda (e)
21784 (let (n)
21785 (if (not (assoc (car e) rtn))
21786 (push e rtn)
21787 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21788 (setq rtn (assq-delete-all (car e) rtn))
21789 (push n rtn))))
21790 alist)
21791 rtn))
21793 (defun org-delete-all (elts list)
21794 "Remove all elements in ELTS from LIST."
21795 (while elts
21796 (setq list (delete (pop elts) list)))
21797 list)
21799 (defun org-count (cl-item cl-seq)
21800 "Count the number of occurrences of ITEM in SEQ.
21801 Taken from `count' in cl-seq.el with all keyword arguments removed."
21802 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21803 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21804 (while (< cl-start cl-end)
21805 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21806 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21807 (setq cl-start (1+ cl-start)))
21808 cl-count))
21810 (defun org-remove-if (predicate seq)
21811 "Remove everything from SEQ that fulfills PREDICATE."
21812 (let (res e)
21813 (while seq
21814 (setq e (pop seq))
21815 (if (not (funcall predicate e)) (push e res)))
21816 (nreverse res)))
21818 (defun org-remove-if-not (predicate seq)
21819 "Remove everything from SEQ that does not fulfill PREDICATE."
21820 (let (res e)
21821 (while seq
21822 (setq e (pop seq))
21823 (if (funcall predicate e) (push e res)))
21824 (nreverse res)))
21826 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21827 "Reduce two-argument FUNCTION across SEQ.
21828 Taken from `reduce' in cl-seq.el with all keyword arguments but
21829 \":initial-value\" removed."
21830 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21831 (cadr (memq :initial-value cl-keys)))
21832 (cl-seq (pop cl-seq))
21833 (t (funcall cl-func)))))
21834 (while cl-seq
21835 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21836 cl-accum))
21838 (defun org-every (pred seq)
21839 "Return true if PREDICATE is true of every element of SEQ.
21840 Adapted from `every' in cl.el."
21841 (catch 'org-every
21842 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21845 (defun org-some (pred seq)
21846 "Return true if PREDICATE is true of any element of SEQ.
21847 Adapted from `some' in cl.el."
21848 (catch 'org-some
21849 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21850 nil))
21852 (defun org-back-over-empty-lines ()
21853 "Move backwards over whitespace, to the beginning of the first empty line.
21854 Returns the number of empty lines passed."
21855 (let ((pos (point)))
21856 (if (cdr (assoc 'heading org-blank-before-new-entry))
21857 (skip-chars-backward " \t\n\r")
21858 (unless (eobp)
21859 (forward-line -1)))
21860 (beginning-of-line 2)
21861 (goto-char (min (point) pos))
21862 (count-lines (point) pos)))
21864 (defun org-skip-whitespace ()
21865 (skip-chars-forward " \t\n\r"))
21867 (defun org-point-in-group (point group &optional context)
21868 "Check if POINT is in match-group GROUP.
21869 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21870 match. If the match group does not exist or point is not inside it,
21871 return nil."
21872 (and (match-beginning group)
21873 (>= point (match-beginning group))
21874 (<= point (match-end group))
21875 (if context
21876 (list context (match-beginning group) (match-end group))
21877 t)))
21879 (defun org-switch-to-buffer-other-window (&rest args)
21880 "Switch to buffer in a second window on the current frame.
21881 In particular, do not allow pop-up frames.
21882 Returns the newly created buffer."
21883 (org-no-popups
21884 (apply 'switch-to-buffer-other-window args)))
21886 (defun org-combine-plists (&rest plists)
21887 "Create a single property list from all plists in PLISTS.
21888 The process starts by copying the first list, and then setting properties
21889 from the other lists. Settings in the last list are the most significant
21890 ones and overrule settings in the other lists."
21891 (let ((rtn (copy-sequence (pop plists)))
21892 p v ls)
21893 (while plists
21894 (setq ls (pop plists))
21895 (while ls
21896 (setq p (pop ls) v (pop ls))
21897 (setq rtn (plist-put rtn p v))))
21898 rtn))
21900 (defun org-replace-escapes (string table)
21901 "Replace %-escapes in STRING with values in TABLE.
21902 TABLE is an association list with keys like \"%a\" and string values.
21903 The sequences in STRING may contain normal field width and padding information,
21904 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21905 so values can contain further %-escapes if they are define later in TABLE."
21906 (let ((tbl (copy-alist table))
21907 (case-fold-search nil)
21908 (pchg 0)
21909 e re rpl)
21910 (while (setq e (pop tbl))
21911 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21912 (when (and (cdr e) (string-match re (cdr e)))
21913 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21914 (safe "SREF"))
21915 (add-text-properties 0 3 (list 'sref sref) safe)
21916 (setcdr e (replace-match safe t t (cdr e)))))
21917 (while (string-match re string)
21918 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21919 (cdr e)))
21920 (setq string (replace-match rpl t t string))))
21921 (while (setq pchg (next-property-change pchg string))
21922 (let ((sref (get-text-property pchg 'sref string)))
21923 (when (and sref (string-match "SREF" string pchg))
21924 (setq string (replace-match sref t t string)))))
21925 string))
21927 (defun org-sublist (list start end)
21928 "Return a section of LIST, from START to END.
21929 Counting starts at 1."
21930 (let (rtn (c start))
21931 (setq list (nthcdr (1- start) list))
21932 (while (and list (<= c end))
21933 (push (pop list) rtn)
21934 (setq c (1+ c)))
21935 (nreverse rtn)))
21937 (defun org-find-base-buffer-visiting (file)
21938 "Like `find-buffer-visiting' but always return the base buffer and
21939 not an indirect buffer."
21940 (let ((buf (or (get-file-buffer file)
21941 (find-buffer-visiting file))))
21942 (if buf
21943 (or (buffer-base-buffer buf) buf)
21944 nil)))
21946 (defun org-image-file-name-regexp (&optional extensions)
21947 "Return regexp matching the file names of images.
21948 If EXTENSIONS is given, only match these."
21949 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21950 (image-file-name-regexp)
21951 (let ((image-file-name-extensions
21952 (or extensions
21953 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21954 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21955 (concat "\\."
21956 (regexp-opt (nconc (mapcar 'upcase
21957 image-file-name-extensions)
21958 image-file-name-extensions)
21960 "\\'"))))
21962 (defun org-file-image-p (file &optional extensions)
21963 "Return non-nil if FILE is an image."
21964 (save-match-data
21965 (string-match (org-image-file-name-regexp extensions) file)))
21967 (defun org-get-cursor-date (&optional with-time)
21968 "Return the date at cursor in as a time.
21969 This works in the calendar and in the agenda, anywhere else it just
21970 returns the current time.
21971 If WITH-TIME is non-nil, returns the time of the event at point (in
21972 the agenda) or the current time of the day."
21973 (let (date day defd tp tm hod mod)
21974 (when with-time
21975 (setq tp (get-text-property (point) 'time))
21976 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21977 (setq hod (string-to-number (match-string 1 tp))
21978 mod (string-to-number (match-string 2 tp))))
21979 (or tp (setq hod (nth 2 (decode-time (current-time)))
21980 mod (nth 1 (decode-time (current-time))))))
21981 (cond
21982 ((eq major-mode 'calendar-mode)
21983 (setq date (calendar-cursor-to-date)
21984 defd (encode-time 0 (or mod 0) (or hod 0)
21985 (nth 1 date) (nth 0 date) (nth 2 date))))
21986 ((eq major-mode 'org-agenda-mode)
21987 (setq day (get-text-property (point) 'day))
21988 (if day
21989 (setq date (calendar-gregorian-from-absolute day)
21990 defd (encode-time 0 (or mod 0) (or hod 0)
21991 (nth 1 date) (nth 0 date) (nth 2 date))))))
21992 (or defd (current-time))))
21994 (defun org-mark-subtree (&optional up)
21995 "Mark the current subtree.
21996 This puts point at the start of the current subtree, and mark at
21997 the end. If a numeric prefix UP is given, move up into the
21998 hierarchy of headlines by UP levels before marking the subtree."
21999 (interactive "P")
22000 (org-with-limited-levels
22001 (cond ((org-at-heading-p) (beginning-of-line))
22002 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22003 (t (outline-previous-visible-heading 1))))
22004 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22005 (if (org-called-interactively-p 'any)
22006 (call-interactively 'org-mark-element)
22007 (org-mark-element)))
22010 ;;; Indentation
22012 (defun org-indent-line ()
22013 "Indent line depending on context."
22014 (interactive)
22015 (let* ((pos (point))
22016 (itemp (org-at-item-p))
22017 (case-fold-search t)
22018 (org-drawer-regexp (or org-drawer-regexp "\000"))
22019 (inline-task-p (and (featurep 'org-inlinetask)
22020 (org-inlinetask-in-task-p)))
22021 (inline-re (and inline-task-p
22022 (org-inlinetask-outline-regexp)))
22023 column)
22024 (if (and orgstruct-is-++ (eq pos (point)))
22025 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22026 (indent-according-to-mode))
22027 (beginning-of-line 1)
22028 (cond
22029 ;; Headings
22030 ((looking-at org-outline-regexp) (setq column 0))
22031 ;; Footnote definition
22032 ((looking-at org-footnote-definition-re) (setq column 0))
22033 ;; Literal examples
22034 ((looking-at "[ \t]*:\\( \\|$\\)")
22035 (setq column (org-get-indentation))) ; do nothing
22036 ;; Lists
22037 ((ignore-errors (goto-char (org-in-item-p)))
22038 (setq column (if itemp
22039 (org-get-indentation)
22040 (org-list-item-body-column (point))))
22041 (goto-char pos))
22042 ;; Drawers
22043 ((and (looking-at "[ \t]*:END:")
22044 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22045 (save-excursion
22046 (goto-char (1- (match-beginning 1)))
22047 (setq column (current-column))))
22048 ;; Special blocks
22049 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22050 (save-excursion
22051 (re-search-backward
22052 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22053 (setq column (org-get-indentation (match-string 0))))
22054 ((and (not (looking-at "[ \t]*#\\+begin_"))
22055 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22056 (save-excursion
22057 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22058 (setq column
22059 (cond ((equal (downcase (match-string 1)) "src")
22060 ;; src blocks: let `org-edit-src-exit' handle them
22061 (org-get-indentation))
22062 ((equal (downcase (match-string 1)) "example")
22063 (max (org-get-indentation)
22064 (org-get-indentation (match-string 0))))
22066 (org-get-indentation (match-string 0))))))
22067 ;; This line has nothing special, look at the previous relevant
22068 ;; line to compute indentation
22070 (beginning-of-line 0)
22071 (while (and (not (bobp))
22072 (not (looking-at org-table-line-regexp))
22073 (not (looking-at org-drawer-regexp))
22074 ;; When point started in an inline task, do not move
22075 ;; above task starting line.
22076 (not (and inline-task-p (looking-at inline-re)))
22077 ;; Skip drawers, blocks, empty lines, verbatim,
22078 ;; comments, tables, footnotes definitions, lists,
22079 ;; inline tasks.
22080 (or (and (looking-at "[ \t]*:END:")
22081 (re-search-backward org-drawer-regexp nil t))
22082 (and (looking-at "[ \t]*#\\+end_")
22083 (re-search-backward "[ \t]*#\\+begin_"nil t))
22084 (looking-at "[ \t]*[\n:#|]")
22085 (looking-at org-footnote-definition-re)
22086 (and (not inline-task-p)
22087 (featurep 'org-inlinetask)
22088 (org-inlinetask-in-task-p)
22089 (or (org-inlinetask-goto-beginning) t))))
22090 (beginning-of-line 0))
22091 (cond
22092 ;; There was a list item above.
22093 ((ignore-errors (goto-char (org-in-item-p)))
22094 (goto-char (org-list-get-top-point (org-list-struct)))
22095 (setq column (org-get-indentation)))
22096 ;; There was an heading above.
22097 ((looking-at "\\*+[ \t]+")
22098 (if (not org-adapt-indentation)
22099 (setq column 0)
22100 (goto-char (match-end 0))
22101 (setq column (current-column))))
22102 ;; A drawer had started and is unfinished
22103 ((looking-at org-drawer-regexp)
22104 (goto-char (1- (match-beginning 1)))
22105 (setq column (current-column)))
22106 ;; Else, nothing noticeable found: get indentation and go on.
22107 (t (setq column (org-get-indentation))))))
22108 ;; Now apply indentation and move cursor accordingly
22109 (goto-char pos)
22110 (if (<= (current-column) (current-indentation))
22111 (org-indent-line-to column)
22112 (save-excursion (org-indent-line-to column)))
22113 ;; Special polishing for properties, see `org-property-format'
22114 (setq column (current-column))
22115 (beginning-of-line 1)
22116 (if (looking-at org-property-re)
22117 (replace-match (concat (match-string 4)
22118 (format org-property-format
22119 (match-string 1) (match-string 3)))
22120 t t))
22121 (org-move-to-column column))))
22123 (defun org-indent-drawer ()
22124 "Indent the drawer at point."
22125 (interactive)
22126 (let ((p (point))
22127 (e (and (save-excursion (re-search-forward ":END:" nil t))
22128 (match-end 0)))
22129 (folded
22130 (save-excursion
22131 (end-of-line)
22132 (when (overlays-at (point))
22133 (member 'invisible (overlay-properties
22134 (car (overlays-at (point)))))))))
22135 (when folded (org-cycle))
22136 (indent-for-tab-command)
22137 (while (and (move-beginning-of-line 2) (< (point) e))
22138 (indent-for-tab-command))
22139 (goto-char p)
22140 (when folded (org-cycle)))
22141 (message "Drawer at point indented"))
22143 (defun org-indent-block ()
22144 "Indent the block at point."
22145 (interactive)
22146 (let ((p (point))
22147 (case-fold-search t)
22148 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22149 (match-end 0)))
22150 (folded
22151 (save-excursion
22152 (end-of-line)
22153 (when (overlays-at (point))
22154 (member 'invisible (overlay-properties
22155 (car (overlays-at (point)))))))))
22156 (when folded (org-cycle))
22157 (indent-for-tab-command)
22158 (while (and (move-beginning-of-line 2) (< (point) e))
22159 (indent-for-tab-command))
22160 (goto-char p)
22161 (when folded (org-cycle)))
22162 (message "Block at point indented"))
22164 (defun org-indent-region (start end)
22165 "Indent region."
22166 (interactive "r")
22167 (save-excursion
22168 (let ((line-end (org-current-line end)))
22169 (goto-char start)
22170 (while (< (org-current-line) line-end)
22171 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22172 (t (call-interactively 'org-indent-line)))
22173 (move-beginning-of-line 2)))))
22176 ;;; Filling
22178 ;; We use our own fill-paragraph and auto-fill functions.
22180 ;; `org-fill-paragraph' relies on adaptive filling and context
22181 ;; checking. Appropriate `fill-prefix' is computed with
22182 ;; `org-adaptive-fill-function'.
22184 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22185 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22186 ;; `org-adaptive-fill-function' value. Internally,
22187 ;; `org-comment-line-break-function' breaks the line.
22189 ;; `org-setup-filling' installs filling and auto-filling related
22190 ;; variables during `org-mode' initialization.
22192 (defvar org-element-paragraph-separate) ; org-element.el
22193 (defun org-setup-filling ()
22194 (require 'org-element)
22195 ;; Prevent auto-fill from inserting unwanted new items.
22196 (when (boundp 'fill-nobreak-predicate)
22197 (org-set-local
22198 'fill-nobreak-predicate
22199 (org-uniquify
22200 (append fill-nobreak-predicate
22201 '(org-fill-line-break-nobreak-p
22202 org-fill-paragraph-with-timestamp-nobreak-p)))))
22203 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22204 (org-set-local 'paragraph-start paragraph-ending)
22205 (org-set-local 'paragraph-separate paragraph-ending))
22206 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22207 (org-set-local 'auto-fill-inhibit-regexp nil)
22208 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22209 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22210 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22212 (defun org-fill-line-break-nobreak-p ()
22213 "Non-nil when a new line at point would create an Org line break."
22214 (save-excursion
22215 (skip-chars-backward "[ \t]")
22216 (skip-chars-backward "\\\\")
22217 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22219 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22220 "Non-nil when a new line at point would split a timestamp."
22221 (and (org-at-timestamp-p t)
22222 (not (looking-at org-ts-regexp-both))))
22224 (declare-function message-in-body-p "message" ())
22225 (defvar orgtbl-line-start-regexp) ; From org-table.el
22226 (defun org-adaptive-fill-function ()
22227 "Compute a fill prefix for the current line.
22228 Return fill prefix, as a string, or nil if current line isn't
22229 meant to be filled. For convenience, if `adaptive-fill-regexp'
22230 matches in paragraphs or comments, use it."
22231 (catch 'exit
22232 (when (derived-mode-p 'message-mode)
22233 (save-excursion
22234 (beginning-of-line)
22235 (cond ((or (not (message-in-body-p))
22236 (looking-at orgtbl-line-start-regexp))
22237 (throw 'exit nil))
22238 ((looking-at message-cite-prefix-regexp)
22239 (throw 'exit (match-string-no-properties 0)))
22240 ((looking-at org-outline-regexp)
22241 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22242 (org-with-wide-buffer
22243 (let* ((p (line-beginning-position))
22244 (element (save-excursion
22245 (beginning-of-line)
22246 (or (ignore-errors (org-element-at-point))
22247 (user-error "An element cannot be parsed line %d"
22248 (line-number-at-pos (point))))))
22249 (type (org-element-type element))
22250 (post-affiliated (org-element-property :post-affiliated element)))
22251 (unless (and post-affiliated (< p post-affiliated))
22252 (case type
22253 (comment
22254 (save-excursion
22255 (beginning-of-line)
22256 (looking-at "[ \t]*")
22257 (concat (match-string 0) "# ")))
22258 (footnote-definition "")
22259 ((item plain-list)
22260 (make-string (org-list-item-body-column
22261 (or post-affiliated
22262 (org-element-property :begin element)))
22263 ? ))
22264 (paragraph
22265 ;; Fill prefix is usually the same as the current line,
22266 ;; unless the paragraph is at the beginning of an item.
22267 (let ((parent (org-element-property :parent element)))
22268 (save-excursion
22269 (beginning-of-line)
22270 (cond ((eq (org-element-type parent) 'item)
22271 (make-string (org-list-item-body-column
22272 (org-element-property :begin parent))
22273 ? ))
22274 ((and adaptive-fill-regexp
22275 ;; Locally disable
22276 ;; `adaptive-fill-function' to let
22277 ;; `fill-context-prefix' handle
22278 ;; `adaptive-fill-regexp' variable.
22279 (let (adaptive-fill-function)
22280 (fill-context-prefix
22281 post-affiliated
22282 (org-element-property :end element)))))
22283 ((looking-at "[ \t]+") (match-string 0))
22284 (t "")))))
22285 (comment-block
22286 ;; Only fill contents if P is within block boundaries.
22287 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22288 (forward-line)
22289 (point)))
22290 (cend (save-excursion
22291 (goto-char (org-element-property :end element))
22292 (skip-chars-backward " \r\t\n")
22293 (line-beginning-position))))
22294 (when (and (>= p cbeg) (< p cend))
22295 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22296 (match-string 0)
22297 ""))))))))))
22299 (declare-function message-goto-body "message" ())
22300 (defvar message-cite-prefix-regexp) ; From message.el
22301 (defun org-fill-paragraph (&optional justify)
22302 "Fill element at point, when applicable.
22304 This function only applies to comment blocks, comments, example
22305 blocks and paragraphs. Also, as a special case, re-align table
22306 when point is at one.
22308 If JUSTIFY is non-nil (interactively, with prefix argument),
22309 justify as well. If `sentence-end-double-space' is non-nil, then
22310 period followed by one space does not end a sentence, so don't
22311 break a line there. The variable `fill-column' controls the
22312 width for filling.
22314 For convenience, when point is at a plain list, an item or
22315 a footnote definition, try to fill the first paragraph within."
22316 (interactive)
22317 (if (and (derived-mode-p 'message-mode)
22318 (or (not (message-in-body-p))
22319 (save-excursion (move-beginning-of-line 1)
22320 (looking-at message-cite-prefix-regexp))))
22321 ;; First ensure filling is correct in message-mode.
22322 (let ((fill-paragraph-function
22323 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22324 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22325 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22326 (paragraph-separate
22327 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22328 (fill-paragraph nil))
22329 (with-syntax-table org-mode-transpose-word-syntax-table
22330 ;; Move to end of line in order to get the first paragraph
22331 ;; within a plain list or a footnote definition.
22332 (let ((element (save-excursion
22333 (end-of-line)
22334 (or (ignore-errors (org-element-at-point))
22335 (user-error "An element cannot be parsed line %d"
22336 (line-number-at-pos (point)))))))
22337 ;; First check if point is in a blank line at the beginning of
22338 ;; the buffer. In that case, ignore filling.
22339 (case (org-element-type element)
22340 ;; Use major mode filling function is src blocks.
22341 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22342 ;; Align Org tables, leave table.el tables as-is.
22343 (table-row (org-table-align) t)
22344 (table
22345 (when (eq (org-element-property :type element) 'org)
22346 (save-excursion
22347 (goto-char (org-element-property :post-affiliated element))
22348 (org-table-align)))
22350 (paragraph
22351 ;; Paragraphs may contain `line-break' type objects.
22352 (let ((beg (max (point-min)
22353 (org-element-property :contents-begin element)))
22354 (end (min (point-max)
22355 (org-element-property :contents-end element))))
22356 ;; Do nothing if point is at an affiliated keyword.
22357 (if (< (line-end-position) beg) t
22358 (when (derived-mode-p 'message-mode)
22359 ;; In `message-mode', do not fill following citation
22360 ;; in current paragraph nor text before message body.
22361 (let ((body-start (save-excursion (message-goto-body))))
22362 (when body-start (setq beg (max body-start beg))))
22363 (when (save-excursion
22364 (re-search-forward
22365 (concat "^" message-cite-prefix-regexp) end t))
22366 (setq end (match-beginning 0))))
22367 ;; Fill paragraph, taking line breaks into account.
22368 ;; For that, slice the paragraph using line breaks as
22369 ;; separators, and fill the parts in reverse order to
22370 ;; avoid messing with markers.
22371 (save-excursion
22372 (goto-char end)
22373 (mapc
22374 (lambda (pos)
22375 (fill-region-as-paragraph pos (point) justify)
22376 (goto-char pos))
22377 ;; Find the list of ending positions for line breaks
22378 ;; in the current paragraph. Add paragraph
22379 ;; beginning to include first slice.
22380 (nreverse
22381 (cons beg
22382 (org-element-map
22383 (org-element--parse-objects
22384 beg end nil (org-element-restriction 'paragraph))
22385 'line-break
22386 (lambda (lb) (org-element-property :end lb)))))))
22387 t)))
22388 ;; Contents of `comment-block' type elements should be
22389 ;; filled as plain text, but only if point is within block
22390 ;; markers.
22391 (comment-block
22392 (let* ((case-fold-search t)
22393 (beg (save-excursion
22394 (goto-char (org-element-property :begin element))
22395 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22396 (forward-line)
22397 (point)))
22398 (end (save-excursion
22399 (goto-char (org-element-property :end element))
22400 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22401 (line-beginning-position))))
22402 (if (or (< (point) beg) (> (point) end)) t
22403 (fill-region-as-paragraph
22404 (save-excursion (end-of-line)
22405 (re-search-backward "^[ \t]*$" beg 'move)
22406 (line-beginning-position))
22407 (save-excursion (beginning-of-line)
22408 (re-search-forward "^[ \t]*$" end 'move)
22409 (line-beginning-position))
22410 justify))))
22411 ;; Fill comments.
22412 (comment
22413 (let ((begin (org-element-property :post-affiliated element))
22414 (end (org-element-property :end element)))
22415 (when (and (>= (point) begin) (<= (point) end))
22416 (let ((begin (save-excursion
22417 (end-of-line)
22418 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22419 (progn (forward-line) (point))
22420 begin)))
22421 (end (save-excursion
22422 (end-of-line)
22423 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22424 (1- (line-beginning-position))
22425 (skip-chars-backward " \r\t\n")
22426 (line-end-position)))))
22427 ;; Do not fill comments when at a blank line.
22428 (when (> end begin)
22429 (let ((fill-prefix
22430 (save-excursion
22431 (beginning-of-line)
22432 (looking-at "[ \t]*#")
22433 (let ((comment-prefix (match-string 0)))
22434 (goto-char (match-end 0))
22435 (if (looking-at adaptive-fill-regexp)
22436 (concat comment-prefix (match-string 0))
22437 (concat comment-prefix " "))))))
22438 (save-excursion
22439 (fill-region-as-paragraph begin end justify))))))
22441 ;; Ignore every other element.
22442 (otherwise t))))))
22444 (defun org-auto-fill-function ()
22445 "Auto-fill function."
22446 ;; Check if auto-filling is meaningful.
22447 (let ((fc (current-fill-column)))
22448 (when (and fc (> (current-column) fc))
22449 (let* ((fill-prefix (org-adaptive-fill-function))
22450 ;; Enforce empty fill prefix, if required. Otherwise, it
22451 ;; will be computed again.
22452 (adaptive-fill-mode (not (equal fill-prefix ""))))
22453 (when fill-prefix (do-auto-fill))))))
22455 (defun org-comment-line-break-function (&optional soft)
22456 "Break line at point and indent, continuing comment if within one.
22457 The inserted newline is marked hard if variable
22458 `use-hard-newlines' is true, unless optional argument SOFT is
22459 non-nil."
22460 (if soft (insert-and-inherit ?\n) (newline 1))
22461 (save-excursion (forward-char -1) (delete-horizontal-space))
22462 (delete-horizontal-space)
22463 (indent-to-left-margin)
22464 (insert-before-markers-and-inherit fill-prefix))
22467 ;;; Comments
22469 ;; Org comments syntax is quite complex. It requires the entire line
22470 ;; to be just a comment. Also, even with the right syntax at the
22471 ;; beginning of line, some some elements (i.e. verse-block or
22472 ;; example-block) don't accept comments. Usual Emacs comment commands
22473 ;; cannot cope with those requirements. Therefore, Org replaces them.
22475 ;; Org still relies on `comment-dwim', but cannot trust
22476 ;; `comment-only-p'. So, `comment-region-function' and
22477 ;; `uncomment-region-function' both point
22478 ;; to`org-comment-or-uncomment-region'. Eventually,
22479 ;; `org-insert-comment' takes care of insertion of comments at the
22480 ;; beginning of line.
22482 ;; `org-setup-comments-handling' install comments related variables
22483 ;; during `org-mode' initialization.
22485 (defun org-setup-comments-handling ()
22486 (interactive)
22487 (org-set-local 'comment-use-syntax nil)
22488 (org-set-local 'comment-start "# ")
22489 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22490 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22491 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22492 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22494 (defun org-insert-comment ()
22495 "Insert an empty comment above current line.
22496 If the line is empty, insert comment at its beginning."
22497 (beginning-of-line)
22498 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22499 (org-indent-line)
22500 (insert "# "))
22502 (defvar comment-empty-lines) ; From newcomment.el.
22503 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22504 "Comment or uncomment each non-blank line in the region.
22505 Uncomment each non-blank line between BEG and END if it only
22506 contains commented lines. Otherwise, comment them."
22507 (save-restriction
22508 ;; Restrict region
22509 (narrow-to-region (save-excursion (goto-char beg)
22510 (skip-chars-forward " \r\t\n" end)
22511 (line-beginning-position))
22512 (save-excursion (goto-char end)
22513 (skip-chars-backward " \r\t\n" beg)
22514 (line-end-position)))
22515 (let ((uncommentp
22516 ;; UNCOMMENTP is non-nil when every non blank line between
22517 ;; BEG and END is a comment.
22518 (save-excursion
22519 (goto-char (point-min))
22520 (while (and (not (eobp))
22521 (let ((element (org-element-at-point)))
22522 (and (eq (org-element-type element) 'comment)
22523 (goto-char (min (point-max)
22524 (org-element-property
22525 :end element)))))))
22526 (eobp))))
22527 (if uncommentp
22528 ;; Only blank lines and comments in region: uncomment it.
22529 (save-excursion
22530 (goto-char (point-min))
22531 (while (not (eobp))
22532 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22533 (replace-match "" nil nil nil 1))
22534 (forward-line)))
22535 ;; Comment each line in region.
22536 (let ((min-indent (point-max)))
22537 ;; First find the minimum indentation across all lines.
22538 (save-excursion
22539 (goto-char (point-min))
22540 (while (and (not (eobp)) (not (zerop min-indent)))
22541 (unless (looking-at "[ \t]*$")
22542 (setq min-indent (min min-indent (current-indentation))))
22543 (forward-line)))
22544 ;; Then loop over all lines.
22545 (save-excursion
22546 (goto-char (point-min))
22547 (while (not (eobp))
22548 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22549 ;; Don't get fooled by invisible text (e.g. link path)
22550 ;; when moving to column MIN-INDENT.
22551 (let ((buffer-invisibility-spec nil))
22552 (org-move-to-column min-indent t))
22553 (insert comment-start))
22554 (forward-line))))))))
22557 ;;; Planning
22559 ;; This section contains tools to operate on timestamp objects, as
22560 ;; returned by, e.g. `org-element-context'.
22562 (defun org-timestamp-has-time-p (timestamp)
22563 "Non-nil when TIMESTAMP has a time specified."
22564 (org-element-property :hour-start timestamp))
22566 (defun org-timestamp-format (timestamp format &optional end utc)
22567 "Format a TIMESTAMP element into a string.
22569 FORMAT is a format specifier to be passed to
22570 `format-time-string'.
22572 When optional argument END is non-nil, use end of date-range or
22573 time-range, if possible.
22575 When optional argument UTC is non-nil, time will be expressed as
22576 Universal Time."
22577 (format-time-string
22578 format
22579 (apply 'encode-time
22580 (cons 0
22581 (mapcar
22582 (lambda (prop) (or (org-element-property prop timestamp) 0))
22583 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22584 '(:minute-start :hour-start :day-start :month-start
22585 :year-start)))))
22586 utc))
22588 (defun org-timestamp-split-range (timestamp &optional end)
22589 "Extract a timestamp object from a date or time range.
22591 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22592 the end of the range. Otherwise, extract its start.
22594 Return a new timestamp object sharing the same parent as
22595 TIMESTAMP."
22596 (let ((type (org-element-property :type timestamp)))
22597 (if (memq type '(active inactive diary)) timestamp
22598 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22599 ;; Set new type.
22600 (org-element-put-property
22601 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22602 ;; Copy start properties over end properties if END is
22603 ;; non-nil. Otherwise, copy end properties over `start' ones.
22604 (let ((p-alist '((:minute-start . :minute-end)
22605 (:hour-start . :hour-end)
22606 (:day-start . :day-end)
22607 (:month-start . :month-end)
22608 (:year-start . :year-end))))
22609 (dolist (p-cell p-alist)
22610 (org-element-put-property
22611 split-ts
22612 (funcall (if end 'car 'cdr) p-cell)
22613 (org-element-property
22614 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22615 ;; Eventually refresh `:raw-value'.
22616 (org-element-put-property split-ts :raw-value nil)
22617 (org-element-put-property
22618 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22620 (defun org-timestamp-translate (timestamp &optional boundary)
22621 "Apply `org-translate-time' on a TIMESTAMP object.
22622 When optional argument BOUNDARY is non-nil, it is either the
22623 symbol `start' or `end'. In this case, only translate the
22624 starting or ending part of TIMESTAMP if it is a date or time
22625 range. Otherwise, translate both parts."
22626 (if (and (not boundary)
22627 (memq (org-element-property :type timestamp)
22628 '(active-range inactive-range)))
22629 (concat
22630 (org-translate-time
22631 (org-element-property :raw-value
22632 (org-timestamp-split-range timestamp)))
22633 "--"
22634 (org-translate-time
22635 (org-element-property :raw-value
22636 (org-timestamp-split-range timestamp t))))
22637 (org-translate-time
22638 (org-element-property
22639 :raw-value
22640 (if (not boundary) timestamp
22641 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22645 ;;; Other stuff.
22647 (defun org-toggle-fixed-width-section (arg)
22648 "Toggle the fixed-width export.
22649 If there is no active region, the QUOTE keyword at the current headline is
22650 inserted or removed. When present, it causes the text between this headline
22651 and the next to be exported as fixed-width text, and unmodified.
22652 If there is an active region, this command adds or removes a colon as the
22653 first character of this line. If the first character of a line is a colon,
22654 this line is also exported in fixed-width font."
22655 (interactive "P")
22656 (let* ((cc 0)
22657 (regionp (org-region-active-p))
22658 (beg (if regionp (region-beginning) (point)))
22659 (end (if regionp (region-end)))
22660 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22661 (case-fold-search nil)
22662 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22663 off)
22664 (if regionp
22665 (save-excursion
22666 (goto-char beg)
22667 (setq cc (current-column))
22668 (beginning-of-line 1)
22669 (setq off (looking-at re))
22670 (while (> nlines 0)
22671 (setq nlines (1- nlines))
22672 (beginning-of-line 1)
22673 (cond
22674 (arg
22675 (org-move-to-column cc t)
22676 (insert ": \n")
22677 (forward-line -1))
22678 ((and off (looking-at re))
22679 (replace-match "" t t nil 1))
22680 ((not off) (org-move-to-column cc t) (insert ": ")))
22681 (forward-line 1)))
22682 (save-excursion
22683 (org-back-to-heading)
22684 (cond
22685 ((looking-at (format org-heading-keyword-regexp-format
22686 org-quote-string))
22687 (goto-char (match-end 1))
22688 (looking-at (concat " +" org-quote-string))
22689 (replace-match "" t t)
22690 (when (eolp) (insert " ")))
22691 ((looking-at org-outline-regexp)
22692 (goto-char (match-end 0))
22693 (insert org-quote-string " ")))))))
22695 (defun org-reftex-citation ()
22696 "Use reftex-citation to insert a citation into the buffer.
22697 This looks for a line like
22699 #+BIBLIOGRAPHY: foo plain option:-d
22701 and derives from it that foo.bib is the bibliography file relevant
22702 for this document. It then installs the necessary environment for RefTeX
22703 to work in this buffer and calls `reftex-citation' to insert a citation
22704 into the buffer.
22706 Export of such citations to both LaTeX and HTML is handled by the contributed
22707 package ox-bibtex by Taru Karttunen."
22708 (interactive)
22709 (let ((reftex-docstruct-symbol 'rds)
22710 (reftex-cite-format "\\cite{%l}")
22711 rds bib)
22712 (save-excursion
22713 (save-restriction
22714 (widen)
22715 (let ((case-fold-search t)
22716 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22717 (if (not (save-excursion
22718 (or (re-search-forward re nil t)
22719 (re-search-backward re nil t))))
22720 (error "No bibliography defined in file")
22721 (setq bib (concat (match-string 1) ".bib")
22722 rds (list (list 'bib bib)))))))
22723 (call-interactively 'reftex-citation)))
22725 ;;;; Functions extending outline functionality
22727 (defun org-beginning-of-line (&optional arg)
22728 "Go to the beginning of the current line. If that is invisible, continue
22729 to a visible line beginning. This makes the function of C-a more intuitive.
22730 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22731 first attempt, and only move to after the tags when the cursor is already
22732 beyond the end of the headline."
22733 (interactive "P")
22734 (let ((pos (point))
22735 (special (if (consp org-special-ctrl-a/e)
22736 (car org-special-ctrl-a/e)
22737 org-special-ctrl-a/e))
22738 deactivate-mark refpos)
22739 (if (org-bound-and-true-p visual-line-mode)
22740 (beginning-of-visual-line 1)
22741 (beginning-of-line 1))
22742 (if (and arg (fboundp 'move-beginning-of-line))
22743 (call-interactively 'move-beginning-of-line)
22744 (if (bobp)
22746 (backward-char 1)
22747 (if (org-truely-invisible-p)
22748 (while (and (not (bobp)) (org-truely-invisible-p))
22749 (backward-char 1)
22750 (beginning-of-line 1))
22751 (forward-char 1))))
22752 (when special
22753 (cond
22754 ((and (looking-at org-complex-heading-regexp)
22755 (= (char-after (match-end 1)) ?\ ))
22756 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22757 (point-at-eol)))
22758 (goto-char
22759 (if (eq special t)
22760 (cond ((> pos refpos) refpos)
22761 ((= pos (point)) refpos)
22762 (t (point)))
22763 (cond ((> pos (point)) (point))
22764 ((not (eq last-command this-command)) (point))
22765 (t refpos)))))
22766 ((org-at-item-p)
22767 ;; Being at an item and not looking at an the item means point
22768 ;; was previously moved to beginning of a visual line, which
22769 ;; doesn't contain the item. Therefore, do nothing special,
22770 ;; just stay here.
22771 (when (looking-at org-list-full-item-re)
22772 ;; Set special position at first white space character after
22773 ;; bullet, and check-box, if any.
22774 (let ((after-bullet
22775 (let ((box (match-end 3)))
22776 (if (not box) (match-end 1)
22777 (let ((after (char-after box)))
22778 (if (and after (= after ? )) (1+ box) box))))))
22779 ;; Special case: Move point to special position when
22780 ;; currently after it or at beginning of line.
22781 (if (eq special t)
22782 (when (or (> pos after-bullet) (= (point) pos))
22783 (goto-char after-bullet))
22784 ;; Reversed case: Move point to special position when
22785 ;; point was already at beginning of line and command is
22786 ;; repeated.
22787 (when (and (= (point) pos) (eq last-command this-command))
22788 (goto-char after-bullet))))))))
22789 (org-no-warnings
22790 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22791 (setq disable-point-adjustment
22792 (or (not (invisible-p (point)))
22793 (not (invisible-p (max (point-min) (1- (point))))))))
22795 (defun org-end-of-line (&optional arg)
22796 "Go to the end of the line.
22797 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22798 tags on the first attempt, and only move to after the tags when
22799 the cursor is already beyond the end of the headline."
22800 (interactive "P")
22801 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22802 org-special-ctrl-a/e))
22803 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22804 'end-of-visual-line)
22805 ((fboundp 'move-end-of-line) 'move-end-of-line)
22806 (t 'end-of-line)))
22807 deactivate-mark)
22808 (if (or (not special) arg) (call-interactively move-fun)
22809 (let* ((element (save-excursion (beginning-of-line)
22810 (org-element-at-point)))
22811 (type (org-element-type element)))
22812 (cond
22813 ((memq type '(headline inlinetask))
22814 (let ((pos (point)))
22815 (beginning-of-line 1)
22816 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22817 (if (eq special t)
22818 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22819 (goto-char (match-beginning 1))
22820 (goto-char (match-end 0)))
22821 (if (or (< pos (match-end 0))
22822 (not (eq this-command last-command)))
22823 (goto-char (match-end 0))
22824 (goto-char (match-beginning 1))))
22825 (call-interactively move-fun))))
22826 ((outline-invisible-p (line-end-position))
22827 ;; If element is hidden, `move-end-of-line' would put point
22828 ;; after it. Use `end-of-line' to stay on current line.
22829 (call-interactively 'end-of-line))
22830 (t (call-interactively move-fun)))))
22831 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22832 (setq disable-point-adjustment
22833 (or (not (invisible-p (point)))
22834 (not (invisible-p (max (point-min) (1- (point))))))))
22836 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22837 (define-key org-mode-map "\C-e" 'org-end-of-line)
22839 (defun org-backward-sentence (&optional arg)
22840 "Go to beginning of sentence, or beginning of table field.
22841 This will call `backward-sentence' or `org-table-beginning-of-field',
22842 depending on context."
22843 (interactive "P")
22844 (cond
22845 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22846 (t (call-interactively 'backward-sentence))))
22848 (defun org-forward-sentence (&optional arg)
22849 "Go to end of sentence, or end of table field.
22850 This will call `forward-sentence' or `org-table-end-of-field',
22851 depending on context."
22852 (interactive "P")
22853 (cond
22854 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22855 (t (call-interactively 'forward-sentence))))
22857 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22858 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22860 (defun org-kill-line (&optional arg)
22861 "Kill line, to tags or end of line."
22862 (interactive "P")
22863 (cond
22864 ((or (not org-special-ctrl-k)
22865 (bolp)
22866 (not (org-at-heading-p)))
22867 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22868 org-ctrl-k-protect-subtree)
22869 (if (or (eq org-ctrl-k-protect-subtree 'error)
22870 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22871 (user-error "C-k aborted as it would kill a hidden subtree")))
22872 (call-interactively
22873 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22874 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22875 (kill-region (point) (match-beginning 1))
22876 (org-set-tags nil t))
22877 (t (kill-region (point) (point-at-eol)))))
22879 (define-key org-mode-map "\C-k" 'org-kill-line)
22881 (defun org-yank (&optional arg)
22882 "Yank. If the kill is a subtree, treat it specially.
22883 This command will look at the current kill and check if is a single
22884 subtree, or a series of subtrees[1]. If it passes the test, and if the
22885 cursor is at the beginning of a line or after the stars of a currently
22886 empty headline, then the yank is handled specially. How exactly depends
22887 on the value of the following variables, both set by default.
22889 org-yank-folded-subtrees
22890 When set, the subtree(s) will be folded after insertion, but only
22891 if doing so would now swallow text after the yanked text.
22893 org-yank-adjusted-subtrees
22894 When set, the subtree will be promoted or demoted in order to
22895 fit into the local outline tree structure, which means that the level
22896 will be adjusted so that it becomes the smaller one of the two
22897 *visible* surrounding headings.
22899 Any prefix to this command will cause `yank' to be called directly with
22900 no special treatment. In particular, a simple \\[universal-argument] prefix \
22901 will just
22902 plainly yank the text as it is.
22904 \[1] The test checks if the first non-white line is a heading
22905 and if there are no other headings with fewer stars."
22906 (interactive "P")
22907 (org-yank-generic 'yank arg))
22909 (defun org-yank-generic (command arg)
22910 "Perform some yank-like command.
22912 This function implements the behavior described in the `org-yank'
22913 documentation. However, it has been generalized to work for any
22914 interactive command with similar behavior."
22916 ;; pretend to be command COMMAND
22917 (setq this-command command)
22919 (if arg
22920 (call-interactively command)
22922 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22923 (and (org-kill-is-subtree-p)
22924 (or (bolp)
22925 (and (looking-at "[ \t]*$")
22926 (string-match
22927 "\\`\\*+\\'"
22928 (buffer-substring (point-at-bol) (point)))))))
22929 swallowp)
22930 (cond
22931 ((and subtreep org-yank-folded-subtrees)
22932 (let ((beg (point))
22933 end)
22934 (if (and subtreep org-yank-adjusted-subtrees)
22935 (org-paste-subtree nil nil 'for-yank)
22936 (call-interactively command))
22938 (setq end (point))
22939 (goto-char beg)
22940 (when (and (bolp) subtreep
22941 (not (setq swallowp
22942 (org-yank-folding-would-swallow-text beg end))))
22943 (org-with-limited-levels
22944 (or (looking-at org-outline-regexp)
22945 (re-search-forward org-outline-regexp-bol end t))
22946 (while (and (< (point) end) (looking-at org-outline-regexp))
22947 (hide-subtree)
22948 (org-cycle-show-empty-lines 'folded)
22949 (condition-case nil
22950 (outline-forward-same-level 1)
22951 (error (goto-char end))))))
22952 (when swallowp
22953 (message
22954 "Inserted text not folded because that would swallow text"))
22956 (goto-char end)
22957 (skip-chars-forward " \t\n\r")
22958 (beginning-of-line 1)
22959 (push-mark beg 'nomsg)))
22960 ((and subtreep org-yank-adjusted-subtrees)
22961 (let ((beg (point-at-bol)))
22962 (org-paste-subtree nil nil 'for-yank)
22963 (push-mark beg 'nomsg)))
22965 (call-interactively command))))))
22967 (defun org-yank-folding-would-swallow-text (beg end)
22968 "Would hide-subtree at BEG swallow any text after END?"
22969 (let (level)
22970 (org-with-limited-levels
22971 (save-excursion
22972 (goto-char beg)
22973 (when (or (looking-at org-outline-regexp)
22974 (re-search-forward org-outline-regexp-bol end t))
22975 (setq level (org-outline-level)))
22976 (goto-char end)
22977 (skip-chars-forward " \t\r\n\v\f")
22978 (if (or (eobp)
22979 (and (bolp) (looking-at org-outline-regexp)
22980 (<= (org-outline-level) level)))
22981 nil ; Nothing would be swallowed
22982 t))))) ; something would swallow
22984 (define-key org-mode-map "\C-y" 'org-yank)
22986 (defun org-truely-invisible-p ()
22987 "Check if point is at a character currently not visible.
22988 This version does not only check the character property, but also
22989 `visible-mode'."
22990 ;; Early versions of noutline don't have `outline-invisible-p'.
22991 (if (org-bound-and-true-p visible-mode)
22993 (outline-invisible-p)))
22995 (defun org-invisible-p2 ()
22996 "Check if point is at a character currently not visible."
22997 (save-excursion
22998 (if (and (eolp) (not (bobp))) (backward-char 1))
22999 ;; Early versions of noutline don't have `outline-invisible-p'.
23000 (outline-invisible-p)))
23002 (defun org-back-to-heading (&optional invisible-ok)
23003 "Call `outline-back-to-heading', but provide a better error message."
23004 (condition-case nil
23005 (outline-back-to-heading invisible-ok)
23006 (error (error "Before first headline at position %d in buffer %s"
23007 (point) (current-buffer)))))
23009 (defun org-before-first-heading-p ()
23010 "Before first heading?"
23011 (save-excursion
23012 (end-of-line)
23013 (null (re-search-backward org-outline-regexp-bol nil t))))
23015 (defun org-at-heading-p (&optional ignored)
23016 (outline-on-heading-p t))
23017 ;; Compatibility alias with Org versions < 7.8.03
23018 (defalias 'org-on-heading-p 'org-at-heading-p)
23020 (defun org-at-comment-p nil
23021 "Is cursor in a line starting with a # character?"
23022 (save-excursion
23023 (beginning-of-line)
23024 (looking-at "^#")))
23026 (defun org-at-drawer-p nil
23027 "Is cursor at a drawer keyword?"
23028 (save-excursion
23029 (move-beginning-of-line 1)
23030 (looking-at org-drawer-regexp)))
23032 (defun org-at-block-p nil
23033 "Is cursor at a block keyword?"
23034 (save-excursion
23035 (move-beginning-of-line 1)
23036 (looking-at org-block-regexp)))
23038 (defun org-point-at-end-of-empty-headline ()
23039 "If point is at the end of an empty headline, return t, else nil.
23040 If the heading only contains a TODO keyword, it is still still considered
23041 empty."
23042 (and (looking-at "[ \t]*$")
23043 (when org-todo-line-regexp
23044 (save-excursion
23045 (beginning-of-line 1)
23046 (let ((case-fold-search nil))
23047 (looking-at org-todo-line-regexp)
23048 (string= (match-string 3) ""))))))
23050 (defun org-at-heading-or-item-p ()
23051 (or (org-at-heading-p) (org-at-item-p)))
23053 (defun org-at-target-p ()
23054 (or (org-in-regexp org-radio-target-regexp)
23055 (org-in-regexp org-target-regexp)))
23056 ;; Compatibility alias with Org versions < 7.8.03
23057 (defalias 'org-on-target-p 'org-at-target-p)
23059 (defun org-up-heading-all (arg)
23060 "Move to the heading line of which the present line is a subheading.
23061 This function considers both visible and invisible heading lines.
23062 With argument, move up ARG levels."
23063 (if (fboundp 'outline-up-heading-all)
23064 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23065 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23067 (defun org-up-heading-safe ()
23068 "Move to the heading line of which the present line is a subheading.
23069 This version will not throw an error. It will return the level of the
23070 headline found, or nil if no higher level is found.
23072 Also, this function will be a lot faster than `outline-up-heading',
23073 because it relies on stars being the outline starters. This can really
23074 make a significant difference in outlines with very many siblings."
23075 (let (start-level re)
23076 (org-back-to-heading t)
23077 (setq start-level (funcall outline-level))
23078 (if (equal start-level 1)
23080 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23081 (if (re-search-backward re nil t)
23082 (funcall outline-level)))))
23084 (defun org-first-sibling-p ()
23085 "Is this heading the first child of its parents?"
23086 (interactive)
23087 (let ((re org-outline-regexp-bol)
23088 level l)
23089 (unless (org-at-heading-p t)
23090 (user-error "Not at a heading"))
23091 (setq level (funcall outline-level))
23092 (save-excursion
23093 (if (not (re-search-backward re nil t))
23095 (setq l (funcall outline-level))
23096 (< l level)))))
23098 (defun org-goto-sibling (&optional previous)
23099 "Goto the next sibling, even if it is invisible.
23100 When PREVIOUS is set, go to the previous sibling instead. Returns t
23101 when a sibling was found. When none is found, return nil and don't
23102 move point."
23103 (let ((fun (if previous 're-search-backward 're-search-forward))
23104 (pos (point))
23105 (re org-outline-regexp-bol)
23106 level l)
23107 (when (condition-case nil (org-back-to-heading t) (error nil))
23108 (setq level (funcall outline-level))
23109 (catch 'exit
23110 (or previous (forward-char 1))
23111 (while (funcall fun re nil t)
23112 (setq l (funcall outline-level))
23113 (when (< l level) (goto-char pos) (throw 'exit nil))
23114 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23115 (goto-char pos)
23116 nil))))
23118 (defun org-show-siblings ()
23119 "Show all siblings of the current headline."
23120 (save-excursion
23121 (while (org-goto-sibling) (org-flag-heading nil)))
23122 (save-excursion
23123 (while (org-goto-sibling 'previous)
23124 (org-flag-heading nil))))
23126 (defun org-goto-first-child ()
23127 "Goto the first child, even if it is invisible.
23128 Return t when a child was found. Otherwise don't move point and
23129 return nil."
23130 (let (level (pos (point)) (re org-outline-regexp-bol))
23131 (when (condition-case nil (org-back-to-heading t) (error nil))
23132 (setq level (outline-level))
23133 (forward-char 1)
23134 (if (and (re-search-forward re nil t) (> (outline-level) level))
23135 (progn (goto-char (match-beginning 0)) t)
23136 (goto-char pos) nil))))
23138 (defun org-show-hidden-entry ()
23139 "Show an entry where even the heading is hidden."
23140 (save-excursion
23141 (org-show-entry)))
23143 (defun org-flag-heading (flag &optional entry)
23144 "Flag the current heading. FLAG non-nil means make invisible.
23145 When ENTRY is non-nil, show the entire entry."
23146 (save-excursion
23147 (org-back-to-heading t)
23148 ;; Check if we should show the entire entry
23149 (if entry
23150 (progn
23151 (org-show-entry)
23152 (save-excursion
23153 (and (outline-next-heading)
23154 (org-flag-heading nil))))
23155 (outline-flag-region (max (point-min) (1- (point)))
23156 (save-excursion (outline-end-of-heading) (point))
23157 flag))))
23159 (defun org-get-next-sibling ()
23160 "Move to next heading of the same level, and return point.
23161 If there is no such heading, return nil.
23162 This is like outline-next-sibling, but invisible headings are ok."
23163 (let ((level (funcall outline-level)))
23164 (outline-next-heading)
23165 (while (and (not (eobp)) (> (funcall outline-level) level))
23166 (outline-next-heading))
23167 (if (or (eobp) (< (funcall outline-level) level))
23169 (point))))
23171 (defun org-get-last-sibling ()
23172 "Move to previous heading of the same level, and return point.
23173 If there is no such heading, return nil."
23174 (let ((opoint (point))
23175 (level (funcall outline-level)))
23176 (outline-previous-heading)
23177 (when (and (/= (point) opoint) (outline-on-heading-p t))
23178 (while (and (> (funcall outline-level) level)
23179 (not (bobp)))
23180 (outline-previous-heading))
23181 (if (< (funcall outline-level) level)
23183 (point)))))
23185 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23186 "Goto to the end of a subtree."
23187 ;; This contains an exact copy of the original function, but it uses
23188 ;; `org-back-to-heading', to make it work also in invisible
23189 ;; trees. And is uses an invisible-ok argument.
23190 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23191 ;; Furthermore, when used inside Org, finding the end of a large subtree
23192 ;; with many children and grandchildren etc, this can be much faster
23193 ;; than the outline version.
23194 (org-back-to-heading invisible-ok)
23195 (let ((first t)
23196 (level (funcall outline-level)))
23197 (if (and (derived-mode-p 'org-mode) (< level 1000))
23198 ;; A true heading (not a plain list item), in Org-mode
23199 ;; This means we can easily find the end by looking
23200 ;; only for the right number of stars. Using a regexp to do
23201 ;; this is so much faster than using a Lisp loop.
23202 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23203 (forward-char 1)
23204 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23205 ;; something else, do it the slow way
23206 (while (and (not (eobp))
23207 (or first (> (funcall outline-level) level)))
23208 (setq first nil)
23209 (outline-next-heading)))
23210 (unless to-heading
23211 (if (memq (preceding-char) '(?\n ?\^M))
23212 (progn
23213 ;; Go to end of line before heading
23214 (forward-char -1)
23215 (if (memq (preceding-char) '(?\n ?\^M))
23216 ;; leave blank line before heading
23217 (forward-char -1))))))
23218 (point))
23220 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23221 "Use Org version in org-mode, for dramatic speed-up."
23222 (if (derived-mode-p 'org-mode)
23223 (progn
23224 (org-end-of-subtree nil t)
23225 (unless (eobp) (backward-char 1)))
23226 ad-do-it))
23228 (defun org-end-of-meta-data-and-drawers ()
23229 "Jump to the first text after meta data and drawers in the current entry.
23230 This will move over empty lines, lines with planning time stamps,
23231 clocking lines, and drawers."
23232 (org-back-to-heading t)
23233 (let ((end (save-excursion (outline-next-heading) (point)))
23234 (re (concat "\\(" org-drawer-regexp "\\)"
23235 "\\|" "[ \t]*" org-keyword-time-regexp)))
23236 (forward-line 1)
23237 (while (re-search-forward re end t)
23238 (if (not (match-end 1))
23239 ;; empty or planning line
23240 (forward-line 1)
23241 ;; a drawer, find the end
23242 (re-search-forward "^[ \t]*:END:" end 'move)
23243 (forward-line 1)))
23244 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23245 (point)))
23247 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23248 "Move forward to the ARG'th subheading at same level as this one.
23249 Stop at the first and last subheadings of a superior heading.
23250 Normally this only looks at visible headings, but when INVISIBLE-OK is
23251 non-nil it will also look at invisible ones."
23252 (interactive "p")
23253 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23254 (if (and arg (< arg 0))
23255 (goto-char (point-min))
23256 (outline-next-heading))
23257 (org-at-heading-p)
23258 (let ((level (- (match-end 0) (match-beginning 0) 1))
23259 (f (if (and arg (< arg 0))
23260 're-search-backward
23261 're-search-forward))
23262 (count (if arg (abs arg) 1))
23263 (result (point)))
23264 (while (and (prog1 (> count 0)
23265 (forward-char (if (and arg (< arg 0)) -1 1)))
23266 (funcall f org-outline-regexp-bol nil 'move))
23267 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23268 (cond ((< l level) (setq count 0))
23269 ((and (= l level)
23270 (or invisible-ok
23271 (progn
23272 (goto-char (line-beginning-position))
23273 (not (outline-invisible-p)))))
23274 (setq count (1- count))
23275 (when (eq l level)
23276 (setq result (point)))))))
23277 (goto-char result))
23278 (beginning-of-line 1)))
23280 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23281 "Move backward to the ARG'th subheading at same level as this one.
23282 Stop at the first and last subheadings of a superior heading."
23283 (interactive "p")
23284 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23286 (defun org-next-block (arg &optional backward block-regexp)
23287 "Jump to the next block.
23288 With a prefix argument ARG, jump forward ARG many source blocks.
23289 When BACKWARD is non-nil, jump to the previous block.
23290 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23291 (interactive "p")
23292 (let ((re (or block-regexp org-block-regexp))
23293 (re-search-fn (or (and backward 're-search-backward)
23294 're-search-forward)))
23295 (if (looking-at re) (forward-char 1))
23296 (condition-case nil
23297 (funcall re-search-fn re nil nil arg)
23298 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23299 (goto-char (match-beginning 0)) (org-show-context)))
23301 (defun org-previous-block (arg &optional block-regexp)
23302 "Jump to the previous block.
23303 With a prefix argument ARG, jump backward ARG many source blocks.
23304 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23305 (interactive "p")
23306 (org-next-block arg t block-regexp))
23308 (defun org-forward-paragraph ()
23309 "Move forward to beginning of next paragraph or equivalent.
23311 The function moves point to the beginning of the next visible
23312 structural element, which can be a paragraph, a table, a list
23313 item, etc. It also provides some special moves for convenience:
23315 - On an affiliated keyword, jump to the beginning of the
23316 relative element.
23317 - On an item or a footnote definition, move to the second
23318 element inside, if any.
23319 - On a table or a property drawer, jump after it.
23320 - On a verse or source block, stop after blank lines."
23321 (interactive)
23322 (when (eobp) (user-error "Cannot move further down"))
23323 (let* ((deactivate-mark nil)
23324 (element (org-element-at-point))
23325 (type (org-element-type element))
23326 (post-affiliated (org-element-property :post-affiliated element))
23327 (contents-begin (org-element-property :contents-begin element))
23328 (contents-end (org-element-property :contents-end element))
23329 (end (let ((end (org-element-property :end element)) (parent element))
23330 (while (and (setq parent (org-element-property :parent parent))
23331 (= (org-element-property :contents-end parent) end))
23332 (setq end (org-element-property :end parent)))
23333 end)))
23334 (cond ((not element)
23335 (skip-chars-forward " \r\t\n")
23336 (or (eobp) (beginning-of-line)))
23337 ;; On affiliated keywords, move to element's beginning.
23338 ((and post-affiliated (< (point) post-affiliated))
23339 (goto-char post-affiliated))
23340 ;; At a table row, move to the end of the table. Similarly,
23341 ;; at a node property, move to the end of the property
23342 ;; drawer.
23343 ((memq type '(node-property table-row))
23344 (goto-char (org-element-property
23345 :end (org-element-property :parent element))))
23346 ((memq type '(property-drawer table)) (goto-char end))
23347 ;; Consider blank lines as separators in verse and source
23348 ;; blocks to ease editing.
23349 ((memq type '(src-block verse-block))
23350 (when (eq type 'src-block)
23351 (setq contents-end
23352 (save-excursion (goto-char end)
23353 (skip-chars-backward " \r\t\n")
23354 (line-beginning-position))))
23355 (beginning-of-line)
23356 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23357 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23358 (goto-char end)
23359 (skip-chars-forward " \r\t\n")
23360 (if (= (point) contents-end) (goto-char end)
23361 (beginning-of-line))))
23362 ;; With no contents, just skip element.
23363 ((not contents-begin) (goto-char end))
23364 ;; If contents are invisible, skip the element altogether.
23365 ((outline-invisible-p (line-end-position))
23366 (case type
23367 (headline
23368 (org-with-limited-levels (outline-next-visible-heading 1)))
23369 ;; At a plain list, make sure we move to the next item
23370 ;; instead of skipping the whole list.
23371 (plain-list (forward-char)
23372 (org-forward-paragraph))
23373 (otherwise (goto-char end))))
23374 ((>= (point) contents-end) (goto-char end))
23375 ((>= (point) contents-begin)
23376 ;; This can only happen on paragraphs and plain lists.
23377 (case type
23378 (paragraph (goto-char end))
23379 ;; At a plain list, try to move to second element in
23380 ;; first item, if possible.
23381 (plain-list (end-of-line)
23382 (org-forward-paragraph))))
23383 ;; When contents start on the middle of a line (e.g. in
23384 ;; items and footnote definitions), try to reach first
23385 ;; element starting after current line.
23386 ((> (line-end-position) contents-begin)
23387 (end-of-line)
23388 (org-forward-paragraph))
23389 (t (goto-char contents-begin)))))
23391 (defun org-backward-paragraph ()
23392 "Move backward to start of previous paragraph or equivalent.
23394 The function moves point to the beginning of the current
23395 structural element, which can be a paragraph, a table, a list
23396 item, etc., or to the beginning of the previous visible one if
23397 point is already there. It also provides some special moves for
23398 convenience:
23400 - On an affiliated keyword, jump to the first one.
23401 - On a table or a property drawer, move to its beginning.
23402 - On a verse or source block, stop before blank lines."
23403 (interactive)
23404 (when (bobp) (user-error "Cannot move further up"))
23405 (let* ((deactivate-mark nil)
23406 (element (org-element-at-point))
23407 (type (org-element-type element))
23408 (contents-begin (org-element-property :contents-begin element))
23409 (contents-end (org-element-property :contents-end element))
23410 (post-affiliated (org-element-property :post-affiliated element))
23411 (begin (org-element-property :begin element)))
23412 (cond
23413 ((not element) (goto-char (point-min)))
23414 ((= (point) begin)
23415 (backward-char)
23416 (org-backward-paragraph))
23417 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23418 ((memq type '(node-property table-row))
23419 (goto-char (org-element-property
23420 :post-affiliated (org-element-property :parent element))))
23421 ((memq type '(property-drawer table)) (goto-char begin))
23422 ((memq type '(src-block verse-block))
23423 (when (eq type 'src-block)
23424 (setq contents-begin
23425 (save-excursion (goto-char begin) (forward-line) (point))))
23426 (if (= (point) contents-begin) (goto-char post-affiliated)
23427 ;; Inside a verse block, see blank lines as paragraph
23428 ;; separators.
23429 (let ((origin (point)))
23430 (skip-chars-backward " \r\t\n" contents-begin)
23431 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23432 (skip-chars-forward " \r\t\n" origin)
23433 (if (= (point) origin) (goto-char contents-begin)
23434 (beginning-of-line))))))
23435 ((not contents-begin) (goto-char (or post-affiliated begin)))
23436 ((eq type 'paragraph)
23437 (goto-char contents-begin)
23438 ;; When at first paragraph in an item or a footnote definition,
23439 ;; move directly to beginning of line.
23440 (let ((parent-contents
23441 (org-element-property
23442 :contents-begin (org-element-property :parent element))))
23443 (when (and parent-contents (= parent-contents contents-begin))
23444 (beginning-of-line))))
23445 ;; At the end of a greater element, move to the beginning of the
23446 ;; last element within.
23447 ((>= (point) contents-end)
23448 (goto-char (1- contents-end))
23449 (org-backward-paragraph))
23450 (t (goto-char (or post-affiliated begin))))
23451 ;; Ensure we never leave point invisible.
23452 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23454 (defun org-forward-element ()
23455 "Move forward by one element.
23456 Move to the next element at the same level, when possible."
23457 (interactive)
23458 (cond ((eobp) (user-error "Cannot move further down"))
23459 ((org-with-limited-levels (org-at-heading-p))
23460 (let ((origin (point)))
23461 (goto-char (org-end-of-subtree nil t))
23462 (unless (org-with-limited-levels (org-at-heading-p))
23463 (goto-char origin)
23464 (user-error "Cannot move further down"))))
23466 (let* ((elem (org-element-at-point))
23467 (end (org-element-property :end elem))
23468 (parent (org-element-property :parent elem)))
23469 (cond ((and parent (= (org-element-property :contents-end parent) end))
23470 (goto-char (org-element-property :end parent)))
23471 ((integer-or-marker-p end) (goto-char end))
23472 (t (message "No element at point")))))))
23474 (defun org-backward-element ()
23475 "Move backward by one element.
23476 Move to the previous element at the same level, when possible."
23477 (interactive)
23478 (cond ((bobp) (user-error "Cannot move further up"))
23479 ((org-with-limited-levels (org-at-heading-p))
23480 ;; At a headline, move to the previous one, if any, or stay
23481 ;; here.
23482 (let ((origin (point)))
23483 (org-with-limited-levels (org-backward-heading-same-level 1))
23484 ;; When current headline has no sibling above, move to its
23485 ;; parent.
23486 (when (= (point) origin)
23487 (or (org-with-limited-levels (org-up-heading-safe))
23488 (progn (goto-char origin)
23489 (user-error "Cannot move further up"))))))
23491 (let* ((trail (org-element-at-point 'keep-trail))
23492 (elem (car trail))
23493 (prev-elem (nth 1 trail))
23494 (beg (org-element-property :begin elem)))
23495 (cond
23496 ;; Move to beginning of current element if point isn't
23497 ;; there already.
23498 ((null beg) (message "No element at point"))
23499 ((/= (point) beg) (goto-char beg))
23500 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23501 ((org-before-first-heading-p) (goto-char (point-min)))
23502 (t (org-back-to-heading)))))))
23504 (defun org-up-element ()
23505 "Move to upper element."
23506 (interactive)
23507 (if (org-with-limited-levels (org-at-heading-p))
23508 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23509 (let* ((elem (org-element-at-point))
23510 (parent (org-element-property :parent elem)))
23511 (if parent (goto-char (org-element-property :begin parent))
23512 (if (org-with-limited-levels (org-before-first-heading-p))
23513 (user-error "No surrounding element")
23514 (org-with-limited-levels (org-back-to-heading)))))))
23516 (defvar org-element-greater-elements)
23517 (defun org-down-element ()
23518 "Move to inner element."
23519 (interactive)
23520 (let ((element (org-element-at-point)))
23521 (cond
23522 ((memq (org-element-type element) '(plain-list table))
23523 (goto-char (org-element-property :contents-begin element))
23524 (forward-char))
23525 ((memq (org-element-type element) org-element-greater-elements)
23526 ;; If contents are hidden, first disclose them.
23527 (when (outline-invisible-p (line-end-position)) (org-cycle))
23528 (goto-char (or (org-element-property :contents-begin element)
23529 (user-error "No content for this element"))))
23530 (t (user-error "No inner element")))))
23532 (defun org-drag-element-backward ()
23533 "Move backward element at point."
23534 (interactive)
23535 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23536 (let* ((trail (org-element-at-point 'keep-trail))
23537 (elem (car trail))
23538 (prev-elem (nth 1 trail)))
23539 ;; Error out if no previous element or previous element is
23540 ;; a parent of the current one.
23541 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23542 (user-error "Cannot drag element backward")
23543 (let ((pos (point)))
23544 (org-element-swap-A-B prev-elem elem)
23545 (goto-char (+ (org-element-property :begin prev-elem)
23546 (- pos (org-element-property :begin elem)))))))))
23548 (defun org-drag-element-forward ()
23549 "Move forward element at point."
23550 (interactive)
23551 (let* ((pos (point))
23552 (elem (org-element-at-point)))
23553 (when (= (point-max) (org-element-property :end elem))
23554 (user-error "Cannot drag element forward"))
23555 (goto-char (org-element-property :end elem))
23556 (let ((next-elem (org-element-at-point)))
23557 (when (or (org-element-nested-p elem next-elem)
23558 (and (eq (org-element-type next-elem) 'headline)
23559 (not (eq (org-element-type elem) 'headline))))
23560 (goto-char pos)
23561 (user-error "Cannot drag element forward"))
23562 ;; Compute new position of point: it's shifted by NEXT-ELEM
23563 ;; body's length (without final blanks) and by the length of
23564 ;; blanks between ELEM and NEXT-ELEM.
23565 (let ((size-next (- (save-excursion
23566 (goto-char (org-element-property :end next-elem))
23567 (skip-chars-backward " \r\t\n")
23568 (forward-line)
23569 ;; Small correction if buffer doesn't end
23570 ;; with a newline character.
23571 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23572 (org-element-property :begin next-elem)))
23573 (size-blank (- (org-element-property :end elem)
23574 (save-excursion
23575 (goto-char (org-element-property :end elem))
23576 (skip-chars-backward " \r\t\n")
23577 (forward-line)
23578 (point)))))
23579 (org-element-swap-A-B elem next-elem)
23580 (goto-char (+ pos size-next size-blank))))))
23582 (defun org-drag-line-forward (arg)
23583 "Drag the line at point ARG lines forward."
23584 (interactive "p")
23585 (dotimes (n (abs arg))
23586 (let ((c (current-column)))
23587 (if (< 0 arg)
23588 (progn
23589 (beginning-of-line 2)
23590 (transpose-lines 1)
23591 (beginning-of-line 0))
23592 (transpose-lines 1)
23593 (beginning-of-line -1))
23594 (org-move-to-column c))))
23596 (defun org-drag-line-backward (arg)
23597 "Drag the line at point ARG lines backward."
23598 (interactive "p")
23599 (org-drag-line-forward (- arg)))
23601 (defun org-mark-element ()
23602 "Put point at beginning of this element, mark at end.
23604 Interactively, if this command is repeated or (in Transient Mark
23605 mode) if the mark is active, it marks the next element after the
23606 ones already marked."
23607 (interactive)
23608 (let (deactivate-mark)
23609 (if (and (org-called-interactively-p 'any)
23610 (or (and (eq last-command this-command) (mark t))
23611 (and transient-mark-mode mark-active)))
23612 (set-mark
23613 (save-excursion
23614 (goto-char (mark))
23615 (goto-char (org-element-property :end (org-element-at-point)))))
23616 (let ((element (org-element-at-point)))
23617 (end-of-line)
23618 (push-mark (org-element-property :end element) t t)
23619 (goto-char (org-element-property :begin element))))))
23621 (defun org-narrow-to-element ()
23622 "Narrow buffer to current element."
23623 (interactive)
23624 (let ((elem (org-element-at-point)))
23625 (cond
23626 ((eq (car elem) 'headline)
23627 (narrow-to-region
23628 (org-element-property :begin elem)
23629 (org-element-property :end elem)))
23630 ((memq (car elem) org-element-greater-elements)
23631 (narrow-to-region
23632 (org-element-property :contents-begin elem)
23633 (org-element-property :contents-end elem)))
23635 (narrow-to-region
23636 (org-element-property :begin elem)
23637 (org-element-property :end elem))))))
23639 (defun org-transpose-element ()
23640 "Transpose current and previous elements, keeping blank lines between.
23641 Point is moved after both elements."
23642 (interactive)
23643 (org-skip-whitespace)
23644 (let ((end (org-element-property :end (org-element-at-point))))
23645 (org-drag-element-backward)
23646 (goto-char end)))
23648 (defun org-unindent-buffer ()
23649 "Un-indent the visible part of the buffer.
23650 Relative indentation (between items, inside blocks, etc.) isn't
23651 modified."
23652 (interactive)
23653 (unless (eq major-mode 'org-mode)
23654 (user-error "Cannot un-indent a buffer not in Org mode"))
23655 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23656 unindent-tree ; For byte-compiler.
23657 (unindent-tree
23658 (function
23659 (lambda (contents)
23660 (mapc
23661 (lambda (element)
23662 (if (memq (org-element-type element) '(headline section))
23663 (funcall unindent-tree (org-element-contents element))
23664 (save-excursion
23665 (save-restriction
23666 (narrow-to-region
23667 (org-element-property :begin element)
23668 (org-element-property :end element))
23669 (org-do-remove-indentation)))))
23670 (reverse contents))))))
23671 (funcall unindent-tree (org-element-contents parse-tree))))
23673 (defun org-show-subtree ()
23674 "Show everything after this heading at deeper levels."
23675 (interactive)
23676 (outline-flag-region
23677 (point)
23678 (save-excursion
23679 (org-end-of-subtree t t))
23680 nil))
23682 (defun org-show-entry ()
23683 "Show the body directly following this heading.
23684 Show the heading too, if it is currently invisible."
23685 (interactive)
23686 (save-excursion
23687 (condition-case nil
23688 (progn
23689 (org-back-to-heading t)
23690 (outline-flag-region
23691 (max (point-min) (1- (point)))
23692 (save-excursion
23693 (if (re-search-forward
23694 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23695 (match-beginning 1)
23696 (point-max)))
23697 nil)
23698 (org-cycle-hide-drawers 'children))
23699 (error nil))))
23701 (defun org-make-options-regexp (kwds &optional extra)
23702 "Make a regular expression for keyword lines."
23703 (concat
23704 "^#\\+\\("
23705 (mapconcat 'regexp-quote kwds "\\|")
23706 (if extra (concat "\\|" extra))
23707 "\\):[ \t]*\\(.*\\)"))
23709 ;; Make isearch reveal the necessary context
23710 (defun org-isearch-end ()
23711 "Reveal context after isearch exits."
23712 (when isearch-success ; only if search was successful
23713 (if (featurep 'xemacs)
23714 ;; Under XEmacs, the hook is run in the correct place,
23715 ;; we directly show the context.
23716 (org-show-context 'isearch)
23717 ;; In Emacs the hook runs *before* restoring the overlays.
23718 ;; So we have to use a one-time post-command-hook to do this.
23719 ;; (Emacs 22 has a special variable, see function `org-mode')
23720 (unless (and (boundp 'isearch-mode-end-hook-quit)
23721 isearch-mode-end-hook-quit)
23722 ;; Only when the isearch was not quitted.
23723 (org-add-hook 'post-command-hook 'org-isearch-post-command
23724 'append 'local)))
23725 (org-fix-ellipsis-at-bol)))
23727 (defun org-isearch-post-command ()
23728 "Remove self from hook, and show context."
23729 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23730 (org-show-context 'isearch))
23733 ;;;; Integration with and fixes for other packages
23735 ;;; Imenu support
23737 (defvar org-imenu-markers nil
23738 "All markers currently used by Imenu.")
23739 (make-variable-buffer-local 'org-imenu-markers)
23741 (defun org-imenu-new-marker (&optional pos)
23742 "Return a new marker for use by Imenu, and remember the marker."
23743 (let ((m (make-marker)))
23744 (move-marker m (or pos (point)))
23745 (push m org-imenu-markers)
23748 (defun org-imenu-get-tree ()
23749 "Produce the index for Imenu."
23750 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23751 (setq org-imenu-markers nil)
23752 (let* ((n org-imenu-depth)
23753 (re (concat "^" (org-get-limited-outline-regexp)))
23754 (subs (make-vector (1+ n) nil))
23755 (last-level 0)
23756 m level head0 head)
23757 (save-excursion
23758 (save-restriction
23759 (widen)
23760 (goto-char (point-max))
23761 (while (re-search-backward re nil t)
23762 (setq level (org-reduced-level (funcall outline-level)))
23763 (when (and (<= level n)
23764 (looking-at org-complex-heading-regexp)
23765 (setq head0 (org-match-string-no-properties 4)))
23766 (setq head (org-link-display-format head0)
23767 m (org-imenu-new-marker))
23768 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23769 (if (>= level last-level)
23770 (push (cons head m) (aref subs level))
23771 (push (cons head (aref subs (1+ level))) (aref subs level))
23772 (loop for i from (1+ level) to n do (aset subs i nil)))
23773 (setq last-level level)))))
23774 (aref subs 1)))
23776 (eval-after-load "imenu"
23777 '(progn
23778 (add-hook 'imenu-after-jump-hook
23779 (lambda ()
23780 (if (derived-mode-p 'org-mode)
23781 (org-show-context 'org-goto))))))
23783 (defun org-link-display-format (link)
23784 "Replace a link with its the description.
23785 If there is no description, use the link target."
23786 (save-match-data
23787 (if (string-match org-bracket-link-analytic-regexp link)
23788 (replace-match (if (match-end 5)
23789 (match-string 5 link)
23790 (concat (match-string 1 link)
23791 (match-string 3 link)))
23792 nil t link)
23793 link)))
23795 (defun org-toggle-link-display ()
23796 "Toggle the literal or descriptive display of links."
23797 (interactive)
23798 (if org-descriptive-links
23799 (progn (org-remove-from-invisibility-spec '(org-link))
23800 (org-restart-font-lock)
23801 (setq org-descriptive-links nil))
23802 (progn (add-to-invisibility-spec '(org-link))
23803 (org-restart-font-lock)
23804 (setq org-descriptive-links t))))
23806 ;; Speedbar support
23808 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23809 "Overlay marking the agenda restriction line in speedbar.")
23810 (overlay-put org-speedbar-restriction-lock-overlay
23811 'face 'org-agenda-restriction-lock)
23812 (overlay-put org-speedbar-restriction-lock-overlay
23813 'help-echo "Agendas are currently limited to this item.")
23814 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23816 (defun org-speedbar-set-agenda-restriction ()
23817 "Restrict future agenda commands to the location at point in speedbar.
23818 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23819 (interactive)
23820 (require 'org-agenda)
23821 (let (p m tp np dir txt)
23822 (cond
23823 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23824 'org-imenu t))
23825 (setq m (get-text-property p 'org-imenu-marker))
23826 (with-current-buffer (marker-buffer m)
23827 (goto-char m)
23828 (org-agenda-set-restriction-lock 'subtree)))
23829 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23830 'speedbar-function 'speedbar-find-file))
23831 (setq tp (previous-single-property-change
23832 (1+ p) 'speedbar-function)
23833 np (next-single-property-change
23834 tp 'speedbar-function)
23835 dir (speedbar-line-directory)
23836 txt (buffer-substring-no-properties (or tp (point-min))
23837 (or np (point-max))))
23838 (with-current-buffer (find-file-noselect
23839 (let ((default-directory dir))
23840 (expand-file-name txt)))
23841 (unless (derived-mode-p 'org-mode)
23842 (user-error "Cannot restrict to non-Org-mode file"))
23843 (org-agenda-set-restriction-lock 'file)))
23844 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23845 (move-overlay org-speedbar-restriction-lock-overlay
23846 (point-at-bol) (point-at-eol))
23847 (setq current-prefix-arg nil)
23848 (org-agenda-maybe-redo)))
23850 (defvar speedbar-file-key-map)
23851 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23852 (eval-after-load "speedbar"
23853 '(progn
23854 (speedbar-add-supported-extension ".org")
23855 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23856 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23857 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23858 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23859 (add-hook 'speedbar-visiting-tag-hook
23860 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23862 ;;; Fixes and Hacks for problems with other packages
23864 ;; Make flyspell not check words in links, to not mess up our keymap
23865 (defvar org-element-affiliated-keywords) ; From org-element.el
23866 (defvar org-element-block-name-alist) ; From org-element.el
23867 (defun org-mode-flyspell-verify ()
23868 "Don't let flyspell put overlays at active buttons, or on
23869 {todo,all-time,additional-option-like}-keywords."
23870 (require 'org-element) ; For `org-element-affiliated-keywords'
23871 (let ((pos (max (1- (point)) (point-min)))
23872 (word (thing-at-point 'word)))
23873 (and (not (get-text-property pos 'keymap))
23874 (not (get-text-property pos 'org-no-flyspell))
23875 (not (member word org-todo-keywords-1))
23876 (not (member word org-all-time-keywords))
23877 (not (member word org-options-keywords))
23878 (not (member word (mapcar 'car org-startup-options)))
23879 (not (member-ignore-case word org-element-affiliated-keywords))
23880 (not (member-ignore-case word (org-get-export-keywords)))
23881 (not (member-ignore-case
23882 word (mapcar 'car org-element-block-name-alist)))
23883 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23884 (not (org-in-src-block-p)))))
23886 (defun org-remove-flyspell-overlays-in (beg end)
23887 "Remove flyspell overlays in region."
23888 (and (org-bound-and-true-p flyspell-mode)
23889 (fboundp 'flyspell-delete-region-overlays)
23890 (flyspell-delete-region-overlays beg end))
23891 (add-text-properties beg end '(org-no-flyspell t)))
23893 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23894 (eval-after-load "bookmark"
23895 '(if (boundp 'bookmark-after-jump-hook)
23896 ;; We can use the hook
23897 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23898 ;; Hook not available, use advice
23899 (defadvice bookmark-jump (after org-make-visible activate)
23900 "Make the position visible."
23901 (org-bookmark-jump-unhide))))
23903 ;; Make sure saveplace shows the location if it was hidden
23904 (eval-after-load "saveplace"
23905 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23906 "Make the position visible."
23907 (org-bookmark-jump-unhide)))
23909 ;; Make sure ecb shows the location if it was hidden
23910 (eval-after-load "ecb"
23911 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23912 "Make hierarchy visible when jumping into location from ECB tree buffer."
23913 (if (derived-mode-p 'org-mode)
23914 (org-show-context))))
23916 (defun org-bookmark-jump-unhide ()
23917 "Unhide the current position, to show the bookmark location."
23918 (and (derived-mode-p 'org-mode)
23919 (or (outline-invisible-p)
23920 (save-excursion (goto-char (max (point-min) (1- (point))))
23921 (outline-invisible-p)))
23922 (org-show-context 'bookmark-jump)))
23924 ;; Make session.el ignore our circular variable
23925 (defvar session-globals-exclude)
23926 (eval-after-load "session"
23927 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23929 ;;;; Finish up
23931 (provide 'org)
23933 (run-hooks 'org-load-hook)
23935 ;;; org.el ends here