ox-org: Add interactive functions to back-end
[org-mode.git] / lisp / org.el
blob1c15afd546d619b88a8abaa9f56214617ef5c5d0
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: Bastien Guerry <bzg at gnu 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/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro `org-with-limited-levels'.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches a headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (unless (boundp 'calendar-view-holidays-initially-flag)
107 (org-defvaralias 'calendar-view-holidays-initially-flag
108 'view-calendar-holidays-initially))
109 (unless (boundp 'calendar-view-diary-initially-flag)
110 (org-defvaralias 'calendar-view-diary-initially-flag
111 'view-diary-entries-initially))
112 (unless (boundp 'diary-fancy-buffer)
113 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
115 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
116 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
117 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
118 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "ox-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-table-set-constants "org-table" ())
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 (defcustom org-babel-load-languages '((emacs-lisp . t))
183 "Languages which can be evaluated in Org-mode buffers.
184 This list can be used to load support for any of the languages
185 below, note that each language will depend on a different set of
186 system executables and/or Emacs modes. When a language is
187 \"loaded\", then code blocks in that language can be evaluated
188 with `org-babel-execute-src-block' bound by default to C-c
189 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
190 be set to remove code block evaluation from the C-c C-c
191 keybinding. By default only Emacs Lisp (which has no
192 requirements) is loaded."
193 :group 'org-babel
194 :set 'org-babel-do-load-languages
195 :version "24.1"
196 :type '(alist :tag "Babel Languages"
197 :key-type
198 (choice
199 (const :tag "Awk" awk)
200 (const :tag "C" C)
201 (const :tag "R" R)
202 (const :tag "Asymptote" asymptote)
203 (const :tag "Calc" calc)
204 (const :tag "Clojure" clojure)
205 (const :tag "CSS" css)
206 (const :tag "Ditaa" ditaa)
207 (const :tag "Dot" dot)
208 (const :tag "Emacs Lisp" emacs-lisp)
209 (const :tag "Fortran" fortran)
210 (const :tag "Gnuplot" gnuplot)
211 (const :tag "Haskell" haskell)
212 (const :tag "IO" io)
213 (const :tag "Java" java)
214 (const :tag "Javascript" js)
215 (const :tag "LaTeX" latex)
216 (const :tag "Ledger" ledger)
217 (const :tag "Lilypond" lilypond)
218 (const :tag "Lisp" lisp)
219 (const :tag "Makefile" makefile)
220 (const :tag "Maxima" maxima)
221 (const :tag "Matlab" matlab)
222 (const :tag "Mscgen" mscgen)
223 (const :tag "Ocaml" ocaml)
224 (const :tag "Octave" octave)
225 (const :tag "Org" org)
226 (const :tag "Perl" perl)
227 (const :tag "Pico Lisp" picolisp)
228 (const :tag "PlantUML" plantuml)
229 (const :tag "Python" python)
230 (const :tag "Ruby" ruby)
231 (const :tag "Sass" sass)
232 (const :tag "Scala" scala)
233 (const :tag "Scheme" scheme)
234 (const :tag "Screen" screen)
235 (const :tag "Shell Script" sh)
236 (const :tag "Shen" shen)
237 (const :tag "Sql" sql)
238 (const :tag "Sqlite" sqlite))
239 :value-type (boolean :tag "Activate" :value t)))
241 ;;;; Customization variables
242 (defcustom org-clone-delete-id nil
243 "Remove ID property of clones of a subtree.
244 When non-nil, clones of a subtree don't inherit the ID property.
245 Otherwise they inherit the ID property with a new unique
246 identifier."
247 :type 'boolean
248 :version "24.1"
249 :group 'org-id)
251 ;;; Version
252 (org-check-version)
254 ;;;###autoload
255 (defun org-version (&optional here full message)
256 "Show the org-mode version in the echo area.
257 With prefix argument HERE, insert it at point.
258 When FULL is non-nil, use a verbose version string.
259 When MESSAGE is non-nil, display a message with the version."
260 (interactive "P")
261 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
262 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
263 (load-suffixes (list ".el"))
264 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
265 (org-trash (or
266 (and (fboundp 'org-release) (fboundp 'org-git-version))
267 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
268 (load-suffixes save-load-suffixes)
269 (org-version (org-release))
270 (git-version (org-git-version))
271 (version (format "Org-mode version %s (%s @ %s)"
272 org-version
273 git-version
274 (if org-install-dir
275 (if (string= org-dir org-install-dir)
276 org-install-dir
277 (concat "mixed installation! " org-install-dir " and " org-dir))
278 "org-loaddefs.el can not be found!")))
279 (_version (if full version org-version)))
280 (if (org-called-interactively-p 'interactive)
281 (if here
282 (insert version)
283 (message version))
284 (if message (message _version))
285 _version)))
287 (defconst org-version (org-version))
289 ;;; Compatibility constants
291 ;;; The custom variables
293 (defgroup org nil
294 "Outline-based notes management and organizer."
295 :tag "Org"
296 :group 'outlines
297 :group 'calendar)
299 (defcustom org-mode-hook nil
300 "Mode hook for Org-mode, run after the mode was turned on."
301 :group 'org
302 :type 'hook)
304 (defcustom org-load-hook nil
305 "Hook that is run after org.el has been loaded."
306 :group 'org
307 :type 'hook)
309 (defcustom org-log-buffer-setup-hook nil
310 "Hook that is run after an Org log buffer is created."
311 :group 'org
312 :version "24.1"
313 :type 'hook)
315 (defvar org-modules) ; defined below
316 (defvar org-modules-loaded nil
317 "Have the modules been loaded already?")
319 (defun org-load-modules-maybe (&optional force)
320 "Load all extensions listed in `org-modules'."
321 (when (or force (not org-modules-loaded))
322 (mapc (lambda (ext)
323 (condition-case nil (require ext)
324 (error (message "Problems while trying to load feature `%s'" ext))))
325 org-modules)
326 (setq org-modules-loaded t)))
328 (defun org-set-modules (var value)
329 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
330 (set var value)
331 (when (featurep 'org)
332 (org-load-modules-maybe 'force)))
334 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
335 "Modules that should always be loaded together with org.el.
337 If a description starts with <C>, the file is not part of Emacs
338 and loading it will require that you have downloaded and properly
339 installed the Org mode distribution.
341 You can also use this system to load external packages (i.e. neither Org
342 core modules, nor modules from the CONTRIB directory). Just add symbols
343 to the end of the list. If the package is called org-xyz.el, then you need
344 to add the symbol `xyz', and the package must have a call to:
346 \(provide 'org-xyz)
348 For export specific modules, see also `org-export-backends'."
349 :group 'org
350 :set 'org-set-modules
351 :version "24.4"
352 :package-version '(Org . "8.0")
353 :type
354 '(set :greedy t
355 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
356 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
357 (const :tag " crypt: Encryption of subtrees" org-crypt)
358 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
359 (const :tag " docview: Links to doc-view buffers" org-docview)
360 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
361 (const :tag " id: Global IDs for identifying entries" org-id)
362 (const :tag " info: Links to Info nodes" org-info)
363 (const :tag " habit: Track your consistency with habits" org-habit)
364 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
365 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
366 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
367 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
368 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
369 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
370 (const :tag " mouse: Additional mouse support" org-mouse)
372 (const :tag "C vm: Links to VM folders/messages" org-vm)
373 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
374 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
375 (const :tag "C mew: Links to Mew folders/messages" org-mew)
376 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
377 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
378 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
379 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
380 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
381 (const :tag "C collector: Collect properties into tables" org-collector)
382 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
383 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
384 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
385 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
386 (const :tag "C eval: Include command output as text" org-eval)
387 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
388 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
389 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
390 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
391 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
393 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
395 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
396 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
397 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
398 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
399 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
400 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
401 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
402 (const :tag "C mtags: Support for muse-like tags" org-mtags)
403 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
404 (const :tag "C registry: A registry for Org-mode links" org-registry)
405 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
406 (const :tag "C secretary: Team management with org-mode" org-secretary)
407 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
408 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
409 (const :tag "C track: Keep up with Org-mode development" org-track)
410 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
411 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
412 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
414 (defvar org-export-registered-backends) ; From ox.el
415 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
416 (defcustom org-export-backends '(ascii html icalendar latex)
417 "List of export back-ends that should be always available.
419 If a description starts with <C>, the file is not part of Emacs
420 and loading it will require that you have downloaded and properly
421 installed the Org mode distribution.
423 Unlike to `org-modules', libraries in this list will not be
424 loaded along with Org, but only once the export framework is
425 needed.
427 This variable needs to be set before org.el is loaded. If you
428 need to make a change while Emacs is running, use the customize
429 interface or run the following code, where VALUE stands for the
430 new value of the variable, after updating it:
432 \(progn
433 \(setq org-export-registered-backends
434 \(org-remove-if-not
435 \(lambda (backend)
436 \(or (memq backend val)
437 \(catch 'parentp
438 \(mapc
439 \(lambda (b)
440 \(and (org-export-derived-backend-p b (car backend))
441 \(throw 'parentp t)))
442 val)
443 nil)))
444 org-export-registered-backends))
445 \(let ((new-list (mapcar 'car org-export-registered-backends)))
446 \(dolist (backend val)
447 \(cond
448 \((not (load (format \"ox-%s\" backend) t t))
449 \(message \"Problems while trying to load export back-end `%s'\"
450 backend))
451 \((not (memq backend new-list)) (push backend new-list))))
452 \(set-default var new-list)))
454 Adding a back-end to this list will also pull the back-end it
455 depends on, if any."
456 :group 'org
457 :group 'org-export
458 :version "24.4"
459 :package-version '(Org . "8.0")
460 :initialize 'custom-initialize-set
461 :set (lambda (var val)
462 (if (not (featurep 'ox)) (set-default var val)
463 ;; Any back-end not required anymore (not present in VAL and not
464 ;; a parent of any back-end in the new value) is removed from the
465 ;; list of registered back-ends.
466 (setq org-export-registered-backends
467 (org-remove-if-not
468 (lambda (backend)
469 (or (memq backend val)
470 (catch 'parentp
471 (mapc
472 (lambda (b)
473 (and (org-export-derived-backend-p b (car backend))
474 (throw 'parentp t)))
475 val)
476 nil)))
477 org-export-registered-backends))
478 ;; Now build NEW-LIST of both new back-ends and required
479 ;; parents.
480 (let ((new-list (mapcar 'car org-export-registered-backends)))
481 (dolist (backend val)
482 (cond
483 ((not (load (format "ox-%s" backend) t t))
484 (message "Problems while trying to load export back-end `%s'"
485 backend))
486 ((not (memq backend new-list)) (push backend new-list))))
487 ;; Set VAR to that list with fixed dependencies.
488 (set-default var new-list))))
489 :type '(set :greedy t
490 (const :tag " ascii Export buffer to ASCII format" ascii)
491 (const :tag " beamer Export buffer to Beamer presentation" beamer)
492 (const :tag " html Export buffer to HTML format" html)
493 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
494 (const :tag " latex Export buffer to LaTeX format" latex)
495 (const :tag " man Export buffer to MAN format" man)
496 (const :tag " md Export buffer to Markdown format" md)
497 (const :tag " odt Export buffer to ODT format" odt)
498 (const :tag " org Export buffer to Org format" org)
499 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
500 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
501 (const :tag "C deck Export buffer to deck.js presentations" deck)
502 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
503 (const :tag "C groff Export buffer to Groff format" groff)
504 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
505 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
506 (const :tag "C s5 Export buffer to s5 presentations" s5)
507 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
509 (eval-after-load 'ox
510 '(mapc
511 (lambda (backend)
512 (condition-case nil (require (intern (format "ox-%s" backend)))
513 (error (message "Problems while trying to load export back-end `%s'"
514 backend))))
515 org-export-backends))
517 (defcustom org-support-shift-select nil
518 "Non-nil means make shift-cursor commands select text when possible.
520 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
521 start selecting a region, or enlarge regions started in this way.
522 In Org-mode, in special contexts, these same keys are used for
523 other purposes, important enough to compete with shift selection.
524 Org tries to balance these needs by supporting `shift-select-mode'
525 outside these special contexts, under control of this variable.
527 The default of this variable is nil, to avoid confusing behavior. Shifted
528 cursor keys will then execute Org commands in the following contexts:
529 - on a headline, changing TODO state (left/right) and priority (up/down)
530 - on a time stamp, changing the time
531 - in a plain list item, changing the bullet type
532 - in a property definition line, switching between allowed values
533 - in the BEGIN line of a clock table (changing the time block).
534 Outside these contexts, the commands will throw an error.
536 When this variable is t and the cursor is not in a special
537 context, Org-mode will support shift-selection for making and
538 enlarging regions. To make this more effective, the bullet
539 cycling will no longer happen anywhere in an item line, but only
540 if the cursor is exactly on the bullet.
542 If you set this variable to the symbol `always', then the keys
543 will not be special in headlines, property lines, and item lines,
544 to make shift selection work there as well. If this is what you
545 want, you can use the following alternative commands: `C-c C-t'
546 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
547 can be used to switch TODO sets, `C-c -' to cycle item bullet
548 types, and properties can be edited by hand or in column view.
550 However, when the cursor is on a timestamp, shift-cursor commands
551 will still edit the time stamp - this is just too good to give up.
553 XEmacs user should have this variable set to nil, because
554 `shift-select-mode' is in Emacs 23 or later only."
555 :group 'org
556 :type '(choice
557 (const :tag "Never" nil)
558 (const :tag "When outside special context" t)
559 (const :tag "Everywhere except timestamps" always)))
561 (defcustom org-loop-over-headlines-in-active-region nil
562 "Shall some commands act upon headlines in the active region?
564 When set to `t', some commands will be performed in all headlines
565 within the active region.
567 When set to `start-level', some commands will be performed in all
568 headlines within the active region, provided that these headlines
569 are of the same level than the first one.
571 When set to a string, those commands will be performed on the
572 matching headlines within the active region. Such string must be
573 a tags/property/todo match as it is used in the agenda tags view.
575 The list of commands is: `org-schedule', `org-deadline',
576 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
577 `org-archive-to-archive-sibling'. The archiving commands skip
578 already archived entries."
579 :type '(choice (const :tag "Don't loop" nil)
580 (const :tag "All headlines in active region" t)
581 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
582 (string :tag "Tags/Property/Todo matcher"))
583 :version "24.1"
584 :group 'org-todo
585 :group 'org-archive)
587 (defgroup org-startup nil
588 "Options concerning startup of Org-mode."
589 :tag "Org Startup"
590 :group 'org)
592 (defcustom org-startup-folded t
593 "Non-nil means entering Org-mode will switch to OVERVIEW.
594 This can also be configured on a per-file basis by adding one of
595 the following lines anywhere in the buffer:
597 #+STARTUP: fold (or `overview', this is equivalent)
598 #+STARTUP: nofold (or `showall', this is equivalent)
599 #+STARTUP: content
600 #+STARTUP: showeverything
602 By default, this option is ignored when Org opens agenda files
603 for the first time. If you want the agenda to honor the startup
604 option, set `org-agenda-inhibit-startup' to nil."
605 :group 'org-startup
606 :type '(choice
607 (const :tag "nofold: show all" nil)
608 (const :tag "fold: overview" t)
609 (const :tag "content: all headlines" content)
610 (const :tag "show everything, even drawers" showeverything)))
612 (defcustom org-startup-truncated t
613 "Non-nil means entering Org-mode will set `truncate-lines'.
614 This is useful since some lines containing links can be very long and
615 uninteresting. Also tables look terrible when wrapped."
616 :group 'org-startup
617 :type 'boolean)
619 (defcustom org-startup-indented nil
620 "Non-nil means turn on `org-indent-mode' on startup.
621 This can also be configured on a per-file basis by adding one of
622 the following lines anywhere in the buffer:
624 #+STARTUP: indent
625 #+STARTUP: noindent"
626 :group 'org-structure
627 :type '(choice
628 (const :tag "Not" nil)
629 (const :tag "Globally (slow on startup in large files)" t)))
631 (defcustom org-use-sub-superscripts t
632 "Non-nil means interpret \"_\" and \"^\" for display.
633 When this option is turned on, you can use TeX-like syntax for sub- and
634 superscripts. Several characters after \"_\" or \"^\" will be
635 considered as a single item - so grouping with {} is normally not
636 needed. For example, the following things will be parsed as single
637 sub- or superscripts.
639 10^24 or 10^tau several digits will be considered 1 item.
640 10^-12 or 10^-tau a leading sign with digits or a word
641 x^2-y^3 will be read as x^2 - y^3, because items are
642 terminated by almost any nonword/nondigit char.
643 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
645 Still, ambiguity is possible - so when in doubt use {} to enclose
646 the sub/superscript. If you set this variable to the symbol
647 `{}', the braces are *required* in order to trigger
648 interpretations as sub/superscript. This can be helpful in
649 documents that need \"_\" frequently in plain text."
650 :group 'org-startup
651 :version "24.1"
652 :type '(choice
653 (const :tag "Always interpret" t)
654 (const :tag "Only with braces" {})
655 (const :tag "Never interpret" nil)))
657 (defcustom org-startup-with-beamer-mode nil
658 "Non-nil means turn on `org-beamer-mode' on startup.
659 This can also be configured on a per-file basis by adding one of
660 the following lines anywhere in the buffer:
662 #+STARTUP: beamer"
663 :group 'org-startup
664 :version "24.1"
665 :type 'boolean)
667 (defcustom org-startup-align-all-tables nil
668 "Non-nil means align all tables when visiting a file.
669 This is useful when the column width in tables is forced with <N> cookies
670 in table fields. Such tables will look correct only after the first re-align.
671 This can also be configured on a per-file basis by adding one of
672 the following lines anywhere in the buffer:
673 #+STARTUP: align
674 #+STARTUP: noalign"
675 :group 'org-startup
676 :type 'boolean)
678 (defcustom org-startup-with-inline-images nil
679 "Non-nil means show inline images when loading a new Org file.
680 This can also be configured on a per-file basis by adding one of
681 the following lines anywhere in the buffer:
682 #+STARTUP: inlineimages
683 #+STARTUP: noinlineimages"
684 :group 'org-startup
685 :version "24.1"
686 :type 'boolean)
688 (defcustom org-startup-with-latex-preview nil
689 "Non-nil means preview LaTeX fragments when loading a new Org file.
691 This can also be configured on a per-file basis by adding one of
692 the followinglines anywhere in the buffer:
693 #+STARTUP: latexpreview
694 #+STARTUP: nolatexpreview"
695 :group 'org-startup
696 :version "24.4"
697 :package-version '(Org . "8.0")
698 :type 'boolean)
700 (defcustom org-insert-mode-line-in-empty-file nil
701 "Non-nil means insert the first line setting Org-mode in empty files.
702 When the function `org-mode' is called interactively in an empty file, this
703 normally means that the file name does not automatically trigger Org-mode.
704 To ensure that the file will always be in Org-mode in the future, a
705 line enforcing Org-mode will be inserted into the buffer, if this option
706 has been set."
707 :group 'org-startup
708 :type 'boolean)
710 (defcustom org-replace-disputed-keys nil
711 "Non-nil means use alternative key bindings for some keys.
712 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
713 These keys are also used by other packages like shift-selection-mode'
714 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
715 If you want to use Org-mode together with one of these other modes,
716 or more generally if you would like to move some Org-mode commands to
717 other keys, set this variable and configure the keys with the variable
718 `org-disputed-keys'.
720 This option is only relevant at load-time of Org-mode, and must be set
721 *before* org.el is loaded. Changing it requires a restart of Emacs to
722 become effective."
723 :group 'org-startup
724 :type 'boolean)
726 (defcustom org-use-extra-keys nil
727 "Non-nil means use extra key sequence definitions for certain commands.
728 This happens automatically if you run XEmacs or if `window-system'
729 is nil. This variable lets you do the same manually. You must
730 set it before loading org.
732 Example: on Carbon Emacs 22 running graphically, with an external
733 keyboard on a Powerbook, the default way of setting M-left might
734 not work for either Alt or ESC. Setting this variable will make
735 it work for ESC."
736 :group 'org-startup
737 :type 'boolean)
739 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
741 (defcustom org-disputed-keys
742 '(([(shift up)] . [(meta p)])
743 ([(shift down)] . [(meta n)])
744 ([(shift left)] . [(meta -)])
745 ([(shift right)] . [(meta +)])
746 ([(control shift right)] . [(meta shift +)])
747 ([(control shift left)] . [(meta shift -)]))
748 "Keys for which Org-mode and other modes compete.
749 This is an alist, cars are the default keys, second element specifies
750 the alternative to use when `org-replace-disputed-keys' is t.
752 Keys can be specified in any syntax supported by `define-key'.
753 The value of this option takes effect only at Org-mode's startup,
754 therefore you'll have to restart Emacs to apply it after changing."
755 :group 'org-startup
756 :type 'alist)
758 (defun org-key (key)
759 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
760 Or return the original if not disputed.
761 Also apply the translations defined in `org-xemacs-key-equivalents'."
762 (when org-replace-disputed-keys
763 (let* ((nkey (key-description key))
764 (x (org-find-if (lambda (x)
765 (equal (key-description (car x)) nkey))
766 org-disputed-keys)))
767 (setq key (if x (cdr x) key))))
768 (when (featurep 'xemacs)
769 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
770 key)
772 (defun org-find-if (predicate seq)
773 (catch 'exit
774 (while seq
775 (if (funcall predicate (car seq))
776 (throw 'exit (car seq))
777 (pop seq)))))
779 (defun org-defkey (keymap key def)
780 "Define a key, possibly translated, as returned by `org-key'."
781 (define-key keymap (org-key key) def))
783 (defcustom org-ellipsis nil
784 "The ellipsis to use in the Org-mode outline.
785 When nil, just use the standard three dots. When a string, use that instead,
786 When a face, use the standard 3 dots, but with the specified face.
787 The change affects only Org-mode (which will then use its own display table).
788 Changing this requires executing `M-x org-mode' in a buffer to become
789 effective."
790 :group 'org-startup
791 :type '(choice (const :tag "Default" nil)
792 (face :tag "Face" :value org-warning)
793 (string :tag "String" :value "...#")))
795 (defvar org-display-table nil
796 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
798 (defgroup org-keywords nil
799 "Keywords in Org-mode."
800 :tag "Org Keywords"
801 :group 'org)
803 (defcustom org-deadline-string "DEADLINE:"
804 "String to mark deadline entries.
805 A deadline is this string, followed by a time stamp. Should be a word,
806 terminated by a colon. You can insert a schedule keyword and
807 a timestamp with \\[org-deadline].
808 Changes become only effective after restarting Emacs."
809 :group 'org-keywords
810 :type 'string)
812 (defcustom org-scheduled-string "SCHEDULED:"
813 "String to mark scheduled TODO entries.
814 A schedule is this string, followed by a time stamp. Should be a word,
815 terminated by a colon. You can insert a schedule keyword and
816 a timestamp with \\[org-schedule].
817 Changes become only effective after restarting Emacs."
818 :group 'org-keywords
819 :type 'string)
821 (defcustom org-closed-string "CLOSED:"
822 "String used as the prefix for timestamps logging closing a TODO entry."
823 :group 'org-keywords
824 :type 'string)
826 (defcustom org-clock-string "CLOCK:"
827 "String used as prefix for timestamps clocking work hours on an item."
828 :group 'org-keywords
829 :type 'string)
831 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
832 org-scheduled-string "\\|"
833 org-deadline-string "\\|"
834 org-closed-string "\\|"
835 org-clock-string "\\)")
836 "Matches a line with planning or clock info.")
838 (defcustom org-comment-string "COMMENT"
839 "Entries starting with this keyword will never be exported.
840 An entry can be toggled between COMMENT and normal with
841 \\[org-toggle-comment].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-quote-string "QUOTE"
847 "Entries starting with this keyword will be exported in fixed-width font.
848 Quoting applies only to the text in the entry following the headline, and does
849 not extend beyond the next headline, even if that is lower level.
850 An entry can be toggled between QUOTE and normal with
851 \\[org-toggle-fixed-width-section]."
852 :group 'org-keywords
853 :type 'string)
855 (defconst org-repeat-re
856 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
857 "Regular expression for specifying repeated events.
858 After a match, group 1 contains the repeat expression.")
860 (defgroup org-structure nil
861 "Options concerning the general structure of Org-mode files."
862 :tag "Org Structure"
863 :group 'org)
865 (defgroup org-reveal-location nil
866 "Options about how to make context of a location visible."
867 :tag "Org Reveal Location"
868 :group 'org-structure)
870 (defconst org-context-choice
871 '(choice
872 (const :tag "Always" t)
873 (const :tag "Never" nil)
874 (repeat :greedy t :tag "Individual contexts"
875 (cons
876 (choice :tag "Context"
877 (const agenda)
878 (const org-goto)
879 (const occur-tree)
880 (const tags-tree)
881 (const link-search)
882 (const mark-goto)
883 (const bookmark-jump)
884 (const isearch)
885 (const default))
886 (boolean))))
887 "Contexts for the reveal options.")
889 (defcustom org-show-hierarchy-above '((default . t))
890 "Non-nil means show full hierarchy when revealing a location.
891 Org-mode often shows locations in an org-mode file which might have
892 been invisible before. When this is set, the hierarchy of headings
893 above the exposed location is shown.
894 Turning this off for example for sparse trees makes them very compact.
895 Instead of t, this can also be an alist specifying this option for different
896 contexts. Valid contexts are
897 agenda when exposing an entry from the agenda
898 org-goto when using the command `org-goto' on key C-c C-j
899 occur-tree when using the command `org-occur' on key C-c /
900 tags-tree when constructing a sparse tree based on tags matches
901 link-search when exposing search matches associated with a link
902 mark-goto when exposing the jump goal of a mark
903 bookmark-jump when exposing a bookmark location
904 isearch when exiting from an incremental search
905 default default for all contexts not set explicitly"
906 :group 'org-reveal-location
907 :type org-context-choice)
909 (defcustom org-show-following-heading '((default . nil))
910 "Non-nil means show following heading when revealing a location.
911 Org-mode often shows locations in an org-mode file which might have
912 been invisible before. When this is set, the heading following the
913 match is shown.
914 Turning this off for example for sparse trees makes them very compact,
915 but makes it harder to edit the location of the match. In such a case,
916 use the command \\[org-reveal] to show more context.
917 Instead of t, this can also be an alist specifying this option for different
918 contexts. See `org-show-hierarchy-above' for valid contexts."
919 :group 'org-reveal-location
920 :type org-context-choice)
922 (defcustom org-show-siblings '((default . nil) (isearch t))
923 "Non-nil means show all sibling heading when revealing a location.
924 Org-mode often shows locations in an org-mode file which might have
925 been invisible before. When this is set, the sibling of the current entry
926 heading are all made visible. If `org-show-hierarchy-above' is t,
927 the same happens on each level of the hierarchy above the current entry.
929 By default this is on for the isearch context, off for all other contexts.
930 Turning this off for example for sparse trees makes them very compact,
931 but makes it harder to edit the location of the match. In such a case,
932 use the command \\[org-reveal] to show more context.
933 Instead of t, this can also be an alist specifying this option for different
934 contexts. See `org-show-hierarchy-above' for valid contexts."
935 :group 'org-reveal-location
936 :type org-context-choice)
938 (defcustom org-show-entry-below '((default . nil))
939 "Non-nil means show the entry below a headline when revealing a location.
940 Org-mode often shows locations in an org-mode file which might have
941 been invisible before. When this is set, the text below the headline that is
942 exposed is also shown.
944 By default this is off for all contexts.
945 Instead of t, this can also be an alist specifying this option for different
946 contexts. See `org-show-hierarchy-above' for valid contexts."
947 :group 'org-reveal-location
948 :type org-context-choice)
950 (defcustom org-indirect-buffer-display 'other-window
951 "How should indirect tree buffers be displayed?
952 This applies to indirect buffers created with the commands
953 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
954 Valid values are:
955 current-window Display in the current window
956 other-window Just display in another window.
957 dedicated-frame Create one new frame, and re-use it each time.
958 new-frame Make a new frame each time. Note that in this case
959 previously-made indirect buffers are kept, and you need to
960 kill these buffers yourself."
961 :group 'org-structure
962 :group 'org-agenda-windows
963 :type '(choice
964 (const :tag "In current window" current-window)
965 (const :tag "In current frame, other window" other-window)
966 (const :tag "Each time a new frame" new-frame)
967 (const :tag "One dedicated frame" dedicated-frame)))
969 (defcustom org-use-speed-commands nil
970 "Non-nil means activate single letter commands at beginning of a headline.
971 This may also be a function to test for appropriate locations where speed
972 commands should be active."
973 :group 'org-structure
974 :type '(choice
975 (const :tag "Never" nil)
976 (const :tag "At beginning of headline stars" t)
977 (function)))
979 (defcustom org-speed-commands-user nil
980 "Alist of additional speed commands.
981 This list will be checked before `org-speed-commands-default'
982 when the variable `org-use-speed-commands' is non-nil
983 and when the cursor is at the beginning of a headline.
984 The car if each entry is a string with a single letter, which must
985 be assigned to `self-insert-command' in the global map.
986 The cdr is either a command to be called interactively, a function
987 to be called, or a form to be evaluated.
988 An entry that is just a list with a single string will be interpreted
989 as a descriptive headline that will be added when listing the speed
990 commands in the Help buffer using the `?' speed command."
991 :group 'org-structure
992 :type '(repeat :value ("k" . ignore)
993 (choice :value ("k" . ignore)
994 (list :tag "Descriptive Headline" (string :tag "Headline"))
995 (cons :tag "Letter and Command"
996 (string :tag "Command letter")
997 (choice
998 (function)
999 (sexp))))))
1001 (defgroup org-cycle nil
1002 "Options concerning visibility cycling in Org-mode."
1003 :tag "Org Cycle"
1004 :group 'org-structure)
1006 (defcustom org-cycle-skip-children-state-if-no-children t
1007 "Non-nil means skip CHILDREN state in entries that don't have any."
1008 :group 'org-cycle
1009 :type 'boolean)
1011 (defcustom org-cycle-max-level nil
1012 "Maximum level which should still be subject to visibility cycling.
1013 Levels higher than this will, for cycling, be treated as text, not a headline.
1014 When `org-odd-levels-only' is set, a value of N in this variable actually
1015 means 2N-1 stars as the limiting headline.
1016 When nil, cycle all levels.
1017 Note that the limiting level of cycling is also influenced by
1018 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1019 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1020 than its value."
1021 :group 'org-cycle
1022 :type '(choice
1023 (const :tag "No limit" nil)
1024 (integer :tag "Maximum level")))
1026 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1027 "Names of drawers. Drawers are not opened by cycling on the headline above.
1028 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1029 this:
1030 :DRAWERNAME:
1031 .....
1032 :END:
1033 The drawer \"PROPERTIES\" is special for capturing properties through
1034 the property API.
1036 Drawers can be defined on the per-file basis with a line like:
1038 #+DRAWERS: HIDDEN STATE PROPERTIES"
1039 :group 'org-structure
1040 :group 'org-cycle
1041 :type '(repeat (string :tag "Drawer Name")))
1043 (defcustom org-hide-block-startup nil
1044 "Non-nil means entering Org-mode will fold all blocks.
1045 This can also be set in on a per-file basis with
1047 #+STARTUP: hideblocks
1048 #+STARTUP: showblocks"
1049 :group 'org-startup
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-global-at-bob nil
1054 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1055 This makes it possible to do global cycling without having to use S-TAB or
1056 \\[universal-argument] TAB. For this special case to work, the first line
1057 of the buffer must not be a headline -- it may be empty or some other text.
1058 When used in this way, `org-cycle-hook' is disabled temporarily to make
1059 sure the cursor stays at the beginning of the buffer. When this option is
1060 nil, don't do anything special at the beginning of the buffer."
1061 :group 'org-cycle
1062 :type 'boolean)
1064 (defcustom org-cycle-level-after-item/entry-creation t
1065 "Non-nil means cycle entry level or item indentation in new empty entries.
1067 When the cursor is at the end of an empty headline, i.e., with only stars
1068 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1069 and then all possible ancestor states, before returning to the original state.
1070 This makes data entry extremely fast: M-RET to create a new headline,
1071 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1073 When the cursor is at the end of an empty plain list item, one TAB will
1074 make it a subitem, two or more tabs will back up to make this an item
1075 higher up in the item hierarchy."
1076 :group 'org-cycle
1077 :type 'boolean)
1079 (defcustom org-cycle-emulate-tab t
1080 "Where should `org-cycle' emulate TAB.
1081 nil Never
1082 white Only in completely white lines
1083 whitestart Only at the beginning of lines, before the first non-white char
1084 t Everywhere except in headlines
1085 exc-hl-bol Everywhere except at the start of a headline
1086 If TAB is used in a place where it does not emulate TAB, the current subtree
1087 visibility is cycled."
1088 :group 'org-cycle
1089 :type '(choice (const :tag "Never" nil)
1090 (const :tag "Only in completely white lines" white)
1091 (const :tag "Before first char in a line" whitestart)
1092 (const :tag "Everywhere except in headlines" t)
1093 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1096 (defcustom org-cycle-separator-lines 2
1097 "Number of empty lines needed to keep an empty line between collapsed trees.
1098 If you leave an empty line between the end of a subtree and the following
1099 headline, this empty line is hidden when the subtree is folded.
1100 Org-mode will leave (exactly) one empty line visible if the number of
1101 empty lines is equal or larger to the number given in this variable.
1102 So the default 2 means at least 2 empty lines after the end of a subtree
1103 are needed to produce free space between a collapsed subtree and the
1104 following headline.
1106 If the number is negative, and the number of empty lines is at least -N,
1107 all empty lines are shown.
1109 Special case: when 0, never leave empty lines in collapsed view."
1110 :group 'org-cycle
1111 :type 'integer)
1112 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1114 (defcustom org-pre-cycle-hook nil
1115 "Hook that is run before visibility cycling is happening.
1116 The function(s) in this hook must accept a single argument which indicates
1117 the new state that will be set right after running this hook. The
1118 argument is a symbol. Before a global state change, it can have the values
1119 `overview', `content', or `all'. Before a local state change, it can have
1120 the values `folded', `children', or `subtree'."
1121 :group 'org-cycle
1122 :type 'hook)
1124 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1125 org-cycle-hide-drawers
1126 org-cycle-hide-inline-tasks
1127 org-cycle-show-empty-lines
1128 org-optimize-window-after-visibility-change)
1129 "Hook that is run after `org-cycle' has changed the buffer visibility.
1130 The function(s) in this hook must accept a single argument which indicates
1131 the new state that was set by the most recent `org-cycle' command. The
1132 argument is a symbol. After a global state change, it can have the values
1133 `overview', `contents', or `all'. After a local state change, it can have
1134 the values `folded', `children', or `subtree'."
1135 :group 'org-cycle
1136 :type 'hook)
1138 (defgroup org-edit-structure nil
1139 "Options concerning structure editing in Org-mode."
1140 :tag "Org Edit Structure"
1141 :group 'org-structure)
1143 (defcustom org-odd-levels-only nil
1144 "Non-nil means skip even levels and only use odd levels for the outline.
1145 This has the effect that two stars are being added/taken away in
1146 promotion/demotion commands. It also influences how levels are
1147 handled by the exporters.
1148 Changing it requires restart of `font-lock-mode' to become effective
1149 for fontification also in regions already fontified.
1150 You may also set this on a per-file basis by adding one of the following
1151 lines to the buffer:
1153 #+STARTUP: odd
1154 #+STARTUP: oddeven"
1155 :group 'org-edit-structure
1156 :group 'org-appearance
1157 :type 'boolean)
1159 (defcustom org-adapt-indentation t
1160 "Non-nil means adapt indentation to outline node level.
1162 When this variable is set, Org assumes that you write outlines by
1163 indenting text in each node to align with the headline (after the stars).
1164 The following issues are influenced by this variable:
1166 - When this is set and the *entire* text in an entry is indented, the
1167 indentation is increased by one space in a demotion command, and
1168 decreased by one in a promotion command. If any line in the entry
1169 body starts with text at column 0, indentation is not changed at all.
1171 - Property drawers and planning information is inserted indented when
1172 this variable s set. When nil, they will not be indented.
1174 - TAB indents a line relative to context. The lines below a headline
1175 will be indented when this variable is set.
1177 Note that this is all about true indentation, by adding and removing
1178 space characters. See also `org-indent.el' which does level-dependent
1179 indentation in a virtual way, i.e. at display time in Emacs."
1180 :group 'org-edit-structure
1181 :type 'boolean)
1183 (defcustom org-special-ctrl-a/e nil
1184 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1186 When t, `C-a' will bring back the cursor to the beginning of the
1187 headline text, i.e. after the stars and after a possible TODO
1188 keyword. In an item, this will be the position after bullet and
1189 check-box, if any. When the cursor is already at that position,
1190 another `C-a' will bring it to the beginning of the line.
1192 `C-e' will jump to the end of the headline, ignoring the presence
1193 of tags in the headline. A second `C-e' will then jump to the
1194 true end of the line, after any tags. This also means that, when
1195 this variable is non-nil, `C-e' also will never jump beyond the
1196 end of the heading of a folded section, i.e. not after the
1197 ellipses.
1199 When set to the symbol `reversed', the first `C-a' or `C-e' works
1200 normally, going to the true line boundary first. Only a directly
1201 following, identical keypress will bring the cursor to the
1202 special positions.
1204 This may also be a cons cell where the behavior for `C-a' and
1205 `C-e' is set separately."
1206 :group 'org-edit-structure
1207 :type '(choice
1208 (const :tag "off" nil)
1209 (const :tag "on: after stars/bullet and before tags first" t)
1210 (const :tag "reversed: true line boundary first" reversed)
1211 (cons :tag "Set C-a and C-e separately"
1212 (choice :tag "Special C-a"
1213 (const :tag "off" nil)
1214 (const :tag "on: after stars/bullet first" t)
1215 (const :tag "reversed: before stars/bullet first" reversed))
1216 (choice :tag "Special C-e"
1217 (const :tag "off" nil)
1218 (const :tag "on: before tags first" t)
1219 (const :tag "reversed: after tags first" reversed)))))
1220 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1222 (defcustom org-special-ctrl-k nil
1223 "Non-nil means `C-k' will behave specially in headlines.
1224 When nil, `C-k' will call the default `kill-line' command.
1225 When t, the following will happen while the cursor is in the headline:
1227 - When the cursor is at the beginning of a headline, kill the entire
1228 line and possible the folded subtree below the line.
1229 - When in the middle of the headline text, kill the headline up to the tags.
1230 - When after the headline text, kill the tags."
1231 :group 'org-edit-structure
1232 :type 'boolean)
1234 (defcustom org-ctrl-k-protect-subtree nil
1235 "Non-nil means, do not delete a hidden subtree with C-k.
1236 When set to the symbol `error', simply throw an error when C-k is
1237 used to kill (part-of) a headline that has hidden text behind it.
1238 Any other non-nil value will result in a query to the user, if it is
1239 OK to kill that hidden subtree. When nil, kill without remorse."
1240 :group 'org-edit-structure
1241 :version "24.1"
1242 :type '(choice
1243 (const :tag "Do not protect hidden subtrees" nil)
1244 (const :tag "Protect hidden subtrees with a security query" t)
1245 (const :tag "Never kill a hidden subtree with C-k" error)))
1247 (defcustom org-catch-invisible-edits nil
1248 "Check if in invisible region before inserting or deleting a character.
1249 Valid values are:
1251 nil Do not check, so just do invisible edits.
1252 error Throw an error and do nothing.
1253 show Make point visible, and do the requested edit.
1254 show-and-error Make point visible, then throw an error and abort the edit.
1255 smart Make point visible, and do insertion/deletion if it is
1256 adjacent to visible text and the change feels predictable.
1257 Never delete a previously invisible character or add in the
1258 middle or right after an invisible region. Basically, this
1259 allows insertion and backward-delete right before ellipses.
1260 FIXME: maybe in this case we should not even show?"
1261 :group 'org-edit-structure
1262 :version "24.1"
1263 :type '(choice
1264 (const :tag "Do not check" nil)
1265 (const :tag "Throw error when trying to edit" error)
1266 (const :tag "Unhide, but do not do the edit" show-and-error)
1267 (const :tag "Show invisible part and do the edit" show)
1268 (const :tag "Be smart and do the right thing" smart)))
1270 (defcustom org-yank-folded-subtrees t
1271 "Non-nil means when yanking subtrees, fold them.
1272 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1273 it starts with a heading and all other headings in it are either children
1274 or siblings, then fold all the subtrees. However, do this only if no
1275 text after the yank would be swallowed into a folded tree by this action."
1276 :group 'org-edit-structure
1277 :type 'boolean)
1279 (defcustom org-yank-adjusted-subtrees nil
1280 "Non-nil means when yanking subtrees, adjust the level.
1281 With this setting, `org-paste-subtree' is used to insert the subtree, see
1282 this function for details."
1283 :group 'org-edit-structure
1284 :type 'boolean)
1286 (defcustom org-M-RET-may-split-line '((default . t))
1287 "Non-nil means M-RET will split the line at the cursor position.
1288 When nil, it will go to the end of the line before making a
1289 new line.
1290 You may also set this option in a different way for different
1291 contexts. Valid contexts are:
1293 headline when creating a new headline
1294 item when creating a new item
1295 table in a table field
1296 default the value to be used for all contexts not explicitly
1297 customized"
1298 :group 'org-structure
1299 :group 'org-table
1300 :type '(choice
1301 (const :tag "Always" t)
1302 (const :tag "Never" nil)
1303 (repeat :greedy t :tag "Individual contexts"
1304 (cons
1305 (choice :tag "Context"
1306 (const headline)
1307 (const item)
1308 (const table)
1309 (const default))
1310 (boolean)))))
1313 (defcustom org-insert-heading-respect-content nil
1314 "Non-nil means insert new headings after the current subtree.
1315 When nil, the new heading is created directly after the current line.
1316 The commands \\[org-insert-heading-respect-content] and
1317 \\[org-insert-todo-heading-respect-content] turn this variable on
1318 for the duration of the command."
1319 :group 'org-structure
1320 :type 'boolean)
1322 (defcustom org-blank-before-new-entry '((heading . auto)
1323 (plain-list-item . auto))
1324 "Should `org-insert-heading' leave a blank line before new heading/item?
1325 The value is an alist, with `heading' and `plain-list-item' as CAR,
1326 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1327 which case Org will look at the surrounding headings/items and try to
1328 make an intelligent decision whether to insert a blank line or not.
1330 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1331 the setting here is ignored and no empty line is inserted to avoid breaking
1332 the list structure."
1333 :group 'org-edit-structure
1334 :type '(list
1335 (cons (const heading)
1336 (choice (const :tag "Never" nil)
1337 (const :tag "Always" t)
1338 (const :tag "Auto" auto)))
1339 (cons (const plain-list-item)
1340 (choice (const :tag "Never" nil)
1341 (const :tag "Always" t)
1342 (const :tag "Auto" auto)))))
1344 (defcustom org-insert-heading-hook nil
1345 "Hook being run after inserting a new heading."
1346 :group 'org-edit-structure
1347 :type 'hook)
1349 (defcustom org-enable-fixed-width-editor t
1350 "Non-nil means lines starting with \":\" are treated as fixed-width.
1351 This currently only means they are never auto-wrapped.
1352 When nil, such lines will be treated like ordinary lines.
1353 See also the QUOTE keyword."
1354 :group 'org-edit-structure
1355 :type 'boolean)
1357 (defcustom org-goto-auto-isearch t
1358 "Non-nil means typing characters in `org-goto' starts incremental search.
1359 When nil, you can use these keybindings to navigate the buffer:
1361 q Quit the org-goto interface
1362 n Go to the next visible heading
1363 p Go to the previous visible heading
1364 f Go one heading forward on same level
1365 b Go one heading backward on same level
1366 u Go one heading up"
1367 :group 'org-edit-structure
1368 :type 'boolean)
1370 (defgroup org-sparse-trees nil
1371 "Options concerning sparse trees in Org-mode."
1372 :tag "Org Sparse Trees"
1373 :group 'org-structure)
1375 (defcustom org-highlight-sparse-tree-matches t
1376 "Non-nil means highlight all matches that define a sparse tree.
1377 The highlights will automatically disappear the next time the buffer is
1378 changed by an edit command."
1379 :group 'org-sparse-trees
1380 :type 'boolean)
1382 (defcustom org-remove-highlights-with-change t
1383 "Non-nil means any change to the buffer will remove temporary highlights.
1384 Such highlights are created by `org-occur' and `org-clock-display'.
1385 When nil, `C-c C-c needs to be used to get rid of the highlights.
1386 The highlights created by `org-preview-latex-fragment' always need
1387 `C-c C-c' to be removed."
1388 :group 'org-sparse-trees
1389 :group 'org-time
1390 :type 'boolean)
1393 (defcustom org-occur-hook '(org-first-headline-recenter)
1394 "Hook that is run after `org-occur' has constructed a sparse tree.
1395 This can be used to recenter the window to show as much of the structure
1396 as possible."
1397 :group 'org-sparse-trees
1398 :type 'hook)
1400 (defgroup org-imenu-and-speedbar nil
1401 "Options concerning imenu and speedbar in Org-mode."
1402 :tag "Org Imenu and Speedbar"
1403 :group 'org-structure)
1405 (defcustom org-imenu-depth 2
1406 "The maximum level for Imenu access to Org-mode headlines.
1407 This also applied for speedbar access."
1408 :group 'org-imenu-and-speedbar
1409 :type 'integer)
1411 (defgroup org-table nil
1412 "Options concerning tables in Org-mode."
1413 :tag "Org Table"
1414 :group 'org)
1416 (defcustom org-enable-table-editor 'optimized
1417 "Non-nil means lines starting with \"|\" are handled by the table editor.
1418 When nil, such lines will be treated like ordinary lines.
1420 When equal to the symbol `optimized', the table editor will be optimized to
1421 do the following:
1422 - Automatic overwrite mode in front of whitespace in table fields.
1423 This makes the structure of the table stay in tact as long as the edited
1424 field does not exceed the column width.
1425 - Minimize the number of realigns. Normally, the table is aligned each time
1426 TAB or RET are pressed to move to another field. With optimization this
1427 happens only if changes to a field might have changed the column width.
1428 Optimization requires replacing the functions `self-insert-command',
1429 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1430 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1431 very good at guessing when a re-align will be necessary, but you can always
1432 force one with \\[org-ctrl-c-ctrl-c].
1434 If you would like to use the optimized version in Org-mode, but the
1435 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1437 This variable can be used to turn on and off the table editor during a session,
1438 but in order to toggle optimization, a restart is required.
1440 See also the variable `org-table-auto-blank-field'."
1441 :group 'org-table
1442 :type '(choice
1443 (const :tag "off" nil)
1444 (const :tag "on" t)
1445 (const :tag "on, optimized" optimized)))
1447 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1448 (version<= emacs-version "24.1"))
1449 "Non-nil means cluster self-insert commands for undo when possible.
1450 If this is set, then, like in the Emacs command loop, 20 consecutive
1451 characters will be undone together.
1452 This is configurable, because there is some impact on typing performance."
1453 :group 'org-table
1454 :type 'boolean)
1456 (defcustom org-table-tab-recognizes-table.el t
1457 "Non-nil means TAB will automatically notice a table.el table.
1458 When it sees such a table, it moves point into it and - if necessary -
1459 calls `table-recognize-table'."
1460 :group 'org-table-editing
1461 :type 'boolean)
1463 (defgroup org-link nil
1464 "Options concerning links in Org-mode."
1465 :tag "Org Link"
1466 :group 'org)
1468 (defvar org-link-abbrev-alist-local nil
1469 "Buffer-local version of `org-link-abbrev-alist', which see.
1470 The value of this is taken from the #+LINK lines.")
1471 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1473 (defcustom org-link-abbrev-alist nil
1474 "Alist of link abbreviations.
1475 The car of each element is a string, to be replaced at the start of a link.
1476 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1477 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1479 [[linkkey:tag][description]]
1481 The 'linkkey' must be a word word, starting with a letter, followed
1482 by letters, numbers, '-' or '_'.
1484 If REPLACE is a string, the tag will simply be appended to create the link.
1485 If the string contains \"%s\", the tag will be inserted there. If the string
1486 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1487 at that point (see the function `url-hexify-string'). If the string contains
1488 the specifier \"%(my-function)\", then the custom function `my-function' will
1489 be invoked: this function takes the tag as its only argument and must return
1490 a string.
1492 REPLACE may also be a function that will be called with the tag as the
1493 only argument to create the link, which should be returned as a string.
1495 See the manual for examples."
1496 :group 'org-link
1497 :type '(repeat
1498 (cons
1499 (string :tag "Protocol")
1500 (choice
1501 (string :tag "Format")
1502 (function)))))
1504 (defcustom org-descriptive-links t
1505 "Non-nil means Org will display descriptive links.
1506 E.g. [[http://orgmode.org][Org website]] will be displayed as
1507 \"Org Website\", hiding the link itself and just displaying its
1508 description. When set to `nil', Org will display the full links
1509 literally.
1511 You can interactively set the value of this variable by calling
1512 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1513 :group 'org-link
1514 :type 'boolean)
1516 (defcustom org-link-file-path-type 'adaptive
1517 "How the path name in file links should be stored.
1518 Valid values are:
1520 relative Relative to the current directory, i.e. the directory of the file
1521 into which the link is being inserted.
1522 absolute Absolute path, if possible with ~ for home directory.
1523 noabbrev Absolute path, no abbreviation of home directory.
1524 adaptive Use relative path for files in the current directory and sub-
1525 directories of it. For other files, use an absolute path."
1526 :group 'org-link
1527 :type '(choice
1528 (const relative)
1529 (const absolute)
1530 (const noabbrev)
1531 (const adaptive)))
1533 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1534 "Types of links that should be activated in Org-mode files.
1535 This is a list of symbols, each leading to the activation of a certain link
1536 type. In principle, it does not hurt to turn on most link types - there may
1537 be a small gain when turning off unused link types. The types are:
1539 bracket The recommended [[link][description]] or [[link]] links with hiding.
1540 angle Links in angular brackets that may contain whitespace like
1541 <bbdb:Carsten Dominik>.
1542 plain Plain links in normal text, no whitespace, like http://google.com.
1543 radio Text that is matched by a radio target, see manual for details.
1544 tag Tag settings in a headline (link to tag search).
1545 date Time stamps (link to calendar).
1546 footnote Footnote labels.
1548 Changing this variable requires a restart of Emacs to become effective."
1549 :group 'org-link
1550 :type '(set :greedy t
1551 (const :tag "Double bracket links" bracket)
1552 (const :tag "Angular bracket links" angle)
1553 (const :tag "Plain text links" plain)
1554 (const :tag "Radio target matches" radio)
1555 (const :tag "Tags" tag)
1556 (const :tag "Timestamps" date)
1557 (const :tag "Footnotes" footnote)))
1559 (defcustom org-make-link-description-function nil
1560 "Function to use for generating link descriptions from links.
1561 When nil, the link location will be used. This function must take
1562 two parameters: the first one is the link, the second one is the
1563 description generated by `org-insert-link'. The function should
1564 return the description to use."
1565 :group 'org-link
1566 :type 'function)
1568 (defgroup org-link-store nil
1569 "Options concerning storing links in Org-mode."
1570 :tag "Org Store Link"
1571 :group 'org-link)
1573 (defcustom org-url-hexify-p t
1574 "When non-nil, hexify URL when creating a link."
1575 :type 'boolean
1576 :version "24.3"
1577 :group 'org-link-store)
1579 (defcustom org-email-link-description-format "Email %c: %.30s"
1580 "Format of the description part of a link to an email or usenet message.
1581 The following %-escapes will be replaced by corresponding information:
1583 %F full \"From\" field
1584 %f name, taken from \"From\" field, address if no name
1585 %T full \"To\" field
1586 %t first name in \"To\" field, address if no name
1587 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1588 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1589 %s subject
1590 %d date
1591 %m message-id.
1593 You may use normal field width specification between the % and the letter.
1594 This is for example useful to limit the length of the subject.
1596 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1597 :group 'org-link-store
1598 :type 'string)
1600 (defcustom org-from-is-user-regexp
1601 (let (r1 r2)
1602 (when (and user-mail-address (not (string= user-mail-address "")))
1603 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1604 (when (and user-full-name (not (string= user-full-name "")))
1605 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1606 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1607 "Regexp matched against the \"From:\" header of an email or usenet message.
1608 It should match if the message is from the user him/herself."
1609 :group 'org-link-store
1610 :type 'regexp)
1612 (defcustom org-context-in-file-links t
1613 "Non-nil means file links from `org-store-link' contain context.
1614 A search string will be added to the file name with :: as separator and
1615 used to find the context when the link is activated by the command
1616 `org-open-at-point'. When this option is t, the entire active region
1617 will be placed in the search string of the file link. If set to a
1618 positive integer, only the first n lines of context will be stored.
1620 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1621 negates this setting for the duration of the command."
1622 :group 'org-link-store
1623 :type '(choice boolean integer))
1625 (defcustom org-keep-stored-link-after-insertion nil
1626 "Non-nil means keep link in list for entire session.
1628 The command `org-store-link' adds a link pointing to the current
1629 location to an internal list. These links accumulate during a session.
1630 The command `org-insert-link' can be used to insert links into any
1631 Org-mode file (offering completion for all stored links). When this
1632 option is nil, every link which has been inserted once using \\[org-insert-link]
1633 will be removed from the list, to make completing the unused links
1634 more efficient."
1635 :group 'org-link-store
1636 :type 'boolean)
1638 (defgroup org-link-follow nil
1639 "Options concerning following links in Org-mode."
1640 :tag "Org Follow Link"
1641 :group 'org-link)
1643 (defcustom org-link-translation-function nil
1644 "Function to translate links with different syntax to Org syntax.
1645 This can be used to translate links created for example by the Planner
1646 or emacs-wiki packages to Org syntax.
1647 The function must accept two parameters, a TYPE containing the link
1648 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1649 which is everything after the link protocol. It should return a cons
1650 with possibly modified values of type and path.
1651 Org contains a function for this, so if you set this variable to
1652 `org-translate-link-from-planner', you should be able follow many
1653 links created by planner."
1654 :group 'org-link-follow
1655 :type 'function)
1657 (defcustom org-follow-link-hook nil
1658 "Hook that is run after a link has been followed."
1659 :group 'org-link-follow
1660 :type 'hook)
1662 (defcustom org-tab-follows-link nil
1663 "Non-nil means on links TAB will follow the link.
1664 Needs to be set before org.el is loaded.
1665 This really should not be used, it does not make sense, and the
1666 implementation is bad."
1667 :group 'org-link-follow
1668 :type 'boolean)
1670 (defcustom org-return-follows-link nil
1671 "Non-nil means on links RET will follow the link.
1672 In tables, the special behavior of RET has precedence."
1673 :group 'org-link-follow
1674 :type 'boolean)
1676 (defcustom org-mouse-1-follows-link
1677 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1678 "Non-nil means mouse-1 on a link will follow the link.
1679 A longer mouse click will still set point. Does not work on XEmacs.
1680 Needs to be set before org.el is loaded."
1681 :group 'org-link-follow
1682 :type 'boolean)
1684 (defcustom org-mark-ring-length 4
1685 "Number of different positions to be recorded in the ring.
1686 Changing this requires a restart of Emacs to work correctly."
1687 :group 'org-link-follow
1688 :type 'integer)
1690 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1691 "Non-nil means internal links in Org files must exactly match a headline.
1692 When nil, the link search tries to match a phrase with all words
1693 in the search text."
1694 :group 'org-link-follow
1695 :version "24.1"
1696 :type '(choice
1697 (const :tag "Use fuzzy text search" nil)
1698 (const :tag "Match only exact headline" t)
1699 (const :tag "Match exact headline or query to create it"
1700 query-to-create)))
1702 (defcustom org-link-frame-setup
1703 '((vm . vm-visit-folder-other-frame)
1704 (vm-imap . vm-visit-imap-folder-other-frame)
1705 (gnus . org-gnus-no-new-news)
1706 (file . find-file-other-window)
1707 (wl . wl-other-frame))
1708 "Setup the frame configuration for following links.
1709 When following a link with Emacs, it may often be useful to display
1710 this link in another window or frame. This variable can be used to
1711 set this up for the different types of links.
1712 For VM, use any of
1713 `vm-visit-folder'
1714 `vm-visit-folder-other-window'
1715 `vm-visit-folder-other-frame'
1716 For Gnus, use any of
1717 `gnus'
1718 `gnus-other-frame'
1719 `org-gnus-no-new-news'
1720 For FILE, use any of
1721 `find-file'
1722 `find-file-other-window'
1723 `find-file-other-frame'
1724 For Wanderlust use any of
1725 `wl'
1726 `wl-other-frame'
1727 For the calendar, use the variable `calendar-setup'.
1728 For BBDB, it is currently only possible to display the matches in
1729 another window."
1730 :group 'org-link-follow
1731 :type '(list
1732 (cons (const vm)
1733 (choice
1734 (const vm-visit-folder)
1735 (const vm-visit-folder-other-window)
1736 (const vm-visit-folder-other-frame)))
1737 (cons (const gnus)
1738 (choice
1739 (const gnus)
1740 (const gnus-other-frame)
1741 (const org-gnus-no-new-news)))
1742 (cons (const file)
1743 (choice
1744 (const find-file)
1745 (const find-file-other-window)
1746 (const find-file-other-frame)))
1747 (cons (const wl)
1748 (choice
1749 (const wl)
1750 (const wl-other-frame)))))
1752 (defcustom org-display-internal-link-with-indirect-buffer nil
1753 "Non-nil means use indirect buffer to display infile links.
1754 Activating internal links (from one location in a file to another location
1755 in the same file) normally just jumps to the location. When the link is
1756 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1757 is displayed in
1758 another window. When this option is set, the other window actually displays
1759 an indirect buffer clone of the current buffer, to avoid any visibility
1760 changes to the current buffer."
1761 :group 'org-link-follow
1762 :type 'boolean)
1764 (defcustom org-open-non-existing-files nil
1765 "Non-nil means `org-open-file' will open non-existing files.
1766 When nil, an error will be generated.
1767 This variable applies only to external applications because they
1768 might choke on non-existing files. If the link is to a file that
1769 will be opened in Emacs, the variable is ignored."
1770 :group 'org-link-follow
1771 :type 'boolean)
1773 (defcustom org-open-directory-means-index-dot-org nil
1774 "Non-nil means a link to a directory really means to index.org.
1775 When nil, following a directory link will run dired or open a finder/explorer
1776 window on that directory."
1777 :group 'org-link-follow
1778 :type 'boolean)
1780 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1781 "Function and arguments to call for following mailto links.
1782 This is a list with the first element being a Lisp function, and the
1783 remaining elements being arguments to the function. In string arguments,
1784 %a will be replaced by the address, and %s will be replaced by the subject
1785 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1786 :group 'org-link-follow
1787 :type '(choice
1788 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1789 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1790 (const :tag "message-mail" (message-mail "%a" "%s"))
1791 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1793 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1794 "Non-nil means ask for confirmation before executing shell links.
1795 Shell links can be dangerous: just think about a link
1797 [[shell:rm -rf ~/*][Google Search]]
1799 This link would show up in your Org-mode document as \"Google Search\",
1800 but really it would remove your entire home directory.
1801 Therefore we advise against setting this variable to nil.
1802 Just change it to `y-or-n-p' if you want to confirm with a
1803 single keystroke rather than having to type \"yes\"."
1804 :group 'org-link-follow
1805 :type '(choice
1806 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1807 (const :tag "with y-or-n (faster)" y-or-n-p)
1808 (const :tag "no confirmation (dangerous)" nil)))
1809 (put 'org-confirm-shell-link-function
1810 'safe-local-variable
1811 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1813 (defcustom org-confirm-shell-link-not-regexp ""
1814 "A regexp to skip confirmation for shell links."
1815 :group 'org-link-follow
1816 :version "24.1"
1817 :type 'regexp)
1819 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1820 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1821 Elisp links can be dangerous: just think about a link
1823 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1825 This link would show up in your Org-mode document as \"Google Search\",
1826 but really it would remove your entire home directory.
1827 Therefore we advise against setting this variable to nil.
1828 Just change it to `y-or-n-p' if you want to confirm with a
1829 single keystroke rather than having to type \"yes\"."
1830 :group 'org-link-follow
1831 :type '(choice
1832 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1833 (const :tag "with y-or-n (faster)" y-or-n-p)
1834 (const :tag "no confirmation (dangerous)" nil)))
1835 (put 'org-confirm-shell-link-function
1836 'safe-local-variable
1837 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1839 (defcustom org-confirm-elisp-link-not-regexp ""
1840 "A regexp to skip confirmation for Elisp links."
1841 :group 'org-link-follow
1842 :version "24.1"
1843 :type 'regexp)
1845 (defconst org-file-apps-defaults-gnu
1846 '((remote . emacs)
1847 (system . mailcap)
1848 (t . mailcap))
1849 "Default file applications on a UNIX or GNU/Linux system.
1850 See `org-file-apps'.")
1852 (defconst org-file-apps-defaults-macosx
1853 '((remote . emacs)
1854 (t . "open %s")
1855 (system . "open %s")
1856 ("ps.gz" . "gv %s")
1857 ("eps.gz" . "gv %s")
1858 ("dvi" . "xdvi %s")
1859 ("fig" . "xfig %s"))
1860 "Default file applications on a MacOS X system.
1861 The system \"open\" is known as a default, but we use X11 applications
1862 for some files for which the OS does not have a good default.
1863 See `org-file-apps'.")
1865 (defconst org-file-apps-defaults-windowsnt
1866 (list
1867 '(remote . emacs)
1868 (cons t
1869 (list (if (featurep 'xemacs)
1870 'mswindows-shell-execute
1871 'w32-shell-execute)
1872 "open" 'file))
1873 (cons 'system
1874 (list (if (featurep 'xemacs)
1875 'mswindows-shell-execute
1876 'w32-shell-execute)
1877 "open" 'file)))
1878 "Default file applications on a Windows NT system.
1879 The system \"open\" is used for most files.
1880 See `org-file-apps'.")
1882 (defcustom org-file-apps
1884 (auto-mode . emacs)
1885 ("\\.mm\\'" . default)
1886 ("\\.x?html?\\'" . default)
1887 ("\\.pdf\\'" . default)
1889 "External applications for opening `file:path' items in a document.
1890 Org-mode uses system defaults for different file types, but
1891 you can use this variable to set the application for a given file
1892 extension. The entries in this list are cons cells where the car identifies
1893 files and the cdr the corresponding command. Possible values for the
1894 file identifier are
1895 \"string\" A string as a file identifier can be interpreted in different
1896 ways, depending on its contents:
1898 - Alphanumeric characters only:
1899 Match links with this file extension.
1900 Example: (\"pdf\" . \"evince %s\")
1901 to open PDFs with evince.
1903 - Regular expression: Match links where the
1904 filename matches the regexp. If you want to
1905 use groups here, use shy groups.
1907 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1908 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1909 to open *.html and *.xhtml with firefox.
1911 - Regular expression which contains (non-shy) groups:
1912 Match links where the whole link, including \"::\", and
1913 anything after that, matches the regexp.
1914 In a custom command string, %1, %2, etc. are replaced with
1915 the parts of the link that were matched by the groups.
1916 For backwards compatibility, if a command string is given
1917 that does not use any of the group matches, this case is
1918 handled identically to the second one (i.e. match against
1919 file name only).
1920 In a custom lisp form, you can access the group matches with
1921 (match-string n link).
1923 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1924 to open [[file:document.pdf::5]] with evince at page 5.
1926 `directory' Matches a directory
1927 `remote' Matches a remote file, accessible through tramp or efs.
1928 Remote files most likely should be visited through Emacs
1929 because external applications cannot handle such paths.
1930 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1931 so all files Emacs knows how to handle. Using this with
1932 command `emacs' will open most files in Emacs. Beware that this
1933 will also open html files inside Emacs, unless you add
1934 (\"html\" . default) to the list as well.
1935 t Default for files not matched by any of the other options.
1936 `system' The system command to open files, like `open' on Windows
1937 and Mac OS X, and mailcap under GNU/Linux. This is the command
1938 that will be selected if you call `C-c C-o' with a double
1939 \\[universal-argument] \\[universal-argument] prefix.
1941 Possible values for the command are:
1942 `emacs' The file will be visited by the current Emacs process.
1943 `default' Use the default application for this file type, which is the
1944 association for t in the list, most likely in the system-specific
1945 part.
1946 This can be used to overrule an unwanted setting in the
1947 system-specific variable.
1948 `system' Use the system command for opening files, like \"open\".
1949 This command is specified by the entry whose car is `system'.
1950 Most likely, the system-specific version of this variable
1951 does define this command, but you can overrule/replace it
1952 here.
1953 string A command to be executed by a shell; %s will be replaced
1954 by the path to the file.
1955 sexp A Lisp form which will be evaluated. The file path will
1956 be available in the Lisp variable `file'.
1957 For more examples, see the system specific constants
1958 `org-file-apps-defaults-macosx'
1959 `org-file-apps-defaults-windowsnt'
1960 `org-file-apps-defaults-gnu'."
1961 :group 'org-link-follow
1962 :type '(repeat
1963 (cons (choice :value ""
1964 (string :tag "Extension")
1965 (const :tag "System command to open files" system)
1966 (const :tag "Default for unrecognized files" t)
1967 (const :tag "Remote file" remote)
1968 (const :tag "Links to a directory" directory)
1969 (const :tag "Any files that have Emacs modes"
1970 auto-mode))
1971 (choice :value ""
1972 (const :tag "Visit with Emacs" emacs)
1973 (const :tag "Use default" default)
1974 (const :tag "Use the system command" system)
1975 (string :tag "Command")
1976 (sexp :tag "Lisp form")))))
1978 (defcustom org-doi-server-url "http://dx.doi.org/"
1979 "The URL of the DOI server."
1980 :type 'string
1981 :version "24.3"
1982 :group 'org-link-follow)
1984 (defgroup org-refile nil
1985 "Options concerning refiling entries in Org-mode."
1986 :tag "Org Refile"
1987 :group 'org)
1989 (defcustom org-directory "~/org"
1990 "Directory with org files.
1991 This is just a default location to look for Org files. There is no need
1992 at all to put your files into this directory. It is only used in the
1993 following situations:
1995 1. When a capture template specifies a target file that is not an
1996 absolute path. The path will then be interpreted relative to
1997 `org-directory'
1998 2. When a capture note is filed away in an interactive way (when exiting the
1999 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2000 with `org-directory' as the default path."
2001 :group 'org-refile
2002 :group 'org-remember
2003 :group 'org-capture
2004 :type 'directory)
2006 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2007 "Default target for storing notes.
2008 Used as a fall back file for org-remember.el and org-capture.el, for
2009 templates that do not specify a target file."
2010 :group 'org-refile
2011 :group 'org-remember
2012 :group 'org-capture
2013 :type '(choice
2014 (const :tag "Default from remember-data-file" nil)
2015 file))
2017 (defcustom org-goto-interface 'outline
2018 "The default interface to be used for `org-goto'.
2019 Allowed values are:
2020 outline The interface shows an outline of the relevant file
2021 and the correct heading is found by moving through
2022 the outline or by searching with incremental search.
2023 outline-path-completion Headlines in the current buffer are offered via
2024 completion. This is the interface also used by
2025 the refile command."
2026 :group 'org-refile
2027 :type '(choice
2028 (const :tag "Outline" outline)
2029 (const :tag "Outline-path-completion" outline-path-completion)))
2031 (defcustom org-goto-max-level 5
2032 "Maximum target level when running `org-goto' with refile interface."
2033 :group 'org-refile
2034 :type 'integer)
2036 (defcustom org-reverse-note-order nil
2037 "Non-nil means store new notes at the beginning of a file or entry.
2038 When nil, new notes will be filed to the end of a file or entry.
2039 This can also be a list with cons cells of regular expressions that
2040 are matched against file names, and values."
2041 :group 'org-remember
2042 :group 'org-capture
2043 :group 'org-refile
2044 :type '(choice
2045 (const :tag "Reverse always" t)
2046 (const :tag "Reverse never" nil)
2047 (repeat :tag "By file name regexp"
2048 (cons regexp boolean))))
2050 (defcustom org-log-refile nil
2051 "Information to record when a task is refiled.
2053 Possible values are:
2055 nil Don't add anything
2056 time Add a time stamp to the task
2057 note Prompt for a note and add it with template `org-log-note-headings'
2059 This option can also be set with on a per-file-basis with
2061 #+STARTUP: nologrefile
2062 #+STARTUP: logrefile
2063 #+STARTUP: lognoterefile
2065 You can have local logging settings for a subtree by setting the LOGGING
2066 property to one or more of these keywords.
2068 When bulk-refiling from the agenda, the value `note' is forbidden and
2069 will temporarily be changed to `time'."
2070 :group 'org-refile
2071 :group 'org-progress
2072 :version "24.1"
2073 :type '(choice
2074 (const :tag "No logging" nil)
2075 (const :tag "Record timestamp" time)
2076 (const :tag "Record timestamp with note." note)))
2078 (defcustom org-refile-targets nil
2079 "Targets for refiling entries with \\[org-refile].
2080 This is a list of cons cells. Each cell contains:
2081 - a specification of the files to be considered, either a list of files,
2082 or a symbol whose function or variable value will be used to retrieve
2083 a file name or a list of file names. If you use `org-agenda-files' for
2084 that, all agenda files will be scanned for targets. Nil means consider
2085 headings in the current buffer.
2086 - A specification of how to find candidate refile targets. This may be
2087 any of:
2088 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2089 This tag has to be present in all target headlines, inheritance will
2090 not be considered.
2091 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2092 todo keyword.
2093 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2094 headlines that are refiling targets.
2095 - a cons cell (:level . N). Any headline of level N is considered a target.
2096 Note that, when `org-odd-levels-only' is set, level corresponds to
2097 order in hierarchy, not to the number of stars.
2098 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2099 Note that, when `org-odd-levels-only' is set, level corresponds to
2100 order in hierarchy, not to the number of stars.
2102 Each element of this list generates a set of possible targets.
2103 The union of these sets is presented (with completion) to
2104 the user by `org-refile'.
2106 You can set the variable `org-refile-target-verify-function' to a function
2107 to verify each headline found by the simple criteria above.
2109 When this variable is nil, all top-level headlines in the current buffer
2110 are used, equivalent to the value `((nil . (:level . 1))'."
2111 :group 'org-refile
2112 :type '(repeat
2113 (cons
2114 (choice :value org-agenda-files
2115 (const :tag "All agenda files" org-agenda-files)
2116 (const :tag "Current buffer" nil)
2117 (function) (variable) (file))
2118 (choice :tag "Identify target headline by"
2119 (cons :tag "Specific tag" (const :value :tag) (string))
2120 (cons :tag "TODO keyword" (const :value :todo) (string))
2121 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2122 (cons :tag "Level number" (const :value :level) (integer))
2123 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2125 (defcustom org-refile-target-verify-function nil
2126 "Function to verify if the headline at point should be a refile target.
2127 The function will be called without arguments, with point at the
2128 beginning of the headline. It should return t and leave point
2129 where it is if the headline is a valid target for refiling.
2131 If the target should not be selected, the function must return nil.
2132 In addition to this, it may move point to a place from where the search
2133 should be continued. For example, the function may decide that the entire
2134 subtree of the current entry should be excluded and move point to the end
2135 of the subtree."
2136 :group 'org-refile
2137 :type 'function)
2139 (defcustom org-refile-use-cache nil
2140 "Non-nil means cache refile targets to speed up the process.
2141 The cache for a particular file will be updated automatically when
2142 the buffer has been killed, or when any of the marker used for flagging
2143 refile targets no longer points at a live buffer.
2144 If you have added new entries to a buffer that might themselves be targets,
2145 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2146 find that easier, `C-u C-u C-u C-c C-w'."
2147 :group 'org-refile
2148 :version "24.1"
2149 :type 'boolean)
2151 (defcustom org-refile-use-outline-path nil
2152 "Non-nil means provide refile targets as paths.
2153 So a level 3 headline will be available as level1/level2/level3.
2155 When the value is `file', also include the file name (without directory)
2156 into the path. In this case, you can also stop the completion after
2157 the file name, to get entries inserted as top level in the file.
2159 When `full-file-path', include the full file path."
2160 :group 'org-refile
2161 :type '(choice
2162 (const :tag "Not" nil)
2163 (const :tag "Yes" t)
2164 (const :tag "Start with file name" file)
2165 (const :tag "Start with full file path" full-file-path)))
2167 (defcustom org-outline-path-complete-in-steps t
2168 "Non-nil means complete the outline path in hierarchical steps.
2169 When Org-mode uses the refile interface to select an outline path
2170 \(see variable `org-refile-use-outline-path'), the completion of
2171 the path can be done is a single go, or if can be done in steps down
2172 the headline hierarchy. Going in steps is probably the best if you
2173 do not use a special completion package like `ido' or `icicles'.
2174 However, when using these packages, going in one step can be very
2175 fast, while still showing the whole path to the entry."
2176 :group 'org-refile
2177 :type 'boolean)
2179 (defcustom org-refile-allow-creating-parent-nodes nil
2180 "Non-nil means allow to create new nodes as refile targets.
2181 New nodes are then created by adding \"/new node name\" to the completion
2182 of an existing node. When the value of this variable is `confirm',
2183 new node creation must be confirmed by the user (recommended)
2184 When nil, the completion must match an existing entry.
2186 Note that, if the new heading is not seen by the criteria
2187 listed in `org-refile-targets', multiple instances of the same
2188 heading would be created by trying again to file under the new
2189 heading."
2190 :group 'org-refile
2191 :type '(choice
2192 (const :tag "Never" nil)
2193 (const :tag "Always" t)
2194 (const :tag "Prompt for confirmation" confirm)))
2196 (defcustom org-refile-active-region-within-subtree nil
2197 "Non-nil means also refile active region within a subtree.
2199 By default `org-refile' doesn't allow refiling regions if they
2200 don't contain a set of subtrees, but it might be convenient to
2201 do so sometimes: in that case, the first line of the region is
2202 converted to a headline before refiling."
2203 :group 'org-refile
2204 :version "24.1"
2205 :type 'boolean)
2207 (defgroup org-todo nil
2208 "Options concerning TODO items in Org-mode."
2209 :tag "Org TODO"
2210 :group 'org)
2212 (defgroup org-progress nil
2213 "Options concerning Progress logging in Org-mode."
2214 :tag "Org Progress"
2215 :group 'org-time)
2217 (defvar org-todo-interpretation-widgets
2218 '((:tag "Sequence (cycling hits every state)" sequence)
2219 (:tag "Type (cycling directly to DONE)" type))
2220 "The available interpretation symbols for customizing `org-todo-keywords'.
2221 Interested libraries should add to this list.")
2223 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2224 "List of TODO entry keyword sequences and their interpretation.
2225 \\<org-mode-map>This is a list of sequences.
2227 Each sequence starts with a symbol, either `sequence' or `type',
2228 indicating if the keywords should be interpreted as a sequence of
2229 action steps, or as different types of TODO items. The first
2230 keywords are states requiring action - these states will select a headline
2231 for inclusion into the global TODO list Org-mode produces. If one of
2232 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2233 signify that no further action is necessary. If \"|\" is not found,
2234 the last keyword is treated as the only DONE state of the sequence.
2236 The command \\[org-todo] cycles an entry through these states, and one
2237 additional state where no keyword is present. For details about this
2238 cycling, see the manual.
2240 TODO keywords and interpretation can also be set on a per-file basis with
2241 the special #+SEQ_TODO and #+TYP_TODO lines.
2243 Each keyword can optionally specify a character for fast state selection
2244 \(in combination with the variable `org-use-fast-todo-selection')
2245 and specifiers for state change logging, using the same syntax that
2246 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2247 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2248 indicates to record a time stamp each time this state is selected.
2250 Each keyword may also specify if a timestamp or a note should be
2251 recorded when entering or leaving the state, by adding additional
2252 characters in the parenthesis after the keyword. This looks like this:
2253 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2254 record only the time of the state change. With X and Y being either
2255 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2256 Y when leaving the state if and only if the *target* state does not
2257 define X. You may omit any of the fast-selection key or X or /Y,
2258 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2260 For backward compatibility, this variable may also be just a list
2261 of keywords. In this case the interpretation (sequence or type) will be
2262 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2263 :group 'org-todo
2264 :group 'org-keywords
2265 :type '(choice
2266 (repeat :tag "Old syntax, just keywords"
2267 (string :tag "Keyword"))
2268 (repeat :tag "New syntax"
2269 (cons
2270 (choice
2271 :tag "Interpretation"
2272 ;;Quick and dirty way to see
2273 ;;`org-todo-interpretations'. This takes the
2274 ;;place of item arguments
2275 :convert-widget
2276 (lambda (widget)
2277 (widget-put widget
2278 :args (mapcar
2279 #'(lambda (x)
2280 (widget-convert
2281 (cons 'const x)))
2282 org-todo-interpretation-widgets))
2283 widget))
2284 (repeat
2285 (string :tag "Keyword"))))))
2287 (defvar org-todo-keywords-1 nil
2288 "All TODO and DONE keywords active in a buffer.")
2289 (make-variable-buffer-local 'org-todo-keywords-1)
2290 (defvar org-todo-keywords-for-agenda nil)
2291 (defvar org-done-keywords-for-agenda nil)
2292 (defvar org-drawers-for-agenda nil)
2293 (defvar org-todo-keyword-alist-for-agenda nil)
2294 (defvar org-tag-alist-for-agenda nil
2295 "Alist of all tags from all agenda files.")
2296 (defvar org-tag-groups-alist-for-agenda nil
2297 "Alist of all groups tags from all current agenda files.")
2298 (defvar org-tag-groups-alist nil)
2299 (make-variable-buffer-local 'org-tag-groups-alist)
2300 (defvar org-agenda-contributing-files nil)
2301 (defvar org-not-done-keywords nil)
2302 (make-variable-buffer-local 'org-not-done-keywords)
2303 (defvar org-done-keywords nil)
2304 (make-variable-buffer-local 'org-done-keywords)
2305 (defvar org-todo-heads nil)
2306 (make-variable-buffer-local 'org-todo-heads)
2307 (defvar org-todo-sets nil)
2308 (make-variable-buffer-local 'org-todo-sets)
2309 (defvar org-todo-log-states nil)
2310 (make-variable-buffer-local 'org-todo-log-states)
2311 (defvar org-todo-kwd-alist nil)
2312 (make-variable-buffer-local 'org-todo-kwd-alist)
2313 (defvar org-todo-key-alist nil)
2314 (make-variable-buffer-local 'org-todo-key-alist)
2315 (defvar org-todo-key-trigger nil)
2316 (make-variable-buffer-local 'org-todo-key-trigger)
2318 (defcustom org-todo-interpretation 'sequence
2319 "Controls how TODO keywords are interpreted.
2320 This variable is in principle obsolete and is only used for
2321 backward compatibility, if the interpretation of todo keywords is
2322 not given already in `org-todo-keywords'. See that variable for
2323 more information."
2324 :group 'org-todo
2325 :group 'org-keywords
2326 :type '(choice (const sequence)
2327 (const type)))
2329 (defcustom org-use-fast-todo-selection t
2330 "Non-nil means use the fast todo selection scheme with C-c C-t.
2331 This variable describes if and under what circumstances the cycling
2332 mechanism for TODO keywords will be replaced by a single-key, direct
2333 selection scheme.
2335 When nil, fast selection is never used.
2337 When the symbol `prefix', it will be used when `org-todo' is called
2338 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2339 `C-u t' in an agenda buffer.
2341 When t, fast selection is used by default. In this case, the prefix
2342 argument forces cycling instead.
2344 In all cases, the special interface is only used if access keys have
2345 actually been assigned by the user, i.e. if keywords in the configuration
2346 are followed by a letter in parenthesis, like TODO(t)."
2347 :group 'org-todo
2348 :type '(choice
2349 (const :tag "Never" nil)
2350 (const :tag "By default" t)
2351 (const :tag "Only with C-u C-c C-t" prefix)))
2353 (defcustom org-provide-todo-statistics t
2354 "Non-nil means update todo statistics after insert and toggle.
2355 ALL-HEADLINES means update todo statistics by including headlines
2356 with no TODO keyword as well, counting them as not done.
2357 A list of TODO keywords means the same, but skip keywords that are
2358 not in this list.
2360 When this is set, todo statistics is updated in the parent of the
2361 current entry each time a todo state is changed."
2362 :group 'org-todo
2363 :type '(choice
2364 (const :tag "Yes, only for TODO entries" t)
2365 (const :tag "Yes, including all entries" 'all-headlines)
2366 (repeat :tag "Yes, for TODOs in this list"
2367 (string :tag "TODO keyword"))
2368 (other :tag "No TODO statistics" nil)))
2370 (defcustom org-hierarchical-todo-statistics t
2371 "Non-nil means TODO statistics covers just direct children.
2372 When nil, all entries in the subtree are considered.
2373 This has only an effect if `org-provide-todo-statistics' is set.
2374 To set this to nil for only a single subtree, use a COOKIE_DATA
2375 property and include the word \"recursive\" into the value."
2376 :group 'org-todo
2377 :type 'boolean)
2379 (defcustom org-after-todo-state-change-hook nil
2380 "Hook which is run after the state of a TODO item was changed.
2381 The new state (a string with a TODO keyword, or nil) is available in the
2382 Lisp variable `org-state'."
2383 :group 'org-todo
2384 :type 'hook)
2386 (defvar org-blocker-hook nil
2387 "Hook for functions that are allowed to block a state change.
2389 Functions in this hook should not modify the buffer.
2390 Each function gets as its single argument a property list,
2391 see `org-trigger-hook' for more information about this list.
2393 If any of the functions in this hook returns nil, the state change
2394 is blocked.")
2396 (defvar org-trigger-hook nil
2397 "Hook for functions that are triggered by a state change.
2399 Each function gets as its single argument a property list with at
2400 least the following elements:
2402 (:type type-of-change :position pos-at-entry-start
2403 :from old-state :to new-state)
2405 Depending on the type, more properties may be present.
2407 This mechanism is currently implemented for:
2409 TODO state changes
2410 ------------------
2411 :type todo-state-change
2412 :from previous state (keyword as a string), or nil, or a symbol
2413 'todo' or 'done', to indicate the general type of state.
2414 :to new state, like in :from")
2416 (defcustom org-enforce-todo-dependencies nil
2417 "Non-nil means undone TODO entries will block switching the parent to DONE.
2418 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2419 be blocked if any prior sibling is not yet done.
2420 Finally, if the parent is blocked because of ordered siblings of its own,
2421 the child will also be blocked."
2422 :set (lambda (var val)
2423 (set var val)
2424 (if val
2425 (add-hook 'org-blocker-hook
2426 'org-block-todo-from-children-or-siblings-or-parent)
2427 (remove-hook 'org-blocker-hook
2428 'org-block-todo-from-children-or-siblings-or-parent)))
2429 :group 'org-todo
2430 :type 'boolean)
2432 (defcustom org-enforce-todo-checkbox-dependencies nil
2433 "Non-nil means unchecked boxes will block switching the parent to DONE.
2434 When this is nil, checkboxes have no influence on switching TODO states.
2435 When non-nil, you first need to check off all check boxes before the TODO
2436 entry can be switched to DONE.
2437 This variable needs to be set before org.el is loaded, and you need to
2438 restart Emacs after a change to make the change effective. The only way
2439 to change is while Emacs is running is through the customize interface."
2440 :set (lambda (var val)
2441 (set var val)
2442 (if val
2443 (add-hook 'org-blocker-hook
2444 'org-block-todo-from-checkboxes)
2445 (remove-hook 'org-blocker-hook
2446 'org-block-todo-from-checkboxes)))
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-treat-insert-todo-heading-as-state-change nil
2451 "Non-nil means inserting a TODO heading is treated as state change.
2452 So when the command \\[org-insert-todo-heading] is used, state change
2453 logging will apply if appropriate. When nil, the new TODO item will
2454 be inserted directly, and no logging will take place."
2455 :group 'org-todo
2456 :type 'boolean)
2458 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2459 "Non-nil means switching TODO states with S-cursor counts as state change.
2460 This is the default behavior. However, setting this to nil allows a
2461 convenient way to select a TODO state and bypass any logging associated
2462 with that."
2463 :group 'org-todo
2464 :type 'boolean)
2466 (defcustom org-todo-state-tags-triggers nil
2467 "Tag changes that should be triggered by TODO state changes.
2468 This is a list. Each entry is
2470 (state-change (tag . flag) .......)
2472 State-change can be a string with a state, and empty string to indicate the
2473 state that has no TODO keyword, or it can be one of the symbols `todo'
2474 or `done', meaning any not-done or done state, respectively."
2475 :group 'org-todo
2476 :group 'org-tags
2477 :type '(repeat
2478 (cons (choice :tag "When changing to"
2479 (const :tag "Not-done state" todo)
2480 (const :tag "Done state" done)
2481 (string :tag "State"))
2482 (repeat
2483 (cons :tag "Tag action"
2484 (string :tag "Tag")
2485 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2487 (defcustom org-log-done nil
2488 "Information to record when a task moves to the DONE state.
2490 Possible values are:
2492 nil Don't add anything, just change the keyword
2493 time Add a time stamp to the task
2494 note Prompt for a note and add it with template `org-log-note-headings'
2496 This option can also be set with on a per-file-basis with
2498 #+STARTUP: nologdone
2499 #+STARTUP: logdone
2500 #+STARTUP: lognotedone
2502 You can have local logging settings for a subtree by setting the LOGGING
2503 property to one or more of these keywords."
2504 :group 'org-todo
2505 :group 'org-progress
2506 :type '(choice
2507 (const :tag "No logging" nil)
2508 (const :tag "Record CLOSED timestamp" time)
2509 (const :tag "Record CLOSED timestamp with note." note)))
2511 ;; Normalize old uses of org-log-done.
2512 (cond
2513 ((eq org-log-done t) (setq org-log-done 'time))
2514 ((and (listp org-log-done) (memq 'done org-log-done))
2515 (setq org-log-done 'note)))
2517 (defcustom org-log-reschedule nil
2518 "Information to record when the scheduling date of a tasks is modified.
2520 Possible values are:
2522 nil Don't add anything, just change the date
2523 time Add a time stamp to the task
2524 note Prompt for a note and add it with template `org-log-note-headings'
2526 This option can also be set with on a per-file-basis with
2528 #+STARTUP: nologreschedule
2529 #+STARTUP: logreschedule
2530 #+STARTUP: lognotereschedule"
2531 :group 'org-todo
2532 :group 'org-progress
2533 :type '(choice
2534 (const :tag "No logging" nil)
2535 (const :tag "Record timestamp" time)
2536 (const :tag "Record timestamp with note." note)))
2538 (defcustom org-log-redeadline nil
2539 "Information to record when the deadline date of a tasks is modified.
2541 Possible values are:
2543 nil Don't add anything, just change the date
2544 time Add a time stamp to the task
2545 note Prompt for a note and add it with template `org-log-note-headings'
2547 This option can also be set with on a per-file-basis with
2549 #+STARTUP: nologredeadline
2550 #+STARTUP: logredeadline
2551 #+STARTUP: lognoteredeadline
2553 You can have local logging settings for a subtree by setting the LOGGING
2554 property to one or more of these keywords."
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type '(choice
2558 (const :tag "No logging" nil)
2559 (const :tag "Record timestamp" time)
2560 (const :tag "Record timestamp with note." note)))
2562 (defcustom org-log-note-clock-out nil
2563 "Non-nil means record a note when clocking out of an item.
2564 This can also be configured on a per-file basis by adding one of
2565 the following lines anywhere in the buffer:
2567 #+STARTUP: lognoteclock-out
2568 #+STARTUP: nolognoteclock-out"
2569 :group 'org-todo
2570 :group 'org-progress
2571 :type 'boolean)
2573 (defcustom org-log-done-with-time t
2574 "Non-nil means the CLOSED time stamp will contain date and time.
2575 When nil, only the date will be recorded."
2576 :group 'org-progress
2577 :type 'boolean)
2579 (defcustom org-log-note-headings
2580 '((done . "CLOSING NOTE %t")
2581 (state . "State %-12s from %-12S %t")
2582 (note . "Note taken on %t")
2583 (reschedule . "Rescheduled from %S on %t")
2584 (delschedule . "Not scheduled, was %S on %t")
2585 (redeadline . "New deadline from %S on %t")
2586 (deldeadline . "Removed deadline, was %S on %t")
2587 (refile . "Refiled on %t")
2588 (clock-out . ""))
2589 "Headings for notes added to entries.
2590 The value is an alist, with the car being a symbol indicating the note
2591 context, and the cdr is the heading to be used. The heading may also be the
2592 empty string.
2593 %t in the heading will be replaced by a time stamp.
2594 %T will be an active time stamp instead the default inactive one
2595 %d will be replaced by a short-format time stamp.
2596 %D will be replaced by an active short-format time stamp.
2597 %s will be replaced by the new TODO state, in double quotes.
2598 %S will be replaced by the old TODO state, in double quotes.
2599 %u will be replaced by the user name.
2600 %U will be replaced by the full user name.
2602 In fact, it is not a good idea to change the `state' entry, because
2603 agenda log mode depends on the format of these entries."
2604 :group 'org-todo
2605 :group 'org-progress
2606 :type '(list :greedy t
2607 (cons (const :tag "Heading when closing an item" done) string)
2608 (cons (const :tag
2609 "Heading when changing todo state (todo sequence only)"
2610 state) string)
2611 (cons (const :tag "Heading when just taking a note" note) string)
2612 (cons (const :tag "Heading when clocking out" clock-out) string)
2613 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2614 (cons (const :tag "Heading when rescheduling" reschedule) string)
2615 (cons (const :tag "Heading when changing deadline" redeadline) string)
2616 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2617 (cons (const :tag "Heading when refiling" refile) string)))
2619 (unless (assq 'note org-log-note-headings)
2620 (push '(note . "%t") org-log-note-headings))
2622 (defcustom org-log-into-drawer nil
2623 "Non-nil means insert state change notes and time stamps into a drawer.
2624 When nil, state changes notes will be inserted after the headline and
2625 any scheduling and clock lines, but not inside a drawer.
2627 The value of this variable should be the name of the drawer to use.
2628 LOGBOOK is proposed as the default drawer for this purpose, you can
2629 also set this to a string to define the drawer of your choice.
2631 A value of t is also allowed, representing \"LOGBOOK\".
2633 A value of t or nil can also be set with on a per-file-basis with
2635 #+STARTUP: logdrawer
2636 #+STARTUP: nologdrawer
2638 If this variable is set, `org-log-state-notes-insert-after-drawers'
2639 will be ignored.
2641 You can set the property LOG_INTO_DRAWER to overrule this setting for
2642 a subtree."
2643 :group 'org-todo
2644 :group 'org-progress
2645 :type '(choice
2646 (const :tag "Not into a drawer" nil)
2647 (const :tag "LOGBOOK" t)
2648 (string :tag "Other")))
2650 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2652 (defun org-log-into-drawer ()
2653 "Return the value of `org-log-into-drawer', but let properties overrule.
2654 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2655 used instead of the default value."
2656 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2657 (cond
2658 ((not p) org-log-into-drawer)
2659 ((equal p "nil") nil)
2660 ((equal p "t") "LOGBOOK")
2661 (t p))))
2663 (defcustom org-log-state-notes-insert-after-drawers nil
2664 "Non-nil means insert state change notes after any drawers in entry.
2665 Only the drawers that *immediately* follow the headline and the
2666 deadline/scheduled line are skipped.
2667 When nil, insert notes right after the heading and perhaps the line
2668 with deadline/scheduling if present.
2670 This variable will have no effect if `org-log-into-drawer' is
2671 set."
2672 :group 'org-todo
2673 :group 'org-progress
2674 :type 'boolean)
2676 (defcustom org-log-states-order-reversed t
2677 "Non-nil means the latest state note will be directly after heading.
2678 When nil, the state change notes will be ordered according to time.
2680 This option can also be set with on a per-file-basis with
2682 #+STARTUP: logstatesreversed
2683 #+STARTUP: nologstatesreversed"
2684 :group 'org-todo
2685 :group 'org-progress
2686 :type 'boolean)
2688 (defcustom org-todo-repeat-to-state nil
2689 "The TODO state to which a repeater should return the repeating task.
2690 By default this is the first task in a TODO sequence, or the previous state
2691 in a TODO_TYP set. But you can specify another task here.
2692 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2693 :group 'org-todo
2694 :version "24.1"
2695 :type '(choice (const :tag "Head of sequence" nil)
2696 (string :tag "Specific state")))
2698 (defcustom org-log-repeat 'time
2699 "Non-nil means record moving through the DONE state when triggering repeat.
2700 An auto-repeating task is immediately switched back to TODO when
2701 marked DONE. If you are not logging state changes (by adding \"@\"
2702 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2703 record a closing note, there will be no record of the task moving
2704 through DONE. This variable forces taking a note anyway.
2706 nil Don't force a record
2707 time Record a time stamp
2708 note Prompt for a note and add it with template `org-log-note-headings'
2710 This option can also be set with on a per-file-basis with
2712 #+STARTUP: nologrepeat
2713 #+STARTUP: logrepeat
2714 #+STARTUP: lognoterepeat
2716 You can have local logging settings for a subtree by setting the LOGGING
2717 property to one or more of these keywords."
2718 :group 'org-todo
2719 :group 'org-progress
2720 :type '(choice
2721 (const :tag "Don't force a record" nil)
2722 (const :tag "Force recording the DONE state" time)
2723 (const :tag "Force recording a note with the DONE state" note)))
2726 (defgroup org-priorities nil
2727 "Priorities in Org-mode."
2728 :tag "Org Priorities"
2729 :group 'org-todo)
2731 (defcustom org-enable-priority-commands t
2732 "Non-nil means priority commands are active.
2733 When nil, these commands will be disabled, so that you never accidentally
2734 set a priority."
2735 :group 'org-priorities
2736 :type 'boolean)
2738 (defcustom org-highest-priority ?A
2739 "The highest priority of TODO items. A character like ?A, ?B etc.
2740 Must have a smaller ASCII number than `org-lowest-priority'."
2741 :group 'org-priorities
2742 :type 'character)
2744 (defcustom org-lowest-priority ?C
2745 "The lowest priority of TODO items. A character like ?A, ?B etc.
2746 Must have a larger ASCII number than `org-highest-priority'."
2747 :group 'org-priorities
2748 :type 'character)
2750 (defcustom org-default-priority ?B
2751 "The default priority of TODO items.
2752 This is the priority an item gets if no explicit priority is given.
2753 When starting to cycle on an empty priority the first step in the cycle
2754 depends on `org-priority-start-cycle-with-default'. The resulting first
2755 step priority must not exceed the range from `org-highest-priority' to
2756 `org-lowest-priority' which means that `org-default-priority' has to be
2757 in this range exclusive or inclusive the range boundaries. Else the
2758 first step refuses to set the default and the second will fall back
2759 to (depending on the command used) the highest or lowest priority."
2760 :group 'org-priorities
2761 :type 'character)
2763 (defcustom org-priority-start-cycle-with-default t
2764 "Non-nil means start with default priority when starting to cycle.
2765 When this is nil, the first step in the cycle will be (depending on the
2766 command used) one higher or lower than the default priority.
2767 See also `org-default-priority'."
2768 :group 'org-priorities
2769 :type 'boolean)
2771 (defcustom org-get-priority-function nil
2772 "Function to extract the priority from a string.
2773 The string is normally the headline. If this is nil Org computes the
2774 priority from the priority cookie like [#A] in the headline. It returns
2775 an integer, increasing by 1000 for each priority level.
2776 The user can set a different function here, which should take a string
2777 as an argument and return the numeric priority."
2778 :group 'org-priorities
2779 :version "24.1"
2780 :type 'function)
2782 (defgroup org-time nil
2783 "Options concerning time stamps and deadlines in Org-mode."
2784 :tag "Org Time"
2785 :group 'org)
2787 (defcustom org-insert-labeled-timestamps-at-point nil
2788 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2789 When nil, these labeled time stamps are forces into the second line of an
2790 entry, just after the headline. When scheduling from the global TODO list,
2791 the time stamp will always be forced into the second line."
2792 :group 'org-time
2793 :type 'boolean)
2795 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2796 "Formats for `format-time-string' which are used for time stamps.
2797 It is not recommended to change this constant.")
2799 (defcustom org-time-stamp-rounding-minutes '(0 5)
2800 "Number of minutes to round time stamps to.
2801 These are two values, the first applies when first creating a time stamp.
2802 The second applies when changing it with the commands `S-up' and `S-down'.
2803 When changing the time stamp, this means that it will change in steps
2804 of N minutes, as given by the second value.
2806 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2807 numbers should be factors of 60, so for example 5, 10, 15.
2809 When this is larger than 1, you can still force an exact time stamp by using
2810 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2811 and by using a prefix arg to `S-up/down' to specify the exact number
2812 of minutes to shift."
2813 :group 'org-time
2814 :get #'(lambda (var) ; Make sure both elements are there
2815 (if (integerp (default-value var))
2816 (list (default-value var) 5)
2817 (default-value var)))
2818 :type '(list
2819 (integer :tag "when inserting times")
2820 (integer :tag "when modifying times")))
2822 ;; Normalize old customizations of this variable.
2823 (when (integerp org-time-stamp-rounding-minutes)
2824 (setq org-time-stamp-rounding-minutes
2825 (list org-time-stamp-rounding-minutes
2826 org-time-stamp-rounding-minutes)))
2828 (defcustom org-display-custom-times nil
2829 "Non-nil means overlay custom formats over all time stamps.
2830 The formats are defined through the variable `org-time-stamp-custom-formats'.
2831 To turn this on on a per-file basis, insert anywhere in the file:
2832 #+STARTUP: customtime"
2833 :group 'org-time
2834 :set 'set-default
2835 :type 'sexp)
2836 (make-variable-buffer-local 'org-display-custom-times)
2838 (defcustom org-time-stamp-custom-formats
2839 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2840 "Custom formats for time stamps. See `format-time-string' for the syntax.
2841 These are overlaid over the default ISO format if the variable
2842 `org-display-custom-times' is set. Time like %H:%M should be at the
2843 end of the second format. The custom formats are also honored by export
2844 commands, if custom time display is turned on at the time of export."
2845 :group 'org-time
2846 :type 'sexp)
2848 (defun org-time-stamp-format (&optional long inactive)
2849 "Get the right format for a time string."
2850 (let ((f (if long (cdr org-time-stamp-formats)
2851 (car org-time-stamp-formats))))
2852 (if inactive
2853 (concat "[" (substring f 1 -1) "]")
2854 f)))
2856 (defcustom org-time-clocksum-format
2857 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2858 "The format string used when creating CLOCKSUM lines.
2859 This is also used when Org mode generates a time duration.
2861 The value can be a single format string containing two
2862 %-sequences, which will be filled with the number of hours and
2863 minutes in that order.
2865 Alternatively, the value can be a plist associating any of the
2866 keys :years, :months, :weeks, :days, :hours or :minutes with
2867 format strings. The time duration is formatted using only the
2868 time components that are needed and concatenating the results.
2869 If a time unit in absent, it falls back to the next smallest
2870 unit.
2872 The keys :require-years, :require-months, :require-days,
2873 :require-weeks, :require-hours, :require-minutes are also
2874 meaningful. A non-nil value for these keys indicates that the
2875 corresponding time component should always be included, even if
2876 its value is 0.
2879 For example,
2881 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2882 :require-minutes t)
2884 means durations longer than a day will be expressed in days,
2885 hours and minutes, and durations less than a day will always be
2886 expressed in hours and minutes (even for durations less than an
2887 hour).
2889 The value
2891 \(:days \"%dd\" :minutes \"%dm\")
2893 means durations longer than a day will be expressed in days and
2894 minutes, and durations less than a day will be expressed entirely
2895 in minutes (even for durations longer than an hour)."
2896 :group 'org-time
2897 :group 'org-clock
2898 :version "24.4"
2899 :package-version '(Org . "8.0")
2900 :type '(choice (string :tag "Format string")
2901 (set :tag "Plist"
2902 (group :inline t (const :tag "Years" :years)
2903 (string :tag "Format string"))
2904 (group :inline t
2905 (const :tag "Always show years" :require-years)
2906 (const t))
2907 (group :inline t (const :tag "Months" :months)
2908 (string :tag "Format string"))
2909 (group :inline t
2910 (const :tag "Always show months" :require-months)
2911 (const t))
2912 (group :inline t (const :tag "Weeks" :weeks)
2913 (string :tag "Format string"))
2914 (group :inline t
2915 (const :tag "Always show weeks" :require-weeks)
2916 (const t))
2917 (group :inline t (const :tag "Days" :days)
2918 (string :tag "Format string"))
2919 (group :inline t
2920 (const :tag "Always show days" :require-days)
2921 (const t))
2922 (group :inline t (const :tag "Hours" :hours)
2923 (string :tag "Format string"))
2924 (group :inline t
2925 (const :tag "Always show hours" :require-hours)
2926 (const t))
2927 (group :inline t (const :tag "Minutes" :minutes)
2928 (string :tag "Format string"))
2929 (group :inline t
2930 (const :tag "Always show minutes" :require-minutes)
2931 (const t)))))
2933 (defcustom org-time-clocksum-use-fractional nil
2934 "When non-nil, \\[org-clock-display] uses fractional times.
2935 See `org-time-clocksum-format' for more on time clock formats."
2936 :group 'org-time
2937 :group 'org-clock
2938 :version "24.3"
2939 :type 'boolean)
2941 (defcustom org-time-clocksum-use-effort-durations nil
2942 "When non-nil, \\[org-clock-display] uses effort durations.
2943 E.g. by default, one day is considered to be a 8 hours effort,
2944 so a task that has been clocked for 16 hours will be displayed
2945 as during 2 days in the clock display or in the clocktable.
2947 See `org-effort-durations' on how to set effort durations
2948 and `org-time-clocksum-format' for more on time clock formats."
2949 :group 'org-time
2950 :group 'org-clock
2951 :version "24.4"
2952 :package-version '(Org . "8.0")
2953 :type 'boolean)
2955 (defcustom org-time-clocksum-fractional-format "%.2f"
2956 "The format string used when creating CLOCKSUM lines,
2957 or when Org mode generates a time duration, if
2958 `org-time-clocksum-use-fractional' is enabled.
2960 The value can be a single format string containing one
2961 %-sequence, which will be filled with the number of hours as
2962 a float.
2964 Alternatively, the value can be a plist associating any of the
2965 keys :years, :months, :weeks, :days, :hours or :minutes with
2966 a format string. The time duration is formatted using the
2967 largest time unit which gives a non-zero integer part. If all
2968 specified formats have zero integer part, the smallest time unit
2969 is used."
2970 :group 'org-time
2971 :type '(choice (string :tag "Format string")
2972 (set (group :inline t (const :tag "Years" :years)
2973 (string :tag "Format string"))
2974 (group :inline t (const :tag "Months" :months)
2975 (string :tag "Format string"))
2976 (group :inline t (const :tag "Weeks" :weeks)
2977 (string :tag "Format string"))
2978 (group :inline t (const :tag "Days" :days)
2979 (string :tag "Format string"))
2980 (group :inline t (const :tag "Hours" :hours)
2981 (string :tag "Format string"))
2982 (group :inline t (const :tag "Minutes" :minutes)
2983 (string :tag "Format string")))))
2985 (defcustom org-deadline-warning-days 14
2986 "Number of days before expiration during which a deadline becomes active.
2987 This variable governs the display in sparse trees and in the agenda.
2988 When 0 or negative, it means use this number (the absolute value of it)
2989 even if a deadline has a different individual lead time specified.
2991 Custom commands can set this variable in the options section."
2992 :group 'org-time
2993 :group 'org-agenda-daily/weekly
2994 :type 'integer)
2996 (defcustom org-scheduled-delay-days 0
2997 "Number of days before a scheduled item becomes active.
2998 This variable governs the display in sparse trees and in the agenda.
2999 The default value (i.e. 0) means: don't delay scheduled item.
3000 When negative, it means use this number (the absolute value of it)
3001 even if a scheduled item has a different individual delay time
3002 specified.
3004 Custom commands can set this variable in the options section."
3005 :group 'org-time
3006 :group 'org-agenda-daily/weekly
3007 :version "24.4"
3008 :package-version '(Org . "8.0")
3009 :type 'integer)
3011 (defcustom org-read-date-prefer-future t
3012 "Non-nil means assume future for incomplete date input from user.
3013 This affects the following situations:
3014 1. The user gives a month but not a year.
3015 For example, if it is April and you enter \"feb 2\", this will be read
3016 as Feb 2, *next* year. \"May 5\", however, will be this year.
3017 2. The user gives a day, but no month.
3018 For example, if today is the 15th, and you enter \"3\", Org-mode will
3019 read this as the third of *next* month. However, if you enter \"17\",
3020 it will be considered as *this* month.
3022 If you set this variable to the symbol `time', then also the following
3023 will work:
3025 3. If the user gives a time.
3026 If the time is before now, it will be interpreted as tomorrow.
3028 Currently none of this works for ISO week specifications.
3030 When this option is nil, the current day, month and year will always be
3031 used as defaults.
3033 See also `org-agenda-jump-prefer-future'."
3034 :group 'org-time
3035 :type '(choice
3036 (const :tag "Never" nil)
3037 (const :tag "Check month and day" t)
3038 (const :tag "Check month, day, and time" time)))
3040 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3041 "Should the agenda jump command prefer the future for incomplete dates?
3042 The default is to do the same as configured in `org-read-date-prefer-future'.
3043 But you can also set a deviating value here.
3044 This may t or nil, or the symbol `org-read-date-prefer-future'."
3045 :group 'org-agenda
3046 :group 'org-time
3047 :version "24.1"
3048 :type '(choice
3049 (const :tag "Use org-read-date-prefer-future"
3050 org-read-date-prefer-future)
3051 (const :tag "Never" nil)
3052 (const :tag "Always" t)))
3054 (defcustom org-read-date-force-compatible-dates t
3055 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3057 Depending on the system Emacs is running on, certain dates cannot
3058 be represented with the type used internally to represent time.
3059 Dates between 1970-1-1 and 2038-1-1 can always be represented
3060 correctly. Some systems allow for earlier dates, some for later,
3061 some for both. One way to find out it to insert any date into an
3062 Org buffer, putting the cursor on the year and hitting S-up and
3063 S-down to test the range.
3065 When this variable is set to t, the date/time prompt will not let
3066 you specify dates outside the 1970-2037 range, so it is certain that
3067 these dates will work in whatever version of Emacs you are
3068 running, and also that you can move a file from one Emacs implementation
3069 to another. WHenever Org is forcing the year for you, it will display
3070 a message and beep.
3072 When this variable is nil, Org will check if the date is
3073 representable in the specific Emacs implementation you are using.
3074 If not, it will force a year, usually the current year, and beep
3075 to remind you. Currently this setting is not recommended because
3076 the likelihood that you will open your Org files in an Emacs that
3077 has limited date range is not negligible.
3079 A workaround for this problem is to use diary sexp dates for time
3080 stamps outside of this range."
3081 :group 'org-time
3082 :version "24.1"
3083 :type 'boolean)
3085 (defcustom org-read-date-display-live t
3086 "Non-nil means display current interpretation of date prompt live.
3087 This display will be in an overlay, in the minibuffer."
3088 :group 'org-time
3089 :type 'boolean)
3091 (defcustom org-read-date-popup-calendar t
3092 "Non-nil means pop up a calendar when prompting for a date.
3093 In the calendar, the date can be selected with mouse-1. However, the
3094 minibuffer will also be active, and you can simply enter the date as well.
3095 When nil, only the minibuffer will be available."
3096 :group 'org-time
3097 :type 'boolean)
3098 (org-defvaralias 'org-popup-calendar-for-date-prompt
3099 'org-read-date-popup-calendar)
3101 (make-obsolete-variable
3102 'org-read-date-minibuffer-setup-hook
3103 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3104 (defcustom org-read-date-minibuffer-setup-hook nil
3105 "Hook to be used to set up keys for the date/time interface.
3106 Add key definitions to `minibuffer-local-map', which will be a
3107 temporary copy.
3109 WARNING: This option is obsolete, you should use
3110 `org-read-date-minibuffer-local-map' to set up keys."
3111 :group 'org-time
3112 :type 'hook)
3114 (defcustom org-extend-today-until 0
3115 "The hour when your day really ends. Must be an integer.
3116 This has influence for the following applications:
3117 - When switching the agenda to \"today\". It it is still earlier than
3118 the time given here, the day recognized as TODAY is actually yesterday.
3119 - When a date is read from the user and it is still before the time given
3120 here, the current date and time will be assumed to be yesterday, 23:59.
3121 Also, timestamps inserted in capture templates follow this rule.
3123 IMPORTANT: This is a feature whose implementation is and likely will
3124 remain incomplete. Really, it is only here because past midnight seems to
3125 be the favorite working time of John Wiegley :-)"
3126 :group 'org-time
3127 :type 'integer)
3129 (defcustom org-use-effective-time nil
3130 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3131 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3132 \"effective time\" of any timestamps between midnight and 8am will be
3133 23:59 of the previous day."
3134 :group 'org-time
3135 :version "24.1"
3136 :type 'boolean)
3138 (defcustom org-use-last-clock-out-time-as-effective-time nil
3139 "When non-nil, use the last clock out time for `org-todo'.
3140 Note that this option has precedence over the combined use of
3141 `org-use-effective-time' and `org-extend-today-until'."
3142 :group 'org-time
3143 :version "24.4"
3144 :package-version '(Org . "8.0")
3145 :type 'boolean)
3147 (defcustom org-edit-timestamp-down-means-later nil
3148 "Non-nil means S-down will increase the time in a time stamp.
3149 When nil, S-up will increase."
3150 :group 'org-time
3151 :type 'boolean)
3153 (defcustom org-calendar-follow-timestamp-change t
3154 "Non-nil means make the calendar window follow timestamp changes.
3155 When a timestamp is modified and the calendar window is visible, it will be
3156 moved to the new date."
3157 :group 'org-time
3158 :type 'boolean)
3160 (defgroup org-tags nil
3161 "Options concerning tags in Org-mode."
3162 :tag "Org Tags"
3163 :group 'org)
3165 (defcustom org-tag-alist nil
3166 "List of tags allowed in Org-mode files.
3167 When this list is nil, Org-mode will base TAG input on what is already in the
3168 buffer.
3169 The value of this variable is an alist, the car of each entry must be a
3170 keyword as a string, the cdr may be a character that is used to select
3171 that tag through the fast-tag-selection interface.
3172 See the manual for details."
3173 :group 'org-tags
3174 :type '(repeat
3175 (choice
3176 (cons (string :tag "Tag name")
3177 (character :tag "Access char"))
3178 (list :tag "Start radio group"
3179 (const :startgroup)
3180 (option (string :tag "Group description")))
3181 (list :tag "Group tags delimiter"
3182 (const :grouptags))
3183 (list :tag "End radio group"
3184 (const :endgroup)
3185 (option (string :tag "Group description")))
3186 (const :tag "New line" (:newline)))))
3188 (defcustom org-tag-persistent-alist nil
3189 "List of tags that will always appear in all Org-mode files.
3190 This is in addition to any in buffer settings or customizations
3191 of `org-tag-alist'.
3192 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3193 The value of this variable is an alist, the car of each entry must be a
3194 keyword as a string, the cdr may be a character that is used to select
3195 that tag through the fast-tag-selection interface.
3196 See the manual for details.
3197 To disable these tags on a per-file basis, insert anywhere in the file:
3198 #+STARTUP: noptag"
3199 :group 'org-tags
3200 :type '(repeat
3201 (choice
3202 (cons (string :tag "Tag name")
3203 (character :tag "Access char"))
3204 (const :tag "Start radio group" (:startgroup))
3205 (const :tag "Group tags delimiter" (:grouptags))
3206 (const :tag "End radio group" (:endgroup))
3207 (const :tag "New line" (:newline)))))
3209 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3210 "If non-nil, always offer completion for all tags of all agenda files.
3211 Instead of customizing this variable directly, you might want to
3212 set it locally for capture buffers, because there no list of
3213 tags in that file can be created dynamically (there are none).
3215 (add-hook 'org-capture-mode-hook
3216 (lambda ()
3217 (set (make-local-variable
3218 'org-complete-tags-always-offer-all-agenda-tags)
3219 t)))"
3220 :group 'org-tags
3221 :version "24.1"
3222 :type 'boolean)
3224 (defvar org-file-tags nil
3225 "List of tags that can be inherited by all entries in the file.
3226 The tags will be inherited if the variable `org-use-tag-inheritance'
3227 says they should be.
3228 This variable is populated from #+FILETAGS lines.")
3230 (defcustom org-use-fast-tag-selection 'auto
3231 "Non-nil means use fast tag selection scheme.
3232 This is a special interface to select and deselect tags with single keys.
3233 When nil, fast selection is never used.
3234 When the symbol `auto', fast selection is used if and only if selection
3235 characters for tags have been configured, either through the variable
3236 `org-tag-alist' or through a #+TAGS line in the buffer.
3237 When t, fast selection is always used and selection keys are assigned
3238 automatically if necessary."
3239 :group 'org-tags
3240 :type '(choice
3241 (const :tag "Always" t)
3242 (const :tag "Never" nil)
3243 (const :tag "When selection characters are configured" 'auto)))
3245 (defcustom org-fast-tag-selection-single-key nil
3246 "Non-nil means fast tag selection exits after first change.
3247 When nil, you have to press RET to exit it.
3248 During fast tag selection, you can toggle this flag with `C-c'.
3249 This variable can also have the value `expert'. In this case, the window
3250 displaying the tags menu is not even shown, until you press C-c again."
3251 :group 'org-tags
3252 :type '(choice
3253 (const :tag "No" nil)
3254 (const :tag "Yes" t)
3255 (const :tag "Expert" expert)))
3257 (defvar org-fast-tag-selection-include-todo nil
3258 "Non-nil means fast tags selection interface will also offer TODO states.
3259 This is an undocumented feature, you should not rely on it.")
3261 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3262 "The column to which tags should be indented in a headline.
3263 If this number is positive, it specifies the column. If it is negative,
3264 it means that the tags should be flushright to that column. For example,
3265 -80 works well for a normal 80 character screen.
3266 When 0, place tags directly after headline text, with only one space in
3267 between."
3268 :group 'org-tags
3269 :type 'integer)
3271 (defcustom org-auto-align-tags t
3272 "Non-nil keeps tags aligned when modifying headlines.
3273 Some operations (i.e. demoting) change the length of a headline and
3274 therefore shift the tags around. With this option turned on, after
3275 each such operation the tags are again aligned to `org-tags-column'."
3276 :group 'org-tags
3277 :type 'boolean)
3279 (defcustom org-use-tag-inheritance t
3280 "Non-nil means tags in levels apply also for sublevels.
3281 When nil, only the tags directly given in a specific line apply there.
3282 This may also be a list of tags that should be inherited, or a regexp that
3283 matches tags that should be inherited. Additional control is possible
3284 with the variable `org-tags-exclude-from-inheritance' which gives an
3285 explicit list of tags to be excluded from inheritance, even if the value of
3286 `org-use-tag-inheritance' would select it for inheritance.
3288 If this option is t, a match early-on in a tree can lead to a large
3289 number of matches in the subtree when constructing the agenda or creating
3290 a sparse tree. If you only want to see the first match in a tree during
3291 a search, check out the variable `org-tags-match-list-sublevels'."
3292 :group 'org-tags
3293 :type '(choice
3294 (const :tag "Not" nil)
3295 (const :tag "Always" t)
3296 (repeat :tag "Specific tags" (string :tag "Tag"))
3297 (regexp :tag "Tags matched by regexp")))
3299 (defcustom org-tags-exclude-from-inheritance nil
3300 "List of tags that should never be inherited.
3301 This is a way to exclude a few tags from inheritance. For way to do
3302 the opposite, to actively allow inheritance for selected tags,
3303 see the variable `org-use-tag-inheritance'."
3304 :group 'org-tags
3305 :type '(repeat (string :tag "Tag")))
3307 (defun org-tag-inherit-p (tag)
3308 "Check if TAG is one that should be inherited."
3309 (cond
3310 ((member tag org-tags-exclude-from-inheritance) nil)
3311 ((eq org-use-tag-inheritance t) t)
3312 ((not org-use-tag-inheritance) nil)
3313 ((stringp org-use-tag-inheritance)
3314 (string-match org-use-tag-inheritance tag))
3315 ((listp org-use-tag-inheritance)
3316 (member tag org-use-tag-inheritance))
3317 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3319 (defcustom org-tags-match-list-sublevels t
3320 "Non-nil means list also sublevels of headlines matching a search.
3321 This variable applies to tags/property searches, and also to stuck
3322 projects because this search is based on a tags match as well.
3324 When set to the symbol `indented', sublevels are indented with
3325 leading dots.
3327 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3328 the sublevels of a headline matching a tag search often also match
3329 the same search. Listing all of them can create very long lists.
3330 Setting this variable to nil causes subtrees of a match to be skipped.
3332 This variable is semi-obsolete and probably should always be true. It
3333 is better to limit inheritance to certain tags using the variables
3334 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3335 :group 'org-tags
3336 :type '(choice
3337 (const :tag "No, don't list them" nil)
3338 (const :tag "Yes, do list them" t)
3339 (const :tag "List them, indented with leading dots" indented)))
3341 (defcustom org-tags-sort-function nil
3342 "When set, tags are sorted using this function as a comparator."
3343 :group 'org-tags
3344 :type '(choice
3345 (const :tag "No sorting" nil)
3346 (const :tag "Alphabetical" string<)
3347 (const :tag "Reverse alphabetical" string>)
3348 (function :tag "Custom function" nil)))
3350 (defvar org-tags-history nil
3351 "History of minibuffer reads for tags.")
3352 (defvar org-last-tags-completion-table nil
3353 "The last used completion table for tags.")
3354 (defvar org-after-tags-change-hook nil
3355 "Hook that is run after the tags in a line have changed.")
3357 (defgroup org-properties nil
3358 "Options concerning properties in Org-mode."
3359 :tag "Org Properties"
3360 :group 'org)
3362 (defcustom org-property-format "%-10s %s"
3363 "How property key/value pairs should be formatted by `indent-line'.
3364 When `indent-line' hits a property definition, it will format the line
3365 according to this format, mainly to make sure that the values are
3366 lined-up with respect to each other."
3367 :group 'org-properties
3368 :type 'string)
3370 (defcustom org-properties-postprocess-alist nil
3371 "Alist of properties and functions to adjust inserted values.
3372 Elements of this alist must be of the form
3374 ([string] [function])
3376 where [string] must be a property name and [function] must be a
3377 lambda expression: this lambda expression must take one argument,
3378 the value to adjust, and return the new value as a string.
3380 For example, this element will allow the property \"Remaining\"
3381 to be updated wrt the relation between the \"Effort\" property
3382 and the clock summary:
3384 ((\"Remaining\" (lambda(value)
3385 (let ((clocksum (org-clock-sum-current-item))
3386 (effort (org-duration-string-to-minutes
3387 (org-entry-get (point) \"Effort\"))))
3388 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3389 :group 'org-properties
3390 :version "24.1"
3391 :type '(alist :key-type (string :tag "Property")
3392 :value-type (function :tag "Function")))
3394 (defcustom org-use-property-inheritance nil
3395 "Non-nil means properties apply also for sublevels.
3397 This setting is chiefly used during property searches. Turning it on can
3398 cause significant overhead when doing a search, which is why it is not
3399 on by default.
3401 When nil, only the properties directly given in the current entry count.
3402 When t, every property is inherited. The value may also be a list of
3403 properties that should have inheritance, or a regular expression matching
3404 properties that should be inherited.
3406 However, note that some special properties use inheritance under special
3407 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3408 and the properties ending in \"_ALL\" when they are used as descriptor
3409 for valid values of a property.
3411 Note for programmers:
3412 When querying an entry with `org-entry-get', you can control if inheritance
3413 should be used. By default, `org-entry-get' looks only at the local
3414 properties. You can request inheritance by setting the inherit argument
3415 to t (to force inheritance) or to `selective' (to respect the setting
3416 in this variable)."
3417 :group 'org-properties
3418 :type '(choice
3419 (const :tag "Not" nil)
3420 (const :tag "Always" t)
3421 (repeat :tag "Specific properties" (string :tag "Property"))
3422 (regexp :tag "Properties matched by regexp")))
3424 (defun org-property-inherit-p (property)
3425 "Check if PROPERTY is one that should be inherited."
3426 (cond
3427 ((eq org-use-property-inheritance t) t)
3428 ((not org-use-property-inheritance) nil)
3429 ((stringp org-use-property-inheritance)
3430 (string-match org-use-property-inheritance property))
3431 ((listp org-use-property-inheritance)
3432 (member property org-use-property-inheritance))
3433 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3435 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3436 "The default column format, if no other format has been defined.
3437 This variable can be set on the per-file basis by inserting a line
3439 #+COLUMNS: %25ITEM ....."
3440 :group 'org-properties
3441 :type 'string)
3443 (defcustom org-columns-ellipses ".."
3444 "The ellipses to be used when a field in column view is truncated.
3445 When this is the empty string, as many characters as possible are shown,
3446 but then there will be no visual indication that the field has been truncated.
3447 When this is a string of length N, the last N characters of a truncated
3448 field are replaced by this string. If the column is narrower than the
3449 ellipses string, only part of the ellipses string will be shown."
3450 :group 'org-properties
3451 :type 'string)
3453 (defcustom org-columns-modify-value-for-display-function nil
3454 "Function that modifies values for display in column view.
3455 For example, it can be used to cut out a certain part from a time stamp.
3456 The function must take 2 arguments:
3458 column-title The title of the column (*not* the property name)
3459 value The value that should be modified.
3461 The function should return the value that should be displayed,
3462 or nil if the normal value should be used."
3463 :group 'org-properties
3464 :type 'function)
3466 (defcustom org-effort-property "Effort"
3467 "The property that is being used to keep track of effort estimates.
3468 Effort estimates given in this property need to have the format H:MM."
3469 :group 'org-properties
3470 :group 'org-progress
3471 :type '(string :tag "Property"))
3473 (defconst org-global-properties-fixed
3474 '(("VISIBILITY_ALL" . "folded children content all")
3475 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3476 "List of property/value pairs that can be inherited by any entry.
3478 These are fixed values, for the preset properties. The user variable
3479 that can be used to add to this list is `org-global-properties'.
3481 The entries in this list are cons cells where the car is a property
3482 name and cdr is a string with the value. If the value represents
3483 multiple items like an \"_ALL\" property, separate the items by
3484 spaces.")
3486 (defcustom org-global-properties nil
3487 "List of property/value pairs that can be inherited by any entry.
3489 This list will be combined with the constant `org-global-properties-fixed'.
3491 The entries in this list are cons cells where the car is a property
3492 name and cdr is a string with the value.
3494 You can set buffer-local values for the same purpose in the variable
3495 `org-file-properties' this by adding lines like
3497 #+PROPERTY: NAME VALUE"
3498 :group 'org-properties
3499 :type '(repeat
3500 (cons (string :tag "Property")
3501 (string :tag "Value"))))
3503 (defvar org-file-properties nil
3504 "List of property/value pairs that can be inherited by any entry.
3505 Valid for the current buffer.
3506 This variable is populated from #+PROPERTY lines.")
3507 (make-variable-buffer-local 'org-file-properties)
3509 (defgroup org-agenda nil
3510 "Options concerning agenda views in Org-mode."
3511 :tag "Org Agenda"
3512 :group 'org)
3514 (defvar org-category nil
3515 "Variable used by org files to set a category for agenda display.
3516 Such files should use a file variable to set it, for example
3518 # -*- mode: org; org-category: \"ELisp\"
3520 or contain a special line
3522 #+CATEGORY: ELisp
3524 If the file does not specify a category, then file's base name
3525 is used instead.")
3526 (make-variable-buffer-local 'org-category)
3527 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3529 (defcustom org-agenda-files nil
3530 "The files to be used for agenda display.
3531 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3532 \\[org-remove-file]. You can also use customize to edit the list.
3534 If an entry is a directory, all files in that directory that are matched by
3535 `org-agenda-file-regexp' will be part of the file list.
3537 If the value of the variable is not a list but a single file name, then
3538 the list of agenda files is actually stored and maintained in that file, one
3539 agenda file per line. In this file paths can be given relative to
3540 `org-directory'. Tilde expansion and environment variable substitution
3541 are also made."
3542 :group 'org-agenda
3543 :type '(choice
3544 (repeat :tag "List of files and directories" file)
3545 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3547 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3548 "Regular expression to match files for `org-agenda-files'.
3549 If any element in the list in that variable contains a directory instead
3550 of a normal file, all files in that directory that are matched by this
3551 regular expression will be included."
3552 :group 'org-agenda
3553 :type 'regexp)
3555 (defcustom org-agenda-text-search-extra-files nil
3556 "List of extra files to be searched by text search commands.
3557 These files will be search in addition to the agenda files by the
3558 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3559 Note that these files will only be searched for text search commands,
3560 not for the other agenda views like todo lists, tag searches or the weekly
3561 agenda. This variable is intended to list notes and possibly archive files
3562 that should also be searched by these two commands.
3563 In fact, if the first element in the list is the symbol `agenda-archives',
3564 than all archive files of all agenda files will be added to the search
3565 scope."
3566 :group 'org-agenda
3567 :type '(set :greedy t
3568 (const :tag "Agenda Archives" agenda-archives)
3569 (repeat :inline t (file))))
3571 (org-defvaralias 'org-agenda-multi-occur-extra-files
3572 'org-agenda-text-search-extra-files)
3574 (defcustom org-agenda-skip-unavailable-files nil
3575 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3576 A nil value means to remove them, after a query, from the list."
3577 :group 'org-agenda
3578 :type 'boolean)
3580 (defcustom org-calendar-to-agenda-key [?c]
3581 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3582 The command `org-calendar-goto-agenda' will be bound to this key. The
3583 default is the character `c' because then `c' can be used to switch back and
3584 forth between agenda and calendar."
3585 :group 'org-agenda
3586 :type 'sexp)
3588 (defcustom org-calendar-insert-diary-entry-key [?i]
3589 "The key to be installed in `calendar-mode-map' for adding diary entries.
3590 This option is irrelevant until `org-agenda-diary-file' has been configured
3591 to point to an Org-mode file. When that is the case, the command
3592 `org-agenda-diary-entry' will be bound to the key given here, by default
3593 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3594 if you want to continue doing this, you need to change this to a different
3595 key."
3596 :group 'org-agenda
3597 :type 'sexp)
3599 (defcustom org-agenda-diary-file 'diary-file
3600 "File to which to add new entries with the `i' key in agenda and calendar.
3601 When this is the symbol `diary-file', the functionality in the Emacs
3602 calendar will be used to add entries to the `diary-file'. But when this
3603 points to a file, `org-agenda-diary-entry' will be used instead."
3604 :group 'org-agenda
3605 :type '(choice
3606 (const :tag "The standard Emacs diary file" diary-file)
3607 (file :tag "Special Org file diary entries")))
3609 (eval-after-load "calendar"
3610 '(progn
3611 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3612 'org-calendar-goto-agenda)
3613 (add-hook 'calendar-mode-hook
3614 (lambda ()
3615 (unless (eq org-agenda-diary-file 'diary-file)
3616 (define-key calendar-mode-map
3617 org-calendar-insert-diary-entry-key
3618 'org-agenda-diary-entry))))))
3620 (defgroup org-latex nil
3621 "Options for embedding LaTeX code into Org-mode."
3622 :tag "Org LaTeX"
3623 :group 'org)
3625 (defcustom org-format-latex-options
3626 '(:foreground default :background default :scale 1.0
3627 :html-foreground "Black" :html-background "Transparent"
3628 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3629 "Options for creating images from LaTeX fragments.
3630 This is a property list with the following properties:
3631 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3632 `default' means use the foreground of the default face.
3633 `auto' means use the foreground from the text face.
3634 :background the background color, or \"Transparent\".
3635 `default' means use the background of the default face.
3636 `auto' means use the background from the text face.
3637 :scale a scaling factor for the size of the images, to get more pixels
3638 :html-foreground, :html-background, :html-scale
3639 the same numbers for HTML export.
3640 :matchers a list indicating which matchers should be used to
3641 find LaTeX fragments. Valid members of this list are:
3642 \"begin\" find environments
3643 \"$1\" find single characters surrounded by $.$
3644 \"$\" find math expressions surrounded by $...$
3645 \"$$\" find math expressions surrounded by $$....$$
3646 \"\\(\" find math expressions surrounded by \\(...\\)
3647 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3648 :group 'org-latex
3649 :type 'plist)
3651 (defcustom org-format-latex-signal-error t
3652 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3653 When nil, just push out a message."
3654 :group 'org-latex
3655 :version "24.1"
3656 :type 'boolean)
3658 (defcustom org-latex-to-mathml-jar-file nil
3659 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3660 Use this to specify additional executable file say a jar file.
3662 When using MathToWeb as the converter, specify the full-path to
3663 your mathtoweb.jar file."
3664 :group 'org-latex
3665 :version "24.1"
3666 :type '(choice
3667 (const :tag "None" nil)
3668 (file :tag "JAR file" :must-match t)))
3670 (defcustom org-latex-to-mathml-convert-command nil
3671 "Command to convert LaTeX fragments to MathML.
3672 Replace format-specifiers in the command as noted below and use
3673 `shell-command' to convert LaTeX to MathML.
3674 %j: Executable file in fully expanded form as specified by
3675 `org-latex-to-mathml-jar-file'.
3676 %I: Input LaTeX file in fully expanded form
3677 %o: Output MathML file
3678 This command is used by `org-create-math-formula'.
3680 When using MathToWeb as the converter, set this to
3681 \"java -jar %j -unicode -force -df %o %I\"."
3682 :group 'org-latex
3683 :version "24.1"
3684 :type '(choice
3685 (const :tag "None" nil)
3686 (string :tag "\nShell command")))
3688 (defcustom org-latex-create-formula-image-program 'dvipng
3689 "Program to convert LaTeX fragments with.
3691 dvipng Process the LaTeX fragments to dvi file, then convert
3692 dvi files to png files using dvipng.
3693 This will also include processing of non-math environments.
3694 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3695 to convert pdf files to png files"
3696 :group 'org-latex
3697 :version "24.1"
3698 :type '(choice
3699 (const :tag "dvipng" dvipng)
3700 (const :tag "imagemagick" imagemagick)))
3702 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3703 "Path to store latex preview images.
3704 A relative path here creates many directories relative to the
3705 processed org files paths. An absolute path puts all preview
3706 images at the same place."
3707 :group 'org-latex
3708 :version "24.3"
3709 :type 'string)
3711 (defun org-format-latex-mathml-available-p ()
3712 "Return t if `org-latex-to-mathml-convert-command' is usable."
3713 (save-match-data
3714 (when (and (boundp 'org-latex-to-mathml-convert-command)
3715 org-latex-to-mathml-convert-command)
3716 (let ((executable (car (split-string
3717 org-latex-to-mathml-convert-command))))
3718 (when (executable-find executable)
3719 (if (string-match
3720 "%j" org-latex-to-mathml-convert-command)
3721 (file-readable-p org-latex-to-mathml-jar-file)
3722 t))))))
3724 (defcustom org-format-latex-header "\\documentclass{article}
3725 \\usepackage[usenames]{color}
3726 \\usepackage{amsmath}
3727 \\usepackage[mathscr]{eucal}
3728 \\pagestyle{empty} % do not remove
3729 \[PACKAGES]
3730 \[DEFAULT-PACKAGES]
3731 % The settings below are copied from fullpage.sty
3732 \\setlength{\\textwidth}{\\paperwidth}
3733 \\addtolength{\\textwidth}{-3cm}
3734 \\setlength{\\oddsidemargin}{1.5cm}
3735 \\addtolength{\\oddsidemargin}{-2.54cm}
3736 \\setlength{\\evensidemargin}{\\oddsidemargin}
3737 \\setlength{\\textheight}{\\paperheight}
3738 \\addtolength{\\textheight}{-\\headheight}
3739 \\addtolength{\\textheight}{-\\headsep}
3740 \\addtolength{\\textheight}{-\\footskip}
3741 \\addtolength{\\textheight}{-3cm}
3742 \\setlength{\\topmargin}{1.5cm}
3743 \\addtolength{\\topmargin}{-2.54cm}"
3744 "The document header used for processing LaTeX fragments.
3745 It is imperative that this header make sure that no page number
3746 appears on the page. The package defined in the variables
3747 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3748 will either replace the placeholder \"[PACKAGES]\" in this
3749 header, or they will be appended."
3750 :group 'org-latex
3751 :type 'string)
3753 (defun org-set-packages-alist (var val)
3754 "Set the packages alist and make sure it has 3 elements per entry."
3755 (set var (mapcar (lambda (x)
3756 (if (and (consp x) (= (length x) 2))
3757 (list (car x) (nth 1 x) t)
3759 val)))
3761 (defun org-get-packages-alist (var)
3762 "Get the packages alist and make sure it has 3 elements per entry."
3763 (mapcar (lambda (x)
3764 (if (and (consp x) (= (length x) 2))
3765 (list (car x) (nth 1 x) t)
3767 (default-value var)))
3769 (defcustom org-latex-default-packages-alist
3770 '(("AUTO" "inputenc" t)
3771 ("T1" "fontenc" t)
3772 ("" "fixltx2e" nil)
3773 ("" "graphicx" t)
3774 ("" "longtable" nil)
3775 ("" "float" nil)
3776 ("" "wrapfig" nil)
3777 ("" "soul" t)
3778 ("" "textcomp" t)
3779 ("" "marvosym" t)
3780 ("" "wasysym" t)
3781 ("" "latexsym" t)
3782 ("" "amssymb" t)
3783 ("" "hyperref" nil)
3784 "\\tolerance=1000")
3785 "Alist of default packages to be inserted in the header.
3787 Change this only if one of the packages here causes an
3788 incompatibility with another package you are using.
3790 The packages in this list are needed by one part or another of
3791 Org mode to function properly:
3793 - inputenc, fontenc: for basic font and character selection
3794 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3795 symbols used for interpreting the entities in `org-entities'.
3796 You can skip some of these packages if you don't use any of the
3797 symbols in it.
3798 - graphicx: for including images
3799 - float, wrapfig: for figure placement
3800 - longtable: for long tables
3801 - hyperref: for cross references
3803 Therefore you should not modify this variable unless you know
3804 what you are doing. The one reason to change it anyway is that
3805 you might be loading some other package that conflicts with one
3806 of the default packages. Each cell is of the format
3807 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3808 the package also needs to be included when compiling LaTeX
3809 snippets into images for inclusion into non-LaTeX output."
3810 :group 'org-latex
3811 :group 'org-export-latex
3812 :set 'org-set-packages-alist
3813 :get 'org-get-packages-alist
3814 :version "24.1"
3815 :type '(repeat
3816 (choice
3817 (list :tag "options/package pair"
3818 (string :tag "options")
3819 (string :tag "package")
3820 (boolean :tag "Snippet"))
3821 (string :tag "A line of LaTeX"))))
3823 (defcustom org-latex-packages-alist nil
3824 "Alist of packages to be inserted in every LaTeX header.
3826 These will be inserted after `org-latex-default-packages-alist'.
3827 Each cell is of the format:
3829 \(\"options\" \"package\" snippet-flag)
3831 SNIPPET-FLAG, when t, indicates that this package is also needed
3832 when turning LaTeX snippets into images for inclusion into
3833 non-LaTeX output.
3835 Make sure that you only list packages here which:
3837 - you want in every file
3838 - do not conflict with the setup in `org-format-latex-header'.
3839 - do not conflict with the default packages in
3840 `org-latex-default-packages-alist'."
3841 :group 'org-latex
3842 :group 'org-export-latex
3843 :set 'org-set-packages-alist
3844 :get 'org-get-packages-alist
3845 :type '(repeat
3846 (choice
3847 (list :tag "options/package pair"
3848 (string :tag "options")
3849 (string :tag "package")
3850 (boolean :tag "Snippet"))
3851 (string :tag "A line of LaTeX"))))
3853 (defgroup org-appearance nil
3854 "Settings for Org-mode appearance."
3855 :tag "Org Appearance"
3856 :group 'org)
3858 (defcustom org-level-color-stars-only nil
3859 "Non-nil means fontify only the stars in each headline.
3860 When nil, the entire headline is fontified.
3861 Changing it requires restart of `font-lock-mode' to become effective
3862 also in regions already fontified."
3863 :group 'org-appearance
3864 :type 'boolean)
3866 (defcustom org-hide-leading-stars nil
3867 "Non-nil means hide the first N-1 stars in a headline.
3868 This works by using the face `org-hide' for these stars. This
3869 face is white for a light background, and black for a dark
3870 background. You may have to customize the face `org-hide' to
3871 make this work.
3872 Changing it requires restart of `font-lock-mode' to become effective
3873 also in regions already fontified.
3874 You may also set this on a per-file basis by adding one of the following
3875 lines to the buffer:
3877 #+STARTUP: hidestars
3878 #+STARTUP: showstars"
3879 :group 'org-appearance
3880 :type 'boolean)
3882 (defcustom org-hidden-keywords nil
3883 "List of symbols corresponding to keywords to be hidden the org buffer.
3884 For example, a value '(title) for this list will make the document's title
3885 appear in the buffer without the initial #+TITLE: keyword."
3886 :group 'org-appearance
3887 :version "24.1"
3888 :type '(set (const :tag "#+AUTHOR" author)
3889 (const :tag "#+DATE" date)
3890 (const :tag "#+EMAIL" email)
3891 (const :tag "#+TITLE" title)))
3893 (defcustom org-custom-properties nil
3894 "List of properties (as strings) with a special meaning.
3895 The default use of these custom properties is to let the user
3896 hide them with `org-toggle-custom-properties-visibility'."
3897 :group 'org-properties
3898 :group 'org-appearance
3899 :version "24.3"
3900 :type '(repeat (string :tag "Property Name")))
3902 (defcustom org-fontify-done-headline nil
3903 "Non-nil means change the face of a headline if it is marked DONE.
3904 Normally, only the TODO/DONE keyword indicates the state of a headline.
3905 When this is non-nil, the headline after the keyword is set to the
3906 `org-headline-done' as an additional indication."
3907 :group 'org-appearance
3908 :type 'boolean)
3910 (defcustom org-fontify-emphasized-text t
3911 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3912 Changing this variable requires a restart of Emacs to take effect."
3913 :group 'org-appearance
3914 :type 'boolean)
3916 (defcustom org-fontify-whole-heading-line nil
3917 "Non-nil means fontify the whole line for headings.
3918 This is useful when setting a background color for the
3919 org-level-* faces."
3920 :group 'org-appearance
3921 :type 'boolean)
3923 (defcustom org-highlight-latex-and-related nil
3924 "Non-nil means highlight LaTeX related syntax in the buffer.
3925 When non nil, the value should be a list containing any of the
3926 following symbols:
3927 `latex' Highlight LaTeX snippets and environments.
3928 `script' Highlight subscript and superscript.
3929 `entities' Highlight entities."
3930 :group 'org-appearance
3931 :version "24.4"
3932 :package-version '(Org . "8.0")
3933 :type '(choice
3934 (const :tag "No highlighting" nil)
3935 (set :greedy t :tag "Highlight"
3936 (const :tag "LaTeX snippets and environments" latex)
3937 (const :tag "Subscript and superscript" script)
3938 (const :tag "Entities" entities))))
3940 (defcustom org-hide-emphasis-markers nil
3941 "Non-nil mean font-lock should hide the emphasis marker characters."
3942 :group 'org-appearance
3943 :type 'boolean)
3945 (defcustom org-pretty-entities nil
3946 "Non-nil means show entities as UTF8 characters.
3947 When nil, the \\name form remains in the buffer."
3948 :group 'org-appearance
3949 :version "24.1"
3950 :type 'boolean)
3952 (defcustom org-pretty-entities-include-sub-superscripts t
3953 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3954 :group 'org-appearance
3955 :version "24.1"
3956 :type 'boolean)
3958 (defvar org-emph-re nil
3959 "Regular expression for matching emphasis.
3960 After a match, the match groups contain these elements:
3961 0 The match of the full regular expression, including the characters
3962 before and after the proper match
3963 1 The character before the proper match, or empty at beginning of line
3964 2 The proper match, including the leading and trailing markers
3965 3 The leading marker like * or /, indicating the type of highlighting
3966 4 The text between the emphasis markers, not including the markers
3967 5 The character after the match, empty at the end of a line")
3968 (defvar org-verbatim-re nil
3969 "Regular expression for matching verbatim text.")
3970 (defvar org-emphasis-regexp-components) ; defined just below
3971 (defvar org-emphasis-alist) ; defined just below
3972 (defun org-set-emph-re (var val)
3973 "Set variable and compute the emphasis regular expression."
3974 (set var val)
3975 (when (and (boundp 'org-emphasis-alist)
3976 (boundp 'org-emphasis-regexp-components)
3977 org-emphasis-alist org-emphasis-regexp-components)
3978 (let* ((e org-emphasis-regexp-components)
3979 (pre (car e))
3980 (post (nth 1 e))
3981 (border (nth 2 e))
3982 (body (nth 3 e))
3983 (nl (nth 4 e))
3984 (body1 (concat body "*?"))
3985 (markers (mapconcat 'car org-emphasis-alist ""))
3986 (vmarkers (mapconcat
3987 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3988 org-emphasis-alist "")))
3989 ;; make sure special characters appear at the right position in the class
3990 (if (string-match "\\^" markers)
3991 (setq markers (concat (replace-match "" t t markers) "^")))
3992 (if (string-match "-" markers)
3993 (setq markers (concat (replace-match "" t t markers) "-")))
3994 (if (string-match "\\^" vmarkers)
3995 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3996 (if (string-match "-" vmarkers)
3997 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3998 (if (> nl 0)
3999 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4000 (int-to-string nl) "\\}")))
4001 ;; Make the regexp
4002 (setq org-emph-re
4003 (concat "\\([" pre "]\\|^\\)"
4004 "\\("
4005 "\\([" markers "]\\)"
4006 "\\("
4007 "[^" border "]\\|"
4008 "[^" border "]"
4009 body1
4010 "[^" border "]"
4011 "\\)"
4012 "\\3\\)"
4013 "\\([" post "]\\|$\\)"))
4014 (setq org-verbatim-re
4015 (concat "\\([" pre "]\\|^\\)"
4016 "\\("
4017 "\\([" vmarkers "]\\)"
4018 "\\("
4019 "[^" border "]\\|"
4020 "[^" border "]"
4021 body1
4022 "[^" border "]"
4023 "\\)"
4024 "\\3\\)"
4025 "\\([" post "]\\|$\\)")))))
4027 (defcustom org-emphasis-regexp-components
4028 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4029 "Components used to build the regular expression for emphasis.
4030 This is a list with five entries. Terminology: In an emphasis string
4031 like \" *strong word* \", we call the initial space PREMATCH, the final
4032 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4033 and \"trong wor\" is the body. The different components in this variable
4034 specify what is allowed/forbidden in each part:
4036 pre Chars allowed as prematch. Beginning of line will be allowed too.
4037 post Chars allowed as postmatch. End of line will be allowed too.
4038 border The chars *forbidden* as border characters.
4039 body-regexp A regexp like \".\" to match a body character. Don't use
4040 non-shy groups here, and don't allow newline here.
4041 newline The maximum number of newlines allowed in an emphasis exp.
4043 Use customize to modify this, or restart Emacs after changing it."
4044 :group 'org-appearance
4045 :set 'org-set-emph-re
4046 :type '(list
4047 (sexp :tag "Allowed chars in pre ")
4048 (sexp :tag "Allowed chars in post ")
4049 (sexp :tag "Forbidden chars in border ")
4050 (sexp :tag "Regexp for body ")
4051 (integer :tag "number of newlines allowed")
4052 (option (boolean :tag "Please ignore this button"))))
4054 (defcustom org-emphasis-alist
4055 `(("*" bold "<b>" "</b>")
4056 ("/" italic "<i>" "</i>")
4057 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4058 ("=" org-code "<code>" "</code>" verbatim)
4059 ("~" org-verbatim "<code>" "</code>" verbatim)
4060 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4061 "<del>" "</del>")
4063 "Special syntax for emphasized text.
4064 Text starting and ending with a special character will be emphasized, for
4065 example *bold*, _underlined_ and /italic/. This variable sets the marker
4066 characters, the face to be used by font-lock for highlighting in Org-mode
4067 Emacs buffers, and the HTML tags to be used for this.
4068 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4069 Use customize to modify this, or restart Emacs after changing it."
4070 :group 'org-appearance
4071 :set 'org-set-emph-re
4072 :type '(repeat
4073 (list
4074 (string :tag "Marker character")
4075 (choice
4076 (face :tag "Font-lock-face")
4077 (plist :tag "Face property list"))
4078 (string :tag "HTML start tag")
4079 (string :tag "HTML end tag")
4080 (option (const verbatim)))))
4082 (defvar org-protecting-blocks
4083 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4084 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4085 This is needed for font-lock setup.")
4087 ;;; Miscellaneous options
4089 (defgroup org-completion nil
4090 "Completion in Org-mode."
4091 :tag "Org Completion"
4092 :group 'org)
4094 (defcustom org-completion-use-ido nil
4095 "Non-nil means use ido completion wherever possible.
4096 Note that `ido-mode' must be active for this variable to be relevant.
4097 If you decide to turn this variable on, you might well want to turn off
4098 `org-outline-path-complete-in-steps'.
4099 See also `org-completion-use-iswitchb'."
4100 :group 'org-completion
4101 :type 'boolean)
4103 (defcustom org-completion-use-iswitchb nil
4104 "Non-nil means use iswitchb completion wherever possible.
4105 Note that `iswitchb-mode' must be active for this variable to be relevant.
4106 If you decide to turn this variable on, you might well want to turn off
4107 `org-outline-path-complete-in-steps'.
4108 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4109 :group 'org-completion
4110 :type 'boolean)
4112 (defcustom org-completion-fallback-command 'hippie-expand
4113 "The expansion command called by \\[pcomplete] in normal context.
4114 Normal means, no org-mode-specific context."
4115 :group 'org-completion
4116 :type 'function)
4118 ;;; Functions and variables from their packages
4119 ;; Declared here to avoid compiler warnings
4121 ;; XEmacs only
4122 (defvar outline-mode-menu-heading)
4123 (defvar outline-mode-menu-show)
4124 (defvar outline-mode-menu-hide)
4125 (defvar zmacs-regions) ; XEmacs regions
4127 ;; Emacs only
4128 (defvar mark-active)
4130 ;; Various packages
4131 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4132 (declare-function calendar-forward-day "cal-move" (arg))
4133 (declare-function calendar-goto-date "cal-move" (date))
4134 (declare-function calendar-goto-today "cal-move" ())
4135 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4136 (defvar calc-embedded-close-formula)
4137 (defvar calc-embedded-open-formula)
4138 (declare-function cdlatex-tab "ext:cdlatex" ())
4139 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4140 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4141 (defvar font-lock-unfontify-region-function)
4142 (declare-function iswitchb-read-buffer "iswitchb"
4143 (prompt &optional default require-match start matches-set))
4144 (defvar iswitchb-temp-buflist)
4145 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4146 (defvar org-agenda-tags-todo-honor-ignore-options)
4147 (declare-function org-agenda-skip "org-agenda" ())
4148 (declare-function
4149 org-agenda-format-item "org-agenda"
4150 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4151 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4152 (declare-function org-agenda-change-all-lines "org-agenda"
4153 (newhead hdmarker &optional fixface just-this))
4154 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4155 (declare-function org-agenda-maybe-redo "org-agenda" ())
4156 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4157 (beg end))
4158 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4159 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4160 "org-agenda" (&optional end))
4161 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4162 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4163 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4164 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4165 (declare-function org-indent-mode "org-indent" (&optional arg))
4166 (declare-function parse-time-string "parse-time" (string))
4167 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4168 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4169 (defvar remember-data-file)
4170 (defvar texmathp-why)
4171 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4172 (declare-function table--at-cell-p "table" (position &optional object at-column))
4174 (defvar org-latex-regexps)
4176 ;;; Autoload and prepare some org modules
4178 ;; Some table stuff that needs to be defined here, because it is used
4179 ;; by the functions setting up org-mode or checking for table context.
4181 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4182 "Detect an org-type or table-type table.")
4183 (defconst org-table-line-regexp "^[ \t]*|"
4184 "Detect an org-type table line.")
4185 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4186 "Detect an org-type table line.")
4187 (defconst org-table-hline-regexp "^[ \t]*|-"
4188 "Detect an org-type table hline.")
4189 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4190 "Detect a table-type table hline.")
4191 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4192 "Detect the first line outside a table when searching from within it.
4193 This works for both table types.")
4195 ;; Autoload the functions in org-table.el that are needed by functions here.
4197 (eval-and-compile
4198 (org-autoload "org-table"
4199 '(org-table-begin org-table-blank-field org-table-end)))
4201 ;;;###autoload
4202 (defun turn-on-orgtbl ()
4203 "Unconditionally turn on `orgtbl-mode'."
4204 (require 'org-table)
4205 (orgtbl-mode 1))
4207 (defun org-at-table-p (&optional table-type)
4208 "Return t if the cursor is inside an org-type table.
4209 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4210 (if org-enable-table-editor
4211 (save-excursion
4212 (beginning-of-line 1)
4213 (looking-at (if table-type org-table-any-line-regexp
4214 org-table-line-regexp)))
4215 nil))
4216 (defsubst org-table-p () (org-at-table-p))
4218 (defun org-at-table.el-p ()
4219 "Return t if and only if we are at a table.el table."
4220 (and (org-at-table-p 'any)
4221 (save-excursion
4222 (goto-char (org-table-begin 'any))
4223 (looking-at org-table1-hline-regexp))))
4225 (defun org-table-recognize-table.el ()
4226 "If there is a table.el table nearby, recognize it and move into it."
4227 (if org-table-tab-recognizes-table.el
4228 (if (org-at-table.el-p)
4229 (progn
4230 (beginning-of-line 1)
4231 (if (looking-at org-table-dataline-regexp)
4233 (if (looking-at org-table1-hline-regexp)
4234 (progn
4235 (beginning-of-line 2)
4236 (if (looking-at org-table-any-border-regexp)
4237 (beginning-of-line -1)))))
4238 (if (re-search-forward "|" (org-table-end t) t)
4239 (progn
4240 (require 'table)
4241 (if (table--at-cell-p (point))
4243 (message "recognizing table.el table...")
4244 (table-recognize-table)
4245 (message "recognizing table.el table...done")))
4246 (error "This should not happen"))
4248 nil)
4249 nil))
4251 (defun org-at-table-hline-p ()
4252 "Return t if the cursor is inside a hline in a table."
4253 (if org-enable-table-editor
4254 (save-excursion
4255 (beginning-of-line 1)
4256 (looking-at org-table-hline-regexp))
4257 nil))
4259 (defvar org-table-clean-did-remove-column nil)
4260 (defun org-table-map-tables (function &optional quietly)
4261 "Apply FUNCTION to the start of all tables in the buffer."
4262 (save-excursion
4263 (save-restriction
4264 (widen)
4265 (goto-char (point-min))
4266 (while (re-search-forward org-table-any-line-regexp nil t)
4267 (unless quietly
4268 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4269 (beginning-of-line 1)
4270 (when (and (looking-at org-table-line-regexp)
4271 ;; Exclude tables in src/example/verbatim/clocktable blocks
4272 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4273 (save-excursion (funcall function))
4274 (or (looking-at org-table-line-regexp)
4275 (forward-char 1)))
4276 (re-search-forward org-table-any-border-regexp nil 1))))
4277 (unless quietly (message "Mapping tables: done")))
4279 ;; Declare and autoload functions from ox.el and al.
4281 (declare-function org-export-get-environment "ox"
4282 (&optional backend subtreep ext-plist))
4283 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4285 ;; Declare and autoload functions from org-agenda.el
4287 (eval-and-compile
4288 (org-autoload "org-agenda"
4289 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4291 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4292 (declare-function org-clock-update-mode-line "org-clock" ())
4293 (declare-function org-resolve-clocks "org-clock"
4294 (&optional also-non-dangling-p prompt last-valid))
4295 (defvar org-clock-start-time)
4296 (defvar org-clock-marker (make-marker)
4297 "Marker recording the last clock-in.")
4298 (defvar org-clock-hd-marker (make-marker)
4299 "Marker recording the last clock-in, but the headline position.")
4300 (defvar org-clock-heading ""
4301 "The heading of the current clock entry.")
4302 (defun org-clock-is-active ()
4303 "Return non-nil if clock is currently running.
4304 The return value is actually the clock marker."
4305 (marker-buffer org-clock-marker))
4307 (eval-and-compile
4308 (org-autoload "org-clock" '(org-clock-remove-overlays
4309 org-clock-update-time-maybe
4310 org-clocktable-shift)))
4312 (defun org-check-running-clock ()
4313 "Check if the current buffer contains the running clock.
4314 If yes, offer to stop it and to save the buffer with the changes."
4315 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4316 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4317 (buffer-name))))
4318 (org-clock-out)
4319 (when (y-or-n-p "Save changed buffer?")
4320 (save-buffer))))
4322 (defun org-clocktable-try-shift (dir n)
4323 "Check if this line starts a clock table, if yes, shift the time block."
4324 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4325 (org-clocktable-shift dir n)))
4327 ;;;###autoload
4328 (defun org-clock-persistence-insinuate ()
4329 "Set up hooks for clock persistence."
4330 (require 'org-clock)
4331 (add-hook 'org-mode-hook 'org-clock-load)
4332 (add-hook 'kill-emacs-hook 'org-clock-save))
4334 ;; Define the variable already here, to make sure we have it.
4335 (defvar org-indent-mode nil
4336 "Non-nil if Org-Indent mode is enabled.
4337 Use the command `org-indent-mode' to change this variable.")
4339 ;; Autoload archiving code
4340 ;; The stuff that is needed for cycling and tags has to be defined here.
4342 (defgroup org-archive nil
4343 "Options concerning archiving in Org-mode."
4344 :tag "Org Archive"
4345 :group 'org-structure)
4347 (defcustom org-archive-location "%s_archive::"
4348 "The location where subtrees should be archived.
4350 The value of this variable is a string, consisting of two parts,
4351 separated by a double-colon. The first part is a filename and
4352 the second part is a headline.
4354 When the filename is omitted, archiving happens in the same file.
4355 %s in the filename will be replaced by the current file
4356 name (without the directory part). Archiving to a different file
4357 is useful to keep archived entries from contributing to the
4358 Org-mode Agenda.
4360 The archived entries will be filed as subtrees of the specified
4361 headline. When the headline is omitted, the subtrees are simply
4362 filed away at the end of the file, as top-level entries. Also in
4363 the heading you can use %s to represent the file name, this can be
4364 useful when using the same archive for a number of different files.
4366 Here are a few examples:
4367 \"%s_archive::\"
4368 If the current file is Projects.org, archive in file
4369 Projects.org_archive, as top-level trees. This is the default.
4371 \"::* Archived Tasks\"
4372 Archive in the current file, under the top-level headline
4373 \"* Archived Tasks\".
4375 \"~/org/archive.org::\"
4376 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4378 \"~/org/archive.org::* From %s\"
4379 Archive in file ~/org/archive.org (absolute path), under headlines
4380 \"From FILENAME\" where file name is the current file name.
4382 \"~/org/datetree.org::datetree/* Finished Tasks\"
4383 The \"datetree/\" string is special, signifying to archive
4384 items to the datetree. Items are placed in either the CLOSED
4385 date of the item, or the current date if there is no CLOSED date.
4386 The heading will be a subentry to the current date. There doesn't
4387 need to be a heading, but there always needs to be a slash after
4388 datetree. For example, to store archived items directly in the
4389 datetree, use \"~/org/datetree.org::datetree/\".
4391 \"basement::** Finished Tasks\"
4392 Archive in file ./basement (relative path), as level 3 trees
4393 below the level 2 heading \"** Finished Tasks\".
4395 You may set this option on a per-file basis by adding to the buffer a
4396 line like
4398 #+ARCHIVE: basement::** Finished Tasks
4400 You may also define it locally for a subtree by setting an ARCHIVE property
4401 in the entry. If such a property is found in an entry, or anywhere up
4402 the hierarchy, it will be used."
4403 :group 'org-archive
4404 :type 'string)
4406 (defcustom org-archive-tag "ARCHIVE"
4407 "The tag that marks a subtree as archived.
4408 An archived subtree does not open during visibility cycling, and does
4409 not contribute to the agenda listings.
4410 After changing this, font-lock must be restarted in the relevant buffers to
4411 get the proper fontification."
4412 :group 'org-archive
4413 :group 'org-keywords
4414 :type 'string)
4416 (defcustom org-agenda-skip-archived-trees t
4417 "Non-nil means the agenda will skip any items located in archived trees.
4418 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4419 variable is no longer recommended, you should leave it at the value t.
4420 Instead, use the key `v' to cycle the archives-mode in the agenda."
4421 :group 'org-archive
4422 :group 'org-agenda-skip
4423 :type 'boolean)
4425 (defcustom org-columns-skip-archived-trees t
4426 "Non-nil means ignore archived trees when creating column view."
4427 :group 'org-archive
4428 :group 'org-properties
4429 :type 'boolean)
4431 (defcustom org-cycle-open-archived-trees nil
4432 "Non-nil means `org-cycle' will open archived trees.
4433 An archived tree is a tree marked with the tag ARCHIVE.
4434 When nil, archived trees will stay folded. You can still open them with
4435 normal outline commands like `show-all', but not with the cycling commands."
4436 :group 'org-archive
4437 :group 'org-cycle
4438 :type 'boolean)
4440 (defcustom org-sparse-tree-open-archived-trees nil
4441 "Non-nil means sparse tree construction shows matches in archived trees.
4442 When nil, matches in these trees are highlighted, but the trees are kept in
4443 collapsed state."
4444 :group 'org-archive
4445 :group 'org-sparse-trees
4446 :type 'boolean)
4448 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4449 "The default date type when building a sparse tree.
4450 When this is nil, a date is a scheduled or a deadline timestamp.
4451 Otherwise, these types are allowed:
4453 all: all timestamps
4454 active: only active timestamps (<...>)
4455 inactive: only inactive timestamps (<...)
4456 scheduled: only scheduled timestamps
4457 deadline: only deadline timestamps"
4458 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4459 (const :tag "All timestamps" all)
4460 (const :tag "Only active timestamps" active)
4461 (const :tag "Only inactive timestamps" inactive)
4462 (const :tag "Only scheduled timestamps" scheduled)
4463 (const :tag "Only deadline timestamps" deadline)
4464 (const :tag "Only closed timestamps" closed))
4465 :version "24.3"
4466 :group 'org-sparse-trees)
4468 (defun org-cycle-hide-archived-subtrees (state)
4469 "Re-hide all archived subtrees after a visibility state change."
4470 (when (and (not org-cycle-open-archived-trees)
4471 (not (memq state '(overview folded))))
4472 (save-excursion
4473 (let* ((globalp (memq state '(contents all)))
4474 (beg (if globalp (point-min) (point)))
4475 (end (if globalp (point-max) (org-end-of-subtree t))))
4476 (org-hide-archived-subtrees beg end)
4477 (goto-char beg)
4478 (if (looking-at (concat ".*:" org-archive-tag ":"))
4479 (message "%s" (substitute-command-keys
4480 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4482 (defun org-force-cycle-archived ()
4483 "Cycle subtree even if it is archived."
4484 (interactive)
4485 (setq this-command 'org-cycle)
4486 (let ((org-cycle-open-archived-trees t))
4487 (call-interactively 'org-cycle)))
4489 (defun org-hide-archived-subtrees (beg end)
4490 "Re-hide all archived subtrees after a visibility state change."
4491 (save-excursion
4492 (let* ((re (concat ":" org-archive-tag ":")))
4493 (goto-char beg)
4494 (while (re-search-forward re end t)
4495 (when (org-at-heading-p)
4496 (org-flag-subtree t)
4497 (org-end-of-subtree t))))))
4499 (declare-function outline-end-of-heading "outline" ())
4500 (declare-function outline-flag-region "outline" (from to flag))
4501 (defun org-flag-subtree (flag)
4502 (save-excursion
4503 (org-back-to-heading t)
4504 (outline-end-of-heading)
4505 (outline-flag-region (point)
4506 (progn (org-end-of-subtree t) (point))
4507 flag)))
4509 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4511 (eval-and-compile
4512 (org-autoload "org-archive"
4513 '(org-add-archive-files)))
4515 ;; Autoload Column View Code
4517 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4518 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4519 (declare-function org-columns-compute "org-colview" (property))
4521 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4522 '(org-columns-number-to-string
4523 org-columns-get-format-and-top-level
4524 org-columns-compute
4525 org-columns-remove-overlays))
4527 ;; Autoload ID code
4529 (declare-function org-id-store-link "org-id")
4530 (declare-function org-id-locations-load "org-id")
4531 (declare-function org-id-locations-save "org-id")
4532 (defvar org-id-track-globally)
4533 (org-autoload "org-id"
4534 '(org-id-new
4535 org-id-copy
4536 org-id-get-with-outline-path-completion
4537 org-id-get-with-outline-drilling))
4539 ;;; Variables for pre-computed regular expressions, all buffer local
4541 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4542 "Matches first line of a hidden block.")
4543 (make-variable-buffer-local 'org-drawer-regexp)
4544 (defvar org-todo-regexp nil
4545 "Matches any of the TODO state keywords.")
4546 (make-variable-buffer-local 'org-todo-regexp)
4547 (defvar org-not-done-regexp nil
4548 "Matches any of the TODO state keywords except the last one.")
4549 (make-variable-buffer-local 'org-not-done-regexp)
4550 (defvar org-not-done-heading-regexp nil
4551 "Matches a TODO headline that is not done.")
4552 (make-variable-buffer-local 'org-not-done-regexp)
4553 (defvar org-todo-line-regexp nil
4554 "Matches a headline and puts TODO state into group 2 if present.")
4555 (make-variable-buffer-local 'org-todo-line-regexp)
4556 (defvar org-complex-heading-regexp nil
4557 "Matches a headline and puts everything into groups:
4558 group 1: the stars
4559 group 2: The todo keyword, maybe
4560 group 3: Priority cookie
4561 group 4: True headline
4562 group 5: Tags")
4563 (make-variable-buffer-local 'org-complex-heading-regexp)
4564 (defvar org-complex-heading-regexp-format nil
4565 "Printf format to make regexp to match an exact headline.
4566 This regexp will match the headline of any node which has the
4567 exact headline text that is put into the format, but may have any
4568 TODO state, priority and tags.")
4569 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4570 (defvar org-todo-line-tags-regexp nil
4571 "Matches a headline and puts TODO state into group 2 if present.
4572 Also put tags into group 4 if tags are present.")
4573 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4574 (defvar org-ds-keyword-length 12
4575 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4576 (make-variable-buffer-local 'org-ds-keyword-length)
4577 (defvar org-deadline-regexp nil
4578 "Matches the DEADLINE keyword.")
4579 (make-variable-buffer-local 'org-deadline-regexp)
4580 (defvar org-deadline-time-regexp nil
4581 "Matches the DEADLINE keyword together with a time stamp.")
4582 (make-variable-buffer-local 'org-deadline-time-regexp)
4583 (defvar org-deadline-time-hour-regexp nil
4584 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4585 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4586 (defvar org-deadline-line-regexp nil
4587 "Matches the DEADLINE keyword and the rest of the line.")
4588 (make-variable-buffer-local 'org-deadline-line-regexp)
4589 (defvar org-scheduled-regexp nil
4590 "Matches the SCHEDULED keyword.")
4591 (make-variable-buffer-local 'org-scheduled-regexp)
4592 (defvar org-scheduled-time-regexp nil
4593 "Matches the SCHEDULED keyword together with a time stamp.")
4594 (make-variable-buffer-local 'org-scheduled-time-regexp)
4595 (defvar org-scheduled-time-hour-regexp nil
4596 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4597 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4598 (defvar org-closed-time-regexp nil
4599 "Matches the CLOSED keyword together with a time stamp.")
4600 (make-variable-buffer-local 'org-closed-time-regexp)
4602 (defvar org-keyword-time-regexp nil
4603 "Matches any of the 4 keywords, together with the time stamp.")
4604 (make-variable-buffer-local 'org-keyword-time-regexp)
4605 (defvar org-keyword-time-not-clock-regexp nil
4606 "Matches any of the 3 keywords, together with the time stamp.")
4607 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4608 (defvar org-maybe-keyword-time-regexp nil
4609 "Matches a timestamp, possibly preceded by a keyword.")
4610 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4611 (defvar org-all-time-keywords nil
4612 "List of time keywords.")
4613 (make-variable-buffer-local 'org-all-time-keywords)
4615 (defconst org-plain-time-of-day-regexp
4616 (concat
4617 "\\(\\<[012]?[0-9]"
4618 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4619 "\\(--?"
4620 "\\(\\<[012]?[0-9]"
4621 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4622 "\\)?")
4623 "Regular expression to match a plain time or time range.
4624 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4625 groups carry important information:
4626 0 the full match
4627 1 the first time, range or not
4628 8 the second time, if it is a range.")
4630 (defconst org-plain-time-extension-regexp
4631 (concat
4632 "\\(\\<[012]?[0-9]"
4633 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4634 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4635 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4636 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4637 groups carry important information:
4638 0 the full match
4639 7 hours of duration
4640 9 minutes of duration")
4642 (defconst org-stamp-time-of-day-regexp
4643 (concat
4644 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4645 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4646 "\\(--?"
4647 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4648 "Regular expression to match a timestamp time or time range.
4649 After a match, the following groups carry important information:
4650 0 the full match
4651 1 date plus weekday, for back referencing to make sure both times are on the same day
4652 2 the first time, range or not
4653 4 the second time, if it is a range.")
4655 (defconst org-startup-options
4656 '(("fold" org-startup-folded t)
4657 ("overview" org-startup-folded t)
4658 ("nofold" org-startup-folded nil)
4659 ("showall" org-startup-folded nil)
4660 ("showeverything" org-startup-folded showeverything)
4661 ("content" org-startup-folded content)
4662 ("indent" org-startup-indented t)
4663 ("noindent" org-startup-indented nil)
4664 ("hidestars" org-hide-leading-stars t)
4665 ("showstars" org-hide-leading-stars nil)
4666 ("odd" org-odd-levels-only t)
4667 ("oddeven" org-odd-levels-only nil)
4668 ("align" org-startup-align-all-tables t)
4669 ("noalign" org-startup-align-all-tables nil)
4670 ("inlineimages" org-startup-with-inline-images t)
4671 ("noinlineimages" org-startup-with-inline-images nil)
4672 ("latexpreview" org-startup-with-latex-preview t)
4673 ("nolatexpreview" org-startup-with-latex-preview nil)
4674 ("customtime" org-display-custom-times t)
4675 ("logdone" org-log-done time)
4676 ("lognotedone" org-log-done note)
4677 ("nologdone" org-log-done nil)
4678 ("lognoteclock-out" org-log-note-clock-out t)
4679 ("nolognoteclock-out" org-log-note-clock-out nil)
4680 ("logrepeat" org-log-repeat state)
4681 ("lognoterepeat" org-log-repeat note)
4682 ("logdrawer" org-log-into-drawer t)
4683 ("nologdrawer" org-log-into-drawer nil)
4684 ("logstatesreversed" org-log-states-order-reversed t)
4685 ("nologstatesreversed" org-log-states-order-reversed nil)
4686 ("nologrepeat" org-log-repeat nil)
4687 ("logreschedule" org-log-reschedule time)
4688 ("lognotereschedule" org-log-reschedule note)
4689 ("nologreschedule" org-log-reschedule nil)
4690 ("logredeadline" org-log-redeadline time)
4691 ("lognoteredeadline" org-log-redeadline note)
4692 ("nologredeadline" org-log-redeadline nil)
4693 ("logrefile" org-log-refile time)
4694 ("lognoterefile" org-log-refile note)
4695 ("nologrefile" org-log-refile nil)
4696 ("fninline" org-footnote-define-inline t)
4697 ("nofninline" org-footnote-define-inline nil)
4698 ("fnlocal" org-footnote-section nil)
4699 ("fnauto" org-footnote-auto-label t)
4700 ("fnprompt" org-footnote-auto-label nil)
4701 ("fnconfirm" org-footnote-auto-label confirm)
4702 ("fnplain" org-footnote-auto-label plain)
4703 ("fnadjust" org-footnote-auto-adjust t)
4704 ("nofnadjust" org-footnote-auto-adjust nil)
4705 ("constcgs" constants-unit-system cgs)
4706 ("constSI" constants-unit-system SI)
4707 ("noptag" org-tag-persistent-alist nil)
4708 ("hideblocks" org-hide-block-startup t)
4709 ("nohideblocks" org-hide-block-startup nil)
4710 ("beamer" org-startup-with-beamer-mode t)
4711 ("entitiespretty" org-pretty-entities t)
4712 ("entitiesplain" org-pretty-entities nil))
4713 "Variable associated with STARTUP options for org-mode.
4714 Each element is a list of three items: the startup options (as written
4715 in the #+STARTUP line), the corresponding variable, and the value to set
4716 this variable to if the option is found. An optional forth element PUSH
4717 means to push this value onto the list in the variable.")
4719 (defun org-update-property-plist (key val props)
4720 "Update PROPS with KEY and VAL."
4721 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4722 (key (if appending (substring key 0 (- (length key) 1)) key))
4723 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4724 (previous (cdr (assoc key props))))
4725 (if appending
4726 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4727 (cons (cons key val) remainder))))
4729 (defconst org-block-regexp
4730 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4731 "Regular expression for hiding blocks.")
4732 (defconst org-heading-keyword-regexp-format
4733 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4734 "Printf format for a regexp matching a headline with some keyword.
4735 This regexp will match the headline of any node which has the
4736 exact keyword that is put into the format. The keyword isn't in
4737 any group by default, but the stars and the body are.")
4738 (defconst org-heading-keyword-maybe-regexp-format
4739 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4740 "Printf format for a regexp matching a headline, possibly with some keyword.
4741 This regexp can match any headline with the specified keyword, or
4742 without a keyword. The keyword isn't in any group by default,
4743 but the stars and the body are.")
4745 (defcustom org-group-tags t
4746 "When non-nil (the default), use group tags.
4747 This can be turned on/off through `org-toggle-tags-groups'."
4748 :group 'org-tags
4749 :group 'org-startup
4750 :type 'boolean)
4752 (defun org-toggle-tags-groups ()
4753 "Toggle support for group tags.
4754 Support for group tags is controlled by the option
4755 `org-group-tags', which is non-nil by default."
4756 (interactive)
4757 (setq org-group-tags (not org-group-tags))
4758 (cond ((and (derived-mode-p 'org-agenda-mode)
4759 org-group-tags)
4760 (org-agenda-redo))
4761 ((derived-mode-p 'org-mode)
4762 (let ((org-inhibit-startup t)) (org-mode))))
4763 (message "Groups tags support has been turned %s"
4764 (if org-group-tags "on" "off")))
4766 (defun org-set-regexps-and-options-for-tags ()
4767 "Precompute regular expressions used for tags in the current buffer."
4768 (when (derived-mode-p 'org-mode)
4769 (org-set-local 'org-file-tags nil)
4770 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4771 (splitre "[ \t]+")
4772 tags ftags key value
4773 (start 0))
4774 (save-excursion
4775 (save-restriction
4776 (widen)
4777 (goto-char (point-min))
4778 (while (re-search-forward re nil t)
4779 (setq key (upcase (org-match-string-no-properties 1))
4780 value (org-match-string-no-properties 2))
4781 (if (stringp value) (setq value (org-trim value)))
4782 (cond
4783 ((equal key "TAGS")
4784 (setq tags (append tags (if tags '("\\n") nil)
4785 (org-split-string value splitre))))
4786 ((equal key "FILETAGS")
4787 (when (string-match "\\S-" value)
4788 (setq ftags
4789 (append
4790 ftags
4791 (apply 'append
4792 (mapcar (lambda (x) (org-split-string x ":"))
4793 (org-split-string value)))))))))))
4794 ;; Process the file tags.
4795 (and ftags (org-set-local 'org-file-tags
4796 (mapcar 'org-add-prop-inherited ftags)))
4797 (org-set-local 'org-tag-groups-alist nil)
4798 ;; Process the tags.
4799 ;; FIXME
4800 (when tags
4801 (let (e tgs g)
4802 (while (setq e (pop tags))
4803 (cond
4804 ((equal e "{")
4805 (progn (push '(:startgroup) tgs)
4806 (when (equal (nth 1 tags) ":")
4807 (push (list (replace-regexp-in-string
4808 "(.+)$" "" (nth 0 tags)))
4809 org-tag-groups-alist)
4810 (setq g 0))))
4811 ((equal e ":") (push '(:grouptags) tgs))
4812 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4813 ((equal e "\\n") (push '(:newline) tgs))
4814 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4815 (push (cons (match-string 1 e)
4816 (string-to-char (match-string 2 e))) tgs)
4817 (if (and g (> g 0))
4818 (setcar org-tag-groups-alist
4819 (append (car org-tag-groups-alist)
4820 (list (match-string 1 e)))))
4821 (if g (setq g (1+ g))))
4822 (t (push (list e) tgs)
4823 (if (and g (> g 0))
4824 (setcar org-tag-groups-alist
4825 (append (car org-tag-groups-alist) (list e))))
4826 (if g (setq g (1+ g))))))
4827 (org-set-local 'org-tag-alist nil)
4828 (while (setq e (pop tgs))
4829 (or (and (stringp (car e))
4830 (assoc (car e) org-tag-alist))
4831 (push e org-tag-alist))))))))
4833 (defun org-set-regexps-and-options ()
4834 "Precompute regular expressions used in the current buffer."
4835 (when (derived-mode-p 'org-mode)
4836 (org-set-local 'org-todo-kwd-alist nil)
4837 (org-set-local 'org-todo-key-alist nil)
4838 (org-set-local 'org-todo-key-trigger nil)
4839 (org-set-local 'org-todo-keywords-1 nil)
4840 (org-set-local 'org-done-keywords nil)
4841 (org-set-local 'org-todo-heads nil)
4842 (org-set-local 'org-todo-sets nil)
4843 (org-set-local 'org-todo-log-states nil)
4844 (org-set-local 'org-file-properties nil)
4845 (let ((re (org-make-options-regexp
4846 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4847 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4848 "SETUPFILE" "OPTIONS")
4849 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4850 (splitre "[ \t]+")
4851 (scripts org-use-sub-superscripts)
4852 kwds kws0 kwsa key log value cat arch const links hw dws
4853 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4854 (start 0))
4855 (save-excursion
4856 (save-restriction
4857 (widen)
4858 (goto-char (point-min))
4859 (while (or (and ext-setup-or-nil
4860 (string-match re ext-setup-or-nil start)
4861 (setq start (match-end 0)))
4862 (and (setq ext-setup-or-nil nil start 0)
4863 (re-search-forward re nil t)))
4864 (setq key (upcase (match-string 1 ext-setup-or-nil))
4865 value (org-match-string-no-properties 2 ext-setup-or-nil))
4866 (if (stringp value) (setq value (org-trim value)))
4867 (cond
4868 ((equal key "CATEGORY")
4869 (setq cat value))
4870 ((member key '("SEQ_TODO" "TODO"))
4871 (push (cons 'sequence (org-split-string value splitre)) kwds))
4872 ((equal key "TYP_TODO")
4873 (push (cons 'type (org-split-string value splitre)) kwds))
4874 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4875 ;; general TODO-like setup
4876 (push (cons (intern (downcase (match-string 1 key)))
4877 (org-split-string value splitre)) kwds))
4878 ((equal key "COLUMNS")
4879 (org-set-local 'org-columns-default-format value))
4880 ((equal key "LINK")
4881 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4882 (push (cons (match-string 1 value)
4883 (org-trim (match-string 2 value)))
4884 links)))
4885 ((equal key "PRIORITIES")
4886 (setq prio (org-split-string value " +")))
4887 ((equal key "PROPERTY")
4888 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4889 (setq props (org-update-property-plist (match-string 1 value)
4890 (match-string 2 value)
4891 props))))
4892 ((equal key "DRAWERS")
4893 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4894 ((equal key "CONSTANTS")
4895 (org-table-set-constants))
4896 ((equal key "STARTUP")
4897 (let ((opts (org-split-string value splitre))
4898 l var val)
4899 (while (setq l (pop opts))
4900 (when (setq l (assoc l org-startup-options))
4901 (setq var (nth 1 l) val (nth 2 l))
4902 (if (not (nth 3 l))
4903 (set (make-local-variable var) val)
4904 (if (not (listp (symbol-value var)))
4905 (set (make-local-variable var) nil))
4906 (set (make-local-variable var) (symbol-value var))
4907 (add-to-list var val))))))
4908 ((equal key "ARCHIVE")
4909 (setq arch value)
4910 (remove-text-properties 0 (length arch)
4911 '(face t fontified t) arch))
4912 ((equal key "OPTIONS")
4913 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4914 (setq scripts (read (match-string 2 value)))))
4915 ((and (equal key "SETUPFILE")
4916 ;; Prevent checking in Gnus messages
4917 (not buffer-read-only))
4918 (setq setup-contents (org-file-contents
4919 (expand-file-name
4920 (org-remove-double-quotes value))
4921 'noerror))
4922 (if (not ext-setup-or-nil)
4923 (setq ext-setup-or-nil setup-contents start 0)
4924 (setq ext-setup-or-nil
4925 (concat (substring ext-setup-or-nil 0 start)
4926 "\n" setup-contents "\n"
4927 (substring ext-setup-or-nil start)))))))
4928 ;; search for property blocks
4929 (goto-char (point-min))
4930 (while (re-search-forward org-block-regexp nil t)
4931 (when (equal "PROPERTY" (upcase (match-string 1)))
4932 (setq value (replace-regexp-in-string
4933 "[\n\r]" " " (match-string 4)))
4934 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4935 (setq props (org-update-property-plist (match-string 1 value)
4936 (match-string 2 value)
4937 props)))))))
4938 (org-set-local 'org-use-sub-superscripts scripts)
4939 (when cat
4940 (org-set-local 'org-category (intern cat))
4941 (push (cons "CATEGORY" cat) props))
4942 (when prio
4943 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4944 (setq prio (mapcar 'string-to-char prio))
4945 (org-set-local 'org-highest-priority (nth 0 prio))
4946 (org-set-local 'org-lowest-priority (nth 1 prio))
4947 (org-set-local 'org-default-priority (nth 2 prio)))
4948 (and props (org-set-local 'org-file-properties (nreverse props)))
4949 (and drawers (org-set-local 'org-drawers drawers))
4950 (and arch (org-set-local 'org-archive-location arch))
4951 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4952 ;; Process the TODO keywords
4953 (unless kwds
4954 ;; Use the global values as if they had been given locally.
4955 (setq kwds (default-value 'org-todo-keywords))
4956 (if (stringp (car kwds))
4957 (setq kwds (list (cons org-todo-interpretation
4958 (default-value 'org-todo-keywords)))))
4959 (setq kwds (reverse kwds)))
4960 (setq kwds (nreverse kwds))
4961 (let (inter kws kw)
4962 (while (setq kws (pop kwds))
4963 (let ((kws (or
4964 (run-hook-with-args-until-success
4965 'org-todo-setup-filter-hook kws)
4966 kws)))
4967 (setq inter (pop kws) sep (member "|" kws)
4968 kws0 (delete "|" (copy-sequence kws))
4969 kwsa nil
4970 kws1 (mapcar
4971 (lambda (x)
4972 ;; 1 2
4973 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4974 (progn
4975 (setq kw (match-string 1 x)
4976 key (and (match-end 2) (match-string 2 x))
4977 log (org-extract-log-state-settings x))
4978 (push (cons kw (and key (string-to-char key))) kwsa)
4979 (and log (push log org-todo-log-states))
4981 (error "Invalid TODO keyword %s" x)))
4982 kws0)
4983 kwsa (if kwsa (append '((:startgroup))
4984 (nreverse kwsa)
4985 '((:endgroup))))
4986 hw (car kws1)
4987 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4988 tail (list inter hw (car dws) (org-last dws))))
4989 (add-to-list 'org-todo-heads hw 'append)
4990 (push kws1 org-todo-sets)
4991 (setq org-done-keywords (append org-done-keywords dws nil))
4992 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4993 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4994 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4995 (setq org-todo-sets (nreverse org-todo-sets)
4996 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4997 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4998 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4999 ;; Compute the regular expressions and other local variables.
5000 ;; Using `org-outline-regexp-bol' would complicate them much,
5001 ;; because of the fixed white space at the end of that string.
5002 (if (not org-done-keywords)
5003 (setq org-done-keywords (and org-todo-keywords-1
5004 (list (org-last org-todo-keywords-1)))))
5005 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5006 (length org-scheduled-string)
5007 (length org-clock-string)
5008 (length org-closed-string)))
5009 org-drawer-regexp
5010 (concat "^[ \t]*:\\("
5011 (mapconcat 'regexp-quote org-drawers "\\|")
5012 "\\):[ \t]*$")
5013 org-not-done-keywords
5014 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5015 org-todo-regexp
5016 (concat "\\("
5017 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5018 "\\)")
5019 org-not-done-regexp
5020 (concat "\\("
5021 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5022 "\\)")
5023 org-not-done-heading-regexp
5024 (format org-heading-keyword-regexp-format org-not-done-regexp)
5025 org-todo-line-regexp
5026 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5027 org-complex-heading-regexp
5028 (concat "^\\(\\*+\\)"
5029 "\\(?: +" org-todo-regexp "\\)?"
5030 "\\(?: +\\(\\[#.\\]\\)\\)?"
5031 "\\(?: +\\(.*?\\)\\)??"
5032 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5033 "[ \t]*$")
5034 org-complex-heading-regexp-format
5035 (concat "^\\(\\*+\\)"
5036 "\\(?: +" org-todo-regexp "\\)?"
5037 "\\(?: +\\(\\[#.\\]\\)\\)?"
5038 "\\(?: +"
5039 ;; Stats cookies can be stuck to body.
5040 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5041 "\\(%s\\)"
5042 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5043 "\\)"
5044 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5045 "[ \t]*$")
5046 org-todo-line-tags-regexp
5047 (concat "^\\(\\*+\\)"
5048 "\\(?: +" org-todo-regexp "\\)?"
5049 "\\(?: +\\(.*?\\)\\)??"
5050 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5051 "[ \t]*$")
5052 org-deadline-regexp (concat "\\<" org-deadline-string)
5053 org-deadline-time-regexp
5054 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5055 org-deadline-time-hour-regexp
5056 (concat "\\<" org-deadline-string
5057 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5058 org-deadline-line-regexp
5059 (concat "\\<\\(" org-deadline-string "\\).*")
5060 org-scheduled-regexp
5061 (concat "\\<" org-scheduled-string)
5062 org-scheduled-time-regexp
5063 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5064 org-scheduled-time-hour-regexp
5065 (concat "\\<" org-scheduled-string
5066 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5067 org-closed-time-regexp
5068 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5069 org-keyword-time-regexp
5070 (concat "\\<\\(" org-scheduled-string
5071 "\\|" org-deadline-string
5072 "\\|" org-closed-string
5073 "\\|" org-clock-string "\\)"
5074 " *[[<]\\([^]>]+\\)[]>]")
5075 org-keyword-time-not-clock-regexp
5076 (concat "\\<\\(" org-scheduled-string
5077 "\\|" org-deadline-string
5078 "\\|" org-closed-string
5079 "\\)"
5080 " *[[<]\\([^]>]+\\)[]>]")
5081 org-maybe-keyword-time-regexp
5082 (concat "\\(\\<\\(" org-scheduled-string
5083 "\\|" org-deadline-string
5084 "\\|" org-closed-string
5085 "\\|" org-clock-string "\\)\\)?"
5086 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5087 org-all-time-keywords
5088 (mapcar (lambda (w) (substring w 0 -1))
5089 (list org-scheduled-string org-deadline-string
5090 org-clock-string org-closed-string)))
5091 (org-compute-latex-and-related-regexp)
5092 (org-set-font-lock-defaults))))
5094 (defun org-file-contents (file &optional noerror)
5095 "Return the contents of FILE, as a string."
5096 (if (or (not file)
5097 (not (file-readable-p file)))
5098 (if noerror
5099 (message "Cannot read file \"%s\"" file)
5100 (error "Cannot read file \"%s\"" file))
5101 (with-temp-buffer
5102 (insert-file-contents file)
5103 (buffer-string))))
5105 (defun org-extract-log-state-settings (x)
5106 "Extract the log state setting from a TODO keyword string.
5107 This will extract info from a string like \"WAIT(w@/!)\"."
5108 (let (kw key log1 log2)
5109 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5110 (setq kw (match-string 1 x)
5111 key (and (match-end 2) (match-string 2 x))
5112 log1 (and (match-end 3) (match-string 3 x))
5113 log2 (and (match-end 4) (match-string 4 x)))
5114 (and (or log1 log2)
5115 (list kw
5116 (and log1 (if (equal log1 "!") 'time 'note))
5117 (and log2 (if (equal log2 "!") 'time 'note)))))))
5119 (defun org-remove-keyword-keys (list)
5120 "Remove a pair of parenthesis at the end of each string in LIST."
5121 (mapcar (lambda (x)
5122 (if (string-match "(.*)$" x)
5123 (substring x 0 (match-beginning 0))
5125 list))
5127 (defun org-assign-fast-keys (alist)
5128 "Assign fast keys to a keyword-key alist.
5129 Respect keys that are already there."
5130 (let (new e (alt ?0))
5131 (while (setq e (pop alist))
5132 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5133 (cdr e)) ;; Key already assigned.
5134 (push e new)
5135 (let ((clist (string-to-list (downcase (car e))))
5136 (used (append new alist)))
5137 (when (= (car clist) ?@)
5138 (pop clist))
5139 (while (and clist (rassoc (car clist) used))
5140 (pop clist))
5141 (unless clist
5142 (while (rassoc alt used)
5143 (incf alt)))
5144 (push (cons (car e) (or (car clist) alt)) new))))
5145 (nreverse new)))
5147 ;;; Some variables used in various places
5149 (defvar org-window-configuration nil
5150 "Used in various places to store a window configuration.")
5151 (defvar org-selected-window nil
5152 "Used in various places to store a window configuration.")
5153 (defvar org-finish-function nil
5154 "Function to be called when `C-c C-c' is used.
5155 This is for getting out of special buffers like capture.")
5158 ;; FIXME: Occasionally check by commenting these, to make sure
5159 ;; no other functions uses these, forgetting to let-bind them.
5160 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5161 (defvar org-last-state)
5162 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5164 ;; Defined somewhere in this file, but used before definition.
5165 (defvar org-entities) ;; defined in org-entities.el
5166 (defvar org-struct-menu)
5167 (defvar org-org-menu)
5168 (defvar org-tbl-menu)
5170 ;;;; Define the Org-mode
5172 ;; We use a before-change function to check if a table might need
5173 ;; an update.
5174 (defvar org-table-may-need-update t
5175 "Indicates that a table might need an update.
5176 This variable is set by `org-before-change-function'.
5177 `org-table-align' sets it back to nil.")
5178 (defun org-before-change-function (beg end)
5179 "Every change indicates that a table might need an update."
5180 (setq org-table-may-need-update t))
5181 (defvar org-mode-map)
5182 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5183 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5184 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5185 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5186 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5187 (defvar org-table-buffer-is-an nil)
5189 (defvar bidi-paragraph-direction)
5190 (defvar buffer-face-mode-face)
5192 (require 'outline)
5193 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5194 (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"))
5195 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5197 ;; Other stuff we need.
5198 (require 'time-date)
5199 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5200 (require 'easymenu)
5201 (require 'overlay)
5203 ;; (require 'org-macs) moved higher up in the file before it is first used
5204 (require 'org-entities)
5205 ;; (require 'org-compat) moved higher up in the file before it is first used
5206 (require 'org-faces)
5207 (require 'org-list)
5208 (require 'org-pcomplete)
5209 (require 'org-src)
5210 (require 'org-footnote)
5211 (require 'org-macro)
5213 ;; babel
5214 (require 'ob)
5216 ;;;###autoload
5217 (define-derived-mode org-mode outline-mode "Org"
5218 "Outline-based notes management and organizer, alias
5219 \"Carsten's outline-mode for keeping track of everything.\"
5221 Org-mode develops organizational tasks around a NOTES file which
5222 contains information about projects as plain text. Org-mode is
5223 implemented on top of outline-mode, which is ideal to keep the content
5224 of large files well structured. It supports ToDo items, deadlines and
5225 time stamps, which magically appear in the diary listing of the Emacs
5226 calendar. Tables are easily created with a built-in table editor.
5227 Plain text URL-like links connect to websites, emails (VM), Usenet
5228 messages (Gnus), BBDB entries, and any files related to the project.
5229 For printing and sharing of notes, an Org-mode file (or a part of it)
5230 can be exported as a structured ASCII or HTML file.
5232 The following commands are available:
5234 \\{org-mode-map}"
5236 ;; Get rid of Outline menus, they are not needed
5237 ;; Need to do this here because define-derived-mode sets up
5238 ;; the keymap so late. Still, it is a waste to call this each time
5239 ;; we switch another buffer into org-mode.
5240 (if (featurep 'xemacs)
5241 (when (boundp 'outline-mode-menu-heading)
5242 ;; Assume this is Greg's port, it uses easymenu
5243 (easy-menu-remove outline-mode-menu-heading)
5244 (easy-menu-remove outline-mode-menu-show)
5245 (easy-menu-remove outline-mode-menu-hide))
5246 (define-key org-mode-map [menu-bar headings] 'undefined)
5247 (define-key org-mode-map [menu-bar hide] 'undefined)
5248 (define-key org-mode-map [menu-bar show] 'undefined))
5250 (org-load-modules-maybe)
5251 (easy-menu-add org-org-menu)
5252 (easy-menu-add org-tbl-menu)
5253 (org-install-agenda-files-menu)
5254 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5255 (add-to-invisibility-spec '(org-cwidth))
5256 (add-to-invisibility-spec '(org-hide-block . t))
5257 (when (featurep 'xemacs)
5258 (org-set-local 'line-move-ignore-invisible t))
5259 (org-set-local 'outline-regexp org-outline-regexp)
5260 (org-set-local 'outline-level 'org-outline-level)
5261 (setq bidi-paragraph-direction 'left-to-right)
5262 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5263 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5264 (when (and org-ellipsis
5265 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5266 (fboundp 'make-glyph-code))
5267 (unless org-display-table
5268 (setq org-display-table (make-display-table)))
5269 (set-display-table-slot
5270 org-display-table 4
5271 (vconcat (mapcar
5272 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5273 org-ellipsis)))
5274 (if (stringp org-ellipsis) org-ellipsis "..."))))
5275 (setq buffer-display-table org-display-table))
5276 (org-set-regexps-and-options-for-tags)
5277 (org-set-regexps-and-options)
5278 (when (and org-tag-faces (not org-tags-special-faces-re))
5279 ;; tag faces set outside customize.... force initialization.
5280 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5281 ;; Calc embedded
5282 (org-set-local 'calc-embedded-open-mode "# ")
5283 ;; Modify a few syntax entries
5284 (modify-syntax-entry ?@ "w")
5285 (modify-syntax-entry ?\" "\"")
5286 (if org-startup-truncated (setq truncate-lines t))
5287 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5288 (org-set-local 'font-lock-unfontify-region-function
5289 'org-unfontify-region)
5290 ;; Activate before-change-function
5291 (org-set-local 'org-table-may-need-update t)
5292 (org-add-hook 'before-change-functions 'org-before-change-function nil
5293 'local)
5294 ;; Check for running clock before killing a buffer
5295 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5296 ;; Initialize macros templates.
5297 (org-macro-initialize-templates)
5298 ;; Initialize radio targets.
5299 (org-update-radio-target-regexp)
5300 ;; Indentation.
5301 (org-set-local 'indent-line-function 'org-indent-line)
5302 (org-set-local 'indent-region-function 'org-indent-region)
5303 ;; Filling and auto-filling.
5304 (org-setup-filling)
5305 ;; Comments.
5306 (org-setup-comments-handling)
5307 ;; Beginning/end of defun
5308 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5309 (org-set-local 'end-of-defun-function 'org-forward-element)
5310 ;; Next error for sparse trees
5311 (org-set-local 'next-error-function 'org-occur-next-match)
5312 ;; Make sure dependence stuff works reliably, even for users who set it
5313 ;; too late :-(
5314 (if org-enforce-todo-dependencies
5315 (add-hook 'org-blocker-hook
5316 'org-block-todo-from-children-or-siblings-or-parent)
5317 (remove-hook 'org-blocker-hook
5318 'org-block-todo-from-children-or-siblings-or-parent))
5319 (if org-enforce-todo-checkbox-dependencies
5320 (add-hook 'org-blocker-hook
5321 'org-block-todo-from-checkboxes)
5322 (remove-hook 'org-blocker-hook
5323 'org-block-todo-from-checkboxes))
5325 ;; Align options lines
5326 (org-set-local
5327 'align-mode-rules-list
5328 '((org-in-buffer-settings
5329 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5330 (modes . '(org-mode)))))
5332 ;; Imenu
5333 (org-set-local 'imenu-create-index-function
5334 'org-imenu-get-tree)
5336 ;; Make isearch reveal context
5337 (if (or (featurep 'xemacs)
5338 (not (boundp 'outline-isearch-open-invisible-function)))
5339 ;; Emacs 21 and XEmacs make use of the hook
5340 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5341 ;; Emacs 22 deals with this through a special variable
5342 (org-set-local 'outline-isearch-open-invisible-function
5343 (lambda (&rest ignore) (org-show-context 'isearch)))
5344 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5346 ;; Setup the pcomplete hooks
5347 (set (make-local-variable 'pcomplete-command-completion-function)
5348 'org-pcomplete-initial)
5349 (set (make-local-variable 'pcomplete-command-name-function)
5350 'org-command-at-point)
5351 (set (make-local-variable 'pcomplete-default-completion-function)
5352 'ignore)
5353 (set (make-local-variable 'pcomplete-parse-arguments-function)
5354 'org-parse-arguments)
5355 (set (make-local-variable 'pcomplete-termination-string) "")
5356 (when (>= emacs-major-version 23)
5357 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5359 ;; If empty file that did not turn on org-mode automatically, make it to.
5360 (if (and org-insert-mode-line-in-empty-file
5361 (org-called-interactively-p 'any)
5362 (= (point-min) (point-max)))
5363 (insert "# -*- mode: org -*-\n\n"))
5364 (unless org-inhibit-startup
5365 (org-unmodified
5366 (and org-startup-with-beamer-mode (org-beamer-mode))
5367 (when org-startup-align-all-tables
5368 (org-table-map-tables 'org-table-align 'quietly))
5369 (when org-startup-with-inline-images
5370 (org-display-inline-images))
5371 (when org-startup-with-latex-preview
5372 (org-preview-latex-fragment))
5373 (unless org-inhibit-startup-visibility-stuff
5374 (org-set-startup-visibility))))
5375 ;; Try to set org-hide correctly
5376 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5378 ;; Update `customize-package-emacs-version-alist'
5379 (add-to-list 'customize-package-emacs-version-alist
5380 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5381 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5382 ("8.0" . "24.4")))
5384 (defvar org-mode-transpose-word-syntax-table
5385 (let ((st (make-syntax-table)))
5386 (mapc (lambda(c) (modify-syntax-entry
5387 (string-to-char (car c)) "w p" st))
5388 org-emphasis-alist)
5389 st))
5391 (when (fboundp 'abbrev-table-put)
5392 (abbrev-table-put org-mode-abbrev-table
5393 :parents (list text-mode-abbrev-table)))
5395 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5397 (defsubst org-fix-ellipsis-at-bol ()
5398 (save-excursion (goto-char (window-start)) (recenter 0)))
5400 (defun org-find-invisible-foreground ()
5401 (let ((candidates (remove
5402 "unspecified-bg"
5403 (nconc
5404 (list (face-background 'default)
5405 (face-background 'org-default))
5406 (mapcar
5407 (lambda (alist)
5408 (when (boundp alist)
5409 (cdr (assoc 'background-color (symbol-value alist)))))
5410 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5411 (list (face-foreground 'org-hide))))))
5412 (car (remove nil candidates))))
5414 (defun org-current-time (&optional rounding-minutes past)
5415 "Current time, possibly rounded to ROUNDING-MINUTES.
5416 When ROUNDING-MINUTES is not an integer, fall back on the car of
5417 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5418 the rounding returns a past time."
5419 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5420 (car org-time-stamp-rounding-minutes)))
5421 (time (decode-time)) res)
5422 (if (< r 1)
5423 (current-time)
5424 (setq res
5425 (apply 'encode-time
5426 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5427 (nthcdr 2 time))))
5428 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5429 (seconds-to-time (- (org-float-time res) (* r 60)))
5430 res))))
5432 (defun org-today ()
5433 "Return today date, considering `org-extend-today-until'."
5434 (time-to-days
5435 (time-subtract (current-time)
5436 (list 0 (* 3600 org-extend-today-until) 0))))
5438 ;;;; Font-Lock stuff, including the activators
5440 (defvar org-mouse-map (make-sparse-keymap))
5441 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5442 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5443 (when org-mouse-1-follows-link
5444 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5445 (when org-tab-follows-link
5446 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5447 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5449 (require 'font-lock)
5451 (defconst org-non-link-chars "]\t\n\r<>")
5452 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5453 "shell" "elisp" "doi" "message"))
5454 (defvar org-link-types-re nil
5455 "Matches a link that has a url-like prefix like \"http:\"")
5456 (defvar org-link-re-with-space nil
5457 "Matches a link with spaces, optional angular brackets around it.")
5458 (defvar org-link-re-with-space2 nil
5459 "Matches a link with spaces, optional angular brackets around it.")
5460 (defvar org-link-re-with-space3 nil
5461 "Matches a link with spaces, only for internal part in bracket links.")
5462 (defvar org-angle-link-re nil
5463 "Matches link with angular brackets, spaces are allowed.")
5464 (defvar org-plain-link-re nil
5465 "Matches plain link, without spaces.")
5466 (defvar org-bracket-link-regexp nil
5467 "Matches a link in double brackets.")
5468 (defvar org-bracket-link-analytic-regexp nil
5469 "Regular expression used to analyze links.
5470 Here is what the match groups contain after a match:
5471 1: http:
5472 2: http
5473 3: path
5474 4: [desc]
5475 5: desc")
5476 (defvar org-bracket-link-analytic-regexp++ nil
5477 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5478 (defvar org-any-link-re nil
5479 "Regular expression matching any link.")
5481 (defconst org-match-sexp-depth 3
5482 "Number of stacked braces for sub/superscript matching.")
5484 (defun org-create-multibrace-regexp (left right n)
5485 "Create a regular expression which will match a balanced sexp.
5486 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5487 as single character strings.
5488 The regexp returned will match the entire expression including the
5489 delimiters. It will also define a single group which contains the
5490 match except for the outermost delimiters. The maximum depth of
5491 stacked delimiters is N. Escaping delimiters is not possible."
5492 (let* ((nothing (concat "[^" left right "]*?"))
5493 (or "\\|")
5494 (re nothing)
5495 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5496 (while (> n 1)
5497 (setq n (1- n)
5498 re (concat re or next)
5499 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5500 (concat left "\\(" re "\\)" right)))
5502 (defvar org-match-substring-regexp
5503 (concat
5504 "\\(\\S-\\)\\([_^]\\)\\("
5505 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5506 "\\|"
5507 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5508 "\\|"
5509 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5510 "The regular expression matching a sub- or superscript.")
5512 (defvar org-match-substring-with-braces-regexp
5513 (concat
5514 "\\(\\S-\\)\\([_^]\\)\\("
5515 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5516 "\\)")
5517 "The regular expression matching a sub- or superscript, forcing braces.")
5519 (defun org-make-link-regexps ()
5520 "Update the link regular expressions.
5521 This should be called after the variable `org-link-types' has changed."
5522 (setq org-link-types-re
5523 (concat
5524 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5525 org-link-re-with-space
5526 (concat
5527 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5528 "\\([^" org-non-link-chars " ]"
5529 "[^" org-non-link-chars "]*"
5530 "[^" org-non-link-chars " ]\\)>?")
5531 org-link-re-with-space2
5532 (concat
5533 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5534 "\\([^" org-non-link-chars " ]"
5535 "[^\t\n\r]*"
5536 "[^" org-non-link-chars " ]\\)>?")
5537 org-link-re-with-space3
5538 (concat
5539 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5540 "\\([^" org-non-link-chars " ]"
5541 "[^\t\n\r]*\\)")
5542 org-angle-link-re
5543 (concat
5544 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5545 "\\([^" org-non-link-chars " ]"
5546 "[^" org-non-link-chars "]*"
5547 "\\)>")
5548 org-plain-link-re
5549 (concat
5550 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5551 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5552 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5553 org-bracket-link-regexp
5554 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5555 org-bracket-link-analytic-regexp
5556 (concat
5557 "\\[\\["
5558 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5559 "\\([^]]+\\)"
5560 "\\]"
5561 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5562 "\\]")
5563 org-bracket-link-analytic-regexp++
5564 (concat
5565 "\\[\\["
5566 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5567 "\\([^]]+\\)"
5568 "\\]"
5569 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5570 "\\]")
5571 org-any-link-re
5572 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5573 org-angle-link-re "\\)\\|\\("
5574 org-plain-link-re "\\)")))
5576 (org-make-link-regexps)
5578 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5579 "Regular expression for fast time stamp matching.")
5580 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5581 "Regular expression for fast time stamp matching.")
5582 (defconst org-ts-regexp0
5583 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5584 "Regular expression matching time strings for analysis.
5585 This one does not require the space after the date, so it can be used
5586 on a string that terminates immediately after the date.")
5587 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5588 "Regular expression matching time strings for analysis.")
5589 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5590 "Regular expression matching time stamps, with groups.")
5591 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5592 "Regular expression matching time stamps (also [..]), with groups.")
5593 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5594 "Regular expression matching a time stamp range.")
5595 (defconst org-tr-regexp-both
5596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5597 "Regular expression matching a time stamp range.")
5598 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5599 org-ts-regexp "\\)?")
5600 "Regular expression matching a time stamp or time stamp range.")
5601 (defconst org-tsr-regexp-both
5602 (concat org-ts-regexp-both "\\(--?-?"
5603 org-ts-regexp-both "\\)?")
5604 "Regular expression matching a time stamp or time stamp range.
5605 The time stamps may be either active or inactive.")
5607 (defvar org-emph-face nil)
5609 (defun org-do-emphasis-faces (limit)
5610 "Run through the buffer and add overlays to emphasized strings."
5611 (let (rtn a)
5612 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5613 (if (not (= (char-after (match-beginning 3))
5614 (char-after (match-beginning 4))))
5615 (progn
5616 (setq rtn t)
5617 (setq a (assoc (match-string 3) org-emphasis-alist))
5618 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5619 'face
5620 (nth 1 a))
5621 (and (nth 4 a)
5622 (org-remove-flyspell-overlays-in
5623 (match-beginning 0) (match-end 0)))
5624 (add-text-properties (match-beginning 2) (match-end 2)
5625 '(font-lock-multiline t org-emphasis t))
5626 (when org-hide-emphasis-markers
5627 (add-text-properties (match-end 4) (match-beginning 5)
5628 '(invisible org-link))
5629 (add-text-properties (match-beginning 3) (match-end 3)
5630 '(invisible org-link)))))
5631 (backward-char 1))
5632 rtn))
5634 (defun org-emphasize (&optional char)
5635 "Insert or change an emphasis, i.e. a font like bold or italic.
5636 If there is an active region, change that region to a new emphasis.
5637 If there is no region, just insert the marker characters and position
5638 the cursor between them.
5639 CHAR should be either the marker character, or the first character of the
5640 HTML tag associated with that emphasis. If CHAR is a space, the means
5641 to remove the emphasis of the selected region.
5642 If char is not given (for example in an interactive call) it
5643 will be prompted for."
5644 (interactive)
5645 (let ((eal org-emphasis-alist) e det
5646 (erc org-emphasis-regexp-components)
5647 (prompt "")
5648 (string "") beg end move tag c s)
5649 (if (org-region-active-p)
5650 (setq beg (region-beginning) end (region-end)
5651 string (buffer-substring beg end))
5652 (setq move t))
5654 (while (setq e (pop eal))
5655 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5656 c (aref tag 0))
5657 (push (cons c (string-to-char (car e))) det)
5658 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5659 (substring tag 1)))))
5660 (setq det (nreverse det))
5661 (unless char
5662 (message "%s" (concat "Emphasis marker or tag:" prompt))
5663 (setq char (read-char-exclusive)))
5664 (setq char (or (cdr (assoc char det)) char))
5665 (if (equal char ?\ )
5666 (setq s "" move nil)
5667 (unless (assoc (char-to-string char) org-emphasis-alist)
5668 (error "No such emphasis marker: \"%c\"" char))
5669 (setq s (char-to-string char)))
5670 (while (and (> (length string) 1)
5671 (equal (substring string 0 1) (substring string -1))
5672 (assoc (substring string 0 1) org-emphasis-alist))
5673 (setq string (substring string 1 -1)))
5674 (setq string (concat s string s))
5675 (if beg (delete-region beg end))
5676 (unless (or (bolp)
5677 (string-match (concat "[" (nth 0 erc) "\n]")
5678 (char-to-string (char-before (point)))))
5679 (insert " "))
5680 (unless (or (eobp)
5681 (string-match (concat "[" (nth 1 erc) "\n]")
5682 (char-to-string (char-after (point)))))
5683 (insert " ") (backward-char 1))
5684 (insert string)
5685 (and move (backward-char 1))))
5687 (defconst org-nonsticky-props
5688 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5690 (defsubst org-rear-nonsticky-at (pos)
5691 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5693 (defun org-activate-plain-links (limit)
5694 "Run through the buffer and add overlays to links."
5695 (let (f hl)
5696 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5697 (not (org-in-src-block-p)))
5698 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5699 (setq f (get-text-property (match-beginning 0) 'face))
5700 (setq hl (org-match-string-no-properties 0))
5701 (if (or (eq f 'org-tag)
5702 (and (listp f) (memq 'org-tag f)))
5704 (add-text-properties (match-beginning 0) (match-end 0)
5705 (list 'mouse-face 'highlight
5706 'face 'org-link
5707 'htmlize-link `(:uri ,hl)
5708 'keymap org-mouse-map))
5709 (org-rear-nonsticky-at (match-end 0)))
5710 t)))
5712 (defun org-activate-code (limit)
5713 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5714 (progn
5715 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5716 (remove-text-properties (match-beginning 0) (match-end 0)
5717 '(display t invisible t intangible t))
5718 t)))
5720 (defcustom org-src-fontify-natively nil
5721 "When non-nil, fontify code in code blocks."
5722 :type 'boolean
5723 :version "24.1"
5724 :group 'org-appearance
5725 :group 'org-babel)
5727 (defcustom org-allow-promoting-top-level-subtree nil
5728 "When non-nil, allow promoting a top level subtree.
5729 The leading star of the top level headline will be replaced
5730 by a #."
5731 :type 'boolean
5732 :version "24.1"
5733 :group 'org-appearance)
5735 (defun org-fontify-meta-lines-and-blocks (limit)
5736 (condition-case nil
5737 (org-fontify-meta-lines-and-blocks-1 limit)
5738 (error (message "org-mode fontification error"))))
5740 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5741 "Fontify #+ lines and blocks."
5742 (let ((case-fold-search t))
5743 (if (re-search-forward
5744 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5745 limit t)
5746 (let ((beg (match-beginning 0))
5747 (block-start (match-end 0))
5748 (block-end nil)
5749 (lang (match-string 7))
5750 (beg1 (line-beginning-position 2))
5751 (dc1 (downcase (match-string 2)))
5752 (dc3 (downcase (match-string 3)))
5753 end end1 quoting block-type ovl)
5754 (cond
5755 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5756 ;; a single line of backend-specific content
5757 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5758 (remove-text-properties (match-beginning 0) (match-end 0)
5759 '(display t invisible t intangible t))
5760 (add-text-properties (match-beginning 1) (match-end 3)
5761 '(font-lock-fontified t face org-meta-line))
5762 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5763 '(font-lock-fontified t face org-block))
5764 ; for backend-specific code
5766 ((and (match-end 4) (equal dc3 "+begin"))
5767 ;; Truly a block
5768 (setq block-type (downcase (match-string 5))
5769 quoting (member block-type org-protecting-blocks))
5770 (when (re-search-forward
5771 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5772 nil t) ;; on purpose, we look further than LIMIT
5773 (setq end (min (point-max) (match-end 0))
5774 end1 (min (point-max) (1- (match-beginning 0))))
5775 (setq block-end (match-beginning 0))
5776 (when quoting
5777 (remove-text-properties beg end
5778 '(display t invisible t intangible t)))
5779 (add-text-properties
5780 beg end
5781 '(font-lock-fontified t font-lock-multiline t))
5782 (add-text-properties beg beg1 '(face org-meta-line))
5783 (add-text-properties end1 (min (point-max) (1+ end))
5784 '(face org-meta-line)) ; for end_src
5785 (cond
5786 ((and lang (not (string= lang "")) org-src-fontify-natively)
5787 (org-src-font-lock-fontify-block lang block-start block-end)
5788 ;; remove old background overlays
5789 (mapc (lambda (ov)
5790 (if (eq (overlay-get ov 'face) 'org-block-background)
5791 (delete-overlay ov)))
5792 (overlays-at (/ (+ beg1 block-end) 2)))
5793 ;; add a background overlay
5794 (setq ovl (make-overlay beg1 block-end))
5795 (overlay-put ovl 'face 'org-block-background)
5796 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5797 (quoting
5798 (add-text-properties beg1 (min (point-max) (1+ end1))
5799 '(face org-block))) ; end of source block
5800 ((not org-fontify-quote-and-verse-blocks))
5801 ((string= block-type "quote")
5802 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5803 ((string= block-type "verse")
5804 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5805 (add-text-properties beg beg1 '(face org-block-begin-line))
5806 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5807 '(face org-block-end-line))
5809 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5810 (add-text-properties
5811 beg (match-end 3)
5812 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5813 '(font-lock-fontified t invisible t)
5814 '(font-lock-fontified t face org-document-info-keyword)))
5815 (add-text-properties
5816 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5817 (if (string-equal dc1 "+title:")
5818 '(font-lock-fontified t face org-document-title)
5819 '(font-lock-fontified t face org-document-info))))
5820 ((or (equal dc1 "+results")
5821 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5822 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5823 "+call:" "+header:" "+headers:" "+name:"))
5824 (and (match-end 4) (equal dc3 "+attr")))
5825 (add-text-properties
5826 beg (match-end 0)
5827 '(font-lock-fontified t face org-meta-line))
5829 ((member dc3 '(" " ""))
5830 (add-text-properties
5831 beg (match-end 0)
5832 '(font-lock-fontified t face font-lock-comment-face)))
5833 ((not (member (char-after beg) '(?\ ?\t)))
5834 ;; just any other in-buffer setting, but not indented
5835 (add-text-properties
5836 beg (match-end 0)
5837 '(font-lock-fontified t face org-meta-line))
5839 (t nil))))))
5841 (defun org-activate-angle-links (limit)
5842 "Run through the buffer and add overlays to links."
5843 (if (and (re-search-forward org-angle-link-re limit t)
5844 (not (org-in-src-block-p)))
5845 (progn
5846 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5847 (add-text-properties (match-beginning 0) (match-end 0)
5848 (list 'mouse-face 'highlight
5849 'keymap org-mouse-map))
5850 (org-rear-nonsticky-at (match-end 0))
5851 t)))
5853 (defun org-activate-footnote-links (limit)
5854 "Run through the buffer and add overlays to footnotes."
5855 (let ((fn (org-footnote-next-reference-or-definition limit)))
5856 (when fn
5857 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5858 (org-remove-flyspell-overlays-in beg end)
5859 (add-text-properties beg end
5860 (list 'mouse-face 'highlight
5861 'keymap org-mouse-map
5862 'help-echo
5863 (if (= (point-at-bol) beg)
5864 "Footnote definition"
5865 "Footnote reference")
5866 'font-lock-fontified t
5867 'font-lock-multiline t
5868 'face 'org-footnote))))))
5870 (defun org-activate-bracket-links (limit)
5871 "Run through the buffer and add overlays to bracketed links."
5872 (if (and (re-search-forward org-bracket-link-regexp limit t)
5873 (not (org-in-src-block-p)))
5874 (let* ((hl (org-match-string-no-properties 1))
5875 (help (concat "LINK: " hl))
5876 ;; FIXME: Above we should remove the escapes. But that
5877 ;; requires another match, protecting match data, a lot
5878 ;; of overhead for font-lock.
5879 (ip (org-maybe-intangible
5880 (list 'invisible 'org-link
5881 'keymap org-mouse-map 'mouse-face 'highlight
5882 'font-lock-multiline t 'help-echo help
5883 'htmlize-link `(:uri ,hl))))
5884 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5885 'font-lock-multiline t 'help-echo help
5886 'htmlize-link `(:uri ,hl))))
5887 ;; We need to remove the invisible property here. Table narrowing
5888 ;; may have made some of this invisible.
5889 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5890 (remove-text-properties (match-beginning 0) (match-end 0)
5891 '(invisible nil))
5892 (if (match-end 3)
5893 (progn
5894 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5895 (org-rear-nonsticky-at (match-beginning 3))
5896 (add-text-properties (match-beginning 3) (match-end 3) vp)
5897 (org-rear-nonsticky-at (match-end 3))
5898 (add-text-properties (match-end 3) (match-end 0) ip)
5899 (org-rear-nonsticky-at (match-end 0)))
5900 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5901 (org-rear-nonsticky-at (match-beginning 1))
5902 (add-text-properties (match-beginning 1) (match-end 1) vp)
5903 (org-rear-nonsticky-at (match-end 1))
5904 (add-text-properties (match-end 1) (match-end 0) ip)
5905 (org-rear-nonsticky-at (match-end 0)))
5906 t)))
5908 (defun org-activate-dates (limit)
5909 "Run through the buffer and add overlays to dates."
5910 (if (and (re-search-forward org-tsr-regexp-both limit t)
5911 (not (equal (char-before (match-beginning 0)) 91)))
5912 (progn
5913 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5914 (add-text-properties (match-beginning 0) (match-end 0)
5915 (list 'mouse-face 'highlight
5916 'keymap org-mouse-map))
5917 (org-rear-nonsticky-at (match-end 0))
5918 (when org-display-custom-times
5919 (if (match-end 3)
5920 (org-display-custom-time (match-beginning 3) (match-end 3)))
5921 (org-display-custom-time (match-beginning 1) (match-end 1)))
5922 t)))
5924 (defvar org-target-link-regexp nil
5925 "Regular expression matching radio targets in plain text.")
5926 (make-variable-buffer-local 'org-target-link-regexp)
5927 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5928 "Regular expression matching a link target.")
5929 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5930 "Regular expression matching a radio target.")
5931 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5932 "Regular expression matching any target.")
5934 (defun org-activate-target-links (limit)
5935 "Run through the buffer and add overlays to target matches."
5936 (when org-target-link-regexp
5937 (let ((case-fold-search t))
5938 (if (re-search-forward org-target-link-regexp limit t)
5939 (progn
5940 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5941 (add-text-properties (match-beginning 0) (match-end 0)
5942 (list 'mouse-face 'highlight
5943 'keymap org-mouse-map
5944 'help-echo "Radio target link"
5945 'org-linked-text t))
5946 (org-rear-nonsticky-at (match-end 0))
5947 t)))))
5949 (defun org-update-radio-target-regexp ()
5950 "Find all radio targets in this file and update the regular expression."
5951 (interactive)
5952 (when (memq 'radio org-activate-links)
5953 (setq org-target-link-regexp
5954 (org-make-target-link-regexp (org-all-targets 'radio)))
5955 (org-restart-font-lock)))
5957 (defun org-hide-wide-columns (limit)
5958 (let (s e)
5959 (setq s (text-property-any (point) (or limit (point-max))
5960 'org-cwidth t))
5961 (when s
5962 (setq e (next-single-property-change s 'org-cwidth))
5963 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5964 (goto-char e)
5965 t)))
5967 (defvar org-latex-and-related-regexp nil
5968 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5969 (defvar org-match-substring-regexp)
5970 (defvar org-match-substring-with-braces-regexp)
5972 (defun org-compute-latex-and-related-regexp ()
5973 "Compute regular expression for LaTeX, entities and sub/superscript.
5974 Result depends on variable `org-highlight-latex-and-related'."
5975 (org-set-local
5976 'org-latex-and-related-regexp
5977 (let* ((re-sub
5978 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5979 ((eq org-use-sub-superscripts '{})
5980 (list org-match-substring-with-braces-regexp))
5981 (org-use-sub-superscripts (list org-match-substring-regexp))))
5982 (re-latex
5983 (when (memq 'latex org-highlight-latex-and-related)
5984 (let ((matchers (plist-get org-format-latex-options :matchers)))
5985 (delq nil
5986 (mapcar (lambda (x)
5987 (and (member (car x) matchers) (nth 1 x)))
5988 org-latex-regexps)))))
5989 (re-entities
5990 (when (memq 'entities org-highlight-latex-and-related)
5991 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5992 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5994 (defun org-do-latex-and-related (limit)
5995 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5996 LIMIT bounds the search for syntax to highlight. Stop at first
5997 highlighted object, if any. Return t if some highlighting was
5998 done, nil otherwise."
5999 (when (org-string-nw-p org-latex-and-related-regexp)
6000 (catch 'found
6001 (while (re-search-forward org-latex-and-related-regexp limit t)
6002 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6003 'face))
6004 '(org-code org-verbatim underline))
6005 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6006 '(?_ ?^))
6008 0)))
6009 (font-lock-prepend-text-property
6010 (+ offset (match-beginning 0)) (match-end 0)
6011 'face 'org-latex-and-related)
6012 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6013 '(font-lock-multiline t)))
6014 (throw 'found t)))
6015 nil)))
6017 (defun org-restart-font-lock ()
6018 "Restart `font-lock-mode', to force refontification."
6019 (when (and (boundp 'font-lock-mode) font-lock-mode)
6020 (font-lock-mode -1)
6021 (font-lock-mode 1)))
6023 (defun org-all-targets (&optional radio)
6024 "Return a list of all targets in this file.
6025 When optional argument RADIO is non-nil, only find radio
6026 targets."
6027 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6028 (save-excursion
6029 (goto-char (point-min))
6030 (while (re-search-forward re nil t)
6031 ;; Make sure point is really within the object.
6032 (backward-char)
6033 (let ((obj (org-element-context)))
6034 (when (memq (org-element-type obj) '(radio-target target))
6035 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6036 rtn)))
6038 (defun org-make-target-link-regexp (targets)
6039 "Make regular expression matching all strings in TARGETS.
6040 The regular expression finds the targets also if there is a line break
6041 between words."
6042 (and targets
6043 (concat
6044 "\\<\\("
6045 (mapconcat
6046 (lambda (x)
6047 (setq x (regexp-quote x))
6048 (while (string-match " +" x)
6049 (setq x (replace-match "\\s-+" t t x)))
6051 targets
6052 "\\|")
6053 "\\)\\>")))
6055 (defun org-activate-tags (limit)
6056 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6057 (progn
6058 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6059 (add-text-properties (match-beginning 1) (match-end 1)
6060 (list 'mouse-face 'highlight
6061 'keymap org-mouse-map))
6062 (org-rear-nonsticky-at (match-end 1))
6063 t)))
6065 (defun org-outline-level ()
6066 "Compute the outline level of the heading at point.
6067 If this is called at a normal headline, the level is the number of stars.
6068 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6069 (save-excursion
6070 (if (not (condition-case nil
6071 (org-back-to-heading t)
6072 (error nil)))
6074 (looking-at org-outline-regexp)
6075 (1- (- (match-end 0) (match-beginning 0))))))
6077 (defvar org-font-lock-keywords nil)
6079 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6080 "Regular expression matching a property line.")
6082 (defvar org-font-lock-hook nil
6083 "Functions to be called for special font lock stuff.")
6085 (defvar org-font-lock-set-keywords-hook nil
6086 "Functions that can manipulate `org-font-lock-extra-keywords'.
6087 This is called after `org-font-lock-extra-keywords' is defined, but before
6088 it is installed to be used by font lock. This can be useful if something
6089 needs to be inserted at a specific position in the font-lock sequence.")
6091 (defun org-font-lock-hook (limit)
6092 "Run `org-font-lock-hook' within LIMIT."
6093 (run-hook-with-args 'org-font-lock-hook limit))
6095 (defun org-set-font-lock-defaults ()
6096 "Set font lock defaults for the current buffer."
6097 (let* ((em org-fontify-emphasized-text)
6098 (lk org-activate-links)
6099 (org-font-lock-extra-keywords
6100 (list
6101 ;; Call the hook
6102 '(org-font-lock-hook)
6103 ;; Headlines
6104 `(,(if org-fontify-whole-heading-line
6105 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6106 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6107 (1 (org-get-level-face 1))
6108 (2 (org-get-level-face 2))
6109 (3 (org-get-level-face 3)))
6110 ;; Table lines
6111 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6112 (1 'org-table t))
6113 ;; Table internals
6114 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6115 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6116 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6117 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6118 ;; Drawers
6119 (list org-drawer-regexp '(0 'org-special-keyword t))
6120 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6121 ;; Properties
6122 (list org-property-re
6123 '(1 'org-special-keyword t)
6124 '(3 'org-property-value t))
6125 ;; Links
6126 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6127 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6128 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6129 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6130 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6131 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6132 (if (memq 'footnote lk) '(org-activate-footnote-links))
6133 ;; Targets.
6134 (list org-any-target-regexp '(0 'org-target t))
6135 ;; Diary sexps.
6136 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6137 ;; Macro
6138 '("{{{.+}}}" (0 'org-macro t))
6139 '(org-hide-wide-columns (0 nil append))
6140 ;; TODO keyword
6141 (list (format org-heading-keyword-regexp-format
6142 org-todo-regexp)
6143 '(2 (org-get-todo-face 2) t))
6144 ;; DONE
6145 (if org-fontify-done-headline
6146 (list (format org-heading-keyword-regexp-format
6147 (concat
6148 "\\(?:"
6149 (mapconcat 'regexp-quote org-done-keywords "\\|")
6150 "\\)"))
6151 '(2 'org-headline-done t))
6152 nil)
6153 ;; Priorities
6154 '(org-font-lock-add-priority-faces)
6155 ;; Tags
6156 '(org-font-lock-add-tag-faces)
6157 ;; Tags groups
6158 (if (and org-group-tags org-tag-groups-alist)
6159 (list (concat org-outline-regexp-bol ".+\\(:"
6160 (regexp-opt (mapcar 'car org-tag-groups-alist))
6161 ":\\).*$")
6162 '(1 'org-tag-group prepend)))
6163 ;; Special keywords
6164 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6165 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6166 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6167 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6168 ;; Emphasis
6169 (if em
6170 (if (featurep 'xemacs)
6171 '(org-do-emphasis-faces (0 nil append))
6172 '(org-do-emphasis-faces)))
6173 ;; Checkboxes
6174 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6175 1 'org-checkbox prepend)
6176 (if (cdr (assq 'checkbox org-list-automatic-rules))
6177 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6178 (0 (org-get-checkbox-statistics-face) t)))
6179 ;; Description list items
6180 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6181 1 'org-list-dt prepend)
6182 ;; ARCHIVEd headings
6183 (list (concat
6184 org-outline-regexp-bol
6185 "\\(.*:" org-archive-tag ":.*\\)")
6186 '(1 'org-archived prepend))
6187 ;; Specials
6188 '(org-do-latex-and-related)
6189 '(org-fontify-entities)
6190 '(org-raise-scripts)
6191 ;; Code
6192 '(org-activate-code (1 'org-code t))
6193 ;; COMMENT
6194 (list (format org-heading-keyword-regexp-format
6195 (concat "\\("
6196 org-comment-string "\\|" org-quote-string
6197 "\\)"))
6198 '(2 'org-special-keyword t))
6199 ;; Blocks and meta lines
6200 '(org-fontify-meta-lines-and-blocks)
6202 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6203 (run-hooks 'org-font-lock-set-keywords-hook)
6204 ;; Now set the full font-lock-keywords
6205 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6206 (org-set-local 'font-lock-defaults
6207 '(org-font-lock-keywords t nil nil backward-paragraph))
6208 (kill-local-variable 'font-lock-keywords) nil))
6210 (defun org-toggle-pretty-entities ()
6211 "Toggle the composition display of entities as UTF8 characters."
6212 (interactive)
6213 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6214 (org-restart-font-lock)
6215 (if org-pretty-entities
6216 (message "Entities are now displayed as UTF8 characters")
6217 (save-restriction
6218 (widen)
6219 (org-decompose-region (point-min) (point-max))
6220 (message "Entities are now displayed as plain text"))))
6222 (defvar org-custom-properties-overlays nil
6223 "List of overlays used for custom properties.")
6224 (make-variable-buffer-local 'org-custom-properties-overlays)
6226 (defun org-toggle-custom-properties-visibility ()
6227 "Display or hide properties in `org-custom-properties'."
6228 (interactive)
6229 (if org-custom-properties-overlays
6230 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6231 (setq org-custom-properties-overlays nil))
6232 (unless (not org-custom-properties)
6233 (save-excursion
6234 (save-restriction
6235 (widen)
6236 (goto-char (point-min))
6237 (while (re-search-forward org-property-re nil t)
6238 (mapc (lambda(p)
6239 (when (equal p (substring (match-string 1) 1 -1))
6240 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6241 (overlay-put o 'invisible t)
6242 (overlay-put o 'org-custom-property t)
6243 (push o org-custom-properties-overlays))))
6244 org-custom-properties)))))))
6246 (defun org-fontify-entities (limit)
6247 "Find an entity to fontify."
6248 (let (ee)
6249 (when org-pretty-entities
6250 (catch 'match
6251 (while (re-search-forward
6252 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6253 limit t)
6254 (if (and (not (org-in-indented-comment-line))
6255 (setq ee (org-entity-get (match-string 1)))
6256 (= (length (nth 6 ee)) 1))
6257 (let*
6258 ((end (if (equal (match-string 2) "{}")
6259 (match-end 2)
6260 (match-end 1))))
6261 (add-text-properties
6262 (match-beginning 0) end
6263 (list 'font-lock-fontified t))
6264 (compose-region (match-beginning 0) end
6265 (nth 6 ee) nil)
6266 (backward-char 1)
6267 (throw 'match t))))
6268 nil))))
6270 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6271 "Fontify string S like in Org-mode."
6272 (with-temp-buffer
6273 (insert s)
6274 (let ((org-odd-levels-only odd-levels))
6275 (org-mode)
6276 (font-lock-fontify-buffer)
6277 (buffer-string))))
6279 (defvar org-m nil)
6280 (defvar org-l nil)
6281 (defvar org-f nil)
6282 (defun org-get-level-face (n)
6283 "Get the right face for match N in font-lock matching of headlines."
6284 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6285 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6286 (if org-cycle-level-faces
6287 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6288 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6289 (cond
6290 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6291 ((eq n 2) org-f)
6292 (t (if org-level-color-stars-only nil org-f))))
6295 (defun org-get-todo-face (kwd)
6296 "Get the right face for a TODO keyword KWD.
6297 If KWD is a number, get the corresponding match group."
6298 (if (numberp kwd) (setq kwd (match-string kwd)))
6299 (or (org-face-from-face-or-color
6300 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6301 (and (member kwd org-done-keywords) 'org-done)
6302 'org-todo))
6304 (defun org-face-from-face-or-color (context inherit face-or-color)
6305 "Create a face list that inherits INHERIT, but sets the foreground color.
6306 When FACE-OR-COLOR is not a string, just return it."
6307 (if (stringp face-or-color)
6308 (list :inherit inherit
6309 (cdr (assoc context org-faces-easy-properties))
6310 face-or-color)
6311 face-or-color))
6313 (defun org-font-lock-add-tag-faces (limit)
6314 "Add the special tag faces."
6315 (when (and org-tag-faces org-tags-special-faces-re)
6316 (while (re-search-forward org-tags-special-faces-re limit t)
6317 (add-text-properties (match-beginning 1) (match-end 1)
6318 (list 'face (org-get-tag-face 1)
6319 'font-lock-fontified t))
6320 (backward-char 1))))
6322 (defun org-font-lock-add-priority-faces (limit)
6323 "Add the special priority faces."
6324 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6325 (when (save-match-data (org-at-heading-p))
6326 (add-text-properties
6327 (match-beginning 0) (match-end 0)
6328 (list 'face (or (org-face-from-face-or-color
6329 'priority 'org-priority
6330 (cdr (assoc (char-after (match-beginning 1))
6331 org-priority-faces)))
6332 'org-priority)
6333 'font-lock-fontified t)))))
6335 (defun org-get-tag-face (kwd)
6336 "Get the right face for a TODO keyword KWD.
6337 If KWD is a number, get the corresponding match group."
6338 (if (numberp kwd) (setq kwd (match-string kwd)))
6339 (or (org-face-from-face-or-color
6340 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6341 'org-tag))
6343 (defun org-unfontify-region (beg end &optional maybe_loudly)
6344 "Remove fontification and activation overlays from links."
6345 (font-lock-default-unfontify-region beg end)
6346 (let* ((buffer-undo-list t)
6347 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6348 (inhibit-modification-hooks t)
6349 deactivate-mark buffer-file-name buffer-file-truename)
6350 (org-decompose-region beg end)
6351 (remove-text-properties beg end
6352 '(mouse-face t keymap t org-linked-text t
6353 invisible t intangible t
6354 org-no-flyspell t org-emphasis t))
6355 (org-remove-font-lock-display-properties beg end)))
6357 (defconst org-script-display '(((raise -0.3) (height 0.7))
6358 ((raise 0.3) (height 0.7))
6359 ((raise -0.5))
6360 ((raise 0.5)))
6361 "Display properties for showing superscripts and subscripts.")
6363 (defun org-remove-font-lock-display-properties (beg end)
6364 "Remove specific display properties that have been added by font lock.
6365 The will remove the raise properties that are used to show superscripts
6366 and subscripts."
6367 (let (next prop)
6368 (while (< beg end)
6369 (setq next (next-single-property-change beg 'display nil end)
6370 prop (get-text-property beg 'display))
6371 (if (member prop org-script-display)
6372 (put-text-property beg next 'display nil))
6373 (setq beg next))))
6375 (defun org-raise-scripts (limit)
6376 "Add raise properties to sub/superscripts."
6377 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6378 (if (re-search-forward
6379 (if (eq org-use-sub-superscripts t)
6380 org-match-substring-regexp
6381 org-match-substring-with-braces-regexp)
6382 limit t)
6383 (let* ((pos (point)) table-p comment-p
6384 (mpos (match-beginning 3))
6385 (emph-p (get-text-property mpos 'org-emphasis))
6386 (link-p (get-text-property mpos 'mouse-face))
6387 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6388 (goto-char (point-at-bol))
6389 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6390 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6391 (goto-char pos)
6392 ;; Handle a_b^c
6393 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6394 (if (or comment-p emph-p link-p keyw-p)
6396 (put-text-property (match-beginning 3) (match-end 0)
6397 'display
6398 (if (equal (char-after (match-beginning 2)) ?^)
6399 (nth (if table-p 3 1) org-script-display)
6400 (nth (if table-p 2 0) org-script-display)))
6401 (add-text-properties (match-beginning 2) (match-end 2)
6402 (list 'invisible t
6403 'org-dwidth t 'org-dwidth-n 1))
6404 (if (and (eq (char-after (match-beginning 3)) ?{)
6405 (eq (char-before (match-end 3)) ?}))
6406 (progn
6407 (add-text-properties
6408 (match-beginning 3) (1+ (match-beginning 3))
6409 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6410 (add-text-properties
6411 (1- (match-end 3)) (match-end 3)
6412 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6413 t)))))
6415 ;;;; Visibility cycling, including org-goto and indirect buffer
6417 ;;; Cycling
6419 (defvar org-cycle-global-status nil)
6420 (make-variable-buffer-local 'org-cycle-global-status)
6421 (put 'org-cycle-global-status 'org-state t)
6422 (defvar org-cycle-subtree-status nil)
6423 (make-variable-buffer-local 'org-cycle-subtree-status)
6424 (put 'org-cycle-subtree-status 'org-state t)
6426 (defvar org-inlinetask-min-level)
6428 ;;;###autoload
6429 (defun org-cycle (&optional arg)
6430 "TAB-action and visibility cycling for Org-mode.
6432 This is the command invoked in Org-mode by the TAB key. Its main purpose
6433 is outline visibility cycling, but it also invokes other actions
6434 in special contexts.
6436 - When this function is called with a prefix argument, rotate the entire
6437 buffer through 3 states (global cycling)
6438 1. OVERVIEW: Show only top-level headlines.
6439 2. CONTENTS: Show all headlines of all levels, but no body text.
6440 3. SHOW ALL: Show everything.
6441 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6442 determined by the variable `org-startup-folded', and by any VISIBILITY
6443 properties in the buffer.
6444 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6445 including any drawers.
6447 - When inside a table, re-align the table and move to the next field.
6449 - When point is at the beginning of a headline, rotate the subtree started
6450 by this line through 3 different states (local cycling)
6451 1. FOLDED: Only the main headline is shown.
6452 2. CHILDREN: The main headline and the direct children are shown.
6453 From this state, you can move to one of the children
6454 and zoom in further.
6455 3. SUBTREE: Show the entire subtree, including body text.
6456 If there is no subtree, switch directly from CHILDREN to FOLDED.
6458 - When point is at the beginning of an empty headline and the variable
6459 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6460 of the headline by demoting and promoting it to likely levels. This
6461 speeds up creation document structure by pressing TAB once or several
6462 times right after creating a new headline.
6464 - When there is a numeric prefix, go up to a heading with level ARG, do
6465 a `show-subtree' and return to the previous cursor position. If ARG
6466 is negative, go up that many levels.
6468 - When point is not at the beginning of a headline, execute the global
6469 binding for TAB, which is re-indenting the line. See the option
6470 `org-cycle-emulate-tab' for details.
6472 - Special case: if point is at the beginning of the buffer and there is
6473 no headline in line 1, this function will act as if called with prefix arg
6474 (C-u TAB, same as S-TAB) also when called without prefix arg.
6475 But only if also the variable `org-cycle-global-at-bob' is t."
6476 (interactive "P")
6477 (org-load-modules-maybe)
6478 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6479 (and org-cycle-level-after-item/entry-creation
6480 (or (org-cycle-level)
6481 (org-cycle-item-indentation))))
6482 (let* (message-log-max ; Don't populate the *Messages* buffer
6483 (limit-level
6484 (or org-cycle-max-level
6485 (and (boundp 'org-inlinetask-min-level)
6486 org-inlinetask-min-level
6487 (1- org-inlinetask-min-level))))
6488 (nstars (and limit-level
6489 (if org-odd-levels-only
6490 (and limit-level (1- (* limit-level 2)))
6491 limit-level)))
6492 (org-outline-regexp
6493 (if (not (derived-mode-p 'org-mode))
6494 outline-regexp
6495 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6496 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6497 (not (looking-at org-outline-regexp))))
6498 (org-cycle-hook
6499 (if bob-special
6500 (delq 'org-optimize-window-after-visibility-change
6501 (copy-sequence org-cycle-hook))
6502 org-cycle-hook))
6503 (pos (point)))
6505 (if (or bob-special (equal arg '(4)))
6506 ;; special case: use global cycling
6507 (setq arg t))
6509 (cond
6511 ((equal arg '(16))
6512 (setq last-command 'dummy)
6513 (org-set-startup-visibility)
6514 (message "Startup visibility, plus VISIBILITY properties"))
6516 ((equal arg '(64))
6517 (show-all)
6518 (message "Entire buffer visible, including drawers"))
6520 ;; Table: enter it or move to the next field.
6521 ((org-at-table-p 'any)
6522 (if (org-at-table.el-p)
6523 (message "Use C-c ' to edit table.el tables")
6524 (if arg (org-table-edit-field t)
6525 (org-table-justify-field-maybe)
6526 (call-interactively 'org-table-next-field))))
6528 ((run-hook-with-args-until-success
6529 'org-tab-after-check-for-table-hook))
6531 ;; Global cycling: delegate to `org-cycle-internal-global'.
6532 ((eq arg t) (org-cycle-internal-global))
6534 ;; Drawers: delegate to `org-flag-drawer'.
6535 ((and org-drawers org-drawer-regexp
6536 (save-excursion
6537 (beginning-of-line 1)
6538 (looking-at org-drawer-regexp)))
6539 (org-flag-drawer ; toggle block visibility
6540 (not (get-char-property (match-end 0) 'invisible))))
6542 ;; Show-subtree, ARG levels up from here.
6543 ((integerp arg)
6544 (save-excursion
6545 (org-back-to-heading)
6546 (outline-up-heading (if (< arg 0) (- arg)
6547 (- (funcall outline-level) arg)))
6548 (org-show-subtree)))
6550 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6551 ((and (featurep 'org-inlinetask)
6552 (org-inlinetask-at-task-p)
6553 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6554 (org-inlinetask-toggle-visibility))
6556 ((org-try-cdlatex-tab))
6558 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6559 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6560 (save-excursion (beginning-of-line 1)
6561 (looking-at org-outline-regexp)))
6562 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6563 (org-cycle-internal-local))
6565 ;; From there: TAB emulation and template completion.
6566 (buffer-read-only (org-back-to-heading))
6568 ((run-hook-with-args-until-success
6569 'org-tab-after-check-for-cycling-hook))
6571 ((org-try-structure-completion))
6573 ((run-hook-with-args-until-success
6574 'org-tab-before-tab-emulation-hook))
6576 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6577 (or (not (bolp))
6578 (not (looking-at org-outline-regexp))))
6579 (call-interactively (global-key-binding "\t")))
6581 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6582 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6583 (or (and (eq org-cycle-emulate-tab 'white)
6584 (= (match-end 0) (point-at-eol)))
6585 (and (eq org-cycle-emulate-tab 'whitestart)
6586 (>= (match-end 0) pos))))
6588 (eq org-cycle-emulate-tab t))
6589 (call-interactively (global-key-binding "\t")))
6591 (t (save-excursion
6592 (org-back-to-heading)
6593 (org-cycle)))))))
6595 (defun org-cycle-internal-global ()
6596 "Do the global cycling action."
6597 ;; Hack to avoid display of messages for .org attachments in Gnus
6598 (let (message-log-max ; Don't populate the *Messages* buffer
6599 (ga (string-match "\\*fontification" (buffer-name))))
6600 (cond
6601 ((and (eq last-command this-command)
6602 (eq org-cycle-global-status 'overview))
6603 ;; We just created the overview - now do table of contents
6604 ;; This can be slow in very large buffers, so indicate action
6605 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6606 (unless ga (message "CONTENTS..."))
6607 (org-content)
6608 (unless ga (message "CONTENTS...done"))
6609 (setq org-cycle-global-status 'contents)
6610 (run-hook-with-args 'org-cycle-hook 'contents))
6612 ((and (eq last-command this-command)
6613 (eq org-cycle-global-status 'contents))
6614 ;; We just showed the table of contents - now show everything
6615 (run-hook-with-args 'org-pre-cycle-hook 'all)
6616 (show-all)
6617 (unless ga (message "SHOW ALL"))
6618 (setq org-cycle-global-status 'all)
6619 (run-hook-with-args 'org-cycle-hook 'all))
6622 ;; Default action: go to overview
6623 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6624 (org-overview)
6625 (unless ga (message "OVERVIEW"))
6626 (setq org-cycle-global-status 'overview)
6627 (run-hook-with-args 'org-cycle-hook 'overview)))))
6629 (defun org-cycle-internal-local ()
6630 "Do the local cycling action."
6631 (let (message-log-max ; Don't populate the *Messages* buffer
6632 (goal-column 0) eoh eol eos has-children children-skipped struct)
6633 ;; First, determine end of headline (EOH), end of subtree or item
6634 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6635 (save-excursion
6636 (if (org-at-item-p)
6637 (progn
6638 (beginning-of-line)
6639 (setq struct (org-list-struct))
6640 (setq eoh (point-at-eol))
6641 (setq eos (org-list-get-item-end-before-blank (point) struct))
6642 (setq has-children (org-list-has-child-p (point) struct)))
6643 (org-back-to-heading)
6644 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6645 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6646 (setq has-children
6647 (or (save-excursion
6648 (let ((level (funcall outline-level)))
6649 (outline-next-heading)
6650 (and (org-at-heading-p t)
6651 (> (funcall outline-level) level))))
6652 (save-excursion
6653 (org-list-search-forward (org-item-beginning-re) eos t)))))
6654 ;; Determine end invisible part of buffer (EOL)
6655 (beginning-of-line 2)
6656 ;; XEmacs doesn't have `next-single-char-property-change'
6657 (if (featurep 'xemacs)
6658 (while (and (not (eobp)) ;; this is like `next-line'
6659 (get-char-property (1- (point)) 'invisible))
6660 (beginning-of-line 2))
6661 (while (and (not (eobp)) ;; this is like `next-line'
6662 (get-char-property (1- (point)) 'invisible))
6663 (goto-char (next-single-char-property-change (point) 'invisible))
6664 (and (eolp) (beginning-of-line 2))))
6665 (setq eol (point)))
6666 ;; Find out what to do next and set `this-command'
6667 (cond
6668 ((= eos eoh)
6669 ;; Nothing is hidden behind this heading
6670 (unless (org-before-first-heading-p)
6671 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6672 (message "EMPTY ENTRY")
6673 (setq org-cycle-subtree-status nil)
6674 (save-excursion
6675 (goto-char eos)
6676 (outline-next-heading)
6677 (if (outline-invisible-p) (org-flag-heading nil))))
6678 ((and (or (>= eol eos)
6679 (not (string-match "\\S-" (buffer-substring eol eos))))
6680 (or has-children
6681 (not (setq children-skipped
6682 org-cycle-skip-children-state-if-no-children))))
6683 ;; Entire subtree is hidden in one line: children view
6684 (unless (org-before-first-heading-p)
6685 (run-hook-with-args 'org-pre-cycle-hook 'children))
6686 (if (org-at-item-p)
6687 (org-list-set-item-visibility (point-at-bol) struct 'children)
6688 (org-show-entry)
6689 (org-with-limited-levels (show-children))
6690 ;; FIXME: This slows down the func way too much.
6691 ;; How keep drawers hidden in subtree anyway?
6692 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6693 ;; (org-cycle-hide-drawers 'subtree))
6695 ;; Fold every list in subtree to top-level items.
6696 (when (eq org-cycle-include-plain-lists 'integrate)
6697 (save-excursion
6698 (org-back-to-heading)
6699 (while (org-list-search-forward (org-item-beginning-re) eos t)
6700 (beginning-of-line 1)
6701 (let* ((struct (org-list-struct))
6702 (prevs (org-list-prevs-alist struct))
6703 (end (org-list-get-bottom-point struct)))
6704 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6705 (org-list-get-all-items (point) struct prevs))
6706 (goto-char (if (< end eos) end eos)))))))
6707 (message "CHILDREN")
6708 (save-excursion
6709 (goto-char eos)
6710 (outline-next-heading)
6711 (if (outline-invisible-p) (org-flag-heading nil)))
6712 (setq org-cycle-subtree-status 'children)
6713 (unless (org-before-first-heading-p)
6714 (run-hook-with-args 'org-cycle-hook 'children)))
6715 ((or children-skipped
6716 (and (eq last-command this-command)
6717 (eq org-cycle-subtree-status 'children)))
6718 ;; We just showed the children, or no children are there,
6719 ;; now show everything.
6720 (unless (org-before-first-heading-p)
6721 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6722 (outline-flag-region eoh eos nil)
6723 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6724 (setq org-cycle-subtree-status 'subtree)
6725 (unless (org-before-first-heading-p)
6726 (run-hook-with-args 'org-cycle-hook 'subtree)))
6728 ;; Default action: hide the subtree.
6729 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6730 (outline-flag-region eoh eos t)
6731 (message "FOLDED")
6732 (setq org-cycle-subtree-status 'folded)
6733 (unless (org-before-first-heading-p)
6734 (run-hook-with-args 'org-cycle-hook 'folded))))))
6736 ;;;###autoload
6737 (defun org-global-cycle (&optional arg)
6738 "Cycle the global visibility. For details see `org-cycle'.
6739 With \\[universal-argument] prefix arg, switch to startup visibility.
6740 With a numeric prefix, show all headlines up to that level."
6741 (interactive "P")
6742 (let ((org-cycle-include-plain-lists
6743 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6744 (cond
6745 ((integerp arg)
6746 (show-all)
6747 (hide-sublevels arg)
6748 (setq org-cycle-global-status 'contents))
6749 ((equal arg '(4))
6750 (org-set-startup-visibility)
6751 (message "Startup visibility, plus VISIBILITY properties."))
6753 (org-cycle '(4))))))
6755 (defun org-set-startup-visibility ()
6756 "Set the visibility required by startup options and properties."
6757 (cond
6758 ((eq org-startup-folded t)
6759 (org-cycle '(4)))
6760 ((eq org-startup-folded 'content)
6761 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6762 (org-cycle '(4)) (org-cycle '(4)))))
6763 (unless (eq org-startup-folded 'showeverything)
6764 (if org-hide-block-startup (org-hide-block-all))
6765 (org-set-visibility-according-to-property 'no-cleanup)
6766 (org-cycle-hide-archived-subtrees 'all)
6767 (org-cycle-hide-drawers 'all)
6768 (org-cycle-show-empty-lines t)))
6770 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6771 "Switch subtree visibilities according to :VISIBILITY: property."
6772 (interactive)
6773 (let (org-show-entry-below state)
6774 (save-excursion
6775 (goto-char (point-min))
6776 (while (re-search-forward
6777 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6778 nil t)
6779 (setq state (match-string 1))
6780 (save-excursion
6781 (org-back-to-heading t)
6782 (hide-subtree)
6783 (org-reveal)
6784 (cond
6785 ((equal state '("fold" "folded"))
6786 (hide-subtree))
6787 ((equal state "children")
6788 (org-show-hidden-entry)
6789 (show-children))
6790 ((equal state "content")
6791 (save-excursion
6792 (save-restriction
6793 (org-narrow-to-subtree)
6794 (org-content))))
6795 ((member state '("all" "showall"))
6796 (show-subtree)))))
6797 (unless no-cleanup
6798 (org-cycle-hide-archived-subtrees 'all)
6799 (org-cycle-hide-drawers 'all)
6800 (org-cycle-show-empty-lines 'all)))))
6802 ;; This function uses outline-regexp instead of the more fundamental
6803 ;; org-outline-regexp so that org-cycle-global works outside of Org
6804 ;; buffers, where outline-regexp is needed.
6805 (defun org-overview ()
6806 "Switch to overview mode, showing only top-level headlines.
6807 Really, this shows all headlines with level equal or greater than the level
6808 of the first headline in the buffer. This is important, because if the
6809 first headline is not level one, then (hide-sublevels 1) gives confusing
6810 results."
6811 (interactive)
6812 (let ((l (org-current-line))
6813 (level (save-excursion
6814 (goto-char (point-min))
6815 (if (re-search-forward (concat "^" outline-regexp) nil t)
6816 (progn
6817 (goto-char (match-beginning 0))
6818 (funcall outline-level))))))
6819 (and level (hide-sublevels level))
6820 (recenter '(4))
6821 (org-goto-line l)))
6823 (defun org-content (&optional arg)
6824 "Show all headlines in the buffer, like a table of contents.
6825 With numerical argument N, show content up to level N."
6826 (interactive "P")
6827 (save-excursion
6828 ;; Visit all headings and show their offspring
6829 (and (integerp arg) (org-overview))
6830 (goto-char (point-max))
6831 (catch 'exit
6832 (while (and (progn (condition-case nil
6833 (outline-previous-visible-heading 1)
6834 (error (goto-char (point-min))))
6836 (looking-at org-outline-regexp))
6837 (if (integerp arg)
6838 (show-children (1- arg))
6839 (show-branches))
6840 (if (bobp) (throw 'exit nil))))))
6843 (defun org-optimize-window-after-visibility-change (state)
6844 "Adjust the window after a change in outline visibility.
6845 This function is the default value of the hook `org-cycle-hook'."
6846 (when (get-buffer-window (current-buffer))
6847 (cond
6848 ((eq state 'content) nil)
6849 ((eq state 'all) nil)
6850 ((eq state 'folded) nil)
6851 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6852 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6854 (defun org-remove-empty-overlays-at (pos)
6855 "Remove outline overlays that do not contain non-white stuff."
6856 (mapc
6857 (lambda (o)
6858 (and (eq 'outline (overlay-get o 'invisible))
6859 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6860 (overlay-end o))))
6861 (delete-overlay o)))
6862 (overlays-at pos)))
6864 (defun org-clean-visibility-after-subtree-move ()
6865 "Fix visibility issues after moving a subtree."
6866 ;; First, find a reasonable region to look at:
6867 ;; Start two siblings above, end three below
6868 (let* ((beg (save-excursion
6869 (and (org-get-last-sibling)
6870 (org-get-last-sibling))
6871 (point)))
6872 (end (save-excursion
6873 (and (org-get-next-sibling)
6874 (org-get-next-sibling)
6875 (org-get-next-sibling))
6876 (if (org-at-heading-p)
6877 (point-at-eol)
6878 (point))))
6879 (level (looking-at "\\*+"))
6880 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6881 (save-excursion
6882 (save-restriction
6883 (narrow-to-region beg end)
6884 (when re
6885 ;; Properly fold already folded siblings
6886 (goto-char (point-min))
6887 (while (re-search-forward re nil t)
6888 (if (and (not (outline-invisible-p))
6889 (save-excursion
6890 (goto-char (point-at-eol)) (outline-invisible-p)))
6891 (hide-entry))))
6892 (org-cycle-show-empty-lines 'overview)
6893 (org-cycle-hide-drawers 'overview)))))
6895 (defun org-cycle-show-empty-lines (state)
6896 "Show empty lines above all visible headlines.
6897 The region to be covered depends on STATE when called through
6898 `org-cycle-hook'. Lisp program can use t for STATE to get the
6899 entire buffer covered. Note that an empty line is only shown if there
6900 are at least `org-cycle-separator-lines' empty lines before the headline."
6901 (when (not (= org-cycle-separator-lines 0))
6902 (save-excursion
6903 (let* ((n (abs org-cycle-separator-lines))
6904 (re (cond
6905 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6906 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6907 (t (let ((ns (number-to-string (- n 2))))
6908 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6909 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6910 beg end b e)
6911 (cond
6912 ((memq state '(overview contents t))
6913 (setq beg (point-min) end (point-max)))
6914 ((memq state '(children folded))
6915 (setq beg (point) end (progn (org-end-of-subtree t t)
6916 (beginning-of-line 2)
6917 (point)))))
6918 (when beg
6919 (goto-char beg)
6920 (while (re-search-forward re end t)
6921 (unless (get-char-property (match-end 1) 'invisible)
6922 (setq e (match-end 1))
6923 (if (< org-cycle-separator-lines 0)
6924 (setq b (save-excursion
6925 (goto-char (match-beginning 0))
6926 (org-back-over-empty-lines)
6927 (if (save-excursion
6928 (goto-char (max (point-min) (1- (point))))
6929 (org-at-heading-p))
6930 (1- (point))
6931 (point))))
6932 (setq b (match-beginning 1)))
6933 (outline-flag-region b e nil)))))))
6934 ;; Never hide empty lines at the end of the file.
6935 (save-excursion
6936 (goto-char (point-max))
6937 (outline-previous-heading)
6938 (outline-end-of-heading)
6939 (if (and (looking-at "[ \t\n]+")
6940 (= (match-end 0) (point-max)))
6941 (outline-flag-region (point) (match-end 0) nil))))
6943 (defun org-show-empty-lines-in-parent ()
6944 "Move to the parent and re-show empty lines before visible headlines."
6945 (save-excursion
6946 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6947 (org-cycle-show-empty-lines context))))
6949 (defun org-files-list ()
6950 "Return `org-agenda-files' list, plus all open org-mode files.
6951 This is useful for operations that need to scan all of a user's
6952 open and agenda-wise Org files."
6953 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6954 (dolist (buf (buffer-list))
6955 (with-current-buffer buf
6956 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6957 (let ((file (expand-file-name (buffer-file-name))))
6958 (unless (member file files)
6959 (push file files))))))
6960 files))
6962 (defsubst org-entry-beginning-position ()
6963 "Return the beginning position of the current entry."
6964 (save-excursion (outline-back-to-heading t) (point)))
6966 (defsubst org-entry-end-position ()
6967 "Return the end position of the current entry."
6968 (save-excursion (outline-next-heading) (point)))
6970 (defun org-cycle-hide-drawers (state)
6971 "Re-hide all drawers after a visibility state change."
6972 (when (and (derived-mode-p 'org-mode)
6973 (not (memq state '(overview folded contents))))
6974 (save-excursion
6975 (let* ((globalp (memq state '(contents all)))
6976 (beg (if globalp (point-min) (point)))
6977 (end (if globalp (point-max)
6978 (if (eq state 'children)
6979 (save-excursion (outline-next-heading) (point))
6980 (org-end-of-subtree t)))))
6981 (goto-char beg)
6982 (while (re-search-forward org-drawer-regexp end t)
6983 (org-flag-drawer t))))))
6985 (defun org-cycle-hide-inline-tasks (state)
6986 "Re-hide inline task when switching to 'contents visibility state."
6987 (when (and (eq state 'contents)
6988 (boundp 'org-inlinetask-min-level)
6989 org-inlinetask-min-level)
6990 (hide-sublevels (1- org-inlinetask-min-level))))
6992 (defun org-flag-drawer (flag)
6993 "When FLAG is non-nil, hide the drawer we are within.
6994 Otherwise make it visible."
6995 (save-excursion
6996 (beginning-of-line 1)
6997 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6998 (let ((b (match-end 0)))
6999 (if (re-search-forward
7000 "^[ \t]*:END:"
7001 (save-excursion (outline-next-heading) (point)) t)
7002 (outline-flag-region b (point-at-eol) flag)
7003 (error ":END: line missing at position %s" b))))))
7005 (defun org-subtree-end-visible-p ()
7006 "Is the end of the current subtree visible?"
7007 (pos-visible-in-window-p
7008 (save-excursion (org-end-of-subtree t) (point))))
7010 (defun org-first-headline-recenter (&optional N)
7011 "Move cursor to the first headline and recenter the headline.
7012 Optional argument N means put the headline into the Nth line of the window."
7013 (goto-char (point-min))
7014 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7015 (beginning-of-line)
7016 (recenter (prefix-numeric-value N))))
7018 ;;; Saving and restoring visibility
7020 (defun org-outline-overlay-data (&optional use-markers)
7021 "Return a list of the locations of all outline overlays.
7022 These are overlays with the `invisible' property value `outline'.
7023 The return value is a list of cons cells, with start and stop
7024 positions for each overlay.
7025 If USE-MARKERS is set, return the positions as markers."
7026 (let (beg end)
7027 (save-excursion
7028 (save-restriction
7029 (widen)
7030 (delq nil
7031 (mapcar (lambda (o)
7032 (when (eq (overlay-get o 'invisible) 'outline)
7033 (setq beg (overlay-start o)
7034 end (overlay-end o))
7035 (and beg end (> end beg)
7036 (if use-markers
7037 (cons (move-marker (make-marker) beg)
7038 (move-marker (make-marker) end))
7039 (cons beg end)))))
7040 (overlays-in (point-min) (point-max))))))))
7042 (defun org-set-outline-overlay-data (data)
7043 "Create visibility overlays for all positions in DATA.
7044 DATA should have been made by `org-outline-overlay-data'."
7045 (let (o)
7046 (save-excursion
7047 (save-restriction
7048 (widen)
7049 (show-all)
7050 (mapc (lambda (c)
7051 (outline-flag-region (car c) (cdr c) t))
7052 data)))))
7054 ;;; Folding of blocks
7056 (defvar org-hide-block-overlays nil
7057 "Overlays hiding blocks.")
7058 (make-variable-buffer-local 'org-hide-block-overlays)
7060 (defun org-block-map (function &optional start end)
7061 "Call FUNCTION at the head of all source blocks in the current buffer.
7062 Optional arguments START and END can be used to limit the range."
7063 (let ((start (or start (point-min)))
7064 (end (or end (point-max))))
7065 (save-excursion
7066 (goto-char start)
7067 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7068 (save-excursion
7069 (save-match-data
7070 (goto-char (match-beginning 0))
7071 (funcall function)))))))
7073 (defun org-hide-block-toggle-all ()
7074 "Toggle the visibility of all blocks in the current buffer."
7075 (org-block-map #'org-hide-block-toggle))
7077 (defun org-hide-block-all ()
7078 "Fold all blocks in the current buffer."
7079 (interactive)
7080 (org-show-block-all)
7081 (org-block-map #'org-hide-block-toggle-maybe))
7083 (defun org-show-block-all ()
7084 "Unfold all blocks in the current buffer."
7085 (interactive)
7086 (mapc 'delete-overlay org-hide-block-overlays)
7087 (setq org-hide-block-overlays nil))
7089 (defun org-hide-block-toggle-maybe ()
7090 "Toggle visibility of block at point."
7091 (interactive)
7092 (let ((case-fold-search t))
7093 (if (save-excursion
7094 (beginning-of-line 1)
7095 (looking-at org-block-regexp))
7096 (progn (org-hide-block-toggle)
7097 t) ;; to signal that we took action
7098 nil))) ;; to signal that we did not
7100 (defun org-hide-block-toggle (&optional force)
7101 "Toggle the visibility of the current block."
7102 (interactive)
7103 (save-excursion
7104 (beginning-of-line)
7105 (if (re-search-forward org-block-regexp nil t)
7106 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7107 (end (match-end 0)) ;; end of entire body
7109 (if (memq t (mapcar (lambda (overlay)
7110 (eq (overlay-get overlay 'invisible)
7111 'org-hide-block))
7112 (overlays-at start)))
7113 (if (or (not force) (eq force 'off))
7114 (mapc (lambda (ov)
7115 (when (member ov org-hide-block-overlays)
7116 (setq org-hide-block-overlays
7117 (delq ov org-hide-block-overlays)))
7118 (when (eq (overlay-get ov 'invisible)
7119 'org-hide-block)
7120 (delete-overlay ov)))
7121 (overlays-at start)))
7122 (setq ov (make-overlay start end))
7123 (overlay-put ov 'invisible 'org-hide-block)
7124 ;; make the block accessible to isearch
7125 (overlay-put
7126 ov 'isearch-open-invisible
7127 (lambda (ov)
7128 (when (member ov org-hide-block-overlays)
7129 (setq org-hide-block-overlays
7130 (delq ov org-hide-block-overlays)))
7131 (when (eq (overlay-get ov 'invisible)
7132 'org-hide-block)
7133 (delete-overlay ov))))
7134 (push ov org-hide-block-overlays)))
7135 (error "Not looking at a source block"))))
7137 ;; org-tab-after-check-for-cycling-hook
7138 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7139 ;; Remove overlays when changing major mode
7140 (add-hook 'org-mode-hook
7141 (lambda () (org-add-hook 'change-major-mode-hook
7142 'org-show-block-all 'append 'local)))
7144 ;;; Org-goto
7146 (defvar org-goto-window-configuration nil)
7147 (defvar org-goto-marker nil)
7148 (defvar org-goto-map)
7149 (defun org-goto-map ()
7150 "Set the keymap `org-goto'."
7151 (setq org-goto-map
7152 (let ((map (make-sparse-keymap)))
7153 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7154 mouse-drag-region universal-argument org-occur))
7155 cmd)
7156 (while (setq cmd (pop cmds))
7157 (substitute-key-definition cmd cmd map global-map)))
7158 (suppress-keymap map)
7159 (org-defkey map "\C-m" 'org-goto-ret)
7160 (org-defkey map [(return)] 'org-goto-ret)
7161 (org-defkey map [(left)] 'org-goto-left)
7162 (org-defkey map [(right)] 'org-goto-right)
7163 (org-defkey map [(control ?g)] 'org-goto-quit)
7164 (org-defkey map "\C-i" 'org-cycle)
7165 (org-defkey map [(tab)] 'org-cycle)
7166 (org-defkey map [(down)] 'outline-next-visible-heading)
7167 (org-defkey map [(up)] 'outline-previous-visible-heading)
7168 (if org-goto-auto-isearch
7169 (if (fboundp 'define-key-after)
7170 (define-key-after map [t] 'org-goto-local-auto-isearch)
7171 nil)
7172 (org-defkey map "q" 'org-goto-quit)
7173 (org-defkey map "n" 'outline-next-visible-heading)
7174 (org-defkey map "p" 'outline-previous-visible-heading)
7175 (org-defkey map "f" 'outline-forward-same-level)
7176 (org-defkey map "b" 'outline-backward-same-level)
7177 (org-defkey map "u" 'outline-up-heading))
7178 (org-defkey map "/" 'org-occur)
7179 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7180 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7181 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7182 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7183 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7184 map)))
7186 (defconst org-goto-help
7187 "Browse buffer copy, to find location or copy text.%s
7188 RET=jump to location C-g=quit and return to previous location
7189 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7191 (defvar org-goto-start-pos) ; dynamically scoped parameter
7193 (defun org-goto (&optional alternative-interface)
7194 "Look up a different location in the current file, keeping current visibility.
7196 When you want look-up or go to a different location in a
7197 document, the fastest way is often to fold the entire buffer and
7198 then dive into the tree. This method has the disadvantage, that
7199 the previous location will be folded, which may not be what you
7200 want.
7202 This command works around this by showing a copy of the current
7203 buffer in an indirect buffer, in overview mode. You can dive
7204 into the tree in that copy, use org-occur and incremental search
7205 to find a location. When pressing RET or `Q', the command
7206 returns to the original buffer in which the visibility is still
7207 unchanged. After RET it will also jump to the location selected
7208 in the indirect buffer and expose the headline hierarchy above.
7210 With a prefix argument, use the alternative interface: e.g. if
7211 `org-goto-interface' is 'outline use 'outline-path-completion."
7212 (interactive "P")
7213 (org-goto-map)
7214 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7215 (org-refile-use-outline-path t)
7216 (org-refile-target-verify-function nil)
7217 (interface
7218 (if (not alternative-interface)
7219 org-goto-interface
7220 (if (eq org-goto-interface 'outline)
7221 'outline-path-completion
7222 'outline)))
7223 (org-goto-start-pos (point))
7224 (selected-point
7225 (if (eq interface 'outline)
7226 (car (org-get-location (current-buffer) org-goto-help))
7227 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7228 (org-refile-check-position pa)
7229 (nth 3 pa)))))
7230 (if selected-point
7231 (progn
7232 (org-mark-ring-push org-goto-start-pos)
7233 (goto-char selected-point)
7234 (if (or (outline-invisible-p) (org-invisible-p2))
7235 (org-show-context 'org-goto)))
7236 (message "Quit"))))
7238 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7239 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7240 (defvar org-goto-local-auto-isearch-map) ; defined below
7242 (defun org-get-location (buf help)
7243 "Let the user select a location in the Org-mode buffer BUF.
7244 This function uses a recursive edit. It returns the selected position
7245 or nil."
7246 (org-no-popups
7247 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7248 (isearch-hide-immediately nil)
7249 (isearch-search-fun-function
7250 (lambda () 'org-goto-local-search-headings))
7251 (org-goto-selected-point org-goto-exit-command))
7252 (save-excursion
7253 (save-window-excursion
7254 (delete-other-windows)
7255 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7256 (org-pop-to-buffer-same-window
7257 (condition-case nil
7258 (make-indirect-buffer (current-buffer) "*org-goto*")
7259 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7260 (with-output-to-temp-buffer "*Org Help*"
7261 (princ (format help (if org-goto-auto-isearch
7262 " Just type for auto-isearch."
7263 " n/p/f/b/u to navigate, q to quit."))))
7264 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7265 (setq buffer-read-only nil)
7266 (let ((org-startup-truncated t)
7267 (org-startup-folded nil)
7268 (org-startup-align-all-tables nil))
7269 (org-mode)
7270 (org-overview))
7271 (setq buffer-read-only t)
7272 (if (and (boundp 'org-goto-start-pos)
7273 (integer-or-marker-p org-goto-start-pos))
7274 (let ((org-show-hierarchy-above t)
7275 (org-show-siblings t)
7276 (org-show-following-heading t))
7277 (goto-char org-goto-start-pos)
7278 (and (outline-invisible-p) (org-show-context)))
7279 (goto-char (point-min)))
7280 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7281 (message "Select location and press RET")
7282 (use-local-map org-goto-map)
7283 (recursive-edit)))
7284 (kill-buffer "*org-goto*")
7285 (cons org-goto-selected-point org-goto-exit-command))))
7287 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7288 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7289 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7290 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7292 (defun org-goto-local-search-headings (string bound noerror)
7293 "Search and make sure that any matches are in headlines."
7294 (catch 'return
7295 (while (if isearch-forward
7296 (search-forward string bound noerror)
7297 (search-backward string bound noerror))
7298 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7299 (and (member :headline context)
7300 (not (member :tags context))))
7301 (throw 'return (point))))))
7303 (defun org-goto-local-auto-isearch ()
7304 "Start isearch."
7305 (interactive)
7306 (goto-char (point-min))
7307 (let ((keys (this-command-keys)))
7308 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7309 (isearch-mode t)
7310 (isearch-process-search-char (string-to-char keys)))))
7312 (defun org-goto-ret (&optional arg)
7313 "Finish `org-goto' by going to the new location."
7314 (interactive "P")
7315 (setq org-goto-selected-point (point)
7316 org-goto-exit-command 'return)
7317 (throw 'exit nil))
7319 (defun org-goto-left ()
7320 "Finish `org-goto' by going to the new location."
7321 (interactive)
7322 (if (org-at-heading-p)
7323 (progn
7324 (beginning-of-line 1)
7325 (setq org-goto-selected-point (point)
7326 org-goto-exit-command 'left)
7327 (throw 'exit nil))
7328 (error "Not on a heading")))
7330 (defun org-goto-right ()
7331 "Finish `org-goto' by going to the new location."
7332 (interactive)
7333 (if (org-at-heading-p)
7334 (progn
7335 (setq org-goto-selected-point (point)
7336 org-goto-exit-command 'right)
7337 (throw 'exit nil))
7338 (error "Not on a heading")))
7340 (defun org-goto-quit ()
7341 "Finish `org-goto' without cursor motion."
7342 (interactive)
7343 (setq org-goto-selected-point nil)
7344 (setq org-goto-exit-command 'quit)
7345 (throw 'exit nil))
7347 ;;; Indirect buffer display of subtrees
7349 (defvar org-indirect-dedicated-frame nil
7350 "This is the frame being used for indirect tree display.")
7351 (defvar org-last-indirect-buffer nil)
7353 (defun org-tree-to-indirect-buffer (&optional arg)
7354 "Create indirect buffer and narrow it to current subtree.
7355 With a numerical prefix ARG, go up to this level and then take that tree.
7356 If ARG is negative, go up that many levels.
7358 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7359 indirect buffer previously made with this command, to avoid proliferation of
7360 indirect buffers. However, when you call the command with a \
7361 \\[universal-argument] prefix, or
7362 when `org-indirect-buffer-display' is `new-frame', the last buffer
7363 is kept so that you can work with several indirect buffers at the same time.
7364 If `org-indirect-buffer-display' is `dedicated-frame', the \
7365 \\[universal-argument] prefix also
7366 requests that a new frame be made for the new buffer, so that the dedicated
7367 frame is not changed."
7368 (interactive "P")
7369 (let ((cbuf (current-buffer))
7370 (cwin (selected-window))
7371 (pos (point))
7372 beg end level heading ibuf)
7373 (save-excursion
7374 (org-back-to-heading t)
7375 (when (numberp arg)
7376 (setq level (org-outline-level))
7377 (if (< arg 0) (setq arg (+ level arg)))
7378 (while (> (setq level (org-outline-level)) arg)
7379 (org-up-heading-safe)))
7380 (setq beg (point)
7381 heading (org-get-heading))
7382 (org-end-of-subtree t t)
7383 (if (org-at-heading-p) (backward-char 1))
7384 (setq end (point)))
7385 (if (and (buffer-live-p org-last-indirect-buffer)
7386 (not (eq org-indirect-buffer-display 'new-frame))
7387 (not arg))
7388 (kill-buffer org-last-indirect-buffer))
7389 (setq ibuf (org-get-indirect-buffer cbuf)
7390 org-last-indirect-buffer ibuf)
7391 (cond
7392 ((or (eq org-indirect-buffer-display 'new-frame)
7393 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7394 (select-frame (make-frame))
7395 (delete-other-windows)
7396 (org-pop-to-buffer-same-window ibuf)
7397 (org-set-frame-title heading))
7398 ((eq org-indirect-buffer-display 'dedicated-frame)
7399 (raise-frame
7400 (select-frame (or (and org-indirect-dedicated-frame
7401 (frame-live-p org-indirect-dedicated-frame)
7402 org-indirect-dedicated-frame)
7403 (setq org-indirect-dedicated-frame (make-frame)))))
7404 (delete-other-windows)
7405 (org-pop-to-buffer-same-window ibuf)
7406 (org-set-frame-title (concat "Indirect: " heading)))
7407 ((eq org-indirect-buffer-display 'current-window)
7408 (org-pop-to-buffer-same-window ibuf))
7409 ((eq org-indirect-buffer-display 'other-window)
7410 (pop-to-buffer ibuf))
7411 (t (error "Invalid value")))
7412 (if (featurep 'xemacs)
7413 (save-excursion (org-mode) (turn-on-font-lock)))
7414 (narrow-to-region beg end)
7415 (show-all)
7416 (goto-char pos)
7417 (run-hook-with-args 'org-cycle-hook 'all)
7418 (and (window-live-p cwin) (select-window cwin))))
7420 (defun org-get-indirect-buffer (&optional buffer)
7421 (setq buffer (or buffer (current-buffer)))
7422 (let ((n 1) (base (buffer-name buffer)) bname)
7423 (while (buffer-live-p
7424 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7425 (setq n (1+ n)))
7426 (condition-case nil
7427 (make-indirect-buffer buffer bname 'clone)
7428 (error (make-indirect-buffer buffer bname)))))
7430 (defun org-set-frame-title (title)
7431 "Set the title of the current frame to the string TITLE."
7432 ;; FIXME: how to name a single frame in XEmacs???
7433 (unless (featurep 'xemacs)
7434 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7436 ;;;; Structure editing
7438 ;;; Inserting headlines
7440 (defun org-previous-line-empty-p (&optional next)
7441 "Is the previous line a blank line?
7442 When NEXT is non-nil, check the next line instead."
7443 (save-excursion
7444 (and (not (bobp))
7445 (or (beginning-of-line (if next 2 0)) t)
7446 (save-match-data
7447 (looking-at "[ \t]*$")))))
7449 (defun org-insert-heading (&optional arg invisible-ok)
7450 "Insert a new heading or item with same depth at point.
7451 If point is in a plain list and ARG is nil, create a new list item.
7452 With one universal prefix argument, insert a heading even in lists.
7453 With two universal prefix arguments, insert the heading at the end
7454 of the parent subtree.
7456 If point is at the beginning of a headline, insert a sibling before
7457 the current headline. If point is not at the beginning, split the line
7458 and create a new headline with the text in the current line after point
7459 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7461 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7462 This is important for non-interactive uses of the command."
7463 (interactive "P")
7464 (cond
7465 ((or (= (buffer-size) 0)
7466 (and (not (save-excursion
7467 (and (ignore-errors (org-back-to-heading invisible-ok))
7468 (org-at-heading-p))))
7469 (or arg (not (org-in-item-p)))))
7470 (insert
7471 (if (org-previous-line-empty-p) "" "\n")
7472 (if (org-in-src-block-p) ",* " "* "))
7473 (run-hooks 'org-insert-heading-hook))
7474 ((or arg (not (org-insert-item
7475 (save-excursion
7476 (beginning-of-line)
7477 (looking-at org-list-full-item-re)
7478 (match-string 3)))))
7479 (let (begn endn)
7480 (when (org-buffer-narrowed-p)
7481 (setq begn (point-min) endn (point-max))
7482 (widen))
7483 (let* ((empty-line-p nil)
7484 (eops (equal arg '(16))) ; insert at end of parent subtree
7485 (org-insert-heading-respect-content
7486 (or (not (null arg)) org-insert-heading-respect-content))
7487 (level nil)
7488 (on-heading (org-at-heading-p))
7489 (head (save-excursion
7490 (condition-case nil
7491 (progn
7492 (org-back-to-heading invisible-ok)
7493 (when (and (not on-heading)
7494 (featurep 'org-inlinetask)
7495 (integerp org-inlinetask-min-level)
7496 (>= (length (match-string 0))
7497 org-inlinetask-min-level))
7498 ;; Find a heading level before the inline task
7499 (while (and (setq level (org-up-heading-safe))
7500 (>= level org-inlinetask-min-level)))
7501 (if (org-at-heading-p)
7502 (org-back-to-heading invisible-ok)
7503 (error "This should not happen")))
7504 (unless (and (save-excursion
7505 (save-match-data
7506 (org-backward-heading-same-level 1 invisible-ok))
7507 (= (point) (match-beginning 0)))
7508 (not (org-previous-line-empty-p t)))
7509 (setq empty-line-p (org-previous-line-empty-p)))
7510 (match-string 0))
7511 (error "* "))))
7512 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7513 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7514 pos hide-previous previous-pos)
7515 (if ;; At the beginning of a heading, open a new line for insertiong
7516 (and (bolp) (org-at-heading-p)
7517 (not eops)
7518 (or (bobp)
7519 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7520 (open-line (if blank 2 1))
7521 (save-excursion
7522 (setq previous-pos (point-at-bol))
7523 (end-of-line)
7524 (setq hide-previous (outline-invisible-p)))
7525 (and org-insert-heading-respect-content
7526 (save-excursion
7527 (while (outline-invisible-p)
7528 (org-show-subtree)
7529 (org-up-heading-safe))))
7530 (let ((split
7531 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7532 (save-excursion
7533 (let ((p (point)))
7534 (goto-char (point-at-bol))
7535 (and (looking-at org-complex-heading-regexp)
7536 (match-beginning 4)
7537 (> p (match-beginning 4)))))))
7538 tags pos)
7539 (cond
7540 ;; Insert a new line, possibly at end of parent subtree
7541 (org-insert-heading-respect-content
7542 (if (not eops)
7543 (progn
7544 (org-end-of-subtree nil t)
7545 (and (looking-at "^\\*") (backward-char 1))
7546 (while (and (not (bobp))
7547 ;; Don't delete spaces in empty headlines
7548 (not (looking-back org-outline-regexp))
7549 (member (char-before) '(?\ ?\t ?\n)))
7550 (backward-delete-char 1)))
7551 (let ((p (point)))
7552 (org-up-heading-safe)
7553 (if (= p (point))
7554 (goto-char (point-max))
7555 (org-end-of-subtree nil t))))
7556 (when (featurep 'org-inlinetask)
7557 (while (and (not (eobp))
7558 (looking-at "\\(\\*+\\)[ \t]+")
7559 (>= (length (match-string 1))
7560 org-inlinetask-min-level))
7561 (org-end-of-subtree nil t)))
7562 (or (bolp) (newline))
7563 (or (org-previous-line-empty-p)
7564 (and blank (newline)))
7565 (if (or empty-line-p eops) (open-line 1)))
7566 ;; Insert a headling containing text after point
7567 ((org-at-heading-p)
7568 (when hide-previous
7569 (show-children)
7570 (org-show-entry))
7571 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7572 (setq tags (and (match-end 2) (match-string 2)))
7573 (and (match-end 1)
7574 (delete-region (match-beginning 1) (match-end 1)))
7575 (setq pos (point-at-bol))
7576 (or split (end-of-line 1))
7577 (delete-horizontal-space)
7578 (if (string-match "\\`\\*+\\'"
7579 (buffer-substring (point-at-bol) (point)))
7580 (insert " "))
7581 (newline (if blank 2 1))
7582 (when tags
7583 (save-excursion
7584 (goto-char pos)
7585 (end-of-line 1)
7586 (insert " " tags)
7587 (org-set-tags nil 'align))))
7589 (or split (end-of-line 1))
7590 (newline (if blank 2 1))))))
7591 (insert head) (just-one-space)
7592 (setq pos (point))
7593 (end-of-line 1)
7594 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7595 (when (and org-insert-heading-respect-content hide-previous)
7596 (save-excursion
7597 (goto-char previous-pos)
7598 (hide-subtree)))
7599 (when (and begn endn)
7600 (narrow-to-region (min (point) begn) (max (point) endn)))
7601 (run-hooks 'org-insert-heading-hook))))))
7603 (defun org-get-heading (&optional no-tags no-todo)
7604 "Return the heading of the current entry, without the stars.
7605 When NO-TAGS is non-nil, don't include tags.
7606 When NO-TODO is non-nil, don't include TODO keywords."
7607 (save-excursion
7608 (org-back-to-heading t)
7609 (cond
7610 ((and no-tags no-todo)
7611 (looking-at org-complex-heading-regexp)
7612 (match-string 4))
7613 (no-tags
7614 (looking-at (concat org-outline-regexp
7615 "\\(.*?\\)"
7616 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7617 (match-string 1))
7618 (no-todo
7619 (looking-at org-todo-line-regexp)
7620 (match-string 3))
7621 (t (looking-at org-heading-regexp)
7622 (match-string 2)))))
7624 (defvar orgstruct-mode) ; defined below
7626 (defun org-heading-components ()
7627 "Return the components of the current heading.
7628 This is a list with the following elements:
7629 - the level as an integer
7630 - the reduced level, different if `org-odd-levels-only' is set.
7631 - the TODO keyword, or nil
7632 - the priority character, like ?A, or nil if no priority is given
7633 - the headline text itself, or the tags string if no headline text
7634 - the tags string, or nil."
7635 (save-excursion
7636 (org-back-to-heading t)
7637 (if (let (case-fold-search)
7638 (looking-at
7639 (if orgstruct-mode
7640 org-heading-regexp
7641 org-complex-heading-regexp)))
7642 (if orgstruct-mode
7643 (list (length (match-string 1))
7644 (org-reduced-level (length (match-string 1)))
7647 (match-string 2)
7648 nil)
7649 (list (length (match-string 1))
7650 (org-reduced-level (length (match-string 1)))
7651 (org-match-string-no-properties 2)
7652 (and (match-end 3) (aref (match-string 3) 2))
7653 (org-match-string-no-properties 4)
7654 (org-match-string-no-properties 5))))))
7656 (defun org-get-entry ()
7657 "Get the entry text, after heading, entire subtree."
7658 (save-excursion
7659 (org-back-to-heading t)
7660 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7662 (defun org-insert-heading-after-current ()
7663 "Insert a new heading with same level as current, after current subtree."
7664 (interactive)
7665 (org-back-to-heading)
7666 (org-insert-heading)
7667 (org-move-subtree-down)
7668 (end-of-line 1))
7670 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7671 "Insert heading with `org-insert-heading-respect-content' set to t."
7672 (interactive "P")
7673 (let ((org-insert-heading-respect-content t))
7674 (org-insert-heading arg invisible-ok)))
7676 (defun org-insert-todo-heading-respect-content (&optional force-state)
7677 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7678 (interactive "P")
7679 (let ((org-insert-heading-respect-content t))
7680 (org-insert-todo-heading force-state t)))
7682 (defun org-insert-todo-heading (arg &optional force-heading)
7683 "Insert a new heading with the same level and TODO state as current heading.
7684 If the heading has no TODO state, or if the state is DONE, use the first
7685 state (TODO by default). Also one prefix arg, force first state. With two
7686 prefix args, force inserting at the end of the parent subtree."
7687 (interactive "P")
7688 (when (or force-heading (not (org-insert-item 'checkbox)))
7689 (org-insert-heading (or (and (equal arg '(16)) '(16))
7690 force-heading))
7691 (save-excursion
7692 (org-back-to-heading)
7693 (outline-previous-heading)
7694 (looking-at org-todo-line-regexp))
7695 (let*
7696 ((new-mark-x
7697 (if (or arg
7698 (not (match-beginning 2))
7699 (member (match-string 2) org-done-keywords))
7700 (car org-todo-keywords-1)
7701 (match-string 2)))
7702 (new-mark
7704 (run-hook-with-args-until-success
7705 'org-todo-get-default-hook new-mark-x nil)
7706 new-mark-x)))
7707 (beginning-of-line 1)
7708 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7709 (if org-treat-insert-todo-heading-as-state-change
7710 (org-todo new-mark)
7711 (insert new-mark " "))))
7712 (when org-provide-todo-statistics
7713 (org-update-parent-todo-statistics))))
7715 (defun org-insert-subheading (arg)
7716 "Insert a new subheading and demote it.
7717 Works for outline headings and for plain lists alike."
7718 (interactive "P")
7719 (org-insert-heading arg)
7720 (cond
7721 ((org-at-heading-p) (org-do-demote))
7722 ((org-at-item-p) (org-indent-item))))
7724 (defun org-insert-todo-subheading (arg)
7725 "Insert a new subheading with TODO keyword or checkbox and demote it.
7726 Works for outline headings and for plain lists alike."
7727 (interactive "P")
7728 (org-insert-todo-heading arg)
7729 (cond
7730 ((org-at-heading-p) (org-do-demote))
7731 ((org-at-item-p) (org-indent-item))))
7733 ;;; Promotion and Demotion
7735 (defvar org-after-demote-entry-hook nil
7736 "Hook run after an entry has been demoted.
7737 The cursor will be at the beginning of the entry.
7738 When a subtree is being demoted, the hook will be called for each node.")
7740 (defvar org-after-promote-entry-hook nil
7741 "Hook run after an entry has been promoted.
7742 The cursor will be at the beginning of the entry.
7743 When a subtree is being promoted, the hook will be called for each node.")
7745 (defun org-promote-subtree ()
7746 "Promote the entire subtree.
7747 See also `org-promote'."
7748 (interactive)
7749 (save-excursion
7750 (org-with-limited-levels (org-map-tree 'org-promote)))
7751 (org-fix-position-after-promote))
7753 (defun org-demote-subtree ()
7754 "Demote the entire subtree. See `org-demote'.
7755 See also `org-promote'."
7756 (interactive)
7757 (save-excursion
7758 (org-with-limited-levels (org-map-tree 'org-demote)))
7759 (org-fix-position-after-promote))
7762 (defun org-do-promote ()
7763 "Promote the current heading higher up the tree.
7764 If the region is active in `transient-mark-mode', promote all headings
7765 in the region."
7766 (interactive)
7767 (save-excursion
7768 (if (org-region-active-p)
7769 (org-map-region 'org-promote (region-beginning) (region-end))
7770 (org-promote)))
7771 (org-fix-position-after-promote))
7773 (defun org-do-demote ()
7774 "Demote the current heading lower down the tree.
7775 If the region is active in `transient-mark-mode', demote all headings
7776 in the region."
7777 (interactive)
7778 (save-excursion
7779 (if (org-region-active-p)
7780 (org-map-region 'org-demote (region-beginning) (region-end))
7781 (org-demote)))
7782 (org-fix-position-after-promote))
7784 (defun org-fix-position-after-promote ()
7785 "Make sure that after pro/demotion cursor position is right."
7786 (let ((pos (point)))
7787 (when (save-excursion
7788 (beginning-of-line 1)
7789 (looking-at org-todo-line-regexp)
7790 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7791 (cond ((eobp) (insert " "))
7792 ((eolp) (insert " "))
7793 ((equal (char-after) ?\ ) (forward-char 1))))))
7795 (defun org-current-level ()
7796 "Return the level of the current entry, or nil if before the first headline.
7797 The level is the number of stars at the beginning of the headline."
7798 (save-excursion
7799 (org-with-limited-levels
7800 (if (ignore-errors (org-back-to-heading t))
7801 (funcall outline-level)))))
7803 (defun org-get-previous-line-level ()
7804 "Return the outline depth of the last headline before the current line.
7805 Returns 0 for the first headline in the buffer, and nil if before the
7806 first headline."
7807 (let ((current-level (org-current-level))
7808 (prev-level (when (> (line-number-at-pos) 1)
7809 (save-excursion
7810 (beginning-of-line 0)
7811 (org-current-level)))))
7812 (cond ((null current-level) nil) ; Before first headline
7813 ((null prev-level) 0) ; At first headline
7814 (prev-level))))
7816 (defun org-reduced-level (l)
7817 "Compute the effective level of a heading.
7818 This takes into account the setting of `org-odd-levels-only'."
7819 (cond
7820 ((zerop l) 0)
7821 (org-odd-levels-only (1+ (floor (/ l 2))))
7822 (t l)))
7824 (defun org-level-increment ()
7825 "Return the number of stars that will be added or removed at a
7826 time to headlines when structure editing, based on the value of
7827 `org-odd-levels-only'."
7828 (if org-odd-levels-only 2 1))
7830 (defun org-get-valid-level (level &optional change)
7831 "Rectify a level change under the influence of `org-odd-levels-only'
7832 LEVEL is a current level, CHANGE is by how much the level should be
7833 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7834 even level numbers will become the next higher odd number."
7835 (if org-odd-levels-only
7836 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7837 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7838 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7839 (max 1 (+ level (or change 0)))))
7841 (if (boundp 'define-obsolete-function-alias)
7842 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7843 (define-obsolete-function-alias 'org-get-legal-level
7844 'org-get-valid-level)
7845 (define-obsolete-function-alias 'org-get-legal-level
7846 'org-get-valid-level "23.1")))
7848 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7849 ;; ̀org-with-limited-levels'
7850 (defun org-promote ()
7851 "Promote the current heading higher up the tree.
7852 If the region is active in `transient-mark-mode', promote all headings
7853 in the region."
7854 (org-back-to-heading t)
7855 (let* ((level (save-match-data (funcall outline-level)))
7856 (after-change-functions (remove 'flyspell-after-change-function
7857 after-change-functions))
7858 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7859 (diff (abs (- level (length up-head) -1))))
7860 (cond ((and (= level 1) org-called-with-limited-levels
7861 org-allow-promoting-top-level-subtree)
7862 (replace-match "# " nil t))
7863 ((= level 1)
7864 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7865 (t (replace-match up-head nil t)))
7866 ;; Fixup tag positioning
7867 (unless (= level 1)
7868 (and org-auto-align-tags (org-set-tags nil t))
7869 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7870 (run-hooks 'org-after-promote-entry-hook)))
7872 (defun org-demote ()
7873 "Demote the current heading lower down the tree.
7874 If the region is active in `transient-mark-mode', demote all headings
7875 in the region."
7876 (org-back-to-heading t)
7877 (let* ((level (save-match-data (funcall outline-level)))
7878 (after-change-functions (remove 'flyspell-after-change-function
7879 after-change-functions))
7880 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7881 (diff (abs (- level (length down-head) -1))))
7882 (replace-match down-head nil t)
7883 ;; Fixup tag positioning
7884 (and org-auto-align-tags (org-set-tags nil t))
7885 (if org-adapt-indentation (org-fixup-indentation diff))
7886 (run-hooks 'org-after-demote-entry-hook)))
7888 (defun org-cycle-level ()
7889 "Cycle the level of an empty headline through possible states.
7890 This goes first to child, then to parent, level, then up the hierarchy.
7891 After top level, it switches back to sibling level."
7892 (interactive)
7893 (let ((org-adapt-indentation nil))
7894 (when (org-point-at-end-of-empty-headline)
7895 (setq this-command 'org-cycle-level) ; Only needed for caching
7896 (let ((cur-level (org-current-level))
7897 (prev-level (org-get-previous-line-level)))
7898 (cond
7899 ;; If first headline in file, promote to top-level.
7900 ((= prev-level 0)
7901 (loop repeat (/ (- cur-level 1) (org-level-increment))
7902 do (org-do-promote)))
7903 ;; If same level as prev, demote one.
7904 ((= prev-level cur-level)
7905 (org-do-demote))
7906 ;; If parent is top-level, promote to top level if not already.
7907 ((= prev-level 1)
7908 (loop repeat (/ (- cur-level 1) (org-level-increment))
7909 do (org-do-promote)))
7910 ;; If top-level, return to prev-level.
7911 ((= cur-level 1)
7912 (loop repeat (/ (- prev-level 1) (org-level-increment))
7913 do (org-do-demote)))
7914 ;; If less than prev-level, promote one.
7915 ((< cur-level prev-level)
7916 (org-do-promote))
7917 ;; If deeper than prev-level, promote until higher than
7918 ;; prev-level.
7919 ((> cur-level prev-level)
7920 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7921 do (org-do-promote))))
7922 t))))
7924 (defun org-map-tree (fun)
7925 "Call FUN for every heading underneath the current one."
7926 (org-back-to-heading)
7927 (let ((level (funcall outline-level)))
7928 (save-excursion
7929 (funcall fun)
7930 (while (and (progn
7931 (outline-next-heading)
7932 (> (funcall outline-level) level))
7933 (not (eobp)))
7934 (funcall fun)))))
7936 (defun org-map-region (fun beg end)
7937 "Call FUN for every heading between BEG and END."
7938 (let ((org-ignore-region t))
7939 (save-excursion
7940 (setq end (copy-marker end))
7941 (goto-char beg)
7942 (if (and (re-search-forward org-outline-regexp-bol nil t)
7943 (< (point) end))
7944 (funcall fun))
7945 (while (and (progn
7946 (outline-next-heading)
7947 (< (point) end))
7948 (not (eobp)))
7949 (funcall fun)))))
7951 (defvar org-property-end-re) ; silence byte-compiler
7952 (defun org-fixup-indentation (diff)
7953 "Change the indentation in the current entry by DIFF.
7954 However, if any line in the current entry has no indentation, or if it
7955 would end up with no indentation after the change, nothing at all is done."
7956 (save-excursion
7957 (let ((end (save-excursion (outline-next-heading)
7958 (point-marker)))
7959 (prohibit (if (> diff 0)
7960 "^\\S-"
7961 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7962 col)
7963 (unless (save-excursion (end-of-line 1)
7964 (re-search-forward prohibit end t))
7965 (while (and (< (point) end)
7966 (re-search-forward "^[ \t]+" end t))
7967 (goto-char (match-end 0))
7968 (setq col (current-column))
7969 (if (< diff 0) (replace-match ""))
7970 (org-indent-to-column (+ diff col))))
7971 (move-marker end nil))))
7973 (defun org-convert-to-odd-levels ()
7974 "Convert an org-mode file with all levels allowed to one with odd levels.
7975 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7976 level 5 etc."
7977 (interactive)
7978 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7979 (let ((outline-level 'org-outline-level)
7980 (org-odd-levels-only nil) n)
7981 (save-excursion
7982 (goto-char (point-min))
7983 (while (re-search-forward "^\\*\\*+ " nil t)
7984 (setq n (- (length (match-string 0)) 2))
7985 (while (>= (setq n (1- n)) 0)
7986 (org-demote))
7987 (end-of-line 1))))))
7989 (defun org-convert-to-oddeven-levels ()
7990 "Convert an org-mode file with only odd levels to one with odd/even levels.
7991 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7992 file contains a section with an even level, conversion would
7993 destroy the structure of the file. An error is signaled in this
7994 case."
7995 (interactive)
7996 (goto-char (point-min))
7997 ;; First check if there are no even levels
7998 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7999 (org-show-context t)
8000 (error "Not all levels are odd in this file. Conversion not possible"))
8001 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8002 (let ((outline-regexp org-outline-regexp)
8003 (outline-level 'org-outline-level)
8004 (org-odd-levels-only nil) n)
8005 (save-excursion
8006 (goto-char (point-min))
8007 (while (re-search-forward "^\\*\\*+ " nil t)
8008 (setq n (/ (1- (length (match-string 0))) 2))
8009 (while (>= (setq n (1- n)) 0)
8010 (org-promote))
8011 (end-of-line 1))))))
8013 (defun org-tr-level (n)
8014 "Make N odd if required."
8015 (if org-odd-levels-only (1+ (/ n 2)) n))
8017 ;;; Vertical tree motion, cutting and pasting of subtrees
8019 (defun org-move-subtree-up (&optional arg)
8020 "Move the current subtree up past ARG headlines of the same level."
8021 (interactive "p")
8022 (org-move-subtree-down (- (prefix-numeric-value arg))))
8024 (defun org-move-subtree-down (&optional arg)
8025 "Move the current subtree down past ARG headlines of the same level."
8026 (interactive "p")
8027 (setq arg (prefix-numeric-value arg))
8028 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8029 'org-get-last-sibling))
8030 (ins-point (make-marker))
8031 (cnt (abs arg))
8032 (col (current-column))
8033 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8034 ;; Select the tree
8035 (org-back-to-heading)
8036 (setq beg0 (point))
8037 (save-excursion
8038 (setq ne-beg (org-back-over-empty-lines))
8039 (setq beg (point)))
8040 (save-match-data
8041 (save-excursion (outline-end-of-heading)
8042 (setq folded (outline-invisible-p)))
8043 (outline-end-of-subtree))
8044 (outline-next-heading)
8045 (setq ne-end (org-back-over-empty-lines))
8046 (setq end (point))
8047 (goto-char beg0)
8048 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8049 ;; include less whitespace
8050 (save-excursion
8051 (goto-char beg)
8052 (forward-line (- ne-beg ne-end))
8053 (setq beg (point))))
8054 ;; Find insertion point, with error handling
8055 (while (> cnt 0)
8056 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8057 (progn (goto-char beg0)
8058 (user-error "Cannot move past superior level or buffer limit")))
8059 (setq cnt (1- cnt)))
8060 (if (> arg 0)
8061 ;; Moving forward - still need to move over subtree
8062 (progn (org-end-of-subtree t t)
8063 (save-excursion
8064 (org-back-over-empty-lines)
8065 (or (bolp) (newline)))))
8066 (setq ne-ins (org-back-over-empty-lines))
8067 (move-marker ins-point (point))
8068 (setq txt (buffer-substring beg end))
8069 (org-save-markers-in-region beg end)
8070 (delete-region beg end)
8071 (org-remove-empty-overlays-at beg)
8072 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8073 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8074 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8075 (let ((bbb (point)))
8076 (insert-before-markers txt)
8077 (org-reinstall-markers-in-region bbb)
8078 (move-marker ins-point bbb))
8079 (or (bolp) (insert "\n"))
8080 (setq ins-end (point))
8081 (goto-char ins-point)
8082 (org-skip-whitespace)
8083 (when (and (< arg 0)
8084 (org-first-sibling-p)
8085 (> ne-ins ne-beg))
8086 ;; Move whitespace back to beginning
8087 (save-excursion
8088 (goto-char ins-end)
8089 (let ((kill-whole-line t))
8090 (kill-line (- ne-ins ne-beg)) (point)))
8091 (insert (make-string (- ne-ins ne-beg) ?\n)))
8092 (move-marker ins-point nil)
8093 (if folded
8094 (hide-subtree)
8095 (org-show-entry)
8096 (show-children)
8097 (org-cycle-hide-drawers 'children))
8098 (org-clean-visibility-after-subtree-move)
8099 ;; move back to the initial column we were at
8100 (move-to-column col)))
8102 (defvar org-subtree-clip ""
8103 "Clipboard for cut and paste of subtrees.
8104 This is actually only a copy of the kill, because we use the normal kill
8105 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8107 (defvar org-subtree-clip-folded nil
8108 "Was the last copied subtree folded?
8109 This is used to fold the tree back after pasting.")
8111 (defun org-cut-subtree (&optional n)
8112 "Cut the current subtree into the clipboard.
8113 With prefix arg N, cut this many sequential subtrees.
8114 This is a short-hand for marking the subtree and then cutting it."
8115 (interactive "p")
8116 (org-copy-subtree n 'cut))
8118 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8119 "Cut the current subtree into the clipboard.
8120 With prefix arg N, cut this many sequential subtrees.
8121 This is a short-hand for marking the subtree and then copying it.
8122 If CUT is non-nil, actually cut the subtree.
8123 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8124 of some markers in the region, even if CUT is non-nil. This is
8125 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8126 (interactive "p")
8127 (let (beg end folded (beg0 (point)))
8128 (if (org-called-interactively-p 'any)
8129 (org-back-to-heading nil) ; take what looks like a subtree
8130 (org-back-to-heading t)) ; take what is really there
8131 (setq beg (point))
8132 (skip-chars-forward " \t\r\n")
8133 (save-match-data
8134 (if nosubtrees
8135 (outline-next-heading)
8136 (save-excursion (outline-end-of-heading)
8137 (setq folded (outline-invisible-p)))
8138 (condition-case nil
8139 (org-forward-heading-same-level (1- n) t)
8140 (error nil))
8141 (org-end-of-subtree t t)))
8142 (setq end (point))
8143 (goto-char beg0)
8144 (when (> end beg)
8145 (setq org-subtree-clip-folded folded)
8146 (when (or cut force-store-markers)
8147 (org-save-markers-in-region beg end))
8148 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8149 (setq org-subtree-clip (current-kill 0))
8150 (message "%s: Subtree(s) with %d characters"
8151 (if cut "Cut" "Copied")
8152 (length org-subtree-clip)))))
8154 (defun org-paste-subtree (&optional level tree for-yank)
8155 "Paste the clipboard as a subtree, with modification of headline level.
8156 The entire subtree is promoted or demoted in order to match a new headline
8157 level.
8159 If the cursor is at the beginning of a headline, the same level as
8160 that headline is used to paste the tree.
8162 If not, the new level is derived from the *visible* headings
8163 before and after the insertion point, and taken to be the inferior headline
8164 level of the two. So if the previous visible heading is level 3 and the
8165 next is level 4 (or vice versa), level 4 will be used for insertion.
8166 This makes sure that the subtree remains an independent subtree and does
8167 not swallow low level entries.
8169 You can also force a different level, either by using a numeric prefix
8170 argument, or by inserting the heading marker by hand. For example, if the
8171 cursor is after \"*****\", then the tree will be shifted to level 5.
8173 If optional TREE is given, use this text instead of the kill ring.
8175 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8176 move back over whitespace before inserting, and move point to the end of
8177 the inserted text when done."
8178 (interactive "P")
8179 (setq tree (or tree (and kill-ring (current-kill 0))))
8180 (unless (org-kill-is-subtree-p tree)
8181 (error "%s"
8182 (substitute-command-keys
8183 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8184 (org-with-limited-levels
8185 (let* ((visp (not (outline-invisible-p)))
8186 (txt tree)
8187 (^re_ "\\(\\*+\\)[ \t]*")
8188 (old-level (if (string-match org-outline-regexp-bol txt)
8189 (- (match-end 0) (match-beginning 0) 1)
8190 -1))
8191 (force-level (cond (level (prefix-numeric-value level))
8192 ((and (looking-at "[ \t]*$")
8193 (string-match
8194 "^\\*+$" (buffer-substring
8195 (point-at-bol) (point))))
8196 (- (match-end 1) (match-beginning 1)))
8197 ((and (bolp)
8198 (looking-at org-outline-regexp))
8199 (- (match-end 0) (point) 1))))
8200 (previous-level (save-excursion
8201 (condition-case nil
8202 (progn
8203 (outline-previous-visible-heading 1)
8204 (if (looking-at ^re_)
8205 (- (match-end 0) (match-beginning 0) 1)
8207 (error 1))))
8208 (next-level (save-excursion
8209 (condition-case nil
8210 (progn
8211 (or (looking-at org-outline-regexp)
8212 (outline-next-visible-heading 1))
8213 (if (looking-at ^re_)
8214 (- (match-end 0) (match-beginning 0) 1)
8216 (error 1))))
8217 (new-level (or force-level (max previous-level next-level)))
8218 (shift (if (or (= old-level -1)
8219 (= new-level -1)
8220 (= old-level new-level))
8222 (- new-level old-level)))
8223 (delta (if (> shift 0) -1 1))
8224 (func (if (> shift 0) 'org-demote 'org-promote))
8225 (org-odd-levels-only nil)
8226 beg end newend)
8227 ;; Remove the forced level indicator
8228 (if force-level
8229 (delete-region (point-at-bol) (point)))
8230 ;; Paste
8231 (beginning-of-line (if (bolp) 1 2))
8232 (setq beg (point))
8233 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8234 (insert-before-markers txt)
8235 (unless (string-match "\n\\'" txt) (insert "\n"))
8236 (setq newend (point))
8237 (org-reinstall-markers-in-region beg)
8238 (setq end (point))
8239 (goto-char beg)
8240 (skip-chars-forward " \t\n\r")
8241 (setq beg (point))
8242 (if (and (outline-invisible-p) visp)
8243 (save-excursion (outline-show-heading)))
8244 ;; Shift if necessary
8245 (unless (= shift 0)
8246 (save-restriction
8247 (narrow-to-region beg end)
8248 (while (not (= shift 0))
8249 (org-map-region func (point-min) (point-max))
8250 (setq shift (+ delta shift)))
8251 (goto-char (point-min))
8252 (setq newend (point-max))))
8253 (when (or (org-called-interactively-p 'interactive) for-yank)
8254 (message "Clipboard pasted as level %d subtree" new-level))
8255 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8256 kill-ring
8257 (eq org-subtree-clip (current-kill 0))
8258 org-subtree-clip-folded)
8259 ;; The tree was folded before it was killed/copied
8260 (hide-subtree))
8261 (and for-yank (goto-char newend)))))
8263 (defun org-kill-is-subtree-p (&optional txt)
8264 "Check if the current kill is an outline subtree, or a set of trees.
8265 Returns nil if kill does not start with a headline, or if the first
8266 headline level is not the largest headline level in the tree.
8267 So this will actually accept several entries of equal levels as well,
8268 which is OK for `org-paste-subtree'.
8269 If optional TXT is given, check this string instead of the current kill."
8270 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8271 (re (org-get-limited-outline-regexp))
8272 (^re (concat "^" re))
8273 (start-level (and kill
8274 (string-match
8275 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8276 kill)
8277 (- (match-end 2) (match-beginning 2) 1)))
8278 (start (1+ (or (match-beginning 2) -1))))
8279 (if (not start-level)
8280 (progn
8281 nil) ;; does not even start with a heading
8282 (catch 'exit
8283 (while (setq start (string-match ^re kill (1+ start)))
8284 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8285 (throw 'exit nil)))
8286 t))))
8288 (defvar org-markers-to-move nil
8289 "Markers that should be moved with a cut-and-paste operation.
8290 Those markers are stored together with their positions relative to
8291 the start of the region.")
8293 (defun org-save-markers-in-region (beg end)
8294 "Check markers in region.
8295 If these markers are between BEG and END, record their position relative
8296 to BEG, so that after moving the block of text, we can put the markers back
8297 into place.
8298 This function gets called just before an entry or tree gets cut from the
8299 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8300 called immediately, to move the markers with the entries."
8301 (setq org-markers-to-move nil)
8302 (when (featurep 'org-clock)
8303 (org-clock-save-markers-for-cut-and-paste beg end))
8304 (when (featurep 'org-agenda)
8305 (org-agenda-save-markers-for-cut-and-paste beg end)))
8307 (defun org-check-and-save-marker (marker beg end)
8308 "Check if MARKER is between BEG and END.
8309 If yes, remember the marker and the distance to BEG."
8310 (when (and (marker-buffer marker)
8311 (equal (marker-buffer marker) (current-buffer)))
8312 (if (and (>= marker beg) (< marker end))
8313 (push (cons marker (- marker beg)) org-markers-to-move))))
8315 (defun org-reinstall-markers-in-region (beg)
8316 "Move all remembered markers to their position relative to BEG."
8317 (mapc (lambda (x)
8318 (move-marker (car x) (+ beg (cdr x))))
8319 org-markers-to-move)
8320 (setq org-markers-to-move nil))
8322 (defun org-narrow-to-subtree ()
8323 "Narrow buffer to the current subtree."
8324 (interactive)
8325 (save-excursion
8326 (save-match-data
8327 (org-with-limited-levels
8328 (narrow-to-region
8329 (progn (org-back-to-heading t) (point))
8330 (progn (org-end-of-subtree t t)
8331 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8332 (point)))))))
8334 (defun org-narrow-to-block ()
8335 "Narrow buffer to the current block."
8336 (interactive)
8337 (let* ((case-fold-search t)
8338 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8339 "^[ \t]*#\\+end_.*")))
8340 (if blockp
8341 (narrow-to-region (car blockp) (cdr blockp))
8342 (error "Not in a block"))))
8344 (eval-when-compile
8345 (defvar org-property-drawer-re))
8347 (defvar org-property-start-re) ;; defined below
8348 (defun org-clone-subtree-with-time-shift (n &optional shift)
8349 "Clone the task (subtree) at point N times.
8350 The clones will be inserted as siblings.
8352 In interactive use, the user will be prompted for the number of
8353 clones to be produced. When called with a universal prefix argument
8354 and if the entry has a timestamp, the user will also be prompted for
8355 a time shift, which may be a repeater as used in time stamps, for
8356 example `+3d'.
8358 When a valid repeater is given and the entry contains any time
8359 stamps, the clones will become a sequence in time, with time
8360 stamps in the subtree shifted for each clone produced. If SHIFT
8361 is nil or the empty string, time stamps will be left alone. The
8362 ID property of the original subtree is removed.
8364 If the original subtree did contain time stamps with a repeater,
8365 the following will happen:
8366 - the repeater will be removed in each clone
8367 - an additional clone will be produced, with the current, unshifted
8368 date(s) in the entry.
8369 - the original entry will be placed *after* all the clones, with
8370 repeater intact.
8371 - the start days in the repeater in the original entry will be shifted
8372 to past the last clone.
8373 In this way you can spell out a number of instances of a repeating task,
8374 and still retain the repeater to cover future instances of the task."
8375 (interactive "nNumber of clones to produce: ")
8376 (let ((shift
8377 (or shift
8378 (if (and (equal current-prefix-arg '(4))
8379 (save-excursion
8380 (re-search-forward org-ts-regexp-both
8381 (save-excursion
8382 (org-end-of-subtree t)
8383 (point)) t)))
8384 (read-from-minibuffer
8385 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8386 ""))) ;; No time shift
8387 (n-no-remove -1)
8388 (drawer-re org-drawer-regexp)
8389 beg end template task idprop
8390 shift-n shift-what doshift nmin nmax)
8391 (if (not (and (integerp n) (> n 0)))
8392 (error "Invalid number of replications %s" n))
8393 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8394 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8395 shift)))
8396 (error "Invalid shift specification %s" shift))
8397 (when doshift
8398 (setq shift-n (string-to-number (match-string 1 shift))
8399 shift-what (cdr (assoc (match-string 2 shift)
8400 '(("d" . day) ("w" . week)
8401 ("m" . month) ("y" . year))))))
8402 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8403 (setq nmin 1 nmax n)
8404 (org-back-to-heading t)
8405 (setq beg (point))
8406 (setq idprop (org-entry-get nil "ID"))
8407 (org-end-of-subtree t t)
8408 (or (bolp) (insert "\n"))
8409 (setq end (point))
8410 (setq template (buffer-substring beg end))
8411 (when (and doshift
8412 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8413 (delete-region beg end)
8414 (setq end beg)
8415 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8416 (goto-char end)
8417 (loop for n from nmin to nmax do
8418 ;; prepare clone
8419 (with-temp-buffer
8420 (insert template)
8421 (org-mode)
8422 (goto-char (point-min))
8423 (org-show-subtree)
8424 (and idprop (if org-clone-delete-id
8425 (org-entry-delete nil "ID")
8426 (org-id-get-create t)))
8427 (unless (= n 0)
8428 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8429 (kill-whole-line))
8430 (goto-char (point-min))
8431 (while (re-search-forward drawer-re nil t)
8432 (mapc (lambda (d)
8433 (org-remove-empty-drawer-at d (point))) org-drawers)))
8434 (goto-char (point-min))
8435 (when doshift
8436 (while (re-search-forward org-ts-regexp-both nil t)
8437 (org-timestamp-change (* n shift-n) shift-what))
8438 (unless (= n n-no-remove)
8439 (goto-char (point-min))
8440 (while (re-search-forward org-ts-regexp nil t)
8441 (save-excursion
8442 (goto-char (match-beginning 0))
8443 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8444 (delete-region (match-beginning 1) (match-end 1)))))))
8445 (setq task (buffer-string)))
8446 (insert task))
8447 (goto-char beg)))
8449 ;;; Outline Sorting
8451 (defun org-sort (with-case)
8452 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8453 Optional argument WITH-CASE means sort case-sensitively."
8454 (interactive "P")
8455 (cond
8456 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8457 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8459 (org-call-with-arg 'org-sort-entries with-case))))
8461 (defun org-sort-remove-invisible (s)
8462 "Remove invisible links from string S."
8463 (remove-text-properties 0 (length s) org-rm-props s)
8464 (while (string-match org-bracket-link-regexp s)
8465 (setq s (replace-match (if (match-end 2)
8466 (match-string 3 s)
8467 (match-string 1 s)) t t s)))
8468 (let ((st (format " %s " s)))
8469 (while (string-match org-emph-re st)
8470 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8471 (setq s (substring st 1 -1)))
8474 (defvar org-priority-regexp) ; defined later in the file
8476 (defvar org-after-sorting-entries-or-items-hook nil
8477 "Hook that is run after a bunch of entries or items have been sorted.
8478 When children are sorted, the cursor is in the parent line when this
8479 hook gets called. When a region or a plain list is sorted, the cursor
8480 will be in the first entry of the sorted region/list.")
8482 (defun org-sort-entries
8483 (&optional with-case sorting-type getkey-func compare-func property)
8484 "Sort entries on a certain level of an outline tree.
8485 If there is an active region, the entries in the region are sorted.
8486 Else, if the cursor is before the first entry, sort the top-level items.
8487 Else, the children of the entry at point are sorted.
8489 Sorting can be alphabetically, numerically, by date/time as given by
8490 a time stamp, by a property, by priority order, or by a custom function.
8492 The command prompts for the sorting type unless it has been given to the
8493 function through the SORTING-TYPE argument, which needs to be a character,
8494 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8495 precise meaning of each character:
8497 n Numerically, by converting the beginning of the entry/item to a number.
8498 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8499 o By order of TODO keywords.
8500 t By date/time, either the first active time stamp in the entry, or, if
8501 none exist, by the first inactive one.
8502 s By the scheduled date/time.
8503 d By deadline date/time.
8504 c By creation time, which is assumed to be the first inactive time stamp
8505 at the beginning of a line.
8506 p By priority according to the cookie.
8507 r By the value of a property.
8509 Capital letters will reverse the sort order.
8511 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8512 called with point at the beginning of the record. It must return either
8513 a string or a number that should serve as the sorting key for that record.
8515 Comparing entries ignores case by default. However, with an optional argument
8516 WITH-CASE, the sorting considers case as well.
8518 Sorting is done against the visible part of the headlines, it ignores hidden
8519 links."
8520 (interactive "P")
8521 (let ((case-func (if with-case 'identity 'downcase))
8522 (cmstr
8523 ;; The clock marker is lost when using `sort-subr', let's
8524 ;; store the clocking string.
8525 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8526 (save-excursion
8527 (goto-char org-clock-marker)
8528 (looking-back "^.*") (match-string-no-properties 0))))
8529 start beg end stars re re2
8530 txt what tmp)
8531 ;; Find beginning and end of region to sort
8532 (cond
8533 ((org-region-active-p)
8534 ;; we will sort the region
8535 (setq end (region-end)
8536 what "region")
8537 (goto-char (region-beginning))
8538 (if (not (org-at-heading-p)) (outline-next-heading))
8539 (setq start (point)))
8540 ((or (org-at-heading-p)
8541 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8542 ;; we will sort the children of the current headline
8543 (org-back-to-heading)
8544 (setq start (point)
8545 end (progn (org-end-of-subtree t t)
8546 (or (bolp) (insert "\n"))
8547 (org-back-over-empty-lines)
8548 (point))
8549 what "children")
8550 (goto-char start)
8551 (show-subtree)
8552 (outline-next-heading))
8554 ;; we will sort the top-level entries in this file
8555 (goto-char (point-min))
8556 (or (org-at-heading-p) (outline-next-heading))
8557 (setq start (point))
8558 (goto-char (point-max))
8559 (beginning-of-line 1)
8560 (when (looking-at ".*?\\S-")
8561 ;; File ends in a non-white line
8562 (end-of-line 1)
8563 (insert "\n"))
8564 (setq end (point-max))
8565 (setq what "top-level")
8566 (goto-char start)
8567 (show-all)))
8569 (setq beg (point))
8570 (if (>= beg end) (error "Nothing to sort"))
8572 (looking-at "\\(\\*+\\)")
8573 (setq stars (match-string 1)
8574 re (concat "^" (regexp-quote stars) " +")
8575 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8576 txt (buffer-substring beg end))
8577 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8578 (if (and (not (equal stars "*")) (string-match re2 txt))
8579 (error "Region to sort contains a level above the first entry"))
8581 (unless sorting-type
8582 (message
8583 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8584 [t]ime [s]cheduled [d]eadline [c]reated
8585 A/N/P/R/O/F/T/S/D/C means reversed:"
8586 what)
8587 (setq sorting-type (read-char-exclusive))
8589 (unless getkey-func
8590 (and (= (downcase sorting-type) ?f)
8591 (setq getkey-func
8592 (org-icompleting-read "Sort using function: "
8593 obarray 'fboundp t nil nil))
8594 (setq getkey-func (intern getkey-func))))
8596 (and (= (downcase sorting-type) ?r)
8597 (not property)
8598 (setq property
8599 (org-icompleting-read "Property: "
8600 (mapcar 'list (org-buffer-property-keys t))
8601 nil t))))
8603 (message "Sorting entries...")
8605 (save-restriction
8606 (narrow-to-region start end)
8607 (let ((dcst (downcase sorting-type))
8608 (case-fold-search nil)
8609 (now (current-time)))
8610 (sort-subr
8611 (/= dcst sorting-type)
8612 ;; This function moves to the beginning character of the "record" to
8613 ;; be sorted.
8614 (lambda nil
8615 (if (re-search-forward re nil t)
8616 (goto-char (match-beginning 0))
8617 (goto-char (point-max))))
8618 ;; This function moves to the last character of the "record" being
8619 ;; sorted.
8620 (lambda nil
8621 (save-match-data
8622 (condition-case nil
8623 (outline-forward-same-level 1)
8624 (error
8625 (goto-char (point-max))))))
8626 ;; This function returns the value that gets sorted against.
8627 (lambda nil
8628 (cond
8629 ((= dcst ?n)
8630 (if (looking-at org-complex-heading-regexp)
8631 (string-to-number (org-sort-remove-invisible (match-string 4)))
8632 nil))
8633 ((= dcst ?a)
8634 (if (looking-at org-complex-heading-regexp)
8635 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8636 nil))
8637 ((= dcst ?t)
8638 (let ((end (save-excursion (outline-next-heading) (point))))
8639 (if (or (re-search-forward org-ts-regexp end t)
8640 (re-search-forward org-ts-regexp-both end t))
8641 (org-time-string-to-seconds (match-string 0))
8642 (org-float-time now))))
8643 ((= dcst ?c)
8644 (let ((end (save-excursion (outline-next-heading) (point))))
8645 (if (re-search-forward
8646 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8647 end t)
8648 (org-time-string-to-seconds (match-string 0))
8649 (org-float-time now))))
8650 ((= dcst ?s)
8651 (let ((end (save-excursion (outline-next-heading) (point))))
8652 (if (re-search-forward org-scheduled-time-regexp end t)
8653 (org-time-string-to-seconds (match-string 1))
8654 (org-float-time now))))
8655 ((= dcst ?d)
8656 (let ((end (save-excursion (outline-next-heading) (point))))
8657 (if (re-search-forward org-deadline-time-regexp end t)
8658 (org-time-string-to-seconds (match-string 1))
8659 (org-float-time now))))
8660 ((= dcst ?p)
8661 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8662 (string-to-char (match-string 2))
8663 org-default-priority))
8664 ((= dcst ?r)
8665 (or (org-entry-get nil property) ""))
8666 ((= dcst ?o)
8667 (if (looking-at org-complex-heading-regexp)
8668 (- 9999 (length (member (match-string 2)
8669 org-todo-keywords-1)))))
8670 ((= dcst ?f)
8671 (if getkey-func
8672 (progn
8673 (setq tmp (funcall getkey-func))
8674 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8675 tmp)
8676 (error "Invalid key function `%s'" getkey-func)))
8677 (t (error "Invalid sorting type `%c'" sorting-type))))
8679 (cond
8680 ((= dcst ?a) 'string<)
8681 ((= dcst ?f) compare-func)
8682 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8683 (run-hooks 'org-after-sorting-entries-or-items-hook)
8684 ;; Reset the clock marker if needed
8685 (when cmstr
8686 (save-excursion
8687 (goto-char start)
8688 (search-forward cmstr nil t)
8689 (move-marker org-clock-marker (point))))
8690 (message "Sorting entries...done")))
8692 (defun org-do-sort (table what &optional with-case sorting-type)
8693 "Sort TABLE of WHAT according to SORTING-TYPE.
8694 The user will be prompted for the SORTING-TYPE if the call to this
8695 function does not specify it. WHAT is only for the prompt, to indicate
8696 what is being sorted. The sorting key will be extracted from
8697 the car of the elements of the table.
8698 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8699 (unless sorting-type
8700 (message
8701 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8702 what)
8703 (setq sorting-type (read-char-exclusive)))
8704 (let ((dcst (downcase sorting-type))
8705 extractfun comparefun)
8706 ;; Define the appropriate functions
8707 (cond
8708 ((= dcst ?n)
8709 (setq extractfun 'string-to-number
8710 comparefun (if (= dcst sorting-type) '< '>)))
8711 ((= dcst ?a)
8712 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8713 (lambda(x) (downcase (org-sort-remove-invisible x))))
8714 comparefun (if (= dcst sorting-type)
8715 'string<
8716 (lambda (a b) (and (not (string< a b))
8717 (not (string= a b)))))))
8718 ((= dcst ?t)
8719 (setq extractfun
8720 (lambda (x)
8721 (if (or (string-match org-ts-regexp x)
8722 (string-match org-ts-regexp-both x))
8723 (org-float-time
8724 (org-time-string-to-time (match-string 0 x)))
8726 comparefun (if (= dcst sorting-type) '< '>)))
8727 (t (error "Invalid sorting type `%c'" sorting-type)))
8729 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8730 table)
8731 (lambda (a b) (funcall comparefun (car a) (car b))))))
8734 ;;; The orgstruct minor mode
8736 ;; Define a minor mode which can be used in other modes in order to
8737 ;; integrate the org-mode structure editing commands.
8739 ;; This is really a hack, because the org-mode structure commands use
8740 ;; keys which normally belong to the major mode. Here is how it
8741 ;; works: The minor mode defines all the keys necessary to operate the
8742 ;; structure commands, but wraps the commands into a function which
8743 ;; tests if the cursor is currently at a headline or a plain list
8744 ;; item. If that is the case, the structure command is used,
8745 ;; temporarily setting many Org-mode variables like regular
8746 ;; expressions for filling etc. However, when any of those keys is
8747 ;; used at a different location, function uses `key-binding' to look
8748 ;; up if the key has an associated command in another currently active
8749 ;; keymap (minor modes, major mode, global), and executes that
8750 ;; command. There might be problems if any of the keys is otherwise
8751 ;; used as a prefix key.
8753 (defcustom orgstruct-heading-prefix-regexp nil
8754 "Regexp that matches the custom prefix of Org headlines in
8755 orgstruct(++)-mode."
8756 :group 'org
8757 :version "24.4"
8758 :package-version '(Org . "8.0")
8759 :type 'string)
8760 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8762 (defcustom orgstruct-setup-hook nil
8763 "Hook run after orgstruct-mode-map is filled."
8764 :group 'org
8765 :version "24.4"
8766 :package-version '(Org . "8.0")
8767 :type 'hook)
8769 (defvar orgstruct-initialized nil)
8771 (defvar org-local-vars nil
8772 "List of local variables, for use by `orgstruct-mode'.")
8774 ;;;###autoload
8775 (define-minor-mode orgstruct-mode
8776 "Toggle the minor mode `orgstruct-mode'.
8777 This mode is for using Org-mode structure commands in other
8778 modes. The following keys behave as if Org-mode were active, if
8779 the cursor is on a headline, or on a plain list item (both as
8780 defined by Org-mode)."
8781 nil " OrgStruct" (make-sparse-keymap)
8782 (funcall (if orgstruct-mode
8783 'add-to-invisibility-spec
8784 'remove-from-invisibility-spec)
8785 '(outline . t))
8786 (when orgstruct-mode
8787 (org-load-modules-maybe)
8788 (unless orgstruct-initialized
8789 (orgstruct-setup)
8790 (setq orgstruct-initialized t))))
8792 ;;;###autoload
8793 (defun turn-on-orgstruct ()
8794 "Unconditionally turn on `orgstruct-mode'."
8795 (orgstruct-mode 1))
8797 (defvar org-fb-vars nil)
8798 (make-variable-buffer-local 'org-fb-vars)
8799 (defun orgstruct++-mode (&optional arg)
8800 "Toggle `orgstruct-mode', the enhanced version of it.
8801 In addition to setting orgstruct-mode, this also exports all
8802 indentation and autofilling variables from org-mode into the
8803 buffer. It will also recognize item context in multiline items."
8804 (interactive "P")
8805 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8806 (if (< arg 1)
8807 (progn (orgstruct-mode -1)
8808 (mapc (lambda(v)
8809 (org-set-local (car v)
8810 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8811 org-fb-vars))
8812 (orgstruct-mode 1)
8813 (setq org-fb-vars nil)
8814 (let (var val)
8815 (mapc
8816 (lambda (x)
8817 (when (string-match
8818 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8819 (symbol-name (car x)))
8820 (setq var (car x) val (nth 1 x))
8821 (push (list var `(quote ,(eval var))) org-fb-vars)
8822 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8823 org-local-vars)
8824 (org-set-local 'orgstruct-is-++ t))))
8826 (defvar orgstruct-is-++ nil
8827 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8828 (make-variable-buffer-local 'orgstruct-is-++)
8830 ;;;###autoload
8831 (defun turn-on-orgstruct++ ()
8832 "Unconditionally turn on `orgstruct++-mode'."
8833 (orgstruct++-mode 1))
8835 (defun orgstruct-error ()
8836 "Error when there is no default binding for a structure key."
8837 (interactive)
8838 (funcall (if (fboundp 'user-error)
8839 'user-error
8840 'error)
8841 "This key has no function outside structure elements"))
8843 (defun orgstruct-setup ()
8844 "Setup orgstruct keymap."
8845 (dolist (cell '((org-demote . t)
8846 (org-metaleft . t)
8847 (org-metaright . t)
8848 (org-promote . t)
8849 (org-shiftmetaleft . t)
8850 (org-shiftmetaright . t)
8851 org-backward-element
8852 org-backward-heading-same-level
8853 org-ctrl-c-ret
8854 org-ctrl-c-minus
8855 org-ctrl-c-star
8856 org-cycle
8857 org-forward-heading-same-level
8858 org-insert-heading
8859 org-insert-heading-respect-content
8860 org-kill-note-or-show-branches
8861 org-mark-subtree
8862 org-meta-return
8863 org-metadown
8864 org-metaup
8865 org-narrow-to-subtree
8866 org-promote-subtree
8867 org-reveal
8868 org-shiftdown
8869 org-shiftleft
8870 org-shiftmetadown
8871 org-shiftmetaup
8872 org-shiftright
8873 org-shifttab
8874 org-shifttab
8875 org-shiftup
8876 org-show-subtree
8877 org-sort
8878 org-up-element
8879 outline-demote
8880 outline-next-visible-heading
8881 outline-previous-visible-heading
8882 outline-promote
8883 outline-up-heading
8884 show-children))
8885 (let ((f (or (car-safe cell) cell))
8886 (disable-when-heading-prefix (cdr-safe cell)))
8887 (when (fboundp f)
8888 (dolist (binding (nconc (where-is-internal f org-mode-map)
8889 (where-is-internal f outline-mode-map)))
8890 ;; TODO use local-function-key-map
8891 (dolist (rep '(("<tab>" . "TAB")
8892 ("<return>" . "RET")
8893 ("<escape>" . "ESC")
8894 ("<delete>" . "DEL")))
8895 (setq binding (read-kbd-macro
8896 (let ((case-fold-search))
8897 (replace-regexp-in-string
8898 (regexp-quote (cdr rep))
8899 (car rep)
8900 (key-description binding))))))
8901 (let ((key (lookup-key orgstruct-mode-map binding)))
8902 (when (or (not key) (numberp key))
8903 (condition-case nil
8904 (org-defkey orgstruct-mode-map
8905 binding
8906 (orgstruct-make-binding f binding disable-when-heading-prefix))
8907 (error nil))))))))
8908 (run-hooks 'orgstruct-setup-hook))
8910 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8911 "Create a function for binding in the structure minor mode.
8912 FUN is the command to call inside a table. KEY is the key that
8913 should be checked in for a command to execute outside of tables.
8914 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8915 if `orgstruct-heading-prefix-regexp' is non-nil."
8916 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8917 (let ((nname name)
8918 (i 0))
8919 (while (fboundp (intern nname))
8920 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8921 (setq name (intern nname)))
8922 (eval
8923 (let ((bindings '((org-heading-regexp
8924 (concat "^"
8925 orgstruct-heading-prefix-regexp
8926 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8927 (org-outline-regexp
8928 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8929 (org-outline-regexp-bol
8930 (concat "^" org-outline-regexp))
8931 (outline-regexp org-outline-regexp)
8932 (outline-heading-end-regexp "\n")
8933 (outline-level 'org-outline-level)
8934 (outline-heading-alist))))
8935 `(defun ,name (arg)
8936 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8937 "Outside of structure, run the binding of `"
8938 (key-description key) "'."
8939 (when disable-when-heading-prefix
8940 (concat
8941 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8942 "back to the default binding due to limitations of Org's implementation of\n"
8943 "`" (symbol-name fun) "'.")))
8944 (interactive "p")
8945 (let* ((disable
8946 ,(when disable-when-heading-prefix
8947 '(and orgstruct-heading-prefix-regexp
8948 (not (string= orgstruct-heading-prefix-regexp "")))))
8949 (fallback
8950 (or disable
8951 (not
8952 (let* ,bindings
8953 (org-context-p 'headline 'item
8954 ,(when (memq fun '(org-insert-heading))
8955 '(when orgstruct-is-++
8956 'item-body))))))))
8957 (if fallback
8958 (let* ((orgstruct-mode)
8959 (binding
8960 (loop with key = ,key
8961 for rep in
8962 '(nil
8963 ("<\\([^>]*\\)tab>" . "\\1TAB")
8964 ("<\\([^>]*\\)return>" . "\\1RET")
8965 ("<\\([^>]*\\)escape>" . "\\1ESC")
8966 ("<\\([^>]*\\)delete>" . "\\1DEL"))
8968 (when rep
8969 (setq key (read-kbd-macro
8970 (let ((case-fold-search))
8971 (replace-regexp-in-string
8972 (car rep)
8973 (cdr rep)
8974 (key-description key))))))
8975 thereis (key-binding key))))
8976 (if (keymapp binding)
8977 (set-temporary-overlay-map binding)
8978 (let ((func (or binding
8979 (unless disable
8980 'orgstruct-error))))
8981 (when func
8982 (call-interactively func)))))
8983 (org-run-like-in-org-mode
8984 (lambda ()
8985 (interactive)
8986 (let* ,bindings
8987 (call-interactively ',fun)))))))))
8988 name))
8990 (defun org-contextualize-keys (alist contexts)
8991 "Return valid elements in ALIST depending on CONTEXTS.
8993 `org-agenda-custom-commands' or `org-capture-templates' are the
8994 values used for ALIST, and `org-agenda-custom-commands-contexts'
8995 or `org-capture-templates-contexts' are the associated contexts
8996 definitions."
8997 (let ((contexts
8998 ;; normalize contexts
8999 (mapcar
9000 (lambda(c) (cond ((listp (cadr c))
9001 (list (car c) (car c) (cadr c)))
9002 ((string= "" (cadr c))
9003 (list (car c) (car c) (caddr c)))
9004 (t c))) contexts))
9005 (a alist) c r s)
9006 ;; loop over all commands or templates
9007 (while (setq c (pop a))
9008 (let (vrules repl)
9009 (cond
9010 ((not (assoc (car c) contexts))
9011 (push c r))
9012 ((and (assoc (car c) contexts)
9013 (setq vrules (org-contextualize-validate-key
9014 (car c) contexts)))
9015 (mapc (lambda (vr)
9016 (when (not (equal (car vr) (cadr vr)))
9017 (setq repl vr))) vrules)
9018 (if (not repl) (push c r)
9019 (push (cadr repl) s)
9020 (push
9021 (cons (car c)
9022 (cdr (or (assoc (cadr repl) alist)
9023 (error "Undefined key `%s' as contextual replacement for `%s'"
9024 (cadr repl) (car c)))))
9025 r))))))
9026 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9027 (delq
9029 (delete-dups
9030 (mapcar (lambda (x)
9031 (let ((tpl (car x)))
9032 (when (not (delq
9034 (mapcar (lambda(y)
9035 (equal y tpl)) s))) x)))
9036 (reverse r))))))
9038 (defun org-contextualize-validate-key (key contexts)
9039 "Check CONTEXTS for agenda or capture KEY."
9040 (let (r rr res)
9041 (while (setq r (pop contexts))
9042 (mapc
9043 (lambda (rr)
9044 (when
9045 (and (equal key (car r))
9046 (if (functionp rr) (funcall rr)
9047 (or (and (eq (car rr) 'in-file)
9048 (buffer-file-name)
9049 (string-match (cdr rr) (buffer-file-name)))
9050 (and (eq (car rr) 'in-mode)
9051 (string-match (cdr rr) (symbol-name major-mode)))
9052 (and (eq (car rr) 'in-buffer)
9053 (string-match (cdr rr) (buffer-name)))
9054 (when (and (eq (car rr) 'not-in-file)
9055 (buffer-file-name))
9056 (not (string-match (cdr rr) (buffer-file-name))))
9057 (when (eq (car rr) 'not-in-mode)
9058 (not (string-match (cdr rr) (symbol-name major-mode))))
9059 (when (eq (car rr) 'not-in-buffer)
9060 (not (string-match (cdr rr) (buffer-name)))))))
9061 (push r res)))
9062 (car (last r))))
9063 (delete-dups (delq nil res))))
9065 (defun org-context-p (&rest contexts)
9066 "Check if local context is any of CONTEXTS.
9067 Possible values in the list of contexts are `table', `headline', and `item'."
9068 (let ((pos (point)))
9069 (goto-char (point-at-bol))
9070 (prog1 (or (and (memq 'table contexts)
9071 (looking-at "[ \t]*|"))
9072 (and (memq 'headline contexts)
9073 (looking-at org-outline-regexp))
9074 (and (memq 'item contexts)
9075 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9076 (and (memq 'item-body contexts)
9077 (org-in-item-p)))
9078 (goto-char pos))))
9080 (defun org-get-local-variables ()
9081 "Return a list of all local variables in an Org mode buffer."
9082 (let (varlist)
9083 (with-current-buffer (get-buffer-create "*Org tmp*")
9084 (erase-buffer)
9085 (org-mode)
9086 (setq varlist (buffer-local-variables)))
9087 (kill-buffer "*Org tmp*")
9088 (delq nil
9089 (mapcar
9090 (lambda (x)
9091 (setq x
9092 (if (symbolp x)
9093 (list x)
9094 (list (car x) (cdr x))))
9095 (if (and (not (get (car x) 'org-state))
9096 (string-match
9097 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9098 (symbol-name (car x))))
9099 x nil))
9100 varlist))))
9102 (defun org-clone-local-variables (from-buffer &optional regexp)
9103 "Clone local variables from FROM-BUFFER.
9104 Optional argument REGEXP selects variables to clone."
9105 (mapc
9106 (lambda (pair)
9107 (and (symbolp (car pair))
9108 (or (null regexp)
9109 (string-match regexp (symbol-name (car pair))))
9110 (set (make-local-variable (car pair))
9111 (cdr pair))))
9112 (buffer-local-variables from-buffer)))
9114 ;;;###autoload
9115 (defun org-run-like-in-org-mode (cmd)
9116 "Run a command, pretending that the current buffer is in Org-mode.
9117 This will temporarily bind local variables that are typically bound in
9118 Org-mode to the values they have in Org-mode, and then interactively
9119 call CMD."
9120 (org-load-modules-maybe)
9121 (unless org-local-vars
9122 (setq org-local-vars (org-get-local-variables)))
9123 (let (binds)
9124 (dolist (var org-local-vars)
9125 (when (or (not (boundp (car var)))
9126 (eq (symbol-value (car var))
9127 (default-value (car var))))
9128 (push (list (car var) `(quote ,(cadr var))) binds)))
9129 (eval `(let ,binds
9130 (call-interactively (quote ,cmd))))))
9132 ;;;; Archiving
9134 (defun org-get-category (&optional pos force-refresh)
9135 "Get the category applying to position POS."
9136 (save-match-data
9137 (if force-refresh (org-refresh-category-properties))
9138 (let ((pos (or pos (point))))
9139 (or (get-text-property pos 'org-category)
9140 (progn (org-refresh-category-properties)
9141 (get-text-property pos 'org-category))))))
9143 (defun org-refresh-category-properties ()
9144 "Refresh category text properties in the buffer."
9145 (let ((case-fold-search t)
9146 (inhibit-read-only t)
9147 (def-cat (cond
9148 ((null org-category)
9149 (if buffer-file-name
9150 (file-name-sans-extension
9151 (file-name-nondirectory buffer-file-name))
9152 "???"))
9153 ((symbolp org-category) (symbol-name org-category))
9154 (t org-category)))
9155 beg end cat pos optionp)
9156 (org-with-silent-modifications
9157 (save-excursion
9158 (save-restriction
9159 (widen)
9160 (goto-char (point-min))
9161 (put-text-property (point) (point-max) 'org-category def-cat)
9162 (while (re-search-forward
9163 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9164 (setq pos (match-end 0)
9165 optionp (equal (char-after (match-beginning 0)) ?#)
9166 cat (org-trim (match-string 2)))
9167 (if optionp
9168 (setq beg (point-at-bol) end (point-max))
9169 (org-back-to-heading t)
9170 (setq beg (point) end (org-end-of-subtree t t)))
9171 (put-text-property beg end 'org-category cat)
9172 (put-text-property beg end 'org-category-position beg)
9173 (goto-char pos)))))))
9175 (defun org-refresh-properties (dprop tprop)
9176 "Refresh buffer text properties.
9177 DPROP is the drawer property and TPROP is the corresponding text
9178 property to set."
9179 (let ((case-fold-search t)
9180 (inhibit-read-only t) p)
9181 (org-with-silent-modifications
9182 (save-excursion
9183 (save-restriction
9184 (widen)
9185 (goto-char (point-min))
9186 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9187 (setq p (org-match-string-no-properties 1))
9188 (save-excursion
9189 (org-back-to-heading t)
9190 (put-text-property
9191 (point-at-bol) (point-at-eol) tprop p))))))))
9194 ;;;; Link Stuff
9196 ;;; Link abbreviations
9198 (defun org-link-expand-abbrev (link)
9199 "Apply replacements as defined in `org-link-abbrev-alist'."
9200 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9201 (let* ((key (match-string 1 link))
9202 (as (or (assoc key org-link-abbrev-alist-local)
9203 (assoc key org-link-abbrev-alist)))
9204 (tag (and (match-end 2) (match-string 3 link)))
9205 rpl)
9206 (if (not as)
9207 link
9208 (setq rpl (cdr as))
9209 (cond
9210 ((symbolp rpl) (funcall rpl tag))
9211 ((string-match "%(\\([^)]+\\))" rpl)
9212 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9213 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9214 ((string-match "%h" rpl)
9215 (replace-match (url-hexify-string (or tag "")) t t rpl))
9216 (t (concat rpl tag)))))
9217 link))
9219 ;;; Storing and inserting links
9221 (defvar org-insert-link-history nil
9222 "Minibuffer history for links inserted with `org-insert-link'.")
9224 (defvar org-stored-links nil
9225 "Contains the links stored with `org-store-link'.")
9227 (defvar org-store-link-plist nil
9228 "Plist with info about the most recently link created with `org-store-link'.")
9230 (defvar org-link-protocols nil
9231 "Link protocols added to Org-mode using `org-add-link-type'.")
9233 (defvar org-store-link-functions nil
9234 "List of functions that are called to create and store a link.
9235 Each function will be called in turn until one returns a non-nil
9236 value. Each function should check if it is responsible for creating
9237 this link (for example by looking at the major mode).
9238 If not, it must exit and return nil.
9239 If yes, it should return a non-nil value after a calling
9240 `org-store-link-props' with a list of properties and values.
9241 Special properties are:
9243 :type The link prefix, like \"http\". This must be given.
9244 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9245 This is obligatory as well.
9246 :description Optional default description for the second pair
9247 of brackets in an Org-mode link. The user can still change
9248 this when inserting this link into an Org-mode buffer.
9250 In addition to these, any additional properties can be specified
9251 and then used in capture templates.")
9253 (defun org-add-link-type (type &optional follow export)
9254 "Add TYPE to the list of `org-link-types'.
9255 Re-compute all regular expressions depending on `org-link-types'
9257 FOLLOW and EXPORT are two functions.
9259 FOLLOW should take the link path as the single argument and do whatever
9260 is necessary to follow the link, for example find a file or display
9261 a mail message.
9263 EXPORT should format the link path for export to one of the export formats.
9264 It should be a function accepting three arguments:
9266 path the path of the link, the text after the prefix (like \"http:\")
9267 desc the description of the link, if any, or a description added by
9268 org-export-normalize-links if there is none
9269 format the export format, a symbol like `html' or `latex' or `ascii'..
9271 The function may use the FORMAT information to return different values
9272 depending on the format. The return value will be put literally into
9273 the exported file. If the return value is nil, this means Org should
9274 do what it normally does with links which do not have EXPORT defined.
9276 Org-mode has a built-in default for exporting links. If you are happy with
9277 this default, there is no need to define an export function for the link
9278 type. For a simple example of an export function, see `org-bbdb.el'."
9279 (add-to-list 'org-link-types type t)
9280 (org-make-link-regexps)
9281 (if (assoc type org-link-protocols)
9282 (setcdr (assoc type org-link-protocols) (list follow export))
9283 (push (list type follow export) org-link-protocols)))
9285 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9286 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9288 ;;;###autoload
9289 (defun org-store-link (arg)
9290 "\\<org-mode-map>Store an org-link to the current location.
9291 This link is added to `org-stored-links' and can later be inserted
9292 into an org-buffer with \\[org-insert-link].
9294 For some link types, a prefix arg is interpreted.
9295 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9296 For file links, arg negates `org-context-in-file-links'.
9298 A double prefix arg force skipping storing functions that are not
9299 part of Org's core.
9301 A triple prefix arg force storing a link for each line in the
9302 active region."
9303 (interactive "P")
9304 (org-load-modules-maybe)
9305 (if (and (equal arg '(64)) (org-region-active-p))
9306 (save-excursion
9307 (let ((end (region-end)))
9308 (goto-char (region-beginning))
9309 (set-mark (point))
9310 (while (< (point-at-eol) end)
9311 (move-end-of-line 1) (activate-mark)
9312 (let (current-prefix-arg)
9313 (call-interactively 'org-store-link))
9314 (move-beginning-of-line 2)
9315 (set-mark (point)))))
9316 (org-with-limited-levels
9317 (setq org-store-link-plist nil)
9318 (let (link cpltxt desc description search
9319 txt custom-id agenda-link sfuns sfunsn)
9320 (cond
9322 ;; Store a link using an external link type
9323 ((and (not (equal arg '(16)))
9324 (setq sfuns
9325 (delq
9326 nil (mapcar (lambda (f)
9327 (let (fs) (if (funcall f) (push f fs))))
9328 org-store-link-functions))
9329 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9330 (or (and (cdr sfuns)
9331 (funcall (intern
9332 (completing-read
9333 "Which function for creating the link? "
9334 sfunsn t (car sfunsn)))))
9335 (funcall (caar sfuns)))
9336 (setq link (plist-get org-store-link-plist :link)
9337 desc (or (plist-get org-store-link-plist
9338 :description) link))))
9340 ;; Store a link from a source code buffer
9341 ((org-src-edit-buffer-p)
9342 (let (label gc)
9343 (while (or (not label)
9344 (save-excursion
9345 (save-restriction
9346 (widen)
9347 (goto-char (point-min))
9348 (re-search-forward
9349 (regexp-quote (format org-coderef-label-format label))
9350 nil t))))
9351 (when label (message "Label exists already") (sit-for 2))
9352 (setq label (read-string "Code line label: " label)))
9353 (end-of-line 1)
9354 (setq link (format org-coderef-label-format label))
9355 (setq gc (- 79 (length link)))
9356 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9357 (insert link)
9358 (setq link (concat "(" label ")") desc nil)))
9360 ;; We are in the agenda, link to referenced location
9361 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9362 (let ((m (or (get-text-property (point) 'org-hd-marker)
9363 (get-text-property (point) 'org-marker))))
9364 (when m
9365 (org-with-point-at m
9366 (setq agenda-link
9367 (if (org-called-interactively-p 'any)
9368 (call-interactively 'org-store-link)
9369 (org-store-link nil)))))))
9371 ((eq major-mode 'calendar-mode)
9372 (let ((cd (calendar-cursor-to-date)))
9373 (setq link
9374 (format-time-string
9375 (car org-time-stamp-formats)
9376 (apply 'encode-time
9377 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9378 nil nil nil))))
9379 (org-store-link-props :type "calendar" :date cd)))
9381 ((eq major-mode 'help-mode)
9382 (setq link (concat "help:" (save-excursion
9383 (goto-char (point-min))
9384 (looking-at "^[^ ]+")
9385 (match-string 0))))
9386 (org-store-link-props :type "help"))
9388 ((eq major-mode 'w3-mode)
9389 (setq cpltxt (if (and (buffer-name)
9390 (not (string-match "Untitled" (buffer-name))))
9391 (buffer-name)
9392 (url-view-url t))
9393 link (url-view-url t))
9394 (org-store-link-props :type "w3" :url (url-view-url t)))
9396 ((eq major-mode 'image-mode)
9397 (setq cpltxt (concat "file:"
9398 (abbreviate-file-name buffer-file-name))
9399 link cpltxt)
9400 (org-store-link-props :type "image" :file buffer-file-name))
9402 ;; In dired, store a link to the file of the current line
9403 ((eq major-mode 'dired-mode)
9404 (let ((file (dired-get-filename nil t)))
9405 (setq file (if file
9406 (abbreviate-file-name
9407 (expand-file-name (dired-get-filename nil t)))
9408 ;; otherwise, no file so use current directory.
9409 default-directory))
9410 (setq cpltxt (concat "file:" file)
9411 link cpltxt)))
9413 ((setq search (run-hook-with-args-until-success
9414 'org-create-file-search-functions))
9415 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9416 "::" search))
9417 (setq cpltxt (or description link)))
9419 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9420 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9421 (cond
9422 ;; Store a link using the radio target at point
9423 ((org-in-regexp "<<\\(.*?\\)>>")
9424 (setq cpltxt
9425 (concat "file:"
9426 (abbreviate-file-name
9427 (buffer-file-name (buffer-base-buffer)))
9428 "::" (match-string 1))
9429 link cpltxt))
9430 ((and (featurep 'org-id)
9431 (or (eq org-id-link-to-org-use-id t)
9432 (and (org-called-interactively-p 'any)
9433 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9434 (and (eq org-id-link-to-org-use-id
9435 'create-if-interactive-and-no-custom-id)
9436 (not custom-id))))
9437 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9438 ;; Store a link using the ID at point
9439 (setq link (condition-case nil
9440 (prog1 (org-id-store-link)
9441 (setq desc (plist-get org-store-link-plist
9442 :description)))
9443 (error
9444 ;; Probably before first headline, link only to file
9445 (concat "file:"
9446 (abbreviate-file-name
9447 (buffer-file-name (buffer-base-buffer))))))))
9449 ;; Just link to current headline
9450 (setq cpltxt (concat "file:"
9451 (abbreviate-file-name
9452 (buffer-file-name (buffer-base-buffer)))))
9453 ;; Add a context search string
9454 (when (org-xor org-context-in-file-links arg)
9455 (let* ((ee (org-element-at-point))
9456 (et (org-element-type ee))
9457 (ev (plist-get (cadr ee) :value))
9458 (ek (plist-get (cadr ee) :key))
9459 (eok (and (stringp ek) (string-match "name\\|target" ek))))
9460 (setq txt (cond
9461 ((org-at-heading-p) nil)
9462 ((and (eq et 'keyword) eok) ev)
9463 ((org-region-active-p)
9464 (buffer-substring (region-beginning) (region-end)))))
9465 (when (or (null txt) (string-match "\\S-" txt))
9466 (setq cpltxt
9467 (concat cpltxt "::"
9468 (condition-case nil
9469 (org-make-org-heading-search-string txt)
9470 (error "")))
9471 desc (or (and (eq et 'keyword) eok ev)
9472 (nth 4 (ignore-errors (org-heading-components)))
9473 "NONE")))))
9474 (if (string-match "::\\'" cpltxt)
9475 (setq cpltxt (substring cpltxt 0 -2)))
9476 (setq link cpltxt))))
9478 ((buffer-file-name (buffer-base-buffer))
9479 ;; Just link to this file here.
9480 (setq cpltxt (concat "file:"
9481 (abbreviate-file-name
9482 (buffer-file-name (buffer-base-buffer)))))
9483 ;; Add a context string.
9484 (when (org-xor org-context-in-file-links arg)
9485 (setq txt (if (org-region-active-p)
9486 (buffer-substring (region-beginning) (region-end))
9487 (buffer-substring (point-at-bol) (point-at-eol))))
9488 ;; Only use search option if there is some text.
9489 (when (string-match "\\S-" txt)
9490 (setq cpltxt
9491 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9492 desc "NONE")))
9493 (setq link cpltxt))
9495 ((org-called-interactively-p 'interactive)
9496 (user-error "No method for storing a link from this buffer"))
9498 (t (setq link nil)))
9500 ;; We're done setting link and desc, clean up
9501 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9502 (setq link (or link cpltxt)
9503 desc (or desc cpltxt))
9504 (cond ((equal desc "NONE") (setq desc nil))
9505 ((string-match org-bracket-link-regexp desc)
9506 (setq desc
9507 (replace-regexp-in-string
9508 org-bracket-link-regexp
9509 (concat "\\3" (if (equal (length (match-string 0 desc))
9510 (length desc)) "*" "")) desc))))
9512 ;; Return the link
9513 (if (not (and (or (org-called-interactively-p 'any)
9514 executing-kbd-macro) link))
9515 (or agenda-link (and link (org-make-link-string link desc)))
9516 (push (list link desc) org-stored-links)
9517 (message "Stored: %s" (or desc link))
9518 (when custom-id
9519 (setq link (concat "file:" (abbreviate-file-name
9520 (buffer-file-name)) "::#" custom-id))
9521 (push (list link desc) org-stored-links)))))))
9523 (defun org-store-link-props (&rest plist)
9524 "Store link properties, extract names and addresses."
9525 (let (x adr)
9526 (when (setq x (plist-get plist :from))
9527 (setq adr (mail-extract-address-components x))
9528 (setq plist (plist-put plist :fromname (car adr)))
9529 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9530 (when (setq x (plist-get plist :to))
9531 (setq adr (mail-extract-address-components x))
9532 (setq plist (plist-put plist :toname (car adr)))
9533 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9534 (let ((from (plist-get plist :from))
9535 (to (plist-get plist :to)))
9536 (when (and from to org-from-is-user-regexp)
9537 (setq plist
9538 (plist-put plist :fromto
9539 (if (string-match org-from-is-user-regexp from)
9540 (concat "to %t")
9541 (concat "from %f"))))))
9542 (setq org-store-link-plist plist))
9544 (defun org-add-link-props (&rest plist)
9545 "Add these properties to the link property list."
9546 (let (key value)
9547 (while plist
9548 (setq key (pop plist) value (pop plist))
9549 (setq org-store-link-plist
9550 (plist-put org-store-link-plist key value)))))
9552 (defun org-email-link-description (&optional fmt)
9553 "Return the description part of an email link.
9554 This takes information from `org-store-link-plist' and formats it
9555 according to FMT (default from `org-email-link-description-format')."
9556 (setq fmt (or fmt org-email-link-description-format))
9557 (let* ((p org-store-link-plist)
9558 (to (plist-get p :toaddress))
9559 (from (plist-get p :fromaddress))
9560 (table
9561 (list
9562 (cons "%c" (plist-get p :fromto))
9563 (cons "%F" (plist-get p :from))
9564 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9565 (cons "%T" (plist-get p :to))
9566 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9567 (cons "%s" (plist-get p :subject))
9568 (cons "%d" (plist-get p :date))
9569 (cons "%m" (plist-get p :message-id)))))
9570 (when (string-match "%c" fmt)
9571 ;; Check if the user wrote this message
9572 (if (and org-from-is-user-regexp from to
9573 (save-match-data (string-match org-from-is-user-regexp from)))
9574 (setq fmt (replace-match "to %t" t t fmt))
9575 (setq fmt (replace-match "from %f" t t fmt))))
9576 (org-replace-escapes fmt table)))
9578 (defun org-make-org-heading-search-string (&optional string)
9579 "Make search string for the current headline or STRING."
9580 (let ((s (or string
9581 (and (derived-mode-p 'org-mode)
9582 (save-excursion
9583 (org-back-to-heading t)
9584 (org-element-property :raw-value (org-element-at-point))))))
9585 (lines org-context-in-file-links))
9586 (or string (setq s (concat "*" s))) ; Add * for headlines
9587 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9588 (when (and string (integerp lines) (> lines 0))
9589 (let ((slines (org-split-string s "\n")))
9590 (when (< lines (length slines))
9591 (setq s (mapconcat
9592 'identity
9593 (reverse (nthcdr (- (length slines) lines)
9594 (reverse slines))) "\n")))))
9595 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9597 (defun org-make-link-string (link &optional description)
9598 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9599 (unless (string-match "\\S-" link)
9600 (error "Empty link"))
9601 (when (and description
9602 (stringp description)
9603 (not (string-match "\\S-" description)))
9604 (setq description nil))
9605 (when (stringp description)
9606 ;; Remove brackets from the description, they are fatal.
9607 (while (string-match "\\[" description)
9608 (setq description (replace-match "{" t t description)))
9609 (while (string-match "\\]" description)
9610 (setq description (replace-match "}" t t description))))
9611 (when (equal link description)
9612 ;; No description needed, it is identical
9613 (setq description nil))
9614 (when (and (not description)
9615 (not (string-match (org-image-file-name-regexp) link))
9616 (not (equal link (org-link-escape link))))
9617 (setq description (org-extract-attributes link)))
9618 (setq link
9619 (cond ((string-match (org-image-file-name-regexp) link) link)
9620 ((string-match org-link-types-re link)
9621 (concat (match-string 1 link)
9622 (org-link-escape (substring link (match-end 1)))))
9623 (t (org-link-escape link))))
9624 (concat "[[" link "]"
9625 (if description (concat "[" description "]") "")
9626 "]"))
9628 (defconst org-link-escape-chars
9629 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9630 "List of characters that should be escaped in link.
9631 This is the list that is used for internal purposes.")
9633 (defconst org-link-escape-chars-browser
9634 '(?\ )
9635 "List of escapes for characters that are problematic in links.
9636 This is the list that is used before handing over to the browser.")
9638 (defun org-link-escape (text &optional table merge)
9639 "Return percent escaped representation of TEXT.
9640 TEXT is a string with the text to escape.
9641 Optional argument TABLE is a list with characters that should be
9642 escaped. When nil, `org-link-escape-chars' is used.
9643 If optional argument MERGE is set, merge TABLE into
9644 `org-link-escape-chars'."
9645 (cond
9646 ((and table merge)
9647 (mapc (lambda (defchr)
9648 (unless (member defchr table)
9649 (setq table (cons defchr table)))) org-link-escape-chars))
9650 ((null table)
9651 (setq table org-link-escape-chars)))
9652 (mapconcat
9653 (lambda (char)
9654 (if (or (member char table)
9655 (and (or (< char 32) (= char 37) (> char 126))
9656 org-url-hexify-p))
9657 (mapconcat (lambda (sequence-element)
9658 (format "%%%.2X" sequence-element))
9659 (or (encode-coding-char char 'utf-8)
9660 (error "Unable to percent escape character: %s"
9661 (char-to-string char))) "")
9662 (char-to-string char))) text ""))
9664 (defun org-link-unescape (str)
9665 "Unhex hexified Unicode strings as returned from the JavaScript function
9666 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9667 (unless (and (null str) (string= "" str))
9668 (let ((pos 0) (case-fold-search t) unhexed)
9669 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9670 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9671 (setq str (replace-match unhexed t t str))
9672 (setq pos (+ pos (length unhexed))))))
9673 str)
9675 (defun org-link-unescape-compound (hex)
9676 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9677 Note: this function also decodes single byte encodings like
9678 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9679 (save-match-data
9680 (let* ((bytes (cdr (split-string hex "%")))
9681 (ret "")
9682 (eat 0)
9683 (sum 0))
9684 (while bytes
9685 (let* ((val (string-to-number (pop bytes) 16))
9686 (shift-xor
9687 (if (= 0 eat)
9688 (cond
9689 ((>= val 252) (cons 6 252))
9690 ((>= val 248) (cons 5 248))
9691 ((>= val 240) (cons 4 240))
9692 ((>= val 224) (cons 3 224))
9693 ((>= val 192) (cons 2 192))
9694 (t (cons 0 0)))
9695 (cons 6 128))))
9696 (if (>= val 192) (setq eat (car shift-xor)))
9697 (setq val (logxor val (cdr shift-xor)))
9698 (setq sum (+ (lsh sum (car shift-xor)) val))
9699 (if (> eat 0) (setq eat (- eat 1)))
9700 (cond
9701 ((= 0 eat) ;multi byte
9702 (setq ret (concat ret (org-char-to-string sum)))
9703 (setq sum 0))
9704 ((not bytes) ; single byte(s)
9705 (setq ret (org-link-unescape-single-byte-sequence hex))))
9706 )) ;; end (while bytes
9707 ret )))
9709 (defun org-link-unescape-single-byte-sequence (hex)
9710 "Unhexify hex-encoded single byte character sequences."
9711 (mapconcat (lambda (byte)
9712 (char-to-string (string-to-number byte 16)))
9713 (cdr (split-string hex "%")) ""))
9715 (defun org-xor (a b)
9716 "Exclusive or."
9717 (if a (not b) b))
9719 (defun org-fixup-message-id-for-http (s)
9720 "Replace special characters in a message id, so it can be used in an http query."
9721 (when (string-match "%" s)
9722 (setq s (mapconcat (lambda (c)
9723 (if (eq c ?%)
9724 "%25"
9725 (char-to-string c)))
9726 s "")))
9727 (while (string-match "<" s)
9728 (setq s (replace-match "%3C" t t s)))
9729 (while (string-match ">" s)
9730 (setq s (replace-match "%3E" t t s)))
9731 (while (string-match "@" s)
9732 (setq s (replace-match "%40" t t s)))
9735 (defun org-link-prettify (link)
9736 "Return a human-readable representation of LINK.
9737 The car of LINK must be a raw link the cdr of LINK must be either
9738 a link description or nil."
9739 (let ((desc (or (cadr link) "<no description>")))
9740 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9741 "<" (car link) ">")))
9743 ;;;###autoload
9744 (defun org-insert-link-global ()
9745 "Insert a link like Org-mode does.
9746 This command can be called in any mode to insert a link in Org-mode syntax."
9747 (interactive)
9748 (org-load-modules-maybe)
9749 (org-run-like-in-org-mode 'org-insert-link))
9751 (defun org-insert-all-links (&optional keep)
9752 "Insert all links in `org-stored-links'."
9753 (interactive "P")
9754 (let ((links (copy-sequence org-stored-links)) l)
9755 (while (setq l (if keep (pop links) (pop org-stored-links)))
9756 (insert "- ")
9757 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9758 (insert "\n"))))
9760 (defun org-link-fontify-links-to-this-file ()
9761 "Fontify links to the current file in `org-stored-links'."
9762 (let ((f (buffer-file-name)) a b)
9763 (setq a (mapcar (lambda(l)
9764 (let ((ll (car l)))
9765 (when (and (string-match "^file:\\(.+\\)::" ll)
9766 (equal f (expand-file-name (match-string 1 ll))))
9767 ll)))
9768 org-stored-links))
9769 (when (featurep 'org-id)
9770 (setq b (mapcar (lambda(l)
9771 (let ((ll (car l)))
9772 (when (and (string-match "^id:\\(.+\\)$" ll)
9773 (equal f (expand-file-name
9774 (or (org-id-find-id-file
9775 (match-string 1 ll)) ""))))
9776 ll)))
9777 org-stored-links)))
9778 (mapcar (lambda(l)
9779 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9780 (delq nil (append a b)))))
9782 (defvar org-link-links-in-this-file nil)
9783 (defun org-insert-link (&optional complete-file link-location default-description)
9784 "Insert a link. At the prompt, enter the link.
9786 Completion can be used to insert any of the link protocol prefixes like
9787 http or ftp in use.
9789 The history can be used to select a link previously stored with
9790 `org-store-link'. When the empty string is entered (i.e. if you just
9791 press RET at the prompt), the link defaults to the most recently
9792 stored link. As SPC triggers completion in the minibuffer, you need to
9793 use M-SPC or C-q SPC to force the insertion of a space character.
9795 You will also be prompted for a description, and if one is given, it will
9796 be displayed in the buffer instead of the link.
9798 If there is already a link at point, this command will allow you to edit link
9799 and description parts.
9801 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9802 be selected using completion. The path to the file will be relative to the
9803 current directory if the file is in the current directory or a subdirectory.
9804 Otherwise, the link will be the absolute path as completed in the minibuffer
9805 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9806 option `org-link-file-path-type'.
9808 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9809 the current directory or below.
9811 With three \\[universal-argument] prefixes, negate the meaning of
9812 `org-keep-stored-link-after-insertion'.
9814 If `org-make-link-description-function' is non-nil, this function will be
9815 called with the link target, and the result will be the default
9816 link description.
9818 If the LINK-LOCATION parameter is non-nil, this value will be
9819 used as the link location instead of reading one interactively.
9821 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9822 be used as the default description."
9823 (interactive "P")
9824 (let* ((wcf (current-window-configuration))
9825 (origbuf (current-buffer))
9826 (region (if (org-region-active-p)
9827 (buffer-substring (region-beginning) (region-end))))
9828 (remove (and region (list (region-beginning) (region-end))))
9829 (desc region)
9830 tmphist ; byte-compile incorrectly complains about this
9831 (link link-location)
9832 (abbrevs org-link-abbrev-alist-local)
9833 entry file all-prefixes auto-desc)
9834 (cond
9835 (link-location) ; specified by arg, just use it.
9836 ((org-in-regexp org-bracket-link-regexp 1)
9837 ;; We do have a link at point, and we are going to edit it.
9838 (setq remove (list (match-beginning 0) (match-end 0)))
9839 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9840 (setq link (read-string "Link: "
9841 (org-link-unescape
9842 (org-match-string-no-properties 1)))))
9843 ((or (org-in-regexp org-angle-link-re)
9844 (org-in-regexp org-plain-link-re))
9845 ;; Convert to bracket link
9846 (setq remove (list (match-beginning 0) (match-end 0))
9847 link (read-string "Link: "
9848 (org-remove-angle-brackets (match-string 0)))))
9849 ((member complete-file '((4) (16)))
9850 ;; Completing read for file names.
9851 (setq link (org-file-complete-link complete-file)))
9853 ;; Read link, with completion for stored links.
9854 (org-link-fontify-links-to-this-file)
9855 (org-switch-to-buffer-other-window "*Org Links*")
9856 (with-current-buffer "*Org Links*"
9857 (erase-buffer)
9858 (insert "Insert a link.
9859 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9860 (when org-stored-links
9861 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9862 (insert (mapconcat 'org-link-prettify
9863 (reverse org-stored-links) "\n")))
9864 (goto-char (point-min)))
9865 (let ((cw (selected-window)))
9866 (select-window (get-buffer-window "*Org Links*" 'visible))
9867 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9868 (unless (pos-visible-in-window-p (point-max))
9869 (org-fit-window-to-buffer))
9870 (and (window-live-p cw) (select-window cw)))
9871 ;; Fake a link history, containing the stored links.
9872 (setq tmphist (append (mapcar 'car org-stored-links)
9873 org-insert-link-history))
9874 (setq all-prefixes (append (mapcar 'car abbrevs)
9875 (mapcar 'car org-link-abbrev-alist)
9876 org-link-types))
9877 (unwind-protect
9878 (progn
9879 (setq link
9880 (org-completing-read
9881 "Link: "
9882 (append
9883 (mapcar (lambda (x) (concat x ":"))
9884 all-prefixes)
9885 (mapcar 'car org-stored-links))
9886 nil nil nil
9887 'tmphist
9888 (caar org-stored-links)))
9889 (if (not (string-match "\\S-" link))
9890 (error "No link selected"))
9891 (mapc (lambda(l)
9892 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9893 org-stored-links)
9894 (if (or (member link all-prefixes)
9895 (and (equal ":" (substring link -1))
9896 (member (substring link 0 -1) all-prefixes)
9897 (setq link (substring link 0 -1))))
9898 (setq link (with-current-buffer origbuf
9899 (org-link-try-special-completion link)))))
9900 (set-window-configuration wcf)
9901 (kill-buffer "*Org Links*"))
9902 (setq entry (assoc link org-stored-links))
9903 (or entry (push link org-insert-link-history))
9904 (setq desc (or desc (nth 1 entry)))))
9906 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9907 (not org-keep-stored-link-after-insertion))
9908 (setq org-stored-links (delq (assoc link org-stored-links)
9909 org-stored-links)))
9911 (if (string-match org-plain-link-re link)
9912 ;; URL-like link, normalize the use of angular brackets.
9913 (setq link (org-remove-angle-brackets link)))
9915 ;; Check if we are linking to the current file with a search
9916 ;; option If yes, simplify the link by using only the search
9917 ;; option.
9918 (when (and buffer-file-name
9919 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9920 (let* ((path (match-string 1 link))
9921 (case-fold-search nil)
9922 (search (match-string 2 link)))
9923 (save-match-data
9924 (if (equal (file-truename buffer-file-name) (file-truename path))
9925 ;; We are linking to this same file, with a search option
9926 (setq link search)))))
9928 ;; Check if we can/should use a relative path. If yes, simplify the link
9929 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9930 (let* ((type (match-string 1 link))
9931 (path (match-string 2 link))
9932 (origpath path)
9933 (case-fold-search nil))
9934 (cond
9935 ((or (eq org-link-file-path-type 'absolute)
9936 (equal complete-file '(16)))
9937 (setq path (abbreviate-file-name (expand-file-name path))))
9938 ((eq org-link-file-path-type 'noabbrev)
9939 (setq path (expand-file-name path)))
9940 ((eq org-link-file-path-type 'relative)
9941 (setq path (file-relative-name path)))
9943 (save-match-data
9944 (if (string-match (concat "^" (regexp-quote
9945 (expand-file-name
9946 (file-name-as-directory
9947 default-directory))))
9948 (expand-file-name path))
9949 ;; We are linking a file with relative path name.
9950 (setq path (substring (expand-file-name path)
9951 (match-end 0)))
9952 (setq path (abbreviate-file-name (expand-file-name path)))))))
9953 (setq link (concat type path))
9954 (if (equal desc origpath)
9955 (setq desc path))))
9957 (if org-make-link-description-function
9958 (setq desc
9959 (or (condition-case nil
9960 (funcall org-make-link-description-function link desc)
9961 (error (progn (message "Can't get link description from `%s'"
9962 (symbol-name org-make-link-description-function))
9963 (sit-for 2) nil)))
9964 (read-string "Description: " default-description)))
9965 (if default-description (setq desc default-description)
9966 (setq desc (or (and auto-desc desc)
9967 (read-string "Description: " desc)))))
9969 (unless (string-match "\\S-" desc) (setq desc nil))
9970 (if remove (apply 'delete-region remove))
9971 (insert (org-make-link-string link desc))))
9973 (defun org-link-try-special-completion (type)
9974 "If there is completion support for link type TYPE, offer it."
9975 (let ((fun (intern (concat "org-" type "-complete-link"))))
9976 (if (functionp fun)
9977 (funcall fun)
9978 (read-string "Link (no completion support): " (concat type ":")))))
9980 (defun org-file-complete-link (&optional arg)
9981 "Create a file link using completion."
9982 (let (file link)
9983 (setq file (org-iread-file-name "File: "))
9984 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9985 (pwd1 (file-name-as-directory (abbreviate-file-name
9986 (expand-file-name ".")))))
9987 (cond
9988 ((equal arg '(16))
9989 (setq link (concat
9990 "file:"
9991 (abbreviate-file-name (expand-file-name file)))))
9992 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9993 (setq link (concat "file:" (match-string 1 file))))
9994 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9995 (expand-file-name file))
9996 (setq link (concat
9997 "file:" (match-string 1 (expand-file-name file)))))
9998 (t (setq link (concat "file:" file)))))
9999 link))
10001 (defun org-iread-file-name (&rest args)
10002 "Read-file-name using `ido-mode' speedup if available.
10003 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10004 See `read-file-name' for a description of parameters."
10005 (org-without-partial-completion
10006 (if (and org-completion-use-ido
10007 (fboundp 'ido-read-file-name)
10008 (boundp 'ido-mode) ido-mode
10009 (listp (second args)))
10010 (let ((ido-enter-matching-directory nil))
10011 (apply 'ido-read-file-name args))
10012 (apply 'read-file-name args))))
10014 (defun org-completing-read (&rest args)
10015 "Completing-read with SPACE being a normal character."
10016 (let ((enable-recursive-minibuffers t)
10017 (minibuffer-local-completion-map
10018 (copy-keymap minibuffer-local-completion-map)))
10019 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10020 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10021 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10022 (apply 'org-icompleting-read args)))
10024 (defun org-completing-read-no-i (&rest args)
10025 (let (org-completion-use-ido org-completion-use-iswitchb)
10026 (apply 'org-completing-read args)))
10028 (defun org-iswitchb-completing-read (prompt choices &rest args)
10029 "Use iswitch as a completing-read replacement to choose from choices.
10030 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10031 from."
10032 (let* ((iswitchb-use-virtual-buffers nil)
10033 (iswitchb-make-buflist-hook
10034 (lambda ()
10035 (setq iswitchb-temp-buflist choices))))
10036 (iswitchb-read-buffer prompt)))
10038 (defun org-icompleting-read (&rest args)
10039 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10040 (org-without-partial-completion
10041 (if (and org-completion-use-ido
10042 (fboundp 'ido-completing-read)
10043 (boundp 'ido-mode) ido-mode
10044 (listp (second args)))
10045 (let ((ido-enter-matching-directory nil))
10046 (apply 'ido-completing-read (concat (car args))
10047 (if (consp (car (nth 1 args)))
10048 (mapcar 'car (nth 1 args))
10049 (nth 1 args))
10050 (cddr args)))
10051 (if (and org-completion-use-iswitchb
10052 (boundp 'iswitchb-mode) iswitchb-mode
10053 (listp (second args)))
10054 (apply 'org-iswitchb-completing-read (concat (car args))
10055 (if (consp (car (nth 1 args)))
10056 (mapcar 'car (nth 1 args))
10057 (nth 1 args))
10058 (cddr args))
10059 (apply 'completing-read args)))))
10061 (defun org-extract-attributes (s)
10062 "Extract the attributes cookie from a string and set as text property."
10063 (let (a attr (start 0) key value)
10064 (save-match-data
10065 (when (string-match "{{\\([^}]+\\)}}$" s)
10066 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10067 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10068 (setq key (match-string 1 a) value (match-string 2 a)
10069 start (match-end 0)
10070 attr (plist-put attr (intern key) value))))
10071 (org-add-props s nil 'org-attr attr))
10074 (defun org-extract-attributes-from-string (tag)
10075 (let (key value attr)
10076 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10077 (setq key (match-string 1 tag) value (match-string 2 tag)
10078 tag (replace-match "" t t tag)
10079 attr (plist-put attr (intern key) value)))
10080 (cons tag attr)))
10082 (defun org-attributes-to-string (plist)
10083 "Format a property list into an HTML attribute list."
10084 (let ((s "") key value)
10085 (while plist
10086 (setq key (pop plist) value (pop plist))
10087 (and value
10088 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10091 ;;; Opening/following a link
10093 (defvar org-link-search-failed nil)
10095 (defvar org-open-link-functions nil
10096 "Hook for functions finding a plain text link.
10097 These functions must take a single argument, the link content.
10098 They will be called for links that look like [[link text][description]]
10099 when LINK TEXT does not have a protocol like \"http:\" and does not look
10100 like a filename (e.g. \"./blue.png\").
10102 These functions will be called *before* Org attempts to resolve the
10103 link by doing text searches in the current buffer - so if you want a
10104 link \"[[target]]\" to still find \"<<target>>\", your function should
10105 handle this as a special case.
10107 When the function does handle the link, it must return a non-nil value.
10108 If it decides that it is not responsible for this link, it must return
10109 nil to indicate that that Org-mode can continue with other options
10110 like exact and fuzzy text search.")
10112 (defun org-next-link (&optional search-backward)
10113 "Move forward to the next link.
10114 If the link is in hidden text, expose it."
10115 (interactive "P")
10116 (when (and org-link-search-failed (eq this-command last-command))
10117 (goto-char (point-min))
10118 (message "Link search wrapped back to beginning of buffer"))
10119 (setq org-link-search-failed nil)
10120 (let* ((pos (point))
10121 (ct (org-context))
10122 (a (assoc :link ct))
10123 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10124 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10125 ((looking-at org-any-link-re)
10126 ;; Don't stay stuck at link without an org-link face
10127 (forward-char (if search-backward -1 1))))
10128 (if (funcall srch-fun org-any-link-re nil t)
10129 (progn
10130 (goto-char (match-beginning 0))
10131 (if (outline-invisible-p) (org-show-context)))
10132 (goto-char pos)
10133 (setq org-link-search-failed t)
10134 (message "No further link found"))))
10136 (defun org-previous-link ()
10137 "Move backward to the previous link.
10138 If the link is in hidden text, expose it."
10139 (interactive)
10140 (funcall 'org-next-link t))
10142 (defun org-translate-link (s)
10143 "Translate a link string if a translation function has been defined."
10144 (if (and org-link-translation-function
10145 (fboundp org-link-translation-function)
10146 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10147 (progn
10148 (setq s (funcall org-link-translation-function
10149 (match-string 1 s) (match-string 2 s)))
10150 (concat (car s) ":" (cdr s)))
10153 (defun org-translate-link-from-planner (type path)
10154 "Translate a link from Emacs Planner syntax so that Org can follow it.
10155 This is still an experimental function, your mileage may vary."
10156 (cond
10157 ((member type '("http" "https" "news" "ftp"))
10158 ;; standard Internet links are the same.
10159 nil)
10160 ((and (equal type "irc") (string-match "^//" path))
10161 ;; Planner has two / at the beginning of an irc link, we have 1.
10162 ;; We should have zero, actually....
10163 (setq path (substring path 1)))
10164 ((and (equal type "lisp") (string-match "^/" path))
10165 ;; Planner has a slash, we do not.
10166 (setq type "elisp" path (substring path 1)))
10167 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10168 ;; A typical message link. Planner has the id after the final slash,
10169 ;; we separate it with a hash mark
10170 (setq path (concat (match-string 1 path) "#"
10171 (org-remove-angle-brackets (match-string 2 path)))))
10173 (cons type path))
10175 (defun org-find-file-at-mouse (ev)
10176 "Open file link or URL at mouse."
10177 (interactive "e")
10178 (mouse-set-point ev)
10179 (org-open-at-point 'in-emacs))
10181 (defun org-open-at-mouse (ev)
10182 "Open file link or URL at mouse.
10183 See the docstring of `org-open-file' for details."
10184 (interactive "e")
10185 (mouse-set-point ev)
10186 (if (eq major-mode 'org-agenda-mode)
10187 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10188 (org-open-at-point))
10190 (defvar org-window-config-before-follow-link nil
10191 "The window configuration before following a link.
10192 This is saved in case the need arises to restore it.")
10194 (defvar org-open-link-marker (make-marker)
10195 "Marker pointing to the location where `org-open-at-point; was called.")
10197 ;;;###autoload
10198 (defun org-open-at-point-global ()
10199 "Follow a link like Org-mode does.
10200 This command can be called in any mode to follow a link that has
10201 Org-mode syntax."
10202 (interactive)
10203 (org-run-like-in-org-mode 'org-open-at-point))
10205 ;;;###autoload
10206 (defun org-open-link-from-string (s &optional arg reference-buffer)
10207 "Open a link in the string S, as if it was in Org-mode."
10208 (interactive "sLink: \nP")
10209 (let ((reference-buffer (or reference-buffer (current-buffer))))
10210 (with-temp-buffer
10211 (let ((org-inhibit-startup (not reference-buffer)))
10212 (org-mode)
10213 (insert s)
10214 (goto-char (point-min))
10215 (when reference-buffer
10216 (setq org-link-abbrev-alist-local
10217 (with-current-buffer reference-buffer
10218 org-link-abbrev-alist-local)))
10219 (org-open-at-point arg reference-buffer)))))
10221 (defvar org-open-at-point-functions nil
10222 "Hook that is run when following a link at point.
10224 Functions in this hook must return t if they identify and follow
10225 a link at point. If they don't find anything interesting at point,
10226 they must return nil.")
10228 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10229 (defun org-open-at-point (&optional arg reference-buffer)
10230 "Open link at or after point.
10231 If there is no link at point, this function will search forward up to
10232 the end of the current line.
10233 Normally, files will be opened by an appropriate application. If the
10234 optional prefix argument ARG is non-nil, Emacs will visit the file.
10235 With a double prefix argument, try to open outside of Emacs, in the
10236 application the system uses for this file type."
10237 (interactive "P")
10238 ;; if in a code block, then open the block's results
10239 (unless (call-interactively #'org-babel-open-src-block-result)
10240 (org-load-modules-maybe)
10241 (move-marker org-open-link-marker (point))
10242 (setq org-window-config-before-follow-link (current-window-configuration))
10243 (org-remove-occur-highlights nil nil t)
10244 (cond
10245 ((and (org-at-heading-p)
10246 (not (org-at-timestamp-p t))
10247 (not (org-in-regexp
10248 (concat org-plain-link-re "\\|"
10249 org-bracket-link-regexp "\\|"
10250 org-angle-link-re "\\|"
10251 "[ \t]:[^ \t\n]+:[ \t]*$")))
10252 (not (get-text-property (point) 'org-linked-text)))
10253 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10254 (lk0 (car lkall))
10255 (lk (if (stringp lk0) (list lk0) lk0))
10256 (lkend (cdr lkall)))
10257 (mapcar (lambda(l)
10258 (search-forward l nil lkend)
10259 (goto-char (match-beginning 0))
10260 (org-open-at-point))
10261 lk))
10262 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10263 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10264 ((and (org-at-timestamp-p t)
10265 (not (org-in-regexp org-bracket-link-regexp)))
10266 (org-follow-timestamp-link))
10267 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10268 (not (org-in-regexp org-any-link-re)))
10269 (org-footnote-action))
10271 (let (type path link line search (pos (point)))
10272 (catch 'match
10273 (save-excursion
10274 (skip-chars-forward "^]\n\r")
10275 (when (org-in-regexp org-bracket-link-regexp 1)
10276 (setq link (org-extract-attributes
10277 (org-link-unescape (org-match-string-no-properties 1))))
10278 (while (string-match " *\n *" link)
10279 (setq link (replace-match " " t t link)))
10280 (setq link (org-link-expand-abbrev link))
10281 (cond
10282 ((or (file-name-absolute-p link)
10283 (string-match "^\\.\\.?/" link))
10284 (setq type "file" path link))
10285 ((string-match org-link-re-with-space3 link)
10286 (setq type (match-string 1 link) path (match-string 2 link)))
10287 ((string-match "^help:+\\(.+\\)" link)
10288 (setq type "help" path (match-string 1 link)))
10289 (t (setq type "thisfile" path link)))
10290 (throw 'match t)))
10292 (when (get-text-property (point) 'org-linked-text)
10293 (setq type "thisfile"
10294 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10295 (1+ (point)) (point))
10296 path (buffer-substring
10297 (or (previous-single-property-change pos 'org-linked-text)
10298 (point-min))
10299 (or (next-single-property-change pos 'org-linked-text)
10300 (point-max))))
10301 (throw 'match t))
10303 (save-excursion
10304 (when (or (org-in-regexp org-angle-link-re)
10305 (let ((match (org-in-regexp org-plain-link-re)))
10306 ;; Check a plain link is not within a bracket link
10307 (and match
10308 (save-excursion
10309 (progn
10310 (goto-char (car match))
10311 (not (org-in-regexp org-bracket-link-regexp))))))
10312 (let ((line_ending (save-excursion (end-of-line) (point))))
10313 ;; We are in a line before a plain or bracket link
10314 (or (re-search-forward org-plain-link-re line_ending t)
10315 (re-search-forward org-bracket-link-regexp line_ending t))))
10316 (setq type (match-string 1)
10317 path (org-link-unescape (match-string 2)))
10318 (throw 'match t)))
10319 (save-excursion
10320 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10321 (setq type "tags"
10322 path (match-string 1))
10323 (while (string-match ":" path)
10324 (setq path (replace-match "+" t t path)))
10325 (throw 'match t)))
10326 (when (org-in-regexp "<\\([^><\n]+\\)>")
10327 (setq type "tree-match"
10328 path (match-string 1))
10329 (throw 'match t)))
10330 (unless path
10331 (user-error "No link found"))
10333 ;; switch back to reference buffer
10334 ;; needed when if called in a temporary buffer through
10335 ;; org-open-link-from-string
10336 (with-current-buffer (or reference-buffer (current-buffer))
10338 ;; Remove any trailing spaces in path
10339 (if (string-match " +\\'" path)
10340 (setq path (replace-match "" t t path)))
10341 (if (and org-link-translation-function
10342 (fboundp org-link-translation-function))
10343 ;; Check if we need to translate the link
10344 (let ((tmp (funcall org-link-translation-function type path)))
10345 (setq type (car tmp) path (cdr tmp))))
10347 (cond
10349 ((assoc type org-link-protocols)
10350 (funcall (nth 1 (assoc type org-link-protocols)) path))
10352 ((equal type "help")
10353 (let ((f-or-v (intern path)))
10354 (cond ((fboundp f-or-v)
10355 (describe-function f-or-v))
10356 ((boundp f-or-v)
10357 (describe-variable f-or-v))
10358 (t (error "Not a known function or variable")))))
10360 ((equal type "mailto")
10361 (let ((cmd (car org-link-mailto-program))
10362 (args (cdr org-link-mailto-program)) args1
10363 (address path) (subject "") a)
10364 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10365 (setq address (match-string 1 path)
10366 subject (org-link-escape (match-string 2 path))))
10367 (while args
10368 (cond
10369 ((not (stringp (car args))) (push (pop args) args1))
10370 (t (setq a (pop args))
10371 (if (string-match "%a" a)
10372 (setq a (replace-match address t t a)))
10373 (if (string-match "%s" a)
10374 (setq a (replace-match subject t t a)))
10375 (push a args1))))
10376 (apply cmd (nreverse args1))))
10378 ((member type '("http" "https" "ftp" "news"))
10379 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10380 (org-link-escape
10381 path org-link-escape-chars-browser)
10382 path))))
10384 ((string= type "doi")
10385 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10386 (org-link-escape
10387 path org-link-escape-chars-browser)
10388 path))))
10390 ((member type '("message"))
10391 (browse-url (concat type ":" path)))
10393 ((string= type "tags")
10394 (org-tags-view arg path))
10396 ((string= type "tree-match")
10397 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10399 ((string= type "file")
10400 (if (string-match "::\\([0-9]+\\)\\'" path)
10401 (setq line (string-to-number (match-string 1 path))
10402 path (substring path 0 (match-beginning 0)))
10403 (if (string-match "::\\(.+\\)\\'" path)
10404 (setq search (match-string 1 path)
10405 path (substring path 0 (match-beginning 0)))))
10406 (if (string-match "[*?{]" (file-name-nondirectory path))
10407 (dired path)
10408 (org-open-file path arg line search)))
10410 ((string= type "shell")
10411 (let ((buf (generate-new-buffer "*Org Shell Output"))
10412 (cmd path))
10413 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10414 (string-match org-confirm-shell-link-not-regexp cmd))
10415 (not org-confirm-shell-link-function)
10416 (funcall org-confirm-shell-link-function
10417 (format "Execute \"%s\" in shell? "
10418 (org-add-props cmd nil
10419 'face 'org-warning))))
10420 (progn
10421 (message "Executing %s" cmd)
10422 (shell-command cmd buf)
10423 (if (featurep 'midnight)
10424 (setq clean-buffer-list-kill-buffer-names
10425 (cons buf clean-buffer-list-kill-buffer-names))))
10426 (error "Abort"))))
10428 ((string= type "elisp")
10429 (let ((cmd path))
10430 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10431 (string-match org-confirm-elisp-link-not-regexp cmd))
10432 (not org-confirm-elisp-link-function)
10433 (funcall org-confirm-elisp-link-function
10434 (format "Execute \"%s\" as elisp? "
10435 (org-add-props cmd nil
10436 'face 'org-warning))))
10437 (message "%s => %s" cmd
10438 (if (equal (string-to-char cmd) ?\()
10439 (eval (read cmd))
10440 (call-interactively (read cmd))))
10441 (error "Abort"))))
10443 ((and (string= type "thisfile")
10444 (run-hook-with-args-until-success
10445 'org-open-link-functions path)))
10447 ((string= type "thisfile")
10448 (if arg
10449 (switch-to-buffer-other-window
10450 (org-get-buffer-for-internal-link (current-buffer)))
10451 (org-mark-ring-push))
10452 (let ((cmd `(org-link-search
10453 ,path
10454 ,(cond ((equal arg '(4)) ''occur)
10455 ((equal arg '(16)) ''org-occur))
10456 ,pos)))
10457 (condition-case nil (let ((org-link-search-inhibit-query t))
10458 (eval cmd))
10459 (error (progn (widen) (eval cmd))))))
10461 (t (browse-url-at-point)))))))
10462 (move-marker org-open-link-marker nil)
10463 (run-hook-with-args 'org-follow-link-hook)))
10465 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10466 "Offer links in the current entry and return the selected link.
10467 If there is only one link, return it.
10468 If NTH is an integer, return the NTH link found.
10469 If ZERO is a string, check also this string for a link, and if
10470 there is one, return it."
10471 (with-current-buffer buffer
10472 (save-excursion
10473 (save-restriction
10474 (widen)
10475 (goto-char marker)
10476 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10477 "\\(" org-angle-link-re "\\)\\|"
10478 "\\(" org-plain-link-re "\\)"))
10479 (cnt ?0)
10480 (in-emacs (if (integerp nth) nil nth))
10481 have-zero end links link c)
10482 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10483 (push (match-string 0 zero) links)
10484 (setq cnt (1- cnt) have-zero t))
10485 (save-excursion
10486 (org-back-to-heading t)
10487 (setq end (save-excursion (outline-next-heading) (point)))
10488 (while (re-search-forward re end t)
10489 (push (match-string 0) links))
10490 (setq links (org-uniquify (reverse links))))
10491 (cond
10492 ((null links)
10493 (message "No links"))
10494 ((equal (length links) 1)
10495 (setq link (car links)))
10496 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10497 (setq link (nth (if have-zero nth (1- nth)) links)))
10498 (t ; we have to select a link
10499 (save-excursion
10500 (save-window-excursion
10501 (delete-other-windows)
10502 (with-output-to-temp-buffer "*Select Link*"
10503 (mapc (lambda (l)
10504 (if (not (string-match org-bracket-link-regexp l))
10505 (princ (format "[%c] %s\n" (incf cnt)
10506 (org-remove-angle-brackets l)))
10507 (if (match-end 3)
10508 (princ (format "[%c] %s (%s)\n" (incf cnt)
10509 (match-string 3 l) (match-string 1 l)))
10510 (princ (format "[%c] %s\n" (incf cnt)
10511 (match-string 1 l))))))
10512 links))
10513 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10514 (message "Select link to open, RET to open all:")
10515 (setq c (read-char-exclusive))
10516 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10517 (when (equal c ?q) (error "Abort"))
10518 (if (equal c ?\C-m)
10519 (setq link links)
10520 (setq nth (- c ?0))
10521 (if have-zero (setq nth (1+ nth)))
10522 (unless (and (integerp nth) (>= (length links) nth))
10523 (error "Invalid link selection"))
10524 (setq link (nth (1- nth) links)))))
10525 (cons link end))))))
10527 ;; Add special file links that specify the way of opening
10529 (org-add-link-type "file+sys" 'org-open-file-with-system)
10530 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10531 (defun org-open-file-with-system (path)
10532 "Open file at PATH using the system way of opening it."
10533 (org-open-file path 'system))
10534 (defun org-open-file-with-emacs (path)
10535 "Open file at PATH in Emacs."
10536 (org-open-file path 'emacs))
10539 ;;; File search
10541 (defvar org-create-file-search-functions nil
10542 "List of functions to construct the right search string for a file link.
10543 These functions are called in turn with point at the location to
10544 which the link should point.
10546 A function in the hook should first test if it would like to
10547 handle this file type, for example by checking the `major-mode'
10548 or the file extension. If it decides not to handle this file, it
10549 should just return nil to give other functions a chance. If it
10550 does handle the file, it must return the search string to be used
10551 when following the link. The search string will be part of the
10552 file link, given after a double colon, and `org-open-at-point'
10553 will automatically search for it. If special measures must be
10554 taken to make the search successful, another function should be
10555 added to the companion hook `org-execute-file-search-functions',
10556 which see.
10558 A function in this hook may also use `setq' to set the variable
10559 `description' to provide a suggestion for the descriptive text to
10560 be used for this link when it gets inserted into an Org-mode
10561 buffer with \\[org-insert-link].")
10563 (defvar org-execute-file-search-functions nil
10564 "List of functions to execute a file search triggered by a link.
10566 Functions added to this hook must accept a single argument, the
10567 search string that was part of the file link, the part after the
10568 double colon. The function must first check if it would like to
10569 handle this search, for example by checking the `major-mode' or
10570 the file extension. If it decides not to handle this search, it
10571 should just return nil to give other functions a chance. If it
10572 does handle the search, it must return a non-nil value to keep
10573 other functions from trying.
10575 Each function can access the current prefix argument through the
10576 variable `current-prefix-arg'. Note that a single prefix is used
10577 to force opening a link in Emacs, so it may be good to only use a
10578 numeric or double prefix to guide the search function.
10580 In case this is needed, a function in this hook can also restore
10581 the window configuration before `org-open-at-point' was called using:
10583 (set-window-configuration org-window-config-before-follow-link)")
10585 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10586 (defun org-link-search (s &optional type avoid-pos stealth)
10587 "Search for a link search option.
10588 If S is surrounded by forward slashes, it is interpreted as a
10589 regular expression. In org-mode files, this will create an `org-occur'
10590 sparse tree. In ordinary files, `occur' will be used to list matches.
10591 If the current buffer is in `dired-mode', grep will be used to search
10592 in all files. If AVOID-POS is given, ignore matches near that position.
10594 When optional argument STEALTH is non-nil, do not modify
10595 visibility around point, thus ignoring
10596 `org-show-hierarchy-above', `org-show-following-heading' and
10597 `org-show-siblings' variables."
10598 (let ((case-fold-search t)
10599 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10600 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10601 (append '(("") (" ") ("\t") ("\n"))
10602 org-emphasis-alist)
10603 "\\|") "\\)"))
10604 (pos (point))
10605 (pre nil) (post nil)
10606 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10607 (cond
10608 ;; First check if there are any special search functions
10609 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10610 ;; Now try the builtin stuff
10611 ((and (equal (string-to-char s0) ?#)
10612 (> (length s0) 1)
10613 (save-excursion
10614 (goto-char (point-min))
10615 (and
10616 (re-search-forward
10617 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10618 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10619 (setq type 'dedicated
10620 pos (match-beginning 0))))
10621 ;; There is an exact target for this
10622 (goto-char pos)
10623 (org-back-to-heading t)))
10624 ((save-excursion
10625 (goto-char (point-min))
10626 (and
10627 (re-search-forward
10628 (concat "<<" (regexp-quote s0) ">>") nil t)
10629 (setq type 'dedicated
10630 pos (match-beginning 0))))
10631 ;; There is an exact target for this
10632 (goto-char pos))
10633 ((save-excursion
10634 (goto-char (point-min))
10635 (and
10636 (re-search-forward
10637 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10638 (setq type 'dedicated pos (match-beginning 0))))
10639 ;; Found an invisible target.
10640 (goto-char pos))
10641 ((save-excursion
10642 (goto-char (point-min))
10643 (and
10644 (re-search-forward
10645 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10646 (setq type 'dedicated pos (match-beginning 0))))
10647 ;; Found an element with a matching #+name affiliated keyword.
10648 (goto-char pos))
10649 ((and (string-match "^(\\(.*\\))$" s0)
10650 (save-excursion
10651 (goto-char (point-min))
10652 (and
10653 (re-search-forward
10654 (concat "[^[]" (regexp-quote
10655 (format org-coderef-label-format
10656 (match-string 1 s0))))
10657 nil t)
10658 (setq type 'dedicated
10659 pos (1+ (match-beginning 0))))))
10660 ;; There is a coderef target for this
10661 (goto-char pos))
10662 ((string-match "^/\\(.*\\)/$" s)
10663 ;; A regular expression
10664 (cond
10665 ((derived-mode-p 'org-mode)
10666 (org-occur (match-string 1 s)))
10667 (t (org-do-occur (match-string 1 s)))))
10668 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10669 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10670 (goto-char (point-min))
10671 (cond
10672 ((let (case-fold-search)
10673 (re-search-forward (format org-complex-heading-regexp-format
10674 (regexp-quote s))
10675 nil t))
10676 ;; OK, found a match
10677 (setq type 'dedicated)
10678 (goto-char (match-beginning 0)))
10679 ((and (not org-link-search-inhibit-query)
10680 (eq org-link-search-must-match-exact-headline 'query-to-create)
10681 (y-or-n-p "No match - create this as a new heading? "))
10682 (goto-char (point-max))
10683 (or (bolp) (newline))
10684 (insert "* " s "\n")
10685 (beginning-of-line 0))
10687 (goto-char pos)
10688 (error "No match"))))
10690 ;; A normal search string
10691 (when (equal (string-to-char s) ?*)
10692 ;; Anchor on headlines, post may include tags.
10693 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10694 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10695 s (substring s 1)))
10696 (remove-text-properties
10697 0 (length s)
10698 '(face nil mouse-face nil keymap nil fontified nil) s)
10699 ;; Make a series of regular expressions to find a match
10700 (setq words (org-split-string s "[ \n\r\t]+")
10702 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10703 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10704 "\\)" markers)
10705 re2a_ (concat "\\(" (mapconcat 'downcase words
10706 "[ \t\r\n]+") "\\)[ \t\r\n]")
10707 re2a (concat "[ \t\r\n]" re2a_)
10708 re4_ (concat "\\(" (mapconcat 'downcase words
10709 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10710 re4 (concat "[^a-zA-Z_]" re4_)
10712 re1 (concat pre re2 post)
10713 re3 (concat pre (if pre re4_ re4) post)
10714 re5 (concat pre ".*" re4)
10715 re2 (concat pre re2)
10716 re2a (concat pre (if pre re2a_ re2a))
10717 re4 (concat pre (if pre re4_ re4))
10718 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10719 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10720 re5 "\\)"
10722 (cond
10723 ((eq type 'org-occur) (org-occur reall))
10724 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10725 (t (goto-char (point-min))
10726 (setq type 'fuzzy)
10727 (if (or (and (org-search-not-self 1 re0 nil t)
10728 (setq type 'dedicated))
10729 (org-search-not-self 1 re1 nil t)
10730 (org-search-not-self 1 re2 nil t)
10731 (org-search-not-self 1 re2a nil t)
10732 (org-search-not-self 1 re3 nil t)
10733 (org-search-not-self 1 re4 nil t)
10734 (org-search-not-self 1 re5 nil t))
10735 (goto-char (match-beginning 1))
10736 (goto-char pos)
10737 (error "No match"))))))
10738 (and (derived-mode-p 'org-mode)
10739 (not stealth)
10740 (org-show-context 'link-search))
10741 type))
10743 (defun org-search-not-self (group &rest args)
10744 "Execute `re-search-forward', but only accept matches that do not
10745 enclose the position of `org-open-link-marker'."
10746 (let ((m org-open-link-marker))
10747 (catch 'exit
10748 (while (apply 're-search-forward args)
10749 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10750 (goto-char (match-end group))
10751 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10752 (> (match-beginning 0) (marker-position m))
10753 (< (match-end 0) (marker-position m)))
10754 (save-match-data
10755 (or (not (org-in-regexp
10756 org-bracket-link-analytic-regexp 1))
10757 (not (match-end 4)) ; no description
10758 (and (<= (match-beginning 4) (point))
10759 (>= (match-end 4) (point))))))
10760 (throw 'exit (point))))))))
10762 (defun org-get-buffer-for-internal-link (buffer)
10763 "Return a buffer to be used for displaying the link target of internal links."
10764 (cond
10765 ((not org-display-internal-link-with-indirect-buffer)
10766 buffer)
10767 ((string-match "(Clone)$" (buffer-name buffer))
10768 (message "Buffer is already a clone, not making another one")
10769 ;; we also do not modify visibility in this case
10770 buffer)
10771 (t ; make a new indirect buffer for displaying the link
10772 (let* ((bn (buffer-name buffer))
10773 (ibn (concat bn "(Clone)"))
10774 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10775 (with-current-buffer ib (org-overview))
10776 ib))))
10778 (defun org-do-occur (regexp &optional cleanup)
10779 "Call the Emacs command `occur'.
10780 If CLEANUP is non-nil, remove the printout of the regular expression
10781 in the *Occur* buffer. This is useful if the regex is long and not useful
10782 to read."
10783 (occur regexp)
10784 (when cleanup
10785 (let ((cwin (selected-window)) win beg end)
10786 (when (setq win (get-buffer-window "*Occur*"))
10787 (select-window win))
10788 (goto-char (point-min))
10789 (when (re-search-forward "match[a-z]+" nil t)
10790 (setq beg (match-end 0))
10791 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10792 (setq end (1- (match-beginning 0)))))
10793 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10794 (goto-char (point-min))
10795 (select-window cwin))))
10797 ;;; The mark ring for links jumps
10799 (defvar org-mark-ring nil
10800 "Mark ring for positions before jumps in Org-mode.")
10801 (defvar org-mark-ring-last-goto nil
10802 "Last position in the mark ring used to go back.")
10803 ;; Fill and close the ring
10804 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10805 (loop for i from 1 to org-mark-ring-length do
10806 (push (make-marker) org-mark-ring))
10807 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10808 org-mark-ring)
10810 (defun org-mark-ring-push (&optional pos buffer)
10811 "Put the current position or POS into the mark ring and rotate it."
10812 (interactive)
10813 (setq pos (or pos (point)))
10814 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10815 (move-marker (car org-mark-ring)
10816 (or pos (point))
10817 (or buffer (current-buffer)))
10818 (message "%s"
10819 (substitute-command-keys
10820 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10822 (defun org-mark-ring-goto (&optional n)
10823 "Jump to the previous position in the mark ring.
10824 With prefix arg N, jump back that many stored positions. When
10825 called several times in succession, walk through the entire ring.
10826 Org-mode commands jumping to a different position in the current file,
10827 or to another Org-mode file, automatically push the old position
10828 onto the ring."
10829 (interactive "p")
10830 (let (p m)
10831 (if (eq last-command this-command)
10832 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10833 (setq p org-mark-ring))
10834 (setq org-mark-ring-last-goto p)
10835 (setq m (car p))
10836 (org-pop-to-buffer-same-window (marker-buffer m))
10837 (goto-char m)
10838 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10840 (defun org-remove-angle-brackets (s)
10841 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10842 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10844 (defun org-add-angle-brackets (s)
10845 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10846 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10848 (defun org-remove-double-quotes (s)
10849 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10850 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10853 ;;; Following specific links
10855 (defun org-follow-timestamp-link ()
10856 "Open an agenda view for the time-stamp date/range at point."
10857 (cond
10858 ((org-at-date-range-p t)
10859 (let ((org-agenda-start-on-weekday)
10860 (t1 (match-string 1))
10861 (t2 (match-string 2)) tt1 tt2)
10862 (setq tt1 (time-to-days (org-time-string-to-time t1))
10863 tt2 (time-to-days (org-time-string-to-time t2)))
10864 (let ((org-agenda-buffer-tmp-name
10865 (format "*Org Agenda(a:%s)"
10866 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10867 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10868 ((org-at-timestamp-p t)
10869 (let ((org-agenda-buffer-tmp-name
10870 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10871 (org-agenda-list nil (time-to-days (org-time-string-to-time
10872 (substring (match-string 1) 0 10)))
10873 1)))
10874 (t (error "This should not happen"))))
10877 ;;; Following file links
10878 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10879 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10880 (declare-function mailcap-mime-info
10881 "mailcap" (string &optional request no-decode))
10882 (defvar org-wait nil)
10883 (defun org-open-file (path &optional in-emacs line search)
10884 "Open the file at PATH.
10885 First, this expands any special file name abbreviations. Then the
10886 configuration variable `org-file-apps' is checked if it contains an
10887 entry for this file type, and if yes, the corresponding command is launched.
10889 If no application is found, Emacs simply visits the file.
10891 With optional prefix argument IN-EMACS, Emacs will visit the file.
10892 With a double \\[universal-argument] \\[universal-argument] \
10893 prefix arg, Org tries to avoid opening in Emacs
10894 and to use an external application to visit the file.
10896 Optional LINE specifies a line to go to, optional SEARCH a string
10897 to search for. If LINE or SEARCH is given, the file will be
10898 opened in Emacs, unless an entry from org-file-apps that makes
10899 use of groups in a regexp matches.
10901 If you want to change the way frames are used when following a
10902 link, please customize `org-link-frame-setup'.
10904 If the file does not exist, an error is thrown."
10905 (let* ((file (if (equal path "")
10906 buffer-file-name
10907 (substitute-in-file-name (expand-file-name path))))
10908 (file-apps (append org-file-apps (org-default-apps)))
10909 (apps (org-remove-if
10910 'org-file-apps-entry-match-against-dlink-p file-apps))
10911 (apps-dlink (org-remove-if-not
10912 'org-file-apps-entry-match-against-dlink-p file-apps))
10913 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10914 (dirp (if remp nil (file-directory-p file)))
10915 (file (if (and dirp org-open-directory-means-index-dot-org)
10916 (concat (file-name-as-directory file) "index.org")
10917 file))
10918 (a-m-a-p (assq 'auto-mode apps))
10919 (dfile (downcase file))
10920 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10921 (link (cond ((and (eq line nil)
10922 (eq search nil))
10923 file)
10924 (line
10925 (concat file "::" (number-to-string line)))
10926 (search
10927 (concat file "::" search))))
10928 (dlink (downcase link))
10929 (old-buffer (current-buffer))
10930 (old-pos (point))
10931 (old-mode major-mode)
10932 ext cmd link-match-data)
10933 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10934 (setq ext (match-string 1 dfile))
10935 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10936 (setq ext (match-string 1 dfile))))
10937 (cond
10938 ((member in-emacs '((16) system))
10939 (setq cmd (cdr (assoc 'system apps))))
10940 (in-emacs (setq cmd 'emacs))
10942 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10943 (and dirp (cdr (assoc 'directory apps)))
10944 ; first, try matching against apps-dlink
10945 ; if we get a match here, store the match data for later
10946 (let ((match (assoc-default dlink apps-dlink
10947 'string-match)))
10948 (if match
10949 (progn (setq link-match-data (match-data))
10950 match)
10951 (progn (setq in-emacs (or in-emacs line search))
10952 nil))) ; if we have no match in apps-dlink,
10953 ; always open the file in emacs if line or search
10954 ; is given (for backwards compatibility)
10955 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10956 'string-match)
10957 (cdr (assoc ext apps))
10958 (cdr (assoc t apps))))))
10959 (when (eq cmd 'system)
10960 (setq cmd (cdr (assoc 'system apps))))
10961 (when (eq cmd 'default)
10962 (setq cmd (cdr (assoc t apps))))
10963 (when (eq cmd 'mailcap)
10964 (require 'mailcap)
10965 (mailcap-parse-mailcaps)
10966 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10967 (command (mailcap-mime-info mime-type)))
10968 (if (stringp command)
10969 (setq cmd command)
10970 (setq cmd 'emacs))))
10971 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10972 (not (file-exists-p file))
10973 (not org-open-non-existing-files))
10974 (error "No such file: %s" file))
10975 (cond
10976 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10977 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10978 (while (string-match "['\"]%s['\"]" cmd)
10979 (setq cmd (replace-match "%s" t t cmd)))
10980 (while (string-match "%s" cmd)
10981 (setq cmd (replace-match
10982 (save-match-data
10983 (shell-quote-argument
10984 (convert-standard-filename file)))
10985 t t cmd)))
10987 ;; Replace "%1", "%2" etc. in command with group matches from regex
10988 (save-match-data
10989 (let ((match-index 1)
10990 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10991 (set-match-data link-match-data)
10992 (while (<= match-index number-of-groups)
10993 (let ((regex (concat "%" (number-to-string match-index)))
10994 (replace-with (match-string match-index dlink)))
10995 (while (string-match regex cmd)
10996 (setq cmd (replace-match replace-with t t cmd))))
10997 (setq match-index (+ match-index 1)))))
10999 (save-window-excursion
11000 (message "Running %s...done" cmd)
11001 (start-process-shell-command cmd nil cmd)
11002 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11003 ((or (stringp cmd)
11004 (eq cmd 'emacs))
11005 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11006 (widen)
11007 (if line (org-goto-line line)
11008 (if search (org-link-search search))))
11009 ((consp cmd)
11010 (let ((file (convert-standard-filename file)))
11011 (save-match-data
11012 (set-match-data link-match-data)
11013 (eval cmd))))
11014 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11015 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11016 (or (not (equal old-buffer (current-buffer)))
11017 (not (equal old-pos (point))))
11018 (org-mark-ring-push old-pos old-buffer))))
11020 (defun org-file-apps-entry-match-against-dlink-p (entry)
11021 "This function returns non-nil if `entry' uses a regular
11022 expression which should be matched against the whole link by
11023 org-open-file.
11025 It assumes that is the case when the entry uses a regular
11026 expression which has at least one grouping construct and the
11027 action is either a lisp form or a command string containing
11028 '%1', i.e. using at least one subexpression match as a
11029 parameter."
11030 (let ((selector (car entry))
11031 (action (cdr entry)))
11032 (if (stringp selector)
11033 (and (> (regexp-opt-depth selector) 0)
11034 (or (and (stringp action)
11035 (string-match "%[0-9]" action))
11036 (consp action)))
11037 nil)))
11039 (defun org-default-apps ()
11040 "Return the default applications for this operating system."
11041 (cond
11042 ((eq system-type 'darwin)
11043 org-file-apps-defaults-macosx)
11044 ((eq system-type 'windows-nt)
11045 org-file-apps-defaults-windowsnt)
11046 (t org-file-apps-defaults-gnu)))
11048 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11049 "Convert extensions to regular expressions in the cars of LIST.
11050 Also, weed out any non-string entries, because the return value is used
11051 only for regexp matching.
11052 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11053 point to the symbol `emacs', indicating that the file should
11054 be opened in Emacs."
11055 (append
11056 (delq nil
11057 (mapcar (lambda (x)
11058 (if (not (stringp (car x)))
11060 (if (string-match "\\W" (car x))
11062 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11063 list))
11064 (if add-auto-mode
11065 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11067 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11068 (defun org-file-remote-p (file)
11069 "Test whether FILE specifies a location on a remote system.
11070 Return non-nil if the location is indeed remote.
11072 For example, the filename \"/user@host:/foo\" specifies a location
11073 on the system \"/user@host:\"."
11074 (cond ((fboundp 'file-remote-p)
11075 (file-remote-p file))
11076 ((fboundp 'tramp-handle-file-remote-p)
11077 (tramp-handle-file-remote-p file))
11078 ((and (boundp 'ange-ftp-name-format)
11079 (string-match (car ange-ftp-name-format) file))
11080 t)))
11083 ;;;; Refiling
11085 (defun org-get-org-file ()
11086 "Read a filename, with default directory `org-directory'."
11087 (let ((default (or org-default-notes-file remember-data-file)))
11088 (read-file-name (format "File name [%s]: " default)
11089 (file-name-as-directory org-directory)
11090 default)))
11092 (defun org-notes-order-reversed-p ()
11093 "Check if the current file should receive notes in reversed order."
11094 (cond
11095 ((not org-reverse-note-order) nil)
11096 ((eq t org-reverse-note-order) t)
11097 ((not (listp org-reverse-note-order)) nil)
11098 (t (catch 'exit
11099 (let ((all org-reverse-note-order)
11100 entry)
11101 (while (setq entry (pop all))
11102 (if (string-match (car entry) buffer-file-name)
11103 (throw 'exit (cdr entry))))
11104 nil)))))
11106 (defvar org-refile-target-table nil
11107 "The list of refile targets, created by `org-refile'.")
11109 (defvar org-agenda-new-buffers nil
11110 "Buffers created to visit agenda files.")
11112 (defvar org-refile-cache nil
11113 "Cache for refile targets.")
11115 (defvar org-refile-markers nil
11116 "All the markers used for caching refile locations.")
11118 (defun org-refile-marker (pos)
11119 "Get a new refile marker, but only if caching is in use."
11120 (if (not org-refile-use-cache)
11122 (let ((m (make-marker)))
11123 (move-marker m pos)
11124 (push m org-refile-markers)
11125 m)))
11127 (defun org-refile-cache-clear ()
11128 "Clear the refile cache and disable all the markers."
11129 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11130 (setq org-refile-markers nil)
11131 (setq org-refile-cache nil)
11132 (message "Refile cache has been cleared"))
11134 (defun org-refile-cache-check-set (set)
11135 "Check if all the markers in the cache still have live buffers."
11136 (let (marker)
11137 (catch 'exit
11138 (while (and set (setq marker (nth 3 (pop set))))
11139 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11140 (when (and marker (null (marker-buffer marker)))
11141 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11142 (sit-for 3)
11143 (throw 'exit nil)))
11144 t)))
11146 (defun org-refile-cache-put (set &rest identifiers)
11147 "Push the refile targets SET into the cache, under IDENTIFIERS."
11148 (let* ((key (sha1 (prin1-to-string identifiers)))
11149 (entry (assoc key org-refile-cache)))
11150 (if entry
11151 (setcdr entry set)
11152 (push (cons key set) org-refile-cache))))
11154 (defun org-refile-cache-get (&rest identifiers)
11155 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11156 (cond
11157 ((not org-refile-cache) nil)
11158 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11160 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11161 org-refile-cache))))
11162 (and set (org-refile-cache-check-set set) set)))))
11164 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11165 "Produce a table with refile targets."
11166 (let ((case-fold-search nil)
11167 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11168 (entries (or org-refile-targets '((nil . (:level . 1)))))
11169 targets tgs txt re files f desc descre fast-path-p level pos0)
11170 (message "Getting targets...")
11171 (with-current-buffer (or default-buffer (current-buffer))
11172 (while (setq entry (pop entries))
11173 (setq files (car entry) desc (cdr entry))
11174 (setq fast-path-p nil)
11175 (cond
11176 ((null files) (setq files (list (current-buffer))))
11177 ((eq files 'org-agenda-files)
11178 (setq files (org-agenda-files 'unrestricted)))
11179 ((and (symbolp files) (fboundp files))
11180 (setq files (funcall files)))
11181 ((and (symbolp files) (boundp files))
11182 (setq files (symbol-value files))))
11183 (if (stringp files) (setq files (list files)))
11184 (cond
11185 ((eq (car desc) :tag)
11186 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11187 ((eq (car desc) :todo)
11188 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11189 ((eq (car desc) :regexp)
11190 (setq descre (cdr desc)))
11191 ((eq (car desc) :level)
11192 (setq descre (concat "^\\*\\{" (number-to-string
11193 (if org-odd-levels-only
11194 (1- (* 2 (cdr desc)))
11195 (cdr desc)))
11196 "\\}[ \t]")))
11197 ((eq (car desc) :maxlevel)
11198 (setq fast-path-p t)
11199 (setq descre (concat "^\\*\\{1," (number-to-string
11200 (if org-odd-levels-only
11201 (1- (* 2 (cdr desc)))
11202 (cdr desc)))
11203 "\\}[ \t]")))
11204 (t (error "Bad refiling target description %s" desc)))
11205 (while (setq f (pop files))
11206 (with-current-buffer
11207 (if (bufferp f) f (org-get-agenda-file-buffer f))
11209 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11210 (progn
11211 (if (bufferp f) (setq f (buffer-file-name
11212 (buffer-base-buffer f))))
11213 (setq f (and f (expand-file-name f)))
11214 (if (eq org-refile-use-outline-path 'file)
11215 (push (list (file-name-nondirectory f) f nil nil) tgs))
11216 (save-excursion
11217 (save-restriction
11218 (widen)
11219 (goto-char (point-min))
11220 (while (re-search-forward descre nil t)
11221 (goto-char (setq pos0 (point-at-bol)))
11222 (catch 'next
11223 (when org-refile-target-verify-function
11224 (save-match-data
11225 (or (funcall org-refile-target-verify-function)
11226 (throw 'next t))))
11227 (when (and (looking-at org-complex-heading-regexp)
11228 (not (member (match-string 4) excluded-entries))
11229 (match-string 4))
11230 (setq level (org-reduced-level
11231 (- (match-end 1) (match-beginning 1)))
11232 txt (org-link-display-format (match-string 4))
11233 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11234 re (format org-complex-heading-regexp-format
11235 (regexp-quote (match-string 4))))
11236 (when org-refile-use-outline-path
11237 (setq txt (mapconcat
11238 'org-protect-slash
11239 (append
11240 (if (eq org-refile-use-outline-path
11241 'file)
11242 (list (file-name-nondirectory
11243 (buffer-file-name
11244 (buffer-base-buffer))))
11245 (if (eq org-refile-use-outline-path
11246 'full-file-path)
11247 (list (buffer-file-name
11248 (buffer-base-buffer)))))
11249 (org-get-outline-path fast-path-p
11250 level txt)
11251 (list txt))
11252 "/")))
11253 (push (list txt f re (org-refile-marker (point)))
11254 tgs)))
11255 (when (= (point) pos0)
11256 ;; verification function has not moved point
11257 (goto-char (point-at-eol))))))))
11258 (when org-refile-use-cache
11259 (org-refile-cache-put tgs (buffer-file-name) descre))
11260 (setq targets (append tgs targets))
11261 ))))
11262 (message "Getting targets...done")
11263 (nreverse targets)))
11265 (defun org-protect-slash (s)
11266 (while (string-match "/" s)
11267 (setq s (replace-match "\\" t t s)))
11270 (defvar org-olpa (make-vector 20 nil))
11272 (defun org-get-outline-path (&optional fastp level heading)
11273 "Return the outline path to the current entry, as a list.
11275 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11276 routine which makes outline path derivations for an entire file,
11277 avoiding backtracing. Refile target collection makes use of that."
11278 (if fastp
11279 (progn
11280 (if (> level 19)
11281 (error "Outline path failure, more than 19 levels"))
11282 (loop for i from level upto 19 do
11283 (aset org-olpa i nil))
11284 (prog1
11285 (delq nil (append org-olpa nil))
11286 (aset org-olpa level heading)))
11287 (let (rtn case-fold-search)
11288 (save-excursion
11289 (save-restriction
11290 (widen)
11291 (while (org-up-heading-safe)
11292 (when (looking-at org-complex-heading-regexp)
11293 (push (org-match-string-no-properties 4) rtn)))
11294 rtn)))))
11296 (defun org-format-outline-path (path &optional width prefix separator)
11297 "Format the outline path PATH for display.
11298 WIDTH is the maximum number of characters that is available.
11299 PREFIX is a prefix to be included in the returned string,
11300 such as the file name.
11301 SEPARATOR is inserted between the different parts of the path,
11302 the default is \"/\"."
11303 (setq width (or width 79))
11304 (if prefix (setq width (- width (length prefix))))
11305 (if (not path)
11306 (or prefix "")
11307 (let* ((nsteps (length path))
11308 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11309 (maxwidth (if (<= total-width width)
11310 10000 ;; everything fits
11311 ;; we need to shorten the level headings
11312 (/ (- width nsteps) nsteps)))
11313 (org-odd-levels-only nil)
11314 (n 0)
11315 (total (1+ (length prefix))))
11316 (setq maxwidth (max maxwidth 10))
11317 (concat prefix
11318 (if prefix (or separator "/"))
11319 (mapconcat
11320 (lambda (h)
11321 (setq n (1+ n))
11322 (if (and (= n nsteps) (< maxwidth 10000))
11323 (setq maxwidth (- total-width total)))
11324 (if (< (length h) maxwidth)
11325 (progn (setq total (+ total (length h) 1)) h)
11326 (setq h (substring h 0 (- maxwidth 2))
11327 total (+ total maxwidth 1))
11328 (if (string-match "[ \t]+\\'" h)
11329 (setq h (substring h 0 (match-beginning 0))))
11330 (setq h (concat h "..")))
11331 (org-add-props h nil 'face
11332 (nth (% (1- n) org-n-level-faces)
11333 org-level-faces))
11335 path (or separator "/"))))))
11337 (defun org-display-outline-path (&optional file current separator just-return-string)
11338 "Display the current outline path in the echo area.
11340 If FILE is non-nil, prepend the output with the file name.
11341 If CURRENT is non-nil, append the current heading to the output.
11342 SEPARATOR is passed through to `org-format-outline-path'. It separates
11343 the different parts of the path and defaults to \"/\".
11344 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11345 (interactive "P")
11346 (let* (case-fold-search
11347 message-log-max ; Don't populate the *Messages* buffer
11348 (bfn (buffer-file-name (buffer-base-buffer)))
11349 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11350 res)
11351 (if current (setq path (append path
11352 (save-excursion
11353 (org-back-to-heading t)
11354 (if (looking-at org-complex-heading-regexp)
11355 (list (match-string 4)))))))
11356 (setq res
11357 (org-format-outline-path
11358 path
11359 (1- (frame-width))
11360 (and file bfn (concat (file-name-nondirectory bfn) separator))
11361 separator))
11362 (if just-return-string
11363 (org-no-properties res)
11364 (message "%s" res))))
11366 (defvar org-refile-history nil
11367 "History for refiling operations.")
11369 (defvar org-after-refile-insert-hook nil
11370 "Hook run after `org-refile' has inserted its stuff at the new location.
11371 Note that this is still *before* the stuff will be removed from
11372 the *old* location.")
11374 (defvar org-capture-last-stored-marker)
11375 (defvar org-refile-keep nil
11376 "Non-nil means `org-refile' will copy instead of refile.")
11378 (defun org-copy ()
11379 "Like `org-refile', but copy."
11380 (interactive)
11381 (let ((org-refile-keep t))
11382 (funcall 'org-refile nil nil nil "Copy")))
11384 (defun org-refile (&optional goto default-buffer rfloc msg)
11385 "Move the entry or entries at point to another heading.
11386 The list of target headings is compiled using the information in
11387 `org-refile-targets', which see.
11389 At the target location, the entry is filed as a subitem of the target
11390 heading. Depending on `org-reverse-note-order', the new subitem will
11391 either be the first or the last subitem.
11393 If there is an active region, all entries in that region will be moved.
11394 However, the region must fulfill the requirement that the first heading
11395 is the first one sets the top-level of the moved text - at most siblings
11396 below it are allowed.
11398 With prefix arg GOTO, the command will only visit the target location
11399 and not actually move anything.
11401 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11402 go to the location where the last refiling operation has put the subtree.
11403 With a prefix argument of `2', refile to the running clock.
11405 RFLOC can be a refile location obtained in a different way.
11407 MSG is a string to replace \"Refile\" in the default prompt with
11408 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11410 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11412 If you are using target caching (see `org-refile-use-cache'),
11413 you have to clear the target cache in order to find new targets.
11414 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11415 prefix argument (`C-u C-u C-u C-c C-w')."
11417 (interactive "P")
11418 (if (member goto '(0 (64)))
11419 (org-refile-cache-clear)
11420 (let* ((actionmsg (or msg "Refile"))
11421 (cbuf (current-buffer))
11422 (regionp (org-region-active-p))
11423 (region-start (and regionp (region-beginning)))
11424 (region-end (and regionp (region-end)))
11425 (region-length (and regionp (- region-end region-start)))
11426 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11427 pos it nbuf file re level reversed)
11428 (setq last-command nil)
11429 (when regionp
11430 (goto-char region-start)
11431 (or (bolp) (goto-char (point-at-bol)))
11432 (setq region-start (point))
11433 (unless (or (org-kill-is-subtree-p
11434 (buffer-substring region-start region-end))
11435 (prog1 org-refile-active-region-within-subtree
11436 (org-toggle-heading)))
11437 (error "The region is not a (sequence of) subtree(s)")))
11438 (if (equal goto '(16))
11439 (org-refile-goto-last-stored)
11440 (when (or
11441 (and (equal goto 2)
11442 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11443 (prog1
11444 (setq it (list (or org-clock-heading "running clock")
11445 (buffer-file-name
11446 (marker-buffer org-clock-hd-marker))
11448 (marker-position org-clock-hd-marker)))
11449 (setq goto nil)))
11450 (setq it (or rfloc
11451 (let (heading-text)
11452 (save-excursion
11453 (unless goto
11454 (org-back-to-heading t)
11455 (setq heading-text
11456 (nth 4 (org-heading-components))))
11458 (org-refile-get-location
11459 (cond (goto "Goto")
11460 (regionp (concat actionmsg " region to"))
11461 (t (concat actionmsg " subtree \""
11462 heading-text "\" to")))
11463 default-buffer
11464 (and (not (equal '(4) goto))
11465 org-refile-allow-creating-parent-nodes)
11466 goto))))))
11467 (setq file (nth 1 it)
11468 re (nth 2 it)
11469 pos (nth 3 it))
11470 (if (and (not goto)
11472 (equal (buffer-file-name) file)
11473 (if regionp
11474 (and (>= pos region-start)
11475 (<= pos region-end))
11476 (and (>= pos (point))
11477 (< pos (save-excursion
11478 (org-end-of-subtree t t))))))
11479 (error "Cannot refile to position inside the tree or region"))
11481 (setq nbuf (or (find-buffer-visiting file)
11482 (find-file-noselect file)))
11483 (if goto
11484 (progn
11485 (org-pop-to-buffer-same-window nbuf)
11486 (goto-char pos)
11487 (org-show-context 'org-goto))
11488 (if regionp
11489 (progn
11490 (org-kill-new (buffer-substring region-start region-end))
11491 (org-save-markers-in-region region-start region-end))
11492 (org-copy-subtree 1 nil t))
11493 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11494 (find-file-noselect file)))
11495 (setq reversed (org-notes-order-reversed-p))
11496 (save-excursion
11497 (save-restriction
11498 (widen)
11499 (if pos
11500 (progn
11501 (goto-char pos)
11502 (looking-at org-outline-regexp)
11503 (setq level (org-get-valid-level (funcall outline-level) 1))
11504 (goto-char
11505 (if reversed
11506 (or (outline-next-heading) (point-max))
11507 (or (save-excursion (org-get-next-sibling))
11508 (org-end-of-subtree t t)
11509 (point-max)))))
11510 (setq level 1)
11511 (if (not reversed)
11512 (goto-char (point-max))
11513 (goto-char (point-min))
11514 (or (outline-next-heading) (goto-char (point-max)))))
11515 (if (not (bolp)) (newline))
11516 (org-paste-subtree level)
11517 (when org-log-refile
11518 (org-add-log-setup 'refile nil nil 'findpos
11519 org-log-refile)
11520 (unless (eq org-log-refile 'note)
11521 (save-excursion (org-add-log-note))))
11522 (and org-auto-align-tags
11523 (let ((org-loop-over-headlines-in-active-region nil))
11524 (org-set-tags nil t)))
11525 (with-demoted-errors
11526 (bookmark-set "org-refile-last-stored"))
11527 ;; If we are refiling for capture, make sure that the
11528 ;; last-capture pointers point here
11529 (when (org-bound-and-true-p org-refile-for-capture)
11530 (with-demoted-errors
11531 (bookmark-set "org-capture-last-stored-marker"))
11532 (move-marker org-capture-last-stored-marker (point)))
11533 (if (fboundp 'deactivate-mark) (deactivate-mark))
11534 (run-hooks 'org-after-refile-insert-hook))))
11535 (unless org-refile-keep
11536 (if regionp
11537 (delete-region (point) (+ (point) region-length))
11538 (org-cut-subtree)))
11539 (when (featurep 'org-inlinetask)
11540 (org-inlinetask-remove-END-maybe))
11541 (setq org-markers-to-move nil)
11542 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11544 (defun org-refile-goto-last-stored ()
11545 "Go to the location where the last refile was stored."
11546 (interactive)
11547 (bookmark-jump "org-refile-last-stored")
11548 (message "This is the location of the last refile"))
11550 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11551 no-exclude)
11552 "Prompt the user for a refile location, using PROMPT.
11553 PROMPT should not be suffixed with a colon and a space, because
11554 this function appends the default value from
11555 `org-refile-history' automatically, if that is not empty.
11556 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11557 this is used for the GOTO interface."
11558 (let ((org-refile-targets org-refile-targets)
11559 (org-refile-use-outline-path org-refile-use-outline-path)
11560 excluded-entries)
11561 (when (and (derived-mode-p 'org-mode)
11562 (not org-refile-use-cache)
11563 (not no-exclude))
11564 (org-map-tree
11565 (lambda()
11566 (setq excluded-entries
11567 (append excluded-entries (list (org-get-heading t t)))))))
11568 (setq org-refile-target-table
11569 (org-refile-get-targets default-buffer excluded-entries)))
11570 (unless org-refile-target-table
11571 (error "No refile targets"))
11572 (let* ((cbuf (current-buffer))
11573 (partial-completion-mode nil)
11574 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11575 (cfunc (if (and org-refile-use-outline-path
11576 org-outline-path-complete-in-steps)
11577 'org-olpath-completing-read
11578 'org-icompleting-read))
11579 (extra (if org-refile-use-outline-path "/" ""))
11580 (cbnex (concat (buffer-name) extra))
11581 (filename (and cfn (expand-file-name cfn)))
11582 (tbl (mapcar
11583 (lambda (x)
11584 (if (and (not (member org-refile-use-outline-path
11585 '(file full-file-path)))
11586 (not (equal filename (nth 1 x))))
11587 (cons (concat (car x) extra " ("
11588 (file-name-nondirectory (nth 1 x)) ")")
11589 (cdr x))
11590 (cons (concat (car x) extra) (cdr x))))
11591 org-refile-target-table))
11592 (completion-ignore-case t)
11593 cdef
11594 (prompt (concat prompt
11595 (or (and (car org-refile-history)
11596 (concat " (default " (car org-refile-history) ")"))
11597 (and (assoc cbnex tbl) (setq cdef cbnex)
11598 (concat " (default " cbnex ")"))) ": "))
11599 pa answ parent-target child parent old-hist)
11600 (setq old-hist org-refile-history)
11601 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11602 nil 'org-refile-history (or cdef (car org-refile-history))))
11603 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11604 (org-refile-check-position pa)
11605 (if pa
11606 (progn
11607 (when (or (not org-refile-history)
11608 (not (eq old-hist org-refile-history))
11609 (not (equal (car pa) (car org-refile-history))))
11610 (setq org-refile-history
11611 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11612 org-refile-history
11613 (cdr org-refile-history))))
11614 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11615 (pop org-refile-history)))
11617 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11618 (progn
11619 (setq parent (match-string 1 answ)
11620 child (match-string 2 answ))
11621 (setq parent-target (or (assoc parent tbl)
11622 (assoc (concat parent "/") tbl)))
11623 (when (and parent-target
11624 (or (eq new-nodes t)
11625 (and (eq new-nodes 'confirm)
11626 (y-or-n-p (format "Create new node \"%s\"? "
11627 child)))))
11628 (org-refile-new-child parent-target child)))
11629 (error "Invalid target location")))))
11631 (declare-function org-string-nw-p "org-macs" (s))
11632 (defun org-refile-check-position (refile-pointer)
11633 "Check if the refile pointer matches the headline to which it points."
11634 (let* ((file (nth 1 refile-pointer))
11635 (re (nth 2 refile-pointer))
11636 (pos (nth 3 refile-pointer))
11637 buffer)
11638 (if (and (not (markerp pos)) (not file))
11639 (error "Please save the buffer to a file before refiling")
11640 (when (org-string-nw-p re)
11641 (setq buffer (if (markerp pos)
11642 (marker-buffer pos)
11643 (or (find-buffer-visiting file)
11644 (find-file-noselect file))))
11645 (with-current-buffer buffer
11646 (save-excursion
11647 (save-restriction
11648 (widen)
11649 (goto-char pos)
11650 (beginning-of-line 1)
11651 (unless (org-looking-at-p re)
11652 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11654 (defun org-refile-new-child (parent-target child)
11655 "Use refile target PARENT-TARGET to add new CHILD below it."
11656 (unless parent-target
11657 (error "Cannot find parent for new node"))
11658 (let ((file (nth 1 parent-target))
11659 (pos (nth 3 parent-target))
11660 level)
11661 (with-current-buffer (or (find-buffer-visiting file)
11662 (find-file-noselect file))
11663 (save-excursion
11664 (save-restriction
11665 (widen)
11666 (if pos
11667 (goto-char pos)
11668 (goto-char (point-max))
11669 (if (not (bolp)) (newline)))
11670 (when (looking-at org-outline-regexp)
11671 (setq level (funcall outline-level))
11672 (org-end-of-subtree t t))
11673 (org-back-over-empty-lines)
11674 (insert "\n" (make-string
11675 (if pos (org-get-valid-level level 1) 1) ?*)
11676 " " child "\n")
11677 (beginning-of-line 0)
11678 (list (concat (car parent-target) "/" child) file "" (point)))))))
11680 (defun org-olpath-completing-read (prompt collection &rest args)
11681 "Read an outline path like a file name."
11682 (let ((thetable collection)
11683 (org-completion-use-ido nil) ; does not work with ido.
11684 (org-completion-use-iswitchb nil)) ; or iswitchb
11685 (apply
11686 'org-icompleting-read prompt
11687 (lambda (string predicate &optional flag)
11688 (let (rtn r f (l (length string)))
11689 (cond
11690 ((eq flag nil)
11691 ;; try completion
11692 (try-completion string thetable))
11693 ((eq flag t)
11694 ;; all-completions
11695 (setq rtn (all-completions string thetable predicate))
11696 (mapcar
11697 (lambda (x)
11698 (setq r (substring x l))
11699 (if (string-match " ([^)]*)$" x)
11700 (setq f (match-string 0 x))
11701 (setq f ""))
11702 (if (string-match "/" r)
11703 (concat string (substring r 0 (match-end 0)) f)
11705 rtn))
11706 ((eq flag 'lambda)
11707 ;; exact match?
11708 (assoc string thetable)))))
11709 args)))
11711 ;;;; Dynamic blocks
11713 (defun org-find-dblock (name)
11714 "Find the first dynamic block with name NAME in the buffer.
11715 If not found, stay at current position and return nil."
11716 (let ((case-fold-search t) pos)
11717 (save-excursion
11718 (goto-char (point-min))
11719 (setq pos (and (re-search-forward
11720 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11721 (match-beginning 0))))
11722 (if pos (goto-char pos))
11723 pos))
11725 (defconst org-dblock-start-re
11726 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11727 "Matches the start line of a dynamic block, with parameters.")
11729 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11730 "Matches the end of a dynamic block.")
11732 (defun org-create-dblock (plist)
11733 "Create a dynamic block section, with parameters taken from PLIST.
11734 PLIST must contain a :name entry which is used as name of the block."
11735 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11736 (end-of-line 1)
11737 (newline))
11738 (let ((col (current-column))
11739 (name (plist-get plist :name)))
11740 (insert "#+BEGIN: " name)
11741 (while plist
11742 (if (eq (car plist) :name)
11743 (setq plist (cddr plist))
11744 (insert " " (prin1-to-string (pop plist)))))
11745 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11746 (beginning-of-line -2)))
11748 (defun org-prepare-dblock ()
11749 "Prepare dynamic block for refresh.
11750 This empties the block, puts the cursor at the insert position and returns
11751 the property list including an extra property :name with the block name."
11752 (unless (looking-at org-dblock-start-re)
11753 (error "Not at a dynamic block"))
11754 (let* ((begdel (1+ (match-end 0)))
11755 (name (org-no-properties (match-string 1)))
11756 (params (append (list :name name)
11757 (read (concat "(" (match-string 3) ")")))))
11758 (save-excursion
11759 (beginning-of-line 1)
11760 (skip-chars-forward " \t")
11761 (setq params (plist-put params :indentation-column (current-column))))
11762 (unless (re-search-forward org-dblock-end-re nil t)
11763 (error "Dynamic block not terminated"))
11764 (setq params
11765 (append params
11766 (list :content (buffer-substring
11767 begdel (match-beginning 0)))))
11768 (delete-region begdel (match-beginning 0))
11769 (goto-char begdel)
11770 (open-line 1)
11771 params))
11773 (defun org-map-dblocks (&optional command)
11774 "Apply COMMAND to all dynamic blocks in the current buffer.
11775 If COMMAND is not given, use `org-update-dblock'."
11776 (let ((cmd (or command 'org-update-dblock)))
11777 (save-excursion
11778 (goto-char (point-min))
11779 (while (re-search-forward org-dblock-start-re nil t)
11780 (goto-char (match-beginning 0))
11781 (save-excursion
11782 (condition-case nil
11783 (funcall cmd)
11784 (error (message "Error during update of dynamic block"))))
11785 (unless (re-search-forward org-dblock-end-re nil t)
11786 (error "Dynamic block not terminated"))))))
11788 (defun org-dblock-update (&optional arg)
11789 "User command for updating dynamic blocks.
11790 Update the dynamic block at point. With prefix ARG, update all dynamic
11791 blocks in the buffer."
11792 (interactive "P")
11793 (if arg
11794 (org-update-all-dblocks)
11795 (or (looking-at org-dblock-start-re)
11796 (org-beginning-of-dblock))
11797 (org-update-dblock)))
11799 (defun org-update-dblock ()
11800 "Update the dynamic block at point.
11801 This means to empty the block, parse for parameters and then call
11802 the correct writing function."
11803 (interactive)
11804 (save-window-excursion
11805 (let* ((pos (point))
11806 (line (org-current-line))
11807 (params (org-prepare-dblock))
11808 (name (plist-get params :name))
11809 (indent (plist-get params :indentation-column))
11810 (cmd (intern (concat "org-dblock-write:" name))))
11811 (message "Updating dynamic block `%s' at line %d..." name line)
11812 (funcall cmd params)
11813 (message "Updating dynamic block `%s' at line %d...done" name line)
11814 (goto-char pos)
11815 (when (and indent (> indent 0))
11816 (setq indent (make-string indent ?\ ))
11817 (save-excursion
11818 (org-beginning-of-dblock)
11819 (forward-line 1)
11820 (while (not (looking-at org-dblock-end-re))
11821 (insert indent)
11822 (beginning-of-line 2))
11823 (when (looking-at org-dblock-end-re)
11824 (and (looking-at "[ \t]+")
11825 (replace-match ""))
11826 (insert indent)))))))
11828 (defun org-beginning-of-dblock ()
11829 "Find the beginning of the dynamic block at point.
11830 Error if there is no such block at point."
11831 (let ((pos (point))
11832 beg)
11833 (end-of-line 1)
11834 (if (and (re-search-backward org-dblock-start-re nil t)
11835 (setq beg (match-beginning 0))
11836 (re-search-forward org-dblock-end-re nil t)
11837 (> (match-end 0) pos))
11838 (goto-char beg)
11839 (goto-char pos)
11840 (error "Not in a dynamic block"))))
11842 (defun org-update-all-dblocks ()
11843 "Update all dynamic blocks in the buffer.
11844 This function can be used in a hook."
11845 (interactive)
11846 (when (derived-mode-p 'org-mode)
11847 (org-map-dblocks 'org-update-dblock)))
11850 ;;;; Completion
11852 (defun org-get-export-keywords ()
11853 "Return a list of all currently understood export keywords.
11854 Export keywords include options, block names, attributes and
11855 keywords relative to each registered export back-end."
11856 (delq nil
11857 (let (keywords)
11858 (mapc
11859 (lambda (back-end)
11860 (let ((props (cdr back-end)))
11861 ;; Back-end name (for keywords, like #+LATEX:)
11862 (push (upcase (symbol-name (car back-end))) keywords)
11863 ;; Back-end options.
11864 (mapc (lambda (option) (push (cadr option) keywords))
11865 (plist-get (cdr back-end) :options-alist))))
11866 (org-bound-and-true-p org-export-registered-backends))
11867 keywords)))
11869 (defconst org-options-keywords
11870 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11871 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11872 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11873 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11874 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "TARGET:"))
11876 (defcustom org-structure-template-alist
11877 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11878 "<src lang=\"?\">\n\n</src>")
11879 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11880 "<example>\n?\n</example>")
11881 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11882 "<quote>\n?\n</quote>")
11883 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11884 "<verse>\n?\n</verse>")
11885 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11886 "<verbatim>\n?\n</verbatim>")
11887 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11888 "<center>\n?\n</center>")
11889 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11890 "<literal style=\"latex\">\n?\n</literal>")
11891 ("L" "#+LaTeX: "
11892 "<literal style=\"latex\">?</literal>")
11893 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11894 "<literal style=\"html\">\n?\n</literal>")
11895 ("H" "#+HTML: "
11896 "<literal style=\"html\">?</literal>")
11897 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11898 ("A" "#+ASCII: ")
11899 ("i" "#+INDEX: ?"
11900 "#+INDEX: ?")
11901 ("I" "#+INCLUDE: %file ?"
11902 "<include file=%file markup=\"?\">"))
11903 "Structure completion elements.
11904 This is a list of abbreviation keys and values. The value gets inserted
11905 if you type `<' followed by the key and then press the completion key,
11906 usually `M-TAB'. %file will be replaced by a file name after prompting
11907 for the file using completion. The cursor will be placed at the position
11908 of the `?` in the template.
11909 There are two templates for each key, the first uses the original Org syntax,
11910 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11911 the default when the /org-mtags.el/ module has been loaded. See also the
11912 variable `org-mtags-prefer-muse-templates'."
11913 :group 'org-completion
11914 :type '(repeat
11915 (string :tag "Key")
11916 (string :tag "Template")
11917 (string :tag "Muse Template")))
11919 (defun org-try-structure-completion ()
11920 "Try to complete a structure template before point.
11921 This looks for strings like \"<e\" on an otherwise empty line and
11922 expands them."
11923 (let ((l (buffer-substring (point-at-bol) (point)))
11925 (when (and (looking-at "[ \t]*$")
11926 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11927 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11928 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11929 (match-beginning 1)) a)
11930 t)))
11932 (defun org-complete-expand-structure-template (start cell)
11933 "Expand a structure template."
11934 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11935 (rpl (nth (if musep 2 1) cell))
11936 (ind ""))
11937 (delete-region start (point))
11938 (when (string-match "\\`#\\+" rpl)
11939 (cond
11940 ((bolp))
11941 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11942 (setq ind (buffer-substring (point-at-bol) (point))))
11943 (t (newline))))
11944 (setq start (point))
11945 (if (string-match "%file" rpl)
11946 (setq rpl (replace-match
11947 (concat
11948 "\""
11949 (save-match-data
11950 (abbreviate-file-name (read-file-name "Include file: ")))
11951 "\"")
11952 t t rpl)))
11953 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11954 (concat "\n" ind)))
11955 (insert rpl)
11956 (if (re-search-backward "\\?" start t) (delete-char 1))))
11958 ;;;; TODO, DEADLINE, Comments
11960 (defun org-toggle-comment ()
11961 "Change the COMMENT state of an entry."
11962 (interactive)
11963 (save-excursion
11964 (org-back-to-heading)
11965 (let (case-fold-search)
11966 (cond
11967 ((looking-at (format org-heading-keyword-regexp-format
11968 org-comment-string))
11969 (goto-char (match-end 1))
11970 (looking-at (concat " +" org-comment-string))
11971 (replace-match "" t t)
11972 (when (eolp) (insert " ")))
11973 ((looking-at org-outline-regexp)
11974 (goto-char (match-end 0))
11975 (insert org-comment-string " "))))))
11977 (defvar org-last-todo-state-is-todo nil
11978 "This is non-nil when the last TODO state change led to a TODO state.
11979 If the last change removed the TODO tag or switched to DONE, then
11980 this is nil.")
11982 (defvar org-setting-tags nil) ; dynamically skipped
11984 (defvar org-todo-setup-filter-hook nil
11985 "Hook for functions that pre-filter todo specs.
11986 Each function takes a todo spec and returns either nil or the spec
11987 transformed into canonical form." )
11989 (defvar org-todo-get-default-hook nil
11990 "Hook for functions that get a default item for todo.
11991 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11992 nil or a string to be used for the todo mark." )
11994 (defvar org-agenda-headline-snapshot-before-repeat)
11996 (defun org-current-effective-time ()
11997 "Return current time adjusted for `org-extend-today-until' variable."
11998 (let* ((ct (org-current-time))
11999 (dct (decode-time ct))
12000 (ct1
12001 (cond
12002 (org-use-last-clock-out-time-as-effective-time
12003 (or (org-clock-get-last-clock-out-time) ct))
12004 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12005 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12006 (t ct))))
12007 ct1))
12009 (defun org-todo-yesterday (&optional arg)
12010 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12011 (interactive "P")
12012 (if (eq major-mode 'org-agenda-mode)
12013 (apply 'org-agenda-todo-yesterday arg)
12014 (let* ((hour (third (decode-time
12015 (org-current-time))))
12016 (org-extend-today-until (1+ hour)))
12017 (org-todo arg))))
12019 (defvar org-block-entry-blocking ""
12020 "First entry preventing the TODO state change.")
12022 (defun org-todo (&optional arg)
12023 "Change the TODO state of an item.
12024 The state of an item is given by a keyword at the start of the heading,
12025 like
12026 *** TODO Write paper
12027 *** DONE Call mom
12029 The different keywords are specified in the variable `org-todo-keywords'.
12030 By default the available states are \"TODO\" and \"DONE\".
12031 So for this example: when the item starts with TODO, it is changed to DONE.
12032 When it starts with DONE, the DONE is removed. And when neither TODO nor
12033 DONE are present, add TODO at the beginning of the heading.
12035 With \\[universal-argument] prefix arg, use completion to determine the new \
12036 state.
12037 With numeric prefix arg, switch to that state.
12038 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12039 keywords (nextset).
12040 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12041 With a numeric prefix arg of 0, inhibit note taking for the change.
12043 For calling through lisp, arg is also interpreted in the following way:
12044 'none -> empty state
12045 \"\"(empty string) -> switch to empty state
12046 'done -> switch to DONE
12047 'nextset -> switch to the next set of keywords
12048 'previousset -> switch to the previous set of keywords
12049 \"WAITING\" -> switch to the specified keyword, but only if it
12050 really is a member of `org-todo-keywords'."
12051 (interactive "P")
12052 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12053 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12054 'region-start-level 'region))
12055 org-loop-over-headlines-in-active-region)
12056 (org-map-entries
12057 `(org-todo ,arg)
12058 org-loop-over-headlines-in-active-region
12059 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12060 (if (equal arg '(16)) (setq arg 'nextset))
12061 (let ((org-blocker-hook org-blocker-hook)
12062 commentp
12063 case-fold-search)
12064 (when (equal arg '(64))
12065 (setq arg nil org-blocker-hook nil))
12066 (when (and org-blocker-hook
12067 (or org-inhibit-blocking
12068 (org-entry-get nil "NOBLOCKING")))
12069 (setq org-blocker-hook nil))
12070 (save-excursion
12071 (catch 'exit
12072 (org-back-to-heading t)
12073 (when (looking-at (concat "^\\*+ " org-comment-string))
12074 (org-toggle-comment)
12075 (setq commentp t))
12076 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12077 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12078 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12079 (let* ((match-data (match-data))
12080 (startpos (point-at-bol))
12081 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12082 (org-log-done org-log-done)
12083 (org-log-repeat org-log-repeat)
12084 (org-todo-log-states org-todo-log-states)
12085 (org-inhibit-logging
12086 (if (equal arg 0)
12087 (progn (setq arg nil) 'note) org-inhibit-logging))
12088 (this (match-string 1))
12089 (hl-pos (match-beginning 0))
12090 (head (org-get-todo-sequence-head this))
12091 (ass (assoc head org-todo-kwd-alist))
12092 (interpret (nth 1 ass))
12093 (done-word (nth 3 ass))
12094 (final-done-word (nth 4 ass))
12095 (org-last-state (or this ""))
12096 (completion-ignore-case t)
12097 (member (member this org-todo-keywords-1))
12098 (tail (cdr member))
12099 (org-state (cond
12100 ((and org-todo-key-trigger
12101 (or (and (equal arg '(4))
12102 (eq org-use-fast-todo-selection 'prefix))
12103 (and (not arg) org-use-fast-todo-selection
12104 (not (eq org-use-fast-todo-selection
12105 'prefix)))))
12106 ;; Use fast selection
12107 (org-fast-todo-selection))
12108 ((and (equal arg '(4))
12109 (or (not org-use-fast-todo-selection)
12110 (not org-todo-key-trigger)))
12111 ;; Read a state with completion
12112 (org-icompleting-read
12113 "State: " (mapcar 'list org-todo-keywords-1)
12114 nil t))
12115 ((eq arg 'right)
12116 (if this
12117 (if tail (car tail) nil)
12118 (car org-todo-keywords-1)))
12119 ((eq arg 'left)
12120 (if (equal member org-todo-keywords-1)
12122 (if this
12123 (nth (- (length org-todo-keywords-1)
12124 (length tail) 2)
12125 org-todo-keywords-1)
12126 (org-last org-todo-keywords-1))))
12127 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12128 (setq arg nil))) ; hack to fall back to cycling
12129 (arg
12130 ;; user or caller requests a specific state
12131 (cond
12132 ((equal arg "") nil)
12133 ((eq arg 'none) nil)
12134 ((eq arg 'done) (or done-word (car org-done-keywords)))
12135 ((eq arg 'nextset)
12136 (or (car (cdr (member head org-todo-heads)))
12137 (car org-todo-heads)))
12138 ((eq arg 'previousset)
12139 (let ((org-todo-heads (reverse org-todo-heads)))
12140 (or (car (cdr (member head org-todo-heads)))
12141 (car org-todo-heads))))
12142 ((car (member arg org-todo-keywords-1)))
12143 ((stringp arg)
12144 (error "State `%s' not valid in this file" arg))
12145 ((nth (1- (prefix-numeric-value arg))
12146 org-todo-keywords-1))))
12147 ((null member) (or head (car org-todo-keywords-1)))
12148 ((equal this final-done-word) nil) ;; -> make empty
12149 ((null tail) nil) ;; -> first entry
12150 ((memq interpret '(type priority))
12151 (if (eq this-command last-command)
12152 (car tail)
12153 (if (> (length tail) 0)
12154 (or done-word (car org-done-keywords))
12155 nil)))
12157 (car tail))))
12158 (org-state (or
12159 (run-hook-with-args-until-success
12160 'org-todo-get-default-hook org-state org-last-state)
12161 org-state))
12162 (next (if org-state (concat " " org-state " ") " "))
12163 (change-plist (list :type 'todo-state-change :from this :to org-state
12164 :position startpos))
12165 dolog now-done-p)
12166 (when org-blocker-hook
12167 (setq org-last-todo-state-is-todo
12168 (not (member this org-done-keywords)))
12169 (unless (save-excursion
12170 (save-match-data
12171 (org-with-wide-buffer
12172 (run-hook-with-args-until-failure
12173 'org-blocker-hook change-plist))))
12174 (if (org-called-interactively-p 'interactive)
12175 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12176 this org-state org-block-entry-blocking)
12177 ;; fail silently
12178 (message "TODO state change from %s to %s blocked (by \"%s\")"
12179 this org-state org-block-entry-blocking)
12180 (throw 'exit nil))))
12181 (store-match-data match-data)
12182 (replace-match next t t)
12183 (unless (pos-visible-in-window-p hl-pos)
12184 (message "TODO state changed to %s" (org-trim next)))
12185 (unless head
12186 (setq head (org-get-todo-sequence-head org-state)
12187 ass (assoc head org-todo-kwd-alist)
12188 interpret (nth 1 ass)
12189 done-word (nth 3 ass)
12190 final-done-word (nth 4 ass)))
12191 (when (memq arg '(nextset previousset))
12192 (message "Keyword-Set %d/%d: %s"
12193 (- (length org-todo-sets) -1
12194 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12195 (length org-todo-sets)
12196 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12197 (setq org-last-todo-state-is-todo
12198 (not (member org-state org-done-keywords)))
12199 (setq now-done-p (and (member org-state org-done-keywords)
12200 (not (member this org-done-keywords))))
12201 (and logging (org-local-logging logging))
12202 (when (and (or org-todo-log-states org-log-done)
12203 (not (eq org-inhibit-logging t))
12204 (not (memq arg '(nextset previousset))))
12205 ;; we need to look at recording a time and note
12206 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12207 (nth 2 (assoc this org-todo-log-states))))
12208 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12209 (setq dolog 'time))
12210 (when (and org-state
12211 (member org-state org-not-done-keywords)
12212 (not (member this org-not-done-keywords)))
12213 ;; This is now a todo state and was not one before
12214 ;; If there was a CLOSED time stamp, get rid of it.
12215 (org-add-planning-info nil nil 'closed))
12216 (when (and now-done-p org-log-done)
12217 ;; It is now done, and it was not done before
12218 (org-add-planning-info 'closed (org-current-effective-time))
12219 (if (and (not dolog) (eq 'note org-log-done))
12220 (org-add-log-setup 'done org-state this 'findpos 'note)))
12221 (when (and org-state dolog)
12222 ;; This is a non-nil state, and we need to log it
12223 (org-add-log-setup 'state org-state this 'findpos dolog)))
12224 ;; Fixup tag positioning
12225 (org-todo-trigger-tag-changes org-state)
12226 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12227 (when org-provide-todo-statistics
12228 (org-update-parent-todo-statistics))
12229 (run-hooks 'org-after-todo-state-change-hook)
12230 (if (and arg (not (member org-state org-done-keywords)))
12231 (setq head (org-get-todo-sequence-head org-state)))
12232 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12233 ;; Do we need to trigger a repeat?
12234 (when now-done-p
12235 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12236 ;; This is for the agenda, take a snapshot of the headline.
12237 (save-match-data
12238 (setq org-agenda-headline-snapshot-before-repeat
12239 (org-get-heading))))
12240 (org-auto-repeat-maybe org-state))
12241 ;; Fixup cursor location if close to the keyword
12242 (if (and (outline-on-heading-p)
12243 (not (bolp))
12244 (save-excursion (beginning-of-line 1)
12245 (looking-at org-todo-line-regexp))
12246 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12247 (progn
12248 (goto-char (or (match-end 2) (match-end 1)))
12249 (and (looking-at " ") (just-one-space))))
12250 (when org-trigger-hook
12251 (save-excursion
12252 (run-hook-with-args 'org-trigger-hook change-plist)))
12253 (when commentp (org-toggle-comment))))))))
12255 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12256 "Block turning an entry into a TODO, using the hierarchy.
12257 This checks whether the current task should be blocked from state
12258 changes. Such blocking occurs when:
12260 1. The task has children which are not all in a completed state.
12262 2. A task has a parent with the property :ORDERED:, and there
12263 are siblings prior to the current task with incomplete
12264 status.
12266 3. The parent of the task is blocked because it has siblings that should
12267 be done first, or is child of a block grandparent TODO entry."
12269 (if (not org-enforce-todo-dependencies)
12270 t ; if locally turned off don't block
12271 (catch 'dont-block
12272 ;; If this is not a todo state change, or if this entry is already DONE,
12273 ;; do not block
12274 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12275 (member (plist-get change-plist :from)
12276 (cons 'done org-done-keywords))
12277 (member (plist-get change-plist :to)
12278 (cons 'todo org-not-done-keywords))
12279 (not (plist-get change-plist :to)))
12280 (throw 'dont-block t))
12281 ;; If this task has children, and any are undone, it's blocked
12282 (save-excursion
12283 (org-back-to-heading t)
12284 (let ((this-level (funcall outline-level)))
12285 (outline-next-heading)
12286 (let ((child-level (funcall outline-level)))
12287 (while (and (not (eobp))
12288 (> child-level this-level))
12289 ;; this todo has children, check whether they are all
12290 ;; completed
12291 (if (and (not (org-entry-is-done-p))
12292 (org-entry-is-todo-p))
12293 (progn (setq org-block-entry-blocking (org-get-heading))
12294 (throw 'dont-block nil)))
12295 (outline-next-heading)
12296 (setq child-level (funcall outline-level))))))
12297 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12298 ;; any previous siblings are undone, it's blocked
12299 (save-excursion
12300 (org-back-to-heading t)
12301 (let* ((pos (point))
12302 (parent-pos (and (org-up-heading-safe) (point))))
12303 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12304 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12305 (forward-line 1)
12306 (re-search-forward org-not-done-heading-regexp pos t))
12307 (setq org-block-entry-blocking (match-string 0))
12308 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12309 ;; Search further up the hierarchy, to see if an ancestor is blocked
12310 (while t
12311 (goto-char parent-pos)
12312 (if (not (looking-at org-not-done-heading-regexp))
12313 (throw 'dont-block t)) ; do not block, parent is not a TODO
12314 (setq pos (point))
12315 (setq parent-pos (and (org-up-heading-safe) (point)))
12316 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12317 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12318 (forward-line 1)
12319 (re-search-forward org-not-done-heading-regexp pos t)
12320 (setq org-block-entry-blocking (org-get-heading)))
12321 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12323 (defcustom org-track-ordered-property-with-tag nil
12324 "Should the ORDERED property also be shown as a tag?
12325 The ORDERED property decides if an entry should require subtasks to be
12326 completed in sequence. Since a property is not very visible, setting
12327 this option means that toggling the ORDERED property with the command
12328 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12329 not relevant for the behavior, but it makes things more visible.
12331 Note that toggling the tag with tags commands will not change the property
12332 and therefore not influence behavior!
12334 This can be t, meaning the tag ORDERED should be used, It can also be a
12335 string to select a different tag for this task."
12336 :group 'org-todo
12337 :type '(choice
12338 (const :tag "No tracking" nil)
12339 (const :tag "Track with ORDERED tag" t)
12340 (string :tag "Use other tag")))
12342 (defun org-toggle-ordered-property ()
12343 "Toggle the ORDERED property of the current entry.
12344 For better visibility, you can track the value of this property with a tag.
12345 See variable `org-track-ordered-property-with-tag'."
12346 (interactive)
12347 (let* ((t1 org-track-ordered-property-with-tag)
12348 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12349 (save-excursion
12350 (org-back-to-heading)
12351 (if (org-entry-get nil "ORDERED")
12352 (progn
12353 (org-delete-property "ORDERED" "PROPERTIES")
12354 (and tag (org-toggle-tag tag 'off))
12355 (message "Subtasks can be completed in arbitrary order"))
12356 (org-entry-put nil "ORDERED" "t")
12357 (and tag (org-toggle-tag tag 'on))
12358 (message "Subtasks must be completed in sequence")))))
12360 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12361 (defun org-block-todo-from-checkboxes (change-plist)
12362 "Block turning an entry into a TODO, using checkboxes.
12363 This checks whether the current task should be blocked from state
12364 changes because there are unchecked boxes in this entry."
12365 (if (not org-enforce-todo-checkbox-dependencies)
12366 t ; if locally turned off don't block
12367 (catch 'dont-block
12368 ;; If this is not a todo state change, or if this entry is already DONE,
12369 ;; do not block
12370 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12371 (member (plist-get change-plist :from)
12372 (cons 'done org-done-keywords))
12373 (member (plist-get change-plist :to)
12374 (cons 'todo org-not-done-keywords))
12375 (not (plist-get change-plist :to)))
12376 (throw 'dont-block t))
12377 ;; If this task has checkboxes that are not checked, it's blocked
12378 (save-excursion
12379 (org-back-to-heading t)
12380 (let ((beg (point)) end)
12381 (outline-next-heading)
12382 (setq end (point))
12383 (goto-char beg)
12384 (if (org-list-search-forward
12385 (concat (org-item-beginning-re)
12386 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12387 "\\[[- ]\\]")
12388 end t)
12389 (progn
12390 (if (boundp 'org-blocked-by-checkboxes)
12391 (setq org-blocked-by-checkboxes t))
12392 (throw 'dont-block nil)))))
12393 t))) ; do not block
12395 (defun org-entry-blocked-p ()
12396 "Is the current entry blocked?"
12397 (org-with-silent-modifications
12398 (if (org-entry-get nil "NOBLOCKING")
12399 nil ;; Never block this entry
12400 (not (run-hook-with-args-until-failure
12401 'org-blocker-hook
12402 (list :type 'todo-state-change
12403 :position (point)
12404 :from 'todo
12405 :to 'done))))))
12407 (defun org-update-statistics-cookies (all)
12408 "Update the statistics cookie, either from TODO or from checkboxes.
12409 This should be called with the cursor in a line with a statistics cookie."
12410 (interactive "P")
12411 (if all
12412 (progn
12413 (org-update-checkbox-count 'all)
12414 (org-map-entries 'org-update-parent-todo-statistics))
12415 (if (not (org-at-heading-p))
12416 (org-update-checkbox-count)
12417 (let ((pos (point-marker))
12418 end l1 l2)
12419 (ignore-errors (org-back-to-heading t))
12420 (if (not (org-at-heading-p))
12421 (org-update-checkbox-count)
12422 (setq l1 (org-outline-level))
12423 (setq end (save-excursion
12424 (outline-next-heading)
12425 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12426 (point)))
12427 (if (and (save-excursion
12428 (re-search-forward
12429 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12430 (not (save-excursion (re-search-forward
12431 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12432 (org-update-checkbox-count)
12433 (if (and l2 (> l2 l1))
12434 (progn
12435 (goto-char end)
12436 (org-update-parent-todo-statistics))
12437 (goto-char pos)
12438 (beginning-of-line 1)
12439 (while (re-search-forward
12440 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12441 (point-at-eol) t)
12442 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12443 (goto-char pos)
12444 (move-marker pos nil)))))
12446 (defvar org-entry-property-inherited-from) ;; defined below
12447 (defun org-update-parent-todo-statistics ()
12448 "Update any statistics cookie in the parent of the current headline.
12449 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12450 the entire subtree and this will travel up the hierarchy and update
12451 statistics everywhere."
12452 (let* ((prop (save-excursion (org-up-heading-safe)
12453 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12454 (recursive (or (not org-hierarchical-todo-statistics)
12455 (and prop (string-match "\\<recursive\\>" prop))))
12456 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12458 (first t)
12459 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12460 level ltoggle l1 new ndel
12461 (cnt-all 0) (cnt-done 0) is-percent kwd
12462 checkbox-beg ov ovs ove cookie-present)
12463 (catch 'exit
12464 (save-excursion
12465 (beginning-of-line 1)
12466 (setq ltoggle (funcall outline-level))
12467 ;; Three situations are to consider:
12469 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12470 ;; to the top-level ancestor on the headline;
12472 ;; 2. If parent has "recursive" property, repeat up to the
12473 ;; headline setting that property, taking inheritance into
12474 ;; account;
12476 ;; 3. Else, move up to direct parent and proceed only once.
12477 (while (and (setq level (org-up-heading-safe))
12478 (or recursive first)
12479 (>= (point) lim))
12480 (setq first nil cookie-present nil)
12481 (unless (and level
12482 (not (string-match
12483 "\\<checkbox\\>"
12484 (downcase (or (org-entry-get nil "COOKIE_DATA")
12485 "")))))
12486 (throw 'exit nil))
12487 (while (re-search-forward box-re (point-at-eol) t)
12488 (setq cnt-all 0 cnt-done 0 cookie-present t)
12489 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12490 (save-match-data
12491 (unless (outline-next-heading) (throw 'exit nil))
12492 (while (and (looking-at org-complex-heading-regexp)
12493 (> (setq l1 (length (match-string 1))) level))
12494 (setq kwd (and (or recursive (= l1 ltoggle))
12495 (match-string 2)))
12496 (if (or (eq org-provide-todo-statistics 'all-headlines)
12497 (and (listp org-provide-todo-statistics)
12498 (or (member kwd org-provide-todo-statistics)
12499 (member kwd org-done-keywords))))
12500 (setq cnt-all (1+ cnt-all))
12501 (if (eq org-provide-todo-statistics t)
12502 (and kwd (setq cnt-all (1+ cnt-all)))))
12503 (and (member kwd org-done-keywords)
12504 (setq cnt-done (1+ cnt-done)))
12505 (outline-next-heading)))
12506 (setq new
12507 (if is-percent
12508 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12509 (format "[%d/%d]" cnt-done cnt-all))
12510 ndel (- (match-end 0) checkbox-beg))
12511 ;; handle overlays when updating cookie from column view
12512 (when (setq ov (car (overlays-at checkbox-beg)))
12513 (setq ovs (overlay-start ov) ove (overlay-end ov))
12514 (delete-overlay ov))
12515 (goto-char checkbox-beg)
12516 (insert new)
12517 (delete-region (point) (+ (point) ndel))
12518 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12519 (when ov (move-overlay ov ovs ove)))
12520 (when cookie-present
12521 (run-hook-with-args 'org-after-todo-statistics-hook
12522 cnt-done (- cnt-all cnt-done))))))
12523 (run-hooks 'org-todo-statistics-hook)))
12525 (defvar org-after-todo-statistics-hook nil
12526 "Hook that is called after a TODO statistics cookie has been updated.
12527 Each function is called with two arguments: the number of not-done entries
12528 and the number of done entries.
12530 For example, the following function, when added to this hook, will switch
12531 an entry to DONE when all children are done, and back to TODO when new
12532 entries are set to a TODO status. Note that this hook is only called
12533 when there is a statistics cookie in the headline!
12535 (defun org-summary-todo (n-done n-not-done)
12536 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12537 (let (org-log-done org-log-states) ; turn off logging
12538 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12541 (defvar org-todo-statistics-hook nil
12542 "Hook that is run whenever Org thinks TODO statistics should be updated.
12543 This hook runs even if there is no statistics cookie present, in which case
12544 `org-after-todo-statistics-hook' would not run.")
12546 (defun org-todo-trigger-tag-changes (state)
12547 "Apply the changes defined in `org-todo-state-tags-triggers'."
12548 (let ((l org-todo-state-tags-triggers)
12549 changes)
12550 (when (or (not state) (equal state ""))
12551 (setq changes (append changes (cdr (assoc "" l)))))
12552 (when (and (stringp state) (> (length state) 0))
12553 (setq changes (append changes (cdr (assoc state l)))))
12554 (when (member state org-not-done-keywords)
12555 (setq changes (append changes (cdr (assoc 'todo l)))))
12556 (when (member state org-done-keywords)
12557 (setq changes (append changes (cdr (assoc 'done l)))))
12558 (dolist (c changes)
12559 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12561 (defun org-local-logging (value)
12562 "Get logging settings from a property VALUE."
12563 (let* (words w a)
12564 ;; directly set the variables, they are already local.
12565 (setq org-log-done nil
12566 org-log-repeat nil
12567 org-todo-log-states nil)
12568 (setq words (org-split-string value))
12569 (while (setq w (pop words))
12570 (cond
12571 ((setq a (assoc w org-startup-options))
12572 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12573 (set (nth 1 a) (nth 2 a))))
12574 ((setq a (org-extract-log-state-settings w))
12575 (and (member (car a) org-todo-keywords-1)
12576 (push a org-todo-log-states)))))))
12578 (defun org-get-todo-sequence-head (kwd)
12579 "Return the head of the TODO sequence to which KWD belongs.
12580 If KWD is not set, check if there is a text property remembering the
12581 right sequence."
12582 (let (p)
12583 (cond
12584 ((not kwd)
12585 (or (get-text-property (point-at-bol) 'org-todo-head)
12586 (progn
12587 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12588 nil (point-at-eol)))
12589 (get-text-property p 'org-todo-head))))
12590 ((not (member kwd org-todo-keywords-1))
12591 (car org-todo-keywords-1))
12592 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12594 (defun org-fast-todo-selection ()
12595 "Fast TODO keyword selection with single keys.
12596 Returns the new TODO keyword, or nil if no state change should occur."
12597 (let* ((fulltable org-todo-key-alist)
12598 (done-keywords org-done-keywords) ;; needed for the faces.
12599 (maxlen (apply 'max (mapcar
12600 (lambda (x)
12601 (if (stringp (car x)) (string-width (car x)) 0))
12602 fulltable)))
12603 (expert nil)
12604 (fwidth (+ maxlen 3 1 3))
12605 (ncol (/ (- (window-width) 4) fwidth))
12606 tg cnt e c tbl
12607 groups ingroup)
12608 (save-excursion
12609 (save-window-excursion
12610 (if expert
12611 (set-buffer (get-buffer-create " *Org todo*"))
12612 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12613 (erase-buffer)
12614 (org-set-local 'org-done-keywords done-keywords)
12615 (setq tbl fulltable cnt 0)
12616 (while (setq e (pop tbl))
12617 (cond
12618 ((equal e '(:startgroup))
12619 (push '() groups) (setq ingroup t)
12620 (when (not (= cnt 0))
12621 (setq cnt 0)
12622 (insert "\n"))
12623 (insert "{ "))
12624 ((equal e '(:endgroup))
12625 (setq ingroup nil cnt 0)
12626 (insert "}\n"))
12627 ((equal e '(:newline))
12628 (when (not (= cnt 0))
12629 (setq cnt 0)
12630 (insert "\n")
12631 (setq e (car tbl))
12632 (while (equal (car tbl) '(:newline))
12633 (insert "\n")
12634 (setq tbl (cdr tbl)))))
12636 (setq tg (car e) c (cdr e))
12637 (if ingroup (push tg (car groups)))
12638 (setq tg (org-add-props tg nil 'face
12639 (org-get-todo-face tg)))
12640 (if (and (= cnt 0) (not ingroup)) (insert " "))
12641 (insert "[" c "] " tg (make-string
12642 (- fwidth 4 (length tg)) ?\ ))
12643 (when (= (setq cnt (1+ cnt)) ncol)
12644 (insert "\n")
12645 (if ingroup (insert " "))
12646 (setq cnt 0)))))
12647 (insert "\n")
12648 (goto-char (point-min))
12649 (if (not expert) (org-fit-window-to-buffer))
12650 (message "[a-z..]:Set [SPC]:clear")
12651 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12652 (cond
12653 ((or (= c ?\C-g)
12654 (and (= c ?q) (not (rassoc c fulltable))))
12655 (setq quit-flag t))
12656 ((= c ?\ ) nil)
12657 ((setq e (rassoc c fulltable) tg (car e))
12659 (t (setq quit-flag t)))))))
12661 (defun org-entry-is-todo-p ()
12662 (member (org-get-todo-state) org-not-done-keywords))
12664 (defun org-entry-is-done-p ()
12665 (member (org-get-todo-state) org-done-keywords))
12667 (defun org-get-todo-state ()
12668 (save-excursion
12669 (org-back-to-heading t)
12670 (and (looking-at org-todo-line-regexp)
12671 (match-end 2)
12672 (match-string 2))))
12674 (defun org-at-date-range-p (&optional inactive-ok)
12675 "Is the cursor inside a date range?"
12676 (interactive)
12677 (save-excursion
12678 (catch 'exit
12679 (let ((pos (point)))
12680 (skip-chars-backward "^[<\r\n")
12681 (skip-chars-backward "<[")
12682 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12683 (>= (match-end 0) pos)
12684 (throw 'exit t))
12685 (skip-chars-backward "^<[\r\n")
12686 (skip-chars-backward "<[")
12687 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12688 (>= (match-end 0) pos)
12689 (throw 'exit t)))
12690 nil)))
12692 (defun org-get-repeat (&optional tagline)
12693 "Check if there is a deadline/schedule with repeater in this entry."
12694 (save-match-data
12695 (save-excursion
12696 (org-back-to-heading t)
12697 (and (re-search-forward (if tagline
12698 (concat tagline "\\s-*" org-repeat-re)
12699 org-repeat-re)
12700 (org-entry-end-position) t)
12701 (match-string-no-properties 1)))))
12703 (defvar org-last-changed-timestamp)
12704 (defvar org-last-inserted-timestamp)
12705 (defvar org-log-post-message)
12706 (defvar org-log-note-purpose)
12707 (defvar org-log-note-how)
12708 (defvar org-log-note-extra)
12709 (defun org-auto-repeat-maybe (done-word)
12710 "Check if the current headline contains a repeated deadline/schedule.
12711 If yes, set TODO state back to what it was and change the base date
12712 of repeating deadline/scheduled time stamps to new date.
12713 This function is run automatically after each state change to a DONE state."
12714 ;; last-state is dynamically scoped into this function
12715 (let* ((repeat (org-get-repeat))
12716 (aa (assoc org-last-state org-todo-kwd-alist))
12717 (interpret (nth 1 aa))
12718 (head (nth 2 aa))
12719 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12720 (msg "Entry repeats: ")
12721 (org-log-done nil)
12722 (org-todo-log-states nil)
12723 re type n what ts time to-state)
12724 (when repeat
12725 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12726 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12727 org-todo-repeat-to-state))
12728 (unless (and to-state (member to-state org-todo-keywords-1))
12729 (setq to-state (if (eq interpret 'type) org-last-state head)))
12730 (org-todo to-state)
12731 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12732 (org-entry-put nil "LAST_REPEAT" (format-time-string
12733 (org-time-stamp-format t t))))
12734 (when org-log-repeat
12735 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12736 (memq 'org-add-log-note post-command-hook))
12737 ;; OK, we are already setup for some record
12738 (if (eq org-log-repeat 'note)
12739 ;; make sure we take a note, not only a time stamp
12740 (setq org-log-note-how 'note))
12741 ;; Set up for taking a record
12742 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12743 org-last-state
12744 'findpos org-log-repeat)))
12745 (org-back-to-heading t)
12746 (org-add-planning-info nil nil 'closed)
12747 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12748 org-deadline-time-regexp "\\)\\|\\("
12749 org-ts-regexp "\\)"))
12750 (while (re-search-forward
12751 re (save-excursion (outline-next-heading) (point)) t)
12752 (setq type (if (match-end 1) org-scheduled-string
12753 (if (match-end 3) org-deadline-string "Plain:"))
12754 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12755 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12756 (setq n (string-to-number (match-string 2 ts))
12757 what (match-string 3 ts))
12758 (if (equal what "w") (setq n (* n 7) what "d"))
12759 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12760 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12761 ;; Preparation, see if we need to modify the start date for the change
12762 (when (match-end 1)
12763 (setq time (save-match-data (org-time-string-to-time ts)))
12764 (cond
12765 ((equal (match-string 1 ts) ".")
12766 ;; Shift starting date to today
12767 (org-timestamp-change
12768 (- (org-today) (time-to-days time))
12769 'day))
12770 ((equal (match-string 1 ts) "+")
12771 (let ((nshiftmax 10) (nshift 0))
12772 (while (or (= nshift 0)
12773 (<= (time-to-days time)
12774 (time-to-days (current-time))))
12775 (when (= (incf nshift) nshiftmax)
12776 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12777 (error "Abort")))
12778 (org-timestamp-change n (cdr (assoc what whata)))
12779 (org-at-timestamp-p t)
12780 (setq ts (match-string 1))
12781 (setq time (save-match-data (org-time-string-to-time ts)))))
12782 (org-timestamp-change (- n) (cdr (assoc what whata)))
12783 ;; rematch, so that we have everything in place for the real shift
12784 (org-at-timestamp-p t)
12785 (setq ts (match-string 1))
12786 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12787 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12788 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12789 (setq org-log-post-message msg)
12790 (message "%s" msg))))
12792 (defun org-show-todo-tree (arg)
12793 "Make a compact tree which shows all headlines marked with TODO.
12794 The tree will show the lines where the regexp matches, and all higher
12795 headlines above the match.
12796 With a \\[universal-argument] prefix, prompt for a regexp to match.
12797 With a numeric prefix N, construct a sparse tree for the Nth element
12798 of `org-todo-keywords-1'."
12799 (interactive "P")
12800 (let ((case-fold-search nil)
12801 (kwd-re
12802 (cond ((null arg) org-not-done-regexp)
12803 ((equal arg '(4))
12804 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12805 (mapcar 'list org-todo-keywords-1))))
12806 (concat "\\("
12807 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12808 "\\)\\>")))
12809 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12810 (regexp-quote (nth (1- (prefix-numeric-value arg))
12811 org-todo-keywords-1)))
12812 (t (error "Invalid prefix argument: %s" arg)))))
12813 (message "%d TODO entries found"
12814 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12816 (defun org-deadline (arg &optional time)
12817 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12818 With one universal prefix argument, remove any deadline from the item.
12819 With two universal prefix arguments, prompt for a warning delay.
12820 With argument TIME, set the deadline at the corresponding date. TIME
12821 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12822 (interactive "P")
12823 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12824 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12825 'region-start-level 'region))
12826 org-loop-over-headlines-in-active-region)
12827 (org-map-entries
12828 `(org-deadline ',arg ,time)
12829 org-loop-over-headlines-in-active-region
12830 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12831 (let* ((old-date (org-entry-get nil "DEADLINE"))
12832 (old-date-time (if old-date (org-time-string-to-time old-date)))
12833 (repeater (and old-date
12834 (string-match
12835 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12836 old-date)
12837 (match-string 1 old-date))))
12838 (cond
12839 ((equal arg '(4))
12840 (when (and old-date org-log-redeadline)
12841 (org-add-log-setup 'deldeadline nil old-date 'findpos
12842 org-log-redeadline))
12843 (org-remove-timestamp-with-keyword org-deadline-string)
12844 (message "Item no longer has a deadline."))
12845 ((equal arg '(16))
12846 (save-excursion
12847 (if (re-search-forward
12848 org-deadline-time-regexp
12849 (save-excursion (outline-next-heading) (point)) t)
12850 (let* ((rpl0 (match-string 1))
12851 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12852 (replace-match
12853 (concat org-deadline-string
12854 " <" rpl
12855 (format " -%dd"
12856 (abs
12857 (- (time-to-days
12858 (save-match-data
12859 (org-read-date nil t nil "Warn starting from" old-date-time)))
12860 (time-to-days old-date-time))))
12861 ">") t t))
12862 (user-error "No deadline information to update"))))
12864 (org-add-planning-info 'deadline time 'closed)
12865 (when (and old-date org-log-redeadline
12866 (not (equal old-date
12867 (substring org-last-inserted-timestamp 1 -1))))
12868 (org-add-log-setup 'redeadline nil old-date 'findpos
12869 org-log-redeadline))
12870 (when repeater
12871 (save-excursion
12872 (org-back-to-heading t)
12873 (when (re-search-forward (concat org-deadline-string " "
12874 org-last-inserted-timestamp)
12875 (save-excursion
12876 (outline-next-heading) (point)) t)
12877 (goto-char (1- (match-end 0)))
12878 (insert " " repeater)
12879 (setq org-last-inserted-timestamp
12880 (concat (substring org-last-inserted-timestamp 0 -1)
12881 " " repeater
12882 (substring org-last-inserted-timestamp -1))))))
12883 (message "Deadline on %s" org-last-inserted-timestamp))))))
12885 (defun org-schedule (arg &optional time)
12886 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12887 With one universal prefix argument, remove any scheduling date from the item.
12888 With two universal prefix arguments, prompt for a delay cookie.
12889 With argument TIME, scheduled at the corresponding date. TIME can
12890 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12891 (interactive "P")
12892 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12893 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12894 'region-start-level 'region))
12895 org-loop-over-headlines-in-active-region)
12896 (org-map-entries
12897 `(org-schedule ',arg ,time)
12898 org-loop-over-headlines-in-active-region
12899 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12900 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12901 (old-date-time (if old-date (org-time-string-to-time old-date)))
12902 (repeater (and old-date
12903 (string-match
12904 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12905 old-date)
12906 (match-string 1 old-date))))
12907 (cond
12908 ((equal arg '(4))
12909 (progn
12910 (when (and old-date org-log-reschedule)
12911 (org-add-log-setup 'delschedule nil old-date 'findpos
12912 org-log-reschedule))
12913 (org-remove-timestamp-with-keyword org-scheduled-string)
12914 (message "Item is no longer scheduled.")))
12915 ((equal arg '(16))
12916 (save-excursion
12917 (if (re-search-forward
12918 org-scheduled-time-regexp
12919 (save-excursion (outline-next-heading) (point)) t)
12920 (let* ((rpl0 (match-string 1))
12921 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12922 (replace-match
12923 (concat org-scheduled-string
12924 " <" rpl
12925 (format " -%dd"
12926 (abs
12927 (- (time-to-days
12928 (save-match-data
12929 (org-read-date nil t nil "Delay until" old-date-time)))
12930 (time-to-days old-date-time))))
12931 ">") t t))
12932 (user-error "No scheduled information to update"))))
12934 (org-add-planning-info 'scheduled time 'closed)
12935 (when (and old-date org-log-reschedule
12936 (not (equal old-date
12937 (substring org-last-inserted-timestamp 1 -1))))
12938 (org-add-log-setup 'reschedule nil old-date 'findpos
12939 org-log-reschedule))
12940 (when repeater
12941 (save-excursion
12942 (org-back-to-heading t)
12943 (when (re-search-forward (concat org-scheduled-string " "
12944 org-last-inserted-timestamp)
12945 (save-excursion
12946 (outline-next-heading) (point)) t)
12947 (goto-char (1- (match-end 0)))
12948 (insert " " repeater)
12949 (setq org-last-inserted-timestamp
12950 (concat (substring org-last-inserted-timestamp 0 -1)
12951 " " repeater
12952 (substring org-last-inserted-timestamp -1))))))
12953 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12955 (defun org-get-scheduled-time (pom &optional inherit)
12956 "Get the scheduled time as a time tuple, of a format suitable
12957 for calling org-schedule with, or if there is no scheduling,
12958 returns nil."
12959 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12960 (when time
12961 (apply 'encode-time (org-parse-time-string time)))))
12963 (defun org-get-deadline-time (pom &optional inherit)
12964 "Get the deadline as a time tuple, of a format suitable for
12965 calling org-deadline with, or if there is no scheduling, returns
12966 nil."
12967 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12968 (when time
12969 (apply 'encode-time (org-parse-time-string time)))))
12971 (defun org-remove-timestamp-with-keyword (keyword)
12972 "Remove all time stamps with KEYWORD in the current entry."
12973 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12974 beg)
12975 (save-excursion
12976 (org-back-to-heading t)
12977 (setq beg (point))
12978 (outline-next-heading)
12979 (while (re-search-backward re beg t)
12980 (replace-match "")
12981 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12982 (equal (char-before) ?\ ))
12983 (backward-delete-char 1)
12984 (if (string-match "^[ \t]*$" (buffer-substring
12985 (point-at-bol) (point-at-eol)))
12986 (delete-region (point-at-bol)
12987 (min (point-max) (1+ (point-at-eol))))))))))
12989 (defun org-add-planning-info (what &optional time &rest remove)
12990 "Insert new timestamp with keyword in the line directly after the headline.
12991 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12992 If non is given, the user is prompted for a date.
12993 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12994 be removed."
12995 (interactive)
12996 (let (org-time-was-given org-end-time-was-given ts
12997 end default-time default-input)
12999 (catch 'exit
13000 (when (and (memq what '(scheduled deadline))
13001 (or (not time)
13002 (and (stringp time)
13003 (string-match "^[-+]+[0-9]" time))))
13004 ;; Try to get a default date/time from existing timestamp
13005 (save-excursion
13006 (org-back-to-heading t)
13007 (setq end (save-excursion (outline-next-heading) (point)))
13008 (when (re-search-forward (if (eq what 'scheduled)
13009 org-scheduled-time-regexp
13010 org-deadline-time-regexp)
13011 end t)
13012 (setq ts (match-string 1)
13013 default-time
13014 (apply 'encode-time (org-parse-time-string ts))
13015 default-input (and ts (org-get-compact-tod ts))))))
13016 (when what
13017 (setq time
13018 (if (stringp time)
13019 ;; This is a string (relative or absolute), set proper date
13020 (apply 'encode-time
13021 (org-read-date-analyze
13022 time default-time (decode-time default-time)))
13023 ;; If necessary, get the time from the user
13024 (or time (org-read-date nil 'to-time nil nil
13025 default-time default-input)))))
13027 (when (and org-insert-labeled-timestamps-at-point
13028 (member what '(scheduled deadline)))
13029 (insert
13030 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13031 (org-insert-time-stamp time org-time-was-given
13032 nil nil nil (list org-end-time-was-given))
13033 (setq what nil))
13034 (save-excursion
13035 (save-restriction
13036 (let (col list elt ts buffer-invisibility-spec)
13037 (org-back-to-heading t)
13038 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13039 (goto-char (match-end 1))
13040 (setq col (current-column))
13041 (goto-char (match-end 0))
13042 (if (eobp) (insert "\n") (forward-char 1))
13043 (when (and (not what)
13044 (not (looking-at
13045 (concat "[ \t]*"
13046 org-keyword-time-not-clock-regexp))))
13047 ;; Nothing to add, nothing to remove...... :-)
13048 (throw 'exit nil))
13049 (if (and (not (looking-at org-outline-regexp))
13050 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13051 "[^\r\n]*"))
13052 (not (equal (match-string 1) org-clock-string)))
13053 (narrow-to-region (match-beginning 0) (match-end 0))
13054 (insert-before-markers "\n")
13055 (backward-char 1)
13056 (narrow-to-region (point) (point))
13057 (and org-adapt-indentation (org-indent-to-column col)))
13058 ;; Check if we have to remove something.
13059 (setq list (cons what remove))
13060 (while list
13061 (setq elt (pop list))
13062 (when (or (and (eq elt 'scheduled)
13063 (re-search-forward org-scheduled-time-regexp nil t))
13064 (and (eq elt 'deadline)
13065 (re-search-forward org-deadline-time-regexp nil t))
13066 (and (eq elt 'closed)
13067 (re-search-forward org-closed-time-regexp nil t)))
13068 (replace-match "")
13069 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13070 (and (looking-at "[ \t]+") (replace-match ""))
13071 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13072 (when what
13073 (insert
13074 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13075 (cond ((eq what 'scheduled) org-scheduled-string)
13076 ((eq what 'deadline) org-deadline-string)
13077 ((eq what 'closed) org-closed-string))
13078 " ")
13079 (setq ts (org-insert-time-stamp
13080 time
13081 (or org-time-was-given
13082 (and (eq what 'closed) org-log-done-with-time))
13083 (eq what 'closed)
13084 nil nil (list org-end-time-was-given)))
13085 (insert
13086 (if (not (or (bolp) (eq (char-before) ?\ )
13087 (memq (char-after) '(32 10))
13088 (eobp))) " " ""))
13089 (end-of-line 1))
13090 (goto-char (point-min))
13091 (widen)
13092 (if (and (looking-at "[ \t]*\n")
13093 (equal (char-before) ?\n))
13094 (delete-region (1- (point)) (point-at-eol)))
13095 ts))))))
13097 (defvar org-log-note-marker (make-marker))
13098 (defvar org-log-note-purpose nil)
13099 (defvar org-log-note-state nil)
13100 (defvar org-log-note-previous-state nil)
13101 (defvar org-log-note-how nil)
13102 (defvar org-log-note-extra nil)
13103 (defvar org-log-note-window-configuration nil)
13104 (defvar org-log-note-return-to (make-marker))
13105 (defvar org-log-note-effective-time nil
13106 "Remembered current time so that dynamically scoped
13107 `org-extend-today-until' affects tha timestamps in state change
13108 log")
13110 (defvar org-log-post-message nil
13111 "Message to be displayed after a log note has been stored.
13112 The auto-repeater uses this.")
13114 (defun org-add-note ()
13115 "Add a note to the current entry.
13116 This is done in the same way as adding a state change note."
13117 (interactive)
13118 (org-add-log-setup 'note nil nil 'findpos nil))
13120 (defvar org-property-end-re)
13121 (defun org-add-log-setup (&optional purpose state prev-state
13122 findpos how extra)
13123 "Set up the post command hook to take a note.
13124 If this is about to TODO state change, the new state is expected in STATE.
13125 When FINDPOS is non-nil, find the correct position for the note in
13126 the current entry. If not, assume that it can be inserted at point.
13127 HOW is an indicator what kind of note should be created.
13128 EXTRA is additional text that will be inserted into the notes buffer."
13129 (let* ((org-log-into-drawer (org-log-into-drawer))
13130 (drawer (cond ((stringp org-log-into-drawer)
13131 org-log-into-drawer)
13132 (org-log-into-drawer "LOGBOOK"))))
13133 (save-restriction
13134 (save-excursion
13135 (when findpos
13136 (org-back-to-heading t)
13137 (narrow-to-region (point) (save-excursion
13138 (outline-next-heading) (point)))
13139 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13140 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13141 "[^\r\n]*\\)?"))
13142 (goto-char (match-end 0))
13143 (cond
13144 (drawer
13145 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13146 nil t)
13147 (progn
13148 (goto-char (match-end 0))
13149 (or org-log-states-order-reversed
13150 (and (re-search-forward org-property-end-re nil t)
13151 (goto-char (1- (match-beginning 0))))))
13152 (insert "\n:" drawer ":\n:END:")
13153 (beginning-of-line 0)
13154 (org-indent-line)
13155 (beginning-of-line 2)
13156 (org-indent-line)
13157 (end-of-line 0)))
13158 ((and org-log-state-notes-insert-after-drawers
13159 (save-excursion
13160 (forward-line) (looking-at org-drawer-regexp)))
13161 (forward-line)
13162 (while (looking-at org-drawer-regexp)
13163 (goto-char (match-end 0))
13164 (re-search-forward org-property-end-re (point-max) t)
13165 (forward-line))
13166 (forward-line -1)))
13167 (unless org-log-states-order-reversed
13168 (and (= (char-after) ?\n) (forward-char 1))
13169 (org-skip-over-state-notes)
13170 (skip-chars-backward " \t\n\r")))
13171 (move-marker org-log-note-marker (point))
13172 (setq org-log-note-purpose purpose
13173 org-log-note-state state
13174 org-log-note-previous-state prev-state
13175 org-log-note-how how
13176 org-log-note-extra extra
13177 org-log-note-effective-time (org-current-effective-time))
13178 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13180 (defun org-skip-over-state-notes ()
13181 "Skip past the list of State notes in an entry."
13182 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13183 (when (ignore-errors (goto-char (org-in-item-p)))
13184 (let* ((struct (org-list-struct))
13185 (prevs (org-list-prevs-alist struct)))
13186 (while (looking-at "[ \t]*- State")
13187 (goto-char (or (org-list-get-next-item (point) struct prevs)
13188 (org-list-get-item-end (point) struct)))))))
13190 (defun org-add-log-note (&optional purpose)
13191 "Pop up a window for taking a note, and add this note later at point."
13192 (remove-hook 'post-command-hook 'org-add-log-note)
13193 (setq org-log-note-window-configuration (current-window-configuration))
13194 (delete-other-windows)
13195 (move-marker org-log-note-return-to (point))
13196 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13197 (goto-char org-log-note-marker)
13198 (org-switch-to-buffer-other-window "*Org Note*")
13199 (erase-buffer)
13200 (if (memq org-log-note-how '(time state))
13201 (let (current-prefix-arg) (org-store-log-note))
13202 (let ((org-inhibit-startup t)) (org-mode))
13203 (insert (format "# Insert note for %s.
13204 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13205 (cond
13206 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13207 ((eq org-log-note-purpose 'done) "closed todo item")
13208 ((eq org-log-note-purpose 'state)
13209 (format "state change from \"%s\" to \"%s\""
13210 (or org-log-note-previous-state "")
13211 (or org-log-note-state "")))
13212 ((eq org-log-note-purpose 'reschedule)
13213 "rescheduling")
13214 ((eq org-log-note-purpose 'delschedule)
13215 "no longer scheduled")
13216 ((eq org-log-note-purpose 'redeadline)
13217 "changing deadline")
13218 ((eq org-log-note-purpose 'deldeadline)
13219 "removing deadline")
13220 ((eq org-log-note-purpose 'refile)
13221 "refiling")
13222 ((eq org-log-note-purpose 'note)
13223 "this entry")
13224 (t (error "This should not happen")))))
13225 (if org-log-note-extra (insert org-log-note-extra))
13226 (org-set-local 'org-finish-function 'org-store-log-note)
13227 (run-hooks 'org-log-buffer-setup-hook)))
13229 (defvar org-note-abort nil) ; dynamically scoped
13230 (defun org-store-log-note ()
13231 "Finish taking a log note, and insert it to where it belongs."
13232 (let ((txt (buffer-string)))
13233 (kill-buffer (current-buffer))
13234 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13235 lines ind bul)
13236 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13237 (setq txt (replace-match "" t t txt)))
13238 (if (string-match "\\s-+\\'" txt)
13239 (setq txt (replace-match "" t t txt)))
13240 (setq lines (org-split-string txt "\n"))
13241 (when (and note (string-match "\\S-" note))
13242 (setq note
13243 (org-replace-escapes
13244 note
13245 (list (cons "%u" (user-login-name))
13246 (cons "%U" user-full-name)
13247 (cons "%t" (format-time-string
13248 (org-time-stamp-format 'long 'inactive)
13249 org-log-note-effective-time))
13250 (cons "%T" (format-time-string
13251 (org-time-stamp-format 'long nil)
13252 org-log-note-effective-time))
13253 (cons "%d" (format-time-string
13254 (org-time-stamp-format nil 'inactive)
13255 org-log-note-effective-time))
13256 (cons "%D" (format-time-string
13257 (org-time-stamp-format nil nil)
13258 org-log-note-effective-time))
13259 (cons "%s" (if org-log-note-state
13260 (concat "\"" org-log-note-state "\"")
13261 ""))
13262 (cons "%S" (if org-log-note-previous-state
13263 (concat "\"" org-log-note-previous-state "\"")
13264 "\"\"")))))
13265 (if lines (setq note (concat note " \\\\")))
13266 (push note lines))
13267 (when (or current-prefix-arg org-note-abort)
13268 (when org-log-into-drawer
13269 (org-remove-empty-drawer-at
13270 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13271 org-log-note-marker))
13272 (setq lines nil))
13273 (when lines
13274 (with-current-buffer (marker-buffer org-log-note-marker)
13275 (save-excursion
13276 (goto-char org-log-note-marker)
13277 (move-marker org-log-note-marker nil)
13278 (end-of-line 1)
13279 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13280 (setq ind (save-excursion
13281 (if (ignore-errors (goto-char (org-in-item-p)))
13282 (let ((struct (org-list-struct)))
13283 (org-list-get-ind
13284 (org-list-get-top-point struct) struct))
13285 (skip-chars-backward " \r\t\n")
13286 (cond
13287 ((and (org-at-heading-p)
13288 org-adapt-indentation)
13289 (1+ (org-current-level)))
13290 ((org-at-heading-p) 0)
13291 (t (org-get-indentation))))))
13292 (setq bul (org-list-bullet-string "-"))
13293 (org-indent-line-to ind)
13294 (insert bul (pop lines))
13295 (let ((ind-body (+ (length bul) ind)))
13296 (while lines
13297 (insert "\n")
13298 (org-indent-line-to ind-body)
13299 (insert (pop lines))))
13300 (message "Note stored")
13301 (org-back-to-heading t)
13302 (org-cycle-hide-drawers 'children))))))
13303 (set-window-configuration org-log-note-window-configuration)
13304 (with-current-buffer (marker-buffer org-log-note-return-to)
13305 (goto-char org-log-note-return-to))
13306 (move-marker org-log-note-return-to nil)
13307 (and org-log-post-message (message "%s" org-log-post-message)))
13309 (defun org-remove-empty-drawer-at (drawer pos)
13310 "Remove an empty drawer DRAWER at position POS.
13311 POS may also be a marker."
13312 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13313 (save-excursion
13314 (save-restriction
13315 (widen)
13316 (goto-char pos)
13317 (if (org-in-regexp
13318 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13319 (replace-match ""))))))
13321 (defvar org-ts-type nil)
13322 (defun org-sparse-tree (&optional arg type)
13323 "Create a sparse tree, prompt for the details.
13324 This command can create sparse trees. You first need to select the type
13325 of match used to create the tree:
13327 t Show all TODO entries.
13328 T Show entries with a specific TODO keyword.
13329 m Show entries selected by a tags/property match.
13330 p Enter a property name and its value (both with completion on existing
13331 names/values) and show entries with that property.
13332 r Show entries matching a regular expression (`/' can be used as well).
13333 b Show deadlines and scheduled items before a date.
13334 a Show deadlines and scheduled items after a date.
13335 d Show deadlines due within `org-deadline-warning-days'.
13336 D Show deadlines and scheduled items between a date range."
13337 (interactive "P")
13338 (let (ans kwd value ts-type)
13339 (setq type (or type org-sparse-tree-default-date-type))
13340 (setq org-ts-type type)
13341 (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"
13342 (cond ((eq type 'all) "all timestamps")
13343 ((eq type 'scheduled) "only scheduled")
13344 ((eq type 'deadline) "only deadline")
13345 ((eq type 'active) "only active timestamps")
13346 ((eq type 'inactive) "only inactive timestamps")
13347 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13348 ((eq type 'closed) "with a closed time-stamp")
13349 (t "scheduled/deadline")))
13350 (setq ans (read-char-exclusive))
13351 (cond
13352 ((equal ans ?c)
13353 (org-sparse-tree
13354 arg (cadr (member type '(scheduled-or-deadline
13355 all scheduled deadline active inactive closed)))))
13356 ((equal ans ?d)
13357 (call-interactively 'org-check-deadlines))
13358 ((equal ans ?b)
13359 (call-interactively 'org-check-before-date))
13360 ((equal ans ?a)
13361 (call-interactively 'org-check-after-date))
13362 ((equal ans ?D)
13363 (call-interactively 'org-check-dates-range))
13364 ((equal ans ?t)
13365 (call-interactively 'org-show-todo-tree))
13366 ((equal ans ?T)
13367 (org-show-todo-tree '(4)))
13368 ((member ans '(?T ?m))
13369 (call-interactively 'org-match-sparse-tree))
13370 ((member ans '(?p ?P))
13371 (setq kwd (org-icompleting-read "Property: "
13372 (mapcar 'list (org-buffer-property-keys))))
13373 (setq value (org-icompleting-read "Value: "
13374 (mapcar 'list (org-property-values kwd))))
13375 (unless (string-match "\\`{.*}\\'" value)
13376 (setq value (concat "\"" value "\"")))
13377 (org-match-sparse-tree arg (concat kwd "=" value)))
13378 ((member ans '(?r ?R ?/))
13379 (call-interactively 'org-occur))
13380 (t (error "No such sparse tree command \"%c\"" ans)))))
13382 (defvar org-occur-highlights nil
13383 "List of overlays used for occur matches.")
13384 (make-variable-buffer-local 'org-occur-highlights)
13385 (defvar org-occur-parameters nil
13386 "Parameters of the active org-occur calls.
13387 This is a list, each call to org-occur pushes as cons cell,
13388 containing the regular expression and the callback, onto the list.
13389 The list can contain several entries if `org-occur' has been called
13390 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13391 will only contain one set of parameters. When the highlights are
13392 removed (for example with `C-c C-c', or with the next edit (depending
13393 on `org-remove-highlights-with-change'), this variable is emptied
13394 as well.")
13395 (make-variable-buffer-local 'org-occur-parameters)
13397 (defun org-occur (regexp &optional keep-previous callback)
13398 "Make a compact tree which shows all matches of REGEXP.
13399 The tree will show the lines where the regexp matches, and all higher
13400 headlines above the match. It will also show the heading after the match,
13401 to make sure editing the matching entry is easy.
13402 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13403 call to `org-occur' will be kept, to allow stacking of calls to this
13404 command.
13405 If CALLBACK is non-nil, it is a function which is called to confirm
13406 that the match should indeed be shown."
13407 (interactive "sRegexp: \nP")
13408 (when (equal regexp "")
13409 (error "Regexp cannot be empty"))
13410 (unless keep-previous
13411 (org-remove-occur-highlights nil nil t))
13412 (push (cons regexp callback) org-occur-parameters)
13413 (let ((cnt 0))
13414 (save-excursion
13415 (goto-char (point-min))
13416 (if (or (not keep-previous) ; do not want to keep
13417 (not org-occur-highlights)) ; no previous matches
13418 ;; hide everything
13419 (org-overview))
13420 (while (re-search-forward regexp nil t)
13421 (when (or (not callback)
13422 (save-match-data (funcall callback)))
13423 (setq cnt (1+ cnt))
13424 (when org-highlight-sparse-tree-matches
13425 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13426 (org-show-context 'occur-tree))))
13427 (when org-remove-highlights-with-change
13428 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13429 nil 'local))
13430 (unless org-sparse-tree-open-archived-trees
13431 (org-hide-archived-subtrees (point-min) (point-max)))
13432 (run-hooks 'org-occur-hook)
13433 (if (org-called-interactively-p 'interactive)
13434 (message "%d match(es) for regexp %s" cnt regexp))
13435 cnt))
13437 (defun org-occur-next-match (&optional n reset)
13438 "Function for `next-error-function' to find sparse tree matches.
13439 N is the number of matches to move, when negative move backwards.
13440 RESET is entirely ignored - this function always goes back to the
13441 starting point when no match is found."
13442 (let* ((limit (if (< n 0) (point-min) (point-max)))
13443 (search-func (if (< n 0)
13444 'previous-single-char-property-change
13445 'next-single-char-property-change))
13446 (n (abs n))
13447 (pos (point))
13449 (catch 'exit
13450 (while (setq p1 (funcall search-func (point) 'org-type))
13451 (when (equal p1 limit)
13452 (goto-char pos)
13453 (error "No more matches"))
13454 (when (equal (get-char-property p1 'org-type) 'org-occur)
13455 (setq n (1- n))
13456 (when (= n 0)
13457 (goto-char p1)
13458 (throw 'exit (point))))
13459 (goto-char p1))
13460 (goto-char p1)
13461 (error "No more matches"))))
13463 (defun org-show-context (&optional key)
13464 "Make sure point and context are visible.
13465 How much context is shown depends upon the variables
13466 `org-show-hierarchy-above', `org-show-following-heading',
13467 `org-show-entry-below' and `org-show-siblings'."
13468 (let ((heading-p (org-at-heading-p t))
13469 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13470 (following-p (org-get-alist-option org-show-following-heading key))
13471 (entry-p (org-get-alist-option org-show-entry-below key))
13472 (siblings-p (org-get-alist-option org-show-siblings key)))
13473 ;; Show heading or entry text
13474 (if (and heading-p (not entry-p))
13475 (org-flag-heading nil) ; only show the heading
13476 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13477 (org-show-hidden-entry))) ; show entire entry
13478 (when following-p
13479 ;; Show next sibling, or heading below text
13480 (save-excursion
13481 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13482 (org-flag-heading nil))))
13483 (when siblings-p (org-show-siblings))
13484 (when hierarchy-p
13485 ;; show all higher headings, possibly with siblings
13486 (save-excursion
13487 (while (and (condition-case nil
13488 (progn (org-up-heading-all 1) t)
13489 (error nil))
13490 (not (bobp)))
13491 (org-flag-heading nil)
13492 (when siblings-p (org-show-siblings)))))
13493 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13495 (defvar org-reveal-start-hook nil
13496 "Hook run before revealing a location.")
13498 (defun org-reveal (&optional siblings)
13499 "Show current entry, hierarchy above it, and the following headline.
13500 This can be used to show a consistent set of context around locations
13501 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13502 not t for the search context.
13504 With optional argument SIBLINGS, on each level of the hierarchy all
13505 siblings are shown. This repairs the tree structure to what it would
13506 look like when opened with hierarchical calls to `org-cycle'.
13507 With double optional argument \\[universal-argument] \\[universal-argument], \
13508 go to the parent and show the
13509 entire tree."
13510 (interactive "P")
13511 (run-hooks 'org-reveal-start-hook)
13512 (let ((org-show-hierarchy-above t)
13513 (org-show-following-heading t)
13514 (org-show-siblings (if siblings t org-show-siblings)))
13515 (org-show-context nil))
13516 (when (equal siblings '(16))
13517 (save-excursion
13518 (when (org-up-heading-safe)
13519 (org-show-subtree)
13520 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13522 (defun org-highlight-new-match (beg end)
13523 "Highlight from BEG to END and mark the highlight is an occur headline."
13524 (let ((ov (make-overlay beg end)))
13525 (overlay-put ov 'face 'secondary-selection)
13526 (overlay-put ov 'org-type 'org-occur)
13527 (push ov org-occur-highlights)))
13529 (defun org-remove-occur-highlights (&optional beg end noremove)
13530 "Remove the occur highlights from the buffer.
13531 BEG and END are ignored. If NOREMOVE is nil, remove this function
13532 from the `before-change-functions' in the current buffer."
13533 (interactive)
13534 (unless org-inhibit-highlight-removal
13535 (mapc 'delete-overlay org-occur-highlights)
13536 (setq org-occur-highlights nil)
13537 (setq org-occur-parameters nil)
13538 (unless noremove
13539 (remove-hook 'before-change-functions
13540 'org-remove-occur-highlights 'local))))
13542 ;;;; Priorities
13544 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13545 "Regular expression matching the priority indicator.")
13547 (defvar org-remove-priority-next-time nil)
13549 (defun org-priority-up ()
13550 "Increase the priority of the current item."
13551 (interactive)
13552 (org-priority 'up))
13554 (defun org-priority-down ()
13555 "Decrease the priority of the current item."
13556 (interactive)
13557 (org-priority 'down))
13559 (defun org-priority (&optional action show)
13560 "Change the priority of an item.
13561 ACTION can be `set', `up', `down', or a character."
13562 (interactive "P")
13563 (if (equal action '(4))
13564 (org-show-priority)
13565 (unless org-enable-priority-commands
13566 (error "Priority commands are disabled"))
13567 (setq action (or action 'set))
13568 (let (current new news have remove)
13569 (save-excursion
13570 (org-back-to-heading t)
13571 (if (looking-at org-priority-regexp)
13572 (setq current (string-to-char (match-string 2))
13573 have t))
13574 (cond
13575 ((eq action 'remove)
13576 (setq remove t new ?\ ))
13577 ((or (eq action 'set)
13578 (if (featurep 'xemacs) (characterp action) (integerp action)))
13579 (if (not (eq action 'set))
13580 (setq new action)
13581 (message "Priority %c-%c, SPC to remove: "
13582 org-highest-priority org-lowest-priority)
13583 (save-match-data
13584 (setq new (read-char-exclusive))))
13585 (if (and (= (upcase org-highest-priority) org-highest-priority)
13586 (= (upcase org-lowest-priority) org-lowest-priority))
13587 (setq new (upcase new)))
13588 (cond ((equal new ?\ ) (setq remove t))
13589 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13590 (error "Priority must be between `%c' and `%c'"
13591 org-highest-priority org-lowest-priority))))
13592 ((eq action 'up)
13593 (setq new (if have
13594 (1- current) ; normal cycling
13595 ;; last priority was empty
13596 (if (eq last-command this-command)
13597 org-lowest-priority ; wrap around empty to lowest
13598 ;; default
13599 (if org-priority-start-cycle-with-default
13600 org-default-priority
13601 (1- org-default-priority))))))
13602 ((eq action 'down)
13603 (setq new (if have
13604 (1+ current) ; normal cycling
13605 ;; last priority was empty
13606 (if (eq last-command this-command)
13607 org-highest-priority ; wrap around empty to highest
13608 ;; default
13609 (if org-priority-start-cycle-with-default
13610 org-default-priority
13611 (1+ org-default-priority))))))
13612 (t (error "Invalid action")))
13613 (if (or (< (upcase new) org-highest-priority)
13614 (> (upcase new) org-lowest-priority))
13615 (if (and (memq action '(up down))
13616 (not have) (not (eq last-command this-command)))
13617 ;; `new' is from default priority
13618 (error
13619 "The default can not be set, see `org-default-priority' why")
13620 ;; normal cycling: `new' is beyond highest/lowest priority
13621 ;; and is wrapped around to the empty priority
13622 (setq remove t)))
13623 (setq news (format "%c" new))
13624 (if have
13625 (if remove
13626 (replace-match "" t t nil 1)
13627 (replace-match news t t nil 2))
13628 (if remove
13629 (error "No priority cookie found in line")
13630 (let ((case-fold-search nil))
13631 (looking-at org-todo-line-regexp))
13632 (if (match-end 2)
13633 (progn
13634 (goto-char (match-end 2))
13635 (insert " [#" news "]"))
13636 (goto-char (match-beginning 3))
13637 (insert "[#" news "] "))))
13638 (org-preserve-lc (org-set-tags nil 'align)))
13639 (if remove
13640 (message "Priority removed")
13641 (message "Priority of current item set to %s" news)))))
13643 (defun org-show-priority ()
13644 "Show the priority of the current item.
13645 This priority is composed of the main priority given with the [#A] cookies,
13646 and by additional input from the age of a schedules or deadline entry."
13647 (interactive)
13648 (let ((pri (if (eq major-mode 'org-agenda-mode)
13649 (org-get-at-bol 'priority)
13650 (save-excursion
13651 (save-match-data
13652 (beginning-of-line)
13653 (and (looking-at org-heading-regexp)
13654 (org-get-priority (match-string 0))))))))
13655 (message "Priority is %d" (if pri pri -1000))))
13657 (defun org-get-priority (s)
13658 "Find priority cookie and return priority."
13659 (save-match-data
13660 (if (functionp org-get-priority-function)
13661 (funcall org-get-priority-function)
13662 (if (not (string-match org-priority-regexp s))
13663 (* 1000 (- org-lowest-priority org-default-priority))
13664 (* 1000 (- org-lowest-priority
13665 (string-to-char (match-string 2 s))))))))
13667 ;;;; Tags
13669 (defvar org-agenda-archives-mode)
13670 (defvar org-map-continue-from nil
13671 "Position from where mapping should continue.
13672 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13674 (defvar org-scanner-tags nil
13675 "The current tag list while the tags scanner is running.")
13676 (defvar org-trust-scanner-tags nil
13677 "Should `org-get-tags-at' use the tags for the scanner.
13678 This is for internal dynamical scoping only.
13679 When this is non-nil, the function `org-get-tags-at' will return the value
13680 of `org-scanner-tags' instead of building the list by itself. This
13681 can lead to large speed-ups when the tags scanner is used in a file with
13682 many entries, and when the list of tags is retrieved, for example to
13683 obtain a list of properties. Building the tags list for each entry in such
13684 a file becomes an N^2 operation - but with this variable set, it scales
13685 as N.")
13687 (defun org-scan-tags (action matcher todo-only &optional start-level)
13688 "Sca headline tags with inheritance and produce output ACTION.
13690 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13691 or `agenda' to produce an entry list for an agenda view. It can also be
13692 a Lisp form or a function that should be called at each matched headline, in
13693 this case the return value is a list of all return values from these calls.
13695 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13696 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13697 only lines with a not-done TODO keyword are included in the output.
13698 This should be the same variable that was scoped into
13699 and set by `org-make-tags-matcher' when it constructed MATCHER.
13701 START-LEVEL can be a string with asterisks, reducing the scope to
13702 headlines matching this string."
13703 (require 'org-agenda)
13704 (let* ((re (concat "^"
13705 (if start-level
13706 ;; Get the correct level to match
13707 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13708 org-outline-regexp)
13709 " *\\(\\<\\("
13710 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13711 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13712 (props (list 'face 'default
13713 'done-face 'org-agenda-done
13714 'undone-face 'default
13715 'mouse-face 'highlight
13716 'org-not-done-regexp org-not-done-regexp
13717 'org-todo-regexp org-todo-regexp
13718 'org-complex-heading-regexp org-complex-heading-regexp
13719 'help-echo
13720 (format "mouse-2 or RET jump to org file %s"
13721 (abbreviate-file-name
13722 (or (buffer-file-name (buffer-base-buffer))
13723 (buffer-name (buffer-base-buffer)))))))
13724 (case-fold-search nil)
13725 (org-map-continue-from nil)
13726 lspos tags tags-list
13727 (tags-alist (list (cons 0 org-file-tags)))
13728 (llast 0) rtn rtn1 level category i txt
13729 todo marker entry priority)
13730 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13731 (setq action (list 'lambda nil action)))
13732 (save-excursion
13733 (goto-char (point-min))
13734 (when (eq action 'sparse-tree)
13735 (org-overview)
13736 (org-remove-occur-highlights))
13737 (while (re-search-forward re nil t)
13738 (setq org-map-continue-from nil)
13739 (catch :skip
13740 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13741 tags (if (match-end 4) (org-match-string-no-properties 4)))
13742 (goto-char (setq lspos (match-beginning 0)))
13743 (setq level (org-reduced-level (org-outline-level))
13744 category (org-get-category))
13745 (setq i llast llast level)
13746 ;; remove tag lists from same and sublevels
13747 (while (>= i level)
13748 (when (setq entry (assoc i tags-alist))
13749 (setq tags-alist (delete entry tags-alist)))
13750 (setq i (1- i)))
13751 ;; add the next tags
13752 (when tags
13753 (setq tags (org-split-string tags ":")
13754 tags-alist
13755 (cons (cons level tags) tags-alist)))
13756 ;; compile tags for current headline
13757 (setq tags-list
13758 (if org-use-tag-inheritance
13759 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13760 tags)
13761 org-scanner-tags tags-list)
13762 (when org-use-tag-inheritance
13763 (setcdr (car tags-alist)
13764 (mapcar (lambda (x)
13765 (setq x (copy-sequence x))
13766 (org-add-prop-inherited x))
13767 (cdar tags-alist))))
13768 (when (and tags org-use-tag-inheritance
13769 (or (not (eq t org-use-tag-inheritance))
13770 org-tags-exclude-from-inheritance))
13771 ;; selective inheritance, remove uninherited ones
13772 (setcdr (car tags-alist)
13773 (org-remove-uninherited-tags (cdar tags-alist))))
13774 (when (and
13776 ;; eval matcher only when the todo condition is OK
13777 (and (or (not todo-only) (member todo org-not-done-keywords))
13778 (let ((case-fold-search t) (org-trust-scanner-tags t))
13779 (eval matcher)))
13781 ;; Call the skipper, but return t if it does not skip,
13782 ;; so that the `and' form continues evaluating
13783 (progn
13784 (unless (eq action 'sparse-tree) (org-agenda-skip))
13787 ;; Check if timestamps are deselecting this entry
13788 (or (not todo-only)
13789 (and (member todo org-not-done-keywords)
13790 (or (not org-agenda-tags-todo-honor-ignore-options)
13791 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13793 ;; select this headline
13794 (cond
13795 ((eq action 'sparse-tree)
13796 (and org-highlight-sparse-tree-matches
13797 (org-get-heading) (match-end 0)
13798 (org-highlight-new-match
13799 (match-beginning 1) (match-end 1)))
13800 (org-show-context 'tags-tree))
13801 ((eq action 'agenda)
13802 (setq txt (org-agenda-format-item
13804 (concat
13805 (if (eq org-tags-match-list-sublevels 'indented)
13806 (make-string (1- level) ?.) "")
13807 (org-get-heading))
13808 level category
13809 tags-list)
13810 priority (org-get-priority txt))
13811 (goto-char lspos)
13812 (setq marker (org-agenda-new-marker))
13813 (org-add-props txt props
13814 'org-marker marker 'org-hd-marker marker 'org-category category
13815 'todo-state todo
13816 'priority priority 'type "tagsmatch")
13817 (push txt rtn))
13818 ((functionp action)
13819 (setq org-map-continue-from nil)
13820 (save-excursion
13821 (setq rtn1 (funcall action))
13822 (push rtn1 rtn)))
13823 (t (error "Invalid action")))
13825 ;; if we are to skip sublevels, jump to end of subtree
13826 (unless org-tags-match-list-sublevels
13827 (org-end-of-subtree t)
13828 (backward-char 1))))
13829 ;; Get the correct position from where to continue
13830 (if org-map-continue-from
13831 (goto-char org-map-continue-from)
13832 (and (= (point) lspos) (end-of-line 1)))))
13833 (when (and (eq action 'sparse-tree)
13834 (not org-sparse-tree-open-archived-trees))
13835 (org-hide-archived-subtrees (point-min) (point-max)))
13836 (nreverse rtn)))
13838 (defun org-remove-uninherited-tags (tags)
13839 "Remove all tags that are not inherited from the list TAGS."
13840 (cond
13841 ((eq org-use-tag-inheritance t)
13842 (if org-tags-exclude-from-inheritance
13843 (org-delete-all org-tags-exclude-from-inheritance tags)
13844 tags))
13845 ((not org-use-tag-inheritance) nil)
13846 ((stringp org-use-tag-inheritance)
13847 (delq nil (mapcar
13848 (lambda (x)
13849 (if (and (string-match org-use-tag-inheritance x)
13850 (not (member x org-tags-exclude-from-inheritance)))
13851 x nil))
13852 tags)))
13853 ((listp org-use-tag-inheritance)
13854 (delq nil (mapcar
13855 (lambda (x)
13856 (if (member x org-use-tag-inheritance) x nil))
13857 tags)))))
13859 (defun org-match-sparse-tree (&optional todo-only match)
13860 "Create a sparse tree according to tags string MATCH.
13861 MATCH can contain positive and negative selection of tags, like
13862 \"+WORK+URGENT-WITHBOSS\".
13863 If optional argument TODO-ONLY is non-nil, only select lines that are
13864 also TODO lines."
13865 (interactive "P")
13866 (org-agenda-prepare-buffers (list (current-buffer)))
13867 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13869 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13871 (defvar org-cached-props nil)
13872 (defun org-cached-entry-get (pom property)
13873 (if (or (eq t org-use-property-inheritance)
13874 (and (stringp org-use-property-inheritance)
13875 (string-match org-use-property-inheritance property))
13876 (and (listp org-use-property-inheritance)
13877 (member property org-use-property-inheritance)))
13878 ;; Caching is not possible, check it directly
13879 (org-entry-get pom property 'inherit)
13880 ;; Get all properties, so that we can do complicated checks easily
13881 (cdr (assoc property (or org-cached-props
13882 (setq org-cached-props
13883 (org-entry-properties pom)))))))
13885 (defun org-global-tags-completion-table (&optional files)
13886 "Return the list of all tags in all agenda buffer/files.
13887 Optional FILES argument is a list of files which can be used
13888 instead of the agenda files."
13889 (save-excursion
13890 (org-uniquify
13891 (delq nil
13892 (apply 'append
13893 (mapcar
13894 (lambda (file)
13895 (set-buffer (find-file-noselect file))
13896 (append (org-get-buffer-tags)
13897 (mapcar (lambda (x) (if (stringp (car-safe x))
13898 (list (car-safe x)) nil))
13899 org-tag-alist)))
13900 (if (and files (car files))
13901 files
13902 (org-agenda-files))))))))
13904 (defun org-make-tags-matcher (match)
13905 "Create the TAGS/TODO matcher form for the selection string MATCH.
13907 The variable `todo-only' is scoped dynamically into this function.
13908 It will be set to t if the matcher restricts matching to TODO entries,
13909 otherwise will not be touched.
13911 Returns a cons of the selection string MATCH and the constructed
13912 lisp form implementing the matcher. The matcher is to be evaluated
13913 at an Org entry, with point on the headline, and returns t if the
13914 entry matches the selection string MATCH. The returned lisp form
13915 references two variables with information about the entry, which
13916 must be bound around the form's evaluation: todo, the TODO keyword
13917 at the entry (or nil of none); and tags-list, the list of all tags
13918 at the entry including inherited ones. Additionally, the category
13919 of the entry (if any) must be specified as the text property
13920 'org-category on the headline.
13922 See also `org-scan-tags'.
13924 (declare (special todo-only))
13925 (unless (boundp 'todo-only)
13926 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13927 (unless match
13928 ;; Get a new match request, with completion
13929 (let ((org-last-tags-completion-table
13930 (org-global-tags-completion-table)))
13931 (setq match (org-completing-read-no-i
13932 "Match: " 'org-tags-completion-function nil nil nil
13933 'org-tags-history))))
13935 ;; Parse the string and create a lisp form
13936 (let ((match0 match)
13937 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13938 minus tag mm
13939 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13940 orterms term orlist re-p str-p level-p level-op time-p
13941 prop-p pn pv po gv rest)
13942 ;; Expand group tags
13943 (setq match (org-tags-expand match))
13944 (if (string-match "/+" match)
13945 ;; match contains also a todo-matching request
13946 (progn
13947 (setq tagsmatch (substring match 0 (match-beginning 0))
13948 todomatch (substring match (match-end 0)))
13949 (if (string-match "^!" todomatch)
13950 (setq todo-only t todomatch (substring todomatch 1)))
13951 (if (string-match "^\\s-*$" todomatch)
13952 (setq todomatch nil)))
13953 ;; only matching tags
13954 (setq tagsmatch match todomatch nil))
13956 ;; Make the tags matcher
13957 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13958 (setq tagsmatcher t)
13959 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13960 (while (setq term (pop orterms))
13961 (while (and (equal (substring term -1) "\\") orterms)
13962 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13963 (while (string-match re term)
13964 (setq rest (substring term (match-end 0))
13965 minus (and (match-end 1)
13966 (equal (match-string 1 term) "-"))
13967 tag (save-match-data (replace-regexp-in-string
13968 "\\\\-" "-"
13969 (match-string 2 term)))
13970 re-p (equal (string-to-char tag) ?{)
13971 level-p (match-end 4)
13972 prop-p (match-end 5)
13973 mm (cond
13974 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13975 (level-p
13976 (setq level-op (org-op-to-function (match-string 3 term)))
13977 `(,level-op level ,(string-to-number
13978 (match-string 4 term))))
13979 (prop-p
13980 (setq pn (match-string 5 term)
13981 po (match-string 6 term)
13982 pv (match-string 7 term)
13983 re-p (equal (string-to-char pv) ?{)
13984 str-p (equal (string-to-char pv) ?\")
13985 time-p (save-match-data
13986 (string-match "^\"[[<].*[]>]\"$" pv))
13987 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13988 (if time-p (setq pv (org-matcher-time pv)))
13989 (setq po (org-op-to-function po (if time-p 'time str-p)))
13990 (cond
13991 ((equal pn "CATEGORY")
13992 (setq gv '(get-text-property (point) 'org-category)))
13993 ((equal pn "TODO")
13994 (setq gv 'todo))
13996 (setq gv `(org-cached-entry-get nil ,pn))))
13997 (if re-p
13998 (if (eq po 'org<>)
13999 `(not (string-match ,pv (or ,gv "")))
14000 `(string-match ,pv (or ,gv "")))
14001 (if str-p
14002 `(,po (or ,gv "") ,pv)
14003 `(,po (string-to-number (or ,gv ""))
14004 ,(string-to-number pv) ))))
14005 (t `(member ,tag tags-list)))
14006 mm (if minus (list 'not mm) mm)
14007 term rest)
14008 (push mm tagsmatcher))
14009 (push (if (> (length tagsmatcher) 1)
14010 (cons 'and tagsmatcher)
14011 (car tagsmatcher))
14012 orlist)
14013 (setq tagsmatcher nil))
14014 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14015 (setq tagsmatcher
14016 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14017 ;; Make the todo matcher
14018 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14019 (setq todomatcher t)
14020 (setq orterms (org-split-string todomatch "|") orlist nil)
14021 (while (setq term (pop orterms))
14022 (while (string-match re term)
14023 (setq minus (and (match-end 1)
14024 (equal (match-string 1 term) "-"))
14025 kwd (match-string 2 term)
14026 re-p (equal (string-to-char kwd) ?{)
14027 term (substring term (match-end 0))
14028 mm (if re-p
14029 `(string-match ,(substring kwd 1 -1) todo)
14030 (list 'equal 'todo kwd))
14031 mm (if minus (list 'not mm) mm))
14032 (push mm todomatcher))
14033 (push (if (> (length todomatcher) 1)
14034 (cons 'and todomatcher)
14035 (car todomatcher))
14036 orlist)
14037 (setq todomatcher nil))
14038 (setq todomatcher (if (> (length orlist) 1)
14039 (cons 'or orlist) (car orlist))))
14041 ;; Return the string and lisp forms of the matcher
14042 (setq matcher (if todomatcher
14043 (list 'and tagsmatcher todomatcher)
14044 tagsmatcher))
14045 (when todo-only
14046 (setq matcher (list 'and '(member todo org-not-done-keywords)
14047 matcher)))
14048 (cons match0 matcher)))
14050 (defun org-tags-expand (match &optional single-as-list downcased)
14051 "Expand group tags in MATCH.
14053 This replaces every group tag in MATCH with a regexp tag search.
14054 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14055 will be replaced like this:
14057 Work => {\(?:Work\|Lab\|Conf\}
14058 +Work => +{\(?:Work\|Lab\|Conf\}
14059 -Work => -{\(?:Work\|Lab\|Conf\}
14061 Replacing by a regexp preserves the structure of the match.
14062 E.g., this expansion
14064 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14066 will match anything tagged with \"Lab\" and \"Home\", or tagged
14067 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14069 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14070 assumed to be a single group tag, and the function will return
14071 the list of tags in this group.
14073 When DOWNCASE is non-nil, expand downcased TAGS."
14074 (if org-group-tags
14075 (let* ((case-fold-search t)
14076 (stable org-mode-syntax-table)
14077 (tal (or org-tag-groups-alist-for-agenda
14078 org-tag-groups-alist))
14079 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14080 (tml (mapcar 'car tal))
14081 (rtnmatch match) rpl)
14082 ;; @ and _ are allowed as word-components in tags
14083 (modify-syntax-entry ?@ "w" stable)
14084 (modify-syntax-entry ?_ "w" stable)
14085 (while (and tml (string-match
14086 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14087 rtnmatch))
14088 (let* ((dir (match-string 1 rtnmatch))
14089 (tag (match-string 2 rtnmatch))
14090 (tag (if downcased (downcase tag) tag)))
14091 (setq tml (delete tag tml))
14092 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14093 (setq rtnmatch
14094 (replace-match
14095 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14096 (if single-as-list
14097 (or (reverse rpl) (list rtnmatch))
14098 rtnmatch))
14099 (if single-as-list (list (if downcased (downcase match) match))
14100 match)))
14102 (defun org-op-to-function (op &optional stringp)
14103 "Turn an operator into the appropriate function."
14104 (setq op
14105 (cond
14106 ((equal op "<" ) '(< string< org-time<))
14107 ((equal op ">" ) '(> org-string> org-time>))
14108 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14109 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14110 ((member op '("=" "==")) '(= string= org-time=))
14111 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14112 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14114 (defun org<> (a b) (not (= a b)))
14115 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14116 (defun org-string>= (a b) (not (string< a b)))
14117 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14118 (defun org-string<> (a b) (not (string= a b)))
14119 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14120 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14121 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14122 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14123 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14124 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14125 (defun org-2ft (s)
14126 "Convert S to a floating point time.
14127 If S is already a number, just return it. If it is a string, parse
14128 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14129 (cond
14130 ((numberp s) s)
14131 ((stringp s)
14132 (condition-case nil
14133 (float-time (apply 'encode-time (org-parse-time-string s)))
14134 (error 0.)))
14135 (t 0.)))
14137 (defun org-time-today ()
14138 "Time in seconds today at 0:00.
14139 Returns the float number of seconds since the beginning of the
14140 epoch to the beginning of today (00:00)."
14141 (float-time (apply 'encode-time
14142 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14144 (defun org-matcher-time (s)
14145 "Interpret a time comparison value."
14146 (save-match-data
14147 (cond
14148 ((string= s "<now>") (float-time))
14149 ((string= s "<today>") (org-time-today))
14150 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14151 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14152 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14153 (+ (org-time-today)
14154 (* (string-to-number (match-string 1 s))
14155 (cdr (assoc (match-string 2 s)
14156 '(("d" . 86400.0) ("w" . 604800.0)
14157 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14158 (t (org-2ft s)))))
14160 (defun org-match-any-p (re list)
14161 "Does re match any element of list?"
14162 (setq list (mapcar (lambda (x) (string-match re x)) list))
14163 (delq nil list))
14165 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14166 (defvar org-tags-overlay (make-overlay 1 1))
14167 (org-detach-overlay org-tags-overlay)
14169 (defun org-get-local-tags-at (&optional pos)
14170 "Get a list of tags defined in the current headline."
14171 (org-get-tags-at pos 'local))
14173 (defun org-get-local-tags ()
14174 "Get a list of tags defined in the current headline."
14175 (org-get-tags-at nil 'local))
14177 (defun org-get-tags-at (&optional pos local)
14178 "Get a list of all headline tags applicable at POS.
14179 POS defaults to point. If tags are inherited, the list contains
14180 the targets in the same sequence as the headlines appear, i.e.
14181 the tags of the current headline come last.
14182 When LOCAL is non-nil, only return tags from the current headline,
14183 ignore inherited ones."
14184 (interactive)
14185 (if (and org-trust-scanner-tags
14186 (or (not pos) (equal pos (point)))
14187 (not local))
14188 org-scanner-tags
14189 (let (tags ltags lastpos parent)
14190 (save-excursion
14191 (save-restriction
14192 (widen)
14193 (goto-char (or pos (point)))
14194 (save-match-data
14195 (catch 'done
14196 (condition-case nil
14197 (progn
14198 (org-back-to-heading t)
14199 (while (not (equal lastpos (point)))
14200 (setq lastpos (point))
14201 (when (looking-at
14202 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14203 (setq ltags (org-split-string
14204 (org-match-string-no-properties 1) ":"))
14205 (when parent
14206 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14207 (setq tags (append
14208 (if parent
14209 (org-remove-uninherited-tags ltags)
14210 ltags)
14211 tags)))
14212 (or org-use-tag-inheritance (throw 'done t))
14213 (if local (throw 'done t))
14214 (or (org-up-heading-safe) (error nil))
14215 (setq parent t)))
14216 (error nil)))))
14217 (if local
14218 tags
14219 (reverse (delete-dups
14220 (reverse (append
14221 (org-remove-uninherited-tags
14222 org-file-tags) tags)))))))))
14224 (defun org-add-prop-inherited (s)
14225 (add-text-properties 0 (length s) '(inherited t) s)
14228 (defun org-toggle-tag (tag &optional onoff)
14229 "Toggle the tag TAG for the current line.
14230 If ONOFF is `on' or `off', don't toggle but set to this state."
14231 (let (res current)
14232 (save-excursion
14233 (org-back-to-heading t)
14234 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14235 (point-at-eol) t)
14236 (progn
14237 (setq current (match-string 1))
14238 (replace-match ""))
14239 (setq current ""))
14240 (setq current (nreverse (org-split-string current ":")))
14241 (cond
14242 ((eq onoff 'on)
14243 (setq res t)
14244 (or (member tag current) (push tag current)))
14245 ((eq onoff 'off)
14246 (or (not (member tag current)) (setq current (delete tag current))))
14247 (t (if (member tag current)
14248 (setq current (delete tag current))
14249 (setq res t)
14250 (push tag current))))
14251 (end-of-line 1)
14252 (if current
14253 (progn
14254 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14255 (org-set-tags nil t))
14256 (delete-horizontal-space))
14257 (run-hooks 'org-after-tags-change-hook))
14258 res))
14260 (defun org-align-tags-here (to-col)
14261 ;; Assumes that this is a headline
14262 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14263 (beginning-of-line 1)
14264 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14265 (< pos (match-beginning 2)))
14266 (progn
14267 (setq tags-l (- (match-end 2) (match-beginning 2)))
14268 (goto-char (match-beginning 1))
14269 (insert " ")
14270 (delete-region (point) (1+ (match-beginning 2)))
14271 (setq ncol (max (current-column)
14272 (1+ col)
14273 (if (> to-col 0)
14274 to-col
14275 (- (abs to-col) tags-l))))
14276 (setq p (point))
14277 (insert (make-string (- ncol (current-column)) ?\ ))
14278 (setq ncol (current-column))
14279 (when indent-tabs-mode (tabify p (point-at-eol)))
14280 (org-move-to-column (min ncol col) t))
14281 (goto-char pos))))
14283 (defun org-set-tags-command (&optional arg just-align)
14284 "Call the set-tags command for the current entry."
14285 (interactive "P")
14286 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14287 (org-set-tags arg just-align)
14288 (save-excursion
14289 (unless (and (org-region-active-p)
14290 org-loop-over-headlines-in-active-region)
14291 (org-back-to-heading t))
14292 (org-set-tags arg just-align))))
14294 (defun org-set-tags-to (data)
14295 "Set the tags of the current entry to DATA, replacing the current tags.
14296 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14297 If DATA is nil or the empty string, any tags will be removed."
14298 (interactive "sTags: ")
14299 (setq data
14300 (cond
14301 ((eq data nil) "")
14302 ((equal data "") "")
14303 ((stringp data)
14304 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14305 ":"))
14306 ((listp data)
14307 (concat ":" (mapconcat 'identity data ":") ":"))))
14308 (when data
14309 (save-excursion
14310 (org-back-to-heading t)
14311 (when (looking-at org-complex-heading-regexp)
14312 (if (match-end 5)
14313 (progn
14314 (goto-char (match-beginning 5))
14315 (insert data)
14316 (delete-region (point) (point-at-eol))
14317 (org-set-tags nil 'align))
14318 (goto-char (point-at-eol))
14319 (insert " " data)
14320 (org-set-tags nil 'align)))
14321 (beginning-of-line 1)
14322 (if (looking-at ".*?\\([ \t]+\\)$")
14323 (delete-region (match-beginning 1) (match-end 1))))))
14325 (defun org-align-all-tags ()
14326 "Align the tags i all headings."
14327 (interactive)
14328 (save-excursion
14329 (or (ignore-errors (org-back-to-heading t))
14330 (outline-next-heading))
14331 (if (org-at-heading-p)
14332 (org-set-tags t)
14333 (message "No headings"))))
14335 (defvar org-indent-indentation-per-level)
14336 (defun org-set-tags (&optional arg just-align)
14337 "Set the tags for the current headline.
14338 With prefix ARG, realign all tags in headings in the current buffer."
14339 (interactive "P")
14340 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14341 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14342 'region-start-level 'region))
14343 org-loop-over-headlines-in-active-region)
14344 (org-map-entries
14345 ;; We don't use ARG and JUST-ALIGN here these args are not
14346 ;; useful when looping over headlines
14347 `(org-set-tags)
14348 org-loop-over-headlines-in-active-region
14349 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14350 (let* ((re org-outline-regexp-bol)
14351 (current (unless arg (org-get-tags-string)))
14352 (col (current-column))
14353 (org-setting-tags t)
14354 table current-tags inherited-tags ; computed below when needed
14355 tags p0 c0 c1 rpl di tc level)
14356 (if arg
14357 (save-excursion
14358 (goto-char (point-min))
14359 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14360 (while (re-search-forward re nil t)
14361 (org-set-tags nil t)
14362 (end-of-line 1)))
14363 (message "All tags realigned to column %d" org-tags-column))
14364 (if just-align
14365 (setq tags current)
14366 ;; Get a new set of tags from the user
14367 (save-excursion
14368 (setq table (append org-tag-persistent-alist
14369 (or org-tag-alist (org-get-buffer-tags))
14370 (and
14371 org-complete-tags-always-offer-all-agenda-tags
14372 (org-global-tags-completion-table
14373 (org-agenda-files))))
14374 org-last-tags-completion-table table
14375 current-tags (org-split-string current ":")
14376 inherited-tags (nreverse
14377 (nthcdr (length current-tags)
14378 (nreverse (org-get-tags-at))))
14379 tags
14380 (if (or (eq t org-use-fast-tag-selection)
14381 (and org-use-fast-tag-selection
14382 (delq nil (mapcar 'cdr table))))
14383 (org-fast-tag-selection
14384 current-tags inherited-tags table
14385 (if org-fast-tag-selection-include-todo
14386 org-todo-key-alist))
14387 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14388 (org-trim
14389 (org-icompleting-read "Tags: "
14390 'org-tags-completion-function
14391 nil nil current 'org-tags-history))))))
14392 (while (string-match "[-+&]+" tags)
14393 ;; No boolean logic, just a list
14394 (setq tags (replace-match ":" t t tags))))
14396 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14398 (if org-tags-sort-function
14399 (setq tags (mapconcat 'identity
14400 (sort (org-split-string
14401 tags (org-re "[^[:alnum:]_@#%]+"))
14402 org-tags-sort-function) ":")))
14404 (if (string-match "\\`[\t ]*\\'" tags)
14405 (setq tags "")
14406 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14407 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14409 ;; Insert new tags at the correct column
14410 (beginning-of-line 1)
14411 (setq level (or (and (looking-at org-outline-regexp)
14412 (- (match-end 0) (point) 1))
14414 (cond
14415 ((and (equal current "") (equal tags "")))
14416 ((re-search-forward
14417 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14418 (point-at-eol) t)
14419 (if (equal tags "")
14420 (setq rpl "")
14421 (goto-char (match-beginning 0))
14422 (setq c0 (current-column)
14423 ;; compute offset for the case of org-indent-mode active
14424 di (if org-indent-mode
14425 (* (1- org-indent-indentation-per-level) (1- level))
14427 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14428 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14429 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14430 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14431 (replace-match rpl t t)
14432 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14433 tags)
14434 (t (error "Tags alignment failed")))
14435 (org-move-to-column col)
14436 (unless just-align
14437 (run-hooks 'org-after-tags-change-hook))))))
14439 (defun org-change-tag-in-region (beg end tag off)
14440 "Add or remove TAG for each entry in the region.
14441 This works in the agenda, and also in an org-mode buffer."
14442 (interactive
14443 (list (region-beginning) (region-end)
14444 (let ((org-last-tags-completion-table
14445 (if (derived-mode-p 'org-mode)
14446 (org-get-buffer-tags)
14447 (org-global-tags-completion-table))))
14448 (org-icompleting-read
14449 "Tag: " 'org-tags-completion-function nil nil nil
14450 'org-tags-history))
14451 (progn
14452 (message "[s]et or [r]emove? ")
14453 (equal (read-char-exclusive) ?r))))
14454 (if (fboundp 'deactivate-mark) (deactivate-mark))
14455 (let ((agendap (equal major-mode 'org-agenda-mode))
14456 l1 l2 m buf pos newhead (cnt 0))
14457 (goto-char end)
14458 (setq l2 (1- (org-current-line)))
14459 (goto-char beg)
14460 (setq l1 (org-current-line))
14461 (loop for l from l1 to l2 do
14462 (org-goto-line l)
14463 (setq m (get-text-property (point) 'org-hd-marker))
14464 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14465 (and agendap m))
14466 (setq buf (if agendap (marker-buffer m) (current-buffer))
14467 pos (if agendap m (point)))
14468 (with-current-buffer buf
14469 (save-excursion
14470 (save-restriction
14471 (goto-char pos)
14472 (setq cnt (1+ cnt))
14473 (org-toggle-tag tag (if off 'off 'on))
14474 (setq newhead (org-get-heading)))))
14475 (and agendap (org-agenda-change-all-lines newhead m))))
14476 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14478 (defun org-tags-completion-function (string predicate &optional flag)
14479 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14480 (confirm (lambda (x) (stringp (car x)))))
14481 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14482 (setq s1 (match-string 1 string)
14483 s2 (match-string 2 string))
14484 (setq s1 "" s2 string))
14485 (cond
14486 ((eq flag nil)
14487 ;; try completion
14488 (setq rtn (try-completion s2 ctable confirm))
14489 (if (stringp rtn)
14490 (setq rtn
14491 (concat s1 s2 (substring rtn (length s2))
14492 (if (and org-add-colon-after-tag-completion
14493 (assoc rtn ctable))
14494 ":" ""))))
14495 rtn)
14496 ((eq flag t)
14497 ;; all-completions
14498 (all-completions s2 ctable confirm))
14499 ((eq flag 'lambda)
14500 ;; exact match?
14501 (assoc s2 ctable)))))
14503 (defun org-fast-tag-insert (kwd tags face &optional end)
14504 "Insert KDW, and the TAGS, the latter with face FACE.
14505 Also insert END."
14506 (insert (format "%-12s" (concat kwd ":"))
14507 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14508 (or end "")))
14510 (defun org-fast-tag-show-exit (flag)
14511 (save-excursion
14512 (org-goto-line 3)
14513 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14514 (replace-match ""))
14515 (when flag
14516 (end-of-line 1)
14517 (org-move-to-column (- (window-width) 19) t)
14518 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14520 (defun org-set-current-tags-overlay (current prefix)
14521 "Add an overlay to CURRENT tag with PREFIX."
14522 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14523 (if (featurep 'xemacs)
14524 (org-overlay-display org-tags-overlay (concat prefix s)
14525 'secondary-selection)
14526 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14527 (org-overlay-display org-tags-overlay (concat prefix s)))))
14529 (defvar org-last-tag-selection-key nil)
14530 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14531 "Fast tag selection with single keys.
14532 CURRENT is the current list of tags in the headline, INHERITED is the
14533 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14534 possibly with grouping information. TODO-TABLE is a similar table with
14535 TODO keywords, should these have keys assigned to them.
14536 If the keys are nil, a-z are automatically assigned.
14537 Returns the new tags string, or nil to not change the current settings."
14538 (let* ((fulltable (append table todo-table))
14539 (maxlen (apply 'max (mapcar
14540 (lambda (x)
14541 (if (stringp (car x)) (string-width (car x)) 0))
14542 fulltable)))
14543 (buf (current-buffer))
14544 (expert (eq org-fast-tag-selection-single-key 'expert))
14545 (buffer-tags nil)
14546 (fwidth (+ maxlen 3 1 3))
14547 (ncol (/ (- (window-width) 4) fwidth))
14548 (i-face 'org-done)
14549 (c-face 'org-todo)
14550 tg cnt e c char c1 c2 ntable tbl rtn
14551 ov-start ov-end ov-prefix
14552 (exit-after-next org-fast-tag-selection-single-key)
14553 (done-keywords org-done-keywords)
14554 groups ingroup)
14555 (save-excursion
14556 (beginning-of-line 1)
14557 (if (looking-at
14558 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14559 (setq ov-start (match-beginning 1)
14560 ov-end (match-end 1)
14561 ov-prefix "")
14562 (setq ov-start (1- (point-at-eol))
14563 ov-end (1+ ov-start))
14564 (skip-chars-forward "^\n\r")
14565 (setq ov-prefix
14566 (concat
14567 (buffer-substring (1- (point)) (point))
14568 (if (> (current-column) org-tags-column)
14570 (make-string (- org-tags-column (current-column)) ?\ ))))))
14571 (move-overlay org-tags-overlay ov-start ov-end)
14572 (save-window-excursion
14573 (if expert
14574 (set-buffer (get-buffer-create " *Org tags*"))
14575 (delete-other-windows)
14576 (split-window-vertically)
14577 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14578 (erase-buffer)
14579 (org-set-local 'org-done-keywords done-keywords)
14580 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14581 (org-fast-tag-insert "Current" current c-face "\n\n")
14582 (org-fast-tag-show-exit exit-after-next)
14583 (org-set-current-tags-overlay current ov-prefix)
14584 (setq tbl fulltable char ?a cnt 0)
14585 (while (setq e (pop tbl))
14586 (cond
14587 ((equal (car e) :startgroup)
14588 (push '() groups) (setq ingroup t)
14589 (when (not (= cnt 0))
14590 (setq cnt 0)
14591 (insert "\n"))
14592 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14593 ((equal (car e) :endgroup)
14594 (setq ingroup nil cnt 0)
14595 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14596 ((equal e '(:newline))
14597 (when (not (= cnt 0))
14598 (setq cnt 0)
14599 (insert "\n")
14600 (setq e (car tbl))
14601 (while (equal (car tbl) '(:newline))
14602 (insert "\n")
14603 (setq tbl (cdr tbl)))))
14604 ((equal e '(:grouptags)) nil)
14606 (setq tg (copy-sequence (car e)) c2 nil)
14607 (if (cdr e)
14608 (setq c (cdr e))
14609 ;; automatically assign a character.
14610 (setq c1 (string-to-char
14611 (downcase (substring
14612 tg (if (= (string-to-char tg) ?@) 1 0)))))
14613 (if (or (rassoc c1 ntable) (rassoc c1 table))
14614 (while (or (rassoc char ntable) (rassoc char table))
14615 (setq char (1+ char)))
14616 (setq c2 c1))
14617 (setq c (or c2 char)))
14618 (if ingroup (push tg (car groups)))
14619 (setq tg (org-add-props tg nil 'face
14620 (cond
14621 ((not (assoc tg table))
14622 (org-get-todo-face tg))
14623 ((member tg current) c-face)
14624 ((member tg inherited) i-face))))
14625 (if (equal (caar tbl) :grouptags)
14626 (org-add-props tg nil 'face 'org-tag-group))
14627 (if (and (= cnt 0) (not ingroup)) (insert " "))
14628 (insert "[" c "] " tg (make-string
14629 (- fwidth 4 (length tg)) ?\ ))
14630 (push (cons tg c) ntable)
14631 (when (= (setq cnt (1+ cnt)) ncol)
14632 (insert "\n")
14633 (if ingroup (insert " "))
14634 (setq cnt 0)))))
14635 (setq ntable (nreverse ntable))
14636 (insert "\n")
14637 (goto-char (point-min))
14638 (if (not expert) (org-fit-window-to-buffer))
14639 (setq rtn
14640 (catch 'exit
14641 (while t
14642 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14643 (if (not groups) "no " "")
14644 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14645 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14646 (setq org-last-tag-selection-key c)
14647 (cond
14648 ((= c ?\r) (throw 'exit t))
14649 ((= c ?!)
14650 (setq groups (not groups))
14651 (goto-char (point-min))
14652 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14653 ((= c ?\C-c)
14654 (if (not expert)
14655 (org-fast-tag-show-exit
14656 (setq exit-after-next (not exit-after-next)))
14657 (setq expert nil)
14658 (delete-other-windows)
14659 (set-window-buffer (split-window-vertically) " *Org tags*")
14660 (org-switch-to-buffer-other-window " *Org tags*")
14661 (org-fit-window-to-buffer)))
14662 ((or (= c ?\C-g)
14663 (and (= c ?q) (not (rassoc c ntable))))
14664 (org-detach-overlay org-tags-overlay)
14665 (setq quit-flag t))
14666 ((= c ?\ )
14667 (setq current nil)
14668 (if exit-after-next (setq exit-after-next 'now)))
14669 ((= c ?\t)
14670 (condition-case nil
14671 (setq tg (org-icompleting-read
14672 "Tag: "
14673 (or buffer-tags
14674 (with-current-buffer buf
14675 (org-get-buffer-tags)))))
14676 (quit (setq tg "")))
14677 (when (string-match "\\S-" tg)
14678 (add-to-list 'buffer-tags (list tg))
14679 (if (member tg current)
14680 (setq current (delete tg current))
14681 (push tg current)))
14682 (if exit-after-next (setq exit-after-next 'now)))
14683 ((setq e (rassoc c todo-table) tg (car e))
14684 (with-current-buffer buf
14685 (save-excursion (org-todo tg)))
14686 (if exit-after-next (setq exit-after-next 'now)))
14687 ((setq e (rassoc c ntable) tg (car e))
14688 (if (member tg current)
14689 (setq current (delete tg current))
14690 (loop for g in groups do
14691 (if (member tg g)
14692 (mapc (lambda (x)
14693 (setq current (delete x current)))
14694 g)))
14695 (push tg current))
14696 (if exit-after-next (setq exit-after-next 'now))))
14698 ;; Create a sorted list
14699 (setq current
14700 (sort current
14701 (lambda (a b)
14702 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14703 (if (eq exit-after-next 'now) (throw 'exit t))
14704 (goto-char (point-min))
14705 (beginning-of-line 2)
14706 (delete-region (point) (point-at-eol))
14707 (org-fast-tag-insert "Current" current c-face)
14708 (org-set-current-tags-overlay current ov-prefix)
14709 (while (re-search-forward
14710 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14711 (setq tg (match-string 1))
14712 (add-text-properties
14713 (match-beginning 1) (match-end 1)
14714 (list 'face
14715 (cond
14716 ((member tg current) c-face)
14717 ((member tg inherited) i-face)
14718 (t (get-text-property (match-beginning 1) 'face))))))
14719 (goto-char (point-min)))))
14720 (org-detach-overlay org-tags-overlay)
14721 (if rtn
14722 (mapconcat 'identity current ":")
14723 nil))))
14725 (defun org-get-tags-string ()
14726 "Get the TAGS string in the current headline."
14727 (unless (org-at-heading-p t)
14728 (error "Not on a heading"))
14729 (save-excursion
14730 (beginning-of-line 1)
14731 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14732 (org-match-string-no-properties 1)
14733 "")))
14735 (defun org-get-tags ()
14736 "Get the list of tags specified in the current headline."
14737 (org-split-string (org-get-tags-string) ":"))
14739 (defun org-get-buffer-tags ()
14740 "Get a table of all tags used in the buffer, for completion."
14741 (let (tags)
14742 (save-excursion
14743 (goto-char (point-min))
14744 (while (re-search-forward
14745 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14746 (when (equal (char-after (point-at-bol 0)) ?*)
14747 (mapc (lambda (x) (add-to-list 'tags x))
14748 (org-split-string (org-match-string-no-properties 1) ":")))))
14749 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14750 (mapcar 'list tags)))
14752 ;;;; The mapping API
14754 (defun org-map-entries (func &optional match scope &rest skip)
14755 "Call FUNC at each headline selected by MATCH in SCOPE.
14757 FUNC is a function or a lisp form. The function will be called without
14758 arguments, with the cursor positioned at the beginning of the headline.
14759 The return values of all calls to the function will be collected and
14760 returned as a list.
14762 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14763 does not need to preserve point. After evaluation, the cursor will be
14764 moved to the end of the line (presumably of the headline of the
14765 processed entry) and search continues from there. Under some
14766 circumstances, this may not produce the wanted results. For example,
14767 if you have removed (e.g. archived) the current (sub)tree it could
14768 mean that the next entry will be skipped entirely. In such cases, you
14769 can specify the position from where search should continue by making
14770 FUNC set the variable `org-map-continue-from' to the desired buffer
14771 position.
14773 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14774 Only headlines that are matched by this query will be considered during
14775 the iteration. When MATCH is nil or t, all headlines will be
14776 visited by the iteration.
14778 SCOPE determines the scope of this command. It can be any of:
14780 nil The current buffer, respecting the restriction if any
14781 tree The subtree started with the entry at point
14782 region The entries within the active region, if any
14783 region-start-level
14784 The entries within the active region, but only those at
14785 the same level than the first one.
14786 file The current buffer, without restriction
14787 file-with-archives
14788 The current buffer, and any archives associated with it
14789 agenda All agenda files
14790 agenda-with-archives
14791 All agenda files with any archive files associated with them
14792 \(file1 file2 ...)
14793 If this is a list, all files in the list will be scanned
14795 The remaining args are treated as settings for the skipping facilities of
14796 the scanner. The following items can be given here:
14798 archive skip trees with the archive tag
14799 comment skip trees with the COMMENT keyword
14800 function or Emacs Lisp form:
14801 will be used as value for `org-agenda-skip-function', so
14802 whenever the function returns a position, FUNC will not be
14803 called for that entry and search will continue from the
14804 position returned
14806 If your function needs to retrieve the tags including inherited tags
14807 at the *current* entry, you can use the value of the variable
14808 `org-scanner-tags' which will be much faster than getting the value
14809 with `org-get-tags-at'. If your function gets properties with
14810 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14811 to t around the call to `org-entry-properties' to get the same speedup.
14812 Note that if your function moves around to retrieve tags and properties at
14813 a *different* entry, you cannot use these techniques."
14814 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14815 (not (org-region-active-p)))
14816 (let* ((org-agenda-archives-mode nil) ; just to make sure
14817 (org-agenda-skip-archived-trees (memq 'archive skip))
14818 (org-agenda-skip-comment-trees (memq 'comment skip))
14819 (org-agenda-skip-function
14820 (car (org-delete-all '(comment archive) skip)))
14821 (org-tags-match-list-sublevels t)
14822 (start-level (eq scope 'region-start-level))
14823 matcher file res
14824 org-todo-keywords-for-agenda
14825 org-done-keywords-for-agenda
14826 org-todo-keyword-alist-for-agenda
14827 org-drawers-for-agenda
14828 org-tag-alist-for-agenda
14829 todo-only)
14831 (cond
14832 ((eq match t) (setq matcher t))
14833 ((eq match nil) (setq matcher t))
14834 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14836 (save-window-excursion
14837 (save-restriction
14838 (cond ((eq scope 'tree)
14839 (org-back-to-heading t)
14840 (org-narrow-to-subtree)
14841 (setq scope nil))
14842 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14843 (org-region-active-p))
14844 ;; If needed, set start-level to a string like "2"
14845 (when start-level
14846 (save-excursion
14847 (goto-char (region-beginning))
14848 (unless (org-at-heading-p) (outline-next-heading))
14849 (setq start-level (org-current-level))))
14850 (narrow-to-region (region-beginning)
14851 (save-excursion
14852 (goto-char (region-end))
14853 (unless (and (bolp) (org-at-heading-p))
14854 (outline-next-heading))
14855 (point)))
14856 (setq scope nil)))
14858 (if (not scope)
14859 (progn
14860 (org-agenda-prepare-buffers
14861 (list (buffer-file-name (current-buffer))))
14862 (setq res (org-scan-tags func matcher todo-only start-level)))
14863 ;; Get the right scope
14864 (cond
14865 ((and scope (listp scope) (symbolp (car scope)))
14866 (setq scope (eval scope)))
14867 ((eq scope 'agenda)
14868 (setq scope (org-agenda-files t)))
14869 ((eq scope 'agenda-with-archives)
14870 (setq scope (org-agenda-files t))
14871 (setq scope (org-add-archive-files scope)))
14872 ((eq scope 'file)
14873 (setq scope (list (buffer-file-name))))
14874 ((eq scope 'file-with-archives)
14875 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14876 (org-agenda-prepare-buffers scope)
14877 (while (setq file (pop scope))
14878 (with-current-buffer (org-find-base-buffer-visiting file)
14879 (save-excursion
14880 (save-restriction
14881 (widen)
14882 (goto-char (point-min))
14883 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14884 res)))
14886 ;;;; Properties
14888 ;;; Setting and retrieving properties
14890 (defconst org-special-properties
14891 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14892 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14893 "The special properties valid in Org-mode.
14895 These are properties that are not defined in the property drawer,
14896 but in some other way.")
14898 (defconst org-default-properties
14899 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14900 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14901 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14902 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14903 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14904 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14905 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14906 "Some properties that are used by Org-mode for various purposes.
14907 Being in this list makes sure that they are offered for completion.")
14909 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14910 "Regular expression matching the first line of a property drawer.")
14912 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14913 "Regular expression matching the last line of a property drawer.")
14915 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14916 "Regular expression matching the first line of a property drawer.")
14918 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14919 "Regular expression matching the first line of a property drawer.")
14921 (defconst org-property-drawer-re
14922 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14923 org-property-end-re "\\)\n?")
14924 "Matches an entire property drawer.")
14926 (defconst org-clock-drawer-re
14927 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14928 org-property-end-re "\\)\n?")
14929 "Matches an entire clock drawer.")
14931 (defsubst org-re-property (property)
14932 "Return a regexp matching a PROPERTY line.
14933 Match group 1 will be set to the value."
14934 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14936 (defsubst org-re-property-keyword (property)
14937 "Return a regexp matching a PROPERTY line, possibly with no
14938 value for the property."
14939 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14941 (defun org-property-action ()
14942 "Do an action on properties."
14943 (interactive)
14944 (let (c)
14945 (org-at-property-p)
14946 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14947 (setq c (read-char-exclusive))
14948 (cond
14949 ((equal c ?s)
14950 (call-interactively 'org-set-property))
14951 ((equal c ?d)
14952 (call-interactively 'org-delete-property))
14953 ((equal c ?D)
14954 (call-interactively 'org-delete-property-globally))
14955 ((equal c ?c)
14956 (call-interactively 'org-compute-property-at-point))
14957 (t (error "No such property action %c" c)))))
14959 (defun org-inc-effort ()
14960 "Increment the value of the effort property in the current entry."
14961 (interactive)
14962 (org-set-effort nil t))
14964 (defvar org-clock-effort) ;; Defined in org-clock.el
14965 (defvar org-clock-current-task) ;; Defined in org-clock.el
14966 (defun org-set-effort (&optional value increment)
14967 "Set the effort property of the current entry.
14968 With numerical prefix arg, use the nth allowed value, 0 stands for the
14969 10th allowed value.
14971 When INCREMENT is non-nil, set the property to the next allowed value."
14972 (interactive "P")
14973 (if (equal value 0) (setq value 10))
14974 (let* ((completion-ignore-case t)
14975 (prop org-effort-property)
14976 (cur (org-entry-get nil prop))
14977 (allowed (org-property-get-allowed-values nil prop 'table))
14978 (existing (mapcar 'list (org-property-values prop)))
14979 (heading (nth 4 (org-heading-components)))
14981 (val (cond
14982 ((stringp value) value)
14983 ((and allowed (integerp value))
14984 (or (car (nth (1- value) allowed))
14985 (car (org-last allowed))))
14986 ((and allowed increment)
14987 (or (caadr (member (list cur) allowed))
14988 (error "Allowed effort values are not set")))
14989 (allowed
14990 (message "Select 1-9,0, [RET%s]: %s"
14991 (if cur (concat "=" cur) "")
14992 (mapconcat 'car allowed " "))
14993 (setq rpl (read-char-exclusive))
14994 (if (equal rpl ?\r)
14996 (setq rpl (- rpl ?0))
14997 (if (equal rpl 0) (setq rpl 10))
14998 (if (and (> rpl 0) (<= rpl (length allowed)))
14999 (car (nth (1- rpl) allowed))
15000 (org-completing-read "Effort: " allowed nil))))
15002 (let (org-completion-use-ido org-completion-use-iswitchb)
15003 (org-completing-read
15004 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15005 (concat "[" cur "]") "")
15006 ": ")
15007 existing nil nil "" nil cur))))))
15008 (unless (equal (org-entry-get nil prop) val)
15009 (org-entry-put nil prop val))
15010 (save-excursion
15011 (org-back-to-heading t)
15012 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15013 (when (string= heading org-clock-current-task)
15014 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15015 (org-clock-update-mode-line))
15016 (message "%s is now %s" prop val)))
15018 (defun org-at-property-p ()
15019 "Is cursor inside a property drawer?"
15020 (save-excursion
15021 (beginning-of-line 1)
15022 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15023 (save-match-data ;; Used by calling procedures
15024 (let ((p (point))
15025 (range (unless (org-before-first-heading-p)
15026 (org-get-property-block))))
15027 (and range (<= (car range) p) (< p (cdr range))))))))
15029 (defun org-get-property-block (&optional beg end force)
15030 "Return the (beg . end) range of the body of the property drawer.
15031 BEG and END are the beginning and end of the current subtree, or of
15032 the part before the first headline. If they are not given, they will
15033 be found. If the drawer does not exist and FORCE is non-nil, create
15034 the drawer."
15035 (catch 'exit
15036 (save-excursion
15037 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15038 (progn (org-back-to-heading t) (point))))
15039 (end (or end (and (not (outline-next-heading)) (point-max))
15040 (point))))
15041 (goto-char beg)
15042 (if (re-search-forward org-property-start-re end t)
15043 (setq beg (1+ (match-end 0)))
15044 (if force
15045 (save-excursion
15046 (org-insert-property-drawer)
15047 (setq end (progn (outline-next-heading) (point))))
15048 (throw 'exit nil))
15049 (goto-char beg)
15050 (if (re-search-forward org-property-start-re end t)
15051 (setq beg (1+ (match-end 0)))))
15052 (if (re-search-forward org-property-end-re end t)
15053 (setq end (match-beginning 0))
15054 (or force (throw 'exit nil))
15055 (goto-char beg)
15056 (setq end beg)
15057 (org-indent-line)
15058 (insert ":END:\n"))
15059 (cons beg end)))))
15061 (defun org-entry-properties (&optional pom which specific)
15062 "Get all properties of the entry at point-or-marker POM.
15063 This includes the TODO keyword, the tags, time strings for deadline,
15064 scheduled, and clocking, and any additional properties defined in the
15065 entry. The return value is an alist, keys may occur multiple times
15066 if the property key was used several times.
15067 POM may also be nil, in which case the current entry is used.
15068 If WHICH is nil or `all', get all properties. If WHICH is
15069 `special' or `standard', only get that subclass. If WHICH
15070 is a string only get exactly this property. SPECIFIC can be a string, the
15071 specific property we are interested in. Specifying it can speed
15072 things up because then unnecessary parsing is avoided."
15073 (setq which (or which 'all))
15074 (org-with-point-at pom
15075 (let ((clockstr (substring org-clock-string 0 -1))
15076 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15077 (case-fold-search nil)
15078 beg end range props sum-props key key1 value string clocksum clocksumt)
15079 (save-excursion
15080 (when (condition-case nil
15081 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15082 (error nil))
15083 (setq beg (point))
15084 (setq sum-props (get-text-property (point) 'org-summaries))
15085 (setq clocksum (get-text-property (point) :org-clock-minutes)
15086 clocksumt (get-text-property (point) :org-clock-minutes-today))
15087 (outline-next-heading)
15088 (setq end (point))
15089 (when (memq which '(all special))
15090 ;; Get the special properties, like TODO and tags
15091 (goto-char beg)
15092 (when (and (or (not specific) (string= specific "TODO"))
15093 (looking-at org-todo-line-regexp) (match-end 2))
15094 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15095 (when (and (or (not specific) (string= specific "PRIORITY"))
15096 (looking-at org-priority-regexp))
15097 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15098 (when (or (not specific) (string= specific "FILE"))
15099 (push (cons "FILE" buffer-file-name) props))
15100 (when (and (or (not specific) (string= specific "TAGS"))
15101 (setq value (org-get-tags-string))
15102 (string-match "\\S-" value))
15103 (push (cons "TAGS" value) props))
15104 (when (and (or (not specific) (string= specific "ALLTAGS"))
15105 (setq value (org-get-tags-at)))
15106 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15107 ":"))
15108 props))
15109 (when (or (not specific) (string= specific "BLOCKED"))
15110 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15111 (when (or (not specific)
15112 (member specific
15113 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15114 "TIMESTAMP" "TIMESTAMP_IA")))
15115 (catch 'match
15116 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15117 (setq key (if (match-end 1)
15118 (substring (org-match-string-no-properties 1)
15119 0 -1))
15120 string (if (equal key clockstr)
15121 (org-trim
15122 (buffer-substring-no-properties
15123 (match-beginning 3) (goto-char
15124 (point-at-eol))))
15125 (substring (org-match-string-no-properties 3)
15126 1 -1)))
15127 ;; Get the correct property name from the key. This is
15128 ;; necessary if the user has configured time keywords.
15129 (setq key1 (concat key ":"))
15130 (cond
15131 ((not key)
15132 (setq key
15133 (if (= (char-after (match-beginning 3)) ?\[)
15134 "TIMESTAMP_IA" "TIMESTAMP")))
15135 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15136 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15137 ((equal key1 org-closed-string) (setq key "CLOSED"))
15138 ((equal key1 org-clock-string) (setq key "CLOCK")))
15139 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15140 (progn
15141 (push (cons key string) props)
15142 ;; no need to search further if match is found
15143 (throw 'match t))
15144 (when (or (equal key "CLOCK") (not (assoc key props)))
15145 (push (cons key string) props)))))))
15147 (when (memq which '(all standard))
15148 ;; Get the standard properties, like :PROP: ...
15149 (setq range (org-get-property-block beg end))
15150 (when range
15151 (goto-char (car range))
15152 (while (re-search-forward
15153 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15154 (cdr range) t)
15155 (setq key (org-match-string-no-properties 1)
15156 value (org-trim (or (org-match-string-no-properties 2) "")))
15157 (unless (member key excluded)
15158 (push (cons key (or value "")) props)))))
15159 (if clocksum
15160 (push (cons "CLOCKSUM"
15161 (org-columns-number-to-string (/ (float clocksum) 60.)
15162 'add_times))
15163 props))
15164 (if clocksumt
15165 (push (cons "CLOCKSUM_T"
15166 (org-columns-number-to-string (/ (float clocksumt) 60.)
15167 'add_times))
15168 props))
15169 (unless (assoc "CATEGORY" props)
15170 (push (cons "CATEGORY" (org-get-category)) props))
15171 (append sum-props (nreverse props)))))))
15173 (defun org-entry-get (pom property &optional inherit literal-nil)
15174 "Get value of PROPERTY for entry or content at point-or-marker POM.
15175 If INHERIT is non-nil and the entry does not have the property,
15176 then also check higher levels of the hierarchy.
15177 If INHERIT is the symbol `selective', use inheritance only if the setting
15178 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15179 If the property is present but empty, the return value is the empty string.
15180 If the property is not present at all, nil is returned.
15182 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15183 do not interpret it as the list atom nil. This is used for inheritance
15184 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15185 (org-with-point-at pom
15186 (if (and inherit (if (eq inherit 'selective)
15187 (org-property-inherit-p property)
15189 (org-entry-get-with-inheritance property literal-nil)
15190 (if (member property org-special-properties)
15191 ;; We need a special property. Use `org-entry-properties' to
15192 ;; retrieve it, but specify the wanted property
15193 (cdr (assoc property (org-entry-properties nil 'special property)))
15194 (let ((range (org-get-property-block)))
15195 (when (and range (not (eq (car range) (cdr range))))
15196 (let* ((props (list (or (assoc property org-file-properties)
15197 (assoc property org-global-properties)
15198 (assoc property org-global-properties-fixed))))
15199 (ap (lambda (key)
15200 (when (re-search-forward
15201 (org-re-property key) (cdr range) t)
15202 (setq props
15203 (org-update-property-plist
15205 (if (match-end 1)
15206 (org-match-string-no-properties 1) "")
15207 props)))))
15208 val)
15209 (goto-char (car range))
15210 (funcall ap property)
15211 (goto-char (car range))
15212 (while (funcall ap (concat property "+")))
15213 (setq val (cdr (assoc property props)))
15214 (when val (if literal-nil val (org-not-nil val))))))))))
15216 (defun org-property-or-variable-value (var &optional inherit)
15217 "Check if there is a property fixing the value of VAR.
15218 If yes, return this value. If not, return the current value of the variable."
15219 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15220 (if (and prop (stringp prop) (string-match "\\S-" prop))
15221 (read prop)
15222 (symbol-value var))))
15224 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15225 "Delete the property PROPERTY from entry at point-or-marker POM.
15226 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15227 an empty drawer to delete."
15228 (org-with-point-at pom
15229 (if (member property org-special-properties)
15230 nil ; cannot delete these properties.
15231 (let ((range (org-get-property-block)))
15232 (if (and range
15233 (goto-char (car range))
15234 (re-search-forward
15235 (org-re-property property)
15236 (cdr range) t))
15237 (progn
15238 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15239 (and delete-empty-drawer
15240 (org-remove-empty-drawer-at
15241 delete-empty-drawer (car range)))
15243 nil)))))
15245 ;; Multi-values properties are properties that contain multiple values
15246 ;; These values are assumed to be single words, separated by whitespace.
15247 (defun org-entry-add-to-multivalued-property (pom property value)
15248 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15249 (let* ((old (org-entry-get pom property))
15250 (values (and old (org-split-string old "[ \t]"))))
15251 (setq value (org-entry-protect-space value))
15252 (unless (member value values)
15253 (setq values (append values (list value)))
15254 (org-entry-put pom property
15255 (mapconcat 'identity values " ")))))
15257 (defun org-entry-remove-from-multivalued-property (pom property value)
15258 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15259 (let* ((old (org-entry-get pom property))
15260 (values (and old (org-split-string old "[ \t]"))))
15261 (setq value (org-entry-protect-space value))
15262 (when (member value values)
15263 (setq values (delete value values))
15264 (org-entry-put pom property
15265 (mapconcat 'identity values " ")))))
15267 (defun org-entry-member-in-multivalued-property (pom property value)
15268 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15269 (let* ((old (org-entry-get pom property))
15270 (values (and old (org-split-string old "[ \t]"))))
15271 (setq value (org-entry-protect-space value))
15272 (member value values)))
15274 (defun org-entry-get-multivalued-property (pom property)
15275 "Return a list of values in a multivalued property."
15276 (let* ((value (org-entry-get pom property))
15277 (values (and value (org-split-string value "[ \t]"))))
15278 (mapcar 'org-entry-restore-space values)))
15280 (defun org-entry-put-multivalued-property (pom property &rest values)
15281 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15282 VALUES should be a list of strings. Spaces will be protected."
15283 (org-entry-put pom property
15284 (mapconcat 'org-entry-protect-space values " "))
15285 (let* ((value (org-entry-get pom property))
15286 (values (and value (org-split-string value "[ \t]"))))
15287 (mapcar 'org-entry-restore-space values)))
15289 (defun org-entry-protect-space (s)
15290 "Protect spaces and newline in string S."
15291 (while (string-match " " s)
15292 (setq s (replace-match "%20" t t s)))
15293 (while (string-match "\n" s)
15294 (setq s (replace-match "%0A" t t s)))
15297 (defun org-entry-restore-space (s)
15298 "Restore spaces and newline in string S."
15299 (while (string-match "%20" s)
15300 (setq s (replace-match " " t t s)))
15301 (while (string-match "%0A" s)
15302 (setq s (replace-match "\n" t t s)))
15305 (defvar org-entry-property-inherited-from (make-marker)
15306 "Marker pointing to the entry from where a property was inherited.
15307 Each call to `org-entry-get-with-inheritance' will set this marker to the
15308 location of the entry where the inheritance search matched. If there was
15309 no match, the marker will point nowhere.
15310 Note that also `org-entry-get' calls this function, if the INHERIT flag
15311 is set.")
15313 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15314 "Get PROPERTY of entry or content at point, search higher levels if needed.
15315 The search will stop at the first ancestor which has the property defined.
15316 If the value found is \"nil\", return nil to show that the property
15317 should be considered as undefined (this is the meaning of nil here).
15318 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15319 (move-marker org-entry-property-inherited-from nil)
15320 (let (tmp)
15321 (save-excursion
15322 (save-restriction
15323 (widen)
15324 (catch 'ex
15325 (while t
15326 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15327 (or (ignore-errors (org-back-to-heading t))
15328 (goto-char (point-min)))
15329 (move-marker org-entry-property-inherited-from (point))
15330 (throw 'ex tmp))
15331 (or (ignore-errors (org-up-heading-safe))
15332 (throw 'ex nil))))))
15333 (setq tmp (or tmp
15334 (cdr (assoc property org-file-properties))
15335 (cdr (assoc property org-global-properties))
15336 (cdr (assoc property org-global-properties-fixed))))
15337 (if literal-nil tmp (org-not-nil tmp))))
15339 (defvar org-property-changed-functions nil
15340 "Hook called when the value of a property has changed.
15341 Each hook function should accept two arguments, the name of the property
15342 and the new value.")
15344 (defun org-entry-put (pom property value)
15345 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15346 (org-with-point-at pom
15347 (org-back-to-heading t)
15348 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15349 range)
15350 (cond
15351 ((equal property "TODO")
15352 (when (and (stringp value) (string-match "\\S-" value)
15353 (not (member value org-todo-keywords-1)))
15354 (error "\"%s\" is not a valid TODO state" value))
15355 (if (or (not value)
15356 (not (string-match "\\S-" value)))
15357 (setq value 'none))
15358 (org-todo value)
15359 (org-set-tags nil 'align))
15360 ((equal property "PRIORITY")
15361 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15362 (string-to-char value) ?\ ))
15363 (org-set-tags nil 'align))
15364 ((equal property "CLOCKSUM")
15365 (if (not (re-search-forward
15366 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15367 (error "Cannot find a clock log")
15368 (goto-char (- (match-end 1) 2))
15369 (cond
15370 ((eq value 'earlier) (org-timestamp-down))
15371 ((eq value 'later) (org-timestamp-up)))
15372 (org-clock-sum-current-item)))
15373 ((equal property "SCHEDULED")
15374 (if (re-search-forward org-scheduled-time-regexp end t)
15375 (cond
15376 ((eq value 'earlier) (org-timestamp-change -1 'day))
15377 ((eq value 'later) (org-timestamp-change 1 'day))
15378 (t (call-interactively 'org-schedule)))
15379 (call-interactively 'org-schedule)))
15380 ((equal property "DEADLINE")
15381 (if (re-search-forward org-deadline-time-regexp end t)
15382 (cond
15383 ((eq value 'earlier) (org-timestamp-change -1 'day))
15384 ((eq value 'later) (org-timestamp-change 1 'day))
15385 (t (call-interactively 'org-deadline)))
15386 (call-interactively 'org-deadline)))
15387 ((member property org-special-properties)
15388 (error "The %s property can not yet be set with `org-entry-put'"
15389 property))
15390 (t ; a non-special property
15391 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15392 (setq range (org-get-property-block beg end 'force))
15393 (goto-char (car range))
15394 (if (re-search-forward
15395 (org-re-property-keyword property) (cdr range) t)
15396 (progn
15397 (delete-region (match-beginning 0) (match-end 0))
15398 (goto-char (match-beginning 0)))
15399 (goto-char (cdr range))
15400 (insert "\n")
15401 (backward-char 1)
15402 (org-indent-line))
15403 (insert ":" property ":")
15404 (and value (insert " " value))
15405 (org-indent-line)))))
15406 (run-hook-with-args 'org-property-changed-functions property value)))
15408 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15409 "Get all property keys in the current buffer.
15410 With INCLUDE-SPECIALS, also list the special properties that reflect things
15411 like tags and TODO state.
15412 With INCLUDE-DEFAULTS, also include properties that has special meaning
15413 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15414 and others.
15415 With INCLUDE-COLUMNS, also include property names given in COLUMN
15416 formats in the current buffer."
15417 (let (rtn range cfmt s p)
15418 (save-excursion
15419 (save-restriction
15420 (widen)
15421 (goto-char (point-min))
15422 (while (re-search-forward org-property-start-re nil t)
15423 (setq range (org-get-property-block))
15424 (goto-char (car range))
15425 (while (re-search-forward
15426 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15427 (cdr range) t)
15428 (add-to-list 'rtn (org-match-string-no-properties 1)))
15429 (outline-next-heading))))
15431 (when include-specials
15432 (setq rtn (append org-special-properties rtn)))
15434 (when include-defaults
15435 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15436 (add-to-list 'rtn org-effort-property))
15438 (when include-columns
15439 (save-excursion
15440 (save-restriction
15441 (widen)
15442 (goto-char (point-min))
15443 (while (re-search-forward
15444 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15445 nil t)
15446 (setq cfmt (match-string 2) s 0)
15447 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15448 cfmt s)
15449 (setq s (match-end 0)
15450 p (match-string 1 cfmt))
15451 (unless (or (equal p "ITEM")
15452 (member p org-special-properties))
15453 (add-to-list 'rtn (match-string 1 cfmt))))))))
15455 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15457 (defun org-property-values (key)
15458 "Return a list of all values of property KEY in the current buffer."
15459 (save-excursion
15460 (save-restriction
15461 (widen)
15462 (goto-char (point-min))
15463 (let ((re (org-re-property key))
15464 values)
15465 (while (re-search-forward re nil t)
15466 (add-to-list 'values (org-trim (match-string 1))))
15467 (delete "" values)))))
15469 (defun org-insert-property-drawer ()
15470 "Insert a property drawer into the current entry."
15471 (org-back-to-heading t)
15472 (looking-at org-outline-regexp)
15473 (let ((indent (if org-adapt-indentation
15474 (- (match-end 0) (match-beginning 0))
15476 (beg (point))
15477 (re (concat "^[ \t]*" org-keyword-time-regexp))
15478 end hiddenp)
15479 (outline-next-heading)
15480 (setq end (point))
15481 (goto-char beg)
15482 (while (re-search-forward re end t))
15483 (setq hiddenp (outline-invisible-p))
15484 (end-of-line 1)
15485 (and (equal (char-after) ?\n) (forward-char 1))
15486 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15487 (if (member (match-string 1) '("CLOCK:" ":END:"))
15488 ;; just skip this line
15489 (beginning-of-line 2)
15490 ;; Drawer start, find the end
15491 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15492 (beginning-of-line 1)))
15493 (org-skip-over-state-notes)
15494 (skip-chars-backward " \t\n\r")
15495 (if (eq (char-before) ?*) (forward-char 1))
15496 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15497 (beginning-of-line 0)
15498 (org-indent-to-column indent)
15499 (beginning-of-line 2)
15500 (org-indent-to-column indent)
15501 (beginning-of-line 0)
15502 (if hiddenp
15503 (save-excursion
15504 (org-back-to-heading t)
15505 (hide-entry))
15506 (org-flag-drawer t))))
15508 (defun org-insert-drawer (&optional arg drawer)
15509 "Insert a drawer at point.
15511 Optional argument DRAWER, when non-nil, is a string representing
15512 drawer's name. Otherwise, the user is prompted for a name.
15514 If a region is active, insert the drawer around that region
15515 instead.
15517 Point is left between drawer's boundaries."
15518 (interactive "P")
15519 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15520 "LOGBOOK"))
15521 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15522 ;; internally by Org. They are meant to be inserted
15523 ;; automatically.
15524 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15525 ;; Remove system drawers from list. Note: For some reason,
15526 ;; `org-completing-read' ignores the predicate while
15527 ;; `completing-read' handles it fine.
15528 (drawer (if arg "PROPERTIES"
15529 (or drawer
15530 (completing-read
15531 "Drawer: " org-drawers
15532 (lambda (d) (not (member d system-drawers))))))))
15533 (cond
15534 ;; With C-u, fall back on `org-insert-property-drawer'
15535 (arg (org-insert-property-drawer))
15536 ;; With an active region, insert a drawer at point.
15537 ((not (org-region-active-p))
15538 (progn
15539 (unless (bolp) (insert "\n"))
15540 (insert (format ":%s:\n\n:END:\n" drawer))
15541 (forward-line -2)))
15542 ;; Otherwise, insert the drawer at point
15544 (let ((rbeg (region-beginning))
15545 (rend (copy-marker (region-end))))
15546 (unwind-protect
15547 (progn
15548 (goto-char rbeg)
15549 (beginning-of-line)
15550 (when (save-excursion
15551 (re-search-forward org-outline-regexp-bol rend t))
15552 (error "Drawers cannot contain headlines"))
15553 ;; Position point at the beginning of the first
15554 ;; non-blank line in region. Insert drawer's opening
15555 ;; there, then indent it.
15556 (org-skip-whitespace)
15557 (beginning-of-line)
15558 (insert ":" drawer ":\n")
15559 (forward-line -1)
15560 (indent-for-tab-command)
15561 ;; Move point to the beginning of the first blank line
15562 ;; after the last non-blank line in region. Insert
15563 ;; drawer's closing, then indent it.
15564 (goto-char rend)
15565 (skip-chars-backward " \r\t\n")
15566 (insert "\n:END:")
15567 (deactivate-mark t)
15568 (indent-for-tab-command)
15569 (unless (eolp) (insert "\n")))
15570 ;; Clear marker, whatever the outcome of insertion is.
15571 (set-marker rend nil)))))))
15573 (defvar org-property-set-functions-alist nil
15574 "Property set function alist.
15575 Each entry should have the following format:
15577 (PROPERTY . READ-FUNCTION)
15579 The read function will be called with the same argument as
15580 `org-completing-read'.")
15582 (defun org-set-property-function (property)
15583 "Get the function that should be used to set PROPERTY.
15584 This is computed according to `org-property-set-functions-alist'."
15585 (or (cdr (assoc property org-property-set-functions-alist))
15586 'org-completing-read))
15588 (defun org-read-property-value (property)
15589 "Read PROPERTY value from user."
15590 (let* ((completion-ignore-case t)
15591 (allowed (org-property-get-allowed-values nil property 'table))
15592 (cur (org-entry-get nil property))
15593 (prompt (concat property " value"
15594 (if (and cur (string-match "\\S-" cur))
15595 (concat " [" cur "]") "") ": "))
15596 (set-function (org-set-property-function property))
15597 (val (if allowed
15598 (funcall set-function prompt allowed nil
15599 (not (get-text-property 0 'org-unrestricted
15600 (caar allowed))))
15601 (let (org-completion-use-ido org-completion-use-iswitchb)
15602 (funcall set-function prompt
15603 (mapcar 'list (org-property-values property))
15604 nil nil "" nil cur)))))
15605 (if (equal val "")
15607 val)))
15609 (defvar org-last-set-property nil)
15610 (defvar org-last-set-property-value nil)
15611 (defun org-read-property-name ()
15612 "Read a property name."
15613 (let* ((completion-ignore-case t)
15614 (keys (org-buffer-property-keys nil t t))
15615 (default-prop (or (save-excursion
15616 (save-match-data
15617 (beginning-of-line)
15618 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15619 (null (string= (match-string 1) "END"))
15620 (match-string 1))))
15621 org-last-set-property))
15622 (property (org-icompleting-read
15623 (concat "Property"
15624 (if default-prop (concat " [" default-prop "]") "")
15625 ": ")
15626 (mapcar 'list keys)
15627 nil nil nil nil
15628 default-prop)))
15629 (if (member property keys)
15630 property
15631 (or (cdr (assoc (downcase property)
15632 (mapcar (lambda (x) (cons (downcase x) x))
15633 keys)))
15634 property))))
15636 (defun org-set-property-and-value (use-last)
15637 "Allow to set [PROPERTY]: [value] direction from prompt.
15638 When use-default, don't even ask, just use the last
15639 \"[PROPERTY]: [value]\" string from the history."
15640 (interactive "P")
15641 (let* ((completion-ignore-case t)
15642 (pv (or (and use-last org-last-set-property-value)
15643 (org-completing-read
15644 "Enter a \"[Property]: [value]\" pair: "
15645 nil nil nil nil nil
15646 org-last-set-property-value)))
15647 prop val)
15648 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15649 (setq prop (match-string 1 pv)
15650 val (match-string 2 pv))
15651 (org-set-property prop val))))
15653 (defun org-set-property (property value)
15654 "In the current entry, set PROPERTY to VALUE.
15655 When called interactively, this will prompt for a property name, offering
15656 completion on existing and default properties. And then it will prompt
15657 for a value, offering completion either on allowed values (via an inherited
15658 xxx_ALL property) or on existing values in other instances of this property
15659 in the current file."
15660 (interactive (list nil nil))
15661 (let* ((property (or property (org-read-property-name)))
15662 (value (or value (org-read-property-value property)))
15663 (fn (cdr (assoc property org-properties-postprocess-alist))))
15664 (setq org-last-set-property property)
15665 (setq org-last-set-property-value (concat property ": " value))
15666 ;; Possibly postprocess the inserted value:
15667 (when fn (setq value (funcall fn value)))
15668 (unless (equal (org-entry-get nil property) value)
15669 (org-entry-put nil property value))))
15671 (defun org-delete-property (property &optional delete-empty-drawer)
15672 "In the current entry, delete PROPERTY.
15673 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15674 an empty drawer to delete."
15675 (interactive
15676 (let* ((completion-ignore-case t)
15677 (prop (org-icompleting-read "Property: "
15678 (org-entry-properties nil 'standard))))
15679 (list prop)))
15680 (message "Property %s %s" property
15681 (if (org-entry-delete nil property delete-empty-drawer)
15682 "deleted"
15683 "was not present in the entry")))
15685 (defun org-delete-property-globally (property)
15686 "Remove PROPERTY globally, from all entries."
15687 (interactive
15688 (let* ((completion-ignore-case t)
15689 (prop (org-icompleting-read
15690 "Globally remove property: "
15691 (mapcar 'list (org-buffer-property-keys)))))
15692 (list prop)))
15693 (save-excursion
15694 (save-restriction
15695 (widen)
15696 (goto-char (point-min))
15697 (let ((cnt 0))
15698 (while (re-search-forward
15699 (org-re-property property)
15700 nil t)
15701 (setq cnt (1+ cnt))
15702 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15703 (message "Property \"%s\" removed from %d entries" property cnt)))))
15705 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15707 (defun org-compute-property-at-point ()
15708 "Compute the property at point.
15709 This looks for an enclosing column format, extracts the operator and
15710 then applies it to the property in the column format's scope."
15711 (interactive)
15712 (unless (org-at-property-p)
15713 (error "Not at a property"))
15714 (let ((prop (org-match-string-no-properties 2)))
15715 (org-columns-get-format-and-top-level)
15716 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15717 (error "No operator defined for property %s" prop))
15718 (org-columns-compute prop)))
15720 (defvar org-property-allowed-value-functions nil
15721 "Hook for functions supplying allowed values for a specific property.
15722 The functions must take a single argument, the name of the property, and
15723 return a flat list of allowed values. If \":ETC\" is one of
15724 the values, this means that these values are intended as defaults for
15725 completion, but that other values should be allowed too.
15726 The functions must return nil if they are not responsible for this
15727 property.")
15729 (defun org-property-get-allowed-values (pom property &optional table)
15730 "Get allowed values for the property PROPERTY.
15731 When TABLE is non-nil, return an alist that can directly be used for
15732 completion."
15733 (let (vals)
15734 (cond
15735 ((equal property "TODO")
15736 (setq vals (org-with-point-at pom
15737 (append org-todo-keywords-1 '("")))))
15738 ((equal property "PRIORITY")
15739 (let ((n org-lowest-priority))
15740 (while (>= n org-highest-priority)
15741 (push (char-to-string n) vals)
15742 (setq n (1- n)))))
15743 ((member property org-special-properties))
15744 ((setq vals (run-hook-with-args-until-success
15745 'org-property-allowed-value-functions property)))
15747 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15748 (when (and vals (string-match "\\S-" vals))
15749 (setq vals (car (read-from-string (concat "(" vals ")"))))
15750 (setq vals (mapcar (lambda (x)
15751 (cond ((stringp x) x)
15752 ((numberp x) (number-to-string x))
15753 ((symbolp x) (symbol-name x))
15754 (t "???")))
15755 vals)))))
15756 (when (member ":ETC" vals)
15757 (setq vals (remove ":ETC" vals))
15758 (org-add-props (car vals) '(org-unrestricted t)))
15759 (if table (mapcar 'list vals) vals)))
15761 (defun org-property-previous-allowed-value (&optional previous)
15762 "Switch to the next allowed value for this property."
15763 (interactive)
15764 (org-property-next-allowed-value t))
15766 (defun org-property-next-allowed-value (&optional previous)
15767 "Switch to the next allowed value for this property."
15768 (interactive)
15769 (unless (org-at-property-p)
15770 (error "Not at a property"))
15771 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15772 (key (match-string 2))
15773 (value (match-string 3))
15774 (allowed (or (org-property-get-allowed-values (point) key)
15775 (and (member value '("[ ]" "[-]" "[X]"))
15776 '("[ ]" "[X]"))))
15777 (heading (save-match-data (nth 4 (org-heading-components))))
15778 nval)
15779 (unless allowed
15780 (error "Allowed values for this property have not been defined"))
15781 (if previous (setq allowed (reverse allowed)))
15782 (if (member value allowed)
15783 (setq nval (car (cdr (member value allowed)))))
15784 (setq nval (or nval (car allowed)))
15785 (if (equal nval value)
15786 (error "Only one allowed value for this property"))
15787 (org-at-property-p)
15788 (replace-match (concat " :" key ": " nval) t t)
15789 (org-indent-line)
15790 (beginning-of-line 1)
15791 (skip-chars-forward " \t")
15792 (when (equal prop org-effort-property)
15793 (save-excursion
15794 (org-back-to-heading t)
15795 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15796 (when (string= org-clock-current-task heading)
15797 (setq org-clock-effort nval)
15798 (org-clock-update-mode-line)))
15799 (run-hook-with-args 'org-property-changed-functions key nval)))
15801 (defun org-find-olp (path &optional this-buffer)
15802 "Return a marker pointing to the entry at outline path OLP.
15803 If anything goes wrong, throw an error.
15804 You can wrap this call to catch the error like this:
15806 (condition-case msg
15807 (org-mobile-locate-entry (match-string 4))
15808 (error (nth 1 msg)))
15810 The return value will then be either a string with the error message,
15811 or a marker if everything is OK.
15813 If THIS-BUFFER is set, the outline path does not contain a file,
15814 only headings."
15815 (let* ((file (if this-buffer buffer-file-name (pop path)))
15816 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15817 (level 1)
15818 (lmin 1)
15819 (lmax 1)
15820 limit re end found pos heading cnt flevel)
15821 (unless buffer (error "File not found :%s" file))
15822 (with-current-buffer buffer
15823 (save-excursion
15824 (save-restriction
15825 (widen)
15826 (setq limit (point-max))
15827 (goto-char (point-min))
15828 (while (setq heading (pop path))
15829 (setq re (format org-complex-heading-regexp-format
15830 (regexp-quote heading)))
15831 (setq cnt 0 pos (point))
15832 (while (re-search-forward re end t)
15833 (setq level (- (match-end 1) (match-beginning 1)))
15834 (if (and (>= level lmin) (<= level lmax))
15835 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15836 (when (= cnt 0) (error "Heading not found on level %d: %s"
15837 lmax heading))
15838 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15839 lmax heading))
15840 (goto-char found)
15841 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15842 (setq end (save-excursion (org-end-of-subtree t t))))
15843 (when (org-at-heading-p)
15844 (point-marker)))))))
15846 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15847 "Find node HEADING in BUFFER.
15848 Return a marker to the heading if it was found, or nil if not.
15849 If POS-ONLY is set, return just the position instead of a marker.
15851 The heading text must match exact, but it may have a TODO keyword,
15852 a priority cookie and tags in the standard locations."
15853 (with-current-buffer (or buffer (current-buffer))
15854 (save-excursion
15855 (save-restriction
15856 (widen)
15857 (goto-char (point-min))
15858 (let (case-fold-search)
15859 (if (re-search-forward
15860 (format org-complex-heading-regexp-format
15861 (regexp-quote heading)) nil t)
15862 (if pos-only
15863 (match-beginning 0)
15864 (move-marker (make-marker) (match-beginning 0)))))))))
15866 (defun org-find-exact-heading-in-directory (heading &optional dir)
15867 "Find Org node headline HEADING in all .org files in directory DIR.
15868 When the target headline is found, return a marker to this location."
15869 (let ((files (directory-files (or dir default-directory)
15870 nil "\\`[^.#].*\\.org\\'"))
15871 file visiting m buffer)
15872 (catch 'found
15873 (while (setq file (pop files))
15874 (message "trying %s" file)
15875 (setq visiting (org-find-base-buffer-visiting file))
15876 (setq buffer (or visiting (find-file-noselect file)))
15877 (setq m (org-find-exact-headline-in-buffer
15878 heading buffer))
15879 (when (and (not m) (not visiting)) (kill-buffer buffer))
15880 (and m (throw 'found m))))))
15882 (defun org-find-entry-with-id (ident)
15883 "Locate the entry that contains the ID property with exact value IDENT.
15884 IDENT can be a string, a symbol or a number, this function will search for
15885 the string representation of it.
15886 Return the position where this entry starts, or nil if there is no such entry."
15887 (interactive "sID: ")
15888 (let ((id (cond
15889 ((stringp ident) ident)
15890 ((symbol-name ident) (symbol-name ident))
15891 ((numberp ident) (number-to-string ident))
15892 (t (error "IDENT %s must be a string, symbol or number" ident))))
15893 (case-fold-search nil))
15894 (save-excursion
15895 (save-restriction
15896 (widen)
15897 (goto-char (point-min))
15898 (when (re-search-forward
15899 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15900 nil t)
15901 (org-back-to-heading t)
15902 (point))))))
15904 ;;;; Timestamps
15906 (defvar org-last-changed-timestamp nil)
15907 (defvar org-last-inserted-timestamp nil
15908 "The last time stamp inserted with `org-insert-time-stamp'.")
15909 (defvar org-time-was-given) ; dynamically scoped parameter
15910 (defvar org-end-time-was-given) ; dynamically scoped parameter
15911 (defvar org-ts-what) ; dynamically scoped parameter
15913 (defun org-time-stamp (arg &optional inactive)
15914 "Prompt for a date/time and insert a time stamp.
15915 If the user specifies a time like HH:MM or if this command is
15916 called with at least one prefix argument, the time stamp contains
15917 the date and the time. Otherwise, only the date is be included.
15919 All parts of a date not specified by the user is filled in from
15920 the current date/time. So if you just press return without
15921 typing anything, the time stamp will represent the current
15922 date/time.
15924 If there is already a timestamp at the cursor, it will be
15925 modified.
15927 With two universal prefix arguments, insert an active timestamp
15928 with the current time without prompting the user."
15929 (interactive "P")
15930 (let* ((ts nil)
15931 (default-time
15932 ;; Default time is either today, or, when entering a range,
15933 ;; the range start.
15934 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15935 (save-excursion
15936 (re-search-backward
15937 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15938 (- (point) 20) t)))
15939 (apply 'encode-time (org-parse-time-string (match-string 1)))
15940 (current-time)))
15941 (default-input (and ts (org-get-compact-tod ts)))
15942 (repeater (save-excursion
15943 (save-match-data
15944 (beginning-of-line)
15945 (when (re-search-forward
15946 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15947 (save-excursion (progn (end-of-line) (point))) t)
15948 (match-string 0)))))
15949 org-time-was-given org-end-time-was-given time)
15950 (cond
15951 ((and (org-at-timestamp-p t)
15952 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15953 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15954 (insert "--")
15955 (setq time (let ((this-command this-command))
15956 (org-read-date arg 'totime nil nil
15957 default-time default-input inactive)))
15958 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15959 ((org-at-timestamp-p t)
15960 (setq time (let ((this-command this-command))
15961 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15962 (when (org-at-timestamp-p t) ; just to get the match data
15963 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15964 (replace-match "")
15965 (setq org-last-changed-timestamp
15966 (org-insert-time-stamp
15967 time (or org-time-was-given arg)
15968 inactive nil nil (list org-end-time-was-given)))
15969 (when repeater (goto-char (1- (point))) (insert " " repeater)
15970 (setq org-last-changed-timestamp
15971 (concat (substring org-last-inserted-timestamp 0 -1)
15972 " " repeater ">"))))
15973 (message "Timestamp updated"))
15974 ((equal arg '(16))
15975 (org-insert-time-stamp (current-time) t))
15977 (setq time (let ((this-command this-command))
15978 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15979 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15980 nil nil (list org-end-time-was-given))))))
15982 ;; FIXME: can we use this for something else, like computing time differences?
15983 (defun org-get-compact-tod (s)
15984 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15985 (let* ((t1 (match-string 1 s))
15986 (h1 (string-to-number (match-string 2 s)))
15987 (m1 (string-to-number (match-string 3 s)))
15988 (t2 (and (match-end 4) (match-string 5 s)))
15989 (h2 (and t2 (string-to-number (match-string 6 s))))
15990 (m2 (and t2 (string-to-number (match-string 7 s))))
15991 dh dm)
15992 (if (not t2)
15994 (setq dh (- h2 h1) dm (- m2 m1))
15995 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15996 (concat t1 "+" (number-to-string dh)
15997 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15999 (defun org-time-stamp-inactive (&optional arg)
16000 "Insert an inactive time stamp.
16001 An inactive time stamp is enclosed in square brackets instead of angle
16002 brackets. It is inactive in the sense that it does not trigger agenda entries,
16003 does not link to the calendar and cannot be changed with the S-cursor keys.
16004 So these are more for recording a certain time/date."
16005 (interactive "P")
16006 (org-time-stamp arg 'inactive))
16008 (defvar org-date-ovl (make-overlay 1 1))
16009 (overlay-put org-date-ovl 'face 'org-date-selected)
16010 (org-detach-overlay org-date-ovl)
16012 (defvar org-ans1) ; dynamically scoped parameter
16013 (defvar org-ans2) ; dynamically scoped parameter
16015 (defvar org-plain-time-of-day-regexp) ; defined below
16017 (defvar org-overriding-default-time nil) ; dynamically scoped
16018 (defvar org-read-date-overlay nil)
16019 (defvar org-dcst nil) ; dynamically scoped
16020 (defvar org-read-date-history nil)
16021 (defvar org-read-date-final-answer nil)
16022 (defvar org-read-date-analyze-futurep nil)
16023 (defvar org-read-date-analyze-forced-year nil)
16024 (defvar org-read-date-inactive)
16026 (defvar org-read-date-minibuffer-local-map
16027 (let ((map (make-sparse-keymap)))
16028 (set-keymap-parent map minibuffer-local-map)
16029 (org-defkey map (kbd ".")
16030 (lambda () (interactive)
16031 (org-eval-in-calendar '(calendar-goto-today))))
16032 (org-defkey map [(meta shift left)]
16033 (lambda () (interactive)
16034 (org-eval-in-calendar '(calendar-backward-month 1))))
16035 (org-defkey map [(meta shift right)]
16036 (lambda () (interactive)
16037 (org-eval-in-calendar '(calendar-forward-month 1))))
16038 (org-defkey map [(meta shift up)]
16039 (lambda () (interactive)
16040 (org-eval-in-calendar '(calendar-backward-year 1))))
16041 (org-defkey map [(meta shift down)]
16042 (lambda () (interactive)
16043 (org-eval-in-calendar '(calendar-forward-year 1))))
16044 (org-defkey map [?\e (shift left)]
16045 (lambda () (interactive)
16046 (org-eval-in-calendar '(calendar-backward-month 1))))
16047 (org-defkey map [?\e (shift right)]
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(calendar-forward-month 1))))
16050 (org-defkey map [?\e (shift up)]
16051 (lambda () (interactive)
16052 (org-eval-in-calendar '(calendar-backward-year 1))))
16053 (org-defkey map [?\e (shift down)]
16054 (lambda () (interactive)
16055 (org-eval-in-calendar '(calendar-forward-year 1))))
16056 (org-defkey map [(shift up)]
16057 (lambda () (interactive)
16058 (org-eval-in-calendar '(calendar-backward-week 1))))
16059 (org-defkey map [(shift down)]
16060 (lambda () (interactive)
16061 (org-eval-in-calendar '(calendar-forward-week 1))))
16062 (org-defkey map [(shift left)]
16063 (lambda () (interactive)
16064 (org-eval-in-calendar '(calendar-backward-day 1))))
16065 (org-defkey map [(shift right)]
16066 (lambda () (interactive)
16067 (org-eval-in-calendar '(calendar-forward-day 1))))
16068 (org-defkey map "!"
16069 (lambda () (interactive)
16070 (org-eval-in-calendar '(diary-view-entries))
16071 (message "")))
16072 (org-defkey map ">"
16073 (lambda () (interactive)
16074 (org-eval-in-calendar '(scroll-calendar-left 1))))
16075 (org-defkey map "<"
16076 (lambda () (interactive)
16077 (org-eval-in-calendar '(scroll-calendar-right 1))))
16078 (org-defkey map "\C-v"
16079 (lambda () (interactive)
16080 (org-eval-in-calendar
16081 '(calendar-scroll-left-three-months 1))))
16082 (org-defkey map "\M-v"
16083 (lambda () (interactive)
16084 (org-eval-in-calendar
16085 '(calendar-scroll-right-three-months 1))))
16086 map)
16087 "Keymap for minibuffer commands when using `org-read-date'.")
16089 (defun org-read-date (&optional org-with-time to-time from-string prompt
16090 default-time default-input inactive)
16091 "Read a date, possibly a time, and make things smooth for the user.
16092 The prompt will suggest to enter an ISO date, but you can also enter anything
16093 which will at least partially be understood by `parse-time-string'.
16094 Unrecognized parts of the date will default to the current day, month, year,
16095 hour and minute. If this command is called to replace a timestamp at point,
16096 or to enter the second timestamp of a range, the default time is taken
16097 from the existing stamp. Furthermore, the command prefers the future,
16098 so if you are giving a date where the year is not given, and the day-month
16099 combination is already past in the current year, it will assume you
16100 mean next year. For details, see the manual. A few examples:
16102 3-2-5 --> 2003-02-05
16103 feb 15 --> currentyear-02-15
16104 2/15 --> currentyear-02-15
16105 sep 12 9 --> 2009-09-12
16106 12:45 --> today 12:45
16107 22 sept 0:34 --> currentyear-09-22 0:34
16108 12 --> currentyear-currentmonth-12
16109 Fri --> nearest Friday (today or later)
16110 etc.
16112 Furthermore you can specify a relative date by giving, as the *first* thing
16113 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16114 change in days weeks, months, years.
16115 With a single plus or minus, the date is relative to today. With a double
16116 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16117 +4d --> four days from today
16118 +4 --> same as above
16119 +2w --> two weeks from today
16120 ++5 --> five days from default date
16122 The function understands only English month and weekday abbreviations.
16124 While prompting, a calendar is popped up - you can also select the
16125 date with the mouse (button 1). The calendar shows a period of three
16126 months. To scroll it to other months, use the keys `>' and `<'.
16127 If you don't like the calendar, turn it off with
16128 \(setq org-read-date-popup-calendar nil)
16130 With optional argument TO-TIME, the date will immediately be converted
16131 to an internal time.
16132 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16133 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16134 still enter a time, and this function will inform the calling routine
16135 about this change. The calling routine may then choose to change the
16136 format used to insert the time stamp into the buffer to include the time.
16137 With optional argument FROM-STRING, read from this string instead from
16138 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16139 the time/date that is used for everything that is not specified by the
16140 user."
16141 (require 'parse-time)
16142 (let* ((org-time-stamp-rounding-minutes
16143 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16144 (org-dcst org-display-custom-times)
16145 (ct (org-current-time))
16146 (org-def (or org-overriding-default-time default-time ct))
16147 (org-defdecode (decode-time org-def))
16148 (dummy (progn
16149 (when (< (nth 2 org-defdecode) org-extend-today-until)
16150 (setcar (nthcdr 2 org-defdecode) -1)
16151 (setcar (nthcdr 1 org-defdecode) 59)
16152 (setq org-def (apply 'encode-time org-defdecode)
16153 org-defdecode (decode-time org-def)))))
16154 (mouse-autoselect-window nil) ; Don't let the mouse jump
16155 (calendar-frame-setup nil)
16156 (calendar-setup nil)
16157 (calendar-move-hook nil)
16158 (calendar-view-diary-initially-flag nil)
16159 (calendar-view-holidays-initially-flag nil)
16160 (timestr (format-time-string
16161 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16162 (prompt (concat (if prompt (concat prompt " ") "")
16163 (format "Date+time [%s]: " timestr)))
16164 ans (org-ans0 "") org-ans1 org-ans2 final)
16166 (cond
16167 (from-string (setq ans from-string))
16168 (org-read-date-popup-calendar
16169 (save-excursion
16170 (save-window-excursion
16171 (calendar)
16172 (org-eval-in-calendar '(setq cursor-type nil) t)
16173 (unwind-protect
16174 (progn
16175 (calendar-forward-day (- (time-to-days org-def)
16176 (calendar-absolute-from-gregorian
16177 (calendar-current-date))))
16178 (org-eval-in-calendar nil t)
16179 (let* ((old-map (current-local-map))
16180 (map (copy-keymap calendar-mode-map))
16181 (minibuffer-local-map
16182 (copy-keymap org-read-date-minibuffer-local-map)))
16183 (org-defkey map (kbd "RET") 'org-calendar-select)
16184 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16185 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16186 (unwind-protect
16187 (progn
16188 (use-local-map map)
16189 (setq org-read-date-inactive inactive)
16190 (add-hook 'post-command-hook 'org-read-date-display)
16191 (setq org-ans0 (read-string prompt default-input
16192 'org-read-date-history nil))
16193 ;; org-ans0: from prompt
16194 ;; org-ans1: from mouse click
16195 ;; org-ans2: from calendar motion
16196 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16197 (remove-hook 'post-command-hook 'org-read-date-display)
16198 (use-local-map old-map)
16199 (when org-read-date-overlay
16200 (delete-overlay org-read-date-overlay)
16201 (setq org-read-date-overlay nil)))))
16202 (bury-buffer "*Calendar*")))))
16204 (t ; Naked prompt only
16205 (unwind-protect
16206 (setq ans (read-string prompt default-input
16207 'org-read-date-history timestr))
16208 (when org-read-date-overlay
16209 (delete-overlay org-read-date-overlay)
16210 (setq org-read-date-overlay nil)))))
16212 (setq final (org-read-date-analyze ans org-def org-defdecode))
16214 (when org-read-date-analyze-forced-year
16215 (message "Year was forced into %s"
16216 (if org-read-date-force-compatible-dates
16217 "compatible range (1970-2037)"
16218 "range representable on this machine"))
16219 (ding))
16221 ;; One round trip to get rid of 34th of August and stuff like that....
16222 (setq final (decode-time (apply 'encode-time final)))
16224 (setq org-read-date-final-answer ans)
16226 (if to-time
16227 (apply 'encode-time final)
16228 (if (and (boundp 'org-time-was-given) org-time-was-given)
16229 (format "%04d-%02d-%02d %02d:%02d"
16230 (nth 5 final) (nth 4 final) (nth 3 final)
16231 (nth 2 final) (nth 1 final))
16232 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16234 (defvar org-def)
16235 (defvar org-defdecode)
16236 (defvar org-with-time)
16237 (defun org-read-date-display ()
16238 "Display the current date prompt interpretation in the minibuffer."
16239 (when org-read-date-display-live
16240 (when org-read-date-overlay
16241 (delete-overlay org-read-date-overlay))
16242 (when (minibufferp (current-buffer))
16243 (save-excursion
16244 (end-of-line 1)
16245 (while (not (equal (buffer-substring
16246 (max (point-min) (- (point) 4)) (point))
16247 " "))
16248 (insert " ")))
16249 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16250 " " (or org-ans1 org-ans2)))
16251 (org-end-time-was-given nil)
16252 (f (org-read-date-analyze ans org-def org-defdecode))
16253 (fmts (if org-dcst
16254 org-time-stamp-custom-formats
16255 org-time-stamp-formats))
16256 (fmt (if (or org-with-time
16257 (and (boundp 'org-time-was-given) org-time-was-given))
16258 (cdr fmts)
16259 (car fmts)))
16260 (txt (format-time-string fmt (apply 'encode-time f)))
16261 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16262 (txt (concat "=> " txt)))
16263 (when (and org-end-time-was-given
16264 (string-match org-plain-time-of-day-regexp txt))
16265 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16266 org-end-time-was-given
16267 (substring txt (match-end 0)))))
16268 (when org-read-date-analyze-futurep
16269 (setq txt (concat txt " (=>F)")))
16270 (setq org-read-date-overlay
16271 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16272 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16274 (defun org-read-date-analyze (ans org-def org-defdecode)
16275 "Analyze the combined answer of the date prompt."
16276 ;; FIXME: cleanup and comment
16277 (let ((nowdecode (decode-time (current-time)))
16278 delta deltan deltaw deltadef year month day
16279 hour minute second wday pm h2 m2 tl wday1
16280 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16281 (setq org-read-date-analyze-futurep nil
16282 org-read-date-analyze-forced-year nil)
16283 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16284 (setq ans "+0"))
16286 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16287 (setq ans (replace-match "" t t ans)
16288 deltan (car delta)
16289 deltaw (nth 1 delta)
16290 deltadef (nth 2 delta)))
16292 ;; Check if there is an iso week date in there. If yes, store the
16293 ;; info and postpone interpreting it until the rest of the parsing
16294 ;; is done.
16295 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16296 (setq iso-year (if (match-end 1)
16297 (org-small-year-to-year
16298 (string-to-number (match-string 1 ans))))
16299 iso-weekday (if (match-end 3)
16300 (string-to-number (match-string 3 ans)))
16301 iso-week (string-to-number (match-string 2 ans)))
16302 (setq ans (replace-match "" t t ans)))
16304 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16305 (when (string-match
16306 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16307 (setq year (if (match-end 2)
16308 (string-to-number (match-string 2 ans))
16309 (progn (setq kill-year t)
16310 (string-to-number (format-time-string "%Y"))))
16311 month (string-to-number (match-string 3 ans))
16312 day (string-to-number (match-string 4 ans)))
16313 (if (< year 100) (setq year (+ 2000 year)))
16314 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16315 t nil ans)))
16317 ;; Help matching dotted european dates
16318 (when (string-match
16319 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16320 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16321 (setq kill-year t)
16322 (string-to-number (format-time-string "%Y")))
16323 day (string-to-number (match-string 1 ans))
16324 month (string-to-number (match-string 2 ans))
16325 ans (replace-match (format "%04d-%02d-%02d" year month day)
16326 t nil ans)))
16328 ;; Help matching american dates, like 5/30 or 5/30/7
16329 (when (string-match
16330 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16331 (setq year (if (match-end 4)
16332 (string-to-number (match-string 4 ans))
16333 (progn (setq kill-year t)
16334 (string-to-number (format-time-string "%Y"))))
16335 month (string-to-number (match-string 1 ans))
16336 day (string-to-number (match-string 2 ans)))
16337 (if (< year 100) (setq year (+ 2000 year)))
16338 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16339 t nil ans)))
16340 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16341 ;; If there is a time with am/pm, and *no* time without it, we convert
16342 ;; so that matching will be successful.
16343 (loop for i from 1 to 2 do ; twice, for end time as well
16344 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16345 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16346 (setq hour (string-to-number (match-string 1 ans))
16347 minute (if (match-end 3)
16348 (string-to-number (match-string 3 ans))
16350 pm (equal ?p
16351 (string-to-char (downcase (match-string 4 ans)))))
16352 (if (and (= hour 12) (not pm))
16353 (setq hour 0)
16354 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16355 (setq ans (replace-match (format "%02d:%02d" hour minute)
16356 t t ans))))
16358 ;; Check if a time range is given as a duration
16359 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16360 (setq hour (string-to-number (match-string 1 ans))
16361 h2 (+ hour (string-to-number (match-string 3 ans)))
16362 minute (string-to-number (match-string 2 ans))
16363 m2 (+ minute (if (match-end 5) (string-to-number
16364 (match-string 5 ans))0)))
16365 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16366 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16367 t t ans)))
16369 ;; Check if there is a time range
16370 (when (boundp 'org-end-time-was-given)
16371 (setq org-time-was-given nil)
16372 (when (and (string-match org-plain-time-of-day-regexp ans)
16373 (match-end 8))
16374 (setq org-end-time-was-given (match-string 8 ans))
16375 (setq ans (concat (substring ans 0 (match-beginning 7))
16376 (substring ans (match-end 7))))))
16378 (setq tl (parse-time-string ans)
16379 day (or (nth 3 tl) (nth 3 org-defdecode))
16380 month (or (nth 4 tl)
16381 (if (and org-read-date-prefer-future
16382 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16383 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16384 (nth 4 org-defdecode)))
16385 year (or (and (not kill-year) (nth 5 tl))
16386 (if (and org-read-date-prefer-future
16387 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16388 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16389 (nth 5 org-defdecode)))
16390 hour (or (nth 2 tl) (nth 2 org-defdecode))
16391 minute (or (nth 1 tl) (nth 1 org-defdecode))
16392 second (or (nth 0 tl) 0)
16393 wday (nth 6 tl))
16395 (when (and (eq org-read-date-prefer-future 'time)
16396 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16397 (equal day (nth 3 nowdecode))
16398 (equal month (nth 4 nowdecode))
16399 (equal year (nth 5 nowdecode))
16400 (nth 2 tl)
16401 (or (< (nth 2 tl) (nth 2 nowdecode))
16402 (and (= (nth 2 tl) (nth 2 nowdecode))
16403 (nth 1 tl)
16404 (< (nth 1 tl) (nth 1 nowdecode)))))
16405 (setq day (1+ day)
16406 futurep t))
16408 ;; Special date definitions below
16409 (cond
16410 (iso-week
16411 ;; There was an iso week
16412 (require 'cal-iso)
16413 (setq futurep nil)
16414 (setq year (or iso-year year)
16415 day (or iso-weekday wday 1)
16416 wday nil ; to make sure that the trigger below does not match
16417 iso-date (calendar-gregorian-from-absolute
16418 (calendar-absolute-from-iso
16419 (list iso-week day year))))
16420 ; FIXME: Should we also push ISO weeks into the future?
16421 ; (when (and org-read-date-prefer-future
16422 ; (not iso-year)
16423 ; (< (calendar-absolute-from-gregorian iso-date)
16424 ; (time-to-days (current-time))))
16425 ; (setq year (1+ year)
16426 ; iso-date (calendar-gregorian-from-absolute
16427 ; (calendar-absolute-from-iso
16428 ; (list iso-week day year)))))
16429 (setq month (car iso-date)
16430 year (nth 2 iso-date)
16431 day (nth 1 iso-date)))
16432 (deltan
16433 (setq futurep nil)
16434 (unless deltadef
16435 (let ((now (decode-time (current-time))))
16436 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16437 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16438 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16439 ((equal deltaw "m") (setq month (+ month deltan)))
16440 ((equal deltaw "y") (setq year (+ year deltan)))))
16441 ((and wday (not (nth 3 tl)))
16442 ;; Weekday was given, but no day, so pick that day in the week
16443 ;; on or after the derived date.
16444 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16445 (unless (equal wday wday1)
16446 (setq day (+ day (% (- wday wday1 -7) 7))))))
16447 (if (and (boundp 'org-time-was-given)
16448 (nth 2 tl))
16449 (setq org-time-was-given t))
16450 (if (< year 100) (setq year (+ 2000 year)))
16451 ;; Check of the date is representable
16452 (if org-read-date-force-compatible-dates
16453 (progn
16454 (if (< year 1970)
16455 (setq year 1970 org-read-date-analyze-forced-year t))
16456 (if (> year 2037)
16457 (setq year 2037 org-read-date-analyze-forced-year t)))
16458 (condition-case nil
16459 (ignore (encode-time second minute hour day month year))
16460 (error
16461 (setq year (nth 5 org-defdecode))
16462 (setq org-read-date-analyze-forced-year t))))
16463 (setq org-read-date-analyze-futurep futurep)
16464 (list second minute hour day month year)))
16466 (defvar parse-time-weekdays)
16467 (defun org-read-date-get-relative (s today default)
16468 "Check string S for special relative date string.
16469 TODAY and DEFAULT are internal times, for today and for a default.
16470 Return shift list (N what def-flag)
16471 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16472 N is the number of WHATs to shift.
16473 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16474 the DEFAULT date rather than TODAY."
16475 (require 'parse-time)
16476 (when (and
16477 (string-match
16478 (concat
16479 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16480 "\\([0-9]+\\)?"
16481 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16482 "\\([ \t]\\|$\\)") s)
16483 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16484 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16485 (string-to-char (substring (match-string 1 s) -1))
16486 ?+))
16487 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16488 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16489 (what (if (match-end 3) (match-string 3 s) "d"))
16490 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16491 (date (if rel default today))
16492 (wday (nth 6 (decode-time date)))
16493 delta)
16494 (if wday1
16495 (progn
16496 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16497 (if (= dir ?-) (setq delta (- delta 7)))
16498 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16499 (list delta "d" rel))
16500 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16502 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16503 "Turn a user-specified date into the internal representation.
16504 The internal representation needed by the calendar is (month day year).
16505 This is a wrapper to handle the brain-dead convention in calendar that
16506 user function argument order change dependent on argument order."
16507 (if (boundp 'calendar-date-style)
16508 (cond
16509 ((eq calendar-date-style 'american)
16510 (list arg1 arg2 arg3))
16511 ((eq calendar-date-style 'european)
16512 (list arg2 arg1 arg3))
16513 ((eq calendar-date-style 'iso)
16514 (list arg2 arg3 arg1)))
16515 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16516 (if (org-bound-and-true-p european-calendar-style)
16517 (list arg2 arg1 arg3)
16518 (list arg1 arg2 arg3)))))
16520 (defun org-eval-in-calendar (form &optional keepdate)
16521 "Eval FORM in the calendar window and return to current window.
16522 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16523 otherwise stick to the current value of `org-ans2'."
16524 (let ((sf (selected-frame))
16525 (sw (selected-window)))
16526 (select-window (get-buffer-window "*Calendar*" t))
16527 (eval form)
16528 (when (and (not keepdate) (calendar-cursor-to-date))
16529 (let* ((date (calendar-cursor-to-date))
16530 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16531 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16532 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16533 (select-window sw)
16534 (org-select-frame-set-input-focus sf)))
16536 (defun org-calendar-select ()
16537 "Return to `org-read-date' with the date currently selected.
16538 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16539 (interactive)
16540 (when (calendar-cursor-to-date)
16541 (let* ((date (calendar-cursor-to-date))
16542 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16543 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16544 (if (active-minibuffer-window) (exit-minibuffer))))
16546 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16547 "Insert a date stamp for the date given by the internal TIME.
16548 WITH-HM means use the stamp format that includes the time of the day.
16549 INACTIVE means use square brackets instead of angular ones, so that the
16550 stamp will not contribute to the agenda.
16551 PRE and POST are optional strings to be inserted before and after the
16552 stamp.
16553 The command returns the inserted time stamp."
16554 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16555 stamp)
16556 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16557 (insert-before-markers (or pre ""))
16558 (when (listp extra)
16559 (setq extra (car extra))
16560 (if (and (stringp extra)
16561 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16562 (setq extra (format "-%02d:%02d"
16563 (string-to-number (match-string 1 extra))
16564 (string-to-number (match-string 2 extra))))
16565 (setq extra nil)))
16566 (when extra
16567 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16568 (insert-before-markers (setq stamp (format-time-string fmt time)))
16569 (insert-before-markers (or post ""))
16570 (setq org-last-inserted-timestamp stamp)))
16572 (defun org-toggle-time-stamp-overlays ()
16573 "Toggle the use of custom time stamp formats."
16574 (interactive)
16575 (setq org-display-custom-times (not org-display-custom-times))
16576 (unless org-display-custom-times
16577 (let ((p (point-min)) (bmp (buffer-modified-p)))
16578 (while (setq p (next-single-property-change p 'display))
16579 (if (and (get-text-property p 'display)
16580 (eq (get-text-property p 'face) 'org-date))
16581 (remove-text-properties
16582 p (setq p (next-single-property-change p 'display))
16583 '(display t))))
16584 (set-buffer-modified-p bmp)))
16585 (if (featurep 'xemacs)
16586 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16587 (org-restart-font-lock)
16588 (setq org-table-may-need-update t)
16589 (if org-display-custom-times
16590 (message "Time stamps are overlaid with custom format")
16591 (message "Time stamp overlays removed")))
16593 (defun org-display-custom-time (beg end)
16594 "Overlay modified time stamp format over timestamp between BEG and END."
16595 (let* ((ts (buffer-substring beg end))
16596 t1 w1 with-hm tf time str w2 (off 0))
16597 (save-match-data
16598 (setq t1 (org-parse-time-string ts t))
16599 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16600 (setq off (- (match-end 0) (match-beginning 0)))))
16601 (setq end (- end off))
16602 (setq w1 (- end beg)
16603 with-hm (and (nth 1 t1) (nth 2 t1))
16604 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16605 time (org-fix-decoded-time t1)
16606 str (org-add-props
16607 (format-time-string
16608 (substring tf 1 -1) (apply 'encode-time time))
16609 nil 'mouse-face 'highlight)
16610 w2 (length str))
16611 (if (not (= w2 w1))
16612 (add-text-properties (1+ beg) (+ 2 beg)
16613 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16614 (if (featurep 'xemacs)
16615 (progn
16616 (put-text-property beg end 'invisible t)
16617 (put-text-property beg end 'end-glyph (make-glyph str)))
16618 (put-text-property beg end 'display str))))
16620 (defun org-translate-time (string)
16621 "Translate all timestamps in STRING to custom format.
16622 But do this only if the variable `org-display-custom-times' is set."
16623 (when org-display-custom-times
16624 (save-match-data
16625 (let* ((start 0)
16626 (re org-ts-regexp-both)
16627 t1 with-hm inactive tf time str beg end)
16628 (while (setq start (string-match re string start))
16629 (setq beg (match-beginning 0)
16630 end (match-end 0)
16631 t1 (save-match-data
16632 (org-parse-time-string (substring string beg end) t))
16633 with-hm (and (nth 1 t1) (nth 2 t1))
16634 inactive (equal (substring string beg (1+ beg)) "[")
16635 tf (funcall (if with-hm 'cdr 'car)
16636 org-time-stamp-custom-formats)
16637 time (org-fix-decoded-time t1)
16638 str (format-time-string
16639 (concat
16640 (if inactive "[" "<") (substring tf 1 -1)
16641 (if inactive "]" ">"))
16642 (apply 'encode-time time))
16643 string (replace-match str t t string)
16644 start (+ start (length str)))))))
16645 string)
16647 (defun org-fix-decoded-time (time)
16648 "Set 0 instead of nil for the first 6 elements of time.
16649 Don't touch the rest."
16650 (let ((n 0))
16651 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16653 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16655 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16656 "Difference between TIMESTAMP-STRING and now in days.
16657 If SECONDS is non-nil, return the difference in seconds."
16658 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16659 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16660 (funcall fdiff (current-time)))))
16662 (defun org-deadline-close (timestamp-string &optional ndays)
16663 "Is the time in TIMESTAMP-STRING close to the current date?"
16664 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16665 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16666 (not (org-entry-is-done-p))))
16668 (defun org-get-wdays (ts &optional delay zero-delay)
16669 "Get the deadline lead time appropriate for timestring TS.
16670 When DELAY is non-nil, get the delay time for scheduled items
16671 instead of the deadline lead time. When ZERO-DELAY is non-nil
16672 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16673 don't try to find the delay cookie in the scheduled timestamp."
16674 (let ((tv (if delay org-scheduled-delay-days
16675 org-deadline-warning-days)))
16676 (cond
16677 ((or (and delay (< tv 0))
16678 (and delay zero-delay (<= tv 0))
16679 (and (not delay) (<= tv 0)))
16680 ;; Enforce this value no matter what
16681 (- tv))
16682 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16683 ;; lead time is specified.
16684 (floor (* (string-to-number (match-string 1 ts))
16685 (cdr (assoc (match-string 2 ts)
16686 '(("d" . 1) ("w" . 7)
16687 ("m" . 30.4) ("y" . 365.25)
16688 ("h" . 0.041667)))))))
16689 ;; go for the default.
16690 (t tv))))
16692 (defun org-calendar-select-mouse (ev)
16693 "Return to `org-read-date' with the date currently selected.
16694 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16695 (interactive "e")
16696 (mouse-set-point ev)
16697 (when (calendar-cursor-to-date)
16698 (let* ((date (calendar-cursor-to-date))
16699 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16700 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16701 (if (active-minibuffer-window) (exit-minibuffer))))
16703 (defun org-check-deadlines (ndays)
16704 "Check if there are any deadlines due or past due.
16705 A deadline is considered due if it happens within `org-deadline-warning-days'
16706 days from today's date. If the deadline appears in an entry marked DONE,
16707 it is not shown. The prefix arg NDAYS can be used to test that many
16708 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16709 (interactive "P")
16710 (let* ((org-warn-days
16711 (cond
16712 ((equal ndays '(4)) 100000)
16713 (ndays (prefix-numeric-value ndays))
16714 (t (abs org-deadline-warning-days))))
16715 (case-fold-search nil)
16716 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16717 (callback
16718 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16720 (message "%d deadlines past-due or due within %d days"
16721 (org-occur regexp nil callback)
16722 org-warn-days)))
16724 (defsubst org-re-timestamp (type)
16725 "Return a regexp for timestamp TYPE.
16726 Allowed values for TYPE are:
16728 all: all timestamps
16729 active: only active timestamps (<...>)
16730 inactive: only inactive timestamps ([...])
16731 scheduled: only scheduled timestamps
16732 deadline: only deadline timestamps
16733 closed: only closed time-stamps
16735 When TYPE is nil, fall back on returning a regexp that matches
16736 both scheduled and deadline timestamps."
16737 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16738 ((eq type 'active) org-ts-regexp)
16739 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16740 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16741 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16742 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16743 ((eq type 'scheduled-or-deadline)
16744 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16746 (defun org-check-before-date (date)
16747 "Check if there are deadlines or scheduled entries before DATE."
16748 (interactive (list (org-read-date)))
16749 (let ((case-fold-search nil)
16750 (regexp (org-re-timestamp org-ts-type))
16751 (callback
16752 (lambda () (time-less-p
16753 (org-time-string-to-time (match-string 1))
16754 (org-time-string-to-time date)))))
16755 (message "%d entries before %s"
16756 (org-occur regexp nil callback) date)))
16758 (defun org-check-after-date (date)
16759 "Check if there are deadlines or scheduled entries after DATE."
16760 (interactive (list (org-read-date)))
16761 (let ((case-fold-search nil)
16762 (regexp (org-re-timestamp org-ts-type))
16763 (callback
16764 (lambda () (not
16765 (time-less-p
16766 (org-time-string-to-time (match-string 1))
16767 (org-time-string-to-time date))))))
16768 (message "%d entries after %s"
16769 (org-occur regexp nil callback) date)))
16771 (defun org-check-dates-range (start-date end-date)
16772 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16773 (interactive (list (org-read-date nil nil nil "Range starts")
16774 (org-read-date nil nil nil "Range end")))
16775 (let ((case-fold-search nil)
16776 (regexp (org-re-timestamp org-ts-type))
16777 (callback
16778 (lambda ()
16779 (let ((match (match-string 1)))
16780 (and
16781 (not (time-less-p
16782 (org-time-string-to-time match)
16783 (org-time-string-to-time start-date)))
16784 (time-less-p
16785 (org-time-string-to-time match)
16786 (org-time-string-to-time end-date)))))))
16787 (message "%d entries between %s and %s"
16788 (org-occur regexp nil callback) start-date end-date)))
16790 (defun org-evaluate-time-range (&optional to-buffer)
16791 "Evaluate a time range by computing the difference between start and end.
16792 Normally the result is just printed in the echo area, but with prefix arg
16793 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16794 If the time range is actually in a table, the result is inserted into the
16795 next column.
16796 For time difference computation, a year is assumed to be exactly 365
16797 days in order to avoid rounding problems."
16798 (interactive "P")
16800 (org-clock-update-time-maybe)
16801 (save-excursion
16802 (unless (org-at-date-range-p t)
16803 (goto-char (point-at-bol))
16804 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16805 (if (not (org-at-date-range-p t))
16806 (error "Not at a time-stamp range, and none found in current line")))
16807 (let* ((ts1 (match-string 1))
16808 (ts2 (match-string 2))
16809 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16810 (match-end (match-end 0))
16811 (time1 (org-time-string-to-time ts1))
16812 (time2 (org-time-string-to-time ts2))
16813 (t1 (org-float-time time1))
16814 (t2 (org-float-time time2))
16815 (diff (abs (- t2 t1)))
16816 (negative (< (- t2 t1) 0))
16817 ;; (ys (floor (* 365 24 60 60)))
16818 (ds (* 24 60 60))
16819 (hs (* 60 60))
16820 (fy "%dy %dd %02d:%02d")
16821 (fy1 "%dy %dd")
16822 (fd "%dd %02d:%02d")
16823 (fd1 "%dd")
16824 (fh "%02d:%02d")
16825 y d h m align)
16826 (if havetime
16827 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16829 d (floor (/ diff ds)) diff (mod diff ds)
16830 h (floor (/ diff hs)) diff (mod diff hs)
16831 m (floor (/ diff 60)))
16832 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16834 d (floor (+ (/ diff ds) 0.5))
16835 h 0 m 0))
16836 (if (not to-buffer)
16837 (message "%s" (org-make-tdiff-string y d h m))
16838 (if (org-at-table-p)
16839 (progn
16840 (goto-char match-end)
16841 (setq align t)
16842 (and (looking-at " *|") (goto-char (match-end 0))))
16843 (goto-char match-end))
16844 (if (looking-at
16845 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16846 (replace-match ""))
16847 (if negative (insert " -"))
16848 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16849 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16850 (insert " " (format fh h m))))
16851 (if align (org-table-align))
16852 (message "Time difference inserted")))))
16854 (defun org-make-tdiff-string (y d h m)
16855 (let ((fmt "")
16856 (l nil))
16857 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16858 l (push y l)))
16859 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16860 l (push d l)))
16861 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16862 l (push h l)))
16863 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16864 l (push m l)))
16865 (apply 'format fmt (nreverse l))))
16867 (defun org-time-string-to-time (s &optional buffer pos)
16868 "Convert a timestamp string into internal time."
16869 (condition-case errdata
16870 (apply 'encode-time (org-parse-time-string s))
16871 (error (error "Bad timestamp `%s'%s\nError was: %s"
16872 s (if (not (and buffer pos))
16874 (format " at %d in buffer `%s'" pos buffer))
16875 (cdr errdata)))))
16877 (defun org-time-string-to-seconds (s)
16878 "Convert a timestamp string to a number of seconds."
16879 (org-float-time (org-time-string-to-time s)))
16881 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16882 "Convert a time stamp to an absolute day number.
16883 If there is a specifier for a cyclic time stamp, get the closest
16884 date to DAYNR.
16885 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16886 The variable `date' is bound by the calendar when this is called."
16887 (cond
16888 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16889 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16890 daynr
16891 (+ daynr 1000)))
16892 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16893 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16894 (time-to-days (current-time))) (match-string 0 s)
16895 prefer show-all))
16896 (t (time-to-days
16897 (condition-case errdata
16898 (apply 'encode-time (org-parse-time-string s))
16899 (error (error "Bad timestamp `%s'%s\nError was: %s"
16900 s (if (not (and buffer pos))
16902 (format " at %d in buffer `%s'" pos buffer))
16903 (cdr errdata))))))))
16905 (defun org-days-to-iso-week (days)
16906 "Return the iso week number."
16907 (require 'cal-iso)
16908 (car (calendar-iso-from-absolute days)))
16910 (defun org-small-year-to-year (year)
16911 "Convert 2-digit years into 4-digit years.
16912 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16913 The year 2000 cannot be abbreviated. Any year larger than 99
16914 is returned unchanged."
16915 (if (< year 38)
16916 (setq year (+ 2000 year))
16917 (if (< year 100)
16918 (setq year (+ 1900 year))))
16919 year)
16921 (defun org-time-from-absolute (d)
16922 "Return the time corresponding to date D.
16923 D may be an absolute day number, or a calendar-type list (month day year)."
16924 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16925 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16927 (defun org-calendar-holiday ()
16928 "List of holidays, for Diary display in Org-mode."
16929 (require 'holidays)
16930 (let ((hl (funcall
16931 (if (fboundp 'calendar-check-holidays)
16932 'calendar-check-holidays 'check-calendar-holidays) date)))
16933 (if hl (mapconcat 'identity hl "; "))))
16935 (defun org-diary-sexp-entry (sexp entry date)
16936 "Process a SEXP diary ENTRY for DATE."
16937 (require 'diary-lib)
16938 (let ((result (if calendar-debug-sexp
16939 (let ((stack-trace-on-error t))
16940 (eval (car (read-from-string sexp))))
16941 (condition-case nil
16942 (eval (car (read-from-string sexp)))
16943 (error
16944 (beep)
16945 (message "Bad sexp at line %d in %s: %s"
16946 (org-current-line)
16947 (buffer-file-name) sexp)
16948 (sleep-for 2))))))
16949 (cond ((stringp result) (split-string result "; "))
16950 ((and (consp result)
16951 (not (consp (cdr result)))
16952 (stringp (cdr result))) (cdr result))
16953 ((and (consp result)
16954 (stringp (car result))) result)
16955 (result entry))))
16957 (defun org-diary-to-ical-string (frombuf)
16958 "Get iCalendar entries from diary entries in buffer FROMBUF.
16959 This uses the icalendar.el library."
16960 (let* ((tmpdir (if (featurep 'xemacs)
16961 (temp-directory)
16962 temporary-file-directory))
16963 (tmpfile (make-temp-name
16964 (expand-file-name "orgics" tmpdir)))
16965 buf rtn b e)
16966 (with-current-buffer frombuf
16967 (icalendar-export-region (point-min) (point-max) tmpfile)
16968 (setq buf (find-buffer-visiting tmpfile))
16969 (set-buffer buf)
16970 (goto-char (point-min))
16971 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16972 (setq b (match-beginning 0)))
16973 (goto-char (point-max))
16974 (if (re-search-backward "^END:VEVENT" nil t)
16975 (setq e (match-end 0)))
16976 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16977 (kill-buffer buf)
16978 (delete-file tmpfile)
16979 rtn))
16981 (defun org-closest-date (start current change prefer show-all)
16982 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16983 When PREFER is `past', return a date that is either CURRENT or past.
16984 When PREFER is `future', return a date that is either CURRENT or future.
16985 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16986 ;; Make the proper lists from the dates
16987 (catch 'exit
16988 (let ((a1 '(("h" . hour)
16989 ("d" . day)
16990 ("w" . week)
16991 ("m" . month)
16992 ("y" . year)))
16993 (shour (nth 2 (org-parse-time-string start)))
16994 dn dw sday cday n1 n2 n0
16995 d m y y1 y2 date1 date2 nmonths nm ny m2)
16997 (setq start (org-date-to-gregorian start)
16998 current (org-date-to-gregorian
16999 (if show-all
17000 current
17001 (time-to-days (current-time))))
17002 sday (calendar-absolute-from-gregorian start)
17003 cday (calendar-absolute-from-gregorian current))
17005 (if (<= cday sday) (throw 'exit sday))
17007 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17008 (setq dn (string-to-number (match-string 1 change))
17009 dw (cdr (assoc (match-string 2 change) a1)))
17010 (error "Invalid change specifier: %s" change))
17011 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17012 (cond
17013 ((eq dw 'hour)
17014 (let ((missing-hours
17015 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17016 dn)))
17017 (setq n1 (if (zerop missing-hours) cday
17018 (- cday (1+ (floor (/ missing-hours 24)))))
17019 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17020 ((eq dw 'day)
17021 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17022 n2 (+ n1 dn)))
17023 ((eq dw 'year)
17024 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17025 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17026 (setq date1 (list m d y1)
17027 n1 (calendar-absolute-from-gregorian date1)
17028 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17029 n2 (calendar-absolute-from-gregorian date2)))
17030 ((eq dw 'month)
17031 ;; approx number of month between the two dates
17032 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17033 ;; How often does dn fit in there?
17034 (setq d (nth 1 start) m (car start) y (nth 2 start)
17035 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17036 m (+ m nm)
17037 ny (floor (/ m 12))
17038 y (+ y ny)
17039 m (- m (* ny 12)))
17040 (while (> m 12) (setq m (- m 12) y (1+ y)))
17041 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17042 (setq m2 (+ m dn) y2 y)
17043 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17044 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17045 (while (<= n2 cday)
17046 (setq n1 n2 m m2 y y2)
17047 (setq m2 (+ m dn) y2 y)
17048 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17049 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17050 ;; Make sure n1 is the earlier date
17051 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17052 (if show-all
17053 (cond
17054 ((eq prefer 'past) (if (= cday n2) n2 n1))
17055 ((eq prefer 'future) (if (= cday n1) n1 n2))
17056 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17057 (cond
17058 ((eq prefer 'past) (if (= cday n2) n2 n1))
17059 ((eq prefer 'future) (if (= cday n1) n1 n2))
17060 (t (if (= cday n1) n1 n2)))))))
17062 (defun org-date-to-gregorian (date)
17063 "Turn any specification of DATE into a Gregorian date for the calendar."
17064 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17065 ((and (listp date) (= (length date) 3)) date)
17066 ((stringp date)
17067 (setq date (org-parse-time-string date))
17068 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17069 ((listp date)
17070 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17072 (defun org-parse-time-string (s &optional nodefault)
17073 "Parse the standard Org-mode time string.
17074 This should be a lot faster than the normal `parse-time-string'.
17075 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17076 hour and minute fields will be nil if not given."
17077 (cond ((string-match org-ts-regexp0 s)
17078 (list 0
17079 (if (or (match-beginning 8) (not nodefault))
17080 (string-to-number (or (match-string 8 s) "0")))
17081 (if (or (match-beginning 7) (not nodefault))
17082 (string-to-number (or (match-string 7 s) "0")))
17083 (string-to-number (match-string 4 s))
17084 (string-to-number (match-string 3 s))
17085 (string-to-number (match-string 2 s))
17086 nil nil nil))
17087 ((string-match "^<[^>]+>$" s)
17088 (decode-time (seconds-to-time (org-matcher-time s))))
17089 (t (error "Not a standard Org-mode time string: %s" s))))
17091 (defun org-timestamp-up (&optional arg)
17092 "Increase the date item at the cursor by one.
17093 If the cursor is on the year, change the year. If it is on the month,
17094 the day or the time, change that.
17095 With prefix ARG, change by that many units."
17096 (interactive "p")
17097 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17099 (defun org-timestamp-down (&optional arg)
17100 "Decrease the date item at the cursor by one.
17101 If the cursor is on the year, change the year. If it is on the month,
17102 the day or the time, change that.
17103 With prefix ARG, change by that many units."
17104 (interactive "p")
17105 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17107 (defun org-timestamp-up-day (&optional arg)
17108 "Increase the date in the time stamp by one day.
17109 With prefix ARG, change that many days."
17110 (interactive "p")
17111 (if (and (not (org-at-timestamp-p t))
17112 (org-at-heading-p))
17113 (org-todo 'up)
17114 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17116 (defun org-timestamp-down-day (&optional arg)
17117 "Decrease the date in the time stamp by one day.
17118 With prefix ARG, change that many days."
17119 (interactive "p")
17120 (if (and (not (org-at-timestamp-p t))
17121 (org-at-heading-p))
17122 (org-todo 'down)
17123 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17125 (defun org-at-timestamp-p (&optional inactive-ok)
17126 "Determine if the cursor is in or at a timestamp."
17127 (interactive)
17128 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17129 (pos (point))
17130 (ans (or (looking-at tsr)
17131 (save-excursion
17132 (skip-chars-backward "^[<\n\r\t")
17133 (if (> (point) (point-min)) (backward-char 1))
17134 (and (looking-at tsr)
17135 (> (- (match-end 0) pos) -1))))))
17136 (and ans
17137 (boundp 'org-ts-what)
17138 (setq org-ts-what
17139 (cond
17140 ((= pos (match-beginning 0)) 'bracket)
17141 ;; Point is considered to be "on the bracket" whether
17142 ;; it's really on it or right after it.
17143 ((= pos (1- (match-end 0))) 'bracket)
17144 ((= pos (match-end 0)) 'after)
17145 ((org-pos-in-match-range pos 2) 'year)
17146 ((org-pos-in-match-range pos 3) 'month)
17147 ((org-pos-in-match-range pos 7) 'hour)
17148 ((org-pos-in-match-range pos 8) 'minute)
17149 ((or (org-pos-in-match-range pos 4)
17150 (org-pos-in-match-range pos 5)) 'day)
17151 ((and (> pos (or (match-end 8) (match-end 5)))
17152 (< pos (match-end 0)))
17153 (- pos (or (match-end 8) (match-end 5))))
17154 (t 'day))))
17155 ans))
17157 (defun org-toggle-timestamp-type ()
17158 "Toggle the type (<active> or [inactive]) of a time stamp."
17159 (interactive)
17160 (when (org-at-timestamp-p t)
17161 (let ((beg (match-beginning 0)) (end (match-end 0))
17162 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17163 (save-excursion
17164 (goto-char beg)
17165 (while (re-search-forward "[][<>]" end t)
17166 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17167 t t)))
17168 (message "Timestamp is now %sactive"
17169 (if (equal (char-after beg) ?<) "" "in")))))
17171 (defun org-at-clock-log-p nil
17172 "Is the cursor on the clock log line?"
17173 (save-excursion
17174 (move-beginning-of-line 1)
17175 (looking-at "^[ \t]*CLOCK:")))
17177 (defvar org-clock-history) ; defined in org-clock.el
17178 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17179 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17180 "Change the date in the time stamp at point.
17181 The date will be changed by N times WHAT. WHAT can be `day', `month',
17182 `year', `minute', `second'. If WHAT is not given, the cursor position
17183 in the timestamp determines what will be changed.
17184 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17185 (let ((origin (point)) origin-cat
17186 with-hm inactive
17187 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17188 org-ts-what
17189 extra rem
17190 ts time time0 fixnext clrgx)
17191 (if (not (org-at-timestamp-p t))
17192 (error "Not at a timestamp"))
17193 (if (and (not what) (eq org-ts-what 'bracket))
17194 (org-toggle-timestamp-type)
17195 ;; Point isn't on brackets. Remember the part of the time-stamp
17196 ;; the point was in. Indeed, size of time-stamps may change,
17197 ;; but point must be kept in the same category nonetheless.
17198 (setq origin-cat org-ts-what)
17199 (if (and (not what) (not (eq org-ts-what 'day))
17200 org-display-custom-times
17201 (get-text-property (point) 'display)
17202 (not (get-text-property (1- (point)) 'display)))
17203 (setq org-ts-what 'day))
17204 (setq org-ts-what (or what org-ts-what)
17205 inactive (= (char-after (match-beginning 0)) ?\[)
17206 ts (match-string 0))
17207 (replace-match "")
17208 (when (string-match
17209 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17211 (setq extra (match-string 1 ts))
17212 (if suppress-tmp-delay
17213 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17214 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17215 (setq with-hm t))
17216 (setq time0 (org-parse-time-string ts))
17217 (when (and updown
17218 (eq org-ts-what 'minute)
17219 (not current-prefix-arg))
17220 ;; This looks like s-up and s-down. Change by one rounding step.
17221 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17222 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17223 (setcar (cdr time0) (+ (nth 1 time0)
17224 (if (> n 0) (- rem) (- dm rem))))))
17225 (setq time
17226 (encode-time (or (car time0) 0)
17227 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17228 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17229 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17230 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17231 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17232 (nthcdr 6 time0)))
17233 (when (and (member org-ts-what '(hour minute))
17234 extra
17235 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17236 (setq extra (org-modify-ts-extra
17237 extra
17238 (if (eq org-ts-what 'hour) 2 5)
17239 n dm)))
17240 (when (integerp org-ts-what)
17241 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17242 (if (eq what 'calendar)
17243 (let ((cal-date (org-get-date-from-calendar)))
17244 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17245 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17246 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17247 (setcar time0 (or (car time0) 0))
17248 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17249 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17250 (setq time (apply 'encode-time time0))))
17251 ;; Insert the new time-stamp, and ensure point stays in the same
17252 ;; category as before (i.e. not after the last position in that
17253 ;; category).
17254 (let ((pos (point)))
17255 ;; Stay before inserted string. `save-excursion' is of no use.
17256 (setq org-last-changed-timestamp
17257 (org-insert-time-stamp time with-hm inactive nil nil extra))
17258 (goto-char pos))
17259 (save-match-data
17260 (looking-at org-ts-regexp3)
17261 (goto-char (cond
17262 ;; `day' category ends before `hour' if any, or at
17263 ;; the end of the day name.
17264 ((eq origin-cat 'day)
17265 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17266 ((eq origin-cat 'hour) (min (match-end 7) origin))
17267 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17268 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17269 ;; `year' and `month' have both fixed size: point
17270 ;; couldn't have moved into another part.
17271 (t origin))))
17272 ;; Update clock if on a CLOCK line.
17273 (org-clock-update-time-maybe)
17274 ;; Maybe adjust the closest clock in `org-clock-history'
17275 (when org-clock-adjust-closest
17276 (if (not (and (org-at-clock-log-p)
17277 (< 1 (length (delq nil (mapcar 'marker-position
17278 org-clock-history))))))
17279 (message "No clock to adjust")
17280 (cond ((save-excursion ; fix previous clock?
17281 (re-search-backward org-ts-regexp0 nil t)
17282 (org-looking-back (concat org-clock-string " \\[")))
17283 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17284 ((save-excursion ; fix next clock?
17285 (re-search-backward org-ts-regexp0 nil t)
17286 (looking-at (concat org-ts-regexp0 "\\] =>")))
17287 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17288 (save-window-excursion
17289 ;; Find closest clock to point, adjust the previous/next one in history
17290 (let* ((p (save-excursion (org-back-to-heading t)))
17291 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17292 (clfixnth
17293 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17294 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17295 (if (not clfixpos)
17296 (message "No clock to adjust")
17297 (save-excursion
17298 (org-goto-marker-or-bmk clfixpos)
17299 (org-show-subtree)
17300 (when (re-search-forward clrgx nil t)
17301 (goto-char (match-beginning 1))
17302 (let (org-clock-adjust-closest)
17303 (org-timestamp-change n org-ts-what updown))
17304 (message "Clock adjusted in %s for heading: %s"
17305 (file-name-nondirectory (buffer-file-name))
17306 (org-get-heading t t)))))))))
17307 ;; Try to recenter the calendar window, if any.
17308 (if (and org-calendar-follow-timestamp-change
17309 (get-buffer-window "*Calendar*" t)
17310 (memq org-ts-what '(day month year)))
17311 (org-recenter-calendar (time-to-days time))))))
17313 (defun org-modify-ts-extra (s pos n dm)
17314 "Change the different parts of the lead-time and repeat fields in timestamp."
17315 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17316 ng h m new rem)
17317 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17318 (cond
17319 ((or (org-pos-in-match-range pos 2)
17320 (org-pos-in-match-range pos 3))
17321 (setq m (string-to-number (match-string 3 s))
17322 h (string-to-number (match-string 2 s)))
17323 (if (org-pos-in-match-range pos 2)
17324 (setq h (+ h n))
17325 (setq n (* dm (org-no-warnings (signum n))))
17326 (when (not (= 0 (setq rem (% m dm))))
17327 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17328 (setq m (+ m n)))
17329 (if (< m 0) (setq m (+ m 60) h (1- h)))
17330 (if (> m 59) (setq m (- m 60) h (1+ h)))
17331 (setq h (min 24 (max 0 h)))
17332 (setq ng 1 new (format "-%02d:%02d" h m)))
17333 ((org-pos-in-match-range pos 6)
17334 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17335 ((org-pos-in-match-range pos 5)
17336 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17338 ((org-pos-in-match-range pos 9)
17339 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17340 ((org-pos-in-match-range pos 8)
17341 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17343 (when ng
17344 (setq s (concat
17345 (substring s 0 (match-beginning ng))
17347 (substring s (match-end ng))))))
17350 (defun org-recenter-calendar (date)
17351 "If the calendar is visible, recenter it to DATE."
17352 (let ((cwin (get-buffer-window "*Calendar*" t)))
17353 (when cwin
17354 (let ((calendar-move-hook nil))
17355 (with-selected-window cwin
17356 (calendar-goto-date (if (listp date) date
17357 (calendar-gregorian-from-absolute date))))))))
17359 (defun org-goto-calendar (&optional arg)
17360 "Go to the Emacs calendar at the current date.
17361 If there is a time stamp in the current line, go to that date.
17362 A prefix ARG can be used to force the current date."
17363 (interactive "P")
17364 (let ((tsr org-ts-regexp) diff
17365 (calendar-move-hook nil)
17366 (calendar-view-holidays-initially-flag nil)
17367 (calendar-view-diary-initially-flag nil))
17368 (if (or (org-at-timestamp-p)
17369 (save-excursion
17370 (beginning-of-line 1)
17371 (looking-at (concat ".*" tsr))))
17372 (let ((d1 (time-to-days (current-time)))
17373 (d2 (time-to-days
17374 (org-time-string-to-time (match-string 1)))))
17375 (setq diff (- d2 d1))))
17376 (calendar)
17377 (calendar-goto-today)
17378 (if (and diff (not arg)) (calendar-forward-day diff))))
17380 (defun org-get-date-from-calendar ()
17381 "Return a list (month day year) of date at point in calendar."
17382 (with-current-buffer "*Calendar*"
17383 (save-match-data
17384 (calendar-cursor-to-date))))
17386 (defun org-date-from-calendar ()
17387 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17388 If there is already a time stamp at the cursor position, update it."
17389 (interactive)
17390 (if (org-at-timestamp-p t)
17391 (org-timestamp-change 0 'calendar)
17392 (let ((cal-date (org-get-date-from-calendar)))
17393 (org-insert-time-stamp
17394 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17396 (defcustom org-effort-durations
17397 `(("h" . 60)
17398 ("d" . ,(* 60 8))
17399 ("w" . ,(* 60 8 5))
17400 ("m" . ,(* 60 8 5 4))
17401 ("y" . ,(* 60 8 5 40)))
17402 "Conversion factor to minutes for an effort modifier.
17404 Each entry has the form (MODIFIER . MINUTES).
17406 In an effort string, a number followed by MODIFIER is multiplied
17407 by the specified number of MINUTES to obtain an effort in
17408 minutes.
17410 For example, if the value of this variable is ((\"hours\" . 60)), then an
17411 effort string \"2hours\" is equivalent to 120 minutes."
17412 :group 'org-agenda
17413 :version "24.1"
17414 :type '(alist :key-type (string :tag "Modifier")
17415 :value-type (number :tag "Minutes")))
17417 (defun org-minutes-to-clocksum-string (m)
17418 "Format number of minutes as a clocksum string.
17419 The format is determined by `org-time-clocksum-format',
17420 `org-time-clocksum-use-fractional' and
17421 `org-time-clocksum-fractional-format' and
17422 `org-time-clocksum-use-effort-durations'."
17423 (let ((clocksum "") h d w mo y fmt n)
17424 (setq h (if org-time-clocksum-use-effort-durations
17425 (cdr (assoc "h" org-effort-durations)) 60)
17426 d (if org-time-clocksum-use-effort-durations
17427 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17428 w (if org-time-clocksum-use-effort-durations
17429 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17430 mo (if org-time-clocksum-use-effort-durations
17431 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17432 y (if org-time-clocksum-use-effort-durations
17433 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17434 ;; fractional format
17435 (if org-time-clocksum-use-fractional
17436 (cond
17437 ;; single format string
17438 ((stringp org-time-clocksum-fractional-format)
17439 (format org-time-clocksum-fractional-format (/ m (float h))))
17440 ;; choice of fractional formats for different time units
17441 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17442 (> (/ (truncate m) (* y d h)) 0))
17443 (format fmt (/ m (* y d (float h)))))
17444 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17445 (> (/ (truncate m) (* mo d h)) 0))
17446 (format fmt (/ m (* mo d (float h)))))
17447 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17448 (> (/ (truncate m) (* w d h)) 0))
17449 (format fmt (/ m (* w d (float h)))))
17450 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17451 (> (/ (truncate m) (* d h)) 0))
17452 (format fmt (/ m (* d (float h)))))
17453 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17454 (> (/ (truncate m) h) 0))
17455 (format fmt (/ m (float h))))
17456 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17457 (format fmt m))
17458 ;; fall back to smallest time unit with a format
17459 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17460 (format fmt (/ m (float h))))
17461 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17462 (format fmt (/ m (* d (float h)))))
17463 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17464 (format fmt (/ m (* w d (float h)))))
17465 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17466 (format fmt (/ m (* mo d (float h)))))
17467 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17468 (format fmt (/ m (* y d (float h))))))
17469 ;; standard (non-fractional) format, with single format string
17470 (if (stringp org-time-clocksum-format)
17471 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17472 ;; separate formats components
17473 (and (setq fmt (plist-get org-time-clocksum-format :years))
17474 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17475 (plist-get org-time-clocksum-format :require-years))
17476 (setq clocksum (concat clocksum (format fmt n))
17477 m (- m (* n y d h))))
17478 (and (setq fmt (plist-get org-time-clocksum-format :months))
17479 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17480 (plist-get org-time-clocksum-format :require-months))
17481 (setq clocksum (concat clocksum (format fmt n))
17482 m (- m (* n mo d h))))
17483 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17484 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17485 (plist-get org-time-clocksum-format :require-weeks))
17486 (setq clocksum (concat clocksum (format fmt n))
17487 m (- m (* n w d h))))
17488 (and (setq fmt (plist-get org-time-clocksum-format :days))
17489 (or (> (setq n (/ (truncate m) (* d h))) 0)
17490 (plist-get org-time-clocksum-format :require-days))
17491 (setq clocksum (concat clocksum (format fmt n))
17492 m (- m (* n d h))))
17493 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17494 (or (> (setq n (/ (truncate m) h)) 0)
17495 (plist-get org-time-clocksum-format :require-hours))
17496 (setq clocksum (concat clocksum (format fmt n))
17497 m (- m (* n h))))
17498 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17499 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17500 (setq clocksum (concat clocksum (format fmt m))))
17501 ;; return formatted time duration
17502 clocksum))))
17504 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17505 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17506 "Org mode version 8.0")
17508 (defun org-hours-to-clocksum-string (n)
17509 (org-minutes-to-clocksum-string (* n 60)))
17511 (defun org-hh:mm-string-to-minutes (s)
17512 "Convert a string H:MM to a number of minutes.
17513 If the string is just a number, interpret it as minutes.
17514 In fact, the first hh:mm or number in the string will be taken,
17515 there can be extra stuff in the string.
17516 If no number is found, the return value is 0."
17517 (cond
17518 ((integerp s) s)
17519 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17520 (+ (* (string-to-number (match-string 1 s)) 60)
17521 (string-to-number (match-string 2 s))))
17522 ((string-match "\\([0-9]+\\)" s)
17523 (string-to-number (match-string 1 s)))
17524 (t 0)))
17526 (defcustom org-image-actual-width t
17527 "Should we use the actual width of images when inlining them?
17529 When set to `t', always use the image width.
17531 When set to a number, use imagemagick (when available) to set
17532 the image's width to this value.
17534 When set to a number in a list, try to get the width from any
17535 #+ATTR.* keyword if it matches a width specification like
17537 #+ATTR_HTML: :width 300px
17539 and fall back on that number if none is found.
17541 When set to nil, try to get the width from an #+ATTR.* keyword
17542 and fall back on the original width if none is found.
17544 This requires Emacs >= 24.1, build with imagemagick support."
17545 :group 'org-appearance
17546 :version "24.4"
17547 :package-version '(Org . "8.0")
17548 :type '(choice
17549 (const :tag "Use the image width" t)
17550 (integer :tag "Use a number of pixels")
17551 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17552 (const :tag "Use #+ATTR* or don't resize" nil)))
17554 (defcustom org-agenda-inhibit-startup nil
17555 "Inhibit startup when preparing agenda buffers.
17556 When this variable is `t' (the default), the initialization of
17557 the Org agenda buffers is inhibited: e.g. the visibility state
17558 is not set, the tables are not re-aligned, etc."
17559 :type 'boolean
17560 :version "24.3"
17561 :group 'org-agenda)
17563 (defun org-duration-string-to-minutes (s &optional output-to-string)
17564 "Convert a duration string S to minutes.
17566 A bare number is interpreted as minutes, modifiers can be set by
17567 customizing `org-effort-durations' (which see).
17569 Entries containing a colon are interpreted as H:MM by
17570 `org-hh:mm-string-to-minutes'."
17571 (let ((result 0)
17572 (re (concat "\\([0-9.]+\\) *\\("
17573 (regexp-opt (mapcar 'car org-effort-durations))
17574 "\\)")))
17575 (while (string-match re s)
17576 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17577 (string-to-number (match-string 1 s))))
17578 (setq s (replace-match "" nil t s)))
17579 (setq result (floor result))
17580 (incf result (org-hh:mm-string-to-minutes s))
17581 (if output-to-string (number-to-string result) result)))
17583 ;;;; Files
17585 (defun org-save-all-org-buffers ()
17586 "Save all Org-mode buffers without user confirmation."
17587 (interactive)
17588 (message "Saving all Org-mode buffers...")
17589 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17590 (when (featurep 'org-id) (org-id-locations-save))
17591 (message "Saving all Org-mode buffers... done"))
17593 (defun org-revert-all-org-buffers ()
17594 "Revert all Org-mode buffers.
17595 Prompt for confirmation when there are unsaved changes.
17596 Be sure you know what you are doing before letting this function
17597 overwrite your changes.
17599 This function is useful in a setup where one tracks org files
17600 with a version control system, to revert on one machine after pulling
17601 changes from another. I believe the procedure must be like this:
17603 1. M-x org-save-all-org-buffers
17604 2. Pull changes from the other machine, resolve conflicts
17605 3. M-x org-revert-all-org-buffers"
17606 (interactive)
17607 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17608 (error "Abort"))
17609 (save-excursion
17610 (save-window-excursion
17611 (mapc
17612 (lambda (b)
17613 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17614 (with-current-buffer b buffer-file-name))
17615 (org-pop-to-buffer-same-window b)
17616 (revert-buffer t 'no-confirm)))
17617 (buffer-list))
17618 (when (and (featurep 'org-id) org-id-track-globally)
17619 (org-id-locations-load)))))
17621 ;;;; Agenda files
17623 ;;;###autoload
17624 (defun org-switchb (&optional arg)
17625 "Switch between Org buffers.
17626 With one prefix argument, restrict available buffers to files.
17627 With two prefix arguments, restrict available buffers to agenda files.
17629 Defaults to `iswitchb' for buffer name completion.
17630 Set `org-completion-use-ido' to make it use ido instead."
17631 (interactive "P")
17632 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17633 ((equal arg '(16)) (org-buffer-list 'agenda))
17634 (t (org-buffer-list))))
17635 (org-completion-use-iswitchb org-completion-use-iswitchb)
17636 (org-completion-use-ido org-completion-use-ido))
17637 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17638 (setq org-completion-use-iswitchb t))
17639 (org-pop-to-buffer-same-window
17640 (org-icompleting-read "Org buffer: "
17641 (mapcar 'list (mapcar 'buffer-name blist))
17642 nil t))))
17644 ;;; Define some older names previously used for this functionality
17645 ;;;###autoload
17646 (defalias 'org-ido-switchb 'org-switchb)
17647 ;;;###autoload
17648 (defalias 'org-iswitchb 'org-switchb)
17650 (defun org-buffer-list (&optional predicate exclude-tmp)
17651 "Return a list of Org buffers.
17652 PREDICATE can be `export', `files' or `agenda'.
17654 export restrict the list to Export buffers.
17655 files restrict the list to buffers visiting Org files.
17656 agenda restrict the list to buffers visiting agenda files.
17658 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17659 (let* ((bfn nil)
17660 (agenda-files (and (eq predicate 'agenda)
17661 (mapcar 'file-truename (org-agenda-files t))))
17662 (filter
17663 (cond
17664 ((eq predicate 'files)
17665 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17666 ((eq predicate 'export)
17667 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17668 ((eq predicate 'agenda)
17669 (lambda (b)
17670 (with-current-buffer b
17671 (and (derived-mode-p 'org-mode)
17672 (setq bfn (buffer-file-name b))
17673 (member (file-truename bfn) agenda-files)))))
17674 (t (lambda (b) (with-current-buffer b
17675 (or (derived-mode-p 'org-mode)
17676 (string-match "\*Org .*Export"
17677 (buffer-name b)))))))))
17678 (delq nil
17679 (mapcar
17680 (lambda(b)
17681 (if (and (funcall filter b)
17682 (or (not exclude-tmp)
17683 (not (string-match "tmp" (buffer-name b)))))
17685 nil))
17686 (buffer-list)))))
17688 (defun org-agenda-files (&optional unrestricted archives)
17689 "Get the list of agenda files.
17690 Optional UNRESTRICTED means return the full list even if a restriction
17691 is currently in place.
17692 When ARCHIVES is t, include all archive files that are really being
17693 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17694 `org-agenda-archives-mode' is t."
17695 (let ((files
17696 (cond
17697 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17698 ((stringp org-agenda-files) (org-read-agenda-file-list))
17699 ((listp org-agenda-files) org-agenda-files)
17700 (t (error "Invalid value of `org-agenda-files'")))))
17701 (setq files (apply 'append
17702 (mapcar (lambda (f)
17703 (if (file-directory-p f)
17704 (directory-files
17705 f t org-agenda-file-regexp)
17706 (list f)))
17707 files)))
17708 (when org-agenda-skip-unavailable-files
17709 (setq files (delq nil
17710 (mapcar (function
17711 (lambda (file)
17712 (and (file-readable-p file) file)))
17713 files))))
17714 (when (or (eq archives t)
17715 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17716 (setq files (org-add-archive-files files)))
17717 files))
17719 (defun org-agenda-file-p (&optional file)
17720 "Return non-nil, if FILE is an agenda file.
17721 If FILE is omitted, use the file associated with the current
17722 buffer."
17723 (member (or file (buffer-file-name))
17724 (org-agenda-files t)))
17726 (defun org-edit-agenda-file-list ()
17727 "Edit the list of agenda files.
17728 Depending on setup, this either uses customize to edit the variable
17729 `org-agenda-files', or it visits the file that is holding the list. In the
17730 latter case, the buffer is set up in a way that saving it automatically kills
17731 the buffer and restores the previous window configuration."
17732 (interactive)
17733 (if (stringp org-agenda-files)
17734 (let ((cw (current-window-configuration)))
17735 (find-file org-agenda-files)
17736 (org-set-local 'org-window-configuration cw)
17737 (org-add-hook 'after-save-hook
17738 (lambda ()
17739 (set-window-configuration
17740 (prog1 org-window-configuration
17741 (kill-buffer (current-buffer))))
17742 (org-install-agenda-files-menu)
17743 (message "New agenda file list installed"))
17744 nil 'local)
17745 (message "%s" (substitute-command-keys
17746 "Edit list and finish with \\[save-buffer]")))
17747 (customize-variable 'org-agenda-files)))
17749 (defun org-store-new-agenda-file-list (list)
17750 "Set new value for the agenda file list and save it correctly."
17751 (if (stringp org-agenda-files)
17752 (let ((fe (org-read-agenda-file-list t)) b u)
17753 (while (setq b (find-buffer-visiting org-agenda-files))
17754 (kill-buffer b))
17755 (with-temp-file org-agenda-files
17756 (insert
17757 (mapconcat
17758 (lambda (f) ;; Keep un-expanded entries.
17759 (if (setq u (assoc f fe))
17760 (cdr u)
17762 list "\n")
17763 "\n")))
17764 (let ((org-mode-hook nil) (org-inhibit-startup t)
17765 (org-insert-mode-line-in-empty-file nil))
17766 (setq org-agenda-files list)
17767 (customize-save-variable 'org-agenda-files org-agenda-files))))
17769 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17770 "Read the list of agenda files from a file.
17771 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17772 filenames, used by `org-store-new-agenda-file-list' to write back
17773 un-expanded file names."
17774 (when (file-directory-p org-agenda-files)
17775 (error "`org-agenda-files' cannot be a single directory"))
17776 (when (stringp org-agenda-files)
17777 (with-temp-buffer
17778 (insert-file-contents org-agenda-files)
17779 (mapcar
17780 (lambda (f)
17781 (let ((e (expand-file-name (substitute-in-file-name f)
17782 org-directory)))
17783 (if pair-with-expansion
17784 (cons e f)
17785 e)))
17786 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17788 ;;;###autoload
17789 (defun org-cycle-agenda-files ()
17790 "Cycle through the files in `org-agenda-files'.
17791 If the current buffer visits an agenda file, find the next one in the list.
17792 If the current buffer does not, find the first agenda file."
17793 (interactive)
17794 (let* ((fs (org-agenda-files t))
17795 (files (append fs (list (car fs))))
17796 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17797 file)
17798 (unless files (error "No agenda files"))
17799 (catch 'exit
17800 (while (setq file (pop files))
17801 (if (equal (file-truename file) tcf)
17802 (when (car files)
17803 (find-file (car files))
17804 (throw 'exit t))))
17805 (find-file (car fs)))
17806 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17808 (defun org-agenda-file-to-front (&optional to-end)
17809 "Move/add the current file to the top of the agenda file list.
17810 If the file is not present in the list, it is added to the front. If it is
17811 present, it is moved there. With optional argument TO-END, add/move to the
17812 end of the list."
17813 (interactive "P")
17814 (let ((org-agenda-skip-unavailable-files nil)
17815 (file-alist (mapcar (lambda (x)
17816 (cons (file-truename x) x))
17817 (org-agenda-files t)))
17818 (ctf (file-truename
17819 (or buffer-file-name
17820 (error "Please save the current buffer to a file"))))
17821 x had)
17822 (setq x (assoc ctf file-alist) had x)
17824 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17825 (if to-end
17826 (setq file-alist (append (delq x file-alist) (list x)))
17827 (setq file-alist (cons x (delq x file-alist))))
17828 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17829 (org-install-agenda-files-menu)
17830 (message "File %s to %s of agenda file list"
17831 (if had "moved" "added") (if to-end "end" "front"))))
17833 (defun org-remove-file (&optional file)
17834 "Remove current file from the list of files in variable `org-agenda-files'.
17835 These are the files which are being checked for agenda entries.
17836 Optional argument FILE means use this file instead of the current."
17837 (interactive)
17838 (let* ((org-agenda-skip-unavailable-files nil)
17839 (file (or file buffer-file-name
17840 (error "Current buffer does not visit a file")))
17841 (true-file (file-truename file))
17842 (afile (abbreviate-file-name file))
17843 (files (delq nil (mapcar
17844 (lambda (x)
17845 (if (equal true-file
17846 (file-truename x))
17847 nil x))
17848 (org-agenda-files t)))))
17849 (if (not (= (length files) (length (org-agenda-files t))))
17850 (progn
17851 (org-store-new-agenda-file-list files)
17852 (org-install-agenda-files-menu)
17853 (message "Removed file: %s" afile))
17854 (message "File was not in list: %s (not removed)" afile))))
17856 (defun org-file-menu-entry (file)
17857 (vector file (list 'find-file file) t))
17859 (defun org-check-agenda-file (file)
17860 "Make sure FILE exists. If not, ask user what to do."
17861 (when (not (file-exists-p file))
17862 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17863 (abbreviate-file-name file))
17864 (let ((r (downcase (read-char-exclusive))))
17865 (cond
17866 ((equal r ?r)
17867 (org-remove-file file)
17868 (throw 'nextfile t))
17869 (t (error "Abort"))))))
17871 (defun org-get-agenda-file-buffer (file)
17872 "Get a buffer visiting FILE. If the buffer needs to be created, add
17873 it to the list of buffers which might be released later."
17874 (let ((buf (org-find-base-buffer-visiting file)))
17875 (if buf
17876 buf ; just return it
17877 ;; Make a new buffer and remember it
17878 (setq buf (find-file-noselect file))
17879 (if buf (push buf org-agenda-new-buffers))
17880 buf)))
17882 (defun org-release-buffers (blist)
17883 "Release all buffers in list, asking the user for confirmation when needed.
17884 When a buffer is unmodified, it is just killed. When modified, it is saved
17885 \(if the user agrees) and then killed."
17886 (let (buf file)
17887 (while (setq buf (pop blist))
17888 (setq file (buffer-file-name buf))
17889 (when (and (buffer-modified-p buf)
17890 file
17891 (y-or-n-p (format "Save file %s? " file)))
17892 (with-current-buffer buf (save-buffer)))
17893 (kill-buffer buf))))
17895 (defun org-agenda-prepare-buffers (files)
17896 "Create buffers for all agenda files, protect archived trees and comments."
17897 (interactive)
17898 (let ((pa '(:org-archived t))
17899 (pc '(:org-comment t))
17900 (pall '(:org-archived t :org-comment t))
17901 (inhibit-read-only t)
17902 (org-inhibit-startup org-agenda-inhibit-startup)
17903 (rea (concat ":" org-archive-tag ":"))
17904 file re)
17905 (setq org-tag-alist-for-agenda nil
17906 org-tag-groups-alist-for-agenda nil)
17907 (save-excursion
17908 (save-restriction
17909 (while (setq file (pop files))
17910 (catch 'nextfile
17911 (if (bufferp file)
17912 (set-buffer file)
17913 (org-check-agenda-file file)
17914 (set-buffer (org-get-agenda-file-buffer file)))
17915 (widen)
17916 (org-set-regexps-and-options-for-tags)
17917 (org-refresh-category-properties)
17918 (org-refresh-properties org-effort-property 'org-effort)
17919 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17920 (setq org-todo-keywords-for-agenda
17921 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17922 (setq org-done-keywords-for-agenda
17923 (append org-done-keywords-for-agenda org-done-keywords))
17924 (setq org-todo-keyword-alist-for-agenda
17925 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17926 (setq org-drawers-for-agenda
17927 (append org-drawers-for-agenda org-drawers))
17928 (unless (equal org-tag-alist-for-agenda org-tag-alist)
17929 (setq org-tag-alist-for-agenda
17930 (append org-tag-alist-for-agenda org-tag-alist)))
17931 (if org-group-tags
17932 (setq org-tag-groups-alist-for-agenda
17933 (org-uniquify-alist
17934 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17935 (org-with-silent-modifications
17936 (save-excursion
17937 (remove-text-properties (point-min) (point-max) pall)
17938 (when org-agenda-skip-archived-trees
17939 (goto-char (point-min))
17940 (while (re-search-forward rea nil t)
17941 (if (org-at-heading-p t)
17942 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17943 (goto-char (point-min))
17944 (setq re (format org-heading-keyword-regexp-format
17945 org-comment-string))
17946 (while (re-search-forward re nil t)
17947 (add-text-properties
17948 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17949 (setq org-todo-keywords-for-agenda
17950 (org-uniquify org-todo-keywords-for-agenda))
17951 (setq org-todo-keyword-alist-for-agenda
17952 (org-uniquify org-todo-keyword-alist-for-agenda))))
17955 ;;;; CDLaTeX minor mode
17957 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17958 "Keymap for the minor `org-cdlatex-mode'.")
17960 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17961 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17962 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17963 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17964 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17966 (defvar org-cdlatex-texmathp-advice-is-done nil
17967 "Flag remembering if we have applied the advice to texmathp already.")
17969 (define-minor-mode org-cdlatex-mode
17970 "Toggle the minor `org-cdlatex-mode'.
17971 This mode supports entering LaTeX environment and math in LaTeX fragments
17972 in Org-mode.
17973 \\{org-cdlatex-mode-map}"
17974 nil " OCDL" nil
17975 (when org-cdlatex-mode
17976 (require 'cdlatex)
17977 (run-hooks 'cdlatex-mode-hook)
17978 (cdlatex-compute-tables))
17979 (unless org-cdlatex-texmathp-advice-is-done
17980 (setq org-cdlatex-texmathp-advice-is-done t)
17981 (defadvice texmathp (around org-math-always-on activate)
17982 "Always return t in org-mode buffers.
17983 This is because we want to insert math symbols without dollars even outside
17984 the LaTeX math segments. If Orgmode thinks that point is actually inside
17985 an embedded LaTeX fragment, let texmathp do its job.
17986 \\[org-cdlatex-mode-map]"
17987 (interactive)
17988 (let (p)
17989 (cond
17990 ((not (derived-mode-p 'org-mode)) ad-do-it)
17991 ((eq this-command 'cdlatex-math-symbol)
17992 (setq ad-return-value t
17993 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17995 (let ((p (org-inside-LaTeX-fragment-p)))
17996 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17997 (setq ad-return-value t
17998 texmathp-why '("Org-mode embedded math" . 0))
17999 (if p ad-do-it)))))))))
18001 (defun turn-on-org-cdlatex ()
18002 "Unconditionally turn on `org-cdlatex-mode'."
18003 (org-cdlatex-mode 1))
18005 (defun org-try-cdlatex-tab ()
18006 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18007 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18008 - inside a LaTeX fragment, or
18009 - after the first word in a line, where an abbreviation expansion could
18010 insert a LaTeX environment."
18011 (when org-cdlatex-mode
18012 (cond
18013 ;; Before any word on the line: No expansion possible.
18014 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18015 ;; Just after first word on the line: Expand it. Make sure it
18016 ;; cannot happen on headlines, though.
18017 ((save-excursion
18018 (skip-chars-backward "a-zA-Z0-9*")
18019 (skip-chars-backward " \t")
18020 (and (bolp) (not (org-at-heading-p))))
18021 (cdlatex-tab) t)
18022 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18024 (defun org-cdlatex-underscore-caret (&optional arg)
18025 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18026 Revert to the normal definition outside of these fragments."
18027 (interactive "P")
18028 (if (org-inside-LaTeX-fragment-p)
18029 (call-interactively 'cdlatex-sub-superscript)
18030 (let (org-cdlatex-mode)
18031 (call-interactively (key-binding (vector last-input-event))))))
18033 (defun org-cdlatex-math-modify (&optional arg)
18034 "Execute `cdlatex-math-modify' in LaTeX fragments.
18035 Revert to the normal definition outside of these fragments."
18036 (interactive "P")
18037 (if (org-inside-LaTeX-fragment-p)
18038 (call-interactively 'cdlatex-math-modify)
18039 (let (org-cdlatex-mode)
18040 (call-interactively (key-binding (vector last-input-event))))))
18044 ;;;; LaTeX fragments
18046 (defvar org-latex-regexps
18047 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18048 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18049 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18050 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18051 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18052 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18053 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18054 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18055 "Regular expressions for matching embedded LaTeX.")
18057 (defun org-inside-LaTeX-fragment-p ()
18058 "Test if point is inside a LaTeX fragment.
18059 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18060 sequence appearing also before point.
18061 Even though the matchers for math are configurable, this function assumes
18062 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18063 delimiters are skipped when they have been removed by customization.
18064 The return value is nil, or a cons cell with the delimiter and the
18065 position of this delimiter.
18067 This function does a reasonably good job, but can locally be fooled by
18068 for example currency specifications. For example it will assume being in
18069 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18070 fragments that are properly closed, but during editing, we have to live
18071 with the uncertainty caused by missing closing delimiters. This function
18072 looks only before point, not after."
18073 (catch 'exit
18074 (let ((pos (point))
18075 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18076 (lim (progn
18077 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18078 (point)))
18079 dd-on str (start 0) m re)
18080 (goto-char pos)
18081 (when dodollar
18082 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18083 re (nth 1 (assoc "$" org-latex-regexps)))
18084 (while (string-match re str start)
18085 (cond
18086 ((= (match-end 0) (length str))
18087 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18088 ((= (match-end 0) (- (length str) 5))
18089 (throw 'exit nil))
18090 (t (setq start (match-end 0))))))
18091 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18092 (goto-char pos)
18093 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18094 (and (match-beginning 2) (throw 'exit nil))
18095 ;; count $$
18096 (while (re-search-backward "\\$\\$" lim t)
18097 (setq dd-on (not dd-on)))
18098 (goto-char pos)
18099 (if dd-on (cons "$$" m))))))
18101 (defun org-inside-latex-macro-p ()
18102 "Is point inside a LaTeX macro or its arguments?"
18103 (save-match-data
18104 (org-in-regexp
18105 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18107 (defvar org-latex-fragment-image-overlays nil
18108 "List of overlays carrying the images of latex fragments.")
18109 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18111 (defun org-remove-latex-fragment-image-overlays ()
18112 "Remove all overlays with LaTeX fragment images in current buffer."
18113 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18114 (setq org-latex-fragment-image-overlays nil))
18116 (defun org-preview-latex-fragment (&optional subtree)
18117 "Preview the LaTeX fragment at point, or all locally or globally.
18118 If the cursor is in a LaTeX fragment, create the image and overlay
18119 it over the source code. If there is no fragment at point, display
18120 all fragments in the current text, from one headline to the next. With
18121 prefix SUBTREE, display all fragments in the current subtree. With a
18122 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18123 the cursor is before the first headline,
18124 display all fragments in the buffer.
18125 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18126 (interactive "P")
18127 (unless buffer-file-name
18128 (error "Can't preview LaTeX fragment in a non-file buffer"))
18129 (org-remove-latex-fragment-image-overlays)
18130 (save-excursion
18131 (save-restriction
18132 (let (beg end at msg)
18133 (cond
18134 ((or (equal subtree '(16))
18135 (not (save-excursion
18136 (re-search-backward org-outline-regexp-bol nil t))))
18137 (setq beg (point-min) end (point-max)
18138 msg "Creating images for buffer...%s"))
18139 ((equal subtree '(4))
18140 (org-back-to-heading)
18141 (setq beg (point) end (org-end-of-subtree t)
18142 msg "Creating images for subtree...%s"))
18144 (if (setq at (org-inside-LaTeX-fragment-p))
18145 (goto-char (max (point-min) (- (cdr at) 2)))
18146 (org-back-to-heading))
18147 (setq beg (point) end (progn (outline-next-heading) (point))
18148 msg (if at "Creating image...%s"
18149 "Creating images for entry...%s"))))
18150 (message msg "")
18151 (narrow-to-region beg end)
18152 (goto-char beg)
18153 (org-format-latex
18154 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18155 (file-name-nondirectory
18156 buffer-file-name)))
18157 default-directory 'overlays msg at 'forbuffer
18158 org-latex-create-formula-image-program)
18159 (message msg "done. Use `C-c C-c' to remove images.")))))
18161 (defun org-format-latex (prefix &optional dir overlays msg at
18162 forbuffer processing-type)
18163 "Replace LaTeX fragments with links to an image, and produce images.
18164 Some of the options can be changed using the variable
18165 `org-format-latex-options'."
18166 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18167 (let* ((prefixnodir (file-name-nondirectory prefix))
18168 (absprefix (expand-file-name prefix dir))
18169 (todir (file-name-directory absprefix))
18170 (opt org-format-latex-options)
18171 (optnew org-format-latex-options)
18172 (matchers (plist-get opt :matchers))
18173 (re-list org-latex-regexps)
18174 (cnt 0) txt hash link beg end re e checkdir
18175 string
18176 m n block-type block linkfile movefile ov)
18177 ;; Check the different regular expressions
18178 (while (setq e (pop re-list))
18179 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18180 block (if block-type "\n\n" ""))
18181 (when (member m matchers)
18182 (goto-char (point-min))
18183 (while (re-search-forward re nil t)
18184 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18185 (or (not overlays)
18186 (not (eq (get-char-property (match-beginning n)
18187 'org-overlay-type)
18188 'org-latex-overlay))))
18189 (cond
18190 ((eq processing-type 'verbatim))
18191 ((eq processing-type 'mathjax)
18192 ;; Prepare for MathJax processing.
18193 (setq string (match-string n))
18194 (when (member m '("$" "$1"))
18195 (save-excursion
18196 (delete-region (match-beginning n) (match-end n))
18197 (goto-char (match-beginning n))
18198 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18199 ((or (eq processing-type 'dvipng)
18200 (eq processing-type 'imagemagick))
18201 ;; Process to an image.
18202 (setq txt (match-string n)
18203 beg (match-beginning n) end (match-end n)
18204 cnt (1+ cnt))
18205 (let ((face (face-at-point))
18206 (fg (plist-get opt :foreground))
18207 (bg (plist-get opt :background))
18208 ;; Ensure full list is printed.
18209 print-length print-level)
18210 (when forbuffer
18211 ;; Get the colors from the face at point.
18212 (goto-char beg)
18213 (when (eq fg 'auto)
18214 (setq fg (face-attribute face :foreground nil 'default)))
18215 (when (eq bg 'auto)
18216 (setq bg (face-attribute face :background nil 'default)))
18217 (setq optnew (copy-sequence opt))
18218 (plist-put optnew :foreground fg)
18219 (plist-put optnew :background bg))
18220 (setq hash (sha1 (prin1-to-string
18221 (list org-format-latex-header
18222 org-latex-default-packages-alist
18223 org-latex-packages-alist
18224 org-format-latex-options
18225 forbuffer txt fg bg)))
18226 linkfile (format "%s_%s.png" prefix hash)
18227 movefile (format "%s_%s.png" absprefix hash)))
18228 (setq link (concat block "[[file:" linkfile "]]" block))
18229 (if msg (message msg cnt))
18230 (goto-char beg)
18231 (unless checkdir ; Ensure the directory exists.
18232 (setq checkdir t)
18233 (or (file-directory-p todir) (make-directory todir t)))
18234 (unless (file-exists-p movefile)
18235 (org-create-formula-image
18236 txt movefile optnew forbuffer processing-type))
18237 (if overlays
18238 (progn
18239 (mapc (lambda (o)
18240 (if (eq (overlay-get o 'org-overlay-type)
18241 'org-latex-overlay)
18242 (delete-overlay o)))
18243 (overlays-in beg end))
18244 (setq ov (make-overlay beg end))
18245 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18246 (if (featurep 'xemacs)
18247 (progn
18248 (overlay-put ov 'invisible t)
18249 (overlay-put
18250 ov 'end-glyph
18251 (make-glyph (vector 'png :file movefile))))
18252 (overlay-put
18253 ov 'display
18254 (list 'image :type 'png :file movefile :ascent 'center)))
18255 (push ov org-latex-fragment-image-overlays)
18256 (goto-char end))
18257 (delete-region beg end)
18258 (insert (org-add-props link
18259 (list 'org-latex-src
18260 (replace-regexp-in-string
18261 "\"" "" txt)
18262 'org-latex-src-embed-type
18263 (if block-type 'paragraph 'character))))))
18264 ((eq processing-type 'mathml)
18265 ;; Process to MathML
18266 (unless (save-match-data (org-format-latex-mathml-available-p))
18267 (error "LaTeX to MathML converter not configured"))
18268 (setq txt (match-string n)
18269 beg (match-beginning n) end (match-end n)
18270 cnt (1+ cnt))
18271 (if msg (message msg cnt))
18272 (goto-char beg)
18273 (delete-region beg end)
18274 (insert (org-format-latex-as-mathml
18275 txt block-type prefix dir)))
18277 (error "Unknown conversion type %s for latex fragments"
18278 processing-type)))))))))
18280 (defun org-create-math-formula (latex-frag &optional mathml-file)
18281 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18282 Use `org-latex-to-mathml-convert-command'. If the conversion is
18283 sucessful, return the portion between \"<math...> </math>\"
18284 elements otherwise return nil. When MATHML-FILE is specified,
18285 write the results in to that file. When invoked as an
18286 interactive command, prompt for LATEX-FRAG, with initial value
18287 set to the current active region and echo the results for user
18288 inspection."
18289 (interactive (list (let ((frag (when (org-region-active-p)
18290 (buffer-substring-no-properties
18291 (region-beginning) (region-end)))))
18292 (read-string "LaTeX Fragment: " frag nil frag))))
18293 (unless latex-frag (error "Invalid latex-frag"))
18294 (let* ((tmp-in-file (file-relative-name
18295 (make-temp-name (expand-file-name "ltxmathml-in"))))
18296 (ignore (write-region latex-frag nil tmp-in-file))
18297 (tmp-out-file (file-relative-name
18298 (make-temp-name (expand-file-name "ltxmathml-out"))))
18299 (cmd (format-spec
18300 org-latex-to-mathml-convert-command
18301 `((?j . ,(shell-quote-argument
18302 (expand-file-name org-latex-to-mathml-jar-file)))
18303 (?I . ,(shell-quote-argument tmp-in-file))
18304 (?o . ,(shell-quote-argument tmp-out-file)))))
18305 mathml shell-command-output)
18306 (when (org-called-interactively-p 'any)
18307 (unless (org-format-latex-mathml-available-p)
18308 (error "LaTeX to MathML converter not configured")))
18309 (message "Running %s" cmd)
18310 (setq shell-command-output (shell-command-to-string cmd))
18311 (setq mathml
18312 (when (file-readable-p tmp-out-file)
18313 (with-current-buffer (find-file-noselect tmp-out-file t)
18314 (goto-char (point-min))
18315 (when (re-search-forward
18316 (concat
18317 (regexp-quote
18318 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18319 "\\(.\\|\n\\)*"
18320 (regexp-quote "</math>")) nil t)
18321 (prog1 (match-string 0) (kill-buffer))))))
18322 (cond
18323 (mathml
18324 (setq mathml
18325 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18326 (when mathml-file
18327 (write-region mathml nil mathml-file))
18328 (when (org-called-interactively-p 'any)
18329 (message mathml)))
18330 ((message "LaTeX to MathML conversion failed")
18331 (message shell-command-output)))
18332 (delete-file tmp-in-file)
18333 (when (file-exists-p tmp-out-file)
18334 (delete-file tmp-out-file))
18335 mathml))
18337 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18338 prefix &optional dir)
18339 "Use `org-create-math-formula' but check local cache first."
18340 (let* ((absprefix (expand-file-name prefix dir))
18341 (print-length nil) (print-level nil)
18342 (formula-id (concat
18343 "formula-"
18344 (sha1
18345 (prin1-to-string
18346 (list latex-frag
18347 org-latex-to-mathml-convert-command)))))
18348 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18349 (formula-cache-dir (file-name-directory formula-cache)))
18351 (unless (file-directory-p formula-cache-dir)
18352 (make-directory formula-cache-dir t))
18354 (unless (file-exists-p formula-cache)
18355 (org-create-math-formula latex-frag formula-cache))
18357 (if (file-exists-p formula-cache)
18358 ;; Successful conversion. Return the link to MathML file.
18359 (org-add-props
18360 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18361 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18362 'org-latex-src-embed-type (if latex-frag-type
18363 'paragraph 'character)))
18364 ;; Failed conversion. Return the LaTeX fragment verbatim
18365 latex-frag)))
18367 (defun org-create-formula-image (string tofile options buffer &optional type)
18368 "Create an image from LaTeX source using dvipng or convert.
18369 This function calls either `org-create-formula-image-with-dvipng'
18370 or `org-create-formula-image-with-imagemagick' depending on the
18371 value of `org-latex-create-formula-image-program' or on the value
18372 of the optional TYPE variable.
18374 Note: ultimately these two function should be combined as they
18375 share a good deal of logic."
18376 (org-check-external-command
18377 "latex" "needed to convert LaTeX fragments to images")
18378 (funcall
18379 (case (or type org-latex-create-formula-image-program)
18380 ('dvipng
18381 (org-check-external-command
18382 "dvipng" "needed to convert LaTeX fragments to images")
18383 #'org-create-formula-image-with-dvipng)
18384 ('imagemagick
18385 (org-check-external-command
18386 "convert" "you need to install imagemagick")
18387 #'org-create-formula-image-with-imagemagick)
18388 (t (error
18389 "invalid value of `org-latex-create-formula-image-program'")))
18390 string tofile options buffer))
18392 (declare-function org-export--get-global-options "ox" (&optional backend))
18393 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18394 (defun org-create-formula--latex-header ()
18395 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18396 (org-latex-guess-inputenc
18397 (org-splice-latex-header
18398 org-format-latex-header
18399 org-latex-default-packages-alist
18400 org-latex-packages-alist t
18401 (plist-get
18402 (org-combine-plists
18403 (org-export--get-global-options 'latex)
18404 (org-export--get-inbuffer-options 'latex))
18405 :latex-header))))
18407 ;; This function borrows from Ganesh Swami's latex2png.el
18408 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18409 "This calls dvipng."
18410 (require 'ox-latex)
18411 (let* ((tmpdir (if (featurep 'xemacs)
18412 (temp-directory)
18413 temporary-file-directory))
18414 (texfilebase (make-temp-name
18415 (expand-file-name "orgtex" tmpdir)))
18416 (texfile (concat texfilebase ".tex"))
18417 (dvifile (concat texfilebase ".dvi"))
18418 (pngfile (concat texfilebase ".png"))
18419 (fnh (if (featurep 'xemacs)
18420 (font-height (face-font 'default))
18421 (face-attribute 'default :height nil)))
18422 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18423 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18424 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18425 "Black"))
18426 (bg (or (plist-get options (if buffer :background :html-background))
18427 "Transparent")))
18428 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18429 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18430 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18431 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18432 (let ((latex-header (org-create-formula--latex-header)))
18433 (with-temp-file texfile
18434 (insert latex-header)
18435 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18436 (let ((dir default-directory))
18437 (condition-case nil
18438 (progn
18439 (cd tmpdir)
18440 (call-process "latex" nil nil nil texfile))
18441 (error nil))
18442 (cd dir))
18443 (if (not (file-exists-p dvifile))
18444 (progn (message "Failed to create dvi file from %s" texfile) nil)
18445 (condition-case nil
18446 (if (featurep 'xemacs)
18447 (call-process "dvipng" nil nil nil
18448 "-fg" fg "-bg" bg
18449 "-T" "tight"
18450 "-o" pngfile
18451 dvifile)
18452 (call-process "dvipng" nil nil nil
18453 "-fg" fg "-bg" bg
18454 "-D" dpi
18455 ;;"-x" scale "-y" scale
18456 "-T" "tight"
18457 "-o" pngfile
18458 dvifile))
18459 (error nil))
18460 (if (not (file-exists-p pngfile))
18461 (if org-format-latex-signal-error
18462 (error "Failed to create png file from %s" texfile)
18463 (message "Failed to create png file from %s" texfile)
18464 nil)
18465 ;; Use the requested file name and clean up
18466 (copy-file pngfile tofile 'replace)
18467 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18468 (if (file-exists-p (concat texfilebase e))
18469 (delete-file (concat texfilebase e))))
18470 pngfile))))
18472 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18473 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18474 "This calls convert, which is included into imagemagick."
18475 (require 'ox-latex)
18476 (let* ((tmpdir (if (featurep 'xemacs)
18477 (temp-directory)
18478 temporary-file-directory))
18479 (texfilebase (make-temp-name
18480 (expand-file-name "orgtex" tmpdir)))
18481 (texfile (concat texfilebase ".tex"))
18482 (pdffile (concat texfilebase ".pdf"))
18483 (pngfile (concat texfilebase ".png"))
18484 (fnh (if (featurep 'xemacs)
18485 (font-height (face-font 'default))
18486 (face-attribute 'default :height nil)))
18487 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18488 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18489 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18490 "black"))
18491 (bg (or (plist-get options (if buffer :background :html-background))
18492 "white")))
18493 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18494 (setq fg (org-latex-color-format fg)))
18495 (if (eq bg 'default) (setq bg (org-latex-color :background))
18496 (setq bg (org-latex-color-format
18497 (if (string= bg "Transparent") "white" bg))))
18498 (let ((latex-header (org-create-formula--latex-header)))
18499 (with-temp-file texfile
18500 (insert latex-header)
18501 (insert "\n\\begin{document}\n"
18502 "\\definecolor{fg}{rgb}{" fg "}\n"
18503 "\\definecolor{bg}{rgb}{" bg "}\n"
18504 "\n\\pagecolor{bg}\n"
18505 "\n{\\color{fg}\n"
18506 string
18507 "\n}\n"
18508 "\n\\end{document}\n")))
18509 (org-latex-compile texfile t)
18510 (if (not (file-exists-p pdffile))
18511 (progn (message "Failed to create pdf file from %s" texfile) nil)
18512 (condition-case nil
18513 (if (featurep 'xemacs)
18514 (call-process "convert" nil nil nil
18515 "-density" "96"
18516 "-trim"
18517 "-antialias"
18518 pdffile
18519 "-quality" "100"
18520 ;; "-sharpen" "0x1.0"
18521 pngfile)
18522 (call-process "convert" nil nil nil
18523 "-density" dpi
18524 "-trim"
18525 "-antialias"
18526 pdffile
18527 "-quality" "100"
18528 ;; "-sharpen" "0x1.0"
18529 pngfile))
18530 (error nil))
18531 (if (not (file-exists-p pngfile))
18532 (if org-format-latex-signal-error
18533 (error "Failed to create png file from %s" texfile)
18534 (message "Failed to create png file from %s" texfile)
18535 nil)
18536 ;; Use the requested file name and clean up
18537 (copy-file pngfile tofile 'replace)
18538 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18539 (if (file-exists-p (concat texfilebase e))
18540 (delete-file (concat texfilebase e))))
18541 pngfile))))
18543 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18544 "Fill a LaTeX header template TPL.
18545 In the template, the following place holders will be recognized:
18547 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18548 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18549 [PACKAGES] \\usepackage statements for PKG
18550 [NO-PACKAGES] do not include PKG
18551 [EXTRA] the string EXTRA
18552 [NO-EXTRA] do not include EXTRA
18554 For backward compatibility, if both the positive and the negative place
18555 holder is missing, the positive one (without the \"NO-\") will be
18556 assumed to be present at the end of the template.
18557 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18558 EXTRA is a string.
18559 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18560 (let (rpl (end ""))
18561 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18562 (setq rpl (if (or (match-end 1) (not def-pkg))
18563 "" (org-latex-packages-to-string def-pkg snippets-p t))
18564 tpl (replace-match rpl t t tpl))
18565 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18567 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18568 (setq rpl (if (or (match-end 1) (not pkg))
18569 "" (org-latex-packages-to-string pkg snippets-p t))
18570 tpl (replace-match rpl t t tpl))
18571 (if pkg (setq end
18572 (concat end "\n"
18573 (org-latex-packages-to-string pkg snippets-p)))))
18575 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18576 (setq rpl (if (or (match-end 1) (not extra))
18577 "" (concat extra "\n"))
18578 tpl (replace-match rpl t t tpl))
18579 (if (and extra (string-match "\\S-" extra))
18580 (setq end (concat end "\n" extra))))
18582 (if (string-match "\\S-" end)
18583 (concat tpl "\n" end)
18584 tpl)))
18586 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18587 "Turn an alist of packages into a string with the \\usepackage macros."
18588 (setq pkg (mapconcat (lambda(p)
18589 (cond
18590 ((stringp p) p)
18591 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18592 (format "%% Package %s omitted" (cadr p)))
18593 ((equal "" (car p))
18594 (format "\\usepackage{%s}" (cadr p)))
18596 (format "\\usepackage[%s]{%s}"
18597 (car p) (cadr p)))))
18599 "\n"))
18600 (if newline (concat pkg "\n") pkg))
18602 (defun org-dvipng-color (attr)
18603 "Return a RGB color specification for dvipng."
18604 (apply 'format "rgb %s %s %s"
18605 (mapcar 'org-normalize-color
18606 (if (featurep 'xemacs)
18607 (color-rgb-components
18608 (face-property 'default
18609 (cond ((eq attr :foreground) 'foreground)
18610 ((eq attr :background) 'background))))
18611 (color-values (face-attribute 'default attr nil))))))
18613 (defun org-dvipng-color-format (color-name)
18614 "Convert COLOR-NAME to a RGB color value for dvipng."
18615 (apply 'format "rgb %s %s %s"
18616 (mapcar 'org-normalize-color
18617 (color-values color-name))))
18619 (defun org-latex-color (attr)
18620 "Return a RGB color for the LaTeX color package."
18621 (apply 'format "%s,%s,%s"
18622 (mapcar 'org-normalize-color
18623 (if (featurep 'xemacs)
18624 (color-rgb-components
18625 (face-property 'default
18626 (cond ((eq attr :foreground) 'foreground)
18627 ((eq attr :background) 'background))))
18628 (color-values (face-attribute 'default attr nil))))))
18630 (defun org-latex-color-format (color-name)
18631 "Convert COLOR-NAME to a RGB color value."
18632 (apply 'format "%s,%s,%s"
18633 (mapcar 'org-normalize-color
18634 (color-values color-name))))
18636 (defun org-normalize-color (value)
18637 "Return string to be used as color value for an RGB component."
18638 (format "%g" (/ value 65535.0)))
18642 ;; Image display
18644 (defvar org-inline-image-overlays nil)
18645 (make-variable-buffer-local 'org-inline-image-overlays)
18647 (defun org-toggle-inline-images (&optional include-linked)
18648 "Toggle the display of inline images.
18649 INCLUDE-LINKED is passed to `org-display-inline-images'."
18650 (interactive "P")
18651 (if org-inline-image-overlays
18652 (progn
18653 (org-remove-inline-images)
18654 (message "Inline image display turned off"))
18655 (org-display-inline-images include-linked)
18656 (if (and (org-called-interactively-p)
18657 org-inline-image-overlays)
18658 (message "%d images displayed inline"
18659 (length org-inline-image-overlays))
18660 (message "No images to display inline"))))
18662 (defun org-redisplay-inline-images ()
18663 "Refresh the display of inline images."
18664 (interactive)
18665 (if (not org-inline-image-overlays)
18666 (org-toggle-inline-images)
18667 (org-toggle-inline-images)
18668 (org-toggle-inline-images)))
18670 (defun org-display-inline-images (&optional include-linked refresh beg end)
18671 "Display inline images.
18672 Normally only links without a description part are inlined, because this
18673 is how it will work for export. When INCLUDE-LINKED is set, also links
18674 with a description part will be inlined. This can be nice for a quick
18675 look at those images, but it does not reflect what exported files will look
18676 like.
18677 When REFRESH is set, refresh existing images between BEG and END.
18678 This will create new image displays only if necessary.
18679 BEG and END default to the buffer boundaries."
18680 (interactive "P")
18681 (unless refresh
18682 (org-remove-inline-images)
18683 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18684 (save-excursion
18685 (save-restriction
18686 (widen)
18687 (setq beg (or beg (point-min)) end (or end (point-max)))
18688 (goto-char beg)
18689 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18690 (substring (org-image-file-name-regexp) 0 -2)
18691 "\\)\\]" (if include-linked "" "\\]")))
18692 (case-fold-search t)
18693 old file ov img type attrwidth width)
18694 (while (re-search-forward re end t)
18695 (setq old (get-char-property-and-overlay (match-beginning 1)
18696 'org-image-overlay)
18697 file (expand-file-name
18698 (concat (or (match-string 3) "") (match-string 4))))
18699 (when (image-type-available-p 'imagemagick)
18700 (setq attrwidth (if (or (listp org-image-actual-width)
18701 (null org-image-actual-width))
18702 (save-excursion
18703 (save-match-data
18704 (when (re-search-backward
18705 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18706 (save-excursion
18707 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18708 (string-to-number (match-string 1))))))
18709 width (cond ((eq org-image-actual-width t) nil)
18710 ((null org-image-actual-width) attrwidth)
18711 ((numberp org-image-actual-width)
18712 org-image-actual-width)
18713 ((listp org-image-actual-width)
18714 (or attrwidth (car org-image-actual-width))))
18715 type (if width 'imagemagick)))
18716 (when (file-exists-p file)
18717 (if (and (car-safe old) refresh)
18718 (image-refresh (overlay-get (cdr old) 'display))
18719 (setq img (save-match-data (create-image file type nil :width width)))
18720 (when img
18721 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18722 (overlay-put ov 'display img)
18723 (overlay-put ov 'face 'default)
18724 (overlay-put ov 'org-image-overlay t)
18725 (overlay-put ov 'modification-hooks
18726 (list 'org-display-inline-remove-overlay))
18727 (push ov org-inline-image-overlays)))))))))
18729 (define-obsolete-function-alias
18730 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18732 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18733 "Remove inline-display overlay if a corresponding region is modified."
18734 (let ((inhibit-modification-hooks t))
18735 (when (and ov after)
18736 (delete ov org-inline-image-overlays)
18737 (delete-overlay ov))))
18739 (defun org-remove-inline-images ()
18740 "Remove inline display of images."
18741 (interactive)
18742 (mapc 'delete-overlay org-inline-image-overlays)
18743 (setq org-inline-image-overlays nil))
18745 ;;;; Key bindings
18747 ;; Outline functions from `outline-mode-prefix-map'
18748 ;; that can be remapped in Org:
18749 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18750 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18751 (define-key org-mode-map [remap outline-forward-same-level]
18752 'org-forward-heading-same-level)
18753 (define-key org-mode-map [remap outline-backward-same-level]
18754 'org-backward-heading-same-level)
18755 (define-key org-mode-map [remap show-branches]
18756 'org-kill-note-or-show-branches)
18757 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18758 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18759 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18761 ;; Outline functions from `outline-mode-prefix-map' that can not
18762 ;; be remapped in Org:
18764 ;; - the column "key binding" shows whether the Outline function is still
18765 ;; available in Org mode on the same key that it has been bound to in
18766 ;; Outline mode:
18767 ;; - "overridden": key used for a different functionality in Org mode
18768 ;; - else: key still bound to the same Outline function in Org mode
18770 ;; | Outline function | key binding | Org replacement |
18771 ;; |------------------------------------+-------------+-----------------------|
18772 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18773 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18774 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18775 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18776 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18777 ;; | `show-entry' | overridden | no replacement |
18778 ;; | `show-children' | `C-c C-i' | visibility cycling |
18779 ;; | `show-branches' | `C-c C-k' | still same function |
18780 ;; | `show-subtree' | overridden | visibility cycling |
18781 ;; | `show-all' | overridden | no replacement |
18782 ;; | `hide-subtree' | overridden | visibility cycling |
18783 ;; | `hide-body' | overridden | no replacement |
18784 ;; | `hide-entry' | overridden | visibility cycling |
18785 ;; | `hide-leaves' | overridden | no replacement |
18786 ;; | `hide-sublevels' | overridden | no replacement |
18787 ;; | `hide-other' | overridden | no replacement |
18789 ;; Make `C-c C-x' a prefix key
18790 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18792 ;; TAB key with modifiers
18793 (org-defkey org-mode-map "\C-i" 'org-cycle)
18794 (org-defkey org-mode-map [(tab)] 'org-cycle)
18795 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18796 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18797 ;; The following line is necessary under Suse GNU/Linux
18798 (unless (featurep 'xemacs)
18799 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18800 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18801 (define-key org-mode-map [backtab] 'org-shifttab)
18803 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18804 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18805 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18807 ;; Cursor keys with modifiers
18808 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18809 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18810 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18811 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18813 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18814 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18815 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18816 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18818 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18819 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18820 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18821 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18823 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18824 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18825 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18826 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18828 ;; Babel keys
18829 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18830 (mapc (lambda (pair)
18831 (define-key org-babel-map (car pair) (cdr pair)))
18832 org-babel-key-bindings)
18834 ;;; Extra keys for tty access.
18835 ;; We only set them when really needed because otherwise the
18836 ;; menus don't show the simple keys
18838 (when (or org-use-extra-keys
18839 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18840 (not window-system))
18841 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18842 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18843 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18844 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18845 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18846 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18847 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18848 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18849 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18850 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18851 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18852 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18853 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18854 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18855 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18856 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18857 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18858 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18859 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18860 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18861 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18862 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18863 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18864 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18865 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18866 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18867 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18868 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18870 ;; All the other keys
18872 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18873 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18874 (if (boundp 'narrow-map)
18875 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18876 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18877 (if (boundp 'narrow-map)
18878 (org-defkey narrow-map "b" 'org-narrow-to-block)
18879 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18880 (if (boundp 'narrow-map)
18881 (org-defkey narrow-map "e" 'org-narrow-to-element)
18882 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18883 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18884 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18885 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18886 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18887 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18888 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18889 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18890 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18891 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18892 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18893 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18894 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18895 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18896 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18897 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18898 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18899 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18900 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18901 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18902 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18903 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18904 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18905 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18906 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18907 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18908 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18909 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18910 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18911 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18912 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18913 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18914 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18915 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18916 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18917 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18918 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18919 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18920 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18921 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18922 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18923 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18924 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18925 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18926 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18927 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18928 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18929 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18930 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18931 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18932 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18933 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18934 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18935 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18936 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18937 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18938 (org-defkey org-mode-map "\C-c^" 'org-sort)
18939 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18940 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18941 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18942 (org-defkey org-mode-map "\C-m" 'org-return)
18943 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18944 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18945 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18946 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18947 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18948 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18949 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18950 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18951 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18952 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18953 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18954 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18955 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18956 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18957 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18958 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18959 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18960 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18961 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18962 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18963 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18964 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18965 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18967 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18968 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18969 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18971 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18972 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18973 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18974 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18975 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18976 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18977 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18978 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18979 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18980 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18981 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18982 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18983 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18984 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18985 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18986 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18987 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18988 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18989 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18990 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18991 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18992 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18993 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18995 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18996 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18997 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18998 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18999 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19001 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19003 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19005 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19006 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19008 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19011 (when (featurep 'xemacs)
19012 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19015 (defconst org-speed-commands-default
19017 ("Outline Navigation")
19018 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19019 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19020 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19021 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19022 ("F" . org-next-block)
19023 ("B" . org-previous-block)
19024 ("u" . (org-speed-move-safe 'outline-up-heading))
19025 ("j" . org-goto)
19026 ("g" . (org-refile t))
19027 ("Outline Visibility")
19028 ("c" . org-cycle)
19029 ("C" . org-shifttab)
19030 (" " . org-display-outline-path)
19031 ("s" . org-narrow-to-subtree)
19032 ("=" . org-columns)
19033 ("Outline Structure Editing")
19034 ("U" . org-shiftmetaup)
19035 ("D" . org-shiftmetadown)
19036 ("r" . org-metaright)
19037 ("l" . org-metaleft)
19038 ("R" . org-shiftmetaright)
19039 ("L" . org-shiftmetaleft)
19040 ("i" . (progn (forward-char 1) (call-interactively
19041 'org-insert-heading-respect-content)))
19042 ("^" . org-sort)
19043 ("w" . org-refile)
19044 ("a" . org-archive-subtree-default-with-confirmation)
19045 ("@" . org-mark-subtree)
19046 ("#" . org-toggle-comment)
19047 ("Clock Commands")
19048 ("I" . org-clock-in)
19049 ("O" . org-clock-out)
19050 ("Meta Data Editing")
19051 ("t" . org-todo)
19052 ("," . (org-priority))
19053 ("0" . (org-priority ?\ ))
19054 ("1" . (org-priority ?A))
19055 ("2" . (org-priority ?B))
19056 ("3" . (org-priority ?C))
19057 (":" . org-set-tags-command)
19058 ("e" . org-set-effort)
19059 ("E" . org-inc-effort)
19060 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19061 (org-entry-put (point) "APPT_WARNTIME" m)))
19062 ("Agenda Views etc")
19063 ("v" . org-agenda)
19064 ("/" . org-sparse-tree)
19065 ("Misc")
19066 ("o" . org-open-at-point)
19067 ("?" . org-speed-command-help)
19068 ("<" . (org-agenda-set-restriction-lock 'subtree))
19069 (">" . (org-agenda-remove-restriction-lock))
19071 "The default speed commands.")
19073 (defun org-print-speed-command (e)
19074 (if (> (length (car e)) 1)
19075 (progn
19076 (princ "\n")
19077 (princ (car e))
19078 (princ "\n")
19079 (princ (make-string (length (car e)) ?-))
19080 (princ "\n"))
19081 (princ (car e))
19082 (princ " ")
19083 (if (symbolp (cdr e))
19084 (princ (symbol-name (cdr e)))
19085 (prin1 (cdr e)))
19086 (princ "\n")))
19088 (defun org-speed-command-help ()
19089 "Show the available speed commands."
19090 (interactive)
19091 (if (not org-use-speed-commands)
19092 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19093 (with-output-to-temp-buffer "*Help*"
19094 (princ "User-defined Speed commands\n===========================\n")
19095 (mapc 'org-print-speed-command org-speed-commands-user)
19096 (princ "\n")
19097 (princ "Built-in Speed commands\n=======================\n")
19098 (mapc 'org-print-speed-command org-speed-commands-default))
19099 (with-current-buffer "*Help*"
19100 (setq truncate-lines t))))
19102 (defun org-speed-move-safe (cmd)
19103 "Execute CMD, but make sure that the cursor always ends up in a headline.
19104 If not, return to the original position and throw an error."
19105 (interactive)
19106 (let ((pos (point)))
19107 (call-interactively cmd)
19108 (unless (and (bolp) (org-at-heading-p))
19109 (goto-char pos)
19110 (error "Boundary reached while executing %s" cmd))))
19112 (defvar org-self-insert-command-undo-counter 0)
19114 (defvar org-table-auto-blank-field) ; defined in org-table.el
19115 (defvar org-speed-command nil)
19117 (define-obsolete-function-alias
19118 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19120 (defun org-speed-command-activate (keys)
19121 "Hook for activating single-letter speed commands.
19122 `org-speed-commands-default' specifies a minimal command set.
19123 Use `org-speed-commands-user' for further customization."
19124 (when (or (and (bolp) (looking-at org-outline-regexp))
19125 (and (functionp org-use-speed-commands)
19126 (funcall org-use-speed-commands)))
19127 (cdr (assoc keys (append org-speed-commands-user
19128 org-speed-commands-default)))))
19130 (define-obsolete-function-alias
19131 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19133 (defun org-babel-speed-command-activate (keys)
19134 "Hook for activating single-letter code block commands."
19135 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19136 (cdr (assoc keys org-babel-key-bindings))))
19138 (defcustom org-speed-command-hook
19139 '(org-speed-command-default-hook org-babel-speed-command-hook)
19140 "Hook for activating speed commands at strategic locations.
19141 Hook functions are called in sequence until a valid handler is
19142 found.
19144 Each hook takes a single argument, a user-pressed command key
19145 which is also a `self-insert-command' from the global map.
19147 Within the hook, examine the cursor position and the command key
19148 and return nil or a valid handler as appropriate. Handler could
19149 be one of an interactive command, a function, or a form.
19151 Set `org-use-speed-commands' to non-nil value to enable this
19152 hook. The default setting is `org-speed-command-activate'."
19153 :group 'org-structure
19154 :version "24.1"
19155 :type 'hook)
19157 (defun org-self-insert-command (N)
19158 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19159 If the cursor is in a table looking at whitespace, the whitespace is
19160 overwritten, and the table is not marked as requiring realignment."
19161 (interactive "p")
19162 (org-check-before-invisible-edit 'insert)
19163 (cond
19164 ((and org-use-speed-commands
19165 (setq org-speed-command
19166 (run-hook-with-args-until-success
19167 'org-speed-command-hook (this-command-keys))))
19168 (cond
19169 ((commandp org-speed-command)
19170 (setq this-command org-speed-command)
19171 (call-interactively org-speed-command))
19172 ((functionp org-speed-command)
19173 (funcall org-speed-command))
19174 ((and org-speed-command (listp org-speed-command))
19175 (eval org-speed-command))
19176 (t (let (org-use-speed-commands)
19177 (call-interactively 'org-self-insert-command)))))
19178 ((and
19179 (org-table-p)
19180 (progn
19181 ;; check if we blank the field, and if that triggers align
19182 (and (featurep 'org-table) org-table-auto-blank-field
19183 (member last-command
19184 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19185 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19186 ;; got extra space, this field does not determine column width
19187 (let (org-table-may-need-update) (org-table-blank-field))
19188 ;; no extra space, this field may determine column width
19189 (org-table-blank-field)))
19191 (eq N 1)
19192 (looking-at "[^|\n]* |"))
19193 (let (org-table-may-need-update)
19194 (goto-char (1- (match-end 0)))
19195 (backward-delete-char 1)
19196 (goto-char (match-beginning 0))
19197 (self-insert-command N)))
19199 (setq org-table-may-need-update t)
19200 (self-insert-command N)
19201 (org-fix-tags-on-the-fly)
19202 (if org-self-insert-cluster-for-undo
19203 (if (not (eq last-command 'org-self-insert-command))
19204 (setq org-self-insert-command-undo-counter 1)
19205 (if (>= org-self-insert-command-undo-counter 20)
19206 (setq org-self-insert-command-undo-counter 1)
19207 (and (> org-self-insert-command-undo-counter 0)
19208 buffer-undo-list (listp buffer-undo-list)
19209 (not (cadr buffer-undo-list)) ; remove nil entry
19210 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19211 (setq org-self-insert-command-undo-counter
19212 (1+ org-self-insert-command-undo-counter))))))))
19214 (defun org-check-before-invisible-edit (kind)
19215 "Check is editing if kind KIND would be dangerous with invisible text around.
19216 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19217 ;; First, try to get out of here as quickly as possible, to reduce overhead
19218 (if (and org-catch-invisible-edits
19219 (or (not (boundp 'visible-mode)) (not visible-mode))
19220 (or (get-char-property (point) 'invisible)
19221 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19222 ;; OK, we need to take a closer look
19223 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19224 (invisible-before-point (if (bobp) nil (get-char-property
19225 (1- (point)) 'invisible)))
19226 (border-and-ok-direction
19228 ;; Check if we are acting predictably before invisible text
19229 (and invisible-at-point (not invisible-before-point)
19230 (memq kind '(insert delete-backward)))
19231 ;; Check if we are acting predictably after invisible text
19232 ;; This works not well, and I have turned it off. It seems
19233 ;; better to always show and stop after invisible text.
19234 ;; (and (not invisible-at-point) invisible-before-point
19235 ;; (memq kind '(insert delete)))
19237 (when (or (memq invisible-at-point '(outline org-hide-block t))
19238 (memq invisible-before-point '(outline org-hide-block t)))
19239 (if (eq org-catch-invisible-edits 'error)
19240 (error "Editing in invisible areas is prohibited - make visible first"))
19241 (if (and org-custom-properties-overlays
19242 (y-or-n-p "Display invisible properties in this buffer? "))
19243 (org-toggle-custom-properties-visibility)
19244 ;; Make the area visible
19245 (save-excursion
19246 (if invisible-before-point
19247 (goto-char (previous-single-char-property-change
19248 (point) 'invisible)))
19249 (org-cycle))
19250 (cond
19251 ((eq org-catch-invisible-edits 'show)
19252 ;; That's it, we do the edit after showing
19253 (message
19254 "Unfolding invisible region around point before editing")
19255 (sit-for 1))
19256 ((and (eq org-catch-invisible-edits 'smart)
19257 border-and-ok-direction)
19258 (message "Unfolding invisible region around point before editing"))
19260 ;; Don't do the edit, make the user repeat it in full visibility
19261 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19263 (defun org-fix-tags-on-the-fly ()
19264 (when (and (equal (char-after (point-at-bol)) ?*)
19265 (org-at-heading-p))
19266 (org-align-tags-here org-tags-column)))
19268 (defun org-delete-backward-char (N)
19269 "Like `delete-backward-char', insert whitespace at field end in tables.
19270 When deleting backwards, in tables this function will insert whitespace in
19271 front of the next \"|\" separator, to keep the table aligned. The table will
19272 still be marked for re-alignment if the field did fill the entire column,
19273 because, in this case the deletion might narrow the column."
19274 (interactive "p")
19275 (save-match-data
19276 (org-check-before-invisible-edit 'delete-backward)
19277 (if (and (org-table-p)
19278 (eq N 1)
19279 (string-match "|" (buffer-substring (point-at-bol) (point)))
19280 (looking-at ".*?|"))
19281 (let ((pos (point))
19282 (noalign (looking-at "[^|\n\r]* |"))
19283 (c org-table-may-need-update))
19284 (backward-delete-char N)
19285 (if (not overwrite-mode)
19286 (progn
19287 (skip-chars-forward "^|")
19288 (insert " ")
19289 (goto-char (1- pos))))
19290 ;; noalign: if there were two spaces at the end, this field
19291 ;; does not determine the width of the column.
19292 (if noalign (setq org-table-may-need-update c)))
19293 (backward-delete-char N)
19294 (org-fix-tags-on-the-fly))))
19296 (defun org-delete-char (N)
19297 "Like `delete-char', but insert whitespace at field end in tables.
19298 When deleting characters, in tables this function will insert whitespace in
19299 front of the next \"|\" separator, to keep the table aligned. The table will
19300 still be marked for re-alignment if the field did fill the entire column,
19301 because, in this case the deletion might narrow the column."
19302 (interactive "p")
19303 (save-match-data
19304 (org-check-before-invisible-edit 'delete)
19305 (if (and (org-table-p)
19306 (not (bolp))
19307 (not (= (char-after) ?|))
19308 (eq N 1))
19309 (if (looking-at ".*?|")
19310 (let ((pos (point))
19311 (noalign (looking-at "[^|\n\r]* |"))
19312 (c org-table-may-need-update))
19313 (replace-match
19314 (concat (substring (match-string 0) 1 -1) " |") nil t)
19315 (goto-char pos)
19316 ;; noalign: if there were two spaces at the end, this field
19317 ;; does not determine the width of the column.
19318 (if noalign (setq org-table-may-need-update c)))
19319 (delete-char N))
19320 (delete-char N)
19321 (org-fix-tags-on-the-fly))))
19323 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19324 (put 'org-self-insert-command 'delete-selection t)
19325 (put 'orgtbl-self-insert-command 'delete-selection t)
19326 (put 'org-delete-char 'delete-selection 'supersede)
19327 (put 'org-delete-backward-char 'delete-selection 'supersede)
19328 (put 'org-yank 'delete-selection 'yank)
19330 ;; Make `flyspell-mode' delay after some commands
19331 (put 'org-self-insert-command 'flyspell-delayed t)
19332 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19333 (put 'org-delete-char 'flyspell-delayed t)
19334 (put 'org-delete-backward-char 'flyspell-delayed t)
19336 ;; Make pabbrev-mode expand after org-mode commands
19337 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19338 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19340 ;; How to do this: Measure non-white length of current string
19341 ;; If equal to column width, we should realign.
19343 (defun org-remap (map &rest commands)
19344 "In MAP, remap the functions given in COMMANDS.
19345 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19346 (let (new old)
19347 (while commands
19348 (setq old (pop commands) new (pop commands))
19349 (if (fboundp 'command-remapping)
19350 (org-defkey map (vector 'remap old) new)
19351 (substitute-key-definition old new map global-map)))))
19353 (defun org-transpose-words ()
19354 "Transpose words for Org.
19355 This uses the `org-mode-transpose-word-syntax-table' syntax
19356 table, which interprets characters in `org-emphasis-alist' as
19357 word constituants."
19358 (interactive)
19359 (with-syntax-table org-mode-transpose-word-syntax-table
19360 (call-interactively 'transpose-words)))
19361 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19363 (when (eq org-enable-table-editor 'optimized)
19364 ;; If the user wants maximum table support, we need to hijack
19365 ;; some standard editing functions
19366 (org-remap org-mode-map
19367 'self-insert-command 'org-self-insert-command
19368 'delete-char 'org-delete-char
19369 'delete-backward-char 'org-delete-backward-char)
19370 (org-defkey org-mode-map "|" 'org-force-self-insert))
19372 (defvar org-ctrl-c-ctrl-c-hook nil
19373 "Hook for functions attaching themselves to `C-c C-c'.
19375 This can be used to add additional functionality to the C-c C-c
19376 key which executes context-dependent commands. This hook is run
19377 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19378 run after the last test.
19380 Each function will be called with no arguments. The function
19381 must check if the context is appropriate for it to act. If yes,
19382 it should do its thing and then return a non-nil value. If the
19383 context is wrong, just do nothing and return nil.")
19385 (defvar org-ctrl-c-ctrl-c-final-hook nil
19386 "Hook for functions attaching themselves to `C-c C-c'.
19388 This can be used to add additional functionality to the C-c C-c
19389 key which executes context-dependent commands. This hook is run
19390 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19391 before the first test.
19393 Each function will be called with no arguments. The function
19394 must check if the context is appropriate for it to act. If yes,
19395 it should do its thing and then return a non-nil value. If the
19396 context is wrong, just do nothing and return nil.")
19398 (defvar org-tab-first-hook nil
19399 "Hook for functions to attach themselves to TAB.
19400 See `org-ctrl-c-ctrl-c-hook' for more information.
19401 This hook runs as the first action when TAB is pressed, even before
19402 `org-cycle' messes around with the `outline-regexp' to cater for
19403 inline tasks and plain list item folding.
19404 If any function in this hook returns t, any other actions that
19405 would have been caused by TAB (such as table field motion or visibility
19406 cycling) will not occur.")
19408 (defvar org-tab-after-check-for-table-hook nil
19409 "Hook for functions to attach themselves to TAB.
19410 See `org-ctrl-c-ctrl-c-hook' for more information.
19411 This hook runs after it has been established that the cursor is not in a
19412 table, but before checking if the cursor is in a headline or if global cycling
19413 should be done.
19414 If any function in this hook returns t, not other actions like visibility
19415 cycling will be done.")
19417 (defvar org-tab-after-check-for-cycling-hook nil
19418 "Hook for functions to attach themselves to TAB.
19419 See `org-ctrl-c-ctrl-c-hook' for more information.
19420 This hook runs after it has been established that not table field motion and
19421 not visibility should be done because of current context. This is probably
19422 the place where a package like yasnippets can hook in.")
19424 (defvar org-tab-before-tab-emulation-hook nil
19425 "Hook for functions to attach themselves to TAB.
19426 See `org-ctrl-c-ctrl-c-hook' for more information.
19427 This hook runs after every other options for TAB have been exhausted, but
19428 before indentation and \t insertion takes place.")
19430 (defvar org-metaleft-hook nil
19431 "Hook for functions attaching themselves to `M-left'.
19432 See `org-ctrl-c-ctrl-c-hook' for more information.")
19433 (defvar org-metaright-hook nil
19434 "Hook for functions attaching themselves to `M-right'.
19435 See `org-ctrl-c-ctrl-c-hook' for more information.")
19436 (defvar org-metaup-hook nil
19437 "Hook for functions attaching themselves to `M-up'.
19438 See `org-ctrl-c-ctrl-c-hook' for more information.")
19439 (defvar org-metadown-hook nil
19440 "Hook for functions attaching themselves to `M-down'.
19441 See `org-ctrl-c-ctrl-c-hook' for more information.")
19442 (defvar org-shiftmetaleft-hook nil
19443 "Hook for functions attaching themselves to `M-S-left'.
19444 See `org-ctrl-c-ctrl-c-hook' for more information.")
19445 (defvar org-shiftmetaright-hook nil
19446 "Hook for functions attaching themselves to `M-S-right'.
19447 See `org-ctrl-c-ctrl-c-hook' for more information.")
19448 (defvar org-shiftmetaup-hook nil
19449 "Hook for functions attaching themselves to `M-S-up'.
19450 See `org-ctrl-c-ctrl-c-hook' for more information.")
19451 (defvar org-shiftmetadown-hook nil
19452 "Hook for functions attaching themselves to `M-S-down'.
19453 See `org-ctrl-c-ctrl-c-hook' for more information.")
19454 (defvar org-metareturn-hook nil
19455 "Hook for functions attaching themselves to `M-RET'.
19456 See `org-ctrl-c-ctrl-c-hook' for more information.")
19457 (defvar org-shiftup-hook nil
19458 "Hook for functions attaching themselves to `S-up'.
19459 See `org-ctrl-c-ctrl-c-hook' for more information.")
19460 (defvar org-shiftup-final-hook nil
19461 "Hook for functions attaching themselves to `S-up'.
19462 This one runs after all other options except shift-select have been excluded.
19463 See `org-ctrl-c-ctrl-c-hook' for more information.")
19464 (defvar org-shiftdown-hook nil
19465 "Hook for functions attaching themselves to `S-down'.
19466 See `org-ctrl-c-ctrl-c-hook' for more information.")
19467 (defvar org-shiftdown-final-hook nil
19468 "Hook for functions attaching themselves to `S-down'.
19469 This one runs after all other options except shift-select have been excluded.
19470 See `org-ctrl-c-ctrl-c-hook' for more information.")
19471 (defvar org-shiftleft-hook nil
19472 "Hook for functions attaching themselves to `S-left'.
19473 See `org-ctrl-c-ctrl-c-hook' for more information.")
19474 (defvar org-shiftleft-final-hook nil
19475 "Hook for functions attaching themselves to `S-left'.
19476 This one runs after all other options except shift-select have been excluded.
19477 See `org-ctrl-c-ctrl-c-hook' for more information.")
19478 (defvar org-shiftright-hook nil
19479 "Hook for functions attaching themselves to `S-right'.
19480 See `org-ctrl-c-ctrl-c-hook' for more information.")
19481 (defvar org-shiftright-final-hook nil
19482 "Hook for functions attaching themselves to `S-right'.
19483 This one runs after all other options except shift-select have been excluded.
19484 See `org-ctrl-c-ctrl-c-hook' for more information.")
19486 (defun org-modifier-cursor-error ()
19487 "Throw an error, a modified cursor command was applied in wrong context."
19488 (error "This command is active in special context like tables, headlines or items"))
19490 (defun org-shiftselect-error ()
19491 "Throw an error because Shift-Cursor command was applied in wrong context."
19492 (if (and (boundp 'shift-select-mode) shift-select-mode)
19493 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19494 (error "This command works only in special context like headlines or timestamps")))
19496 (defun org-call-for-shift-select (cmd)
19497 (let ((this-command-keys-shift-translated t))
19498 (call-interactively cmd)))
19500 (defun org-shifttab (&optional arg)
19501 "Global visibility cycling or move to previous table field.
19502 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19503 on context.
19504 See the individual commands for more information."
19505 (interactive "P")
19506 (cond
19507 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19508 ((integerp arg)
19509 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19510 (message "Content view to level: %d" arg)
19511 (org-content (prefix-numeric-value arg2))
19512 (setq org-cycle-global-status 'overview)))
19513 (t (call-interactively 'org-global-cycle))))
19515 (defun org-shiftmetaleft ()
19516 "Promote subtree or delete table column.
19517 Calls `org-promote-subtree', `org-outdent-item-tree', or
19518 `org-table-delete-column', depending on context. See the
19519 individual commands for more information."
19520 (interactive)
19521 (cond
19522 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19523 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19524 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19525 ((if (not (org-region-active-p)) (org-at-item-p)
19526 (save-excursion (goto-char (region-beginning))
19527 (org-at-item-p)))
19528 (call-interactively 'org-outdent-item-tree))
19529 (t (org-modifier-cursor-error))))
19531 (defun org-shiftmetaright ()
19532 "Demote subtree or insert table column.
19533 Calls `org-demote-subtree', `org-indent-item-tree', or
19534 `org-table-insert-column', depending on context. See the
19535 individual commands for more information."
19536 (interactive)
19537 (cond
19538 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19539 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19540 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19541 ((if (not (org-region-active-p)) (org-at-item-p)
19542 (save-excursion (goto-char (region-beginning))
19543 (org-at-item-p)))
19544 (call-interactively 'org-indent-item-tree))
19545 (t (org-modifier-cursor-error))))
19547 (defun org-shiftmetaup (&optional arg)
19548 "Move subtree up or kill table row.
19549 Calls `org-move-subtree-up' or `org-table-kill-row' or
19550 `org-move-item-up' or `org-timestamp-up', depending on context.
19551 See the individual commands for more information."
19552 (interactive "P")
19553 (cond
19554 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19555 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19556 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19557 ((org-at-item-p) (call-interactively 'org-move-item-up))
19558 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19559 (call-interactively 'org-timestamp-up)))
19560 (t (call-interactively 'org-drag-line-backward))))
19562 (defun org-shiftmetadown (&optional arg)
19563 "Move subtree down or insert table row.
19564 Calls `org-move-subtree-down' or `org-table-insert-row' or
19565 `org-move-item-down' or `org-timestamp-up', depending on context.
19566 See the individual commands for more information."
19567 (interactive "P")
19568 (cond
19569 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19570 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19571 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19572 ((org-at-item-p) (call-interactively 'org-move-item-down))
19573 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19574 (call-interactively 'org-timestamp-down)))
19575 (t (call-interactively 'org-drag-line-forward))))
19577 (defsubst org-hidden-tree-error ()
19578 (error
19579 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19581 (defun org-metaleft (&optional arg)
19582 "Promote heading or move table column to left.
19583 Calls `org-do-promote' or `org-table-move-column', depending on context.
19584 With no specific context, calls the Emacs default `backward-word'.
19585 See the individual commands for more information."
19586 (interactive "P")
19587 (cond
19588 ((run-hook-with-args-until-success 'org-metaleft-hook))
19589 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19590 ((org-with-limited-levels
19591 (or (org-at-heading-p)
19592 (and (org-region-active-p)
19593 (save-excursion
19594 (goto-char (region-beginning))
19595 (org-at-heading-p)))))
19596 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19597 (call-interactively 'org-do-promote))
19598 ;; At an inline task.
19599 ((org-at-heading-p)
19600 (call-interactively 'org-inlinetask-promote))
19601 ((or (org-at-item-p)
19602 (and (org-region-active-p)
19603 (save-excursion
19604 (goto-char (region-beginning))
19605 (org-at-item-p))))
19606 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19607 (call-interactively 'org-outdent-item))
19608 (t (call-interactively 'backward-word))))
19610 (defun org-metaright (&optional arg)
19611 "Demote a subtree, a list item or move table column to right.
19612 In front of a drawer or a block keyword, indent it correctly.
19613 With no specific context, calls the Emacs default `forward-word'.
19614 See the individual commands for more information."
19615 (interactive "P")
19616 (cond
19617 ((run-hook-with-args-until-success 'org-metaright-hook))
19618 ((org-at-table-p) (call-interactively 'org-table-move-column))
19619 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19620 ((org-at-block-p) (call-interactively 'org-indent-block))
19621 ((org-with-limited-levels
19622 (or (org-at-heading-p)
19623 (and (org-region-active-p)
19624 (save-excursion
19625 (goto-char (region-beginning))
19626 (org-at-heading-p)))))
19627 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19628 (call-interactively 'org-do-demote))
19629 ;; At an inline task.
19630 ((org-at-heading-p)
19631 (call-interactively 'org-inlinetask-demote))
19632 ((or (org-at-item-p)
19633 (and (org-region-active-p)
19634 (save-excursion
19635 (goto-char (region-beginning))
19636 (org-at-item-p))))
19637 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19638 (call-interactively 'org-indent-item))
19639 (t (call-interactively 'forward-word))))
19641 (defun org-check-for-hidden (what)
19642 "Check if there are hidden headlines/items in the current visual line.
19643 WHAT can be either `headlines' or `items'. If the current line is
19644 an outline or item heading and it has a folded subtree below it,
19645 this function returns t, nil otherwise."
19646 (let ((re (cond
19647 ((eq what 'headlines) org-outline-regexp-bol)
19648 ((eq what 'items) (org-item-beginning-re))
19649 (t (error "This should not happen"))))
19650 beg end)
19651 (save-excursion
19652 (catch 'exit
19653 (unless (org-region-active-p)
19654 (setq beg (point-at-bol))
19655 (beginning-of-line 2)
19656 (while (and (not (eobp)) ;; this is like `next-line'
19657 (get-char-property (1- (point)) 'invisible))
19658 (beginning-of-line 2))
19659 (setq end (point))
19660 (goto-char beg)
19661 (goto-char (point-at-eol))
19662 (setq end (max end (point)))
19663 (while (re-search-forward re end t)
19664 (if (get-char-property (match-beginning 0) 'invisible)
19665 (throw 'exit t))))
19666 nil))))
19668 (defun org-metaup (&optional arg)
19669 "Move subtree up or move table row up.
19670 Calls `org-move-subtree-up' or `org-table-move-row' or
19671 `org-move-item-up', depending on context. See the individual commands
19672 for more information."
19673 (interactive "P")
19674 (cond
19675 ((run-hook-with-args-until-success 'org-metaup-hook))
19676 ((org-region-active-p)
19677 (let* ((a (min (region-beginning) (region-end)))
19678 (b (1- (max (region-beginning) (region-end))))
19679 (c (save-excursion (goto-char a)
19680 (move-beginning-of-line 0)))
19681 (d (save-excursion (goto-char a)
19682 (move-end-of-line 0) (point))))
19683 (transpose-regions a b c d)
19684 (goto-char c)))
19685 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19686 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19687 ((org-at-item-p) (call-interactively 'org-move-item-up))
19688 (t (org-drag-element-backward))))
19690 (defun org-metadown (&optional arg)
19691 "Move subtree down or move table row down.
19692 Calls `org-move-subtree-down' or `org-table-move-row' or
19693 `org-move-item-down', depending on context. See the individual
19694 commands for more information."
19695 (interactive "P")
19696 (cond
19697 ((run-hook-with-args-until-success 'org-metadown-hook))
19698 ((org-region-active-p)
19699 (let* ((a (min (region-beginning) (region-end)))
19700 (b (max (region-beginning) (region-end)))
19701 (c (save-excursion (goto-char b)
19702 (move-beginning-of-line 1)))
19703 (d (save-excursion (goto-char b)
19704 (move-end-of-line 1) (1+ (point)))))
19705 (transpose-regions a b c d)
19706 (goto-char d)))
19707 ((org-at-table-p) (call-interactively 'org-table-move-row))
19708 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19709 ((org-at-item-p) (call-interactively 'org-move-item-down))
19710 (t (org-drag-element-forward))))
19712 (defun org-shiftup (&optional arg)
19713 "Increase item in timestamp or increase priority of current headline.
19714 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19715 depending on context. See the individual commands for more information."
19716 (interactive "P")
19717 (cond
19718 ((run-hook-with-args-until-success 'org-shiftup-hook))
19719 ((and org-support-shift-select (org-region-active-p))
19720 (org-call-for-shift-select 'previous-line))
19721 ((org-at-timestamp-p t)
19722 (call-interactively (if org-edit-timestamp-down-means-later
19723 'org-timestamp-down 'org-timestamp-up)))
19724 ((and (not (eq org-support-shift-select 'always))
19725 org-enable-priority-commands
19726 (org-at-heading-p))
19727 (call-interactively 'org-priority-up))
19728 ((and (not org-support-shift-select) (org-at-item-p))
19729 (call-interactively 'org-previous-item))
19730 ((org-clocktable-try-shift 'up arg))
19731 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19732 (org-support-shift-select
19733 (org-call-for-shift-select 'previous-line))
19734 (t (org-shiftselect-error))))
19736 (defun org-shiftdown (&optional arg)
19737 "Decrease item in timestamp or decrease priority of current headline.
19738 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19739 depending on context. See the individual commands for more information."
19740 (interactive "P")
19741 (cond
19742 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19743 ((and org-support-shift-select (org-region-active-p))
19744 (org-call-for-shift-select 'next-line))
19745 ((org-at-timestamp-p t)
19746 (call-interactively (if org-edit-timestamp-down-means-later
19747 'org-timestamp-up 'org-timestamp-down)))
19748 ((and (not (eq org-support-shift-select 'always))
19749 org-enable-priority-commands
19750 (org-at-heading-p))
19751 (call-interactively 'org-priority-down))
19752 ((and (not org-support-shift-select) (org-at-item-p))
19753 (call-interactively 'org-next-item))
19754 ((org-clocktable-try-shift 'down arg))
19755 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19756 (org-support-shift-select
19757 (org-call-for-shift-select 'next-line))
19758 (t (org-shiftselect-error))))
19760 (defun org-shiftright (&optional arg)
19761 "Cycle the thing at point or in the current line, depending on context.
19762 Depending on context, this does one of the following:
19764 - switch a timestamp at point one day into the future
19765 - on a headline, switch to the next TODO keyword.
19766 - on an item, switch entire list to the next bullet type
19767 - on a property line, switch to the next allowed value
19768 - on a clocktable definition line, move time block into the future"
19769 (interactive "P")
19770 (cond
19771 ((run-hook-with-args-until-success 'org-shiftright-hook))
19772 ((and org-support-shift-select (org-region-active-p))
19773 (org-call-for-shift-select 'forward-char))
19774 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19775 ((and (not (eq org-support-shift-select 'always))
19776 (org-at-heading-p))
19777 (let ((org-inhibit-logging
19778 (not org-treat-S-cursor-todo-selection-as-state-change))
19779 (org-inhibit-blocking
19780 (not org-treat-S-cursor-todo-selection-as-state-change)))
19781 (org-call-with-arg 'org-todo 'right)))
19782 ((or (and org-support-shift-select
19783 (not (eq org-support-shift-select 'always))
19784 (org-at-item-bullet-p))
19785 (and (not org-support-shift-select) (org-at-item-p)))
19786 (org-call-with-arg 'org-cycle-list-bullet nil))
19787 ((and (not (eq org-support-shift-select 'always))
19788 (org-at-property-p))
19789 (call-interactively 'org-property-next-allowed-value))
19790 ((org-clocktable-try-shift 'right arg))
19791 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19792 (org-support-shift-select
19793 (org-call-for-shift-select 'forward-char))
19794 (t (org-shiftselect-error))))
19796 (defun org-shiftleft (&optional arg)
19797 "Cycle the thing at point or in the current line, depending on context.
19798 Depending on context, this does one of the following:
19800 - switch a timestamp at point one day into the past
19801 - on a headline, switch to the previous TODO keyword.
19802 - on an item, switch entire list to the previous bullet type
19803 - on a property line, switch to the previous allowed value
19804 - on a clocktable definition line, move time block into the past"
19805 (interactive "P")
19806 (cond
19807 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19808 ((and org-support-shift-select (org-region-active-p))
19809 (org-call-for-shift-select 'backward-char))
19810 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19811 ((and (not (eq org-support-shift-select 'always))
19812 (org-at-heading-p))
19813 (let ((org-inhibit-logging
19814 (not org-treat-S-cursor-todo-selection-as-state-change))
19815 (org-inhibit-blocking
19816 (not org-treat-S-cursor-todo-selection-as-state-change)))
19817 (org-call-with-arg 'org-todo 'left)))
19818 ((or (and org-support-shift-select
19819 (not (eq org-support-shift-select 'always))
19820 (org-at-item-bullet-p))
19821 (and (not org-support-shift-select) (org-at-item-p)))
19822 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19823 ((and (not (eq org-support-shift-select 'always))
19824 (org-at-property-p))
19825 (call-interactively 'org-property-previous-allowed-value))
19826 ((org-clocktable-try-shift 'left arg))
19827 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19828 (org-support-shift-select
19829 (org-call-for-shift-select 'backward-char))
19830 (t (org-shiftselect-error))))
19832 (defun org-shiftcontrolright ()
19833 "Switch to next TODO set."
19834 (interactive)
19835 (cond
19836 ((and org-support-shift-select (org-region-active-p))
19837 (org-call-for-shift-select 'forward-word))
19838 ((and (not (eq org-support-shift-select 'always))
19839 (org-at-heading-p))
19840 (org-call-with-arg 'org-todo 'nextset))
19841 (org-support-shift-select
19842 (org-call-for-shift-select 'forward-word))
19843 (t (org-shiftselect-error))))
19845 (defun org-shiftcontrolleft ()
19846 "Switch to previous TODO set."
19847 (interactive)
19848 (cond
19849 ((and org-support-shift-select (org-region-active-p))
19850 (org-call-for-shift-select 'backward-word))
19851 ((and (not (eq org-support-shift-select 'always))
19852 (org-at-heading-p))
19853 (org-call-with-arg 'org-todo 'previousset))
19854 (org-support-shift-select
19855 (org-call-for-shift-select 'backward-word))
19856 (t (org-shiftselect-error))))
19858 (defun org-shiftcontrolup (&optional n)
19859 "Change timestamps synchronously up in CLOCK log lines.
19860 Optional argument N tells to change by that many units."
19861 (interactive "P")
19862 (cond ((and (not org-support-shift-select)
19863 (org-at-clock-log-p)
19864 (org-at-timestamp-p t))
19865 (org-clock-timestamps-up n))
19866 (t (org-shiftselect-error))))
19868 (defun org-shiftcontroldown (&optional n)
19869 "Change timestamps synchronously down in CLOCK log lines.
19870 Optional argument N tells to change by that many units."
19871 (interactive "P")
19872 (cond ((and (not org-support-shift-select)
19873 (org-at-clock-log-p)
19874 (org-at-timestamp-p t))
19875 (org-clock-timestamps-down n))
19876 (t (org-shiftselect-error))))
19878 (defun org-ctrl-c-ret ()
19879 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19880 (interactive)
19881 (cond
19882 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19883 (t (call-interactively 'org-insert-heading))))
19885 (defun org-find-visible ()
19886 (let ((s (point)))
19887 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19888 (get-char-property s 'invisible)))
19890 (defun org-find-invisible ()
19891 (let ((s (point)))
19892 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19893 (not (get-char-property s 'invisible))))
19896 (defun org-copy-visible (beg end)
19897 "Copy the visible parts of the region."
19898 (interactive "r")
19899 (let (snippets s)
19900 (save-excursion
19901 (save-restriction
19902 (narrow-to-region beg end)
19903 (setq s (goto-char (point-min)))
19904 (while (not (= (point) (point-max)))
19905 (goto-char (org-find-invisible))
19906 (push (buffer-substring s (point)) snippets)
19907 (setq s (goto-char (org-find-visible))))))
19908 (kill-new (apply 'concat (nreverse snippets)))))
19910 (defun org-copy-special ()
19911 "Copy region in table or copy current subtree.
19912 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19913 See the individual commands for more information."
19914 (interactive)
19915 (call-interactively
19916 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19918 (defun org-cut-special ()
19919 "Cut region in table or cut current subtree.
19920 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19921 See the individual commands for more information."
19922 (interactive)
19923 (call-interactively
19924 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19926 (defun org-paste-special (arg)
19927 "Paste rectangular region into table, or past subtree relative to level.
19928 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19929 See the individual commands for more information."
19930 (interactive "P")
19931 (if (org-at-table-p)
19932 (org-table-paste-rectangle)
19933 (org-paste-subtree arg)))
19935 (defsubst org-in-fixed-width-region-p ()
19936 "Is point in a fixed-width region?"
19937 (save-match-data
19938 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19940 (defun org-edit-special (&optional arg)
19941 "Call a special editor for the element at point.
19942 When at a table, call the formula editor with `org-table-edit-formulas'.
19943 When in a source code block, call `org-edit-src-code'.
19944 When in a fixed-width region, call `org-edit-fixed-width-region'.
19945 When at an #+INCLUDE keyword, visit the included file.
19946 On a link, call `ffap' to visit the link at point.
19947 Otherwise, return a user error."
19948 (interactive "P")
19949 (let ((element (org-element-at-point)))
19950 (assert (not buffer-read-only) nil
19951 "Buffer is read-only: %s" (buffer-name))
19952 (case (org-element-type element)
19953 (src-block
19954 (if (not arg) (org-edit-src-code)
19955 (let* ((info (org-babel-get-src-block-info))
19956 (lang (nth 0 info))
19957 (params (nth 2 info))
19958 (session (cdr (assq :session params))))
19959 (if (not session) (org-edit-src-code)
19960 ;; At a src-block with a session and function called with
19961 ;; an ARG: switch to the buffer related to the inferior
19962 ;; process.
19963 (switch-to-buffer
19964 (funcall (intern (concat "org-babel-prep-session:" lang))
19965 session params))))))
19966 (keyword
19967 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19968 (find-file
19969 (org-remove-double-quotes
19970 (car (org-split-string (org-element-property :value element)))))
19971 (user-error "No special environment to edit here")))
19972 (table
19973 (if (eq (org-element-property :type element) 'table.el)
19974 (org-edit-src-code)
19975 (call-interactively 'org-table-edit-formulas)))
19976 ;; Only Org tables contain `table-row' type elements.
19977 (table-row (call-interactively 'org-table-edit-formulas))
19978 ((example-block export-block) (org-edit-src-code))
19979 (fixed-width (org-edit-fixed-width-region))
19980 (otherwise
19981 ;; No notable element at point. Though, we may be at a link,
19982 ;; which is an object. Thus, scan deeper.
19983 (if (eq (org-element-type (org-element-context element)) 'link)
19984 (call-interactively 'ffap)
19985 (user-error "No special environment to edit here"))))))
19987 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19988 (defun org-ctrl-c-ctrl-c (&optional arg)
19989 "Set tags in headline, or update according to changed information at point.
19991 This command does many different things, depending on context:
19993 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19994 this is what we do.
19996 - If the cursor is on a statistics cookie, update it.
19998 - If the cursor is in a headline, prompt for tags and insert them
19999 into the current line, aligned to `org-tags-column'. When called
20000 with prefix arg, realign all tags in the current buffer.
20002 - If the cursor is in one of the special #+KEYWORD lines, this
20003 triggers scanning the buffer for these lines and updating the
20004 information.
20006 - If the cursor is inside a table, realign the table. This command
20007 works even if the automatic table editor has been turned off.
20009 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20010 the entire table.
20012 - If the cursor is at a footnote reference or definition, jump to
20013 the corresponding definition or references, respectively.
20015 - If the cursor is a the beginning of a dynamic block, update it.
20017 - If the current buffer is a capture buffer, close note and file it.
20019 - If the cursor is on a <<<target>>>, update radio targets and
20020 corresponding links in this buffer.
20022 - If the cursor is on a numbered item in a plain list, renumber the
20023 ordered list.
20025 - If the cursor is on a checkbox, toggle it.
20027 - If the cursor is on a code block, evaluate it. The variable
20028 `org-confirm-babel-evaluate' can be used to control prompting
20029 before code block evaluation, by default every code block
20030 evaluation requires confirmation. Code block evaluation can be
20031 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20032 (interactive "P")
20033 (cond
20034 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20035 org-occur-highlights
20036 org-latex-fragment-image-overlays)
20037 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20038 (org-remove-occur-highlights)
20039 (org-remove-latex-fragment-image-overlays)
20040 (message "Temporary highlights/overlays removed from current buffer"))
20041 ((and (local-variable-p 'org-finish-function (current-buffer))
20042 (fboundp org-finish-function))
20043 (funcall org-finish-function))
20044 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20046 (let* ((context (org-element-context)) (type (org-element-type context)))
20047 ;; Test if point is within a blank line.
20048 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20049 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20050 (user-error "C-c C-c can do nothing useful at this location"))
20051 ;; For convenience: at the first line of a paragraph on the
20052 ;; same line as an item, apply function on that item instead.
20053 (when (eq type 'paragraph)
20054 (let ((parent (org-element-property :parent context)))
20055 (when (and (eq (org-element-type parent) 'item)
20056 (= (point-at-bol) (org-element-property :begin parent)))
20057 (setq context parent type 'item))))
20058 ;; Act according to type of element or object at point.
20059 (case type
20060 (clock (org-clock-update-time-maybe))
20061 (dynamic-block
20062 (save-excursion
20063 (goto-char (org-element-property :post-affiliated context))
20064 (org-update-dblock)))
20065 (footnote-definition
20066 (goto-char (org-element-property :post-affiliated context))
20067 (call-interactively 'org-footnote-action))
20068 (footnote-reference (call-interactively 'org-footnote-action))
20069 ((headline inlinetask)
20070 (save-excursion (goto-char (org-element-property :begin context))
20071 (call-interactively 'org-set-tags)))
20072 (item
20073 ;; At an item: a double C-u set checkbox to "[-]"
20074 ;; unconditionally, whereas a single one will toggle its
20075 ;; presence. Without an universal argument, if the item
20076 ;; has a checkbox, toggle it. Otherwise repair the list.
20077 (let* ((box (org-element-property :checkbox context))
20078 (struct (org-element-property :structure context))
20079 (old-struct (copy-tree struct))
20080 (parents (org-list-parents-alist struct))
20081 (prevs (org-list-prevs-alist struct))
20082 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20083 (org-list-set-checkbox
20084 (org-element-property :begin context) struct
20085 (cond ((equal arg '(16)) "[-]")
20086 ((and (not box) (equal arg '(4))) "[ ]")
20087 ((or (not box) (equal arg '(4))) nil)
20088 ((eq box 'on) "[ ]")
20089 (t "[X]")))
20090 ;; Mimic `org-list-write-struct' but with grabbing
20091 ;; a return value from `org-list-struct-fix-box'.
20092 (org-list-struct-fix-ind struct parents 2)
20093 (org-list-struct-fix-item-end struct)
20094 (org-list-struct-fix-bul struct prevs)
20095 (org-list-struct-fix-ind struct parents)
20096 (let ((block-item
20097 (org-list-struct-fix-box struct parents prevs orderedp)))
20098 (if (and box (equal struct old-struct))
20099 (if (equal arg '(16))
20100 (message "Checkboxes already reset")
20101 (user-error "Cannot toggle this checkbox: %s"
20102 (if (eq box 'on)
20103 "all subitems checked"
20104 "unchecked subitems")))
20105 (org-list-struct-apply-struct struct old-struct)
20106 (org-update-checkbox-count-maybe))
20107 (when block-item
20108 (message "Checkboxes were removed due to empty box at line %d"
20109 (org-current-line block-item))))))
20110 (keyword
20111 (let ((org-inhibit-startup-visibility-stuff t)
20112 (org-startup-align-all-tables nil))
20113 (when (boundp 'org-table-coordinate-overlays)
20114 (mapc 'delete-overlay org-table-coordinate-overlays)
20115 (setq org-table-coordinate-overlays nil))
20116 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20117 (message "Local setup has been refreshed"))
20118 (plain-list
20119 ;; At a plain list, with a double C-u argument, set
20120 ;; checkboxes of each item to "[-]", whereas a single one
20121 ;; will toggle their presence according to the state of the
20122 ;; first item in the list. Without an argument, repair the
20123 ;; list.
20124 (let* ((begin (org-element-property :contents-begin context))
20125 (struct (org-element-property :structure context))
20126 (old-struct (copy-tree struct))
20127 (first-box (save-excursion
20128 (goto-char begin)
20129 (looking-at org-list-full-item-re)
20130 (match-string-no-properties 3)))
20131 (new-box (cond ((equal arg '(16)) "[-]")
20132 ((equal arg '(4)) (unless first-box "[ ]"))
20133 ((equal first-box "[X]") "[ ]")
20134 (t "[X]"))))
20135 (cond
20136 (arg
20137 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20138 (org-list-get-all-items
20139 begin struct (org-list-prevs-alist struct))))
20140 ((and first-box (eq (point) begin))
20141 ;; For convenience, when point is at bol on the first
20142 ;; item of the list and no argument is provided, simply
20143 ;; toggle checkbox of that item, if any.
20144 (org-list-set-checkbox begin struct new-box)))
20145 (org-list-write-struct
20146 struct (org-list-parents-alist struct) old-struct)
20147 (org-update-checkbox-count-maybe)
20148 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
20149 ((property-drawer node-property)
20150 (call-interactively 'org-property-action))
20151 ((radio-target target)
20152 (call-interactively 'org-update-radio-target-regexp))
20153 (statistics-cookie
20154 (call-interactively 'org-update-statistics-cookies))
20155 ((table table-cell table-row)
20156 ;; At a table, recalculate every field and align it. Also
20157 ;; send the table if necessary. If the table has
20158 ;; a `table.el' type, just give up. At a table row or
20159 ;; cell, maybe recalculate line but always align table.
20160 (if (eq (org-element-property :type context) 'table.el)
20161 (message "Use C-c ' to edit table.el tables")
20162 (let ((org-enable-table-editor t))
20163 (if (or (eq type 'table)
20164 ;; Check if point is at a TBLFM line.
20165 (and (eq type 'table-row)
20166 (= (point) (org-element-property :end context))))
20167 (save-excursion
20168 (goto-char (org-element-property :contents-begin context))
20169 (org-call-with-arg 'org-table-recalculate (or arg t))
20170 (orgtbl-send-table 'maybe))
20171 (org-table-maybe-eval-formula)
20172 (cond (arg (call-interactively 'org-table-recalculate))
20173 ((org-table-maybe-recalculate-line))
20174 (t (org-table-align)))))))
20175 (timestamp (org-timestamp-change 0 'day))
20176 (otherwise
20177 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20178 (user-error
20179 "C-c C-c can do nothing useful at this location")))))))))
20181 (defun org-mode-restart ()
20182 "Restart Org-mode, to scan again for special lines.
20183 Also updates the keyword regular expressions."
20184 (interactive)
20185 (org-mode)
20186 (message "Org-mode restarted"))
20188 (defun org-kill-note-or-show-branches ()
20189 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20190 (interactive)
20191 (if (not org-finish-function)
20192 (progn
20193 (hide-subtree)
20194 (call-interactively 'show-branches))
20195 (let ((org-note-abort t))
20196 (funcall org-finish-function))))
20198 (defun org-return (&optional indent)
20199 "Goto next table row or insert a newline.
20200 Calls `org-table-next-row' or `newline', depending on context.
20201 See the individual commands for more information."
20202 (interactive)
20203 (let (org-ts-what)
20204 (cond
20205 ((or (bobp) (org-in-src-block-p))
20206 (if indent (newline-and-indent) (newline)))
20207 ((org-at-table-p)
20208 (org-table-justify-field-maybe)
20209 (call-interactively 'org-table-next-row))
20210 ;; when `newline-and-indent' is called within a list, make sure
20211 ;; text moved stays inside the item.
20212 ((and (org-in-item-p) indent)
20213 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20214 (progn
20215 (save-match-data (newline))
20216 (org-indent-line-to (length (match-string 0))))
20217 (let ((ind (org-get-indentation)))
20218 (newline)
20219 (if (org-looking-back org-list-end-re)
20220 (org-indent-line)
20221 (org-indent-line-to ind)))))
20222 ((and org-return-follows-link
20223 (org-at-timestamp-p t)
20224 (not (eq org-ts-what 'after)))
20225 (org-follow-timestamp-link))
20226 ((and org-return-follows-link
20227 (let ((tprop (get-text-property (point) 'face)))
20228 (or (eq tprop 'org-link)
20229 (and (listp tprop) (memq 'org-link tprop)))))
20230 (call-interactively 'org-open-at-point))
20231 ((and (org-at-heading-p)
20232 (looking-at
20233 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20234 (org-show-entry)
20235 (end-of-line 1)
20236 (newline))
20237 (t (if indent (newline-and-indent) (newline))))))
20239 (defun org-return-indent ()
20240 "Goto next table row or insert a newline and indent.
20241 Calls `org-table-next-row' or `newline-and-indent', depending on
20242 context. See the individual commands for more information."
20243 (interactive)
20244 (org-return t))
20246 (defun org-ctrl-c-star ()
20247 "Compute table, or change heading status of lines.
20248 Calls `org-table-recalculate' or `org-toggle-heading',
20249 depending on context."
20250 (interactive)
20251 (cond
20252 ((org-at-table-p)
20253 (call-interactively 'org-table-recalculate))
20255 ;; Convert all lines in region to list items
20256 (call-interactively 'org-toggle-heading))))
20258 (defun org-ctrl-c-minus ()
20259 "Insert separator line in table or modify bullet status of line.
20260 Also turns a plain line or a region of lines into list items.
20261 Calls `org-table-insert-hline', `org-toggle-item', or
20262 `org-cycle-list-bullet', depending on context."
20263 (interactive)
20264 (cond
20265 ((org-at-table-p)
20266 (call-interactively 'org-table-insert-hline))
20267 ((org-region-active-p)
20268 (call-interactively 'org-toggle-item))
20269 ((org-in-item-p)
20270 (call-interactively 'org-cycle-list-bullet))
20272 (call-interactively 'org-toggle-item))))
20274 (defun org-toggle-item (arg)
20275 "Convert headings or normal lines to items, items to normal lines.
20276 If there is no active region, only the current line is considered.
20278 If the first non blank line in the region is a headline, convert
20279 all headlines to items, shifting text accordingly.
20281 If it is an item, convert all items to normal lines.
20283 If it is normal text, change region into a list of items.
20284 With a prefix argument ARG, change the region in a single item."
20285 (interactive "P")
20286 (let ((shift-text
20287 (function
20288 ;; Shift text in current section to IND, from point to END.
20289 ;; The function leaves point to END line.
20290 (lambda (ind end)
20291 (let ((min-i 1000) (end (copy-marker end)))
20292 ;; First determine the minimum indentation (MIN-I) of
20293 ;; the text.
20294 (save-excursion
20295 (catch 'exit
20296 (while (< (point) end)
20297 (let ((i (org-get-indentation)))
20298 (cond
20299 ;; Skip blank lines and inline tasks.
20300 ((looking-at "^[ \t]*$"))
20301 ((looking-at org-outline-regexp-bol))
20302 ;; We can't find less than 0 indentation.
20303 ((zerop i) (throw 'exit (setq min-i 0)))
20304 ((< i min-i) (setq min-i i))))
20305 (forward-line))))
20306 ;; Then indent each line so that a line indented to
20307 ;; MIN-I becomes indented to IND. Ignore blank lines
20308 ;; and inline tasks in the process.
20309 (let ((delta (- ind min-i)))
20310 (while (< (point) end)
20311 (unless (or (looking-at "^[ \t]*$")
20312 (looking-at org-outline-regexp-bol))
20313 (org-indent-line-to (+ (org-get-indentation) delta)))
20314 (forward-line)))))))
20315 (skip-blanks
20316 (function
20317 ;; Return beginning of first non-blank line, starting from
20318 ;; line at POS.
20319 (lambda (pos)
20320 (save-excursion
20321 (goto-char pos)
20322 (skip-chars-forward " \r\t\n")
20323 (point-at-bol)))))
20324 beg end)
20325 ;; Determine boundaries of changes.
20326 (if (org-region-active-p)
20327 (setq beg (funcall skip-blanks (region-beginning))
20328 end (copy-marker (region-end)))
20329 (setq beg (funcall skip-blanks (point-at-bol))
20330 end (copy-marker (point-at-eol))))
20331 ;; Depending on the starting line, choose an action on the text
20332 ;; between BEG and END.
20333 (org-with-limited-levels
20334 (save-excursion
20335 (goto-char beg)
20336 (cond
20337 ;; Case 1. Start at an item: de-itemize. Note that it only
20338 ;; happens when a region is active: `org-ctrl-c-minus'
20339 ;; would call `org-cycle-list-bullet' otherwise.
20340 ((org-at-item-p)
20341 (while (< (point) end)
20342 (when (org-at-item-p)
20343 (skip-chars-forward " \t")
20344 (delete-region (point) (match-end 0)))
20345 (forward-line)))
20346 ;; Case 2. Start at an heading: convert to items.
20347 ((org-at-heading-p)
20348 (let* ((bul (org-list-bullet-string "-"))
20349 (bul-len (length bul))
20350 ;; Indentation of the first heading. It should be
20351 ;; relative to the indentation of its parent, if any.
20352 (start-ind (save-excursion
20353 (cond
20354 ((not org-adapt-indentation) 0)
20355 ((not (outline-previous-heading)) 0)
20356 (t (length (match-string 0))))))
20357 ;; Level of first heading. Further headings will be
20358 ;; compared to it to determine hierarchy in the list.
20359 (ref-level (org-reduced-level (org-outline-level))))
20360 (while (< (point) end)
20361 (let* ((level (org-reduced-level (org-outline-level)))
20362 (delta (max 0 (- level ref-level))))
20363 ;; If current headline is less indented than the first
20364 ;; one, set it as reference, in order to preserve
20365 ;; subtrees.
20366 (when (< level ref-level) (setq ref-level level))
20367 (replace-match bul t t)
20368 (org-indent-line-to (+ start-ind (* delta bul-len)))
20369 ;; Ensure all text down to END (or SECTION-END) belongs
20370 ;; to the newly created item.
20371 (let ((section-end (save-excursion
20372 (or (outline-next-heading) (point)))))
20373 (forward-line)
20374 (funcall shift-text
20375 (+ start-ind (* (1+ delta) bul-len))
20376 (min end section-end)))))))
20377 ;; Case 3. Normal line with ARG: make the first line of region
20378 ;; an item, and shift indentation of others lines to
20379 ;; set them as item's body.
20380 (arg (let* ((bul (org-list-bullet-string "-"))
20381 (bul-len (length bul))
20382 (ref-ind (org-get-indentation)))
20383 (skip-chars-forward " \t")
20384 (insert bul)
20385 (forward-line)
20386 (while (< (point) end)
20387 ;; Ensure that lines less indented than first one
20388 ;; still get included in item body.
20389 (funcall shift-text
20390 (+ ref-ind bul-len)
20391 (min end (save-excursion (or (outline-next-heading)
20392 (point)))))
20393 (forward-line))))
20394 ;; Case 4. Normal line without ARG: turn each non-item line
20395 ;; into an item.
20397 (while (< (point) end)
20398 (unless (or (org-at-heading-p) (org-at-item-p))
20399 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20400 (replace-match
20401 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20402 (forward-line))))))))
20404 (defun org-toggle-heading (&optional nstars)
20405 "Convert headings to normal text, or items or text to headings.
20406 If there is no active region, only convert the current line.
20408 With a \\[universal-argument] prefix, convert the whole list at
20409 point into heading.
20411 In a region:
20413 - If the first non blank line is a headline, remove the stars
20414 from all headlines in the region.
20416 - If it is a normal line, turn each and every normal line (i.e.,
20417 not an heading or an item) in the region into headings. If you
20418 want to convert only the first line of this region, use one
20419 universal prefix argument.
20421 - If it is a plain list item, turn all plain list items into headings.
20423 When converting a line into a heading, the number of stars is chosen
20424 such that the lines become children of the current entry. However,
20425 when a numeric prefix argument is given, its value determines the
20426 number of stars to add."
20427 (interactive "P")
20428 (let ((skip-blanks
20429 (function
20430 ;; Return beginning of first non-blank line, starting from
20431 ;; line at POS.
20432 (lambda (pos)
20433 (save-excursion
20434 (goto-char pos)
20435 (while (org-at-comment-p) (forward-line))
20436 (skip-chars-forward " \r\t\n")
20437 (point-at-bol)))))
20438 beg end toggled)
20439 ;; Determine boundaries of changes. If a universal prefix has
20440 ;; been given, put the list in a region. If region ends at a bol,
20441 ;; do not consider the last line to be in the region.
20443 (when (and current-prefix-arg (org-at-item-p))
20444 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20445 (org-mark-element))
20447 (if (org-region-active-p)
20448 (setq beg (funcall skip-blanks (region-beginning))
20449 end (copy-marker (save-excursion
20450 (goto-char (region-end))
20451 (if (bolp) (point) (point-at-eol)))))
20452 (setq beg (funcall skip-blanks (point-at-bol))
20453 end (copy-marker (point-at-eol))))
20454 ;; Ensure inline tasks don't count as headings.
20455 (org-with-limited-levels
20456 (save-excursion
20457 (goto-char beg)
20458 (cond
20459 ;; Case 1. Started at an heading: de-star headings.
20460 ((org-at-heading-p)
20461 (while (< (point) end)
20462 (when (org-at-heading-p t)
20463 (looking-at org-outline-regexp) (replace-match "")
20464 (setq toggled t))
20465 (forward-line)))
20466 ;; Case 2. Started at an item: change items into headlines.
20467 ;; One star will be added by `org-list-to-subtree'.
20468 ((org-at-item-p)
20469 (let* ((stars (make-string
20470 ;; subtract the star that will be added again by
20471 ;; `org-list-to-subtree'
20472 (if (numberp nstars) (1- nstars)
20473 (or (org-current-level) 0))
20474 ?*))
20475 (add-stars
20476 (cond (nstars "") ; stars from prefix only
20477 ((equal stars "") "") ; before first heading
20478 (org-odd-levels-only "*") ; inside heading, odd
20479 (t "")))) ; inside heading, oddeven
20480 (while (< (point) end)
20481 (when (org-at-item-p)
20482 ;; Pay attention to cases when region ends before list.
20483 (let* ((struct (org-list-struct))
20484 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20485 (save-restriction
20486 (narrow-to-region (point) list-end)
20487 (insert
20488 (org-list-to-subtree
20489 (org-list-parse-list t)
20490 '(:istart (concat stars add-stars (funcall get-stars depth))
20491 :icount (concat stars add-stars (funcall get-stars depth)))))))
20492 (setq toggled t))
20493 (forward-line))))
20494 ;; Case 3. Started at normal text: make every line an heading,
20495 ;; skipping headlines and items.
20496 (t (let* ((stars
20497 (make-string
20498 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20499 (add-stars
20500 (cond (nstars "") ; stars from prefix only
20501 ((equal stars "") "*") ; before first heading
20502 (org-odd-levels-only "**") ; inside heading, odd
20503 (t "*"))) ; inside heading, oddeven
20504 (rpl (concat stars add-stars " "))
20505 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20506 (while (< (point) (if (equal nstars '(4)) lend end))
20507 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20508 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20509 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20510 (forward-line)))))))
20511 (unless toggled (message "Cannot toggle heading from here"))))
20513 (defun org-meta-return (&optional arg)
20514 "Insert a new heading or wrap a region in a table.
20515 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20516 See the individual commands for more information."
20517 (interactive "P")
20518 (cond
20519 ((run-hook-with-args-until-success 'org-metareturn-hook))
20520 ((or (org-at-drawer-p) (org-at-property-p))
20521 (newline-and-indent))
20522 ((org-at-table-p)
20523 (call-interactively 'org-table-wrap-region))
20524 (t (call-interactively 'org-insert-heading))))
20526 ;;; Menu entries
20528 (defsubst org-in-subtree-not-table-p ()
20529 "Are we in a subtree and not in a table?"
20530 (and (not (org-before-first-heading-p))
20531 (not (org-at-table-p))))
20533 ;; Define the Org-mode menus
20534 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20535 '("Tbl"
20536 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20537 ["Next Field" org-cycle (org-at-table-p)]
20538 ["Previous Field" org-shifttab (org-at-table-p)]
20539 ["Next Row" org-return (org-at-table-p)]
20540 "--"
20541 ["Blank Field" org-table-blank-field (org-at-table-p)]
20542 ["Edit Field" org-table-edit-field (org-at-table-p)]
20543 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20544 "--"
20545 ("Column"
20546 ["Move Column Left" org-metaleft (org-at-table-p)]
20547 ["Move Column Right" org-metaright (org-at-table-p)]
20548 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20549 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20550 ("Row"
20551 ["Move Row Up" org-metaup (org-at-table-p)]
20552 ["Move Row Down" org-metadown (org-at-table-p)]
20553 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20554 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20555 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20556 "--"
20557 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20558 ("Rectangle"
20559 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20560 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20561 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20562 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20563 "--"
20564 ("Calculate"
20565 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20566 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20567 ["Edit Formulas" org-edit-special (org-at-table-p)]
20568 "--"
20569 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20570 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20571 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20572 "--"
20573 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20574 "--"
20575 ["Sum Column/Rectangle" org-table-sum
20576 (or (org-at-table-p) (org-region-active-p))]
20577 ["Which Column?" org-table-current-column (org-at-table-p)])
20578 ["Debug Formulas"
20579 org-table-toggle-formula-debugger
20580 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20581 ["Show Col/Row Numbers"
20582 org-table-toggle-coordinate-overlays
20583 :style toggle
20584 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20585 "--"
20586 ["Create" org-table-create (and (not (org-at-table-p))
20587 org-enable-table-editor)]
20588 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20589 ["Import from File" org-table-import (not (org-at-table-p))]
20590 ["Export to File" org-table-export (org-at-table-p)]
20591 "--"
20592 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20594 (easy-menu-define org-org-menu org-mode-map "Org menu"
20595 '("Org"
20596 ("Show/Hide"
20597 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20598 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20599 ["Sparse Tree..." org-sparse-tree t]
20600 ["Reveal Context" org-reveal t]
20601 ["Show All" show-all t]
20602 "--"
20603 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20604 "--"
20605 ["New Heading" org-insert-heading t]
20606 ("Navigate Headings"
20607 ["Up" outline-up-heading t]
20608 ["Next" outline-next-visible-heading t]
20609 ["Previous" outline-previous-visible-heading t]
20610 ["Next Same Level" outline-forward-same-level t]
20611 ["Previous Same Level" outline-backward-same-level t]
20612 "--"
20613 ["Jump" org-goto t])
20614 ("Edit Structure"
20615 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20616 "--"
20617 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20618 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20619 "--"
20620 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20621 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20622 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20623 "--"
20624 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20625 "--"
20626 ["Copy visible text" org-copy-visible t]
20627 "--"
20628 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20629 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20630 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20631 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20632 "--"
20633 ["Sort Region/Children" org-sort t]
20634 "--"
20635 ["Convert to odd levels" org-convert-to-odd-levels t]
20636 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20637 ("Editing"
20638 ["Emphasis..." org-emphasize t]
20639 ["Edit Source Example" org-edit-special t]
20640 "--"
20641 ["Footnote new/jump" org-footnote-action t]
20642 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20643 ("Archive"
20644 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20645 "--"
20646 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20647 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20648 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20650 "--"
20651 ("Hyperlinks"
20652 ["Store Link (Global)" org-store-link t]
20653 ["Find existing link to here" org-occur-link-in-agenda-files t]
20654 ["Insert Link" org-insert-link t]
20655 ["Follow Link" org-open-at-point t]
20656 "--"
20657 ["Next link" org-next-link t]
20658 ["Previous link" org-previous-link t]
20659 "--"
20660 ["Descriptive Links"
20661 org-toggle-link-display
20662 :style radio
20663 :selected org-descriptive-links
20665 ["Literal Links"
20666 org-toggle-link-display
20667 :style radio
20668 :selected (not org-descriptive-links)])
20669 "--"
20670 ("TODO Lists"
20671 ["TODO/DONE/-" org-todo t]
20672 ("Select keyword"
20673 ["Next keyword" org-shiftright (org-at-heading-p)]
20674 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20675 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20676 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20677 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20678 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20679 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20680 "--"
20681 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20682 :selected org-enforce-todo-dependencies :style toggle :active t]
20683 "Settings for tree at point"
20684 ["Do Children sequentially" org-toggle-ordered-property :style radio
20685 :selected (org-entry-get nil "ORDERED")
20686 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20687 ["Do Children parallel" org-toggle-ordered-property :style radio
20688 :selected (not (org-entry-get nil "ORDERED"))
20689 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20690 "--"
20691 ["Set Priority" org-priority t]
20692 ["Priority Up" org-shiftup t]
20693 ["Priority Down" org-shiftdown t]
20694 "--"
20695 ["Get news from all feeds" org-feed-update-all t]
20696 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20697 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20698 ("TAGS and Properties"
20699 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20700 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20701 "--"
20702 ["Set property" org-set-property (not (org-before-first-heading-p))]
20703 ["Column view of properties" org-columns t]
20704 ["Insert Column View DBlock" org-insert-columns-dblock t])
20705 ("Dates and Scheduling"
20706 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20707 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20708 ("Change Date"
20709 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20710 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20711 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20712 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20713 ["Compute Time Range" org-evaluate-time-range t]
20714 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20715 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20716 "--"
20717 ["Custom time format" org-toggle-time-stamp-overlays
20718 :style radio :selected org-display-custom-times]
20719 "--"
20720 ["Goto Calendar" org-goto-calendar t]
20721 ["Date from Calendar" org-date-from-calendar t]
20722 "--"
20723 ["Start/Restart Timer" org-timer-start t]
20724 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20725 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20726 ["Insert Timer String" org-timer t]
20727 ["Insert Timer Item" org-timer-item t])
20728 ("Logging work"
20729 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20730 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20731 ["Clock out" org-clock-out t]
20732 ["Clock cancel" org-clock-cancel t]
20733 "--"
20734 ["Mark as default task" org-clock-mark-default-task t]
20735 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20736 ["Goto running clock" org-clock-goto t]
20737 "--"
20738 ["Display times" org-clock-display t]
20739 ["Create clock table" org-clock-report t]
20740 "--"
20741 ["Record DONE time"
20742 (progn (setq org-log-done (not org-log-done))
20743 (message "Switching to %s will %s record a timestamp"
20744 (car org-done-keywords)
20745 (if org-log-done "automatically" "not")))
20746 :style toggle :selected org-log-done])
20747 "--"
20748 ["Agenda Command..." org-agenda t]
20749 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20750 ("File List for Agenda")
20751 ("Special views current file"
20752 ["TODO Tree" org-show-todo-tree t]
20753 ["Check Deadlines" org-check-deadlines t]
20754 ["Timeline" org-timeline t]
20755 ["Tags/Property tree" org-match-sparse-tree t])
20756 "--"
20757 ["Export/Publish..." org-export-dispatch t]
20758 ("LaTeX"
20759 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20760 :selected org-cdlatex-mode]
20761 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20762 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20763 ["Modify math symbol" org-cdlatex-math-modify
20764 (org-inside-LaTeX-fragment-p)]
20765 ["Insert citation" org-reftex-citation t]
20766 "--"
20767 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20768 "--"
20769 ("MobileOrg"
20770 ["Push Files and Views" org-mobile-push t]
20771 ["Get Captured and Flagged" org-mobile-pull t]
20772 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20773 "--"
20774 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20775 "--"
20776 ("Documentation"
20777 ["Show Version" org-version t]
20778 ["Info Documentation" org-info t])
20779 ("Customize"
20780 ["Browse Org Group" org-customize t]
20781 "--"
20782 ["Expand This Menu" org-create-customize-menu
20783 (fboundp 'customize-menu-create)])
20784 ["Send bug report" org-submit-bug-report t]
20785 "--"
20786 ("Refresh/Reload"
20787 ["Refresh setup current buffer" org-mode-restart t]
20788 ["Reload Org (after update)" org-reload t]
20789 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20792 (defun org-info (&optional node)
20793 "Read documentation for Org-mode in the info system.
20794 With optional NODE, go directly to that node."
20795 (interactive)
20796 (info (format "(org)%s" (or node ""))))
20798 ;;;###autoload
20799 (defun org-submit-bug-report ()
20800 "Submit a bug report on Org-mode via mail.
20802 Don't hesitate to report any problems or inaccurate documentation.
20804 If you don't have setup sending mail from (X)Emacs, please copy the
20805 output buffer into your mail program, as it gives us important
20806 information about your Org-mode version and configuration."
20807 (interactive)
20808 (require 'reporter)
20809 (org-load-modules-maybe)
20810 (org-require-autoloaded-modules)
20811 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20812 (reporter-submit-bug-report
20813 "emacs-orgmode@gnu.org"
20814 (org-version nil 'full)
20815 (let (list)
20816 (save-window-excursion
20817 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20818 (delete-other-windows)
20819 (erase-buffer)
20820 (insert "You are about to submit a bug report to the Org-mode mailing list.
20822 We would like to add your full Org-mode and Outline configuration to the
20823 bug report. This greatly simplifies the work of the maintainer and
20824 other experts on the mailing list.
20826 HOWEVER, some variables you have customized may contain private
20827 information. The names of customers, colleagues, or friends, might
20828 appear in the form of file names, tags, todo states, or search strings.
20829 If you answer yes to the prompt, you might want to check and remove
20830 such private information before sending the email.")
20831 (add-text-properties (point-min) (point-max) '(face org-warning))
20832 (when (yes-or-no-p "Include your Org-mode configuration ")
20833 (mapatoms
20834 (lambda (v)
20835 (and (boundp v)
20836 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20837 (or (and (symbol-value v)
20838 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20839 (and
20840 (get v 'custom-type) (get v 'standard-value)
20841 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20842 (push v list)))))
20843 (kill-buffer (get-buffer "*Warn about privacy*"))
20844 list))
20845 nil nil
20846 "Remember to cover the basics, that is, what you expected to happen and
20847 what in fact did happen. You don't know how to make a good report? See
20849 http://orgmode.org/manual/Feedback.html#Feedback
20851 Your bug report will be posted to the Org-mode mailing list.
20852 ------------------------------------------------------------------------")
20853 (save-excursion
20854 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20855 (replace-match "\\1Bug: \\3 [\\2]")))))
20858 (defun org-install-agenda-files-menu ()
20859 (let ((bl (buffer-list)))
20860 (save-excursion
20861 (while bl
20862 (set-buffer (pop bl))
20863 (if (derived-mode-p 'org-mode) (setq bl nil)))
20864 (when (derived-mode-p 'org-mode)
20865 (easy-menu-change
20866 '("Org") "File List for Agenda"
20867 (append
20868 (list
20869 ["Edit File List" (org-edit-agenda-file-list) t]
20870 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20871 ["Remove Current File from List" org-remove-file t]
20872 ["Cycle through agenda files" org-cycle-agenda-files t]
20873 ["Occur in all agenda files" org-occur-in-agenda-files t]
20874 "--")
20875 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20877 ;;;; Documentation
20879 (defun org-require-autoloaded-modules ()
20880 (interactive)
20881 (mapc 'require
20882 '(org-agenda org-archive org-attach org-clock org-colview org-id
20883 org-remember org-table org-timer)))
20885 ;;;###autoload
20886 (defun org-reload (&optional uncompiled)
20887 "Reload all org lisp files.
20888 With prefix arg UNCOMPILED, load the uncompiled versions."
20889 (interactive "P")
20890 (require 'loadhist)
20891 (let* ((org-dir (org-find-library-dir "org"))
20892 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20893 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20894 (remove-re (mapconcat 'identity
20895 (mapcar (lambda (f) (concat "^" f "$"))
20896 (list (if (featurep 'xemacs)
20897 "org-colview"
20898 "org-colview-xemacs")
20899 "org" "org-loaddefs" "org-version"))
20900 "\\|"))
20901 (feats (delete-dups
20902 (mapcar 'file-name-sans-extension
20903 (mapcar 'file-name-nondirectory
20904 (delq nil
20905 (mapcar 'feature-file
20906 features))))))
20907 (lfeat (append
20908 (sort
20909 (setq feats
20910 (delq nil (mapcar
20911 (lambda (f)
20912 (if (and (string-match feature-re f)
20913 (not (string-match remove-re f)))
20914 f nil))
20915 feats)))
20916 'string-lessp)
20917 (list "org-version" "org")))
20918 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20919 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20920 load-uncore load-misses)
20921 (setq load-misses
20922 (delq 't
20923 (mapcar (lambda (f)
20924 (or (org-load-noerror-mustsuffix (concat org-dir f))
20925 (and (string= org-dir contrib-dir)
20926 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20927 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20928 (add-to-list 'load-uncore f 'append)
20931 lfeat)))
20932 (if load-uncore
20933 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20934 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20935 (if load-misses
20936 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20937 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20938 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20940 ;;;###autoload
20941 (defun org-customize ()
20942 "Call the customize function with org as argument."
20943 (interactive)
20944 (org-load-modules-maybe)
20945 (org-require-autoloaded-modules)
20946 (customize-browse 'org))
20948 (defun org-create-customize-menu ()
20949 "Create a full customization menu for Org-mode, insert it into the menu."
20950 (interactive)
20951 (org-load-modules-maybe)
20952 (org-require-autoloaded-modules)
20953 (if (fboundp 'customize-menu-create)
20954 (progn
20955 (easy-menu-change
20956 '("Org") "Customize"
20957 `(["Browse Org group" org-customize t]
20958 "--"
20959 ,(customize-menu-create 'org)
20960 ["Set" Custom-set t]
20961 ["Save" Custom-save t]
20962 ["Reset to Current" Custom-reset-current t]
20963 ["Reset to Saved" Custom-reset-saved t]
20964 ["Reset to Standard Settings" Custom-reset-standard t]))
20965 (message "\"Org\"-menu now contains full customization menu"))
20966 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20968 ;;;; Miscellaneous stuff
20970 ;;; Generally useful functions
20972 (defun org-get-at-bol (property)
20973 "Get text property PROPERTY at beginning of line."
20974 (get-text-property (point-at-bol) property))
20976 (defun org-find-text-property-in-string (prop s)
20977 "Return the first non-nil value of property PROP in string S."
20978 (or (get-text-property 0 prop s)
20979 (get-text-property (or (next-single-property-change 0 prop s) 0)
20980 prop s)))
20982 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20983 "Display the given MESSAGE as a warning."
20984 (if (fboundp 'display-warning)
20985 (display-warning 'org message
20986 (if (featurep 'xemacs) 'warning :warning))
20987 (let ((buf (get-buffer-create "*Org warnings*")))
20988 (with-current-buffer buf
20989 (goto-char (point-max))
20990 (insert "Warning (Org): " message)
20991 (unless (bolp)
20992 (newline)))
20993 (display-buffer buf)
20994 (sit-for 0))))
20996 (defun org-eval (form)
20997 "Eval FORM and return result."
20998 (condition-case error
20999 (eval form)
21000 (error (format "%%![Error: %s]" error))))
21002 (defun org-in-clocktable-p ()
21003 "Check if the cursor is in a clocktable."
21004 (let ((pos (point)) start)
21005 (save-excursion
21006 (end-of-line 1)
21007 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21008 (setq start (match-beginning 0))
21009 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21010 (>= (match-end 0) pos)
21011 start))))
21013 (defun org-in-commented-line ()
21014 "Is point in a line starting with `#'?"
21015 (equal (char-after (point-at-bol)) ?#))
21017 (defun org-in-indented-comment-line ()
21018 "Is point in a line starting with `#' after some white space?"
21019 (save-excursion
21020 (save-match-data
21021 (goto-char (point-at-bol))
21022 (looking-at "[ \t]*#"))))
21024 (defun org-in-verbatim-emphasis ()
21025 (save-match-data
21026 (and (org-in-regexp org-emph-re 2)
21027 (>= (point) (match-beginning 3))
21028 (<= (point) (match-end 4))
21029 (member (match-string 3) '("=" "~")))))
21031 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21032 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21033 (if (and marker (marker-buffer marker)
21034 (buffer-live-p (marker-buffer marker)))
21035 (progn
21036 (org-pop-to-buffer-same-window (marker-buffer marker))
21037 (if (or (> marker (point-max)) (< marker (point-min)))
21038 (widen))
21039 (goto-char marker)
21040 (org-show-context 'org-goto))
21041 (if bookmark
21042 (bookmark-jump bookmark)
21043 (error "Cannot find location"))))
21045 (defun org-quote-csv-field (s)
21046 "Quote field for inclusion in CSV material."
21047 (if (string-match "[\",]" s)
21048 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21051 (defun org-force-self-insert (N)
21052 "Needed to enforce self-insert under remapping."
21053 (interactive "p")
21054 (self-insert-command N))
21056 (defun org-string-width (s)
21057 "Compute width of string, ignoring invisible characters.
21058 This ignores character with invisibility property `org-link', and also
21059 characters with property `org-cwidth', because these will become invisible
21060 upon the next fontification round."
21061 (let (b l)
21062 (when (or (eq t buffer-invisibility-spec)
21063 (assq 'org-link buffer-invisibility-spec))
21064 (while (setq b (text-property-any 0 (length s)
21065 'invisible 'org-link s))
21066 (setq s (concat (substring s 0 b)
21067 (substring s (or (next-single-property-change
21068 b 'invisible s) (length s)))))))
21069 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21070 (setq s (concat (substring s 0 b)
21071 (substring s (or (next-single-property-change
21072 b 'org-cwidth s) (length s))))))
21073 (setq l (string-width s) b -1)
21074 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21075 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21078 (defun org-shorten-string (s maxlength)
21079 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21080 If the string is shorter or has length MAXLENGTH, just return the
21081 original string. If it is longer, the functions finds a space in the
21082 string, breaks this string off at that locations and adds three dots
21083 as ellipsis. Including the ellipsis, the string will not be longer
21084 than MAXLENGTH. If finding a good breaking point in the string does
21085 not work, the string is just chopped off in the middle of a word
21086 if necessary."
21087 (if (<= (length s) maxlength)
21089 (let* ((n (max (- maxlength 4) 1))
21090 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21091 (if (string-match re s)
21092 (concat (match-string 1 s) "...")
21093 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21095 (defun org-get-indentation (&optional line)
21096 "Get the indentation of the current line, interpreting tabs.
21097 When LINE is given, assume it represents a line and compute its indentation."
21098 (if line
21099 (if (string-match "^ *" (org-remove-tabs line))
21100 (match-end 0))
21101 (save-excursion
21102 (beginning-of-line 1)
21103 (skip-chars-forward " \t")
21104 (current-column))))
21106 (defun org-get-string-indentation (s)
21107 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21108 (let ((n -1) (i 0) (w tab-width) c)
21109 (catch 'exit
21110 (while (< (setq n (1+ n)) (length s))
21111 (setq c (aref s n))
21112 (cond ((= c ?\ ) (setq i (1+ i)))
21113 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21114 (t (throw 'exit t)))))
21117 (defun org-remove-tabs (s &optional width)
21118 "Replace tabulators in S with spaces.
21119 Assumes that s is a single line, starting in column 0."
21120 (setq width (or width tab-width))
21121 (while (string-match "\t" s)
21122 (setq s (replace-match
21123 (make-string
21124 (- (* width (/ (+ (match-beginning 0) width) width))
21125 (match-beginning 0)) ?\ )
21126 t t s)))
21129 (defun org-fix-indentation (line ind)
21130 "Fix indentation in LINE.
21131 IND is a cons cell with target and minimum indentation.
21132 If the current indentation in LINE is smaller than the minimum,
21133 leave it alone. If it is larger than ind, set it to the target."
21134 (let* ((l (org-remove-tabs line))
21135 (i (org-get-indentation l))
21136 (i1 (car ind)) (i2 (cdr ind)))
21137 (if (>= i i2) (setq l (substring line i2)))
21138 (if (> i1 0)
21139 (concat (make-string i1 ?\ ) l)
21140 l)))
21142 (defun org-remove-indentation (code &optional n)
21143 "Remove the maximum common indentation from the lines in CODE.
21144 N may optionally be the number of spaces to remove."
21145 (with-temp-buffer
21146 (insert code)
21147 (org-do-remove-indentation n)
21148 (buffer-string)))
21150 (defun org-do-remove-indentation (&optional n)
21151 "Remove the maximum common indentation from the buffer."
21152 (untabify (point-min) (point-max))
21153 (let ((min 10000) re)
21154 (if n
21155 (setq min n)
21156 (goto-char (point-min))
21157 (while (re-search-forward "^ *[^ \n]" nil t)
21158 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21159 (unless (or (= min 0) (= min 10000))
21160 (setq re (format "^ \\{%d\\}" min))
21161 (goto-char (point-min))
21162 (while (re-search-forward re nil t)
21163 (replace-match "")
21164 (end-of-line 1))
21165 min)))
21167 (defun org-fill-template (template alist)
21168 "Find each %key of ALIST in TEMPLATE and replace it."
21169 (let ((case-fold-search nil)
21170 entry key value)
21171 (setq alist (sort (copy-sequence alist)
21172 (lambda (a b) (< (length (car a)) (length (car b))))))
21173 (while (setq entry (pop alist))
21174 (setq template
21175 (replace-regexp-in-string
21176 (concat "%" (regexp-quote (car entry)))
21177 (or (cdr entry) "") template t t)))
21178 template))
21180 (defun org-base-buffer (buffer)
21181 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21182 (if (not buffer)
21183 buffer
21184 (or (buffer-base-buffer buffer)
21185 buffer)))
21187 (defun org-trim (s)
21188 "Remove whitespace at beginning and end of string."
21189 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21190 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21193 (defun org-wrap (string &optional width lines)
21194 "Wrap string to either a number of lines, or a width in characters.
21195 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21196 that costs. If there is a word longer than WIDTH, the text is actually
21197 wrapped to the length of that word.
21198 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21199 many lines, whatever width that takes.
21200 The return value is a list of lines, without newlines at the end."
21201 (let* ((words (org-split-string string "[ \t\n]+"))
21202 (maxword (apply 'max (mapcar 'org-string-width words)))
21203 w ll)
21204 (cond (width
21205 (org-do-wrap words (max maxword width)))
21206 (lines
21207 (setq w maxword)
21208 (setq ll (org-do-wrap words maxword))
21209 (if (<= (length ll) lines)
21211 (setq ll words)
21212 (while (> (length ll) lines)
21213 (setq w (1+ w))
21214 (setq ll (org-do-wrap words w)))
21215 ll))
21216 (t (error "Cannot wrap this")))))
21218 (defun org-do-wrap (words width)
21219 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21220 (let (lines line)
21221 (while words
21222 (setq line (pop words))
21223 (while (and words (< (+ (length line) (length (car words))) width))
21224 (setq line (concat line " " (pop words))))
21225 (setq lines (push line lines)))
21226 (nreverse lines)))
21228 (defun org-split-string (string &optional separators)
21229 "Splits STRING into substrings at SEPARATORS.
21230 No empty strings are returned if there are matches at the beginning
21231 and end of string."
21232 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21233 (start 0)
21234 notfirst
21235 (list nil))
21236 (while (and (string-match rexp string
21237 (if (and notfirst
21238 (= start (match-beginning 0))
21239 (< start (length string)))
21240 (1+ start) start))
21241 (< (match-beginning 0) (length string)))
21242 (setq notfirst t)
21243 (or (eq (match-beginning 0) 0)
21244 (and (eq (match-beginning 0) (match-end 0))
21245 (eq (match-beginning 0) start))
21246 (setq list
21247 (cons (substring string start (match-beginning 0))
21248 list)))
21249 (setq start (match-end 0)))
21250 (or (eq start (length string))
21251 (setq list
21252 (cons (substring string start)
21253 list)))
21254 (nreverse list)))
21256 (defun org-quote-vert (s)
21257 "Replace \"|\" with \"\\vert\"."
21258 (while (string-match "|" s)
21259 (setq s (replace-match "\\vert" t t s)))
21262 (defun org-uuidgen-p (s)
21263 "Is S an ID created by UUIDGEN?"
21264 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21266 (defun org-in-src-block-p (&optional inside)
21267 "Whether point is in a code source block.
21268 When INSIDE is non-nil, don't consider we are within a src block
21269 when point is at #+BEGIN_SRC or #+END_SRC."
21270 (let ((case-fold-search t) ov)
21271 (or (and (setq ov (overlays-at (point)))
21272 (memq 'org-block-background
21273 (overlay-properties (car ov))))
21274 (and (not inside)
21275 (save-match-data
21276 (save-excursion
21277 (beginning-of-line)
21278 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21280 (defun org-context ()
21281 "Return a list of contexts of the current cursor position.
21282 If several contexts apply, all are returned.
21283 Each context entry is a list with a symbol naming the context, and
21284 two positions indicating start and end of the context. Possible
21285 contexts are:
21287 :headline anywhere in a headline
21288 :headline-stars on the leading stars in a headline
21289 :todo-keyword on a TODO keyword (including DONE) in a headline
21290 :tags on the TAGS in a headline
21291 :priority on the priority cookie in a headline
21292 :item on the first line of a plain list item
21293 :item-bullet on the bullet/number of a plain list item
21294 :checkbox on the checkbox in a plain list item
21295 :table in an org-mode table
21296 :table-special on a special filed in a table
21297 :table-table in a table.el table
21298 :clocktable in a clocktable
21299 :src-block in a source block
21300 :link on a hyperlink
21301 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21302 :target on a <<target>>
21303 :radio-target on a <<<radio-target>>>
21304 :latex-fragment on a LaTeX fragment
21305 :latex-preview on a LaTeX fragment with overlaid preview image
21307 This function expects the position to be visible because it uses font-lock
21308 faces as a help to recognize the following contexts: :table-special, :link,
21309 and :keyword."
21310 (let* ((f (get-text-property (point) 'face))
21311 (faces (if (listp f) f (list f)))
21312 (case-fold-search t)
21313 (p (point)) clist o)
21314 ;; First the large context
21315 (cond
21316 ((org-at-heading-p t)
21317 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21318 (when (progn
21319 (beginning-of-line 1)
21320 (looking-at org-todo-line-tags-regexp))
21321 (push (org-point-in-group p 1 :headline-stars) clist)
21322 (push (org-point-in-group p 2 :todo-keyword) clist)
21323 (push (org-point-in-group p 4 :tags) clist))
21324 (goto-char p)
21325 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21326 (if (looking-at "\\[#[A-Z0-9]\\]")
21327 (push (org-point-in-group p 0 :priority) clist)))
21329 ((org-at-item-p)
21330 (push (org-point-in-group p 2 :item-bullet) clist)
21331 (push (list :item (point-at-bol)
21332 (save-excursion (org-end-of-item) (point)))
21333 clist)
21334 (and (org-at-item-checkbox-p)
21335 (push (org-point-in-group p 0 :checkbox) clist)))
21337 ((org-at-table-p)
21338 (push (list :table (org-table-begin) (org-table-end)) clist)
21339 (if (memq 'org-formula faces)
21340 (push (list :table-special
21341 (previous-single-property-change p 'face)
21342 (next-single-property-change p 'face)) clist)))
21343 ((org-at-table-p 'any)
21344 (push (list :table-table) clist)))
21345 (goto-char p)
21347 (let ((case-fold-search t))
21348 ;; New the "medium" contexts: clocktables, source blocks
21349 (cond ((org-in-clocktable-p)
21350 (push (list :clocktable
21351 (and (or (looking-at "#\\+BEGIN: clocktable")
21352 (search-backward "#+BEGIN: clocktable" nil t))
21353 (match-beginning 0))
21354 (and (re-search-forward "#\\+END:?" nil t)
21355 (match-end 0))) clist))
21356 ((org-in-src-block-p)
21357 (push (list :src-block
21358 (and (or (looking-at "#\\+BEGIN_SRC")
21359 (search-backward "#+BEGIN_SRC" nil t))
21360 (match-beginning 0))
21361 (and (search-forward "#+END_SRC" nil t)
21362 (match-beginning 0))) clist))))
21363 (goto-char p)
21365 ;; Now the small context
21366 (cond
21367 ((org-at-timestamp-p)
21368 (push (org-point-in-group p 0 :timestamp) clist))
21369 ((memq 'org-link faces)
21370 (push (list :link
21371 (previous-single-property-change p 'face)
21372 (next-single-property-change p 'face)) clist))
21373 ((memq 'org-special-keyword faces)
21374 (push (list :keyword
21375 (previous-single-property-change p 'face)
21376 (next-single-property-change p 'face)) clist))
21377 ((org-at-target-p)
21378 (push (org-point-in-group p 0 :target) clist)
21379 (goto-char (1- (match-beginning 0)))
21380 (if (looking-at org-radio-target-regexp)
21381 (push (org-point-in-group p 0 :radio-target) clist))
21382 (goto-char p))
21383 ((setq o (car (delq nil
21384 (mapcar
21385 (lambda (x)
21386 (if (memq x org-latex-fragment-image-overlays) x))
21387 (overlays-at (point))))))
21388 (push (list :latex-fragment
21389 (overlay-start o) (overlay-end o)) clist)
21390 (push (list :latex-preview
21391 (overlay-start o) (overlay-end o)) clist))
21392 ((org-inside-LaTeX-fragment-p)
21393 ;; FIXME: positions wrong.
21394 (push (list :latex-fragment (point) (point)) clist)))
21396 (setq clist (nreverse (delq nil clist)))
21397 clist))
21399 ;; FIXME: Compare with at-regexp-p Do we need both?
21400 (defun org-in-regexp (re &optional nlines visually)
21401 "Check if point is inside a match of regexp.
21402 Normally only the current line is checked, but you can include NLINES extra
21403 lines both before and after point into the search.
21404 If VISUALLY is set, require that the cursor is not after the match but
21405 really on, so that the block visually is on the match."
21406 (catch 'exit
21407 (let ((pos (point))
21408 (eol (point-at-eol (+ 1 (or nlines 0))))
21409 (inc (if visually 1 0)))
21410 (save-excursion
21411 (beginning-of-line (- 1 (or nlines 0)))
21412 (while (re-search-forward re eol t)
21413 (if (and (<= (match-beginning 0) pos)
21414 (>= (+ inc (match-end 0)) pos))
21415 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21417 (defun org-at-regexp-p (regexp)
21418 "Is point inside a match of REGEXP in the current line?"
21419 (catch 'exit
21420 (save-excursion
21421 (let ((pos (point)) (end (point-at-eol)))
21422 (beginning-of-line 1)
21423 (while (re-search-forward regexp end t)
21424 (if (and (<= (match-beginning 0) pos)
21425 (>= (match-end 0) pos))
21426 (throw 'exit t)))
21427 nil))))
21429 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21430 "Non-nil when point is between matches of START-RE and END-RE.
21432 Also return a non-nil value when point is on one of the matches.
21434 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21435 buffer positions. Default values are the positions of headlines
21436 surrounding the point.
21438 The functions returns a cons cell whose car (resp. cdr) is the
21439 position before START-RE (resp. after END-RE)."
21440 (save-match-data
21441 (let ((pos (point))
21442 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21443 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21444 beg end)
21445 (save-excursion
21446 ;; Point is on a block when on START-RE or if START-RE can be
21447 ;; found before it...
21448 (and (or (org-at-regexp-p start-re)
21449 (re-search-backward start-re limit-up t))
21450 (setq beg (match-beginning 0))
21451 ;; ... and END-RE after it...
21452 (goto-char (match-end 0))
21453 (re-search-forward end-re limit-down t)
21454 (> (setq end (match-end 0)) pos)
21455 ;; ... without another START-RE in-between.
21456 (goto-char (match-beginning 0))
21457 (not (re-search-backward start-re (1+ beg) t))
21458 ;; Return value.
21459 (cons beg end))))))
21461 (defun org-in-block-p (names)
21462 "Non-nil when point belongs to a block whose name belongs to NAMES.
21464 NAMES is a list of strings containing names of blocks.
21466 Return first block name matched, or nil. Beware that in case of
21467 nested blocks, the returned name may not belong to the closest
21468 block from point."
21469 (save-match-data
21470 (catch 'exit
21471 (let ((case-fold-search t)
21472 (lim-up (save-excursion (outline-previous-heading)))
21473 (lim-down (save-excursion (outline-next-heading))))
21474 (mapc (lambda (name)
21475 (let ((n (regexp-quote name)))
21476 (when (org-between-regexps-p
21477 (concat "^[ \t]*#\\+begin_" n)
21478 (concat "^[ \t]*#\\+end_" n)
21479 lim-up lim-down)
21480 (throw 'exit n))))
21481 names))
21482 nil)))
21484 (defun org-occur-in-agenda-files (regexp &optional nlines)
21485 "Call `multi-occur' with buffers for all agenda files."
21486 (interactive "sOrg-files matching: \np")
21487 (let* ((files (org-agenda-files))
21488 (tnames (mapcar 'file-truename files))
21489 (extra org-agenda-text-search-extra-files)
21491 (when (eq (car extra) 'agenda-archives)
21492 (setq extra (cdr extra))
21493 (setq files (org-add-archive-files files)))
21494 (while (setq f (pop extra))
21495 (unless (member (file-truename f) tnames)
21496 (add-to-list 'files f 'append)
21497 (add-to-list 'tnames (file-truename f) 'append)))
21498 (multi-occur
21499 (mapcar (lambda (x)
21500 (with-current-buffer
21501 (or (get-file-buffer x) (find-file-noselect x))
21502 (widen)
21503 (current-buffer)))
21504 files)
21505 regexp)))
21507 (if (boundp 'occur-mode-find-occurrence-hook)
21508 ;; Emacs 23
21509 (add-hook 'occur-mode-find-occurrence-hook
21510 (lambda ()
21511 (when (derived-mode-p 'org-mode)
21512 (org-reveal))))
21513 ;; Emacs 22
21514 (defadvice occur-mode-goto-occurrence
21515 (after org-occur-reveal activate)
21516 (and (derived-mode-p 'org-mode) (org-reveal)))
21517 (defadvice occur-mode-goto-occurrence-other-window
21518 (after org-occur-reveal activate)
21519 (and (derived-mode-p 'org-mode) (org-reveal)))
21520 (defadvice occur-mode-display-occurrence
21521 (after org-occur-reveal activate)
21522 (when (derived-mode-p 'org-mode)
21523 (let ((pos (occur-mode-find-occurrence)))
21524 (with-current-buffer (marker-buffer pos)
21525 (save-excursion
21526 (goto-char pos)
21527 (org-reveal)))))))
21529 (defun org-occur-link-in-agenda-files ()
21530 "Create a link and search for it in the agendas.
21531 The link is not stored in `org-stored-links', it is just created
21532 for the search purpose."
21533 (interactive)
21534 (let ((link (condition-case nil
21535 (org-store-link nil)
21536 (error "Unable to create a link to here"))))
21537 (org-occur-in-agenda-files (regexp-quote link))))
21539 (defun org-reverse-string (string)
21540 "Return the reverse of STRING."
21541 (apply 'string (reverse (string-to-list string))))
21543 (defun org-uniquify (list)
21544 "Remove duplicate elements from LIST."
21545 (let (res)
21546 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21547 res))
21549 (defun org-uniquify-alist (alist)
21550 "Merge duplicate elements of an alist.
21552 For example, in this alist:
21554 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21555 => '((a 1 3) (b 2))
21557 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21558 (let (rtn)
21559 (mapc
21560 (lambda (e)
21561 (let (n)
21562 (if (not (assoc (car e) rtn))
21563 (push e rtn)
21564 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21565 (setq rtn (assq-delete-all (car e) rtn))
21566 (push n rtn))))
21567 alist)
21568 rtn))
21570 (defun org-delete-all (elts list)
21571 "Remove all elements in ELTS from LIST."
21572 (while elts
21573 (setq list (delete (pop elts) list)))
21574 list)
21576 (defun org-count (cl-item cl-seq)
21577 "Count the number of occurrences of ITEM in SEQ.
21578 Taken from `count' in cl-seq.el with all keyword arguments removed."
21579 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21580 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21581 (while (< cl-start cl-end)
21582 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21583 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21584 (setq cl-start (1+ cl-start)))
21585 cl-count))
21587 (defun org-remove-if (predicate seq)
21588 "Remove everything from SEQ that fulfills PREDICATE."
21589 (let (res e)
21590 (while seq
21591 (setq e (pop seq))
21592 (if (not (funcall predicate e)) (push e res)))
21593 (nreverse res)))
21595 (defun org-remove-if-not (predicate seq)
21596 "Remove everything from SEQ that does not fulfill PREDICATE."
21597 (let (res e)
21598 (while seq
21599 (setq e (pop seq))
21600 (if (funcall predicate e) (push e res)))
21601 (nreverse res)))
21603 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21604 "Reduce two-argument FUNCTION across SEQ.
21605 Taken from `reduce' in cl-seq.el with all keyword arguments but
21606 \":initial-value\" removed."
21607 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21608 (cadr (memq :initial-value cl-keys)))
21609 (cl-seq (pop cl-seq))
21610 (t (funcall cl-func)))))
21611 (while cl-seq
21612 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21613 cl-accum))
21615 (defun org-back-over-empty-lines ()
21616 "Move backwards over whitespace, to the beginning of the first empty line.
21617 Returns the number of empty lines passed."
21618 (let ((pos (point)))
21619 (if (cdr (assoc 'heading org-blank-before-new-entry))
21620 (skip-chars-backward " \t\n\r")
21621 (unless (eobp)
21622 (forward-line -1)))
21623 (beginning-of-line 2)
21624 (goto-char (min (point) pos))
21625 (count-lines (point) pos)))
21627 (defun org-skip-whitespace ()
21628 (skip-chars-forward " \t\n\r"))
21630 (defun org-point-in-group (point group &optional context)
21631 "Check if POINT is in match-group GROUP.
21632 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21633 match. If the match group does not exist or point is not inside it,
21634 return nil."
21635 (and (match-beginning group)
21636 (>= point (match-beginning group))
21637 (<= point (match-end group))
21638 (if context
21639 (list context (match-beginning group) (match-end group))
21640 t)))
21642 (defun org-switch-to-buffer-other-window (&rest args)
21643 "Switch to buffer in a second window on the current frame.
21644 In particular, do not allow pop-up frames.
21645 Returns the newly created buffer."
21646 (org-no-popups
21647 (apply 'switch-to-buffer-other-window args)))
21649 (defun org-combine-plists (&rest plists)
21650 "Create a single property list from all plists in PLISTS.
21651 The process starts by copying the first list, and then setting properties
21652 from the other lists. Settings in the last list are the most significant
21653 ones and overrule settings in the other lists."
21654 (let ((rtn (copy-sequence (pop plists)))
21655 p v ls)
21656 (while plists
21657 (setq ls (pop plists))
21658 (while ls
21659 (setq p (pop ls) v (pop ls))
21660 (setq rtn (plist-put rtn p v))))
21661 rtn))
21663 (defun org-replace-escapes (string table)
21664 "Replace %-escapes in STRING with values in TABLE.
21665 TABLE is an association list with keys like \"%a\" and string values.
21666 The sequences in STRING may contain normal field width and padding information,
21667 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21668 so values can contain further %-escapes if they are define later in TABLE."
21669 (let ((tbl (copy-alist table))
21670 (case-fold-search nil)
21671 (pchg 0)
21672 e re rpl)
21673 (while (setq e (pop tbl))
21674 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21675 (when (and (cdr e) (string-match re (cdr e)))
21676 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21677 (safe "SREF"))
21678 (add-text-properties 0 3 (list 'sref sref) safe)
21679 (setcdr e (replace-match safe t t (cdr e)))))
21680 (while (string-match re string)
21681 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21682 (cdr e)))
21683 (setq string (replace-match rpl t t string))))
21684 (while (setq pchg (next-property-change pchg string))
21685 (let ((sref (get-text-property pchg 'sref string)))
21686 (when (and sref (string-match "SREF" string pchg))
21687 (setq string (replace-match sref t t string)))))
21688 string))
21690 (defun org-sublist (list start end)
21691 "Return a section of LIST, from START to END.
21692 Counting starts at 1."
21693 (let (rtn (c start))
21694 (setq list (nthcdr (1- start) list))
21695 (while (and list (<= c end))
21696 (push (pop list) rtn)
21697 (setq c (1+ c)))
21698 (nreverse rtn)))
21700 (defun org-find-base-buffer-visiting (file)
21701 "Like `find-buffer-visiting' but always return the base buffer and
21702 not an indirect buffer."
21703 (let ((buf (or (get-file-buffer file)
21704 (find-buffer-visiting file))))
21705 (if buf
21706 (or (buffer-base-buffer buf) buf)
21707 nil)))
21709 (defun org-image-file-name-regexp (&optional extensions)
21710 "Return regexp matching the file names of images.
21711 If EXTENSIONS is given, only match these."
21712 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21713 (image-file-name-regexp)
21714 (let ((image-file-name-extensions
21715 (or extensions
21716 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21717 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21718 (concat "\\."
21719 (regexp-opt (nconc (mapcar 'upcase
21720 image-file-name-extensions)
21721 image-file-name-extensions)
21723 "\\'"))))
21725 (defun org-file-image-p (file &optional extensions)
21726 "Return non-nil if FILE is an image."
21727 (save-match-data
21728 (string-match (org-image-file-name-regexp extensions) file)))
21730 (defun org-get-cursor-date (&optional with-time)
21731 "Return the date at cursor in as a time.
21732 This works in the calendar and in the agenda, anywhere else it just
21733 returns the current time.
21734 If WITH-TIME is non-nil, returns the time of the event at point (in
21735 the agenda) or the current time of the day."
21736 (let (date day defd tp tm hod mod)
21737 (when with-time
21738 (setq tp (get-text-property (point) 'time))
21739 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21740 (setq hod (string-to-number (match-string 1 tp))
21741 mod (string-to-number (match-string 2 tp))))
21742 (or tp (setq hod (nth 2 (decode-time (current-time)))
21743 mod (nth 1 (decode-time (current-time))))))
21744 (cond
21745 ((eq major-mode 'calendar-mode)
21746 (setq date (calendar-cursor-to-date)
21747 defd (encode-time 0 (or mod 0) (or hod 0)
21748 (nth 1 date) (nth 0 date) (nth 2 date))))
21749 ((eq major-mode 'org-agenda-mode)
21750 (setq day (get-text-property (point) 'day))
21751 (if day
21752 (setq date (calendar-gregorian-from-absolute day)
21753 defd (encode-time 0 (or mod 0) (or hod 0)
21754 (nth 1 date) (nth 0 date) (nth 2 date))))))
21755 (or defd (current-time))))
21757 (defun org-mark-subtree (&optional up)
21758 "Mark the current subtree.
21759 This puts point at the start of the current subtree, and mark at
21760 the end. If a numeric prefix UP is given, move up into the
21761 hierarchy of headlines by UP levels before marking the subtree."
21762 (interactive "P")
21763 (org-with-limited-levels
21764 (cond ((org-at-heading-p) (beginning-of-line))
21765 ((org-before-first-heading-p) (error "Not in a subtree"))
21766 (t (outline-previous-visible-heading 1))))
21767 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21768 (if (org-called-interactively-p 'any)
21769 (call-interactively 'org-mark-element)
21770 (org-mark-element)))
21773 ;;; Indentation
21775 (defun org-indent-line ()
21776 "Indent line depending on context."
21777 (interactive)
21778 (let* ((pos (point))
21779 (itemp (org-at-item-p))
21780 (case-fold-search t)
21781 (org-drawer-regexp (or org-drawer-regexp "\000"))
21782 (inline-task-p (and (featurep 'org-inlinetask)
21783 (org-inlinetask-in-task-p)))
21784 (inline-re (and inline-task-p
21785 (org-inlinetask-outline-regexp)))
21786 column)
21787 (if (and orgstruct-is-++ (eq pos (point)))
21788 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21789 (indent-according-to-mode))
21790 (beginning-of-line 1)
21791 (cond
21792 ;; Headings
21793 ((looking-at org-outline-regexp) (setq column 0))
21794 ;; Footnote definition
21795 ((looking-at org-footnote-definition-re) (setq column 0))
21796 ;; Literal examples
21797 ((looking-at "[ \t]*:\\( \\|$\\)")
21798 (setq column (org-get-indentation))) ; do nothing
21799 ;; Lists
21800 ((ignore-errors (goto-char (org-in-item-p)))
21801 (setq column (if itemp
21802 (org-get-indentation)
21803 (org-list-item-body-column (point))))
21804 (goto-char pos))
21805 ;; Drawers
21806 ((and (looking-at "[ \t]*:END:")
21807 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21808 (save-excursion
21809 (goto-char (1- (match-beginning 1)))
21810 (setq column (current-column))))
21811 ;; Special blocks
21812 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21813 (save-excursion
21814 (re-search-backward
21815 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21816 (setq column (org-get-indentation (match-string 0))))
21817 ((and (not (looking-at "[ \t]*#\\+begin_"))
21818 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21819 (save-excursion
21820 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21821 (setq column
21822 (cond ((equal (downcase (match-string 1)) "src")
21823 ;; src blocks: let `org-edit-src-exit' handle them
21824 (org-get-indentation))
21825 ((equal (downcase (match-string 1)) "example")
21826 (max (org-get-indentation)
21827 (org-get-indentation (match-string 0))))
21829 (org-get-indentation (match-string 0))))))
21830 ;; This line has nothing special, look at the previous relevant
21831 ;; line to compute indentation
21833 (beginning-of-line 0)
21834 (while (and (not (bobp))
21835 (not (looking-at org-table-line-regexp))
21836 (not (looking-at org-drawer-regexp))
21837 ;; When point started in an inline task, do not move
21838 ;; above task starting line.
21839 (not (and inline-task-p (looking-at inline-re)))
21840 ;; Skip drawers, blocks, empty lines, verbatim,
21841 ;; comments, tables, footnotes definitions, lists,
21842 ;; inline tasks.
21843 (or (and (looking-at "[ \t]*:END:")
21844 (re-search-backward org-drawer-regexp nil t))
21845 (and (looking-at "[ \t]*#\\+end_")
21846 (re-search-backward "[ \t]*#\\+begin_"nil t))
21847 (looking-at "[ \t]*[\n:#|]")
21848 (looking-at org-footnote-definition-re)
21849 (and (not inline-task-p)
21850 (featurep 'org-inlinetask)
21851 (org-inlinetask-in-task-p)
21852 (or (org-inlinetask-goto-beginning) t))))
21853 (beginning-of-line 0))
21854 (cond
21855 ;; There was a list item above.
21856 ((save-excursion
21857 (and (ignore-errors (goto-char (org-in-item-p)))
21858 (goto-char
21859 (org-list-get-top-point (org-list-struct)))))
21860 (looking-at org-list-full-item-re)
21861 (setq column (length (match-string 0))))
21862 ;; There was an heading above.
21863 ((looking-at "\\*+[ \t]+")
21864 (if (not org-adapt-indentation)
21865 (setq column 0)
21866 (goto-char (match-end 0))
21867 (setq column (current-column))))
21868 ;; A drawer had started and is unfinished
21869 ((looking-at org-drawer-regexp)
21870 (goto-char (1- (match-beginning 1)))
21871 (setq column (current-column)))
21872 ;; Else, nothing noticeable found: get indentation and go on.
21873 (t (setq column (org-get-indentation))))))
21874 ;; Now apply indentation and move cursor accordingly
21875 (goto-char pos)
21876 (if (<= (current-column) (current-indentation))
21877 (org-indent-line-to column)
21878 (save-excursion (org-indent-line-to column)))
21879 ;; Special polishing for properties, see `org-property-format'
21880 (setq column (current-column))
21881 (beginning-of-line 1)
21882 (if (looking-at
21883 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21884 (replace-match (concat (match-string 1)
21885 (format org-property-format
21886 (match-string 2) (match-string 3)))
21887 t t))
21888 (org-move-to-column column))))
21890 (defun org-indent-drawer ()
21891 "Indent the drawer at point."
21892 (interactive)
21893 (let ((p (point))
21894 (e (and (save-excursion (re-search-forward ":END:" nil t))
21895 (match-end 0)))
21896 (folded
21897 (save-excursion
21898 (end-of-line)
21899 (when (overlays-at (point))
21900 (member 'invisible (overlay-properties
21901 (car (overlays-at (point)))))))))
21902 (when folded (org-cycle))
21903 (indent-for-tab-command)
21904 (while (and (move-beginning-of-line 2) (< (point) e))
21905 (indent-for-tab-command))
21906 (goto-char p)
21907 (when folded (org-cycle)))
21908 (message "Drawer at point indented"))
21910 (defun org-indent-block ()
21911 "Indent the block at point."
21912 (interactive)
21913 (let ((p (point))
21914 (case-fold-search t)
21915 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21916 (match-end 0)))
21917 (folded
21918 (save-excursion
21919 (end-of-line)
21920 (when (overlays-at (point))
21921 (member 'invisible (overlay-properties
21922 (car (overlays-at (point)))))))))
21923 (when folded (org-cycle))
21924 (indent-for-tab-command)
21925 (while (and (move-beginning-of-line 2) (< (point) e))
21926 (indent-for-tab-command))
21927 (goto-char p)
21928 (when folded (org-cycle)))
21929 (message "Block at point indented"))
21931 (defun org-indent-region (start end)
21932 "Indent region."
21933 (interactive "r")
21934 (save-excursion
21935 (let ((line-end (org-current-line end)))
21936 (goto-char start)
21937 (while (< (org-current-line) line-end)
21938 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21939 (t (call-interactively 'org-indent-line)))
21940 (move-beginning-of-line 2)))))
21943 ;;; Filling
21945 ;; We use our own fill-paragraph and auto-fill functions.
21947 ;; `org-fill-paragraph' relies on adaptive filling and context
21948 ;; checking. Appropriate `fill-prefix' is computed with
21949 ;; `org-adaptive-fill-function'.
21951 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21952 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21953 ;; `org-adaptive-fill-function' value. Internally,
21954 ;; `org-comment-line-break-function' breaks the line.
21956 ;; `org-setup-filling' installs filling and auto-filling related
21957 ;; variables during `org-mode' initialization.
21959 (defun org-setup-filling ()
21960 (interactive)
21961 ;; Prevent auto-fill from inserting unwanted new items.
21962 (when (boundp 'fill-nobreak-predicate)
21963 (org-set-local
21964 'fill-nobreak-predicate
21965 (org-uniquify
21966 (append fill-nobreak-predicate
21967 '(org-fill-paragraph-separate-nobreak-p
21968 org-fill-line-break-nobreak-p
21969 org-fill-paragraph-with-timestamp-nobreak-p)))))
21970 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21971 (org-set-local 'auto-fill-inhibit-regexp nil)
21972 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21973 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21974 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21976 (defvar org-element-paragraph-separate) ; org-element.el
21977 (defun org-fill-paragraph-separate-nobreak-p ()
21978 "Non-nil when a line break at point would insert a new item."
21979 (looking-at (substring org-element-paragraph-separate 1)))
21981 (defun org-fill-line-break-nobreak-p ()
21982 "Non-nil when a line break at point would create an Org line break."
21983 (save-excursion
21984 (skip-chars-backward "[ \t]")
21985 (skip-chars-backward "\\\\")
21986 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21988 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21989 "Non-nil when a line break at point would insert a new item."
21990 (and (org-at-timestamp-p t)
21991 (not (looking-at org-ts-regexp-both))))
21993 (declare-function message-in-body-p "message" ())
21994 (defvar orgtbl-line-start-regexp) ; From org-table.el
21995 (defun org-adaptive-fill-function ()
21996 "Compute a fill prefix for the current line.
21997 Return fill prefix, as a string, or nil if current line isn't
21998 meant to be filled."
21999 (let (prefix)
22000 (catch 'exit
22001 (when (derived-mode-p 'message-mode)
22002 (save-excursion
22003 (beginning-of-line)
22004 (cond ((or (not (message-in-body-p))
22005 (looking-at orgtbl-line-start-regexp))
22006 (throw 'exit nil))
22007 ((looking-at message-cite-prefix-regexp)
22008 (throw 'exit (match-string-no-properties 0)))
22009 ((looking-at org-outline-regexp)
22010 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22011 (org-with-wide-buffer
22012 (let* ((p (line-beginning-position))
22013 (element (save-excursion (beginning-of-line)
22014 (org-element-at-point)))
22015 (type (org-element-type element))
22016 (post-affiliated (org-element-property :post-affiliated element)))
22017 (unless (and post-affiliated (< p post-affiliated))
22018 (case type
22019 (comment (looking-at "[ \t]*# ?") (match-string 0))
22020 (footnote-definition "")
22021 ((item plain-list)
22022 (make-string (org-list-item-body-column
22023 (or post-affiliated
22024 (org-element-property :begin element)))
22025 ? ))
22026 (paragraph
22027 ;; Fill prefix is usually the same as the current line,
22028 ;; except if the paragraph is at the beginning of an item.
22029 (let ((parent (org-element-property :parent element)))
22030 (cond ((eq (org-element-type parent) 'item)
22031 (make-string (org-list-item-body-column
22032 (org-element-property :begin parent))
22033 ? ))
22034 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22035 (match-string 0))
22036 (t ""))))
22037 (comment-block
22038 ;; Only fill contents if P is within block boundaries.
22039 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22040 (forward-line)
22041 (point)))
22042 (cend (save-excursion
22043 (goto-char (org-element-property :end element))
22044 (skip-chars-backward " \r\t\n")
22045 (line-beginning-position))))
22046 (when (and (>= p cbeg) (< p cend))
22047 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22048 (match-string 0)
22049 "")))))))))))
22051 (declare-function message-goto-body "message" ())
22052 (defvar message-cite-prefix-regexp) ; From message.el
22053 (defun org-fill-paragraph (&optional justify)
22054 "Fill element at point, when applicable.
22056 This function only applies to comment blocks, comments, example
22057 blocks and paragraphs. Also, as a special case, re-align table
22058 when point is at one.
22060 If JUSTIFY is non-nil (interactively, with prefix argument),
22061 justify as well. If `sentence-end-double-space' is non-nil, then
22062 period followed by one space does not end a sentence, so don't
22063 break a line there. The variable `fill-column' controls the
22064 width for filling.
22066 For convenience, when point is at a plain list, an item or
22067 a footnote definition, try to fill the first paragraph within."
22068 (interactive)
22069 (if (and (derived-mode-p 'message-mode)
22070 (or (not (message-in-body-p))
22071 (save-excursion (move-beginning-of-line 1)
22072 (looking-at message-cite-prefix-regexp))))
22073 ;; First ensure filling is correct in message-mode.
22074 (let ((fill-paragraph-function
22075 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22076 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22077 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22078 (paragraph-separate
22079 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22080 (fill-paragraph nil))
22081 (with-syntax-table org-mode-transpose-word-syntax-table
22082 ;; Move to end of line in order to get the first paragraph
22083 ;; within a plain list or a footnote definition.
22084 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22085 ;; First check if point is in a blank line at the beginning of
22086 ;; the buffer. In that case, ignore filling.
22087 (case (org-element-type element)
22088 ;; Use major mode filling function is src blocks.
22089 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22090 ;; Align Org tables, leave table.el tables as-is.
22091 (table-row (org-table-align) t)
22092 (table
22093 (when (eq (org-element-property :type element) 'org)
22094 (org-table-align))
22096 (paragraph
22097 ;; Paragraphs may contain `line-break' type objects.
22098 (let ((beg (max (point-min)
22099 (org-element-property :contents-begin element)))
22100 (end (min (point-max)
22101 (org-element-property :contents-end element))))
22102 ;; Do nothing if point is at an affiliated keyword.
22103 (if (< (line-end-position) beg) t
22104 (when (derived-mode-p 'message-mode)
22105 ;; In `message-mode', do not fill following citation
22106 ;; in current paragraph nor text before message body.
22107 (let ((body-start (save-excursion (message-goto-body))))
22108 (when body-start (setq beg (max body-start beg))))
22109 (when (save-excursion
22110 (re-search-forward
22111 (concat "^" message-cite-prefix-regexp) end t))
22112 (setq end (match-beginning 0))))
22113 ;; Fill paragraph, taking line breaks into account.
22114 ;; For that, slice the paragraph using line breaks as
22115 ;; separators, and fill the parts in reverse order to
22116 ;; avoid messing with markers.
22117 (save-excursion
22118 (goto-char end)
22119 (mapc
22120 (lambda (pos)
22121 (fill-region-as-paragraph pos (point) justify)
22122 (goto-char pos))
22123 ;; Find the list of ending positions for line breaks
22124 ;; in the current paragraph. Add paragraph
22125 ;; beginning to include first slice.
22126 (nreverse
22127 (cons beg
22128 (org-element-map
22129 (org-element--parse-objects
22130 beg end nil (org-element-restriction 'paragraph))
22131 'line-break
22132 (lambda (lb) (org-element-property :end lb)))))))
22133 t)))
22134 ;; Contents of `comment-block' type elements should be
22135 ;; filled as plain text, but only if point is within block
22136 ;; markers.
22137 (comment-block
22138 (let* ((case-fold-search t)
22139 (beg (save-excursion
22140 (goto-char (org-element-property :begin element))
22141 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22142 (forward-line)
22143 (point)))
22144 (end (save-excursion
22145 (goto-char (org-element-property :end element))
22146 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22147 (line-beginning-position))))
22148 (when (and (>= (point) beg) (< (point) end))
22149 (fill-region-as-paragraph
22150 (save-excursion
22151 (end-of-line)
22152 (re-search-backward "^[ \t]*$" beg 'move)
22153 (line-beginning-position))
22154 (save-excursion
22155 (beginning-of-line)
22156 (re-search-forward "^[ \t]*$" end 'move)
22157 (line-beginning-position))
22158 justify)))
22160 ;; Fill comments.
22161 (comment (fill-comment-paragraph justify))
22162 ;; Ignore every other element.
22163 (otherwise t))))))
22165 (defun org-auto-fill-function ()
22166 "Auto-fill function."
22167 ;; Check if auto-filling is meaningful.
22168 (let ((fc (current-fill-column)))
22169 (when (and fc (> (current-column) fc))
22170 (let* ((fill-prefix (org-adaptive-fill-function))
22171 ;; Enforce empty fill prefix, if required. Otherwise, it
22172 ;; will be computed again.
22173 (adaptive-fill-mode (not (equal fill-prefix ""))))
22174 (when fill-prefix (do-auto-fill))))))
22176 (defun org-comment-line-break-function (&optional soft)
22177 "Break line at point and indent, continuing comment if within one.
22178 The inserted newline is marked hard if variable
22179 `use-hard-newlines' is true, unless optional argument SOFT is
22180 non-nil."
22181 (if soft (insert-and-inherit ?\n) (newline 1))
22182 (save-excursion (forward-char -1) (delete-horizontal-space))
22183 (delete-horizontal-space)
22184 (indent-to-left-margin)
22185 (insert-before-markers-and-inherit fill-prefix))
22188 ;;; Comments
22190 ;; Org comments syntax is quite complex. It requires the entire line
22191 ;; to be just a comment. Also, even with the right syntax at the
22192 ;; beginning of line, some some elements (i.e. verse-block or
22193 ;; example-block) don't accept comments. Usual Emacs comment commands
22194 ;; cannot cope with those requirements. Therefore, Org replaces them.
22196 ;; Org still relies on `comment-dwim', but cannot trust
22197 ;; `comment-only-p'. So, `comment-region-function' and
22198 ;; `uncomment-region-function' both point
22199 ;; to`org-comment-or-uncomment-region'. Eventually,
22200 ;; `org-insert-comment' takes care of insertion of comments at the
22201 ;; beginning of line.
22203 ;; `org-setup-comments-handling' install comments related variables
22204 ;; during `org-mode' initialization.
22206 (defun org-setup-comments-handling ()
22207 (interactive)
22208 (org-set-local 'comment-use-syntax nil)
22209 (org-set-local 'comment-start "# ")
22210 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22211 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22212 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22213 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22215 (defun org-insert-comment ()
22216 "Insert an empty comment above current line.
22217 If the line is empty, insert comment at its beginning."
22218 (beginning-of-line)
22219 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22220 (org-indent-line)
22221 (insert "# "))
22223 (defvar comment-empty-lines) ; From newcomment.el.
22224 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22225 "Comment or uncomment each non-blank line in the region.
22226 Uncomment each non-blank line between BEG and END if it only
22227 contains commented lines. Otherwise, comment them."
22228 (save-restriction
22229 ;; Restrict region
22230 (narrow-to-region (save-excursion (goto-char beg)
22231 (skip-chars-forward " \r\t\n" end)
22232 (line-beginning-position))
22233 (save-excursion (goto-char end)
22234 (skip-chars-backward " \r\t\n" beg)
22235 (line-end-position)))
22236 (let ((uncommentp
22237 ;; UNCOMMENTP is non-nil when every non blank line between
22238 ;; BEG and END is a comment.
22239 (save-excursion
22240 (goto-char (point-min))
22241 (while (and (not (eobp))
22242 (let ((element (org-element-at-point)))
22243 (and (eq (org-element-type element) 'comment)
22244 (goto-char (min (point-max)
22245 (org-element-property
22246 :end element)))))))
22247 (eobp))))
22248 (if uncommentp
22249 ;; Only blank lines and comments in region: uncomment it.
22250 (save-excursion
22251 (goto-char (point-min))
22252 (while (not (eobp))
22253 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22254 (replace-match "" nil nil nil 1))
22255 (forward-line)))
22256 ;; Comment each line in region.
22257 (let ((min-indent (point-max)))
22258 ;; First find the minimum indentation across all lines.
22259 (save-excursion
22260 (goto-char (point-min))
22261 (while (and (not (eobp)) (not (zerop min-indent)))
22262 (unless (looking-at "[ \t]*$")
22263 (setq min-indent (min min-indent (current-indentation))))
22264 (forward-line)))
22265 ;; Then loop over all lines.
22266 (save-excursion
22267 (goto-char (point-min))
22268 (while (not (eobp))
22269 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22270 ;; Don't get fooled by invisible text (e.g. link path)
22271 ;; when moving to column MIN-INDENT.
22272 (let ((buffer-invisibility-spec nil))
22273 (org-move-to-column min-indent t))
22274 (insert comment-start))
22275 (forward-line))))))))
22278 ;;; Planning
22280 ;; This section contains tools to operate on timestamp objects, as
22281 ;; returned by, e.g. `org-element-context'.
22283 (defun org-timestamp-has-time-p (timestamp)
22284 "Non-nil when TIMESTAMP has a time specified."
22285 (org-element-property :hour-start timestamp))
22287 (defun org-timestamp-format (timestamp format &optional end utc)
22288 "Format a TIMESTAMP element into a string.
22290 FORMAT is a format specifier to be passed to
22291 `format-time-string'.
22293 When optional argument END is non-nil, use end of date-range or
22294 time-range, if possible.
22296 When optional argument UTC is non-nil, time will be expressed as
22297 Universal Time."
22298 (format-time-string
22299 format
22300 (apply 'encode-time
22301 (cons 0
22302 (mapcar
22303 (lambda (prop) (or (org-element-property prop timestamp) 0))
22304 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22305 '(:minute-start :hour-start :day-start :month-start
22306 :year-start)))))
22307 utc))
22309 (defun org-timestamp-split-range (timestamp &optional end)
22310 "Extract a timestamp object from a date or time range.
22312 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22313 the end of the range. Otherwise, extract its start.
22315 Return a new timestamp object sharing the same parent as
22316 TIMESTAMP."
22317 (let ((type (org-element-property :type timestamp)))
22318 (if (memq type '(active inactive diary)) timestamp
22319 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22320 ;; Set new type.
22321 (org-element-put-property
22322 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22323 ;; Copy start properties over end properties if END is
22324 ;; non-nil. Otherwise, copy end properties over `start' ones.
22325 (let ((p-alist '((:minute-start . :minute-end)
22326 (:hour-start . :hour-end)
22327 (:day-start . :day-end)
22328 (:month-start . :month-end)
22329 (:year-start . :year-end))))
22330 (dolist (p-cell p-alist)
22331 (org-element-put-property
22332 split-ts
22333 (funcall (if end 'car 'cdr) p-cell)
22334 (org-element-property
22335 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22336 ;; Eventually refresh `:raw-value'.
22337 (org-element-put-property split-ts :raw-value nil)
22338 (org-element-put-property
22339 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22341 (defun org-timestamp-translate (timestamp &optional boundary)
22342 "Apply `org-translate-time' on a TIMESTAMP object.
22343 When optional argument BOUNDARY is non-nil, it is either the
22344 symbol `start' or `end'. In this case, only translate the
22345 starting or ending part of TIMESTAMP if it is a date or time
22346 range. Otherwise, translate both parts."
22347 (if (and (not boundary)
22348 (memq (org-element-property :type timestamp)
22349 '(active-range inactive-range)))
22350 (concat
22351 (org-translate-time
22352 (org-element-property :raw-value
22353 (org-timestamp-split-range timestamp)))
22354 "--"
22355 (org-translate-time
22356 (org-element-property :raw-value
22357 (org-timestamp-split-range timestamp t))))
22358 (org-translate-time
22359 (org-element-property
22360 :raw-value
22361 (if (not boundary) timestamp
22362 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22366 ;;; Other stuff.
22368 (defun org-toggle-fixed-width-section (arg)
22369 "Toggle the fixed-width export.
22370 If there is no active region, the QUOTE keyword at the current headline is
22371 inserted or removed. When present, it causes the text between this headline
22372 and the next to be exported as fixed-width text, and unmodified.
22373 If there is an active region, this command adds or removes a colon as the
22374 first character of this line. If the first character of a line is a colon,
22375 this line is also exported in fixed-width font."
22376 (interactive "P")
22377 (let* ((cc 0)
22378 (regionp (org-region-active-p))
22379 (beg (if regionp (region-beginning) (point)))
22380 (end (if regionp (region-end)))
22381 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22382 (case-fold-search nil)
22383 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22384 off)
22385 (if regionp
22386 (save-excursion
22387 (goto-char beg)
22388 (setq cc (current-column))
22389 (beginning-of-line 1)
22390 (setq off (looking-at re))
22391 (while (> nlines 0)
22392 (setq nlines (1- nlines))
22393 (beginning-of-line 1)
22394 (cond
22395 (arg
22396 (org-move-to-column cc t)
22397 (insert ": \n")
22398 (forward-line -1))
22399 ((and off (looking-at re))
22400 (replace-match "" t t nil 1))
22401 ((not off) (org-move-to-column cc t) (insert ": ")))
22402 (forward-line 1)))
22403 (save-excursion
22404 (org-back-to-heading)
22405 (cond
22406 ((looking-at (format org-heading-keyword-regexp-format
22407 org-quote-string))
22408 (goto-char (match-end 1))
22409 (looking-at (concat " +" org-quote-string))
22410 (replace-match "" t t)
22411 (when (eolp) (insert " ")))
22412 ((looking-at org-outline-regexp)
22413 (goto-char (match-end 0))
22414 (insert org-quote-string " ")))))))
22416 (defun org-reftex-citation ()
22417 "Use reftex-citation to insert a citation into the buffer.
22418 This looks for a line like
22420 #+BIBLIOGRAPHY: foo plain option:-d
22422 and derives from it that foo.bib is the bibliography file relevant
22423 for this document. It then installs the necessary environment for RefTeX
22424 to work in this buffer and calls `reftex-citation' to insert a citation
22425 into the buffer.
22427 Export of such citations to both LaTeX and HTML is handled by the contributed
22428 package org-exp-bibtex by Taru Karttunen."
22429 (interactive)
22430 (let ((reftex-docstruct-symbol 'rds)
22431 (reftex-cite-format "\\cite{%l}")
22432 rds bib)
22433 (save-excursion
22434 (save-restriction
22435 (widen)
22436 (let ((case-fold-search t)
22437 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22438 (if (not (save-excursion
22439 (or (re-search-forward re nil t)
22440 (re-search-backward re nil t))))
22441 (error "No bibliography defined in file")
22442 (setq bib (concat (match-string 1) ".bib")
22443 rds (list (list 'bib bib)))))))
22444 (call-interactively 'reftex-citation)))
22446 ;;;; Functions extending outline functionality
22448 (defun org-beginning-of-line (&optional arg)
22449 "Go to the beginning of the current line. If that is invisible, continue
22450 to a visible line beginning. This makes the function of C-a more intuitive.
22451 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22452 first attempt, and only move to after the tags when the cursor is already
22453 beyond the end of the headline."
22454 (interactive "P")
22455 (let ((pos (point))
22456 (special (if (consp org-special-ctrl-a/e)
22457 (car org-special-ctrl-a/e)
22458 org-special-ctrl-a/e))
22459 refpos)
22460 (if (org-bound-and-true-p visual-line-mode)
22461 (beginning-of-visual-line 1)
22462 (beginning-of-line 1))
22463 (if (and arg (fboundp 'move-beginning-of-line))
22464 (call-interactively 'move-beginning-of-line)
22465 (if (bobp)
22467 (backward-char 1)
22468 (if (org-truely-invisible-p)
22469 (while (and (not (bobp)) (org-truely-invisible-p))
22470 (backward-char 1)
22471 (beginning-of-line 1))
22472 (forward-char 1))))
22473 (when special
22474 (cond
22475 ((and (looking-at org-complex-heading-regexp)
22476 (= (char-after (match-end 1)) ?\ ))
22477 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22478 (point-at-eol)))
22479 (goto-char
22480 (if (eq special t)
22481 (cond ((> pos refpos) refpos)
22482 ((= pos (point)) refpos)
22483 (t (point)))
22484 (cond ((> pos (point)) (point))
22485 ((not (eq last-command this-command)) (point))
22486 (t refpos)))))
22487 ((org-at-item-p)
22488 ;; Being at an item and not looking at an the item means point
22489 ;; was previously moved to beginning of a visual line, which
22490 ;; doesn't contain the item. Therefore, do nothing special,
22491 ;; just stay here.
22492 (when (looking-at org-list-full-item-re)
22493 ;; Set special position at first white space character after
22494 ;; bullet, and check-box, if any.
22495 (let ((after-bullet
22496 (let ((box (match-end 3)))
22497 (if (not box) (match-end 1)
22498 (let ((after (char-after box)))
22499 (if (and after (= after ? )) (1+ box) box))))))
22500 ;; Special case: Move point to special position when
22501 ;; currently after it or at beginning of line.
22502 (if (eq special t)
22503 (when (or (> pos after-bullet) (= (point) pos))
22504 (goto-char after-bullet))
22505 ;; Reversed case: Move point to special position when
22506 ;; point was already at beginning of line and command is
22507 ;; repeated.
22508 (when (and (= (point) pos) (eq last-command this-command))
22509 (goto-char after-bullet))))))))
22510 (org-no-warnings
22511 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22513 (defun org-end-of-line (&optional arg)
22514 "Go to the end of the line.
22515 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22516 tags on the first attempt, and only move to after the tags when
22517 the cursor is already beyond the end of the headline."
22518 (interactive "P")
22519 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22520 org-special-ctrl-a/e))
22521 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22522 'end-of-visual-line)
22523 ((fboundp 'move-end-of-line) 'move-end-of-line)
22524 (t 'end-of-line))))
22525 (if (or (not special) arg) (call-interactively move-fun)
22526 (let* ((element (save-excursion (beginning-of-line)
22527 (org-element-at-point)))
22528 (type (org-element-type element)))
22529 (cond
22530 ((memq type '(headline inlinetask))
22531 (let ((pos (point)))
22532 (beginning-of-line 1)
22533 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22534 (if (eq special t)
22535 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22536 (goto-char (match-beginning 1))
22537 (goto-char (match-end 0)))
22538 (if (or (< pos (match-end 0))
22539 (not (eq this-command last-command)))
22540 (goto-char (match-end 0))
22541 (goto-char (match-beginning 1))))
22542 (call-interactively move-fun))))
22543 ((org-element-property :hiddenp element)
22544 ;; If element is hidden, `move-end-of-line' would put point
22545 ;; after it. Use `end-of-line' to stay on current line.
22546 (call-interactively 'end-of-line))
22547 (t (call-interactively move-fun)))))
22548 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22550 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22551 (define-key org-mode-map "\C-e" 'org-end-of-line)
22553 (defun org-backward-sentence (&optional arg)
22554 "Go to beginning of sentence, or beginning of table field.
22555 This will call `backward-sentence' or `org-table-beginning-of-field',
22556 depending on context."
22557 (interactive "P")
22558 (cond
22559 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22560 (t (call-interactively 'backward-sentence))))
22562 (defun org-forward-sentence (&optional arg)
22563 "Go to end of sentence, or end of table field.
22564 This will call `forward-sentence' or `org-table-end-of-field',
22565 depending on context."
22566 (interactive "P")
22567 (cond
22568 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22569 (t (call-interactively 'forward-sentence))))
22571 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22572 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22574 (defun org-kill-line (&optional arg)
22575 "Kill line, to tags or end of line."
22576 (interactive "P")
22577 (cond
22578 ((or (not org-special-ctrl-k)
22579 (bolp)
22580 (not (org-at-heading-p)))
22581 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22582 org-ctrl-k-protect-subtree)
22583 (if (or (eq org-ctrl-k-protect-subtree 'error)
22584 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22585 (error "C-k aborted - would kill hidden subtree")))
22586 (call-interactively
22587 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22588 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22589 (kill-region (point) (match-beginning 1))
22590 (org-set-tags nil t))
22591 (t (kill-region (point) (point-at-eol)))))
22593 (define-key org-mode-map "\C-k" 'org-kill-line)
22595 (defun org-yank (&optional arg)
22596 "Yank. If the kill is a subtree, treat it specially.
22597 This command will look at the current kill and check if is a single
22598 subtree, or a series of subtrees[1]. If it passes the test, and if the
22599 cursor is at the beginning of a line or after the stars of a currently
22600 empty headline, then the yank is handled specially. How exactly depends
22601 on the value of the following variables, both set by default.
22603 org-yank-folded-subtrees
22604 When set, the subtree(s) will be folded after insertion, but only
22605 if doing so would now swallow text after the yanked text.
22607 org-yank-adjusted-subtrees
22608 When set, the subtree will be promoted or demoted in order to
22609 fit into the local outline tree structure, which means that the level
22610 will be adjusted so that it becomes the smaller one of the two
22611 *visible* surrounding headings.
22613 Any prefix to this command will cause `yank' to be called directly with
22614 no special treatment. In particular, a simple \\[universal-argument] prefix \
22615 will just
22616 plainly yank the text as it is.
22618 \[1] The test checks if the first non-white line is a heading
22619 and if there are no other headings with fewer stars."
22620 (interactive "P")
22621 (org-yank-generic 'yank arg))
22623 (defun org-yank-generic (command arg)
22624 "Perform some yank-like command.
22626 This function implements the behavior described in the `org-yank'
22627 documentation. However, it has been generalized to work for any
22628 interactive command with similar behavior."
22630 ;; pretend to be command COMMAND
22631 (setq this-command command)
22633 (if arg
22634 (call-interactively command)
22636 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22637 (and (org-kill-is-subtree-p)
22638 (or (bolp)
22639 (and (looking-at "[ \t]*$")
22640 (string-match
22641 "\\`\\*+\\'"
22642 (buffer-substring (point-at-bol) (point)))))))
22643 swallowp)
22644 (cond
22645 ((and subtreep org-yank-folded-subtrees)
22646 (let ((beg (point))
22647 end)
22648 (if (and subtreep org-yank-adjusted-subtrees)
22649 (org-paste-subtree nil nil 'for-yank)
22650 (call-interactively command))
22652 (setq end (point))
22653 (goto-char beg)
22654 (when (and (bolp) subtreep
22655 (not (setq swallowp
22656 (org-yank-folding-would-swallow-text beg end))))
22657 (org-with-limited-levels
22658 (or (looking-at org-outline-regexp)
22659 (re-search-forward org-outline-regexp-bol end t))
22660 (while (and (< (point) end) (looking-at org-outline-regexp))
22661 (hide-subtree)
22662 (org-cycle-show-empty-lines 'folded)
22663 (condition-case nil
22664 (outline-forward-same-level 1)
22665 (error (goto-char end))))))
22666 (when swallowp
22667 (message
22668 "Inserted text not folded because that would swallow text"))
22670 (goto-char end)
22671 (skip-chars-forward " \t\n\r")
22672 (beginning-of-line 1)
22673 (push-mark beg 'nomsg)))
22674 ((and subtreep org-yank-adjusted-subtrees)
22675 (let ((beg (point-at-bol)))
22676 (org-paste-subtree nil nil 'for-yank)
22677 (push-mark beg 'nomsg)))
22679 (call-interactively command))))))
22681 (defun org-yank-folding-would-swallow-text (beg end)
22682 "Would hide-subtree at BEG swallow any text after END?"
22683 (let (level)
22684 (org-with-limited-levels
22685 (save-excursion
22686 (goto-char beg)
22687 (when (or (looking-at org-outline-regexp)
22688 (re-search-forward org-outline-regexp-bol end t))
22689 (setq level (org-outline-level)))
22690 (goto-char end)
22691 (skip-chars-forward " \t\r\n\v\f")
22692 (if (or (eobp)
22693 (and (bolp) (looking-at org-outline-regexp)
22694 (<= (org-outline-level) level)))
22695 nil ; Nothing would be swallowed
22696 t))))) ; something would swallow
22698 (define-key org-mode-map "\C-y" 'org-yank)
22700 (defun org-truely-invisible-p ()
22701 "Check if point is at a character currently not visible.
22702 This version does not only check the character property, but also
22703 `visible-mode'."
22704 ;; Early versions of noutline don't have `outline-invisible-p'.
22705 (if (org-bound-and-true-p visible-mode)
22707 (outline-invisible-p)))
22709 (defun org-invisible-p2 ()
22710 "Check if point is at a character currently not visible."
22711 (save-excursion
22712 (if (and (eolp) (not (bobp))) (backward-char 1))
22713 ;; Early versions of noutline don't have `outline-invisible-p'.
22714 (outline-invisible-p)))
22716 (defun org-back-to-heading (&optional invisible-ok)
22717 "Call `outline-back-to-heading', but provide a better error message."
22718 (condition-case nil
22719 (outline-back-to-heading invisible-ok)
22720 (error (error "Before first headline at position %d in buffer %s"
22721 (point) (current-buffer)))))
22723 (defun org-before-first-heading-p ()
22724 "Before first heading?"
22725 (save-excursion
22726 (end-of-line)
22727 (null (re-search-backward org-outline-regexp-bol nil t))))
22729 (defun org-at-heading-p (&optional ignored)
22730 (outline-on-heading-p t))
22731 ;; Compatibility alias with Org versions < 7.8.03
22732 (defalias 'org-on-heading-p 'org-at-heading-p)
22734 (defun org-at-comment-p nil
22735 "Is cursor in a line starting with a # character?"
22736 (save-excursion
22737 (beginning-of-line)
22738 (looking-at "^#")))
22740 (defun org-at-drawer-p nil
22741 "Is cursor at a drawer keyword?"
22742 (save-excursion
22743 (move-beginning-of-line 1)
22744 (looking-at org-drawer-regexp)))
22746 (defun org-at-block-p nil
22747 "Is cursor at a block keyword?"
22748 (save-excursion
22749 (move-beginning-of-line 1)
22750 (looking-at org-block-regexp)))
22752 (defun org-point-at-end-of-empty-headline ()
22753 "If point is at the end of an empty headline, return t, else nil.
22754 If the heading only contains a TODO keyword, it is still still considered
22755 empty."
22756 (and (looking-at "[ \t]*$")
22757 (when org-todo-line-regexp
22758 (save-excursion
22759 (beginning-of-line 1)
22760 (let ((case-fold-search nil))
22761 (looking-at org-todo-line-regexp)
22762 (string= (match-string 3) ""))))))
22764 (defun org-at-heading-or-item-p ()
22765 (or (org-at-heading-p) (org-at-item-p)))
22767 (defun org-at-target-p ()
22768 (or (org-in-regexp org-radio-target-regexp)
22769 (org-in-regexp org-target-regexp)))
22770 ;; Compatibility alias with Org versions < 7.8.03
22771 (defalias 'org-on-target-p 'org-at-target-p)
22773 (defun org-up-heading-all (arg)
22774 "Move to the heading line of which the present line is a subheading.
22775 This function considers both visible and invisible heading lines.
22776 With argument, move up ARG levels."
22777 (if (fboundp 'outline-up-heading-all)
22778 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22779 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22781 (defun org-up-heading-safe ()
22782 "Move to the heading line of which the present line is a subheading.
22783 This version will not throw an error. It will return the level of the
22784 headline found, or nil if no higher level is found.
22786 Also, this function will be a lot faster than `outline-up-heading',
22787 because it relies on stars being the outline starters. This can really
22788 make a significant difference in outlines with very many siblings."
22789 (let (start-level re)
22790 (org-back-to-heading t)
22791 (setq start-level (funcall outline-level))
22792 (if (equal start-level 1)
22794 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22795 (if (re-search-backward re nil t)
22796 (funcall outline-level)))))
22798 (defun org-first-sibling-p ()
22799 "Is this heading the first child of its parents?"
22800 (interactive)
22801 (let ((re org-outline-regexp-bol)
22802 level l)
22803 (unless (org-at-heading-p t)
22804 (error "Not at a heading"))
22805 (setq level (funcall outline-level))
22806 (save-excursion
22807 (if (not (re-search-backward re nil t))
22809 (setq l (funcall outline-level))
22810 (< l level)))))
22812 (defun org-goto-sibling (&optional previous)
22813 "Goto the next sibling, even if it is invisible.
22814 When PREVIOUS is set, go to the previous sibling instead. Returns t
22815 when a sibling was found. When none is found, return nil and don't
22816 move point."
22817 (let ((fun (if previous 're-search-backward 're-search-forward))
22818 (pos (point))
22819 (re org-outline-regexp-bol)
22820 level l)
22821 (when (condition-case nil (org-back-to-heading t) (error nil))
22822 (setq level (funcall outline-level))
22823 (catch 'exit
22824 (or previous (forward-char 1))
22825 (while (funcall fun re nil t)
22826 (setq l (funcall outline-level))
22827 (when (< l level) (goto-char pos) (throw 'exit nil))
22828 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22829 (goto-char pos)
22830 nil))))
22832 (defun org-show-siblings ()
22833 "Show all siblings of the current headline."
22834 (save-excursion
22835 (while (org-goto-sibling) (org-flag-heading nil)))
22836 (save-excursion
22837 (while (org-goto-sibling 'previous)
22838 (org-flag-heading nil))))
22840 (defun org-goto-first-child ()
22841 "Goto the first child, even if it is invisible.
22842 Return t when a child was found. Otherwise don't move point and
22843 return nil."
22844 (let (level (pos (point)) (re org-outline-regexp-bol))
22845 (when (condition-case nil (org-back-to-heading t) (error nil))
22846 (setq level (outline-level))
22847 (forward-char 1)
22848 (if (and (re-search-forward re nil t) (> (outline-level) level))
22849 (progn (goto-char (match-beginning 0)) t)
22850 (goto-char pos) nil))))
22852 (defun org-show-hidden-entry ()
22853 "Show an entry where even the heading is hidden."
22854 (save-excursion
22855 (org-show-entry)))
22857 (defun org-flag-heading (flag &optional entry)
22858 "Flag the current heading. FLAG non-nil means make invisible.
22859 When ENTRY is non-nil, show the entire entry."
22860 (save-excursion
22861 (org-back-to-heading t)
22862 ;; Check if we should show the entire entry
22863 (if entry
22864 (progn
22865 (org-show-entry)
22866 (save-excursion
22867 (and (outline-next-heading)
22868 (org-flag-heading nil))))
22869 (outline-flag-region (max (point-min) (1- (point)))
22870 (save-excursion (outline-end-of-heading) (point))
22871 flag))))
22873 (defun org-get-next-sibling ()
22874 "Move to next heading of the same level, and return point.
22875 If there is no such heading, return nil.
22876 This is like outline-next-sibling, but invisible headings are ok."
22877 (let ((level (funcall outline-level)))
22878 (outline-next-heading)
22879 (while (and (not (eobp)) (> (funcall outline-level) level))
22880 (outline-next-heading))
22881 (if (or (eobp) (< (funcall outline-level) level))
22883 (point))))
22885 (defun org-get-last-sibling ()
22886 "Move to previous heading of the same level, and return point.
22887 If there is no such heading, return nil."
22888 (let ((opoint (point))
22889 (level (funcall outline-level)))
22890 (outline-previous-heading)
22891 (when (and (/= (point) opoint) (outline-on-heading-p t))
22892 (while (and (> (funcall outline-level) level)
22893 (not (bobp)))
22894 (outline-previous-heading))
22895 (if (< (funcall outline-level) level)
22897 (point)))))
22899 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22900 "Goto to the end of a subtree."
22901 ;; This contains an exact copy of the original function, but it uses
22902 ;; `org-back-to-heading', to make it work also in invisible
22903 ;; trees. And is uses an invisible-ok argument.
22904 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22905 ;; Furthermore, when used inside Org, finding the end of a large subtree
22906 ;; with many children and grandchildren etc, this can be much faster
22907 ;; than the outline version.
22908 (org-back-to-heading invisible-ok)
22909 (let ((first t)
22910 (level (funcall outline-level)))
22911 (if (and (derived-mode-p 'org-mode) (< level 1000))
22912 ;; A true heading (not a plain list item), in Org-mode
22913 ;; This means we can easily find the end by looking
22914 ;; only for the right number of stars. Using a regexp to do
22915 ;; this is so much faster than using a Lisp loop.
22916 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22917 (forward-char 1)
22918 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22919 ;; something else, do it the slow way
22920 (while (and (not (eobp))
22921 (or first (> (funcall outline-level) level)))
22922 (setq first nil)
22923 (outline-next-heading)))
22924 (unless to-heading
22925 (if (memq (preceding-char) '(?\n ?\^M))
22926 (progn
22927 ;; Go to end of line before heading
22928 (forward-char -1)
22929 (if (memq (preceding-char) '(?\n ?\^M))
22930 ;; leave blank line before heading
22931 (forward-char -1))))))
22932 (point))
22934 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22935 "Use Org version in org-mode, for dramatic speed-up."
22936 (if (derived-mode-p 'org-mode)
22937 (progn
22938 (org-end-of-subtree nil t)
22939 (unless (eobp) (backward-char 1)))
22940 ad-do-it))
22942 (defun org-end-of-meta-data-and-drawers ()
22943 "Jump to the first text after meta data and drawers in the current entry.
22944 This will move over empty lines, lines with planning time stamps,
22945 clocking lines, and drawers."
22946 (org-back-to-heading t)
22947 (let ((end (save-excursion (outline-next-heading) (point)))
22948 (re (concat "\\(" org-drawer-regexp "\\)"
22949 "\\|" "[ \t]*" org-keyword-time-regexp)))
22950 (forward-line 1)
22951 (while (re-search-forward re end t)
22952 (if (not (match-end 1))
22953 ;; empty or planning line
22954 (forward-line 1)
22955 ;; a drawer, find the end
22956 (re-search-forward "^[ \t]*:END:" end 'move)
22957 (forward-line 1)))
22958 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22959 (point)))
22961 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22962 "Move forward to the ARG'th subheading at same level as this one.
22963 Stop at the first and last subheadings of a superior heading.
22964 Normally this only looks at visible headings, but when INVISIBLE-OK is
22965 non-nil it will also look at invisible ones."
22966 (interactive "p")
22967 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22968 (if (and arg (< arg 0))
22969 (goto-char (point-min))
22970 (outline-next-heading))
22971 (org-at-heading-p)
22972 (let ((level (- (match-end 0) (match-beginning 0) 1))
22973 (f (if (and arg (< arg 0))
22974 're-search-backward
22975 're-search-forward))
22976 (count (if arg (abs arg) 1))
22977 (result (point)))
22978 (forward-char (if (and arg (< arg 0)) -1 1))
22979 (while (and (> count 0)
22980 (funcall f org-outline-regexp-bol nil 'move))
22981 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22982 (cond ((< l level) (setq count 0))
22983 ((and (= l level)
22984 (or invisible-ok
22985 (progn
22986 (goto-char (line-beginning-position))
22987 (not (outline-invisible-p)))))
22988 (setq count (1- count))
22989 (when (eq l level)
22990 (setq result (point)))))))
22991 (goto-char result))
22992 (beginning-of-line 1)))
22994 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22995 "Move backward to the ARG'th subheading at same level as this one.
22996 Stop at the first and last subheadings of a superior heading."
22997 (interactive "p")
22998 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23000 (defun org-next-block (arg &optional backward block-regexp)
23001 "Jump to the next block.
23002 With a prefix argument ARG, jump forward ARG many source blocks.
23003 When BACKWARD is non-nil, jump to the previous block.
23004 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23005 (interactive "p")
23006 (let ((re (or block-regexp org-block-regexp))
23007 (re-search-fn (or (and backward 're-search-backward)
23008 're-search-forward)))
23009 (if (looking-at re) (forward-char 1))
23010 (condition-case nil
23011 (funcall re-search-fn re nil nil arg)
23012 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23013 (goto-char (match-beginning 0)) (org-show-context)))
23015 (defun org-previous-block (arg &optional block-regexp)
23016 "Jump to the previous block.
23017 With a prefix argument ARG, jump backward ARG many source blocks.
23018 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23019 (interactive "p")
23020 (org-next-block arg t block-regexp))
23022 (defun org-forward-element ()
23023 "Move forward by one element.
23024 Move to the next element at the same level, when possible."
23025 (interactive)
23026 (cond ((eobp) (user-error "Cannot move further down"))
23027 ((org-with-limited-levels (org-at-heading-p))
23028 (let ((origin (point)))
23029 (goto-char (org-end-of-subtree nil t))
23030 (unless (org-with-limited-levels (org-at-heading-p))
23031 (goto-char origin)
23032 (user-error "Cannot move further down"))))
23034 (let* ((elem (org-element-at-point))
23035 (end (org-element-property :end elem))
23036 (parent (org-element-property :parent elem)))
23037 (if (and parent (= (org-element-property :contents-end parent) end))
23038 (goto-char (org-element-property :end parent))
23039 (goto-char end))))))
23041 (defun org-backward-element ()
23042 "Move backward by one element.
23043 Move to the previous element at the same level, when possible."
23044 (interactive)
23045 (cond ((bobp) (user-error "Cannot move further up"))
23046 ((org-with-limited-levels (org-at-heading-p))
23047 ;; At a headline, move to the previous one, if any, or stay
23048 ;; here.
23049 (let ((origin (point)))
23050 (org-with-limited-levels (org-backward-heading-same-level 1))
23051 ;; When current headline has no sibling above, move to its
23052 ;; parent.
23053 (when (= (point) origin)
23054 (or (org-with-limited-levels (org-up-heading-safe))
23055 (progn (goto-char origin)
23056 (user-error "Cannot move further up"))))))
23058 (let* ((trail (org-element-at-point 'keep-trail))
23059 (elem (car trail))
23060 (prev-elem (nth 1 trail))
23061 (beg (org-element-property :begin elem)))
23062 (cond
23063 ;; Move to beginning of current element if point isn't
23064 ;; there already.
23065 ((/= (point) beg) (goto-char beg))
23066 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23067 ((org-before-first-heading-p) (goto-char (point-min)))
23068 (t (org-back-to-heading)))))))
23070 (defun org-up-element ()
23071 "Move to upper element."
23072 (interactive)
23073 (if (org-with-limited-levels (org-at-heading-p))
23074 (unless (org-up-heading-safe) (error "No surrounding element"))
23075 (let* ((elem (org-element-at-point))
23076 (parent (org-element-property :parent elem)))
23077 (if parent (goto-char (org-element-property :begin parent))
23078 (if (org-with-limited-levels (org-before-first-heading-p))
23079 (error "No surrounding element")
23080 (org-with-limited-levels (org-back-to-heading)))))))
23082 (defvar org-element-greater-elements)
23083 (defun org-down-element ()
23084 "Move to inner element."
23085 (interactive)
23086 (let ((element (org-element-at-point)))
23087 (cond
23088 ((memq (org-element-type element) '(plain-list table))
23089 (goto-char (org-element-property :contents-begin element))
23090 (forward-char))
23091 ((memq (org-element-type element) org-element-greater-elements)
23092 ;; If contents are hidden, first disclose them.
23093 (when (org-element-property :hiddenp element) (org-cycle))
23094 (goto-char (or (org-element-property :contents-begin element)
23095 (error "No content for this element"))))
23096 (t (error "No inner element")))))
23098 (defun org-drag-element-backward ()
23099 "Move backward element at point."
23100 (interactive)
23101 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23102 (let* ((trail (org-element-at-point 'keep-trail))
23103 (elem (car trail))
23104 (prev-elem (nth 1 trail)))
23105 ;; Error out if no previous element or previous element is
23106 ;; a parent of the current one.
23107 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23108 (error "Cannot drag element backward")
23109 (let ((pos (point)))
23110 (org-element-swap-A-B prev-elem elem)
23111 (goto-char (+ (org-element-property :begin prev-elem)
23112 (- pos (org-element-property :begin elem)))))))))
23114 (defun org-drag-element-forward ()
23115 "Move forward element at point."
23116 (interactive)
23117 (let* ((pos (point))
23118 (elem (org-element-at-point)))
23119 (when (= (point-max) (org-element-property :end elem))
23120 (error "Cannot drag element forward"))
23121 (goto-char (org-element-property :end elem))
23122 (let ((next-elem (org-element-at-point)))
23123 (when (or (org-element-nested-p elem next-elem)
23124 (and (eq (org-element-type next-elem) 'headline)
23125 (not (eq (org-element-type elem) 'headline))))
23126 (goto-char pos)
23127 (error "Cannot drag element forward"))
23128 ;; Compute new position of point: it's shifted by NEXT-ELEM
23129 ;; body's length (without final blanks) and by the length of
23130 ;; blanks between ELEM and NEXT-ELEM.
23131 (let ((size-next (- (save-excursion
23132 (goto-char (org-element-property :end next-elem))
23133 (skip-chars-backward " \r\t\n")
23134 (forward-line)
23135 ;; Small correction if buffer doesn't end
23136 ;; with a newline character.
23137 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23138 (org-element-property :begin next-elem)))
23139 (size-blank (- (org-element-property :end elem)
23140 (save-excursion
23141 (goto-char (org-element-property :end elem))
23142 (skip-chars-backward " \r\t\n")
23143 (forward-line)
23144 (point)))))
23145 (org-element-swap-A-B elem next-elem)
23146 (goto-char (+ pos size-next size-blank))))))
23148 (defun org-drag-line-forward (arg)
23149 "Drag the line at point ARG lines forward."
23150 (interactive "p")
23151 (dotimes (n (abs arg))
23152 (let ((c (current-column)))
23153 (if (< 0 arg)
23154 (progn
23155 (beginning-of-line 2)
23156 (transpose-lines 1)
23157 (beginning-of-line 0))
23158 (transpose-lines 1)
23159 (beginning-of-line -1))
23160 (org-move-to-column c))))
23162 (defun org-drag-line-backward (arg)
23163 "Drag the line at point ARG lines backward."
23164 (interactive "p")
23165 (org-drag-line-forward (- arg)))
23167 (defun org-mark-element ()
23168 "Put point at beginning of this element, mark at end.
23170 Interactively, if this command is repeated or (in Transient Mark
23171 mode) if the mark is active, it marks the next element after the
23172 ones already marked."
23173 (interactive)
23174 (let (deactivate-mark)
23175 (if (and (org-called-interactively-p 'any)
23176 (or (and (eq last-command this-command) (mark t))
23177 (and transient-mark-mode mark-active)))
23178 (set-mark
23179 (save-excursion
23180 (goto-char (mark))
23181 (goto-char (org-element-property :end (org-element-at-point)))))
23182 (let ((element (org-element-at-point)))
23183 (end-of-line)
23184 (push-mark (org-element-property :end element) t t)
23185 (goto-char (org-element-property :begin element))))))
23187 (defun org-narrow-to-element ()
23188 "Narrow buffer to current element."
23189 (interactive)
23190 (let ((elem (org-element-at-point)))
23191 (cond
23192 ((eq (car elem) 'headline)
23193 (narrow-to-region
23194 (org-element-property :begin elem)
23195 (org-element-property :end elem)))
23196 ((memq (car elem) org-element-greater-elements)
23197 (narrow-to-region
23198 (org-element-property :contents-begin elem)
23199 (org-element-property :contents-end elem)))
23201 (narrow-to-region
23202 (org-element-property :begin elem)
23203 (org-element-property :end elem))))))
23205 (defun org-transpose-element ()
23206 "Transpose current and previous elements, keeping blank lines between.
23207 Point is moved after both elements."
23208 (interactive)
23209 (org-skip-whitespace)
23210 (let ((end (org-element-property :end (org-element-at-point))))
23211 (org-drag-element-backward)
23212 (goto-char end)))
23214 (defun org-unindent-buffer ()
23215 "Un-indent the visible part of the buffer.
23216 Relative indentation (between items, inside blocks, etc.) isn't
23217 modified."
23218 (interactive)
23219 (unless (eq major-mode 'org-mode)
23220 (error "Cannot un-indent a buffer not in Org mode"))
23221 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23222 unindent-tree ; For byte-compiler.
23223 (unindent-tree
23224 (function
23225 (lambda (contents)
23226 (mapc
23227 (lambda (element)
23228 (if (memq (org-element-type element) '(headline section))
23229 (funcall unindent-tree (org-element-contents element))
23230 (save-excursion
23231 (save-restriction
23232 (narrow-to-region
23233 (org-element-property :begin element)
23234 (org-element-property :end element))
23235 (org-do-remove-indentation)))))
23236 (reverse contents))))))
23237 (funcall unindent-tree (org-element-contents parse-tree))))
23239 (defun org-show-subtree ()
23240 "Show everything after this heading at deeper levels."
23241 (interactive)
23242 (outline-flag-region
23243 (point)
23244 (save-excursion
23245 (org-end-of-subtree t t))
23246 nil))
23248 (defun org-show-entry ()
23249 "Show the body directly following this heading.
23250 Show the heading too, if it is currently invisible."
23251 (interactive)
23252 (save-excursion
23253 (condition-case nil
23254 (progn
23255 (org-back-to-heading t)
23256 (outline-flag-region
23257 (max (point-min) (1- (point)))
23258 (save-excursion
23259 (if (re-search-forward
23260 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23261 (match-beginning 1)
23262 (point-max)))
23263 nil)
23264 (org-cycle-hide-drawers 'children))
23265 (error nil))))
23267 (defun org-make-options-regexp (kwds &optional extra)
23268 "Make a regular expression for keyword lines."
23269 (concat
23270 "^#\\+\\("
23271 (mapconcat 'regexp-quote kwds "\\|")
23272 (if extra (concat "\\|" extra))
23273 "\\):[ \t]*\\(.*\\)"))
23275 ;; Make isearch reveal the necessary context
23276 (defun org-isearch-end ()
23277 "Reveal context after isearch exits."
23278 (when isearch-success ; only if search was successful
23279 (if (featurep 'xemacs)
23280 ;; Under XEmacs, the hook is run in the correct place,
23281 ;; we directly show the context.
23282 (org-show-context 'isearch)
23283 ;; In Emacs the hook runs *before* restoring the overlays.
23284 ;; So we have to use a one-time post-command-hook to do this.
23285 ;; (Emacs 22 has a special variable, see function `org-mode')
23286 (unless (and (boundp 'isearch-mode-end-hook-quit)
23287 isearch-mode-end-hook-quit)
23288 ;; Only when the isearch was not quitted.
23289 (org-add-hook 'post-command-hook 'org-isearch-post-command
23290 'append 'local)))
23291 (org-fix-ellipsis-at-bol)))
23293 (defun org-isearch-post-command ()
23294 "Remove self from hook, and show context."
23295 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23296 (org-show-context 'isearch))
23299 ;;;; Integration with and fixes for other packages
23301 ;;; Imenu support
23303 (defvar org-imenu-markers nil
23304 "All markers currently used by Imenu.")
23305 (make-variable-buffer-local 'org-imenu-markers)
23307 (defun org-imenu-new-marker (&optional pos)
23308 "Return a new marker for use by Imenu, and remember the marker."
23309 (let ((m (make-marker)))
23310 (move-marker m (or pos (point)))
23311 (push m org-imenu-markers)
23314 (defun org-imenu-get-tree ()
23315 "Produce the index for Imenu."
23316 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23317 (setq org-imenu-markers nil)
23318 (let* ((n org-imenu-depth)
23319 (re (concat "^" (org-get-limited-outline-regexp)))
23320 (subs (make-vector (1+ n) nil))
23321 (last-level 0)
23322 m level head0 head)
23323 (save-excursion
23324 (save-restriction
23325 (widen)
23326 (goto-char (point-max))
23327 (while (re-search-backward re nil t)
23328 (setq level (org-reduced-level (funcall outline-level)))
23329 (when (and (<= level n)
23330 (looking-at org-complex-heading-regexp)
23331 (setq head0 (org-match-string-no-properties 4)))
23332 (setq head (org-link-display-format head0)
23333 m (org-imenu-new-marker))
23334 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23335 (if (>= level last-level)
23336 (push (cons head m) (aref subs level))
23337 (push (cons head (aref subs (1+ level))) (aref subs level))
23338 (loop for i from (1+ level) to n do (aset subs i nil)))
23339 (setq last-level level)))))
23340 (aref subs 1)))
23342 (eval-after-load "imenu"
23343 '(progn
23344 (add-hook 'imenu-after-jump-hook
23345 (lambda ()
23346 (if (derived-mode-p 'org-mode)
23347 (org-show-context 'org-goto))))))
23349 (defun org-link-display-format (link)
23350 "Replace a link with its the description.
23351 If there is no description, use the link target."
23352 (save-match-data
23353 (if (string-match org-bracket-link-analytic-regexp link)
23354 (replace-match (if (match-end 5)
23355 (match-string 5 link)
23356 (concat (match-string 1 link)
23357 (match-string 3 link)))
23358 nil t link)
23359 link)))
23361 (defun org-toggle-link-display ()
23362 "Toggle the literal or descriptive display of links."
23363 (interactive)
23364 (if org-descriptive-links
23365 (progn (org-remove-from-invisibility-spec '(org-link))
23366 (org-restart-font-lock)
23367 (setq org-descriptive-links nil))
23368 (progn (add-to-invisibility-spec '(org-link))
23369 (org-restart-font-lock)
23370 (setq org-descriptive-links t))))
23372 ;; Speedbar support
23374 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23375 "Overlay marking the agenda restriction line in speedbar.")
23376 (overlay-put org-speedbar-restriction-lock-overlay
23377 'face 'org-agenda-restriction-lock)
23378 (overlay-put org-speedbar-restriction-lock-overlay
23379 'help-echo "Agendas are currently limited to this item.")
23380 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23382 (defun org-speedbar-set-agenda-restriction ()
23383 "Restrict future agenda commands to the location at point in speedbar.
23384 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23385 (interactive)
23386 (require 'org-agenda)
23387 (let (p m tp np dir txt)
23388 (cond
23389 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23390 'org-imenu t))
23391 (setq m (get-text-property p 'org-imenu-marker))
23392 (with-current-buffer (marker-buffer m)
23393 (goto-char m)
23394 (org-agenda-set-restriction-lock 'subtree)))
23395 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23396 'speedbar-function 'speedbar-find-file))
23397 (setq tp (previous-single-property-change
23398 (1+ p) 'speedbar-function)
23399 np (next-single-property-change
23400 tp 'speedbar-function)
23401 dir (speedbar-line-directory)
23402 txt (buffer-substring-no-properties (or tp (point-min))
23403 (or np (point-max))))
23404 (with-current-buffer (find-file-noselect
23405 (let ((default-directory dir))
23406 (expand-file-name txt)))
23407 (unless (derived-mode-p 'org-mode)
23408 (error "Cannot restrict to non-Org-mode file"))
23409 (org-agenda-set-restriction-lock 'file)))
23410 (t (error "Don't know how to restrict Org-mode's agenda")))
23411 (move-overlay org-speedbar-restriction-lock-overlay
23412 (point-at-bol) (point-at-eol))
23413 (setq current-prefix-arg nil)
23414 (org-agenda-maybe-redo)))
23416 (eval-after-load "speedbar"
23417 '(progn
23418 (speedbar-add-supported-extension ".org")
23419 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23420 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23421 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23422 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23423 (add-hook 'speedbar-visiting-tag-hook
23424 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23426 ;;; Fixes and Hacks for problems with other packages
23428 ;; Make flyspell not check words in links, to not mess up our keymap
23429 (defvar org-element-affiliated-keywords) ; From org-element.el
23430 (defvar org-element-block-name-alist) ; From org-element.el
23431 (defun org-mode-flyspell-verify ()
23432 "Don't let flyspell put overlays at active buttons, or on
23433 {todo,all-time,additional-option-like}-keywords."
23434 (require 'org-element) ; For `org-element-affiliated-keywords'
23435 (let ((pos (max (1- (point)) (point-min)))
23436 (word (thing-at-point 'word)))
23437 (and (not (get-text-property pos 'keymap))
23438 (not (get-text-property pos 'org-no-flyspell))
23439 (not (member word org-todo-keywords-1))
23440 (not (member word org-all-time-keywords))
23441 (not (member word org-options-keywords))
23442 (not (member word (mapcar 'car org-startup-options)))
23443 (not (member-ignore-case word org-element-affiliated-keywords))
23444 (not (member-ignore-case word (org-get-export-keywords)))
23445 (not (member-ignore-case
23446 word (mapcar 'car org-element-block-name-alist)))
23447 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23449 (defun org-remove-flyspell-overlays-in (beg end)
23450 "Remove flyspell overlays in region."
23451 (and (org-bound-and-true-p flyspell-mode)
23452 (fboundp 'flyspell-delete-region-overlays)
23453 (flyspell-delete-region-overlays beg end))
23454 (add-text-properties beg end '(org-no-flyspell t)))
23456 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23457 (eval-after-load "bookmark"
23458 '(if (boundp 'bookmark-after-jump-hook)
23459 ;; We can use the hook
23460 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23461 ;; Hook not available, use advice
23462 (defadvice bookmark-jump (after org-make-visible activate)
23463 "Make the position visible."
23464 (org-bookmark-jump-unhide))))
23466 ;; Make sure saveplace shows the location if it was hidden
23467 (eval-after-load "saveplace"
23468 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23469 "Make the position visible."
23470 (org-bookmark-jump-unhide)))
23472 ;; Make sure ecb shows the location if it was hidden
23473 (eval-after-load "ecb"
23474 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23475 "Make hierarchy visible when jumping into location from ECB tree buffer."
23476 (if (derived-mode-p 'org-mode)
23477 (org-show-context))))
23479 (defun org-bookmark-jump-unhide ()
23480 "Unhide the current position, to show the bookmark location."
23481 (and (derived-mode-p 'org-mode)
23482 (or (outline-invisible-p)
23483 (save-excursion (goto-char (max (point-min) (1- (point))))
23484 (outline-invisible-p)))
23485 (org-show-context 'bookmark-jump)))
23487 ;; Make session.el ignore our circular variable
23488 (eval-after-load "session"
23489 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23491 ;;;; Finish up
23493 (provide 'org)
23495 (run-hooks 'org-load-hook)
23497 ;;; org.el ends here