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.
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
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
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
79 (require 'format-spec
)
81 (load "org-loaddefs.el" t t t
)
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
)
167 (defun org-babel-do-load-languages (sym value
)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value
)
171 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
174 (require (intern (concat "ob-" lang
))))
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."
194 :set
'org-babel-do-load-languages
196 :type
'(alist :tag
"Babel Languages"
199 (const :tag
"Awk" awk
)
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
)
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
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."
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")))
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)"
275 (if (string= org-dir 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
)
284 (if message
(message _version
))
287 (defconst org-version
(org-version))
289 ;;; Compatibility constants
291 ;;; The custom variables
294 "Outline-based notes management and organizer."
299 (defcustom org-mode-hook nil
300 "Mode hook for Org-mode, run after the mode was turned on."
304 (defcustom org-load-hook nil
305 "Hook that is run after org.el has been loaded."
309 (defcustom org-log-buffer-setup-hook nil
310 "Hook that is run after an Org log buffer is created."
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
))
323 (condition-case nil
(require ext
)
324 (error (message "Problems while trying to load feature `%s'" ext
))))
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."
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:
348 For export specific modules, see also `org-export-backends'."
350 :set
'org-set-modules
352 :package-version
'(Org .
"8.0")
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
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:
433 \(setq org-export-registered-backends
436 \(or (memq backend val)
440 \(and (org-export-derived-backend-p b (car backend))
441 \(throw 'parentp t)))
444 org-export-registered-backends))
445 \(let ((new-list (mapcar 'car org-export-registered-backends)))
446 \(dolist (backend val)
448 \((not (load (format \"ox-%s\" backend) t t))
449 \(message \"Problems while trying to load export back-end `%s'\"
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
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
469 (or (memq backend val
)
473 (and (org-export-derived-backend-p b
(car backend
))
477 org-export-registered-backends
))
478 ;; Now build NEW-LIST of both new back-ends and required
480 (let ((new-list (mapcar 'car org-export-registered-backends
)))
481 (dolist (backend val
)
483 ((not (load (format "ox-%s" backend
) t t
))
484 (message "Problems while trying to load export back-end `%s'"
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
" texinfo Export buffer to Texinfo format" texinfo
)
499 (const :tag
"C confluence Export buffer to Confluence Wiki format" confluence
)
500 (const :tag
"C deck Export buffer to deck.js presentations" deck
)
501 (const :tag
"C freemind Export buffer to Freemind mindmap format" freemind
)
502 (const :tag
"C groff Export buffer to Groff format" groff
)
503 (const :tag
"C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter
)
504 (const :tag
"C RSS 2.0 Export buffer to RSS 2.0 format" rss
)
505 (const :tag
"C s5 Export buffer to s5 presentations" s5
)
506 (const :tag
"C taskjuggler Export buffer to TaskJuggler format" taskjuggler
)))
511 (condition-case nil
(require (intern (format "ox-%s" backend
)))
512 (error (message "Problems while trying to load export back-end `%s'"
514 org-export-backends
))
516 (defcustom org-support-shift-select nil
517 "Non-nil means make shift-cursor commands select text when possible.
519 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
520 start selecting a region, or enlarge regions started in this way.
521 In Org-mode, in special contexts, these same keys are used for
522 other purposes, important enough to compete with shift selection.
523 Org tries to balance these needs by supporting `shift-select-mode'
524 outside these special contexts, under control of this variable.
526 The default of this variable is nil, to avoid confusing behavior. Shifted
527 cursor keys will then execute Org commands in the following contexts:
528 - on a headline, changing TODO state (left/right) and priority (up/down)
529 - on a time stamp, changing the time
530 - in a plain list item, changing the bullet type
531 - in a property definition line, switching between allowed values
532 - in the BEGIN line of a clock table (changing the time block).
533 Outside these contexts, the commands will throw an error.
535 When this variable is t and the cursor is not in a special
536 context, Org-mode will support shift-selection for making and
537 enlarging regions. To make this more effective, the bullet
538 cycling will no longer happen anywhere in an item line, but only
539 if the cursor is exactly on the bullet.
541 If you set this variable to the symbol `always', then the keys
542 will not be special in headlines, property lines, and item lines,
543 to make shift selection work there as well. If this is what you
544 want, you can use the following alternative commands: `C-c C-t'
545 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
546 can be used to switch TODO sets, `C-c -' to cycle item bullet
547 types, and properties can be edited by hand or in column view.
549 However, when the cursor is on a timestamp, shift-cursor commands
550 will still edit the time stamp - this is just too good to give up.
552 XEmacs user should have this variable set to nil, because
553 `shift-select-mode' is in Emacs 23 or later only."
556 (const :tag
"Never" nil
)
557 (const :tag
"When outside special context" t
)
558 (const :tag
"Everywhere except timestamps" always
)))
560 (defcustom org-loop-over-headlines-in-active-region nil
561 "Shall some commands act upon headlines in the active region?
563 When set to `t', some commands will be performed in all headlines
564 within the active region.
566 When set to `start-level', some commands will be performed in all
567 headlines within the active region, provided that these headlines
568 are of the same level than the first one.
570 When set to a string, those commands will be performed on the
571 matching headlines within the active region. Such string must be
572 a tags/property/todo match as it is used in the agenda tags view.
574 The list of commands is: `org-schedule', `org-deadline',
575 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
576 `org-archive-to-archive-sibling'. The archiving commands skip
577 already archived entries."
578 :type
'(choice (const :tag
"Don't loop" nil
)
579 (const :tag
"All headlines in active region" t
)
580 (const :tag
"In active region, headlines at the same level than the first one" 'start-level
)
581 (string :tag
"Tags/Property/Todo matcher"))
586 (defgroup org-startup nil
587 "Options concerning startup of Org-mode."
591 (defcustom org-startup-folded t
592 "Non-nil means entering Org-mode will switch to OVERVIEW.
593 This can also be configured on a per-file basis by adding one of
594 the following lines anywhere in the buffer:
596 #+STARTUP: fold (or `overview', this is equivalent)
597 #+STARTUP: nofold (or `showall', this is equivalent)
599 #+STARTUP: showeverything
601 By default, this option is ignored when Org opens agenda files
602 for the first time. If you want the agenda to honor the startup
603 option, set `org-agenda-inhibit-startup' to nil."
606 (const :tag
"nofold: show all" nil
)
607 (const :tag
"fold: overview" t
)
608 (const :tag
"content: all headlines" content
)
609 (const :tag
"show everything, even drawers" showeverything
)))
611 (defcustom org-startup-truncated t
612 "Non-nil means entering Org-mode will set `truncate-lines'.
613 This is useful since some lines containing links can be very long and
614 uninteresting. Also tables look terrible when wrapped."
618 (defcustom org-startup-indented nil
619 "Non-nil means turn on `org-indent-mode' on startup.
620 This can also be configured on a per-file basis by adding one of
621 the following lines anywhere in the buffer:
625 :group
'org-structure
627 (const :tag
"Not" nil
)
628 (const :tag
"Globally (slow on startup in large files)" t
)))
630 (defcustom org-use-sub-superscripts t
631 "Non-nil means interpret \"_\" and \"^\" for display.
632 When this option is turned on, you can use TeX-like syntax for sub- and
633 superscripts. Several characters after \"_\" or \"^\" will be
634 considered as a single item - so grouping with {} is normally not
635 needed. For example, the following things will be parsed as single
636 sub- or superscripts.
638 10^24 or 10^tau several digits will be considered 1 item.
639 10^-12 or 10^-tau a leading sign with digits or a word
640 x^2-y^3 will be read as x^2 - y^3, because items are
641 terminated by almost any nonword/nondigit char.
642 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
644 Still, ambiguity is possible - so when in doubt use {} to enclose
645 the sub/superscript. If you set this variable to the symbol
646 `{}', the braces are *required* in order to trigger
647 interpretations as sub/superscript. This can be helpful in
648 documents that need \"_\" frequently in plain text."
652 (const :tag
"Always interpret" t
)
653 (const :tag
"Only with braces" {})
654 (const :tag
"Never interpret" nil
)))
656 (defcustom org-startup-with-beamer-mode nil
657 "Non-nil means turn on `org-beamer-mode' on startup.
658 This can also be configured on a per-file basis by adding one of
659 the following lines anywhere in the buffer:
666 (defcustom org-startup-align-all-tables nil
667 "Non-nil means align all tables when visiting a file.
668 This is useful when the column width in tables is forced with <N> cookies
669 in table fields. Such tables will look correct only after the first re-align.
670 This can also be configured on a per-file basis by adding one of
671 the following lines anywhere in the buffer:
677 (defcustom org-startup-with-inline-images nil
678 "Non-nil means show inline images when loading a new Org file.
679 This can also be configured on a per-file basis by adding one of
680 the following lines anywhere in the buffer:
681 #+STARTUP: inlineimages
682 #+STARTUP: noinlineimages"
687 (defcustom org-startup-with-latex-preview nil
688 "Non-nil means preview LaTeX fragments when loading a new Org file.
690 This can also be configured on a per-file basis by adding one of
691 the followinglines anywhere in the buffer:
692 #+STARTUP: latexpreview
693 #+STARTUP: nolatexpreview"
696 :package-version
'(Org .
"8.0")
699 (defcustom org-insert-mode-line-in-empty-file nil
700 "Non-nil means insert the first line setting Org-mode in empty files.
701 When the function `org-mode' is called interactively in an empty file, this
702 normally means that the file name does not automatically trigger Org-mode.
703 To ensure that the file will always be in Org-mode in the future, a
704 line enforcing Org-mode will be inserted into the buffer, if this option
709 (defcustom org-replace-disputed-keys nil
710 "Non-nil means use alternative key bindings for some keys.
711 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
712 These keys are also used by other packages like shift-selection-mode'
713 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
714 If you want to use Org-mode together with one of these other modes,
715 or more generally if you would like to move some Org-mode commands to
716 other keys, set this variable and configure the keys with the variable
719 This option is only relevant at load-time of Org-mode, and must be set
720 *before* org.el is loaded. Changing it requires a restart of Emacs to
725 (defcustom org-use-extra-keys nil
726 "Non-nil means use extra key sequence definitions for certain commands.
727 This happens automatically if you run XEmacs or if `window-system'
728 is nil. This variable lets you do the same manually. You must
729 set it before loading org.
731 Example: on Carbon Emacs 22 running graphically, with an external
732 keyboard on a Powerbook, the default way of setting M-left might
733 not work for either Alt or ESC. Setting this variable will make
738 (org-defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
)
740 (defcustom org-disputed-keys
741 '(([(shift up
)] .
[(meta p
)])
742 ([(shift down
)] .
[(meta n
)])
743 ([(shift left
)] .
[(meta -
)])
744 ([(shift right
)] .
[(meta +)])
745 ([(control shift right
)] .
[(meta shift
+)])
746 ([(control shift left
)] .
[(meta shift -
)]))
747 "Keys for which Org-mode and other modes compete.
748 This is an alist, cars are the default keys, second element specifies
749 the alternative to use when `org-replace-disputed-keys' is t.
751 Keys can be specified in any syntax supported by `define-key'.
752 The value of this option takes effect only at Org-mode's startup,
753 therefore you'll have to restart Emacs to apply it after changing."
758 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
759 Or return the original if not disputed.
760 Also apply the translations defined in `org-xemacs-key-equivalents'."
761 (when org-replace-disputed-keys
762 (let* ((nkey (key-description key
))
763 (x (org-find-if (lambda (x)
764 (equal (key-description (car x
)) nkey
))
766 (setq key
(if x
(cdr x
) key
))))
767 (when (featurep 'xemacs
)
768 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
771 (defun org-find-if (predicate seq
)
774 (if (funcall predicate
(car seq
))
775 (throw 'exit
(car seq
))
778 (defun org-defkey (keymap key def
)
779 "Define a key, possibly translated, as returned by `org-key'."
780 (define-key keymap
(org-key key
) def
))
782 (defcustom org-ellipsis nil
783 "The ellipsis to use in the Org-mode outline.
784 When nil, just use the standard three dots. When a string, use that instead,
785 When a face, use the standard 3 dots, but with the specified face.
786 The change affects only Org-mode (which will then use its own display table).
787 Changing this requires executing `M-x org-mode' in a buffer to become
790 :type
'(choice (const :tag
"Default" nil
)
791 (face :tag
"Face" :value org-warning
)
792 (string :tag
"String" :value
"...#")))
794 (defvar org-display-table nil
795 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
797 (defgroup org-keywords nil
798 "Keywords in Org-mode."
802 (defcustom org-deadline-string
"DEADLINE:"
803 "String to mark deadline entries.
804 A deadline is this string, followed by a time stamp. Should be a word,
805 terminated by a colon. You can insert a schedule keyword and
806 a timestamp with \\[org-deadline].
807 Changes become only effective after restarting Emacs."
811 (defcustom org-scheduled-string
"SCHEDULED:"
812 "String to mark scheduled TODO entries.
813 A schedule is this string, followed by a time stamp. Should be a word,
814 terminated by a colon. You can insert a schedule keyword and
815 a timestamp with \\[org-schedule].
816 Changes become only effective after restarting Emacs."
820 (defcustom org-closed-string
"CLOSED:"
821 "String used as the prefix for timestamps logging closing a TODO entry."
825 (defcustom org-clock-string
"CLOCK:"
826 "String used as prefix for timestamps clocking work hours on an item."
830 (defconst org-planning-or-clock-line-re
(concat "^[ \t]*\\("
831 org-scheduled-string
"\\|"
832 org-deadline-string
"\\|"
833 org-closed-string
"\\|"
834 org-clock-string
"\\)")
835 "Matches a line with planning or clock info.")
837 (defcustom org-comment-string
"COMMENT"
838 "Entries starting with this keyword will never be exported.
839 An entry can be toggled between COMMENT and normal with
840 \\[org-toggle-comment].
841 Changes become only effective after restarting Emacs."
845 (defcustom org-quote-string
"QUOTE"
846 "Entries starting with this keyword will be exported in fixed-width font.
847 Quoting applies only to the text in the entry following the headline, and does
848 not extend beyond the next headline, even if that is lower level.
849 An entry can be toggled between QUOTE and normal with
850 \\[org-toggle-fixed-width-section]."
854 (defconst org-repeat-re
855 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
856 "Regular expression for specifying repeated events.
857 After a match, group 1 contains the repeat expression.")
859 (defgroup org-structure nil
860 "Options concerning the general structure of Org-mode files."
864 (defgroup org-reveal-location nil
865 "Options about how to make context of a location visible."
866 :tag
"Org Reveal Location"
867 :group
'org-structure
)
869 (defconst org-context-choice
871 (const :tag
"Always" t
)
872 (const :tag
"Never" nil
)
873 (repeat :greedy t
:tag
"Individual contexts"
875 (choice :tag
"Context"
882 (const bookmark-jump
)
886 "Contexts for the reveal options.")
888 (defcustom org-show-hierarchy-above
'((default . t
))
889 "Non-nil means show full hierarchy when revealing a location.
890 Org-mode often shows locations in an org-mode file which might have
891 been invisible before. When this is set, the hierarchy of headings
892 above the exposed location is shown.
893 Turning this off for example for sparse trees makes them very compact.
894 Instead of t, this can also be an alist specifying this option for different
895 contexts. Valid contexts are
896 agenda when exposing an entry from the agenda
897 org-goto when using the command `org-goto' on key C-c C-j
898 occur-tree when using the command `org-occur' on key C-c /
899 tags-tree when constructing a sparse tree based on tags matches
900 link-search when exposing search matches associated with a link
901 mark-goto when exposing the jump goal of a mark
902 bookmark-jump when exposing a bookmark location
903 isearch when exiting from an incremental search
904 default default for all contexts not set explicitly"
905 :group
'org-reveal-location
906 :type org-context-choice
)
908 (defcustom org-show-following-heading
'((default . nil
))
909 "Non-nil means show following heading when revealing a location.
910 Org-mode often shows locations in an org-mode file which might have
911 been invisible before. When this is set, the heading following the
913 Turning this off for example for sparse trees makes them very compact,
914 but makes it harder to edit the location of the match. In such a case,
915 use the command \\[org-reveal] to show more context.
916 Instead of t, this can also be an alist specifying this option for different
917 contexts. See `org-show-hierarchy-above' for valid contexts."
918 :group
'org-reveal-location
919 :type org-context-choice
)
921 (defcustom org-show-siblings
'((default . nil
) (isearch t
))
922 "Non-nil means show all sibling heading when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the sibling of the current entry
925 heading are all made visible. If `org-show-hierarchy-above' is t,
926 the same happens on each level of the hierarchy above the current entry.
928 By default this is on for the isearch context, off for all other contexts.
929 Turning this off for example for sparse trees makes them very compact,
930 but makes it harder to edit the location of the match. In such a case,
931 use the command \\[org-reveal] to show more context.
932 Instead of t, this can also be an alist specifying this option for different
933 contexts. See `org-show-hierarchy-above' for valid contexts."
934 :group
'org-reveal-location
935 :type org-context-choice
)
937 (defcustom org-show-entry-below
'((default . nil
))
938 "Non-nil means show the entry below a headline when revealing a location.
939 Org-mode often shows locations in an org-mode file which might have
940 been invisible before. When this is set, the text below the headline that is
941 exposed is also shown.
943 By default this is off for all contexts.
944 Instead of t, this can also be an alist specifying this option for different
945 contexts. See `org-show-hierarchy-above' for valid contexts."
946 :group
'org-reveal-location
947 :type org-context-choice
)
949 (defcustom org-indirect-buffer-display
'other-window
950 "How should indirect tree buffers be displayed?
951 This applies to indirect buffers created with the commands
952 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
954 current-window Display in the current window
955 other-window Just display in another window.
956 dedicated-frame Create one new frame, and re-use it each time.
957 new-frame Make a new frame each time. Note that in this case
958 previously-made indirect buffers are kept, and you need to
959 kill these buffers yourself."
960 :group
'org-structure
961 :group
'org-agenda-windows
963 (const :tag
"In current window" current-window
)
964 (const :tag
"In current frame, other window" other-window
)
965 (const :tag
"Each time a new frame" new-frame
)
966 (const :tag
"One dedicated frame" dedicated-frame
)))
968 (defcustom org-use-speed-commands nil
969 "Non-nil means activate single letter commands at beginning of a headline.
970 This may also be a function to test for appropriate locations where speed
971 commands should be active."
972 :group
'org-structure
974 (const :tag
"Never" nil
)
975 (const :tag
"At beginning of headline stars" t
)
978 (defcustom org-speed-commands-user nil
979 "Alist of additional speed commands.
980 This list will be checked before `org-speed-commands-default'
981 when the variable `org-use-speed-commands' is non-nil
982 and when the cursor is at the beginning of a headline.
983 The car if each entry is a string with a single letter, which must
984 be assigned to `self-insert-command' in the global map.
985 The cdr is either a command to be called interactively, a function
986 to be called, or a form to be evaluated.
987 An entry that is just a list with a single string will be interpreted
988 as a descriptive headline that will be added when listing the speed
989 commands in the Help buffer using the `?' speed command."
990 :group
'org-structure
991 :type
'(repeat :value
("k" . ignore
)
992 (choice :value
("k" . ignore
)
993 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
994 (cons :tag
"Letter and Command"
995 (string :tag
"Command letter")
1000 (defgroup org-cycle nil
1001 "Options concerning visibility cycling in Org-mode."
1003 :group
'org-structure
)
1005 (defcustom org-cycle-skip-children-state-if-no-children t
1006 "Non-nil means skip CHILDREN state in entries that don't have any."
1010 (defcustom org-cycle-max-level nil
1011 "Maximum level which should still be subject to visibility cycling.
1012 Levels higher than this will, for cycling, be treated as text, not a headline.
1013 When `org-odd-levels-only' is set, a value of N in this variable actually
1014 means 2N-1 stars as the limiting headline.
1015 When nil, cycle all levels.
1016 Note that the limiting level of cycling is also influenced by
1017 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1018 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1022 (const :tag
"No limit" nil
)
1023 (integer :tag
"Maximum level")))
1025 (defcustom org-drawers
'("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1026 "Names of drawers. Drawers are not opened by cycling on the headline above.
1027 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1032 The drawer \"PROPERTIES\" is special for capturing properties through
1035 Drawers can be defined on the per-file basis with a line like:
1037 #+DRAWERS: HIDDEN STATE PROPERTIES"
1038 :group
'org-structure
1040 :type
'(repeat (string :tag
"Drawer Name")))
1042 (defcustom org-hide-block-startup nil
1043 "Non-nil means entering Org-mode will fold all blocks.
1044 This can also be set in on a per-file basis with
1046 #+STARTUP: hideblocks
1047 #+STARTUP: showblocks"
1052 (defcustom org-cycle-global-at-bob nil
1053 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1054 This makes it possible to do global cycling without having to use S-TAB or
1055 \\[universal-argument] TAB. For this special case to work, the first line
1056 of the buffer must not be a headline -- it may be empty or some other text.
1057 When used in this way, `org-cycle-hook' is disabled temporarily to make
1058 sure the cursor stays at the beginning of the buffer. When this option is
1059 nil, don't do anything special at the beginning of the buffer."
1063 (defcustom org-cycle-level-after-item
/entry-creation t
1064 "Non-nil means cycle entry level or item indentation in new empty entries.
1066 When the cursor is at the end of an empty headline, i.e., with only stars
1067 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1068 and then all possible ancestor states, before returning to the original state.
1069 This makes data entry extremely fast: M-RET to create a new headline,
1070 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1072 When the cursor is at the end of an empty plain list item, one TAB will
1073 make it a subitem, two or more tabs will back up to make this an item
1074 higher up in the item hierarchy."
1078 (defcustom org-cycle-emulate-tab t
1079 "Where should `org-cycle' emulate TAB.
1081 white Only in completely white lines
1082 whitestart Only at the beginning of lines, before the first non-white char
1083 t Everywhere except in headlines
1084 exc-hl-bol Everywhere except at the start of a headline
1085 If TAB is used in a place where it does not emulate TAB, the current subtree
1086 visibility is cycled."
1088 :type
'(choice (const :tag
"Never" nil
)
1089 (const :tag
"Only in completely white lines" white
)
1090 (const :tag
"Before first char in a line" whitestart
)
1091 (const :tag
"Everywhere except in headlines" t
)
1092 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)
1095 (defcustom org-cycle-separator-lines
2
1096 "Number of empty lines needed to keep an empty line between collapsed trees.
1097 If you leave an empty line between the end of a subtree and the following
1098 headline, this empty line is hidden when the subtree is folded.
1099 Org-mode will leave (exactly) one empty line visible if the number of
1100 empty lines is equal or larger to the number given in this variable.
1101 So the default 2 means at least 2 empty lines after the end of a subtree
1102 are needed to produce free space between a collapsed subtree and the
1105 If the number is negative, and the number of empty lines is at least -N,
1106 all empty lines are shown.
1108 Special case: when 0, never leave empty lines in collapsed view."
1111 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
1113 (defcustom org-pre-cycle-hook nil
1114 "Hook that is run before visibility cycling is happening.
1115 The function(s) in this hook must accept a single argument which indicates
1116 the new state that will be set right after running this hook. The
1117 argument is a symbol. Before a global state change, it can have the values
1118 `overview', `content', or `all'. Before a local state change, it can have
1119 the values `folded', `children', or `subtree'."
1123 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1124 org-cycle-hide-drawers
1125 org-cycle-hide-inline-tasks
1126 org-cycle-show-empty-lines
1127 org-optimize-window-after-visibility-change
)
1128 "Hook that is run after `org-cycle' has changed the buffer visibility.
1129 The function(s) in this hook must accept a single argument which indicates
1130 the new state that was set by the most recent `org-cycle' command. The
1131 argument is a symbol. After a global state change, it can have the values
1132 `overview', `contents', or `all'. After a local state change, it can have
1133 the values `folded', `children', or `subtree'."
1137 (defgroup org-edit-structure nil
1138 "Options concerning structure editing in Org-mode."
1139 :tag
"Org Edit Structure"
1140 :group
'org-structure
)
1142 (defcustom org-odd-levels-only nil
1143 "Non-nil means skip even levels and only use odd levels for the outline.
1144 This has the effect that two stars are being added/taken away in
1145 promotion/demotion commands. It also influences how levels are
1146 handled by the exporters.
1147 Changing it requires restart of `font-lock-mode' to become effective
1148 for fontification also in regions already fontified.
1149 You may also set this on a per-file basis by adding one of the following
1150 lines to the buffer:
1154 :group
'org-edit-structure
1155 :group
'org-appearance
1158 (defcustom org-adapt-indentation t
1159 "Non-nil means adapt indentation to outline node level.
1161 When this variable is set, Org assumes that you write outlines by
1162 indenting text in each node to align with the headline (after the stars).
1163 The following issues are influenced by this variable:
1165 - When this is set and the *entire* text in an entry is indented, the
1166 indentation is increased by one space in a demotion command, and
1167 decreased by one in a promotion command. If any line in the entry
1168 body starts with text at column 0, indentation is not changed at all.
1170 - Property drawers and planning information is inserted indented when
1171 this variable s set. When nil, they will not be indented.
1173 - TAB indents a line relative to context. The lines below a headline
1174 will be indented when this variable is set.
1176 Note that this is all about true indentation, by adding and removing
1177 space characters. See also `org-indent.el' which does level-dependent
1178 indentation in a virtual way, i.e. at display time in Emacs."
1179 :group
'org-edit-structure
1182 (defcustom org-special-ctrl-a
/e nil
1183 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1185 When t, `C-a' will bring back the cursor to the beginning of the
1186 headline text, i.e. after the stars and after a possible TODO
1187 keyword. In an item, this will be the position after bullet and
1188 check-box, if any. When the cursor is already at that position,
1189 another `C-a' will bring it to the beginning of the line.
1191 `C-e' will jump to the end of the headline, ignoring the presence
1192 of tags in the headline. A second `C-e' will then jump to the
1193 true end of the line, after any tags. This also means that, when
1194 this variable is non-nil, `C-e' also will never jump beyond the
1195 end of the heading of a folded section, i.e. not after the
1198 When set to the symbol `reversed', the first `C-a' or `C-e' works
1199 normally, going to the true line boundary first. Only a directly
1200 following, identical keypress will bring the cursor to the
1203 This may also be a cons cell where the behavior for `C-a' and
1204 `C-e' is set separately."
1205 :group
'org-edit-structure
1207 (const :tag
"off" nil
)
1208 (const :tag
"on: after stars/bullet and before tags first" t
)
1209 (const :tag
"reversed: true line boundary first" reversed
)
1210 (cons :tag
"Set C-a and C-e separately"
1211 (choice :tag
"Special C-a"
1212 (const :tag
"off" nil
)
1213 (const :tag
"on: after stars/bullet first" t
)
1214 (const :tag
"reversed: before stars/bullet first" reversed
))
1215 (choice :tag
"Special C-e"
1216 (const :tag
"off" nil
)
1217 (const :tag
"on: before tags first" t
)
1218 (const :tag
"reversed: after tags first" reversed
)))))
1219 (org-defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
)
1221 (defcustom org-special-ctrl-k nil
1222 "Non-nil means `C-k' will behave specially in headlines.
1223 When nil, `C-k' will call the default `kill-line' command.
1224 When t, the following will happen while the cursor is in the headline:
1226 - When the cursor is at the beginning of a headline, kill the entire
1227 line and possible the folded subtree below the line.
1228 - When in the middle of the headline text, kill the headline up to the tags.
1229 - When after the headline text, kill the tags."
1230 :group
'org-edit-structure
1233 (defcustom org-ctrl-k-protect-subtree nil
1234 "Non-nil means, do not delete a hidden subtree with C-k.
1235 When set to the symbol `error', simply throw an error when C-k is
1236 used to kill (part-of) a headline that has hidden text behind it.
1237 Any other non-nil value will result in a query to the user, if it is
1238 OK to kill that hidden subtree. When nil, kill without remorse."
1239 :group
'org-edit-structure
1242 (const :tag
"Do not protect hidden subtrees" nil
)
1243 (const :tag
"Protect hidden subtrees with a security query" t
)
1244 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1246 (defcustom org-catch-invisible-edits nil
1247 "Check if in invisible region before inserting or deleting a character.
1250 nil Do not check, so just do invisible edits.
1251 error Throw an error and do nothing.
1252 show Make point visible, and do the requested edit.
1253 show-and-error Make point visible, then throw an error and abort the edit.
1254 smart Make point visible, and do insertion/deletion if it is
1255 adjacent to visible text and the change feels predictable.
1256 Never delete a previously invisible character or add in the
1257 middle or right after an invisible region. Basically, this
1258 allows insertion and backward-delete right before ellipses.
1259 FIXME: maybe in this case we should not even show?"
1260 :group
'org-edit-structure
1263 (const :tag
"Do not check" nil
)
1264 (const :tag
"Throw error when trying to edit" error
)
1265 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1266 (const :tag
"Show invisible part and do the edit" show
)
1267 (const :tag
"Be smart and do the right thing" smart
)))
1269 (defcustom org-yank-folded-subtrees t
1270 "Non-nil means when yanking subtrees, fold them.
1271 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1272 it starts with a heading and all other headings in it are either children
1273 or siblings, then fold all the subtrees. However, do this only if no
1274 text after the yank would be swallowed into a folded tree by this action."
1275 :group
'org-edit-structure
1278 (defcustom org-yank-adjusted-subtrees nil
1279 "Non-nil means when yanking subtrees, adjust the level.
1280 With this setting, `org-paste-subtree' is used to insert the subtree, see
1281 this function for details."
1282 :group
'org-edit-structure
1285 (defcustom org-M-RET-may-split-line
'((default . t
))
1286 "Non-nil means M-RET will split the line at the cursor position.
1287 When nil, it will go to the end of the line before making a
1289 You may also set this option in a different way for different
1290 contexts. Valid contexts are:
1292 headline when creating a new headline
1293 item when creating a new item
1294 table in a table field
1295 default the value to be used for all contexts not explicitly
1297 :group
'org-structure
1300 (const :tag
"Always" t
)
1301 (const :tag
"Never" nil
)
1302 (repeat :greedy t
:tag
"Individual contexts"
1304 (choice :tag
"Context"
1312 (defcustom org-insert-heading-respect-content nil
1313 "Non-nil means insert new headings after the current subtree.
1314 When nil, the new heading is created directly after the current line.
1315 The commands \\[org-insert-heading-respect-content] and
1316 \\[org-insert-todo-heading-respect-content] turn this variable on
1317 for the duration of the command."
1318 :group
'org-structure
1321 (defcustom org-blank-before-new-entry
'((heading . auto
)
1322 (plain-list-item . auto
))
1323 "Should `org-insert-heading' leave a blank line before new heading/item?
1324 The value is an alist, with `heading' and `plain-list-item' as CAR,
1325 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1326 which case Org will look at the surrounding headings/items and try to
1327 make an intelligent decision whether to insert a blank line or not.
1329 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1330 the setting here is ignored and no empty line is inserted to avoid breaking
1331 the list structure."
1332 :group
'org-edit-structure
1334 (cons (const heading
)
1335 (choice (const :tag
"Never" nil
)
1336 (const :tag
"Always" t
)
1337 (const :tag
"Auto" auto
)))
1338 (cons (const plain-list-item
)
1339 (choice (const :tag
"Never" nil
)
1340 (const :tag
"Always" t
)
1341 (const :tag
"Auto" auto
)))))
1343 (defcustom org-insert-heading-hook nil
1344 "Hook being run after inserting a new heading."
1345 :group
'org-edit-structure
1348 (defcustom org-enable-fixed-width-editor t
1349 "Non-nil means lines starting with \":\" are treated as fixed-width.
1350 This currently only means they are never auto-wrapped.
1351 When nil, such lines will be treated like ordinary lines.
1352 See also the QUOTE keyword."
1353 :group
'org-edit-structure
1356 (defcustom org-goto-auto-isearch t
1357 "Non-nil means typing characters in `org-goto' starts incremental search.
1358 When nil, you can use these keybindings to navigate the buffer:
1360 q Quit the org-goto interface
1361 n Go to the next visible heading
1362 p Go to the previous visible heading
1363 f Go one heading forward on same level
1364 b Go one heading backward on same level
1365 u Go one heading up"
1366 :group
'org-edit-structure
1369 (defgroup org-sparse-trees nil
1370 "Options concerning sparse trees in Org-mode."
1371 :tag
"Org Sparse Trees"
1372 :group
'org-structure
)
1374 (defcustom org-highlight-sparse-tree-matches t
1375 "Non-nil means highlight all matches that define a sparse tree.
1376 The highlights will automatically disappear the next time the buffer is
1377 changed by an edit command."
1378 :group
'org-sparse-trees
1381 (defcustom org-remove-highlights-with-change t
1382 "Non-nil means any change to the buffer will remove temporary highlights.
1383 Such highlights are created by `org-occur' and `org-clock-display'.
1384 When nil, `C-c C-c needs to be used to get rid of the highlights.
1385 The highlights created by `org-preview-latex-fragment' always need
1386 `C-c C-c' to be removed."
1387 :group
'org-sparse-trees
1392 (defcustom org-occur-hook
'(org-first-headline-recenter)
1393 "Hook that is run after `org-occur' has constructed a sparse tree.
1394 This can be used to recenter the window to show as much of the structure
1396 :group
'org-sparse-trees
1399 (defgroup org-imenu-and-speedbar nil
1400 "Options concerning imenu and speedbar in Org-mode."
1401 :tag
"Org Imenu and Speedbar"
1402 :group
'org-structure
)
1404 (defcustom org-imenu-depth
2
1405 "The maximum level for Imenu access to Org-mode headlines.
1406 This also applied for speedbar access."
1407 :group
'org-imenu-and-speedbar
1410 (defgroup org-table nil
1411 "Options concerning tables in Org-mode."
1415 (defcustom org-enable-table-editor
'optimized
1416 "Non-nil means lines starting with \"|\" are handled by the table editor.
1417 When nil, such lines will be treated like ordinary lines.
1419 When equal to the symbol `optimized', the table editor will be optimized to
1421 - Automatic overwrite mode in front of whitespace in table fields.
1422 This makes the structure of the table stay in tact as long as the edited
1423 field does not exceed the column width.
1424 - Minimize the number of realigns. Normally, the table is aligned each time
1425 TAB or RET are pressed to move to another field. With optimization this
1426 happens only if changes to a field might have changed the column width.
1427 Optimization requires replacing the functions `self-insert-command',
1428 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1429 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1430 very good at guessing when a re-align will be necessary, but you can always
1431 force one with \\[org-ctrl-c-ctrl-c].
1433 If you would like to use the optimized version in Org-mode, but the
1434 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1436 This variable can be used to turn on and off the table editor during a session,
1437 but in order to toggle optimization, a restart is required.
1439 See also the variable `org-table-auto-blank-field'."
1442 (const :tag
"off" nil
)
1444 (const :tag
"on, optimized" optimized
)))
1446 (defcustom org-self-insert-cluster-for-undo
(or (featurep 'xemacs
)
1447 (version<= emacs-version
"24.1"))
1448 "Non-nil means cluster self-insert commands for undo when possible.
1449 If this is set, then, like in the Emacs command loop, 20 consecutive
1450 characters will be undone together.
1451 This is configurable, because there is some impact on typing performance."
1455 (defcustom org-table-tab-recognizes-table.el t
1456 "Non-nil means TAB will automatically notice a table.el table.
1457 When it sees such a table, it moves point into it and - if necessary -
1458 calls `table-recognize-table'."
1459 :group
'org-table-editing
1462 (defgroup org-link nil
1463 "Options concerning links in Org-mode."
1467 (defvar org-link-abbrev-alist-local nil
1468 "Buffer-local version of `org-link-abbrev-alist', which see.
1469 The value of this is taken from the #+LINK lines.")
1470 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1472 (defcustom org-link-abbrev-alist nil
1473 "Alist of link abbreviations.
1474 The car of each element is a string, to be replaced at the start of a link.
1475 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1476 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1478 [[linkkey:tag][description]]
1480 The 'linkkey' must be a word word, starting with a letter, followed
1481 by letters, numbers, '-' or '_'.
1483 If REPLACE is a string, the tag will simply be appended to create the link.
1484 If the string contains \"%s\", the tag will be inserted there. If the string
1485 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1486 at that point (see the function `url-hexify-string'). If the string contains
1487 the specifier \"%(my-function)\", then the custom function `my-function' will
1488 be invoked: this function takes the tag as its only argument and must return
1491 REPLACE may also be a function that will be called with the tag as the
1492 only argument to create the link, which should be returned as a string.
1494 See the manual for examples."
1498 (string :tag
"Protocol")
1500 (string :tag
"Format")
1503 (defcustom org-descriptive-links t
1504 "Non-nil means Org will display descriptive links.
1505 E.g. [[http://orgmode.org][Org website]] will be displayed as
1506 \"Org Website\", hiding the link itself and just displaying its
1507 description. When set to `nil', Org will display the full links
1510 You can interactively set the value of this variable by calling
1511 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1515 (defcustom org-link-file-path-type
'adaptive
1516 "How the path name in file links should be stored.
1519 relative Relative to the current directory, i.e. the directory of the file
1520 into which the link is being inserted.
1521 absolute Absolute path, if possible with ~ for home directory.
1522 noabbrev Absolute path, no abbreviation of home directory.
1523 adaptive Use relative path for files in the current directory and sub-
1524 directories of it. For other files, use an absolute path."
1532 (defcustom org-activate-links
'(bracket angle plain radio tag date footnote
)
1533 "Types of links that should be activated in Org-mode files.
1534 This is a list of symbols, each leading to the activation of a certain link
1535 type. In principle, it does not hurt to turn on most link types - there may
1536 be a small gain when turning off unused link types. The types are:
1538 bracket The recommended [[link][description]] or [[link]] links with hiding.
1539 angle Links in angular brackets that may contain whitespace like
1540 <bbdb:Carsten Dominik>.
1541 plain Plain links in normal text, no whitespace, like http://google.com.
1542 radio Text that is matched by a radio target, see manual for details.
1543 tag Tag settings in a headline (link to tag search).
1544 date Time stamps (link to calendar).
1545 footnote Footnote labels.
1547 Changing this variable requires a restart of Emacs to become effective."
1549 :type
'(set :greedy t
1550 (const :tag
"Double bracket links" bracket
)
1551 (const :tag
"Angular bracket links" angle
)
1552 (const :tag
"Plain text links" plain
)
1553 (const :tag
"Radio target matches" radio
)
1554 (const :tag
"Tags" tag
)
1555 (const :tag
"Timestamps" date
)
1556 (const :tag
"Footnotes" footnote
)))
1558 (defcustom org-make-link-description-function nil
1559 "Function to use for generating link descriptions from links.
1560 When nil, the link location will be used. This function must take
1561 two parameters: the first one is the link, the second one is the
1562 description generated by `org-insert-link'. The function should
1563 return the description to use."
1567 (defgroup org-link-store nil
1568 "Options concerning storing links in Org-mode."
1569 :tag
"Org Store Link"
1572 (defcustom org-url-hexify-p t
1573 "When non-nil, hexify URL when creating a link."
1576 :group
'org-link-store
)
1578 (defcustom org-email-link-description-format
"Email %c: %.30s"
1579 "Format of the description part of a link to an email or usenet message.
1580 The following %-escapes will be replaced by corresponding information:
1582 %F full \"From\" field
1583 %f name, taken from \"From\" field, address if no name
1584 %T full \"To\" field
1585 %t first name in \"To\" field, address if no name
1586 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1587 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1592 You may use normal field width specification between the % and the letter.
1593 This is for example useful to limit the length of the subject.
1595 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1596 :group
'org-link-store
1599 (defcustom org-from-is-user-regexp
1601 (when (and user-mail-address
(not (string= user-mail-address
"")))
1602 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1603 (when (and user-full-name
(not (string= user-full-name
"")))
1604 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1605 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1606 "Regexp matched against the \"From:\" header of an email or usenet message.
1607 It should match if the message is from the user him/herself."
1608 :group
'org-link-store
1611 (defcustom org-context-in-file-links t
1612 "Non-nil means file links from `org-store-link' contain context.
1613 A search string will be added to the file name with :: as separator and
1614 used to find the context when the link is activated by the command
1615 `org-open-at-point'. When this option is t, the entire active region
1616 will be placed in the search string of the file link. If set to a
1617 positive integer, only the first n lines of context will be stored.
1619 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1620 negates this setting for the duration of the command."
1621 :group
'org-link-store
1622 :type
'(choice boolean integer
))
1624 (defcustom org-keep-stored-link-after-insertion nil
1625 "Non-nil means keep link in list for entire session.
1627 The command `org-store-link' adds a link pointing to the current
1628 location to an internal list. These links accumulate during a session.
1629 The command `org-insert-link' can be used to insert links into any
1630 Org-mode file (offering completion for all stored links). When this
1631 option is nil, every link which has been inserted once using \\[org-insert-link]
1632 will be removed from the list, to make completing the unused links
1634 :group
'org-link-store
1637 (defgroup org-link-follow nil
1638 "Options concerning following links in Org-mode."
1639 :tag
"Org Follow Link"
1642 (defcustom org-link-translation-function nil
1643 "Function to translate links with different syntax to Org syntax.
1644 This can be used to translate links created for example by the Planner
1645 or emacs-wiki packages to Org syntax.
1646 The function must accept two parameters, a TYPE containing the link
1647 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1648 which is everything after the link protocol. It should return a cons
1649 with possibly modified values of type and path.
1650 Org contains a function for this, so if you set this variable to
1651 `org-translate-link-from-planner', you should be able follow many
1652 links created by planner."
1653 :group
'org-link-follow
1656 (defcustom org-follow-link-hook nil
1657 "Hook that is run after a link has been followed."
1658 :group
'org-link-follow
1661 (defcustom org-tab-follows-link nil
1662 "Non-nil means on links TAB will follow the link.
1663 Needs to be set before org.el is loaded.
1664 This really should not be used, it does not make sense, and the
1665 implementation is bad."
1666 :group
'org-link-follow
1669 (defcustom org-return-follows-link nil
1670 "Non-nil means on links RET will follow the link.
1671 In tables, the special behavior of RET has precedence."
1672 :group
'org-link-follow
1675 (defcustom org-mouse-1-follows-link
1676 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1677 "Non-nil means mouse-1 on a link will follow the link.
1678 A longer mouse click will still set point. Does not work on XEmacs.
1679 Needs to be set before org.el is loaded."
1680 :group
'org-link-follow
1683 (defcustom org-mark-ring-length
4
1684 "Number of different positions to be recorded in the ring.
1685 Changing this requires a restart of Emacs to work correctly."
1686 :group
'org-link-follow
1689 (defcustom org-link-search-must-match-exact-headline
'query-to-create
1690 "Non-nil means internal links in Org files must exactly match a headline.
1691 When nil, the link search tries to match a phrase with all words
1692 in the search text."
1693 :group
'org-link-follow
1696 (const :tag
"Use fuzzy text search" nil
)
1697 (const :tag
"Match only exact headline" t
)
1698 (const :tag
"Match exact headline or query to create it"
1701 (defcustom org-link-frame-setup
1702 '((vm . vm-visit-folder-other-frame
)
1703 (vm-imap . vm-visit-imap-folder-other-frame
)
1704 (gnus . org-gnus-no-new-news
)
1705 (file . find-file-other-window
)
1706 (wl . wl-other-frame
))
1707 "Setup the frame configuration for following links.
1708 When following a link with Emacs, it may often be useful to display
1709 this link in another window or frame. This variable can be used to
1710 set this up for the different types of links.
1713 `vm-visit-folder-other-window'
1714 `vm-visit-folder-other-frame'
1715 For Gnus, use any of
1718 `org-gnus-no-new-news'
1719 For FILE, use any of
1721 `find-file-other-window'
1722 `find-file-other-frame'
1723 For Wanderlust use any of
1726 For the calendar, use the variable `calendar-setup'.
1727 For BBDB, it is currently only possible to display the matches in
1729 :group
'org-link-follow
1733 (const vm-visit-folder
)
1734 (const vm-visit-folder-other-window
)
1735 (const vm-visit-folder-other-frame
)))
1739 (const gnus-other-frame
)
1740 (const org-gnus-no-new-news
)))
1744 (const find-file-other-window
)
1745 (const find-file-other-frame
)))
1749 (const wl-other-frame
)))))
1751 (defcustom org-display-internal-link-with-indirect-buffer nil
1752 "Non-nil means use indirect buffer to display infile links.
1753 Activating internal links (from one location in a file to another location
1754 in the same file) normally just jumps to the location. When the link is
1755 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1757 another window. When this option is set, the other window actually displays
1758 an indirect buffer clone of the current buffer, to avoid any visibility
1759 changes to the current buffer."
1760 :group
'org-link-follow
1763 (defcustom org-open-non-existing-files nil
1764 "Non-nil means `org-open-file' will open non-existing files.
1765 When nil, an error will be generated.
1766 This variable applies only to external applications because they
1767 might choke on non-existing files. If the link is to a file that
1768 will be opened in Emacs, the variable is ignored."
1769 :group
'org-link-follow
1772 (defcustom org-open-directory-means-index-dot-org nil
1773 "Non-nil means a link to a directory really means to index.org.
1774 When nil, following a directory link will run dired or open a finder/explorer
1775 window on that directory."
1776 :group
'org-link-follow
1779 (defcustom org-link-mailto-program
'(browse-url "mailto:%a?subject=%s")
1780 "Function and arguments to call for following mailto links.
1781 This is a list with the first element being a Lisp function, and the
1782 remaining elements being arguments to the function. In string arguments,
1783 %a will be replaced by the address, and %s will be replaced by the subject
1784 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1785 :group
'org-link-follow
1787 (const :tag
"browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1788 (const :tag
"compose-mail" (compose-mail "%a" "%s"))
1789 (const :tag
"message-mail" (message-mail "%a" "%s"))
1790 (cons :tag
"other" (function) (repeat :tag
"argument" sexp
))))
1792 (defcustom org-confirm-shell-link-function
'yes-or-no-p
1793 "Non-nil means ask for confirmation before executing shell links.
1794 Shell links can be dangerous: just think about a link
1796 [[shell:rm -rf ~/*][Google Search]]
1798 This link would show up in your Org-mode document as \"Google Search\",
1799 but really it would remove your entire home directory.
1800 Therefore we advise against setting this variable to nil.
1801 Just change it to `y-or-n-p' if you want to confirm with a
1802 single keystroke rather than having to type \"yes\"."
1803 :group
'org-link-follow
1805 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1806 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1807 (const :tag
"no confirmation (dangerous)" nil
)))
1808 (put 'org-confirm-shell-link-function
1809 'safe-local-variable
1810 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1812 (defcustom org-confirm-shell-link-not-regexp
""
1813 "A regexp to skip confirmation for shell links."
1814 :group
'org-link-follow
1818 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
1819 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1820 Elisp links can be dangerous: just think about a link
1822 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1824 This link would show up in your Org-mode document as \"Google Search\",
1825 but really it would remove your entire home directory.
1826 Therefore we advise against setting this variable to nil.
1827 Just change it to `y-or-n-p' if you want to confirm with a
1828 single keystroke rather than having to type \"yes\"."
1829 :group
'org-link-follow
1831 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1832 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1833 (const :tag
"no confirmation (dangerous)" nil
)))
1834 (put 'org-confirm-shell-link-function
1835 'safe-local-variable
1836 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1838 (defcustom org-confirm-elisp-link-not-regexp
""
1839 "A regexp to skip confirmation for Elisp links."
1840 :group
'org-link-follow
1844 (defconst org-file-apps-defaults-gnu
1848 "Default file applications on a UNIX or GNU/Linux system.
1849 See `org-file-apps'.")
1851 (defconst org-file-apps-defaults-macosx
1854 (system .
"open %s")
1856 ("eps.gz" .
"gv %s")
1858 ("fig" .
"xfig %s"))
1859 "Default file applications on a MacOS X system.
1860 The system \"open\" is known as a default, but we use X11 applications
1861 for some files for which the OS does not have a good default.
1862 See `org-file-apps'.")
1864 (defconst org-file-apps-defaults-windowsnt
1868 (list (if (featurep 'xemacs
)
1869 'mswindows-shell-execute
1873 (list (if (featurep 'xemacs
)
1874 'mswindows-shell-execute
1877 "Default file applications on a Windows NT system.
1878 The system \"open\" is used for most files.
1879 See `org-file-apps'.")
1881 (defcustom org-file-apps
1884 ("\\.mm\\'" . default
)
1885 ("\\.x?html?\\'" . default
)
1886 ("\\.pdf\\'" . default
)
1888 "External applications for opening `file:path' items in a document.
1889 Org-mode uses system defaults for different file types, but
1890 you can use this variable to set the application for a given file
1891 extension. The entries in this list are cons cells where the car identifies
1892 files and the cdr the corresponding command. Possible values for the
1894 \"string\" A string as a file identifier can be interpreted in different
1895 ways, depending on its contents:
1897 - Alphanumeric characters only:
1898 Match links with this file extension.
1899 Example: (\"pdf\" . \"evince %s\")
1900 to open PDFs with evince.
1902 - Regular expression: Match links where the
1903 filename matches the regexp. If you want to
1904 use groups here, use shy groups.
1906 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1907 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1908 to open *.html and *.xhtml with firefox.
1910 - Regular expression which contains (non-shy) groups:
1911 Match links where the whole link, including \"::\", and
1912 anything after that, matches the regexp.
1913 In a custom command string, %1, %2, etc. are replaced with
1914 the parts of the link that were matched by the groups.
1915 For backwards compatibility, if a command string is given
1916 that does not use any of the group matches, this case is
1917 handled identically to the second one (i.e. match against
1919 In a custom lisp form, you can access the group matches with
1920 (match-string n link).
1922 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1923 to open [[file:document.pdf::5]] with evince at page 5.
1925 `directory' Matches a directory
1926 `remote' Matches a remote file, accessible through tramp or efs.
1927 Remote files most likely should be visited through Emacs
1928 because external applications cannot handle such paths.
1929 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1930 so all files Emacs knows how to handle. Using this with
1931 command `emacs' will open most files in Emacs. Beware that this
1932 will also open html files inside Emacs, unless you add
1933 (\"html\" . default) to the list as well.
1934 t Default for files not matched by any of the other options.
1935 `system' The system command to open files, like `open' on Windows
1936 and Mac OS X, and mailcap under GNU/Linux. This is the command
1937 that will be selected if you call `C-c C-o' with a double
1938 \\[universal-argument] \\[universal-argument] prefix.
1940 Possible values for the command are:
1941 `emacs' The file will be visited by the current Emacs process.
1942 `default' Use the default application for this file type, which is the
1943 association for t in the list, most likely in the system-specific
1945 This can be used to overrule an unwanted setting in the
1946 system-specific variable.
1947 `system' Use the system command for opening files, like \"open\".
1948 This command is specified by the entry whose car is `system'.
1949 Most likely, the system-specific version of this variable
1950 does define this command, but you can overrule/replace it
1952 string A command to be executed by a shell; %s will be replaced
1953 by the path to the file.
1954 sexp A Lisp form which will be evaluated. The file path will
1955 be available in the Lisp variable `file'.
1956 For more examples, see the system specific constants
1957 `org-file-apps-defaults-macosx'
1958 `org-file-apps-defaults-windowsnt'
1959 `org-file-apps-defaults-gnu'."
1960 :group
'org-link-follow
1962 (cons (choice :value
""
1963 (string :tag
"Extension")
1964 (const :tag
"System command to open files" system
)
1965 (const :tag
"Default for unrecognized files" t
)
1966 (const :tag
"Remote file" remote
)
1967 (const :tag
"Links to a directory" directory
)
1968 (const :tag
"Any files that have Emacs modes"
1971 (const :tag
"Visit with Emacs" emacs
)
1972 (const :tag
"Use default" default
)
1973 (const :tag
"Use the system command" system
)
1974 (string :tag
"Command")
1975 (sexp :tag
"Lisp form")))))
1977 (defcustom org-doi-server-url
"http://dx.doi.org/"
1978 "The URL of the DOI server."
1981 :group
'org-link-follow
)
1983 (defgroup org-refile nil
1984 "Options concerning refiling entries in Org-mode."
1988 (defcustom org-directory
"~/org"
1989 "Directory with org files.
1990 This is just a default location to look for Org files. There is no need
1991 at all to put your files into this directory. It is only used in the
1992 following situations:
1994 1. When a capture template specifies a target file that is not an
1995 absolute path. The path will then be interpreted relative to
1997 2. When a capture note is filed away in an interactive way (when exiting the
1998 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1999 with `org-directory' as the default path."
2001 :group
'org-remember
2005 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
2006 "Default target for storing notes.
2007 Used as a fall back file for org-remember.el and org-capture.el, for
2008 templates that do not specify a target file."
2010 :group
'org-remember
2013 (const :tag
"Default from remember-data-file" nil
)
2016 (defcustom org-goto-interface
'outline
2017 "The default interface to be used for `org-goto'.
2019 outline The interface shows an outline of the relevant file
2020 and the correct heading is found by moving through
2021 the outline or by searching with incremental search.
2022 outline-path-completion Headlines in the current buffer are offered via
2023 completion. This is the interface also used by
2024 the refile command."
2027 (const :tag
"Outline" outline
)
2028 (const :tag
"Outline-path-completion" outline-path-completion
)))
2030 (defcustom org-goto-max-level
5
2031 "Maximum target level when running `org-goto' with refile interface."
2035 (defcustom org-reverse-note-order nil
2036 "Non-nil means store new notes at the beginning of a file or entry.
2037 When nil, new notes will be filed to the end of a file or entry.
2038 This can also be a list with cons cells of regular expressions that
2039 are matched against file names, and values."
2040 :group
'org-remember
2044 (const :tag
"Reverse always" t
)
2045 (const :tag
"Reverse never" nil
)
2046 (repeat :tag
"By file name regexp"
2047 (cons regexp boolean
))))
2049 (defcustom org-log-refile nil
2050 "Information to record when a task is refiled.
2052 Possible values are:
2054 nil Don't add anything
2055 time Add a time stamp to the task
2056 note Prompt for a note and add it with template `org-log-note-headings'
2058 This option can also be set with on a per-file-basis with
2060 #+STARTUP: nologrefile
2061 #+STARTUP: logrefile
2062 #+STARTUP: lognoterefile
2064 You can have local logging settings for a subtree by setting the LOGGING
2065 property to one or more of these keywords.
2067 When bulk-refiling from the agenda, the value `note' is forbidden and
2068 will temporarily be changed to `time'."
2070 :group
'org-progress
2073 (const :tag
"No logging" nil
)
2074 (const :tag
"Record timestamp" time
)
2075 (const :tag
"Record timestamp with note." note
)))
2077 (defcustom org-refile-targets nil
2078 "Targets for refiling entries with \\[org-refile].
2079 This is a list of cons cells. Each cell contains:
2080 - a specification of the files to be considered, either a list of files,
2081 or a symbol whose function or variable value will be used to retrieve
2082 a file name or a list of file names. If you use `org-agenda-files' for
2083 that, all agenda files will be scanned for targets. Nil means consider
2084 headings in the current buffer.
2085 - A specification of how to find candidate refile targets. This may be
2087 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2088 This tag has to be present in all target headlines, inheritance will
2090 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2092 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2093 headlines that are refiling targets.
2094 - a cons cell (:level . N). Any headline of level N is considered a target.
2095 Note that, when `org-odd-levels-only' is set, level corresponds to
2096 order in hierarchy, not to the number of stars.
2097 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2098 Note that, when `org-odd-levels-only' is set, level corresponds to
2099 order in hierarchy, not to the number of stars.
2101 Each element of this list generates a set of possible targets.
2102 The union of these sets is presented (with completion) to
2103 the user by `org-refile'.
2105 You can set the variable `org-refile-target-verify-function' to a function
2106 to verify each headline found by the simple criteria above.
2108 When this variable is nil, all top-level headlines in the current buffer
2109 are used, equivalent to the value `((nil . (:level . 1))'."
2113 (choice :value org-agenda-files
2114 (const :tag
"All agenda files" org-agenda-files
)
2115 (const :tag
"Current buffer" nil
)
2116 (function) (variable) (file))
2117 (choice :tag
"Identify target headline by"
2118 (cons :tag
"Specific tag" (const :value
:tag
) (string))
2119 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
2120 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
2121 (cons :tag
"Level number" (const :value
:level
) (integer))
2122 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2124 (defcustom org-refile-target-verify-function nil
2125 "Function to verify if the headline at point should be a refile target.
2126 The function will be called without arguments, with point at the
2127 beginning of the headline. It should return t and leave point
2128 where it is if the headline is a valid target for refiling.
2130 If the target should not be selected, the function must return nil.
2131 In addition to this, it may move point to a place from where the search
2132 should be continued. For example, the function may decide that the entire
2133 subtree of the current entry should be excluded and move point to the end
2138 (defcustom org-refile-use-cache nil
2139 "Non-nil means cache refile targets to speed up the process.
2140 The cache for a particular file will be updated automatically when
2141 the buffer has been killed, or when any of the marker used for flagging
2142 refile targets no longer points at a live buffer.
2143 If you have added new entries to a buffer that might themselves be targets,
2144 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2145 find that easier, `C-u C-u C-u C-c C-w'."
2150 (defcustom org-refile-use-outline-path nil
2151 "Non-nil means provide refile targets as paths.
2152 So a level 3 headline will be available as level1/level2/level3.
2154 When the value is `file', also include the file name (without directory)
2155 into the path. In this case, you can also stop the completion after
2156 the file name, to get entries inserted as top level in the file.
2158 When `full-file-path', include the full file path."
2161 (const :tag
"Not" nil
)
2162 (const :tag
"Yes" t
)
2163 (const :tag
"Start with file name" file
)
2164 (const :tag
"Start with full file path" full-file-path
)))
2166 (defcustom org-outline-path-complete-in-steps t
2167 "Non-nil means complete the outline path in hierarchical steps.
2168 When Org-mode uses the refile interface to select an outline path
2169 \(see variable `org-refile-use-outline-path'), the completion of
2170 the path can be done is a single go, or if can be done in steps down
2171 the headline hierarchy. Going in steps is probably the best if you
2172 do not use a special completion package like `ido' or `icicles'.
2173 However, when using these packages, going in one step can be very
2174 fast, while still showing the whole path to the entry."
2178 (defcustom org-refile-allow-creating-parent-nodes nil
2179 "Non-nil means allow to create new nodes as refile targets.
2180 New nodes are then created by adding \"/new node name\" to the completion
2181 of an existing node. When the value of this variable is `confirm',
2182 new node creation must be confirmed by the user (recommended)
2183 When nil, the completion must match an existing entry.
2185 Note that, if the new heading is not seen by the criteria
2186 listed in `org-refile-targets', multiple instances of the same
2187 heading would be created by trying again to file under the new
2191 (const :tag
"Never" nil
)
2192 (const :tag
"Always" t
)
2193 (const :tag
"Prompt for confirmation" confirm
)))
2195 (defcustom org-refile-active-region-within-subtree nil
2196 "Non-nil means also refile active region within a subtree.
2198 By default `org-refile' doesn't allow refiling regions if they
2199 don't contain a set of subtrees, but it might be convenient to
2200 do so sometimes: in that case, the first line of the region is
2201 converted to a headline before refiling."
2206 (defgroup org-todo nil
2207 "Options concerning TODO items in Org-mode."
2211 (defgroup org-progress nil
2212 "Options concerning Progress logging in Org-mode."
2216 (defvar org-todo-interpretation-widgets
2217 '((:tag
"Sequence (cycling hits every state)" sequence
)
2218 (:tag
"Type (cycling directly to DONE)" type
))
2219 "The available interpretation symbols for customizing `org-todo-keywords'.
2220 Interested libraries should add to this list.")
2222 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2223 "List of TODO entry keyword sequences and their interpretation.
2224 \\<org-mode-map>This is a list of sequences.
2226 Each sequence starts with a symbol, either `sequence' or `type',
2227 indicating if the keywords should be interpreted as a sequence of
2228 action steps, or as different types of TODO items. The first
2229 keywords are states requiring action - these states will select a headline
2230 for inclusion into the global TODO list Org-mode produces. If one of
2231 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2232 signify that no further action is necessary. If \"|\" is not found,
2233 the last keyword is treated as the only DONE state of the sequence.
2235 The command \\[org-todo] cycles an entry through these states, and one
2236 additional state where no keyword is present. For details about this
2237 cycling, see the manual.
2239 TODO keywords and interpretation can also be set on a per-file basis with
2240 the special #+SEQ_TODO and #+TYP_TODO lines.
2242 Each keyword can optionally specify a character for fast state selection
2243 \(in combination with the variable `org-use-fast-todo-selection')
2244 and specifiers for state change logging, using the same syntax that
2245 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2246 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2247 indicates to record a time stamp each time this state is selected.
2249 Each keyword may also specify if a timestamp or a note should be
2250 recorded when entering or leaving the state, by adding additional
2251 characters in the parenthesis after the keyword. This looks like this:
2252 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2253 record only the time of the state change. With X and Y being either
2254 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2255 Y when leaving the state if and only if the *target* state does not
2256 define X. You may omit any of the fast-selection key or X or /Y,
2257 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2259 For backward compatibility, this variable may also be just a list
2260 of keywords. In this case the interpretation (sequence or type) will be
2261 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2263 :group
'org-keywords
2265 (repeat :tag
"Old syntax, just keywords"
2266 (string :tag
"Keyword"))
2267 (repeat :tag
"New syntax"
2270 :tag
"Interpretation"
2271 ;;Quick and dirty way to see
2272 ;;`org-todo-interpretations'. This takes the
2273 ;;place of item arguments
2281 org-todo-interpretation-widgets
))
2284 (string :tag
"Keyword"))))))
2286 (defvar org-todo-keywords-1 nil
2287 "All TODO and DONE keywords active in a buffer.")
2288 (make-variable-buffer-local 'org-todo-keywords-1
)
2289 (defvar org-todo-keywords-for-agenda nil
)
2290 (defvar org-done-keywords-for-agenda nil
)
2291 (defvar org-drawers-for-agenda nil
)
2292 (defvar org-todo-keyword-alist-for-agenda nil
)
2293 (defvar org-tag-alist-for-agenda nil
2294 "Alist of all tags from all agenda files.")
2295 (defvar org-tag-groups-alist-for-agenda nil
2296 "Alist of all groups tags from all current agenda files.")
2297 (defvar org-tag-groups-alist nil
)
2298 (make-variable-buffer-local 'org-tag-groups-alist
)
2299 (defvar org-agenda-contributing-files nil
)
2300 (defvar org-not-done-keywords nil
)
2301 (make-variable-buffer-local 'org-not-done-keywords
)
2302 (defvar org-done-keywords nil
)
2303 (make-variable-buffer-local 'org-done-keywords
)
2304 (defvar org-todo-heads nil
)
2305 (make-variable-buffer-local 'org-todo-heads
)
2306 (defvar org-todo-sets nil
)
2307 (make-variable-buffer-local 'org-todo-sets
)
2308 (defvar org-todo-log-states nil
)
2309 (make-variable-buffer-local 'org-todo-log-states
)
2310 (defvar org-todo-kwd-alist nil
)
2311 (make-variable-buffer-local 'org-todo-kwd-alist
)
2312 (defvar org-todo-key-alist nil
)
2313 (make-variable-buffer-local 'org-todo-key-alist
)
2314 (defvar org-todo-key-trigger nil
)
2315 (make-variable-buffer-local 'org-todo-key-trigger
)
2317 (defcustom org-todo-interpretation
'sequence
2318 "Controls how TODO keywords are interpreted.
2319 This variable is in principle obsolete and is only used for
2320 backward compatibility, if the interpretation of todo keywords is
2321 not given already in `org-todo-keywords'. See that variable for
2324 :group
'org-keywords
2325 :type
'(choice (const sequence
)
2328 (defcustom org-use-fast-todo-selection t
2329 "Non-nil means use the fast todo selection scheme with C-c C-t.
2330 This variable describes if and under what circumstances the cycling
2331 mechanism for TODO keywords will be replaced by a single-key, direct
2334 When nil, fast selection is never used.
2336 When the symbol `prefix', it will be used when `org-todo' is called
2337 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2338 `C-u t' in an agenda buffer.
2340 When t, fast selection is used by default. In this case, the prefix
2341 argument forces cycling instead.
2343 In all cases, the special interface is only used if access keys have
2344 actually been assigned by the user, i.e. if keywords in the configuration
2345 are followed by a letter in parenthesis, like TODO(t)."
2348 (const :tag
"Never" nil
)
2349 (const :tag
"By default" t
)
2350 (const :tag
"Only with C-u C-c C-t" prefix
)))
2352 (defcustom org-provide-todo-statistics t
2353 "Non-nil means update todo statistics after insert and toggle.
2354 ALL-HEADLINES means update todo statistics by including headlines
2355 with no TODO keyword as well, counting them as not done.
2356 A list of TODO keywords means the same, but skip keywords that are
2359 When this is set, todo statistics is updated in the parent of the
2360 current entry each time a todo state is changed."
2363 (const :tag
"Yes, only for TODO entries" t
)
2364 (const :tag
"Yes, including all entries" 'all-headlines
)
2365 (repeat :tag
"Yes, for TODOs in this list"
2366 (string :tag
"TODO keyword"))
2367 (other :tag
"No TODO statistics" nil
)))
2369 (defcustom org-hierarchical-todo-statistics t
2370 "Non-nil means TODO statistics covers just direct children.
2371 When nil, all entries in the subtree are considered.
2372 This has only an effect if `org-provide-todo-statistics' is set.
2373 To set this to nil for only a single subtree, use a COOKIE_DATA
2374 property and include the word \"recursive\" into the value."
2378 (defcustom org-after-todo-state-change-hook nil
2379 "Hook which is run after the state of a TODO item was changed.
2380 The new state (a string with a TODO keyword, or nil) is available in the
2381 Lisp variable `org-state'."
2385 (defvar org-blocker-hook nil
2386 "Hook for functions that are allowed to block a state change.
2388 Functions in this hook should not modify the buffer.
2389 Each function gets as its single argument a property list,
2390 see `org-trigger-hook' for more information about this list.
2392 If any of the functions in this hook returns nil, the state change
2395 (defvar org-trigger-hook nil
2396 "Hook for functions that are triggered by a state change.
2398 Each function gets as its single argument a property list with at
2399 least the following elements:
2401 (:type type-of-change :position pos-at-entry-start
2402 :from old-state :to new-state)
2404 Depending on the type, more properties may be present.
2406 This mechanism is currently implemented for:
2410 :type todo-state-change
2411 :from previous state (keyword as a string), or nil, or a symbol
2412 'todo' or 'done', to indicate the general type of state.
2413 :to new state, like in :from")
2415 (defcustom org-enforce-todo-dependencies nil
2416 "Non-nil means undone TODO entries will block switching the parent to DONE.
2417 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2418 be blocked if any prior sibling is not yet done.
2419 Finally, if the parent is blocked because of ordered siblings of its own,
2420 the child will also be blocked."
2421 :set
(lambda (var val
)
2424 (add-hook 'org-blocker-hook
2425 'org-block-todo-from-children-or-siblings-or-parent
)
2426 (remove-hook 'org-blocker-hook
2427 'org-block-todo-from-children-or-siblings-or-parent
)))
2431 (defcustom org-enforce-todo-checkbox-dependencies nil
2432 "Non-nil means unchecked boxes will block switching the parent to DONE.
2433 When this is nil, checkboxes have no influence on switching TODO states.
2434 When non-nil, you first need to check off all check boxes before the TODO
2435 entry can be switched to DONE.
2436 This variable needs to be set before org.el is loaded, and you need to
2437 restart Emacs after a change to make the change effective. The only way
2438 to change is while Emacs is running is through the customize interface."
2439 :set
(lambda (var val
)
2442 (add-hook 'org-blocker-hook
2443 'org-block-todo-from-checkboxes
)
2444 (remove-hook 'org-blocker-hook
2445 'org-block-todo-from-checkboxes
)))
2449 (defcustom org-treat-insert-todo-heading-as-state-change nil
2450 "Non-nil means inserting a TODO heading is treated as state change.
2451 So when the command \\[org-insert-todo-heading] is used, state change
2452 logging will apply if appropriate. When nil, the new TODO item will
2453 be inserted directly, and no logging will take place."
2457 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2458 "Non-nil means switching TODO states with S-cursor counts as state change.
2459 This is the default behavior. However, setting this to nil allows a
2460 convenient way to select a TODO state and bypass any logging associated
2465 (defcustom org-todo-state-tags-triggers nil
2466 "Tag changes that should be triggered by TODO state changes.
2467 This is a list. Each entry is
2469 (state-change (tag . flag) .......)
2471 State-change can be a string with a state, and empty string to indicate the
2472 state that has no TODO keyword, or it can be one of the symbols `todo'
2473 or `done', meaning any not-done or done state, respectively."
2477 (cons (choice :tag
"When changing to"
2478 (const :tag
"Not-done state" todo
)
2479 (const :tag
"Done state" done
)
2480 (string :tag
"State"))
2482 (cons :tag
"Tag action"
2484 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2486 (defcustom org-log-done nil
2487 "Information to record when a task moves to the DONE state.
2489 Possible values are:
2491 nil Don't add anything, just change the keyword
2492 time Add a time stamp to the task
2493 note Prompt for a note and add it with template `org-log-note-headings'
2495 This option can also be set with on a per-file-basis with
2497 #+STARTUP: nologdone
2499 #+STARTUP: lognotedone
2501 You can have local logging settings for a subtree by setting the LOGGING
2502 property to one or more of these keywords."
2504 :group
'org-progress
2506 (const :tag
"No logging" nil
)
2507 (const :tag
"Record CLOSED timestamp" time
)
2508 (const :tag
"Record CLOSED timestamp with note." note
)))
2510 ;; Normalize old uses of org-log-done.
2512 ((eq org-log-done t
) (setq org-log-done
'time
))
2513 ((and (listp org-log-done
) (memq 'done org-log-done
))
2514 (setq org-log-done
'note
)))
2516 (defcustom org-log-reschedule nil
2517 "Information to record when the scheduling date of a tasks is modified.
2519 Possible values are:
2521 nil Don't add anything, just change the date
2522 time Add a time stamp to the task
2523 note Prompt for a note and add it with template `org-log-note-headings'
2525 This option can also be set with on a per-file-basis with
2527 #+STARTUP: nologreschedule
2528 #+STARTUP: logreschedule
2529 #+STARTUP: lognotereschedule"
2531 :group
'org-progress
2533 (const :tag
"No logging" nil
)
2534 (const :tag
"Record timestamp" time
)
2535 (const :tag
"Record timestamp with note." note
)))
2537 (defcustom org-log-redeadline nil
2538 "Information to record when the deadline date of a tasks is modified.
2540 Possible values are:
2542 nil Don't add anything, just change the date
2543 time Add a time stamp to the task
2544 note Prompt for a note and add it with template `org-log-note-headings'
2546 This option can also be set with on a per-file-basis with
2548 #+STARTUP: nologredeadline
2549 #+STARTUP: logredeadline
2550 #+STARTUP: lognoteredeadline
2552 You can have local logging settings for a subtree by setting the LOGGING
2553 property to one or more of these keywords."
2555 :group
'org-progress
2557 (const :tag
"No logging" nil
)
2558 (const :tag
"Record timestamp" time
)
2559 (const :tag
"Record timestamp with note." note
)))
2561 (defcustom org-log-note-clock-out nil
2562 "Non-nil means record a note when clocking out of an item.
2563 This can also be configured on a per-file basis by adding one of
2564 the following lines anywhere in the buffer:
2566 #+STARTUP: lognoteclock-out
2567 #+STARTUP: nolognoteclock-out"
2569 :group
'org-progress
2572 (defcustom org-log-done-with-time t
2573 "Non-nil means the CLOSED time stamp will contain date and time.
2574 When nil, only the date will be recorded."
2575 :group
'org-progress
2578 (defcustom org-log-note-headings
2579 '((done .
"CLOSING NOTE %t")
2580 (state .
"State %-12s from %-12S %t")
2581 (note .
"Note taken on %t")
2582 (reschedule .
"Rescheduled from %S on %t")
2583 (delschedule .
"Not scheduled, was %S on %t")
2584 (redeadline .
"New deadline from %S on %t")
2585 (deldeadline .
"Removed deadline, was %S on %t")
2586 (refile .
"Refiled on %t")
2588 "Headings for notes added to entries.
2589 The value is an alist, with the car being a symbol indicating the note
2590 context, and the cdr is the heading to be used. The heading may also be the
2592 %t in the heading will be replaced by a time stamp.
2593 %T will be an active time stamp instead the default inactive one
2594 %d will be replaced by a short-format time stamp.
2595 %D will be replaced by an active short-format time stamp.
2596 %s will be replaced by the new TODO state, in double quotes.
2597 %S will be replaced by the old TODO state, in double quotes.
2598 %u will be replaced by the user name.
2599 %U will be replaced by the full user name.
2601 In fact, it is not a good idea to change the `state' entry, because
2602 agenda log mode depends on the format of these entries."
2604 :group
'org-progress
2605 :type
'(list :greedy t
2606 (cons (const :tag
"Heading when closing an item" done
) string
)
2608 "Heading when changing todo state (todo sequence only)"
2610 (cons (const :tag
"Heading when just taking a note" note
) string
)
2611 (cons (const :tag
"Heading when clocking out" clock-out
) string
)
2612 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2613 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2614 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2615 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2616 (cons (const :tag
"Heading when refiling" refile
) string
)))
2618 (unless (assq 'note org-log-note-headings
)
2619 (push '(note .
"%t") org-log-note-headings
))
2621 (defcustom org-log-into-drawer nil
2622 "Non-nil means insert state change notes and time stamps into a drawer.
2623 When nil, state changes notes will be inserted after the headline and
2624 any scheduling and clock lines, but not inside a drawer.
2626 The value of this variable should be the name of the drawer to use.
2627 LOGBOOK is proposed as the default drawer for this purpose, you can
2628 also set this to a string to define the drawer of your choice.
2630 A value of t is also allowed, representing \"LOGBOOK\".
2632 A value of t or nil can also be set with on a per-file-basis with
2634 #+STARTUP: logdrawer
2635 #+STARTUP: nologdrawer
2637 If this variable is set, `org-log-state-notes-insert-after-drawers'
2640 You can set the property LOG_INTO_DRAWER to overrule this setting for
2643 :group
'org-progress
2645 (const :tag
"Not into a drawer" nil
)
2646 (const :tag
"LOGBOOK" t
)
2647 (string :tag
"Other")))
2649 (org-defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
)
2651 (defun org-log-into-drawer ()
2652 "Return the value of `org-log-into-drawer', but let properties overrule.
2653 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2654 used instead of the default value."
2655 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit t
)))
2657 ((not p
) org-log-into-drawer
)
2658 ((equal p
"nil") nil
)
2659 ((equal p
"t") "LOGBOOK")
2662 (defcustom org-log-state-notes-insert-after-drawers nil
2663 "Non-nil means insert state change notes after any drawers in entry.
2664 Only the drawers that *immediately* follow the headline and the
2665 deadline/scheduled line are skipped.
2666 When nil, insert notes right after the heading and perhaps the line
2667 with deadline/scheduling if present.
2669 This variable will have no effect if `org-log-into-drawer' is
2672 :group
'org-progress
2675 (defcustom org-log-states-order-reversed t
2676 "Non-nil means the latest state note will be directly after heading.
2677 When nil, the state change notes will be ordered according to time.
2679 This option can also be set with on a per-file-basis with
2681 #+STARTUP: logstatesreversed
2682 #+STARTUP: nologstatesreversed"
2684 :group
'org-progress
2687 (defcustom org-todo-repeat-to-state nil
2688 "The TODO state to which a repeater should return the repeating task.
2689 By default this is the first task in a TODO sequence, or the previous state
2690 in a TODO_TYP set. But you can specify another task here.
2691 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2694 :type
'(choice (const :tag
"Head of sequence" nil
)
2695 (string :tag
"Specific state")))
2697 (defcustom org-log-repeat
'time
2698 "Non-nil means record moving through the DONE state when triggering repeat.
2699 An auto-repeating task is immediately switched back to TODO when
2700 marked DONE. If you are not logging state changes (by adding \"@\"
2701 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2702 record a closing note, there will be no record of the task moving
2703 through DONE. This variable forces taking a note anyway.
2705 nil Don't force a record
2706 time Record a time stamp
2707 note Prompt for a note and add it with template `org-log-note-headings'
2709 This option can also be set with on a per-file-basis with
2711 #+STARTUP: nologrepeat
2712 #+STARTUP: logrepeat
2713 #+STARTUP: lognoterepeat
2715 You can have local logging settings for a subtree by setting the LOGGING
2716 property to one or more of these keywords."
2718 :group
'org-progress
2720 (const :tag
"Don't force a record" nil
)
2721 (const :tag
"Force recording the DONE state" time
)
2722 (const :tag
"Force recording a note with the DONE state" note
)))
2725 (defgroup org-priorities nil
2726 "Priorities in Org-mode."
2727 :tag
"Org Priorities"
2730 (defcustom org-enable-priority-commands t
2731 "Non-nil means priority commands are active.
2732 When nil, these commands will be disabled, so that you never accidentally
2734 :group
'org-priorities
2737 (defcustom org-highest-priority ?A
2738 "The highest priority of TODO items. A character like ?A, ?B etc.
2739 Must have a smaller ASCII number than `org-lowest-priority'."
2740 :group
'org-priorities
2743 (defcustom org-lowest-priority ?C
2744 "The lowest priority of TODO items. A character like ?A, ?B etc.
2745 Must have a larger ASCII number than `org-highest-priority'."
2746 :group
'org-priorities
2749 (defcustom org-default-priority ?B
2750 "The default priority of TODO items.
2751 This is the priority an item gets if no explicit priority is given.
2752 When starting to cycle on an empty priority the first step in the cycle
2753 depends on `org-priority-start-cycle-with-default'. The resulting first
2754 step priority must not exceed the range from `org-highest-priority' to
2755 `org-lowest-priority' which means that `org-default-priority' has to be
2756 in this range exclusive or inclusive the range boundaries. Else the
2757 first step refuses to set the default and the second will fall back
2758 to (depending on the command used) the highest or lowest priority."
2759 :group
'org-priorities
2762 (defcustom org-priority-start-cycle-with-default t
2763 "Non-nil means start with default priority when starting to cycle.
2764 When this is nil, the first step in the cycle will be (depending on the
2765 command used) one higher or lower than the default priority.
2766 See also `org-default-priority'."
2767 :group
'org-priorities
2770 (defcustom org-get-priority-function nil
2771 "Function to extract the priority from a string.
2772 The string is normally the headline. If this is nil Org computes the
2773 priority from the priority cookie like [#A] in the headline. It returns
2774 an integer, increasing by 1000 for each priority level.
2775 The user can set a different function here, which should take a string
2776 as an argument and return the numeric priority."
2777 :group
'org-priorities
2781 (defgroup org-time nil
2782 "Options concerning time stamps and deadlines in Org-mode."
2786 (defcustom org-insert-labeled-timestamps-at-point nil
2787 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2788 When nil, these labeled time stamps are forces into the second line of an
2789 entry, just after the headline. When scheduling from the global TODO list,
2790 the time stamp will always be forced into the second line."
2794 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
2795 "Formats for `format-time-string' which are used for time stamps.
2796 It is not recommended to change this constant.")
2798 (defcustom org-time-stamp-rounding-minutes
'(0 5)
2799 "Number of minutes to round time stamps to.
2800 These are two values, the first applies when first creating a time stamp.
2801 The second applies when changing it with the commands `S-up' and `S-down'.
2802 When changing the time stamp, this means that it will change in steps
2803 of N minutes, as given by the second value.
2805 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2806 numbers should be factors of 60, so for example 5, 10, 15.
2808 When this is larger than 1, you can still force an exact time stamp by using
2809 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2810 and by using a prefix arg to `S-up/down' to specify the exact number
2811 of minutes to shift."
2813 :get
#'(lambda (var) ; Make sure both elements are there
2814 (if (integerp (default-value var
))
2815 (list (default-value var
) 5)
2816 (default-value var
)))
2818 (integer :tag
"when inserting times")
2819 (integer :tag
"when modifying times")))
2821 ;; Normalize old customizations of this variable.
2822 (when (integerp org-time-stamp-rounding-minutes
)
2823 (setq org-time-stamp-rounding-minutes
2824 (list org-time-stamp-rounding-minutes
2825 org-time-stamp-rounding-minutes
)))
2827 (defcustom org-display-custom-times nil
2828 "Non-nil means overlay custom formats over all time stamps.
2829 The formats are defined through the variable `org-time-stamp-custom-formats'.
2830 To turn this on on a per-file basis, insert anywhere in the file:
2831 #+STARTUP: customtime"
2835 (make-variable-buffer-local 'org-display-custom-times
)
2837 (defcustom org-time-stamp-custom-formats
2838 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
2839 "Custom formats for time stamps. See `format-time-string' for the syntax.
2840 These are overlaid over the default ISO format if the variable
2841 `org-display-custom-times' is set. Time like %H:%M should be at the
2842 end of the second format. The custom formats are also honored by export
2843 commands, if custom time display is turned on at the time of export."
2847 (defun org-time-stamp-format (&optional long inactive
)
2848 "Get the right format for a time string."
2849 (let ((f (if long
(cdr org-time-stamp-formats
)
2850 (car org-time-stamp-formats
))))
2852 (concat "[" (substring f
1 -
1) "]")
2855 (defcustom org-time-clocksum-format
2856 '(:days
"%dd " :hours
"%d" :require-hours t
:minutes
":%02d" :require-minutes t
)
2857 "The format string used when creating CLOCKSUM lines.
2858 This is also used when Org mode generates a time duration.
2860 The value can be a single format string containing two
2861 %-sequences, which will be filled with the number of hours and
2862 minutes in that order.
2864 Alternatively, the value can be a plist associating any of the
2865 keys :years, :months, :weeks, :days, :hours or :minutes with
2866 format strings. The time duration is formatted using only the
2867 time components that are needed and concatenating the results.
2868 If a time unit in absent, it falls back to the next smallest
2871 The keys :require-years, :require-months, :require-days,
2872 :require-weeks, :require-hours, :require-minutes are also
2873 meaningful. A non-nil value for these keys indicates that the
2874 corresponding time component should always be included, even if
2880 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2883 means durations longer than a day will be expressed in days,
2884 hours and minutes, and durations less than a day will always be
2885 expressed in hours and minutes (even for durations less than an
2890 \(:days \"%dd\" :minutes \"%dm\")
2892 means durations longer than a day will be expressed in days and
2893 minutes, and durations less than a day will be expressed entirely
2894 in minutes (even for durations longer than an hour)."
2898 :package-version
'(Org .
"8.0")
2899 :type
'(choice (string :tag
"Format string")
2901 (group :inline t
(const :tag
"Years" :years
)
2902 (string :tag
"Format string"))
2904 (const :tag
"Always show years" :require-years
)
2906 (group :inline t
(const :tag
"Months" :months
)
2907 (string :tag
"Format string"))
2909 (const :tag
"Always show months" :require-months
)
2911 (group :inline t
(const :tag
"Weeks" :weeks
)
2912 (string :tag
"Format string"))
2914 (const :tag
"Always show weeks" :require-weeks
)
2916 (group :inline t
(const :tag
"Days" :days
)
2917 (string :tag
"Format string"))
2919 (const :tag
"Always show days" :require-days
)
2921 (group :inline t
(const :tag
"Hours" :hours
)
2922 (string :tag
"Format string"))
2924 (const :tag
"Always show hours" :require-hours
)
2926 (group :inline t
(const :tag
"Minutes" :minutes
)
2927 (string :tag
"Format string"))
2929 (const :tag
"Always show minutes" :require-minutes
)
2932 (defcustom org-time-clocksum-use-fractional nil
2933 "When non-nil, \\[org-clock-display] uses fractional times.
2934 See `org-time-clocksum-format' for more on time clock formats."
2940 (defcustom org-time-clocksum-use-effort-durations nil
2941 "When non-nil, \\[org-clock-display] uses effort durations.
2942 E.g. by default, one day is considered to be a 8 hours effort,
2943 so a task that has been clocked for 16 hours will be displayed
2944 as during 2 days in the clock display or in the clocktable.
2946 See `org-effort-durations' on how to set effort durations
2947 and `org-time-clocksum-format' for more on time clock formats."
2951 :package-version
'(Org .
"8.0")
2954 (defcustom org-time-clocksum-fractional-format
"%.2f"
2955 "The format string used when creating CLOCKSUM lines,
2956 or when Org mode generates a time duration, if
2957 `org-time-clocksum-use-fractional' is enabled.
2959 The value can be a single format string containing one
2960 %-sequence, which will be filled with the number of hours as
2963 Alternatively, the value can be a plist associating any of the
2964 keys :years, :months, :weeks, :days, :hours or :minutes with
2965 a format string. The time duration is formatted using the
2966 largest time unit which gives a non-zero integer part. If all
2967 specified formats have zero integer part, the smallest time unit
2970 :type
'(choice (string :tag
"Format string")
2971 (set (group :inline t
(const :tag
"Years" :years
)
2972 (string :tag
"Format string"))
2973 (group :inline t
(const :tag
"Months" :months
)
2974 (string :tag
"Format string"))
2975 (group :inline t
(const :tag
"Weeks" :weeks
)
2976 (string :tag
"Format string"))
2977 (group :inline t
(const :tag
"Days" :days
)
2978 (string :tag
"Format string"))
2979 (group :inline t
(const :tag
"Hours" :hours
)
2980 (string :tag
"Format string"))
2981 (group :inline t
(const :tag
"Minutes" :minutes
)
2982 (string :tag
"Format string")))))
2984 (defcustom org-deadline-warning-days
14
2985 "Number of days before expiration during which a deadline becomes active.
2986 This variable governs the display in sparse trees and in the agenda.
2987 When 0 or negative, it means use this number (the absolute value of it)
2988 even if a deadline has a different individual lead time specified.
2990 Custom commands can set this variable in the options section."
2992 :group
'org-agenda-daily
/weekly
2995 (defcustom org-scheduled-delay-days
0
2996 "Number of days before a scheduled item becomes active.
2997 This variable governs the display in sparse trees and in the agenda.
2998 The default value (i.e. 0) means: don't delay scheduled item.
2999 When negative, it means use this number (the absolute value of it)
3000 even if a scheduled item has a different individual delay time
3003 Custom commands can set this variable in the options section."
3005 :group
'org-agenda-daily
/weekly
3007 :package-version
'(Org .
"8.0")
3010 (defcustom org-read-date-prefer-future t
3011 "Non-nil means assume future for incomplete date input from user.
3012 This affects the following situations:
3013 1. The user gives a month but not a year.
3014 For example, if it is April and you enter \"feb 2\", this will be read
3015 as Feb 2, *next* year. \"May 5\", however, will be this year.
3016 2. The user gives a day, but no month.
3017 For example, if today is the 15th, and you enter \"3\", Org-mode will
3018 read this as the third of *next* month. However, if you enter \"17\",
3019 it will be considered as *this* month.
3021 If you set this variable to the symbol `time', then also the following
3024 3. If the user gives a time.
3025 If the time is before now, it will be interpreted as tomorrow.
3027 Currently none of this works for ISO week specifications.
3029 When this option is nil, the current day, month and year will always be
3032 See also `org-agenda-jump-prefer-future'."
3035 (const :tag
"Never" nil
)
3036 (const :tag
"Check month and day" t
)
3037 (const :tag
"Check month, day, and time" time
)))
3039 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
3040 "Should the agenda jump command prefer the future for incomplete dates?
3041 The default is to do the same as configured in `org-read-date-prefer-future'.
3042 But you can also set a deviating value here.
3043 This may t or nil, or the symbol `org-read-date-prefer-future'."
3048 (const :tag
"Use org-read-date-prefer-future"
3049 org-read-date-prefer-future
)
3050 (const :tag
"Never" nil
)
3051 (const :tag
"Always" t
)))
3053 (defcustom org-read-date-force-compatible-dates t
3054 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3056 Depending on the system Emacs is running on, certain dates cannot
3057 be represented with the type used internally to represent time.
3058 Dates between 1970-1-1 and 2038-1-1 can always be represented
3059 correctly. Some systems allow for earlier dates, some for later,
3060 some for both. One way to find out it to insert any date into an
3061 Org buffer, putting the cursor on the year and hitting S-up and
3062 S-down to test the range.
3064 When this variable is set to t, the date/time prompt will not let
3065 you specify dates outside the 1970-2037 range, so it is certain that
3066 these dates will work in whatever version of Emacs you are
3067 running, and also that you can move a file from one Emacs implementation
3068 to another. WHenever Org is forcing the year for you, it will display
3071 When this variable is nil, Org will check if the date is
3072 representable in the specific Emacs implementation you are using.
3073 If not, it will force a year, usually the current year, and beep
3074 to remind you. Currently this setting is not recommended because
3075 the likelihood that you will open your Org files in an Emacs that
3076 has limited date range is not negligible.
3078 A workaround for this problem is to use diary sexp dates for time
3079 stamps outside of this range."
3084 (defcustom org-read-date-display-live t
3085 "Non-nil means display current interpretation of date prompt live.
3086 This display will be in an overlay, in the minibuffer."
3090 (defcustom org-read-date-popup-calendar t
3091 "Non-nil means pop up a calendar when prompting for a date.
3092 In the calendar, the date can be selected with mouse-1. However, the
3093 minibuffer will also be active, and you can simply enter the date as well.
3094 When nil, only the minibuffer will be available."
3097 (org-defvaralias 'org-popup-calendar-for-date-prompt
3098 'org-read-date-popup-calendar
)
3100 (make-obsolete-variable
3101 'org-read-date-minibuffer-setup-hook
3102 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3103 (defcustom org-read-date-minibuffer-setup-hook nil
3104 "Hook to be used to set up keys for the date/time interface.
3105 Add key definitions to `minibuffer-local-map', which will be a
3108 WARNING: This option is obsolete, you should use
3109 `org-read-date-minibuffer-local-map' to set up keys."
3113 (defcustom org-extend-today-until
0
3114 "The hour when your day really ends. Must be an integer.
3115 This has influence for the following applications:
3116 - When switching the agenda to \"today\". It it is still earlier than
3117 the time given here, the day recognized as TODAY is actually yesterday.
3118 - When a date is read from the user and it is still before the time given
3119 here, the current date and time will be assumed to be yesterday, 23:59.
3120 Also, timestamps inserted in capture templates follow this rule.
3122 IMPORTANT: This is a feature whose implementation is and likely will
3123 remain incomplete. Really, it is only here because past midnight seems to
3124 be the favorite working time of John Wiegley :-)"
3128 (defcustom org-use-effective-time nil
3129 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3130 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3131 \"effective time\" of any timestamps between midnight and 8am will be
3132 23:59 of the previous day."
3137 (defcustom org-use-last-clock-out-time-as-effective-time nil
3138 "When non-nil, use the last clock out time for `org-todo'.
3139 Note that this option has precedence over the combined use of
3140 `org-use-effective-time' and `org-extend-today-until'."
3143 :package-version
'(Org .
"8.0")
3146 (defcustom org-edit-timestamp-down-means-later nil
3147 "Non-nil means S-down will increase the time in a time stamp.
3148 When nil, S-up will increase."
3152 (defcustom org-calendar-follow-timestamp-change t
3153 "Non-nil means make the calendar window follow timestamp changes.
3154 When a timestamp is modified and the calendar window is visible, it will be
3155 moved to the new date."
3159 (defgroup org-tags nil
3160 "Options concerning tags in Org-mode."
3164 (defcustom org-tag-alist nil
3165 "List of tags allowed in Org-mode files.
3166 When this list is nil, Org-mode will base TAG input on what is already in the
3168 The value of this variable is an alist, the car of each entry must be a
3169 keyword as a string, the cdr may be a character that is used to select
3170 that tag through the fast-tag-selection interface.
3171 See the manual for details."
3175 (cons (string :tag
"Tag name")
3176 (character :tag
"Access char"))
3177 (list :tag
"Start radio group"
3179 (option (string :tag
"Group description")))
3180 (list :tag
"Group tags delimiter"
3182 (list :tag
"End radio group"
3184 (option (string :tag
"Group description")))
3185 (const :tag
"New line" (:newline
)))))
3187 (defcustom org-tag-persistent-alist nil
3188 "List of tags that will always appear in all Org-mode files.
3189 This is in addition to any in buffer settings or customizations
3191 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3192 The value of this variable is an alist, the car of each entry must be a
3193 keyword as a string, the cdr may be a character that is used to select
3194 that tag through the fast-tag-selection interface.
3195 See the manual for details.
3196 To disable these tags on a per-file basis, insert anywhere in the file:
3201 (cons (string :tag
"Tag name")
3202 (character :tag
"Access char"))
3203 (const :tag
"Start radio group" (:startgroup
))
3204 (const :tag
"Group tags delimiter" (:grouptags
))
3205 (const :tag
"End radio group" (:endgroup
))
3206 (const :tag
"New line" (:newline
)))))
3208 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3209 "If non-nil, always offer completion for all tags of all agenda files.
3210 Instead of customizing this variable directly, you might want to
3211 set it locally for capture buffers, because there no list of
3212 tags in that file can be created dynamically (there are none).
3214 (add-hook 'org-capture-mode-hook
3216 (set (make-local-variable
3217 'org-complete-tags-always-offer-all-agenda-tags)
3223 (defvar org-file-tags nil
3224 "List of tags that can be inherited by all entries in the file.
3225 The tags will be inherited if the variable `org-use-tag-inheritance'
3226 says they should be.
3227 This variable is populated from #+FILETAGS lines.")
3229 (defcustom org-use-fast-tag-selection
'auto
3230 "Non-nil means use fast tag selection scheme.
3231 This is a special interface to select and deselect tags with single keys.
3232 When nil, fast selection is never used.
3233 When the symbol `auto', fast selection is used if and only if selection
3234 characters for tags have been configured, either through the variable
3235 `org-tag-alist' or through a #+TAGS line in the buffer.
3236 When t, fast selection is always used and selection keys are assigned
3237 automatically if necessary."
3240 (const :tag
"Always" t
)
3241 (const :tag
"Never" nil
)
3242 (const :tag
"When selection characters are configured" 'auto
)))
3244 (defcustom org-fast-tag-selection-single-key nil
3245 "Non-nil means fast tag selection exits after first change.
3246 When nil, you have to press RET to exit it.
3247 During fast tag selection, you can toggle this flag with `C-c'.
3248 This variable can also have the value `expert'. In this case, the window
3249 displaying the tags menu is not even shown, until you press C-c again."
3252 (const :tag
"No" nil
)
3253 (const :tag
"Yes" t
)
3254 (const :tag
"Expert" expert
)))
3256 (defvar org-fast-tag-selection-include-todo nil
3257 "Non-nil means fast tags selection interface will also offer TODO states.
3258 This is an undocumented feature, you should not rely on it.")
3260 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
3261 "The column to which tags should be indented in a headline.
3262 If this number is positive, it specifies the column. If it is negative,
3263 it means that the tags should be flushright to that column. For example,
3264 -80 works well for a normal 80 character screen.
3265 When 0, place tags directly after headline text, with only one space in
3270 (defcustom org-auto-align-tags t
3271 "Non-nil keeps tags aligned when modifying headlines.
3272 Some operations (i.e. demoting) change the length of a headline and
3273 therefore shift the tags around. With this option turned on, after
3274 each such operation the tags are again aligned to `org-tags-column'."
3278 (defcustom org-use-tag-inheritance t
3279 "Non-nil means tags in levels apply also for sublevels.
3280 When nil, only the tags directly given in a specific line apply there.
3281 This may also be a list of tags that should be inherited, or a regexp that
3282 matches tags that should be inherited. Additional control is possible
3283 with the variable `org-tags-exclude-from-inheritance' which gives an
3284 explicit list of tags to be excluded from inheritance, even if the value of
3285 `org-use-tag-inheritance' would select it for inheritance.
3287 If this option is t, a match early-on in a tree can lead to a large
3288 number of matches in the subtree when constructing the agenda or creating
3289 a sparse tree. If you only want to see the first match in a tree during
3290 a search, check out the variable `org-tags-match-list-sublevels'."
3293 (const :tag
"Not" nil
)
3294 (const :tag
"Always" t
)
3295 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3296 (regexp :tag
"Tags matched by regexp")))
3298 (defcustom org-tags-exclude-from-inheritance nil
3299 "List of tags that should never be inherited.
3300 This is a way to exclude a few tags from inheritance. For way to do
3301 the opposite, to actively allow inheritance for selected tags,
3302 see the variable `org-use-tag-inheritance'."
3304 :type
'(repeat (string :tag
"Tag")))
3306 (defun org-tag-inherit-p (tag)
3307 "Check if TAG is one that should be inherited."
3309 ((member tag org-tags-exclude-from-inheritance
) nil
)
3310 ((eq org-use-tag-inheritance t
) t
)
3311 ((not org-use-tag-inheritance
) nil
)
3312 ((stringp org-use-tag-inheritance
)
3313 (string-match org-use-tag-inheritance tag
))
3314 ((listp org-use-tag-inheritance
)
3315 (member tag org-use-tag-inheritance
))
3316 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3318 (defcustom org-tags-match-list-sublevels t
3319 "Non-nil means list also sublevels of headlines matching a search.
3320 This variable applies to tags/property searches, and also to stuck
3321 projects because this search is based on a tags match as well.
3323 When set to the symbol `indented', sublevels are indented with
3326 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3327 the sublevels of a headline matching a tag search often also match
3328 the same search. Listing all of them can create very long lists.
3329 Setting this variable to nil causes subtrees of a match to be skipped.
3331 This variable is semi-obsolete and probably should always be true. It
3332 is better to limit inheritance to certain tags using the variables
3333 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3336 (const :tag
"No, don't list them" nil
)
3337 (const :tag
"Yes, do list them" t
)
3338 (const :tag
"List them, indented with leading dots" indented
)))
3340 (defcustom org-tags-sort-function nil
3341 "When set, tags are sorted using this function as a comparator."
3344 (const :tag
"No sorting" nil
)
3345 (const :tag
"Alphabetical" string
<)
3346 (const :tag
"Reverse alphabetical" string
>)
3347 (function :tag
"Custom function" nil
)))
3349 (defvar org-tags-history nil
3350 "History of minibuffer reads for tags.")
3351 (defvar org-last-tags-completion-table nil
3352 "The last used completion table for tags.")
3353 (defvar org-after-tags-change-hook nil
3354 "Hook that is run after the tags in a line have changed.")
3356 (defgroup org-properties nil
3357 "Options concerning properties in Org-mode."
3358 :tag
"Org Properties"
3361 (defcustom org-property-format
"%-10s %s"
3362 "How property key/value pairs should be formatted by `indent-line'.
3363 When `indent-line' hits a property definition, it will format the line
3364 according to this format, mainly to make sure that the values are
3365 lined-up with respect to each other."
3366 :group
'org-properties
3369 (defcustom org-properties-postprocess-alist nil
3370 "Alist of properties and functions to adjust inserted values.
3371 Elements of this alist must be of the form
3373 ([string] [function])
3375 where [string] must be a property name and [function] must be a
3376 lambda expression: this lambda expression must take one argument,
3377 the value to adjust, and return the new value as a string.
3379 For example, this element will allow the property \"Remaining\"
3380 to be updated wrt the relation between the \"Effort\" property
3381 and the clock summary:
3383 ((\"Remaining\" (lambda(value)
3384 (let ((clocksum (org-clock-sum-current-item))
3385 (effort (org-duration-string-to-minutes
3386 (org-entry-get (point) \"Effort\"))))
3387 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3388 :group
'org-properties
3390 :type
'(alist :key-type
(string :tag
"Property")
3391 :value-type
(function :tag
"Function")))
3393 (defcustom org-use-property-inheritance nil
3394 "Non-nil means properties apply also for sublevels.
3396 This setting is chiefly used during property searches. Turning it on can
3397 cause significant overhead when doing a search, which is why it is not
3400 When nil, only the properties directly given in the current entry count.
3401 When t, every property is inherited. The value may also be a list of
3402 properties that should have inheritance, or a regular expression matching
3403 properties that should be inherited.
3405 However, note that some special properties use inheritance under special
3406 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3407 and the properties ending in \"_ALL\" when they are used as descriptor
3408 for valid values of a property.
3410 Note for programmers:
3411 When querying an entry with `org-entry-get', you can control if inheritance
3412 should be used. By default, `org-entry-get' looks only at the local
3413 properties. You can request inheritance by setting the inherit argument
3414 to t (to force inheritance) or to `selective' (to respect the setting
3416 :group
'org-properties
3418 (const :tag
"Not" nil
)
3419 (const :tag
"Always" t
)
3420 (repeat :tag
"Specific properties" (string :tag
"Property"))
3421 (regexp :tag
"Properties matched by regexp")))
3423 (defun org-property-inherit-p (property)
3424 "Check if PROPERTY is one that should be inherited."
3426 ((eq org-use-property-inheritance t
) t
)
3427 ((not org-use-property-inheritance
) nil
)
3428 ((stringp org-use-property-inheritance
)
3429 (string-match org-use-property-inheritance property
))
3430 ((listp org-use-property-inheritance
)
3431 (member property org-use-property-inheritance
))
3432 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3434 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3435 "The default column format, if no other format has been defined.
3436 This variable can be set on the per-file basis by inserting a line
3438 #+COLUMNS: %25ITEM ....."
3439 :group
'org-properties
3442 (defcustom org-columns-ellipses
".."
3443 "The ellipses to be used when a field in column view is truncated.
3444 When this is the empty string, as many characters as possible are shown,
3445 but then there will be no visual indication that the field has been truncated.
3446 When this is a string of length N, the last N characters of a truncated
3447 field are replaced by this string. If the column is narrower than the
3448 ellipses string, only part of the ellipses string will be shown."
3449 :group
'org-properties
3452 (defcustom org-columns-modify-value-for-display-function nil
3453 "Function that modifies values for display in column view.
3454 For example, it can be used to cut out a certain part from a time stamp.
3455 The function must take 2 arguments:
3457 column-title The title of the column (*not* the property name)
3458 value The value that should be modified.
3460 The function should return the value that should be displayed,
3461 or nil if the normal value should be used."
3462 :group
'org-properties
3465 (defcustom org-effort-property
"Effort"
3466 "The property that is being used to keep track of effort estimates.
3467 Effort estimates given in this property need to have the format H:MM."
3468 :group
'org-properties
3469 :group
'org-progress
3470 :type
'(string :tag
"Property"))
3472 (defconst org-global-properties-fixed
3473 '(("VISIBILITY_ALL" .
"folded children content all")
3474 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3475 "List of property/value pairs that can be inherited by any entry.
3477 These are fixed values, for the preset properties. The user variable
3478 that can be used to add to this list is `org-global-properties'.
3480 The entries in this list are cons cells where the car is a property
3481 name and cdr is a string with the value. If the value represents
3482 multiple items like an \"_ALL\" property, separate the items by
3485 (defcustom org-global-properties nil
3486 "List of property/value pairs that can be inherited by any entry.
3488 This list will be combined with the constant `org-global-properties-fixed'.
3490 The entries in this list are cons cells where the car is a property
3491 name and cdr is a string with the value.
3493 You can set buffer-local values for the same purpose in the variable
3494 `org-file-properties' this by adding lines like
3496 #+PROPERTY: NAME VALUE"
3497 :group
'org-properties
3499 (cons (string :tag
"Property")
3500 (string :tag
"Value"))))
3502 (defvar org-file-properties nil
3503 "List of property/value pairs that can be inherited by any entry.
3504 Valid for the current buffer.
3505 This variable is populated from #+PROPERTY lines.")
3506 (make-variable-buffer-local 'org-file-properties
)
3508 (defgroup org-agenda nil
3509 "Options concerning agenda views in Org-mode."
3513 (defvar org-category nil
3514 "Variable used by org files to set a category for agenda display.
3515 Such files should use a file variable to set it, for example
3517 # -*- mode: org; org-category: \"ELisp\"
3519 or contain a special line
3523 If the file does not specify a category, then file's base name
3525 (make-variable-buffer-local 'org-category
)
3526 (put 'org-category
'safe-local-variable
#'(lambda (x) (or (symbolp x
) (stringp x
))))
3528 (defcustom org-agenda-files nil
3529 "The files to be used for agenda display.
3530 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3531 \\[org-remove-file]. You can also use customize to edit the list.
3533 If an entry is a directory, all files in that directory that are matched by
3534 `org-agenda-file-regexp' will be part of the file list.
3536 If the value of the variable is not a list but a single file name, then
3537 the list of agenda files is actually stored and maintained in that file, one
3538 agenda file per line. In this file paths can be given relative to
3539 `org-directory'. Tilde expansion and environment variable substitution
3543 (repeat :tag
"List of files and directories" file
)
3544 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3546 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3547 "Regular expression to match files for `org-agenda-files'.
3548 If any element in the list in that variable contains a directory instead
3549 of a normal file, all files in that directory that are matched by this
3550 regular expression will be included."
3554 (defcustom org-agenda-text-search-extra-files nil
3555 "List of extra files to be searched by text search commands.
3556 These files will be search in addition to the agenda files by the
3557 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3558 Note that these files will only be searched for text search commands,
3559 not for the other agenda views like todo lists, tag searches or the weekly
3560 agenda. This variable is intended to list notes and possibly archive files
3561 that should also be searched by these two commands.
3562 In fact, if the first element in the list is the symbol `agenda-archives',
3563 than all archive files of all agenda files will be added to the search
3566 :type
'(set :greedy t
3567 (const :tag
"Agenda Archives" agenda-archives
)
3568 (repeat :inline t
(file))))
3570 (org-defvaralias 'org-agenda-multi-occur-extra-files
3571 'org-agenda-text-search-extra-files
)
3573 (defcustom org-agenda-skip-unavailable-files nil
3574 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3575 A nil value means to remove them, after a query, from the list."
3579 (defcustom org-calendar-to-agenda-key
[?c
]
3580 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3581 The command `org-calendar-goto-agenda' will be bound to this key. The
3582 default is the character `c' because then `c' can be used to switch back and
3583 forth between agenda and calendar."
3587 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3588 "The key to be installed in `calendar-mode-map' for adding diary entries.
3589 This option is irrelevant until `org-agenda-diary-file' has been configured
3590 to point to an Org-mode file. When that is the case, the command
3591 `org-agenda-diary-entry' will be bound to the key given here, by default
3592 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3593 if you want to continue doing this, you need to change this to a different
3598 (defcustom org-agenda-diary-file
'diary-file
3599 "File to which to add new entries with the `i' key in agenda and calendar.
3600 When this is the symbol `diary-file', the functionality in the Emacs
3601 calendar will be used to add entries to the `diary-file'. But when this
3602 points to a file, `org-agenda-diary-entry' will be used instead."
3605 (const :tag
"The standard Emacs diary file" diary-file
)
3606 (file :tag
"Special Org file diary entries")))
3608 (eval-after-load "calendar"
3610 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3611 'org-calendar-goto-agenda
)
3612 (add-hook 'calendar-mode-hook
3614 (unless (eq org-agenda-diary-file
'diary-file
)
3615 (define-key calendar-mode-map
3616 org-calendar-insert-diary-entry-key
3617 'org-agenda-diary-entry
))))))
3619 (defgroup org-latex nil
3620 "Options for embedding LaTeX code into Org-mode."
3624 (defcustom org-format-latex-options
3625 '(:foreground default
:background default
:scale
1.0
3626 :html-foreground
"Black" :html-background
"Transparent"
3627 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3628 "Options for creating images from LaTeX fragments.
3629 This is a property list with the following properties:
3630 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3631 `default' means use the foreground of the default face.
3632 `auto' means use the foreground from the text face.
3633 :background the background color, or \"Transparent\".
3634 `default' means use the background of the default face.
3635 `auto' means use the background from the text face.
3636 :scale a scaling factor for the size of the images, to get more pixels
3637 :html-foreground, :html-background, :html-scale
3638 the same numbers for HTML export.
3639 :matchers a list indicating which matchers should be used to
3640 find LaTeX fragments. Valid members of this list are:
3641 \"begin\" find environments
3642 \"$1\" find single characters surrounded by $.$
3643 \"$\" find math expressions surrounded by $...$
3644 \"$$\" find math expressions surrounded by $$....$$
3645 \"\\(\" find math expressions surrounded by \\(...\\)
3646 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3650 (defcustom org-format-latex-signal-error t
3651 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3652 When nil, just push out a message."
3657 (defcustom org-latex-to-mathml-jar-file nil
3658 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3659 Use this to specify additional executable file say a jar file.
3661 When using MathToWeb as the converter, specify the full-path to
3662 your mathtoweb.jar file."
3666 (const :tag
"None" nil
)
3667 (file :tag
"JAR file" :must-match t
)))
3669 (defcustom org-latex-to-mathml-convert-command nil
3670 "Command to convert LaTeX fragments to MathML.
3671 Replace format-specifiers in the command as noted below and use
3672 `shell-command' to convert LaTeX to MathML.
3673 %j: Executable file in fully expanded form as specified by
3674 `org-latex-to-mathml-jar-file'.
3675 %I: Input LaTeX file in fully expanded form
3676 %o: Output MathML file
3677 This command is used by `org-create-math-formula'.
3679 When using MathToWeb as the converter, set this to
3680 \"java -jar %j -unicode -force -df %o %I\"."
3684 (const :tag
"None" nil
)
3685 (string :tag
"\nShell command")))
3687 (defcustom org-latex-create-formula-image-program
'dvipng
3688 "Program to convert LaTeX fragments with.
3690 dvipng Process the LaTeX fragments to dvi file, then convert
3691 dvi files to png files using dvipng.
3692 This will also include processing of non-math environments.
3693 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3694 to convert pdf files to png files"
3698 (const :tag
"dvipng" dvipng
)
3699 (const :tag
"imagemagick" imagemagick
)))
3701 (defcustom org-latex-preview-ltxpng-directory
"ltxpng/"
3702 "Path to store latex preview images.
3703 A relative path here creates many directories relative to the
3704 processed org files paths. An absolute path puts all preview
3705 images at the same place."
3710 (defun org-format-latex-mathml-available-p ()
3711 "Return t if `org-latex-to-mathml-convert-command' is usable."
3713 (when (and (boundp 'org-latex-to-mathml-convert-command
)
3714 org-latex-to-mathml-convert-command
)
3715 (let ((executable (car (split-string
3716 org-latex-to-mathml-convert-command
))))
3717 (when (executable-find executable
)
3719 "%j" org-latex-to-mathml-convert-command
)
3720 (file-readable-p org-latex-to-mathml-jar-file
)
3723 (defcustom org-format-latex-header
"\\documentclass{article}
3724 \\usepackage[usenames]{color}
3725 \\usepackage{amsmath}
3726 \\usepackage[mathscr]{eucal}
3727 \\pagestyle{empty} % do not remove
3730 % The settings below are copied from fullpage.sty
3731 \\setlength{\\textwidth}{\\paperwidth}
3732 \\addtolength{\\textwidth}{-3cm}
3733 \\setlength{\\oddsidemargin}{1.5cm}
3734 \\addtolength{\\oddsidemargin}{-2.54cm}
3735 \\setlength{\\evensidemargin}{\\oddsidemargin}
3736 \\setlength{\\textheight}{\\paperheight}
3737 \\addtolength{\\textheight}{-\\headheight}
3738 \\addtolength{\\textheight}{-\\headsep}
3739 \\addtolength{\\textheight}{-\\footskip}
3740 \\addtolength{\\textheight}{-3cm}
3741 \\setlength{\\topmargin}{1.5cm}
3742 \\addtolength{\\topmargin}{-2.54cm}"
3743 "The document header used for processing LaTeX fragments.
3744 It is imperative that this header make sure that no page number
3745 appears on the page. The package defined in the variables
3746 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3747 will either replace the placeholder \"[PACKAGES]\" in this
3748 header, or they will be appended."
3752 (defun org-set-packages-alist (var val
)
3753 "Set the packages alist and make sure it has 3 elements per entry."
3754 (set var
(mapcar (lambda (x)
3755 (if (and (consp x
) (= (length x
) 2))
3756 (list (car x
) (nth 1 x
) t
)
3760 (defun org-get-packages-alist (var)
3761 "Get the packages alist and make sure it has 3 elements per entry."
3763 (if (and (consp x
) (= (length x
) 2))
3764 (list (car x
) (nth 1 x
) t
)
3766 (default-value var
)))
3768 (defcustom org-latex-default-packages-alist
3769 '(("AUTO" "inputenc" t
)
3773 ("" "longtable" nil
)
3784 "Alist of default packages to be inserted in the header.
3786 Change this only if one of the packages here causes an
3787 incompatibility with another package you are using.
3789 The packages in this list are needed by one part or another of
3790 Org mode to function properly:
3792 - inputenc, fontenc: for basic font and character selection
3793 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3794 symbols used for interpreting the entities in `org-entities'.
3795 You can skip some of these packages if you don't use any of the
3797 - graphicx: for including images
3798 - float, wrapfig: for figure placement
3799 - longtable: for long tables
3800 - hyperref: for cross references
3802 Therefore you should not modify this variable unless you know
3803 what you are doing. The one reason to change it anyway is that
3804 you might be loading some other package that conflicts with one
3805 of the default packages. Each cell is of the format
3806 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3807 the package also needs to be included when compiling LaTeX
3808 snippets into images for inclusion into non-LaTeX output."
3810 :group
'org-export-latex
3811 :set
'org-set-packages-alist
3812 :get
'org-get-packages-alist
3816 (list :tag
"options/package pair"
3817 (string :tag
"options")
3818 (string :tag
"package")
3819 (boolean :tag
"Snippet"))
3820 (string :tag
"A line of LaTeX"))))
3822 (defcustom org-latex-packages-alist nil
3823 "Alist of packages to be inserted in every LaTeX header.
3825 These will be inserted after `org-latex-default-packages-alist'.
3826 Each cell is of the format:
3828 \(\"options\" \"package\" snippet-flag)
3830 SNIPPET-FLAG, when t, indicates that this package is also needed
3831 when turning LaTeX snippets into images for inclusion into
3834 Make sure that you only list packages here which:
3836 - you want in every file
3837 - do not conflict with the setup in `org-format-latex-header'.
3838 - do not conflict with the default packages in
3839 `org-latex-default-packages-alist'."
3841 :group
'org-export-latex
3842 :set
'org-set-packages-alist
3843 :get
'org-get-packages-alist
3846 (list :tag
"options/package pair"
3847 (string :tag
"options")
3848 (string :tag
"package")
3849 (boolean :tag
"Snippet"))
3850 (string :tag
"A line of LaTeX"))))
3852 (defgroup org-appearance nil
3853 "Settings for Org-mode appearance."
3854 :tag
"Org Appearance"
3857 (defcustom org-level-color-stars-only nil
3858 "Non-nil means fontify only the stars in each headline.
3859 When nil, the entire headline is fontified.
3860 Changing it requires restart of `font-lock-mode' to become effective
3861 also in regions already fontified."
3862 :group
'org-appearance
3865 (defcustom org-hide-leading-stars nil
3866 "Non-nil means hide the first N-1 stars in a headline.
3867 This works by using the face `org-hide' for these stars. This
3868 face is white for a light background, and black for a dark
3869 background. You may have to customize the face `org-hide' to
3871 Changing it requires restart of `font-lock-mode' to become effective
3872 also in regions already fontified.
3873 You may also set this on a per-file basis by adding one of the following
3874 lines to the buffer:
3876 #+STARTUP: hidestars
3877 #+STARTUP: showstars"
3878 :group
'org-appearance
3881 (defcustom org-hidden-keywords nil
3882 "List of symbols corresponding to keywords to be hidden the org buffer.
3883 For example, a value '(title) for this list will make the document's title
3884 appear in the buffer without the initial #+TITLE: keyword."
3885 :group
'org-appearance
3887 :type
'(set (const :tag
"#+AUTHOR" author
)
3888 (const :tag
"#+DATE" date
)
3889 (const :tag
"#+EMAIL" email
)
3890 (const :tag
"#+TITLE" title
)))
3892 (defcustom org-custom-properties nil
3893 "List of properties (as strings) with a special meaning.
3894 The default use of these custom properties is to let the user
3895 hide them with `org-toggle-custom-properties-visibility'."
3896 :group
'org-properties
3897 :group
'org-appearance
3899 :type
'(repeat (string :tag
"Property Name")))
3901 (defcustom org-fontify-done-headline nil
3902 "Non-nil means change the face of a headline if it is marked DONE.
3903 Normally, only the TODO/DONE keyword indicates the state of a headline.
3904 When this is non-nil, the headline after the keyword is set to the
3905 `org-headline-done' as an additional indication."
3906 :group
'org-appearance
3909 (defcustom org-fontify-emphasized-text t
3910 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3911 Changing this variable requires a restart of Emacs to take effect."
3912 :group
'org-appearance
3915 (defcustom org-fontify-whole-heading-line nil
3916 "Non-nil means fontify the whole line for headings.
3917 This is useful when setting a background color for the
3919 :group
'org-appearance
3922 (defcustom org-highlight-latex-and-related nil
3923 "Non-nil means highlight LaTeX related syntax in the buffer.
3924 When non nil, the value should be a list containing any of the
3926 `latex' Highlight LaTeX snippets and environments.
3927 `script' Highlight subscript and superscript.
3928 `entities' Highlight entities."
3929 :group
'org-appearance
3931 :package-version
'(Org .
"8.0")
3933 (const :tag
"No highlighting" nil
)
3934 (set :greedy t
:tag
"Highlight"
3935 (const :tag
"LaTeX snippets and environments" latex
)
3936 (const :tag
"Subscript and superscript" script
)
3937 (const :tag
"Entities" entities
))))
3939 (defcustom org-hide-emphasis-markers nil
3940 "Non-nil mean font-lock should hide the emphasis marker characters."
3941 :group
'org-appearance
3944 (defcustom org-pretty-entities nil
3945 "Non-nil means show entities as UTF8 characters.
3946 When nil, the \\name form remains in the buffer."
3947 :group
'org-appearance
3951 (defcustom org-pretty-entities-include-sub-superscripts t
3952 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3953 :group
'org-appearance
3957 (defvar org-emph-re nil
3958 "Regular expression for matching emphasis.
3959 After a match, the match groups contain these elements:
3960 0 The match of the full regular expression, including the characters
3961 before and after the proper match
3962 1 The character before the proper match, or empty at beginning of line
3963 2 The proper match, including the leading and trailing markers
3964 3 The leading marker like * or /, indicating the type of highlighting
3965 4 The text between the emphasis markers, not including the markers
3966 5 The character after the match, empty at the end of a line")
3967 (defvar org-verbatim-re nil
3968 "Regular expression for matching verbatim text.")
3969 (defvar org-emphasis-regexp-components
) ; defined just below
3970 (defvar org-emphasis-alist
) ; defined just below
3971 (defun org-set-emph-re (var val
)
3972 "Set variable and compute the emphasis regular expression."
3974 (when (and (boundp 'org-emphasis-alist
)
3975 (boundp 'org-emphasis-regexp-components
)
3976 org-emphasis-alist org-emphasis-regexp-components
)
3977 (let* ((e org-emphasis-regexp-components
)
3983 (body1 (concat body
"*?"))
3984 (markers (mapconcat 'car org-emphasis-alist
""))
3985 (vmarkers (mapconcat
3986 (lambda (x) (if (eq (nth 4 x
) 'verbatim
) (car x
) ""))
3987 org-emphasis-alist
"")))
3988 ;; make sure special characters appear at the right position in the class
3989 (if (string-match "\\^" markers
)
3990 (setq markers
(concat (replace-match "" t t markers
) "^")))
3991 (if (string-match "-" markers
)
3992 (setq markers
(concat (replace-match "" t t markers
) "-")))
3993 (if (string-match "\\^" vmarkers
)
3994 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
3995 (if (string-match "-" vmarkers
)
3996 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
3998 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
3999 (int-to-string nl
) "\\}")))
4002 (concat "\\([" pre
"]\\|^\\)"
4004 "\\([" markers
"]\\)"
4012 "\\([" post
"]\\|$\\)"))
4013 (setq org-verbatim-re
4014 (concat "\\([" pre
"]\\|^\\)"
4016 "\\([" vmarkers
"]\\)"
4024 "\\([" post
"]\\|$\\)")))))
4026 (defcustom org-emphasis-regexp-components
4027 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4028 "Components used to build the regular expression for emphasis.
4029 This is a list with five entries. Terminology: In an emphasis string
4030 like \" *strong word* \", we call the initial space PREMATCH, the final
4031 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4032 and \"trong wor\" is the body. The different components in this variable
4033 specify what is allowed/forbidden in each part:
4035 pre Chars allowed as prematch. Beginning of line will be allowed too.
4036 post Chars allowed as postmatch. End of line will be allowed too.
4037 border The chars *forbidden* as border characters.
4038 body-regexp A regexp like \".\" to match a body character. Don't use
4039 non-shy groups here, and don't allow newline here.
4040 newline The maximum number of newlines allowed in an emphasis exp.
4042 Use customize to modify this, or restart Emacs after changing it."
4043 :group
'org-appearance
4044 :set
'org-set-emph-re
4046 (sexp :tag
"Allowed chars in pre ")
4047 (sexp :tag
"Allowed chars in post ")
4048 (sexp :tag
"Forbidden chars in border ")
4049 (sexp :tag
"Regexp for body ")
4050 (integer :tag
"number of newlines allowed")
4051 (option (boolean :tag
"Please ignore this button"))))
4053 (defcustom org-emphasis-alist
4054 `(("*" bold
"<b>" "</b>")
4055 ("/" italic
"<i>" "</i>")
4056 ("_" underline
"<span style=\"text-decoration:underline;\">" "</span>")
4057 ("=" org-code
"<code>" "</code>" verbatim
)
4058 ("~" org-verbatim
"<code>" "</code>" verbatim
)
4059 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))
4062 "Special syntax for emphasized text.
4063 Text starting and ending with a special character will be emphasized, for
4064 example *bold*, _underlined_ and /italic/. This variable sets the marker
4065 characters, the face to be used by font-lock for highlighting in Org-mode
4066 Emacs buffers, and the HTML tags to be used for this.
4067 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4068 Use customize to modify this, or restart Emacs after changing it."
4069 :group
'org-appearance
4070 :set
'org-set-emph-re
4073 (string :tag
"Marker character")
4075 (face :tag
"Font-lock-face")
4076 (plist :tag
"Face property list"))
4077 (string :tag
"HTML start tag")
4078 (string :tag
"HTML end tag")
4079 (option (const verbatim
)))))
4081 (defvar org-protecting-blocks
4082 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4083 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4084 This is needed for font-lock setup.")
4086 ;;; Miscellaneous options
4088 (defgroup org-completion nil
4089 "Completion in Org-mode."
4090 :tag
"Org Completion"
4093 (defcustom org-completion-use-ido nil
4094 "Non-nil means use ido completion wherever possible.
4095 Note that `ido-mode' must be active for this variable to be relevant.
4096 If you decide to turn this variable on, you might well want to turn off
4097 `org-outline-path-complete-in-steps'.
4098 See also `org-completion-use-iswitchb'."
4099 :group
'org-completion
4102 (defcustom org-completion-use-iswitchb nil
4103 "Non-nil means use iswitchb completion wherever possible.
4104 Note that `iswitchb-mode' must be active for this variable to be relevant.
4105 If you decide to turn this variable on, you might well want to turn off
4106 `org-outline-path-complete-in-steps'.
4107 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4108 :group
'org-completion
4111 (defcustom org-completion-fallback-command
'hippie-expand
4112 "The expansion command called by \\[pcomplete] in normal context.
4113 Normal means, no org-mode-specific context."
4114 :group
'org-completion
4117 ;;; Functions and variables from their packages
4118 ;; Declared here to avoid compiler warnings
4121 (defvar outline-mode-menu-heading
)
4122 (defvar outline-mode-menu-show
)
4123 (defvar outline-mode-menu-hide
)
4124 (defvar zmacs-regions
) ; XEmacs regions
4127 (defvar mark-active
)
4130 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
4131 (declare-function calendar-forward-day
"cal-move" (arg))
4132 (declare-function calendar-goto-date
"cal-move" (date))
4133 (declare-function calendar-goto-today
"cal-move" ())
4134 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4135 (defvar calc-embedded-close-formula
)
4136 (defvar calc-embedded-open-formula
)
4137 (declare-function cdlatex-tab
"ext:cdlatex" ())
4138 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4139 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
4140 (defvar font-lock-unfontify-region-function
)
4141 (declare-function iswitchb-read-buffer
"iswitchb"
4142 (prompt &optional default require-match start matches-set
))
4143 (defvar iswitchb-temp-buflist
)
4144 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4145 (defvar org-agenda-tags-todo-honor-ignore-options
)
4146 (declare-function org-agenda-skip
"org-agenda" ())
4148 org-agenda-format-item
"org-agenda"
4149 (extra txt
&optional level category tags dotime noprefix remove-re habitp
))
4150 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4151 (declare-function org-agenda-change-all-lines
"org-agenda"
4152 (newhead hdmarker
&optional fixface just-this
))
4153 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4154 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4155 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
4157 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4158 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4159 "org-agenda" (&optional end
))
4160 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4161 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4162 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4163 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4164 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4165 (declare-function parse-time-string
"parse-time" (string))
4166 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4167 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4168 (defvar remember-data-file
)
4169 (defvar texmathp-why
)
4170 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4171 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
4173 (defvar org-latex-regexps
)
4175 ;;; Autoload and prepare some org modules
4177 ;; Some table stuff that needs to be defined here, because it is used
4178 ;; by the functions setting up org-mode or checking for table context.
4180 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
4181 "Detect an org-type or table-type table.")
4182 (defconst org-table-line-regexp
"^[ \t]*|"
4183 "Detect an org-type table line.")
4184 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
4185 "Detect an org-type table line.")
4186 (defconst org-table-hline-regexp
"^[ \t]*|-"
4187 "Detect an org-type table hline.")
4188 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
4189 "Detect a table-type table hline.")
4190 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
4191 "Detect the first line outside a table when searching from within it.
4192 This works for both table types.")
4194 ;; Autoload the functions in org-table.el that are needed by functions here.
4197 (org-autoload "org-table"
4198 '(org-table-begin org-table-blank-field org-table-end
)))
4201 (defun turn-on-orgtbl ()
4202 "Unconditionally turn on `orgtbl-mode'."
4203 (require 'org-table
)
4206 (defun org-at-table-p (&optional table-type
)
4207 "Return t if the cursor is inside an org-type table.
4208 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4209 (if org-enable-table-editor
4211 (beginning-of-line 1)
4212 (looking-at (if table-type org-table-any-line-regexp
4213 org-table-line-regexp
)))
4215 (defsubst org-table-p
() (org-at-table-p))
4217 (defun org-at-table.el-p
()
4218 "Return t if and only if we are at a table.el table."
4219 (and (org-at-table-p 'any
)
4221 (goto-char (org-table-begin 'any
))
4222 (looking-at org-table1-hline-regexp
))))
4224 (defun org-table-recognize-table.el
()
4225 "If there is a table.el table nearby, recognize it and move into it."
4226 (if org-table-tab-recognizes-table.el
4227 (if (org-at-table.el-p
)
4229 (beginning-of-line 1)
4230 (if (looking-at org-table-dataline-regexp
)
4232 (if (looking-at org-table1-hline-regexp
)
4234 (beginning-of-line 2)
4235 (if (looking-at org-table-any-border-regexp
)
4236 (beginning-of-line -
1)))))
4237 (if (re-search-forward "|" (org-table-end t
) t
)
4240 (if (table--at-cell-p (point))
4242 (message "recognizing table.el table...")
4243 (table-recognize-table)
4244 (message "recognizing table.el table...done")))
4245 (error "This should not happen"))
4250 (defun org-at-table-hline-p ()
4251 "Return t if the cursor is inside a hline in a table."
4252 (if org-enable-table-editor
4254 (beginning-of-line 1)
4255 (looking-at org-table-hline-regexp
))
4258 (defvar org-table-clean-did-remove-column nil
)
4259 (defun org-table-map-tables (function &optional quietly
)
4260 "Apply FUNCTION to the start of all tables in the buffer."
4264 (goto-char (point-min))
4265 (while (re-search-forward org-table-any-line-regexp nil t
)
4267 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4268 (beginning-of-line 1)
4269 (when (and (looking-at org-table-line-regexp
)
4270 ;; Exclude tables in src/example/verbatim/clocktable blocks
4271 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4272 (save-excursion (funcall function
))
4273 (or (looking-at org-table-line-regexp
)
4275 (re-search-forward org-table-any-border-regexp nil
1))))
4276 (unless quietly
(message "Mapping tables: done")))
4278 ;; Declare and autoload functions from ox.el and al.
4280 (declare-function org-export-get-environment
"ox"
4281 (&optional backend subtreep ext-plist
))
4282 (declare-function org-latex-guess-inputenc
"ox-latex" (header))
4284 ;; Declare and autoload functions from org-agenda.el
4287 (org-autoload "org-agenda"
4288 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4290 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4291 (declare-function org-clock-update-mode-line
"org-clock" ())
4292 (declare-function org-resolve-clocks
"org-clock"
4293 (&optional also-non-dangling-p prompt last-valid
))
4294 (defvar org-clock-start-time
)
4295 (defvar org-clock-marker
(make-marker)
4296 "Marker recording the last clock-in.")
4297 (defvar org-clock-hd-marker
(make-marker)
4298 "Marker recording the last clock-in, but the headline position.")
4299 (defvar org-clock-heading
""
4300 "The heading of the current clock entry.")
4301 (defun org-clock-is-active ()
4302 "Return non-nil if clock is currently running.
4303 The return value is actually the clock marker."
4304 (marker-buffer org-clock-marker
))
4307 (org-autoload "org-clock" '(org-clock-remove-overlays
4308 org-clock-update-time-maybe
4309 org-clocktable-shift
)))
4311 (defun org-check-running-clock ()
4312 "Check if the current buffer contains the running clock.
4313 If yes, offer to stop it and to save the buffer with the changes."
4314 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4315 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4318 (when (y-or-n-p "Save changed buffer?")
4321 (defun org-clocktable-try-shift (dir n
)
4322 "Check if this line starts a clock table, if yes, shift the time block."
4323 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4324 (org-clocktable-shift dir n
)))
4327 (defun org-clock-persistence-insinuate ()
4328 "Set up hooks for clock persistence."
4329 (require 'org-clock
)
4330 (add-hook 'org-mode-hook
'org-clock-load
)
4331 (add-hook 'kill-emacs-hook
'org-clock-save
))
4333 ;; Define the variable already here, to make sure we have it.
4334 (defvar org-indent-mode nil
4335 "Non-nil if Org-Indent mode is enabled.
4336 Use the command `org-indent-mode' to change this variable.")
4338 ;; Autoload archiving code
4339 ;; The stuff that is needed for cycling and tags has to be defined here.
4341 (defgroup org-archive nil
4342 "Options concerning archiving in Org-mode."
4344 :group
'org-structure
)
4346 (defcustom org-archive-location
"%s_archive::"
4347 "The location where subtrees should be archived.
4349 The value of this variable is a string, consisting of two parts,
4350 separated by a double-colon. The first part is a filename and
4351 the second part is a headline.
4353 When the filename is omitted, archiving happens in the same file.
4354 %s in the filename will be replaced by the current file
4355 name (without the directory part). Archiving to a different file
4356 is useful to keep archived entries from contributing to the
4359 The archived entries will be filed as subtrees of the specified
4360 headline. When the headline is omitted, the subtrees are simply
4361 filed away at the end of the file, as top-level entries. Also in
4362 the heading you can use %s to represent the file name, this can be
4363 useful when using the same archive for a number of different files.
4365 Here are a few examples:
4367 If the current file is Projects.org, archive in file
4368 Projects.org_archive, as top-level trees. This is the default.
4370 \"::* Archived Tasks\"
4371 Archive in the current file, under the top-level headline
4372 \"* Archived Tasks\".
4374 \"~/org/archive.org::\"
4375 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4377 \"~/org/archive.org::* From %s\"
4378 Archive in file ~/org/archive.org (absolute path), under headlines
4379 \"From FILENAME\" where file name is the current file name.
4381 \"~/org/datetree.org::datetree/* Finished Tasks\"
4382 The \"datetree/\" string is special, signifying to archive
4383 items to the datetree. Items are placed in either the CLOSED
4384 date of the item, or the current date if there is no CLOSED date.
4385 The heading will be a subentry to the current date. There doesn't
4386 need to be a heading, but there always needs to be a slash after
4387 datetree. For example, to store archived items directly in the
4388 datetree, use \"~/org/datetree.org::datetree/\".
4390 \"basement::** Finished Tasks\"
4391 Archive in file ./basement (relative path), as level 3 trees
4392 below the level 2 heading \"** Finished Tasks\".
4394 You may set this option on a per-file basis by adding to the buffer a
4397 #+ARCHIVE: basement::** Finished Tasks
4399 You may also define it locally for a subtree by setting an ARCHIVE property
4400 in the entry. If such a property is found in an entry, or anywhere up
4401 the hierarchy, it will be used."
4405 (defcustom org-archive-tag
"ARCHIVE"
4406 "The tag that marks a subtree as archived.
4407 An archived subtree does not open during visibility cycling, and does
4408 not contribute to the agenda listings.
4409 After changing this, font-lock must be restarted in the relevant buffers to
4410 get the proper fontification."
4412 :group
'org-keywords
4415 (defcustom org-agenda-skip-archived-trees t
4416 "Non-nil means the agenda will skip any items located in archived trees.
4417 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4418 variable is no longer recommended, you should leave it at the value t.
4419 Instead, use the key `v' to cycle the archives-mode in the agenda."
4421 :group
'org-agenda-skip
4424 (defcustom org-columns-skip-archived-trees t
4425 "Non-nil means ignore archived trees when creating column view."
4427 :group
'org-properties
4430 (defcustom org-cycle-open-archived-trees nil
4431 "Non-nil means `org-cycle' will open archived trees.
4432 An archived tree is a tree marked with the tag ARCHIVE.
4433 When nil, archived trees will stay folded. You can still open them with
4434 normal outline commands like `show-all', but not with the cycling commands."
4439 (defcustom org-sparse-tree-open-archived-trees nil
4440 "Non-nil means sparse tree construction shows matches in archived trees.
4441 When nil, matches in these trees are highlighted, but the trees are kept in
4444 :group
'org-sparse-trees
4447 (defcustom org-sparse-tree-default-date-type
'scheduled-or-deadline
4448 "The default date type when building a sparse tree.
4449 When this is nil, a date is a scheduled or a deadline timestamp.
4450 Otherwise, these types are allowed:
4453 active: only active timestamps (<...>)
4454 inactive: only inactive timestamps (<...)
4455 scheduled: only scheduled timestamps
4456 deadline: only deadline timestamps"
4457 :type
'(choice (const :tag
"Scheduled or deadline" 'scheduled-or-deadline
)
4458 (const :tag
"All timestamps" all
)
4459 (const :tag
"Only active timestamps" active
)
4460 (const :tag
"Only inactive timestamps" inactive
)
4461 (const :tag
"Only scheduled timestamps" scheduled
)
4462 (const :tag
"Only deadline timestamps" deadline
))
4464 :group
'org-sparse-trees
)
4466 (defun org-cycle-hide-archived-subtrees (state)
4467 "Re-hide all archived subtrees after a visibility state change."
4468 (when (and (not org-cycle-open-archived-trees
)
4469 (not (memq state
'(overview folded
))))
4471 (let* ((globalp (memq state
'(contents all
)))
4472 (beg (if globalp
(point-min) (point)))
4473 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4474 (org-hide-archived-subtrees beg end
)
4476 (if (looking-at (concat ".*:" org-archive-tag
":"))
4477 (message "%s" (substitute-command-keys
4478 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4480 (defun org-force-cycle-archived ()
4481 "Cycle subtree even if it is archived."
4483 (setq this-command
'org-cycle
)
4484 (let ((org-cycle-open-archived-trees t
))
4485 (call-interactively 'org-cycle
)))
4487 (defun org-hide-archived-subtrees (beg end
)
4488 "Re-hide all archived subtrees after a visibility state change."
4490 (let* ((re (concat ":" org-archive-tag
":")))
4492 (while (re-search-forward re end t
)
4493 (when (org-at-heading-p)
4494 (org-flag-subtree t
)
4495 (org-end-of-subtree t
))))))
4497 (declare-function outline-end-of-heading
"outline" ())
4498 (declare-function outline-flag-region
"outline" (from to flag
))
4499 (defun org-flag-subtree (flag)
4501 (org-back-to-heading t
)
4502 (outline-end-of-heading)
4503 (outline-flag-region (point)
4504 (progn (org-end-of-subtree t
) (point))
4507 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4510 (org-autoload "org-archive"
4511 '(org-add-archive-files)))
4513 ;; Autoload Column View Code
4515 (declare-function org-columns-number-to-string
"org-colview" (n fmt
&optional printf
))
4516 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4517 (declare-function org-columns-compute
"org-colview" (property))
4519 (org-autoload (if (featurep 'xemacs
) "org-colview-xemacs" "org-colview")
4520 '(org-columns-number-to-string
4521 org-columns-get-format-and-top-level
4523 org-columns-remove-overlays
))
4527 (declare-function org-id-store-link
"org-id")
4528 (declare-function org-id-locations-load
"org-id")
4529 (declare-function org-id-locations-save
"org-id")
4530 (defvar org-id-track-globally
)
4531 (org-autoload "org-id"
4534 org-id-get-with-outline-path-completion
4535 org-id-get-with-outline-drilling
))
4537 ;;; Variables for pre-computed regular expressions, all buffer local
4539 (defvar org-drawer-regexp
"^[ \t]*:PROPERTIES:[ \t]*$"
4540 "Matches first line of a hidden block.")
4541 (make-variable-buffer-local 'org-drawer-regexp
)
4542 (defvar org-todo-regexp nil
4543 "Matches any of the TODO state keywords.")
4544 (make-variable-buffer-local 'org-todo-regexp
)
4545 (defvar org-not-done-regexp nil
4546 "Matches any of the TODO state keywords except the last one.")
4547 (make-variable-buffer-local 'org-not-done-regexp
)
4548 (defvar org-not-done-heading-regexp nil
4549 "Matches a TODO headline that is not done.")
4550 (make-variable-buffer-local 'org-not-done-regexp
)
4551 (defvar org-todo-line-regexp nil
4552 "Matches a headline and puts TODO state into group 2 if present.")
4553 (make-variable-buffer-local 'org-todo-line-regexp
)
4554 (defvar org-complex-heading-regexp nil
4555 "Matches a headline and puts everything into groups:
4557 group 2: The todo keyword, maybe
4558 group 3: Priority cookie
4559 group 4: True headline
4561 (make-variable-buffer-local 'org-complex-heading-regexp
)
4562 (defvar org-complex-heading-regexp-format nil
4563 "Printf format to make regexp to match an exact headline.
4564 This regexp will match the headline of any node which has the
4565 exact headline text that is put into the format, but may have any
4566 TODO state, priority and tags.")
4567 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4568 (defvar org-todo-line-tags-regexp nil
4569 "Matches a headline and puts TODO state into group 2 if present.
4570 Also put tags into group 4 if tags are present.")
4571 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4572 (defvar org-ds-keyword-length
12
4573 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4574 (make-variable-buffer-local 'org-ds-keyword-length
)
4575 (defvar org-deadline-regexp nil
4576 "Matches the DEADLINE keyword.")
4577 (make-variable-buffer-local 'org-deadline-regexp
)
4578 (defvar org-deadline-time-regexp nil
4579 "Matches the DEADLINE keyword together with a time stamp.")
4580 (make-variable-buffer-local 'org-deadline-time-regexp
)
4581 (defvar org-deadline-time-hour-regexp nil
4582 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4583 (make-variable-buffer-local 'org-deadline-time-hour-regexp
)
4584 (defvar org-deadline-line-regexp nil
4585 "Matches the DEADLINE keyword and the rest of the line.")
4586 (make-variable-buffer-local 'org-deadline-line-regexp
)
4587 (defvar org-scheduled-regexp nil
4588 "Matches the SCHEDULED keyword.")
4589 (make-variable-buffer-local 'org-scheduled-regexp
)
4590 (defvar org-scheduled-time-regexp nil
4591 "Matches the SCHEDULED keyword together with a time stamp.")
4592 (make-variable-buffer-local 'org-scheduled-time-regexp
)
4593 (defvar org-scheduled-time-hour-regexp nil
4594 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4595 (make-variable-buffer-local 'org-scheduled-time-hour-regexp
)
4596 (defvar org-closed-time-regexp nil
4597 "Matches the CLOSED keyword together with a time stamp.")
4598 (make-variable-buffer-local 'org-closed-time-regexp
)
4600 (defvar org-keyword-time-regexp nil
4601 "Matches any of the 4 keywords, together with the time stamp.")
4602 (make-variable-buffer-local 'org-keyword-time-regexp
)
4603 (defvar org-keyword-time-not-clock-regexp nil
4604 "Matches any of the 3 keywords, together with the time stamp.")
4605 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp
)
4606 (defvar org-maybe-keyword-time-regexp nil
4607 "Matches a timestamp, possibly preceded by a keyword.")
4608 (make-variable-buffer-local 'org-maybe-keyword-time-regexp
)
4609 (defvar org-all-time-keywords nil
4610 "List of time keywords.")
4611 (make-variable-buffer-local 'org-all-time-keywords
)
4613 (defconst org-plain-time-of-day-regexp
4616 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4619 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4621 "Regular expression to match a plain time or time range.
4622 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4623 groups carry important information:
4625 1 the first time, range or not
4626 8 the second time, if it is a range.")
4628 (defconst org-plain-time-extension-regexp
4631 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4632 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4633 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4634 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4635 groups carry important information:
4638 9 minutes of duration")
4640 (defconst org-stamp-time-of-day-regexp
4642 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4643 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4645 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4646 "Regular expression to match a timestamp time or time range.
4647 After a match, the following groups carry important information:
4649 1 date plus weekday, for back referencing to make sure both times are on the same day
4650 2 the first time, range or not
4651 4 the second time, if it is a range.")
4653 (defconst org-startup-options
4654 '(("fold" org-startup-folded t
)
4655 ("overview" org-startup-folded t
)
4656 ("nofold" org-startup-folded nil
)
4657 ("showall" org-startup-folded nil
)
4658 ("showeverything" org-startup-folded showeverything
)
4659 ("content" org-startup-folded content
)
4660 ("indent" org-startup-indented t
)
4661 ("noindent" org-startup-indented nil
)
4662 ("hidestars" org-hide-leading-stars t
)
4663 ("showstars" org-hide-leading-stars nil
)
4664 ("odd" org-odd-levels-only t
)
4665 ("oddeven" org-odd-levels-only nil
)
4666 ("align" org-startup-align-all-tables t
)
4667 ("noalign" org-startup-align-all-tables nil
)
4668 ("inlineimages" org-startup-with-inline-images t
)
4669 ("noinlineimages" org-startup-with-inline-images nil
)
4670 ("latexpreview" org-startup-with-latex-preview t
)
4671 ("nolatexpreview" org-startup-with-latex-preview nil
)
4672 ("customtime" org-display-custom-times t
)
4673 ("logdone" org-log-done time
)
4674 ("lognotedone" org-log-done note
)
4675 ("nologdone" org-log-done nil
)
4676 ("lognoteclock-out" org-log-note-clock-out t
)
4677 ("nolognoteclock-out" org-log-note-clock-out nil
)
4678 ("logrepeat" org-log-repeat state
)
4679 ("lognoterepeat" org-log-repeat note
)
4680 ("logdrawer" org-log-into-drawer t
)
4681 ("nologdrawer" org-log-into-drawer nil
)
4682 ("logstatesreversed" org-log-states-order-reversed t
)
4683 ("nologstatesreversed" org-log-states-order-reversed nil
)
4684 ("nologrepeat" org-log-repeat nil
)
4685 ("logreschedule" org-log-reschedule time
)
4686 ("lognotereschedule" org-log-reschedule note
)
4687 ("nologreschedule" org-log-reschedule nil
)
4688 ("logredeadline" org-log-redeadline time
)
4689 ("lognoteredeadline" org-log-redeadline note
)
4690 ("nologredeadline" org-log-redeadline nil
)
4691 ("logrefile" org-log-refile time
)
4692 ("lognoterefile" org-log-refile note
)
4693 ("nologrefile" org-log-refile nil
)
4694 ("fninline" org-footnote-define-inline t
)
4695 ("nofninline" org-footnote-define-inline nil
)
4696 ("fnlocal" org-footnote-section nil
)
4697 ("fnauto" org-footnote-auto-label t
)
4698 ("fnprompt" org-footnote-auto-label nil
)
4699 ("fnconfirm" org-footnote-auto-label confirm
)
4700 ("fnplain" org-footnote-auto-label plain
)
4701 ("fnadjust" org-footnote-auto-adjust t
)
4702 ("nofnadjust" org-footnote-auto-adjust nil
)
4703 ("constcgs" constants-unit-system cgs
)
4704 ("constSI" constants-unit-system SI
)
4705 ("noptag" org-tag-persistent-alist nil
)
4706 ("hideblocks" org-hide-block-startup t
)
4707 ("nohideblocks" org-hide-block-startup nil
)
4708 ("beamer" org-startup-with-beamer-mode t
)
4709 ("entitiespretty" org-pretty-entities t
)
4710 ("entitiesplain" org-pretty-entities nil
))
4711 "Variable associated with STARTUP options for org-mode.
4712 Each element is a list of three items: the startup options (as written
4713 in the #+STARTUP line), the corresponding variable, and the value to set
4714 this variable to if the option is found. An optional forth element PUSH
4715 means to push this value onto the list in the variable.")
4717 (defun org-update-property-plist (key val props
)
4718 "Update PROPS with KEY and VAL."
4719 (let* ((appending (string= "+" (substring key
(- (length key
) 1))))
4720 (key (if appending
(substring key
0 (- (length key
) 1)) key
))
4721 (remainder (org-remove-if (lambda (p) (string= (car p
) key
)) props
))
4722 (previous (cdr (assoc key props
))))
4724 (cons (cons key
(if previous
(concat previous
" " val
) val
)) remainder
)
4725 (cons (cons key val
) remainder
))))
4727 (defconst org-block-regexp
4728 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4729 "Regular expression for hiding blocks.")
4730 (defconst org-heading-keyword-regexp-format
4731 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4732 "Printf format for a regexp matching a headline with some keyword.
4733 This regexp will match the headline of any node which has the
4734 exact keyword that is put into the format. The keyword isn't in
4735 any group by default, but the stars and the body are.")
4736 (defconst org-heading-keyword-maybe-regexp-format
4737 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4738 "Printf format for a regexp matching a headline, possibly with some keyword.
4739 This regexp can match any headline with the specified keyword, or
4740 without a keyword. The keyword isn't in any group by default,
4741 but the stars and the body are.")
4743 (defcustom org-group-tags t
4744 "When non-nil (the default), use group tags.
4745 This can be turned on/off through `org-toggle-tags-groups'."
4750 (defun org-toggle-tags-groups ()
4751 "Toggle support for group tags.
4752 Support for group tags is controlled by the option
4753 `org-group-tags', which is non-nil by default."
4755 (setq org-group-tags
(not org-group-tags
))
4756 (cond ((and (derived-mode-p 'org-agenda-mode
)
4759 ((derived-mode-p 'org-mode
)
4760 (let ((org-inhibit-startup t
)) (org-mode))))
4761 (message "Groups tags support has been turned %s"
4762 (if org-group-tags
"on" "off")))
4764 (defun org-set-regexps-and-options-for-tags ()
4765 "Precompute regular expressions used for tags in the current buffer."
4766 (when (derived-mode-p 'org-mode
)
4767 (org-set-local 'org-file-tags nil
)
4768 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4770 tags ftags key value
4775 (goto-char (point-min))
4776 (while (re-search-forward re nil t
)
4777 (setq key
(upcase (org-match-string-no-properties 1))
4778 value
(org-match-string-no-properties 2))
4779 (if (stringp value
) (setq value
(org-trim value
)))
4782 (setq tags
(append tags
(if tags
'("\\n") nil
)
4783 (org-split-string value splitre
))))
4784 ((equal key
"FILETAGS")
4785 (when (string-match "\\S-" value
)
4790 (mapcar (lambda (x) (org-split-string x
":"))
4791 (org-split-string value
)))))))))))
4792 ;; Process the file tags.
4793 (and ftags
(org-set-local 'org-file-tags
4794 (mapcar 'org-add-prop-inherited ftags
)))
4795 (org-set-local 'org-tag-groups-alist nil
)
4796 ;; Process the tags.
4800 (while (setq e
(pop tags
))
4803 (progn (push '(:startgroup
) tgs
)
4804 (when (equal (nth 1 tags
) ":")
4805 (push (list (replace-regexp-in-string
4806 "(.+)$" "" (nth 0 tags
)))
4807 org-tag-groups-alist
)
4809 ((equal e
":") (push '(:grouptags
) tgs
))
4810 ((equal e
"}") (push '(:endgroup
) tgs
) (if g
(setq g nil
)))
4811 ((equal e
"\\n") (push '(:newline
) tgs
))
4812 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e
)
4813 (push (cons (match-string 1 e
)
4814 (string-to-char (match-string 2 e
))) tgs
)
4816 (setcar org-tag-groups-alist
4817 (append (car org-tag-groups-alist
)
4818 (list (match-string 1 e
)))))
4819 (if g
(setq g
(1+ g
))))
4820 (t (push (list e
) tgs
)
4822 (setcar org-tag-groups-alist
4823 (append (car org-tag-groups-alist
) (list e
))))
4824 (if g
(setq g
(1+ g
))))))
4825 (org-set-local 'org-tag-alist nil
)
4826 (while (setq e
(pop tgs
))
4827 (or (and (stringp (car e
))
4828 (assoc (car e
) org-tag-alist
))
4829 (push e org-tag-alist
))))))))
4831 (defun org-set-regexps-and-options ()
4832 "Precompute regular expressions used in the current buffer."
4833 (when (derived-mode-p 'org-mode
)
4834 (org-set-local 'org-todo-kwd-alist nil
)
4835 (org-set-local 'org-todo-key-alist nil
)
4836 (org-set-local 'org-todo-key-trigger nil
)
4837 (org-set-local 'org-todo-keywords-1 nil
)
4838 (org-set-local 'org-done-keywords nil
)
4839 (org-set-local 'org-todo-heads nil
)
4840 (org-set-local 'org-todo-sets nil
)
4841 (org-set-local 'org-todo-log-states nil
)
4842 (org-set-local 'org-file-properties nil
)
4843 (let ((re (org-make-options-regexp
4844 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4845 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4846 "SETUPFILE" "OPTIONS")
4847 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4849 (scripts org-use-sub-superscripts
)
4850 kwds kws0 kwsa key log value cat arch const links hw dws
4851 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4856 (goto-char (point-min))
4857 (while (or (and ext-setup-or-nil
4858 (string-match re ext-setup-or-nil start
)
4859 (setq start
(match-end 0)))
4860 (and (setq ext-setup-or-nil nil start
0)
4861 (re-search-forward re nil t
)))
4862 (setq key
(upcase (match-string 1 ext-setup-or-nil
))
4863 value
(org-match-string-no-properties 2 ext-setup-or-nil
))
4864 (if (stringp value
) (setq value
(org-trim value
)))
4866 ((equal key
"CATEGORY")
4868 ((member key
'("SEQ_TODO" "TODO"))
4869 (push (cons 'sequence
(org-split-string value splitre
)) kwds
))
4870 ((equal key
"TYP_TODO")
4871 (push (cons 'type
(org-split-string value splitre
)) kwds
))
4872 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key
)
4873 ;; general TODO-like setup
4874 (push (cons (intern (downcase (match-string 1 key
)))
4875 (org-split-string value splitre
)) kwds
))
4876 ((equal key
"COLUMNS")
4877 (org-set-local 'org-columns-default-format value
))
4879 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
4880 (push (cons (match-string 1 value
)
4881 (org-trim (match-string 2 value
)))
4883 ((equal key
"PRIORITIES")
4884 (setq prio
(org-split-string value
" +")))
4885 ((equal key
"PROPERTY")
4886 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4887 (setq props
(org-update-property-plist (match-string 1 value
)
4888 (match-string 2 value
)
4890 ((equal key
"DRAWERS")
4891 (setq drawers
(delete-dups (append org-drawers
(org-split-string value splitre
)))))
4892 ((equal key
"CONSTANTS")
4893 (org-table-set-constants))
4894 ((equal key
"STARTUP")
4895 (let ((opts (org-split-string value splitre
))
4897 (while (setq l
(pop opts
))
4898 (when (setq l
(assoc l org-startup-options
))
4899 (setq var
(nth 1 l
) val
(nth 2 l
))
4901 (set (make-local-variable var
) val
)
4902 (if (not (listp (symbol-value var
)))
4903 (set (make-local-variable var
) nil
))
4904 (set (make-local-variable var
) (symbol-value var
))
4905 (add-to-list var val
))))))
4906 ((equal key
"ARCHIVE")
4908 (remove-text-properties 0 (length arch
)
4909 '(face t fontified t
) arch
))
4910 ((equal key
"OPTIONS")
4911 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value
)
4912 (setq scripts
(read (match-string 2 value
)))))
4913 ((and (equal key
"SETUPFILE")
4914 ;; Prevent checking in Gnus messages
4915 (not buffer-read-only
))
4916 (setq setup-contents
(org-file-contents
4918 (org-remove-double-quotes value
))
4920 (if (not ext-setup-or-nil
)
4921 (setq ext-setup-or-nil setup-contents start
0)
4922 (setq ext-setup-or-nil
4923 (concat (substring ext-setup-or-nil
0 start
)
4924 "\n" setup-contents
"\n"
4925 (substring ext-setup-or-nil start
)))))))
4926 ;; search for property blocks
4927 (goto-char (point-min))
4928 (while (re-search-forward org-block-regexp nil t
)
4929 (when (equal "PROPERTY" (upcase (match-string 1)))
4930 (setq value
(replace-regexp-in-string
4931 "[\n\r]" " " (match-string 4)))
4932 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4933 (setq props
(org-update-property-plist (match-string 1 value
)
4934 (match-string 2 value
)
4936 (org-set-local 'org-use-sub-superscripts scripts
)
4938 (org-set-local 'org-category
(intern cat
))
4939 (push (cons "CATEGORY" cat
) props
))
4941 (if (< (length prio
) 3) (setq prio
'("A" "C" "B")))
4942 (setq prio
(mapcar 'string-to-char prio
))
4943 (org-set-local 'org-highest-priority
(nth 0 prio
))
4944 (org-set-local 'org-lowest-priority
(nth 1 prio
))
4945 (org-set-local 'org-default-priority
(nth 2 prio
)))
4946 (and props
(org-set-local 'org-file-properties
(nreverse props
)))
4947 (and drawers
(org-set-local 'org-drawers drawers
))
4948 (and arch
(org-set-local 'org-archive-location arch
))
4949 (and links
(setq org-link-abbrev-alist-local
(nreverse links
)))
4950 ;; Process the TODO keywords
4952 ;; Use the global values as if they had been given locally.
4953 (setq kwds
(default-value 'org-todo-keywords
))
4954 (if (stringp (car kwds
))
4955 (setq kwds
(list (cons org-todo-interpretation
4956 (default-value 'org-todo-keywords
)))))
4957 (setq kwds
(reverse kwds
)))
4958 (setq kwds
(nreverse kwds
))
4960 (while (setq kws
(pop kwds
))
4962 (run-hook-with-args-until-success
4963 'org-todo-setup-filter-hook kws
)
4965 (setq inter
(pop kws
) sep
(member "|" kws
)
4966 kws0
(delete "|" (copy-sequence kws
))
4971 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x
)
4973 (setq kw
(match-string 1 x
)
4974 key
(and (match-end 2) (match-string 2 x
))
4975 log
(org-extract-log-state-settings x
))
4976 (push (cons kw
(and key
(string-to-char key
))) kwsa
)
4977 (and log
(push log org-todo-log-states
))
4979 (error "Invalid TODO keyword %s" x
)))
4981 kwsa
(if kwsa
(append '((:startgroup
))
4985 dws
(if sep
(org-remove-keyword-keys (cdr sep
)) (last kws1
))
4986 tail
(list inter hw
(car dws
) (org-last dws
))))
4987 (add-to-list 'org-todo-heads hw
'append
)
4988 (push kws1 org-todo-sets
)
4989 (setq org-done-keywords
(append org-done-keywords dws nil
))
4990 (setq org-todo-key-alist
(append org-todo-key-alist kwsa
))
4991 (mapc (lambda (x) (push (cons x tail
) org-todo-kwd-alist
)) kws1
)
4992 (setq org-todo-keywords-1
(append org-todo-keywords-1 kws1 nil
)))
4993 (setq org-todo-sets
(nreverse org-todo-sets
)
4994 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
4995 org-todo-key-trigger
(delq nil
(mapcar 'cdr org-todo-key-alist
))
4996 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
)))
4997 ;; Compute the regular expressions and other local variables.
4998 ;; Using `org-outline-regexp-bol' would complicate them much,
4999 ;; because of the fixed white space at the end of that string.
5000 (if (not org-done-keywords
)
5001 (setq org-done-keywords
(and org-todo-keywords-1
5002 (list (org-last org-todo-keywords-1
)))))
5003 (setq org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
5004 (length org-scheduled-string
)
5005 (length org-clock-string
)
5006 (length org-closed-string
)))
5008 (concat "^[ \t]*:\\("
5009 (mapconcat 'regexp-quote org-drawers
"\\|")
5011 org-not-done-keywords
5012 (org-delete-all org-done-keywords
(copy-sequence org-todo-keywords-1
))
5015 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
5019 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
5021 org-not-done-heading-regexp
5022 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5023 org-todo-line-regexp
5024 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5025 org-complex-heading-regexp
5026 (concat "^\\(\\*+\\)"
5027 "\\(?: +" org-todo-regexp
"\\)?"
5028 "\\(?: +\\(\\[#.\\]\\)\\)?"
5029 "\\(?: +\\(.*?\\)\\)??"
5030 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5032 org-complex-heading-regexp-format
5033 (concat "^\\(\\*+\\)"
5034 "\\(?: +" org-todo-regexp
"\\)?"
5035 "\\(?: +\\(\\[#.\\]\\)\\)?"
5037 ;; Stats cookies can be stuck to body.
5038 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5040 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5042 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5044 org-todo-line-tags-regexp
5045 (concat "^\\(\\*+\\)"
5046 "\\(?: +" org-todo-regexp
"\\)?"
5047 "\\(?: +\\(.*?\\)\\)??"
5048 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5050 org-deadline-regexp
(concat "\\<" org-deadline-string
)
5051 org-deadline-time-regexp
5052 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
5053 org-deadline-time-hour-regexp
5054 (concat "\\<" org-deadline-string
5055 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5056 org-deadline-line-regexp
5057 (concat "\\<\\(" org-deadline-string
"\\).*")
5058 org-scheduled-regexp
5059 (concat "\\<" org-scheduled-string
)
5060 org-scheduled-time-regexp
5061 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
5062 org-scheduled-time-hour-regexp
5063 (concat "\\<" org-scheduled-string
5064 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5065 org-closed-time-regexp
5066 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
5067 org-keyword-time-regexp
5068 (concat "\\<\\(" org-scheduled-string
5069 "\\|" org-deadline-string
5070 "\\|" org-closed-string
5071 "\\|" org-clock-string
"\\)"
5072 " *[[<]\\([^]>]+\\)[]>]")
5073 org-keyword-time-not-clock-regexp
5074 (concat "\\<\\(" org-scheduled-string
5075 "\\|" org-deadline-string
5076 "\\|" org-closed-string
5078 " *[[<]\\([^]>]+\\)[]>]")
5079 org-maybe-keyword-time-regexp
5080 (concat "\\(\\<\\(" org-scheduled-string
5081 "\\|" org-deadline-string
5082 "\\|" org-closed-string
5083 "\\|" org-clock-string
"\\)\\)?"
5084 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5085 org-all-time-keywords
5086 (mapcar (lambda (w) (substring w
0 -
1))
5087 (list org-scheduled-string org-deadline-string
5088 org-clock-string org-closed-string
)))
5089 (org-compute-latex-and-related-regexp)
5090 (org-set-font-lock-defaults))))
5092 (defun org-file-contents (file &optional noerror
)
5093 "Return the contents of FILE, as a string."
5095 (not (file-readable-p file
)))
5097 (message "Cannot read file \"%s\"" file
)
5098 (error "Cannot read file \"%s\"" file
))
5100 (insert-file-contents file
)
5103 (defun org-extract-log-state-settings (x)
5104 "Extract the log state setting from a TODO keyword string.
5105 This will extract info from a string like \"WAIT(w@/!)\"."
5106 (let (kw key log1 log2
)
5107 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5108 (setq kw
(match-string 1 x
)
5109 key
(and (match-end 2) (match-string 2 x
))
5110 log1
(and (match-end 3) (match-string 3 x
))
5111 log2
(and (match-end 4) (match-string 4 x
)))
5114 (and log1
(if (equal log1
"!") 'time
'note
))
5115 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5117 (defun org-remove-keyword-keys (list)
5118 "Remove a pair of parenthesis at the end of each string in LIST."
5120 (if (string-match "(.*)$" x
)
5121 (substring x
0 (match-beginning 0))
5125 (defun org-assign-fast-keys (alist)
5126 "Assign fast keys to a keyword-key alist.
5127 Respect keys that are already there."
5128 (let (new e
(alt ?
0))
5129 (while (setq e
(pop alist
))
5130 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5131 (cdr e
)) ;; Key already assigned.
5133 (let ((clist (string-to-list (downcase (car e
))))
5134 (used (append new alist
)))
5135 (when (= (car clist
) ?
@)
5137 (while (and clist
(rassoc (car clist
) used
))
5140 (while (rassoc alt used
)
5142 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5145 ;;; Some variables used in various places
5147 (defvar org-window-configuration nil
5148 "Used in various places to store a window configuration.")
5149 (defvar org-selected-window nil
5150 "Used in various places to store a window configuration.")
5151 (defvar org-finish-function nil
5152 "Function to be called when `C-c C-c' is used.
5153 This is for getting out of special buffers like capture.")
5156 ;; FIXME: Occasionally check by commenting these, to make sure
5157 ;; no other functions uses these, forgetting to let-bind them.
5158 (org-no-warnings (defvar entry
)) ;; unprefixed, from calendar.el
5159 (defvar org-last-state
)
5160 (org-no-warnings (defvar date
)) ;; unprefixed, from calendar.el
5162 ;; Defined somewhere in this file, but used before definition.
5163 (defvar org-entities
) ;; defined in org-entities.el
5164 (defvar org-struct-menu
)
5165 (defvar org-org-menu
)
5166 (defvar org-tbl-menu
)
5168 ;;;; Define the Org-mode
5170 ;; We use a before-change function to check if a table might need
5172 (defvar org-table-may-need-update t
5173 "Indicates that a table might need an update.
5174 This variable is set by `org-before-change-function'.
5175 `org-table-align' sets it back to nil.")
5176 (defun org-before-change-function (beg end
)
5177 "Every change indicates that a table might need an update."
5178 (setq org-table-may-need-update t
))
5179 (defvar org-mode-map
)
5180 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
5181 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5182 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5183 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5184 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5185 (defvar org-table-buffer-is-an nil
)
5187 (defvar bidi-paragraph-direction
)
5188 (defvar buffer-face-mode-face
)
5191 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
5192 (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"))
5193 (require 'noutline
"noutline" 'noerror
) ;; stock XEmacs does not have it
5195 ;; Other stuff we need.
5196 (require 'time-date
)
5197 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5201 ;; (require 'org-macs) moved higher up in the file before it is first used
5202 (require 'org-entities
)
5203 ;; (require 'org-compat) moved higher up in the file before it is first used
5204 (require 'org-faces
)
5206 (require 'org-pcomplete
)
5208 (require 'org-footnote
)
5209 (require 'org-macro
)
5215 (define-derived-mode org-mode outline-mode
"Org"
5216 "Outline-based notes management and organizer, alias
5217 \"Carsten's outline-mode for keeping track of everything.\"
5219 Org-mode develops organizational tasks around a NOTES file which
5220 contains information about projects as plain text. Org-mode is
5221 implemented on top of outline-mode, which is ideal to keep the content
5222 of large files well structured. It supports ToDo items, deadlines and
5223 time stamps, which magically appear in the diary listing of the Emacs
5224 calendar. Tables are easily created with a built-in table editor.
5225 Plain text URL-like links connect to websites, emails (VM), Usenet
5226 messages (Gnus), BBDB entries, and any files related to the project.
5227 For printing and sharing of notes, an Org-mode file (or a part of it)
5228 can be exported as a structured ASCII or HTML file.
5230 The following commands are available:
5234 ;; Get rid of Outline menus, they are not needed
5235 ;; Need to do this here because define-derived-mode sets up
5236 ;; the keymap so late. Still, it is a waste to call this each time
5237 ;; we switch another buffer into org-mode.
5238 (if (featurep 'xemacs
)
5239 (when (boundp 'outline-mode-menu-heading
)
5240 ;; Assume this is Greg's port, it uses easymenu
5241 (easy-menu-remove outline-mode-menu-heading
)
5242 (easy-menu-remove outline-mode-menu-show
)
5243 (easy-menu-remove outline-mode-menu-hide
))
5244 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5245 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5246 (define-key org-mode-map
[menu-bar show
] 'undefined
))
5248 (org-load-modules-maybe)
5249 (easy-menu-add org-org-menu
)
5250 (easy-menu-add org-tbl-menu
)
5251 (org-install-agenda-files-menu)
5252 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5253 (add-to-invisibility-spec '(org-cwidth))
5254 (add-to-invisibility-spec '(org-hide-block . t
))
5255 (when (featurep 'xemacs
)
5256 (org-set-local 'line-move-ignore-invisible t
))
5257 (org-set-local 'outline-regexp org-outline-regexp
)
5258 (org-set-local 'outline-level
'org-outline-level
)
5259 (setq bidi-paragraph-direction
'left-to-right
)
5260 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5261 (set (make-local-variable 'paragraph-start
) "\f\\|[ \t]*$\\|\\*+ ")
5262 (when (and org-ellipsis
5263 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
5264 (fboundp 'make-glyph-code
))
5265 (unless org-display-table
5266 (setq org-display-table
(make-display-table)))
5267 (set-display-table-slot
5270 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
5272 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
5273 (setq buffer-display-table org-display-table
))
5274 (org-set-regexps-and-options-for-tags)
5275 (org-set-regexps-and-options)
5276 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5277 ;; tag faces set outside customize.... force initialization.
5278 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5280 (org-set-local 'calc-embedded-open-mode
"# ")
5281 ;; Modify a few syntax entries
5282 (modify-syntax-entry ?
@ "w")
5283 (modify-syntax-entry ?
\" "\"")
5284 (if org-startup-truncated
(setq truncate-lines t
))
5285 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5286 (org-set-local 'font-lock-unfontify-region-function
5287 'org-unfontify-region
)
5288 ;; Activate before-change-function
5289 (org-set-local 'org-table-may-need-update t
)
5290 (org-add-hook 'before-change-functions
'org-before-change-function nil
5292 ;; Check for running clock before killing a buffer
5293 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5294 ;; Initialize macros templates.
5295 (org-macro-initialize-templates)
5296 ;; Initialize radio targets.
5297 (org-update-radio-target-regexp)
5299 (org-set-local 'indent-line-function
'org-indent-line
)
5300 (org-set-local 'indent-region-function
'org-indent-region
)
5301 ;; Filling and auto-filling.
5304 (org-setup-comments-handling)
5305 ;; Beginning/end of defun
5306 (org-set-local 'beginning-of-defun-function
'org-backward-element
)
5307 (org-set-local 'end-of-defun-function
'org-forward-element
)
5308 ;; Next error for sparse trees
5309 (org-set-local 'next-error-function
'org-occur-next-match
)
5310 ;; Make sure dependence stuff works reliably, even for users who set it
5312 (if org-enforce-todo-dependencies
5313 (add-hook 'org-blocker-hook
5314 'org-block-todo-from-children-or-siblings-or-parent
)
5315 (remove-hook 'org-blocker-hook
5316 'org-block-todo-from-children-or-siblings-or-parent
))
5317 (if org-enforce-todo-checkbox-dependencies
5318 (add-hook 'org-blocker-hook
5319 'org-block-todo-from-checkboxes
)
5320 (remove-hook 'org-blocker-hook
5321 'org-block-todo-from-checkboxes
))
5323 ;; Align options lines
5325 'align-mode-rules-list
5326 '((org-in-buffer-settings
5327 (regexp .
"^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5328 (modes .
'(org-mode)))))
5331 (org-set-local 'imenu-create-index-function
5332 'org-imenu-get-tree
)
5334 ;; Make isearch reveal context
5335 (if (or (featurep 'xemacs
)
5336 (not (boundp 'outline-isearch-open-invisible-function
)))
5337 ;; Emacs 21 and XEmacs make use of the hook
5338 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
5339 ;; Emacs 22 deals with this through a special variable
5340 (org-set-local 'outline-isearch-open-invisible-function
5341 (lambda (&rest ignore
) (org-show-context 'isearch
)))
5342 (org-add-hook 'isearch-mode-end-hook
'org-fix-ellipsis-at-bol
'append
'local
))
5344 ;; Setup the pcomplete hooks
5345 (set (make-local-variable 'pcomplete-command-completion-function
)
5346 'org-pcomplete-initial
)
5347 (set (make-local-variable 'pcomplete-command-name-function
)
5348 'org-command-at-point
)
5349 (set (make-local-variable 'pcomplete-default-completion-function
)
5351 (set (make-local-variable 'pcomplete-parse-arguments-function
)
5352 'org-parse-arguments
)
5353 (set (make-local-variable 'pcomplete-termination-string
) "")
5354 (when (>= emacs-major-version
23)
5355 (set (make-local-variable 'buffer-face-mode-face
) 'org-default
))
5357 ;; If empty file that did not turn on org-mode automatically, make it to.
5358 (if (and org-insert-mode-line-in-empty-file
5359 (org-called-interactively-p 'any
)
5360 (= (point-min) (point-max)))
5361 (insert "# -*- mode: org -*-\n\n"))
5362 (unless org-inhibit-startup
5364 (and org-startup-with-beamer-mode
(org-beamer-mode))
5365 (when org-startup-align-all-tables
5366 (org-table-map-tables 'org-table-align
'quietly
))
5367 (when org-startup-with-inline-images
5368 (org-display-inline-images))
5369 (when org-startup-with-latex-preview
5370 (org-preview-latex-fragment))
5371 (unless org-inhibit-startup-visibility-stuff
5372 (org-set-startup-visibility))))
5373 ;; Try to set org-hide correctly
5374 (set-face-foreground 'org-hide
(org-find-invisible-foreground)))
5376 ;; Update `customize-package-emacs-version-alist'
5377 (add-to-list 'customize-package-emacs-version-alist
5378 '(Org ("6.21b" .
"23.1") ("6.33x" .
"23.2")
5379 ("7.8.11" .
"24.1") ("7.9.4" .
"24.3")
5382 (defvar org-mode-transpose-word-syntax-table
5383 (let ((st (make-syntax-table)))
5384 (mapc (lambda(c) (modify-syntax-entry
5385 (string-to-char (car c
)) "w p" st
))
5389 (when (fboundp 'abbrev-table-put
)
5390 (abbrev-table-put org-mode-abbrev-table
5391 :parents
(list text-mode-abbrev-table
)))
5393 (put 'org-mode
'flyspell-mode-predicate
'org-mode-flyspell-verify
)
5395 (defsubst org-fix-ellipsis-at-bol
()
5396 (save-excursion (goto-char (window-start)) (recenter 0)))
5398 (defun org-find-invisible-foreground ()
5399 (let ((candidates (remove
5402 (list (face-background 'default
)
5403 (face-background 'org-default
))
5406 (when (boundp alist
)
5407 (cdr (assoc 'background-color
(symbol-value alist
)))))
5408 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5409 (list (face-foreground 'org-hide
))))))
5410 (car (remove nil candidates
))))
5412 (defun org-current-time (&optional rounding-minutes past
)
5413 "Current time, possibly rounded to ROUNDING-MINUTES.
5414 When ROUNDING-MINUTES is not an integer, fall back on the car of
5415 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5416 the rounding returns a past time."
5417 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5418 (car org-time-stamp-rounding-minutes
)))
5419 (time (decode-time)) res
)
5424 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5426 (if (and past
(< (org-float-time (time-subtract (current-time) res
)) 0))
5427 (seconds-to-time (- (org-float-time res
) (* r
60)))
5431 "Return today date, considering `org-extend-today-until'."
5433 (time-subtract (current-time)
5434 (list 0 (* 3600 org-extend-today-until
) 0))))
5436 ;;;; Font-Lock stuff, including the activators
5438 (defvar org-mouse-map
(make-sparse-keymap))
5439 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5440 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5441 (when org-mouse-1-follows-link
5442 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5443 (when org-tab-follows-link
5444 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5445 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5447 (require 'font-lock
)
5449 (defconst org-non-link-chars
"]\t\n\r<>")
5450 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "news"
5451 "shell" "elisp" "doi" "message"))
5452 (defvar org-link-types-re nil
5453 "Matches a link that has a url-like prefix like \"http:\"")
5454 (defvar org-link-re-with-space nil
5455 "Matches a link with spaces, optional angular brackets around it.")
5456 (defvar org-link-re-with-space2 nil
5457 "Matches a link with spaces, optional angular brackets around it.")
5458 (defvar org-link-re-with-space3 nil
5459 "Matches a link with spaces, only for internal part in bracket links.")
5460 (defvar org-angle-link-re nil
5461 "Matches link with angular brackets, spaces are allowed.")
5462 (defvar org-plain-link-re nil
5463 "Matches plain link, without spaces.")
5464 (defvar org-bracket-link-regexp nil
5465 "Matches a link in double brackets.")
5466 (defvar org-bracket-link-analytic-regexp nil
5467 "Regular expression used to analyze links.
5468 Here is what the match groups contain after a match:
5474 (defvar org-bracket-link-analytic-regexp
++ nil
5475 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5476 (defvar org-any-link-re nil
5477 "Regular expression matching any link.")
5479 (defconst org-match-sexp-depth
3
5480 "Number of stacked braces for sub/superscript matching.")
5482 (defun org-create-multibrace-regexp (left right n
)
5483 "Create a regular expression which will match a balanced sexp.
5484 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5485 as single character strings.
5486 The regexp returned will match the entire expression including the
5487 delimiters. It will also define a single group which contains the
5488 match except for the outermost delimiters. The maximum depth of
5489 stacked delimiters is N. Escaping delimiters is not possible."
5490 (let* ((nothing (concat "[^" left right
"]*?"))
5493 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5496 re
(concat re or next
)
5497 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5498 (concat left
"\\(" re
"\\)" right
)))
5500 (defvar org-match-substring-regexp
5502 "\\(\\S-\\)\\([_^]\\)\\("
5503 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5505 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5507 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5508 "The regular expression matching a sub- or superscript.")
5510 (defvar org-match-substring-with-braces-regexp
5512 "\\(\\S-\\)\\([_^]\\)\\("
5513 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5515 "The regular expression matching a sub- or superscript, forcing braces.")
5517 (defun org-make-link-regexps ()
5518 "Update the link regular expressions.
5519 This should be called after the variable `org-link-types' has changed."
5520 (setq org-link-types-re
5522 "\\`\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):")
5523 org-link-re-with-space
5525 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5526 "\\([^" org-non-link-chars
" ]"
5527 "[^" org-non-link-chars
"]*"
5528 "[^" org-non-link-chars
" ]\\)>?")
5529 org-link-re-with-space2
5531 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5532 "\\([^" org-non-link-chars
" ]"
5534 "[^" org-non-link-chars
" ]\\)>?")
5535 org-link-re-with-space3
5537 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5538 "\\([^" org-non-link-chars
" ]"
5542 "<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5543 "\\([^" org-non-link-chars
" ]"
5544 "[^" org-non-link-chars
"]*"
5548 "\\<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5549 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5550 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5551 org-bracket-link-regexp
5552 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5553 org-bracket-link-analytic-regexp
5556 "\\(\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):\\)?"
5559 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5561 org-bracket-link-analytic-regexp
++
5564 "\\(\\(" (mapconcat 'regexp-quote
(cons "coderef" org-link-types
) "\\|") "\\):\\)?"
5567 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5570 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5571 org-angle-link-re
"\\)\\|\\("
5572 org-plain-link-re
"\\)")))
5574 (org-make-link-regexps)
5576 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5577 "Regular expression for fast time stamp matching.")
5578 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5579 "Regular expression for fast time stamp matching.")
5580 (defconst org-ts-regexp0
5581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5582 "Regular expression matching time strings for analysis.
5583 This one does not require the space after the date, so it can be used
5584 on a string that terminates immediately after the date.")
5585 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5586 "Regular expression matching time strings for analysis.")
5587 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
5588 "Regular expression matching time stamps, with groups.")
5589 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
5590 "Regular expression matching time stamps (also [..]), with groups.")
5591 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
5592 "Regular expression matching a time stamp range.")
5593 (defconst org-tr-regexp-both
5594 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
5595 "Regular expression matching a time stamp range.")
5596 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
5597 org-ts-regexp
"\\)?")
5598 "Regular expression matching a time stamp or time stamp range.")
5599 (defconst org-tsr-regexp-both
5600 (concat org-ts-regexp-both
"\\(--?-?"
5601 org-ts-regexp-both
"\\)?")
5602 "Regular expression matching a time stamp or time stamp range.
5603 The time stamps may be either active or inactive.")
5605 (defvar org-emph-face nil
)
5607 (defun org-do-emphasis-faces (limit)
5608 "Run through the buffer and add overlays to emphasized strings."
5610 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
5611 (if (not (= (char-after (match-beginning 3))
5612 (char-after (match-beginning 4))))
5615 (setq a
(assoc (match-string 3) org-emphasis-alist
))
5616 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5620 (org-remove-flyspell-overlays-in
5621 (match-beginning 0) (match-end 0)))
5622 (add-text-properties (match-beginning 2) (match-end 2)
5623 '(font-lock-multiline t org-emphasis t
))
5624 (when org-hide-emphasis-markers
5625 (add-text-properties (match-end 4) (match-beginning 5)
5626 '(invisible org-link
))
5627 (add-text-properties (match-beginning 3) (match-end 3)
5628 '(invisible org-link
)))))
5632 (defun org-emphasize (&optional char
)
5633 "Insert or change an emphasis, i.e. a font like bold or italic.
5634 If there is an active region, change that region to a new emphasis.
5635 If there is no region, just insert the marker characters and position
5636 the cursor between them.
5637 CHAR should be either the marker character, or the first character of the
5638 HTML tag associated with that emphasis. If CHAR is a space, the means
5639 to remove the emphasis of the selected region.
5640 If char is not given (for example in an interactive call) it
5641 will be prompted for."
5643 (let ((eal org-emphasis-alist
) e det
5644 (erc org-emphasis-regexp-components
)
5646 (string "") beg end move tag c s
)
5647 (if (org-region-active-p)
5648 (setq beg
(region-beginning) end
(region-end)
5649 string
(buffer-substring beg end
))
5652 (while (setq e
(pop eal
))
5653 (setq tag
(car (org-split-string (nth 2 e
) "[ <>/]+"))
5655 (push (cons c
(string-to-char (car e
))) det
)
5656 (setq prompt
(concat prompt
(format " [%s%c]%s" (car e
) c
5657 (substring tag
1)))))
5658 (setq det
(nreverse det
))
5660 (message "%s" (concat "Emphasis marker or tag:" prompt
))
5661 (setq char
(read-char-exclusive)))
5662 (setq char
(or (cdr (assoc char det
)) char
))
5663 (if (equal char ?\
)
5664 (setq s
"" move nil
)
5665 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5666 (error "No such emphasis marker: \"%c\"" char
))
5667 (setq s
(char-to-string char
)))
5668 (while (and (> (length string
) 1)
5669 (equal (substring string
0 1) (substring string -
1))
5670 (assoc (substring string
0 1) org-emphasis-alist
))
5671 (setq string
(substring string
1 -
1)))
5672 (setq string
(concat s string s
))
5673 (if beg
(delete-region beg end
))
5675 (string-match (concat "[" (nth 0 erc
) "\n]")
5676 (char-to-string (char-before (point)))))
5679 (string-match (concat "[" (nth 1 erc
) "\n]")
5680 (char-to-string (char-after (point)))))
5681 (insert " ") (backward-char 1))
5683 (and move
(backward-char 1))))
5685 (defconst org-nonsticky-props
5686 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5688 (defsubst org-rear-nonsticky-at
(pos)
5689 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5691 (defun org-activate-plain-links (limit)
5692 "Run through the buffer and add overlays to links."
5694 (when (and (re-search-forward (concat org-plain-link-re
) limit t
)
5695 (not (org-in-src-block-p)))
5696 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5697 (setq f
(get-text-property (match-beginning 0) 'face
))
5698 (setq hl
(org-match-string-no-properties 0))
5699 (if (or (eq f
'org-tag
)
5700 (and (listp f
) (memq 'org-tag f
)))
5702 (add-text-properties (match-beginning 0) (match-end 0)
5703 (list 'mouse-face
'highlight
5705 'htmlize-link
`(:uri
,hl
)
5706 'keymap org-mouse-map
))
5707 (org-rear-nonsticky-at (match-end 0)))
5710 (defun org-activate-code (limit)
5711 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5713 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5714 (remove-text-properties (match-beginning 0) (match-end 0)
5715 '(display t invisible t intangible t
))
5718 (defcustom org-src-fontify-natively nil
5719 "When non-nil, fontify code in code blocks."
5722 :group
'org-appearance
5725 (defcustom org-allow-promoting-top-level-subtree nil
5726 "When non-nil, allow promoting a top level subtree.
5727 The leading star of the top level headline will be replaced
5731 :group
'org-appearance
)
5733 (defun org-fontify-meta-lines-and-blocks (limit)
5735 (org-fontify-meta-lines-and-blocks-1 limit
)
5736 (error (message "org-mode fontification error"))))
5738 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5739 "Fontify #+ lines and blocks."
5740 (let ((case-fold-search t
))
5741 (if (re-search-forward
5742 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5744 (let ((beg (match-beginning 0))
5745 (block-start (match-end 0))
5747 (lang (match-string 7))
5748 (beg1 (line-beginning-position 2))
5749 (dc1 (downcase (match-string 2)))
5750 (dc3 (downcase (match-string 3)))
5751 end end1 quoting block-type ovl
)
5753 ((member dc1
'("+html:" "+ascii:" "+latex:"))
5754 ;; a single line of backend-specific content
5755 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5756 (remove-text-properties (match-beginning 0) (match-end 0)
5757 '(display t invisible t intangible t
))
5758 (add-text-properties (match-beginning 1) (match-end 3)
5759 '(font-lock-fontified t face org-meta-line
))
5760 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5761 '(font-lock-fontified t face org-block
))
5762 ; for backend-specific code
5764 ((and (match-end 4) (equal dc3
"+begin"))
5766 (setq block-type
(downcase (match-string 5))
5767 quoting
(member block-type org-protecting-blocks
))
5768 (when (re-search-forward
5769 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5770 nil t
) ;; on purpose, we look further than LIMIT
5771 (setq end
(min (point-max) (match-end 0))
5772 end1
(min (point-max) (1- (match-beginning 0))))
5773 (setq block-end
(match-beginning 0))
5775 (remove-text-properties beg end
5776 '(display t invisible t intangible t
)))
5777 (add-text-properties
5779 '(font-lock-fontified t font-lock-multiline t
))
5780 (add-text-properties beg beg1
'(face org-meta-line
))
5781 (add-text-properties end1
(min (point-max) (1+ end
))
5782 '(face org-meta-line
)) ; for end_src
5784 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5785 (org-src-font-lock-fontify-block lang block-start block-end
)
5786 ;; remove old background overlays
5788 (if (eq (overlay-get ov
'face
) 'org-block-background
)
5789 (delete-overlay ov
)))
5790 (overlays-at (/ (+ beg1 block-end
) 2)))
5791 ;; add a background overlay
5792 (setq ovl
(make-overlay beg1 block-end
))
5793 (overlay-put ovl
'face
'org-block-background
)
5794 (overlay-put ovl
'evaporate t
)) ;; make it go away when empty
5796 (add-text-properties beg1
(min (point-max) (1+ end1
))
5797 '(face org-block
))) ; end of source block
5798 ((not org-fontify-quote-and-verse-blocks
))
5799 ((string= block-type
"quote")
5800 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
5801 ((string= block-type
"verse")
5802 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
5803 (add-text-properties beg beg1
'(face org-block-begin-line
))
5804 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5805 '(face org-block-end-line
))
5807 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
5808 (add-text-properties
5810 (if (member (intern (substring dc1
0 -
1)) org-hidden-keywords
)
5811 '(font-lock-fontified t invisible t
)
5812 '(font-lock-fontified t face org-document-info-keyword
)))
5813 (add-text-properties
5814 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5815 (if (string-equal dc1
"+title:")
5816 '(font-lock-fontified t face org-document-title
)
5817 '(font-lock-fontified t face org-document-info
))))
5818 ((or (equal dc1
"+results")
5819 (member dc1
'("+begin:" "+end:" "+caption:" "+label:"
5820 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5821 "+call:" "+header:" "+headers:" "+name:"))
5822 (and (match-end 4) (equal dc3
"+attr")))
5823 (add-text-properties
5825 '(font-lock-fontified t face org-meta-line
))
5827 ((member dc3
'(" " ""))
5828 (add-text-properties
5830 '(font-lock-fontified t face font-lock-comment-face
)))
5831 ((not (member (char-after beg
) '(?\ ?
\t)))
5832 ;; just any other in-buffer setting, but not indented
5833 (add-text-properties
5835 '(font-lock-fontified t face org-meta-line
))
5839 (defun org-activate-angle-links (limit)
5840 "Run through the buffer and add overlays to links."
5841 (if (and (re-search-forward org-angle-link-re limit t
)
5842 (not (org-in-src-block-p)))
5844 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5845 (add-text-properties (match-beginning 0) (match-end 0)
5846 (list 'mouse-face
'highlight
5847 'keymap org-mouse-map
))
5848 (org-rear-nonsticky-at (match-end 0))
5851 (defun org-activate-footnote-links (limit)
5852 "Run through the buffer and add overlays to footnotes."
5853 (let ((fn (org-footnote-next-reference-or-definition limit
)))
5855 (let ((beg (nth 1 fn
)) (end (nth 2 fn
)))
5856 (org-remove-flyspell-overlays-in beg end
)
5857 (add-text-properties beg end
5858 (list 'mouse-face
'highlight
5859 'keymap org-mouse-map
5861 (if (= (point-at-bol) beg
)
5862 "Footnote definition"
5863 "Footnote reference")
5864 'font-lock-fontified t
5865 'font-lock-multiline t
5866 'face
'org-footnote
))))))
5868 (defun org-activate-bracket-links (limit)
5869 "Run through the buffer and add overlays to bracketed links."
5870 (if (and (re-search-forward org-bracket-link-regexp limit t
)
5871 (not (org-in-src-block-p)))
5872 (let* ((hl (org-match-string-no-properties 1))
5873 (help (concat "LINK: " hl
))
5874 ;; FIXME: Above we should remove the escapes. But that
5875 ;; requires another match, protecting match data, a lot
5876 ;; of overhead for font-lock.
5877 (ip (org-maybe-intangible
5878 (list 'invisible
'org-link
5879 'keymap org-mouse-map
'mouse-face
'highlight
5880 'font-lock-multiline t
'help-echo help
5881 'htmlize-link
`(:uri
,hl
))))
5882 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
5883 'font-lock-multiline t
'help-echo help
5884 'htmlize-link
`(:uri
,hl
))))
5885 ;; We need to remove the invisible property here. Table narrowing
5886 ;; may have made some of this invisible.
5887 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5888 (remove-text-properties (match-beginning 0) (match-end 0)
5892 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
5893 (org-rear-nonsticky-at (match-beginning 3))
5894 (add-text-properties (match-beginning 3) (match-end 3) vp
)
5895 (org-rear-nonsticky-at (match-end 3))
5896 (add-text-properties (match-end 3) (match-end 0) ip
)
5897 (org-rear-nonsticky-at (match-end 0)))
5898 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
5899 (org-rear-nonsticky-at (match-beginning 1))
5900 (add-text-properties (match-beginning 1) (match-end 1) vp
)
5901 (org-rear-nonsticky-at (match-end 1))
5902 (add-text-properties (match-end 1) (match-end 0) ip
)
5903 (org-rear-nonsticky-at (match-end 0)))
5906 (defun org-activate-dates (limit)
5907 "Run through the buffer and add overlays to dates."
5908 (if (and (re-search-forward org-tsr-regexp-both limit t
)
5909 (not (equal (char-before (match-beginning 0)) 91)))
5911 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5912 (add-text-properties (match-beginning 0) (match-end 0)
5913 (list 'mouse-face
'highlight
5914 'keymap org-mouse-map
))
5915 (org-rear-nonsticky-at (match-end 0))
5916 (when org-display-custom-times
5918 (org-display-custom-time (match-beginning 3) (match-end 3)))
5919 (org-display-custom-time (match-beginning 1) (match-end 1)))
5922 (defvar org-target-link-regexp nil
5923 "Regular expression matching radio targets in plain text.")
5924 (make-variable-buffer-local 'org-target-link-regexp
)
5925 (defvar org-target-regexp
"<<\\([^<>\n\r]+\\)>>"
5926 "Regular expression matching a link target.")
5927 (defvar org-radio-target-regexp
"<<<\\([^<>\n\r]+\\)>>>"
5928 "Regular expression matching a radio target.")
5929 (defvar org-any-target-regexp
"<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5930 "Regular expression matching any target.")
5932 (defun org-activate-target-links (limit)
5933 "Run through the buffer and add overlays to target matches."
5934 (when org-target-link-regexp
5935 (let ((case-fold-search t
))
5936 (if (re-search-forward org-target-link-regexp limit t
)
5938 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5939 (add-text-properties (match-beginning 0) (match-end 0)
5940 (list 'mouse-face
'highlight
5941 'keymap org-mouse-map
5942 'help-echo
"Radio target link"
5943 'org-linked-text t
))
5944 (org-rear-nonsticky-at (match-end 0))
5947 (defun org-update-radio-target-regexp ()
5948 "Find all radio targets in this file and update the regular expression."
5950 (when (memq 'radio org-activate-links
)
5951 (setq org-target-link-regexp
5952 (org-make-target-link-regexp (org-all-targets 'radio
)))
5953 (org-restart-font-lock)))
5955 (defun org-hide-wide-columns (limit)
5957 (setq s
(text-property-any (point) (or limit
(point-max))
5960 (setq e
(next-single-property-change s
'org-cwidth
))
5961 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
5965 (defvar org-latex-and-related-regexp nil
5966 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5967 (defvar org-match-substring-regexp
)
5968 (defvar org-match-substring-with-braces-regexp
)
5970 (defun org-compute-latex-and-related-regexp ()
5971 "Compute regular expression for LaTeX, entities and sub/superscript.
5972 Result depends on variable `org-highlight-latex-and-related'."
5974 'org-latex-and-related-regexp
5976 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
5977 ((eq org-use-sub-superscripts
'{})
5978 (list org-match-substring-with-braces-regexp
))
5979 (org-use-sub-superscripts (list org-match-substring-regexp
))))
5981 (when (memq 'latex org-highlight-latex-and-related
)
5982 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
5985 (and (member (car x
) matchers
) (nth 1 x
)))
5986 org-latex-regexps
)))))
5988 (when (memq 'entities org-highlight-latex-and-related
)
5989 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5990 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
5992 (defun org-do-latex-and-related (limit)
5993 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5994 LIMIT bounds the search for syntax to highlight. Stop at first
5995 highlighted object, if any. Return t if some highlighting was
5996 done, nil otherwise."
5997 (when (org-string-nw-p org-latex-and-related-regexp
)
5999 (while (re-search-forward org-latex-and-related-regexp limit t
)
6000 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6002 '(org-code org-verbatim underline
))
6003 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6007 (font-lock-prepend-text-property
6008 (+ offset
(match-beginning 0)) (match-end 0)
6009 'face
'org-latex-and-related
)
6010 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6011 '(font-lock-multiline t
)))
6015 (defun org-restart-font-lock ()
6016 "Restart `font-lock-mode', to force refontification."
6017 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6019 (font-lock-mode 1)))
6021 (defun org-all-targets (&optional radio
)
6022 "Return a list of all targets in this file.
6023 When optional argument RADIO is non-nil, only find radio
6025 (let ((re (if radio org-radio-target-regexp org-target-regexp
)) rtn
)
6027 (goto-char (point-min))
6028 (while (re-search-forward re nil t
)
6029 ;; Make sure point is really within the object.
6031 (let ((obj (org-element-context)))
6032 (when (memq (org-element-type obj
) '(radio-target target
))
6033 (add-to-list 'rtn
(downcase (org-element-property :value obj
))))))
6036 (defun org-make-target-link-regexp (targets)
6037 "Make regular expression matching all strings in TARGETS.
6038 The regular expression finds the targets also if there is a line break
6045 (setq x
(regexp-quote x
))
6046 (while (string-match " +" x
)
6047 (setq x
(replace-match "\\s-+" t t x
)))
6053 (defun org-activate-tags (limit)
6054 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t
)
6056 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6057 (add-text-properties (match-beginning 1) (match-end 1)
6058 (list 'mouse-face
'highlight
6059 'keymap org-mouse-map
))
6060 (org-rear-nonsticky-at (match-end 1))
6063 (defun org-outline-level ()
6064 "Compute the outline level of the heading at point.
6065 If this is called at a normal headline, the level is the number of stars.
6066 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6068 (if (not (condition-case nil
6069 (org-back-to-heading t
)
6072 (looking-at org-outline-regexp
)
6073 (1- (- (match-end 0) (match-beginning 0))))))
6075 (defvar org-font-lock-keywords nil
)
6077 (defconst org-property-re
(org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6078 "Regular expression matching a property line.")
6080 (defvar org-font-lock-hook nil
6081 "Functions to be called for special font lock stuff.")
6083 (defvar org-font-lock-set-keywords-hook nil
6084 "Functions that can manipulate `org-font-lock-extra-keywords'.
6085 This is called after `org-font-lock-extra-keywords' is defined, but before
6086 it is installed to be used by font lock. This can be useful if something
6087 needs to be inserted at a specific position in the font-lock sequence.")
6089 (defun org-font-lock-hook (limit)
6090 "Run `org-font-lock-hook' within LIMIT."
6091 (run-hook-with-args 'org-font-lock-hook limit
))
6093 (defun org-set-font-lock-defaults ()
6094 "Set font lock defaults for the current buffer."
6095 (let* ((em org-fontify-emphasized-text
)
6096 (lk org-activate-links
)
6097 (org-font-lock-extra-keywords
6100 '(org-font-lock-hook)
6102 `(,(if org-fontify-whole-heading-line
6103 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6104 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6105 (1 (org-get-level-face 1))
6106 (2 (org-get-level-face 2))
6107 (3 (org-get-level-face 3)))
6109 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6112 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6113 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6114 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6115 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6117 (list org-drawer-regexp
'(0 'org-special-keyword t
))
6118 (list "^[ \t]*:END:" '(0 'org-special-keyword t
))
6120 (list org-property-re
6121 '(1 'org-special-keyword t
)
6122 '(3 'org-property-value t
))
6124 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6125 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
6126 (if (memq 'plain lk
) '(org-activate-plain-links (0 'org-link t
)))
6127 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
6128 (if (memq 'radio lk
) '(org-activate-target-links (0 'org-link t
)))
6129 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6130 (if (memq 'footnote lk
) '(org-activate-footnote-links))
6132 (list org-any-target-regexp
'(0 'org-target t
))
6134 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6136 '("{{{.+}}}" (0 'org-macro t
))
6137 '(org-hide-wide-columns (0 nil append
))
6139 (list (format org-heading-keyword-regexp-format
6141 '(2 (org-get-todo-face 2) t
))
6143 (if org-fontify-done-headline
6144 (list (format org-heading-keyword-regexp-format
6147 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6149 '(2 'org-headline-done t
))
6152 '(org-font-lock-add-priority-faces)
6154 '(org-font-lock-add-tag-faces)
6156 (if (and org-group-tags org-tag-groups-alist
)
6157 (list (concat org-outline-regexp-bol
".+\\(:"
6158 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6160 '(1 'org-tag-group prepend
)))
6162 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6163 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6164 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6165 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6168 (if (featurep 'xemacs
)
6169 '(org-do-emphasis-faces (0 nil append
))
6170 '(org-do-emphasis-faces)))
6172 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6173 1 'org-checkbox prepend
)
6174 (if (cdr (assq 'checkbox org-list-automatic-rules
))
6175 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6176 (0 (org-get-checkbox-statistics-face) t
)))
6177 ;; Description list items
6178 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6179 1 'org-list-dt prepend
)
6180 ;; ARCHIVEd headings
6182 org-outline-regexp-bol
6183 "\\(.*:" org-archive-tag
":.*\\)")
6184 '(1 'org-archived prepend
))
6186 '(org-do-latex-and-related)
6187 '(org-fontify-entities)
6188 '(org-raise-scripts)
6190 '(org-activate-code (1 'org-code t
))
6192 (list (format org-heading-keyword-regexp-format
6194 org-comment-string
"\\|" org-quote-string
6196 '(2 'org-special-keyword t
))
6197 ;; Blocks and meta lines
6198 '(org-fontify-meta-lines-and-blocks)
6200 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6201 (run-hooks 'org-font-lock-set-keywords-hook
)
6202 ;; Now set the full font-lock-keywords
6203 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
6204 (org-set-local 'font-lock-defaults
6205 '(org-font-lock-keywords t nil nil backward-paragraph
))
6206 (kill-local-variable 'font-lock-keywords
) nil
))
6208 (defun org-toggle-pretty-entities ()
6209 "Toggle the composition display of entities as UTF8 characters."
6211 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
6212 (org-restart-font-lock)
6213 (if org-pretty-entities
6214 (message "Entities are displayed as UTF8 characters")
6217 (org-decompose-region (point-min) (point-max))
6218 (message "Entities are displayed plain"))))
6220 (defvar org-custom-properties-overlays nil
6221 "List of overlays used for custom properties.")
6222 (make-variable-buffer-local 'org-custom-properties-overlays
)
6224 (defun org-toggle-custom-properties-visibility ()
6225 "Display or hide properties in `org-custom-properties'."
6227 (if org-custom-properties-overlays
6228 (progn (mapc 'delete-overlay org-custom-properties-overlays
)
6229 (setq org-custom-properties-overlays nil
))
6230 (unless (not org-custom-properties
)
6234 (goto-char (point-min))
6235 (while (re-search-forward org-property-re nil t
)
6237 (when (equal p
(substring (match-string 1) 1 -
1))
6238 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6239 (overlay-put o
'invisible t
)
6240 (overlay-put o
'org-custom-property t
)
6241 (push o org-custom-properties-overlays
))))
6242 org-custom-properties
)))))))
6244 (defun org-fontify-entities (limit)
6245 "Find an entity to fontify."
6247 (when org-pretty-entities
6249 (while (re-search-forward
6250 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6252 (if (and (not (org-in-indented-comment-line))
6253 (setq ee
(org-entity-get (match-string 1)))
6254 (= (length (nth 6 ee
)) 1))
6256 ((end (if (equal (match-string 2) "{}")
6259 (add-text-properties
6260 (match-beginning 0) end
6261 (list 'font-lock-fontified t
))
6262 (compose-region (match-beginning 0) end
6268 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6269 "Fontify string S like in Org-mode."
6272 (let ((org-odd-levels-only odd-levels
))
6274 (font-lock-fontify-buffer)
6280 (defun org-get-level-face (n)
6281 "Get the right face for match N in font-lock matching of headlines."
6282 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6283 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6284 (if org-cycle-level-faces
6285 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6286 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6288 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6290 (t (if org-level-color-stars-only nil org-f
))))
6293 (defun org-get-todo-face (kwd)
6294 "Get the right face for a TODO keyword KWD.
6295 If KWD is a number, get the corresponding match group."
6296 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6297 (or (org-face-from-face-or-color
6298 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6299 (and (member kwd org-done-keywords
) 'org-done
)
6302 (defun org-face-from-face-or-color (context inherit face-or-color
)
6303 "Create a face list that inherits INHERIT, but sets the foreground color.
6304 When FACE-OR-COLOR is not a string, just return it."
6305 (if (stringp face-or-color
)
6306 (list :inherit inherit
6307 (cdr (assoc context org-faces-easy-properties
))
6311 (defun org-font-lock-add-tag-faces (limit)
6312 "Add the special tag faces."
6313 (when (and org-tag-faces org-tags-special-faces-re
)
6314 (while (re-search-forward org-tags-special-faces-re limit t
)
6315 (add-text-properties (match-beginning 1) (match-end 1)
6316 (list 'face
(org-get-tag-face 1)
6317 'font-lock-fontified t
))
6318 (backward-char 1))))
6320 (defun org-font-lock-add-priority-faces (limit)
6321 "Add the special priority faces."
6322 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
6323 (when (save-match-data (org-at-heading-p))
6324 (add-text-properties
6325 (match-beginning 0) (match-end 0)
6326 (list 'face
(or (org-face-from-face-or-color
6327 'priority
'org-priority
6328 (cdr (assoc (char-after (match-beginning 1))
6329 org-priority-faces
)))
6331 'font-lock-fontified t
)))))
6333 (defun org-get-tag-face (kwd)
6334 "Get the right face for a TODO keyword KWD.
6335 If KWD is a number, get the corresponding match group."
6336 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6337 (or (org-face-from-face-or-color
6338 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
6341 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
6342 "Remove fontification and activation overlays from links."
6343 (font-lock-default-unfontify-region beg end
)
6344 (let* ((buffer-undo-list t
)
6345 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6346 (inhibit-modification-hooks t
)
6347 deactivate-mark buffer-file-name buffer-file-truename
)
6348 (org-decompose-region beg end
)
6349 (remove-text-properties beg end
6350 '(mouse-face t keymap t org-linked-text t
6351 invisible t intangible t
6352 org-no-flyspell t org-emphasis t
))
6353 (org-remove-font-lock-display-properties beg end
)))
6355 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6356 ((raise 0.3) (height 0.7))
6359 "Display properties for showing superscripts and subscripts.")
6361 (defun org-remove-font-lock-display-properties (beg end
)
6362 "Remove specific display properties that have been added by font lock.
6363 The will remove the raise properties that are used to show superscripts
6367 (setq next
(next-single-property-change beg
'display nil end
)
6368 prop
(get-text-property beg
'display
))
6369 (if (member prop org-script-display
)
6370 (put-text-property beg next
'display nil
))
6373 (defun org-raise-scripts (limit)
6374 "Add raise properties to sub/superscripts."
6375 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
6376 (if (re-search-forward
6377 (if (eq org-use-sub-superscripts t
)
6378 org-match-substring-regexp
6379 org-match-substring-with-braces-regexp
)
6381 (let* ((pos (point)) table-p comment-p
6382 (mpos (match-beginning 3))
6383 (emph-p (get-text-property mpos
'org-emphasis
))
6384 (link-p (get-text-property mpos
'mouse-face
))
6385 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6386 (goto-char (point-at-bol))
6387 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
6388 comment-p
(org-looking-at-p "[ \t]*#"))
6390 ;; FIXME: Should we go back one character here, for a_b^c
6391 ;; (goto-char (1- pos)) ;????????????????????
6392 (if (or comment-p emph-p link-p keyw-p
)
6394 (put-text-property (match-beginning 3) (match-end 0)
6396 (if (equal (char-after (match-beginning 2)) ?^
)
6397 (nth (if table-p
3 1) org-script-display
)
6398 (nth (if table-p
2 0) org-script-display
)))
6399 (add-text-properties (match-beginning 2) (match-end 2)
6401 'org-dwidth t
'org-dwidth-n
1))
6402 (if (and (eq (char-after (match-beginning 3)) ?
{)
6403 (eq (char-before (match-end 3)) ?
}))
6405 (add-text-properties
6406 (match-beginning 3) (1+ (match-beginning 3))
6407 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6408 (add-text-properties
6409 (1- (match-end 3)) (match-end 3)
6410 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
6413 ;;;; Visibility cycling, including org-goto and indirect buffer
6417 (defvar org-cycle-global-status nil
)
6418 (make-variable-buffer-local 'org-cycle-global-status
)
6419 (put 'org-cycle-global-status
'org-state t
)
6420 (defvar org-cycle-subtree-status nil
)
6421 (make-variable-buffer-local 'org-cycle-subtree-status
)
6422 (put 'org-cycle-subtree-status
'org-state t
)
6424 (defvar org-inlinetask-min-level
)
6427 (defun org-cycle (&optional arg
)
6428 "TAB-action and visibility cycling for Org-mode.
6430 This is the command invoked in Org-mode by the TAB key. Its main purpose
6431 is outline visibility cycling, but it also invokes other actions
6432 in special contexts.
6434 - When this function is called with a prefix argument, rotate the entire
6435 buffer through 3 states (global cycling)
6436 1. OVERVIEW: Show only top-level headlines.
6437 2. CONTENTS: Show all headlines of all levels, but no body text.
6438 3. SHOW ALL: Show everything.
6439 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6440 determined by the variable `org-startup-folded', and by any VISIBILITY
6441 properties in the buffer.
6442 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6443 including any drawers.
6445 - When inside a table, re-align the table and move to the next field.
6447 - When point is at the beginning of a headline, rotate the subtree started
6448 by this line through 3 different states (local cycling)
6449 1. FOLDED: Only the main headline is shown.
6450 2. CHILDREN: The main headline and the direct children are shown.
6451 From this state, you can move to one of the children
6452 and zoom in further.
6453 3. SUBTREE: Show the entire subtree, including body text.
6454 If there is no subtree, switch directly from CHILDREN to FOLDED.
6456 - When point is at the beginning of an empty headline and the variable
6457 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6458 of the headline by demoting and promoting it to likely levels. This
6459 speeds up creation document structure by pressing TAB once or several
6460 times right after creating a new headline.
6462 - When there is a numeric prefix, go up to a heading with level ARG, do
6463 a `show-subtree' and return to the previous cursor position. If ARG
6464 is negative, go up that many levels.
6466 - When point is not at the beginning of a headline, execute the global
6467 binding for TAB, which is re-indenting the line. See the option
6468 `org-cycle-emulate-tab' for details.
6470 - Special case: if point is at the beginning of the buffer and there is
6471 no headline in line 1, this function will act as if called with prefix arg
6472 (C-u TAB, same as S-TAB) also when called without prefix arg.
6473 But only if also the variable `org-cycle-global-at-bob' is t."
6475 (org-load-modules-maybe)
6476 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6477 (and org-cycle-level-after-item
/entry-creation
6478 (or (org-cycle-level)
6479 (org-cycle-item-indentation))))
6480 (let* (message-log-max ; Don't populate the *Messages* buffer
6482 (or org-cycle-max-level
6483 (and (boundp 'org-inlinetask-min-level
)
6484 org-inlinetask-min-level
6485 (1- org-inlinetask-min-level
))))
6486 (nstars (and limit-level
6487 (if org-odd-levels-only
6488 (and limit-level
(1- (* limit-level
2)))
6491 (if (not (derived-mode-p 'org-mode
))
6493 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6494 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6495 (not (looking-at org-outline-regexp
))))
6498 (delq 'org-optimize-window-after-visibility-change
6499 (copy-sequence org-cycle-hook
))
6503 (if (or bob-special
(equal arg
'(4)))
6504 ;; special case: use global cycling
6510 (setq last-command
'dummy
)
6511 (org-set-startup-visibility)
6512 (message "Startup visibility, plus VISIBILITY properties"))
6516 (message "Entire buffer visible, including drawers"))
6518 ;; Table: enter it or move to the next field.
6519 ((org-at-table-p 'any
)
6520 (if (org-at-table.el-p
)
6521 (message "Use C-c ' to edit table.el tables")
6522 (if arg
(org-table-edit-field t
)
6523 (org-table-justify-field-maybe)
6524 (call-interactively 'org-table-next-field
))))
6526 ((run-hook-with-args-until-success
6527 'org-tab-after-check-for-table-hook
))
6529 ;; Global cycling: delegate to `org-cycle-internal-global'.
6530 ((eq arg t
) (org-cycle-internal-global))
6532 ;; Drawers: delegate to `org-flag-drawer'.
6533 ((and org-drawers org-drawer-regexp
6535 (beginning-of-line 1)
6536 (looking-at org-drawer-regexp
)))
6537 (org-flag-drawer ; toggle block visibility
6538 (not (get-char-property (match-end 0) 'invisible
))))
6540 ;; Show-subtree, ARG levels up from here.
6543 (org-back-to-heading)
6544 (outline-up-heading (if (< arg
0) (- arg
)
6545 (- (funcall outline-level
) arg
)))
6546 (org-show-subtree)))
6548 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6549 ((and (featurep 'org-inlinetask
)
6550 (org-inlinetask-at-task-p)
6551 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6552 (org-inlinetask-toggle-visibility))
6554 ((org-try-cdlatex-tab))
6556 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6557 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6558 (save-excursion (beginning-of-line 1)
6559 (looking-at org-outline-regexp
)))
6560 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6561 (org-cycle-internal-local))
6563 ;; From there: TAB emulation and template completion.
6564 (buffer-read-only (org-back-to-heading))
6566 ((run-hook-with-args-until-success
6567 'org-tab-after-check-for-cycling-hook
))
6569 ((org-try-structure-completion))
6571 ((run-hook-with-args-until-success
6572 'org-tab-before-tab-emulation-hook
))
6574 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6576 (not (looking-at org-outline-regexp
))))
6577 (call-interactively (global-key-binding "\t")))
6579 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6580 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6581 (or (and (eq org-cycle-emulate-tab
'white
)
6582 (= (match-end 0) (point-at-eol)))
6583 (and (eq org-cycle-emulate-tab
'whitestart
)
6584 (>= (match-end 0) pos
))))
6586 (eq org-cycle-emulate-tab t
))
6587 (call-interactively (global-key-binding "\t")))
6590 (org-back-to-heading)
6593 (defun org-cycle-internal-global ()
6594 "Do the global cycling action."
6595 ;; Hack to avoid display of messages for .org attachments in Gnus
6596 (let (message-log-max ; Don't populate the *Messages* buffer
6597 (ga (string-match "\\*fontification" (buffer-name))))
6599 ((and (eq last-command this-command
)
6600 (eq org-cycle-global-status
'overview
))
6601 ;; We just created the overview - now do table of contents
6602 ;; This can be slow in very large buffers, so indicate action
6603 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6604 (unless ga
(message "CONTENTS..."))
6606 (unless ga
(message "CONTENTS...done"))
6607 (setq org-cycle-global-status
'contents
)
6608 (run-hook-with-args 'org-cycle-hook
'contents
))
6610 ((and (eq last-command this-command
)
6611 (eq org-cycle-global-status
'contents
))
6612 ;; We just showed the table of contents - now show everything
6613 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6615 (unless ga
(message "SHOW ALL"))
6616 (setq org-cycle-global-status
'all
)
6617 (run-hook-with-args 'org-cycle-hook
'all
))
6620 ;; Default action: go to overview
6621 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6623 (unless ga
(message "OVERVIEW"))
6624 (setq org-cycle-global-status
'overview
)
6625 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6627 (defun org-cycle-internal-local ()
6628 "Do the local cycling action."
6629 (let (message-log-max ; Don't populate the *Messages* buffer
6630 (goal-column 0) eoh eol eos has-children children-skipped struct
)
6631 ;; First, determine end of headline (EOH), end of subtree or item
6632 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6637 (setq struct
(org-list-struct))
6638 (setq eoh
(point-at-eol))
6639 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6640 (setq has-children
(org-list-has-child-p (point) struct
)))
6641 (org-back-to-heading)
6642 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6643 (setq eos
(save-excursion (1- (org-end-of-subtree t t
))))
6646 (let ((level (funcall outline-level
)))
6647 (outline-next-heading)
6648 (and (org-at-heading-p t
)
6649 (> (funcall outline-level
) level
))))
6651 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6652 ;; Determine end invisible part of buffer (EOL)
6653 (beginning-of-line 2)
6654 ;; XEmacs doesn't have `next-single-char-property-change'
6655 (if (featurep 'xemacs
)
6656 (while (and (not (eobp)) ;; this is like `next-line'
6657 (get-char-property (1- (point)) 'invisible
))
6658 (beginning-of-line 2))
6659 (while (and (not (eobp)) ;; this is like `next-line'
6660 (get-char-property (1- (point)) 'invisible
))
6661 (goto-char (next-single-char-property-change (point) 'invisible
))
6662 (and (eolp) (beginning-of-line 2))))
6664 ;; Find out what to do next and set `this-command'
6667 ;; Nothing is hidden behind this heading
6668 (unless (org-before-first-heading-p)
6669 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
6670 (message "EMPTY ENTRY")
6671 (setq org-cycle-subtree-status nil
)
6674 (outline-next-heading)
6675 (if (outline-invisible-p) (org-flag-heading nil
))))
6676 ((and (or (>= eol eos
)
6677 (not (string-match "\\S-" (buffer-substring eol eos
))))
6679 (not (setq children-skipped
6680 org-cycle-skip-children-state-if-no-children
))))
6681 ;; Entire subtree is hidden in one line: children view
6682 (unless (org-before-first-heading-p)
6683 (run-hook-with-args 'org-pre-cycle-hook
'children
))
6685 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6687 (org-with-limited-levels (show-children))
6688 ;; FIXME: This slows down the func way too much.
6689 ;; How keep drawers hidden in subtree anyway?
6690 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6691 ;; (org-cycle-hide-drawers 'subtree))
6693 ;; Fold every list in subtree to top-level items.
6694 (when (eq org-cycle-include-plain-lists
'integrate
)
6696 (org-back-to-heading)
6697 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6698 (beginning-of-line 1)
6699 (let* ((struct (org-list-struct))
6700 (prevs (org-list-prevs-alist struct
))
6701 (end (org-list-get-bottom-point struct
)))
6702 (mapc (lambda (e) (org-list-set-item-visibility e struct
'folded
))
6703 (org-list-get-all-items (point) struct prevs
))
6704 (goto-char end
))))))
6705 (message "CHILDREN")
6708 (outline-next-heading)
6709 (if (outline-invisible-p) (org-flag-heading nil
)))
6710 (setq org-cycle-subtree-status
'children
)
6711 (unless (org-before-first-heading-p)
6712 (run-hook-with-args 'org-cycle-hook
'children
)))
6713 ((or children-skipped
6714 (and (eq last-command this-command
)
6715 (eq org-cycle-subtree-status
'children
)))
6716 ;; We just showed the children, or no children are there,
6717 ;; now show everything.
6718 (unless (org-before-first-heading-p)
6719 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
6720 (outline-flag-region eoh eos nil
)
6721 (message (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6722 (setq org-cycle-subtree-status
'subtree
)
6723 (unless (org-before-first-heading-p)
6724 (run-hook-with-args 'org-cycle-hook
'subtree
)))
6726 ;; Default action: hide the subtree.
6727 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6728 (outline-flag-region eoh eos t
)
6730 (setq org-cycle-subtree-status
'folded
)
6731 (unless (org-before-first-heading-p)
6732 (run-hook-with-args 'org-cycle-hook
'folded
))))))
6735 (defun org-global-cycle (&optional arg
)
6736 "Cycle the global visibility. For details see `org-cycle'.
6737 With \\[universal-argument] prefix arg, switch to startup visibility.
6738 With a numeric prefix, show all headlines up to that level."
6740 (let ((org-cycle-include-plain-lists
6741 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6745 (hide-sublevels arg
)
6746 (setq org-cycle-global-status
'contents
))
6748 (org-set-startup-visibility)
6749 (message "Startup visibility, plus VISIBILITY properties."))
6751 (org-cycle '(4))))))
6753 (defun org-set-startup-visibility ()
6754 "Set the visibility required by startup options and properties."
6756 ((eq org-startup-folded t
)
6758 ((eq org-startup-folded
'content
)
6759 (let ((this-command 'org-cycle
) (last-command 'org-cycle
))
6760 (org-cycle '(4)) (org-cycle '(4)))))
6761 (unless (eq org-startup-folded
'showeverything
)
6762 (if org-hide-block-startup
(org-hide-block-all))
6763 (org-set-visibility-according-to-property 'no-cleanup
)
6764 (org-cycle-hide-archived-subtrees 'all
)
6765 (org-cycle-hide-drawers 'all
)
6766 (org-cycle-show-empty-lines t
)))
6768 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
6769 "Switch subtree visibilities according to :VISIBILITY: property."
6771 (let (org-show-entry-below state
)
6773 (goto-char (point-min))
6774 (while (re-search-forward
6775 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6777 (setq state
(match-string 1))
6779 (org-back-to-heading t
)
6783 ((equal state
'("fold" "folded"))
6785 ((equal state
"children")
6786 (org-show-hidden-entry)
6788 ((equal state
"content")
6791 (org-narrow-to-subtree)
6793 ((member state
'("all" "showall"))
6796 (org-cycle-hide-archived-subtrees 'all
)
6797 (org-cycle-hide-drawers 'all
)
6798 (org-cycle-show-empty-lines 'all
)))))
6800 ;; This function uses outline-regexp instead of the more fundamental
6801 ;; org-outline-regexp so that org-cycle-global works outside of Org
6802 ;; buffers, where outline-regexp is needed.
6803 (defun org-overview ()
6804 "Switch to overview mode, showing only top-level headlines.
6805 Really, this shows all headlines with level equal or greater than the level
6806 of the first headline in the buffer. This is important, because if the
6807 first headline is not level one, then (hide-sublevels 1) gives confusing
6810 (let ((l (org-current-line))
6811 (level (save-excursion
6812 (goto-char (point-min))
6813 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
6815 (goto-char (match-beginning 0))
6816 (funcall outline-level
))))))
6817 (and level
(hide-sublevels level
))
6821 (defun org-content (&optional arg
)
6822 "Show all headlines in the buffer, like a table of contents.
6823 With numerical argument N, show content up to level N."
6826 ;; Visit all headings and show their offspring
6827 (and (integerp arg
) (org-overview))
6828 (goto-char (point-max))
6830 (while (and (progn (condition-case nil
6831 (outline-previous-visible-heading 1)
6832 (error (goto-char (point-min))))
6834 (looking-at org-outline-regexp
))
6836 (show-children (1- arg
))
6838 (if (bobp) (throw 'exit nil
))))))
6841 (defun org-optimize-window-after-visibility-change (state)
6842 "Adjust the window after a change in outline visibility.
6843 This function is the default value of the hook `org-cycle-hook'."
6844 (when (get-buffer-window (current-buffer))
6846 ((eq state
'content
) nil
)
6847 ((eq state
'all
) nil
)
6848 ((eq state
'folded
) nil
)
6849 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
6850 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
6852 (defun org-remove-empty-overlays-at (pos)
6853 "Remove outline overlays that do not contain non-white stuff."
6856 (and (eq 'outline
(overlay-get o
'invisible
))
6857 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
6859 (delete-overlay o
)))
6862 (defun org-clean-visibility-after-subtree-move ()
6863 "Fix visibility issues after moving a subtree."
6864 ;; First, find a reasonable region to look at:
6865 ;; Start two siblings above, end three below
6866 (let* ((beg (save-excursion
6867 (and (org-get-last-sibling)
6868 (org-get-last-sibling))
6870 (end (save-excursion
6871 (and (org-get-next-sibling)
6872 (org-get-next-sibling)
6873 (org-get-next-sibling))
6874 (if (org-at-heading-p)
6877 (level (looking-at "\\*+"))
6878 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
6881 (narrow-to-region beg end
)
6883 ;; Properly fold already folded siblings
6884 (goto-char (point-min))
6885 (while (re-search-forward re nil t
)
6886 (if (and (not (outline-invisible-p))
6888 (goto-char (point-at-eol)) (outline-invisible-p)))
6890 (org-cycle-show-empty-lines 'overview
)
6891 (org-cycle-hide-drawers 'overview
)))))
6893 (defun org-cycle-show-empty-lines (state)
6894 "Show empty lines above all visible headlines.
6895 The region to be covered depends on STATE when called through
6896 `org-cycle-hook'. Lisp program can use t for STATE to get the
6897 entire buffer covered. Note that an empty line is only shown if there
6898 are at least `org-cycle-separator-lines' empty lines before the headline."
6899 (when (not (= org-cycle-separator-lines
0))
6901 (let* ((n (abs org-cycle-separator-lines
))
6903 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
6904 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6905 (t (let ((ns (number-to-string (- n
2))))
6906 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
6907 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6910 ((memq state
'(overview contents t
))
6911 (setq beg
(point-min) end
(point-max)))
6912 ((memq state
'(children folded
))
6913 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
6914 (beginning-of-line 2)
6918 (while (re-search-forward re end t
)
6919 (unless (get-char-property (match-end 1) 'invisible
)
6920 (setq e
(match-end 1))
6921 (if (< org-cycle-separator-lines
0)
6922 (setq b
(save-excursion
6923 (goto-char (match-beginning 0))
6924 (org-back-over-empty-lines)
6926 (goto-char (max (point-min) (1- (point))))
6930 (setq b
(match-beginning 1)))
6931 (outline-flag-region b e nil
)))))))
6932 ;; Never hide empty lines at the end of the file.
6934 (goto-char (point-max))
6935 (outline-previous-heading)
6936 (outline-end-of-heading)
6937 (if (and (looking-at "[ \t\n]+")
6938 (= (match-end 0) (point-max)))
6939 (outline-flag-region (point) (match-end 0) nil
))))
6941 (defun org-show-empty-lines-in-parent ()
6942 "Move to the parent and re-show empty lines before visible headlines."
6944 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
6945 (org-cycle-show-empty-lines context
))))
6947 (defun org-files-list ()
6948 "Return `org-agenda-files' list, plus all open org-mode files.
6949 This is useful for operations that need to scan all of a user's
6950 open and agenda-wise Org files."
6951 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
6952 (dolist (buf (buffer-list))
6953 (with-current-buffer buf
6954 (if (and (derived-mode-p 'org-mode
) (buffer-file-name))
6955 (let ((file (expand-file-name (buffer-file-name))))
6956 (unless (member file files
)
6957 (push file files
))))))
6960 (defsubst org-entry-beginning-position
()
6961 "Return the beginning position of the current entry."
6962 (save-excursion (outline-back-to-heading t
) (point)))
6964 (defsubst org-entry-end-position
()
6965 "Return the end position of the current entry."
6966 (save-excursion (outline-next-heading) (point)))
6968 (defun org-cycle-hide-drawers (state)
6969 "Re-hide all drawers after a visibility state change."
6970 (when (and (derived-mode-p 'org-mode
)
6971 (not (memq state
'(overview folded contents
))))
6973 (let* ((globalp (memq state
'(contents all
)))
6974 (beg (if globalp
(point-min) (point)))
6975 (end (if globalp
(point-max)
6976 (if (eq state
'children
)
6977 (save-excursion (outline-next-heading) (point))
6978 (org-end-of-subtree t
)))))
6980 (while (re-search-forward org-drawer-regexp end t
)
6981 (org-flag-drawer t
))))))
6983 (defun org-cycle-hide-inline-tasks (state)
6984 "Re-hide inline task when switching to 'contents visibility state."
6985 (when (and (eq state
'contents
)
6986 (boundp 'org-inlinetask-min-level
)
6987 org-inlinetask-min-level
)
6988 (hide-sublevels (1- org-inlinetask-min-level
))))
6990 (defun org-flag-drawer (flag)
6991 "When FLAG is non-nil, hide the drawer we are within.
6992 Otherwise make it visible."
6994 (beginning-of-line 1)
6995 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6996 (let ((b (match-end 0)))
6997 (if (re-search-forward
6999 (save-excursion (outline-next-heading) (point)) t
)
7000 (outline-flag-region b
(point-at-eol) flag
)
7001 (error ":END: line missing at position %s" b
))))))
7003 (defun org-subtree-end-visible-p ()
7004 "Is the end of the current subtree visible?"
7005 (pos-visible-in-window-p
7006 (save-excursion (org-end-of-subtree t
) (point))))
7008 (defun org-first-headline-recenter (&optional N
)
7009 "Move cursor to the first headline and recenter the headline.
7010 Optional argument N means put the headline into the Nth line of the window."
7011 (goto-char (point-min))
7012 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7014 (recenter (prefix-numeric-value N
))))
7016 ;;; Saving and restoring visibility
7018 (defun org-outline-overlay-data (&optional use-markers
)
7019 "Return a list of the locations of all outline overlays.
7020 These are overlays with the `invisible' property value `outline'.
7021 The return value is a list of cons cells, with start and stop
7022 positions for each overlay.
7023 If USE-MARKERS is set, return the positions as markers."
7030 (when (eq (overlay-get o
'invisible
) 'outline
)
7031 (setq beg
(overlay-start o
)
7032 end
(overlay-end o
))
7033 (and beg end
(> end beg
)
7035 (cons (move-marker (make-marker) beg
)
7036 (move-marker (make-marker) end
))
7038 (overlays-in (point-min) (point-max))))))))
7040 (defun org-set-outline-overlay-data (data)
7041 "Create visibility overlays for all positions in DATA.
7042 DATA should have been made by `org-outline-overlay-data'."
7049 (outline-flag-region (car c
) (cdr c
) t
))
7052 ;;; Folding of blocks
7054 (defvar org-hide-block-overlays nil
7055 "Overlays hiding blocks.")
7056 (make-variable-buffer-local 'org-hide-block-overlays
)
7058 (defun org-block-map (function &optional start end
)
7059 "Call FUNCTION at the head of all source blocks in the current buffer.
7060 Optional arguments START and END can be used to limit the range."
7061 (let ((start (or start
(point-min)))
7062 (end (or end
(point-max))))
7065 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7068 (goto-char (match-beginning 0))
7069 (funcall function
)))))))
7071 (defun org-hide-block-toggle-all ()
7072 "Toggle the visibility of all blocks in the current buffer."
7073 (org-block-map #'org-hide-block-toggle
))
7075 (defun org-hide-block-all ()
7076 "Fold all blocks in the current buffer."
7078 (org-show-block-all)
7079 (org-block-map #'org-hide-block-toggle-maybe
))
7081 (defun org-show-block-all ()
7082 "Unfold all blocks in the current buffer."
7084 (mapc 'delete-overlay org-hide-block-overlays
)
7085 (setq org-hide-block-overlays nil
))
7087 (defun org-hide-block-toggle-maybe ()
7088 "Toggle visibility of block at point."
7090 (let ((case-fold-search t
))
7092 (beginning-of-line 1)
7093 (looking-at org-block-regexp
))
7094 (progn (org-hide-block-toggle)
7095 t
) ;; to signal that we took action
7096 nil
))) ;; to signal that we did not
7098 (defun org-hide-block-toggle (&optional force
)
7099 "Toggle the visibility of the current block."
7103 (if (re-search-forward org-block-regexp nil t
)
7104 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7105 (end (match-end 0)) ;; end of entire body
7107 (if (memq t
(mapcar (lambda (overlay)
7108 (eq (overlay-get overlay
'invisible
)
7110 (overlays-at start
)))
7111 (if (or (not force
) (eq force
'off
))
7113 (when (member ov org-hide-block-overlays
)
7114 (setq org-hide-block-overlays
7115 (delq ov org-hide-block-overlays
)))
7116 (when (eq (overlay-get ov
'invisible
)
7118 (delete-overlay ov
)))
7119 (overlays-at start
)))
7120 (setq ov
(make-overlay start end
))
7121 (overlay-put ov
'invisible
'org-hide-block
)
7122 ;; make the block accessible to isearch
7124 ov
'isearch-open-invisible
7126 (when (member ov org-hide-block-overlays
)
7127 (setq org-hide-block-overlays
7128 (delq ov org-hide-block-overlays
)))
7129 (when (eq (overlay-get ov
'invisible
)
7131 (delete-overlay ov
))))
7132 (push ov org-hide-block-overlays
)))
7133 (error "Not looking at a source block"))))
7135 ;; org-tab-after-check-for-cycling-hook
7136 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
7137 ;; Remove overlays when changing major mode
7138 (add-hook 'org-mode-hook
7139 (lambda () (org-add-hook 'change-major-mode-hook
7140 'org-show-block-all
'append
'local
)))
7144 (defvar org-goto-window-configuration nil
)
7145 (defvar org-goto-marker nil
)
7146 (defvar org-goto-map
)
7147 (defun org-goto-map ()
7148 "Set the keymap `org-goto'."
7150 (let ((map (make-sparse-keymap)))
7151 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7152 mouse-drag-region universal-argument org-occur
))
7154 (while (setq cmd
(pop cmds
))
7155 (substitute-key-definition cmd cmd map global-map
)))
7156 (suppress-keymap map
)
7157 (org-defkey map
"\C-m" 'org-goto-ret
)
7158 (org-defkey map
[(return)] 'org-goto-ret
)
7159 (org-defkey map
[(left)] 'org-goto-left
)
7160 (org-defkey map
[(right)] 'org-goto-right
)
7161 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7162 (org-defkey map
"\C-i" 'org-cycle
)
7163 (org-defkey map
[(tab)] 'org-cycle
)
7164 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7165 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7166 (if org-goto-auto-isearch
7167 (if (fboundp 'define-key-after
)
7168 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7170 (org-defkey map "q" 'org-goto-quit)
7171 (org-defkey map "n" 'outline-next-visible-heading)
7172 (org-defkey map "p" 'outline-previous-visible-heading)
7173 (org-defkey map "f" 'outline-forward-same-level)
7174 (org-defkey map "b" 'outline-backward-same-level)
7175 (org-defkey map "u" 'outline-up-heading))
7176 (org-defkey map "/" 'org-occur)
7177 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7178 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7179 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7180 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7181 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7184 (defconst org-goto-help
7185 "Browse buffer copy, to find location or copy text.%s
7186 RET=jump to location C-g=quit and return to previous location
7187 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7189 (defvar org-goto-start-pos) ; dynamically scoped parameter
7191 (defun org-goto (&optional alternative-interface)
7192 "Look up a different location in the current file, keeping current visibility.
7194 When you want look-up or go to a different location in a
7195 document, the fastest way is often to fold the entire buffer and
7196 then dive into the tree. This method has the disadvantage, that
7197 the previous location will be folded, which may not be what you
7200 This command works around this by showing a copy of the current
7201 buffer in an indirect buffer, in overview mode. You can dive
7202 into the tree in that copy, use org-occur and incremental search
7203 to find a location. When pressing RET or `Q', the command
7204 returns to the original buffer in which the visibility is still
7205 unchanged. After RET it will also jump to the location selected
7206 in the indirect buffer and expose the headline hierarchy above.
7208 With a prefix argument, use the alternative interface: e.g. if
7209 `org-goto-interface' is 'outline use 'outline-path-completion."
7212 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7213 (org-refile-use-outline-path t)
7214 (org-refile-target-verify-function nil)
7216 (if (not alternative-interface)
7218 (if (eq org-goto-interface 'outline)
7219 'outline-path-completion
7221 (org-goto-start-pos (point))
7223 (if (eq interface 'outline)
7224 (car (org-get-location (current-buffer) org-goto-help))
7225 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7226 (org-refile-check-position pa)
7230 (org-mark-ring-push org-goto-start-pos)
7231 (goto-char selected-point)
7232 (if (or (outline-invisible-p) (org-invisible-p2))
7233 (org-show-context 'org-goto)))
7236 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7237 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7238 (defvar org-goto-local-auto-isearch-map) ; defined below
7240 (defun org-get-location (buf help)
7241 "Let the user select a location in the Org-mode buffer BUF.
7242 This function uses a recursive edit. It returns the selected position
7245 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7246 (isearch-hide-immediately nil)
7247 (isearch-search-fun-function
7248 (lambda () 'org-goto-local-search-headings))
7249 (org-goto-selected-point org-goto-exit-command))
7251 (save-window-excursion
7252 (delete-other-windows)
7253 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7254 (org-pop-to-buffer-same-window
7256 (make-indirect-buffer (current-buffer) "*org-goto*")
7257 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7258 (with-output-to-temp-buffer "*Org Help*"
7259 (princ (format help (if org-goto-auto-isearch
7260 " Just type for auto-isearch."
7261 " n/p/f/b/u to navigate, q to quit."))))
7262 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7263 (setq buffer-read-only nil)
7264 (let ((org-startup-truncated t)
7265 (org-startup-folded nil)
7266 (org-startup-align-all-tables nil))
7269 (setq buffer-read-only t)
7270 (if (and (boundp 'org-goto-start-pos)
7271 (integer-or-marker-p org-goto-start-pos))
7272 (let ((org-show-hierarchy-above t)
7273 (org-show-siblings t)
7274 (org-show-following-heading t))
7275 (goto-char org-goto-start-pos)
7276 (and (outline-invisible-p) (org-show-context)))
7277 (goto-char (point-min)))
7278 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7279 (message "Select location and press RET")
7280 (use-local-map org-goto-map)
7282 (kill-buffer "*org-goto*")
7283 (cons org-goto-selected-point org-goto-exit-command))))
7285 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7286 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7287 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7288 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7290 (defun org-goto-local-search-headings (string bound noerror)
7291 "Search and make sure that any matches are in headlines."
7293 (while (if isearch-forward
7294 (search-forward string bound noerror)
7295 (search-backward string bound noerror))
7296 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7297 (and (member :headline context)
7298 (not (member :tags context))))
7299 (throw 'return (point))))))
7301 (defun org-goto-local-auto-isearch ()
7304 (goto-char (point-min))
7305 (let ((keys (this-command-keys)))
7306 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7308 (isearch-process-search-char (string-to-char keys)))))
7310 (defun org-goto-ret (&optional arg)
7311 "Finish `org-goto' by going to the new location."
7313 (setq org-goto-selected-point (point)
7314 org-goto-exit-command 'return)
7317 (defun org-goto-left ()
7318 "Finish `org-goto' by going to the new location."
7320 (if (org-at-heading-p)
7322 (beginning-of-line 1)
7323 (setq org-goto-selected-point (point)
7324 org-goto-exit-command 'left)
7326 (error "Not on a heading")))
7328 (defun org-goto-right ()
7329 "Finish `org-goto' by going to the new location."
7331 (if (org-at-heading-p)
7333 (setq org-goto-selected-point (point)
7334 org-goto-exit-command 'right)
7336 (error "Not on a heading")))
7338 (defun org-goto-quit ()
7339 "Finish `org-goto' without cursor motion."
7341 (setq org-goto-selected-point nil)
7342 (setq org-goto-exit-command 'quit)
7345 ;;; Indirect buffer display of subtrees
7347 (defvar org-indirect-dedicated-frame nil
7348 "This is the frame being used for indirect tree display.")
7349 (defvar org-last-indirect-buffer nil)
7351 (defun org-tree-to-indirect-buffer (&optional arg)
7352 "Create indirect buffer and narrow it to current subtree.
7353 With a numerical prefix ARG, go up to this level and then take that tree.
7354 If ARG is negative, go up that many levels.
7356 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7357 indirect buffer previously made with this command, to avoid proliferation of
7358 indirect buffers. However, when you call the command with a \
7359 \\[universal-argument] prefix, or
7360 when `org-indirect-buffer-display' is `new-frame', the last buffer
7361 is kept so that you can work with several indirect buffers at the same time.
7362 If `org-indirect-buffer-display' is `dedicated-frame', the \
7363 \\[universal-argument] prefix also
7364 requests that a new frame be made for the new buffer, so that the dedicated
7365 frame is not changed."
7367 (let ((cbuf (current-buffer))
7368 (cwin (selected-window))
7370 beg end level heading ibuf)
7372 (org-back-to-heading t)
7374 (setq level (org-outline-level))
7375 (if (< arg 0) (setq arg (+ level arg)))
7376 (while (> (setq level (org-outline-level)) arg)
7377 (org-up-heading-safe)))
7379 heading (org-get-heading))
7380 (org-end-of-subtree t t)
7381 (if (org-at-heading-p) (backward-char 1))
7383 (if (and (buffer-live-p org-last-indirect-buffer)
7384 (not (eq org-indirect-buffer-display 'new-frame))
7386 (kill-buffer org-last-indirect-buffer))
7387 (setq ibuf (org-get-indirect-buffer cbuf)
7388 org-last-indirect-buffer ibuf)
7390 ((or (eq org-indirect-buffer-display 'new-frame)
7391 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7392 (select-frame (make-frame))
7393 (delete-other-windows)
7394 (org-pop-to-buffer-same-window ibuf)
7395 (org-set-frame-title heading))
7396 ((eq org-indirect-buffer-display 'dedicated-frame)
7398 (select-frame (or (and org-indirect-dedicated-frame
7399 (frame-live-p org-indirect-dedicated-frame)
7400 org-indirect-dedicated-frame)
7401 (setq org-indirect-dedicated-frame (make-frame)))))
7402 (delete-other-windows)
7403 (org-pop-to-buffer-same-window ibuf)
7404 (org-set-frame-title (concat "Indirect: " heading)))
7405 ((eq org-indirect-buffer-display 'current-window)
7406 (org-pop-to-buffer-same-window ibuf))
7407 ((eq org-indirect-buffer-display 'other-window)
7408 (pop-to-buffer ibuf))
7409 (t (error "Invalid value")))
7410 (if (featurep 'xemacs)
7411 (save-excursion (org-mode) (turn-on-font-lock)))
7412 (narrow-to-region beg end)
7415 (run-hook-with-args 'org-cycle-hook 'all)
7416 (and (window-live-p cwin) (select-window cwin))))
7418 (defun org-get-indirect-buffer (&optional buffer)
7419 (setq buffer (or buffer (current-buffer)))
7420 (let ((n 1) (base (buffer-name buffer)) bname)
7421 (while (buffer-live-p
7422 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7425 (make-indirect-buffer buffer bname 'clone)
7426 (error (make-indirect-buffer buffer bname)))))
7428 (defun org-set-frame-title (title)
7429 "Set the title of the current frame to the string TITLE."
7430 ;; FIXME: how to name a single frame in XEmacs???
7431 (unless (featurep 'xemacs)
7432 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7434 ;;;; Structure editing
7436 ;;; Inserting headlines
7438 (defun org-previous-line-empty-p (&optional next)
7439 "Is the previous line a blank line?
7440 When NEXT is non-nil, check the next line instead."
7443 (or (beginning-of-line (if next 2 0)) t)
7445 (looking-at "[ \t]*$")))))
7447 (defun org-insert-heading (&optional arg invisible-ok)
7448 "Insert a new heading or item with same depth at point.
7449 If point is in a plain list and ARG is nil, create a new list item.
7450 With one universal prefix argument, insert a heading even in lists.
7451 With two universal prefix arguments, insert the heading at the end
7452 of the parent subtree.
7454 If point is at the beginning of a headline, insert a sibling before
7455 the current headline. If point is not at the beginning, split the line
7456 and create a new headline with the text in the current line after point
7457 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7459 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7460 This is important for non-interactive uses of the command."
7463 ((or (= (buffer-size) 0)
7464 (and (not (save-excursion
7465 (and (ignore-errors (org-back-to-heading invisible-ok))
7466 (org-at-heading-p))))
7467 (or arg (not (org-in-item-p)))))
7469 (if (org-previous-line-empty-p) "" "\n")
7470 (if (org-in-src-block-p) ",* " "* "))
7471 (run-hooks 'org-insert-heading-hook))
7472 ((or arg (not (org-insert-item
7475 (looking-at org-list-full-item-re)
7476 (match-string 3)))))
7478 (when (org-buffer-narrowed-p)
7479 (setq begn (point-min) endn (point-max))
7481 (let* ((empty-line-p nil)
7482 (eops (equal arg '(16))) ; insert at end of parent subtree
7483 (org-insert-heading-respect-content
7484 (or (not (null arg)) org-insert-heading-respect-content))
7486 (on-heading (org-at-heading-p))
7487 (head (save-excursion
7490 (org-back-to-heading invisible-ok)
7491 (when (and (not on-heading)
7492 (featurep 'org-inlinetask)
7493 (integerp org-inlinetask-min-level)
7494 (>= (length (match-string 0))
7495 org-inlinetask-min-level))
7496 ;; Find a heading level before the inline task
7497 (while (and (setq level (org-up-heading-safe))
7498 (>= level org-inlinetask-min-level)))
7499 (if (org-at-heading-p)
7500 (org-back-to-heading invisible-ok)
7501 (error "This should not happen")))
7502 (unless (and (save-excursion
7504 (org-backward-heading-same-level 1 invisible-ok))
7505 (= (point) (match-beginning 0)))
7506 (not (org-previous-line-empty-p t)))
7507 (setq empty-line-p (org-previous-line-empty-p)))
7510 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7511 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7512 pos hide-previous previous-pos)
7513 (if ;; At the beginning of a heading, open a new line for insertiong
7514 (and (bolp) (org-at-heading-p)
7517 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7518 (open-line (if blank 2 1))
7520 (setq previous-pos (point-at-bol))
7522 (setq hide-previous (outline-invisible-p)))
7523 (and org-insert-heading-respect-content
7525 (while (outline-invisible-p)
7527 (org-up-heading-safe))))
7529 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7532 (goto-char (point-at-bol))
7533 (and (looking-at org-complex-heading-regexp)
7535 (> p (match-beginning 4)))))))
7538 ;; Insert a new line, possibly at end of parent subtree
7539 (org-insert-heading-respect-content
7542 (org-end-of-subtree nil t)
7543 (and (looking-at "^\\*") (backward-char 1))
7544 (while (and (not (bobp))
7545 ;; Don't delete spaces in empty headlines
7546 (not (looking-back org-outline-regexp))
7547 (member (char-before) '(?\ ?\t ?\n)))
7548 (backward-delete-char 1)))
7550 (org-up-heading-safe)
7552 (goto-char (point-max))
7553 (org-end-of-subtree nil t))))
7554 (when (featurep 'org-inlinetask)
7555 (while (and (not (eobp))
7556 (looking-at "\\(\\*+\\)[ \t]+")
7557 (>= (length (match-string 1))
7558 org-inlinetask-min-level))
7559 (org-end-of-subtree nil t)))
7560 (or (bolp) (newline))
7561 (or (org-previous-line-empty-p)
7562 (and blank (newline)))
7563 (if (or empty-line-p eops) (open-line 1)))
7564 ;; Insert a headling containing text after point
7569 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7570 (setq tags (and (match-end 2) (match-string 2)))
7572 (delete-region (match-beginning 1) (match-end 1)))
7573 (setq pos (point-at-bol))
7574 (or split (end-of-line 1))
7575 (delete-horizontal-space)
7576 (if (string-match "\\`\\*+\\'"
7577 (buffer-substring (point-at-bol) (point)))
7579 (newline (if blank 2 1))
7585 (org-set-tags nil 'align))))
7587 (or split (end-of-line 1))
7588 (newline (if blank 2 1))))))
7589 (insert head) (just-one-space)
7592 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7593 (when (and org-insert-heading-respect-content hide-previous)
7595 (goto-char previous-pos)
7597 (when (and begn endn)
7598 (narrow-to-region (min (point) begn) (max (point) endn)))
7599 (run-hooks 'org-insert-heading-hook))))))
7601 (defun org-get-heading (&optional no-tags no-todo)
7602 "Return the heading of the current entry, without the stars.
7603 When NO-TAGS is non-nil, don't include tags.
7604 When NO-TODO is non-nil, don't include TODO keywords."
7606 (org-back-to-heading t)
7608 ((and no-tags no-todo)
7609 (looking-at org-complex-heading-regexp)
7612 (looking-at (concat org-outline-regexp
7614 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7617 (looking-at org-todo-line-regexp)
7619 (t (looking-at org-heading-regexp)
7620 (match-string 2)))))
7622 (defvar orgstruct-mode) ; defined below
7624 (defun org-heading-components ()
7625 "Return the components of the current heading.
7626 This is a list with the following elements:
7627 - the level as an integer
7628 - the reduced level, different if `org-odd-levels-only' is set.
7629 - the TODO keyword, or nil
7630 - the priority character, like ?A, or nil if no priority is given
7631 - the headline text itself, or the tags string if no headline text
7632 - the tags string, or nil."
7634 (org-back-to-heading t)
7635 (if (let (case-fold-search)
7639 org-complex-heading-regexp)))
7641 (list (length (match-string 1))
7642 (org-reduced-level (length (match-string 1)))
7647 (list (length (match-string 1))
7648 (org-reduced-level (length (match-string 1)))
7649 (org-match-string-no-properties 2)
7650 (and (match-end 3) (aref (match-string 3) 2))
7651 (org-match-string-no-properties 4)
7652 (org-match-string-no-properties 5))))))
7654 (defun org-get-entry ()
7655 "Get the entry text, after heading, entire subtree."
7657 (org-back-to-heading t)
7658 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7660 (defun org-insert-heading-after-current ()
7661 "Insert a new heading with same level as current, after current subtree."
7663 (org-back-to-heading)
7664 (org-insert-heading)
7665 (org-move-subtree-down)
7668 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7669 "Insert heading with `org-insert-heading-respect-content' set to t."
7671 (let ((org-insert-heading-respect-content t))
7672 (org-insert-heading arg invisible-ok)))
7674 (defun org-insert-todo-heading-respect-content (&optional force-state)
7675 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7677 (let ((org-insert-heading-respect-content t))
7678 (org-insert-todo-heading force-state t)))
7680 (defun org-insert-todo-heading (arg &optional force-heading)
7681 "Insert a new heading with the same level and TODO state as current heading.
7682 If the heading has no TODO state, or if the state is DONE, use the first
7683 state (TODO by default). Also one prefix arg, force first state. With two
7684 prefix args, force inserting at the end of the parent subtree."
7686 (when (or force-heading (not (org-insert-item 'checkbox)))
7687 (org-insert-heading (or (and (equal arg '(16)) '(16))
7690 (org-back-to-heading)
7691 (outline-previous-heading)
7692 (looking-at org-todo-line-regexp))
7696 (not (match-beginning 2))
7697 (member (match-string 2) org-done-keywords))
7698 (car org-todo-keywords-1)
7702 (run-hook-with-args-until-success
7703 'org-todo-get-default-hook new-mark-x nil)
7705 (beginning-of-line 1)
7706 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7707 (if org-treat-insert-todo-heading-as-state-change
7709 (insert new-mark " "))))
7710 (when org-provide-todo-statistics
7711 (org-update-parent-todo-statistics))))
7713 (defun org-insert-subheading (arg)
7714 "Insert a new subheading and demote it.
7715 Works for outline headings and for plain lists alike."
7717 (org-insert-heading arg)
7719 ((org-at-heading-p) (org-do-demote))
7720 ((org-at-item-p) (org-indent-item))))
7722 (defun org-insert-todo-subheading (arg)
7723 "Insert a new subheading with TODO keyword or checkbox and demote it.
7724 Works for outline headings and for plain lists alike."
7726 (org-insert-todo-heading arg)
7728 ((org-at-heading-p) (org-do-demote))
7729 ((org-at-item-p) (org-indent-item))))
7731 ;;; Promotion and Demotion
7733 (defvar org-after-demote-entry-hook nil
7734 "Hook run after an entry has been demoted.
7735 The cursor will be at the beginning of the entry.
7736 When a subtree is being demoted, the hook will be called for each node.")
7738 (defvar org-after-promote-entry-hook nil
7739 "Hook run after an entry has been promoted.
7740 The cursor will be at the beginning of the entry.
7741 When a subtree is being promoted, the hook will be called for each node.")
7743 (defun org-promote-subtree ()
7744 "Promote the entire subtree.
7745 See also `org-promote'."
7748 (org-with-limited-levels (org-map-tree 'org-promote)))
7749 (org-fix-position-after-promote))
7751 (defun org-demote-subtree ()
7752 "Demote the entire subtree. See `org-demote'.
7753 See also `org-promote'."
7756 (org-with-limited-levels (org-map-tree 'org-demote)))
7757 (org-fix-position-after-promote))
7760 (defun org-do-promote ()
7761 "Promote the current heading higher up the tree.
7762 If the region is active in `transient-mark-mode', promote all headings
7766 (if (org-region-active-p)
7767 (org-map-region 'org-promote (region-beginning) (region-end))
7769 (org-fix-position-after-promote))
7771 (defun org-do-demote ()
7772 "Demote the current heading lower down the tree.
7773 If the region is active in `transient-mark-mode', demote all headings
7777 (if (org-region-active-p)
7778 (org-map-region 'org-demote (region-beginning) (region-end))
7780 (org-fix-position-after-promote))
7782 (defun org-fix-position-after-promote ()
7783 "Make sure that after pro/demotion cursor position is right."
7784 (let ((pos (point)))
7785 (when (save-excursion
7786 (beginning-of-line 1)
7787 (looking-at org-todo-line-regexp)
7788 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7789 (cond ((eobp) (insert " "))
7790 ((eolp) (insert " "))
7791 ((equal (char-after) ?\ ) (forward-char 1))))))
7793 (defun org-current-level ()
7794 "Return the level of the current entry, or nil if before the first headline.
7795 The level is the number of stars at the beginning of the headline."
7797 (org-with-limited-levels
7798 (if (ignore-errors (org-back-to-heading t))
7799 (funcall outline-level)))))
7801 (defun org-get-previous-line-level ()
7802 "Return the outline depth of the last headline before the current line.
7803 Returns 0 for the first headline in the buffer, and nil if before the
7805 (let ((current-level (org-current-level))
7806 (prev-level (when (> (line-number-at-pos) 1)
7808 (beginning-of-line 0)
7809 (org-current-level)))))
7810 (cond ((null current-level) nil) ; Before first headline
7811 ((null prev-level) 0) ; At first headline
7814 (defun org-reduced-level (l)
7815 "Compute the effective level of a heading.
7816 This takes into account the setting of `org-odd-levels-only'."
7819 (org-odd-levels-only (1+ (floor (/ l 2))))
7822 (defun org-level-increment ()
7823 "Return the number of stars that will be added or removed at a
7824 time to headlines when structure editing, based on the value of
7825 `org-odd-levels-only'."
7826 (if org-odd-levels-only 2 1))
7828 (defun org-get-valid-level (level &optional change)
7829 "Rectify a level change under the influence of `org-odd-levels-only'
7830 LEVEL is a current level, CHANGE is by how much the level should be
7831 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7832 even level numbers will become the next higher odd number."
7833 (if org-odd-levels-only
7834 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7835 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7836 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7837 (max 1 (+ level (or change 0)))))
7839 (if (boundp 'define-obsolete-function-alias)
7840 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7841 (define-obsolete-function-alias 'org-get-legal-level
7842 'org-get-valid-level)
7843 (define-obsolete-function-alias 'org-get-legal-level
7844 'org-get-valid-level "23.1")))
7846 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7847 ;; ̀org-with-limited-levels'
7848 (defun org-promote ()
7849 "Promote the current heading higher up the tree.
7850 If the region is active in `transient-mark-mode', promote all headings
7852 (org-back-to-heading t)
7853 (let* ((level (save-match-data (funcall outline-level)))
7854 (after-change-functions (remove 'flyspell-after-change-function
7855 after-change-functions))
7856 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7857 (diff (abs (- level (length up-head) -1))))
7858 (cond ((and (= level 1) org-called-with-limited-levels
7859 org-allow-promoting-top-level-subtree)
7860 (replace-match "# " nil t))
7862 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7863 (t (replace-match up-head nil t)))
7864 ;; Fixup tag positioning
7866 (and org-auto-align-tags (org-set-tags nil t))
7867 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7868 (run-hooks 'org-after-promote-entry-hook)))
7870 (defun org-demote ()
7871 "Demote the current heading lower down the tree.
7872 If the region is active in `transient-mark-mode', demote all headings
7874 (org-back-to-heading t)
7875 (let* ((level (save-match-data (funcall outline-level)))
7876 (after-change-functions (remove 'flyspell-after-change-function
7877 after-change-functions))
7878 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7879 (diff (abs (- level (length down-head) -1))))
7880 (replace-match down-head nil t)
7881 ;; Fixup tag positioning
7882 (and org-auto-align-tags (org-set-tags nil t))
7883 (if org-adapt-indentation (org-fixup-indentation diff))
7884 (run-hooks 'org-after-demote-entry-hook)))
7886 (defun org-cycle-level ()
7887 "Cycle the level of an empty headline through possible states.
7888 This goes first to child, then to parent, level, then up the hierarchy.
7889 After top level, it switches back to sibling level."
7891 (let ((org-adapt-indentation nil))
7892 (when (org-point-at-end-of-empty-headline)
7893 (setq this-command 'org-cycle-level) ; Only needed for caching
7894 (let ((cur-level (org-current-level))
7895 (prev-level (org-get-previous-line-level)))
7897 ;; If first headline in file, promote to top-level.
7899 (loop repeat (/ (- cur-level 1) (org-level-increment))
7900 do (org-do-promote)))
7901 ;; If same level as prev, demote one.
7902 ((= prev-level cur-level)
7904 ;; If parent is top-level, promote to top level if not already.
7906 (loop repeat (/ (- cur-level 1) (org-level-increment))
7907 do (org-do-promote)))
7908 ;; If top-level, return to prev-level.
7910 (loop repeat (/ (- prev-level 1) (org-level-increment))
7911 do (org-do-demote)))
7912 ;; If less than prev-level, promote one.
7913 ((< cur-level prev-level)
7915 ;; If deeper than prev-level, promote until higher than
7917 ((> cur-level prev-level)
7918 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7919 do (org-do-promote))))
7922 (defun org-map-tree (fun)
7923 "Call FUN for every heading underneath the current one."
7924 (org-back-to-heading)
7925 (let ((level (funcall outline-level)))
7929 (outline-next-heading)
7930 (> (funcall outline-level) level))
7934 (defun org-map-region (fun beg end)
7935 "Call FUN for every heading between BEG and END."
7936 (let ((org-ignore-region t))
7938 (setq end (copy-marker end))
7940 (if (and (re-search-forward org-outline-regexp-bol nil t)
7944 (outline-next-heading)
7949 (defvar org-property-end-re) ; silence byte-compiler
7950 (defun org-fixup-indentation (diff)
7951 "Change the indentation in the current entry by DIFF.
7952 However, if any line in the current entry has no indentation, or if it
7953 would end up with no indentation after the change, nothing at all is done."
7955 (let ((end (save-excursion (outline-next-heading)
7957 (prohibit (if (> diff 0)
7959 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7961 (unless (save-excursion (end-of-line 1)
7962 (re-search-forward prohibit end t))
7963 (while (and (< (point) end)
7964 (re-search-forward "^[ \t]+" end t))
7965 (goto-char (match-end 0))
7966 (setq col (current-column))
7967 (if (< diff 0) (replace-match ""))
7968 (org-indent-to-column (+ diff col))))
7969 (move-marker end nil))))
7971 (defun org-convert-to-odd-levels ()
7972 "Convert an org-mode file with all levels allowed to one with odd levels.
7973 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7976 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7977 (let ((outline-level 'org-outline-level)
7978 (org-odd-levels-only nil) n)
7980 (goto-char (point-min))
7981 (while (re-search-forward "^\\*\\*+ " nil t)
7982 (setq n (- (length (match-string 0)) 2))
7983 (while (>= (setq n (1- n)) 0)
7985 (end-of-line 1))))))
7987 (defun org-convert-to-oddeven-levels ()
7988 "Convert an org-mode file with only odd levels to one with odd/even levels.
7989 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7990 file contains a section with an even level, conversion would
7991 destroy the structure of the file. An error is signaled in this
7994 (goto-char (point-min))
7995 ;; First check if there are no even levels
7996 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7997 (org-show-context t)
7998 (error "Not all levels are odd in this file. Conversion not possible"))
7999 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8000 (let ((outline-regexp org-outline-regexp)
8001 (outline-level 'org-outline-level)
8002 (org-odd-levels-only nil) n)
8004 (goto-char (point-min))
8005 (while (re-search-forward "^\\*\\*+ " nil t)
8006 (setq n (/ (1- (length (match-string 0))) 2))
8007 (while (>= (setq n (1- n)) 0)
8009 (end-of-line 1))))))
8011 (defun org-tr-level (n)
8012 "Make N odd if required."
8013 (if org-odd-levels-only (1+ (/ n 2)) n))
8015 ;;; Vertical tree motion, cutting and pasting of subtrees
8017 (defun org-move-subtree-up (&optional arg)
8018 "Move the current subtree up past ARG headlines of the same level."
8020 (org-move-subtree-down (- (prefix-numeric-value arg))))
8022 (defun org-move-subtree-down (&optional arg)
8023 "Move the current subtree down past ARG headlines of the same level."
8025 (setq arg (prefix-numeric-value arg))
8026 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8027 'org-get-last-sibling))
8028 (ins-point (make-marker))
8030 (col (current-column))
8031 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8033 (org-back-to-heading)
8036 (setq ne-beg (org-back-over-empty-lines))
8039 (save-excursion (outline-end-of-heading)
8040 (setq folded (outline-invisible-p)))
8041 (outline-end-of-subtree))
8042 (outline-next-heading)
8043 (setq ne-end (org-back-over-empty-lines))
8046 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8047 ;; include less whitespace
8050 (forward-line (- ne-beg ne-end))
8051 (setq beg (point))))
8052 ;; Find insertion point, with error handling
8054 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8055 (progn (goto-char beg0)
8056 (user-error "Cannot move past superior level or buffer limit")))
8057 (setq cnt (1- cnt)))
8059 ;; Moving forward - still need to move over subtree
8060 (progn (org-end-of-subtree t t)
8062 (org-back-over-empty-lines)
8063 (or (bolp) (newline)))))
8064 (setq ne-ins (org-back-over-empty-lines))
8065 (move-marker ins-point (point))
8066 (setq txt (buffer-substring beg end))
8067 (org-save-markers-in-region beg end)
8068 (delete-region beg end)
8069 (org-remove-empty-overlays-at beg)
8070 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8071 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8072 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8073 (let ((bbb (point)))
8074 (insert-before-markers txt)
8075 (org-reinstall-markers-in-region bbb)
8076 (move-marker ins-point bbb))
8077 (or (bolp) (insert "\n"))
8078 (setq ins-end (point))
8079 (goto-char ins-point)
8080 (org-skip-whitespace)
8081 (when (and (< arg 0)
8082 (org-first-sibling-p)
8084 ;; Move whitespace back to beginning
8087 (let ((kill-whole-line t))
8088 (kill-line (- ne-ins ne-beg)) (point)))
8089 (insert (make-string (- ne-ins ne-beg) ?\n)))
8090 (move-marker ins-point nil)
8095 (org-cycle-hide-drawers 'children))
8096 (org-clean-visibility-after-subtree-move)
8097 ;; move back to the initial column we were at
8098 (move-to-column col)))
8100 (defvar org-subtree-clip ""
8101 "Clipboard for cut and paste of subtrees.
8102 This is actually only a copy of the kill, because we use the normal kill
8103 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8105 (defvar org-subtree-clip-folded nil
8106 "Was the last copied subtree folded?
8107 This is used to fold the tree back after pasting.")
8109 (defun org-cut-subtree (&optional n)
8110 "Cut the current subtree into the clipboard.
8111 With prefix arg N, cut this many sequential subtrees.
8112 This is a short-hand for marking the subtree and then cutting it."
8114 (org-copy-subtree n 'cut))
8116 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8117 "Cut the current subtree into the clipboard.
8118 With prefix arg N, cut this many sequential subtrees.
8119 This is a short-hand for marking the subtree and then copying it.
8120 If CUT is non-nil, actually cut the subtree.
8121 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8122 of some markers in the region, even if CUT is non-nil. This is
8123 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8125 (let (beg end folded (beg0 (point)))
8126 (if (org-called-interactively-p 'any)
8127 (org-back-to-heading nil) ; take what looks like a subtree
8128 (org-back-to-heading t)) ; take what is really there
8130 (skip-chars-forward " \t\r\n")
8133 (outline-next-heading)
8134 (save-excursion (outline-end-of-heading)
8135 (setq folded (outline-invisible-p)))
8137 (org-forward-heading-same-level (1- n) t)
8139 (org-end-of-subtree t t)))
8143 (setq org-subtree-clip-folded folded)
8144 (when (or cut force-store-markers)
8145 (org-save-markers-in-region beg end))
8146 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8147 (setq org-subtree-clip (current-kill 0))
8148 (message "%s: Subtree(s) with %d characters"
8149 (if cut "Cut" "Copied")
8150 (length org-subtree-clip)))))
8152 (defun org-paste-subtree (&optional level tree for-yank)
8153 "Paste the clipboard as a subtree, with modification of headline level.
8154 The entire subtree is promoted or demoted in order to match a new headline
8157 If the cursor is at the beginning of a headline, the same level as
8158 that headline is used to paste the tree.
8160 If not, the new level is derived from the *visible* headings
8161 before and after the insertion point, and taken to be the inferior headline
8162 level of the two. So if the previous visible heading is level 3 and the
8163 next is level 4 (or vice versa), level 4 will be used for insertion.
8164 This makes sure that the subtree remains an independent subtree and does
8165 not swallow low level entries.
8167 You can also force a different level, either by using a numeric prefix
8168 argument, or by inserting the heading marker by hand. For example, if the
8169 cursor is after \"*****\", then the tree will be shifted to level 5.
8171 If optional TREE is given, use this text instead of the kill ring.
8173 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8174 move back over whitespace before inserting, and move point to the end of
8175 the inserted text when done."
8177 (setq tree (or tree (and kill-ring (current-kill 0))))
8178 (unless (org-kill-is-subtree-p tree)
8180 (substitute-command-keys
8181 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8182 (org-with-limited-levels
8183 (let* ((visp (not (outline-invisible-p)))
8185 (^re_ "\\(\\*+\\)[ \t]*")
8186 (old-level (if (string-match org-outline-regexp-bol txt)
8187 (- (match-end 0) (match-beginning 0) 1)
8189 (force-level (cond (level (prefix-numeric-value level))
8190 ((and (looking-at "[ \t]*$")
8192 "^\\*+$" (buffer-substring
8193 (point-at-bol) (point))))
8194 (- (match-end 1) (match-beginning 1)))
8196 (looking-at org-outline-regexp))
8197 (- (match-end 0) (point) 1))))
8198 (previous-level (save-excursion
8201 (outline-previous-visible-heading 1)
8202 (if (looking-at ^re_)
8203 (- (match-end 0) (match-beginning 0) 1)
8206 (next-level (save-excursion
8209 (or (looking-at org-outline-regexp)
8210 (outline-next-visible-heading 1))
8211 (if (looking-at ^re_)
8212 (- (match-end 0) (match-beginning 0) 1)
8215 (new-level (or force-level (max previous-level next-level)))
8216 (shift (if (or (= old-level -1)
8218 (= old-level new-level))
8220 (- new-level old-level)))
8221 (delta (if (> shift 0) -1 1))
8222 (func (if (> shift 0) 'org-demote 'org-promote))
8223 (org-odd-levels-only nil)
8225 ;; Remove the forced level indicator
8227 (delete-region (point-at-bol) (point)))
8229 (beginning-of-line (if (bolp) 1 2))
8231 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8232 (insert-before-markers txt)
8233 (unless (string-match "\n\\'" txt) (insert "\n"))
8234 (setq newend (point))
8235 (org-reinstall-markers-in-region beg)
8238 (skip-chars-forward " \t\n\r")
8240 (if (and (outline-invisible-p) visp)
8241 (save-excursion (outline-show-heading)))
8242 ;; Shift if necessary
8245 (narrow-to-region beg end)
8246 (while (not (= shift 0))
8247 (org-map-region func (point-min) (point-max))
8248 (setq shift (+ delta shift)))
8249 (goto-char (point-min))
8250 (setq newend (point-max))))
8251 (when (or (org-called-interactively-p 'interactive) for-yank)
8252 (message "Clipboard pasted as level %d subtree" new-level))
8253 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8255 (eq org-subtree-clip (current-kill 0))
8256 org-subtree-clip-folded)
8257 ;; The tree was folded before it was killed/copied
8259 (and for-yank (goto-char newend)))))
8261 (defun org-kill-is-subtree-p (&optional txt)
8262 "Check if the current kill is an outline subtree, or a set of trees.
8263 Returns nil if kill does not start with a headline, or if the first
8264 headline level is not the largest headline level in the tree.
8265 So this will actually accept several entries of equal levels as well,
8266 which is OK for `org-paste-subtree'.
8267 If optional TXT is given, check this string instead of the current kill."
8268 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8269 (re (org-get-limited-outline-regexp))
8270 (^re (concat "^" re))
8271 (start-level (and kill
8273 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8275 (- (match-end 2) (match-beginning 2) 1)))
8276 (start (1+ (or (match-beginning 2) -1))))
8277 (if (not start-level)
8279 nil) ;; does not even start with a heading
8281 (while (setq start (string-match ^re kill (1+ start)))
8282 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8286 (defvar org-markers-to-move nil
8287 "Markers that should be moved with a cut-and-paste operation.
8288 Those markers are stored together with their positions relative to
8289 the start of the region.")
8291 (defun org-save-markers-in-region (beg end)
8292 "Check markers in region.
8293 If these markers are between BEG and END, record their position relative
8294 to BEG, so that after moving the block of text, we can put the markers back
8296 This function gets called just before an entry or tree gets cut from the
8297 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8298 called immediately, to move the markers with the entries."
8299 (setq org-markers-to-move nil)
8300 (when (featurep 'org-clock)
8301 (org-clock-save-markers-for-cut-and-paste beg end))
8302 (when (featurep 'org-agenda)
8303 (org-agenda-save-markers-for-cut-and-paste beg end)))
8305 (defun org-check-and-save-marker (marker beg end)
8306 "Check if MARKER is between BEG and END.
8307 If yes, remember the marker and the distance to BEG."
8308 (when (and (marker-buffer marker)
8309 (equal (marker-buffer marker) (current-buffer)))
8310 (if (and (>= marker beg) (< marker end))
8311 (push (cons marker (- marker beg)) org-markers-to-move))))
8313 (defun org-reinstall-markers-in-region (beg)
8314 "Move all remembered markers to their position relative to BEG."
8316 (move-marker (car x) (+ beg (cdr x))))
8317 org-markers-to-move)
8318 (setq org-markers-to-move nil))
8320 (defun org-narrow-to-subtree ()
8321 "Narrow buffer to the current subtree."
8325 (org-with-limited-levels
8327 (progn (org-back-to-heading t) (point))
8328 (progn (org-end-of-subtree t t)
8329 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8332 (defun org-narrow-to-block ()
8333 "Narrow buffer to the current block."
8335 (let* ((case-fold-search t)
8336 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8337 "^[ \t]*#\\+end_.*")))
8339 (narrow-to-region (car blockp) (cdr blockp))
8340 (error "Not in a block"))))
8343 (defvar org-property-drawer-re))
8345 (defvar org-property-start-re) ;; defined below
8346 (defun org-clone-subtree-with-time-shift (n &optional shift)
8347 "Clone the task (subtree) at point N times.
8348 The clones will be inserted as siblings.
8350 In interactive use, the user will be prompted for the number of
8351 clones to be produced. When called with a universal prefix argument
8352 and if the entry has a timestamp, the user will also be prompted for
8353 a time shift, which may be a repeater as used in time stamps, for
8356 When a valid repeater is given and the entry contains any time
8357 stamps, the clones will become a sequence in time, with time
8358 stamps in the subtree shifted for each clone produced. If SHIFT
8359 is nil or the empty string, time stamps will be left alone. The
8360 ID property of the original subtree is removed.
8362 If the original subtree did contain time stamps with a repeater,
8363 the following will happen:
8364 - the repeater will be removed in each clone
8365 - an additional clone will be produced, with the current, unshifted
8366 date(s) in the entry.
8367 - the original entry will be placed *after* all the clones, with
8369 - the start days in the repeater in the original entry will be shifted
8370 to past the last clone.
8371 In this way you can spell out a number of instances of a repeating task,
8372 and still retain the repeater to cover future instances of the task."
8373 (interactive "nNumber of clones to produce: ")
8376 (if (and (equal current-prefix-arg '(4))
8378 (re-search-forward org-ts-regexp-both
8380 (org-end-of-subtree t)
8382 (read-from-minibuffer
8383 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8384 ""))) ;; No time shift
8386 (drawer-re org-drawer-regexp)
8387 beg end template task idprop
8388 shift-n shift-what doshift nmin nmax)
8389 (if (not (and (integerp n) (> n 0)))
8390 (error "Invalid number of replications %s" n))
8391 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8392 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8394 (error "Invalid shift specification %s" shift))
8396 (setq shift-n (string-to-number (match-string 1 shift))
8397 shift-what (cdr (assoc (match-string 2 shift)
8398 '(("d" . day) ("w" . week)
8399 ("m" . month) ("y" . year))))))
8400 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8401 (setq nmin 1 nmax n)
8402 (org-back-to-heading t)
8404 (setq idprop (org-entry-get nil "ID"))
8405 (org-end-of-subtree t t)
8406 (or (bolp) (insert "\n"))
8408 (setq template (buffer-substring beg end))
8410 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8411 (delete-region beg end)
8413 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8415 (loop for n from nmin to nmax do
8420 (goto-char (point-min))
8422 (and idprop (if org-clone-delete-id
8423 (org-entry-delete nil "ID")
8424 (org-id-get-create t)))
8426 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8428 (goto-char (point-min))
8429 (while (re-search-forward drawer-re nil t)
8431 (org-remove-empty-drawer-at d (point))) org-drawers)))
8432 (goto-char (point-min))
8434 (while (re-search-forward org-ts-regexp-both nil t)
8435 (org-timestamp-change (* n shift-n) shift-what))
8436 (unless (= n n-no-remove)
8437 (goto-char (point-min))
8438 (while (re-search-forward org-ts-regexp nil t)
8440 (goto-char (match-beginning 0))
8441 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8442 (delete-region (match-beginning 1) (match-end 1)))))))
8443 (setq task (buffer-string)))
8449 (defun org-sort (with-case)
8450 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8451 Optional argument WITH-CASE means sort case-sensitively."
8454 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8455 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8457 (org-call-with-arg 'org-sort-entries with-case))))
8459 (defun org-sort-remove-invisible (s)
8460 "Remove invisible links from string S."
8461 (remove-text-properties 0 (length s) org-rm-props s)
8462 (while (string-match org-bracket-link-regexp s)
8463 (setq s (replace-match (if (match-end 2)
8465 (match-string 1 s)) t t s)))
8466 (let ((st (format " %s " s)))
8467 (while (string-match org-emph-re st)
8468 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8469 (setq s (substring st 1 -1)))
8472 (defvar org-priority-regexp) ; defined later in the file
8474 (defvar org-after-sorting-entries-or-items-hook nil
8475 "Hook that is run after a bunch of entries or items have been sorted.
8476 When children are sorted, the cursor is in the parent line when this
8477 hook gets called. When a region or a plain list is sorted, the cursor
8478 will be in the first entry of the sorted region/list.")
8480 (defun org-sort-entries
8481 (&optional with-case sorting-type getkey-func compare-func property)
8482 "Sort entries on a certain level of an outline tree.
8483 If there is an active region, the entries in the region are sorted.
8484 Else, if the cursor is before the first entry, sort the top-level items.
8485 Else, the children of the entry at point are sorted.
8487 Sorting can be alphabetically, numerically, by date/time as given by
8488 a time stamp, by a property, by priority order, or by a custom function.
8490 The command prompts for the sorting type unless it has been given to the
8491 function through the SORTING-TYPE argument, which needs to be a character,
8492 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8493 precise meaning of each character:
8495 n Numerically, by converting the beginning of the entry/item to a number.
8496 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8497 o By order of TODO keywords.
8498 t By date/time, either the first active time stamp in the entry, or, if
8499 none exist, by the first inactive one.
8500 s By the scheduled date/time.
8501 d By deadline date/time.
8502 c By creation time, which is assumed to be the first inactive time stamp
8503 at the beginning of a line.
8504 p By priority according to the cookie.
8505 r By the value of a property.
8507 Capital letters will reverse the sort order.
8509 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8510 called with point at the beginning of the record. It must return either
8511 a string or a number that should serve as the sorting key for that record.
8513 Comparing entries ignores case by default. However, with an optional argument
8514 WITH-CASE, the sorting considers case as well.
8516 Sorting is done against the visible part of the headlines, it ignores hidden
8519 (let ((case-func (if with-case 'identity 'downcase))
8521 ;; The clock marker is lost when using `sort-subr', let's
8522 ;; store the clocking string.
8523 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8525 (goto-char org-clock-marker)
8526 (looking-back "^.*") (match-string-no-properties 0))))
8527 start beg end stars re re2
8529 ;; Find beginning and end of region to sort
8531 ((org-region-active-p)
8532 ;; we will sort the region
8533 (setq end (region-end)
8535 (goto-char (region-beginning))
8536 (if (not (org-at-heading-p)) (outline-next-heading))
8537 (setq start (point)))
8538 ((or (org-at-heading-p)
8539 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8540 ;; we will sort the children of the current headline
8541 (org-back-to-heading)
8543 end (progn (org-end-of-subtree t t)
8544 (or (bolp) (insert "\n"))
8545 (org-back-over-empty-lines)
8550 (outline-next-heading))
8552 ;; we will sort the top-level entries in this file
8553 (goto-char (point-min))
8554 (or (org-at-heading-p) (outline-next-heading))
8555 (setq start (point))
8556 (goto-char (point-max))
8557 (beginning-of-line 1)
8558 (when (looking-at ".*?\\S-")
8559 ;; File ends in a non-white line
8562 (setq end (point-max))
8563 (setq what "top-level")
8568 (if (>= beg end) (error "Nothing to sort"))
8570 (looking-at "\\(\\*+\\)")
8571 (setq stars (match-string 1)
8572 re (concat "^" (regexp-quote stars) " +")
8573 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8574 txt (buffer-substring beg end))
8575 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8576 (if (and (not (equal stars "*")) (string-match re2 txt))
8577 (error "Region to sort contains a level above the first entry"))
8579 (unless sorting-type
8581 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8582 [t]ime
[s]cheduled [d]eadline [c]reated
8583 A/N/P/R/O/F/T/S/D/C means reversed:"
8585 (setq sorting-type (read-char-exclusive))
8588 (and (= (downcase sorting-type) ?f)
8590 (org-icompleting-read "Sort using function: "
8591 obarray 'fboundp t nil nil))
8592 (setq getkey-func (intern getkey-func))))
8594 (and (= (downcase sorting-type) ?r)
8597 (org-icompleting-read "Property: "
8598 (mapcar 'list (org-buffer-property-keys t))
8601 (message "Sorting entries...")
8604 (narrow-to-region start end)
8605 (let ((dcst (downcase sorting-type))
8606 (case-fold-search nil)
8607 (now (current-time)))
8609 (/= dcst sorting-type)
8610 ;; This function moves to the beginning character of the "record" to
8613 (if (re-search-forward re nil t)
8614 (goto-char (match-beginning 0))
8615 (goto-char (point-max))))
8616 ;; This function moves to the last character of the "record" being
8621 (outline-forward-same-level 1)
8623 (goto-char (point-max))))))
8624 ;; This function returns the value that gets sorted against.
8628 (if (looking-at org-complex-heading-regexp)
8629 (string-to-number (org-sort-remove-invisible (match-string 4)))
8632 (if (looking-at org-complex-heading-regexp)
8633 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8636 (let ((end (save-excursion (outline-next-heading) (point))))
8637 (if (or (re-search-forward org-ts-regexp end t)
8638 (re-search-forward org-ts-regexp-both end t))
8639 (org-time-string-to-seconds (match-string 0))
8640 (org-float-time now))))
8642 (let ((end (save-excursion (outline-next-heading) (point))))
8643 (if (re-search-forward
8644 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8646 (org-time-string-to-seconds (match-string 0))
8647 (org-float-time now))))
8649 (let ((end (save-excursion (outline-next-heading) (point))))
8650 (if (re-search-forward org-scheduled-time-regexp end t)
8651 (org-time-string-to-seconds (match-string 1))
8652 (org-float-time now))))
8654 (let ((end (save-excursion (outline-next-heading) (point))))
8655 (if (re-search-forward org-deadline-time-regexp end t)
8656 (org-time-string-to-seconds (match-string 1))
8657 (org-float-time now))))
8659 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8660 (string-to-char (match-string 2))
8661 org-default-priority))
8663 (or (org-entry-get nil property) ""))
8665 (if (looking-at org-complex-heading-regexp)
8666 (- 9999 (length (member (match-string 2)
8667 org-todo-keywords-1)))))
8671 (setq tmp (funcall getkey-func))
8672 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8674 (error "Invalid key function `%s'" getkey-func)))
8675 (t (error "Invalid sorting type `%c'" sorting-type))))
8678 ((= dcst ?a) 'string<)
8679 ((= dcst ?f) compare-func)
8680 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8681 (run-hooks 'org-after-sorting-entries-or-items-hook)
8682 ;; Reset the clock marker if needed
8686 (search-forward cmstr nil t)
8687 (move-marker org-clock-marker (point))))
8688 (message "Sorting entries...done")))
8690 (defun org-do-sort (table what &optional with-case sorting-type)
8691 "Sort TABLE of WHAT according to SORTING-TYPE.
8692 The user will be prompted for the SORTING-TYPE if the call to this
8693 function does not specify it. WHAT is only for the prompt, to indicate
8694 what is being sorted. The sorting key will be extracted from
8695 the car of the elements of the table.
8696 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8697 (unless sorting-type
8699 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8701 (setq sorting-type (read-char-exclusive)))
8702 (let ((dcst (downcase sorting-type))
8703 extractfun comparefun)
8704 ;; Define the appropriate functions
8707 (setq extractfun 'string-to-number
8708 comparefun (if (= dcst sorting-type) '< '>)))
8710 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8711 (lambda(x) (downcase (org-sort-remove-invisible x))))
8712 comparefun (if (= dcst sorting-type)
8714 (lambda (a b) (and (not (string< a b))
8715 (not (string= a b)))))))
8719 (if (or (string-match org-ts-regexp x)
8720 (string-match org-ts-regexp-both x))
8722 (org-time-string-to-time (match-string 0 x)))
8724 comparefun (if (= dcst sorting-type) '< '>)))
8725 (t (error "Invalid sorting type `%c'" sorting-type)))
8727 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8729 (lambda (a b) (funcall comparefun (car a) (car b))))))
8732 ;;; The orgstruct minor mode
8734 ;; Define a minor mode which can be used in other modes in order to
8735 ;; integrate the org-mode structure editing commands.
8737 ;; This is really a hack, because the org-mode structure commands use
8738 ;; keys which normally belong to the major mode. Here is how it
8739 ;; works: The minor mode defines all the keys necessary to operate the
8740 ;; structure commands, but wraps the commands into a function which
8741 ;; tests if the cursor is currently at a headline or a plain list
8742 ;; item. If that is the case, the structure command is used,
8743 ;; temporarily setting many Org-mode variables like regular
8744 ;; expressions for filling etc. However, when any of those keys is
8745 ;; used at a different location, function uses `key-binding' to look
8746 ;; up if the key has an associated command in another currently active
8747 ;; keymap (minor modes, major mode, global), and executes that
8748 ;; command. There might be problems if any of the keys is otherwise
8749 ;; used as a prefix key.
8751 (defcustom orgstruct-heading-prefix-regexp nil
8752 "Regexp that matches the custom prefix of Org headlines in
8753 orgstruct(++)-mode."
8756 :package-version '(Org . "8.0")
8758 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8760 (defcustom orgstruct-setup-hook nil
8761 "Hook run after orgstruct-mode-map is filled."
8764 :package-version '(Org . "8.0")
8767 (defvar orgstruct-initialized nil)
8769 (defvar org-local-vars nil
8770 "List of local variables, for use by `orgstruct-mode'.")
8773 (define-minor-mode orgstruct-mode
8774 "Toggle the minor mode `orgstruct-mode'.
8775 This mode is for using Org-mode structure commands in other
8776 modes. The following keys behave as if Org-mode were active, if
8777 the cursor is on a headline, or on a plain list item (both as
8778 defined by Org-mode)."
8779 nil " OrgStruct" (make-sparse-keymap)
8780 (funcall (if orgstruct-mode
8781 'add-to-invisibility-spec
8782 'remove-from-invisibility-spec)
8784 (when orgstruct-mode
8785 (org-load-modules-maybe)
8786 (unless orgstruct-initialized
8788 (setq orgstruct-initialized t))))
8791 (defun turn-on-orgstruct ()
8792 "Unconditionally turn on `orgstruct-mode'."
8795 (defvar org-fb-vars nil)
8796 (make-variable-buffer-local 'org-fb-vars)
8797 (defun orgstruct++-mode (&optional arg)
8798 "Toggle `orgstruct-mode', the enhanced version of it.
8799 In addition to setting orgstruct-mode, this also exports all
8800 indentation and autofilling variables from org-mode into the
8801 buffer. It will also recognize item context in multiline items."
8803 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8805 (progn (orgstruct-mode -1)
8807 (org-set-local (car v)
8808 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8811 (setq org-fb-vars nil)
8816 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8817 (symbol-name (car x)))
8818 (setq var (car x) val (nth 1 x))
8819 (push (list var `(quote ,(eval var))) org-fb-vars)
8820 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8822 (org-set-local 'orgstruct-is-++ t))))
8824 (defvar orgstruct-is-++ nil
8825 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8826 (make-variable-buffer-local 'orgstruct-is-++)
8829 (defun turn-on-orgstruct++ ()
8830 "Unconditionally turn on `orgstruct++-mode'."
8831 (orgstruct++-mode 1))
8833 (defun orgstruct-error ()
8834 "Error when there is no default binding for a structure key."
8836 (funcall (if (fboundp 'user-error)
8839 "This key has no function outside structure elements"))
8841 (defun orgstruct-setup ()
8842 "Setup orgstruct keymap."
8843 (dolist (cell '((org-demote . t)
8847 (org-shiftmetaleft . t)
8848 (org-shiftmetaright . t)
8849 org-backward-element
8850 org-backward-heading-same-level
8855 org-forward-heading-same-level
8857 org-insert-heading-respect-content
8858 org-kill-note-or-show-branches
8863 org-narrow-to-subtree
8878 outline-next-visible-heading
8879 outline-previous-visible-heading
8883 (let ((f (or (car-safe cell) cell))
8884 (disable-when-heading-prefix (cdr-safe cell)))
8886 (dolist (binding (nconc (where-is-internal f org-mode-map)
8887 (where-is-internal f outline-mode-map)))
8888 ;; TODO use local-function-key-map
8889 (dolist (rep '(("<tab>" . "TAB")
8890 ("<return>" . "RET")
8891 ("<escape>" . "ESC")
8892 ("<delete>" . "DEL")))
8893 (setq binding (read-kbd-macro
8894 (let ((case-fold-search))
8895 (replace-regexp-in-string
8896 (regexp-quote (cdr rep))
8898 (key-description binding))))))
8899 (let ((key (lookup-key orgstruct-mode-map binding)))
8900 (when (or (not key) (numberp key))
8902 (org-defkey orgstruct-mode-map
8904 (orgstruct-make-binding f binding disable-when-heading-prefix))
8906 (run-hooks 'orgstruct-setup-hook))
8908 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8909 "Create a function for binding in the structure minor mode.
8910 FUN is the command to call inside a table. KEY is the key that
8911 should be checked in for a command to execute outside of tables.
8912 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8913 if `orgstruct-heading-prefix-regexp' is non-nil."
8914 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8917 (while (fboundp (intern nname))
8918 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8919 (setq name (intern nname)))
8921 (let ((bindings '((org-heading-regexp
8923 orgstruct-heading-prefix-regexp
8924 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8926 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8927 (org-outline-regexp-bol
8928 (concat "^" org-outline-regexp))
8929 (outline-regexp org-outline-regexp)
8930 (outline-heading-end-regexp "\n")
8931 (outline-level 'org-outline-level)
8932 (outline-heading-alist))))
8934 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8935 "Outside of structure, run the binding of `"
8936 (key-description key) "'."
8937 (when disable-when-heading-prefix
8939 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8940 "back to the default binding due to limitations of Org's implementation of\n"
8941 "`" (symbol-name fun) "'.")))
8944 ,(when disable-when-heading-prefix
8945 '(and orgstruct-heading-prefix-regexp
8946 (not (string= orgstruct-heading-prefix-regexp "")))))
8951 (org-context-p 'headline 'item
8952 ,(when (memq fun '(org-insert-heading))
8953 '(when orgstruct-is-++
8956 (let* ((orgstruct-mode)
8958 (loop with key = ,key
8961 ("<return>" . "RET")
8962 ("<escape>" . "ESC")
8963 ("<delete>" . "DEL"))
8966 (setq key (read-kbd-macro
8967 (let ((case-fold-search))
8968 (replace-regexp-in-string
8969 (regexp-quote (car rep))
8971 (key-description key))))))
8972 thereis (key-binding key))))
8973 (if (keymapp binding)
8974 (set-temporary-overlay-map binding)
8975 (let ((func (or binding
8977 'orgstruct-error))))
8979 (call-interactively func)))))
8980 (org-run-like-in-org-mode
8984 (call-interactively ',fun)))))))))
8987 (defun org-contextualize-keys (alist contexts)
8988 "Return valid elements in ALIST depending on CONTEXTS.
8990 `org-agenda-custom-commands' or `org-capture-templates' are the
8991 values used for ALIST, and `org-agenda-custom-commands-contexts'
8992 or `org-capture-templates-contexts' are the associated contexts
8995 ;; normalize contexts
8997 (lambda(c) (cond ((listp (cadr c))
8998 (list (car c) (car c) (cadr c)))
8999 ((string= "" (cadr c))
9000 (list (car c) (car c) (caddr c)))
9003 ;; loop over all commands or templates
9004 (while (setq c (pop a))
9007 ((not (assoc (car c) contexts))
9009 ((and (assoc (car c) contexts)
9010 (setq vrules (org-contextualize-validate-key
9013 (when (not (equal (car vr) (cadr vr)))
9014 (setq repl vr))) vrules)
9015 (if (not repl) (push c r)
9016 (push (cadr repl) s)
9019 (cdr (or (assoc (cadr repl) alist)
9020 (error "Undefined key `%s' as contextual replacement for `%s'"
9021 (cadr repl) (car c)))))
9023 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9028 (let ((tpl (car x)))
9032 (equal y tpl)) s))) x)))
9035 (defun org-contextualize-validate-key (key contexts)
9036 "Check CONTEXTS for agenda or capture KEY."
9038 (while (setq r (pop contexts))
9042 (and (equal key (car r))
9043 (if (functionp rr) (funcall rr)
9044 (or (and (eq (car rr) 'in-file)
9046 (string-match (cdr rr) (buffer-file-name)))
9047 (and (eq (car rr) 'in-mode)
9048 (string-match (cdr rr) (symbol-name major-mode)))
9049 (and (eq (car rr) 'in-buffer)
9050 (string-match (cdr rr) (buffer-name)))
9051 (when (and (eq (car rr) 'not-in-file)
9053 (not (string-match (cdr rr) (buffer-file-name))))
9054 (when (eq (car rr) 'not-in-mode)
9055 (not (string-match (cdr rr) (symbol-name major-mode))))
9056 (when (eq (car rr) 'not-in-buffer)
9057 (not (string-match (cdr rr) (buffer-name)))))))
9060 (delete-dups (delq nil res))))
9062 (defun org-context-p (&rest contexts)
9063 "Check if local context is any of CONTEXTS.
9064 Possible values in the list of contexts are `table', `headline', and `item'."
9065 (let ((pos (point)))
9066 (goto-char (point-at-bol))
9067 (prog1 (or (and (memq 'table contexts)
9068 (looking-at "[ \t]*|"))
9069 (and (memq 'headline contexts)
9070 (looking-at org-outline-regexp))
9071 (and (memq 'item contexts)
9072 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9073 (and (memq 'item-body contexts)
9077 (defun org-get-local-variables ()
9078 "Return a list of all local variables in an Org mode buffer."
9080 (with-current-buffer (get-buffer-create "*Org tmp*")
9083 (setq varlist (buffer-local-variables)))
9084 (kill-buffer "*Org tmp*")
9091 (list (car x) (cdr x))))
9092 (if (and (not (get (car x) 'org-state))
9094 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9095 (symbol-name (car x))))
9099 (defun org-clone-local-variables (from-buffer &optional regexp)
9100 "Clone local variables from FROM-BUFFER.
9101 Optional argument REGEXP selects variables to clone."
9104 (and (symbolp (car pair))
9106 (string-match regexp (symbol-name (car pair))))
9107 (set (make-local-variable (car pair))
9109 (buffer-local-variables from-buffer)))
9112 (defun org-run-like-in-org-mode (cmd)
9113 "Run a command, pretending that the current buffer is in Org-mode.
9114 This will temporarily bind local variables that are typically bound in
9115 Org-mode to the values they have in Org-mode, and then interactively
9117 (org-load-modules-maybe)
9118 (unless org-local-vars
9119 (setq org-local-vars (org-get-local-variables)))
9121 (dolist (var org-local-vars)
9122 (when (or (not (boundp (car var)))
9123 (eq (symbol-value (car var))
9124 (default-value (car var))))
9125 (push (list (car var) `(quote ,(cadr var))) binds)))
9127 (call-interactively (quote ,cmd))))))
9131 (defun org-get-category (&optional pos force-refresh)
9132 "Get the category applying to position POS."
9134 (if force-refresh (org-refresh-category-properties))
9135 (let ((pos (or pos (point))))
9136 (or (get-text-property pos 'org-category)
9137 (progn (org-refresh-category-properties)
9138 (get-text-property pos 'org-category))))))
9140 (defun org-refresh-category-properties ()
9141 "Refresh category text properties in the buffer."
9142 (let ((case-fold-search t)
9143 (inhibit-read-only t)
9145 ((null org-category)
9146 (if buffer-file-name
9147 (file-name-sans-extension
9148 (file-name-nondirectory buffer-file-name))
9150 ((symbolp org-category) (symbol-name org-category))
9152 beg end cat pos optionp)
9153 (org-with-silent-modifications
9157 (goto-char (point-min))
9158 (put-text-property (point) (point-max) 'org-category def-cat)
9159 (while (re-search-forward
9160 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9161 (setq pos (match-end 0)
9162 optionp (equal (char-after (match-beginning 0)) ?#)
9163 cat (org-trim (match-string 2)))
9165 (setq beg (point-at-bol) end (point-max))
9166 (org-back-to-heading t)
9167 (setq beg (point) end (org-end-of-subtree t t)))
9168 (put-text-property beg end 'org-category cat)
9169 (put-text-property beg end 'org-category-position beg)
9170 (goto-char pos)))))))
9172 (defun org-refresh-properties (dprop tprop)
9173 "Refresh buffer text properties.
9174 DPROP is the drawer property and TPROP is the corresponding text
9176 (let ((case-fold-search t)
9177 (inhibit-read-only t) p)
9178 (org-with-silent-modifications
9182 (goto-char (point-min))
9183 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9184 (setq p (org-match-string-no-properties 1))
9186 (org-back-to-heading t)
9188 (point-at-bol) (point-at-eol) tprop p))))))))
9193 ;;; Link abbreviations
9195 (defun org-link-expand-abbrev (link)
9196 "Apply replacements as defined in `org-link-abbrev-alist'."
9197 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9198 (let* ((key (match-string 1 link))
9199 (as (or (assoc key org-link-abbrev-alist-local)
9200 (assoc key org-link-abbrev-alist)))
9201 (tag (and (match-end 2) (match-string 3 link)))
9207 ((symbolp rpl) (funcall rpl tag))
9208 ((string-match "%(\\([^)]+\\))" rpl)
9209 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9210 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9211 ((string-match "%h" rpl)
9212 (replace-match (url-hexify-string (or tag "")) t t rpl))
9213 (t (concat rpl tag)))))
9216 ;;; Storing and inserting links
9218 (defvar org-insert-link-history nil
9219 "Minibuffer history for links inserted with `org-insert-link'.")
9221 (defvar org-stored-links nil
9222 "Contains the links stored with `org-store-link'.")
9224 (defvar org-store-link-plist nil
9225 "Plist with info about the most recently link created with `org-store-link'.")
9227 (defvar org-link-protocols nil
9228 "Link protocols added to Org-mode using `org-add-link-type'.")
9230 (defvar org-store-link-functions nil
9231 "List of functions that are called to create and store a link.
9232 Each function will be called in turn until one returns a non-nil
9233 value. Each function should check if it is responsible for creating
9234 this link (for example by looking at the major mode).
9235 If not, it must exit and return nil.
9236 If yes, it should return a non-nil value after a calling
9237 `org-store-link-props' with a list of properties and values.
9238 Special properties are:
9240 :type The link prefix, like \"http\". This must be given.
9241 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9242 This is obligatory as well.
9243 :description Optional default description for the second pair
9244 of brackets in an Org-mode link. The user can still change
9245 this when inserting this link into an Org-mode buffer.
9247 In addition to these, any additional properties can be specified
9248 and then used in capture templates.")
9250 (defun org-add-link-type (type &optional follow export)
9251 "Add TYPE to the list of `org-link-types'.
9252 Re-compute all regular expressions depending on `org-link-types'
9254 FOLLOW and EXPORT are two functions.
9256 FOLLOW should take the link path as the single argument and do whatever
9257 is necessary to follow the link, for example find a file or display
9260 EXPORT should format the link path for export to one of the export formats.
9261 It should be a function accepting three arguments:
9263 path the path of the link, the text after the prefix (like \"http:\")
9264 desc the description of the link, if any, or a description added by
9265 org-export-normalize-links if there is none
9266 format the export format, a symbol like `html' or `latex' or `ascii'..
9268 The function may use the FORMAT information to return different values
9269 depending on the format. The return value will be put literally into
9270 the exported file. If the return value is nil, this means Org should
9271 do what it normally does with links which do not have EXPORT defined.
9273 Org-mode has a built-in default for exporting links. If you are happy with
9274 this default, there is no need to define an export function for the link
9275 type. For a simple example of an export function, see `org-bbdb.el'."
9276 (add-to-list 'org-link-types type t)
9277 (org-make-link-regexps)
9278 (if (assoc type org-link-protocols)
9279 (setcdr (assoc type org-link-protocols) (list follow export))
9280 (push (list type follow export) org-link-protocols)))
9282 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9283 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9286 (defun org-store-link (arg &optional ignore-region)
9287 "\\<org-mode-map>Store an org-link to the current location.
9288 This link is added to `org-stored-links' and can later be inserted
9289 into an org-buffer with \\[org-insert-link].
9291 For some link types, a prefix arg is interpreted.
9292 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9293 For file links, arg negates `org-context-in-file-links'.
9295 A double prefix arg force skipping storing functions that are not
9298 When the region is active and IGNORE-REGION is nil, store each line
9299 in the region as a separate link."
9301 (org-load-modules-maybe)
9302 (setq org-store-link-plist nil) ; reset
9303 (if (and (org-region-active-p) (not ignore-region))
9305 (let ((beg (region-beginning)) (end (region-end)))
9307 (while (< (point-at-eol) end)
9308 (funcall 'org-store-link arg t)
9309 (move-beginning-of-line 2))))
9310 (org-with-limited-levels
9311 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9313 ((and (not (equal arg '(16)))
9316 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9317 org-store-link-functions))
9318 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9319 (or (and (cdr sfuns)
9321 (completing-read "Which function for creating the link? "
9322 sfunsn t (car sfunsn)))))
9323 (funcall (caar sfuns)))
9324 (setq link (plist-get org-store-link-plist :link)
9325 desc (or (plist-get org-store-link-plist :description) link))))
9326 ((org-src-edit-buffer-p)
9328 (while (or (not label)
9332 (goto-char (point-min))
9334 (regexp-quote (format org-coderef-label-format label))
9336 (when label (message "Label exists already") (sit-for 2))
9337 (setq label (read-string "Code line label: " label)))
9339 (setq link (format org-coderef-label-format label))
9340 (setq gc (- 79 (length link)))
9341 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9343 (setq link (concat "(" label ")") desc nil)))
9345 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9346 ;; We are in the agenda, link to referenced location
9347 (let ((m (or (get-text-property (point) 'org-hd-marker)
9348 (get-text-property (point) 'org-marker))))
9350 (org-with-point-at m
9352 (if (org-called-interactively-p 'any)
9353 (call-interactively 'org-store-link)
9354 (org-store-link nil)))))))
9356 ((eq major-mode 'calendar-mode)
9357 (let ((cd (calendar-cursor-to-date)))
9360 (car org-time-stamp-formats)
9362 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9364 (org-store-link-props :type "calendar" :date cd)))
9366 ((eq major-mode 'help-mode)
9367 (setq link (concat "help:" (save-excursion
9368 (goto-char (point-min))
9369 (looking-at "^[^ ]+")
9371 (org-store-link-props :type "help"))
9373 ((eq major-mode 'w3-mode)
9374 (setq cpltxt (if (and (buffer-name)
9375 (not (string-match "Untitled" (buffer-name))))
9378 link (url-view-url t))
9379 (org-store-link-props :type "w3" :url (url-view-url t)))
9381 ((setq search (run-hook-with-args-until-success
9382 'org-create-file-search-functions))
9383 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9385 (setq cpltxt (or description link)))
9387 ((eq major-mode 'image-mode)
9388 (setq cpltxt (concat "file:"
9389 (abbreviate-file-name buffer-file-name))
9391 (org-store-link-props :type "image" :file buffer-file-name))
9393 ((eq major-mode 'dired-mode)
9394 ;; link to the file in the current line
9395 (let ((file (dired-get-filename nil t)))
9397 (abbreviate-file-name
9398 (expand-file-name (dired-get-filename nil t)))
9399 ;; otherwise, no file so use current directory.
9401 (setq cpltxt (concat "file:" file)
9404 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9405 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9407 ((org-in-regexp "<<\\(.*?\\)>>")
9410 (abbreviate-file-name
9411 (buffer-file-name (buffer-base-buffer)))
9412 "::" (match-string 1))
9414 ((and (featurep 'org-id)
9415 (or (eq org-id-link-to-org-use-id t)
9416 (and (org-called-interactively-p 'any)
9417 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9418 (and (eq org-id-link-to-org-use-id
9419 'create-if-interactive-and-no-custom-id)
9421 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9422 ;; We can make a link using the ID.
9423 (setq link (condition-case nil
9424 (prog1 (org-id-store-link)
9425 (setq desc (plist-get org-store-link-plist :description)))
9427 ;; probably before first headline, link to file only
9429 (abbreviate-file-name
9430 (buffer-file-name (buffer-base-buffer))))))))
9432 ;; Just link to current headline
9433 (setq cpltxt (concat "file:"
9434 (abbreviate-file-name
9435 (buffer-file-name (buffer-base-buffer)))))
9436 ;; Add a context search string
9437 (when (org-xor org-context-in-file-links arg)
9438 (let* ((ee (org-element-at-point))
9439 (et (org-element-type ee))
9440 (ev (plist-get (cadr ee) :value)))
9442 ((org-at-heading-p) nil)
9443 ((eq et 'keyword) ev)
9444 ((org-region-active-p)
9445 (buffer-substring (region-beginning) (region-end)))))
9446 (when (or (null txt) (string-match "\\S-" txt))
9450 (org-make-org-heading-search-string txt)
9452 desc (or (and (eq et 'keyword) ev)
9453 (nth 4 (ignore-errors (org-heading-components)))
9455 (if (string-match "::\\'" cpltxt)
9456 (setq cpltxt (substring cpltxt 0 -2)))
9457 (setq link cpltxt))))
9459 ((buffer-file-name (buffer-base-buffer))
9460 ;; Just link to this file here.
9461 (setq cpltxt (concat "file:"
9462 (abbreviate-file-name
9463 (buffer-file-name (buffer-base-buffer)))))
9464 ;; Add a context string
9465 (when (org-xor org-context-in-file-links arg)
9466 (setq txt (if (org-region-active-p)
9467 (buffer-substring (region-beginning) (region-end))
9468 (buffer-substring (point-at-bol) (point-at-eol))))
9469 ;; Only use search option if there is some text.
9470 (when (string-match "\\S-" txt)
9472 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9476 ((org-called-interactively-p 'interactive)
9477 (user-error "No method for storing a link from this buffer"))
9479 (t (setq link nil)))
9481 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9482 (setq link (or link cpltxt)
9483 desc (or desc cpltxt))
9484 (cond ((equal desc "NONE") (setq desc nil))
9485 ((string-match org-bracket-link-regexp desc)
9486 (setq desc (replace-regexp-in-string
9487 org-bracket-link-regexp
9488 (concat "\\3" (if (equal (length (match-string 0 desc))
9489 (length desc)) "*" "")) desc))))
9491 (if (and (or (org-called-interactively-p 'any)
9492 executing-kbd-macro ignore-region) link)
9494 (setq org-stored-links
9495 (cons (list link desc) org-stored-links))
9496 (message "Stored: %s" (or desc link))
9498 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9500 (setq org-stored-links
9501 (cons (list link desc) org-stored-links))))
9502 (or agenda-link (and link (org-make-link-string link desc))))))))
9504 (defun org-store-link-props (&rest plist)
9505 "Store link properties, extract names and addresses."
9507 (when (setq x (plist-get plist :from))
9508 (setq adr (mail-extract-address-components x))
9509 (setq plist (plist-put plist :fromname (car adr)))
9510 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9511 (when (setq x (plist-get plist :to))
9512 (setq adr (mail-extract-address-components x))
9513 (setq plist (plist-put plist :toname (car adr)))
9514 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9515 (let ((from (plist-get plist :from))
9516 (to (plist-get plist :to)))
9517 (when (and from to org-from-is-user-regexp)
9519 (plist-put plist :fromto
9520 (if (string-match org-from-is-user-regexp from)
9522 (concat "from %f"))))))
9523 (setq org-store-link-plist plist))
9525 (defun org-add-link-props (&rest plist)
9526 "Add these properties to the link property list."
9529 (setq key (pop plist) value (pop plist))
9530 (setq org-store-link-plist
9531 (plist-put org-store-link-plist key value)))))
9533 (defun org-email-link-description (&optional fmt)
9534 "Return the description part of an email link.
9535 This takes information from `org-store-link-plist' and formats it
9536 according to FMT (default from `org-email-link-description-format')."
9537 (setq fmt (or fmt org-email-link-description-format))
9538 (let* ((p org-store-link-plist)
9539 (to (plist-get p :toaddress))
9540 (from (plist-get p :fromaddress))
9543 (cons "%c" (plist-get p :fromto))
9544 (cons "%F" (plist-get p :from))
9545 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9546 (cons "%T" (plist-get p :to))
9547 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9548 (cons "%s" (plist-get p :subject))
9549 (cons "%d" (plist-get p :date))
9550 (cons "%m" (plist-get p :message-id)))))
9551 (when (string-match "%c" fmt)
9552 ;; Check if the user wrote this message
9553 (if (and org-from-is-user-regexp from to
9554 (save-match-data (string-match org-from-is-user-regexp from)))
9555 (setq fmt (replace-match "to %t" t t fmt))
9556 (setq fmt (replace-match "from %f" t t fmt))))
9557 (org-replace-escapes fmt table)))
9559 (defun org-make-org-heading-search-string (&optional string)
9560 "Make search string for the current headline or STRING."
9562 (and (derived-mode-p 'org-mode)
9564 (org-back-to-heading t)
9565 (org-element-property :raw-value (org-element-at-point))))))
9566 (lines org-context-in-file-links))
9567 (or string (setq s (concat "*" s))) ; Add * for headlines
9568 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9569 (when (and string (integerp lines) (> lines 0))
9570 (let ((slines (org-split-string s "\n")))
9571 (when (< lines (length slines))
9574 (reverse (nthcdr (- (length slines) lines)
9575 (reverse slines))) "\n")))))
9576 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9578 (defun org-make-link-string (link &optional description)
9579 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9580 (unless (string-match "\\S-" link)
9581 (error "Empty link"))
9582 (when (and description
9583 (stringp description)
9584 (not (string-match "\\S-" description)))
9585 (setq description nil))
9586 (when (stringp description)
9587 ;; Remove brackets from the description, they are fatal.
9588 (while (string-match "\\[" description)
9589 (setq description (replace-match "{" t t description)))
9590 (while (string-match "\\]" description)
9591 (setq description (replace-match "}" t t description))))
9592 (when (equal link description)
9593 ;; No description needed, it is identical
9594 (setq description nil))
9595 (when (and (not description)
9596 (not (string-match (org-image-file-name-regexp) link))
9597 (not (equal link (org-link-escape link))))
9598 (setq description (org-extract-attributes link)))
9600 (cond ((string-match (org-image-file-name-regexp) link) link)
9601 ((string-match org-link-types-re link)
9602 (concat (match-string 1 link)
9603 (org-link-escape (substring link (match-end 1)))))
9604 (t (org-link-escape link))))
9605 (concat "[[" link "]"
9606 (if description (concat "[" description "]") "")
9609 (defconst org-link-escape-chars
9610 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9611 "List of characters that should be escaped in link.
9612 This is the list that is used for internal purposes.")
9614 (defconst org-link-escape-chars-browser
9616 "List of escapes for characters that are problematic in links.
9617 This is the list that is used before handing over to the browser.")
9619 (defun org-link-escape (text &optional table merge)
9620 "Return percent escaped representation of TEXT.
9621 TEXT is a string with the text to escape.
9622 Optional argument TABLE is a list with characters that should be
9623 escaped. When nil, `org-link-escape-chars' is used.
9624 If optional argument MERGE is set, merge TABLE into
9625 `org-link-escape-chars'."
9628 (mapc (lambda (defchr)
9629 (unless (member defchr table)
9630 (setq table (cons defchr table)))) org-link-escape-chars))
9632 (setq table org-link-escape-chars)))
9635 (if (or (member char table)
9636 (and (or (< char 32) (= char 37) (> char 126))
9638 (mapconcat (lambda (sequence-element)
9639 (format "%%%.2X" sequence-element))
9640 (or (encode-coding-char char 'utf-8)
9641 (error "Unable to percent escape character: %s"
9642 (char-to-string char))) "")
9643 (char-to-string char))) text ""))
9645 (defun org-link-unescape (str)
9646 "Unhex hexified Unicode strings as returned from the JavaScript function
9647 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9648 (unless (and (null str) (string= "" str))
9649 (let ((pos 0) (case-fold-search t) unhexed)
9650 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9651 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9652 (setq str (replace-match unhexed t t str))
9653 (setq pos (+ pos (length unhexed))))))
9656 (defun org-link-unescape-compound (hex)
9657 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9658 Note: this function also decodes single byte encodings like
9659 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9661 (let* ((bytes (cdr (split-string hex "%")))
9666 (let* ((val (string-to-number (pop bytes) 16))
9670 ((>= val 252) (cons 6 252))
9671 ((>= val 248) (cons 5 248))
9672 ((>= val 240) (cons 4 240))
9673 ((>= val 224) (cons 3 224))
9674 ((>= val 192) (cons 2 192))
9677 (if (>= val 192) (setq eat (car shift-xor)))
9678 (setq val (logxor val (cdr shift-xor)))
9679 (setq sum (+ (lsh sum (car shift-xor)) val))
9680 (if (> eat 0) (setq eat (- eat 1)))
9682 ((= 0 eat) ;multi byte
9683 (setq ret (concat ret (org-char-to-string sum)))
9685 ((not bytes) ; single byte(s)
9686 (setq ret (org-link-unescape-single-byte-sequence hex))))
9687 )) ;; end (while bytes
9690 (defun org-link-unescape-single-byte-sequence (hex)
9691 "Unhexify hex-encoded single byte character sequences."
9692 (mapconcat (lambda (byte)
9693 (char-to-string (string-to-number byte 16)))
9694 (cdr (split-string hex "%")) ""))
9696 (defun org-xor (a b)
9700 (defun org-fixup-message-id-for-http (s)
9701 "Replace special characters in a message id, so it can be used in an http query."
9702 (when (string-match "%" s)
9703 (setq s (mapconcat (lambda (c)
9706 (char-to-string c)))
9708 (while (string-match "<" s)
9709 (setq s (replace-match "%3C" t t s)))
9710 (while (string-match ">" s)
9711 (setq s (replace-match "%3E" t t s)))
9712 (while (string-match "@" s)
9713 (setq s (replace-match "%40" t t s)))
9716 (defun org-link-prettify (link)
9717 "Return a human-readable representation of LINK.
9718 The car of LINK must be a raw link the cdr of LINK must be either
9719 a link description or nil."
9720 (let ((desc (or (cadr link) "<no description>")))
9721 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9722 "<" (car link) ">")))
9725 (defun org-insert-link-global ()
9726 "Insert a link like Org-mode does.
9727 This command can be called in any mode to insert a link in Org-mode syntax."
9729 (org-load-modules-maybe)
9730 (org-run-like-in-org-mode 'org-insert-link))
9732 (defun org-insert-all-links (&optional keep)
9733 "Insert all links in `org-stored-links'."
9735 (let ((links (copy-sequence org-stored-links)) l)
9736 (while (setq l (if keep (pop links) (pop org-stored-links)))
9738 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9741 (defun org-link-fontify-links-to-this-file ()
9742 "Fontify links to the current file in `org-stored-links'."
9743 (let ((f (buffer-file-name)) a b)
9744 (setq a (mapcar (lambda(l)
9746 (when (and (string-match "^file:\\(.+\\)::" ll)
9747 (equal f (expand-file-name (match-string 1 ll))))
9750 (when (featurep 'org-id)
9751 (setq b (mapcar (lambda(l)
9753 (when (and (string-match "^id:\\(.+\\)$" ll)
9754 (equal f (expand-file-name
9755 (or (org-id-find-id-file
9756 (match-string 1 ll)) ""))))
9760 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9761 (delq nil (append a b)))))
9763 (defvar org-link-links-in-this-file nil)
9764 (defun org-insert-link (&optional complete-file link-location default-description)
9765 "Insert a link. At the prompt, enter the link.
9767 Completion can be used to insert any of the link protocol prefixes like
9770 The history can be used to select a link previously stored with
9771 `org-store-link'. When the empty string is entered (i.e. if you just
9772 press RET at the prompt), the link defaults to the most recently
9773 stored link. As SPC triggers completion in the minibuffer, you need to
9774 use M-SPC or C-q SPC to force the insertion of a space character.
9776 You will also be prompted for a description, and if one is given, it will
9777 be displayed in the buffer instead of the link.
9779 If there is already a link at point, this command will allow you to edit link
9780 and description parts.
9782 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9783 be selected using completion. The path to the file will be relative to the
9784 current directory if the file is in the current directory or a subdirectory.
9785 Otherwise, the link will be the absolute path as completed in the minibuffer
9786 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9787 option `org-link-file-path-type'.
9789 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9790 the current directory or below.
9792 With three \\[universal-argument] prefixes, negate the meaning of
9793 `org-keep-stored-link-after-insertion'.
9795 If `org-make-link-description-function' is non-nil, this function will be
9796 called with the link target, and the result will be the default
9799 If the LINK-LOCATION parameter is non-nil, this value will be
9800 used as the link location instead of reading one interactively.
9802 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9803 be used as the default description."
9805 (let* ((wcf (current-window-configuration))
9806 (origbuf (current-buffer))
9807 (region (if (org-region-active-p)
9808 (buffer-substring (region-beginning) (region-end))))
9809 (remove (and region (list (region-beginning) (region-end))))
9811 tmphist ; byte-compile incorrectly complains about this
9812 (link link-location)
9813 (abbrevs org-link-abbrev-alist-local)
9814 entry file all-prefixes auto-desc)
9816 (link-location) ; specified by arg, just use it.
9817 ((org-in-regexp org-bracket-link-regexp 1)
9818 ;; We do have a link at point, and we are going to edit it.
9819 (setq remove (list (match-beginning 0) (match-end 0)))
9820 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9821 (setq link (read-string "Link: "
9823 (org-match-string-no-properties 1)))))
9824 ((or (org-in-regexp org-angle-link-re)
9825 (org-in-regexp org-plain-link-re))
9826 ;; Convert to bracket link
9827 (setq remove (list (match-beginning 0) (match-end 0))
9828 link (read-string "Link: "
9829 (org-remove-angle-brackets (match-string 0)))))
9830 ((member complete-file '((4) (16)))
9831 ;; Completing read for file names.
9832 (setq link (org-file-complete-link complete-file)))
9834 ;; Read link, with completion for stored links.
9835 (org-link-fontify-links-to-this-file)
9836 (org-switch-to-buffer-other-window "*Org Links*")
9837 (with-current-buffer "*Org Links*"
9839 (insert "Insert a link.
9840 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9841 (when org-stored-links
9842 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9843 (insert (mapconcat 'org-link-prettify
9844 (reverse org-stored-links) "\n")))
9845 (goto-char (point-min)))
9846 (let ((cw (selected-window)))
9847 (select-window (get-buffer-window "*Org Links*" 'visible))
9848 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9849 (unless (pos-visible-in-window-p (point-max))
9850 (org-fit-window-to-buffer))
9851 (and (window-live-p cw) (select-window cw)))
9852 ;; Fake a link history, containing the stored links.
9853 (setq tmphist (append (mapcar 'car org-stored-links)
9854 org-insert-link-history))
9855 (setq all-prefixes (append (mapcar 'car abbrevs)
9856 (mapcar 'car org-link-abbrev-alist)
9861 (org-completing-read
9864 (mapcar (lambda (x) (concat x ":"))
9866 (mapcar 'car org-stored-links))
9869 (caar org-stored-links)))
9870 (if (not (string-match "\\S-" link))
9871 (error "No link selected"))
9873 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9875 (if (or (member link all-prefixes)
9876 (and (equal ":" (substring link -1))
9877 (member (substring link 0 -1) all-prefixes)
9878 (setq link (substring link 0 -1))))
9879 (setq link (with-current-buffer origbuf
9880 (org-link-try-special-completion link)))))
9881 (set-window-configuration wcf)
9882 (kill-buffer "*Org Links*"))
9883 (setq entry (assoc link org-stored-links))
9884 (or entry (push link org-insert-link-history))
9885 (setq desc (or desc (nth 1 entry)))))
9887 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9888 (not org-keep-stored-link-after-insertion))
9889 (setq org-stored-links (delq (assoc link org-stored-links)
9892 (if (string-match org-plain-link-re link)
9893 ;; URL-like link, normalize the use of angular brackets.
9894 (setq link (org-remove-angle-brackets link)))
9896 ;; Check if we are linking to the current file with a search
9897 ;; option If yes, simplify the link by using only the search
9899 (when (and buffer-file-name
9900 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9901 (let* ((path (match-string 1 link))
9902 (case-fold-search nil)
9903 (search (match-string 2 link)))
9905 (if (equal (file-truename buffer-file-name) (file-truename path))
9906 ;; We are linking to this same file, with a search option
9907 (setq link search)))))
9909 ;; Check if we can/should use a relative path. If yes, simplify the link
9910 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9911 (let* ((type (match-string 1 link))
9912 (path (match-string 2 link))
9914 (case-fold-search nil))
9916 ((or (eq org-link-file-path-type 'absolute)
9917 (equal complete-file '(16)))
9918 (setq path (abbreviate-file-name (expand-file-name path))))
9919 ((eq org-link-file-path-type 'noabbrev)
9920 (setq path (expand-file-name path)))
9921 ((eq org-link-file-path-type 'relative)
9922 (setq path (file-relative-name path)))
9925 (if (string-match (concat "^" (regexp-quote
9927 (file-name-as-directory
9928 default-directory))))
9929 (expand-file-name path))
9930 ;; We are linking a file with relative path name.
9931 (setq path (substring (expand-file-name path)
9933 (setq path (abbreviate-file-name (expand-file-name path)))))))
9934 (setq link (concat type path))
9935 (if (equal desc origpath)
9938 (if org-make-link-description-function
9940 (or (condition-case nil
9941 (funcall org-make-link-description-function link desc)
9942 (error (progn (message "Can't get link description from `%s'"
9943 (symbol-name org-make-link-description-function))
9945 (read-string "Description: " default-description)))
9946 (if default-description (setq desc default-description)
9947 (setq desc (or (and auto-desc desc)
9948 (read-string "Description: " desc)))))
9950 (unless (string-match "\\S-" desc) (setq desc nil))
9951 (if remove (apply 'delete-region remove))
9952 (insert (org-make-link-string link desc))))
9954 (defun org-link-try-special-completion (type)
9955 "If there is completion support for link type TYPE, offer it."
9956 (let ((fun (intern (concat "org-" type "-complete-link"))))
9959 (read-string "Link (no completion support): " (concat type ":")))))
9961 (defun org-file-complete-link (&optional arg)
9962 "Create a file link using completion."
9964 (setq file (org-iread-file-name "File: "))
9965 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9966 (pwd1 (file-name-as-directory (abbreviate-file-name
9967 (expand-file-name ".")))))
9972 (abbreviate-file-name (expand-file-name file)))))
9973 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9974 (setq link (concat "file:" (match-string 1 file))))
9975 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9976 (expand-file-name file))
9978 "file:" (match-string 1 (expand-file-name file)))))
9979 (t (setq link (concat "file:" file)))))
9982 (defun org-iread-file-name (&rest args)
9983 "Read-file-name using `ido-mode' speedup if available.
9984 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9985 See `read-file-name' for a description of parameters."
9986 (org-without-partial-completion
9987 (if (and org-completion-use-ido
9988 (fboundp 'ido-read-file-name)
9989 (boundp 'ido-mode) ido-mode
9990 (listp (second args)))
9991 (let ((ido-enter-matching-directory nil))
9992 (apply 'ido-read-file-name args))
9993 (apply 'read-file-name args))))
9995 (defun org-completing-read (&rest args)
9996 "Completing-read with SPACE being a normal character."
9997 (let ((enable-recursive-minibuffers t)
9998 (minibuffer-local-completion-map
9999 (copy-keymap minibuffer-local-completion-map)))
10000 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10001 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10002 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10003 (apply 'org-icompleting-read args)))
10005 (defun org-completing-read-no-i (&rest args)
10006 (let (org-completion-use-ido org-completion-use-iswitchb)
10007 (apply 'org-completing-read args)))
10009 (defun org-iswitchb-completing-read (prompt choices &rest args)
10010 "Use iswitch as a completing-read replacement to choose from choices.
10011 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10013 (let* ((iswitchb-use-virtual-buffers nil)
10014 (iswitchb-make-buflist-hook
10016 (setq iswitchb-temp-buflist choices))))
10017 (iswitchb-read-buffer prompt)))
10019 (defun org-icompleting-read (&rest args)
10020 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10021 (org-without-partial-completion
10022 (if (and org-completion-use-ido
10023 (fboundp 'ido-completing-read)
10024 (boundp 'ido-mode) ido-mode
10025 (listp (second args)))
10026 (let ((ido-enter-matching-directory nil))
10027 (apply 'ido-completing-read (concat (car args))
10028 (if (consp (car (nth 1 args)))
10029 (mapcar 'car (nth 1 args))
10032 (if (and org-completion-use-iswitchb
10033 (boundp 'iswitchb-mode) iswitchb-mode
10034 (listp (second args)))
10035 (apply 'org-iswitchb-completing-read (concat (car args))
10036 (if (consp (car (nth 1 args)))
10037 (mapcar 'car (nth 1 args))
10040 (apply 'completing-read args)))))
10042 (defun org-extract-attributes (s)
10043 "Extract the attributes cookie from a string and set as text property."
10044 (let (a attr (start 0) key value)
10046 (when (string-match "{{\\([^}]+\\)}}$" s)
10047 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10048 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10049 (setq key (match-string 1 a) value (match-string 2 a)
10050 start (match-end 0)
10051 attr (plist-put attr (intern key) value))))
10052 (org-add-props s nil 'org-attr attr))
10055 (defun org-extract-attributes-from-string (tag)
10056 (let (key value attr)
10057 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10058 (setq key (match-string 1 tag) value (match-string 2 tag)
10059 tag (replace-match "" t t tag)
10060 attr (plist-put attr (intern key) value)))
10063 (defun org-attributes-to-string (plist)
10064 "Format a property list into an HTML attribute list."
10065 (let ((s "") key value)
10067 (setq key (pop plist) value (pop plist))
10069 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10072 ;;; Opening/following a link
10074 (defvar org-link-search-failed nil)
10076 (defvar org-open-link-functions nil
10077 "Hook for functions finding a plain text link.
10078 These functions must take a single argument, the link content.
10079 They will be called for links that look like [[link text][description]]
10080 when LINK TEXT does not have a protocol like \"http:\" and does not look
10081 like a filename (e.g. \"./blue.png\").
10083 These functions will be called *before* Org attempts to resolve the
10084 link by doing text searches in the current buffer - so if you want a
10085 link \"[[target]]\" to still find \"<<target>>\", your function should
10086 handle this as a special case.
10088 When the function does handle the link, it must return a non-nil value.
10089 If it decides that it is not responsible for this link, it must return
10090 nil to indicate that that Org-mode can continue with other options
10091 like exact and fuzzy text search.")
10093 (defun org-next-link (&optional search-backward)
10094 "Move forward to the next link.
10095 If the link is in hidden text, expose it."
10097 (when (and org-link-search-failed (eq this-command last-command))
10098 (goto-char (point-min))
10099 (message "Link search wrapped back to beginning of buffer"))
10100 (setq org-link-search-failed nil)
10101 (let* ((pos (point))
10103 (a (assoc :link ct))
10104 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10105 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10106 ((looking-at org-any-link-re)
10107 ;; Don't stay stuck at link without an org-link face
10108 (forward-char (if search-backward -1 1))))
10109 (if (funcall srch-fun org-any-link-re nil t)
10111 (goto-char (match-beginning 0))
10112 (if (outline-invisible-p) (org-show-context)))
10114 (setq org-link-search-failed t)
10115 (message "No further link found"))))
10117 (defun org-previous-link ()
10118 "Move backward to the previous link.
10119 If the link is in hidden text, expose it."
10121 (funcall 'org-next-link t))
10123 (defun org-translate-link (s)
10124 "Translate a link string if a translation function has been defined."
10125 (if (and org-link-translation-function
10126 (fboundp org-link-translation-function)
10127 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10129 (setq s (funcall org-link-translation-function
10130 (match-string 1 s) (match-string 2 s)))
10131 (concat (car s) ":" (cdr s)))
10134 (defun org-translate-link-from-planner (type path)
10135 "Translate a link from Emacs Planner syntax so that Org can follow it.
10136 This is still an experimental function, your mileage may vary."
10138 ((member type '("http" "https" "news" "ftp"))
10139 ;; standard Internet links are the same.
10141 ((and (equal type "irc") (string-match "^//" path))
10142 ;; Planner has two / at the beginning of an irc link, we have 1.
10143 ;; We should have zero, actually....
10144 (setq path (substring path 1)))
10145 ((and (equal type "lisp") (string-match "^/" path))
10146 ;; Planner has a slash, we do not.
10147 (setq type "elisp" path (substring path 1)))
10148 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10149 ;; A typical message link. Planner has the id after the final slash,
10150 ;; we separate it with a hash mark
10151 (setq path (concat (match-string 1 path) "#"
10152 (org-remove-angle-brackets (match-string 2 path)))))
10156 (defun org-find-file-at-mouse (ev)
10157 "Open file link or URL at mouse."
10159 (mouse-set-point ev)
10160 (org-open-at-point 'in-emacs))
10162 (defun org-open-at-mouse (ev)
10163 "Open file link or URL at mouse.
10164 See the docstring of `org-open-file' for details."
10166 (mouse-set-point ev)
10167 (if (eq major-mode 'org-agenda-mode)
10168 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10169 (org-open-at-point))
10171 (defvar org-window-config-before-follow-link nil
10172 "The window configuration before following a link.
10173 This is saved in case the need arises to restore it.")
10175 (defvar org-open-link-marker (make-marker)
10176 "Marker pointing to the location where `org-open-at-point; was called.")
10179 (defun org-open-at-point-global ()
10180 "Follow a link like Org-mode does.
10181 This command can be called in any mode to follow a link that has
10184 (org-run-like-in-org-mode 'org-open-at-point))
10187 (defun org-open-link-from-string (s &optional arg reference-buffer)
10188 "Open a link in the string S, as if it was in Org-mode."
10189 (interactive "sLink: \nP")
10190 (let ((reference-buffer (or reference-buffer (current-buffer))))
10192 (let ((org-inhibit-startup (not reference-buffer)))
10195 (goto-char (point-min))
10196 (when reference-buffer
10197 (setq org-link-abbrev-alist-local
10198 (with-current-buffer reference-buffer
10199 org-link-abbrev-alist-local)))
10200 (org-open-at-point arg reference-buffer)))))
10202 (defvar org-open-at-point-functions nil
10203 "Hook that is run when following a link at point.
10205 Functions in this hook must return t if they identify and follow
10206 a link at point. If they don't find anything interesting at point,
10207 they must return nil.")
10209 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10210 (defun org-open-at-point (&optional arg reference-buffer)
10211 "Open link at or after point.
10212 If there is no link at point, this function will search forward up to
10213 the end of the current line.
10214 Normally, files will be opened by an appropriate application. If the
10215 optional prefix argument ARG is non-nil, Emacs will visit the file.
10216 With a double prefix argument, try to open outside of Emacs, in the
10217 application the system uses for this file type."
10219 ;; if in a code block, then open the block's results
10220 (unless (call-interactively #'org-babel-open-src-block-result)
10221 (org-load-modules-maybe)
10222 (move-marker org-open-link-marker (point))
10223 (setq org-window-config-before-follow-link (current-window-configuration))
10224 (org-remove-occur-highlights nil nil t)
10226 ((and (org-at-heading-p)
10227 (not (org-at-timestamp-p t))
10228 (not (org-in-regexp
10229 (concat org-plain-link-re "\\|"
10230 org-bracket-link-regexp "\\|"
10231 org-angle-link-re "\\|"
10232 "[ \t]:[^ \t\n]+:[ \t]*$")))
10233 (not (get-text-property (point) 'org-linked-text)))
10234 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10236 (lk (if (stringp lk0) (list lk0) lk0))
10237 (lkend (cdr lkall)))
10239 (search-forward l nil lkend)
10240 (goto-char (match-beginning 0))
10241 (org-open-at-point))
10243 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10244 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10245 ((and (org-at-timestamp-p t)
10246 (not (org-in-regexp org-bracket-link-regexp)))
10247 (org-follow-timestamp-link))
10248 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10249 (not (org-in-regexp org-any-link-re)))
10250 (org-footnote-action))
10252 (let (type path link line search (pos (point)))
10255 (skip-chars-forward "^]\n\r")
10256 (when (org-in-regexp org-bracket-link-regexp 1)
10257 (setq link (org-extract-attributes
10258 (org-link-unescape (org-match-string-no-properties 1))))
10259 (while (string-match " *\n *" link)
10260 (setq link (replace-match " " t t link)))
10261 (setq link (org-link-expand-abbrev link))
10263 ((or (file-name-absolute-p link)
10264 (string-match "^\\.\\.?/" link))
10265 (setq type "file" path link))
10266 ((string-match org-link-re-with-space3 link)
10267 (setq type (match-string 1 link) path (match-string 2 link)))
10268 ((string-match "^help:+\\(.+\\)" link)
10269 (setq type "help" path (match-string 1 link)))
10270 (t (setq type "thisfile" path link)))
10273 (when (get-text-property (point) 'org-linked-text)
10274 (setq type "thisfile"
10275 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10276 (1+ (point)) (point))
10277 path (buffer-substring
10278 (or (previous-single-property-change pos 'org-linked-text)
10280 (or (next-single-property-change pos 'org-linked-text)
10285 (when (or (org-in-regexp org-angle-link-re)
10286 (let ((match (org-in-regexp org-plain-link-re)))
10287 ;; Check a plain link is not within a bracket link
10291 (goto-char (car match))
10292 (not (org-in-regexp org-bracket-link-regexp))))))
10293 (let ((line_ending (save-excursion (end-of-line) (point))))
10294 ;; We are in a line before a plain or bracket link
10295 (or (re-search-forward org-plain-link-re line_ending t)
10296 (re-search-forward org-bracket-link-regexp line_ending t))))
10297 (setq type (match-string 1)
10298 path (org-link-unescape (match-string 2)))
10301 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10303 path (match-string 1))
10304 (while (string-match ":" path)
10305 (setq path (replace-match "+" t t path)))
10307 (when (org-in-regexp "<\\([^><\n]+\\)>")
10308 (setq type "tree-match"
10309 path (match-string 1))
10312 (user-error "No link found"))
10314 ;; switch back to reference buffer
10315 ;; needed when if called in a temporary buffer through
10316 ;; org-open-link-from-string
10317 (with-current-buffer (or reference-buffer (current-buffer))
10319 ;; Remove any trailing spaces in path
10320 (if (string-match " +\\'" path)
10321 (setq path (replace-match "" t t path)))
10322 (if (and org-link-translation-function
10323 (fboundp org-link-translation-function))
10324 ;; Check if we need to translate the link
10325 (let ((tmp (funcall org-link-translation-function type path)))
10326 (setq type (car tmp) path (cdr tmp))))
10330 ((assoc type org-link-protocols)
10331 (funcall (nth 1 (assoc type org-link-protocols)) path))
10333 ((equal type "help")
10334 (let ((f-or-v (intern path)))
10335 (cond ((fboundp f-or-v)
10336 (describe-function f-or-v))
10338 (describe-variable f-or-v))
10339 (t (error "Not a known function or variable")))))
10341 ((equal type "mailto")
10342 (let ((cmd (car org-link-mailto-program))
10343 (args (cdr org-link-mailto-program)) args1
10344 (address path) (subject "") a)
10345 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10346 (setq address (match-string 1 path)
10347 subject (org-link-escape (match-string 2 path))))
10350 ((not (stringp (car args))) (push (pop args) args1))
10351 (t (setq a (pop args))
10352 (if (string-match "%a" a)
10353 (setq a (replace-match address t t a)))
10354 (if (string-match "%s" a)
10355 (setq a (replace-match subject t t a)))
10357 (apply cmd (nreverse args1))))
10359 ((member type '("http" "https" "ftp" "news"))
10360 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10362 path org-link-escape-chars-browser)
10365 ((string= type "doi")
10366 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10368 path org-link-escape-chars-browser)
10371 ((member type '("message"))
10372 (browse-url (concat type ":" path)))
10374 ((string= type "tags")
10375 (org-tags-view arg path))
10377 ((string= type "tree-match")
10378 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10380 ((string= type "file")
10381 (if (string-match "::\\([0-9]+\\)\\'" path)
10382 (setq line (string-to-number (match-string 1 path))
10383 path (substring path 0 (match-beginning 0)))
10384 (if (string-match "::\\(.+\\)\\'" path)
10385 (setq search (match-string 1 path)
10386 path (substring path 0 (match-beginning 0)))))
10387 (if (string-match "[*?{]" (file-name-nondirectory path))
10389 (org-open-file path arg line search)))
10391 ((string= type "shell")
10392 (let ((buf (generate-new-buffer "*Org Shell Output"))
10394 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10395 (string-match org-confirm-shell-link-not-regexp cmd))
10396 (not org-confirm-shell-link-function)
10397 (funcall org-confirm-shell-link-function
10398 (format "Execute \"%s\" in shell? "
10399 (org-add-props cmd nil
10400 'face 'org-warning))))
10402 (message "Executing %s" cmd)
10403 (shell-command cmd buf)
10404 (if (featurep 'midnight)
10405 (setq clean-buffer-list-kill-buffer-names
10406 (cons buf clean-buffer-list-kill-buffer-names))))
10409 ((string= type "elisp")
10411 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10412 (string-match org-confirm-elisp-link-not-regexp cmd))
10413 (not org-confirm-elisp-link-function)
10414 (funcall org-confirm-elisp-link-function
10415 (format "Execute \"%s\" as elisp? "
10416 (org-add-props cmd nil
10417 'face 'org-warning))))
10418 (message "%s => %s" cmd
10419 (if (equal (string-to-char cmd) ?\()
10421 (call-interactively (read cmd))))
10424 ((and (string= type "thisfile")
10425 (run-hook-with-args-until-success
10426 'org-open-link-functions path)))
10428 ((string= type "thisfile")
10430 (switch-to-buffer-other-window
10431 (org-get-buffer-for-internal-link (current-buffer)))
10432 (org-mark-ring-push))
10433 (let ((cmd `(org-link-search
10435 ,(cond ((equal arg '(4)) ''occur)
10436 ((equal arg '(16)) ''org-occur))
10438 (condition-case nil (let ((org-link-search-inhibit-query t))
10440 (error (progn (widen) (eval cmd))))))
10442 (t (browse-url-at-point)))))))
10443 (move-marker org-open-link-marker nil)
10444 (run-hook-with-args 'org-follow-link-hook)))
10446 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10447 "Offer links in the current entry and return the selected link.
10448 If there is only one link, return it.
10449 If NTH is an integer, return the NTH link found.
10450 If ZERO is a string, check also this string for a link, and if
10451 there is one, return it."
10452 (with-current-buffer buffer
10457 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10458 "\\(" org-angle-link-re "\\)\\|"
10459 "\\(" org-plain-link-re "\\)"))
10461 (in-emacs (if (integerp nth) nil nth))
10462 have-zero end links link c)
10463 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10464 (push (match-string 0 zero) links)
10465 (setq cnt (1- cnt) have-zero t))
10467 (org-back-to-heading t)
10468 (setq end (save-excursion (outline-next-heading) (point)))
10469 (while (re-search-forward re end t)
10470 (push (match-string 0) links))
10471 (setq links (org-uniquify (reverse links))))
10474 (message "No links"))
10475 ((equal (length links) 1)
10476 (setq link (car links)))
10477 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10478 (setq link (nth (if have-zero nth (1- nth)) links)))
10479 (t ; we have to select a link
10481 (save-window-excursion
10482 (delete-other-windows)
10483 (with-output-to-temp-buffer "*Select Link*"
10485 (if (not (string-match org-bracket-link-regexp l))
10486 (princ (format "[%c] %s\n" (incf cnt)
10487 (org-remove-angle-brackets l)))
10489 (princ (format "[%c] %s (%s)\n" (incf cnt)
10490 (match-string 3 l) (match-string 1 l)))
10491 (princ (format "[%c] %s\n" (incf cnt)
10492 (match-string 1 l))))))
10494 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10495 (message "Select link to open, RET to open all:")
10496 (setq c (read-char-exclusive))
10497 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10498 (when (equal c ?q) (error "Abort"))
10499 (if (equal c ?\C-m)
10501 (setq nth (- c ?0))
10502 (if have-zero (setq nth (1+ nth)))
10503 (unless (and (integerp nth) (>= (length links) nth))
10504 (error "Invalid link selection"))
10505 (setq link (nth (1- nth) links)))))
10506 (cons link end))))))
10508 ;; Add special file links that specify the way of opening
10510 (org-add-link-type "file+sys" 'org-open-file-with-system)
10511 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10512 (defun org-open-file-with-system (path)
10513 "Open file at PATH using the system way of opening it."
10514 (org-open-file path 'system))
10515 (defun org-open-file-with-emacs (path)
10516 "Open file at PATH in Emacs."
10517 (org-open-file path 'emacs))
10522 (defvar org-create-file-search-functions nil
10523 "List of functions to construct the right search string for a file link.
10524 These functions are called in turn with point at the location to
10525 which the link should point.
10527 A function in the hook should first test if it would like to
10528 handle this file type, for example by checking the `major-mode'
10529 or the file extension. If it decides not to handle this file, it
10530 should just return nil to give other functions a chance. If it
10531 does handle the file, it must return the search string to be used
10532 when following the link. The search string will be part of the
10533 file link, given after a double colon, and `org-open-at-point'
10534 will automatically search for it. If special measures must be
10535 taken to make the search successful, another function should be
10536 added to the companion hook `org-execute-file-search-functions',
10539 A function in this hook may also use `setq' to set the variable
10540 `description' to provide a suggestion for the descriptive text to
10541 be used for this link when it gets inserted into an Org-mode
10542 buffer with \\[org-insert-link].")
10544 (defvar org-execute-file-search-functions nil
10545 "List of functions to execute a file search triggered by a link.
10547 Functions added to this hook must accept a single argument, the
10548 search string that was part of the file link, the part after the
10549 double colon. The function must first check if it would like to
10550 handle this search, for example by checking the `major-mode' or
10551 the file extension. If it decides not to handle this search, it
10552 should just return nil to give other functions a chance. If it
10553 does handle the search, it must return a non-nil value to keep
10554 other functions from trying.
10556 Each function can access the current prefix argument through the
10557 variable `current-prefix-arg'. Note that a single prefix is used
10558 to force opening a link in Emacs, so it may be good to only use a
10559 numeric or double prefix to guide the search function.
10561 In case this is needed, a function in this hook can also restore
10562 the window configuration before `org-open-at-point' was called using:
10564 (set-window-configuration org-window-config-before-follow-link)")
10566 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10567 (defun org-link-search (s &optional type avoid-pos stealth)
10568 "Search for a link search option.
10569 If S is surrounded by forward slashes, it is interpreted as a
10570 regular expression. In org-mode files, this will create an `org-occur'
10571 sparse tree. In ordinary files, `occur' will be used to list matches.
10572 If the current buffer is in `dired-mode', grep will be used to search
10573 in all files. If AVOID-POS is given, ignore matches near that position.
10575 When optional argument STEALTH is non-nil, do not modify
10576 visibility around point, thus ignoring
10577 `org-show-hierarchy-above', `org-show-following-heading' and
10578 `org-show-siblings' variables."
10579 (let ((case-fold-search t)
10580 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10581 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10582 (append '(("") (" ") ("\t") ("\n"))
10583 org-emphasis-alist)
10586 (pre nil) (post nil)
10587 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10589 ;; First check if there are any special search functions
10590 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10591 ;; Now try the builtin stuff
10592 ((and (equal (string-to-char s0) ?#)
10595 (goto-char (point-min))
10598 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10599 (setq type 'dedicated
10600 pos (match-beginning 0))))
10601 ;; There is an exact target for this
10603 (org-back-to-heading t)))
10605 (goto-char (point-min))
10608 (concat "<<" (regexp-quote s0) ">>") nil t)
10609 (setq type 'dedicated
10610 pos (match-beginning 0))))
10611 ;; There is an exact target for this
10614 (goto-char (point-min))
10617 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10618 (setq type 'dedicated pos (match-beginning 0))))
10619 ;; Found an invisible target.
10622 (goto-char (point-min))
10625 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10626 (setq type 'dedicated pos (match-beginning 0))))
10627 ;; Found an element with a matching #+name affiliated keyword.
10629 ((and (string-match "^(\\(.*\\))$" s0)
10631 (goto-char (point-min))
10634 (concat "[^[]" (regexp-quote
10635 (format org-coderef-label-format
10636 (match-string 1 s0))))
10638 (setq type 'dedicated
10639 pos (1+ (match-beginning 0))))))
10640 ;; There is a coderef target for this
10642 ((string-match "^/\\(.*\\)/$" s)
10643 ;; A regular expression
10645 ((derived-mode-p 'org-mode)
10646 (org-occur (match-string 1 s)))
10647 (t (org-do-occur (match-string 1 s)))))
10648 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10649 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10650 (goto-char (point-min))
10652 ((let (case-fold-search)
10653 (re-search-forward (format org-complex-heading-regexp-format
10656 ;; OK, found a match
10657 (setq type 'dedicated)
10658 (goto-char (match-beginning 0)))
10659 ((and (not org-link-search-inhibit-query)
10660 (eq org-link-search-must-match-exact-headline 'query-to-create)
10661 (y-or-n-p "No match - create this as a new heading? "))
10662 (goto-char (point-max))
10663 (or (bolp) (newline))
10664 (insert "* " s "\n")
10665 (beginning-of-line 0))
10668 (error "No match"))))
10670 ;; A normal search string
10671 (when (equal (string-to-char s) ?*)
10672 ;; Anchor on headlines, post may include tags.
10673 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10674 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10675 s (substring s 1)))
10676 (remove-text-properties
10678 '(face nil mouse-face nil keymap nil fontified nil) s)
10679 ;; Make a series of regular expressions to find a match
10680 (setq words (org-split-string s "[ \n\r\t]+")
10682 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10683 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10685 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10686 re2a (concat "[ \t\r\n]" re2a_)
10687 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10688 re4 (concat "[^a-zA-Z_]" re4_)
10690 re1 (concat pre re2 post)
10691 re3 (concat pre (if pre re4_ re4) post)
10692 re5 (concat pre ".*" re4)
10693 re2 (concat pre re2)
10694 re2a (concat pre (if pre re2a_ re2a))
10695 re4 (concat pre (if pre re4_ re4))
10696 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10697 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10701 ((eq type 'org-occur) (org-occur reall))
10702 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10703 (t (goto-char (point-min))
10705 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10706 (org-search-not-self 1 re1 nil t)
10707 (org-search-not-self 1 re2 nil t)
10708 (org-search-not-self 1 re2a nil t)
10709 (org-search-not-self 1 re3 nil t)
10710 (org-search-not-self 1 re4 nil t)
10711 (org-search-not-self 1 re5 nil t)
10713 (goto-char (match-beginning 1))
10715 (error "No match"))))))
10716 (and (derived-mode-p 'org-mode)
10718 (org-show-context 'link-search))
10721 (defun org-search-not-self (group &rest args)
10722 "Execute `re-search-forward', but only accept matches that do not
10723 enclose the position of `org-open-link-marker'."
10724 (let ((m org-open-link-marker))
10726 (while (apply 're-search-forward args)
10727 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10728 (goto-char (match-end group))
10729 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10730 (> (match-beginning 0) (marker-position m))
10731 (< (match-end 0) (marker-position m)))
10733 (or (not (org-in-regexp
10734 org-bracket-link-analytic-regexp 1))
10735 (not (match-end 4)) ; no description
10736 (and (<= (match-beginning 4) (point))
10737 (>= (match-end 4) (point))))))
10738 (throw 'exit (point))))))))
10740 (defun org-get-buffer-for-internal-link (buffer)
10741 "Return a buffer to be used for displaying the link target of internal links."
10743 ((not org-display-internal-link-with-indirect-buffer)
10745 ((string-match "(Clone)$" (buffer-name buffer))
10746 (message "Buffer is already a clone, not making another one")
10747 ;; we also do not modify visibility in this case
10749 (t ; make a new indirect buffer for displaying the link
10750 (let* ((bn (buffer-name buffer))
10751 (ibn (concat bn "(Clone)"))
10752 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10753 (with-current-buffer ib (org-overview))
10756 (defun org-do-occur (regexp &optional cleanup)
10757 "Call the Emacs command `occur'.
10758 If CLEANUP is non-nil, remove the printout of the regular expression
10759 in the *Occur* buffer. This is useful if the regex is long and not useful
10763 (let ((cwin (selected-window)) win beg end)
10764 (when (setq win (get-buffer-window "*Occur*"))
10765 (select-window win))
10766 (goto-char (point-min))
10767 (when (re-search-forward "match[a-z]+" nil t)
10768 (setq beg (match-end 0))
10769 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10770 (setq end (1- (match-beginning 0)))))
10771 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10772 (goto-char (point-min))
10773 (select-window cwin))))
10775 ;;; The mark ring for links jumps
10777 (defvar org-mark-ring nil
10778 "Mark ring for positions before jumps in Org-mode.")
10779 (defvar org-mark-ring-last-goto nil
10780 "Last position in the mark ring used to go back.")
10781 ;; Fill and close the ring
10782 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10783 (loop for i from 1 to org-mark-ring-length do
10784 (push (make-marker) org-mark-ring))
10785 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10788 (defun org-mark-ring-push (&optional pos buffer)
10789 "Put the current position or POS into the mark ring and rotate it."
10791 (setq pos (or pos (point)))
10792 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10793 (move-marker (car org-mark-ring)
10795 (or buffer (current-buffer)))
10797 (substitute-command-keys
10798 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10800 (defun org-mark-ring-goto (&optional n)
10801 "Jump to the previous position in the mark ring.
10802 With prefix arg N, jump back that many stored positions. When
10803 called several times in succession, walk through the entire ring.
10804 Org-mode commands jumping to a different position in the current file,
10805 or to another Org-mode file, automatically push the old position
10809 (if (eq last-command this-command)
10810 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10811 (setq p org-mark-ring))
10812 (setq org-mark-ring-last-goto p)
10814 (org-pop-to-buffer-same-window (marker-buffer m))
10816 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10818 (defun org-remove-angle-brackets (s)
10819 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10820 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10822 (defun org-add-angle-brackets (s)
10823 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10824 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10826 (defun org-remove-double-quotes (s)
10827 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10828 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10831 ;;; Following specific links
10833 (defun org-follow-timestamp-link ()
10834 "Open an agenda view for the time-stamp date/range at point."
10836 ((org-at-date-range-p t)
10837 (let ((org-agenda-start-on-weekday)
10838 (t1 (match-string 1))
10839 (t2 (match-string 2)) tt1 tt2)
10840 (setq tt1 (time-to-days (org-time-string-to-time t1))
10841 tt2 (time-to-days (org-time-string-to-time t2)))
10842 (let ((org-agenda-buffer-tmp-name
10843 (format "*Org Agenda(a:%s)"
10844 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10845 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10846 ((org-at-timestamp-p t)
10847 (let ((org-agenda-buffer-tmp-name
10848 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10849 (org-agenda-list nil (time-to-days (org-time-string-to-time
10850 (substring (match-string 1) 0 10)))
10852 (t (error "This should not happen"))))
10855 ;;; Following file links
10856 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10857 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10858 (declare-function mailcap-mime-info
10859 "mailcap" (string &optional request no-decode))
10860 (defvar org-wait nil)
10861 (defun org-open-file (path &optional in-emacs line search)
10862 "Open the file at PATH.
10863 First, this expands any special file name abbreviations. Then the
10864 configuration variable `org-file-apps' is checked if it contains an
10865 entry for this file type, and if yes, the corresponding command is launched.
10867 If no application is found, Emacs simply visits the file.
10869 With optional prefix argument IN-EMACS, Emacs will visit the file.
10870 With a double \\[universal-argument] \\[universal-argument] \
10871 prefix arg, Org tries to avoid opening in Emacs
10872 and to use an external application to visit the file.
10874 Optional LINE specifies a line to go to, optional SEARCH a string
10875 to search for. If LINE or SEARCH is given, the file will be
10876 opened in Emacs, unless an entry from org-file-apps that makes
10877 use of groups in a regexp matches.
10879 If you want to change the way frames are used when following a
10880 link, please customize `org-link-frame-setup'.
10882 If the file does not exist, an error is thrown."
10883 (let* ((file (if (equal path "")
10885 (substitute-in-file-name (expand-file-name path))))
10886 (file-apps (append org-file-apps (org-default-apps)))
10887 (apps (org-remove-if
10888 'org-file-apps-entry-match-against-dlink-p file-apps))
10889 (apps-dlink (org-remove-if-not
10890 'org-file-apps-entry-match-against-dlink-p file-apps))
10891 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10892 (dirp (if remp nil (file-directory-p file)))
10893 (file (if (and dirp org-open-directory-means-index-dot-org)
10894 (concat (file-name-as-directory file) "index.org")
10896 (a-m-a-p (assq 'auto-mode apps))
10897 (dfile (downcase file))
10898 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10899 (link (cond ((and (eq line nil)
10903 (concat file "::" (number-to-string line)))
10905 (concat file "::" search))))
10906 (dlink (downcase link))
10907 (old-buffer (current-buffer))
10909 (old-mode major-mode)
10910 ext cmd link-match-data)
10911 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10912 (setq ext (match-string 1 dfile))
10913 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10914 (setq ext (match-string 1 dfile))))
10916 ((member in-emacs '((16) system))
10917 (setq cmd (cdr (assoc 'system apps))))
10918 (in-emacs (setq cmd 'emacs))
10920 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10921 (and dirp (cdr (assoc 'directory apps)))
10922 ; first, try matching against apps-dlink
10923 ; if we get a match here, store the match data for later
10924 (let ((match (assoc-default dlink apps-dlink
10927 (progn (setq link-match-data (match-data))
10929 (progn (setq in-emacs (or in-emacs line search))
10930 nil))) ; if we have no match in apps-dlink,
10931 ; always open the file in emacs if line or search
10932 ; is given (for backwards compatibility)
10933 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10935 (cdr (assoc ext apps))
10936 (cdr (assoc t apps))))))
10937 (when (eq cmd 'system)
10938 (setq cmd (cdr (assoc 'system apps))))
10939 (when (eq cmd 'default)
10940 (setq cmd (cdr (assoc t apps))))
10941 (when (eq cmd 'mailcap)
10943 (mailcap-parse-mailcaps)
10944 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10945 (command (mailcap-mime-info mime-type)))
10946 (if (stringp command)
10948 (setq cmd 'emacs))))
10949 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10950 (not (file-exists-p file))
10951 (not org-open-non-existing-files))
10952 (error "No such file: %s" file))
10954 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10955 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10956 (while (string-match "['\"]%s['\"]" cmd)
10957 (setq cmd (replace-match "%s" t t cmd)))
10958 (while (string-match "%s" cmd)
10959 (setq cmd (replace-match
10961 (shell-quote-argument
10962 (convert-standard-filename file)))
10965 ;; Replace "%1", "%2" etc. in command with group matches from regex
10967 (let ((match-index 1)
10968 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10969 (set-match-data link-match-data)
10970 (while (<= match-index number-of-groups)
10971 (let ((regex (concat "%" (number-to-string match-index)))
10972 (replace-with (match-string match-index dlink)))
10973 (while (string-match regex cmd)
10974 (setq cmd (replace-match replace-with t t cmd))))
10975 (setq match-index (+ match-index 1)))))
10977 (save-window-excursion
10978 (message "Running %s...done" cmd)
10979 (start-process-shell-command cmd nil cmd)
10980 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10983 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10985 (if line (org-goto-line line)
10986 (if search (org-link-search search))))
10988 (let ((file (convert-standard-filename file)))
10990 (set-match-data link-match-data)
10992 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10993 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10994 (or (not (equal old-buffer (current-buffer)))
10995 (not (equal old-pos (point))))
10996 (org-mark-ring-push old-pos old-buffer))))
10998 (defun org-file-apps-entry-match-against-dlink-p (entry)
10999 "This function returns non-nil if `entry' uses a regular
11000 expression which should be matched against the whole link by
11003 It assumes that is the case when the entry uses a regular
11004 expression which has at least one grouping construct and the
11005 action is either a lisp form or a command string containing
11006 '%1', i.e. using at least one subexpression match as a
11008 (let ((selector (car entry))
11009 (action (cdr entry)))
11010 (if (stringp selector)
11011 (and (> (regexp-opt-depth selector) 0)
11012 (or (and (stringp action)
11013 (string-match "%[0-9]" action))
11017 (defun org-default-apps ()
11018 "Return the default applications for this operating system."
11020 ((eq system-type 'darwin)
11021 org-file-apps-defaults-macosx)
11022 ((eq system-type 'windows-nt)
11023 org-file-apps-defaults-windowsnt)
11024 (t org-file-apps-defaults-gnu)))
11026 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11027 "Convert extensions to regular expressions in the cars of LIST.
11028 Also, weed out any non-string entries, because the return value is used
11029 only for regexp matching.
11030 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11031 point to the symbol `emacs', indicating that the file should
11032 be opened in Emacs."
11035 (mapcar (lambda (x)
11036 (if (not (stringp (car x)))
11038 (if (string-match "\\W" (car x))
11040 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11043 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11045 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11046 (defun org-file-remote-p (file)
11047 "Test whether FILE specifies a location on a remote system.
11048 Return non-nil if the location is indeed remote.
11050 For example, the filename \"/user@host:/foo\" specifies a location
11051 on the system \"/user@host:\"."
11052 (cond ((fboundp 'file-remote-p)
11053 (file-remote-p file))
11054 ((fboundp 'tramp-handle-file-remote-p)
11055 (tramp-handle-file-remote-p file))
11056 ((and (boundp 'ange-ftp-name-format)
11057 (string-match (car ange-ftp-name-format) file))
11063 (defun org-get-org-file ()
11064 "Read a filename, with default directory `org-directory'."
11065 (let ((default (or org-default-notes-file remember-data-file)))
11066 (read-file-name (format "File name [%s]: " default)
11067 (file-name-as-directory org-directory)
11070 (defun org-notes-order-reversed-p ()
11071 "Check if the current file should receive notes in reversed order."
11073 ((not org-reverse-note-order) nil)
11074 ((eq t org-reverse-note-order) t)
11075 ((not (listp org-reverse-note-order)) nil)
11077 (let ((all org-reverse-note-order)
11079 (while (setq entry (pop all))
11080 (if (string-match (car entry) buffer-file-name)
11081 (throw 'exit (cdr entry))))
11084 (defvar org-refile-target-table nil
11085 "The list of refile targets, created by `org-refile'.")
11087 (defvar org-agenda-new-buffers nil
11088 "Buffers created to visit agenda files.")
11090 (defvar org-refile-cache nil
11091 "Cache for refile targets.")
11093 (defvar org-refile-markers nil
11094 "All the markers used for caching refile locations.")
11096 (defun org-refile-marker (pos)
11097 "Get a new refile marker, but only if caching is in use."
11098 (if (not org-refile-use-cache)
11100 (let ((m (make-marker)))
11101 (move-marker m pos)
11102 (push m org-refile-markers)
11105 (defun org-refile-cache-clear ()
11106 "Clear the refile cache and disable all the markers."
11107 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11108 (setq org-refile-markers nil)
11109 (setq org-refile-cache nil)
11110 (message "Refile cache has been cleared"))
11112 (defun org-refile-cache-check-set (set)
11113 "Check if all the markers in the cache still have live buffers."
11116 (while (and set (setq marker (nth 3 (pop set))))
11117 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11118 (when (and marker (null (marker-buffer marker)))
11119 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11121 (throw 'exit nil)))
11124 (defun org-refile-cache-put (set &rest identifiers)
11125 "Push the refile targets SET into the cache, under IDENTIFIERS."
11126 (let* ((key (sha1 (prin1-to-string identifiers)))
11127 (entry (assoc key org-refile-cache)))
11130 (push (cons key set) org-refile-cache))))
11132 (defun org-refile-cache-get (&rest identifiers)
11133 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11135 ((not org-refile-cache) nil)
11136 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11138 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11139 org-refile-cache))))
11140 (and set (org-refile-cache-check-set set) set)))))
11142 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11143 "Produce a table with refile targets."
11144 (let ((case-fold-search nil)
11145 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11146 (entries (or org-refile-targets '((nil . (:level . 1)))))
11147 targets tgs txt re files f desc descre fast-path-p level pos0)
11148 (message "Getting targets...")
11149 (with-current-buffer (or default-buffer (current-buffer))
11150 (while (setq entry (pop entries))
11151 (setq files (car entry) desc (cdr entry))
11152 (setq fast-path-p nil)
11154 ((null files) (setq files (list (current-buffer))))
11155 ((eq files 'org-agenda-files)
11156 (setq files (org-agenda-files 'unrestricted)))
11157 ((and (symbolp files) (fboundp files))
11158 (setq files (funcall files)))
11159 ((and (symbolp files) (boundp files))
11160 (setq files (symbol-value files))))
11161 (if (stringp files) (setq files (list files)))
11163 ((eq (car desc) :tag)
11164 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11165 ((eq (car desc) :todo)
11166 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11167 ((eq (car desc) :regexp)
11168 (setq descre (cdr desc)))
11169 ((eq (car desc) :level)
11170 (setq descre (concat "^\\*\\{" (number-to-string
11171 (if org-odd-levels-only
11172 (1- (* 2 (cdr desc)))
11175 ((eq (car desc) :maxlevel)
11176 (setq fast-path-p t)
11177 (setq descre (concat "^\\*\\{1," (number-to-string
11178 (if org-odd-levels-only
11179 (1- (* 2 (cdr desc)))
11182 (t (error "Bad refiling target description %s" desc)))
11183 (while (setq f (pop files))
11184 (with-current-buffer
11185 (if (bufferp f) f (org-get-agenda-file-buffer f))
11187 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11189 (if (bufferp f) (setq f (buffer-file-name
11190 (buffer-base-buffer f))))
11191 (setq f (and f (expand-file-name f)))
11192 (if (eq org-refile-use-outline-path 'file)
11193 (push (list (file-name-nondirectory f) f nil nil) tgs))
11197 (goto-char (point-min))
11198 (while (re-search-forward descre nil t)
11199 (goto-char (setq pos0 (point-at-bol)))
11201 (when org-refile-target-verify-function
11203 (or (funcall org-refile-target-verify-function)
11205 (when (and (looking-at org-complex-heading-regexp)
11206 (not (member (match-string 4) excluded-entries))
11208 (setq level (org-reduced-level
11209 (- (match-end 1) (match-beginning 1)))
11210 txt (org-link-display-format (match-string 4))
11211 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11212 re (format org-complex-heading-regexp-format
11213 (regexp-quote (match-string 4))))
11214 (when org-refile-use-outline-path
11215 (setq txt (mapconcat
11218 (if (eq org-refile-use-outline-path
11220 (list (file-name-nondirectory
11222 (buffer-base-buffer))))
11223 (if (eq org-refile-use-outline-path
11225 (list (buffer-file-name
11226 (buffer-base-buffer)))))
11227 (org-get-outline-path fast-path-p
11231 (push (list txt f re (org-refile-marker (point)))
11233 (when (= (point) pos0)
11234 ;; verification function has not moved point
11235 (goto-char (point-at-eol))))))))
11236 (when org-refile-use-cache
11237 (org-refile-cache-put tgs (buffer-file-name) descre))
11238 (setq targets (append tgs targets))
11240 (message "Getting targets...done")
11241 (nreverse targets)))
11243 (defun org-protect-slash (s)
11244 (while (string-match "/" s)
11245 (setq s (replace-match "\\" t t s)))
11248 (defvar org-olpa (make-vector 20 nil))
11250 (defun org-get-outline-path (&optional fastp level heading)
11251 "Return the outline path to the current entry, as a list.
11253 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11254 routine which makes outline path derivations for an entire file,
11255 avoiding backtracing. Refile target collection makes use of that."
11259 (error "Outline path failure, more than 19 levels"))
11260 (loop for i from level upto 19 do
11261 (aset org-olpa i nil))
11263 (delq nil (append org-olpa nil))
11264 (aset org-olpa level heading)))
11265 (let (rtn case-fold-search)
11269 (while (org-up-heading-safe)
11270 (when (looking-at org-complex-heading-regexp)
11271 (push (org-match-string-no-properties 4) rtn)))
11274 (defun org-format-outline-path (path &optional width prefix separator)
11275 "Format the outline path PATH for display.
11276 WIDTH is the maximum number of characters that is available.
11277 PREFIX is a prefix to be included in the returned string,
11278 such as the file name.
11279 SEPARATOR is inserted between the different parts of the path,
11280 the default is \"/\"."
11281 (setq width (or width 79))
11282 (if prefix (setq width (- width (length prefix))))
11285 (let* ((nsteps (length path))
11286 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11287 (maxwidth (if (<= total-width width)
11288 10000 ;; everything fits
11289 ;; we need to shorten the level headings
11290 (/ (- width nsteps) nsteps)))
11291 (org-odd-levels-only nil)
11293 (total (1+ (length prefix))))
11294 (setq maxwidth (max maxwidth 10))
11296 (if prefix (or separator "/"))
11300 (if (and (= n nsteps) (< maxwidth 10000))
11301 (setq maxwidth (- total-width total)))
11302 (if (< (length h) maxwidth)
11303 (progn (setq total (+ total (length h) 1)) h)
11304 (setq h (substring h 0 (- maxwidth 2))
11305 total (+ total maxwidth 1))
11306 (if (string-match "[ \t]+\\'" h)
11307 (setq h (substring h 0 (match-beginning 0))))
11308 (setq h (concat h "..")))
11309 (org-add-props h nil 'face
11310 (nth (% (1- n) org-n-level-faces)
11313 path (or separator "/"))))))
11315 (defun org-display-outline-path (&optional file current separator just-return-string)
11316 "Display the current outline path in the echo area.
11318 If FILE is non-nil, prepend the output with the file name.
11319 If CURRENT is non-nil, append the current heading to the output.
11320 SEPARATOR is passed through to `org-format-outline-path'. It separates
11321 the different parts of the path and defaults to \"/\".
11322 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11324 (let* (case-fold-search
11325 message-log-max ; Don't populate the *Messages* buffer
11326 (bfn (buffer-file-name (buffer-base-buffer)))
11327 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11329 (if current (setq path (append path
11331 (org-back-to-heading t)
11332 (if (looking-at org-complex-heading-regexp)
11333 (list (match-string 4)))))))
11335 (org-format-outline-path
11338 (and file bfn (concat (file-name-nondirectory bfn) separator))
11340 (if just-return-string
11341 (org-no-properties res)
11342 (message "%s" res))))
11344 (defvar org-refile-history nil
11345 "History for refiling operations.")
11347 (defvar org-after-refile-insert-hook nil
11348 "Hook run after `org-refile' has inserted its stuff at the new location.
11349 Note that this is still *before* the stuff will be removed from
11350 the *old* location.")
11352 (defvar org-capture-last-stored-marker)
11353 (defvar org-refile-keep nil
11354 "Non-nil means `org-refile' will copy instead of refile.")
11357 "Like `org-refile', but copy."
11359 (let ((org-refile-keep t))
11360 (funcall 'org-refile nil nil nil "Copy")))
11362 (defun org-refile (&optional goto default-buffer rfloc msg)
11363 "Move the entry or entries at point to another heading.
11364 The list of target headings is compiled using the information in
11365 `org-refile-targets', which see.
11367 At the target location, the entry is filed as a subitem of the target
11368 heading. Depending on `org-reverse-note-order', the new subitem will
11369 either be the first or the last subitem.
11371 If there is an active region, all entries in that region will be moved.
11372 However, the region must fulfill the requirement that the first heading
11373 is the first one sets the top-level of the moved text - at most siblings
11374 below it are allowed.
11376 With prefix arg GOTO, the command will only visit the target location
11377 and not actually move anything.
11379 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11380 go to the location where the last refiling operation has put the subtree.
11381 With a prefix argument of `2', refile to the running clock.
11383 RFLOC can be a refile location obtained in a different way.
11385 MSG is a string to replace \"Refile\" in the default prompt with
11386 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11388 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11390 If you are using target caching (see `org-refile-use-cache'),
11391 you have to clear the target cache in order to find new targets.
11392 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11393 prefix argument (`C-u C-u C-u C-c C-w')."
11396 (if (member goto '(0 (64)))
11397 (org-refile-cache-clear)
11398 (let* ((actionmsg (or msg "Refile"))
11399 (cbuf (current-buffer))
11400 (regionp (org-region-active-p))
11401 (region-start (and regionp (region-beginning)))
11402 (region-end (and regionp (region-end)))
11403 (region-length (and regionp (- region-end region-start)))
11404 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11405 pos it nbuf file re level reversed)
11406 (setq last-command nil)
11408 (goto-char region-start)
11409 (or (bolp) (goto-char (point-at-bol)))
11410 (setq region-start (point))
11411 (unless (or (org-kill-is-subtree-p
11412 (buffer-substring region-start region-end))
11413 (prog1 org-refile-active-region-within-subtree
11414 (org-toggle-heading)))
11415 (error "The region is not a (sequence of) subtree(s)")))
11416 (if (equal goto '(16))
11417 (org-refile-goto-last-stored)
11419 (and (equal goto 2)
11420 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11422 (setq it (list (or org-clock-heading "running clock")
11424 (marker-buffer org-clock-hd-marker))
11426 (marker-position org-clock-hd-marker)))
11429 (let (heading-text)
11432 (org-back-to-heading t)
11434 (nth 4 (org-heading-components))))
11436 (org-refile-get-location
11437 (cond (goto "Goto")
11438 (regionp (concat actionmsg " region to"))
11439 (t (concat actionmsg " subtree \""
11440 heading-text "\" to")))
11442 (and (not (equal '(4) goto))
11443 org-refile-allow-creating-parent-nodes)
11445 (setq file (nth 1 it)
11448 (if (and (not goto)
11450 (equal (buffer-file-name) file)
11452 (and (>= pos region-start)
11453 (<= pos region-end))
11454 (and (>= pos (point))
11455 (< pos (save-excursion
11456 (org-end-of-subtree t t))))))
11457 (error "Cannot refile to position inside the tree or region"))
11459 (setq nbuf (or (find-buffer-visiting file)
11460 (find-file-noselect file)))
11463 (org-pop-to-buffer-same-window nbuf)
11465 (org-show-context 'org-goto))
11468 (org-kill-new (buffer-substring region-start region-end))
11469 (org-save-markers-in-region region-start region-end))
11470 (org-copy-subtree 1 nil t))
11471 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11472 (find-file-noselect file)))
11473 (setq reversed (org-notes-order-reversed-p))
11480 (looking-at org-outline-regexp)
11481 (setq level (org-get-valid-level (funcall outline-level) 1))
11484 (or (outline-next-heading) (point-max))
11485 (or (save-excursion (org-get-next-sibling))
11486 (org-end-of-subtree t t)
11490 (goto-char (point-max))
11491 (goto-char (point-min))
11492 (or (outline-next-heading) (goto-char (point-max)))))
11493 (if (not (bolp)) (newline))
11494 (org-paste-subtree level)
11495 (when org-log-refile
11496 (org-add-log-setup 'refile nil nil 'findpos
11498 (unless (eq org-log-refile 'note)
11499 (save-excursion (org-add-log-note))))
11500 (and org-auto-align-tags
11501 (let ((org-loop-over-headlines-in-active-region nil))
11502 (org-set-tags nil t)))
11503 (with-demoted-errors
11504 (bookmark-set "org-refile-last-stored"))
11505 ;; If we are refiling for capture, make sure that the
11506 ;; last-capture pointers point here
11507 (when (org-bound-and-true-p org-refile-for-capture)
11508 (with-demoted-errors
11509 (bookmark-set "org-capture-last-stored-marker"))
11510 (move-marker org-capture-last-stored-marker (point)))
11511 (if (fboundp 'deactivate-mark) (deactivate-mark))
11512 (run-hooks 'org-after-refile-insert-hook))))
11513 (unless org-refile-keep
11515 (delete-region (point) (+ (point) region-length))
11516 (org-cut-subtree)))
11517 (when (featurep 'org-inlinetask)
11518 (org-inlinetask-remove-END-maybe))
11519 (setq org-markers-to-move nil)
11520 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11522 (defun org-refile-goto-last-stored ()
11523 "Go to the location where the last refile was stored."
11525 (bookmark-jump "org-refile-last-stored")
11526 (message "This is the location of the last refile"))
11528 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11530 "Prompt the user for a refile location, using PROMPT.
11531 PROMPT should not be suffixed with a colon and a space, because
11532 this function appends the default value from
11533 `org-refile-history' automatically, if that is not empty.
11534 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11535 this is used for the GOTO interface."
11536 (let ((org-refile-targets org-refile-targets)
11537 (org-refile-use-outline-path org-refile-use-outline-path)
11539 (when (and (derived-mode-p 'org-mode)
11540 (not org-refile-use-cache)
11544 (setq excluded-entries
11545 (append excluded-entries (list (org-get-heading t t)))))))
11546 (setq org-refile-target-table
11547 (org-refile-get-targets default-buffer excluded-entries)))
11548 (unless org-refile-target-table
11549 (error "No refile targets"))
11550 (let* ((cbuf (current-buffer))
11551 (partial-completion-mode nil)
11552 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11553 (cfunc (if (and org-refile-use-outline-path
11554 org-outline-path-complete-in-steps)
11555 'org-olpath-completing-read
11556 'org-icompleting-read))
11557 (extra (if org-refile-use-outline-path "/" ""))
11558 (cbnex (concat (buffer-name) extra))
11559 (filename (and cfn (expand-file-name cfn)))
11562 (if (and (not (member org-refile-use-outline-path
11563 '(file full-file-path)))
11564 (not (equal filename (nth 1 x))))
11565 (cons (concat (car x) extra " ("
11566 (file-name-nondirectory (nth 1 x)) ")")
11568 (cons (concat (car x) extra) (cdr x))))
11569 org-refile-target-table))
11570 (completion-ignore-case t)
11572 (prompt (concat prompt
11573 (or (and (car org-refile-history)
11574 (concat " (default " (car org-refile-history) ")"))
11575 (and (assoc cbnex tbl) (setq cdef cbnex)
11576 (concat " (default " cbnex ")"))) ": "))
11577 pa answ parent-target child parent old-hist)
11578 (setq old-hist org-refile-history)
11579 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11580 nil 'org-refile-history (or cdef (car org-refile-history))))
11581 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11582 (org-refile-check-position pa)
11585 (when (or (not org-refile-history)
11586 (not (eq old-hist org-refile-history))
11587 (not (equal (car pa) (car org-refile-history))))
11588 (setq org-refile-history
11589 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11591 (cdr org-refile-history))))
11592 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11593 (pop org-refile-history)))
11595 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11597 (setq parent (match-string 1 answ)
11598 child (match-string 2 answ))
11599 (setq parent-target (or (assoc parent tbl)
11600 (assoc (concat parent "/") tbl)))
11601 (when (and parent-target
11602 (or (eq new-nodes t)
11603 (and (eq new-nodes 'confirm)
11604 (y-or-n-p (format "Create new node \"%s\"? "
11606 (org-refile-new-child parent-target child)))
11607 (error "Invalid target location")))))
11609 (declare-function org-string-nw-p "org-macs" (s))
11610 (defun org-refile-check-position (refile-pointer)
11611 "Check if the refile pointer matches the headline to which it points."
11612 (let* ((file (nth 1 refile-pointer))
11613 (re (nth 2 refile-pointer))
11614 (pos (nth 3 refile-pointer))
11616 (if (and (not (markerp pos)) (not file))
11617 (error "Please save the buffer to a file before refiling")
11618 (when (org-string-nw-p re)
11619 (setq buffer (if (markerp pos)
11620 (marker-buffer pos)
11621 (or (find-buffer-visiting file)
11622 (find-file-noselect file))))
11623 (with-current-buffer buffer
11628 (beginning-of-line 1)
11629 (unless (org-looking-at-p re)
11630 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11632 (defun org-refile-new-child (parent-target child)
11633 "Use refile target PARENT-TARGET to add new CHILD below it."
11634 (unless parent-target
11635 (error "Cannot find parent for new node"))
11636 (let ((file (nth 1 parent-target))
11637 (pos (nth 3 parent-target))
11639 (with-current-buffer (or (find-buffer-visiting file)
11640 (find-file-noselect file))
11646 (goto-char (point-max))
11647 (if (not (bolp)) (newline)))
11648 (when (looking-at org-outline-regexp)
11649 (setq level (funcall outline-level))
11650 (org-end-of-subtree t t))
11651 (org-back-over-empty-lines)
11652 (insert "\n" (make-string
11653 (if pos (org-get-valid-level level 1) 1) ?*)
11655 (beginning-of-line 0)
11656 (list (concat (car parent-target) "/" child) file "" (point)))))))
11658 (defun org-olpath-completing-read (prompt collection &rest args)
11659 "Read an outline path like a file name."
11660 (let ((thetable collection)
11661 (org-completion-use-ido nil) ; does not work with ido.
11662 (org-completion-use-iswitchb nil)) ; or iswitchb
11664 'org-icompleting-read prompt
11665 (lambda (string predicate &optional flag)
11666 (let (rtn r f (l (length string)))
11670 (try-completion string thetable))
11673 (setq rtn (all-completions string thetable predicate))
11676 (setq r (substring x l))
11677 (if (string-match " ([^)]*)$" x)
11678 (setq f (match-string 0 x))
11680 (if (string-match "/" r)
11681 (concat string (substring r 0 (match-end 0)) f)
11686 (assoc string thetable)))))
11689 ;;;; Dynamic blocks
11691 (defun org-find-dblock (name)
11692 "Find the first dynamic block with name NAME in the buffer.
11693 If not found, stay at current position and return nil."
11694 (let ((case-fold-search t) pos)
11696 (goto-char (point-min))
11697 (setq pos (and (re-search-forward
11698 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11699 (match-beginning 0))))
11700 (if pos (goto-char pos))
11703 (defconst org-dblock-start-re
11704 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11705 "Matches the start line of a dynamic block, with parameters.")
11707 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11708 "Matches the end of a dynamic block.")
11710 (defun org-create-dblock (plist)
11711 "Create a dynamic block section, with parameters taken from PLIST.
11712 PLIST must contain a :name entry which is used as name of the block."
11713 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11716 (let ((col (current-column))
11717 (name (plist-get plist :name)))
11718 (insert "#+BEGIN: " name)
11720 (if (eq (car plist) :name)
11721 (setq plist (cddr plist))
11722 (insert " " (prin1-to-string (pop plist)))))
11723 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11724 (beginning-of-line -2)))
11726 (defun org-prepare-dblock ()
11727 "Prepare dynamic block for refresh.
11728 This empties the block, puts the cursor at the insert position and returns
11729 the property list including an extra property :name with the block name."
11730 (unless (looking-at org-dblock-start-re)
11731 (error "Not at a dynamic block"))
11732 (let* ((begdel (1+ (match-end 0)))
11733 (name (org-no-properties (match-string 1)))
11734 (params (append (list :name name)
11735 (read (concat "(" (match-string 3) ")")))))
11737 (beginning-of-line 1)
11738 (skip-chars-forward " \t")
11739 (setq params (plist-put params :indentation-column (current-column))))
11740 (unless (re-search-forward org-dblock-end-re nil t)
11741 (error "Dynamic block not terminated"))
11744 (list :content (buffer-substring
11745 begdel (match-beginning 0)))))
11746 (delete-region begdel (match-beginning 0))
11751 (defun org-map-dblocks (&optional command)
11752 "Apply COMMAND to all dynamic blocks in the current buffer.
11753 If COMMAND is not given, use `org-update-dblock'."
11754 (let ((cmd (or command 'org-update-dblock)))
11756 (goto-char (point-min))
11757 (while (re-search-forward org-dblock-start-re nil t)
11758 (goto-char (match-beginning 0))
11760 (condition-case nil
11762 (error (message "Error during update of dynamic block"))))
11763 (unless (re-search-forward org-dblock-end-re nil t)
11764 (error "Dynamic block not terminated"))))))
11766 (defun org-dblock-update (&optional arg)
11767 "User command for updating dynamic blocks.
11768 Update the dynamic block at point. With prefix ARG, update all dynamic
11769 blocks in the buffer."
11772 (org-update-all-dblocks)
11773 (or (looking-at org-dblock-start-re)
11774 (org-beginning-of-dblock))
11775 (org-update-dblock)))
11777 (defun org-update-dblock ()
11778 "Update the dynamic block at point.
11779 This means to empty the block, parse for parameters and then call
11780 the correct writing function."
11782 (save-window-excursion
11783 (let* ((pos (point))
11784 (line (org-current-line))
11785 (params (org-prepare-dblock))
11786 (name (plist-get params :name))
11787 (indent (plist-get params :indentation-column))
11788 (cmd (intern (concat "org-dblock-write:" name))))
11789 (message "Updating dynamic block `%s' at line %d..." name line)
11790 (funcall cmd params)
11791 (message "Updating dynamic block `%s' at line %d...done" name line)
11793 (when (and indent (> indent 0))
11794 (setq indent (make-string indent ?\ ))
11796 (org-beginning-of-dblock)
11798 (while (not (looking-at org-dblock-end-re))
11800 (beginning-of-line 2))
11801 (when (looking-at org-dblock-end-re)
11802 (and (looking-at "[ \t]+")
11803 (replace-match ""))
11804 (insert indent)))))))
11806 (defun org-beginning-of-dblock ()
11807 "Find the beginning of the dynamic block at point.
11808 Error if there is no such block at point."
11809 (let ((pos (point))
11812 (if (and (re-search-backward org-dblock-start-re nil t)
11813 (setq beg (match-beginning 0))
11814 (re-search-forward org-dblock-end-re nil t)
11815 (> (match-end 0) pos))
11818 (error "Not in a dynamic block"))))
11820 (defun org-update-all-dblocks ()
11821 "Update all dynamic blocks in the buffer.
11822 This function can be used in a hook."
11824 (when (derived-mode-p 'org-mode)
11825 (org-map-dblocks 'org-update-dblock)))
11830 (defun org-get-export-keywords ()
11831 "Return a list of all currently understood export keywords.
11832 Export keywords include options, block names, attributes and
11833 keywords relative to each registered export back-end."
11838 (let ((props (cdr back-end)))
11839 ;; Back-end name (for keywords, like #+LATEX:)
11840 (push (upcase (symbol-name (car back-end))) keywords)
11841 ;; Back-end options.
11842 (mapc (lambda (option) (push (cadr option) keywords))
11843 (plist-get (cdr back-end) :options-alist))))
11844 (org-bound-and-true-p org-export-registered-backends))
11847 (defconst org-options-keywords
11848 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11849 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11850 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11851 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11852 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11854 (defcustom org-structure-template-alist
11855 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11856 "<src lang=\"?\">\n\n</src>")
11857 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11858 "<example>\n?\n</example>")
11859 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11860 "<quote>\n?\n</quote>")
11861 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11862 "<verse>\n?\n</verse>")
11863 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11864 "<verbatim>\n?\n</verbatim>")
11865 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11866 "<center>\n?\n</center>")
11867 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11868 "<literal style=\"latex\">\n?\n</literal>")
11870 "<literal style=\"latex\">?</literal>")
11871 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11872 "<literal style=\"html\">\n?\n</literal>")
11874 "<literal style=\"html\">?</literal>")
11875 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11879 ("I" "#+INCLUDE: %file ?"
11880 "<include file=%file markup=\"?\">"))
11881 "Structure completion elements.
11882 This is a list of abbreviation keys and values. The value gets inserted
11883 if you type `<' followed by the key and then press the completion key,
11884 usually `M-TAB'. %file will be replaced by a file name after prompting
11885 for the file using completion. The cursor will be placed at the position
11886 of the `?` in the template.
11887 There are two templates for each key, the first uses the original Org syntax,
11888 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11889 the default when the /org-mtags.el/ module has been loaded. See also the
11890 variable `org-mtags-prefer-muse-templates'."
11891 :group 'org-completion
11893 (string :tag "Key")
11894 (string :tag "Template")
11895 (string :tag "Muse Template")))
11897 (defun org-try-structure-completion ()
11898 "Try to complete a structure template before point.
11899 This looks for strings like \"<e\" on an otherwise empty line and
11901 (let ((l (buffer-substring (point-at-bol) (point)))
11903 (when (and (looking-at "[ \t]*$")
11904 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11905 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11906 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11907 (match-beginning 1)) a)
11910 (defun org-complete-expand-structure-template (start cell)
11911 "Expand a structure template."
11912 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11913 (rpl (nth (if musep 2 1) cell))
11915 (delete-region start (point))
11916 (when (string-match "\\`#\\+" rpl)
11919 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11920 (setq ind (buffer-substring (point-at-bol) (point))))
11922 (setq start (point))
11923 (if (string-match "%file" rpl)
11924 (setq rpl (replace-match
11928 (abbreviate-file-name (read-file-name "Include file: ")))
11931 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11932 (concat "\n" ind)))
11934 (if (re-search-backward "\\?" start t) (delete-char 1))))
11936 ;;;; TODO, DEADLINE, Comments
11938 (defun org-toggle-comment ()
11939 "Change the COMMENT state of an entry."
11942 (org-back-to-heading)
11943 (let (case-fold-search)
11945 ((looking-at (format org-heading-keyword-regexp-format
11946 org-comment-string))
11947 (goto-char (match-end 1))
11948 (looking-at (concat " +" org-comment-string))
11949 (replace-match "" t t)
11950 (when (eolp) (insert " ")))
11951 ((looking-at org-outline-regexp)
11952 (goto-char (match-end 0))
11953 (insert org-comment-string " "))))))
11955 (defvar org-last-todo-state-is-todo nil
11956 "This is non-nil when the last TODO state change led to a TODO state.
11957 If the last change removed the TODO tag or switched to DONE, then
11960 (defvar org-setting-tags nil) ; dynamically skipped
11962 (defvar org-todo-setup-filter-hook nil
11963 "Hook for functions that pre-filter todo specs.
11964 Each function takes a todo spec and returns either nil or the spec
11965 transformed into canonical form." )
11967 (defvar org-todo-get-default-hook nil
11968 "Hook for functions that get a default item for todo.
11969 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11970 nil or a string to be used for the todo mark." )
11972 (defvar org-agenda-headline-snapshot-before-repeat)
11974 (defun org-current-effective-time ()
11975 "Return current time adjusted for `org-extend-today-until' variable."
11976 (let* ((ct (org-current-time))
11977 (dct (decode-time ct))
11980 (org-use-last-clock-out-time-as-effective-time
11981 (or (org-clock-get-last-clock-out-time) ct))
11982 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11983 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11987 (defun org-todo-yesterday (&optional arg)
11988 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11990 (if (eq major-mode 'org-agenda-mode)
11991 (apply 'org-agenda-todo-yesterday arg)
11992 (let* ((hour (third (decode-time
11993 (org-current-time))))
11994 (org-extend-today-until (1+ hour)))
11997 (defvar org-block-entry-blocking ""
11998 "First entry preventing the TODO state change.")
12000 (defun org-todo (&optional arg)
12001 "Change the TODO state of an item.
12002 The state of an item is given by a keyword at the start of the heading,
12004 *** TODO Write paper
12007 The different keywords are specified in the variable `org-todo-keywords'.
12008 By default the available states are \"TODO\" and \"DONE\".
12009 So for this example: when the item starts with TODO, it is changed to DONE.
12010 When it starts with DONE, the DONE is removed. And when neither TODO nor
12011 DONE are present, add TODO at the beginning of the heading.
12013 With \\[universal-argument] prefix arg, use completion to determine the new \
12015 With numeric prefix arg, switch to that state.
12016 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12017 keywords (nextset).
12018 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12019 With a numeric prefix arg of 0, inhibit note taking for the change.
12021 For calling through lisp, arg is also interpreted in the following way:
12022 'none -> empty state
12023 \"\"(empty string) -> switch to empty state
12024 'done -> switch to DONE
12025 'nextset -> switch to the next set of keywords
12026 'previousset -> switch to the previous set of keywords
12027 \"WAITING\" -> switch to the specified keyword, but only if it
12028 really is a member of `org-todo-keywords'."
12030 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12031 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12032 'region-start-level 'region))
12033 org-loop-over-headlines-in-active-region)
12036 org-loop-over-headlines-in-active-region
12037 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12038 (if (equal arg '(16)) (setq arg 'nextset))
12039 (let ((org-blocker-hook org-blocker-hook)
12042 (when (equal arg '(64))
12043 (setq arg nil org-blocker-hook nil))
12044 (when (and org-blocker-hook
12045 (or org-inhibit-blocking
12046 (org-entry-get nil "NOBLOCKING")))
12047 (setq org-blocker-hook nil))
12050 (org-back-to-heading t)
12051 (when (looking-at (concat "^\\*+ " org-comment-string))
12052 (org-toggle-comment)
12054 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12055 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12056 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12057 (let* ((match-data (match-data))
12058 (startpos (point-at-bol))
12059 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12060 (org-log-done org-log-done)
12061 (org-log-repeat org-log-repeat)
12062 (org-todo-log-states org-todo-log-states)
12063 (org-inhibit-logging
12065 (progn (setq arg nil) 'note) org-inhibit-logging))
12066 (this (match-string 1))
12067 (hl-pos (match-beginning 0))
12068 (head (org-get-todo-sequence-head this))
12069 (ass (assoc head org-todo-kwd-alist))
12070 (interpret (nth 1 ass))
12071 (done-word (nth 3 ass))
12072 (final-done-word (nth 4 ass))
12073 (org-last-state (or this ""))
12074 (completion-ignore-case t)
12075 (member (member this org-todo-keywords-1))
12076 (tail (cdr member))
12078 ((and org-todo-key-trigger
12079 (or (and (equal arg '(4))
12080 (eq org-use-fast-todo-selection 'prefix))
12081 (and (not arg) org-use-fast-todo-selection
12082 (not (eq org-use-fast-todo-selection
12084 ;; Use fast selection
12085 (org-fast-todo-selection))
12086 ((and (equal arg '(4))
12087 (or (not org-use-fast-todo-selection)
12088 (not org-todo-key-trigger)))
12089 ;; Read a state with completion
12090 (org-icompleting-read
12091 "State: " (mapcar 'list org-todo-keywords-1)
12095 (if tail (car tail) nil)
12096 (car org-todo-keywords-1)))
12098 (if (equal member org-todo-keywords-1)
12101 (nth (- (length org-todo-keywords-1)
12103 org-todo-keywords-1)
12104 (org-last org-todo-keywords-1))))
12105 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12106 (setq arg nil))) ; hack to fall back to cycling
12108 ;; user or caller requests a specific state
12110 ((equal arg "") nil)
12111 ((eq arg 'none) nil)
12112 ((eq arg 'done) (or done-word (car org-done-keywords)))
12114 (or (car (cdr (member head org-todo-heads)))
12115 (car org-todo-heads)))
12116 ((eq arg 'previousset)
12117 (let ((org-todo-heads (reverse org-todo-heads)))
12118 (or (car (cdr (member head org-todo-heads)))
12119 (car org-todo-heads))))
12120 ((car (member arg org-todo-keywords-1)))
12122 (error "State `%s' not valid in this file" arg))
12123 ((nth (1- (prefix-numeric-value arg))
12124 org-todo-keywords-1))))
12125 ((null member) (or head (car org-todo-keywords-1)))
12126 ((equal this final-done-word) nil) ;; -> make empty
12127 ((null tail) nil) ;; -> first entry
12128 ((memq interpret '(type priority))
12129 (if (eq this-command last-command)
12131 (if (> (length tail) 0)
12132 (or done-word (car org-done-keywords))
12137 (run-hook-with-args-until-success
12138 'org-todo-get-default-hook org-state org-last-state)
12140 (next (if org-state (concat " " org-state " ") " "))
12141 (change-plist (list :type 'todo-state-change :from this :to org-state
12142 :position startpos))
12144 (when org-blocker-hook
12145 (setq org-last-todo-state-is-todo
12146 (not (member this org-done-keywords)))
12147 (unless (save-excursion
12149 (org-with-wide-buffer
12150 (run-hook-with-args-until-failure
12151 'org-blocker-hook change-plist))))
12152 (if (org-called-interactively-p 'interactive)
12153 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12154 this org-state org-block-entry-blocking)
12156 (message "TODO state change from %s to %s blocked (by \"%s\")"
12157 this org-state org-block-entry-blocking)
12158 (throw 'exit nil))))
12159 (store-match-data match-data)
12160 (replace-match next t t)
12161 (unless (pos-visible-in-window-p hl-pos)
12162 (message "TODO state changed to %s" (org-trim next)))
12164 (setq head (org-get-todo-sequence-head org-state)
12165 ass (assoc head org-todo-kwd-alist)
12166 interpret (nth 1 ass)
12167 done-word (nth 3 ass)
12168 final-done-word (nth 4 ass)))
12169 (when (memq arg '(nextset previousset))
12170 (message "Keyword-Set %d/%d: %s"
12171 (- (length org-todo-sets) -1
12172 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12173 (length org-todo-sets)
12174 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12175 (setq org-last-todo-state-is-todo
12176 (not (member org-state org-done-keywords)))
12177 (setq now-done-p (and (member org-state org-done-keywords)
12178 (not (member this org-done-keywords))))
12179 (and logging (org-local-logging logging))
12180 (when (and (or org-todo-log-states org-log-done)
12181 (not (eq org-inhibit-logging t))
12182 (not (memq arg '(nextset previousset))))
12183 ;; we need to look at recording a time and note
12184 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12185 (nth 2 (assoc this org-todo-log-states))))
12186 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12187 (setq dolog 'time))
12188 (when (and org-state
12189 (member org-state org-not-done-keywords)
12190 (not (member this org-not-done-keywords)))
12191 ;; This is now a todo state and was not one before
12192 ;; If there was a CLOSED time stamp, get rid of it.
12193 (org-add-planning-info nil nil 'closed))
12194 (when (and now-done-p org-log-done)
12195 ;; It is now done, and it was not done before
12196 (org-add-planning-info 'closed (org-current-effective-time))
12197 (if (and (not dolog) (eq 'note org-log-done))
12198 (org-add-log-setup 'done org-state this 'findpos 'note)))
12199 (when (and org-state dolog)
12200 ;; This is a non-nil state, and we need to log it
12201 (org-add-log-setup 'state org-state this 'findpos dolog)))
12202 ;; Fixup tag positioning
12203 (org-todo-trigger-tag-changes org-state)
12204 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12205 (when org-provide-todo-statistics
12206 (org-update-parent-todo-statistics))
12207 (run-hooks 'org-after-todo-state-change-hook)
12208 (if (and arg (not (member org-state org-done-keywords)))
12209 (setq head (org-get-todo-sequence-head org-state)))
12210 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12211 ;; Do we need to trigger a repeat?
12213 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12214 ;; This is for the agenda, take a snapshot of the headline.
12216 (setq org-agenda-headline-snapshot-before-repeat
12217 (org-get-heading))))
12218 (org-auto-repeat-maybe org-state))
12219 ;; Fixup cursor location if close to the keyword
12220 (if (and (outline-on-heading-p)
12222 (save-excursion (beginning-of-line 1)
12223 (looking-at org-todo-line-regexp))
12224 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12226 (goto-char (or (match-end 2) (match-end 1)))
12227 (and (looking-at " ") (just-one-space))))
12228 (when org-trigger-hook
12230 (run-hook-with-args 'org-trigger-hook change-plist)))
12231 (when commentp (org-toggle-comment))))))))
12233 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12234 "Block turning an entry into a TODO, using the hierarchy.
12235 This checks whether the current task should be blocked from state
12236 changes. Such blocking occurs when:
12238 1. The task has children which are not all in a completed state.
12240 2. A task has a parent with the property :ORDERED:, and there
12241 are siblings prior to the current task with incomplete
12244 3. The parent of the task is blocked because it has siblings that should
12245 be done first, or is child of a block grandparent TODO entry."
12247 (if (not org-enforce-todo-dependencies)
12248 t ; if locally turned off don't block
12250 ;; If this is not a todo state change, or if this entry is already DONE,
12252 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12253 (member (plist-get change-plist :from)
12254 (cons 'done org-done-keywords))
12255 (member (plist-get change-plist :to)
12256 (cons 'todo org-not-done-keywords))
12257 (not (plist-get change-plist :to)))
12258 (throw 'dont-block t))
12259 ;; If this task has children, and any are undone, it's blocked
12261 (org-back-to-heading t)
12262 (let ((this-level (funcall outline-level)))
12263 (outline-next-heading)
12264 (let ((child-level (funcall outline-level)))
12265 (while (and (not (eobp))
12266 (> child-level this-level))
12267 ;; this todo has children, check whether they are all
12269 (if (and (not (org-entry-is-done-p))
12270 (org-entry-is-todo-p))
12271 (progn (setq org-block-entry-blocking (org-get-heading))
12272 (throw 'dont-block nil)))
12273 (outline-next-heading)
12274 (setq child-level (funcall outline-level))))))
12275 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12276 ;; any previous siblings are undone, it's blocked
12278 (org-back-to-heading t)
12279 (let* ((pos (point))
12280 (parent-pos (and (org-up-heading-safe) (point))))
12281 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12282 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12284 (re-search-forward org-not-done-heading-regexp pos t))
12285 (setq org-block-entry-blocking (match-string 0))
12286 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12287 ;; Search further up the hierarchy, to see if an ancestor is blocked
12289 (goto-char parent-pos)
12290 (if (not (looking-at org-not-done-heading-regexp))
12291 (throw 'dont-block t)) ; do not block, parent is not a TODO
12293 (setq parent-pos (and (org-up-heading-safe) (point)))
12294 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12295 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12297 (re-search-forward org-not-done-heading-regexp pos t)
12298 (setq org-block-entry-blocking (org-get-heading)))
12299 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12301 (defcustom org-track-ordered-property-with-tag nil
12302 "Should the ORDERED property also be shown as a tag?
12303 The ORDERED property decides if an entry should require subtasks to be
12304 completed in sequence. Since a property is not very visible, setting
12305 this option means that toggling the ORDERED property with the command
12306 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12307 not relevant for the behavior, but it makes things more visible.
12309 Note that toggling the tag with tags commands will not change the property
12310 and therefore not influence behavior!
12312 This can be t, meaning the tag ORDERED should be used, It can also be a
12313 string to select a different tag for this task."
12316 (const :tag "No tracking" nil)
12317 (const :tag "Track with ORDERED tag" t)
12318 (string :tag "Use other tag")))
12320 (defun org-toggle-ordered-property ()
12321 "Toggle the ORDERED property of the current entry.
12322 For better visibility, you can track the value of this property with a tag.
12323 See variable `org-track-ordered-property-with-tag'."
12325 (let* ((t1 org-track-ordered-property-with-tag)
12326 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12328 (org-back-to-heading)
12329 (if (org-entry-get nil "ORDERED")
12331 (org-delete-property "ORDERED" "PROPERTIES")
12332 (and tag (org-toggle-tag tag 'off))
12333 (message "Subtasks can be completed in arbitrary order"))
12334 (org-entry-put nil "ORDERED" "t")
12335 (and tag (org-toggle-tag tag 'on))
12336 (message "Subtasks must be completed in sequence")))))
12338 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12339 (defun org-block-todo-from-checkboxes (change-plist)
12340 "Block turning an entry into a TODO, using checkboxes.
12341 This checks whether the current task should be blocked from state
12342 changes because there are unchecked boxes in this entry."
12343 (if (not org-enforce-todo-checkbox-dependencies)
12344 t ; if locally turned off don't block
12346 ;; If this is not a todo state change, or if this entry is already DONE,
12348 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12349 (member (plist-get change-plist :from)
12350 (cons 'done org-done-keywords))
12351 (member (plist-get change-plist :to)
12352 (cons 'todo org-not-done-keywords))
12353 (not (plist-get change-plist :to)))
12354 (throw 'dont-block t))
12355 ;; If this task has checkboxes that are not checked, it's blocked
12357 (org-back-to-heading t)
12358 (let ((beg (point)) end)
12359 (outline-next-heading)
12362 (if (org-list-search-forward
12363 (concat (org-item-beginning-re)
12364 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12368 (if (boundp 'org-blocked-by-checkboxes)
12369 (setq org-blocked-by-checkboxes t))
12370 (throw 'dont-block nil)))))
12371 t))) ; do not block
12373 (defun org-entry-blocked-p ()
12374 "Is the current entry blocked?"
12375 (org-with-silent-modifications
12376 (if (org-entry-get nil "NOBLOCKING")
12377 nil ;; Never block this entry
12378 (not (run-hook-with-args-until-failure
12380 (list :type 'todo-state-change
12385 (defun org-update-statistics-cookies (all)
12386 "Update the statistics cookie, either from TODO or from checkboxes.
12387 This should be called with the cursor in a line with a statistics cookie."
12391 (org-update-checkbox-count 'all)
12392 (org-map-entries 'org-update-parent-todo-statistics))
12393 (if (not (org-at-heading-p))
12394 (org-update-checkbox-count)
12395 (let ((pos (point-marker))
12397 (ignore-errors (org-back-to-heading t))
12398 (if (not (org-at-heading-p))
12399 (org-update-checkbox-count)
12400 (setq l1 (org-outline-level))
12401 (setq end (save-excursion
12402 (outline-next-heading)
12403 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12405 (if (and (save-excursion
12407 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12408 (not (save-excursion (re-search-forward
12409 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12410 (org-update-checkbox-count)
12411 (if (and l2 (> l2 l1))
12414 (org-update-parent-todo-statistics))
12416 (beginning-of-line 1)
12417 (while (re-search-forward
12418 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12420 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12422 (move-marker pos nil)))))
12424 (defvar org-entry-property-inherited-from) ;; defined below
12425 (defun org-update-parent-todo-statistics ()
12426 "Update any statistics cookie in the parent of the current headline.
12427 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12428 the entire subtree and this will travel up the hierarchy and update
12429 statistics everywhere."
12430 (let* ((prop (save-excursion (org-up-heading-safe)
12431 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12432 (recursive (or (not org-hierarchical-todo-statistics)
12433 (and prop (string-match "\\<recursive\\>" prop))))
12434 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12437 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12438 level ltoggle l1 new ndel
12439 (cnt-all 0) (cnt-done 0) is-percent kwd
12440 checkbox-beg ov ovs ove cookie-present)
12443 (beginning-of-line 1)
12444 (setq ltoggle (funcall outline-level))
12445 ;; Three situations are to consider:
12447 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12448 ;; to the top-level ancestor on the headline;
12450 ;; 2. If parent has "recursive" property, repeat up to the
12451 ;; headline setting that property, taking inheritance into
12454 ;; 3. Else, move up to direct parent and proceed only once.
12455 (while (and (setq level (org-up-heading-safe))
12456 (or recursive first)
12458 (setq first nil cookie-present nil)
12462 (downcase (or (org-entry-get nil "COOKIE_DATA")
12465 (while (re-search-forward box-re (point-at-eol) t)
12466 (setq cnt-all 0 cnt-done 0 cookie-present t)
12467 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12469 (unless (outline-next-heading) (throw 'exit nil))
12470 (while (and (looking-at org-complex-heading-regexp)
12471 (> (setq l1 (length (match-string 1))) level))
12472 (setq kwd (and (or recursive (= l1 ltoggle))
12474 (if (or (eq org-provide-todo-statistics 'all-headlines)
12475 (and (listp org-provide-todo-statistics)
12476 (or (member kwd org-provide-todo-statistics)
12477 (member kwd org-done-keywords))))
12478 (setq cnt-all (1+ cnt-all))
12479 (if (eq org-provide-todo-statistics t)
12480 (and kwd (setq cnt-all (1+ cnt-all)))))
12481 (and (member kwd org-done-keywords)
12482 (setq cnt-done (1+ cnt-done)))
12483 (outline-next-heading)))
12486 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12487 (format "[%d/%d]" cnt-done cnt-all))
12488 ndel (- (match-end 0) checkbox-beg))
12489 ;; handle overlays when updating cookie from column view
12490 (when (setq ov (car (overlays-at checkbox-beg)))
12491 (setq ovs (overlay-start ov) ove (overlay-end ov))
12492 (delete-overlay ov))
12493 (goto-char checkbox-beg)
12495 (delete-region (point) (+ (point) ndel))
12496 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12497 (when ov (move-overlay ov ovs ove)))
12498 (when cookie-present
12499 (run-hook-with-args 'org-after-todo-statistics-hook
12500 cnt-done (- cnt-all cnt-done))))))
12501 (run-hooks 'org-todo-statistics-hook)))
12503 (defvar org-after-todo-statistics-hook nil
12504 "Hook that is called after a TODO statistics cookie has been updated.
12505 Each function is called with two arguments: the number of not-done entries
12506 and the number of done entries.
12508 For example, the following function, when added to this hook, will switch
12509 an entry to DONE when all children are done, and back to TODO when new
12510 entries are set to a TODO status. Note that this hook is only called
12511 when there is a statistics cookie in the headline!
12513 (defun org-summary-todo (n-done n-not-done)
12514 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12515 (let (org-log-done org-log-states) ; turn off logging
12516 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12519 (defvar org-todo-statistics-hook nil
12520 "Hook that is run whenever Org thinks TODO statistics should be updated.
12521 This hook runs even if there is no statistics cookie present, in which case
12522 `org-after-todo-statistics-hook' would not run.")
12524 (defun org-todo-trigger-tag-changes (state)
12525 "Apply the changes defined in `org-todo-state-tags-triggers'."
12526 (let ((l org-todo-state-tags-triggers)
12528 (when (or (not state) (equal state ""))
12529 (setq changes (append changes (cdr (assoc "" l)))))
12530 (when (and (stringp state) (> (length state) 0))
12531 (setq changes (append changes (cdr (assoc state l)))))
12532 (when (member state org-not-done-keywords)
12533 (setq changes (append changes (cdr (assoc 'todo l)))))
12534 (when (member state org-done-keywords)
12535 (setq changes (append changes (cdr (assoc 'done l)))))
12536 (dolist (c changes)
12537 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12539 (defun org-local-logging (value)
12540 "Get logging settings from a property VALUE."
12542 ;; directly set the variables, they are already local.
12543 (setq org-log-done nil
12545 org-todo-log-states nil)
12546 (setq words (org-split-string value))
12547 (while (setq w (pop words))
12549 ((setq a (assoc w org-startup-options))
12550 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12551 (set (nth 1 a) (nth 2 a))))
12552 ((setq a (org-extract-log-state-settings w))
12553 (and (member (car a) org-todo-keywords-1)
12554 (push a org-todo-log-states)))))))
12556 (defun org-get-todo-sequence-head (kwd)
12557 "Return the head of the TODO sequence to which KWD belongs.
12558 If KWD is not set, check if there is a text property remembering the
12563 (or (get-text-property (point-at-bol) 'org-todo-head)
12565 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12566 nil (point-at-eol)))
12567 (get-text-property p 'org-todo-head))))
12568 ((not (member kwd org-todo-keywords-1))
12569 (car org-todo-keywords-1))
12570 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12572 (defun org-fast-todo-selection ()
12573 "Fast TODO keyword selection with single keys.
12574 Returns the new TODO keyword, or nil if no state change should occur."
12575 (let* ((fulltable org-todo-key-alist)
12576 (done-keywords org-done-keywords) ;; needed for the faces.
12577 (maxlen (apply 'max (mapcar
12579 (if (stringp (car x)) (string-width (car x)) 0))
12582 (fwidth (+ maxlen 3 1 3))
12583 (ncol (/ (- (window-width) 4) fwidth))
12587 (save-window-excursion
12589 (set-buffer (get-buffer-create " *Org todo*"))
12590 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12592 (org-set-local 'org-done-keywords done-keywords)
12593 (setq tbl fulltable cnt 0)
12594 (while (setq e (pop tbl))
12596 ((equal e '(:startgroup))
12597 (push '() groups) (setq ingroup t)
12598 (when (not (= cnt 0))
12602 ((equal e '(:endgroup))
12603 (setq ingroup nil cnt 0)
12605 ((equal e '(:newline))
12606 (when (not (= cnt 0))
12610 (while (equal (car tbl) '(:newline))
12612 (setq tbl (cdr tbl)))))
12614 (setq tg (car e) c (cdr e))
12615 (if ingroup (push tg (car groups)))
12616 (setq tg (org-add-props tg nil 'face
12617 (org-get-todo-face tg)))
12618 (if (and (= cnt 0) (not ingroup)) (insert " "))
12619 (insert "[" c "] " tg (make-string
12620 (- fwidth 4 (length tg)) ?\ ))
12621 (when (= (setq cnt (1+ cnt)) ncol)
12623 (if ingroup (insert " "))
12626 (goto-char (point-min))
12627 (if (not expert) (org-fit-window-to-buffer))
12628 (message "[a-z..]:Set [SPC]:clear")
12629 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12632 (and (= c ?q) (not (rassoc c fulltable))))
12633 (setq quit-flag t))
12635 ((setq e (rassoc c fulltable) tg (car e))
12637 (t (setq quit-flag t)))))))
12639 (defun org-entry-is-todo-p ()
12640 (member (org-get-todo-state) org-not-done-keywords))
12642 (defun org-entry-is-done-p ()
12643 (member (org-get-todo-state) org-done-keywords))
12645 (defun org-get-todo-state ()
12647 (org-back-to-heading t)
12648 (and (looking-at org-todo-line-regexp)
12650 (match-string 2))))
12652 (defun org-at-date-range-p (&optional inactive-ok)
12653 "Is the cursor inside a date range?"
12657 (let ((pos (point)))
12658 (skip-chars-backward "^[<\r\n")
12659 (skip-chars-backward "<[")
12660 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12661 (>= (match-end 0) pos)
12663 (skip-chars-backward "^<[\r\n")
12664 (skip-chars-backward "<[")
12665 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12666 (>= (match-end 0) pos)
12670 (defun org-get-repeat (&optional tagline)
12671 "Check if there is a deadline/schedule with repeater in this entry."
12674 (org-back-to-heading t)
12675 (and (re-search-forward (if tagline
12676 (concat tagline "\\s-*" org-repeat-re)
12678 (org-entry-end-position) t)
12679 (match-string-no-properties 1)))))
12681 (defvar org-last-changed-timestamp)
12682 (defvar org-last-inserted-timestamp)
12683 (defvar org-log-post-message)
12684 (defvar org-log-note-purpose)
12685 (defvar org-log-note-how)
12686 (defvar org-log-note-extra)
12687 (defun org-auto-repeat-maybe (done-word)
12688 "Check if the current headline contains a repeated deadline/schedule.
12689 If yes, set TODO state back to what it was and change the base date
12690 of repeating deadline/scheduled time stamps to new date.
12691 This function is run automatically after each state change to a DONE state."
12692 ;; last-state is dynamically scoped into this function
12693 (let* ((repeat (org-get-repeat))
12694 (aa (assoc org-last-state org-todo-kwd-alist))
12695 (interpret (nth 1 aa))
12697 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12698 (msg "Entry repeats: ")
12700 (org-todo-log-states nil)
12701 re type n what ts time to-state)
12703 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12704 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12705 org-todo-repeat-to-state))
12706 (unless (and to-state (member to-state org-todo-keywords-1))
12707 (setq to-state (if (eq interpret 'type) org-last-state head)))
12708 (org-todo to-state)
12709 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12710 (org-entry-put nil "LAST_REPEAT" (format-time-string
12711 (org-time-stamp-format t t))))
12712 (when org-log-repeat
12713 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12714 (memq 'org-add-log-note post-command-hook))
12715 ;; OK, we are already setup for some record
12716 (if (eq org-log-repeat 'note)
12717 ;; make sure we take a note, not only a time stamp
12718 (setq org-log-note-how 'note))
12719 ;; Set up for taking a record
12720 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12722 'findpos org-log-repeat)))
12723 (org-back-to-heading t)
12724 (org-add-planning-info nil nil 'closed)
12725 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12726 org-deadline-time-regexp "\\)\\|\\("
12727 org-ts-regexp "\\)"))
12728 (while (re-search-forward
12729 re (save-excursion (outline-next-heading) (point)) t)
12730 (setq type (if (match-end 1) org-scheduled-string
12731 (if (match-end 3) org-deadline-string "Plain:"))
12732 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12733 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12734 (setq n (string-to-number (match-string 2 ts))
12735 what (match-string 3 ts))
12736 (if (equal what "w") (setq n (* n 7) what "d"))
12737 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12738 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12739 ;; Preparation, see if we need to modify the start date for the change
12740 (when (match-end 1)
12741 (setq time (save-match-data (org-time-string-to-time ts)))
12743 ((equal (match-string 1 ts) ".")
12744 ;; Shift starting date to today
12745 (org-timestamp-change
12746 (- (org-today) (time-to-days time))
12748 ((equal (match-string 1 ts) "+")
12749 (let ((nshiftmax 10) (nshift 0))
12750 (while (or (= nshift 0)
12751 (<= (time-to-days time)
12752 (time-to-days (current-time))))
12753 (when (= (incf nshift) nshiftmax)
12754 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12756 (org-timestamp-change n (cdr (assoc what whata)))
12757 (org-at-timestamp-p t)
12758 (setq ts (match-string 1))
12759 (setq time (save-match-data (org-time-string-to-time ts)))))
12760 (org-timestamp-change (- n) (cdr (assoc what whata)))
12761 ;; rematch, so that we have everything in place for the real shift
12762 (org-at-timestamp-p t)
12763 (setq ts (match-string 1))
12764 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12765 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12766 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12767 (setq org-log-post-message msg)
12768 (message "%s" msg))))
12770 (defun org-show-todo-tree (arg)
12771 "Make a compact tree which shows all headlines marked with TODO.
12772 The tree will show the lines where the regexp matches, and all higher
12773 headlines above the match.
12774 With a \\[universal-argument] prefix, prompt for a regexp to match.
12775 With a numeric prefix N, construct a sparse tree for the Nth element
12776 of `org-todo-keywords-1'."
12778 (let ((case-fold-search nil)
12780 (cond ((null arg) org-not-done-regexp)
12782 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12783 (mapcar 'list org-todo-keywords-1))))
12785 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12787 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12788 (regexp-quote (nth (1- (prefix-numeric-value arg))
12789 org-todo-keywords-1)))
12790 (t (error "Invalid prefix argument: %s" arg)))))
12791 (message "%d TODO entries found"
12792 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12794 (defun org-deadline (arg &optional time)
12795 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12796 With one universal prefix argument, remove any deadline from the item.
12797 With two universal prefix arguments, prompt for a warning delay.
12798 With argument TIME, set the deadline at the corresponding date. TIME
12799 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12801 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12802 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12803 'region-start-level 'region))
12804 org-loop-over-headlines-in-active-region)
12806 `(org-deadline ',arg ,time)
12807 org-loop-over-headlines-in-active-region
12808 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12809 (let* ((old-date (org-entry-get nil "DEADLINE"))
12810 (old-date-time (if old-date (org-time-string-to-time old-date)))
12811 (repeater (and old-date
12813 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12815 (match-string 1 old-date))))
12818 (when (and old-date org-log-redeadline)
12819 (org-add-log-setup 'deldeadline nil old-date 'findpos
12820 org-log-redeadline))
12821 (org-remove-timestamp-with-keyword org-deadline-string)
12822 (message "Item no longer has a deadline."))
12825 (if (re-search-forward
12826 org-deadline-time-regexp
12827 (save-excursion (outline-next-heading) (point)) t)
12828 (let* ((rpl0 (match-string 1))
12829 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12831 (concat org-deadline-string
12837 (org-read-date nil t nil "Warn starting from" old-date-time)))
12838 (time-to-days old-date-time))))
12840 (user-error "No deadline information to update"))))
12842 (org-add-planning-info 'deadline time 'closed)
12843 (when (and old-date org-log-redeadline
12844 (not (equal old-date
12845 (substring org-last-inserted-timestamp 1 -1))))
12846 (org-add-log-setup 'redeadline nil old-date 'findpos
12847 org-log-redeadline))
12850 (org-back-to-heading t)
12851 (when (re-search-forward (concat org-deadline-string " "
12852 org-last-inserted-timestamp)
12854 (outline-next-heading) (point)) t)
12855 (goto-char (1- (match-end 0)))
12856 (insert " " repeater)
12857 (setq org-last-inserted-timestamp
12858 (concat (substring org-last-inserted-timestamp 0 -1)
12860 (substring org-last-inserted-timestamp -1))))))
12861 (message "Deadline on %s" org-last-inserted-timestamp))))))
12863 (defun org-schedule (arg &optional time)
12864 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12865 With one universal prefix argument, remove any scheduling date from the item.
12866 With two universal prefix arguments, prompt for a delay cookie.
12867 With argument TIME, scheduled at the corresponding date. TIME can
12868 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12870 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12871 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12872 'region-start-level 'region))
12873 org-loop-over-headlines-in-active-region)
12875 `(org-schedule ',arg ,time)
12876 org-loop-over-headlines-in-active-region
12877 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12878 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12879 (old-date-time (if old-date (org-time-string-to-time old-date)))
12880 (repeater (and old-date
12882 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12884 (match-string 1 old-date))))
12888 (when (and old-date org-log-reschedule)
12889 (org-add-log-setup 'delschedule nil old-date 'findpos
12890 org-log-reschedule))
12891 (org-remove-timestamp-with-keyword org-scheduled-string)
12892 (message "Item is no longer scheduled.")))
12895 (if (re-search-forward
12896 org-scheduled-time-regexp
12897 (save-excursion (outline-next-heading) (point)) t)
12898 (let* ((rpl0 (match-string 1))
12899 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12901 (concat org-scheduled-string
12907 (org-read-date nil t nil "Delay until" old-date-time)))
12908 (time-to-days old-date-time))))
12910 (user-error "No scheduled information to update"))))
12912 (org-add-planning-info 'scheduled time 'closed)
12913 (when (and old-date org-log-reschedule
12914 (not (equal old-date
12915 (substring org-last-inserted-timestamp 1 -1))))
12916 (org-add-log-setup 'reschedule nil old-date 'findpos
12917 org-log-reschedule))
12920 (org-back-to-heading t)
12921 (when (re-search-forward (concat org-scheduled-string " "
12922 org-last-inserted-timestamp)
12924 (outline-next-heading) (point)) t)
12925 (goto-char (1- (match-end 0)))
12926 (insert " " repeater)
12927 (setq org-last-inserted-timestamp
12928 (concat (substring org-last-inserted-timestamp 0 -1)
12930 (substring org-last-inserted-timestamp -1))))))
12931 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12933 (defun org-get-scheduled-time (pom &optional inherit)
12934 "Get the scheduled time as a time tuple, of a format suitable
12935 for calling org-schedule with, or if there is no scheduling,
12937 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12939 (apply 'encode-time (org-parse-time-string time)))))
12941 (defun org-get-deadline-time (pom &optional inherit)
12942 "Get the deadline as a time tuple, of a format suitable for
12943 calling org-deadline with, or if there is no scheduling, returns
12945 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12947 (apply 'encode-time (org-parse-time-string time)))))
12949 (defun org-remove-timestamp-with-keyword (keyword)
12950 "Remove all time stamps with KEYWORD in the current entry."
12951 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12954 (org-back-to-heading t)
12956 (outline-next-heading)
12957 (while (re-search-backward re beg t)
12959 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12960 (equal (char-before) ?\ ))
12961 (backward-delete-char 1)
12962 (if (string-match "^[ \t]*$" (buffer-substring
12963 (point-at-bol) (point-at-eol)))
12964 (delete-region (point-at-bol)
12965 (min (point-max) (1+ (point-at-eol))))))))))
12967 (defun org-add-planning-info (what &optional time &rest remove)
12968 "Insert new timestamp with keyword in the line directly after the headline.
12969 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12970 If non is given, the user is prompted for a date.
12971 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12974 (let (org-time-was-given org-end-time-was-given ts
12975 end default-time default-input)
12978 (when (and (memq what '(scheduled deadline))
12980 (and (stringp time)
12981 (string-match "^[-+]+[0-9]" time))))
12982 ;; Try to get a default date/time from existing timestamp
12984 (org-back-to-heading t)
12985 (setq end (save-excursion (outline-next-heading) (point)))
12986 (when (re-search-forward (if (eq what 'scheduled)
12987 org-scheduled-time-regexp
12988 org-deadline-time-regexp)
12990 (setq ts (match-string 1)
12992 (apply 'encode-time (org-parse-time-string ts))
12993 default-input (and ts (org-get-compact-tod ts))))))
12997 ;; This is a string (relative or absolute), set proper date
12998 (apply 'encode-time
12999 (org-read-date-analyze
13000 time default-time (decode-time default-time)))
13001 ;; If necessary, get the time from the user
13002 (or time (org-read-date nil 'to-time nil nil
13003 default-time default-input)))))
13005 (when (and org-insert-labeled-timestamps-at-point
13006 (member what '(scheduled deadline)))
13008 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13009 (org-insert-time-stamp time org-time-was-given
13010 nil nil nil (list org-end-time-was-given))
13014 (let (col list elt ts buffer-invisibility-spec)
13015 (org-back-to-heading t)
13016 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13017 (goto-char (match-end 1))
13018 (setq col (current-column))
13019 (goto-char (match-end 0))
13020 (if (eobp) (insert "\n") (forward-char 1))
13021 (when (and (not what)
13024 org-keyword-time-not-clock-regexp))))
13025 ;; Nothing to add, nothing to remove...... :-)
13027 (if (and (not (looking-at org-outline-regexp))
13028 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13030 (not (equal (match-string 1) org-clock-string)))
13031 (narrow-to-region (match-beginning 0) (match-end 0))
13032 (insert-before-markers "\n")
13034 (narrow-to-region (point) (point))
13035 (and org-adapt-indentation (org-indent-to-column col)))
13036 ;; Check if we have to remove something.
13037 (setq list (cons what remove))
13039 (setq elt (pop list))
13040 (when (or (and (eq elt 'scheduled)
13041 (re-search-forward org-scheduled-time-regexp nil t))
13042 (and (eq elt 'deadline)
13043 (re-search-forward org-deadline-time-regexp nil t))
13044 (and (eq elt 'closed)
13045 (re-search-forward org-closed-time-regexp nil t)))
13047 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13048 (and (looking-at "[ \t]+") (replace-match ""))
13049 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13052 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13053 (cond ((eq what 'scheduled) org-scheduled-string)
13054 ((eq what 'deadline) org-deadline-string)
13055 ((eq what 'closed) org-closed-string))
13057 (setq ts (org-insert-time-stamp
13059 (or org-time-was-given
13060 (and (eq what 'closed) org-log-done-with-time))
13062 nil nil (list org-end-time-was-given)))
13064 (if (not (or (bolp) (eq (char-before) ?\ )
13065 (memq (char-after) '(32 10))
13068 (goto-char (point-min))
13070 (if (and (looking-at "[ \t]*\n")
13071 (equal (char-before) ?\n))
13072 (delete-region (1- (point)) (point-at-eol)))
13075 (defvar org-log-note-marker (make-marker))
13076 (defvar org-log-note-purpose nil)
13077 (defvar org-log-note-state nil)
13078 (defvar org-log-note-previous-state nil)
13079 (defvar org-log-note-how nil)
13080 (defvar org-log-note-extra nil)
13081 (defvar org-log-note-window-configuration nil)
13082 (defvar org-log-note-return-to (make-marker))
13083 (defvar org-log-note-effective-time nil
13084 "Remembered current time so that dynamically scoped
13085 `org-extend-today-until' affects tha timestamps in state change
13088 (defvar org-log-post-message nil
13089 "Message to be displayed after a log note has been stored.
13090 The auto-repeater uses this.")
13092 (defun org-add-note ()
13093 "Add a note to the current entry.
13094 This is done in the same way as adding a state change note."
13096 (org-add-log-setup 'note nil nil 'findpos nil))
13098 (defvar org-property-end-re)
13099 (defun org-add-log-setup (&optional purpose state prev-state
13101 "Set up the post command hook to take a note.
13102 If this is about to TODO state change, the new state is expected in STATE.
13103 When FINDPOS is non-nil, find the correct position for the note in
13104 the current entry. If not, assume that it can be inserted at point.
13105 HOW is an indicator what kind of note should be created.
13106 EXTRA is additional text that will be inserted into the notes buffer."
13107 (let* ((org-log-into-drawer (org-log-into-drawer))
13108 (drawer (cond ((stringp org-log-into-drawer)
13109 org-log-into-drawer)
13110 (org-log-into-drawer "LOGBOOK"))))
13114 (org-back-to-heading t)
13115 (narrow-to-region (point) (save-excursion
13116 (outline-next-heading) (point)))
13117 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13118 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13120 (goto-char (match-end 0))
13123 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13126 (goto-char (match-end 0))
13127 (or org-log-states-order-reversed
13128 (and (re-search-forward org-property-end-re nil t)
13129 (goto-char (1- (match-beginning 0))))))
13130 (insert "\n:" drawer ":\n:END:")
13131 (beginning-of-line 0)
13133 (beginning-of-line 2)
13136 ((and org-log-state-notes-insert-after-drawers
13138 (forward-line) (looking-at org-drawer-regexp)))
13140 (while (looking-at org-drawer-regexp)
13141 (goto-char (match-end 0))
13142 (re-search-forward org-property-end-re (point-max) t)
13144 (forward-line -1)))
13145 (unless org-log-states-order-reversed
13146 (and (= (char-after) ?\n) (forward-char 1))
13147 (org-skip-over-state-notes)
13148 (skip-chars-backward " \t\n\r")))
13149 (move-marker org-log-note-marker (point))
13150 (setq org-log-note-purpose purpose
13151 org-log-note-state state
13152 org-log-note-previous-state prev-state
13153 org-log-note-how how
13154 org-log-note-extra extra
13155 org-log-note-effective-time (org-current-effective-time))
13156 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13158 (defun org-skip-over-state-notes ()
13159 "Skip past the list of State notes in an entry."
13160 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13161 (when (ignore-errors (goto-char (org-in-item-p)))
13162 (let* ((struct (org-list-struct))
13163 (prevs (org-list-prevs-alist struct)))
13164 (while (looking-at "[ \t]*- State")
13165 (goto-char (or (org-list-get-next-item (point) struct prevs)
13166 (org-list-get-item-end (point) struct)))))))
13168 (defun org-add-log-note (&optional purpose)
13169 "Pop up a window for taking a note, and add this note later at point."
13170 (remove-hook 'post-command-hook 'org-add-log-note)
13171 (setq org-log-note-window-configuration (current-window-configuration))
13172 (delete-other-windows)
13173 (move-marker org-log-note-return-to (point))
13174 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13175 (goto-char org-log-note-marker)
13176 (org-switch-to-buffer-other-window "*Org Note*")
13178 (if (memq org-log-note-how '(time state))
13179 (let (current-prefix-arg) (org-store-log-note))
13180 (let ((org-inhibit-startup t)) (org-mode))
13181 (insert (format "# Insert note for %s.
13182 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13184 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13185 ((eq org-log-note-purpose 'done) "closed todo item")
13186 ((eq org-log-note-purpose 'state)
13187 (format "state change from \"%s\" to \"%s\""
13188 (or org-log-note-previous-state "")
13189 (or org-log-note-state "")))
13190 ((eq org-log-note-purpose 'reschedule)
13192 ((eq org-log-note-purpose 'delschedule)
13193 "no longer scheduled")
13194 ((eq org-log-note-purpose 'redeadline)
13195 "changing deadline")
13196 ((eq org-log-note-purpose 'deldeadline)
13197 "removing deadline")
13198 ((eq org-log-note-purpose 'refile)
13200 ((eq org-log-note-purpose 'note)
13202 (t (error "This should not happen")))))
13203 (if org-log-note-extra (insert org-log-note-extra))
13204 (org-set-local 'org-finish-function 'org-store-log-note)
13205 (run-hooks 'org-log-buffer-setup-hook)))
13207 (defvar org-note-abort nil) ; dynamically scoped
13208 (defun org-store-log-note ()
13209 "Finish taking a log note, and insert it to where it belongs."
13210 (let ((txt (buffer-string)))
13211 (kill-buffer (current-buffer))
13212 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13214 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13215 (setq txt (replace-match "" t t txt)))
13216 (if (string-match "\\s-+\\'" txt)
13217 (setq txt (replace-match "" t t txt)))
13218 (setq lines (org-split-string txt "\n"))
13219 (when (and note (string-match "\\S-" note))
13221 (org-replace-escapes
13223 (list (cons "%u" (user-login-name))
13224 (cons "%U" user-full-name)
13225 (cons "%t" (format-time-string
13226 (org-time-stamp-format 'long 'inactive)
13227 org-log-note-effective-time))
13228 (cons "%T" (format-time-string
13229 (org-time-stamp-format 'long nil)
13230 org-log-note-effective-time))
13231 (cons "%d" (format-time-string
13232 (org-time-stamp-format nil 'inactive)
13233 org-log-note-effective-time))
13234 (cons "%D" (format-time-string
13235 (org-time-stamp-format nil nil)
13236 org-log-note-effective-time))
13237 (cons "%s" (if org-log-note-state
13238 (concat "\"" org-log-note-state "\"")
13240 (cons "%S" (if org-log-note-previous-state
13241 (concat "\"" org-log-note-previous-state "\"")
13243 (if lines (setq note (concat note " \\\\")))
13245 (when (or current-prefix-arg org-note-abort)
13246 (when org-log-into-drawer
13247 (org-remove-empty-drawer-at
13248 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13249 org-log-note-marker))
13252 (with-current-buffer (marker-buffer org-log-note-marker)
13254 (goto-char org-log-note-marker)
13255 (move-marker org-log-note-marker nil)
13257 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13258 (setq ind (save-excursion
13259 (if (ignore-errors (goto-char (org-in-item-p)))
13260 (let ((struct (org-list-struct)))
13262 (org-list-get-top-point struct) struct))
13263 (skip-chars-backward " \r\t\n")
13265 ((and (org-at-heading-p)
13266 org-adapt-indentation)
13267 (1+ (org-current-level)))
13268 ((org-at-heading-p) 0)
13269 (t (org-get-indentation))))))
13270 (setq bul (org-list-bullet-string "-"))
13271 (org-indent-line-to ind)
13272 (insert bul (pop lines))
13273 (let ((ind-body (+ (length bul) ind)))
13276 (org-indent-line-to ind-body)
13277 (insert (pop lines))))
13278 (message "Note stored")
13279 (org-back-to-heading t)
13280 (org-cycle-hide-drawers 'children))))))
13281 (set-window-configuration org-log-note-window-configuration)
13282 (with-current-buffer (marker-buffer org-log-note-return-to)
13283 (goto-char org-log-note-return-to))
13284 (move-marker org-log-note-return-to nil)
13285 (and org-log-post-message (message "%s" org-log-post-message)))
13287 (defun org-remove-empty-drawer-at (drawer pos)
13288 "Remove an empty drawer DRAWER at position POS.
13289 POS may also be a marker."
13290 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13296 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13297 (replace-match ""))))))
13299 (defvar org-ts-type nil)
13300 (defun org-sparse-tree (&optional arg type)
13301 "Create a sparse tree, prompt for the details.
13302 This command can create sparse trees. You first need to select the type
13303 of match used to create the tree:
13305 t Show all TODO entries.
13306 T Show entries with a specific TODO keyword.
13307 m Show entries selected by a tags/property match.
13308 p Enter a property name and its value (both with completion on existing
13309 names/values) and show entries with that property.
13310 r Show entries matching a regular expression (`/' can be used as well).
13311 b Show deadlines and scheduled items before a date.
13312 a Show deadlines and scheduled items after a date.
13313 d Show deadlines due within `org-deadline-warning-days'.
13314 D Show deadlines and scheduled items between a date range."
13316 (let (ans kwd value ts-type)
13317 (setq type (or type org-sparse-tree-default-date-type))
13318 (setq org-ts-type type)
13319 (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"
13320 (cond ((eq type 'all) "all timestamps")
13321 ((eq type 'scheduled) "only scheduled")
13322 ((eq type 'deadline) "only deadline")
13323 ((eq type 'active) "only active timestamps")
13324 ((eq type 'inactive) "only inactive timestamps")
13325 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13326 (t "scheduled/deadline")))
13327 (setq ans (read-char-exclusive))
13330 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13332 (call-interactively 'org-check-deadlines))
13334 (call-interactively 'org-check-before-date))
13336 (call-interactively 'org-check-after-date))
13338 (call-interactively 'org-check-dates-range))
13340 (call-interactively 'org-show-todo-tree))
13342 (org-show-todo-tree '(4)))
13343 ((member ans '(?T ?m))
13344 (call-interactively 'org-match-sparse-tree))
13345 ((member ans '(?p ?P))
13346 (setq kwd (org-icompleting-read "Property: "
13347 (mapcar 'list (org-buffer-property-keys))))
13348 (setq value (org-icompleting-read "Value: "
13349 (mapcar 'list (org-property-values kwd))))
13350 (unless (string-match "\\`{.*}\\'" value)
13351 (setq value (concat "\"" value "\"")))
13352 (org-match-sparse-tree arg (concat kwd "=" value)))
13353 ((member ans '(?r ?R ?/))
13354 (call-interactively 'org-occur))
13355 (t (error "No such sparse tree command \"%c\"" ans)))))
13357 (defvar org-occur-highlights nil
13358 "List of overlays used for occur matches.")
13359 (make-variable-buffer-local 'org-occur-highlights)
13360 (defvar org-occur-parameters nil
13361 "Parameters of the active org-occur calls.
13362 This is a list, each call to org-occur pushes as cons cell,
13363 containing the regular expression and the callback, onto the list.
13364 The list can contain several entries if `org-occur' has been called
13365 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13366 will only contain one set of parameters. When the highlights are
13367 removed (for example with `C-c C-c', or with the next edit (depending
13368 on `org-remove-highlights-with-change'), this variable is emptied
13370 (make-variable-buffer-local 'org-occur-parameters)
13372 (defun org-occur (regexp &optional keep-previous callback)
13373 "Make a compact tree which shows all matches of REGEXP.
13374 The tree will show the lines where the regexp matches, and all higher
13375 headlines above the match. It will also show the heading after the match,
13376 to make sure editing the matching entry is easy.
13377 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13378 call to `org-occur' will be kept, to allow stacking of calls to this
13380 If CALLBACK is non-nil, it is a function which is called to confirm
13381 that the match should indeed be shown."
13382 (interactive "sRegexp: \nP")
13383 (when (equal regexp "")
13384 (error "Regexp cannot be empty"))
13385 (unless keep-previous
13386 (org-remove-occur-highlights nil nil t))
13387 (push (cons regexp callback) org-occur-parameters)
13390 (goto-char (point-min))
13391 (if (or (not keep-previous) ; do not want to keep
13392 (not org-occur-highlights)) ; no previous matches
13395 (while (re-search-forward regexp nil t)
13396 (when (or (not callback)
13397 (save-match-data (funcall callback)))
13398 (setq cnt (1+ cnt))
13399 (when org-highlight-sparse-tree-matches
13400 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13401 (org-show-context 'occur-tree))))
13402 (when org-remove-highlights-with-change
13403 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13405 (unless org-sparse-tree-open-archived-trees
13406 (org-hide-archived-subtrees (point-min) (point-max)))
13407 (run-hooks 'org-occur-hook)
13408 (if (org-called-interactively-p 'interactive)
13409 (message "%d match(es) for regexp %s" cnt regexp))
13412 (defun org-occur-next-match (&optional n reset)
13413 "Function for `next-error-function' to find sparse tree matches.
13414 N is the number of matches to move, when negative move backwards.
13415 RESET is entirely ignored - this function always goes back to the
13416 starting point when no match is found."
13417 (let* ((limit (if (< n 0) (point-min) (point-max)))
13418 (search-func (if (< n 0)
13419 'previous-single-char-property-change
13420 'next-single-char-property-change))
13425 (while (setq p1 (funcall search-func (point) 'org-type))
13426 (when (equal p1 limit)
13428 (error "No more matches"))
13429 (when (equal (get-char-property p1 'org-type) 'org-occur)
13433 (throw 'exit (point))))
13436 (error "No more matches"))))
13438 (defun org-show-context (&optional key)
13439 "Make sure point and context are visible.
13440 How much context is shown depends upon the variables
13441 `org-show-hierarchy-above', `org-show-following-heading',
13442 `org-show-entry-below' and `org-show-siblings'."
13443 (let ((heading-p (org-at-heading-p t))
13444 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13445 (following-p (org-get-alist-option org-show-following-heading key))
13446 (entry-p (org-get-alist-option org-show-entry-below key))
13447 (siblings-p (org-get-alist-option org-show-siblings key)))
13448 ;; Show heading or entry text
13449 (if (and heading-p (not entry-p))
13450 (org-flag-heading nil) ; only show the heading
13451 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13452 (org-show-hidden-entry))) ; show entire entry
13454 ;; Show next sibling, or heading below text
13456 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13457 (org-flag-heading nil))))
13458 (when siblings-p (org-show-siblings))
13460 ;; show all higher headings, possibly with siblings
13462 (while (and (condition-case nil
13463 (progn (org-up-heading-all 1) t)
13466 (org-flag-heading nil)
13467 (when siblings-p (org-show-siblings)))))
13468 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13470 (defvar org-reveal-start-hook nil
13471 "Hook run before revealing a location.")
13473 (defun org-reveal (&optional siblings)
13474 "Show current entry, hierarchy above it, and the following headline.
13475 This can be used to show a consistent set of context around locations
13476 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13477 not t for the search context.
13479 With optional argument SIBLINGS, on each level of the hierarchy all
13480 siblings are shown. This repairs the tree structure to what it would
13481 look like when opened with hierarchical calls to `org-cycle'.
13482 With double optional argument \\[universal-argument] \\[universal-argument], \
13483 go to the parent and show the
13486 (run-hooks 'org-reveal-start-hook)
13487 (let ((org-show-hierarchy-above t)
13488 (org-show-following-heading t)
13489 (org-show-siblings (if siblings t org-show-siblings)))
13490 (org-show-context nil))
13491 (when (equal siblings '(16))
13493 (when (org-up-heading-safe)
13495 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13497 (defun org-highlight-new-match (beg end)
13498 "Highlight from BEG to END and mark the highlight is an occur headline."
13499 (let ((ov (make-overlay beg end)))
13500 (overlay-put ov 'face 'secondary-selection)
13501 (overlay-put ov 'org-type 'org-occur)
13502 (push ov org-occur-highlights)))
13504 (defun org-remove-occur-highlights (&optional beg end noremove)
13505 "Remove the occur highlights from the buffer.
13506 BEG and END are ignored. If NOREMOVE is nil, remove this function
13507 from the `before-change-functions' in the current buffer."
13509 (unless org-inhibit-highlight-removal
13510 (mapc 'delete-overlay org-occur-highlights)
13511 (setq org-occur-highlights nil)
13512 (setq org-occur-parameters nil)
13514 (remove-hook 'before-change-functions
13515 'org-remove-occur-highlights 'local))))
13519 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13520 "Regular expression matching the priority indicator.")
13522 (defvar org-remove-priority-next-time nil)
13524 (defun org-priority-up ()
13525 "Increase the priority of the current item."
13527 (org-priority 'up))
13529 (defun org-priority-down ()
13530 "Decrease the priority of the current item."
13532 (org-priority 'down))
13534 (defun org-priority (&optional action show)
13535 "Change the priority of an item.
13536 ACTION can be `set', `up', `down', or a character."
13538 (if (equal action '(4))
13539 (org-show-priority)
13540 (unless org-enable-priority-commands
13541 (error "Priority commands are disabled"))
13542 (setq action (or action 'set))
13543 (let (current new news have remove)
13545 (org-back-to-heading t)
13546 (if (looking-at org-priority-regexp)
13547 (setq current (string-to-char (match-string 2))
13550 ((eq action 'remove)
13551 (setq remove t new ?\ ))
13552 ((or (eq action 'set)
13553 (if (featurep 'xemacs) (characterp action) (integerp action)))
13554 (if (not (eq action 'set))
13556 (message "Priority %c-%c, SPC to remove: "
13557 org-highest-priority org-lowest-priority)
13559 (setq new (read-char-exclusive))))
13560 (if (and (= (upcase org-highest-priority) org-highest-priority)
13561 (= (upcase org-lowest-priority) org-lowest-priority))
13562 (setq new (upcase new)))
13563 (cond ((equal new ?\ ) (setq remove t))
13564 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13565 (error "Priority must be between `%c' and `%c'"
13566 org-highest-priority org-lowest-priority))))
13569 (1- current) ; normal cycling
13570 ;; last priority was empty
13571 (if (eq last-command this-command)
13572 org-lowest-priority ; wrap around empty to lowest
13574 (if org-priority-start-cycle-with-default
13575 org-default-priority
13576 (1- org-default-priority))))))
13579 (1+ current) ; normal cycling
13580 ;; last priority was empty
13581 (if (eq last-command this-command)
13582 org-highest-priority ; wrap around empty to highest
13584 (if org-priority-start-cycle-with-default
13585 org-default-priority
13586 (1+ org-default-priority))))))
13587 (t (error "Invalid action")))
13588 (if (or (< (upcase new) org-highest-priority)
13589 (> (upcase new) org-lowest-priority))
13590 (if (and (memq action '(up down))
13591 (not have) (not (eq last-command this-command)))
13592 ;; `new' is from default priority
13594 "The default can not be set, see `org-default-priority' why")
13595 ;; normal cycling: `new' is beyond highest/lowest priority
13596 ;; and is wrapped around to the empty priority
13598 (setq news (format "%c" new))
13601 (replace-match "" t t nil 1)
13602 (replace-match news t t nil 2))
13604 (error "No priority cookie found in line")
13605 (let ((case-fold-search nil))
13606 (looking-at org-todo-line-regexp))
13609 (goto-char (match-end 2))
13610 (insert " [#" news "]"))
13611 (goto-char (match-beginning 3))
13612 (insert "[#" news "] "))))
13613 (org-preserve-lc (org-set-tags nil 'align)))
13615 (message "Priority removed")
13616 (message "Priority of current item set to %s" news)))))
13618 (defun org-show-priority ()
13619 "Show the priority of the current item.
13620 This priority is composed of the main priority given with the [#A] cookies,
13621 and by additional input from the age of a schedules or deadline entry."
13623 (let ((pri (if (eq major-mode 'org-agenda-mode)
13624 (org-get-at-bol 'priority)
13627 (beginning-of-line)
13628 (and (looking-at org-heading-regexp)
13629 (org-get-priority (match-string 0))))))))
13630 (message "Priority is %d" (if pri pri -1000))))
13632 (defun org-get-priority (s)
13633 "Find priority cookie and return priority."
13635 (if (functionp org-get-priority-function)
13636 (funcall org-get-priority-function)
13637 (if (not (string-match org-priority-regexp s))
13638 (* 1000 (- org-lowest-priority org-default-priority))
13639 (* 1000 (- org-lowest-priority
13640 (string-to-char (match-string 2 s))))))))
13644 (defvar org-agenda-archives-mode)
13645 (defvar org-map-continue-from nil
13646 "Position from where mapping should continue.
13647 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13649 (defvar org-scanner-tags nil
13650 "The current tag list while the tags scanner is running.")
13651 (defvar org-trust-scanner-tags nil
13652 "Should `org-get-tags-at' use the tags for the scanner.
13653 This is for internal dynamical scoping only.
13654 When this is non-nil, the function `org-get-tags-at' will return the value
13655 of `org-scanner-tags' instead of building the list by itself. This
13656 can lead to large speed-ups when the tags scanner is used in a file with
13657 many entries, and when the list of tags is retrieved, for example to
13658 obtain a list of properties. Building the tags list for each entry in such
13659 a file becomes an N^2 operation - but with this variable set, it scales
13662 (defun org-scan-tags (action matcher todo-only &optional start-level)
13663 "Sca headline tags with inheritance and produce output ACTION.
13665 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13666 or `agenda' to produce an entry list for an agenda view. It can also be
13667 a Lisp form or a function that should be called at each matched headline, in
13668 this case the return value is a list of all return values from these calls.
13670 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13671 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13672 only lines with a not-done TODO keyword are included in the output.
13673 This should be the same variable that was scoped into
13674 and set by `org-make-tags-matcher' when it constructed MATCHER.
13676 START-LEVEL can be a string with asterisks, reducing the scope to
13677 headlines matching this string."
13678 (require 'org-agenda)
13679 (let* ((re (concat "^"
13681 ;; Get the correct level to match
13682 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13683 org-outline-regexp)
13685 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13686 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13687 (props (list 'face 'default
13688 'done-face 'org-agenda-done
13689 'undone-face 'default
13690 'mouse-face 'highlight
13691 'org-not-done-regexp org-not-done-regexp
13692 'org-todo-regexp org-todo-regexp
13693 'org-complex-heading-regexp org-complex-heading-regexp
13695 (format "mouse-2 or RET jump to org file %s"
13696 (abbreviate-file-name
13697 (or (buffer-file-name (buffer-base-buffer))
13698 (buffer-name (buffer-base-buffer)))))))
13699 (case-fold-search nil)
13700 (org-map-continue-from nil)
13701 lspos tags tags-list
13702 (tags-alist (list (cons 0 org-file-tags)))
13703 (llast 0) rtn rtn1 level category i txt
13704 todo marker entry priority)
13705 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13706 (setq action (list 'lambda nil action)))
13708 (goto-char (point-min))
13709 (when (eq action 'sparse-tree)
13711 (org-remove-occur-highlights))
13712 (while (re-search-forward re nil t)
13713 (setq org-map-continue-from nil)
13715 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13716 tags (if (match-end 4) (org-match-string-no-properties 4)))
13717 (goto-char (setq lspos (match-beginning 0)))
13718 (setq level (org-reduced-level (org-outline-level))
13719 category (org-get-category))
13720 (setq i llast llast level)
13721 ;; remove tag lists from same and sublevels
13722 (while (>= i level)
13723 (when (setq entry (assoc i tags-alist))
13724 (setq tags-alist (delete entry tags-alist)))
13726 ;; add the next tags
13728 (setq tags (org-split-string tags ":")
13730 (cons (cons level tags) tags-alist)))
13731 ;; compile tags for current headline
13733 (if org-use-tag-inheritance
13734 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13736 org-scanner-tags tags-list)
13737 (when org-use-tag-inheritance
13738 (setcdr (car tags-alist)
13739 (mapcar (lambda (x)
13740 (setq x (copy-sequence x))
13741 (org-add-prop-inherited x))
13742 (cdar tags-alist))))
13743 (when (and tags org-use-tag-inheritance
13744 (or (not (eq t org-use-tag-inheritance))
13745 org-tags-exclude-from-inheritance))
13746 ;; selective inheritance, remove uninherited ones
13747 (setcdr (car tags-alist)
13748 (org-remove-uninherited-tags (cdar tags-alist))))
13751 ;; eval matcher only when the todo condition is OK
13752 (and (or (not todo-only) (member todo org-not-done-keywords))
13753 (let ((case-fold-search t) (org-trust-scanner-tags t))
13756 ;; Call the skipper, but return t if it does not skip,
13757 ;; so that the `and' form continues evaluating
13759 (unless (eq action 'sparse-tree) (org-agenda-skip))
13762 ;; Check if timestamps are deselecting this entry
13763 (or (not todo-only)
13764 (and (member todo org-not-done-keywords)
13765 (or (not org-agenda-tags-todo-honor-ignore-options)
13766 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13768 ;; select this headline
13770 ((eq action 'sparse-tree)
13771 (and org-highlight-sparse-tree-matches
13772 (org-get-heading) (match-end 0)
13773 (org-highlight-new-match
13774 (match-beginning 1) (match-end 1)))
13775 (org-show-context 'tags-tree))
13776 ((eq action 'agenda)
13777 (setq txt (org-agenda-format-item
13780 (if (eq org-tags-match-list-sublevels 'indented)
13781 (make-string (1- level) ?.) "")
13785 priority (org-get-priority txt))
13787 (setq marker (org-agenda-new-marker))
13788 (org-add-props txt props
13789 'org-marker marker 'org-hd-marker marker 'org-category category
13791 'priority priority 'type "tagsmatch")
13793 ((functionp action)
13794 (setq org-map-continue-from nil)
13796 (setq rtn1 (funcall action))
13798 (t (error "Invalid action")))
13800 ;; if we are to skip sublevels, jump to end of subtree
13801 (unless org-tags-match-list-sublevels
13802 (org-end-of-subtree t)
13803 (backward-char 1))))
13804 ;; Get the correct position from where to continue
13805 (if org-map-continue-from
13806 (goto-char org-map-continue-from)
13807 (and (= (point) lspos) (end-of-line 1)))))
13808 (when (and (eq action 'sparse-tree)
13809 (not org-sparse-tree-open-archived-trees))
13810 (org-hide-archived-subtrees (point-min) (point-max)))
13813 (defun org-remove-uninherited-tags (tags)
13814 "Remove all tags that are not inherited from the list TAGS."
13816 ((eq org-use-tag-inheritance t)
13817 (if org-tags-exclude-from-inheritance
13818 (org-delete-all org-tags-exclude-from-inheritance tags)
13820 ((not org-use-tag-inheritance) nil)
13821 ((stringp org-use-tag-inheritance)
13824 (if (and (string-match org-use-tag-inheritance x)
13825 (not (member x org-tags-exclude-from-inheritance)))
13828 ((listp org-use-tag-inheritance)
13831 (if (member x org-use-tag-inheritance) x nil))
13834 (defun org-match-sparse-tree (&optional todo-only match)
13835 "Create a sparse tree according to tags string MATCH.
13836 MATCH can contain positive and negative selection of tags, like
13837 \"+WORK+URGENT-WITHBOSS\".
13838 If optional argument TODO-ONLY is non-nil, only select lines that are
13841 (org-agenda-prepare-buffers (list (current-buffer)))
13842 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13844 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13846 (defvar org-cached-props nil)
13847 (defun org-cached-entry-get (pom property)
13848 (if (or (eq t org-use-property-inheritance)
13849 (and (stringp org-use-property-inheritance)
13850 (string-match org-use-property-inheritance property))
13851 (and (listp org-use-property-inheritance)
13852 (member property org-use-property-inheritance)))
13853 ;; Caching is not possible, check it directly
13854 (org-entry-get pom property 'inherit)
13855 ;; Get all properties, so that we can do complicated checks easily
13856 (cdr (assoc property (or org-cached-props
13857 (setq org-cached-props
13858 (org-entry-properties pom)))))))
13860 (defun org-global-tags-completion-table (&optional files)
13861 "Return the list of all tags in all agenda buffer/files.
13862 Optional FILES argument is a list of files which can be used
13863 instead of the agenda files."
13870 (set-buffer (find-file-noselect file))
13871 (append (org-get-buffer-tags)
13872 (mapcar (lambda (x) (if (stringp (car-safe x))
13873 (list (car-safe x)) nil))
13875 (if (and files (car files))
13877 (org-agenda-files))))))))
13879 (defun org-make-tags-matcher (match)
13880 "Create the TAGS/TODO matcher form for the selection string MATCH.
13882 The variable `todo-only' is scoped dynamically into this function.
13883 It will be set to t if the matcher restricts matching to TODO entries,
13884 otherwise will not be touched.
13886 Returns a cons of the selection string MATCH and the constructed
13887 lisp form implementing the matcher. The matcher is to be evaluated
13888 at an Org entry, with point on the headline, and returns t if the
13889 entry matches the selection string MATCH. The returned lisp form
13890 references two variables with information about the entry, which
13891 must be bound around the form's evaluation: todo, the TODO keyword
13892 at the entry (or nil of none); and tags-list, the list of all tags
13893 at the entry including inherited ones. Additionally, the category
13894 of the entry (if any) must be specified as the text property
13895 'org-category on the headline.
13897 See also `org-scan-tags'.
13899 (declare (special todo-only))
13900 (unless (boundp 'todo-only)
13901 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13903 ;; Get a new match request, with completion
13904 (let ((org-last-tags-completion-table
13905 (org-global-tags-completion-table)))
13906 (setq match (org-completing-read-no-i
13907 "Match: " 'org-tags-completion-function nil nil nil
13908 'org-tags-history))))
13910 ;; Parse the string and create a lisp form
13911 (let ((match0 match)
13912 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13914 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13915 orterms term orlist re-p str-p level-p level-op time-p
13916 prop-p pn pv po gv rest)
13917 ;; Expand group tags
13918 (setq match (org-tags-expand match))
13919 (if (string-match "/+" match)
13920 ;; match contains also a todo-matching request
13922 (setq tagsmatch (substring match 0 (match-beginning 0))
13923 todomatch (substring match (match-end 0)))
13924 (if (string-match "^!" todomatch)
13925 (setq todo-only t todomatch (substring todomatch 1)))
13926 (if (string-match "^\\s-*$" todomatch)
13927 (setq todomatch nil)))
13928 ;; only matching tags
13929 (setq tagsmatch match todomatch nil))
13931 ;; Make the tags matcher
13932 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13933 (setq tagsmatcher t)
13934 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13935 (while (setq term (pop orterms))
13936 (while (and (equal (substring term -1) "\\") orterms)
13937 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13938 (while (string-match re term)
13939 (setq rest (substring term (match-end 0))
13940 minus (and (match-end 1)
13941 (equal (match-string 1 term) "-"))
13942 tag (save-match-data (replace-regexp-in-string
13944 (match-string 2 term)))
13945 re-p (equal (string-to-char tag) ?{)
13946 level-p (match-end 4)
13947 prop-p (match-end 5)
13949 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13951 (setq level-op (org-op-to-function (match-string 3 term)))
13952 `(,level-op level ,(string-to-number
13953 (match-string 4 term))))
13955 (setq pn (match-string 5 term)
13956 po (match-string 6 term)
13957 pv (match-string 7 term)
13958 re-p (equal (string-to-char pv) ?{)
13959 str-p (equal (string-to-char pv) ?\")
13960 time-p (save-match-data
13961 (string-match "^\"[[<].*[]>]\"$" pv))
13962 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13963 (if time-p (setq pv (org-matcher-time pv)))
13964 (setq po (org-op-to-function po (if time-p 'time str-p)))
13966 ((equal pn "CATEGORY")
13967 (setq gv '(get-text-property (point) 'org-category)))
13971 (setq gv `(org-cached-entry-get nil ,pn))))
13974 `(not (string-match ,pv (or ,gv "")))
13975 `(string-match ,pv (or ,gv "")))
13977 `(,po (or ,gv "") ,pv)
13978 `(,po (string-to-number (or ,gv ""))
13979 ,(string-to-number pv) ))))
13980 (t `(member ,tag tags-list)))
13981 mm (if minus (list 'not mm) mm)
13983 (push mm tagsmatcher))
13984 (push (if (> (length tagsmatcher) 1)
13985 (cons 'and tagsmatcher)
13988 (setq tagsmatcher nil))
13989 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13991 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13992 ;; Make the todo matcher
13993 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13994 (setq todomatcher t)
13995 (setq orterms (org-split-string todomatch "|") orlist nil)
13996 (while (setq term (pop orterms))
13997 (while (string-match re term)
13998 (setq minus (and (match-end 1)
13999 (equal (match-string 1 term) "-"))
14000 kwd (match-string 2 term)
14001 re-p (equal (string-to-char kwd) ?{)
14002 term (substring term (match-end 0))
14004 `(string-match ,(substring kwd 1 -1) todo)
14005 (list 'equal 'todo kwd))
14006 mm (if minus (list 'not mm) mm))
14007 (push mm todomatcher))
14008 (push (if (> (length todomatcher) 1)
14009 (cons 'and todomatcher)
14012 (setq todomatcher nil))
14013 (setq todomatcher (if (> (length orlist) 1)
14014 (cons 'or orlist) (car orlist))))
14016 ;; Return the string and lisp forms of the matcher
14017 (setq matcher (if todomatcher
14018 (list 'and tagsmatcher todomatcher)
14021 (setq matcher (list 'and '(member todo org-not-done-keywords)
14023 (cons match0 matcher)))
14025 (defun org-tags-expand (match &optional single-as-list downcased)
14026 "Expand group tags in MATCH.
14028 This replaces every group tag in MATCH with a regexp tag search.
14029 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14030 will be replaced like this:
14032 Work => {\(?:Work\|Lab\|Conf\}
14033 +Work => +{\(?:Work\|Lab\|Conf\}
14034 -Work => -{\(?:Work\|Lab\|Conf\}
14036 Replacing by a regexp preserves the structure of the match.
14037 E.g., this expansion
14039 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14041 will match anything tagged with \"Lab\" and \"Home\", or tagged
14042 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14044 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14045 assumed to be a single group tag, and the function will return
14046 the list of tags in this group.
14048 When DOWNCASE is non-nil, expand downcased TAGS."
14050 (let* ((case-fold-search t)
14051 (stable org-mode-syntax-table)
14052 (tal (or org-tag-groups-alist-for-agenda
14053 org-tag-groups-alist))
14054 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14055 (tml (mapcar 'car tal))
14056 (rtnmatch match) rpl)
14057 ;; @ and _ are allowed as word-components in tags
14058 (modify-syntax-entry ?@ "w" stable)
14059 (modify-syntax-entry ?_ "w" stable)
14060 (while (and tml (string-match
14061 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14063 (let* ((dir (match-string 1 rtnmatch))
14064 (tag (match-string 2 rtnmatch))
14065 (tag (if downcased (downcase tag) tag)))
14066 (setq tml (delete tag tml))
14067 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14070 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14072 (or (reverse rpl) (list rtnmatch))
14074 (if single-as-list (list (if downcased (downcase match) match))
14077 (defun org-op-to-function (op &optional stringp)
14078 "Turn an operator into the appropriate function."
14081 ((equal op "<" ) '(< string< org-time<))
14082 ((equal op ">" ) '(> org-string> org-time>))
14083 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14084 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14085 ((member op '("=" "==")) '(= string= org-time=))
14086 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14087 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14089 (defun org<> (a b) (not (= a b)))
14090 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14091 (defun org-string>= (a b) (not (string< a b)))
14092 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14093 (defun org-string<> (a b) (not (string= a b)))
14094 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14095 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14096 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14097 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14098 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14099 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14101 "Convert S to a floating point time.
14102 If S is already a number, just return it. If it is a string, parse
14103 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14107 (condition-case nil
14108 (float-time (apply 'encode-time (org-parse-time-string s)))
14112 (defun org-time-today ()
14113 "Time in seconds today at 0:00.
14114 Returns the float number of seconds since the beginning of the
14115 epoch to the beginning of today (00:00)."
14116 (float-time (apply 'encode-time
14117 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14119 (defun org-matcher-time (s)
14120 "Interpret a time comparison value."
14123 ((string= s "<now>") (float-time))
14124 ((string= s "<today>") (org-time-today))
14125 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14126 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14127 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14128 (+ (org-time-today)
14129 (* (string-to-number (match-string 1 s))
14130 (cdr (assoc (match-string 2 s)
14131 '(("d" . 86400.0) ("w" . 604800.0)
14132 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14135 (defun org-match-any-p (re list)
14136 "Does re match any element of list?"
14137 (setq list (mapcar (lambda (x) (string-match re x)) list))
14140 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14141 (defvar org-tags-overlay (make-overlay 1 1))
14142 (org-detach-overlay org-tags-overlay)
14144 (defun org-get-local-tags-at (&optional pos)
14145 "Get a list of tags defined in the current headline."
14146 (org-get-tags-at pos 'local))
14148 (defun org-get-local-tags ()
14149 "Get a list of tags defined in the current headline."
14150 (org-get-tags-at nil 'local))
14152 (defun org-get-tags-at (&optional pos local)
14153 "Get a list of all headline tags applicable at POS.
14154 POS defaults to point. If tags are inherited, the list contains
14155 the targets in the same sequence as the headlines appear, i.e.
14156 the tags of the current headline come last.
14157 When LOCAL is non-nil, only return tags from the current headline,
14158 ignore inherited ones."
14160 (if (and org-trust-scanner-tags
14161 (or (not pos) (equal pos (point)))
14164 (let (tags ltags lastpos parent)
14168 (goto-char (or pos (point)))
14171 (condition-case nil
14173 (org-back-to-heading t)
14174 (while (not (equal lastpos (point)))
14175 (setq lastpos (point))
14177 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14178 (setq ltags (org-split-string
14179 (org-match-string-no-properties 1) ":"))
14181 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14184 (org-remove-uninherited-tags ltags)
14187 (or org-use-tag-inheritance (throw 'done t))
14188 (if local (throw 'done t))
14189 (or (org-up-heading-safe) (error nil))
14194 (reverse (delete-dups
14196 (org-remove-uninherited-tags
14197 org-file-tags) tags)))))))))
14199 (defun org-add-prop-inherited (s)
14200 (add-text-properties 0 (length s) '(inherited t) s)
14203 (defun org-toggle-tag (tag &optional onoff)
14204 "Toggle the tag TAG for the current line.
14205 If ONOFF is `on' or `off', don't toggle but set to this state."
14208 (org-back-to-heading t)
14209 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14212 (setq current (match-string 1))
14213 (replace-match ""))
14215 (setq current (nreverse (org-split-string current ":")))
14219 (or (member tag current) (push tag current)))
14221 (or (not (member tag current)) (setq current (delete tag current))))
14222 (t (if (member tag current)
14223 (setq current (delete tag current))
14225 (push tag current))))
14229 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14230 (org-set-tags nil t))
14231 (delete-horizontal-space))
14232 (run-hooks 'org-after-tags-change-hook))
14235 (defun org-align-tags-here (to-col)
14236 ;; Assumes that this is a headline
14237 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14238 (beginning-of-line 1)
14239 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14240 (< pos (match-beginning 2)))
14242 (setq tags-l (- (match-end 2) (match-beginning 2)))
14243 (goto-char (match-beginning 1))
14245 (delete-region (point) (1+ (match-beginning 2)))
14246 (setq ncol (max (current-column)
14250 (- (abs to-col) tags-l))))
14252 (insert (make-string (- ncol (current-column)) ?\ ))
14253 (setq ncol (current-column))
14254 (when indent-tabs-mode (tabify p (point-at-eol)))
14255 (org-move-to-column (min ncol col) t))
14258 (defun org-set-tags-command (&optional arg just-align)
14259 "Call the set-tags command for the current entry."
14261 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14262 (org-set-tags arg just-align)
14264 (unless (and (org-region-active-p)
14265 org-loop-over-headlines-in-active-region)
14266 (org-back-to-heading t))
14267 (org-set-tags arg just-align))))
14269 (defun org-set-tags-to (data)
14270 "Set the tags of the current entry to DATA, replacing the current tags.
14271 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14272 If DATA is nil or the empty string, any tags will be removed."
14273 (interactive "sTags: ")
14277 ((equal data "") "")
14279 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14282 (concat ":" (mapconcat 'identity data ":") ":"))))
14285 (org-back-to-heading t)
14286 (when (looking-at org-complex-heading-regexp)
14289 (goto-char (match-beginning 5))
14291 (delete-region (point) (point-at-eol))
14292 (org-set-tags nil 'align))
14293 (goto-char (point-at-eol))
14295 (org-set-tags nil 'align)))
14296 (beginning-of-line 1)
14297 (if (looking-at ".*?\\([ \t]+\\)$")
14298 (delete-region (match-beginning 1) (match-end 1))))))
14300 (defun org-align-all-tags ()
14301 "Align the tags i all headings."
14304 (or (ignore-errors (org-back-to-heading t))
14305 (outline-next-heading))
14306 (if (org-at-heading-p)
14308 (message "No headings"))))
14310 (defvar org-indent-indentation-per-level)
14311 (defun org-set-tags (&optional arg just-align)
14312 "Set the tags for the current headline.
14313 With prefix ARG, realign all tags in headings in the current buffer."
14315 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14316 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14317 'region-start-level 'region))
14318 org-loop-over-headlines-in-active-region)
14320 ;; We don't use ARG and JUST-ALIGN here these args are not
14321 ;; useful when looping over headlines
14323 org-loop-over-headlines-in-active-region
14324 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14325 (let* ((re org-outline-regexp-bol)
14326 (current (unless arg (org-get-tags-string)))
14327 (col (current-column))
14328 (org-setting-tags t)
14329 table current-tags inherited-tags ; computed below when needed
14330 tags p0 c0 c1 rpl di tc level)
14333 (goto-char (point-min))
14334 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14335 (while (re-search-forward re nil t)
14336 (org-set-tags nil t)
14338 (message "All tags realigned to column %d" org-tags-column))
14340 (setq tags current)
14341 ;; Get a new set of tags from the user
14343 (setq table (append org-tag-persistent-alist
14344 (or org-tag-alist (org-get-buffer-tags))
14346 org-complete-tags-always-offer-all-agenda-tags
14347 (org-global-tags-completion-table
14348 (org-agenda-files))))
14349 org-last-tags-completion-table table
14350 current-tags (org-split-string current ":")
14351 inherited-tags (nreverse
14352 (nthcdr (length current-tags)
14353 (nreverse (org-get-tags-at))))
14355 (if (or (eq t org-use-fast-tag-selection)
14356 (and org-use-fast-tag-selection
14357 (delq nil (mapcar 'cdr table))))
14358 (org-fast-tag-selection
14359 current-tags inherited-tags table
14360 (if org-fast-tag-selection-include-todo
14361 org-todo-key-alist))
14362 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14364 (org-icompleting-read "Tags: "
14365 'org-tags-completion-function
14366 nil nil current 'org-tags-history))))))
14367 (while (string-match "[-+&]+" tags)
14368 ;; No boolean logic, just a list
14369 (setq tags (replace-match ":" t t tags))))
14371 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14373 (if org-tags-sort-function
14374 (setq tags (mapconcat 'identity
14375 (sort (org-split-string
14376 tags (org-re "[^[:alnum:]_@#%]+"))
14377 org-tags-sort-function) ":")))
14379 (if (string-match "\\`[\t ]*\\'" tags)
14381 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14382 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14384 ;; Insert new tags at the correct column
14385 (beginning-of-line 1)
14386 (setq level (or (and (looking-at org-outline-regexp)
14387 (- (match-end 0) (point) 1))
14390 ((and (equal current "") (equal tags "")))
14391 ((re-search-forward
14392 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14394 (if (equal tags "")
14396 (goto-char (match-beginning 0))
14397 (setq c0 (current-column)
14398 ;; compute offset for the case of org-indent-mode active
14399 di (if org-indent-mode
14400 (* (1- org-indent-indentation-per-level) (1- level))
14402 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14403 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14404 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14405 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14406 (replace-match rpl t t)
14407 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14409 (t (error "Tags alignment failed")))
14410 (org-move-to-column col)
14412 (run-hooks 'org-after-tags-change-hook))))))
14414 (defun org-change-tag-in-region (beg end tag off)
14415 "Add or remove TAG for each entry in the region.
14416 This works in the agenda, and also in an org-mode buffer."
14418 (list (region-beginning) (region-end)
14419 (let ((org-last-tags-completion-table
14420 (if (derived-mode-p 'org-mode)
14421 (org-get-buffer-tags)
14422 (org-global-tags-completion-table))))
14423 (org-icompleting-read
14424 "Tag: " 'org-tags-completion-function nil nil nil
14425 'org-tags-history))
14427 (message "[s]et or
[r]emove? ")
14428 (equal (read-char-exclusive) ?r))))
14429 (if (fboundp 'deactivate-mark) (deactivate-mark))
14430 (let ((agendap (equal major-mode 'org-agenda-mode))
14431 l1 l2 m buf pos newhead (cnt 0))
14433 (setq l2 (1- (org-current-line)))
14435 (setq l1 (org-current-line))
14436 (loop for l from l1 to l2 do
14438 (setq m (get-text-property (point) 'org-hd-marker))
14439 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14441 (setq buf (if agendap (marker-buffer m) (current-buffer))
14442 pos (if agendap m (point)))
14443 (with-current-buffer buf
14447 (setq cnt (1+ cnt))
14448 (org-toggle-tag tag (if off 'off 'on))
14449 (setq newhead (org-get-heading)))))
14450 (and agendap (org-agenda-change-all-lines newhead m))))
14451 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14453 (defun org-tags-completion-function (string predicate &optional flag)
14454 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14455 (confirm (lambda (x) (stringp (car x)))))
14456 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14457 (setq s1 (match-string 1 string)
14458 s2 (match-string 2 string))
14459 (setq s1 "" s2 string))
14463 (setq rtn (try-completion s2 ctable confirm))
14466 (concat s1 s2 (substring rtn (length s2))
14467 (if (and org-add-colon-after-tag-completion
14468 (assoc rtn ctable))
14473 (all-completions s2 ctable confirm))
14476 (assoc s2 ctable)))))
14478 (defun org-fast-tag-insert (kwd tags face &optional end)
14479 "Insert KDW, and the TAGS, the latter with face FACE.
14481 (insert (format "%-12s" (concat kwd ":"))
14482 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14485 (defun org-fast-tag-show-exit (flag)
14488 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14489 (replace-match ""))
14492 (org-move-to-column (- (window-width) 19) t)
14493 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14495 (defun org-set-current-tags-overlay (current prefix)
14496 "Add an overlay to CURRENT tag with PREFIX."
14497 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14498 (if (featurep 'xemacs)
14499 (org-overlay-display org-tags-overlay (concat prefix s)
14500 'secondary-selection)
14501 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14502 (org-overlay-display org-tags-overlay (concat prefix s)))))
14504 (defvar org-last-tag-selection-key nil)
14505 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14506 "Fast tag selection with single keys.
14507 CURRENT is the current list of tags in the headline, INHERITED is the
14508 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14509 possibly with grouping information. TODO-TABLE is a similar table with
14510 TODO keywords, should these have keys assigned to them.
14511 If the keys are nil, a-z are automatically assigned.
14512 Returns the new tags string, or nil to not change the current settings."
14513 (let* ((fulltable (append table todo-table))
14514 (maxlen (apply 'max (mapcar
14516 (if (stringp (car x)) (string-width (car x)) 0))
14518 (buf (current-buffer))
14519 (expert (eq org-fast-tag-selection-single-key 'expert))
14521 (fwidth (+ maxlen 3 1 3))
14522 (ncol (/ (- (window-width) 4) fwidth))
14525 tg cnt e c char c1 c2 ntable tbl rtn
14526 ov-start ov-end ov-prefix
14527 (exit-after-next org-fast-tag-selection-single-key)
14528 (done-keywords org-done-keywords)
14531 (beginning-of-line 1)
14533 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14534 (setq ov-start (match-beginning 1)
14535 ov-end (match-end 1)
14537 (setq ov-start (1- (point-at-eol))
14538 ov-end (1+ ov-start))
14539 (skip-chars-forward "^\n\r")
14542 (buffer-substring (1- (point)) (point))
14543 (if (> (current-column) org-tags-column)
14545 (make-string (- org-tags-column (current-column)) ?\ ))))))
14546 (move-overlay org-tags-overlay ov-start ov-end)
14547 (save-window-excursion
14549 (set-buffer (get-buffer-create " *Org tags*"))
14550 (delete-other-windows)
14551 (split-window-vertically)
14552 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14554 (org-set-local 'org-done-keywords done-keywords)
14555 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14556 (org-fast-tag-insert "Current" current c-face "\n\n")
14557 (org-fast-tag-show-exit exit-after-next)
14558 (org-set-current-tags-overlay current ov-prefix)
14559 (setq tbl fulltable char ?a cnt 0)
14560 (while (setq e (pop tbl))
14562 ((equal (car e) :startgroup)
14563 (push '() groups) (setq ingroup t)
14564 (when (not (= cnt 0))
14567 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14568 ((equal (car e) :endgroup)
14569 (setq ingroup nil cnt 0)
14570 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14571 ((equal e '(:newline))
14572 (when (not (= cnt 0))
14576 (while (equal (car tbl) '(:newline))
14578 (setq tbl (cdr tbl)))))
14579 ((equal e '(:grouptags)) nil)
14581 (setq tg (copy-sequence (car e)) c2 nil)
14584 ;; automatically assign a character.
14585 (setq c1 (string-to-char
14586 (downcase (substring
14587 tg (if (= (string-to-char tg) ?@) 1 0)))))
14588 (if (or (rassoc c1 ntable) (rassoc c1 table))
14589 (while (or (rassoc char ntable) (rassoc char table))
14590 (setq char (1+ char)))
14592 (setq c (or c2 char)))
14593 (if ingroup (push tg (car groups)))
14594 (setq tg (org-add-props tg nil 'face
14596 ((not (assoc tg table))
14597 (org-get-todo-face tg))
14598 ((member tg current) c-face)
14599 ((member tg inherited) i-face))))
14600 (if (equal (caar tbl) :grouptags)
14601 (org-add-props tg nil 'face 'org-tag-group))
14602 (if (and (= cnt 0) (not ingroup)) (insert " "))
14603 (insert "[" c "] " tg (make-string
14604 (- fwidth 4 (length tg)) ?\ ))
14605 (push (cons tg c) ntable)
14606 (when (= (setq cnt (1+ cnt)) ncol)
14608 (if ingroup (insert " "))
14610 (setq ntable (nreverse ntable))
14612 (goto-char (point-min))
14613 (if (not expert) (org-fit-window-to-buffer))
14617 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14618 (if (not groups) "no " "")
14619 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14620 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14621 (setq org-last-tag-selection-key c)
14623 ((= c ?\r) (throw 'exit t))
14625 (setq groups (not groups))
14626 (goto-char (point-min))
14627 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14630 (org-fast-tag-show-exit
14631 (setq exit-after-next (not exit-after-next)))
14633 (delete-other-windows)
14634 (set-window-buffer (split-window-vertically) " *Org tags*")
14635 (org-switch-to-buffer-other-window " *Org tags*")
14636 (org-fit-window-to-buffer)))
14638 (and (= c ?q) (not (rassoc c ntable))))
14639 (org-detach-overlay org-tags-overlay)
14640 (setq quit-flag t))
14643 (if exit-after-next (setq exit-after-next 'now)))
14645 (condition-case nil
14646 (setq tg (org-icompleting-read
14649 (with-current-buffer buf
14650 (org-get-buffer-tags)))))
14651 (quit (setq tg "")))
14652 (when (string-match "\\S-" tg)
14653 (add-to-list 'buffer-tags (list tg))
14654 (if (member tg current)
14655 (setq current (delete tg current))
14656 (push tg current)))
14657 (if exit-after-next (setq exit-after-next 'now)))
14658 ((setq e (rassoc c todo-table) tg (car e))
14659 (with-current-buffer buf
14660 (save-excursion (org-todo tg)))
14661 (if exit-after-next (setq exit-after-next 'now)))
14662 ((setq e (rassoc c ntable) tg (car e))
14663 (if (member tg current)
14664 (setq current (delete tg current))
14665 (loop for g in groups do
14668 (setq current (delete x current)))
14671 (if exit-after-next (setq exit-after-next 'now))))
14673 ;; Create a sorted list
14677 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14678 (if (eq exit-after-next 'now) (throw 'exit t))
14679 (goto-char (point-min))
14680 (beginning-of-line 2)
14681 (delete-region (point) (point-at-eol))
14682 (org-fast-tag-insert "Current" current c-face)
14683 (org-set-current-tags-overlay current ov-prefix)
14684 (while (re-search-forward
14685 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14686 (setq tg (match-string 1))
14687 (add-text-properties
14688 (match-beginning 1) (match-end 1)
14691 ((member tg current) c-face)
14692 ((member tg inherited) i-face)
14693 (t (get-text-property (match-beginning 1) 'face))))))
14694 (goto-char (point-min)))))
14695 (org-detach-overlay org-tags-overlay)
14697 (mapconcat 'identity current ":")
14700 (defun org-get-tags-string ()
14701 "Get the TAGS string in the current headline."
14702 (unless (org-at-heading-p t)
14703 (error "Not on a heading"))
14705 (beginning-of-line 1)
14706 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14707 (org-match-string-no-properties 1)
14710 (defun org-get-tags ()
14711 "Get the list of tags specified in the current headline."
14712 (org-split-string (org-get-tags-string) ":"))
14714 (defun org-get-buffer-tags ()
14715 "Get a table of all tags used in the buffer, for completion."
14718 (goto-char (point-min))
14719 (while (re-search-forward
14720 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14721 (when (equal (char-after (point-at-bol 0)) ?*)
14722 (mapc (lambda (x) (add-to-list 'tags x))
14723 (org-split-string (org-match-string-no-properties 1) ":")))))
14724 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14725 (mapcar 'list tags)))
14727 ;;;; The mapping API
14729 (defun org-map-entries (func &optional match scope &rest skip)
14730 "Call FUNC at each headline selected by MATCH in SCOPE.
14732 FUNC is a function or a lisp form. The function will be called without
14733 arguments, with the cursor positioned at the beginning of the headline.
14734 The return values of all calls to the function will be collected and
14735 returned as a list.
14737 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14738 does not need to preserve point. After evaluation, the cursor will be
14739 moved to the end of the line (presumably of the headline of the
14740 processed entry) and search continues from there. Under some
14741 circumstances, this may not produce the wanted results. For example,
14742 if you have removed (e.g. archived) the current (sub)tree it could
14743 mean that the next entry will be skipped entirely. In such cases, you
14744 can specify the position from where search should continue by making
14745 FUNC set the variable `org-map-continue-from' to the desired buffer
14748 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14749 Only headlines that are matched by this query will be considered during
14750 the iteration. When MATCH is nil or t, all headlines will be
14751 visited by the iteration.
14753 SCOPE determines the scope of this command. It can be any of:
14755 nil The current buffer, respecting the restriction if any
14756 tree The subtree started with the entry at point
14757 region The entries within the active region, if any
14759 The entries within the active region, but only those at
14760 the same level than the first one.
14761 file The current buffer, without restriction
14763 The current buffer, and any archives associated with it
14764 agenda All agenda files
14765 agenda-with-archives
14766 All agenda files with any archive files associated with them
14768 If this is a list, all files in the list will be scanned
14770 The remaining args are treated as settings for the skipping facilities of
14771 the scanner. The following items can be given here:
14773 archive skip trees with the archive tag
14774 comment skip trees with the COMMENT keyword
14775 function or Emacs Lisp form:
14776 will be used as value for `org-agenda-skip-function', so
14777 whenever the function returns a position, FUNC will not be
14778 called for that entry and search will continue from the
14781 If your function needs to retrieve the tags including inherited tags
14782 at the *current* entry, you can use the value of the variable
14783 `org-scanner-tags' which will be much faster than getting the value
14784 with `org-get-tags-at'. If your function gets properties with
14785 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14786 to t around the call to `org-entry-properties' to get the same speedup.
14787 Note that if your function moves around to retrieve tags and properties at
14788 a *different* entry, you cannot use these techniques."
14789 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14790 (not (org-region-active-p)))
14791 (let* ((org-agenda-archives-mode nil) ; just to make sure
14792 (org-agenda-skip-archived-trees (memq 'archive skip))
14793 (org-agenda-skip-comment-trees (memq 'comment skip))
14794 (org-agenda-skip-function
14795 (car (org-delete-all '(comment archive) skip)))
14796 (org-tags-match-list-sublevels t)
14797 (start-level (eq scope 'region-start-level))
14799 org-todo-keywords-for-agenda
14800 org-done-keywords-for-agenda
14801 org-todo-keyword-alist-for-agenda
14802 org-drawers-for-agenda
14803 org-tag-alist-for-agenda
14807 ((eq match t) (setq matcher t))
14808 ((eq match nil) (setq matcher t))
14809 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14811 (save-window-excursion
14813 (cond ((eq scope 'tree)
14814 (org-back-to-heading t)
14815 (org-narrow-to-subtree)
14817 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14818 (org-region-active-p))
14819 ;; If needed, set start-level to a string like "2"
14822 (goto-char (region-beginning))
14823 (unless (org-at-heading-p) (outline-next-heading))
14824 (setq start-level (org-current-level))))
14825 (narrow-to-region (region-beginning)
14827 (goto-char (region-end))
14828 (unless (and (bolp) (org-at-heading-p))
14829 (outline-next-heading))
14835 (org-agenda-prepare-buffers
14836 (list (buffer-file-name (current-buffer))))
14837 (setq res (org-scan-tags func matcher todo-only start-level)))
14838 ;; Get the right scope
14840 ((and scope (listp scope) (symbolp (car scope)))
14841 (setq scope (eval scope)))
14842 ((eq scope 'agenda)
14843 (setq scope (org-agenda-files t)))
14844 ((eq scope 'agenda-with-archives)
14845 (setq scope (org-agenda-files t))
14846 (setq scope (org-add-archive-files scope)))
14848 (setq scope (list (buffer-file-name))))
14849 ((eq scope 'file-with-archives)
14850 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14851 (org-agenda-prepare-buffers scope)
14852 (while (setq file (pop scope))
14853 (with-current-buffer (org-find-base-buffer-visiting file)
14857 (goto-char (point-min))
14858 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14863 ;;; Setting and retrieving properties
14865 (defconst org-special-properties
14866 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14867 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14868 "The special properties valid in Org-mode.
14870 These are properties that are not defined in the property drawer,
14871 but in some other way.")
14873 (defconst org-default-properties
14874 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14875 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14876 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14877 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14878 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14879 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14880 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14881 "Some properties that are used by Org-mode for various purposes.
14882 Being in this list makes sure that they are offered for completion.")
14884 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14885 "Regular expression matching the first line of a property drawer.")
14887 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14888 "Regular expression matching the last line of a property drawer.")
14890 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14891 "Regular expression matching the first line of a property drawer.")
14893 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14894 "Regular expression matching the first line of a property drawer.")
14896 (defconst org-property-drawer-re
14897 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14898 org-property-end-re "\\)\n?")
14899 "Matches an entire property drawer.")
14901 (defconst org-clock-drawer-re
14902 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14903 org-property-end-re "\\)\n?")
14904 "Matches an entire clock drawer.")
14906 (defsubst org-re-property (property)
14907 "Return a regexp matching a PROPERTY line.
14908 Match group 1 will be set to the value."
14909 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14911 (defsubst org-re-property-keyword (property)
14912 "Return a regexp matching a PROPERTY line, possibly with no
14913 value for the property."
14914 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14916 (defun org-property-action ()
14917 "Do an action on properties."
14920 (org-at-property-p)
14921 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14922 (setq c (read-char-exclusive))
14925 (call-interactively 'org-set-property))
14927 (call-interactively 'org-delete-property))
14929 (call-interactively 'org-delete-property-globally))
14931 (call-interactively 'org-compute-property-at-point))
14932 (t (error "No such property action %c" c)))))
14934 (defun org-inc-effort ()
14935 "Increment the value of the effort property in the current entry."
14937 (org-set-effort nil t))
14939 (defvar org-clock-effort) ;; Defined in org-clock.el
14940 (defvar org-clock-current-task) ;; Defined in org-clock.el
14941 (defun org-set-effort (&optional value increment)
14942 "Set the effort property of the current entry.
14943 With numerical prefix arg, use the nth allowed value, 0 stands for the
14944 10th allowed value.
14946 When INCREMENT is non-nil, set the property to the next allowed value."
14948 (if (equal value 0) (setq value 10))
14949 (let* ((completion-ignore-case t)
14950 (prop org-effort-property)
14951 (cur (org-entry-get nil prop))
14952 (allowed (org-property-get-allowed-values nil prop 'table))
14953 (existing (mapcar 'list (org-property-values prop)))
14954 (heading (nth 4 (org-heading-components)))
14957 ((stringp value) value)
14958 ((and allowed (integerp value))
14959 (or (car (nth (1- value) allowed))
14960 (car (org-last allowed))))
14961 ((and allowed increment)
14962 (or (caadr (member (list cur) allowed))
14963 (error "Allowed effort values are not set")))
14965 (message "Select 1-9,0, [RET%s]: %s"
14966 (if cur (concat "=" cur) "")
14967 (mapconcat 'car allowed " "))
14968 (setq rpl (read-char-exclusive))
14969 (if (equal rpl ?\r)
14971 (setq rpl (- rpl ?0))
14972 (if (equal rpl 0) (setq rpl 10))
14973 (if (and (> rpl 0) (<= rpl (length allowed)))
14974 (car (nth (1- rpl) allowed))
14975 (org-completing-read "Effort: " allowed nil))))
14977 (let (org-completion-use-ido org-completion-use-iswitchb)
14978 (org-completing-read
14979 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14980 (concat "[" cur "]") "")
14982 existing nil nil "" nil cur))))))
14983 (unless (equal (org-entry-get nil prop) val)
14984 (org-entry-put nil prop val))
14986 (org-back-to-heading t)
14987 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14988 (when (string= heading org-clock-current-task)
14989 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14990 (org-clock-update-mode-line))
14991 (message "%s is now %s" prop val)))
14993 (defun org-at-property-p ()
14994 "Is cursor inside a property drawer?"
14996 (beginning-of-line 1)
14997 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14998 (save-match-data ;; Used by calling procedures
15000 (range (unless (org-before-first-heading-p)
15001 (org-get-property-block))))
15002 (and range (<= (car range) p) (< p (cdr range))))))))
15004 (defun org-get-property-block (&optional beg end force)
15005 "Return the (beg . end) range of the body of the property drawer.
15006 BEG and END are the beginning and end of the current subtree, or of
15007 the part before the first headline. If they are not given, they will
15008 be found. If the drawer does not exist and FORCE is non-nil, create
15012 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15013 (progn (org-back-to-heading t) (point))))
15014 (end (or end (and (not (outline-next-heading)) (point-max))
15017 (if (re-search-forward org-property-start-re end t)
15018 (setq beg (1+ (match-end 0)))
15021 (org-insert-property-drawer)
15022 (setq end (progn (outline-next-heading) (point))))
15025 (if (re-search-forward org-property-start-re end t)
15026 (setq beg (1+ (match-end 0)))))
15027 (if (re-search-forward org-property-end-re end t)
15028 (setq end (match-beginning 0))
15029 (or force (throw 'exit nil))
15033 (insert ":END:\n"))
15036 (defun org-entry-properties (&optional pom which specific)
15037 "Get all properties of the entry at point-or-marker POM.
15038 This includes the TODO keyword, the tags, time strings for deadline,
15039 scheduled, and clocking, and any additional properties defined in the
15040 entry. The return value is an alist, keys may occur multiple times
15041 if the property key was used several times.
15042 POM may also be nil, in which case the current entry is used.
15043 If WHICH is nil or `all', get all properties. If WHICH is
15044 `special' or `standard', only get that subclass. If WHICH
15045 is a string only get exactly this property. SPECIFIC can be a string, the
15046 specific property we are interested in. Specifying it can speed
15047 things up because then unnecessary parsing is avoided."
15048 (setq which (or which 'all))
15049 (org-with-point-at pom
15050 (let ((clockstr (substring org-clock-string 0 -1))
15051 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15052 (case-fold-search nil)
15053 beg end range props sum-props key key1 value string clocksum clocksumt)
15055 (when (condition-case nil
15056 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15059 (setq sum-props (get-text-property (point) 'org-summaries))
15060 (setq clocksum (get-text-property (point) :org-clock-minutes)
15061 clocksumt (get-text-property (point) :org-clock-minutes-today))
15062 (outline-next-heading)
15064 (when (memq which '(all special))
15065 ;; Get the special properties, like TODO and tags
15067 (when (and (or (not specific) (string= specific "TODO"))
15068 (looking-at org-todo-line-regexp) (match-end 2))
15069 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15070 (when (and (or (not specific) (string= specific "PRIORITY"))
15071 (looking-at org-priority-regexp))
15072 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15073 (when (or (not specific) (string= specific "FILE"))
15074 (push (cons "FILE" buffer-file-name) props))
15075 (when (and (or (not specific) (string= specific "TAGS"))
15076 (setq value (org-get-tags-string))
15077 (string-match "\\S-" value))
15078 (push (cons "TAGS" value) props))
15079 (when (and (or (not specific) (string= specific "ALLTAGS"))
15080 (setq value (org-get-tags-at)))
15081 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15084 (when (or (not specific) (string= specific "BLOCKED"))
15085 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15086 (when (or (not specific)
15088 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15089 "TIMESTAMP" "TIMESTAMP_IA")))
15091 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15092 (setq key (if (match-end 1)
15093 (substring (org-match-string-no-properties 1)
15095 string (if (equal key clockstr)
15097 (buffer-substring-no-properties
15098 (match-beginning 3) (goto-char
15100 (substring (org-match-string-no-properties 3)
15102 ;; Get the correct property name from the key. This is
15103 ;; necessary if the user has configured time keywords.
15104 (setq key1 (concat key ":"))
15108 (if (= (char-after (match-beginning 3)) ?\[)
15109 "TIMESTAMP_IA" "TIMESTAMP")))
15110 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15111 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15112 ((equal key1 org-closed-string) (setq key "CLOSED"))
15113 ((equal key1 org-clock-string) (setq key "CLOCK")))
15114 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15116 (push (cons key string) props)
15117 ;; no need to search further if match is found
15119 (when (or (equal key "CLOCK") (not (assoc key props)))
15120 (push (cons key string) props)))))))
15122 (when (memq which '(all standard))
15123 ;; Get the standard properties, like :PROP: ...
15124 (setq range (org-get-property-block beg end))
15126 (goto-char (car range))
15127 (while (re-search-forward
15128 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15130 (setq key (org-match-string-no-properties 1)
15131 value (org-trim (or (org-match-string-no-properties 2) "")))
15132 (unless (member key excluded)
15133 (push (cons key (or value "")) props)))))
15135 (push (cons "CLOCKSUM"
15136 (org-columns-number-to-string (/ (float clocksum) 60.)
15140 (push (cons "CLOCKSUM_T"
15141 (org-columns-number-to-string (/ (float clocksumt) 60.)
15144 (unless (assoc "CATEGORY" props)
15145 (push (cons "CATEGORY" (org-get-category)) props))
15146 (append sum-props (nreverse props)))))))
15148 (defun org-entry-get (pom property &optional inherit literal-nil)
15149 "Get value of PROPERTY for entry or content at point-or-marker POM.
15150 If INHERIT is non-nil and the entry does not have the property,
15151 then also check higher levels of the hierarchy.
15152 If INHERIT is the symbol `selective', use inheritance only if the setting
15153 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15154 If the property is present but empty, the return value is the empty string.
15155 If the property is not present at all, nil is returned.
15157 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15158 do not interpret it as the list atom nil. This is used for inheritance
15159 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15160 (org-with-point-at pom
15161 (if (and inherit (if (eq inherit 'selective)
15162 (org-property-inherit-p property)
15164 (org-entry-get-with-inheritance property literal-nil)
15165 (if (member property org-special-properties)
15166 ;; We need a special property. Use `org-entry-properties' to
15167 ;; retrieve it, but specify the wanted property
15168 (cdr (assoc property (org-entry-properties nil 'special property)))
15169 (let ((range (org-get-property-block)))
15170 (when (and range (not (eq (car range) (cdr range))))
15171 (let* ((props (list (or (assoc property org-file-properties)
15172 (assoc property org-global-properties)
15173 (assoc property org-global-properties-fixed))))
15175 (when (re-search-forward
15176 (org-re-property key) (cdr range) t)
15178 (org-update-property-plist
15181 (org-match-string-no-properties 1) "")
15184 (goto-char (car range))
15185 (funcall ap property)
15186 (goto-char (car range))
15187 (while (funcall ap (concat property "+")))
15188 (setq val (cdr (assoc property props)))
15189 (when val (if literal-nil val (org-not-nil val))))))))))
15191 (defun org-property-or-variable-value (var &optional inherit)
15192 "Check if there is a property fixing the value of VAR.
15193 If yes, return this value. If not, return the current value of the variable."
15194 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15195 (if (and prop (stringp prop) (string-match "\\S-" prop))
15197 (symbol-value var))))
15199 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15200 "Delete the property PROPERTY from entry at point-or-marker POM.
15201 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15202 an empty drawer to delete."
15203 (org-with-point-at pom
15204 (if (member property org-special-properties)
15205 nil ; cannot delete these properties.
15206 (let ((range (org-get-property-block)))
15208 (goto-char (car range))
15210 (org-re-property property)
15213 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15214 (and delete-empty-drawer
15215 (org-remove-empty-drawer-at
15216 delete-empty-drawer (car range)))
15220 ;; Multi-values properties are properties that contain multiple values
15221 ;; These values are assumed to be single words, separated by whitespace.
15222 (defun org-entry-add-to-multivalued-property (pom property value)
15223 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15224 (let* ((old (org-entry-get pom property))
15225 (values (and old (org-split-string old "[ \t]"))))
15226 (setq value (org-entry-protect-space value))
15227 (unless (member value values)
15228 (setq values (append values (list value)))
15229 (org-entry-put pom property
15230 (mapconcat 'identity values " ")))))
15232 (defun org-entry-remove-from-multivalued-property (pom property value)
15233 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15234 (let* ((old (org-entry-get pom property))
15235 (values (and old (org-split-string old "[ \t]"))))
15236 (setq value (org-entry-protect-space value))
15237 (when (member value values)
15238 (setq values (delete value values))
15239 (org-entry-put pom property
15240 (mapconcat 'identity values " ")))))
15242 (defun org-entry-member-in-multivalued-property (pom property value)
15243 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15244 (let* ((old (org-entry-get pom property))
15245 (values (and old (org-split-string old "[ \t]"))))
15246 (setq value (org-entry-protect-space value))
15247 (member value values)))
15249 (defun org-entry-get-multivalued-property (pom property)
15250 "Return a list of values in a multivalued property."
15251 (let* ((value (org-entry-get pom property))
15252 (values (and value (org-split-string value "[ \t]"))))
15253 (mapcar 'org-entry-restore-space values)))
15255 (defun org-entry-put-multivalued-property (pom property &rest values)
15256 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15257 VALUES should be a list of strings. Spaces will be protected."
15258 (org-entry-put pom property
15259 (mapconcat 'org-entry-protect-space values " "))
15260 (let* ((value (org-entry-get pom property))
15261 (values (and value (org-split-string value "[ \t]"))))
15262 (mapcar 'org-entry-restore-space values)))
15264 (defun org-entry-protect-space (s)
15265 "Protect spaces and newline in string S."
15266 (while (string-match " " s)
15267 (setq s (replace-match "%20" t t s)))
15268 (while (string-match "\n" s)
15269 (setq s (replace-match "%0A" t t s)))
15272 (defun org-entry-restore-space (s)
15273 "Restore spaces and newline in string S."
15274 (while (string-match "%20" s)
15275 (setq s (replace-match " " t t s)))
15276 (while (string-match "%0A" s)
15277 (setq s (replace-match "\n" t t s)))
15280 (defvar org-entry-property-inherited-from (make-marker)
15281 "Marker pointing to the entry from where a property was inherited.
15282 Each call to `org-entry-get-with-inheritance' will set this marker to the
15283 location of the entry where the inheritance search matched. If there was
15284 no match, the marker will point nowhere.
15285 Note that also `org-entry-get' calls this function, if the INHERIT flag
15288 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15289 "Get PROPERTY of entry or content at point, search higher levels if needed.
15290 The search will stop at the first ancestor which has the property defined.
15291 If the value found is \"nil\", return nil to show that the property
15292 should be considered as undefined (this is the meaning of nil here).
15293 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15294 (move-marker org-entry-property-inherited-from nil)
15301 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15302 (or (ignore-errors (org-back-to-heading t))
15303 (goto-char (point-min)))
15304 (move-marker org-entry-property-inherited-from (point))
15306 (or (ignore-errors (org-up-heading-safe))
15307 (throw 'ex nil))))))
15309 (cdr (assoc property org-file-properties))
15310 (cdr (assoc property org-global-properties))
15311 (cdr (assoc property org-global-properties-fixed))))
15312 (if literal-nil tmp (org-not-nil tmp))))
15314 (defvar org-property-changed-functions nil
15315 "Hook called when the value of a property has changed.
15316 Each hook function should accept two arguments, the name of the property
15317 and the new value.")
15319 (defun org-entry-put (pom property value)
15320 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15321 (org-with-point-at pom
15322 (org-back-to-heading t)
15323 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15326 ((equal property "TODO")
15327 (when (and (stringp value) (string-match "\\S-" value)
15328 (not (member value org-todo-keywords-1)))
15329 (error "\"%s\" is not a valid TODO state" value))
15330 (if (or (not value)
15331 (not (string-match "\\S-" value)))
15332 (setq value 'none))
15334 (org-set-tags nil 'align))
15335 ((equal property "PRIORITY")
15336 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15337 (string-to-char value) ?\ ))
15338 (org-set-tags nil 'align))
15339 ((equal property "CLOCKSUM")
15340 (if (not (re-search-forward
15341 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15342 (error "Cannot find a clock log")
15343 (goto-char (- (match-end 1) 2))
15345 ((eq value 'earlier) (org-timestamp-down))
15346 ((eq value 'later) (org-timestamp-up)))
15347 (org-clock-sum-current-item)))
15348 ((equal property "SCHEDULED")
15349 (if (re-search-forward org-scheduled-time-regexp end t)
15351 ((eq value 'earlier) (org-timestamp-change -1 'day))
15352 ((eq value 'later) (org-timestamp-change 1 'day))
15353 (t (call-interactively 'org-schedule)))
15354 (call-interactively 'org-schedule)))
15355 ((equal property "DEADLINE")
15356 (if (re-search-forward org-deadline-time-regexp end t)
15358 ((eq value 'earlier) (org-timestamp-change -1 'day))
15359 ((eq value 'later) (org-timestamp-change 1 'day))
15360 (t (call-interactively 'org-deadline)))
15361 (call-interactively 'org-deadline)))
15362 ((member property org-special-properties)
15363 (error "The %s property can not yet be set with `org-entry-put'"
15365 (t ; a non-special property
15366 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15367 (setq range (org-get-property-block beg end 'force))
15368 (goto-char (car range))
15369 (if (re-search-forward
15370 (org-re-property-keyword property) (cdr range) t)
15372 (delete-region (match-beginning 0) (match-end 0))
15373 (goto-char (match-beginning 0)))
15374 (goto-char (cdr range))
15378 (insert ":" property ":")
15379 (and value (insert " " value))
15380 (org-indent-line)))))
15381 (run-hook-with-args 'org-property-changed-functions property value)))
15383 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15384 "Get all property keys in the current buffer.
15385 With INCLUDE-SPECIALS, also list the special properties that reflect things
15386 like tags and TODO state.
15387 With INCLUDE-DEFAULTS, also include properties that has special meaning
15388 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15390 With INCLUDE-COLUMNS, also include property names given in COLUMN
15391 formats in the current buffer."
15392 (let (rtn range cfmt s p)
15396 (goto-char (point-min))
15397 (while (re-search-forward org-property-start-re nil t)
15398 (setq range (org-get-property-block))
15399 (goto-char (car range))
15400 (while (re-search-forward
15401 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15403 (add-to-list 'rtn (org-match-string-no-properties 1)))
15404 (outline-next-heading))))
15406 (when include-specials
15407 (setq rtn (append org-special-properties rtn)))
15409 (when include-defaults
15410 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15411 (add-to-list 'rtn org-effort-property))
15413 (when include-columns
15417 (goto-char (point-min))
15418 (while (re-search-forward
15419 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15421 (setq cfmt (match-string 2) s 0)
15422 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15424 (setq s (match-end 0)
15425 p (match-string 1 cfmt))
15426 (unless (or (equal p "ITEM")
15427 (member p org-special-properties))
15428 (add-to-list 'rtn (match-string 1 cfmt))))))))
15430 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15432 (defun org-property-values (key)
15433 "Return a list of all values of property KEY in the current buffer."
15437 (goto-char (point-min))
15438 (let ((re (org-re-property key))
15440 (while (re-search-forward re nil t)
15441 (add-to-list 'values (org-trim (match-string 1))))
15442 (delete "" values)))))
15444 (defun org-insert-property-drawer ()
15445 "Insert a property drawer into the current entry."
15446 (org-back-to-heading t)
15447 (looking-at org-outline-regexp)
15448 (let ((indent (if org-adapt-indentation
15449 (- (match-end 0) (match-beginning 0))
15452 (re (concat "^[ \t]*" org-keyword-time-regexp))
15454 (outline-next-heading)
15457 (while (re-search-forward re end t))
15458 (setq hiddenp (outline-invisible-p))
15460 (and (equal (char-after) ?\n) (forward-char 1))
15461 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15462 (if (member (match-string 1) '("CLOCK:" ":END:"))
15463 ;; just skip this line
15464 (beginning-of-line 2)
15465 ;; Drawer start, find the end
15466 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15467 (beginning-of-line 1)))
15468 (org-skip-over-state-notes)
15469 (skip-chars-backward " \t\n\r")
15470 (if (eq (char-before) ?*) (forward-char 1))
15471 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15472 (beginning-of-line 0)
15473 (org-indent-to-column indent)
15474 (beginning-of-line 2)
15475 (org-indent-to-column indent)
15476 (beginning-of-line 0)
15479 (org-back-to-heading t)
15481 (org-flag-drawer t))))
15483 (defun org-insert-drawer (&optional arg drawer)
15484 "Insert a drawer at point.
15486 Optional argument DRAWER, when non-nil, is a string representing
15487 drawer's name. Otherwise, the user is prompted for a name.
15489 If a region is active, insert the drawer around that region
15492 Point is left between drawer's boundaries."
15494 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15496 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15497 ;; internally by Org. They are meant to be inserted
15499 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15500 ;; Remove system drawers from list. Note: For some reason,
15501 ;; `org-completing-read' ignores the predicate while
15502 ;; `completing-read' handles it fine.
15503 (drawer (if arg "PROPERTIES"
15506 "Drawer: " org-drawers
15507 (lambda (d) (not (member d system-drawers))))))))
15509 ;; With C-u, fall back on `org-insert-property-drawer'
15510 (arg (org-insert-property-drawer))
15511 ;; With an active region, insert a drawer at point.
15512 ((not (org-region-active-p))
15514 (unless (bolp) (insert "\n"))
15515 (insert (format ":%s:\n\n:END:\n" drawer))
15516 (forward-line -2)))
15517 ;; Otherwise, insert the drawer at point
15519 (let ((rbeg (region-beginning))
15520 (rend (copy-marker (region-end))))
15524 (beginning-of-line)
15525 (when (save-excursion
15526 (re-search-forward org-outline-regexp-bol rend t))
15527 (error "Drawers cannot contain headlines"))
15528 ;; Position point at the beginning of the first
15529 ;; non-blank line in region. Insert drawer's opening
15530 ;; there, then indent it.
15531 (org-skip-whitespace)
15532 (beginning-of-line)
15533 (insert ":" drawer ":\n")
15535 (indent-for-tab-command)
15536 ;; Move point to the beginning of the first blank line
15537 ;; after the last non-blank line in region. Insert
15538 ;; drawer's closing, then indent it.
15540 (skip-chars-backward " \r\t\n")
15542 (deactivate-mark t)
15543 (indent-for-tab-command)
15544 (unless (eolp) (insert "\n")))
15545 ;; Clear marker, whatever the outcome of insertion is.
15546 (set-marker rend nil)))))))
15548 (defvar org-property-set-functions-alist nil
15549 "Property set function alist.
15550 Each entry should have the following format:
15552 (PROPERTY . READ-FUNCTION)
15554 The read function will be called with the same argument as
15555 `org-completing-read'.")
15557 (defun org-set-property-function (property)
15558 "Get the function that should be used to set PROPERTY.
15559 This is computed according to `org-property-set-functions-alist'."
15560 (or (cdr (assoc property org-property-set-functions-alist))
15561 'org-completing-read))
15563 (defun org-read-property-value (property)
15564 "Read PROPERTY value from user."
15565 (let* ((completion-ignore-case t)
15566 (allowed (org-property-get-allowed-values nil property 'table))
15567 (cur (org-entry-get nil property))
15568 (prompt (concat property " value"
15569 (if (and cur (string-match "\\S-" cur))
15570 (concat " [" cur "]") "") ": "))
15571 (set-function (org-set-property-function property))
15573 (funcall set-function prompt allowed nil
15574 (not (get-text-property 0 'org-unrestricted
15576 (let (org-completion-use-ido org-completion-use-iswitchb)
15577 (funcall set-function prompt
15578 (mapcar 'list (org-property-values property))
15579 nil nil "" nil cur)))))
15584 (defvar org-last-set-property nil)
15585 (defvar org-last-set-property-value nil)
15586 (defun org-read-property-name ()
15587 "Read a property name."
15588 (let* ((completion-ignore-case t)
15589 (keys (org-buffer-property-keys nil t t))
15590 (default-prop (or (save-excursion
15592 (beginning-of-line)
15593 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15594 (null (string= (match-string 1) "END"))
15595 (match-string 1))))
15596 org-last-set-property))
15597 (property (org-icompleting-read
15599 (if default-prop (concat " [" default-prop "]") "")
15601 (mapcar 'list keys)
15604 (if (member property keys)
15606 (or (cdr (assoc (downcase property)
15607 (mapcar (lambda (x) (cons (downcase x) x))
15611 (defun org-set-property-and-value (use-last)
15612 "Allow to set [PROPERTY]: [value] direction from prompt.
15613 When use-default, don't even ask, just use the last
15614 \"[PROPERTY]: [value]\" string from the history."
15616 (let* ((completion-ignore-case t)
15617 (pv (or (and use-last org-last-set-property-value)
15618 (org-completing-read
15619 "Enter a \"[Property]: [value]\" pair: "
15620 nil nil nil nil nil
15621 org-last-set-property-value)))
15623 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15624 (setq prop (match-string 1 pv)
15625 val (match-string 2 pv))
15626 (org-set-property prop val))))
15628 (defun org-set-property (property value)
15629 "In the current entry, set PROPERTY to VALUE.
15630 When called interactively, this will prompt for a property name, offering
15631 completion on existing and default properties. And then it will prompt
15632 for a value, offering completion either on allowed values (via an inherited
15633 xxx_ALL property) or on existing values in other instances of this property
15634 in the current file."
15635 (interactive (list nil nil))
15636 (let* ((property (or property (org-read-property-name)))
15637 (value (or value (org-read-property-value property)))
15638 (fn (cdr (assoc property org-properties-postprocess-alist))))
15639 (setq org-last-set-property property)
15640 (setq org-last-set-property-value (concat property ": " value))
15641 ;; Possibly postprocess the inserted value:
15642 (when fn (setq value (funcall fn value)))
15643 (unless (equal (org-entry-get nil property) value)
15644 (org-entry-put nil property value))))
15646 (defun org-delete-property (property &optional delete-empty-drawer)
15647 "In the current entry, delete PROPERTY.
15648 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15649 an empty drawer to delete."
15651 (let* ((completion-ignore-case t)
15652 (prop (org-icompleting-read "Property: "
15653 (org-entry-properties nil 'standard))))
15655 (message "Property %s %s" property
15656 (if (org-entry-delete nil property delete-empty-drawer)
15658 "was not present in the entry")))
15660 (defun org-delete-property-globally (property)
15661 "Remove PROPERTY globally, from all entries."
15663 (let* ((completion-ignore-case t)
15664 (prop (org-icompleting-read
15665 "Globally remove property: "
15666 (mapcar 'list (org-buffer-property-keys)))))
15671 (goto-char (point-min))
15673 (while (re-search-forward
15674 (org-re-property property)
15676 (setq cnt (1+ cnt))
15677 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15678 (message "Property \"%s\" removed from %d entries" property cnt)))))
15680 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15682 (defun org-compute-property-at-point ()
15683 "Compute the property at point.
15684 This looks for an enclosing column format, extracts the operator and
15685 then applies it to the property in the column format's scope."
15687 (unless (org-at-property-p)
15688 (error "Not at a property"))
15689 (let ((prop (org-match-string-no-properties 2)))
15690 (org-columns-get-format-and-top-level)
15691 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15692 (error "No operator defined for property %s" prop))
15693 (org-columns-compute prop)))
15695 (defvar org-property-allowed-value-functions nil
15696 "Hook for functions supplying allowed values for a specific property.
15697 The functions must take a single argument, the name of the property, and
15698 return a flat list of allowed values. If \":ETC\" is one of
15699 the values, this means that these values are intended as defaults for
15700 completion, but that other values should be allowed too.
15701 The functions must return nil if they are not responsible for this
15704 (defun org-property-get-allowed-values (pom property &optional table)
15705 "Get allowed values for the property PROPERTY.
15706 When TABLE is non-nil, return an alist that can directly be used for
15710 ((equal property "TODO")
15711 (setq vals (org-with-point-at pom
15712 (append org-todo-keywords-1 '("")))))
15713 ((equal property "PRIORITY")
15714 (let ((n org-lowest-priority))
15715 (while (>= n org-highest-priority)
15716 (push (char-to-string n) vals)
15718 ((member property org-special-properties))
15719 ((setq vals (run-hook-with-args-until-success
15720 'org-property-allowed-value-functions property)))
15722 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15723 (when (and vals (string-match "\\S-" vals))
15724 (setq vals (car (read-from-string (concat "(" vals ")"))))
15725 (setq vals (mapcar (lambda (x)
15726 (cond ((stringp x) x)
15727 ((numberp x) (number-to-string x))
15728 ((symbolp x) (symbol-name x))
15731 (when (member ":ETC" vals)
15732 (setq vals (remove ":ETC" vals))
15733 (org-add-props (car vals) '(org-unrestricted t)))
15734 (if table (mapcar 'list vals) vals)))
15736 (defun org-property-previous-allowed-value (&optional previous)
15737 "Switch to the next allowed value for this property."
15739 (org-property-next-allowed-value t))
15741 (defun org-property-next-allowed-value (&optional previous)
15742 "Switch to the next allowed value for this property."
15744 (unless (org-at-property-p)
15745 (error "Not at a property"))
15746 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15747 (key (match-string 2))
15748 (value (match-string 3))
15749 (allowed (or (org-property-get-allowed-values (point) key)
15750 (and (member value '("[ ]" "[-]" "[X]"))
15752 (heading (save-match-data (nth 4 (org-heading-components))))
15755 (error "Allowed values for this property have not been defined"))
15756 (if previous (setq allowed (reverse allowed)))
15757 (if (member value allowed)
15758 (setq nval (car (cdr (member value allowed)))))
15759 (setq nval (or nval (car allowed)))
15760 (if (equal nval value)
15761 (error "Only one allowed value for this property"))
15762 (org-at-property-p)
15763 (replace-match (concat " :" key ": " nval) t t)
15765 (beginning-of-line 1)
15766 (skip-chars-forward " \t")
15767 (when (equal prop org-effort-property)
15769 (org-back-to-heading t)
15770 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15771 (when (string= org-clock-current-task heading)
15772 (setq org-clock-effort nval)
15773 (org-clock-update-mode-line)))
15774 (run-hook-with-args 'org-property-changed-functions key nval)))
15776 (defun org-find-olp (path &optional this-buffer)
15777 "Return a marker pointing to the entry at outline path OLP.
15778 If anything goes wrong, throw an error.
15779 You can wrap this call to catch the error like this:
15781 (condition-case msg
15782 (org-mobile-locate-entry (match-string 4))
15783 (error (nth 1 msg)))
15785 The return value will then be either a string with the error message,
15786 or a marker if everything is OK.
15788 If THIS-BUFFER is set, the outline path does not contain a file,
15790 (let* ((file (if this-buffer buffer-file-name (pop path)))
15791 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15795 limit re end found pos heading cnt flevel)
15796 (unless buffer (error "File not found :%s" file))
15797 (with-current-buffer buffer
15801 (setq limit (point-max))
15802 (goto-char (point-min))
15803 (while (setq heading (pop path))
15804 (setq re (format org-complex-heading-regexp-format
15805 (regexp-quote heading)))
15806 (setq cnt 0 pos (point))
15807 (while (re-search-forward re end t)
15808 (setq level (- (match-end 1) (match-beginning 1)))
15809 (if (and (>= level lmin) (<= level lmax))
15810 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15811 (when (= cnt 0) (error "Heading not found on level %d: %s"
15813 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15816 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15817 (setq end (save-excursion (org-end-of-subtree t t))))
15818 (when (org-at-heading-p)
15819 (point-marker)))))))
15821 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15822 "Find node HEADING in BUFFER.
15823 Return a marker to the heading if it was found, or nil if not.
15824 If POS-ONLY is set, return just the position instead of a marker.
15826 The heading text must match exact, but it may have a TODO keyword,
15827 a priority cookie and tags in the standard locations."
15828 (with-current-buffer (or buffer (current-buffer))
15832 (goto-char (point-min))
15833 (let (case-fold-search)
15834 (if (re-search-forward
15835 (format org-complex-heading-regexp-format
15836 (regexp-quote heading)) nil t)
15838 (match-beginning 0)
15839 (move-marker (make-marker) (match-beginning 0)))))))))
15841 (defun org-find-exact-heading-in-directory (heading &optional dir)
15842 "Find Org node headline HEADING in all .org files in directory DIR.
15843 When the target headline is found, return a marker to this location."
15844 (let ((files (directory-files (or dir default-directory)
15845 nil "\\`[^.#].*\\.org\\'"))
15846 file visiting m buffer)
15848 (while (setq file (pop files))
15849 (message "trying %s" file)
15850 (setq visiting (org-find-base-buffer-visiting file))
15851 (setq buffer (or visiting (find-file-noselect file)))
15852 (setq m (org-find-exact-headline-in-buffer
15854 (when (and (not m) (not visiting)) (kill-buffer buffer))
15855 (and m (throw 'found m))))))
15857 (defun org-find-entry-with-id (ident)
15858 "Locate the entry that contains the ID property with exact value IDENT.
15859 IDENT can be a string, a symbol or a number, this function will search for
15860 the string representation of it.
15861 Return the position where this entry starts, or nil if there is no such entry."
15862 (interactive "sID: ")
15864 ((stringp ident) ident)
15865 ((symbol-name ident) (symbol-name ident))
15866 ((numberp ident) (number-to-string ident))
15867 (t (error "IDENT %s must be a string, symbol or number" ident))))
15868 (case-fold-search nil))
15872 (goto-char (point-min))
15873 (when (re-search-forward
15874 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15876 (org-back-to-heading t)
15881 (defvar org-last-changed-timestamp nil)
15882 (defvar org-last-inserted-timestamp nil
15883 "The last time stamp inserted with `org-insert-time-stamp'.")
15884 (defvar org-time-was-given) ; dynamically scoped parameter
15885 (defvar org-end-time-was-given) ; dynamically scoped parameter
15886 (defvar org-ts-what) ; dynamically scoped parameter
15888 (defun org-time-stamp (arg &optional inactive)
15889 "Prompt for a date/time and insert a time stamp.
15890 If the user specifies a time like HH:MM or if this command is
15891 called with at least one prefix argument, the time stamp contains
15892 the date and the time. Otherwise, only the date is be included.
15894 All parts of a date not specified by the user is filled in from
15895 the current date/time. So if you just press return without
15896 typing anything, the time stamp will represent the current
15899 If there is already a timestamp at the cursor, it will be
15902 With two universal prefix arguments, insert an active timestamp
15903 with the current time without prompting the user."
15907 ;; Default time is either today, or, when entering a range,
15908 ;; the range start.
15909 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15911 (re-search-backward
15912 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15913 (- (point) 20) t)))
15914 (apply 'encode-time (org-parse-time-string (match-string 1)))
15916 (default-input (and ts (org-get-compact-tod ts)))
15917 (repeater (save-excursion
15919 (beginning-of-line)
15920 (when (re-search-forward
15921 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15922 (save-excursion (progn (end-of-line) (point))) t)
15923 (match-string 0)))))
15924 org-time-was-given org-end-time-was-given time)
15926 ((and (org-at-timestamp-p t)
15927 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15928 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15930 (setq time (let ((this-command this-command))
15931 (org-read-date arg 'totime nil nil
15932 default-time default-input inactive)))
15933 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15934 ((org-at-timestamp-p t)
15935 (setq time (let ((this-command this-command))
15936 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15937 (when (org-at-timestamp-p t) ; just to get the match data
15938 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15940 (setq org-last-changed-timestamp
15941 (org-insert-time-stamp
15942 time (or org-time-was-given arg)
15943 inactive nil nil (list org-end-time-was-given)))
15944 (when repeater (goto-char (1- (point))) (insert " " repeater)
15945 (setq org-last-changed-timestamp
15946 (concat (substring org-last-inserted-timestamp 0 -1)
15947 " " repeater ">"))))
15948 (message "Timestamp updated"))
15950 (org-insert-time-stamp (current-time) t))
15952 (setq time (let ((this-command this-command))
15953 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15954 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15955 nil nil (list org-end-time-was-given))))))
15957 ;; FIXME: can we use this for something else, like computing time differences?
15958 (defun org-get-compact-tod (s)
15959 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15960 (let* ((t1 (match-string 1 s))
15961 (h1 (string-to-number (match-string 2 s)))
15962 (m1 (string-to-number (match-string 3 s)))
15963 (t2 (and (match-end 4) (match-string 5 s)))
15964 (h2 (and t2 (string-to-number (match-string 6 s))))
15965 (m2 (and t2 (string-to-number (match-string 7 s))))
15969 (setq dh (- h2 h1) dm (- m2 m1))
15970 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15971 (concat t1 "+" (number-to-string dh)
15972 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15974 (defun org-time-stamp-inactive (&optional arg)
15975 "Insert an inactive time stamp.
15976 An inactive time stamp is enclosed in square brackets instead of angle
15977 brackets. It is inactive in the sense that it does not trigger agenda entries,
15978 does not link to the calendar and cannot be changed with the S-cursor keys.
15979 So these are more for recording a certain time/date."
15981 (org-time-stamp arg 'inactive))
15983 (defvar org-date-ovl (make-overlay 1 1))
15984 (overlay-put org-date-ovl 'face 'org-date-selected)
15985 (org-detach-overlay org-date-ovl)
15987 (defvar org-ans1) ; dynamically scoped parameter
15988 (defvar org-ans2) ; dynamically scoped parameter
15990 (defvar org-plain-time-of-day-regexp) ; defined below
15992 (defvar org-overriding-default-time nil) ; dynamically scoped
15993 (defvar org-read-date-overlay nil)
15994 (defvar org-dcst nil) ; dynamically scoped
15995 (defvar org-read-date-history nil)
15996 (defvar org-read-date-final-answer nil)
15997 (defvar org-read-date-analyze-futurep nil)
15998 (defvar org-read-date-analyze-forced-year nil)
15999 (defvar org-read-date-inactive)
16001 (defvar org-read-date-minibuffer-local-map
16002 (let ((map (make-sparse-keymap)))
16003 (set-keymap-parent map minibuffer-local-map)
16004 (org-defkey map (kbd ".")
16005 (lambda () (interactive)
16006 (org-eval-in-calendar '(calendar-goto-today))))
16007 (org-defkey map [(meta shift left)]
16008 (lambda () (interactive)
16009 (org-eval-in-calendar '(calendar-backward-month 1))))
16010 (org-defkey map [(meta shift right)]
16011 (lambda () (interactive)
16012 (org-eval-in-calendar '(calendar-forward-month 1))))
16013 (org-defkey map [(meta shift up)]
16014 (lambda () (interactive)
16015 (org-eval-in-calendar '(calendar-backward-year 1))))
16016 (org-defkey map [(meta shift down)]
16017 (lambda () (interactive)
16018 (org-eval-in-calendar '(calendar-forward-year 1))))
16019 (org-defkey map [?\e (shift left)]
16020 (lambda () (interactive)
16021 (org-eval-in-calendar '(calendar-backward-month 1))))
16022 (org-defkey map [?\e (shift right)]
16023 (lambda () (interactive)
16024 (org-eval-in-calendar '(calendar-forward-month 1))))
16025 (org-defkey map [?\e (shift up)]
16026 (lambda () (interactive)
16027 (org-eval-in-calendar '(calendar-backward-year 1))))
16028 (org-defkey map [?\e (shift down)]
16029 (lambda () (interactive)
16030 (org-eval-in-calendar '(calendar-forward-year 1))))
16031 (org-defkey map [(shift up)]
16032 (lambda () (interactive)
16033 (org-eval-in-calendar '(calendar-backward-week 1))))
16034 (org-defkey map [(shift down)]
16035 (lambda () (interactive)
16036 (org-eval-in-calendar '(calendar-forward-week 1))))
16037 (org-defkey map [(shift left)]
16038 (lambda () (interactive)
16039 (org-eval-in-calendar '(calendar-backward-day 1))))
16040 (org-defkey map [(shift right)]
16041 (lambda () (interactive)
16042 (org-eval-in-calendar '(calendar-forward-day 1))))
16043 (org-defkey map "!"
16044 (lambda () (interactive)
16045 (org-eval-in-calendar '(diary-view-entries))
16047 (org-defkey map ">"
16048 (lambda () (interactive)
16049 (org-eval-in-calendar '(scroll-calendar-left 1))))
16050 (org-defkey map "<"
16051 (lambda () (interactive)
16052 (org-eval-in-calendar '(scroll-calendar-right 1))))
16053 (org-defkey map "\C-v"
16054 (lambda () (interactive)
16055 (org-eval-in-calendar
16056 '(calendar-scroll-left-three-months 1))))
16057 (org-defkey map "\M-v"
16058 (lambda () (interactive)
16059 (org-eval-in-calendar
16060 '(calendar-scroll-right-three-months 1))))
16062 "Keymap for minibuffer commands when using `org-read-date'.")
16064 (defun org-read-date (&optional org-with-time to-time from-string prompt
16065 default-time default-input inactive)
16066 "Read a date, possibly a time, and make things smooth for the user.
16067 The prompt will suggest to enter an ISO date, but you can also enter anything
16068 which will at least partially be understood by `parse-time-string'.
16069 Unrecognized parts of the date will default to the current day, month, year,
16070 hour and minute. If this command is called to replace a timestamp at point,
16071 or to enter the second timestamp of a range, the default time is taken
16072 from the existing stamp. Furthermore, the command prefers the future,
16073 so if you are giving a date where the year is not given, and the day-month
16074 combination is already past in the current year, it will assume you
16075 mean next year. For details, see the manual. A few examples:
16077 3-2-5 --> 2003-02-05
16078 feb 15 --> currentyear-02-15
16079 2/15 --> currentyear-02-15
16080 sep 12 9 --> 2009-09-12
16081 12:45 --> today 12:45
16082 22 sept 0:34 --> currentyear-09-22 0:34
16083 12 --> currentyear-currentmonth-12
16084 Fri --> nearest Friday (today or later)
16087 Furthermore you can specify a relative date by giving, as the *first* thing
16088 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16089 change in days weeks, months, years.
16090 With a single plus or minus, the date is relative to today. With a double
16091 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16092 +4d --> four days from today
16093 +4 --> same as above
16094 +2w --> two weeks from today
16095 ++5 --> five days from default date
16097 The function understands only English month and weekday abbreviations.
16099 While prompting, a calendar is popped up - you can also select the
16100 date with the mouse (button 1). The calendar shows a period of three
16101 months. To scroll it to other months, use the keys `>' and `<'.
16102 If you don't like the calendar, turn it off with
16103 \(setq org-read-date-popup-calendar nil)
16105 With optional argument TO-TIME, the date will immediately be converted
16106 to an internal time.
16107 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16108 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16109 still enter a time, and this function will inform the calling routine
16110 about this change. The calling routine may then choose to change the
16111 format used to insert the time stamp into the buffer to include the time.
16112 With optional argument FROM-STRING, read from this string instead from
16113 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16114 the time/date that is used for everything that is not specified by the
16116 (require 'parse-time)
16117 (let* ((org-time-stamp-rounding-minutes
16118 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16119 (org-dcst org-display-custom-times)
16120 (ct (org-current-time))
16121 (org-def (or org-overriding-default-time default-time ct))
16122 (org-defdecode (decode-time org-def))
16124 (when (< (nth 2 org-defdecode) org-extend-today-until)
16125 (setcar (nthcdr 2 org-defdecode) -1)
16126 (setcar (nthcdr 1 org-defdecode) 59)
16127 (setq org-def (apply 'encode-time org-defdecode)
16128 org-defdecode (decode-time org-def)))))
16129 (mouse-autoselect-window nil) ; Don't let the mouse jump
16130 (calendar-frame-setup nil)
16131 (calendar-setup nil)
16132 (calendar-move-hook nil)
16133 (calendar-view-diary-initially-flag nil)
16134 (calendar-view-holidays-initially-flag nil)
16135 (timestr (format-time-string
16136 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16137 (prompt (concat (if prompt (concat prompt " ") "")
16138 (format "Date+time [%s]: " timestr)))
16139 ans (org-ans0 "") org-ans1 org-ans2 final)
16142 (from-string (setq ans from-string))
16143 (org-read-date-popup-calendar
16145 (save-window-excursion
16147 (org-eval-in-calendar '(setq cursor-type nil) t)
16150 (calendar-forward-day (- (time-to-days org-def)
16151 (calendar-absolute-from-gregorian
16152 (calendar-current-date))))
16153 (org-eval-in-calendar nil t)
16154 (let* ((old-map (current-local-map))
16155 (map (copy-keymap calendar-mode-map))
16156 (minibuffer-local-map
16157 (copy-keymap org-read-date-minibuffer-local-map)))
16158 (org-defkey map (kbd "RET") 'org-calendar-select)
16159 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16160 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16163 (use-local-map map)
16164 (setq org-read-date-inactive inactive)
16165 (add-hook 'post-command-hook 'org-read-date-display)
16166 (setq org-ans0 (read-string prompt default-input
16167 'org-read-date-history nil))
16168 ;; org-ans0: from prompt
16169 ;; org-ans1: from mouse click
16170 ;; org-ans2: from calendar motion
16171 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16172 (remove-hook 'post-command-hook 'org-read-date-display)
16173 (use-local-map old-map)
16174 (when org-read-date-overlay
16175 (delete-overlay org-read-date-overlay)
16176 (setq org-read-date-overlay nil)))))
16177 (bury-buffer "*Calendar*")))))
16179 (t ; Naked prompt only
16181 (setq ans (read-string prompt default-input
16182 'org-read-date-history timestr))
16183 (when org-read-date-overlay
16184 (delete-overlay org-read-date-overlay)
16185 (setq org-read-date-overlay nil)))))
16187 (setq final (org-read-date-analyze ans org-def org-defdecode))
16189 (when org-read-date-analyze-forced-year
16190 (message "Year was forced into %s"
16191 (if org-read-date-force-compatible-dates
16192 "compatible range (1970-2037)"
16193 "range representable on this machine"))
16196 ;; One round trip to get rid of 34th of August and stuff like that....
16197 (setq final (decode-time (apply 'encode-time final)))
16199 (setq org-read-date-final-answer ans)
16202 (apply 'encode-time final)
16203 (if (and (boundp 'org-time-was-given) org-time-was-given)
16204 (format "%04d-%02d-%02d %02d:%02d"
16205 (nth 5 final) (nth 4 final) (nth 3 final)
16206 (nth 2 final) (nth 1 final))
16207 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16210 (defvar org-defdecode)
16211 (defvar org-with-time)
16212 (defun org-read-date-display ()
16213 "Display the current date prompt interpretation in the minibuffer."
16214 (when org-read-date-display-live
16215 (when org-read-date-overlay
16216 (delete-overlay org-read-date-overlay))
16217 (when (minibufferp (current-buffer))
16220 (while (not (equal (buffer-substring
16221 (max (point-min) (- (point) 4)) (point))
16224 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16225 " " (or org-ans1 org-ans2)))
16226 (org-end-time-was-given nil)
16227 (f (org-read-date-analyze ans org-def org-defdecode))
16229 org-time-stamp-custom-formats
16230 org-time-stamp-formats))
16231 (fmt (if (or org-with-time
16232 (and (boundp 'org-time-was-given) org-time-was-given))
16235 (txt (format-time-string fmt (apply 'encode-time f)))
16236 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16237 (txt (concat "=> " txt)))
16238 (when (and org-end-time-was-given
16239 (string-match org-plain-time-of-day-regexp txt))
16240 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16241 org-end-time-was-given
16242 (substring txt (match-end 0)))))
16243 (when org-read-date-analyze-futurep
16244 (setq txt (concat txt " (=>F)")))
16245 (setq org-read-date-overlay
16246 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16247 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16249 (defun org-read-date-analyze (ans org-def org-defdecode)
16250 "Analyze the combined answer of the date prompt."
16251 ;; FIXME: cleanup and comment
16252 (let ((nowdecode (decode-time (current-time)))
16253 delta deltan deltaw deltadef year month day
16254 hour minute second wday pm h2 m2 tl wday1
16255 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16256 (setq org-read-date-analyze-futurep nil
16257 org-read-date-analyze-forced-year nil)
16258 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16261 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16262 (setq ans (replace-match "" t t ans)
16264 deltaw (nth 1 delta)
16265 deltadef (nth 2 delta)))
16267 ;; Check if there is an iso week date in there. If yes, store the
16268 ;; info and postpone interpreting it until the rest of the parsing
16270 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16271 (setq iso-year (if (match-end 1)
16272 (org-small-year-to-year
16273 (string-to-number (match-string 1 ans))))
16274 iso-weekday (if (match-end 3)
16275 (string-to-number (match-string 3 ans)))
16276 iso-week (string-to-number (match-string 2 ans)))
16277 (setq ans (replace-match "" t t ans)))
16279 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16280 (when (string-match
16281 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16282 (setq year (if (match-end 2)
16283 (string-to-number (match-string 2 ans))
16284 (progn (setq kill-year t)
16285 (string-to-number (format-time-string "%Y"))))
16286 month (string-to-number (match-string 3 ans))
16287 day (string-to-number (match-string 4 ans)))
16288 (if (< year 100) (setq year (+ 2000 year)))
16289 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16292 ;; Help matching dotted european dates
16293 (when (string-match
16294 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16295 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16297 (string-to-number (format-time-string "%Y")))
16298 day (string-to-number (match-string 1 ans))
16299 month (string-to-number (match-string 2 ans))
16300 ans (replace-match (format "%04d-%02d-%02d" year month day)
16303 ;; Help matching american dates, like 5/30 or 5/30/7
16304 (when (string-match
16305 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16306 (setq year (if (match-end 4)
16307 (string-to-number (match-string 4 ans))
16308 (progn (setq kill-year t)
16309 (string-to-number (format-time-string "%Y"))))
16310 month (string-to-number (match-string 1 ans))
16311 day (string-to-number (match-string 2 ans)))
16312 (if (< year 100) (setq year (+ 2000 year)))
16313 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16315 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16316 ;; If there is a time with am/pm, and *no* time without it, we convert
16317 ;; so that matching will be successful.
16318 (loop for i from 1 to 2 do ; twice, for end time as well
16319 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16320 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16321 (setq hour (string-to-number (match-string 1 ans))
16322 minute (if (match-end 3)
16323 (string-to-number (match-string 3 ans))
16326 (string-to-char (downcase (match-string 4 ans)))))
16327 (if (and (= hour 12) (not pm))
16329 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16330 (setq ans (replace-match (format "%02d:%02d" hour minute)
16333 ;; Check if a time range is given as a duration
16334 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16335 (setq hour (string-to-number (match-string 1 ans))
16336 h2 (+ hour (string-to-number (match-string 3 ans)))
16337 minute (string-to-number (match-string 2 ans))
16338 m2 (+ minute (if (match-end 5) (string-to-number
16339 (match-string 5 ans))0)))
16340 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16341 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16344 ;; Check if there is a time range
16345 (when (boundp 'org-end-time-was-given)
16346 (setq org-time-was-given nil)
16347 (when (and (string-match org-plain-time-of-day-regexp ans)
16349 (setq org-end-time-was-given (match-string 8 ans))
16350 (setq ans (concat (substring ans 0 (match-beginning 7))
16351 (substring ans (match-end 7))))))
16353 (setq tl (parse-time-string ans)
16354 day (or (nth 3 tl) (nth 3 org-defdecode))
16355 month (or (nth 4 tl)
16356 (if (and org-read-date-prefer-future
16357 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16358 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16359 (nth 4 org-defdecode)))
16360 year (or (and (not kill-year) (nth 5 tl))
16361 (if (and org-read-date-prefer-future
16362 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16363 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16364 (nth 5 org-defdecode)))
16365 hour (or (nth 2 tl) (nth 2 org-defdecode))
16366 minute (or (nth 1 tl) (nth 1 org-defdecode))
16367 second (or (nth 0 tl) 0)
16370 (when (and (eq org-read-date-prefer-future 'time)
16371 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16372 (equal day (nth 3 nowdecode))
16373 (equal month (nth 4 nowdecode))
16374 (equal year (nth 5 nowdecode))
16376 (or (< (nth 2 tl) (nth 2 nowdecode))
16377 (and (= (nth 2 tl) (nth 2 nowdecode))
16379 (< (nth 1 tl) (nth 1 nowdecode)))))
16383 ;; Special date definitions below
16386 ;; There was an iso week
16389 (setq year (or iso-year year)
16390 day (or iso-weekday wday 1)
16391 wday nil ; to make sure that the trigger below does not match
16392 iso-date (calendar-gregorian-from-absolute
16393 (calendar-absolute-from-iso
16394 (list iso-week day year))))
16395 ; FIXME: Should we also push ISO weeks into the future?
16396 ; (when (and org-read-date-prefer-future
16398 ; (< (calendar-absolute-from-gregorian iso-date)
16399 ; (time-to-days (current-time))))
16400 ; (setq year (1+ year)
16401 ; iso-date (calendar-gregorian-from-absolute
16402 ; (calendar-absolute-from-iso
16403 ; (list iso-week day year)))))
16404 (setq month (car iso-date)
16405 year (nth 2 iso-date)
16406 day (nth 1 iso-date)))
16410 (let ((now (decode-time (current-time))))
16411 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16412 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16413 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16414 ((equal deltaw "m") (setq month (+ month deltan)))
16415 ((equal deltaw "y") (setq year (+ year deltan)))))
16416 ((and wday (not (nth 3 tl)))
16417 ;; Weekday was given, but no day, so pick that day in the week
16418 ;; on or after the derived date.
16419 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16420 (unless (equal wday wday1)
16421 (setq day (+ day (% (- wday wday1 -7) 7))))))
16422 (if (and (boundp 'org-time-was-given)
16424 (setq org-time-was-given t))
16425 (if (< year 100) (setq year (+ 2000 year)))
16426 ;; Check of the date is representable
16427 (if org-read-date-force-compatible-dates
16430 (setq year 1970 org-read-date-analyze-forced-year t))
16432 (setq year 2037 org-read-date-analyze-forced-year t)))
16433 (condition-case nil
16434 (ignore (encode-time second minute hour day month year))
16436 (setq year (nth 5 org-defdecode))
16437 (setq org-read-date-analyze-forced-year t))))
16438 (setq org-read-date-analyze-futurep futurep)
16439 (list second minute hour day month year)))
16441 (defvar parse-time-weekdays)
16442 (defun org-read-date-get-relative (s today default)
16443 "Check string S for special relative date string.
16444 TODAY and DEFAULT are internal times, for today and for a default.
16445 Return shift list (N what def-flag)
16446 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16447 N is the number of WHATs to shift.
16448 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16449 the DEFAULT date rather than TODAY."
16450 (require 'parse-time)
16454 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16456 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16457 "\\([ \t]\\|$\\)") s)
16458 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16459 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16460 (string-to-char (substring (match-string 1 s) -1))
16462 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16463 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16464 (what (if (match-end 3) (match-string 3 s) "d"))
16465 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16466 (date (if rel default today))
16467 (wday (nth 6 (decode-time date)))
16471 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16472 (if (= dir ?-) (setq delta (- delta 7)))
16473 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16474 (list delta "d" rel))
16475 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16477 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16478 "Turn a user-specified date into the internal representation.
16479 The internal representation needed by the calendar is (month day year).
16480 This is a wrapper to handle the brain-dead convention in calendar that
16481 user function argument order change dependent on argument order."
16482 (if (boundp 'calendar-date-style)
16484 ((eq calendar-date-style 'american)
16485 (list arg1 arg2 arg3))
16486 ((eq calendar-date-style 'european)
16487 (list arg2 arg1 arg3))
16488 ((eq calendar-date-style 'iso)
16489 (list arg2 arg3 arg1)))
16490 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16491 (if (org-bound-and-true-p european-calendar-style)
16492 (list arg2 arg1 arg3)
16493 (list arg1 arg2 arg3)))))
16495 (defun org-eval-in-calendar (form &optional keepdate)
16496 "Eval FORM in the calendar window and return to current window.
16497 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16498 otherwise stick to the current value of `org-ans2'."
16499 (let ((sf (selected-frame))
16500 (sw (selected-window)))
16501 (select-window (get-buffer-window "*Calendar*" t))
16503 (when (and (not keepdate) (calendar-cursor-to-date))
16504 (let* ((date (calendar-cursor-to-date))
16505 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16506 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16507 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16509 (org-select-frame-set-input-focus sf)))
16511 (defun org-calendar-select ()
16512 "Return to `org-read-date' with the date currently selected.
16513 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16515 (when (calendar-cursor-to-date)
16516 (let* ((date (calendar-cursor-to-date))
16517 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16518 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16519 (if (active-minibuffer-window) (exit-minibuffer))))
16521 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16522 "Insert a date stamp for the date given by the internal TIME.
16523 WITH-HM means use the stamp format that includes the time of the day.
16524 INACTIVE means use square brackets instead of angular ones, so that the
16525 stamp will not contribute to the agenda.
16526 PRE and POST are optional strings to be inserted before and after the
16528 The command returns the inserted time stamp."
16529 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16531 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16532 (insert-before-markers (or pre ""))
16533 (when (listp extra)
16534 (setq extra (car extra))
16535 (if (and (stringp extra)
16536 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16537 (setq extra (format "-%02d:%02d"
16538 (string-to-number (match-string 1 extra))
16539 (string-to-number (match-string 2 extra))))
16542 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16543 (insert-before-markers (setq stamp (format-time-string fmt time)))
16544 (insert-before-markers (or post ""))
16545 (setq org-last-inserted-timestamp stamp)))
16547 (defun org-toggle-time-stamp-overlays ()
16548 "Toggle the use of custom time stamp formats."
16550 (setq org-display-custom-times (not org-display-custom-times))
16551 (unless org-display-custom-times
16552 (let ((p (point-min)) (bmp (buffer-modified-p)))
16553 (while (setq p (next-single-property-change p 'display))
16554 (if (and (get-text-property p 'display)
16555 (eq (get-text-property p 'face) 'org-date))
16556 (remove-text-properties
16557 p (setq p (next-single-property-change p 'display))
16559 (set-buffer-modified-p bmp)))
16560 (if (featurep 'xemacs)
16561 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16562 (org-restart-font-lock)
16563 (setq org-table-may-need-update t)
16564 (if org-display-custom-times
16565 (message "Time stamps are overlaid with custom format")
16566 (message "Time stamp overlays removed")))
16568 (defun org-display-custom-time (beg end)
16569 "Overlay modified time stamp format over timestamp between BEG and END."
16570 (let* ((ts (buffer-substring beg end))
16571 t1 w1 with-hm tf time str w2 (off 0))
16573 (setq t1 (org-parse-time-string ts t))
16574 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16575 (setq off (- (match-end 0) (match-beginning 0)))))
16576 (setq end (- end off))
16577 (setq w1 (- end beg)
16578 with-hm (and (nth 1 t1) (nth 2 t1))
16579 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16580 time (org-fix-decoded-time t1)
16582 (format-time-string
16583 (substring tf 1 -1) (apply 'encode-time time))
16584 nil 'mouse-face 'highlight)
16586 (if (not (= w2 w1))
16587 (add-text-properties (1+ beg) (+ 2 beg)
16588 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16589 (if (featurep 'xemacs)
16591 (put-text-property beg end 'invisible t)
16592 (put-text-property beg end 'end-glyph (make-glyph str)))
16593 (put-text-property beg end 'display str))))
16595 (defun org-translate-time (string)
16596 "Translate all timestamps in STRING to custom format.
16597 But do this only if the variable `org-display-custom-times' is set."
16598 (when org-display-custom-times
16601 (re org-ts-regexp-both)
16602 t1 with-hm inactive tf time str beg end)
16603 (while (setq start (string-match re string start))
16604 (setq beg (match-beginning 0)
16606 t1 (save-match-data
16607 (org-parse-time-string (substring string beg end) t))
16608 with-hm (and (nth 1 t1) (nth 2 t1))
16609 inactive (equal (substring string beg (1+ beg)) "[")
16610 tf (funcall (if with-hm 'cdr 'car)
16611 org-time-stamp-custom-formats)
16612 time (org-fix-decoded-time t1)
16613 str (format-time-string
16615 (if inactive "[" "<") (substring tf 1 -1)
16616 (if inactive "]" ">"))
16617 (apply 'encode-time time))
16618 string (replace-match str t t string)
16619 start (+ start (length str)))))))
16622 (defun org-fix-decoded-time (time)
16623 "Set 0 instead of nil for the first 6 elements of time.
16624 Don't touch the rest."
16626 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16628 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16630 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16631 "Difference between TIMESTAMP-STRING and now in days.
16632 If SECONDS is non-nil, return the difference in seconds."
16633 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16634 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16635 (funcall fdiff (current-time)))))
16637 (defun org-deadline-close (timestamp-string &optional ndays)
16638 "Is the time in TIMESTAMP-STRING close to the current date?"
16639 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16640 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16641 (not (org-entry-is-done-p))))
16643 (defun org-get-wdays (ts &optional delay zero-delay)
16644 "Get the deadline lead time appropriate for timestring TS.
16645 When DELAY is non-nil, get the delay time for scheduled items
16646 instead of the deadline lead time. When ZERO-DELAY is non-nil
16647 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16648 don't try to find the delay cookie in the scheduled timestamp."
16649 (let ((tv (if delay org-scheduled-delay-days
16650 org-deadline-warning-days)))
16652 ((or (and delay (< tv 0))
16653 (and delay zero-delay (<= tv 0))
16654 (and (not delay) (<= tv 0)))
16655 ;; Enforce this value no matter what
16657 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16658 ;; lead time is specified.
16659 (floor (* (string-to-number (match-string 1 ts))
16660 (cdr (assoc (match-string 2 ts)
16661 '(("d" . 1) ("w" . 7)
16662 ("m" . 30.4) ("y" . 365.25)
16663 ("h" . 0.041667)))))))
16664 ;; go for the default.
16667 (defun org-calendar-select-mouse (ev)
16668 "Return to `org-read-date' with the date currently selected.
16669 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16671 (mouse-set-point ev)
16672 (when (calendar-cursor-to-date)
16673 (let* ((date (calendar-cursor-to-date))
16674 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16675 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16676 (if (active-minibuffer-window) (exit-minibuffer))))
16678 (defun org-check-deadlines (ndays)
16679 "Check if there are any deadlines due or past due.
16680 A deadline is considered due if it happens within `org-deadline-warning-days'
16681 days from today's date. If the deadline appears in an entry marked DONE,
16682 it is not shown. The prefix arg NDAYS can be used to test that many
16683 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16685 (let* ((org-warn-days
16687 ((equal ndays '(4)) 100000)
16688 (ndays (prefix-numeric-value ndays))
16689 (t (abs org-deadline-warning-days))))
16690 (case-fold-search nil)
16691 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16693 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16695 (message "%d deadlines past-due or due within %d days"
16696 (org-occur regexp nil callback)
16699 (defsubst org-re-timestamp (type)
16700 "Return a regexp for timestamp TYPE.
16701 Allowed values for TYPE are:
16703 all: all timestamps
16704 active: only active timestamps (<...>)
16705 inactive: only inactive timestamps ([...])
16706 scheduled: only scheduled timestamps
16707 deadline: only deadline timestamps
16709 When TYPE is nil, fall back on returning a regexp that matches
16710 both scheduled and deadline timestamps."
16711 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>
\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16712 ((eq type 'active) org-ts-regexp)
16713 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]")
16714 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16715 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16716 ((eq type 'scheduled-or-deadline)
16717 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16719 (defun org-check-before-date (date)
16720 "Check if there are deadlines or scheduled entries before DATE."
16721 (interactive (list (org-read-date)))
16722 (let ((case-fold-search nil)
16723 (regexp (org-re-timestamp org-ts-type))
16725 (lambda () (time-less-p
16726 (org-time-string-to-time (match-string 1))
16727 (org-time-string-to-time date)))))
16728 (message "%d entries before %s"
16729 (org-occur regexp nil callback) date)))
16731 (defun org-check-after-date (date)
16732 "Check if there are deadlines or scheduled entries after DATE."
16733 (interactive (list (org-read-date)))
16734 (let ((case-fold-search nil)
16735 (regexp (org-re-timestamp org-ts-type))
16739 (org-time-string-to-time (match-string 1))
16740 (org-time-string-to-time date))))))
16741 (message "%d entries after %s"
16742 (org-occur regexp nil callback) date)))
16744 (defun org-check-dates-range (start-date end-date)
16745 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16746 (interactive (list (org-read-date nil nil nil "Range starts")
16747 (org-read-date nil nil nil "Range end")))
16748 (let ((case-fold-search nil)
16749 (regexp (org-re-timestamp org-ts-type))
16752 (let ((match (match-string 1)))
16755 (org-time-string-to-time match)
16756 (org-time-string-to-time start-date)))
16758 (org-time-string-to-time match)
16759 (org-time-string-to-time end-date)))))))
16760 (message "%d entries between %s and %s"
16761 (org-occur regexp nil callback) start-date end-date)))
16763 (defun org-evaluate-time-range (&optional to-buffer)
16764 "Evaluate a time range by computing the difference between start and end.
16765 Normally the result is just printed in the echo area, but with prefix arg
16766 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16767 If the time range is actually in a table, the result is inserted into the
16769 For time difference computation, a year is assumed to be exactly 365
16770 days in order to avoid rounding problems."
16773 (org-clock-update-time-maybe)
16775 (unless (org-at-date-range-p t)
16776 (goto-char (point-at-bol))
16777 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16778 (if (not (org-at-date-range-p t))
16779 (error "Not at a time-stamp range, and none found in current line")))
16780 (let* ((ts1 (match-string 1))
16781 (ts2 (match-string 2))
16782 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16783 (match-end (match-end 0))
16784 (time1 (org-time-string-to-time ts1))
16785 (time2 (org-time-string-to-time ts2))
16786 (t1 (org-float-time time1))
16787 (t2 (org-float-time time2))
16788 (diff (abs (- t2 t1)))
16789 (negative (< (- t2 t1) 0))
16790 ;; (ys (floor (* 365 24 60 60)))
16793 (fy "%dy %dd %02d:%02d")
16795 (fd "%dd %02d:%02d")
16800 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16802 d (floor (/ diff ds)) diff (mod diff ds)
16803 h (floor (/ diff hs)) diff (mod diff hs)
16804 m (floor (/ diff 60)))
16805 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16807 d (floor (+ (/ diff ds) 0.5))
16809 (if (not to-buffer)
16810 (message "%s" (org-make-tdiff-string y d h m))
16811 (if (org-at-table-p)
16813 (goto-char match-end)
16815 (and (looking-at " *|") (goto-char (match-end 0))))
16816 (goto-char match-end))
16818 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16819 (replace-match ""))
16820 (if negative (insert " -"))
16821 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16822 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16823 (insert " " (format fh h m))))
16824 (if align (org-table-align))
16825 (message "Time difference inserted")))))
16827 (defun org-make-tdiff-string (y d h m)
16830 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16832 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16834 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16836 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16838 (apply 'format fmt (nreverse l))))
16840 (defun org-time-string-to-time (s &optional buffer pos)
16841 "Convert a timestamp string into internal time."
16842 (condition-case errdata
16843 (apply 'encode-time (org-parse-time-string s))
16844 (error (error "Bad timestamp `%s'%s\nError was: %s"
16845 s (if (not (and buffer pos))
16847 (format " at %d in buffer `%s'" pos buffer))
16850 (defun org-time-string-to-seconds (s)
16851 "Convert a timestamp string to a number of seconds."
16852 (org-float-time (org-time-string-to-time s)))
16854 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16855 "Convert a time stamp to an absolute day number.
16856 If there is a specifier for a cyclic time stamp, get the closest
16858 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16859 The variable `date' is bound by the calendar when this is called."
16861 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16862 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16865 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16866 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16867 (time-to-days (current-time))) (match-string 0 s)
16870 (condition-case errdata
16871 (apply 'encode-time (org-parse-time-string s))
16872 (error (error "Bad timestamp `%s'%s\nError was: %s"
16873 s (if (not (and buffer pos))
16875 (format " at %d in buffer `%s'" pos buffer))
16876 (cdr errdata))))))))
16878 (defun org-days-to-iso-week (days)
16879 "Return the iso week number."
16881 (car (calendar-iso-from-absolute days)))
16883 (defun org-small-year-to-year (year)
16884 "Convert 2-digit years into 4-digit years.
16885 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16886 The year 2000 cannot be abbreviated. Any year larger than 99
16887 is returned unchanged."
16889 (setq year (+ 2000 year))
16891 (setq year (+ 1900 year))))
16894 (defun org-time-from-absolute (d)
16895 "Return the time corresponding to date D.
16896 D may be an absolute day number, or a calendar-type list (month day year)."
16897 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16898 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16900 (defun org-calendar-holiday ()
16901 "List of holidays, for Diary display in Org-mode."
16902 (require 'holidays)
16904 (if (fboundp 'calendar-check-holidays)
16905 'calendar-check-holidays 'check-calendar-holidays) date)))
16906 (if hl (mapconcat 'identity hl "; "))))
16908 (defun org-diary-sexp-entry (sexp entry date)
16909 "Process a SEXP diary ENTRY for DATE."
16910 (require 'diary-lib)
16911 (let ((result (if calendar-debug-sexp
16912 (let ((stack-trace-on-error t))
16913 (eval (car (read-from-string sexp))))
16914 (condition-case nil
16915 (eval (car (read-from-string sexp)))
16918 (message "Bad sexp at line %d in %s: %s"
16920 (buffer-file-name) sexp)
16922 (cond ((stringp result) (split-string result "; "))
16923 ((and (consp result)
16924 (not (consp (cdr result)))
16925 (stringp (cdr result))) (cdr result))
16926 ((and (consp result)
16927 (stringp (car result))) result)
16930 (defun org-diary-to-ical-string (frombuf)
16931 "Get iCalendar entries from diary entries in buffer FROMBUF.
16932 This uses the icalendar.el library."
16933 (let* ((tmpdir (if (featurep 'xemacs)
16935 temporary-file-directory))
16936 (tmpfile (make-temp-name
16937 (expand-file-name "orgics" tmpdir)))
16939 (with-current-buffer frombuf
16940 (icalendar-export-region (point-min) (point-max) tmpfile)
16941 (setq buf (find-buffer-visiting tmpfile))
16943 (goto-char (point-min))
16944 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16945 (setq b (match-beginning 0)))
16946 (goto-char (point-max))
16947 (if (re-search-backward "^END:VEVENT" nil t)
16948 (setq e (match-end 0)))
16949 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16951 (delete-file tmpfile)
16954 (defun org-closest-date (start current change prefer show-all)
16955 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16956 When PREFER is `past', return a date that is either CURRENT or past.
16957 When PREFER is `future', return a date that is either CURRENT or future.
16958 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16959 ;; Make the proper lists from the dates
16961 (let ((a1 '(("h" . hour)
16966 (shour (nth 2 (org-parse-time-string start)))
16967 dn dw sday cday n1 n2 n0
16968 d m y y1 y2 date1 date2 nmonths nm ny m2)
16970 (setq start (org-date-to-gregorian start)
16971 current (org-date-to-gregorian
16974 (time-to-days (current-time))))
16975 sday (calendar-absolute-from-gregorian start)
16976 cday (calendar-absolute-from-gregorian current))
16978 (if (<= cday sday) (throw 'exit sday))
16980 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16981 (setq dn (string-to-number (match-string 1 change))
16982 dw (cdr (assoc (match-string 2 change) a1)))
16983 (error "Invalid change specifier: %s" change))
16984 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16987 (let ((missing-hours
16988 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16990 (setq n1 (if (zerop missing-hours) cday
16991 (- cday (1+ (floor (/ missing-hours 24)))))
16992 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16994 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16997 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16998 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16999 (setq date1 (list m d y1)
17000 n1 (calendar-absolute-from-gregorian date1)
17001 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17002 n2 (calendar-absolute-from-gregorian date2)))
17004 ;; approx number of month between the two dates
17005 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17006 ;; How often does dn fit in there?
17007 (setq d (nth 1 start) m (car start) y (nth 2 start)
17008 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17010 ny (floor (/ m 12))
17013 (while (> m 12) (setq m (- m 12) y (1+ y)))
17014 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17015 (setq m2 (+ m dn) y2 y)
17016 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17017 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17018 (while (<= n2 cday)
17019 (setq n1 n2 m m2 y y2)
17020 (setq m2 (+ m dn) y2 y)
17021 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17022 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17023 ;; Make sure n1 is the earlier date
17024 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17027 ((eq prefer 'past) (if (= cday n2) n2 n1))
17028 ((eq prefer 'future) (if (= cday n1) n1 n2))
17029 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17031 ((eq prefer 'past) (if (= cday n2) n2 n1))
17032 ((eq prefer 'future) (if (= cday n1) n1 n2))
17033 (t (if (= cday n1) n1 n2)))))))
17035 (defun org-date-to-gregorian (date)
17036 "Turn any specification of DATE into a Gregorian date for the calendar."
17037 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17038 ((and (listp date) (= (length date) 3)) date)
17040 (setq date (org-parse-time-string date))
17041 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17043 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17045 (defun org-parse-time-string (s &optional nodefault)
17046 "Parse the standard Org-mode time string.
17047 This should be a lot faster than the normal `parse-time-string'.
17048 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17049 hour and minute fields will be nil if not given."
17050 (cond ((string-match org-ts-regexp0 s)
17052 (if (or (match-beginning 8) (not nodefault))
17053 (string-to-number (or (match-string 8 s) "0")))
17054 (if (or (match-beginning 7) (not nodefault))
17055 (string-to-number (or (match-string 7 s) "0")))
17056 (string-to-number (match-string 4 s))
17057 (string-to-number (match-string 3 s))
17058 (string-to-number (match-string 2 s))
17060 ((string-match "^<[^>]+>$" s)
17061 (decode-time (seconds-to-time (org-matcher-time s))))
17062 (t (error "Not a standard Org-mode time string: %s" s))))
17064 (defun org-timestamp-up (&optional arg)
17065 "Increase the date item at the cursor by one.
17066 If the cursor is on the year, change the year. If it is on the month,
17067 the day or the time, change that.
17068 With prefix ARG, change by that many units."
17070 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17072 (defun org-timestamp-down (&optional arg)
17073 "Decrease the date item at the cursor by one.
17074 If the cursor is on the year, change the year. If it is on the month,
17075 the day or the time, change that.
17076 With prefix ARG, change by that many units."
17078 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17080 (defun org-timestamp-up-day (&optional arg)
17081 "Increase the date in the time stamp by one day.
17082 With prefix ARG, change that many days."
17084 (if (and (not (org-at-timestamp-p t))
17085 (org-at-heading-p))
17087 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17089 (defun org-timestamp-down-day (&optional arg)
17090 "Decrease the date in the time stamp by one day.
17091 With prefix ARG, change that many days."
17093 (if (and (not (org-at-timestamp-p t))
17094 (org-at-heading-p))
17096 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17098 (defun org-at-timestamp-p (&optional inactive-ok)
17099 "Determine if the cursor is in or at a timestamp."
17101 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17103 (ans (or (looking-at tsr)
17105 (skip-chars-backward "^[<\n\r\t")
17106 (if (> (point) (point-min)) (backward-char 1))
17107 (and (looking-at tsr)
17108 (> (- (match-end 0) pos) -1))))))
17110 (boundp 'org-ts-what)
17113 ((= pos (match-beginning 0)) 'bracket)
17114 ;; Point is considered to be "on the bracket" whether
17115 ;; it's really on it or right after it.
17116 ((= pos (1- (match-end 0))) 'bracket)
17117 ((= pos (match-end 0)) 'after)
17118 ((org-pos-in-match-range pos 2) 'year)
17119 ((org-pos-in-match-range pos 3) 'month)
17120 ((org-pos-in-match-range pos 7) 'hour)
17121 ((org-pos-in-match-range pos 8) 'minute)
17122 ((or (org-pos-in-match-range pos 4)
17123 (org-pos-in-match-range pos 5)) 'day)
17124 ((and (> pos (or (match-end 8) (match-end 5)))
17125 (< pos (match-end 0)))
17126 (- pos (or (match-end 8) (match-end 5))))
17130 (defun org-toggle-timestamp-type ()
17131 "Toggle the type (<active> or [inactive]) of a time stamp."
17133 (when (org-at-timestamp-p t)
17134 (let ((beg (match-beginning 0)) (end (match-end 0))
17135 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17138 (while (re-search-forward "[][<>]" end t)
17139 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17141 (message "Timestamp is now %sactive"
17142 (if (equal (char-after beg) ?<) "" "in")))))
17144 (defun org-at-clock-log-p nil
17145 "Is the cursor on the clock log line?"
17147 (move-beginning-of-line 1)
17148 (looking-at "^[ \t]*CLOCK:")))
17150 (defvar org-clock-history) ; defined in org-clock.el
17151 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17152 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17153 "Change the date in the time stamp at point.
17154 The date will be changed by N times WHAT. WHAT can be `day', `month',
17155 `year', `minute', `second'. If WHAT is not given, the cursor position
17156 in the timestamp determines what will be changed.
17157 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17158 (let ((origin (point)) origin-cat
17160 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17163 ts time time0 fixnext clrgx)
17164 (if (not (org-at-timestamp-p t))
17165 (error "Not at a timestamp"))
17166 (if (and (not what) (eq org-ts-what 'bracket))
17167 (org-toggle-timestamp-type)
17168 ;; Point isn't on brackets. Remember the part of the time-stamp
17169 ;; the point was in. Indeed, size of time-stamps may change,
17170 ;; but point must be kept in the same category nonetheless.
17171 (setq origin-cat org-ts-what)
17172 (if (and (not what) (not (eq org-ts-what 'day))
17173 org-display-custom-times
17174 (get-text-property (point) 'display)
17175 (not (get-text-property (1- (point)) 'display)))
17176 (setq org-ts-what 'day))
17177 (setq org-ts-what (or what org-ts-what)
17178 inactive (= (char-after (match-beginning 0)) ?\[)
17179 ts (match-string 0))
17181 (when (string-match
17182 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17184 (setq extra (match-string 1 ts))
17185 (if suppress-tmp-delay
17186 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17187 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17189 (setq time0 (org-parse-time-string ts))
17191 (eq org-ts-what 'minute)
17192 (not current-prefix-arg))
17193 ;; This looks like s-up and s-down. Change by one rounding step.
17194 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17195 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17196 (setcar (cdr time0) (+ (nth 1 time0)
17197 (if (> n 0) (- rem) (- dm rem))))))
17199 (encode-time (or (car time0) 0)
17200 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17201 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17202 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17203 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17204 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17206 (when (and (member org-ts-what '(hour minute))
17208 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17209 (setq extra (org-modify-ts-extra
17211 (if (eq org-ts-what 'hour) 2 5)
17213 (when (integerp org-ts-what)
17214 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17215 (if (eq what 'calendar)
17216 (let ((cal-date (org-get-date-from-calendar)))
17217 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17218 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17219 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17220 (setcar time0 (or (car time0) 0))
17221 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17222 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17223 (setq time (apply 'encode-time time0))))
17224 ;; Insert the new time-stamp, and ensure point stays in the same
17225 ;; category as before (i.e. not after the last position in that
17227 (let ((pos (point)))
17228 ;; Stay before inserted string. `save-excursion' is of no use.
17229 (setq org-last-changed-timestamp
17230 (org-insert-time-stamp time with-hm inactive nil nil extra))
17233 (looking-at org-ts-regexp3)
17235 ;; `day' category ends before `hour' if any, or at
17236 ;; the end of the day name.
17237 ((eq origin-cat 'day)
17238 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17239 ((eq origin-cat 'hour) (min (match-end 7) origin))
17240 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17241 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17242 ;; `year' and `month' have both fixed size: point
17243 ;; couldn't have moved into another part.
17245 ;; Update clock if on a CLOCK line.
17246 (org-clock-update-time-maybe)
17247 ;; Maybe adjust the closest clock in `org-clock-history'
17248 (when org-clock-adjust-closest
17249 (if (not (and (org-at-clock-log-p)
17250 (< 1 (length (delq nil (mapcar 'marker-position
17251 org-clock-history))))))
17252 (message "No clock to adjust")
17253 (cond ((save-excursion ; fix previous clock?
17254 (re-search-backward org-ts-regexp0 nil t)
17255 (org-looking-back (concat org-clock-string " \\[")))
17256 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17257 ((save-excursion ; fix next clock?
17258 (re-search-backward org-ts-regexp0 nil t)
17259 (looking-at (concat org-ts-regexp0 "\\] =>")))
17260 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17261 (save-window-excursion
17262 ;; Find closest clock to point, adjust the previous/next one in history
17263 (let* ((p (save-excursion (org-back-to-heading t)))
17264 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17266 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17267 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17269 (message "No clock to adjust")
17271 (org-goto-marker-or-bmk clfixpos)
17273 (when (re-search-forward clrgx nil t)
17274 (goto-char (match-beginning 1))
17275 (let (org-clock-adjust-closest)
17276 (org-timestamp-change n org-ts-what updown))
17277 (message "Clock adjusted in %s for heading: %s"
17278 (file-name-nondirectory (buffer-file-name))
17279 (org-get-heading t t)))))))))
17280 ;; Try to recenter the calendar window, if any.
17281 (if (and org-calendar-follow-timestamp-change
17282 (get-buffer-window "*Calendar*" t)
17283 (memq org-ts-what '(day month year)))
17284 (org-recenter-calendar (time-to-days time))))))
17286 (defun org-modify-ts-extra (s pos n dm)
17287 "Change the different parts of the lead-time and repeat fields in timestamp."
17288 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17290 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17292 ((or (org-pos-in-match-range pos 2)
17293 (org-pos-in-match-range pos 3))
17294 (setq m (string-to-number (match-string 3 s))
17295 h (string-to-number (match-string 2 s)))
17296 (if (org-pos-in-match-range pos 2)
17298 (setq n (* dm (org-no-warnings (signum n))))
17299 (when (not (= 0 (setq rem (% m dm))))
17300 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17302 (if (< m 0) (setq m (+ m 60) h (1- h)))
17303 (if (> m 59) (setq m (- m 60) h (1+ h)))
17304 (setq h (min 24 (max 0 h)))
17305 (setq ng 1 new (format "-%02d:%02d" h m)))
17306 ((org-pos-in-match-range pos 6)
17307 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17308 ((org-pos-in-match-range pos 5)
17309 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17311 ((org-pos-in-match-range pos 9)
17312 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17313 ((org-pos-in-match-range pos 8)
17314 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17318 (substring s 0 (match-beginning ng))
17320 (substring s (match-end ng))))))
17323 (defun org-recenter-calendar (date)
17324 "If the calendar is visible, recenter it to DATE."
17325 (let ((cwin (get-buffer-window "*Calendar*" t)))
17327 (let ((calendar-move-hook nil))
17328 (with-selected-window cwin
17329 (calendar-goto-date (if (listp date) date
17330 (calendar-gregorian-from-absolute date))))))))
17332 (defun org-goto-calendar (&optional arg)
17333 "Go to the Emacs calendar at the current date.
17334 If there is a time stamp in the current line, go to that date.
17335 A prefix ARG can be used to force the current date."
17337 (let ((tsr org-ts-regexp) diff
17338 (calendar-move-hook nil)
17339 (calendar-view-holidays-initially-flag nil)
17340 (calendar-view-diary-initially-flag nil))
17341 (if (or (org-at-timestamp-p)
17343 (beginning-of-line 1)
17344 (looking-at (concat ".*" tsr))))
17345 (let ((d1 (time-to-days (current-time)))
17347 (org-time-string-to-time (match-string 1)))))
17348 (setq diff (- d2 d1))))
17350 (calendar-goto-today)
17351 (if (and diff (not arg)) (calendar-forward-day diff))))
17353 (defun org-get-date-from-calendar ()
17354 "Return a list (month day year) of date at point in calendar."
17355 (with-current-buffer "*Calendar*"
17357 (calendar-cursor-to-date))))
17359 (defun org-date-from-calendar ()
17360 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17361 If there is already a time stamp at the cursor position, update it."
17363 (if (org-at-timestamp-p t)
17364 (org-timestamp-change 0 'calendar)
17365 (let ((cal-date (org-get-date-from-calendar)))
17366 (org-insert-time-stamp
17367 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17369 (defcustom org-effort-durations
17372 ("w" . ,(* 60 8 5))
17373 ("m" . ,(* 60 8 5 4))
17374 ("y" . ,(* 60 8 5 40)))
17375 "Conversion factor to minutes for an effort modifier.
17377 Each entry has the form (MODIFIER . MINUTES).
17379 In an effort string, a number followed by MODIFIER is multiplied
17380 by the specified number of MINUTES to obtain an effort in
17383 For example, if the value of this variable is ((\"hours\" . 60)), then an
17384 effort string \"2hours\" is equivalent to 120 minutes."
17387 :type '(alist :key-type (string :tag "Modifier")
17388 :value-type (number :tag "Minutes")))
17390 (defun org-minutes-to-clocksum-string (m)
17391 "Format number of minutes as a clocksum string.
17392 The format is determined by `org-time-clocksum-format',
17393 `org-time-clocksum-use-fractional' and
17394 `org-time-clocksum-fractional-format' and
17395 `org-time-clocksum-use-effort-durations'."
17396 (let ((clocksum "") h d w mo y fmt n)
17397 (setq h (if org-time-clocksum-use-effort-durations
17398 (cdr (assoc "h" org-effort-durations)) 60)
17399 d (if org-time-clocksum-use-effort-durations
17400 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17401 w (if org-time-clocksum-use-effort-durations
17402 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17403 mo (if org-time-clocksum-use-effort-durations
17404 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17405 y (if org-time-clocksum-use-effort-durations
17406 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17407 ;; fractional format
17408 (if org-time-clocksum-use-fractional
17410 ;; single format string
17411 ((stringp org-time-clocksum-fractional-format)
17412 (format org-time-clocksum-fractional-format (/ m (float h))))
17413 ;; choice of fractional formats for different time units
17414 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17415 (> (/ (truncate m) (* y d h)) 0))
17416 (format fmt (/ m (* y d (float h)))))
17417 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17418 (> (/ (truncate m) (* mo d h)) 0))
17419 (format fmt (/ m (* mo d (float h)))))
17420 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17421 (> (/ (truncate m) (* w d h)) 0))
17422 (format fmt (/ m (* w d (float h)))))
17423 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17424 (> (/ (truncate m) (* d h)) 0))
17425 (format fmt (/ m (* d (float h)))))
17426 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17427 (> (/ (truncate m) h) 0))
17428 (format fmt (/ m (float h))))
17429 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17431 ;; fall back to smallest time unit with a format
17432 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17433 (format fmt (/ m (float h))))
17434 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17435 (format fmt (/ m (* d (float h)))))
17436 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17437 (format fmt (/ m (* w d (float h)))))
17438 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17439 (format fmt (/ m (* mo d (float h)))))
17440 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17441 (format fmt (/ m (* y d (float h))))))
17442 ;; standard (non-fractional) format, with single format string
17443 (if (stringp org-time-clocksum-format)
17444 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17445 ;; separate formats components
17446 (and (setq fmt (plist-get org-time-clocksum-format :years))
17447 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17448 (plist-get org-time-clocksum-format :require-years))
17449 (setq clocksum (concat clocksum (format fmt n))
17450 m (- m (* n y d h))))
17451 (and (setq fmt (plist-get org-time-clocksum-format :months))
17452 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17453 (plist-get org-time-clocksum-format :require-months))
17454 (setq clocksum (concat clocksum (format fmt n))
17455 m (- m (* n mo d h))))
17456 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17457 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17458 (plist-get org-time-clocksum-format :require-weeks))
17459 (setq clocksum (concat clocksum (format fmt n))
17460 m (- m (* n w d h))))
17461 (and (setq fmt (plist-get org-time-clocksum-format :days))
17462 (or (> (setq n (/ (truncate m) (* d h))) 0)
17463 (plist-get org-time-clocksum-format :require-days))
17464 (setq clocksum (concat clocksum (format fmt n))
17465 m (- m (* n d h))))
17466 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17467 (or (> (setq n (/ (truncate m) h)) 0)
17468 (plist-get org-time-clocksum-format :require-hours))
17469 (setq clocksum (concat clocksum (format fmt n))
17471 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17472 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17473 (setq clocksum (concat clocksum (format fmt m))))
17474 ;; return formatted time duration
17477 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17478 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17479 "Org mode version 8.0")
17481 (defun org-hours-to-clocksum-string (n)
17482 (org-minutes-to-clocksum-string (* n 60)))
17484 (defun org-hh:mm-string-to-minutes (s)
17485 "Convert a string H:MM to a number of minutes.
17486 If the string is just a number, interpret it as minutes.
17487 In fact, the first hh:mm or number in the string will be taken,
17488 there can be extra stuff in the string.
17489 If no number is found, the return value is 0."
17492 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17493 (+ (* (string-to-number (match-string 1 s)) 60)
17494 (string-to-number (match-string 2 s))))
17495 ((string-match "\\([0-9]+\\)" s)
17496 (string-to-number (match-string 1 s)))
17499 (defcustom org-image-actual-width t
17500 "Should we use the actual width of images when inlining them?
17502 When set to `t', always use the image width.
17504 When set to a number, use imagemagick (when available) to set
17505 the image's width to this value.
17507 When set to a number in a list, try to get the width from any
17508 #+ATTR.* keyword if it matches a width specification like
17510 #+ATTR_HTML: :width 300px
17512 and fall back on that number if none is found.
17514 When set to nil, try to get the width from an #+ATTR.* keyword
17515 and fall back on the original width if none is found.
17517 This requires Emacs >= 24.1, build with imagemagick support."
17518 :group 'org-appearance
17520 :package-version '(Org . "8.0")
17522 (const :tag "Use the image width" t)
17523 (integer :tag "Use a number of pixels")
17524 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17525 (const :tag "Use #+ATTR* or don't resize" nil)))
17527 (defcustom org-agenda-inhibit-startup nil
17528 "Inhibit startup when preparing agenda buffers.
17529 When this variable is `t' (the default), the initialization of
17530 the Org agenda buffers is inhibited: e.g. the visibility state
17531 is not set, the tables are not re-aligned, etc."
17534 :group 'org-agenda)
17536 (defun org-duration-string-to-minutes (s &optional output-to-string)
17537 "Convert a duration string S to minutes.
17539 A bare number is interpreted as minutes, modifiers can be set by
17540 customizing `org-effort-durations' (which see).
17542 Entries containing a colon are interpreted as H:MM by
17543 `org-hh:mm-string-to-minutes'."
17545 (re (concat "\\([0-9.]+\\) *\\("
17546 (regexp-opt (mapcar 'car org-effort-durations))
17548 (while (string-match re s)
17549 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17550 (string-to-number (match-string 1 s))))
17551 (setq s (replace-match "" nil t s)))
17552 (setq result (floor result))
17553 (incf result (org-hh:mm-string-to-minutes s))
17554 (if output-to-string (number-to-string result) result)))
17558 (defun org-save-all-org-buffers ()
17559 "Save all Org-mode buffers without user confirmation."
17561 (message "Saving all Org-mode buffers...")
17562 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17563 (when (featurep 'org-id) (org-id-locations-save))
17564 (message "Saving all Org-mode buffers... done"))
17566 (defun org-revert-all-org-buffers ()
17567 "Revert all Org-mode buffers.
17568 Prompt for confirmation when there are unsaved changes.
17569 Be sure you know what you are doing before letting this function
17570 overwrite your changes.
17572 This function is useful in a setup where one tracks org files
17573 with a version control system, to revert on one machine after pulling
17574 changes from another. I believe the procedure must be like this:
17576 1. M-x org-save-all-org-buffers
17577 2. Pull changes from the other machine, resolve conflicts
17578 3. M-x org-revert-all-org-buffers"
17580 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17583 (save-window-excursion
17586 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17587 (with-current-buffer b buffer-file-name))
17588 (org-pop-to-buffer-same-window b)
17589 (revert-buffer t 'no-confirm)))
17591 (when (and (featurep 'org-id) org-id-track-globally)
17592 (org-id-locations-load)))))
17597 (defun org-switchb (&optional arg)
17598 "Switch between Org buffers.
17599 With one prefix argument, restrict available buffers to files.
17600 With two prefix arguments, restrict available buffers to agenda files.
17602 Defaults to `iswitchb' for buffer name completion.
17603 Set `org-completion-use-ido' to make it use ido instead."
17605 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17606 ((equal arg '(16)) (org-buffer-list 'agenda))
17607 (t (org-buffer-list))))
17608 (org-completion-use-iswitchb org-completion-use-iswitchb)
17609 (org-completion-use-ido org-completion-use-ido))
17610 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17611 (setq org-completion-use-iswitchb t))
17612 (org-pop-to-buffer-same-window
17613 (org-icompleting-read "Org buffer: "
17614 (mapcar 'list (mapcar 'buffer-name blist))
17617 ;;; Define some older names previously used for this functionality
17619 (defalias 'org-ido-switchb 'org-switchb)
17621 (defalias 'org-iswitchb 'org-switchb)
17623 (defun org-buffer-list (&optional predicate exclude-tmp)
17624 "Return a list of Org buffers.
17625 PREDICATE can be `export', `files' or `agenda'.
17627 export restrict the list to Export buffers.
17628 files restrict the list to buffers visiting Org files.
17629 agenda restrict the list to buffers visiting agenda files.
17631 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17633 (agenda-files (and (eq predicate 'agenda)
17634 (mapcar 'file-truename (org-agenda-files t))))
17637 ((eq predicate 'files)
17638 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17639 ((eq predicate 'export)
17640 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17641 ((eq predicate 'agenda)
17643 (with-current-buffer b
17644 (and (derived-mode-p 'org-mode)
17645 (setq bfn (buffer-file-name b))
17646 (member (file-truename bfn) agenda-files)))))
17647 (t (lambda (b) (with-current-buffer b
17648 (or (derived-mode-p 'org-mode)
17649 (string-match "\*Org .*Export"
17650 (buffer-name b)))))))))
17654 (if (and (funcall filter b)
17655 (or (not exclude-tmp)
17656 (not (string-match "tmp" (buffer-name b)))))
17661 (defun org-agenda-files (&optional unrestricted archives)
17662 "Get the list of agenda files.
17663 Optional UNRESTRICTED means return the full list even if a restriction
17664 is currently in place.
17665 When ARCHIVES is t, include all archive files that are really being
17666 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17667 `org-agenda-archives-mode' is t."
17670 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17671 ((stringp org-agenda-files) (org-read-agenda-file-list))
17672 ((listp org-agenda-files) org-agenda-files)
17673 (t (error "Invalid value of `org-agenda-files'")))))
17674 (setq files (apply 'append
17675 (mapcar (lambda (f)
17676 (if (file-directory-p f)
17678 f t org-agenda-file-regexp)
17681 (when org-agenda-skip-unavailable-files
17682 (setq files (delq nil
17685 (and (file-readable-p file) file)))
17687 (when (or (eq archives t)
17688 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17689 (setq files (org-add-archive-files files)))
17692 (defun org-agenda-file-p (&optional file)
17693 "Return non-nil, if FILE is an agenda file.
17694 If FILE is omitted, use the file associated with the current
17696 (member (or file (buffer-file-name))
17697 (org-agenda-files t)))
17699 (defun org-edit-agenda-file-list ()
17700 "Edit the list of agenda files.
17701 Depending on setup, this either uses customize to edit the variable
17702 `org-agenda-files', or it visits the file that is holding the list. In the
17703 latter case, the buffer is set up in a way that saving it automatically kills
17704 the buffer and restores the previous window configuration."
17706 (if (stringp org-agenda-files)
17707 (let ((cw (current-window-configuration)))
17708 (find-file org-agenda-files)
17709 (org-set-local 'org-window-configuration cw)
17710 (org-add-hook 'after-save-hook
17712 (set-window-configuration
17713 (prog1 org-window-configuration
17714 (kill-buffer (current-buffer))))
17715 (org-install-agenda-files-menu)
17716 (message "New agenda file list installed"))
17718 (message "%s" (substitute-command-keys
17719 "Edit list and finish with \\[save-buffer]")))
17720 (customize-variable 'org-agenda-files)))
17722 (defun org-store-new-agenda-file-list (list)
17723 "Set new value for the agenda file list and save it correctly."
17724 (if (stringp org-agenda-files)
17725 (let ((fe (org-read-agenda-file-list t)) b u)
17726 (while (setq b (find-buffer-visiting org-agenda-files))
17728 (with-temp-file org-agenda-files
17731 (lambda (f) ;; Keep un-expanded entries.
17732 (if (setq u (assoc f fe))
17737 (let ((org-mode-hook nil) (org-inhibit-startup t)
17738 (org-insert-mode-line-in-empty-file nil))
17739 (setq org-agenda-files list)
17740 (customize-save-variable 'org-agenda-files org-agenda-files))))
17742 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17743 "Read the list of agenda files from a file.
17744 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17745 filenames, used by `org-store-new-agenda-file-list' to write back
17746 un-expanded file names."
17747 (when (file-directory-p org-agenda-files)
17748 (error "`org-agenda-files' cannot be a single directory"))
17749 (when (stringp org-agenda-files)
17751 (insert-file-contents org-agenda-files)
17754 (let ((e (expand-file-name (substitute-in-file-name f)
17756 (if pair-with-expansion
17759 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17762 (defun org-cycle-agenda-files ()
17763 "Cycle through the files in `org-agenda-files'.
17764 If the current buffer visits an agenda file, find the next one in the list.
17765 If the current buffer does not, find the first agenda file."
17767 (let* ((fs (org-agenda-files t))
17768 (files (append fs (list (car fs))))
17769 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17771 (unless files (error "No agenda files"))
17773 (while (setq file (pop files))
17774 (if (equal (file-truename file) tcf)
17776 (find-file (car files))
17778 (find-file (car fs)))
17779 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17781 (defun org-agenda-file-to-front (&optional to-end)
17782 "Move/add the current file to the top of the agenda file list.
17783 If the file is not present in the list, it is added to the front. If it is
17784 present, it is moved there. With optional argument TO-END, add/move to the
17787 (let ((org-agenda-skip-unavailable-files nil)
17788 (file-alist (mapcar (lambda (x)
17789 (cons (file-truename x) x))
17790 (org-agenda-files t)))
17791 (ctf (file-truename
17792 (or buffer-file-name
17793 (error "Please save the current buffer to a file"))))
17795 (setq x (assoc ctf file-alist) had x)
17797 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17799 (setq file-alist (append (delq x file-alist) (list x)))
17800 (setq file-alist (cons x (delq x file-alist))))
17801 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17802 (org-install-agenda-files-menu)
17803 (message "File %s to %s of agenda file list"
17804 (if had "moved" "added") (if to-end "end" "front"))))
17806 (defun org-remove-file (&optional file)
17807 "Remove current file from the list of files in variable `org-agenda-files'.
17808 These are the files which are being checked for agenda entries.
17809 Optional argument FILE means use this file instead of the current."
17811 (let* ((org-agenda-skip-unavailable-files nil)
17812 (file (or file buffer-file-name
17813 (error "Current buffer does not visit a file")))
17814 (true-file (file-truename file))
17815 (afile (abbreviate-file-name file))
17816 (files (delq nil (mapcar
17818 (if (equal true-file
17821 (org-agenda-files t)))))
17822 (if (not (= (length files) (length (org-agenda-files t))))
17824 (org-store-new-agenda-file-list files)
17825 (org-install-agenda-files-menu)
17826 (message "Removed file: %s" afile))
17827 (message "File was not in list: %s (not removed)" afile))))
17829 (defun org-file-menu-entry (file)
17830 (vector file (list 'find-file file) t))
17832 (defun org-check-agenda-file (file)
17833 "Make sure FILE exists. If not, ask user what to do."
17834 (when (not (file-exists-p file))
17835 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17836 (abbreviate-file-name file))
17837 (let ((r (downcase (read-char-exclusive))))
17840 (org-remove-file file)
17841 (throw 'nextfile t))
17842 (t (error "Abort"))))))
17844 (defun org-get-agenda-file-buffer (file)
17845 "Get a buffer visiting FILE. If the buffer needs to be created, add
17846 it to the list of buffers which might be released later."
17847 (let ((buf (org-find-base-buffer-visiting file)))
17849 buf ; just return it
17850 ;; Make a new buffer and remember it
17851 (setq buf (find-file-noselect file))
17852 (if buf (push buf org-agenda-new-buffers))
17855 (defun org-release-buffers (blist)
17856 "Release all buffers in list, asking the user for confirmation when needed.
17857 When a buffer is unmodified, it is just killed. When modified, it is saved
17858 \(if the user agrees) and then killed."
17860 (while (setq buf (pop blist))
17861 (setq file (buffer-file-name buf))
17862 (when (and (buffer-modified-p buf)
17864 (y-or-n-p (format "Save file %s? " file)))
17865 (with-current-buffer buf (save-buffer)))
17866 (kill-buffer buf))))
17868 (defun org-agenda-prepare-buffers (files)
17869 "Create buffers for all agenda files, protect archived trees and comments."
17871 (let ((pa '(:org-archived t))
17872 (pc '(:org-comment t))
17873 (pall '(:org-archived t :org-comment t))
17874 (inhibit-read-only t)
17875 (org-inhibit-startup org-agenda-inhibit-startup)
17876 (rea (concat ":" org-archive-tag ":"))
17877 file re org-tag-alist)
17878 (setq org-tag-alist-for-agenda nil
17879 org-tag-groups-alist-for-agenda nil)
17882 (while (setq file (pop files))
17886 (org-check-agenda-file file)
17887 (set-buffer (org-get-agenda-file-buffer file)))
17889 (org-set-regexps-and-options-for-tags)
17890 (org-refresh-category-properties)
17891 (org-refresh-properties org-effort-property 'org-effort)
17892 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17893 (setq org-todo-keywords-for-agenda
17894 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17895 (setq org-done-keywords-for-agenda
17896 (append org-done-keywords-for-agenda org-done-keywords))
17897 (setq org-todo-keyword-alist-for-agenda
17898 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17899 (setq org-drawers-for-agenda
17900 (append org-drawers-for-agenda org-drawers))
17901 (setq org-tag-alist-for-agenda
17902 (append org-tag-alist-for-agenda org-tag-alist))
17904 (setq org-tag-groups-alist-for-agenda
17905 (org-uniquify-alist
17906 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17907 (org-with-silent-modifications
17909 (remove-text-properties (point-min) (point-max) pall)
17910 (when org-agenda-skip-archived-trees
17911 (goto-char (point-min))
17912 (while (re-search-forward rea nil t)
17913 (if (org-at-heading-p t)
17914 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17915 (goto-char (point-min))
17916 (setq re (format org-heading-keyword-regexp-format
17917 org-comment-string))
17918 (while (re-search-forward re nil t)
17919 (add-text-properties
17920 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17921 (setq org-todo-keywords-for-agenda
17922 (org-uniquify org-todo-keywords-for-agenda))
17923 (setq org-todo-keyword-alist-for-agenda
17924 (org-uniquify org-todo-keyword-alist-for-agenda))))
17927 ;;;; CDLaTeX minor mode
17929 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17930 "Keymap for the minor `org-cdlatex-mode'.")
17932 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17933 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17934 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17935 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17936 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17938 (defvar org-cdlatex-texmathp-advice-is-done nil
17939 "Flag remembering if we have applied the advice to texmathp already.")
17941 (define-minor-mode org-cdlatex-mode
17942 "Toggle the minor `org-cdlatex-mode'.
17943 This mode supports entering LaTeX environment and math in LaTeX fragments
17945 \\{org-cdlatex-mode-map}"
17947 (when org-cdlatex-mode
17949 (run-hooks 'cdlatex-mode-hook)
17950 (cdlatex-compute-tables))
17951 (unless org-cdlatex-texmathp-advice-is-done
17952 (setq org-cdlatex-texmathp-advice-is-done t)
17953 (defadvice texmathp (around org-math-always-on activate)
17954 "Always return t in org-mode buffers.
17955 This is because we want to insert math symbols without dollars even outside
17956 the LaTeX math segments. If Orgmode thinks that point is actually inside
17957 an embedded LaTeX fragment, let texmathp do its job.
17958 \\[org-cdlatex-mode-map]"
17962 ((not (derived-mode-p 'org-mode)) ad-do-it)
17963 ((eq this-command 'cdlatex-math-symbol)
17964 (setq ad-return-value t
17965 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17967 (let ((p (org-inside-LaTeX-fragment-p)))
17968 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17969 (setq ad-return-value t
17970 texmathp-why '("Org-mode embedded math" . 0))
17971 (if p ad-do-it)))))))))
17973 (defun turn-on-org-cdlatex ()
17974 "Unconditionally turn on `org-cdlatex-mode'."
17975 (org-cdlatex-mode 1))
17977 (defun org-try-cdlatex-tab ()
17978 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17979 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17980 - inside a LaTeX fragment, or
17981 - after the first word in a line, where an abbreviation expansion could
17982 insert a LaTeX environment."
17983 (when org-cdlatex-mode
17985 ;; Before any word on the line: No expansion possible.
17986 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17987 ;; Just after first word on the line: Expand it. Make sure it
17988 ;; cannot happen on headlines, though.
17990 (skip-chars-backward "a-zA-Z0-9*")
17991 (skip-chars-backward " \t")
17992 (and (bolp) (not (org-at-heading-p))))
17994 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17996 (defun org-cdlatex-underscore-caret (&optional arg)
17997 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17998 Revert to the normal definition outside of these fragments."
18000 (if (org-inside-LaTeX-fragment-p)
18001 (call-interactively 'cdlatex-sub-superscript)
18002 (let (org-cdlatex-mode)
18003 (call-interactively (key-binding (vector last-input-event))))))
18005 (defun org-cdlatex-math-modify (&optional arg)
18006 "Execute `cdlatex-math-modify' in LaTeX fragments.
18007 Revert to the normal definition outside of these fragments."
18009 (if (org-inside-LaTeX-fragment-p)
18010 (call-interactively 'cdlatex-math-modify)
18011 (let (org-cdlatex-mode)
18012 (call-interactively (key-binding (vector last-input-event))))))
18016 ;;;; LaTeX fragments
18018 (defvar org-latex-regexps
18019 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18020 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18021 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18022 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18023 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18024 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18025 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18026 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18027 "Regular expressions for matching embedded LaTeX.")
18029 (defun org-inside-LaTeX-fragment-p ()
18030 "Test if point is inside a LaTeX fragment.
18031 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18032 sequence appearing also before point.
18033 Even though the matchers for math are configurable, this function assumes
18034 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18035 delimiters are skipped when they have been removed by customization.
18036 The return value is nil, or a cons cell with the delimiter and the
18037 position of this delimiter.
18039 This function does a reasonably good job, but can locally be fooled by
18040 for example currency specifications. For example it will assume being in
18041 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18042 fragments that are properly closed, but during editing, we have to live
18043 with the uncertainty caused by missing closing delimiters. This function
18044 looks only before point, not after."
18046 (let ((pos (point))
18047 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18049 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18051 dd-on str (start 0) m re)
18054 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18055 re (nth 1 (assoc "$" org-latex-regexps)))
18056 (while (string-match re str start)
18058 ((= (match-end 0) (length str))
18059 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18060 ((= (match-end 0) (- (length str) 5))
18062 (t (setq start (match-end 0))))))
18063 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18065 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18066 (and (match-beginning 2) (throw 'exit nil))
18068 (while (re-search-backward "\\$\\$" lim t)
18069 (setq dd-on (not dd-on)))
18071 (if dd-on (cons "$$" m))))))
18073 (defun org-inside-latex-macro-p ()
18074 "Is point inside a LaTeX macro or its arguments?"
18077 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18079 (defvar org-latex-fragment-image-overlays nil
18080 "List of overlays carrying the images of latex fragments.")
18081 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18083 (defun org-remove-latex-fragment-image-overlays ()
18084 "Remove all overlays with LaTeX fragment images in current buffer."
18085 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18086 (setq org-latex-fragment-image-overlays nil))
18088 (defun org-preview-latex-fragment (&optional subtree)
18089 "Preview the LaTeX fragment at point, or all locally or globally.
18090 If the cursor is in a LaTeX fragment, create the image and overlay
18091 it over the source code. If there is no fragment at point, display
18092 all fragments in the current text, from one headline to the next. With
18093 prefix SUBTREE, display all fragments in the current subtree. With a
18094 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18095 the cursor is before the first headline,
18096 display all fragments in the buffer.
18097 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18099 (unless buffer-file-name
18100 (error "Can't preview LaTeX fragment in a non-file buffer"))
18101 (org-remove-latex-fragment-image-overlays)
18104 (let (beg end at msg)
18106 ((or (equal subtree '(16))
18107 (not (save-excursion
18108 (re-search-backward org-outline-regexp-bol nil t))))
18109 (setq beg (point-min) end (point-max)
18110 msg "Creating images for buffer...%s"))
18111 ((equal subtree '(4))
18112 (org-back-to-heading)
18113 (setq beg (point) end (org-end-of-subtree t)
18114 msg "Creating images for subtree...%s"))
18116 (if (setq at (org-inside-LaTeX-fragment-p))
18117 (goto-char (max (point-min) (- (cdr at) 2)))
18118 (org-back-to-heading))
18119 (setq beg (point) end (progn (outline-next-heading) (point))
18120 msg (if at "Creating image...%s"
18121 "Creating images for entry...%s"))))
18123 (narrow-to-region beg end)
18126 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18127 (file-name-nondirectory
18128 buffer-file-name)))
18129 default-directory 'overlays msg at 'forbuffer
18130 org-latex-create-formula-image-program)
18131 (message msg "done. Use `C-c C-c' to remove images.")))))
18133 (defun org-format-latex (prefix &optional dir overlays msg at
18134 forbuffer processing-type)
18135 "Replace LaTeX fragments with links to an image, and produce images.
18136 Some of the options can be changed using the variable
18137 `org-format-latex-options'."
18138 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18139 (let* ((prefixnodir (file-name-nondirectory prefix))
18140 (absprefix (expand-file-name prefix dir))
18141 (todir (file-name-directory absprefix))
18142 (opt org-format-latex-options)
18143 (optnew org-format-latex-options)
18144 (matchers (plist-get opt :matchers))
18145 (re-list org-latex-regexps)
18146 (cnt 0) txt hash link beg end re e checkdir
18148 m n block-type block linkfile movefile ov)
18149 ;; Check the different regular expressions
18150 (while (setq e (pop re-list))
18151 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18152 block (if block-type "\n\n" ""))
18153 (when (member m matchers)
18154 (goto-char (point-min))
18155 (while (re-search-forward re nil t)
18156 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18158 (not (eq (get-char-property (match-beginning n)
18160 'org-latex-overlay))))
18162 ((eq processing-type 'verbatim))
18163 ((eq processing-type 'mathjax)
18164 ;; Prepare for MathJax processing.
18165 (setq string (match-string n))
18166 (when (member m '("$" "$1"))
18168 (delete-region (match-beginning n) (match-end n))
18169 (goto-char (match-beginning n))
18170 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18171 ((or (eq processing-type 'dvipng)
18172 (eq processing-type 'imagemagick))
18173 ;; Process to an image.
18174 (setq txt (match-string n)
18175 beg (match-beginning n) end (match-end n)
18177 (let ((face (face-at-point))
18178 (fg (plist-get opt :foreground))
18179 (bg (plist-get opt :background))
18180 ;; Ensure full list is printed.
18181 print-length print-level)
18183 ;; Get the colors from the face at point.
18185 (when (eq fg 'auto)
18186 (setq fg (face-attribute face :foreground nil 'default)))
18187 (when (eq bg 'auto)
18188 (setq bg (face-attribute face :background nil 'default)))
18189 (setq optnew (copy-sequence opt))
18190 (plist-put optnew :foreground fg)
18191 (plist-put optnew :background bg))
18192 (setq hash (sha1 (prin1-to-string
18193 (list org-format-latex-header
18194 org-latex-default-packages-alist
18195 org-latex-packages-alist
18196 org-format-latex-options
18197 forbuffer txt fg bg)))
18198 linkfile (format "%s_%s.png" prefix hash)
18199 movefile (format "%s_%s.png" absprefix hash)))
18200 (setq link (concat block "[[file:" linkfile "]]" block))
18201 (if msg (message msg cnt))
18203 (unless checkdir ; Ensure the directory exists.
18205 (or (file-directory-p todir) (make-directory todir t)))
18206 (unless (file-exists-p movefile)
18207 (org-create-formula-image
18208 txt movefile optnew forbuffer processing-type))
18212 (if (eq (overlay-get o 'org-overlay-type)
18213 'org-latex-overlay)
18214 (delete-overlay o)))
18215 (overlays-in beg end))
18216 (setq ov (make-overlay beg end))
18217 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18218 (if (featurep 'xemacs)
18220 (overlay-put ov 'invisible t)
18223 (make-glyph (vector 'png :file movefile))))
18226 (list 'image :type 'png :file movefile :ascent 'center)))
18227 (push ov org-latex-fragment-image-overlays)
18229 (delete-region beg end)
18230 (insert (org-add-props link
18231 (list 'org-latex-src
18232 (replace-regexp-in-string
18234 'org-latex-src-embed-type
18235 (if block-type 'paragraph 'character))))))
18236 ((eq processing-type 'mathml)
18237 ;; Process to MathML
18238 (unless (save-match-data (org-format-latex-mathml-available-p))
18239 (error "LaTeX to MathML converter not configured"))
18240 (setq txt (match-string n)
18241 beg (match-beginning n) end (match-end n)
18243 (if msg (message msg cnt))
18245 (delete-region beg end)
18246 (insert (org-format-latex-as-mathml
18247 txt block-type prefix dir)))
18249 (error "Unknown conversion type %s for latex fragments"
18250 processing-type)))))))))
18252 (defun org-create-math-formula (latex-frag &optional mathml-file)
18253 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18254 Use `org-latex-to-mathml-convert-command'. If the conversion is
18255 sucessful, return the portion between \"<math...> </math>\"
18256 elements otherwise return nil. When MATHML-FILE is specified,
18257 write the results in to that file. When invoked as an
18258 interactive command, prompt for LATEX-FRAG, with initial value
18259 set to the current active region and echo the results for user
18261 (interactive (list (let ((frag (when (org-region-active-p)
18262 (buffer-substring-no-properties
18263 (region-beginning) (region-end)))))
18264 (read-string "LaTeX Fragment: " frag nil frag))))
18265 (unless latex-frag (error "Invalid latex-frag"))
18266 (let* ((tmp-in-file (file-relative-name
18267 (make-temp-name (expand-file-name "ltxmathml-in"))))
18268 (ignore (write-region latex-frag nil tmp-in-file))
18269 (tmp-out-file (file-relative-name
18270 (make-temp-name (expand-file-name "ltxmathml-out"))))
18272 org-latex-to-mathml-convert-command
18273 `((?j . ,(shell-quote-argument
18274 (expand-file-name org-latex-to-mathml-jar-file)))
18275 (?I . ,(shell-quote-argument tmp-in-file))
18276 (?o . ,(shell-quote-argument tmp-out-file)))))
18277 mathml shell-command-output)
18278 (when (org-called-interactively-p 'any)
18279 (unless (org-format-latex-mathml-available-p)
18280 (error "LaTeX to MathML converter not configured")))
18281 (message "Running %s" cmd)
18282 (setq shell-command-output (shell-command-to-string cmd))
18284 (when (file-readable-p tmp-out-file)
18285 (with-current-buffer (find-file-noselect tmp-out-file t)
18286 (goto-char (point-min))
18287 (when (re-search-forward
18290 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18292 (regexp-quote "</math>")) nil t)
18293 (prog1 (match-string 0) (kill-buffer))))))
18297 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18299 (write-region mathml nil mathml-file))
18300 (when (org-called-interactively-p 'any)
18302 ((message "LaTeX to MathML conversion failed")
18303 (message shell-command-output)))
18304 (delete-file tmp-in-file)
18305 (when (file-exists-p tmp-out-file)
18306 (delete-file tmp-out-file))
18309 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18310 prefix &optional dir)
18311 "Use `org-create-math-formula' but check local cache first."
18312 (let* ((absprefix (expand-file-name prefix dir))
18313 (print-length nil) (print-level nil)
18314 (formula-id (concat
18319 org-latex-to-mathml-convert-command)))))
18320 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18321 (formula-cache-dir (file-name-directory formula-cache)))
18323 (unless (file-directory-p formula-cache-dir)
18324 (make-directory formula-cache-dir t))
18326 (unless (file-exists-p formula-cache)
18327 (org-create-math-formula latex-frag formula-cache))
18329 (if (file-exists-p formula-cache)
18330 ;; Successful conversion. Return the link to MathML file.
18332 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18333 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18334 'org-latex-src-embed-type (if latex-frag-type
18335 'paragraph 'character)))
18336 ;; Failed conversion. Return the LaTeX fragment verbatim
18339 (defun org-create-formula-image (string tofile options buffer &optional type)
18340 "Create an image from LaTeX source using dvipng or convert.
18341 This function calls either `org-create-formula-image-with-dvipng'
18342 or `org-create-formula-image-with-imagemagick' depending on the
18343 value of `org-latex-create-formula-image-program' or on the value
18344 of the optional TYPE variable.
18346 Note: ultimately these two function should be combined as they
18347 share a good deal of logic."
18348 (org-check-external-command
18349 "latex" "needed to convert LaTeX fragments to images")
18351 (case (or type org-latex-create-formula-image-program)
18353 (org-check-external-command
18354 "dvipng" "needed to convert LaTeX fragments to images")
18355 #'org-create-formula-image-with-dvipng)
18357 (org-check-external-command
18358 "convert" "you need to install imagemagick")
18359 #'org-create-formula-image-with-imagemagick)
18361 "invalid value of `org-latex-create-formula-image-program'")))
18362 string tofile options buffer))
18364 (declare-function org-export--get-global-options "ox" (&optional backend))
18365 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18366 (defun org-create-formula--latex-header ()
18367 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18368 (org-latex-guess-inputenc
18369 (org-splice-latex-header
18370 org-format-latex-header
18371 org-latex-default-packages-alist
18372 org-latex-packages-alist t
18374 (org-combine-plists
18375 (org-export--get-global-options 'latex)
18376 (org-export--get-inbuffer-options 'latex))
18379 ;; This function borrows from Ganesh Swami's latex2png.el
18380 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18381 "This calls dvipng."
18382 (require 'ox-latex)
18383 (let* ((tmpdir (if (featurep 'xemacs)
18385 temporary-file-directory))
18386 (texfilebase (make-temp-name
18387 (expand-file-name "orgtex" tmpdir)))
18388 (texfile (concat texfilebase ".tex"))
18389 (dvifile (concat texfilebase ".dvi"))
18390 (pngfile (concat texfilebase ".png"))
18391 (fnh (if (featurep 'xemacs)
18392 (font-height (face-font 'default))
18393 (face-attribute 'default :height nil)))
18394 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18395 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18396 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18398 (bg (or (plist-get options (if buffer :background :html-background))
18400 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18401 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18402 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18403 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18404 (let ((latex-header (org-create-formula--latex-header)))
18405 (with-temp-file texfile
18406 (insert latex-header)
18407 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18408 (let ((dir default-directory))
18409 (condition-case nil
18412 (call-process "latex" nil nil nil texfile))
18415 (if (not (file-exists-p dvifile))
18416 (progn (message "Failed to create dvi file from %s" texfile) nil)
18417 (condition-case nil
18418 (if (featurep 'xemacs)
18419 (call-process "dvipng" nil nil nil
18424 (call-process "dvipng" nil nil nil
18427 ;;"-x" scale "-y" scale
18432 (if (not (file-exists-p pngfile))
18433 (if org-format-latex-signal-error
18434 (error "Failed to create png file from %s" texfile)
18435 (message "Failed to create png file from %s" texfile)
18437 ;; Use the requested file name and clean up
18438 (copy-file pngfile tofile 'replace)
18439 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18440 (if (file-exists-p (concat texfilebase e))
18441 (delete-file (concat texfilebase e))))
18444 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18445 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18446 "This calls convert, which is included into imagemagick."
18447 (require 'ox-latex)
18448 (let* ((tmpdir (if (featurep 'xemacs)
18450 temporary-file-directory))
18451 (texfilebase (make-temp-name
18452 (expand-file-name "orgtex" tmpdir)))
18453 (texfile (concat texfilebase ".tex"))
18454 (pdffile (concat texfilebase ".pdf"))
18455 (pngfile (concat texfilebase ".png"))
18456 (fnh (if (featurep 'xemacs)
18457 (font-height (face-font 'default))
18458 (face-attribute 'default :height nil)))
18459 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18460 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18461 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18463 (bg (or (plist-get options (if buffer :background :html-background))
18465 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18466 (setq fg (org-latex-color-format fg)))
18467 (if (eq bg 'default) (setq bg (org-latex-color :background))
18468 (setq bg (org-latex-color-format
18469 (if (string= bg "Transparent") "white" bg))))
18470 (let ((latex-header (org-create-formula--latex-header)))
18471 (with-temp-file texfile
18472 (insert latex-header)
18473 (insert "\n\\begin{document}\n"
18474 "\\definecolor{fg}{rgb}{" fg "}\n"
18475 "\\definecolor{bg}{rgb}{" bg "}\n"
18476 "\n\\pagecolor{bg}\n"
18480 "\n\\end{document}\n")))
18481 (org-latex-compile texfile t)
18482 (if (not (file-exists-p pdffile))
18483 (progn (message "Failed to create pdf file from %s" texfile) nil)
18484 (condition-case nil
18485 (if (featurep 'xemacs)
18486 (call-process "convert" nil nil nil
18492 ;; "-sharpen" "0x1.0"
18494 (call-process "convert" nil nil nil
18500 ;; "-sharpen" "0x1.0"
18503 (if (not (file-exists-p pngfile))
18504 (if org-format-latex-signal-error
18505 (error "Failed to create png file from %s" texfile)
18506 (message "Failed to create png file from %s" texfile)
18508 ;; Use the requested file name and clean up
18509 (copy-file pngfile tofile 'replace)
18510 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18511 (if (file-exists-p (concat texfilebase e))
18512 (delete-file (concat texfilebase e))))
18515 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18516 "Fill a LaTeX header template TPL.
18517 In the template, the following place holders will be recognized:
18519 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18520 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18521 [PACKAGES] \\usepackage statements for PKG
18522 [NO-PACKAGES] do not include PKG
18523 [EXTRA] the string EXTRA
18524 [NO-EXTRA] do not include EXTRA
18526 For backward compatibility, if both the positive and the negative place
18527 holder is missing, the positive one (without the \"NO-\") will be
18528 assumed to be present at the end of the template.
18529 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18531 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18532 (let (rpl (end ""))
18533 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18534 (setq rpl (if (or (match-end 1) (not def-pkg))
18535 "" (org-latex-packages-to-string def-pkg snippets-p t))
18536 tpl (replace-match rpl t t tpl))
18537 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18539 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18540 (setq rpl (if (or (match-end 1) (not pkg))
18541 "" (org-latex-packages-to-string pkg snippets-p t))
18542 tpl (replace-match rpl t t tpl))
18545 (org-latex-packages-to-string pkg snippets-p)))))
18547 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18548 (setq rpl (if (or (match-end 1) (not extra))
18549 "" (concat extra "\n"))
18550 tpl (replace-match rpl t t tpl))
18551 (if (and extra (string-match "\\S-" extra))
18552 (setq end (concat end "\n" extra))))
18554 (if (string-match "\\S-" end)
18555 (concat tpl "\n" end)
18558 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18559 "Turn an alist of packages into a string with the \\usepackage macros."
18560 (setq pkg (mapconcat (lambda(p)
18563 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18564 (format "%% Package %s omitted" (cadr p)))
18565 ((equal "" (car p))
18566 (format "\\usepackage{%s}" (cadr p)))
18568 (format "\\usepackage[%s]{%s}"
18569 (car p) (cadr p)))))
18572 (if newline (concat pkg "\n") pkg))
18574 (defun org-dvipng-color (attr)
18575 "Return a RGB color specification for dvipng."
18576 (apply 'format "rgb %s %s %s"
18577 (mapcar 'org-normalize-color
18578 (if (featurep 'xemacs)
18579 (color-rgb-components
18580 (face-property 'default
18581 (cond ((eq attr :foreground) 'foreground)
18582 ((eq attr :background) 'background))))
18583 (color-values (face-attribute 'default attr nil))))))
18585 (defun org-dvipng-color-format (color-name)
18586 "Convert COLOR-NAME to a RGB color value for dvipng."
18587 (apply 'format "rgb %s %s %s"
18588 (mapcar 'org-normalize-color
18589 (color-values color-name))))
18591 (defun org-latex-color (attr)
18592 "Return a RGB color for the LaTeX color package."
18593 (apply 'format "%s,%s,%s"
18594 (mapcar 'org-normalize-color
18595 (if (featurep 'xemacs)
18596 (color-rgb-components
18597 (face-property 'default
18598 (cond ((eq attr :foreground) 'foreground)
18599 ((eq attr :background) 'background))))
18600 (color-values (face-attribute 'default attr nil))))))
18602 (defun org-latex-color-format (color-name)
18603 "Convert COLOR-NAME to a RGB color value."
18604 (apply 'format "%s,%s,%s"
18605 (mapcar 'org-normalize-color
18606 (color-values color-name))))
18608 (defun org-normalize-color (value)
18609 "Return string to be used as color value for an RGB component."
18610 (format "%g" (/ value 65535.0)))
18616 (defvar org-inline-image-overlays nil)
18617 (make-variable-buffer-local 'org-inline-image-overlays)
18619 (defun org-toggle-inline-images (&optional include-linked)
18620 "Toggle the display of inline images.
18621 INCLUDE-LINKED is passed to `org-display-inline-images'."
18623 (if org-inline-image-overlays
18625 (org-remove-inline-images)
18626 (message "Inline image display turned off"))
18627 (org-display-inline-images include-linked)
18628 (if (and (org-called-interactively-p)
18629 org-inline-image-overlays)
18630 (message "%d images displayed inline"
18631 (length org-inline-image-overlays))
18632 (message "No images to display inline"))))
18634 (defun org-redisplay-inline-images ()
18635 "Refresh the display of inline images."
18637 (if (not org-inline-image-overlays)
18638 (org-toggle-inline-images)
18639 (org-toggle-inline-images)
18640 (org-toggle-inline-images)))
18642 (defun org-display-inline-images (&optional include-linked refresh beg end)
18643 "Display inline images.
18644 Normally only links without a description part are inlined, because this
18645 is how it will work for export. When INCLUDE-LINKED is set, also links
18646 with a description part will be inlined. This can be nice for a quick
18647 look at those images, but it does not reflect what exported files will look
18649 When REFRESH is set, refresh existing images between BEG and END.
18650 This will create new image displays only if necessary.
18651 BEG and END default to the buffer boundaries."
18654 (org-remove-inline-images)
18655 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18659 (setq beg (or beg (point-min)) end (or end (point-max)))
18661 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18662 (substring (org-image-file-name-regexp) 0 -2)
18663 "\\)\\]" (if include-linked "" "\\]")))
18664 (case-fold-search t)
18665 old file ov img type attrwidth width)
18666 (while (re-search-forward re end t)
18667 (setq old (get-char-property-and-overlay (match-beginning 1)
18668 'org-image-overlay)
18669 file (expand-file-name
18670 (concat (or (match-string 3) "") (match-string 4))))
18671 (when (image-type-available-p 'imagemagick)
18672 (setq attrwidth (if (or (listp org-image-actual-width)
18673 (null org-image-actual-width))
18676 (when (re-search-backward
18677 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18679 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18680 (string-to-number (match-string 1))))))
18681 width (cond ((eq org-image-actual-width t) nil)
18682 ((null org-image-actual-width) attrwidth)
18683 ((numberp org-image-actual-width)
18684 org-image-actual-width)
18685 ((listp org-image-actual-width)
18686 (or attrwidth (car org-image-actual-width))))
18687 type (if width 'imagemagick)))
18688 (when (file-exists-p file)
18689 (if (and (car-safe old) refresh)
18690 (image-refresh (overlay-get (cdr old) 'display))
18691 (setq img (save-match-data (create-image file type nil :width width)))
18693 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18694 (overlay-put ov 'display img)
18695 (overlay-put ov 'face 'default)
18696 (overlay-put ov 'org-image-overlay t)
18697 (overlay-put ov 'modification-hooks
18698 (list 'org-display-inline-remove-overlay))
18699 (push ov org-inline-image-overlays)))))))))
18701 (define-obsolete-function-alias
18702 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18704 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18705 "Remove inline-display overlay if a corresponding region is modified."
18706 (let ((inhibit-modification-hooks t))
18707 (when (and ov after)
18708 (delete ov org-inline-image-overlays)
18709 (delete-overlay ov))))
18711 (defun org-remove-inline-images ()
18712 "Remove inline display of images."
18714 (mapc 'delete-overlay org-inline-image-overlays)
18715 (setq org-inline-image-overlays nil))
18719 ;; Outline functions from `outline-mode-prefix-map'
18720 ;; that can be remapped in Org:
18721 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18722 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18723 (define-key org-mode-map [remap outline-forward-same-level]
18724 'org-forward-heading-same-level)
18725 (define-key org-mode-map [remap outline-backward-same-level]
18726 'org-backward-heading-same-level)
18727 (define-key org-mode-map [remap show-branches]
18728 'org-kill-note-or-show-branches)
18729 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18730 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18731 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18733 ;; Outline functions from `outline-mode-prefix-map' that can not
18734 ;; be remapped in Org:
18736 ;; - the column "key binding" shows whether the Outline function is still
18737 ;; available in Org mode on the same key that it has been bound to in
18739 ;; - "overridden": key used for a different functionality in Org mode
18740 ;; - else: key still bound to the same Outline function in Org mode
18742 ;; | Outline function | key binding | Org replacement |
18743 ;; |------------------------------------+-------------+-----------------------|
18744 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18745 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18746 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18747 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18748 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18749 ;; | `show-entry' | overridden | no replacement |
18750 ;; | `show-children' | `C-c C-i' | visibility cycling |
18751 ;; | `show-branches' | `C-c C-k' | still same function |
18752 ;; | `show-subtree' | overridden | visibility cycling |
18753 ;; | `show-all' | overridden | no replacement |
18754 ;; | `hide-subtree' | overridden | visibility cycling |
18755 ;; | `hide-body' | overridden | no replacement |
18756 ;; | `hide-entry' | overridden | visibility cycling |
18757 ;; | `hide-leaves' | overridden | no replacement |
18758 ;; | `hide-sublevels' | overridden | no replacement |
18759 ;; | `hide-other' | overridden | no replacement |
18761 ;; Make `C-c C-x' a prefix key
18762 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18764 ;; TAB key with modifiers
18765 (org-defkey org-mode-map "\C-i" 'org-cycle)
18766 (org-defkey org-mode-map [(tab)] 'org-cycle)
18767 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18768 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18769 ;; The following line is necessary under Suse GNU/Linux
18770 (unless (featurep 'xemacs)
18771 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18772 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18773 (define-key org-mode-map [backtab] 'org-shifttab)
18775 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18776 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18777 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18779 ;; Cursor keys with modifiers
18780 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18781 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18782 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18783 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18785 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18786 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18787 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18788 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18790 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18791 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18792 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18793 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18795 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18796 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18797 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18798 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18801 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18802 (mapc (lambda (pair)
18803 (define-key org-babel-map (car pair) (cdr pair)))
18804 org-babel-key-bindings)
18806 ;;; Extra keys for tty access.
18807 ;; We only set them when really needed because otherwise the
18808 ;; menus don't show the simple keys
18810 (when (or org-use-extra-keys
18811 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18812 (not window-system))
18813 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18814 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18815 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18816 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18817 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18818 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18819 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18820 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18821 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18822 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18823 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18824 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18825 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18826 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18827 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18828 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18829 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18830 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18831 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18832 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18833 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18834 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18835 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18836 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18837 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18838 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18839 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18840 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18842 ;; All the other keys
18844 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18845 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18846 (if (boundp 'narrow-map)
18847 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18848 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18849 (if (boundp 'narrow-map)
18850 (org-defkey narrow-map "b" 'org-narrow-to-block)
18851 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18852 (if (boundp 'narrow-map)
18853 (org-defkey narrow-map "e" 'org-narrow-to-element)
18854 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18855 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18856 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18857 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18858 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18859 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18860 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18861 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18862 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18863 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18864 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18865 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18866 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18867 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18868 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18869 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18870 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18871 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18872 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18873 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18874 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18875 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18876 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18877 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18878 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18879 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18880 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18881 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18882 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18883 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18884 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18885 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18886 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18887 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18888 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18889 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18890 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18891 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18892 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18893 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18894 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18895 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18896 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18897 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18898 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18899 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18900 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18901 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18902 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18903 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18904 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18905 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18906 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18907 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18908 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18909 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18910 (org-defkey org-mode-map "\C-c^" 'org-sort)
18911 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18912 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18913 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18914 (org-defkey org-mode-map "\C-m" 'org-return)
18915 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18916 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18917 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18918 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18919 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18920 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18921 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18922 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18923 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18924 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18925 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18926 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18927 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18928 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18929 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18930 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18931 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18932 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18933 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18934 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18935 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18936 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18937 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18939 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18940 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18941 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18943 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18944 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18945 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18946 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18947 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18948 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18949 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18950 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18951 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18952 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18953 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18954 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18955 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18956 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18957 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18958 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18959 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18960 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18961 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18962 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18963 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18964 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18965 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18967 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18968 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18969 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18970 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18971 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18973 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18975 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18977 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18978 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18980 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18983 (when (featurep 'xemacs)
18984 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18987 (defconst org-speed-commands-default
18989 ("Outline Navigation")
18990 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18991 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18992 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18993 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18994 ("F" . org-next-block)
18995 ("B" . org-previous-block)
18996 ("u" . (org-speed-move-safe 'outline-up-heading))
18998 ("g" . (org-refile t))
18999 ("Outline Visibility")
19001 ("C" . org-shifttab)
19002 (" " . org-display-outline-path)
19003 ("=" . org-columns)
19004 ("Outline Structure Editing")
19005 ("U" . org-shiftmetaup)
19006 ("D" . org-shiftmetadown)
19007 ("r" . org-metaright)
19008 ("l" . org-metaleft)
19009 ("R" . org-shiftmetaright)
19010 ("L" . org-shiftmetaleft)
19011 ("i" . (progn (forward-char 1) (call-interactively
19012 'org-insert-heading-respect-content)))
19015 ("a" . org-archive-subtree-default-with-confirmation)
19016 ("@" . org-mark-subtree)
19017 ("#" . org-toggle-comment)
19019 ("I" . org-clock-in)
19020 ("O" . org-clock-out)
19021 ("Meta Data Editing")
19023 ("," . (org-priority))
19024 ("0" . (org-priority ?\ ))
19025 ("1" . (org-priority ?A))
19026 ("2" . (org-priority ?B))
19027 ("3" . (org-priority ?C))
19028 (":" . org-set-tags-command)
19029 ("e" . org-set-effort)
19030 ("E" . org-inc-effort)
19031 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19032 (org-entry-put (point) "APPT_WARNTIME" m)))
19033 ("Agenda Views etc")
19035 ("/" . org-sparse-tree)
19037 ("o" . org-open-at-point)
19038 ("?" . org-speed-command-help)
19039 ("<" . (org-agenda-set-restriction-lock 'subtree))
19040 (">" . (org-agenda-remove-restriction-lock))
19042 "The default speed commands.")
19044 (defun org-print-speed-command (e)
19045 (if (> (length (car e)) 1)
19050 (princ (make-string (length (car e)) ?-))
19054 (if (symbolp (cdr e))
19055 (princ (symbol-name (cdr e)))
19059 (defun org-speed-command-help ()
19060 "Show the available speed commands."
19062 (if (not org-use-speed-commands)
19063 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19064 (with-output-to-temp-buffer "*Help*"
19065 (princ "User-defined Speed commands\n===========================\n")
19066 (mapc 'org-print-speed-command org-speed-commands-user)
19068 (princ "Built-in Speed commands\n=======================\n")
19069 (mapc 'org-print-speed-command org-speed-commands-default))
19070 (with-current-buffer "*Help*"
19071 (setq truncate-lines t))))
19073 (defun org-speed-move-safe (cmd)
19074 "Execute CMD, but make sure that the cursor always ends up in a headline.
19075 If not, return to the original position and throw an error."
19077 (let ((pos (point)))
19078 (call-interactively cmd)
19079 (unless (and (bolp) (org-at-heading-p))
19081 (error "Boundary reached while executing %s" cmd))))
19083 (defvar org-self-insert-command-undo-counter 0)
19085 (defvar org-table-auto-blank-field) ; defined in org-table.el
19086 (defvar org-speed-command nil)
19088 (define-obsolete-function-alias
19089 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19091 (defun org-speed-command-activate (keys)
19092 "Hook for activating single-letter speed commands.
19093 `org-speed-commands-default' specifies a minimal command set.
19094 Use `org-speed-commands-user' for further customization."
19095 (when (or (and (bolp) (looking-at org-outline-regexp))
19096 (and (functionp org-use-speed-commands)
19097 (funcall org-use-speed-commands)))
19098 (cdr (assoc keys (append org-speed-commands-user
19099 org-speed-commands-default)))))
19101 (define-obsolete-function-alias
19102 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19104 (defun org-babel-speed-command-activate (keys)
19105 "Hook for activating single-letter code block commands."
19106 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19107 (cdr (assoc keys org-babel-key-bindings))))
19109 (defcustom org-speed-command-hook
19110 '(org-speed-command-default-hook org-babel-speed-command-hook)
19111 "Hook for activating speed commands at strategic locations.
19112 Hook functions are called in sequence until a valid handler is
19115 Each hook takes a single argument, a user-pressed command key
19116 which is also a `self-insert-command' from the global map.
19118 Within the hook, examine the cursor position and the command key
19119 and return nil or a valid handler as appropriate. Handler could
19120 be one of an interactive command, a function, or a form.
19122 Set `org-use-speed-commands' to non-nil value to enable this
19123 hook. The default setting is `org-speed-command-activate'."
19124 :group 'org-structure
19128 (defun org-self-insert-command (N)
19129 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19130 If the cursor is in a table looking at whitespace, the whitespace is
19131 overwritten, and the table is not marked as requiring realignment."
19133 (org-check-before-invisible-edit 'insert)
19135 ((and org-use-speed-commands
19136 (setq org-speed-command
19137 (run-hook-with-args-until-success
19138 'org-speed-command-hook (this-command-keys))))
19140 ((commandp org-speed-command)
19141 (setq this-command org-speed-command)
19142 (call-interactively org-speed-command))
19143 ((functionp org-speed-command)
19144 (funcall org-speed-command))
19145 ((and org-speed-command (listp org-speed-command))
19146 (eval org-speed-command))
19147 (t (let (org-use-speed-commands)
19148 (call-interactively 'org-self-insert-command)))))
19152 ;; check if we blank the field, and if that triggers align
19153 (and (featurep 'org-table) org-table-auto-blank-field
19154 (member last-command
19155 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19156 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19157 ;; got extra space, this field does not determine column width
19158 (let (org-table-may-need-update) (org-table-blank-field))
19159 ;; no extra space, this field may determine column width
19160 (org-table-blank-field)))
19163 (looking-at "[^|\n]* |"))
19164 (let (org-table-may-need-update)
19165 (goto-char (1- (match-end 0)))
19166 (backward-delete-char 1)
19167 (goto-char (match-beginning 0))
19168 (self-insert-command N)))
19170 (setq org-table-may-need-update t)
19171 (self-insert-command N)
19172 (org-fix-tags-on-the-fly)
19173 (if org-self-insert-cluster-for-undo
19174 (if (not (eq last-command 'org-self-insert-command))
19175 (setq org-self-insert-command-undo-counter 1)
19176 (if (>= org-self-insert-command-undo-counter 20)
19177 (setq org-self-insert-command-undo-counter 1)
19178 (and (> org-self-insert-command-undo-counter 0)
19179 buffer-undo-list (listp buffer-undo-list)
19180 (not (cadr buffer-undo-list)) ; remove nil entry
19181 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19182 (setq org-self-insert-command-undo-counter
19183 (1+ org-self-insert-command-undo-counter))))))))
19185 (defun org-check-before-invisible-edit (kind)
19186 "Check is editing if kind KIND would be dangerous with invisible text around.
19187 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19188 ;; First, try to get out of here as quickly as possible, to reduce overhead
19189 (if (and org-catch-invisible-edits
19190 (or (not (boundp 'visible-mode)) (not visible-mode))
19191 (or (get-char-property (point) 'invisible)
19192 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19193 ;; OK, we need to take a closer look
19194 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19195 (invisible-before-point (if (bobp) nil (get-char-property
19196 (1- (point)) 'invisible)))
19197 (border-and-ok-direction
19199 ;; Check if we are acting predictably before invisible text
19200 (and invisible-at-point (not invisible-before-point)
19201 (memq kind '(insert delete-backward)))
19202 ;; Check if we are acting predictably after invisible text
19203 ;; This works not well, and I have turned it off. It seems
19204 ;; better to always show and stop after invisible text.
19205 ;; (and (not invisible-at-point) invisible-before-point
19206 ;; (memq kind '(insert delete)))
19208 (when (or (memq invisible-at-point '(outline org-hide-block t))
19209 (memq invisible-before-point '(outline org-hide-block t)))
19210 (if (eq org-catch-invisible-edits 'error)
19211 (error "Editing in invisible areas is prohibited - make visible first"))
19212 (if (and org-custom-properties-overlays
19213 (y-or-n-p "Display invisible properties in this buffer? "))
19214 (org-toggle-custom-properties-visibility)
19215 ;; Make the area visible
19217 (if invisible-before-point
19218 (goto-char (previous-single-char-property-change
19219 (point) 'invisible)))
19222 ((eq org-catch-invisible-edits 'show)
19223 ;; That's it, we do the edit after showing
19225 "Unfolding invisible region around point before editing")
19227 ((and (eq org-catch-invisible-edits 'smart)
19228 border-and-ok-direction)
19229 (message "Unfolding invisible region around point before editing"))
19231 ;; Don't do the edit, make the user repeat it in full visibility
19232 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19234 (defun org-fix-tags-on-the-fly ()
19235 (when (and (equal (char-after (point-at-bol)) ?*)
19236 (org-at-heading-p))
19237 (org-align-tags-here org-tags-column)))
19239 (defun org-delete-backward-char (N)
19240 "Like `delete-backward-char', insert whitespace at field end in tables.
19241 When deleting backwards, in tables this function will insert whitespace in
19242 front of the next \"|\" separator, to keep the table aligned. The table will
19243 still be marked for re-alignment if the field did fill the entire column,
19244 because, in this case the deletion might narrow the column."
19247 (org-check-before-invisible-edit 'delete-backward)
19248 (if (and (org-table-p)
19250 (string-match "|" (buffer-substring (point-at-bol) (point)))
19251 (looking-at ".*?|"))
19252 (let ((pos (point))
19253 (noalign (looking-at "[^|\n\r]* |"))
19254 (c org-table-may-need-update))
19255 (backward-delete-char N)
19256 (if (not overwrite-mode)
19258 (skip-chars-forward "^|")
19260 (goto-char (1- pos))))
19261 ;; noalign: if there were two spaces at the end, this field
19262 ;; does not determine the width of the column.
19263 (if noalign (setq org-table-may-need-update c)))
19264 (backward-delete-char N)
19265 (org-fix-tags-on-the-fly))))
19267 (defun org-delete-char (N)
19268 "Like `delete-char', but insert whitespace at field end in tables.
19269 When deleting characters, in tables this function will insert whitespace in
19270 front of the next \"|\" separator, to keep the table aligned. The table will
19271 still be marked for re-alignment if the field did fill the entire column,
19272 because, in this case the deletion might narrow the column."
19275 (org-check-before-invisible-edit 'delete)
19276 (if (and (org-table-p)
19278 (not (= (char-after) ?|))
19280 (if (looking-at ".*?|")
19281 (let ((pos (point))
19282 (noalign (looking-at "[^|\n\r]* |"))
19283 (c org-table-may-need-update))
19285 (concat (substring (match-string 0) 1 -1) " |") nil t)
19287 ;; noalign: if there were two spaces at the end, this field
19288 ;; does not determine the width of the column.
19289 (if noalign (setq org-table-may-need-update c)))
19292 (org-fix-tags-on-the-fly))))
19294 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19295 (put 'org-self-insert-command 'delete-selection t)
19296 (put 'orgtbl-self-insert-command 'delete-selection t)
19297 (put 'org-delete-char 'delete-selection 'supersede)
19298 (put 'org-delete-backward-char 'delete-selection 'supersede)
19299 (put 'org-yank 'delete-selection 'yank)
19301 ;; Make `flyspell-mode' delay after some commands
19302 (put 'org-self-insert-command 'flyspell-delayed t)
19303 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19304 (put 'org-delete-char 'flyspell-delayed t)
19305 (put 'org-delete-backward-char 'flyspell-delayed t)
19307 ;; Make pabbrev-mode expand after org-mode commands
19308 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19309 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19311 ;; How to do this: Measure non-white length of current string
19312 ;; If equal to column width, we should realign.
19314 (defun org-remap (map &rest commands)
19315 "In MAP, remap the functions given in COMMANDS.
19316 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19319 (setq old (pop commands) new (pop commands))
19320 (if (fboundp 'command-remapping)
19321 (org-defkey map (vector 'remap old) new)
19322 (substitute-key-definition old new map global-map)))))
19324 (defun org-transpose-words ()
19325 "Transpose words for Org.
19326 This uses the `org-mode-transpose-word-syntax-table' syntax
19327 table, which interprets characters in `org-emphasis-alist' as
19328 word constituants."
19330 (with-syntax-table org-mode-transpose-word-syntax-table
19331 (call-interactively 'transpose-words)))
19332 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19334 (when (eq org-enable-table-editor 'optimized)
19335 ;; If the user wants maximum table support, we need to hijack
19336 ;; some standard editing functions
19337 (org-remap org-mode-map
19338 'self-insert-command 'org-self-insert-command
19339 'delete-char 'org-delete-char
19340 'delete-backward-char 'org-delete-backward-char)
19341 (org-defkey org-mode-map "|" 'org-force-self-insert))
19343 (defvar org-ctrl-c-ctrl-c-hook nil
19344 "Hook for functions attaching themselves to `C-c C-c'.
19346 This can be used to add additional functionality to the C-c C-c
19347 key which executes context-dependent commands. This hook is run
19348 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19349 run after the last test.
19351 Each function will be called with no arguments. The function
19352 must check if the context is appropriate for it to act. If yes,
19353 it should do its thing and then return a non-nil value. If the
19354 context is wrong, just do nothing and return nil.")
19356 (defvar org-ctrl-c-ctrl-c-final-hook nil
19357 "Hook for functions attaching themselves to `C-c C-c'.
19359 This can be used to add additional functionality to the C-c C-c
19360 key which executes context-dependent commands. This hook is run
19361 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19362 before the first test.
19364 Each function will be called with no arguments. The function
19365 must check if the context is appropriate for it to act. If yes,
19366 it should do its thing and then return a non-nil value. If the
19367 context is wrong, just do nothing and return nil.")
19369 (defvar org-tab-first-hook nil
19370 "Hook for functions to attach themselves to TAB.
19371 See `org-ctrl-c-ctrl-c-hook' for more information.
19372 This hook runs as the first action when TAB is pressed, even before
19373 `org-cycle' messes around with the `outline-regexp' to cater for
19374 inline tasks and plain list item folding.
19375 If any function in this hook returns t, any other actions that
19376 would have been caused by TAB (such as table field motion or visibility
19377 cycling) will not occur.")
19379 (defvar org-tab-after-check-for-table-hook nil
19380 "Hook for functions to attach themselves to TAB.
19381 See `org-ctrl-c-ctrl-c-hook' for more information.
19382 This hook runs after it has been established that the cursor is not in a
19383 table, but before checking if the cursor is in a headline or if global cycling
19385 If any function in this hook returns t, not other actions like visibility
19386 cycling will be done.")
19388 (defvar org-tab-after-check-for-cycling-hook nil
19389 "Hook for functions to attach themselves to TAB.
19390 See `org-ctrl-c-ctrl-c-hook' for more information.
19391 This hook runs after it has been established that not table field motion and
19392 not visibility should be done because of current context. This is probably
19393 the place where a package like yasnippets can hook in.")
19395 (defvar org-tab-before-tab-emulation-hook nil
19396 "Hook for functions to attach themselves to TAB.
19397 See `org-ctrl-c-ctrl-c-hook' for more information.
19398 This hook runs after every other options for TAB have been exhausted, but
19399 before indentation and \t insertion takes place.")
19401 (defvar org-metaleft-hook nil
19402 "Hook for functions attaching themselves to `M-left'.
19403 See `org-ctrl-c-ctrl-c-hook' for more information.")
19404 (defvar org-metaright-hook nil
19405 "Hook for functions attaching themselves to `M-right'.
19406 See `org-ctrl-c-ctrl-c-hook' for more information.")
19407 (defvar org-metaup-hook nil
19408 "Hook for functions attaching themselves to `M-up'.
19409 See `org-ctrl-c-ctrl-c-hook' for more information.")
19410 (defvar org-metadown-hook nil
19411 "Hook for functions attaching themselves to `M-down'.
19412 See `org-ctrl-c-ctrl-c-hook' for more information.")
19413 (defvar org-shiftmetaleft-hook nil
19414 "Hook for functions attaching themselves to `M-S-left'.
19415 See `org-ctrl-c-ctrl-c-hook' for more information.")
19416 (defvar org-shiftmetaright-hook nil
19417 "Hook for functions attaching themselves to `M-S-right'.
19418 See `org-ctrl-c-ctrl-c-hook' for more information.")
19419 (defvar org-shiftmetaup-hook nil
19420 "Hook for functions attaching themselves to `M-S-up'.
19421 See `org-ctrl-c-ctrl-c-hook' for more information.")
19422 (defvar org-shiftmetadown-hook nil
19423 "Hook for functions attaching themselves to `M-S-down'.
19424 See `org-ctrl-c-ctrl-c-hook' for more information.")
19425 (defvar org-metareturn-hook nil
19426 "Hook for functions attaching themselves to `M-RET'.
19427 See `org-ctrl-c-ctrl-c-hook' for more information.")
19428 (defvar org-shiftup-hook nil
19429 "Hook for functions attaching themselves to `S-up'.
19430 See `org-ctrl-c-ctrl-c-hook' for more information.")
19431 (defvar org-shiftup-final-hook nil
19432 "Hook for functions attaching themselves to `S-up'.
19433 This one runs after all other options except shift-select have been excluded.
19434 See `org-ctrl-c-ctrl-c-hook' for more information.")
19435 (defvar org-shiftdown-hook nil
19436 "Hook for functions attaching themselves to `S-down'.
19437 See `org-ctrl-c-ctrl-c-hook' for more information.")
19438 (defvar org-shiftdown-final-hook nil
19439 "Hook for functions attaching themselves to `S-down'.
19440 This one runs after all other options except shift-select have been excluded.
19441 See `org-ctrl-c-ctrl-c-hook' for more information.")
19442 (defvar org-shiftleft-hook nil
19443 "Hook for functions attaching themselves to `S-left'.
19444 See `org-ctrl-c-ctrl-c-hook' for more information.")
19445 (defvar org-shiftleft-final-hook nil
19446 "Hook for functions attaching themselves to `S-left'.
19447 This one runs after all other options except shift-select have been excluded.
19448 See `org-ctrl-c-ctrl-c-hook' for more information.")
19449 (defvar org-shiftright-hook nil
19450 "Hook for functions attaching themselves to `S-right'.
19451 See `org-ctrl-c-ctrl-c-hook' for more information.")
19452 (defvar org-shiftright-final-hook nil
19453 "Hook for functions attaching themselves to `S-right'.
19454 This one runs after all other options except shift-select have been excluded.
19455 See `org-ctrl-c-ctrl-c-hook' for more information.")
19457 (defun org-modifier-cursor-error ()
19458 "Throw an error, a modified cursor command was applied in wrong context."
19459 (error "This command is active in special context like tables, headlines or items"))
19461 (defun org-shiftselect-error ()
19462 "Throw an error because Shift-Cursor command was applied in wrong context."
19463 (if (and (boundp 'shift-select-mode) shift-select-mode)
19464 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19465 (error "This command works only in special context like headlines or timestamps")))
19467 (defun org-call-for-shift-select (cmd)
19468 (let ((this-command-keys-shift-translated t))
19469 (call-interactively cmd)))
19471 (defun org-shifttab (&optional arg)
19472 "Global visibility cycling or move to previous table field.
19473 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19475 See the individual commands for more information."
19478 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19480 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19481 (message "Content view to level: %d" arg)
19482 (org-content (prefix-numeric-value arg2))
19483 (setq org-cycle-global-status 'overview)))
19484 (t (call-interactively 'org-global-cycle))))
19486 (defun org-shiftmetaleft ()
19487 "Promote subtree or delete table column.
19488 Calls `org-promote-subtree', `org-outdent-item-tree', or
19489 `org-table-delete-column', depending on context. See the
19490 individual commands for more information."
19493 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19494 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19495 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19496 ((if (not (org-region-active-p)) (org-at-item-p)
19497 (save-excursion (goto-char (region-beginning))
19499 (call-interactively 'org-outdent-item-tree))
19500 (t (org-modifier-cursor-error))))
19502 (defun org-shiftmetaright ()
19503 "Demote subtree or insert table column.
19504 Calls `org-demote-subtree', `org-indent-item-tree', or
19505 `org-table-insert-column', depending on context. See the
19506 individual commands for more information."
19509 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19510 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19511 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19512 ((if (not (org-region-active-p)) (org-at-item-p)
19513 (save-excursion (goto-char (region-beginning))
19515 (call-interactively 'org-indent-item-tree))
19516 (t (org-modifier-cursor-error))))
19518 (defun org-shiftmetaup (&optional arg)
19519 "Move subtree up or kill table row.
19520 Calls `org-move-subtree-up' or `org-table-kill-row' or
19521 `org-move-item-up' or `org-timestamp-up', depending on context.
19522 See the individual commands for more information."
19525 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19526 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19527 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19528 ((org-at-item-p) (call-interactively 'org-move-item-up))
19529 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19530 (call-interactively 'org-timestamp-up)))
19531 (t (call-interactively 'org-drag-line-backward))))
19533 (defun org-shiftmetadown (&optional arg)
19534 "Move subtree down or insert table row.
19535 Calls `org-move-subtree-down' or `org-table-insert-row' or
19536 `org-move-item-down' or `org-timestamp-up', depending on context.
19537 See the individual commands for more information."
19540 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19541 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19542 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19543 ((org-at-item-p) (call-interactively 'org-move-item-down))
19544 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19545 (call-interactively 'org-timestamp-down)))
19546 (t (call-interactively 'org-drag-line-forward))))
19548 (defsubst org-hidden-tree-error ()
19550 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19552 (defun org-metaleft (&optional arg)
19553 "Promote heading or move table column to left.
19554 Calls `org-do-promote' or `org-table-move-column', depending on context.
19555 With no specific context, calls the Emacs default `backward-word'.
19556 See the individual commands for more information."
19559 ((run-hook-with-args-until-success 'org-metaleft-hook))
19560 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19561 ((org-with-limited-levels
19562 (or (org-at-heading-p)
19563 (and (org-region-active-p)
19565 (goto-char (region-beginning))
19566 (org-at-heading-p)))))
19567 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19568 (call-interactively 'org-do-promote))
19569 ;; At an inline task.
19570 ((org-at-heading-p)
19571 (call-interactively 'org-inlinetask-promote))
19572 ((or (org-at-item-p)
19573 (and (org-region-active-p)
19575 (goto-char (region-beginning))
19577 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19578 (call-interactively 'org-outdent-item))
19579 (t (call-interactively 'backward-word))))
19581 (defun org-metaright (&optional arg)
19582 "Demote a subtree, a list item or move table column to right.
19583 In front of a drawer or a block keyword, indent it correctly.
19584 With no specific context, calls the Emacs default `forward-word'.
19585 See the individual commands for more information."
19588 ((run-hook-with-args-until-success 'org-metaright-hook))
19589 ((org-at-table-p) (call-interactively 'org-table-move-column))
19590 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19591 ((org-at-block-p) (call-interactively 'org-indent-block))
19592 ((org-with-limited-levels
19593 (or (org-at-heading-p)
19594 (and (org-region-active-p)
19596 (goto-char (region-beginning))
19597 (org-at-heading-p)))))
19598 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19599 (call-interactively 'org-do-demote))
19600 ;; At an inline task.
19601 ((org-at-heading-p)
19602 (call-interactively 'org-inlinetask-demote))
19603 ((or (org-at-item-p)
19604 (and (org-region-active-p)
19606 (goto-char (region-beginning))
19608 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19609 (call-interactively 'org-indent-item))
19610 (t (call-interactively 'forward-word))))
19612 (defun org-check-for-hidden (what)
19613 "Check if there are hidden headlines/items in the current visual line.
19614 WHAT can be either `headlines' or `items'. If the current line is
19615 an outline or item heading and it has a folded subtree below it,
19616 this function returns t, nil otherwise."
19618 ((eq what 'headlines) org-outline-regexp-bol)
19619 ((eq what 'items) (org-item-beginning-re))
19620 (t (error "This should not happen"))))
19624 (unless (org-region-active-p)
19625 (setq beg (point-at-bol))
19626 (beginning-of-line 2)
19627 (while (and (not (eobp)) ;; this is like `next-line'
19628 (get-char-property (1- (point)) 'invisible))
19629 (beginning-of-line 2))
19632 (goto-char (point-at-eol))
19633 (setq end (max end (point)))
19634 (while (re-search-forward re end t)
19635 (if (get-char-property (match-beginning 0) 'invisible)
19639 (defun org-metaup (&optional arg)
19640 "Move subtree up or move table row up.
19641 Calls `org-move-subtree-up' or `org-table-move-row' or
19642 `org-move-item-up', depending on context. See the individual commands
19643 for more information."
19646 ((run-hook-with-args-until-success 'org-metaup-hook))
19647 ((org-region-active-p)
19648 (let* ((a (min (region-beginning) (region-end)))
19649 (b (1- (max (region-beginning) (region-end))))
19650 (c (save-excursion (goto-char a)
19651 (move-beginning-of-line 0)))
19652 (d (save-excursion (goto-char a)
19653 (move-end-of-line 0) (point))))
19654 (transpose-regions a b c d)
19656 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19657 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19658 ((org-at-item-p) (call-interactively 'org-move-item-up))
19659 (t (org-drag-element-backward))))
19661 (defun org-metadown (&optional arg)
19662 "Move subtree down or move table row down.
19663 Calls `org-move-subtree-down' or `org-table-move-row' or
19664 `org-move-item-down', depending on context. See the individual
19665 commands for more information."
19668 ((run-hook-with-args-until-success 'org-metadown-hook))
19669 ((org-region-active-p)
19670 (let* ((a (min (region-beginning) (region-end)))
19671 (b (max (region-beginning) (region-end)))
19672 (c (save-excursion (goto-char b)
19673 (move-beginning-of-line 1)))
19674 (d (save-excursion (goto-char b)
19675 (move-end-of-line 1) (1+ (point)))))
19676 (transpose-regions a b c d)
19678 ((org-at-table-p) (call-interactively 'org-table-move-row))
19679 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19680 ((org-at-item-p) (call-interactively 'org-move-item-down))
19681 (t (org-drag-element-forward))))
19683 (defun org-shiftup (&optional arg)
19684 "Increase item in timestamp or increase priority of current headline.
19685 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19686 depending on context. See the individual commands for more information."
19689 ((run-hook-with-args-until-success 'org-shiftup-hook))
19690 ((and org-support-shift-select (org-region-active-p))
19691 (org-call-for-shift-select 'previous-line))
19692 ((org-at-timestamp-p t)
19693 (call-interactively (if org-edit-timestamp-down-means-later
19694 'org-timestamp-down 'org-timestamp-up)))
19695 ((and (not (eq org-support-shift-select 'always))
19696 org-enable-priority-commands
19697 (org-at-heading-p))
19698 (call-interactively 'org-priority-up))
19699 ((and (not org-support-shift-select) (org-at-item-p))
19700 (call-interactively 'org-previous-item))
19701 ((org-clocktable-try-shift 'up arg))
19702 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19703 (org-support-shift-select
19704 (org-call-for-shift-select 'previous-line))
19705 (t (org-shiftselect-error))))
19707 (defun org-shiftdown (&optional arg)
19708 "Decrease item in timestamp or decrease priority of current headline.
19709 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19710 depending on context. See the individual commands for more information."
19713 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19714 ((and org-support-shift-select (org-region-active-p))
19715 (org-call-for-shift-select 'next-line))
19716 ((org-at-timestamp-p t)
19717 (call-interactively (if org-edit-timestamp-down-means-later
19718 'org-timestamp-up 'org-timestamp-down)))
19719 ((and (not (eq org-support-shift-select 'always))
19720 org-enable-priority-commands
19721 (org-at-heading-p))
19722 (call-interactively 'org-priority-down))
19723 ((and (not org-support-shift-select) (org-at-item-p))
19724 (call-interactively 'org-next-item))
19725 ((org-clocktable-try-shift 'down arg))
19726 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19727 (org-support-shift-select
19728 (org-call-for-shift-select 'next-line))
19729 (t (org-shiftselect-error))))
19731 (defun org-shiftright (&optional arg)
19732 "Cycle the thing at point or in the current line, depending on context.
19733 Depending on context, this does one of the following:
19735 - switch a timestamp at point one day into the future
19736 - on a headline, switch to the next TODO keyword.
19737 - on an item, switch entire list to the next bullet type
19738 - on a property line, switch to the next allowed value
19739 - on a clocktable definition line, move time block into the future"
19742 ((run-hook-with-args-until-success 'org-shiftright-hook))
19743 ((and org-support-shift-select (org-region-active-p))
19744 (org-call-for-shift-select 'forward-char))
19745 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19746 ((and (not (eq org-support-shift-select 'always))
19747 (org-at-heading-p))
19748 (let ((org-inhibit-logging
19749 (not org-treat-S-cursor-todo-selection-as-state-change))
19750 (org-inhibit-blocking
19751 (not org-treat-S-cursor-todo-selection-as-state-change)))
19752 (org-call-with-arg 'org-todo 'right)))
19753 ((or (and org-support-shift-select
19754 (not (eq org-support-shift-select 'always))
19755 (org-at-item-bullet-p))
19756 (and (not org-support-shift-select) (org-at-item-p)))
19757 (org-call-with-arg 'org-cycle-list-bullet nil))
19758 ((and (not (eq org-support-shift-select 'always))
19759 (org-at-property-p))
19760 (call-interactively 'org-property-next-allowed-value))
19761 ((org-clocktable-try-shift 'right arg))
19762 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19763 (org-support-shift-select
19764 (org-call-for-shift-select 'forward-char))
19765 (t (org-shiftselect-error))))
19767 (defun org-shiftleft (&optional arg)
19768 "Cycle the thing at point or in the current line, depending on context.
19769 Depending on context, this does one of the following:
19771 - switch a timestamp at point one day into the past
19772 - on a headline, switch to the previous TODO keyword.
19773 - on an item, switch entire list to the previous bullet type
19774 - on a property line, switch to the previous allowed value
19775 - on a clocktable definition line, move time block into the past"
19778 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19779 ((and org-support-shift-select (org-region-active-p))
19780 (org-call-for-shift-select 'backward-char))
19781 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19782 ((and (not (eq org-support-shift-select 'always))
19783 (org-at-heading-p))
19784 (let ((org-inhibit-logging
19785 (not org-treat-S-cursor-todo-selection-as-state-change))
19786 (org-inhibit-blocking
19787 (not org-treat-S-cursor-todo-selection-as-state-change)))
19788 (org-call-with-arg 'org-todo 'left)))
19789 ((or (and org-support-shift-select
19790 (not (eq org-support-shift-select 'always))
19791 (org-at-item-bullet-p))
19792 (and (not org-support-shift-select) (org-at-item-p)))
19793 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19794 ((and (not (eq org-support-shift-select 'always))
19795 (org-at-property-p))
19796 (call-interactively 'org-property-previous-allowed-value))
19797 ((org-clocktable-try-shift 'left arg))
19798 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19799 (org-support-shift-select
19800 (org-call-for-shift-select 'backward-char))
19801 (t (org-shiftselect-error))))
19803 (defun org-shiftcontrolright ()
19804 "Switch to next TODO set."
19807 ((and org-support-shift-select (org-region-active-p))
19808 (org-call-for-shift-select 'forward-word))
19809 ((and (not (eq org-support-shift-select 'always))
19810 (org-at-heading-p))
19811 (org-call-with-arg 'org-todo 'nextset))
19812 (org-support-shift-select
19813 (org-call-for-shift-select 'forward-word))
19814 (t (org-shiftselect-error))))
19816 (defun org-shiftcontrolleft ()
19817 "Switch to previous TODO set."
19820 ((and org-support-shift-select (org-region-active-p))
19821 (org-call-for-shift-select 'backward-word))
19822 ((and (not (eq org-support-shift-select 'always))
19823 (org-at-heading-p))
19824 (org-call-with-arg 'org-todo 'previousset))
19825 (org-support-shift-select
19826 (org-call-for-shift-select 'backward-word))
19827 (t (org-shiftselect-error))))
19829 (defun org-shiftcontrolup (&optional n)
19830 "Change timestamps synchronously up in CLOCK log lines.
19831 Optional argument N tells to change by that many units."
19833 (cond ((and (not org-support-shift-select)
19834 (org-at-clock-log-p)
19835 (org-at-timestamp-p t))
19836 (org-clock-timestamps-up n))
19837 (t (org-shiftselect-error))))
19839 (defun org-shiftcontroldown (&optional n)
19840 "Change timestamps synchronously down in CLOCK log lines.
19841 Optional argument N tells to change by that many units."
19843 (cond ((and (not org-support-shift-select)
19844 (org-at-clock-log-p)
19845 (org-at-timestamp-p t))
19846 (org-clock-timestamps-down n))
19847 (t (org-shiftselect-error))))
19849 (defun org-ctrl-c-ret ()
19850 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19853 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19854 (t (call-interactively 'org-insert-heading))))
19856 (defun org-find-visible ()
19858 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19859 (get-char-property s 'invisible)))
19861 (defun org-find-invisible ()
19863 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19864 (not (get-char-property s 'invisible))))
19867 (defun org-copy-visible (beg end)
19868 "Copy the visible parts of the region."
19873 (narrow-to-region beg end)
19874 (setq s (goto-char (point-min)))
19875 (while (not (= (point) (point-max)))
19876 (goto-char (org-find-invisible))
19877 (push (buffer-substring s (point)) snippets)
19878 (setq s (goto-char (org-find-visible))))))
19879 (kill-new (apply 'concat (nreverse snippets)))))
19881 (defun org-copy-special ()
19882 "Copy region in table or copy current subtree.
19883 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19884 See the individual commands for more information."
19886 (call-interactively
19887 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19889 (defun org-cut-special ()
19890 "Cut region in table or cut current subtree.
19891 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19892 See the individual commands for more information."
19894 (call-interactively
19895 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19897 (defun org-paste-special (arg)
19898 "Paste rectangular region into table, or past subtree relative to level.
19899 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19900 See the individual commands for more information."
19902 (if (org-at-table-p)
19903 (org-table-paste-rectangle)
19904 (org-paste-subtree arg)))
19906 (defsubst org-in-fixed-width-region-p ()
19907 "Is point in a fixed-width region?"
19909 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19911 (defun org-edit-special (&optional arg)
19912 "Call a special editor for the element at point.
19913 When at a table, call the formula editor with `org-table-edit-formulas'.
19914 When in a source code block, call `org-edit-src-code'.
19915 When in a fixed-width region, call `org-edit-fixed-width-region'.
19916 When at an #+INCLUDE keyword, visit the included file.
19917 On a link, call `ffap' to visit the link at point.
19918 Otherwise, return a user error."
19920 (let ((element (org-element-at-point)))
19921 (assert (not buffer-read-only) nil
19922 "Buffer is read-only: %s" (buffer-name))
19923 (case (org-element-type element)
19925 (if (not arg) (org-edit-src-code)
19926 (let* ((info (org-babel-get-src-block-info))
19927 (lang (nth 0 info))
19928 (params (nth 2 info))
19929 (session (cdr (assq :session params))))
19930 (if (not session) (org-edit-src-code)
19931 ;; At a src-block with a session and function called with
19932 ;; an ARG: switch to the buffer related to the inferior
19934 (funcall (intern (concat "org-babel-prep-session:" lang))
19935 session params)))))
19937 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19939 (org-remove-double-quotes
19940 (car (org-split-string (org-element-property :value element)))))
19941 (user-error "No special environment to edit here")))
19943 (if (eq (org-element-property :type element) 'table.el)
19944 (org-edit-src-code)
19945 (call-interactively 'org-table-edit-formulas)))
19946 ;; Only Org tables contain `table-row' type elements.
19947 (table-row (call-interactively 'org-table-edit-formulas))
19948 ((example-block export-block) (org-edit-src-code))
19949 (fixed-width (org-edit-fixed-width-region))
19951 ;; No notable element at point. Though, we may be at a link,
19952 ;; which is an object. Thus, scan deeper.
19953 (if (eq (org-element-type (org-element-context element)) 'link)
19954 (call-interactively 'ffap)
19955 (user-error "No special environment to edit here"))))))
19957 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19958 (defun org-ctrl-c-ctrl-c (&optional arg)
19959 "Set tags in headline, or update according to changed information at point.
19961 This command does many different things, depending on context:
19963 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19964 this is what we do.
19966 - If the cursor is on a statistics cookie, update it.
19968 - If the cursor is in a headline, prompt for tags and insert them
19969 into the current line, aligned to `org-tags-column'. When called
19970 with prefix arg, realign all tags in the current buffer.
19972 - If the cursor is in one of the special #+KEYWORD lines, this
19973 triggers scanning the buffer for these lines and updating the
19976 - If the cursor is inside a table, realign the table. This command
19977 works even if the automatic table editor has been turned off.
19979 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19982 - If the cursor is at a footnote reference or definition, jump to
19983 the corresponding definition or references, respectively.
19985 - If the cursor is a the beginning of a dynamic block, update it.
19987 - If the current buffer is a capture buffer, close note and file it.
19989 - If the cursor is on a <<<target>>>, update radio targets and
19990 corresponding links in this buffer.
19992 - If the cursor is on a numbered item in a plain list, renumber the
19995 - If the cursor is on a checkbox, toggle it.
19997 - If the cursor is on a code block, evaluate it. The variable
19998 `org-confirm-babel-evaluate' can be used to control prompting
19999 before code block evaluation, by default every code block
20000 evaluation requires confirmation. Code block evaluation can be
20001 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20004 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20005 org-occur-highlights
20006 org-latex-fragment-image-overlays)
20007 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20008 (org-remove-occur-highlights)
20009 (org-remove-latex-fragment-image-overlays)
20010 (message "Temporary highlights/overlays removed from current buffer"))
20011 ((and (local-variable-p 'org-finish-function (current-buffer))
20012 (fboundp org-finish-function))
20013 (funcall org-finish-function))
20014 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20016 (let* ((context (org-element-context)) (type (org-element-type context)))
20017 ;; Test if point is within a blank line.
20018 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20019 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20020 (user-error "C-c C-c can do nothing useful at this location"))
20021 ;; For convenience: at the first line of a paragraph on the
20022 ;; same line as an item, apply function on that item instead.
20023 (when (eq type 'paragraph)
20024 (let ((parent (org-element-property :parent context)))
20025 (when (and (eq (org-element-type parent) 'item)
20026 (= (point-at-bol) (org-element-property :begin parent)))
20027 (setq context parent type 'item))))
20028 ;; Act according to type of element or object at point.
20030 (clock (org-clock-update-time-maybe))
20033 (goto-char (org-element-property :post-affiliated context))
20034 (org-update-dblock)))
20035 (footnote-definition
20036 (goto-char (org-element-property :post-affiliated context))
20037 (call-interactively 'org-footnote-action))
20038 (footnote-reference (call-interactively 'org-footnote-action))
20039 ((headline inlinetask)
20040 (save-excursion (goto-char (org-element-property :begin context))
20041 (call-interactively 'org-set-tags)))
20043 ;; At an item: a double C-u set checkbox to "[-]"
20044 ;; unconditionally, whereas a single one will toggle its
20045 ;; presence. Without an universal argument, if the item
20046 ;; has a checkbox, toggle it. Otherwise repair the list.
20047 (let* ((box (org-element-property :checkbox context))
20048 (struct (org-element-property :structure context))
20049 (old-struct (copy-tree struct))
20050 (parents (org-list-parents-alist struct))
20051 (prevs (org-list-prevs-alist struct))
20052 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20053 (org-list-set-checkbox
20054 (org-element-property :begin context) struct
20055 (cond ((equal arg '(16)) "[-]")
20056 ((and (not box) (equal arg '(4))) "[ ]")
20057 ((or (not box) (equal arg '(4))) nil)
20058 ((eq box 'on) "[ ]")
20060 ;; Mimic `org-list-write-struct' but with grabbing
20061 ;; a return value from `org-list-struct-fix-box'.
20062 (org-list-struct-fix-ind struct parents 2)
20063 (org-list-struct-fix-item-end struct)
20064 (org-list-struct-fix-bul struct prevs)
20065 (org-list-struct-fix-ind struct parents)
20067 (org-list-struct-fix-box struct parents prevs orderedp)))
20068 (if (and box (equal struct old-struct))
20069 (if (equal arg '(16))
20070 (message "Checkboxes already reset")
20071 (user-error "Cannot toggle this checkbox: %s"
20073 "all subitems checked"
20074 "unchecked subitems")))
20075 (org-list-struct-apply-struct struct old-struct)
20076 (org-update-checkbox-count-maybe))
20078 (message "Checkboxes were removed due to empty box at line %d"
20079 (org-current-line block-item))))))
20081 (let ((org-inhibit-startup-visibility-stuff t)
20082 (org-startup-align-all-tables nil))
20083 (when (boundp 'org-table-coordinate-overlays)
20084 (mapc 'delete-overlay org-table-coordinate-overlays)
20085 (setq org-table-coordinate-overlays nil))
20086 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20087 (message "Local setup has been refreshed"))
20089 ;; At a plain list, with a double C-u argument, set
20090 ;; checkboxes of each item to "[-]", whereas a single one
20091 ;; will toggle their presence according to the state of the
20092 ;; first item in the list. Without an argument, repair the
20094 (let* ((begin (org-element-property :contents-begin context))
20095 (struct (org-element-property :structure context))
20096 (old-struct (copy-tree struct))
20097 (first-box (save-excursion
20099 (looking-at org-list-full-item-re)
20100 (match-string-no-properties 3)))
20101 (new-box (cond ((equal arg '(16)) "[-]")
20102 ((equal arg '(4)) (unless first-box "[ ]"))
20103 ((equal first-box "[X]") "[ ]")
20107 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20108 (org-list-get-all-items
20109 begin struct (org-list-prevs-alist struct))))
20110 ((and first-box (eq (point) begin))
20111 ;; For convenience, when point is at bol on the first
20112 ;; item of the list and no argument is provided, simply
20113 ;; toggle checkbox of that item, if any.
20114 (org-list-set-checkbox begin struct new-box)))
20115 (org-list-write-struct
20116 struct (org-list-parents-alist struct) old-struct)
20117 (org-update-checkbox-count-maybe)
20118 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
20119 ((property-drawer node-property)
20120 (call-interactively 'org-property-action))
20121 ((radio-target target)
20122 (call-interactively 'org-update-radio-target-regexp))
20124 (call-interactively 'org-update-statistics-cookies))
20125 ((table table-cell table-row)
20126 ;; At a table, recalculate every field and align it. Also
20127 ;; send the table if necessary. If the table has
20128 ;; a `table.el' type, just give up. At a table row or
20129 ;; cell, maybe recalculate line but always align table.
20130 (if (eq (org-element-property :type context) 'table.el)
20131 (message "Use C-c ' to edit table.el tables")
20132 (let ((org-enable-table-editor t))
20133 (if (or (eq type 'table)
20134 ;; Check if point is at a TBLFM line.
20135 (and (eq type 'table-row)
20136 (= (point) (org-element-property :end context))))
20138 (goto-char (org-element-property :contents-begin context))
20139 (org-call-with-arg 'org-table-recalculate (or arg t))
20140 (orgtbl-send-table 'maybe))
20141 (org-table-maybe-eval-formula)
20142 (cond (arg (call-interactively 'org-table-recalculate))
20143 ((org-table-maybe-recalculate-line))
20144 (t (org-table-align)))))))
20145 (timestamp (org-timestamp-change 0 'day))
20147 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20149 "C-c C-c can do nothing useful at this location")))))))))
20151 (defun org-mode-restart ()
20152 "Restart Org-mode, to scan again for special lines.
20153 Also updates the keyword regular expressions."
20156 (message "Org-mode restarted"))
20158 (defun org-kill-note-or-show-branches ()
20159 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20161 (if (not org-finish-function)
20164 (call-interactively 'show-branches))
20165 (let ((org-note-abort t))
20166 (funcall org-finish-function))))
20168 (defun org-return (&optional indent)
20169 "Goto next table row or insert a newline.
20170 Calls `org-table-next-row' or `newline', depending on context.
20171 See the individual commands for more information."
20175 ((or (bobp) (org-in-src-block-p))
20176 (if indent (newline-and-indent) (newline)))
20178 (org-table-justify-field-maybe)
20179 (call-interactively 'org-table-next-row))
20180 ;; when `newline-and-indent' is called within a list, make sure
20181 ;; text moved stays inside the item.
20182 ((and (org-in-item-p) indent)
20183 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20185 (save-match-data (newline))
20186 (org-indent-line-to (length (match-string 0))))
20187 (let ((ind (org-get-indentation)))
20189 (if (org-looking-back org-list-end-re)
20191 (org-indent-line-to ind)))))
20192 ((and org-return-follows-link
20193 (org-at-timestamp-p t)
20194 (not (eq org-ts-what 'after)))
20195 (org-follow-timestamp-link))
20196 ((and org-return-follows-link
20197 (let ((tprop (get-text-property (point) 'face)))
20198 (or (eq tprop 'org-link)
20199 (and (listp tprop) (memq 'org-link tprop)))))
20200 (call-interactively 'org-open-at-point))
20201 ((and (org-at-heading-p)
20203 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20207 (t (if indent (newline-and-indent) (newline))))))
20209 (defun org-return-indent ()
20210 "Goto next table row or insert a newline and indent.
20211 Calls `org-table-next-row' or `newline-and-indent', depending on
20212 context. See the individual commands for more information."
20216 (defun org-ctrl-c-star ()
20217 "Compute table, or change heading status of lines.
20218 Calls `org-table-recalculate' or `org-toggle-heading',
20219 depending on context."
20223 (call-interactively 'org-table-recalculate))
20225 ;; Convert all lines in region to list items
20226 (call-interactively 'org-toggle-heading))))
20228 (defun org-ctrl-c-minus ()
20229 "Insert separator line in table or modify bullet status of line.
20230 Also turns a plain line or a region of lines into list items.
20231 Calls `org-table-insert-hline', `org-toggle-item', or
20232 `org-cycle-list-bullet', depending on context."
20236 (call-interactively 'org-table-insert-hline))
20237 ((org-region-active-p)
20238 (call-interactively 'org-toggle-item))
20240 (call-interactively 'org-cycle-list-bullet))
20242 (call-interactively 'org-toggle-item))))
20244 (defun org-toggle-item (arg)
20245 "Convert headings or normal lines to items, items to normal lines.
20246 If there is no active region, only the current line is considered.
20248 If the first non blank line in the region is a headline, convert
20249 all headlines to items, shifting text accordingly.
20251 If it is an item, convert all items to normal lines.
20253 If it is normal text, change region into a list of items.
20254 With a prefix argument ARG, change the region in a single item."
20258 ;; Shift text in current section to IND, from point to END.
20259 ;; The function leaves point to END line.
20261 (let ((min-i 1000) (end (copy-marker end)))
20262 ;; First determine the minimum indentation (MIN-I) of
20266 (while (< (point) end)
20267 (let ((i (org-get-indentation)))
20269 ;; Skip blank lines and inline tasks.
20270 ((looking-at "^[ \t]*$"))
20271 ((looking-at org-outline-regexp-bol))
20272 ;; We can't find less than 0 indentation.
20273 ((zerop i) (throw 'exit (setq min-i 0)))
20274 ((< i min-i) (setq min-i i))))
20276 ;; Then indent each line so that a line indented to
20277 ;; MIN-I becomes indented to IND. Ignore blank lines
20278 ;; and inline tasks in the process.
20279 (let ((delta (- ind min-i)))
20280 (while (< (point) end)
20281 (unless (or (looking-at "^[ \t]*$")
20282 (looking-at org-outline-regexp-bol))
20283 (org-indent-line-to (+ (org-get-indentation) delta)))
20284 (forward-line)))))))
20287 ;; Return beginning of first non-blank line, starting from
20292 (skip-chars-forward " \r\t\n")
20295 ;; Determine boundaries of changes.
20296 (if (org-region-active-p)
20297 (setq beg (funcall skip-blanks (region-beginning))
20298 end (copy-marker (region-end)))
20299 (setq beg (funcall skip-blanks (point-at-bol))
20300 end (copy-marker (point-at-eol))))
20301 ;; Depending on the starting line, choose an action on the text
20302 ;; between BEG and END.
20303 (org-with-limited-levels
20307 ;; Case 1. Start at an item: de-itemize. Note that it only
20308 ;; happens when a region is active: `org-ctrl-c-minus'
20309 ;; would call `org-cycle-list-bullet' otherwise.
20311 (while (< (point) end)
20312 (when (org-at-item-p)
20313 (skip-chars-forward " \t")
20314 (delete-region (point) (match-end 0)))
20316 ;; Case 2. Start at an heading: convert to items.
20317 ((org-at-heading-p)
20318 (let* ((bul (org-list-bullet-string "-"))
20319 (bul-len (length bul))
20320 ;; Indentation of the first heading. It should be
20321 ;; relative to the indentation of its parent, if any.
20322 (start-ind (save-excursion
20324 ((not org-adapt-indentation) 0)
20325 ((not (outline-previous-heading)) 0)
20326 (t (length (match-string 0))))))
20327 ;; Level of first heading. Further headings will be
20328 ;; compared to it to determine hierarchy in the list.
20329 (ref-level (org-reduced-level (org-outline-level))))
20330 (while (< (point) end)
20331 (let* ((level (org-reduced-level (org-outline-level)))
20332 (delta (max 0 (- level ref-level))))
20333 ;; If current headline is less indented than the first
20334 ;; one, set it as reference, in order to preserve
20336 (when (< level ref-level) (setq ref-level level))
20337 (replace-match bul t t)
20338 (org-indent-line-to (+ start-ind (* delta bul-len)))
20339 ;; Ensure all text down to END (or SECTION-END) belongs
20340 ;; to the newly created item.
20341 (let ((section-end (save-excursion
20342 (or (outline-next-heading) (point)))))
20344 (funcall shift-text
20345 (+ start-ind (* (1+ delta) bul-len))
20346 (min end section-end)))))))
20347 ;; Case 3. Normal line with ARG: make the first line of region
20348 ;; an item, and shift indentation of others lines to
20349 ;; set them as item's body.
20350 (arg (let* ((bul (org-list-bullet-string "-"))
20351 (bul-len (length bul))
20352 (ref-ind (org-get-indentation)))
20353 (skip-chars-forward " \t")
20356 (while (< (point) end)
20357 ;; Ensure that lines less indented than first one
20358 ;; still get included in item body.
20359 (funcall shift-text
20360 (+ ref-ind bul-len)
20361 (min end (save-excursion (or (outline-next-heading)
20364 ;; Case 4. Normal line without ARG: turn each non-item line
20367 (while (< (point) end)
20368 (unless (or (org-at-heading-p) (org-at-item-p))
20369 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20371 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20372 (forward-line))))))))
20374 (defun org-toggle-heading (&optional nstars)
20375 "Convert headings to normal text, or items or text to headings.
20376 If there is no active region, only convert the current line.
20378 With a \\[universal-argument] prefix, convert the whole list at
20379 point into heading.
20383 - If the first non blank line is a headline, remove the stars
20384 from all headlines in the region.
20386 - If it is a normal line, turn each and every normal line (i.e.,
20387 not an heading or an item) in the region into headings. If you
20388 want to convert only the first line of this region, use one
20389 universal prefix argument.
20391 - If it is a plain list item, turn all plain list items into headings.
20393 When converting a line into a heading, the number of stars is chosen
20394 such that the lines become children of the current entry. However,
20395 when a numeric prefix argument is given, its value determines the
20396 number of stars to add."
20400 ;; Return beginning of first non-blank line, starting from
20405 (while (org-at-comment-p) (forward-line))
20406 (skip-chars-forward " \r\t\n")
20409 ;; Determine boundaries of changes. If a universal prefix has
20410 ;; been given, put the list in a region. If region ends at a bol,
20411 ;; do not consider the last line to be in the region.
20413 (when (and current-prefix-arg (org-at-item-p))
20414 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20415 (org-mark-element))
20417 (if (org-region-active-p)
20418 (setq beg (funcall skip-blanks (region-beginning))
20419 end (copy-marker (save-excursion
20420 (goto-char (region-end))
20421 (if (bolp) (point) (point-at-eol)))))
20422 (setq beg (funcall skip-blanks (point-at-bol))
20423 end (copy-marker (point-at-eol))))
20424 ;; Ensure inline tasks don't count as headings.
20425 (org-with-limited-levels
20429 ;; Case 1. Started at an heading: de-star headings.
20430 ((org-at-heading-p)
20431 (while (< (point) end)
20432 (when (org-at-heading-p t)
20433 (looking-at org-outline-regexp) (replace-match "")
20436 ;; Case 2. Started at an item: change items into headlines.
20437 ;; One star will be added by `org-list-to-subtree'.
20439 (let* ((stars (make-string
20440 ;; subtract the star that will be added again by
20441 ;; `org-list-to-subtree'
20442 (if (numberp nstars) (1- nstars)
20443 (or (org-current-level) 0))
20446 (cond (nstars "") ; stars from prefix only
20447 ((equal stars "") "") ; before first heading
20448 (org-odd-levels-only "*") ; inside heading, odd
20449 (t "")))) ; inside heading, oddeven
20450 (while (< (point) end)
20451 (when (org-at-item-p)
20452 ;; Pay attention to cases when region ends before list.
20453 (let* ((struct (org-list-struct))
20454 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20456 (narrow-to-region (point) list-end)
20458 (org-list-to-subtree
20459 (org-list-parse-list t)
20460 '(:istart (concat stars add-stars (funcall get-stars depth))
20461 :icount (concat stars add-stars (funcall get-stars depth)))))))
20464 ;; Case 3. Started at normal text: make every line an heading,
20465 ;; skipping headlines and items.
20468 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20470 (cond (nstars "") ; stars from prefix only
20471 ((equal stars "") "*") ; before first heading
20472 (org-odd-levels-only "**") ; inside heading, odd
20473 (t "*"))) ; inside heading, oddeven
20474 (rpl (concat stars add-stars " "))
20475 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20476 (while (< (point) (if (equal nstars '(4)) lend end))
20477 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20478 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20479 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20480 (forward-line)))))))
20481 (unless toggled (message "Cannot toggle heading from here"))))
20483 (defun org-meta-return (&optional arg)
20484 "Insert a new heading or wrap a region in a table.
20485 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20486 See the individual commands for more information."
20489 ((run-hook-with-args-until-success 'org-metareturn-hook))
20490 ((or (org-at-drawer-p) (org-at-property-p))
20491 (newline-and-indent))
20493 (call-interactively 'org-table-wrap-region))
20494 (t (call-interactively 'org-insert-heading))))
20498 (defsubst org-in-subtree-not-table-p ()
20499 "Are we in a subtree and not in a table?"
20500 (and (not (org-before-first-heading-p))
20501 (not (org-at-table-p))))
20503 ;; Define the Org-mode menus
20504 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20506 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20507 ["Next Field" org-cycle (org-at-table-p)]
20508 ["Previous Field" org-shifttab (org-at-table-p)]
20509 ["Next Row" org-return (org-at-table-p)]
20511 ["Blank Field" org-table-blank-field (org-at-table-p)]
20512 ["Edit Field" org-table-edit-field (org-at-table-p)]
20513 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20516 ["Move Column Left" org-metaleft (org-at-table-p)]
20517 ["Move Column Right" org-metaright (org-at-table-p)]
20518 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20519 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20521 ["Move Row Up" org-metaup (org-at-table-p)]
20522 ["Move Row Down" org-metadown (org-at-table-p)]
20523 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20524 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20525 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20527 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20529 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20530 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20531 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20532 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20535 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20536 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20537 ["Edit Formulas" org-edit-special (org-at-table-p)]
20539 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20540 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20541 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20543 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20545 ["Sum Column/Rectangle" org-table-sum
20546 (or (org-at-table-p) (org-region-active-p))]
20547 ["Which Column?" org-table-current-column (org-at-table-p)])
20549 org-table-toggle-formula-debugger
20550 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20551 ["Show Col/Row Numbers"
20552 org-table-toggle-coordinate-overlays
20554 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20556 ["Create" org-table-create (and (not (org-at-table-p))
20557 org-enable-table-editor)]
20558 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20559 ["Import from File" org-table-import (not (org-at-table-p))]
20560 ["Export to File" org-table-export (org-at-table-p)]
20562 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20564 (easy-menu-define org-org-menu org-mode-map "Org menu"
20567 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20568 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20569 ["Sparse Tree..." org-sparse-tree t]
20570 ["Reveal Context" org-reveal t]
20571 ["Show All" show-all t]
20573 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20575 ["New Heading" org-insert-heading t]
20576 ("Navigate Headings"
20577 ["Up" outline-up-heading t]
20578 ["Next" outline-next-visible-heading t]
20579 ["Previous" outline-previous-visible-heading t]
20580 ["Next Same Level" outline-forward-same-level t]
20581 ["Previous Same Level" outline-backward-same-level t]
20583 ["Jump" org-goto t])
20585 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20587 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20588 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20590 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20591 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20592 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20594 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20596 ["Copy visible text" org-copy-visible t]
20598 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20599 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20600 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20601 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20603 ["Sort Region/Children" org-sort t]
20605 ["Convert to odd levels" org-convert-to-odd-levels t]
20606 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20608 ["Emphasis..." org-emphasize t]
20609 ["Edit Source Example" org-edit-special t]
20611 ["Footnote new/jump" org-footnote-action t]
20612 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20614 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20616 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20617 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20618 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20622 ["Store Link (Global)" org-store-link t]
20623 ["Find existing link to here" org-occur-link-in-agenda-files t]
20624 ["Insert Link" org-insert-link t]
20625 ["Follow Link" org-open-at-point t]
20627 ["Next link" org-next-link t]
20628 ["Previous link" org-previous-link t]
20630 ["Descriptive Links"
20631 org-toggle-link-display
20633 :selected org-descriptive-links
20636 org-toggle-link-display
20638 :selected (not org-descriptive-links)])
20641 ["TODO/DONE/-" org-todo t]
20643 ["Next keyword" org-shiftright (org-at-heading-p)]
20644 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20645 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20646 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20647 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20648 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20649 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20651 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20652 :selected org-enforce-todo-dependencies :style toggle :active t]
20653 "Settings for tree at point"
20654 ["Do Children sequentially" org-toggle-ordered-property :style radio
20655 :selected (org-entry-get nil "ORDERED")
20656 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20657 ["Do Children parallel" org-toggle-ordered-property :style radio
20658 :selected (not (org-entry-get nil "ORDERED"))
20659 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20661 ["Set Priority" org-priority t]
20662 ["Priority Up" org-shiftup t]
20663 ["Priority Down" org-shiftdown t]
20665 ["Get news from all feeds" org-feed-update-all t]
20666 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20667 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20668 ("TAGS and Properties"
20669 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20670 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20672 ["Set property" org-set-property (not (org-before-first-heading-p))]
20673 ["Column view of properties" org-columns t]
20674 ["Insert Column View DBlock" org-insert-columns-dblock t])
20675 ("Dates and Scheduling"
20676 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20677 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20679 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20680 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20681 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20682 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20683 ["Compute Time Range" org-evaluate-time-range t]
20684 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20685 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20687 ["Custom time format" org-toggle-time-stamp-overlays
20688 :style radio :selected org-display-custom-times]
20690 ["Goto Calendar" org-goto-calendar t]
20691 ["Date from Calendar" org-date-from-calendar t]
20693 ["Start/Restart Timer" org-timer-start t]
20694 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20695 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20696 ["Insert Timer String" org-timer t]
20697 ["Insert Timer Item" org-timer-item t])
20699 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20700 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20701 ["Clock out" org-clock-out t]
20702 ["Clock cancel" org-clock-cancel t]
20704 ["Mark as default task" org-clock-mark-default-task t]
20705 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20706 ["Goto running clock" org-clock-goto t]
20708 ["Display times" org-clock-display t]
20709 ["Create clock table" org-clock-report t]
20711 ["Record DONE time"
20712 (progn (setq org-log-done (not org-log-done))
20713 (message "Switching to %s will %s record a timestamp"
20714 (car org-done-keywords)
20715 (if org-log-done "automatically" "not")))
20716 :style toggle :selected org-log-done])
20718 ["Agenda Command..." org-agenda t]
20719 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20720 ("File List for Agenda")
20721 ("Special views current file"
20722 ["TODO Tree" org-show-todo-tree t]
20723 ["Check Deadlines" org-check-deadlines t]
20724 ["Timeline" org-timeline t]
20725 ["Tags/Property tree" org-match-sparse-tree t])
20727 ["Export/Publish..." org-export-dispatch t]
20729 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20730 :selected org-cdlatex-mode]
20731 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20732 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20733 ["Modify math symbol" org-cdlatex-math-modify
20734 (org-inside-LaTeX-fragment-p)]
20735 ["Insert citation" org-reftex-citation t]
20737 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20740 ["Push Files and Views" org-mobile-push t]
20741 ["Get Captured and Flagged" org-mobile-pull t]
20742 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20744 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20747 ["Show Version" org-version t]
20748 ["Info Documentation" org-info t])
20750 ["Browse Org Group" org-customize t]
20752 ["Expand This Menu" org-create-customize-menu
20753 (fboundp 'customize-menu-create)])
20754 ["Send bug report" org-submit-bug-report t]
20757 ["Refresh setup current buffer" org-mode-restart t]
20758 ["Reload Org (after update)" org-reload t]
20759 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20762 (defun org-info (&optional node)
20763 "Read documentation for Org-mode in the info system.
20764 With optional NODE, go directly to that node."
20766 (info (format "(org)%s" (or node ""))))
20769 (defun org-submit-bug-report ()
20770 "Submit a bug report on Org-mode via mail.
20772 Don't hesitate to report any problems or inaccurate documentation.
20774 If you don't have setup sending mail from (X)Emacs, please copy the
20775 output buffer into your mail program, as it gives us important
20776 information about your Org-mode version and configuration."
20778 (require 'reporter)
20779 (org-load-modules-maybe)
20780 (org-require-autoloaded-modules)
20781 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20782 (reporter-submit-bug-report
20783 "emacs-orgmode@gnu.org"
20784 (org-version nil 'full)
20786 (save-window-excursion
20787 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20788 (delete-other-windows)
20790 (insert "You are about to submit a bug report to the Org-mode mailing list.
20792 We would like to add your full Org-mode and Outline configuration to the
20793 bug report. This greatly simplifies the work of the maintainer and
20794 other experts on the mailing list.
20796 HOWEVER, some variables you have customized may contain private
20797 information. The names of customers, colleagues, or friends, might
20798 appear in the form of file names, tags, todo states, or search strings.
20799 If you answer yes to the prompt, you might want to check and remove
20800 such private information before sending the email.")
20801 (add-text-properties (point-min) (point-max) '(face org-warning))
20802 (when (yes-or-no-p "Include your Org-mode configuration ")
20806 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20807 (or (and (symbol-value v)
20808 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20810 (get v 'custom-type) (get v 'standard-value)
20811 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20813 (kill-buffer (get-buffer "*Warn about privacy*"))
20816 "Remember to cover the basics, that is, what you expected to happen and
20817 what in fact did happen. You don't know how to make a good report? See
20819 http://orgmode.org/manual/Feedback.html#Feedback
20821 Your bug report will be posted to the Org-mode mailing list.
20822 ------------------------------------------------------------------------")
20824 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20825 (replace-match "\\1Bug: \\3 [\\2]")))))
20828 (defun org-install-agenda-files-menu ()
20829 (let ((bl (buffer-list)))
20832 (set-buffer (pop bl))
20833 (if (derived-mode-p 'org-mode) (setq bl nil)))
20834 (when (derived-mode-p 'org-mode)
20836 '("Org") "File List for Agenda"
20839 ["Edit File List" (org-edit-agenda-file-list) t]
20840 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20841 ["Remove Current File from List" org-remove-file t]
20842 ["Cycle through agenda files" org-cycle-agenda-files t]
20843 ["Occur in all agenda files" org-occur-in-agenda-files t]
20845 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20849 (defun org-require-autoloaded-modules ()
20852 '(org-agenda org-archive org-attach org-clock org-colview org-id
20853 org-remember org-table org-timer)))
20856 (defun org-reload (&optional uncompiled)
20857 "Reload all org lisp files.
20858 With prefix arg UNCOMPILED, load the uncompiled versions."
20860 (require 'loadhist)
20861 (let* ((org-dir (org-find-library-dir "org"))
20862 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20863 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20864 (remove-re (mapconcat 'identity
20865 (mapcar (lambda (f) (concat "^" f "$"))
20866 (list (if (featurep 'xemacs)
20868 "org-colview-xemacs")
20869 "org" "org-loaddefs" "org-version"))
20871 (feats (delete-dups
20872 (mapcar 'file-name-sans-extension
20873 (mapcar 'file-name-nondirectory
20875 (mapcar 'feature-file
20882 (if (and (string-match feature-re f)
20883 (not (string-match remove-re f)))
20887 (list "org-version" "org")))
20888 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20889 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20890 load-uncore load-misses)
20893 (mapcar (lambda (f)
20894 (or (org-load-noerror-mustsuffix (concat org-dir f))
20895 (and (string= org-dir contrib-dir)
20896 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20897 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20898 (add-to-list 'load-uncore f 'append)
20903 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20904 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20906 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20907 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20908 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20911 (defun org-customize ()
20912 "Call the customize function with org as argument."
20914 (org-load-modules-maybe)
20915 (org-require-autoloaded-modules)
20916 (customize-browse 'org))
20918 (defun org-create-customize-menu ()
20919 "Create a full customization menu for Org-mode, insert it into the menu."
20921 (org-load-modules-maybe)
20922 (org-require-autoloaded-modules)
20923 (if (fboundp 'customize-menu-create)
20926 '("Org") "Customize"
20927 `(["Browse Org group" org-customize t]
20929 ,(customize-menu-create 'org)
20930 ["Set" Custom-set t]
20931 ["Save" Custom-save t]
20932 ["Reset to Current" Custom-reset-current t]
20933 ["Reset to Saved" Custom-reset-saved t]
20934 ["Reset to Standard Settings" Custom-reset-standard t]))
20935 (message "\"Org\"-menu now contains full customization menu"))
20936 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20938 ;;;; Miscellaneous stuff
20940 ;;; Generally useful functions
20942 (defun org-get-at-bol (property)
20943 "Get text property PROPERTY at beginning of line."
20944 (get-text-property (point-at-bol) property))
20946 (defun org-find-text-property-in-string (prop s)
20947 "Return the first non-nil value of property PROP in string S."
20948 (or (get-text-property 0 prop s)
20949 (get-text-property (or (next-single-property-change 0 prop s) 0)
20952 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20953 "Display the given MESSAGE as a warning."
20954 (if (fboundp 'display-warning)
20955 (display-warning 'org message
20956 (if (featurep 'xemacs) 'warning :warning))
20957 (let ((buf (get-buffer-create "*Org warnings*")))
20958 (with-current-buffer buf
20959 (goto-char (point-max))
20960 (insert "Warning (Org): " message)
20963 (display-buffer buf)
20966 (defun org-eval (form)
20967 "Eval FORM and return result."
20968 (condition-case error
20970 (error (format "%%![Error: %s]" error))))
20972 (defun org-in-clocktable-p ()
20973 "Check if the cursor is in a clocktable."
20974 (let ((pos (point)) start)
20977 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20978 (setq start (match-beginning 0))
20979 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20980 (>= (match-end 0) pos)
20983 (defun org-in-commented-line ()
20984 "Is point in a line starting with `#'?"
20985 (equal (char-after (point-at-bol)) ?#))
20987 (defun org-in-indented-comment-line ()
20988 "Is point in a line starting with `#' after some white space?"
20991 (goto-char (point-at-bol))
20992 (looking-at "[ \t]*#"))))
20994 (defun org-in-verbatim-emphasis ()
20996 (and (org-in-regexp org-emph-re 2)
20997 (>= (point) (match-beginning 3))
20998 (<= (point) (match-end 4))
20999 (member (match-string 3) '("=" "~")))))
21001 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21002 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21003 (if (and marker (marker-buffer marker)
21004 (buffer-live-p (marker-buffer marker)))
21006 (org-pop-to-buffer-same-window (marker-buffer marker))
21007 (if (or (> marker (point-max)) (< marker (point-min)))
21010 (org-show-context 'org-goto))
21012 (bookmark-jump bookmark)
21013 (error "Cannot find location"))))
21015 (defun org-quote-csv-field (s)
21016 "Quote field for inclusion in CSV material."
21017 (if (string-match "[\",]" s)
21018 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21021 (defun org-force-self-insert (N)
21022 "Needed to enforce self-insert under remapping."
21024 (self-insert-command N))
21026 (defun org-string-width (s)
21027 "Compute width of string, ignoring invisible characters.
21028 This ignores character with invisibility property `org-link', and also
21029 characters with property `org-cwidth', because these will become invisible
21030 upon the next fontification round."
21032 (when (or (eq t buffer-invisibility-spec)
21033 (assq 'org-link buffer-invisibility-spec))
21034 (while (setq b (text-property-any 0 (length s)
21035 'invisible 'org-link s))
21036 (setq s (concat (substring s 0 b)
21037 (substring s (or (next-single-property-change
21038 b 'invisible s) (length s)))))))
21039 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21040 (setq s (concat (substring s 0 b)
21041 (substring s (or (next-single-property-change
21042 b 'org-cwidth s) (length s))))))
21043 (setq l (string-width s) b -1)
21044 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21045 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21048 (defun org-shorten-string (s maxlength)
21049 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21050 If the string is shorter or has length MAXLENGTH, just return the
21051 original string. If it is longer, the functions finds a space in the
21052 string, breaks this string off at that locations and adds three dots
21053 as ellipsis. Including the ellipsis, the string will not be longer
21054 than MAXLENGTH. If finding a good breaking point in the string does
21055 not work, the string is just chopped off in the middle of a word
21057 (if (<= (length s) maxlength)
21059 (let* ((n (max (- maxlength 4) 1))
21060 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21061 (if (string-match re s)
21062 (concat (match-string 1 s) "...")
21063 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21065 (defun org-get-indentation (&optional line)
21066 "Get the indentation of the current line, interpreting tabs.
21067 When LINE is given, assume it represents a line and compute its indentation."
21069 (if (string-match "^ *" (org-remove-tabs line))
21072 (beginning-of-line 1)
21073 (skip-chars-forward " \t")
21074 (current-column))))
21076 (defun org-get-string-indentation (s)
21077 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21078 (let ((n -1) (i 0) (w tab-width) c)
21080 (while (< (setq n (1+ n)) (length s))
21081 (setq c (aref s n))
21082 (cond ((= c ?\ ) (setq i (1+ i)))
21083 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21084 (t (throw 'exit t)))))
21087 (defun org-remove-tabs (s &optional width)
21088 "Replace tabulators in S with spaces.
21089 Assumes that s is a single line, starting in column 0."
21090 (setq width (or width tab-width))
21091 (while (string-match "\t" s)
21092 (setq s (replace-match
21094 (- (* width (/ (+ (match-beginning 0) width) width))
21095 (match-beginning 0)) ?\ )
21099 (defun org-fix-indentation (line ind)
21100 "Fix indentation in LINE.
21101 IND is a cons cell with target and minimum indentation.
21102 If the current indentation in LINE is smaller than the minimum,
21103 leave it alone. If it is larger than ind, set it to the target."
21104 (let* ((l (org-remove-tabs line))
21105 (i (org-get-indentation l))
21106 (i1 (car ind)) (i2 (cdr ind)))
21107 (if (>= i i2) (setq l (substring line i2)))
21109 (concat (make-string i1 ?\ ) l)
21112 (defun org-remove-indentation (code &optional n)
21113 "Remove the maximum common indentation from the lines in CODE.
21114 N may optionally be the number of spaces to remove."
21117 (org-do-remove-indentation n)
21120 (defun org-do-remove-indentation (&optional n)
21121 "Remove the maximum common indentation from the buffer."
21122 (untabify (point-min) (point-max))
21123 (let ((min 10000) re)
21126 (goto-char (point-min))
21127 (while (re-search-forward "^ *[^ \n]" nil t)
21128 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21129 (unless (or (= min 0) (= min 10000))
21130 (setq re (format "^ \\{%d\\}" min))
21131 (goto-char (point-min))
21132 (while (re-search-forward re nil t)
21137 (defun org-fill-template (template alist)
21138 "Find each %key of ALIST in TEMPLATE and replace it."
21139 (let ((case-fold-search nil)
21141 (setq alist (sort (copy-sequence alist)
21142 (lambda (a b) (< (length (car a)) (length (car b))))))
21143 (while (setq entry (pop alist))
21145 (replace-regexp-in-string
21146 (concat "%" (regexp-quote (car entry)))
21147 (or (cdr entry) "") template t t)))
21150 (defun org-base-buffer (buffer)
21151 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21154 (or (buffer-base-buffer buffer)
21157 (defun org-trim (s)
21158 "Remove whitespace at beginning and end of string."
21159 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21160 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21163 (defun org-wrap (string &optional width lines)
21164 "Wrap string to either a number of lines, or a width in characters.
21165 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21166 that costs. If there is a word longer than WIDTH, the text is actually
21167 wrapped to the length of that word.
21168 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21169 many lines, whatever width that takes.
21170 The return value is a list of lines, without newlines at the end."
21171 (let* ((words (org-split-string string "[ \t\n]+"))
21172 (maxword (apply 'max (mapcar 'org-string-width words)))
21175 (org-do-wrap words (max maxword width)))
21178 (setq ll (org-do-wrap words maxword))
21179 (if (<= (length ll) lines)
21182 (while (> (length ll) lines)
21184 (setq ll (org-do-wrap words w)))
21186 (t (error "Cannot wrap this")))))
21188 (defun org-do-wrap (words width)
21189 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21192 (setq line (pop words))
21193 (while (and words (< (+ (length line) (length (car words))) width))
21194 (setq line (concat line " " (pop words))))
21195 (setq lines (push line lines)))
21198 (defun org-split-string (string &optional separators)
21199 "Splits STRING into substrings at SEPARATORS.
21200 No empty strings are returned if there are matches at the beginning
21201 and end of string."
21202 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21206 (while (and (string-match rexp string
21208 (= start (match-beginning 0))
21209 (< start (length string)))
21211 (< (match-beginning 0) (length string)))
21213 (or (eq (match-beginning 0) 0)
21214 (and (eq (match-beginning 0) (match-end 0))
21215 (eq (match-beginning 0) start))
21217 (cons (substring string start (match-beginning 0))
21219 (setq start (match-end 0)))
21220 (or (eq start (length string))
21222 (cons (substring string start)
21226 (defun org-quote-vert (s)
21227 "Replace \"|\" with \"\\vert\"."
21228 (while (string-match "|" s)
21229 (setq s (replace-match "\\vert" t t s)))
21232 (defun org-uuidgen-p (s)
21233 "Is S an ID created by UUIDGEN?"
21234 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21236 (defun org-in-src-block-p (&optional inside)
21237 "Whether point is in a code source block.
21238 When INSIDE is non-nil, don't consider we are within a src block
21239 when point is at #+BEGIN_SRC or #+END_SRC."
21240 (let ((case-fold-search t) ov)
21241 (or (and (setq ov (overlays-at (point)))
21242 (memq 'org-block-background
21243 (overlay-properties (car ov))))
21247 (beginning-of-line)
21248 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21250 (defun org-context ()
21251 "Return a list of contexts of the current cursor position.
21252 If several contexts apply, all are returned.
21253 Each context entry is a list with a symbol naming the context, and
21254 two positions indicating start and end of the context. Possible
21257 :headline anywhere in a headline
21258 :headline-stars on the leading stars in a headline
21259 :todo-keyword on a TODO keyword (including DONE) in a headline
21260 :tags on the TAGS in a headline
21261 :priority on the priority cookie in a headline
21262 :item on the first line of a plain list item
21263 :item-bullet on the bullet/number of a plain list item
21264 :checkbox on the checkbox in a plain list item
21265 :table in an org-mode table
21266 :table-special on a special filed in a table
21267 :table-table in a table.el table
21268 :clocktable in a clocktable
21269 :src-block in a source block
21270 :link on a hyperlink
21271 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21272 :target on a <<target>>
21273 :radio-target on a <<<radio-target>>>
21274 :latex-fragment on a LaTeX fragment
21275 :latex-preview on a LaTeX fragment with overlaid preview image
21277 This function expects the position to be visible because it uses font-lock
21278 faces as a help to recognize the following contexts: :table-special, :link,
21280 (let* ((f (get-text-property (point) 'face))
21281 (faces (if (listp f) f (list f)))
21282 (case-fold-search t)
21283 (p (point)) clist o)
21284 ;; First the large context
21286 ((org-at-heading-p t)
21287 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21289 (beginning-of-line 1)
21290 (looking-at org-todo-line-tags-regexp))
21291 (push (org-point-in-group p 1 :headline-stars) clist)
21292 (push (org-point-in-group p 2 :todo-keyword) clist)
21293 (push (org-point-in-group p 4 :tags) clist))
21295 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21296 (if (looking-at "\\[#[A-Z0-9]\\]")
21297 (push (org-point-in-group p 0 :priority) clist)))
21300 (push (org-point-in-group p 2 :item-bullet) clist)
21301 (push (list :item (point-at-bol)
21302 (save-excursion (org-end-of-item) (point)))
21304 (and (org-at-item-checkbox-p)
21305 (push (org-point-in-group p 0 :checkbox) clist)))
21308 (push (list :table (org-table-begin) (org-table-end)) clist)
21309 (if (memq 'org-formula faces)
21310 (push (list :table-special
21311 (previous-single-property-change p 'face)
21312 (next-single-property-change p 'face)) clist)))
21313 ((org-at-table-p 'any)
21314 (push (list :table-table) clist)))
21317 (let ((case-fold-search t))
21318 ;; New the "medium" contexts: clocktables, source blocks
21319 (cond ((org-in-clocktable-p)
21320 (push (list :clocktable
21321 (and (or (looking-at "#\\+BEGIN: clocktable")
21322 (search-backward "#+BEGIN: clocktable" nil t))
21323 (match-beginning 0))
21324 (and (re-search-forward "#\\+END:?" nil t)
21325 (match-end 0))) clist))
21326 ((org-in-src-block-p)
21327 (push (list :src-block
21328 (and (or (looking-at "#\\+BEGIN_SRC")
21329 (search-backward "#+BEGIN_SRC" nil t))
21330 (match-beginning 0))
21331 (and (search-forward "#+END_SRC" nil t)
21332 (match-beginning 0))) clist))))
21335 ;; Now the small context
21337 ((org-at-timestamp-p)
21338 (push (org-point-in-group p 0 :timestamp) clist))
21339 ((memq 'org-link faces)
21341 (previous-single-property-change p 'face)
21342 (next-single-property-change p 'face)) clist))
21343 ((memq 'org-special-keyword faces)
21344 (push (list :keyword
21345 (previous-single-property-change p 'face)
21346 (next-single-property-change p 'face)) clist))
21348 (push (org-point-in-group p 0 :target) clist)
21349 (goto-char (1- (match-beginning 0)))
21350 (if (looking-at org-radio-target-regexp)
21351 (push (org-point-in-group p 0 :radio-target) clist))
21353 ((setq o (car (delq nil
21356 (if (memq x org-latex-fragment-image-overlays) x))
21357 (overlays-at (point))))))
21358 (push (list :latex-fragment
21359 (overlay-start o) (overlay-end o)) clist)
21360 (push (list :latex-preview
21361 (overlay-start o) (overlay-end o)) clist))
21362 ((org-inside-LaTeX-fragment-p)
21363 ;; FIXME: positions wrong.
21364 (push (list :latex-fragment (point) (point)) clist)))
21366 (setq clist (nreverse (delq nil clist)))
21369 ;; FIXME: Compare with at-regexp-p Do we need both?
21370 (defun org-in-regexp (re &optional nlines visually)
21371 "Check if point is inside a match of regexp.
21372 Normally only the current line is checked, but you can include NLINES extra
21373 lines both before and after point into the search.
21374 If VISUALLY is set, require that the cursor is not after the match but
21375 really on, so that the block visually is on the match."
21377 (let ((pos (point))
21378 (eol (point-at-eol (+ 1 (or nlines 0))))
21379 (inc (if visually 1 0)))
21381 (beginning-of-line (- 1 (or nlines 0)))
21382 (while (re-search-forward re eol t)
21383 (if (and (<= (match-beginning 0) pos)
21384 (>= (+ inc (match-end 0)) pos))
21385 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21387 (defun org-at-regexp-p (regexp)
21388 "Is point inside a match of REGEXP in the current line?"
21391 (let ((pos (point)) (end (point-at-eol)))
21392 (beginning-of-line 1)
21393 (while (re-search-forward regexp end t)
21394 (if (and (<= (match-beginning 0) pos)
21395 (>= (match-end 0) pos))
21399 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21400 "Non-nil when point is between matches of START-RE and END-RE.
21402 Also return a non-nil value when point is on one of the matches.
21404 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21405 buffer positions. Default values are the positions of headlines
21406 surrounding the point.
21408 The functions returns a cons cell whose car (resp. cdr) is the
21409 position before START-RE (resp. after END-RE)."
21411 (let ((pos (point))
21412 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21413 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21416 ;; Point is on a block when on START-RE or if START-RE can be
21417 ;; found before it...
21418 (and (or (org-at-regexp-p start-re)
21419 (re-search-backward start-re limit-up t))
21420 (setq beg (match-beginning 0))
21421 ;; ... and END-RE after it...
21422 (goto-char (match-end 0))
21423 (re-search-forward end-re limit-down t)
21424 (> (setq end (match-end 0)) pos)
21425 ;; ... without another START-RE in-between.
21426 (goto-char (match-beginning 0))
21427 (not (re-search-backward start-re (1+ beg) t))
21429 (cons beg end))))))
21431 (defun org-in-block-p (names)
21432 "Non-nil when point belongs to a block whose name belongs to NAMES.
21434 NAMES is a list of strings containing names of blocks.
21436 Return first block name matched, or nil. Beware that in case of
21437 nested blocks, the returned name may not belong to the closest
21441 (let ((case-fold-search t)
21442 (lim-up (save-excursion (outline-previous-heading)))
21443 (lim-down (save-excursion (outline-next-heading))))
21444 (mapc (lambda (name)
21445 (let ((n (regexp-quote name)))
21446 (when (org-between-regexps-p
21447 (concat "^[ \t]*#\\+begin_" n)
21448 (concat "^[ \t]*#\\+end_" n)
21454 (defun org-occur-in-agenda-files (regexp &optional nlines)
21455 "Call `multi-occur' with buffers for all agenda files."
21456 (interactive "sOrg-files matching: \np")
21457 (let* ((files (org-agenda-files))
21458 (tnames (mapcar 'file-truename files))
21459 (extra org-agenda-text-search-extra-files)
21461 (when (eq (car extra) 'agenda-archives)
21462 (setq extra (cdr extra))
21463 (setq files (org-add-archive-files files)))
21464 (while (setq f (pop extra))
21465 (unless (member (file-truename f) tnames)
21466 (add-to-list 'files f 'append)
21467 (add-to-list 'tnames (file-truename f) 'append)))
21469 (mapcar (lambda (x)
21470 (with-current-buffer
21471 (or (get-file-buffer x) (find-file-noselect x))
21477 (if (boundp 'occur-mode-find-occurrence-hook)
21479 (add-hook 'occur-mode-find-occurrence-hook
21481 (when (derived-mode-p 'org-mode)
21484 (defadvice occur-mode-goto-occurrence
21485 (after org-occur-reveal activate)
21486 (and (derived-mode-p 'org-mode) (org-reveal)))
21487 (defadvice occur-mode-goto-occurrence-other-window
21488 (after org-occur-reveal activate)
21489 (and (derived-mode-p 'org-mode) (org-reveal)))
21490 (defadvice occur-mode-display-occurrence
21491 (after org-occur-reveal activate)
21492 (when (derived-mode-p 'org-mode)
21493 (let ((pos (occur-mode-find-occurrence)))
21494 (with-current-buffer (marker-buffer pos)
21499 (defun org-occur-link-in-agenda-files ()
21500 "Create a link and search for it in the agendas.
21501 The link is not stored in `org-stored-links', it is just created
21502 for the search purpose."
21504 (let ((link (condition-case nil
21505 (org-store-link nil)
21506 (error "Unable to create a link to here"))))
21507 (org-occur-in-agenda-files (regexp-quote link))))
21509 (defun org-reverse-string (string)
21510 "Return the reverse of STRING."
21511 (apply 'string (reverse (string-to-list string))))
21513 (defun org-uniquify (list)
21514 "Remove duplicate elements from LIST."
21516 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21519 (defun org-uniquify-alist (alist)
21520 "Merge duplicate elements of an alist.
21522 For example, in this alist:
21524 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21525 => '((a 1 3) (b 2))
21527 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21532 (if (not (assoc (car e) rtn))
21534 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21535 (setq rtn (assq-delete-all (car e) rtn))
21540 (defun org-delete-all (elts list)
21541 "Remove all elements in ELTS from LIST."
21543 (setq list (delete (pop elts) list)))
21546 (defun org-count (cl-item cl-seq)
21547 "Count the number of occurrences of ITEM in SEQ.
21548 Taken from `count' in cl-seq.el with all keyword arguments removed."
21549 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21550 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21551 (while (< cl-start cl-end)
21552 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21553 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21554 (setq cl-start (1+ cl-start)))
21557 (defun org-remove-if (predicate seq)
21558 "Remove everything from SEQ that fulfills PREDICATE."
21562 (if (not (funcall predicate e)) (push e res)))
21565 (defun org-remove-if-not (predicate seq)
21566 "Remove everything from SEQ that does not fulfill PREDICATE."
21570 (if (funcall predicate e) (push e res)))
21573 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21574 "Reduce two-argument FUNCTION across SEQ.
21575 Taken from `reduce' in cl-seq.el with all keyword arguments but
21576 \":initial-value\" removed."
21577 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21578 (cadr (memq :initial-value cl-keys)))
21579 (cl-seq (pop cl-seq))
21580 (t (funcall cl-func)))))
21582 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21585 (defun org-back-over-empty-lines ()
21586 "Move backwards over whitespace, to the beginning of the first empty line.
21587 Returns the number of empty lines passed."
21588 (let ((pos (point)))
21589 (if (cdr (assoc 'heading org-blank-before-new-entry))
21590 (skip-chars-backward " \t\n\r")
21592 (forward-line -1)))
21593 (beginning-of-line 2)
21594 (goto-char (min (point) pos))
21595 (count-lines (point) pos)))
21597 (defun org-skip-whitespace ()
21598 (skip-chars-forward " \t\n\r"))
21600 (defun org-point-in-group (point group &optional context)
21601 "Check if POINT is in match-group GROUP.
21602 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21603 match. If the match group does not exist or point is not inside it,
21605 (and (match-beginning group)
21606 (>= point (match-beginning group))
21607 (<= point (match-end group))
21609 (list context (match-beginning group) (match-end group))
21612 (defun org-switch-to-buffer-other-window (&rest args)
21613 "Switch to buffer in a second window on the current frame.
21614 In particular, do not allow pop-up frames.
21615 Returns the newly created buffer."
21617 (apply 'switch-to-buffer-other-window args)))
21619 (defun org-combine-plists (&rest plists)
21620 "Create a single property list from all plists in PLISTS.
21621 The process starts by copying the first list, and then setting properties
21622 from the other lists. Settings in the last list are the most significant
21623 ones and overrule settings in the other lists."
21624 (let ((rtn (copy-sequence (pop plists)))
21627 (setq ls (pop plists))
21629 (setq p (pop ls) v (pop ls))
21630 (setq rtn (plist-put rtn p v))))
21633 (defun org-replace-escapes (string table)
21634 "Replace %-escapes in STRING with values in TABLE.
21635 TABLE is an association list with keys like \"%a\" and string values.
21636 The sequences in STRING may contain normal field width and padding information,
21637 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21638 so values can contain further %-escapes if they are define later in TABLE."
21639 (let ((tbl (copy-alist table))
21640 (case-fold-search nil)
21643 (while (setq e (pop tbl))
21644 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21645 (when (and (cdr e) (string-match re (cdr e)))
21646 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21648 (add-text-properties 0 3 (list 'sref sref) safe)
21649 (setcdr e (replace-match safe t t (cdr e)))))
21650 (while (string-match re string)
21651 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21653 (setq string (replace-match rpl t t string))))
21654 (while (setq pchg (next-property-change pchg string))
21655 (let ((sref (get-text-property pchg 'sref string)))
21656 (when (and sref (string-match "SREF" string pchg))
21657 (setq string (replace-match sref t t string)))))
21660 (defun org-sublist (list start end)
21661 "Return a section of LIST, from START to END.
21662 Counting starts at 1."
21663 (let (rtn (c start))
21664 (setq list (nthcdr (1- start) list))
21665 (while (and list (<= c end))
21666 (push (pop list) rtn)
21670 (defun org-find-base-buffer-visiting (file)
21671 "Like `find-buffer-visiting' but always return the base buffer and
21672 not an indirect buffer."
21673 (let ((buf (or (get-file-buffer file)
21674 (find-buffer-visiting file))))
21676 (or (buffer-base-buffer buf) buf)
21679 (defun org-image-file-name-regexp (&optional extensions)
21680 "Return regexp matching the file names of images.
21681 If EXTENSIONS is given, only match these."
21682 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21683 (image-file-name-regexp)
21684 (let ((image-file-name-extensions
21686 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21687 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21689 (regexp-opt (nconc (mapcar 'upcase
21690 image-file-name-extensions)
21691 image-file-name-extensions)
21695 (defun org-file-image-p (file &optional extensions)
21696 "Return non-nil if FILE is an image."
21698 (string-match (org-image-file-name-regexp extensions) file)))
21700 (defun org-get-cursor-date (&optional with-time)
21701 "Return the date at cursor in as a time.
21702 This works in the calendar and in the agenda, anywhere else it just
21703 returns the current time.
21704 If WITH-TIME is non-nil, returns the time of the event at point (in
21705 the agenda) or the current time of the day."
21706 (let (date day defd tp tm hod mod)
21708 (setq tp (get-text-property (point) 'time))
21709 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21710 (setq hod (string-to-number (match-string 1 tp))
21711 mod (string-to-number (match-string 2 tp))))
21712 (or tp (setq hod (nth 2 (decode-time (current-time)))
21713 mod (nth 1 (decode-time (current-time))))))
21715 ((eq major-mode 'calendar-mode)
21716 (setq date (calendar-cursor-to-date)
21717 defd (encode-time 0 (or mod 0) (or hod 0)
21718 (nth 1 date) (nth 0 date) (nth 2 date))))
21719 ((eq major-mode 'org-agenda-mode)
21720 (setq day (get-text-property (point) 'day))
21722 (setq date (calendar-gregorian-from-absolute day)
21723 defd (encode-time 0 (or mod 0) (or hod 0)
21724 (nth 1 date) (nth 0 date) (nth 2 date))))))
21725 (or defd (current-time))))
21727 (defun org-mark-subtree (&optional up)
21728 "Mark the current subtree.
21729 This puts point at the start of the current subtree, and mark at
21730 the end. If a numeric prefix UP is given, move up into the
21731 hierarchy of headlines by UP levels before marking the subtree."
21733 (org-with-limited-levels
21734 (cond ((org-at-heading-p) (beginning-of-line))
21735 ((org-before-first-heading-p) (error "Not in a subtree"))
21736 (t (outline-previous-visible-heading 1))))
21737 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21738 (if (org-called-interactively-p 'any)
21739 (call-interactively 'org-mark-element)
21740 (org-mark-element)))
21745 (defun org-indent-line ()
21746 "Indent line depending on context."
21748 (let* ((pos (point))
21749 (itemp (org-at-item-p))
21750 (case-fold-search t)
21751 (org-drawer-regexp (or org-drawer-regexp "\000"))
21752 (inline-task-p (and (featurep 'org-inlinetask)
21753 (org-inlinetask-in-task-p)))
21754 (inline-re (and inline-task-p
21755 (org-inlinetask-outline-regexp)))
21757 (if (and orgstruct-is-++ (eq pos (point)))
21758 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21759 (indent-according-to-mode))
21760 (beginning-of-line 1)
21763 ((looking-at org-outline-regexp) (setq column 0))
21764 ;; Footnote definition
21765 ((looking-at org-footnote-definition-re) (setq column 0))
21766 ;; Literal examples
21767 ((looking-at "[ \t]*:\\( \\|$\\)")
21768 (setq column (org-get-indentation))) ; do nothing
21770 ((ignore-errors (goto-char (org-in-item-p)))
21771 (setq column (if itemp
21772 (org-get-indentation)
21773 (org-list-item-body-column (point))))
21776 ((and (looking-at "[ \t]*:END:")
21777 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21779 (goto-char (1- (match-beginning 1)))
21780 (setq column (current-column))))
21782 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21784 (re-search-backward
21785 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21786 (setq column (org-get-indentation (match-string 0))))
21787 ((and (not (looking-at "[ \t]*#\\+begin_"))
21788 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21790 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21792 (cond ((equal (downcase (match-string 1)) "src")
21793 ;; src blocks: let `org-edit-src-exit' handle them
21794 (org-get-indentation))
21795 ((equal (downcase (match-string 1)) "example")
21796 (max (org-get-indentation)
21797 (org-get-indentation (match-string 0))))
21799 (org-get-indentation (match-string 0))))))
21800 ;; This line has nothing special, look at the previous relevant
21801 ;; line to compute indentation
21803 (beginning-of-line 0)
21804 (while (and (not (bobp))
21805 (not (looking-at org-table-line-regexp))
21806 (not (looking-at org-drawer-regexp))
21807 ;; When point started in an inline task, do not move
21808 ;; above task starting line.
21809 (not (and inline-task-p (looking-at inline-re)))
21810 ;; Skip drawers, blocks, empty lines, verbatim,
21811 ;; comments, tables, footnotes definitions, lists,
21813 (or (and (looking-at "[ \t]*:END:")
21814 (re-search-backward org-drawer-regexp nil t))
21815 (and (looking-at "[ \t]*#\\+end_")
21816 (re-search-backward "[ \t]*#\\+begin_"nil t))
21817 (looking-at "[ \t]*[\n:#|]")
21818 (looking-at org-footnote-definition-re)
21819 (and (ignore-errors (goto-char (org-in-item-p)))
21821 (org-list-get-top-point (org-list-struct))))
21822 (and (not inline-task-p)
21823 (featurep 'org-inlinetask)
21824 (org-inlinetask-in-task-p)
21825 (or (org-inlinetask-goto-beginning) t))))
21826 (beginning-of-line 0))
21828 ;; There was an heading above.
21829 ((looking-at "\\*+[ \t]+")
21830 (if (not org-adapt-indentation)
21832 (goto-char (match-end 0))
21833 (setq column (current-column))))
21834 ;; A drawer had started and is unfinished
21835 ((looking-at org-drawer-regexp)
21836 (goto-char (1- (match-beginning 1)))
21837 (setq column (current-column)))
21838 ;; Else, nothing noticeable found: get indentation and go on.
21839 (t (setq column (org-get-indentation))))))
21840 ;; Now apply indentation and move cursor accordingly
21842 (if (<= (current-column) (current-indentation))
21843 (org-indent-line-to column)
21844 (save-excursion (org-indent-line-to column)))
21845 ;; Special polishing for properties, see `org-property-format'
21846 (setq column (current-column))
21847 (beginning-of-line 1)
21849 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21850 (replace-match (concat (match-string 1)
21851 (format org-property-format
21852 (match-string 2) (match-string 3)))
21854 (org-move-to-column column))))
21856 (defun org-indent-drawer ()
21857 "Indent the drawer at point."
21860 (e (and (save-excursion (re-search-forward ":END:" nil t))
21865 (when (overlays-at (point))
21866 (member 'invisible (overlay-properties
21867 (car (overlays-at (point)))))))))
21868 (when folded (org-cycle))
21869 (indent-for-tab-command)
21870 (while (and (move-beginning-of-line 2) (< (point) e))
21871 (indent-for-tab-command))
21873 (when folded (org-cycle)))
21874 (message "Drawer at point indented"))
21876 (defun org-indent-block ()
21877 "Indent the block at point."
21880 (case-fold-search t)
21881 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21886 (when (overlays-at (point))
21887 (member 'invisible (overlay-properties
21888 (car (overlays-at (point)))))))))
21889 (when folded (org-cycle))
21890 (indent-for-tab-command)
21891 (while (and (move-beginning-of-line 2) (< (point) e))
21892 (indent-for-tab-command))
21894 (when folded (org-cycle)))
21895 (message "Block at point indented"))
21897 (defun org-indent-region (start end)
21901 (let ((line-end (org-current-line end)))
21903 (while (< (org-current-line) line-end)
21904 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21905 (t (call-interactively 'org-indent-line)))
21906 (move-beginning-of-line 2)))))
21911 ;; We use our own fill-paragraph and auto-fill functions.
21913 ;; `org-fill-paragraph' relies on adaptive filling and context
21914 ;; checking. Appropriate `fill-prefix' is computed with
21915 ;; `org-adaptive-fill-function'.
21917 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21918 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21919 ;; `org-adaptive-fill-function' value. Internally,
21920 ;; `org-comment-line-break-function' breaks the line.
21922 ;; `org-setup-filling' installs filling and auto-filling related
21923 ;; variables during `org-mode' initialization.
21925 (defun org-setup-filling ()
21927 ;; Prevent auto-fill from inserting unwanted new items.
21928 (when (boundp 'fill-nobreak-predicate)
21930 'fill-nobreak-predicate
21932 (append fill-nobreak-predicate
21933 '(org-fill-paragraph-separate-nobreak-p
21934 org-fill-line-break-nobreak-p
21935 org-fill-paragraph-with-timestamp-nobreak-p)))))
21936 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21937 (org-set-local 'auto-fill-inhibit-regexp nil)
21938 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21939 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21940 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21942 (defvar org-element-paragraph-separate) ; org-element.el
21943 (defun org-fill-paragraph-separate-nobreak-p ()
21944 "Non-nil when a line break at point would insert a new item."
21945 (looking-at (substring org-element-paragraph-separate 1)))
21947 (defun org-fill-line-break-nobreak-p ()
21948 "Non-nil when a line break at point would create an Org line break."
21950 (skip-chars-backward "[ \t]")
21951 (skip-chars-backward "\\\\")
21952 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21954 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21955 "Non-nil when a line break at point would insert a new item."
21956 (and (org-at-timestamp-p t)
21957 (not (looking-at org-ts-regexp-both))))
21959 (declare-function message-in-body-p "message" ())
21960 (defvar orgtbl-line-start-regexp) ; From org-table.el
21961 (defun org-adaptive-fill-function ()
21962 "Compute a fill prefix for the current line.
21963 Return fill prefix, as a string, or nil if current line isn't
21964 meant to be filled."
21967 (when (derived-mode-p 'message-mode)
21969 (beginning-of-line)
21970 (cond ((or (not (message-in-body-p))
21971 (looking-at orgtbl-line-start-regexp))
21973 ((looking-at message-cite-prefix-regexp)
21974 (throw 'exit (match-string-no-properties 0)))
21975 ((looking-at org-outline-regexp)
21976 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21977 (org-with-wide-buffer
21978 (let* ((p (line-beginning-position))
21979 (element (save-excursion (beginning-of-line)
21980 (org-element-at-point)))
21981 (type (org-element-type element))
21982 (post-affiliated (org-element-property :post-affiliated element)))
21983 (unless (and post-affiliated (< p post-affiliated))
21985 (comment (looking-at "[ \t]*# ?") (match-string 0))
21986 (footnote-definition "")
21988 (make-string (org-list-item-body-column
21989 (or post-affiliated
21990 (org-element-property :begin element)))
21993 ;; Fill prefix is usually the same as the current line,
21994 ;; except if the paragraph is at the beginning of an item.
21995 (let ((parent (org-element-property :parent element)))
21996 (cond ((eq (org-element-type parent) 'item)
21997 (make-string (org-list-item-body-column
21998 (org-element-property :begin parent))
22000 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22004 ;; Only fill contents if P is within block boundaries.
22005 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22008 (cend (save-excursion
22009 (goto-char (org-element-property :end element))
22010 (skip-chars-backward " \r\t\n")
22011 (line-beginning-position))))
22012 (when (and (>= p cbeg) (< p cend))
22013 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22017 (declare-function message-goto-body "message" ())
22018 (defvar message-cite-prefix-regexp) ; From message.el
22019 (defun org-fill-paragraph (&optional justify)
22020 "Fill element at point, when applicable.
22022 This function only applies to comment blocks, comments, example
22023 blocks and paragraphs. Also, as a special case, re-align table
22024 when point is at one.
22026 If JUSTIFY is non-nil (interactively, with prefix argument),
22027 justify as well. If `sentence-end-double-space' is non-nil, then
22028 period followed by one space does not end a sentence, so don't
22029 break a line there. The variable `fill-column' controls the
22032 For convenience, when point is at a plain list, an item or
22033 a footnote definition, try to fill the first paragraph within."
22035 (if (and (derived-mode-p 'message-mode)
22036 (or (not (message-in-body-p))
22037 (save-excursion (move-beginning-of-line 1)
22038 (looking-at message-cite-prefix-regexp))))
22039 ;; First ensure filling is correct in message-mode.
22040 (let ((fill-paragraph-function
22041 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22042 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22043 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22044 (paragraph-separate
22045 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22046 (fill-paragraph nil))
22047 (with-syntax-table org-mode-transpose-word-syntax-table
22048 ;; Move to end of line in order to get the first paragraph
22049 ;; within a plain list or a footnote definition.
22050 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22051 ;; First check if point is in a blank line at the beginning of
22052 ;; the buffer. In that case, ignore filling.
22053 (case (org-element-type element)
22054 ;; Use major mode filling function is src blocks.
22055 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22056 ;; Align Org tables, leave table.el tables as-is.
22057 (table-row (org-table-align) t)
22059 (when (eq (org-element-property :type element) 'org)
22063 ;; Paragraphs may contain `line-break' type objects.
22064 (let ((beg (max (point-min)
22065 (org-element-property :contents-begin element)))
22066 (end (min (point-max)
22067 (org-element-property :contents-end element))))
22068 ;; Do nothing if point is at an affiliated keyword.
22069 (if (< (line-end-position) beg) t
22070 (when (derived-mode-p 'message-mode)
22071 ;; In `message-mode', do not fill following citation
22072 ;; in current paragraph nor text before message body.
22073 (let ((body-start (save-excursion (message-goto-body))))
22074 (when body-start (setq beg (max body-start beg))))
22075 (when (save-excursion
22077 (concat "^" message-cite-prefix-regexp) end t))
22078 (setq end (match-beginning 0))))
22079 ;; Fill paragraph, taking line breaks into account.
22080 ;; For that, slice the paragraph using line breaks as
22081 ;; separators, and fill the parts in reverse order to
22082 ;; avoid messing with markers.
22087 (fill-region-as-paragraph pos (point) justify)
22089 ;; Find the list of ending positions for line breaks
22090 ;; in the current paragraph. Add paragraph
22091 ;; beginning to include first slice.
22095 (org-element--parse-objects
22096 beg end nil (org-element-restriction 'paragraph))
22098 (lambda (lb) (org-element-property :end lb)))))))
22100 ;; Contents of `comment-block' type elements should be
22101 ;; filled as plain text, but only if point is within block
22104 (let* ((case-fold-search t)
22105 (beg (save-excursion
22106 (goto-char (org-element-property :begin element))
22107 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22110 (end (save-excursion
22111 (goto-char (org-element-property :end element))
22112 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22113 (line-beginning-position))))
22114 (when (and (>= (point) beg) (< (point) end))
22115 (fill-region-as-paragraph
22118 (re-search-backward "^[ \t]*$" beg 'move)
22119 (line-beginning-position))
22121 (beginning-of-line)
22122 (re-search-forward "^[ \t]*$" end 'move)
22123 (line-beginning-position))
22127 (comment (fill-comment-paragraph justify))
22128 ;; Ignore every other element.
22131 (defun org-auto-fill-function ()
22132 "Auto-fill function."
22133 ;; Check if auto-filling is meaningful.
22134 (let ((fc (current-fill-column)))
22135 (when (and fc (> (current-column) fc))
22136 (let* ((fill-prefix (org-adaptive-fill-function))
22137 ;; Enforce empty fill prefix, if required. Otherwise, it
22138 ;; will be computed again.
22139 (adaptive-fill-mode (not (equal fill-prefix ""))))
22140 (when fill-prefix (do-auto-fill))))))
22142 (defun org-comment-line-break-function (&optional soft)
22143 "Break line at point and indent, continuing comment if within one.
22144 The inserted newline is marked hard if variable
22145 `use-hard-newlines' is true, unless optional argument SOFT is
22147 (if soft (insert-and-inherit ?\n) (newline 1))
22148 (save-excursion (forward-char -1) (delete-horizontal-space))
22149 (delete-horizontal-space)
22150 (indent-to-left-margin)
22151 (insert-before-markers-and-inherit fill-prefix))
22156 ;; Org comments syntax is quite complex. It requires the entire line
22157 ;; to be just a comment. Also, even with the right syntax at the
22158 ;; beginning of line, some some elements (i.e. verse-block or
22159 ;; example-block) don't accept comments. Usual Emacs comment commands
22160 ;; cannot cope with those requirements. Therefore, Org replaces them.
22162 ;; Org still relies on `comment-dwim', but cannot trust
22163 ;; `comment-only-p'. So, `comment-region-function' and
22164 ;; `uncomment-region-function' both point
22165 ;; to`org-comment-or-uncomment-region'. Eventually,
22166 ;; `org-insert-comment' takes care of insertion of comments at the
22167 ;; beginning of line.
22169 ;; `org-setup-comments-handling' install comments related variables
22170 ;; during `org-mode' initialization.
22172 (defun org-setup-comments-handling ()
22174 (org-set-local 'comment-use-syntax nil)
22175 (org-set-local 'comment-start "# ")
22176 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22177 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22178 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22179 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22181 (defun org-insert-comment ()
22182 "Insert an empty comment above current line.
22183 If the line is empty, insert comment at its beginning."
22184 (beginning-of-line)
22185 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22189 (defvar comment-empty-lines) ; From newcomment.el.
22190 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22191 "Comment or uncomment each non-blank line in the region.
22192 Uncomment each non-blank line between BEG and END if it only
22193 contains commented lines. Otherwise, comment them."
22196 (narrow-to-region (save-excursion (goto-char beg)
22197 (skip-chars-forward " \r\t\n" end)
22198 (line-beginning-position))
22199 (save-excursion (goto-char end)
22200 (skip-chars-backward " \r\t\n" beg)
22201 (line-end-position)))
22203 ;; UNCOMMENTP is non-nil when every non blank line between
22204 ;; BEG and END is a comment.
22206 (goto-char (point-min))
22207 (while (and (not (eobp))
22208 (let ((element (org-element-at-point)))
22209 (and (eq (org-element-type element) 'comment)
22210 (goto-char (min (point-max)
22211 (org-element-property
22212 :end element)))))))
22215 ;; Only blank lines and comments in region: uncomment it.
22217 (goto-char (point-min))
22218 (while (not (eobp))
22219 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22220 (replace-match "" nil nil nil 1))
22222 ;; Comment each line in region.
22223 (let ((min-indent (point-max)))
22224 ;; First find the minimum indentation across all lines.
22226 (goto-char (point-min))
22227 (while (and (not (eobp)) (not (zerop min-indent)))
22228 (unless (looking-at "[ \t]*$")
22229 (setq min-indent (min min-indent (current-indentation))))
22231 ;; Then loop over all lines.
22233 (goto-char (point-min))
22234 (while (not (eobp))
22235 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22236 ;; Don't get fooled by invisible text (e.g. link path)
22237 ;; when moving to column MIN-INDENT.
22238 (let ((buffer-invisibility-spec nil))
22239 (org-move-to-column min-indent t))
22240 (insert comment-start))
22241 (forward-line))))))))
22246 ;; This section contains tools to operate on timestamp objects, as
22247 ;; returned by, e.g. `org-element-context'.
22249 (defun org-timestamp-has-time-p (timestamp)
22250 "Non-nil when TIMESTAMP has a time specified."
22251 (org-element-property :hour-start timestamp))
22253 (defun org-timestamp-format (timestamp format &optional end utc)
22254 "Format a TIMESTAMP element into a string.
22256 FORMAT is a format specifier to be passed to
22257 `format-time-string'.
22259 When optional argument END is non-nil, use end of date-range or
22260 time-range, if possible.
22262 When optional argument UTC is non-nil, time will be expressed as
22264 (format-time-string
22266 (apply 'encode-time
22269 (lambda (prop) (or (org-element-property prop timestamp) 0))
22270 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22271 '(:minute-start :hour-start :day-start :month-start
22275 (defun org-timestamp-split-range (timestamp &optional end)
22276 "Extract a timestamp object from a date or time range.
22278 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22279 the end of the range. Otherwise, extract its start.
22281 Return a new timestamp object sharing the same parent as
22283 (let ((type (org-element-property :type timestamp)))
22284 (if (memq type '(active inactive diary)) timestamp
22285 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22287 (org-element-put-property
22288 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22289 ;; Copy start properties over end properties if END is
22290 ;; non-nil. Otherwise, copy end properties over `start' ones.
22291 (let ((p-alist '((:minute-start . :minute-end)
22292 (:hour-start . :hour-end)
22293 (:day-start . :day-end)
22294 (:month-start . :month-end)
22295 (:year-start . :year-end))))
22296 (dolist (p-cell p-alist)
22297 (org-element-put-property
22299 (funcall (if end 'car 'cdr) p-cell)
22300 (org-element-property
22301 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22302 ;; Eventually refresh `:raw-value'.
22303 (org-element-put-property split-ts :raw-value nil)
22304 (org-element-put-property
22305 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22307 (defun org-timestamp-translate (timestamp &optional boundary)
22308 "Apply `org-translate-time' on a TIMESTAMP object.
22309 When optional argument BOUNDARY is non-nil, it is either the
22310 symbol `start' or `end'. In this case, only translate the
22311 starting or ending part of TIMESTAMP if it is a date or time
22312 range. Otherwise, translate both parts."
22313 (if (and (not boundary)
22314 (memq (org-element-property :type timestamp)
22315 '(active-range inactive-range)))
22317 (org-translate-time
22318 (org-element-property :raw-value
22319 (org-timestamp-split-range timestamp)))
22321 (org-translate-time
22322 (org-element-property :raw-value
22323 (org-timestamp-split-range timestamp t))))
22324 (org-translate-time
22325 (org-element-property
22327 (if (not boundary) timestamp
22328 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22334 (defun org-toggle-fixed-width-section (arg)
22335 "Toggle the fixed-width export.
22336 If there is no active region, the QUOTE keyword at the current headline is
22337 inserted or removed. When present, it causes the text between this headline
22338 and the next to be exported as fixed-width text, and unmodified.
22339 If there is an active region, this command adds or removes a colon as the
22340 first character of this line. If the first character of a line is a colon,
22341 this line is also exported in fixed-width font."
22344 (regionp (org-region-active-p))
22345 (beg (if regionp (region-beginning) (point)))
22346 (end (if regionp (region-end)))
22347 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22348 (case-fold-search nil)
22349 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22354 (setq cc (current-column))
22355 (beginning-of-line 1)
22356 (setq off (looking-at re))
22357 (while (> nlines 0)
22358 (setq nlines (1- nlines))
22359 (beginning-of-line 1)
22362 (org-move-to-column cc t)
22365 ((and off (looking-at re))
22366 (replace-match "" t t nil 1))
22367 ((not off) (org-move-to-column cc t) (insert ": ")))
22370 (org-back-to-heading)
22372 ((looking-at (format org-heading-keyword-regexp-format
22374 (goto-char (match-end 1))
22375 (looking-at (concat " +" org-quote-string))
22376 (replace-match "" t t)
22377 (when (eolp) (insert " ")))
22378 ((looking-at org-outline-regexp)
22379 (goto-char (match-end 0))
22380 (insert org-quote-string " ")))))))
22382 (defun org-reftex-citation ()
22383 "Use reftex-citation to insert a citation into the buffer.
22384 This looks for a line like
22386 #+BIBLIOGRAPHY: foo plain option:-d
22388 and derives from it that foo.bib is the bibliography file relevant
22389 for this document. It then installs the necessary environment for RefTeX
22390 to work in this buffer and calls `reftex-citation' to insert a citation
22393 Export of such citations to both LaTeX and HTML is handled by the contributed
22394 package org-exp-bibtex by Taru Karttunen."
22396 (let ((reftex-docstruct-symbol 'rds)
22397 (reftex-cite-format "\\cite{%l}")
22402 (let ((case-fold-search t)
22403 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22404 (if (not (save-excursion
22405 (or (re-search-forward re nil t)
22406 (re-search-backward re nil t))))
22407 (error "No bibliography defined in file")
22408 (setq bib (concat (match-string 1) ".bib")
22409 rds (list (list 'bib bib)))))))
22410 (call-interactively 'reftex-citation)))
22412 ;;;; Functions extending outline functionality
22414 (defun org-beginning-of-line (&optional arg)
22415 "Go to the beginning of the current line. If that is invisible, continue
22416 to a visible line beginning. This makes the function of C-a more intuitive.
22417 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22418 first attempt, and only move to after the tags when the cursor is already
22419 beyond the end of the headline."
22421 (let ((pos (point))
22422 (special (if (consp org-special-ctrl-a/e)
22423 (car org-special-ctrl-a/e)
22424 org-special-ctrl-a/e))
22426 (if (org-bound-and-true-p visual-line-mode)
22427 (beginning-of-visual-line 1)
22428 (beginning-of-line 1))
22429 (if (and arg (fboundp 'move-beginning-of-line))
22430 (call-interactively 'move-beginning-of-line)
22434 (if (org-truely-invisible-p)
22435 (while (and (not (bobp)) (org-truely-invisible-p))
22437 (beginning-of-line 1))
22438 (forward-char 1))))
22441 ((and (looking-at org-complex-heading-regexp)
22442 (= (char-after (match-end 1)) ?\ ))
22443 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22447 (cond ((> pos refpos) refpos)
22448 ((= pos (point)) refpos)
22450 (cond ((> pos (point)) (point))
22451 ((not (eq last-command this-command)) (point))
22454 ;; Being at an item and not looking at an the item means point
22455 ;; was previously moved to beginning of a visual line, which
22456 ;; doesn't contain the item. Therefore, do nothing special,
22458 (when (looking-at org-list-full-item-re)
22459 ;; Set special position at first white space character after
22460 ;; bullet, and check-box, if any.
22461 (let ((after-bullet
22462 (let ((box (match-end 3)))
22463 (if (not box) (match-end 1)
22464 (let ((after (char-after box)))
22465 (if (and after (= after ? )) (1+ box) box))))))
22466 ;; Special case: Move point to special position when
22467 ;; currently after it or at beginning of line.
22469 (when (or (> pos after-bullet) (= (point) pos))
22470 (goto-char after-bullet))
22471 ;; Reversed case: Move point to special position when
22472 ;; point was already at beginning of line and command is
22474 (when (and (= (point) pos) (eq last-command this-command))
22475 (goto-char after-bullet))))))))
22477 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22479 (defun org-end-of-line (&optional arg)
22480 "Go to the end of the line.
22481 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22482 tags on the first attempt, and only move to after the tags when
22483 the cursor is already beyond the end of the headline."
22485 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22486 org-special-ctrl-a/e))
22487 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22488 'end-of-visual-line)
22489 ((fboundp 'move-end-of-line) 'move-end-of-line)
22490 (t 'end-of-line))))
22491 (if (or (not special) arg) (call-interactively move-fun)
22492 (let* ((element (save-excursion (beginning-of-line)
22493 (org-element-at-point)))
22494 (type (org-element-type element)))
22496 ((memq type '(headline inlinetask))
22497 (let ((pos (point)))
22498 (beginning-of-line 1)
22499 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22501 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22502 (goto-char (match-beginning 1))
22503 (goto-char (match-end 0)))
22504 (if (or (< pos (match-end 0))
22505 (not (eq this-command last-command)))
22506 (goto-char (match-end 0))
22507 (goto-char (match-beginning 1))))
22508 (call-interactively move-fun))))
22509 ((org-element-property :hiddenp element)
22510 ;; If element is hidden, `move-end-of-line' would put point
22511 ;; after it. Use `end-of-line' to stay on current line.
22512 (call-interactively 'end-of-line))
22513 (t (call-interactively move-fun)))))
22514 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22516 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22517 (define-key org-mode-map "\C-e" 'org-end-of-line)
22519 (defun org-backward-sentence (&optional arg)
22520 "Go to beginning of sentence, or beginning of table field.
22521 This will call `backward-sentence' or `org-table-beginning-of-field',
22522 depending on context."
22525 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22526 (t (call-interactively 'backward-sentence))))
22528 (defun org-forward-sentence (&optional arg)
22529 "Go to end of sentence, or end of table field.
22530 This will call `forward-sentence' or `org-table-end-of-field',
22531 depending on context."
22534 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22535 (t (call-interactively 'forward-sentence))))
22537 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22538 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22540 (defun org-kill-line (&optional arg)
22541 "Kill line, to tags or end of line."
22544 ((or (not org-special-ctrl-k)
22546 (not (org-at-heading-p)))
22547 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22548 org-ctrl-k-protect-subtree)
22549 (if (or (eq org-ctrl-k-protect-subtree 'error)
22550 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22551 (error "C-k aborted - would kill hidden subtree")))
22552 (call-interactively
22553 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22554 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22555 (kill-region (point) (match-beginning 1))
22556 (org-set-tags nil t))
22557 (t (kill-region (point) (point-at-eol)))))
22559 (define-key org-mode-map "\C-k" 'org-kill-line)
22561 (defun org-yank (&optional arg)
22562 "Yank. If the kill is a subtree, treat it specially.
22563 This command will look at the current kill and check if is a single
22564 subtree, or a series of subtrees[1]. If it passes the test, and if the
22565 cursor is at the beginning of a line or after the stars of a currently
22566 empty headline, then the yank is handled specially. How exactly depends
22567 on the value of the following variables, both set by default.
22569 org-yank-folded-subtrees
22570 When set, the subtree(s) will be folded after insertion, but only
22571 if doing so would now swallow text after the yanked text.
22573 org-yank-adjusted-subtrees
22574 When set, the subtree will be promoted or demoted in order to
22575 fit into the local outline tree structure, which means that the level
22576 will be adjusted so that it becomes the smaller one of the two
22577 *visible* surrounding headings.
22579 Any prefix to this command will cause `yank' to be called directly with
22580 no special treatment. In particular, a simple \\[universal-argument] prefix \
22582 plainly yank the text as it is.
22584 \[1] The test checks if the first non-white line is a heading
22585 and if there are no other headings with fewer stars."
22587 (org-yank-generic 'yank arg))
22589 (defun org-yank-generic (command arg)
22590 "Perform some yank-like command.
22592 This function implements the behavior described in the `org-yank'
22593 documentation. However, it has been generalized to work for any
22594 interactive command with similar behavior."
22596 ;; pretend to be command COMMAND
22597 (setq this-command command)
22600 (call-interactively command)
22602 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22603 (and (org-kill-is-subtree-p)
22605 (and (looking-at "[ \t]*$")
22608 (buffer-substring (point-at-bol) (point)))))))
22611 ((and subtreep org-yank-folded-subtrees)
22612 (let ((beg (point))
22614 (if (and subtreep org-yank-adjusted-subtrees)
22615 (org-paste-subtree nil nil 'for-yank)
22616 (call-interactively command))
22620 (when (and (bolp) subtreep
22621 (not (setq swallowp
22622 (org-yank-folding-would-swallow-text beg end))))
22623 (org-with-limited-levels
22624 (or (looking-at org-outline-regexp)
22625 (re-search-forward org-outline-regexp-bol end t))
22626 (while (and (< (point) end) (looking-at org-outline-regexp))
22628 (org-cycle-show-empty-lines 'folded)
22629 (condition-case nil
22630 (outline-forward-same-level 1)
22631 (error (goto-char end))))))
22634 "Inserted text not folded because that would swallow text"))
22637 (skip-chars-forward " \t\n\r")
22638 (beginning-of-line 1)
22639 (push-mark beg 'nomsg)))
22640 ((and subtreep org-yank-adjusted-subtrees)
22641 (let ((beg (point-at-bol)))
22642 (org-paste-subtree nil nil 'for-yank)
22643 (push-mark beg 'nomsg)))
22645 (call-interactively command))))))
22647 (defun org-yank-folding-would-swallow-text (beg end)
22648 "Would hide-subtree at BEG swallow any text after END?"
22650 (org-with-limited-levels
22653 (when (or (looking-at org-outline-regexp)
22654 (re-search-forward org-outline-regexp-bol end t))
22655 (setq level (org-outline-level)))
22657 (skip-chars-forward " \t\r\n\v\f")
22659 (and (bolp) (looking-at org-outline-regexp)
22660 (<= (org-outline-level) level)))
22661 nil ; Nothing would be swallowed
22662 t))))) ; something would swallow
22664 (define-key org-mode-map "\C-y" 'org-yank)
22666 (defun org-truely-invisible-p ()
22667 "Check if point is at a character currently not visible.
22668 This version does not only check the character property, but also
22670 ;; Early versions of noutline don't have `outline-invisible-p'.
22671 (if (org-bound-and-true-p visible-mode)
22673 (outline-invisible-p)))
22675 (defun org-invisible-p2 ()
22676 "Check if point is at a character currently not visible."
22678 (if (and (eolp) (not (bobp))) (backward-char 1))
22679 ;; Early versions of noutline don't have `outline-invisible-p'.
22680 (outline-invisible-p)))
22682 (defun org-back-to-heading (&optional invisible-ok)
22683 "Call `outline-back-to-heading', but provide a better error message."
22684 (condition-case nil
22685 (outline-back-to-heading invisible-ok)
22686 (error (error "Before first headline at position %d in buffer %s"
22687 (point) (current-buffer)))))
22689 (defun org-before-first-heading-p ()
22690 "Before first heading?"
22693 (null (re-search-backward org-outline-regexp-bol nil t))))
22695 (defun org-at-heading-p (&optional ignored)
22696 (outline-on-heading-p t))
22697 ;; Compatibility alias with Org versions < 7.8.03
22698 (defalias 'org-on-heading-p 'org-at-heading-p)
22700 (defun org-at-comment-p nil
22701 "Is cursor in a line starting with a # character?"
22703 (beginning-of-line)
22704 (looking-at "^#")))
22706 (defun org-at-drawer-p nil
22707 "Is cursor at a drawer keyword?"
22709 (move-beginning-of-line 1)
22710 (looking-at org-drawer-regexp)))
22712 (defun org-at-block-p nil
22713 "Is cursor at a block keyword?"
22715 (move-beginning-of-line 1)
22716 (looking-at org-block-regexp)))
22718 (defun org-point-at-end-of-empty-headline ()
22719 "If point is at the end of an empty headline, return t, else nil.
22720 If the heading only contains a TODO keyword, it is still still considered
22722 (and (looking-at "[ \t]*$")
22723 (when org-todo-line-regexp
22725 (beginning-of-line 1)
22726 (let ((case-fold-search nil))
22727 (looking-at org-todo-line-regexp)
22728 (string= (match-string 3) ""))))))
22730 (defun org-at-heading-or-item-p ()
22731 (or (org-at-heading-p) (org-at-item-p)))
22733 (defun org-at-target-p ()
22734 (or (org-in-regexp org-radio-target-regexp)
22735 (org-in-regexp org-target-regexp)))
22736 ;; Compatibility alias with Org versions < 7.8.03
22737 (defalias 'org-on-target-p 'org-at-target-p)
22739 (defun org-up-heading-all (arg)
22740 "Move to the heading line of which the present line is a subheading.
22741 This function considers both visible and invisible heading lines.
22742 With argument, move up ARG levels."
22743 (if (fboundp 'outline-up-heading-all)
22744 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22745 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22747 (defun org-up-heading-safe ()
22748 "Move to the heading line of which the present line is a subheading.
22749 This version will not throw an error. It will return the level of the
22750 headline found, or nil if no higher level is found.
22752 Also, this function will be a lot faster than `outline-up-heading',
22753 because it relies on stars being the outline starters. This can really
22754 make a significant difference in outlines with very many siblings."
22755 (let (start-level re)
22756 (org-back-to-heading t)
22757 (setq start-level (funcall outline-level))
22758 (if (equal start-level 1)
22760 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22761 (if (re-search-backward re nil t)
22762 (funcall outline-level)))))
22764 (defun org-first-sibling-p ()
22765 "Is this heading the first child of its parents?"
22767 (let ((re org-outline-regexp-bol)
22769 (unless (org-at-heading-p t)
22770 (error "Not at a heading"))
22771 (setq level (funcall outline-level))
22773 (if (not (re-search-backward re nil t))
22775 (setq l (funcall outline-level))
22778 (defun org-goto-sibling (&optional previous)
22779 "Goto the next sibling, even if it is invisible.
22780 When PREVIOUS is set, go to the previous sibling instead. Returns t
22781 when a sibling was found. When none is found, return nil and don't
22783 (let ((fun (if previous 're-search-backward 're-search-forward))
22785 (re org-outline-regexp-bol)
22787 (when (condition-case nil (org-back-to-heading t) (error nil))
22788 (setq level (funcall outline-level))
22790 (or previous (forward-char 1))
22791 (while (funcall fun re nil t)
22792 (setq l (funcall outline-level))
22793 (when (< l level) (goto-char pos) (throw 'exit nil))
22794 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22798 (defun org-show-siblings ()
22799 "Show all siblings of the current headline."
22801 (while (org-goto-sibling) (org-flag-heading nil)))
22803 (while (org-goto-sibling 'previous)
22804 (org-flag-heading nil))))
22806 (defun org-goto-first-child ()
22807 "Goto the first child, even if it is invisible.
22808 Return t when a child was found. Otherwise don't move point and
22810 (let (level (pos (point)) (re org-outline-regexp-bol))
22811 (when (condition-case nil (org-back-to-heading t) (error nil))
22812 (setq level (outline-level))
22814 (if (and (re-search-forward re nil t) (> (outline-level) level))
22815 (progn (goto-char (match-beginning 0)) t)
22816 (goto-char pos) nil))))
22818 (defun org-show-hidden-entry ()
22819 "Show an entry where even the heading is hidden."
22823 (defun org-flag-heading (flag &optional entry)
22824 "Flag the current heading. FLAG non-nil means make invisible.
22825 When ENTRY is non-nil, show the entire entry."
22827 (org-back-to-heading t)
22828 ;; Check if we should show the entire entry
22833 (and (outline-next-heading)
22834 (org-flag-heading nil))))
22835 (outline-flag-region (max (point-min) (1- (point)))
22836 (save-excursion (outline-end-of-heading) (point))
22839 (defun org-get-next-sibling ()
22840 "Move to next heading of the same level, and return point.
22841 If there is no such heading, return nil.
22842 This is like outline-next-sibling, but invisible headings are ok."
22843 (let ((level (funcall outline-level)))
22844 (outline-next-heading)
22845 (while (and (not (eobp)) (> (funcall outline-level) level))
22846 (outline-next-heading))
22847 (if (or (eobp) (< (funcall outline-level) level))
22851 (defun org-get-last-sibling ()
22852 "Move to previous heading of the same level, and return point.
22853 If there is no such heading, return nil."
22854 (let ((opoint (point))
22855 (level (funcall outline-level)))
22856 (outline-previous-heading)
22857 (when (and (/= (point) opoint) (outline-on-heading-p t))
22858 (while (and (> (funcall outline-level) level)
22860 (outline-previous-heading))
22861 (if (< (funcall outline-level) level)
22865 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22866 "Goto to the end of a subtree."
22867 ;; This contains an exact copy of the original function, but it uses
22868 ;; `org-back-to-heading', to make it work also in invisible
22869 ;; trees. And is uses an invisible-ok argument.
22870 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22871 ;; Furthermore, when used inside Org, finding the end of a large subtree
22872 ;; with many children and grandchildren etc, this can be much faster
22873 ;; than the outline version.
22874 (org-back-to-heading invisible-ok)
22876 (level (funcall outline-level)))
22877 (if (and (derived-mode-p 'org-mode) (< level 1000))
22878 ;; A true heading (not a plain list item), in Org-mode
22879 ;; This means we can easily find the end by looking
22880 ;; only for the right number of stars. Using a regexp to do
22881 ;; this is so much faster than using a Lisp loop.
22882 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22884 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22885 ;; something else, do it the slow way
22886 (while (and (not (eobp))
22887 (or first (> (funcall outline-level) level)))
22889 (outline-next-heading)))
22891 (if (memq (preceding-char) '(?\n ?\^M))
22893 ;; Go to end of line before heading
22895 (if (memq (preceding-char) '(?\n ?\^M))
22896 ;; leave blank line before heading
22897 (forward-char -1))))))
22900 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22901 "Use Org version in org-mode, for dramatic speed-up."
22902 (if (derived-mode-p 'org-mode)
22904 (org-end-of-subtree nil t)
22905 (unless (eobp) (backward-char 1)))
22908 (defun org-end-of-meta-data-and-drawers ()
22909 "Jump to the first text after meta data and drawers in the current entry.
22910 This will move over empty lines, lines with planning time stamps,
22911 clocking lines, and drawers."
22912 (org-back-to-heading t)
22913 (let ((end (save-excursion (outline-next-heading) (point)))
22914 (re (concat "\\(" org-drawer-regexp "\\)"
22915 "\\|" "[ \t]*" org-keyword-time-regexp)))
22917 (while (re-search-forward re end t)
22918 (if (not (match-end 1))
22919 ;; empty or planning line
22921 ;; a drawer, find the end
22922 (re-search-forward "^[ \t]*:END:" end 'move)
22924 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22927 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22928 "Move forward to the ARG'th subheading at same level as this one.
22929 Stop at the first and last subheadings of a superior heading.
22930 Normally this only looks at visible headings, but when INVISIBLE-OK is
22931 non-nil it will also look at invisible ones."
22933 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22934 (if (and arg (< arg 0))
22935 (goto-char (point-min))
22936 (outline-next-heading))
22938 (let ((level (- (match-end 0) (match-beginning 0) 1))
22939 (f (if (and arg (< arg 0))
22940 're-search-backward
22941 're-search-forward))
22942 (count (if arg (abs arg) 1))
22944 (forward-char (if (and arg (< arg 0)) -1 1))
22945 (while (and (> count 0)
22946 (funcall f org-outline-regexp-bol nil 'move))
22947 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22948 (cond ((< l level) (setq count 0))
22952 (goto-char (line-beginning-position))
22953 (not (outline-invisible-p)))))
22954 (setq count (1- count))
22956 (setq result (point)))))))
22957 (goto-char result))
22958 (beginning-of-line 1)))
22960 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22961 "Move backward to the ARG'th subheading at same level as this one.
22962 Stop at the first and last subheadings of a superior heading."
22964 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22966 (defun org-next-block (arg &optional backward block-regexp)
22967 "Jump to the next block.
22968 With a prefix argument ARG, jump forward ARG many source blocks.
22969 When BACKWARD is non-nil, jump to the previous block.
22970 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22972 (let ((re (or block-regexp org-block-regexp))
22973 (re-search-fn (or (and backward 're-search-backward)
22974 're-search-forward)))
22975 (if (looking-at re) (forward-char 1))
22976 (condition-case nil
22977 (funcall re-search-fn re nil nil arg)
22978 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22979 (goto-char (match-beginning 0)) (org-show-context)))
22981 (defun org-previous-block (arg &optional block-regexp)
22982 "Jump to the previous block.
22983 With a prefix argument ARG, jump backward ARG many source blocks.
22984 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22986 (org-next-block arg t block-regexp))
22988 (defun org-forward-element ()
22989 "Move forward by one element.
22990 Move to the next element at the same level, when possible."
22992 (cond ((eobp) (user-error "Cannot move further down"))
22993 ((org-with-limited-levels (org-at-heading-p))
22994 (let ((origin (point)))
22995 (goto-char (org-end-of-subtree nil t))
22996 (unless (org-with-limited-levels (org-at-heading-p))
22998 (user-error "Cannot move further down"))))
23000 (let* ((elem (org-element-at-point))
23001 (end (org-element-property :end elem))
23002 (parent (org-element-property :parent elem)))
23003 (if (and parent (= (org-element-property :contents-end parent) end))
23004 (goto-char (org-element-property :end parent))
23005 (goto-char end))))))
23007 (defun org-backward-element ()
23008 "Move backward by one element.
23009 Move to the previous element at the same level, when possible."
23011 (cond ((bobp) (user-error "Cannot move further up"))
23012 ((org-with-limited-levels (org-at-heading-p))
23013 ;; At a headline, move to the previous one, if any, or stay
23015 (let ((origin (point)))
23016 (org-with-limited-levels (org-backward-heading-same-level 1))
23017 ;; When current headline has no sibling above, move to its
23019 (when (= (point) origin)
23020 (or (org-with-limited-levels (org-up-heading-safe))
23021 (progn (goto-char origin)
23022 (user-error "Cannot move further up"))))))
23024 (let* ((trail (org-element-at-point 'keep-trail))
23026 (prev-elem (nth 1 trail))
23027 (beg (org-element-property :begin elem)))
23029 ;; Move to beginning of current element if point isn't
23031 ((/= (point) beg) (goto-char beg))
23032 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23033 ((org-before-first-heading-p) (goto-char (point-min)))
23034 (t (org-back-to-heading)))))))
23036 (defun org-up-element ()
23037 "Move to upper element."
23039 (if (org-with-limited-levels (org-at-heading-p))
23040 (unless (org-up-heading-safe) (error "No surrounding element"))
23041 (let* ((elem (org-element-at-point))
23042 (parent (org-element-property :parent elem)))
23043 (if parent (goto-char (org-element-property :begin parent))
23044 (if (org-with-limited-levels (org-before-first-heading-p))
23045 (error "No surrounding element")
23046 (org-with-limited-levels (org-back-to-heading)))))))
23048 (defvar org-element-greater-elements)
23049 (defun org-down-element ()
23050 "Move to inner element."
23052 (let ((element (org-element-at-point)))
23054 ((memq (org-element-type element) '(plain-list table))
23055 (goto-char (org-element-property :contents-begin element))
23057 ((memq (org-element-type element) org-element-greater-elements)
23058 ;; If contents are hidden, first disclose them.
23059 (when (org-element-property :hiddenp element) (org-cycle))
23060 (goto-char (or (org-element-property :contents-begin element)
23061 (error "No content for this element"))))
23062 (t (error "No inner element")))))
23064 (defun org-drag-element-backward ()
23065 "Move backward element at point."
23067 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23068 (let* ((trail (org-element-at-point 'keep-trail))
23070 (prev-elem (nth 1 trail)))
23071 ;; Error out if no previous element or previous element is
23072 ;; a parent of the current one.
23073 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23074 (error "Cannot drag element backward")
23075 (let ((pos (point)))
23076 (org-element-swap-A-B prev-elem elem)
23077 (goto-char (+ (org-element-property :begin prev-elem)
23078 (- pos (org-element-property :begin elem)))))))))
23080 (defun org-drag-element-forward ()
23081 "Move forward element at point."
23083 (let* ((pos (point))
23084 (elem (org-element-at-point)))
23085 (when (= (point-max) (org-element-property :end elem))
23086 (error "Cannot drag element forward"))
23087 (goto-char (org-element-property :end elem))
23088 (let ((next-elem (org-element-at-point)))
23089 (when (or (org-element-nested-p elem next-elem)
23090 (and (eq (org-element-type next-elem) 'headline)
23091 (not (eq (org-element-type elem) 'headline))))
23093 (error "Cannot drag element forward"))
23094 ;; Compute new position of point: it's shifted by NEXT-ELEM
23095 ;; body's length (without final blanks) and by the length of
23096 ;; blanks between ELEM and NEXT-ELEM.
23097 (let ((size-next (- (save-excursion
23098 (goto-char (org-element-property :end next-elem))
23099 (skip-chars-backward " \r\t\n")
23101 ;; Small correction if buffer doesn't end
23102 ;; with a newline character.
23103 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23104 (org-element-property :begin next-elem)))
23105 (size-blank (- (org-element-property :end elem)
23107 (goto-char (org-element-property :end elem))
23108 (skip-chars-backward " \r\t\n")
23111 (org-element-swap-A-B elem next-elem)
23112 (goto-char (+ pos size-next size-blank))))))
23114 (defun org-drag-line-forward (arg)
23115 "Drag the line at point ARG lines forward."
23117 (dotimes (n (abs arg))
23118 (let ((c (current-column)))
23121 (beginning-of-line 2)
23122 (transpose-lines 1)
23123 (beginning-of-line 0))
23124 (transpose-lines 1)
23125 (beginning-of-line -1))
23126 (org-move-to-column c))))
23128 (defun org-drag-line-backward (arg)
23129 "Drag the line at point ARG lines backward."
23131 (org-drag-line-forward (- arg)))
23133 (defun org-mark-element ()
23134 "Put point at beginning of this element, mark at end.
23136 Interactively, if this command is repeated or (in Transient Mark
23137 mode) if the mark is active, it marks the next element after the
23138 ones already marked."
23140 (let (deactivate-mark)
23141 (if (and (org-called-interactively-p 'any)
23142 (or (and (eq last-command this-command) (mark t))
23143 (and transient-mark-mode mark-active)))
23147 (goto-char (org-element-property :end (org-element-at-point)))))
23148 (let ((element (org-element-at-point)))
23150 (push-mark (org-element-property :end element) t t)
23151 (goto-char (org-element-property :begin element))))))
23153 (defun org-narrow-to-element ()
23154 "Narrow buffer to current element."
23156 (let ((elem (org-element-at-point)))
23158 ((eq (car elem) 'headline)
23160 (org-element-property :begin elem)
23161 (org-element-property :end elem)))
23162 ((memq (car elem) org-element-greater-elements)
23164 (org-element-property :contents-begin elem)
23165 (org-element-property :contents-end elem)))
23168 (org-element-property :begin elem)
23169 (org-element-property :end elem))))))
23171 (defun org-transpose-element ()
23172 "Transpose current and previous elements, keeping blank lines between.
23173 Point is moved after both elements."
23175 (org-skip-whitespace)
23176 (let ((end (org-element-property :end (org-element-at-point))))
23177 (org-drag-element-backward)
23180 (defun org-unindent-buffer ()
23181 "Un-indent the visible part of the buffer.
23182 Relative indentation (between items, inside blocks, etc.) isn't
23185 (unless (eq major-mode 'org-mode)
23186 (error "Cannot un-indent a buffer not in Org mode"))
23187 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23188 unindent-tree ; For byte-compiler.
23194 (if (memq (org-element-type element) '(headline section))
23195 (funcall unindent-tree (org-element-contents element))
23199 (org-element-property :begin element)
23200 (org-element-property :end element))
23201 (org-do-remove-indentation)))))
23202 (reverse contents))))))
23203 (funcall unindent-tree (org-element-contents parse-tree))))
23205 (defun org-show-subtree ()
23206 "Show everything after this heading at deeper levels."
23208 (outline-flag-region
23211 (org-end-of-subtree t t))
23214 (defun org-show-entry ()
23215 "Show the body directly following this heading.
23216 Show the heading too, if it is currently invisible."
23219 (condition-case nil
23221 (org-back-to-heading t)
23222 (outline-flag-region
23223 (max (point-min) (1- (point)))
23225 (if (re-search-forward
23226 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23227 (match-beginning 1)
23230 (org-cycle-hide-drawers 'children))
23233 (defun org-make-options-regexp (kwds &optional extra)
23234 "Make a regular expression for keyword lines."
23237 (mapconcat 'regexp-quote kwds "\\|")
23238 (if extra (concat "\\|" extra))
23239 "\\):[ \t]*\\(.*\\)"))
23241 ;; Make isearch reveal the necessary context
23242 (defun org-isearch-end ()
23243 "Reveal context after isearch exits."
23244 (when isearch-success ; only if search was successful
23245 (if (featurep 'xemacs)
23246 ;; Under XEmacs, the hook is run in the correct place,
23247 ;; we directly show the context.
23248 (org-show-context 'isearch)
23249 ;; In Emacs the hook runs *before* restoring the overlays.
23250 ;; So we have to use a one-time post-command-hook to do this.
23251 ;; (Emacs 22 has a special variable, see function `org-mode')
23252 (unless (and (boundp 'isearch-mode-end-hook-quit)
23253 isearch-mode-end-hook-quit)
23254 ;; Only when the isearch was not quitted.
23255 (org-add-hook 'post-command-hook 'org-isearch-post-command
23257 (org-fix-ellipsis-at-bol)))
23259 (defun org-isearch-post-command ()
23260 "Remove self from hook, and show context."
23261 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23262 (org-show-context 'isearch))
23265 ;;;; Integration with and fixes for other packages
23269 (defvar org-imenu-markers nil
23270 "All markers currently used by Imenu.")
23271 (make-variable-buffer-local 'org-imenu-markers)
23273 (defun org-imenu-new-marker (&optional pos)
23274 "Return a new marker for use by Imenu, and remember the marker."
23275 (let ((m (make-marker)))
23276 (move-marker m (or pos (point)))
23277 (push m org-imenu-markers)
23280 (defun org-imenu-get-tree ()
23281 "Produce the index for Imenu."
23282 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23283 (setq org-imenu-markers nil)
23284 (let* ((n org-imenu-depth)
23285 (re (concat "^" (org-get-limited-outline-regexp)))
23286 (subs (make-vector (1+ n) nil))
23288 m level head0 head)
23292 (goto-char (point-max))
23293 (while (re-search-backward re nil t)
23294 (setq level (org-reduced-level (funcall outline-level)))
23295 (when (and (<= level n)
23296 (looking-at org-complex-heading-regexp)
23297 (setq head0 (org-match-string-no-properties 4)))
23298 (setq head (org-link-display-format head0)
23299 m (org-imenu-new-marker))
23300 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23301 (if (>= level last-level)
23302 (push (cons head m) (aref subs level))
23303 (push (cons head (aref subs (1+ level))) (aref subs level))
23304 (loop for i from (1+ level) to n do (aset subs i nil)))
23305 (setq last-level level)))))
23308 (eval-after-load "imenu"
23310 (add-hook 'imenu-after-jump-hook
23312 (if (derived-mode-p 'org-mode)
23313 (org-show-context 'org-goto))))))
23315 (defun org-link-display-format (link)
23316 "Replace a link with its the description.
23317 If there is no description, use the link target."
23319 (if (string-match org-bracket-link-analytic-regexp link)
23320 (replace-match (if (match-end 5)
23321 (match-string 5 link)
23322 (concat (match-string 1 link)
23323 (match-string 3 link)))
23327 (defun org-toggle-link-display ()
23328 "Toggle the literal or descriptive display of links."
23330 (if org-descriptive-links
23331 (progn (org-remove-from-invisibility-spec '(org-link))
23332 (org-restart-font-lock)
23333 (setq org-descriptive-links nil))
23334 (progn (add-to-invisibility-spec '(org-link))
23335 (org-restart-font-lock)
23336 (setq org-descriptive-links t))))
23338 ;; Speedbar support
23340 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23341 "Overlay marking the agenda restriction line in speedbar.")
23342 (overlay-put org-speedbar-restriction-lock-overlay
23343 'face 'org-agenda-restriction-lock)
23344 (overlay-put org-speedbar-restriction-lock-overlay
23345 'help-echo "Agendas are currently limited to this item.")
23346 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23348 (defun org-speedbar-set-agenda-restriction ()
23349 "Restrict future agenda commands to the location at point in speedbar.
23350 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23352 (require 'org-agenda)
23353 (let (p m tp np dir txt)
23355 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23357 (setq m (get-text-property p 'org-imenu-marker))
23358 (with-current-buffer (marker-buffer m)
23360 (org-agenda-set-restriction-lock 'subtree)))
23361 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23362 'speedbar-function 'speedbar-find-file))
23363 (setq tp (previous-single-property-change
23364 (1+ p) 'speedbar-function)
23365 np (next-single-property-change
23366 tp 'speedbar-function)
23367 dir (speedbar-line-directory)
23368 txt (buffer-substring-no-properties (or tp (point-min))
23369 (or np (point-max))))
23370 (with-current-buffer (find-file-noselect
23371 (let ((default-directory dir))
23372 (expand-file-name txt)))
23373 (unless (derived-mode-p 'org-mode)
23374 (error "Cannot restrict to non-Org-mode file"))
23375 (org-agenda-set-restriction-lock 'file)))
23376 (t (error "Don't know how to restrict Org-mode's agenda")))
23377 (move-overlay org-speedbar-restriction-lock-overlay
23378 (point-at-bol) (point-at-eol))
23379 (setq current-prefix-arg nil)
23380 (org-agenda-maybe-redo)))
23382 (eval-after-load "speedbar"
23384 (speedbar-add-supported-extension ".org")
23385 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23386 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23387 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23388 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23389 (add-hook 'speedbar-visiting-tag-hook
23390 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23392 ;;; Fixes and Hacks for problems with other packages
23394 ;; Make flyspell not check words in links, to not mess up our keymap
23395 (defvar org-element-affiliated-keywords) ; From org-element.el
23396 (defvar org-element-block-name-alist) ; From org-element.el
23397 (defun org-mode-flyspell-verify ()
23398 "Don't let flyspell put overlays at active buttons, or on
23399 {todo,all-time,additional-option-like}-keywords."
23400 (require 'org-element) ; For `org-element-affiliated-keywords'
23401 (let ((pos (max (1- (point)) (point-min)))
23402 (word (thing-at-point 'word)))
23403 (and (not (get-text-property pos 'keymap))
23404 (not (get-text-property pos 'org-no-flyspell))
23405 (not (member word org-todo-keywords-1))
23406 (not (member word org-all-time-keywords))
23407 (not (member word org-options-keywords))
23408 (not (member word (mapcar 'car org-startup-options)))
23409 (not (member-ignore-case word org-element-affiliated-keywords))
23410 (not (member-ignore-case word (org-get-export-keywords)))
23411 (not (member-ignore-case
23412 word (mapcar 'car org-element-block-name-alist)))
23413 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23415 (defun org-remove-flyspell-overlays-in (beg end)
23416 "Remove flyspell overlays in region."
23417 (and (org-bound-and-true-p flyspell-mode)
23418 (fboundp 'flyspell-delete-region-overlays)
23419 (flyspell-delete-region-overlays beg end))
23420 (add-text-properties beg end '(org-no-flyspell t)))
23422 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23423 (eval-after-load "bookmark"
23424 '(if (boundp 'bookmark-after-jump-hook)
23425 ;; We can use the hook
23426 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23427 ;; Hook not available, use advice
23428 (defadvice bookmark-jump (after org-make-visible activate)
23429 "Make the position visible."
23430 (org-bookmark-jump-unhide))))
23432 ;; Make sure saveplace shows the location if it was hidden
23433 (eval-after-load "saveplace"
23434 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23435 "Make the position visible."
23436 (org-bookmark-jump-unhide)))
23438 ;; Make sure ecb shows the location if it was hidden
23439 (eval-after-load "ecb"
23440 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23441 "Make hierarchy visible when jumping into location from ECB tree buffer."
23442 (if (derived-mode-p 'org-mode)
23443 (org-show-context))))
23445 (defun org-bookmark-jump-unhide ()
23446 "Unhide the current position, to show the bookmark location."
23447 (and (derived-mode-p 'org-mode)
23448 (or (outline-invisible-p)
23449 (save-excursion (goto-char (max (point-min) (1- (point))))
23450 (outline-invisible-p)))
23451 (org-show-context 'bookmark-jump)))
23453 ;; Make session.el ignore our circular variable
23454 (eval-after-load "session"
23455 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23457 ;;;; Experimental code
23459 (defun org-closed-in-range ()
23460 "Sparse tree of items closed in a certain time range.
23461 Still experimental, may disappear in the future."
23463 ;; Get the time interval from the user.
23464 (let* ((time1 (org-float-time
23465 (org-read-date nil 'to-time nil "Starting date: ")))
23466 (time2 (org-float-time
23467 (org-read-date nil 'to-time nil "End date:")))
23468 ;; callback function
23469 (callback (lambda ()
23472 (apply 'encode-time
23473 (org-parse-time-string
23474 (match-string 1))))))
23475 ;; check if time in interval
23476 (and (>= time time1) (<= time time2))))))
23477 ;; make tree, check each match with the callback
23478 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23484 (run-hooks 'org-load-hook)
23486 ;;; org.el ends here