Speed up paragraph filling
[org-mode.git] / lisp / org.el
blob974bc14f0f5bc1b9cde65304002171be947d680b
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
114 (unless (boundp 'calendar-view-holidays-initially-flag)
115 (org-defvaralias 'calendar-view-holidays-initially-flag
116 'view-calendar-holidays-initially))
117 (unless (boundp 'calendar-view-diary-initially-flag)
118 (org-defvaralias 'calendar-view-diary-initially-flag
119 'view-diary-entries-initially))
120 (unless (boundp 'diary-fancy-buffer)
121 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
123 (declare-function org-add-archive-files "org-archive" (files))
125 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
126 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
127 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
128 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
129 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
132 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
133 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
134 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
135 (declare-function org-clock-update-time-maybe "org-clock" ())
136 (declare-function org-clocktable-shift "org-clock" (dir n))
138 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
139 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
140 (declare-function orgtbl-mode "org-table" (&optional arg))
141 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
142 (declare-function org-beamer-mode "ox-beamer" ())
143 (declare-function org-table-blank-field "org-table" ())
144 (declare-function org-table-edit-field "org-table" (arg))
145 (declare-function org-table-insert-row "org-table" (&optional arg))
146 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
147 (declare-function org-table-set-constants "org-table" ())
148 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-add-archive-files "org-archive" (files))
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
153 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
154 (declare-function org-agenda-redo "org-agenda" (&optional all))
155 (declare-function org-table-align "org-table" ())
156 (declare-function org-table-begin "org-table" (&optional table-type))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-end "org-table" (&optional table-type))
159 (declare-function org-table-end-of-field "org-table" (&optional n))
160 (declare-function org-table-insert-row "org-table" (&optional arg))
161 (declare-function org-table-paste-rectangle "org-table" ())
162 (declare-function org-table-maybe-eval-formula "org-table" ())
163 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function org-element-at-point "org-element" ())
166 (declare-function org-element-cache-reset "org-element" (&optional all))
167 (declare-function org-element-cache-refresh "org-element" (pos))
168 (declare-function org-element-contents "org-element" (element))
169 (declare-function org-element-context "org-element" (&optional element))
170 (declare-function org-element-interpret-data "org-element"
171 (data &optional parent))
172 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
173 (declare-function org-element-parse-buffer "org-element"
174 (&optional granularity visible-only))
175 (declare-function org-element-property "org-element" (property element))
176 (declare-function org-element-put-property "org-element"
177 (element property value))
178 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
179 (declare-function org-element-parse-buffer "org-element"
180 (&optional granularity visible-only))
181 (declare-function org-element-type "org-element" (element))
183 (defsubst org-uniquify (list)
184 "Non-destructively remove duplicate elements from LIST."
185 (let ((res (copy-sequence list))) (delete-dups res)))
187 (defsubst org-get-at-bol (property)
188 "Get text property PROPERTY at the beginning of line."
189 (get-text-property (point-at-bol) property))
191 (defsubst org-trim (s)
192 "Remove whitespace at the beginning and the end of string S."
193 (replace-regexp-in-string
194 "\\`[ \t\n\r]+" ""
195 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
197 ;; load languages based on value of `org-babel-load-languages'
198 (defvar org-babel-load-languages)
200 ;;;###autoload
201 (defun org-babel-do-load-languages (sym value)
202 "Load the languages defined in `org-babel-load-languages'."
203 (set-default sym value)
204 (mapc (lambda (pair)
205 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
206 (if active
207 (progn
208 (require (intern (concat "ob-" lang))))
209 (progn
210 (funcall 'fmakunbound
211 (intern (concat "org-babel-execute:" lang)))
212 (funcall 'fmakunbound
213 (intern (concat "org-babel-expand-body:" lang)))))))
214 org-babel-load-languages))
216 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
217 ;;;###autoload
218 (defun org-babel-load-file (file &optional compile)
219 "Load Emacs Lisp source code blocks in the Org-mode FILE.
220 This function exports the source code using `org-babel-tangle'
221 and then loads the resulting file using `load-file'. With prefix
222 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
223 file to byte-code before it is loaded."
224 (interactive "fFile to load: \nP")
225 (let* ((age (lambda (file)
226 (float-time
227 (time-subtract (current-time)
228 (nth 5 (or (file-attributes (file-truename file))
229 (file-attributes file)))))))
230 (base-name (file-name-sans-extension file))
231 (exported-file (concat base-name ".el")))
232 ;; tangle if the org-mode file is newer than the elisp file
233 (unless (and (file-exists-p exported-file)
234 (> (funcall age file) (funcall age exported-file)))
235 (setq exported-file
236 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
237 (message "%s %s"
238 (if compile
239 (progn (byte-compile-file exported-file 'load)
240 "Compiled and loaded")
241 (progn (load-file exported-file) "Loaded"))
242 exported-file)))
244 (defcustom org-babel-load-languages '((emacs-lisp . t))
245 "Languages which can be evaluated in Org-mode buffers.
246 This list can be used to load support for any of the languages
247 below, note that each language will depend on a different set of
248 system executables and/or Emacs modes. When a language is
249 \"loaded\", then code blocks in that language can be evaluated
250 with `org-babel-execute-src-block' bound by default to C-c
251 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
252 be set to remove code block evaluation from the C-c C-c
253 keybinding. By default only Emacs Lisp (which has no
254 requirements) is loaded."
255 :group 'org-babel
256 :set 'org-babel-do-load-languages
257 :version "24.1"
258 :type '(alist :tag "Babel Languages"
259 :key-type
260 (choice
261 (const :tag "Awk" awk)
262 (const :tag "C" C)
263 (const :tag "R" R)
264 (const :tag "Asymptote" asymptote)
265 (const :tag "Calc" calc)
266 (const :tag "Clojure" clojure)
267 (const :tag "CSS" css)
268 (const :tag "Ditaa" ditaa)
269 (const :tag "Dot" dot)
270 (const :tag "Emacs Lisp" emacs-lisp)
271 (const :tag "Fortran" fortran)
272 (const :tag "Gnuplot" gnuplot)
273 (const :tag "Haskell" haskell)
274 (const :tag "IO" io)
275 (const :tag "J" J)
276 (const :tag "Java" java)
277 (const :tag "Javascript" js)
278 (const :tag "LaTeX" latex)
279 (const :tag "Ledger" ledger)
280 (const :tag "Lilypond" lilypond)
281 (const :tag "Lisp" lisp)
282 (const :tag "Makefile" makefile)
283 (const :tag "Maxima" maxima)
284 (const :tag "Matlab" matlab)
285 (const :tag "Mscgen" mscgen)
286 (const :tag "Ocaml" ocaml)
287 (const :tag "Octave" octave)
288 (const :tag "Org" org)
289 (const :tag "Perl" perl)
290 (const :tag "Pico Lisp" picolisp)
291 (const :tag "PlantUML" plantuml)
292 (const :tag "Python" python)
293 (const :tag "Ruby" ruby)
294 (const :tag "Sass" sass)
295 (const :tag "Scala" scala)
296 (const :tag "Scheme" scheme)
297 (const :tag "Screen" screen)
298 (const :tag "Shell Script" shell)
299 (const :tag "Shen" shen)
300 (const :tag "Sql" sql)
301 (const :tag "Sqlite" sqlite)
302 (const :tag "ebnf2ps" ebnf2ps))
303 :value-type (boolean :tag "Activate" :value t)))
305 ;;;; Customization variables
306 (defcustom org-clone-delete-id nil
307 "Remove ID property of clones of a subtree.
308 When non-nil, clones of a subtree don't inherit the ID property.
309 Otherwise they inherit the ID property with a new unique
310 identifier."
311 :type 'boolean
312 :version "24.1"
313 :group 'org-id)
315 ;;; Version
316 (org-check-version)
318 ;;;###autoload
319 (defun org-version (&optional here full message)
320 "Show the org-mode version.
321 Interactively, or when MESSAGE is non-nil, show it in echo area.
322 With prefix argument, or when HERE is non-nil, insert it at point.
323 In non-interactive uses, a reduced version string is output unless
324 FULL is given."
325 (interactive (list current-prefix-arg t (not current-prefix-arg)))
326 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
327 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
328 (load-suffixes (list ".el"))
329 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
330 (org-trash (or
331 (and (fboundp 'org-release) (fboundp 'org-git-version))
332 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
333 (load-suffixes save-load-suffixes)
334 (org-version (org-release))
335 (git-version (org-git-version))
336 (version (format "Org-mode version %s (%s @ %s)"
337 org-version
338 git-version
339 (if org-install-dir
340 (if (string= org-dir org-install-dir)
341 org-install-dir
342 (concat "mixed installation! " org-install-dir " and " org-dir))
343 "org-loaddefs.el can not be found!")))
344 (version1 (if full version org-version)))
345 (when here (insert version1))
346 (when message (message "%s" version1))
347 version1))
349 (defconst org-version (org-version))
352 ;;; Syntax Constants
354 ;;;; Block
356 (defconst org-block-regexp
357 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
358 "Regular expression for hiding blocks.")
360 (defconst org-dblock-start-re
361 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
362 "Matches the start line of a dynamic block, with parameters.")
364 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
365 "Matches the end of a dynamic block.")
367 ;;;; Clock and Planning
369 (defconst org-clock-string "CLOCK:"
370 "String used as prefix for timestamps clocking work hours on an item.")
372 (defconst org-closed-string "CLOSED:"
373 "String used as the prefix for timestamps logging closing a TODO entry.")
375 (defconst org-deadline-string "DEADLINE:"
376 "String to mark deadline entries.
377 A deadline is this string, followed by a time stamp. Should be a word,
378 terminated by a colon. You can insert a schedule keyword and
379 a timestamp with \\[org-deadline].")
381 (defconst org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 A schedule is this string, followed by a time stamp. Should be a word,
384 terminated by a colon. You can insert a schedule keyword and
385 a timestamp with \\[org-schedule].")
387 (defconst org-planning-or-clock-line-re
388 (concat "^[ \t]*"
389 (regexp-opt
390 (list org-clock-string org-closed-string org-deadline-string
391 org-scheduled-string)
393 "Matches a line with planning or clock info.
394 Matched keyword is in group 1.")
396 ;;;; Drawer
398 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
399 "Matches first or last line of a hidden block.
400 Group 1 contains drawer's name or \"END\".")
402 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
403 "Regular expression matching the first line of a property drawer.")
405 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
406 "Regular expression matching the last line of a property drawer.")
408 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
409 "Regular expression matching the first line of a clock drawer.")
411 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
412 "Regular expression matching the last line of a clock drawer.")
414 (defconst org-property-drawer-re
415 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
416 org-property-end-re "\\)\n?")
417 "Matches an entire property drawer.")
419 (defconst org-clock-drawer-re
420 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
421 org-clock-drawer-end-re "\\)\n?")
422 "Matches an entire clock drawer.")
424 ;;;; Headline
426 (defconst org-heading-keyword-regexp-format
427 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
428 "Printf format for a regexp matching a headline with some keyword.
429 This regexp will match the headline of any node which has the
430 exact keyword that is put into the format. The keyword isn't in
431 any group by default, but the stars and the body are.")
433 (defconst org-heading-keyword-maybe-regexp-format
434 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
435 "Printf format for a regexp matching a headline, possibly with some keyword.
436 This regexp can match any headline with the specified keyword, or
437 without a keyword. The keyword isn't in any group by default,
438 but the stars and the body are.")
440 (defconst org-archive-tag "ARCHIVE"
441 "The tag that marks a subtree as archived.
442 An archived subtree does not open during visibility cycling, and does
443 not contribute to the agenda listings.")
445 (defconst org-comment-string "COMMENT"
446 "Entries starting with this keyword will never be exported.
447 An entry can be toggled between COMMENT and normal with
448 \\[org-toggle-comment].")
451 ;;;; LaTeX Environments and Fragments
453 (defconst org-latex-regexps
454 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
455 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
456 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
457 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
458 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
459 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
460 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
461 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
462 "Regular expressions for matching embedded LaTeX.")
464 ;;;; Node Property
466 (defconst org-effort-property "Effort"
467 "The property that is being used to keep track of effort estimates.
468 Effort estimates given in this property need to have the format H:MM.")
470 ;;;; Table
472 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
473 "Detect an org-type or table-type table.")
475 (defconst org-table-line-regexp "^[ \t]*|"
476 "Detect an org-type table line.")
478 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
479 "Detect an org-type table line.")
481 (defconst org-table-hline-regexp "^[ \t]*|-"
482 "Detect an org-type table hline.")
484 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
485 "Detect a table-type table hline.")
487 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
488 "Detect the first line outside a table when searching from within it.
489 This works for both table types.")
491 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
492 "Detect a #+TBLFM line.")
494 ;;;; Timestamp
496 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
497 "Regular expression for fast time stamp matching.")
499 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
500 "Regular expression for fast time stamp matching.")
502 (defconst org-ts-regexp0
503 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
504 "Regular expression matching time strings for analysis.
505 This one does not require the space after the date, so it can be used
506 on a string that terminates immediately after the date.")
508 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
509 "Regular expression matching time strings for analysis.")
511 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
512 "Regular expression matching time stamps, with groups.")
514 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
515 "Regular expression matching time stamps (also [..]), with groups.")
517 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
518 "Regular expression matching a time stamp range.")
520 (defconst org-tr-regexp-both
521 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
522 "Regular expression matching a time stamp range.")
524 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
525 org-ts-regexp "\\)?")
526 "Regular expression matching a time stamp or time stamp range.")
528 (defconst org-tsr-regexp-both
529 (concat org-ts-regexp-both "\\(--?-?"
530 org-ts-regexp-both "\\)?")
531 "Regular expression matching a time stamp or time stamp range.
532 The time stamps may be either active or inactive.")
534 (defconst org-repeat-re
535 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
536 "Regular expression for specifying repeated events.
537 After a match, group 1 contains the repeat expression.")
539 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
540 "Formats for `format-time-string' which are used for time stamps.")
543 ;;; The custom variables
545 (defgroup org nil
546 "Outline-based notes management and organizer."
547 :tag "Org"
548 :group 'outlines
549 :group 'calendar)
551 (defcustom org-mode-hook nil
552 "Mode hook for Org-mode, run after the mode was turned on."
553 :group 'org
554 :type 'hook)
556 (defcustom org-load-hook nil
557 "Hook that is run after org.el has been loaded."
558 :group 'org
559 :type 'hook)
561 (defcustom org-log-buffer-setup-hook nil
562 "Hook that is run after an Org log buffer is created."
563 :group 'org
564 :version "24.1"
565 :type 'hook)
567 (defvar org-modules) ; defined below
568 (defvar org-modules-loaded nil
569 "Have the modules been loaded already?")
571 (defun org-load-modules-maybe (&optional force)
572 "Load all extensions listed in `org-modules'."
573 (when (or force (not org-modules-loaded))
574 (mapc (lambda (ext)
575 (condition-case nil (require ext)
576 (error (message "Problems while trying to load feature `%s'" ext))))
577 org-modules)
578 (setq org-modules-loaded t)))
580 (defun org-set-modules (var value)
581 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
582 (set var value)
583 (when (featurep 'org)
584 (org-load-modules-maybe 'force)
585 (org-element-cache-reset 'all)))
587 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
588 "Modules that should always be loaded together with org.el.
590 If a description starts with <C>, the file is not part of Emacs
591 and loading it will require that you have downloaded and properly
592 installed the Org mode distribution.
594 You can also use this system to load external packages (i.e. neither Org
595 core modules, nor modules from the CONTRIB directory). Just add symbols
596 to the end of the list. If the package is called org-xyz.el, then you need
597 to add the symbol `xyz', and the package must have a call to:
599 \(provide 'org-xyz)
601 For export specific modules, see also `org-export-backends'."
602 :group 'org
603 :set 'org-set-modules
604 :version "24.4"
605 :package-version '(Org . "8.0")
606 :type
607 '(set :greedy t
608 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
609 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
610 (const :tag " crypt: Encryption of subtrees" org-crypt)
611 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
612 (const :tag " docview: Links to doc-view buffers" org-docview)
613 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
614 (const :tag " habit: Track your consistency with habits" org-habit)
615 (const :tag " id: Global IDs for identifying entries" org-id)
616 (const :tag " info: Links to Info nodes" org-info)
617 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
618 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
619 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
620 (const :tag " mouse: Additional mouse support" org-mouse)
621 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
622 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
623 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
625 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
626 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
627 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
628 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
629 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
630 (const :tag "C collector: Collect properties into tables" org-collector)
631 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
632 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
633 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
634 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
635 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
636 (const :tag "C eval: Include command output as text" org-eval)
637 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
638 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
639 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
640 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
641 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
642 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
643 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
644 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
645 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
646 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
647 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
648 (const :tag "C mew: Links to Mew folders/messages" org-mew)
649 (const :tag "C mtags: Support for muse-like tags" org-mtags)
650 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
651 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
652 (const :tag "C registry: A registry for Org-mode links" org-registry)
653 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
654 (const :tag "C secretary: Team management with org-mode" org-secretary)
655 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
656 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
657 (const :tag "C track: Keep up with Org-mode development" org-track)
658 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
659 (const :tag "C vm: Links to VM folders/messages" org-vm)
660 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
661 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
662 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
664 (defvar org-export--registered-backends) ; From ox.el.
665 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
666 (declare-function org-export-backend-name "ox" (backend))
667 (defcustom org-export-backends '(ascii html icalendar latex)
668 "List of export back-ends that should be always available.
670 If a description starts with <C>, the file is not part of Emacs
671 and loading it will require that you have downloaded and properly
672 installed the Org mode distribution.
674 Unlike to `org-modules', libraries in this list will not be
675 loaded along with Org, but only once the export framework is
676 needed.
678 This variable needs to be set before org.el is loaded. If you
679 need to make a change while Emacs is running, use the customize
680 interface or run the following code, where VAL stands for the new
681 value of the variable, after updating it:
683 \(progn
684 \(setq org-export--registered-backends
685 \(org-remove-if-not
686 \(lambda (backend)
687 \(let ((name (org-export-backend-name backend)))
688 \(or (memq name val)
689 \(catch 'parentp
690 \(dolist (b val)
691 \(and (org-export-derived-backend-p b name)
692 \(throw 'parentp t)))))))
693 org-export--registered-backends))
694 \(let ((new-list (mapcar 'org-export-backend-name
695 org-export--registered-backends)))
696 \(dolist (backend val)
697 \(cond
698 \((not (load (format \"ox-%s\" backend) t t))
699 \(message \"Problems while trying to load export back-end `%s'\"
700 backend))
701 \((not (memq backend new-list)) (push backend new-list))))
702 \(set-default 'org-export-backends new-list)))
704 Adding a back-end to this list will also pull the back-end it
705 depends on, if any."
706 :group 'org
707 :group 'org-export
708 :version "24.4"
709 :package-version '(Org . "8.0")
710 :initialize 'custom-initialize-set
711 :set (lambda (var val)
712 (if (not (featurep 'ox)) (set-default var val)
713 ;; Any back-end not required anymore (not present in VAL and not
714 ;; a parent of any back-end in the new value) is removed from the
715 ;; list of registered back-ends.
716 (setq org-export--registered-backends
717 (org-remove-if-not
718 (lambda (backend)
719 (let ((name (org-export-backend-name backend)))
720 (or (memq name val)
721 (catch 'parentp
722 (dolist (b val)
723 (and (org-export-derived-backend-p b name)
724 (throw 'parentp t)))))))
725 org-export--registered-backends))
726 ;; Now build NEW-LIST of both new back-ends and required
727 ;; parents.
728 (let ((new-list (mapcar 'org-export-backend-name
729 org-export--registered-backends)))
730 (dolist (backend val)
731 (cond
732 ((not (load (format "ox-%s" backend) t t))
733 (message "Problems while trying to load export back-end `%s'"
734 backend))
735 ((not (memq backend new-list)) (push backend new-list))))
736 ;; Set VAR to that list with fixed dependencies.
737 (set-default var new-list))))
738 :type '(set :greedy t
739 (const :tag " ascii Export buffer to ASCII format" ascii)
740 (const :tag " beamer Export buffer to Beamer presentation" beamer)
741 (const :tag " html Export buffer to HTML format" html)
742 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
743 (const :tag " latex Export buffer to LaTeX format" latex)
744 (const :tag " man Export buffer to MAN format" man)
745 (const :tag " md Export buffer to Markdown format" md)
746 (const :tag " odt Export buffer to ODT format" odt)
747 (const :tag " org Export buffer to Org format" org)
748 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
749 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
750 (const :tag "C deck Export buffer to deck.js presentations" deck)
751 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
752 (const :tag "C groff Export buffer to Groff format" groff)
753 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
754 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
755 (const :tag "C s5 Export buffer to s5 presentations" s5)
756 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
758 (eval-after-load 'ox
759 '(mapc
760 (lambda (backend)
761 (condition-case nil (require (intern (format "ox-%s" backend)))
762 (error (message "Problems while trying to load export back-end `%s'"
763 backend))))
764 org-export-backends))
766 (defcustom org-support-shift-select nil
767 "Non-nil means make shift-cursor commands select text when possible.
769 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
770 start selecting a region, or enlarge regions started in this way.
771 In Org-mode, in special contexts, these same keys are used for
772 other purposes, important enough to compete with shift selection.
773 Org tries to balance these needs by supporting `shift-select-mode'
774 outside these special contexts, under control of this variable.
776 The default of this variable is nil, to avoid confusing behavior. Shifted
777 cursor keys will then execute Org commands in the following contexts:
778 - on a headline, changing TODO state (left/right) and priority (up/down)
779 - on a time stamp, changing the time
780 - in a plain list item, changing the bullet type
781 - in a property definition line, switching between allowed values
782 - in the BEGIN line of a clock table (changing the time block).
783 Outside these contexts, the commands will throw an error.
785 When this variable is t and the cursor is not in a special
786 context, Org-mode will support shift-selection for making and
787 enlarging regions. To make this more effective, the bullet
788 cycling will no longer happen anywhere in an item line, but only
789 if the cursor is exactly on the bullet.
791 If you set this variable to the symbol `always', then the keys
792 will not be special in headlines, property lines, and item lines,
793 to make shift selection work there as well. If this is what you
794 want, you can use the following alternative commands: `C-c C-t'
795 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
796 can be used to switch TODO sets, `C-c -' to cycle item bullet
797 types, and properties can be edited by hand or in column view.
799 However, when the cursor is on a timestamp, shift-cursor commands
800 will still edit the time stamp - this is just too good to give up.
802 XEmacs user should have this variable set to nil, because
803 `shift-select-mode' is in Emacs 23 or later only."
804 :group 'org
805 :type '(choice
806 (const :tag "Never" nil)
807 (const :tag "When outside special context" t)
808 (const :tag "Everywhere except timestamps" always)))
810 (defcustom org-loop-over-headlines-in-active-region nil
811 "Shall some commands act upon headlines in the active region?
813 When set to `t', some commands will be performed in all headlines
814 within the active region.
816 When set to `start-level', some commands will be performed in all
817 headlines within the active region, provided that these headlines
818 are of the same level than the first one.
820 When set to a string, those commands will be performed on the
821 matching headlines within the active region. Such string must be
822 a tags/property/todo match as it is used in the agenda tags view.
824 The list of commands is: `org-schedule', `org-deadline',
825 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
826 `org-archive-to-archive-sibling'. The archiving commands skip
827 already archived entries."
828 :type '(choice (const :tag "Don't loop" nil)
829 (const :tag "All headlines in active region" t)
830 (const :tag "In active region, headlines at the same level than the first one" start-level)
831 (string :tag "Tags/Property/Todo matcher"))
832 :version "24.1"
833 :group 'org-todo
834 :group 'org-archive)
836 (defgroup org-startup nil
837 "Options concerning startup of Org-mode."
838 :tag "Org Startup"
839 :group 'org)
841 (defcustom org-startup-folded t
842 "Non-nil means entering Org-mode will switch to OVERVIEW.
843 This can also be configured on a per-file basis by adding one of
844 the following lines anywhere in the buffer:
846 #+STARTUP: fold (or `overview', this is equivalent)
847 #+STARTUP: nofold (or `showall', this is equivalent)
848 #+STARTUP: content
849 #+STARTUP: showeverything
851 By default, this option is ignored when Org opens agenda files
852 for the first time. If you want the agenda to honor the startup
853 option, set `org-agenda-inhibit-startup' to nil."
854 :group 'org-startup
855 :type '(choice
856 (const :tag "nofold: show all" nil)
857 (const :tag "fold: overview" t)
858 (const :tag "content: all headlines" content)
859 (const :tag "show everything, even drawers" showeverything)))
861 (defcustom org-startup-truncated t
862 "Non-nil means entering Org-mode will set `truncate-lines'.
863 This is useful since some lines containing links can be very long and
864 uninteresting. Also tables look terrible when wrapped."
865 :group 'org-startup
866 :type 'boolean)
868 (defcustom org-startup-indented nil
869 "Non-nil means turn on `org-indent-mode' on startup.
870 This can also be configured on a per-file basis by adding one of
871 the following lines anywhere in the buffer:
873 #+STARTUP: indent
874 #+STARTUP: noindent"
875 :group 'org-structure
876 :type '(choice
877 (const :tag "Not" nil)
878 (const :tag "Globally (slow on startup in large files)" t)))
880 (defcustom org-use-sub-superscripts t
881 "Non-nil means interpret \"_\" and \"^\" for display.
883 If you want to control how Org exports those characters, see
884 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
885 used to be an alias for `org-export-with-sub-superscripts' in
886 Org <8.0, it is not anymore.
888 When this option is turned on, you can use TeX-like syntax for
889 sub- and superscripts within the buffer. Several characters after
890 \"_\" or \"^\" will be considered as a single item - so grouping
891 with {} is normally not needed. For example, the following things
892 will be parsed as single sub- or superscripts:
894 10^24 or 10^tau several digits will be considered 1 item.
895 10^-12 or 10^-tau a leading sign with digits or a word
896 x^2-y^3 will be read as x^2 - y^3, because items are
897 terminated by almost any nonword/nondigit char.
898 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
900 Still, ambiguity is possible. So when in doubt, use {} to enclose
901 the sub/superscript. If you set this variable to the symbol `{}',
902 the braces are *required* in order to trigger interpretations as
903 sub/superscript. This can be helpful in documents that need \"_\"
904 frequently in plain text."
905 :group 'org-startup
906 :version "24.4"
907 :package-version '(Org . "8.0")
908 :type '(choice
909 (const :tag "Always interpret" t)
910 (const :tag "Only with braces" {})
911 (const :tag "Never interpret" nil)))
913 (defcustom org-startup-with-beamer-mode nil
914 "Non-nil means turn on `org-beamer-mode' on startup.
915 This can also be configured on a per-file basis by adding one of
916 the following lines anywhere in the buffer:
918 #+STARTUP: beamer"
919 :group 'org-startup
920 :version "24.1"
921 :type 'boolean)
923 (defcustom org-startup-align-all-tables nil
924 "Non-nil means align all tables when visiting a file.
925 This is useful when the column width in tables is forced with <N> cookies
926 in table fields. Such tables will look correct only after the first re-align.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
929 #+STARTUP: align
930 #+STARTUP: noalign"
931 :group 'org-startup
932 :type 'boolean)
934 (defcustom org-startup-with-inline-images nil
935 "Non-nil means show inline images when loading a new Org file.
936 This can also be configured on a per-file basis by adding one of
937 the following lines anywhere in the buffer:
938 #+STARTUP: inlineimages
939 #+STARTUP: noinlineimages"
940 :group 'org-startup
941 :version "24.1"
942 :type 'boolean)
944 (defcustom org-startup-with-latex-preview nil
945 "Non-nil means preview LaTeX fragments when loading a new Org file.
947 This can also be configured on a per-file basis by adding one of
948 the following lines anywhere in the buffer:
949 #+STARTUP: latexpreview
950 #+STARTUP: nolatexpreview"
951 :group 'org-startup
952 :version "24.4"
953 :package-version '(Org . "8.0")
954 :type 'boolean)
956 (defcustom org-insert-mode-line-in-empty-file nil
957 "Non-nil means insert the first line setting Org-mode in empty files.
958 When the function `org-mode' is called interactively in an empty file, this
959 normally means that the file name does not automatically trigger Org-mode.
960 To ensure that the file will always be in Org-mode in the future, a
961 line enforcing Org-mode will be inserted into the buffer, if this option
962 has been set."
963 :group 'org-startup
964 :type 'boolean)
966 (defcustom org-replace-disputed-keys nil
967 "Non-nil means use alternative key bindings for some keys.
968 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
969 These keys are also used by other packages like shift-selection-mode'
970 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
971 If you want to use Org-mode together with one of these other modes,
972 or more generally if you would like to move some Org-mode commands to
973 other keys, set this variable and configure the keys with the variable
974 `org-disputed-keys'.
976 This option is only relevant at load-time of Org-mode, and must be set
977 *before* org.el is loaded. Changing it requires a restart of Emacs to
978 become effective."
979 :group 'org-startup
980 :type 'boolean)
982 (defcustom org-use-extra-keys nil
983 "Non-nil means use extra key sequence definitions for certain commands.
984 This happens automatically if you run XEmacs or if `window-system'
985 is nil. This variable lets you do the same manually. You must
986 set it before loading org.
988 Example: on Carbon Emacs 22 running graphically, with an external
989 keyboard on a Powerbook, the default way of setting M-left might
990 not work for either Alt or ESC. Setting this variable will make
991 it work for ESC."
992 :group 'org-startup
993 :type 'boolean)
995 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
997 (defcustom org-disputed-keys
998 '(([(shift up)] . [(meta p)])
999 ([(shift down)] . [(meta n)])
1000 ([(shift left)] . [(meta -)])
1001 ([(shift right)] . [(meta +)])
1002 ([(control shift right)] . [(meta shift +)])
1003 ([(control shift left)] . [(meta shift -)]))
1004 "Keys for which Org-mode and other modes compete.
1005 This is an alist, cars are the default keys, second element specifies
1006 the alternative to use when `org-replace-disputed-keys' is t.
1008 Keys can be specified in any syntax supported by `define-key'.
1009 The value of this option takes effect only at Org-mode's startup,
1010 therefore you'll have to restart Emacs to apply it after changing."
1011 :group 'org-startup
1012 :type 'alist)
1014 (defun org-key (key)
1015 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1016 Or return the original if not disputed.
1017 Also apply the translations defined in `org-xemacs-key-equivalents'."
1018 (when org-replace-disputed-keys
1019 (let* ((nkey (key-description key))
1020 (x (org-find-if (lambda (x)
1021 (equal (key-description (car x)) nkey))
1022 org-disputed-keys)))
1023 (setq key (if x (cdr x) key))))
1024 (when (featurep 'xemacs)
1025 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1026 key)
1028 (defun org-find-if (predicate seq)
1029 (catch 'exit
1030 (while seq
1031 (if (funcall predicate (car seq))
1032 (throw 'exit (car seq))
1033 (pop seq)))))
1035 (defun org-defkey (keymap key def)
1036 "Define a key, possibly translated, as returned by `org-key'."
1037 (define-key keymap (org-key key) def))
1039 (defcustom org-ellipsis nil
1040 "The ellipsis to use in the Org-mode outline.
1041 When nil, just use the standard three dots.
1042 When a string, use that string instead.
1043 When a face, use the standard 3 dots, but with the specified face.
1044 The change affects only Org-mode (which will then use its own display table).
1045 Changing this requires executing \\[org-mode] in a buffer to become
1046 effective."
1047 :group 'org-startup
1048 :type '(choice (const :tag "Default" nil)
1049 (face :tag "Face" :value org-warning)
1050 (string :tag "String" :value "...#")))
1052 (defvar org-display-table nil
1053 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1055 (defgroup org-keywords nil
1056 "Keywords in Org-mode."
1057 :tag "Org Keywords"
1058 :group 'org)
1060 (defcustom org-closed-keep-when-no-todo nil
1061 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1062 :group 'org-todo
1063 :group 'org-keywords
1064 :version "24.4"
1065 :package-version '(Org . "8.0")
1066 :type 'boolean)
1068 (defgroup org-structure nil
1069 "Options concerning the general structure of Org-mode files."
1070 :tag "Org Structure"
1071 :group 'org)
1073 (defgroup org-reveal-location nil
1074 "Options about how to make context of a location visible."
1075 :tag "Org Reveal Location"
1076 :group 'org-structure)
1078 (defconst org-context-choice
1079 '(choice
1080 (const :tag "Always" t)
1081 (const :tag "Never" nil)
1082 (repeat :greedy t :tag "Individual contexts"
1083 (cons
1084 (choice :tag "Context"
1085 (const agenda)
1086 (const org-goto)
1087 (const occur-tree)
1088 (const tags-tree)
1089 (const link-search)
1090 (const mark-goto)
1091 (const bookmark-jump)
1092 (const isearch)
1093 (const default))
1094 (boolean))))
1095 "Contexts for the reveal options.")
1097 (defcustom org-show-hierarchy-above '((default . t))
1098 "Non-nil means show full hierarchy when revealing a location.
1099 Org-mode often shows locations in an org-mode file which might have
1100 been invisible before. When this is set, the hierarchy of headings
1101 above the exposed location is shown.
1102 Turning this off for example for sparse trees makes them very compact.
1103 Instead of t, this can also be an alist specifying this option for different
1104 contexts. Valid contexts are
1105 agenda when exposing an entry from the agenda
1106 org-goto when using the command `org-goto' on key C-c C-j
1107 occur-tree when using the command `org-occur' on key C-c /
1108 tags-tree when constructing a sparse tree based on tags matches
1109 link-search when exposing search matches associated with a link
1110 mark-goto when exposing the jump goal of a mark
1111 bookmark-jump when exposing a bookmark location
1112 isearch when exiting from an incremental search
1113 default default for all contexts not set explicitly"
1114 :group 'org-reveal-location
1115 :type org-context-choice)
1117 (defcustom org-show-following-heading '((default . nil))
1118 "Non-nil means show following heading when revealing a location.
1119 Org-mode often shows locations in an org-mode file which might have
1120 been invisible before. When this is set, the heading following the
1121 match is shown.
1122 Turning this off for example for sparse trees makes them very compact,
1123 but makes it harder to edit the location of the match. In such a case,
1124 use the command \\[org-reveal] to show more context.
1125 Instead of t, this can also be an alist specifying this option for different
1126 contexts. See `org-show-hierarchy-above' for valid contexts."
1127 :group 'org-reveal-location
1128 :type org-context-choice)
1130 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1131 "Non-nil means show all sibling heading when revealing a location.
1132 Org-mode often shows locations in an org-mode file which might have
1133 been invisible before. When this is set, the sibling of the current entry
1134 heading are all made visible. If `org-show-hierarchy-above' is t,
1135 the same happens on each level of the hierarchy above the current entry.
1137 By default this is on for the isearch context, off for all other contexts.
1138 Turning this off for example for sparse trees makes them very compact,
1139 but makes it harder to edit the location of the match. In such a case,
1140 use the command \\[org-reveal] to show more context.
1141 Instead of t, this can also be an alist specifying this option for different
1142 contexts. See `org-show-hierarchy-above' for valid contexts."
1143 :group 'org-reveal-location
1144 :type org-context-choice
1145 :version "24.4"
1146 :package-version '(Org . "8.0"))
1148 (defcustom org-show-entry-below '((default . nil))
1149 "Non-nil means show the entry below a headline when revealing a location.
1150 Org-mode often shows locations in an org-mode file which might have
1151 been invisible before. When this is set, the text below the headline that is
1152 exposed is also shown.
1154 By default this is off for all contexts.
1155 Instead of t, this can also be an alist specifying this option for different
1156 contexts. See `org-show-hierarchy-above' for valid contexts."
1157 :group 'org-reveal-location
1158 :type org-context-choice)
1160 (defcustom org-indirect-buffer-display 'other-window
1161 "How should indirect tree buffers be displayed?
1162 This applies to indirect buffers created with the commands
1163 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1164 Valid values are:
1165 current-window Display in the current window
1166 other-window Just display in another window.
1167 dedicated-frame Create one new frame, and re-use it each time.
1168 new-frame Make a new frame each time. Note that in this case
1169 previously-made indirect buffers are kept, and you need to
1170 kill these buffers yourself."
1171 :group 'org-structure
1172 :group 'org-agenda-windows
1173 :type '(choice
1174 (const :tag "In current window" current-window)
1175 (const :tag "In current frame, other window" other-window)
1176 (const :tag "Each time a new frame" new-frame)
1177 (const :tag "One dedicated frame" dedicated-frame)))
1179 (defcustom org-use-speed-commands nil
1180 "Non-nil means activate single letter commands at beginning of a headline.
1181 This may also be a function to test for appropriate locations where speed
1182 commands should be active.
1184 For example, to activate speed commands when the point is on any
1185 star at the beginning of the headline, you can do this:
1187 (setq org-use-speed-commands
1188 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1189 :group 'org-structure
1190 :type '(choice
1191 (const :tag "Never" nil)
1192 (const :tag "At beginning of headline stars" t)
1193 (function)))
1195 (defcustom org-speed-commands-user nil
1196 "Alist of additional speed commands.
1197 This list will be checked before `org-speed-commands-default'
1198 when the variable `org-use-speed-commands' is non-nil
1199 and when the cursor is at the beginning of a headline.
1200 The car if each entry is a string with a single letter, which must
1201 be assigned to `self-insert-command' in the global map.
1202 The cdr is either a command to be called interactively, a function
1203 to be called, or a form to be evaluated.
1204 An entry that is just a list with a single string will be interpreted
1205 as a descriptive headline that will be added when listing the speed
1206 commands in the Help buffer using the `?' speed command."
1207 :group 'org-structure
1208 :type '(repeat :value ("k" . ignore)
1209 (choice :value ("k" . ignore)
1210 (list :tag "Descriptive Headline" (string :tag "Headline"))
1211 (cons :tag "Letter and Command"
1212 (string :tag "Command letter")
1213 (choice
1214 (function)
1215 (sexp))))))
1217 (defcustom org-bookmark-names-plist
1218 '(:last-capture "org-capture-last-stored"
1219 :last-refile "org-refile-last-stored"
1220 :last-capture-marker "org-capture-last-stored-marker")
1221 "Names for bookmarks automatically set by some Org commands.
1222 This can provide strings as names for a number of bookmarks Org sets
1223 automatically. The following keys are currently implemented:
1224 :last-capture
1225 :last-capture-marker
1226 :last-refile
1227 When a key does not show up in the property list, the corresponding bookmark
1228 is not set."
1229 :group 'org-structure
1230 :type 'plist)
1232 (defgroup org-cycle nil
1233 "Options concerning visibility cycling in Org-mode."
1234 :tag "Org Cycle"
1235 :group 'org-structure)
1237 (defcustom org-cycle-skip-children-state-if-no-children t
1238 "Non-nil means skip CHILDREN state in entries that don't have any."
1239 :group 'org-cycle
1240 :type 'boolean)
1242 (defcustom org-cycle-max-level nil
1243 "Maximum level which should still be subject to visibility cycling.
1244 Levels higher than this will, for cycling, be treated as text, not a headline.
1245 When `org-odd-levels-only' is set, a value of N in this variable actually
1246 means 2N-1 stars as the limiting headline.
1247 When nil, cycle all levels.
1248 Note that the limiting level of cycling is also influenced by
1249 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1250 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1251 than its value."
1252 :group 'org-cycle
1253 :type '(choice
1254 (const :tag "No limit" nil)
1255 (integer :tag "Maximum level")))
1257 (defcustom org-hide-block-startup nil
1258 "Non-nil means entering Org-mode will fold all blocks.
1259 This can also be set in on a per-file basis with
1261 #+STARTUP: hideblocks
1262 #+STARTUP: showblocks"
1263 :group 'org-startup
1264 :group 'org-cycle
1265 :type 'boolean)
1267 (defcustom org-cycle-global-at-bob nil
1268 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1269 This makes it possible to do global cycling without having to use S-TAB or
1270 \\[universal-argument] TAB. For this special case to work, the first line
1271 of the buffer must not be a headline -- it may be empty or some other text.
1272 When used in this way, `org-cycle-hook' is disabled temporarily to make
1273 sure the cursor stays at the beginning of the buffer. When this option is
1274 nil, don't do anything special at the beginning of the buffer."
1275 :group 'org-cycle
1276 :type 'boolean)
1278 (defcustom org-cycle-level-after-item/entry-creation t
1279 "Non-nil means cycle entry level or item indentation in new empty entries.
1281 When the cursor is at the end of an empty headline, i.e., with only stars
1282 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1283 and then all possible ancestor states, before returning to the original state.
1284 This makes data entry extremely fast: M-RET to create a new headline,
1285 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1287 When the cursor is at the end of an empty plain list item, one TAB will
1288 make it a subitem, two or more tabs will back up to make this an item
1289 higher up in the item hierarchy."
1290 :group 'org-cycle
1291 :type 'boolean)
1293 (defcustom org-cycle-emulate-tab t
1294 "Where should `org-cycle' emulate TAB.
1295 nil Never
1296 white Only in completely white lines
1297 whitestart Only at the beginning of lines, before the first non-white char
1298 t Everywhere except in headlines
1299 exc-hl-bol Everywhere except at the start of a headline
1300 If TAB is used in a place where it does not emulate TAB, the current subtree
1301 visibility is cycled."
1302 :group 'org-cycle
1303 :type '(choice (const :tag "Never" nil)
1304 (const :tag "Only in completely white lines" white)
1305 (const :tag "Before first char in a line" whitestart)
1306 (const :tag "Everywhere except in headlines" t)
1307 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1309 (defcustom org-cycle-separator-lines 2
1310 "Number of empty lines needed to keep an empty line between collapsed trees.
1311 If you leave an empty line between the end of a subtree and the following
1312 headline, this empty line is hidden when the subtree is folded.
1313 Org-mode will leave (exactly) one empty line visible if the number of
1314 empty lines is equal or larger to the number given in this variable.
1315 So the default 2 means at least 2 empty lines after the end of a subtree
1316 are needed to produce free space between a collapsed subtree and the
1317 following headline.
1319 If the number is negative, and the number of empty lines is at least -N,
1320 all empty lines are shown.
1322 Special case: when 0, never leave empty lines in collapsed view."
1323 :group 'org-cycle
1324 :type 'integer)
1325 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1327 (defcustom org-pre-cycle-hook nil
1328 "Hook that is run before visibility cycling is happening.
1329 The function(s) in this hook must accept a single argument which indicates
1330 the new state that will be set right after running this hook. The
1331 argument is a symbol. Before a global state change, it can have the values
1332 `overview', `content', or `all'. Before a local state change, it can have
1333 the values `folded', `children', or `subtree'."
1334 :group 'org-cycle
1335 :type 'hook)
1337 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1338 org-cycle-hide-drawers
1339 org-cycle-hide-inline-tasks
1340 org-cycle-show-empty-lines
1341 org-optimize-window-after-visibility-change)
1342 "Hook that is run after `org-cycle' has changed the buffer visibility.
1343 The function(s) in this hook must accept a single argument which indicates
1344 the new state that was set by the most recent `org-cycle' command. The
1345 argument is a symbol. After a global state change, it can have the values
1346 `overview', `contents', or `all'. After a local state change, it can have
1347 the values `folded', `children', or `subtree'."
1348 :group 'org-cycle
1349 :type 'hook)
1351 (defgroup org-edit-structure nil
1352 "Options concerning structure editing in Org-mode."
1353 :tag "Org Edit Structure"
1354 :group 'org-structure)
1356 (defcustom org-odd-levels-only nil
1357 "Non-nil means skip even levels and only use odd levels for the outline.
1358 This has the effect that two stars are being added/taken away in
1359 promotion/demotion commands. It also influences how levels are
1360 handled by the exporters.
1361 Changing it requires restart of `font-lock-mode' to become effective
1362 for fontification also in regions already fontified.
1363 You may also set this on a per-file basis by adding one of the following
1364 lines to the buffer:
1366 #+STARTUP: odd
1367 #+STARTUP: oddeven"
1368 :group 'org-edit-structure
1369 :group 'org-appearance
1370 :type 'boolean)
1372 (defcustom org-adapt-indentation t
1373 "Non-nil means adapt indentation to outline node level.
1375 When this variable is set, Org assumes that you write outlines by
1376 indenting text in each node to align with the headline (after the stars).
1377 The following issues are influenced by this variable:
1379 - When this is set and the *entire* text in an entry is indented, the
1380 indentation is increased by one space in a demotion command, and
1381 decreased by one in a promotion command. If any line in the entry
1382 body starts with text at column 0, indentation is not changed at all.
1384 - Property drawers and planning information is inserted indented when
1385 this variable s set. When nil, they will not be indented.
1387 - TAB indents a line relative to context. The lines below a headline
1388 will be indented when this variable is set.
1390 Note that this is all about true indentation, by adding and removing
1391 space characters. See also `org-indent.el' which does level-dependent
1392 indentation in a virtual way, i.e. at display time in Emacs."
1393 :group 'org-edit-structure
1394 :type 'boolean)
1396 (defcustom org-special-ctrl-a/e nil
1397 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1399 When t, `C-a' will bring back the cursor to the beginning of the
1400 headline text, i.e. after the stars and after a possible TODO
1401 keyword. In an item, this will be the position after bullet and
1402 check-box, if any. When the cursor is already at that position,
1403 another `C-a' will bring it to the beginning of the line.
1405 `C-e' will jump to the end of the headline, ignoring the presence
1406 of tags in the headline. A second `C-e' will then jump to the
1407 true end of the line, after any tags. This also means that, when
1408 this variable is non-nil, `C-e' also will never jump beyond the
1409 end of the heading of a folded section, i.e. not after the
1410 ellipses.
1412 When set to the symbol `reversed', the first `C-a' or `C-e' works
1413 normally, going to the true line boundary first. Only a directly
1414 following, identical keypress will bring the cursor to the
1415 special positions.
1417 This may also be a cons cell where the behavior for `C-a' and
1418 `C-e' is set separately."
1419 :group 'org-edit-structure
1420 :type '(choice
1421 (const :tag "off" nil)
1422 (const :tag "on: after stars/bullet and before tags first" t)
1423 (const :tag "reversed: true line boundary first" reversed)
1424 (cons :tag "Set C-a and C-e separately"
1425 (choice :tag "Special C-a"
1426 (const :tag "off" nil)
1427 (const :tag "on: after stars/bullet first" t)
1428 (const :tag "reversed: before stars/bullet first" reversed))
1429 (choice :tag "Special C-e"
1430 (const :tag "off" nil)
1431 (const :tag "on: before tags first" t)
1432 (const :tag "reversed: after tags first" reversed)))))
1433 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1435 (defcustom org-special-ctrl-k nil
1436 "Non-nil means `C-k' will behave specially in headlines.
1437 When nil, `C-k' will call the default `kill-line' command.
1438 When t, the following will happen while the cursor is in the headline:
1440 - When the cursor is at the beginning of a headline, kill the entire
1441 line and possible the folded subtree below the line.
1442 - When in the middle of the headline text, kill the headline up to the tags.
1443 - When after the headline text, kill the tags."
1444 :group 'org-edit-structure
1445 :type 'boolean)
1447 (defcustom org-ctrl-k-protect-subtree nil
1448 "Non-nil means, do not delete a hidden subtree with C-k.
1449 When set to the symbol `error', simply throw an error when C-k is
1450 used to kill (part-of) a headline that has hidden text behind it.
1451 Any other non-nil value will result in a query to the user, if it is
1452 OK to kill that hidden subtree. When nil, kill without remorse."
1453 :group 'org-edit-structure
1454 :version "24.1"
1455 :type '(choice
1456 (const :tag "Do not protect hidden subtrees" nil)
1457 (const :tag "Protect hidden subtrees with a security query" t)
1458 (const :tag "Never kill a hidden subtree with C-k" error)))
1460 (defcustom org-special-ctrl-o t
1461 "Non-nil means, make `C-o' insert a row in tables."
1462 :group 'org-edit-structure
1463 :type 'boolean)
1465 (defcustom org-catch-invisible-edits nil
1466 "Check if in invisible region before inserting or deleting a character.
1467 Valid values are:
1469 nil Do not check, so just do invisible edits.
1470 error Throw an error and do nothing.
1471 show Make point visible, and do the requested edit.
1472 show-and-error Make point visible, then throw an error and abort the edit.
1473 smart Make point visible, and do insertion/deletion if it is
1474 adjacent to visible text and the change feels predictable.
1475 Never delete a previously invisible character or add in the
1476 middle or right after an invisible region. Basically, this
1477 allows insertion and backward-delete right before ellipses.
1478 FIXME: maybe in this case we should not even show?"
1479 :group 'org-edit-structure
1480 :version "24.1"
1481 :type '(choice
1482 (const :tag "Do not check" nil)
1483 (const :tag "Throw error when trying to edit" error)
1484 (const :tag "Unhide, but do not do the edit" show-and-error)
1485 (const :tag "Show invisible part and do the edit" show)
1486 (const :tag "Be smart and do the right thing" smart)))
1488 (defcustom org-yank-folded-subtrees t
1489 "Non-nil means when yanking subtrees, fold them.
1490 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1491 it starts with a heading and all other headings in it are either children
1492 or siblings, then fold all the subtrees. However, do this only if no
1493 text after the yank would be swallowed into a folded tree by this action."
1494 :group 'org-edit-structure
1495 :type 'boolean)
1497 (defcustom org-yank-adjusted-subtrees nil
1498 "Non-nil means when yanking subtrees, adjust the level.
1499 With this setting, `org-paste-subtree' is used to insert the subtree, see
1500 this function for details."
1501 :group 'org-edit-structure
1502 :type 'boolean)
1504 (defcustom org-M-RET-may-split-line '((default . t))
1505 "Non-nil means M-RET will split the line at the cursor position.
1506 When nil, it will go to the end of the line before making a
1507 new line.
1508 You may also set this option in a different way for different
1509 contexts. Valid contexts are:
1511 headline when creating a new headline
1512 item when creating a new item
1513 table in a table field
1514 default the value to be used for all contexts not explicitly
1515 customized"
1516 :group 'org-structure
1517 :group 'org-table
1518 :type '(choice
1519 (const :tag "Always" t)
1520 (const :tag "Never" nil)
1521 (repeat :greedy t :tag "Individual contexts"
1522 (cons
1523 (choice :tag "Context"
1524 (const headline)
1525 (const item)
1526 (const table)
1527 (const default))
1528 (boolean)))))
1531 (defcustom org-insert-heading-respect-content nil
1532 "Non-nil means insert new headings after the current subtree.
1533 When nil, the new heading is created directly after the current line.
1534 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1535 this variable on for the duration of the command."
1536 :group 'org-structure
1537 :type 'boolean)
1539 (defcustom org-blank-before-new-entry '((heading . auto)
1540 (plain-list-item . auto))
1541 "Should `org-insert-heading' leave a blank line before new heading/item?
1542 The value is an alist, with `heading' and `plain-list-item' as CAR,
1543 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1544 which case Org will look at the surrounding headings/items and try to
1545 make an intelligent decision whether to insert a blank line or not.
1547 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1548 the setting here is ignored and no empty line is inserted to avoid breaking
1549 the list structure."
1550 :group 'org-edit-structure
1551 :type '(list
1552 (cons (const heading)
1553 (choice (const :tag "Never" nil)
1554 (const :tag "Always" t)
1555 (const :tag "Auto" auto)))
1556 (cons (const plain-list-item)
1557 (choice (const :tag "Never" nil)
1558 (const :tag "Always" t)
1559 (const :tag "Auto" auto)))))
1561 (defcustom org-insert-heading-hook nil
1562 "Hook being run after inserting a new heading."
1563 :group 'org-edit-structure
1564 :type 'hook)
1566 (defcustom org-enable-fixed-width-editor t
1567 "Non-nil means lines starting with \":\" are treated as fixed-width.
1568 This currently only means they are never auto-wrapped.
1569 When nil, such lines will be treated like ordinary lines."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-goto-auto-isearch t
1574 "Non-nil means typing characters in `org-goto' starts incremental search.
1575 When nil, you can use these keybindings to navigate the buffer:
1577 q Quit the org-goto interface
1578 n Go to the next visible heading
1579 p Go to the previous visible heading
1580 f Go one heading forward on same level
1581 b Go one heading backward on same level
1582 u Go one heading up"
1583 :group 'org-edit-structure
1584 :type 'boolean)
1586 (defgroup org-sparse-trees nil
1587 "Options concerning sparse trees in Org-mode."
1588 :tag "Org Sparse Trees"
1589 :group 'org-structure)
1591 (defcustom org-highlight-sparse-tree-matches t
1592 "Non-nil means highlight all matches that define a sparse tree.
1593 The highlights will automatically disappear the next time the buffer is
1594 changed by an edit command."
1595 :group 'org-sparse-trees
1596 :type 'boolean)
1598 (defcustom org-remove-highlights-with-change t
1599 "Non-nil means any change to the buffer will remove temporary highlights.
1600 Such highlights are created by `org-occur' and `org-clock-display'.
1601 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1602 The highlights created by `org-toggle-latex-fragment' always need
1603 `C-c C-x C-l' to be removed."
1604 :group 'org-sparse-trees
1605 :group 'org-time
1606 :type 'boolean)
1609 (defcustom org-occur-hook '(org-first-headline-recenter)
1610 "Hook that is run after `org-occur' has constructed a sparse tree.
1611 This can be used to recenter the window to show as much of the structure
1612 as possible."
1613 :group 'org-sparse-trees
1614 :type 'hook)
1616 (defgroup org-imenu-and-speedbar nil
1617 "Options concerning imenu and speedbar in Org-mode."
1618 :tag "Org Imenu and Speedbar"
1619 :group 'org-structure)
1621 (defcustom org-imenu-depth 2
1622 "The maximum level for Imenu access to Org-mode headlines.
1623 This also applied for speedbar access."
1624 :group 'org-imenu-and-speedbar
1625 :type 'integer)
1627 (defgroup org-table nil
1628 "Options concerning tables in Org-mode."
1629 :tag "Org Table"
1630 :group 'org)
1632 (defcustom org-enable-table-editor 'optimized
1633 "Non-nil means lines starting with \"|\" are handled by the table editor.
1634 When nil, such lines will be treated like ordinary lines.
1636 When equal to the symbol `optimized', the table editor will be optimized to
1637 do the following:
1638 - Automatic overwrite mode in front of whitespace in table fields.
1639 This makes the structure of the table stay in tact as long as the edited
1640 field does not exceed the column width.
1641 - Minimize the number of realigns. Normally, the table is aligned each time
1642 TAB or RET are pressed to move to another field. With optimization this
1643 happens only if changes to a field might have changed the column width.
1644 Optimization requires replacing the functions `self-insert-command',
1645 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1646 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1647 very good at guessing when a re-align will be necessary, but you can always
1648 force one with \\[org-ctrl-c-ctrl-c].
1650 If you would like to use the optimized version in Org-mode, but the
1651 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1653 This variable can be used to turn on and off the table editor during a session,
1654 but in order to toggle optimization, a restart is required.
1656 See also the variable `org-table-auto-blank-field'."
1657 :group 'org-table
1658 :type '(choice
1659 (const :tag "off" nil)
1660 (const :tag "on" t)
1661 (const :tag "on, optimized" optimized)))
1663 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1664 (version<= emacs-version "24.1"))
1665 "Non-nil means cluster self-insert commands for undo when possible.
1666 If this is set, then, like in the Emacs command loop, 20 consecutive
1667 characters will be undone together.
1668 This is configurable, because there is some impact on typing performance."
1669 :group 'org-table
1670 :type 'boolean)
1672 (defcustom org-table-tab-recognizes-table.el t
1673 "Non-nil means TAB will automatically notice a table.el table.
1674 When it sees such a table, it moves point into it and - if necessary -
1675 calls `table-recognize-table'."
1676 :group 'org-table-editing
1677 :type 'boolean)
1679 (defgroup org-link nil
1680 "Options concerning links in Org-mode."
1681 :tag "Org Link"
1682 :group 'org)
1684 (defvar org-link-abbrev-alist-local nil
1685 "Buffer-local version of `org-link-abbrev-alist', which see.
1686 The value of this is taken from the #+LINK lines.")
1687 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1689 (defcustom org-link-abbrev-alist nil
1690 "Alist of link abbreviations.
1691 The car of each element is a string, to be replaced at the start of a link.
1692 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1693 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1695 [[linkkey:tag][description]]
1697 The 'linkkey' must be a word word, starting with a letter, followed
1698 by letters, numbers, '-' or '_'.
1700 If REPLACE is a string, the tag will simply be appended to create the link.
1701 If the string contains \"%s\", the tag will be inserted there. If the string
1702 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1703 at that point (see the function `url-hexify-string'). If the string contains
1704 the specifier \"%(my-function)\", then the custom function `my-function' will
1705 be invoked: this function takes the tag as its only argument and must return
1706 a string.
1708 REPLACE may also be a function that will be called with the tag as the
1709 only argument to create the link, which should be returned as a string.
1711 See the manual for examples."
1712 :group 'org-link
1713 :type '(repeat
1714 (cons
1715 (string :tag "Protocol")
1716 (choice
1717 (string :tag "Format")
1718 (function)))))
1720 (defcustom org-descriptive-links t
1721 "Non-nil means Org will display descriptive links.
1722 E.g. [[http://orgmode.org][Org website]] will be displayed as
1723 \"Org Website\", hiding the link itself and just displaying its
1724 description. When set to `nil', Org will display the full links
1725 literally.
1727 You can interactively set the value of this variable by calling
1728 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1729 :group 'org-link
1730 :type 'boolean)
1732 (defcustom org-link-file-path-type 'adaptive
1733 "How the path name in file links should be stored.
1734 Valid values are:
1736 relative Relative to the current directory, i.e. the directory of the file
1737 into which the link is being inserted.
1738 absolute Absolute path, if possible with ~ for home directory.
1739 noabbrev Absolute path, no abbreviation of home directory.
1740 adaptive Use relative path for files in the current directory and sub-
1741 directories of it. For other files, use an absolute path."
1742 :group 'org-link
1743 :type '(choice
1744 (const relative)
1745 (const absolute)
1746 (const noabbrev)
1747 (const adaptive)))
1749 (defvaralias 'org-activate-links 'org-highlight-links)
1750 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1751 "Types of links that should be highlighted in Org-mode files.
1753 This is a list of symbols, each one of them leading to the
1754 highlighting of a certain link type.
1756 You can still open links that are not highlighted.
1758 In principle, it does not hurt to turn on highlighting for all
1759 link types. There may be a small gain when turning off unused
1760 link types. The types are:
1762 bracket The recommended [[link][description]] or [[link]] links with hiding.
1763 angle Links in angular brackets that may contain whitespace like
1764 <bbdb:Carsten Dominik>.
1765 plain Plain links in normal text, no whitespace, like http://google.com.
1766 radio Text that is matched by a radio target, see manual for details.
1767 tag Tag settings in a headline (link to tag search).
1768 date Time stamps (link to calendar).
1769 footnote Footnote labels.
1771 If you set this variable during an Emacs session, use `org-mode-restart'
1772 in the Org buffer so that the change takes effect."
1773 :group 'org-link
1774 :group 'org-appearance
1775 :type '(set :greedy t
1776 (const :tag "Double bracket links" bracket)
1777 (const :tag "Angular bracket links" angle)
1778 (const :tag "Plain text links" plain)
1779 (const :tag "Radio target matches" radio)
1780 (const :tag "Tags" tag)
1781 (const :tag "Timestamps" date)
1782 (const :tag "Footnotes" footnote)))
1784 (defcustom org-make-link-description-function nil
1785 "Function to use for generating link descriptions from links.
1786 When nil, the link location will be used. This function must take
1787 two parameters: the first one is the link, the second one is the
1788 description generated by `org-insert-link'. The function should
1789 return the description to use."
1790 :group 'org-link
1791 :type '(choice (const nil) (function)))
1793 (defgroup org-link-store nil
1794 "Options concerning storing links in Org-mode."
1795 :tag "Org Store Link"
1796 :group 'org-link)
1798 (defcustom org-url-hexify-p t
1799 "When non-nil, hexify URL when creating a link."
1800 :type 'boolean
1801 :version "24.3"
1802 :group 'org-link-store)
1804 (defcustom org-email-link-description-format "Email %c: %.30s"
1805 "Format of the description part of a link to an email or usenet message.
1806 The following %-escapes will be replaced by corresponding information:
1808 %F full \"From\" field
1809 %f name, taken from \"From\" field, address if no name
1810 %T full \"To\" field
1811 %t first name in \"To\" field, address if no name
1812 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1813 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1814 %s subject
1815 %d date
1816 %m message-id.
1818 You may use normal field width specification between the % and the letter.
1819 This is for example useful to limit the length of the subject.
1821 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1822 :group 'org-link-store
1823 :type 'string)
1825 (defcustom org-from-is-user-regexp
1826 (let (r1 r2)
1827 (when (and user-mail-address (not (string= user-mail-address "")))
1828 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1829 (when (and user-full-name (not (string= user-full-name "")))
1830 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1831 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1832 "Regexp matched against the \"From:\" header of an email or usenet message.
1833 It should match if the message is from the user him/herself."
1834 :group 'org-link-store
1835 :type 'regexp)
1837 (defcustom org-context-in-file-links t
1838 "Non-nil means file links from `org-store-link' contain context.
1839 A search string will be added to the file name with :: as separator and
1840 used to find the context when the link is activated by the command
1841 `org-open-at-point'. When this option is t, the entire active region
1842 will be placed in the search string of the file link. If set to a
1843 positive integer, only the first n lines of context will be stored.
1845 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1846 negates this setting for the duration of the command."
1847 :group 'org-link-store
1848 :type '(choice boolean integer))
1850 (defcustom org-keep-stored-link-after-insertion nil
1851 "Non-nil means keep link in list for entire session.
1853 The command `org-store-link' adds a link pointing to the current
1854 location to an internal list. These links accumulate during a session.
1855 The command `org-insert-link' can be used to insert links into any
1856 Org-mode file (offering completion for all stored links). When this
1857 option is nil, every link which has been inserted once using \\[org-insert-link]
1858 will be removed from the list, to make completing the unused links
1859 more efficient."
1860 :group 'org-link-store
1861 :type 'boolean)
1863 (defgroup org-link-follow nil
1864 "Options concerning following links in Org-mode."
1865 :tag "Org Follow Link"
1866 :group 'org-link)
1868 (defcustom org-link-translation-function nil
1869 "Function to translate links with different syntax to Org syntax.
1870 This can be used to translate links created for example by the Planner
1871 or emacs-wiki packages to Org syntax.
1872 The function must accept two parameters, a TYPE containing the link
1873 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1874 which is everything after the link protocol. It should return a cons
1875 with possibly modified values of type and path.
1876 Org contains a function for this, so if you set this variable to
1877 `org-translate-link-from-planner', you should be able follow many
1878 links created by planner."
1879 :group 'org-link-follow
1880 :type '(choice (const nil) (function)))
1882 (defcustom org-follow-link-hook nil
1883 "Hook that is run after a link has been followed."
1884 :group 'org-link-follow
1885 :type 'hook)
1887 (defcustom org-tab-follows-link nil
1888 "Non-nil means on links TAB will follow the link.
1889 Needs to be set before org.el is loaded.
1890 This really should not be used, it does not make sense, and the
1891 implementation is bad."
1892 :group 'org-link-follow
1893 :type 'boolean)
1895 (defcustom org-return-follows-link nil
1896 "Non-nil means on links RET will follow the link.
1897 In tables, the special behavior of RET has precedence."
1898 :group 'org-link-follow
1899 :type 'boolean)
1901 (defcustom org-mouse-1-follows-link
1902 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1903 "Non-nil means mouse-1 on a link will follow the link.
1904 A longer mouse click will still set point. Does not work on XEmacs.
1905 Needs to be set before org.el is loaded."
1906 :group 'org-link-follow
1907 :version "24.4"
1908 :package-version '(Org . "8.3")
1909 :type '(choice
1910 (const :tag "A double click follows the link" double)
1911 (const :tag "Unconditionally follow the link with mouse-1" t)
1912 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1914 (defcustom org-mark-ring-length 4
1915 "Number of different positions to be recorded in the ring.
1916 Changing this requires a restart of Emacs to work correctly."
1917 :group 'org-link-follow
1918 :type 'integer)
1920 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1921 "Non-nil means internal links in Org files must exactly match a headline.
1922 When nil, the link search tries to match a phrase with all words
1923 in the search text."
1924 :group 'org-link-follow
1925 :version "24.1"
1926 :type '(choice
1927 (const :tag "Use fuzzy text search" nil)
1928 (const :tag "Match only exact headline" t)
1929 (const :tag "Match exact headline or query to create it"
1930 query-to-create)))
1932 (defcustom org-link-frame-setup
1933 '((vm . vm-visit-folder-other-frame)
1934 (vm-imap . vm-visit-imap-folder-other-frame)
1935 (gnus . org-gnus-no-new-news)
1936 (file . find-file-other-window)
1937 (wl . wl-other-frame))
1938 "Setup the frame configuration for following links.
1939 When following a link with Emacs, it may often be useful to display
1940 this link in another window or frame. This variable can be used to
1941 set this up for the different types of links.
1942 For VM, use any of
1943 `vm-visit-folder'
1944 `vm-visit-folder-other-window'
1945 `vm-visit-folder-other-frame'
1946 For Gnus, use any of
1947 `gnus'
1948 `gnus-other-frame'
1949 `org-gnus-no-new-news'
1950 For FILE, use any of
1951 `find-file'
1952 `find-file-other-window'
1953 `find-file-other-frame'
1954 For Wanderlust use any of
1955 `wl'
1956 `wl-other-frame'
1957 For the calendar, use the variable `calendar-setup'.
1958 For BBDB, it is currently only possible to display the matches in
1959 another window."
1960 :group 'org-link-follow
1961 :type '(list
1962 (cons (const vm)
1963 (choice
1964 (const vm-visit-folder)
1965 (const vm-visit-folder-other-window)
1966 (const vm-visit-folder-other-frame)))
1967 (cons (const vm-imap)
1968 (choice
1969 (const vm-visit-imap-folder)
1970 (const vm-visit-imap-folder-other-window)
1971 (const vm-visit-imap-folder-other-frame)))
1972 (cons (const gnus)
1973 (choice
1974 (const gnus)
1975 (const gnus-other-frame)
1976 (const org-gnus-no-new-news)))
1977 (cons (const file)
1978 (choice
1979 (const find-file)
1980 (const find-file-other-window)
1981 (const find-file-other-frame)))
1982 (cons (const wl)
1983 (choice
1984 (const wl)
1985 (const wl-other-frame)))))
1987 (defcustom org-display-internal-link-with-indirect-buffer nil
1988 "Non-nil means use indirect buffer to display infile links.
1989 Activating internal links (from one location in a file to another location
1990 in the same file) normally just jumps to the location. When the link is
1991 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1992 is displayed in
1993 another window. When this option is set, the other window actually displays
1994 an indirect buffer clone of the current buffer, to avoid any visibility
1995 changes to the current buffer."
1996 :group 'org-link-follow
1997 :type 'boolean)
1999 (defcustom org-open-non-existing-files nil
2000 "Non-nil means `org-open-file' will open non-existing files.
2001 When nil, an error will be generated.
2002 This variable applies only to external applications because they
2003 might choke on non-existing files. If the link is to a file that
2004 will be opened in Emacs, the variable is ignored."
2005 :group 'org-link-follow
2006 :type 'boolean)
2008 (defcustom org-open-directory-means-index-dot-org nil
2009 "Non-nil means a link to a directory really means to index.org.
2010 When nil, following a directory link will run dired or open a finder/explorer
2011 window on that directory."
2012 :group 'org-link-follow
2013 :type 'boolean)
2015 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2016 "Non-nil means ask for confirmation before executing shell links.
2017 Shell links can be dangerous: just think about a link
2019 [[shell:rm -rf ~/*][Google Search]]
2021 This link would show up in your Org-mode document as \"Google Search\",
2022 but really it would remove your entire home directory.
2023 Therefore we advise against setting this variable to nil.
2024 Just change it to `y-or-n-p' if you want to confirm with a
2025 single keystroke rather than having to type \"yes\"."
2026 :group 'org-link-follow
2027 :type '(choice
2028 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2029 (const :tag "with y-or-n (faster)" y-or-n-p)
2030 (const :tag "no confirmation (dangerous)" nil)))
2031 (put 'org-confirm-shell-link-function
2032 'safe-local-variable
2033 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2035 (defcustom org-confirm-shell-link-not-regexp ""
2036 "A regexp to skip confirmation for shell links."
2037 :group 'org-link-follow
2038 :version "24.1"
2039 :type 'regexp)
2041 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2042 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2043 Elisp links can be dangerous: just think about a link
2045 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2047 This link would show up in your Org-mode document as \"Google Search\",
2048 but really it would remove your entire home directory.
2049 Therefore we advise against setting this variable to nil.
2050 Just change it to `y-or-n-p' if you want to confirm with a
2051 single keystroke rather than having to type \"yes\"."
2052 :group 'org-link-follow
2053 :type '(choice
2054 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2055 (const :tag "with y-or-n (faster)" y-or-n-p)
2056 (const :tag "no confirmation (dangerous)" nil)))
2057 (put 'org-confirm-shell-link-function
2058 'safe-local-variable
2059 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2061 (defcustom org-confirm-elisp-link-not-regexp ""
2062 "A regexp to skip confirmation for Elisp links."
2063 :group 'org-link-follow
2064 :version "24.1"
2065 :type 'regexp)
2067 (defconst org-file-apps-defaults-gnu
2068 '((remote . emacs)
2069 (system . mailcap)
2070 (t . mailcap))
2071 "Default file applications on a UNIX or GNU/Linux system.
2072 See `org-file-apps'.")
2074 (defconst org-file-apps-defaults-macosx
2075 '((remote . emacs)
2076 (t . "open %s")
2077 (system . "open %s")
2078 ("ps.gz" . "gv %s")
2079 ("eps.gz" . "gv %s")
2080 ("dvi" . "xdvi %s")
2081 ("fig" . "xfig %s"))
2082 "Default file applications on a MacOS X system.
2083 The system \"open\" is known as a default, but we use X11 applications
2084 for some files for which the OS does not have a good default.
2085 See `org-file-apps'.")
2087 (defconst org-file-apps-defaults-windowsnt
2088 (list
2089 '(remote . emacs)
2090 (cons t
2091 (list (if (featurep 'xemacs)
2092 'mswindows-shell-execute
2093 'w32-shell-execute)
2094 "open" 'file))
2095 (cons 'system
2096 (list (if (featurep 'xemacs)
2097 'mswindows-shell-execute
2098 'w32-shell-execute)
2099 "open" 'file)))
2100 "Default file applications on a Windows NT system.
2101 The system \"open\" is used for most files.
2102 See `org-file-apps'.")
2104 (defcustom org-file-apps
2105 '((auto-mode . emacs)
2106 ("\\.mm\\'" . default)
2107 ("\\.x?html?\\'" . default)
2108 ("\\.pdf\\'" . default))
2109 "External applications for opening `file:path' items in a document.
2110 Org-mode uses system defaults for different file types, but
2111 you can use this variable to set the application for a given file
2112 extension. The entries in this list are cons cells where the car identifies
2113 files and the cdr the corresponding command. Possible values for the
2114 file identifier are
2115 \"string\" A string as a file identifier can be interpreted in different
2116 ways, depending on its contents:
2118 - Alphanumeric characters only:
2119 Match links with this file extension.
2120 Example: (\"pdf\" . \"evince %s\")
2121 to open PDFs with evince.
2123 - Regular expression: Match links where the
2124 filename matches the regexp. If you want to
2125 use groups here, use shy groups.
2127 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2128 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2129 to open *.html and *.xhtml with firefox.
2131 - Regular expression which contains (non-shy) groups:
2132 Match links where the whole link, including \"::\", and
2133 anything after that, matches the regexp.
2134 In a custom command string, %1, %2, etc. are replaced with
2135 the parts of the link that were matched by the groups.
2136 For backwards compatibility, if a command string is given
2137 that does not use any of the group matches, this case is
2138 handled identically to the second one (i.e. match against
2139 file name only).
2140 In a custom lisp form, you can access the group matches with
2141 (match-string n link).
2143 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2144 to open [[file:document.pdf::5]] with evince at page 5.
2146 `directory' Matches a directory
2147 `remote' Matches a remote file, accessible through tramp or efs.
2148 Remote files most likely should be visited through Emacs
2149 because external applications cannot handle such paths.
2150 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2151 so all files Emacs knows how to handle. Using this with
2152 command `emacs' will open most files in Emacs. Beware that this
2153 will also open html files inside Emacs, unless you add
2154 (\"html\" . default) to the list as well.
2155 t Default for files not matched by any of the other options.
2156 `system' The system command to open files, like `open' on Windows
2157 and Mac OS X, and mailcap under GNU/Linux. This is the command
2158 that will be selected if you call `C-c C-o' with a double
2159 \\[universal-argument] \\[universal-argument] prefix.
2161 Possible values for the command are:
2162 `emacs' The file will be visited by the current Emacs process.
2163 `default' Use the default application for this file type, which is the
2164 association for t in the list, most likely in the system-specific
2165 part.
2166 This can be used to overrule an unwanted setting in the
2167 system-specific variable.
2168 `system' Use the system command for opening files, like \"open\".
2169 This command is specified by the entry whose car is `system'.
2170 Most likely, the system-specific version of this variable
2171 does define this command, but you can overrule/replace it
2172 here.
2173 string A command to be executed by a shell; %s will be replaced
2174 by the path to the file.
2175 sexp A Lisp form which will be evaluated. The file path will
2176 be available in the Lisp variable `file'.
2177 For more examples, see the system specific constants
2178 `org-file-apps-defaults-macosx'
2179 `org-file-apps-defaults-windowsnt'
2180 `org-file-apps-defaults-gnu'."
2181 :group 'org-link-follow
2182 :type '(repeat
2183 (cons (choice :value ""
2184 (string :tag "Extension")
2185 (const :tag "System command to open files" system)
2186 (const :tag "Default for unrecognized files" t)
2187 (const :tag "Remote file" remote)
2188 (const :tag "Links to a directory" directory)
2189 (const :tag "Any files that have Emacs modes"
2190 auto-mode))
2191 (choice :value ""
2192 (const :tag "Visit with Emacs" emacs)
2193 (const :tag "Use default" default)
2194 (const :tag "Use the system command" system)
2195 (string :tag "Command")
2196 (sexp :tag "Lisp form")))))
2198 (defcustom org-doi-server-url "http://dx.doi.org/"
2199 "The URL of the DOI server."
2200 :type 'string
2201 :version "24.3"
2202 :group 'org-link-follow)
2204 (defgroup org-refile nil
2205 "Options concerning refiling entries in Org-mode."
2206 :tag "Org Refile"
2207 :group 'org)
2209 (defcustom org-directory "~/org"
2210 "Directory with org files.
2211 This is just a default location to look for Org files. There is no need
2212 at all to put your files into this directory. It is only used in the
2213 following situations:
2215 1. When a capture template specifies a target file that is not an
2216 absolute path. The path will then be interpreted relative to
2217 `org-directory'
2218 2. When a capture note is filed away in an interactive way (when exiting the
2219 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2220 with `org-directory' as the default path."
2221 :group 'org-refile
2222 :group 'org-capture
2223 :type 'directory)
2225 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2226 "Default target for storing notes.
2227 Used as a fall back file for org-capture.el, for templates that
2228 do not specify a target file."
2229 :group 'org-refile
2230 :group 'org-capture
2231 :type '(choice
2232 (const :tag "Default from remember-data-file" nil)
2233 file))
2235 (defcustom org-goto-interface 'outline
2236 "The default interface to be used for `org-goto'.
2237 Allowed values are:
2238 outline The interface shows an outline of the relevant file
2239 and the correct heading is found by moving through
2240 the outline or by searching with incremental search.
2241 outline-path-completion Headlines in the current buffer are offered via
2242 completion. This is the interface also used by
2243 the refile command."
2244 :group 'org-refile
2245 :type '(choice
2246 (const :tag "Outline" outline)
2247 (const :tag "Outline-path-completion" outline-path-completion)))
2249 (defcustom org-goto-max-level 5
2250 "Maximum target level when running `org-goto' with refile interface."
2251 :group 'org-refile
2252 :type 'integer)
2254 (defcustom org-reverse-note-order nil
2255 "Non-nil means store new notes at the beginning of a file or entry.
2256 When nil, new notes will be filed to the end of a file or entry.
2257 This can also be a list with cons cells of regular expressions that
2258 are matched against file names, and values."
2259 :group 'org-capture
2260 :group 'org-refile
2261 :type '(choice
2262 (const :tag "Reverse always" t)
2263 (const :tag "Reverse never" nil)
2264 (repeat :tag "By file name regexp"
2265 (cons regexp boolean))))
2267 (defcustom org-log-refile nil
2268 "Information to record when a task is refiled.
2270 Possible values are:
2272 nil Don't add anything
2273 time Add a time stamp to the task
2274 note Prompt for a note and add it with template `org-log-note-headings'
2276 This option can also be set with on a per-file-basis with
2278 #+STARTUP: nologrefile
2279 #+STARTUP: logrefile
2280 #+STARTUP: lognoterefile
2282 You can have local logging settings for a subtree by setting the LOGGING
2283 property to one or more of these keywords.
2285 When bulk-refiling from the agenda, the value `note' is forbidden and
2286 will temporarily be changed to `time'."
2287 :group 'org-refile
2288 :group 'org-progress
2289 :version "24.1"
2290 :type '(choice
2291 (const :tag "No logging" nil)
2292 (const :tag "Record timestamp" time)
2293 (const :tag "Record timestamp with note." note)))
2295 (defcustom org-refile-targets nil
2296 "Targets for refiling entries with \\[org-refile].
2297 This is a list of cons cells. Each cell contains:
2298 - a specification of the files to be considered, either a list of files,
2299 or a symbol whose function or variable value will be used to retrieve
2300 a file name or a list of file names. If you use `org-agenda-files' for
2301 that, all agenda files will be scanned for targets. Nil means consider
2302 headings in the current buffer.
2303 - A specification of how to find candidate refile targets. This may be
2304 any of:
2305 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2306 This tag has to be present in all target headlines, inheritance will
2307 not be considered.
2308 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2309 todo keyword.
2310 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2311 headlines that are refiling targets.
2312 - a cons cell (:level . N). Any headline of level N is considered a target.
2313 Note that, when `org-odd-levels-only' is set, level corresponds to
2314 order in hierarchy, not to the number of stars.
2315 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2316 Note that, when `org-odd-levels-only' is set, level corresponds to
2317 order in hierarchy, not to the number of stars.
2319 Each element of this list generates a set of possible targets.
2320 The union of these sets is presented (with completion) to
2321 the user by `org-refile'.
2323 You can set the variable `org-refile-target-verify-function' to a function
2324 to verify each headline found by the simple criteria above.
2326 When this variable is nil, all top-level headlines in the current buffer
2327 are used, equivalent to the value `((nil . (:level . 1))'."
2328 :group 'org-refile
2329 :type '(repeat
2330 (cons
2331 (choice :value org-agenda-files
2332 (const :tag "All agenda files" org-agenda-files)
2333 (const :tag "Current buffer" nil)
2334 (function) (variable) (file))
2335 (choice :tag "Identify target headline by"
2336 (cons :tag "Specific tag" (const :value :tag) (string))
2337 (cons :tag "TODO keyword" (const :value :todo) (string))
2338 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2339 (cons :tag "Level number" (const :value :level) (integer))
2340 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2342 (defcustom org-refile-target-verify-function nil
2343 "Function to verify if the headline at point should be a refile target.
2344 The function will be called without arguments, with point at the
2345 beginning of the headline. It should return t and leave point
2346 where it is if the headline is a valid target for refiling.
2348 If the target should not be selected, the function must return nil.
2349 In addition to this, it may move point to a place from where the search
2350 should be continued. For example, the function may decide that the entire
2351 subtree of the current entry should be excluded and move point to the end
2352 of the subtree."
2353 :group 'org-refile
2354 :type '(choice
2355 (const nil)
2356 (function)))
2358 (defcustom org-refile-use-cache nil
2359 "Non-nil means cache refile targets to speed up the process.
2360 The cache for a particular file will be updated automatically when
2361 the buffer has been killed, or when any of the marker used for flagging
2362 refile targets no longer points at a live buffer.
2363 If you have added new entries to a buffer that might themselves be targets,
2364 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2365 find that easier, `C-u C-u C-u C-c C-w'."
2366 :group 'org-refile
2367 :version "24.1"
2368 :type 'boolean)
2370 (defcustom org-refile-use-outline-path nil
2371 "Non-nil means provide refile targets as paths.
2372 So a level 3 headline will be available as level1/level2/level3.
2374 When the value is `file', also include the file name (without directory)
2375 into the path. In this case, you can also stop the completion after
2376 the file name, to get entries inserted as top level in the file.
2378 When `full-file-path', include the full file path."
2379 :group 'org-refile
2380 :type '(choice
2381 (const :tag "Not" nil)
2382 (const :tag "Yes" t)
2383 (const :tag "Start with file name" file)
2384 (const :tag "Start with full file path" full-file-path)))
2386 (defcustom org-outline-path-complete-in-steps t
2387 "Non-nil means complete the outline path in hierarchical steps.
2388 When Org-mode uses the refile interface to select an outline path
2389 \(see variable `org-refile-use-outline-path'), the completion of
2390 the path can be done is a single go, or if can be done in steps down
2391 the headline hierarchy. Going in steps is probably the best if you
2392 do not use a special completion package like `ido' or `icicles'.
2393 However, when using these packages, going in one step can be very
2394 fast, while still showing the whole path to the entry."
2395 :group 'org-refile
2396 :type 'boolean)
2398 (defcustom org-refile-allow-creating-parent-nodes nil
2399 "Non-nil means allow to create new nodes as refile targets.
2400 New nodes are then created by adding \"/new node name\" to the completion
2401 of an existing node. When the value of this variable is `confirm',
2402 new node creation must be confirmed by the user (recommended).
2403 When nil, the completion must match an existing entry.
2405 Note that, if the new heading is not seen by the criteria
2406 listed in `org-refile-targets', multiple instances of the same
2407 heading would be created by trying again to file under the new
2408 heading."
2409 :group 'org-refile
2410 :type '(choice
2411 (const :tag "Never" nil)
2412 (const :tag "Always" t)
2413 (const :tag "Prompt for confirmation" confirm)))
2415 (defcustom org-refile-active-region-within-subtree nil
2416 "Non-nil means also refile active region within a subtree.
2418 By default `org-refile' doesn't allow refiling regions if they
2419 don't contain a set of subtrees, but it might be convenient to
2420 do so sometimes: in that case, the first line of the region is
2421 converted to a headline before refiling."
2422 :group 'org-refile
2423 :version "24.1"
2424 :type 'boolean)
2426 (defgroup org-todo nil
2427 "Options concerning TODO items in Org-mode."
2428 :tag "Org TODO"
2429 :group 'org)
2431 (defgroup org-progress nil
2432 "Options concerning Progress logging in Org-mode."
2433 :tag "Org Progress"
2434 :group 'org-time)
2436 (defvar org-todo-interpretation-widgets
2437 '((:tag "Sequence (cycling hits every state)" sequence)
2438 (:tag "Type (cycling directly to DONE)" type))
2439 "The available interpretation symbols for customizing `org-todo-keywords'.
2440 Interested libraries should add to this list.")
2442 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2443 "List of TODO entry keyword sequences and their interpretation.
2444 \\<org-mode-map>This is a list of sequences.
2446 Each sequence starts with a symbol, either `sequence' or `type',
2447 indicating if the keywords should be interpreted as a sequence of
2448 action steps, or as different types of TODO items. The first
2449 keywords are states requiring action - these states will select a headline
2450 for inclusion into the global TODO list Org-mode produces. If one of
2451 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2452 signify that no further action is necessary. If \"|\" is not found,
2453 the last keyword is treated as the only DONE state of the sequence.
2455 The command \\[org-todo] cycles an entry through these states, and one
2456 additional state where no keyword is present. For details about this
2457 cycling, see the manual.
2459 TODO keywords and interpretation can also be set on a per-file basis with
2460 the special #+SEQ_TODO and #+TYP_TODO lines.
2462 Each keyword can optionally specify a character for fast state selection
2463 \(in combination with the variable `org-use-fast-todo-selection')
2464 and specifiers for state change logging, using the same syntax that
2465 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2466 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2467 indicates to record a time stamp each time this state is selected.
2469 Each keyword may also specify if a timestamp or a note should be
2470 recorded when entering or leaving the state, by adding additional
2471 characters in the parenthesis after the keyword. This looks like this:
2472 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2473 record only the time of the state change. With X and Y being either
2474 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2475 Y when leaving the state if and only if the *target* state does not
2476 define X. You may omit any of the fast-selection key or X or /Y,
2477 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2479 For backward compatibility, this variable may also be just a list
2480 of keywords. In this case the interpretation (sequence or type) will be
2481 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2482 :group 'org-todo
2483 :group 'org-keywords
2484 :type '(choice
2485 (repeat :tag "Old syntax, just keywords"
2486 (string :tag "Keyword"))
2487 (repeat :tag "New syntax"
2488 (cons
2489 (choice
2490 :tag "Interpretation"
2491 ;;Quick and dirty way to see
2492 ;;`org-todo-interpretations'. This takes the
2493 ;;place of item arguments
2494 :convert-widget
2495 (lambda (widget)
2496 (widget-put widget
2497 :args (mapcar
2498 (lambda (x)
2499 (widget-convert
2500 (cons 'const x)))
2501 org-todo-interpretation-widgets))
2502 widget))
2503 (repeat
2504 (string :tag "Keyword"))))))
2506 (defvar org-todo-keywords-1 nil
2507 "All TODO and DONE keywords active in a buffer.")
2508 (make-variable-buffer-local 'org-todo-keywords-1)
2509 (defvar org-todo-keywords-for-agenda nil)
2510 (defvar org-done-keywords-for-agenda nil)
2511 (defvar org-todo-keyword-alist-for-agenda nil)
2512 (defvar org-tag-alist-for-agenda nil
2513 "Alist of all tags from all agenda files.")
2514 (defvar org-tag-groups-alist-for-agenda nil
2515 "Alist of all groups tags from all current agenda files.")
2516 (defvar org-tag-groups-alist nil)
2517 (make-variable-buffer-local 'org-tag-groups-alist)
2518 (defvar org-agenda-contributing-files nil)
2519 (defvar org-not-done-keywords nil)
2520 (make-variable-buffer-local 'org-not-done-keywords)
2521 (defvar org-done-keywords nil)
2522 (make-variable-buffer-local 'org-done-keywords)
2523 (defvar org-todo-heads nil)
2524 (make-variable-buffer-local 'org-todo-heads)
2525 (defvar org-todo-sets nil)
2526 (make-variable-buffer-local 'org-todo-sets)
2527 (defvar org-todo-log-states nil)
2528 (make-variable-buffer-local 'org-todo-log-states)
2529 (defvar org-todo-kwd-alist nil)
2530 (make-variable-buffer-local 'org-todo-kwd-alist)
2531 (defvar org-todo-key-alist nil)
2532 (make-variable-buffer-local 'org-todo-key-alist)
2533 (defvar org-todo-key-trigger nil)
2534 (make-variable-buffer-local 'org-todo-key-trigger)
2536 (defcustom org-todo-interpretation 'sequence
2537 "Controls how TODO keywords are interpreted.
2538 This variable is in principle obsolete and is only used for
2539 backward compatibility, if the interpretation of todo keywords is
2540 not given already in `org-todo-keywords'. See that variable for
2541 more information."
2542 :group 'org-todo
2543 :group 'org-keywords
2544 :type '(choice (const sequence)
2545 (const type)))
2547 (defcustom org-use-fast-todo-selection t
2548 "Non-nil means use the fast todo selection scheme with C-c C-t.
2549 This variable describes if and under what circumstances the cycling
2550 mechanism for TODO keywords will be replaced by a single-key, direct
2551 selection scheme.
2553 When nil, fast selection is never used.
2555 When the symbol `prefix', it will be used when `org-todo' is called
2556 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2557 `C-u t' in an agenda buffer.
2559 When t, fast selection is used by default. In this case, the prefix
2560 argument forces cycling instead.
2562 In all cases, the special interface is only used if access keys have
2563 actually been assigned by the user, i.e. if keywords in the configuration
2564 are followed by a letter in parenthesis, like TODO(t)."
2565 :group 'org-todo
2566 :type '(choice
2567 (const :tag "Never" nil)
2568 (const :tag "By default" t)
2569 (const :tag "Only with C-u C-c C-t" prefix)))
2571 (defcustom org-provide-todo-statistics t
2572 "Non-nil means update todo statistics after insert and toggle.
2573 ALL-HEADLINES means update todo statistics by including headlines
2574 with no TODO keyword as well, counting them as not done.
2575 A list of TODO keywords means the same, but skip keywords that are
2576 not in this list.
2577 When set to a list of two lists, the first list contains keywords
2578 to consider as TODO keywords, the second list contains keywords
2579 to consider as DONE keywords.
2581 When this is set, todo statistics is updated in the parent of the
2582 current entry each time a todo state is changed."
2583 :group 'org-todo
2584 :type '(choice
2585 (const :tag "Yes, only for TODO entries" t)
2586 (const :tag "Yes, including all entries" all-headlines)
2587 (repeat :tag "Yes, for TODOs in this list"
2588 (string :tag "TODO keyword"))
2589 (list :tag "Yes, for TODOs and DONEs in these lists"
2590 (repeat (string :tag "TODO keyword"))
2591 (repeat (string :tag "DONE keyword")))
2592 (other :tag "No TODO statistics" nil)))
2594 (defcustom org-hierarchical-todo-statistics t
2595 "Non-nil means TODO statistics covers just direct children.
2596 When nil, all entries in the subtree are considered.
2597 This has only an effect if `org-provide-todo-statistics' is set.
2598 To set this to nil for only a single subtree, use a COOKIE_DATA
2599 property and include the word \"recursive\" into the value."
2600 :group 'org-todo
2601 :type 'boolean)
2603 (defcustom org-after-todo-state-change-hook nil
2604 "Hook which is run after the state of a TODO item was changed.
2605 The new state (a string with a TODO keyword, or nil) is available in the
2606 Lisp variable `org-state'."
2607 :group 'org-todo
2608 :type 'hook)
2610 (defvar org-blocker-hook nil
2611 "Hook for functions that are allowed to block a state change.
2613 Functions in this hook should not modify the buffer.
2614 Each function gets as its single argument a property list,
2615 see `org-trigger-hook' for more information about this list.
2617 If any of the functions in this hook returns nil, the state change
2618 is blocked.")
2620 (defvar org-trigger-hook nil
2621 "Hook for functions that are triggered by a state change.
2623 Each function gets as its single argument a property list with at
2624 least the following elements:
2626 (:type type-of-change :position pos-at-entry-start
2627 :from old-state :to new-state)
2629 Depending on the type, more properties may be present.
2631 This mechanism is currently implemented for:
2633 TODO state changes
2634 ------------------
2635 :type todo-state-change
2636 :from previous state (keyword as a string), or nil, or a symbol
2637 'todo' or 'done', to indicate the general type of state.
2638 :to new state, like in :from")
2640 (defcustom org-enforce-todo-dependencies nil
2641 "Non-nil means undone TODO entries will block switching the parent to DONE.
2642 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2643 be blocked if any prior sibling is not yet done.
2644 Finally, if the parent is blocked because of ordered siblings of its own,
2645 the child will also be blocked."
2646 :set (lambda (var val)
2647 (set var val)
2648 (if val
2649 (add-hook 'org-blocker-hook
2650 'org-block-todo-from-children-or-siblings-or-parent)
2651 (remove-hook 'org-blocker-hook
2652 'org-block-todo-from-children-or-siblings-or-parent)))
2653 :group 'org-todo
2654 :type 'boolean)
2656 (defcustom org-enforce-todo-checkbox-dependencies nil
2657 "Non-nil means unchecked boxes will block switching the parent to DONE.
2658 When this is nil, checkboxes have no influence on switching TODO states.
2659 When non-nil, you first need to check off all check boxes before the TODO
2660 entry can be switched to DONE.
2661 This variable needs to be set before org.el is loaded, and you need to
2662 restart Emacs after a change to make the change effective. The only way
2663 to change is while Emacs is running is through the customize interface."
2664 :set (lambda (var val)
2665 (set var val)
2666 (if val
2667 (add-hook 'org-blocker-hook
2668 'org-block-todo-from-checkboxes)
2669 (remove-hook 'org-blocker-hook
2670 'org-block-todo-from-checkboxes)))
2671 :group 'org-todo
2672 :type 'boolean)
2674 (defcustom org-treat-insert-todo-heading-as-state-change nil
2675 "Non-nil means inserting a TODO heading is treated as state change.
2676 So when the command \\[org-insert-todo-heading] is used, state change
2677 logging will apply if appropriate. When nil, the new TODO item will
2678 be inserted directly, and no logging will take place."
2679 :group 'org-todo
2680 :type 'boolean)
2682 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2683 "Non-nil means switching TODO states with S-cursor counts as state change.
2684 This is the default behavior. However, setting this to nil allows a
2685 convenient way to select a TODO state and bypass any logging associated
2686 with that."
2687 :group 'org-todo
2688 :type 'boolean)
2690 (defcustom org-todo-state-tags-triggers nil
2691 "Tag changes that should be triggered by TODO state changes.
2692 This is a list. Each entry is
2694 (state-change (tag . flag) .......)
2696 State-change can be a string with a state, and empty string to indicate the
2697 state that has no TODO keyword, or it can be one of the symbols `todo'
2698 or `done', meaning any not-done or done state, respectively."
2699 :group 'org-todo
2700 :group 'org-tags
2701 :type '(repeat
2702 (cons (choice :tag "When changing to"
2703 (const :tag "Not-done state" todo)
2704 (const :tag "Done state" done)
2705 (string :tag "State"))
2706 (repeat
2707 (cons :tag "Tag action"
2708 (string :tag "Tag")
2709 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2711 (defcustom org-log-done nil
2712 "Information to record when a task moves to the DONE state.
2714 Possible values are:
2716 nil Don't add anything, just change the keyword
2717 time Add a time stamp to the task
2718 note Prompt for a note and add it with template `org-log-note-headings'
2720 This option can also be set with on a per-file-basis with
2722 #+STARTUP: nologdone
2723 #+STARTUP: logdone
2724 #+STARTUP: lognotedone
2726 You can have local logging settings for a subtree by setting the LOGGING
2727 property to one or more of these keywords."
2728 :group 'org-todo
2729 :group 'org-progress
2730 :type '(choice
2731 (const :tag "No logging" nil)
2732 (const :tag "Record CLOSED timestamp" time)
2733 (const :tag "Record CLOSED timestamp with note." note)))
2735 ;; Normalize old uses of org-log-done.
2736 (cond
2737 ((eq org-log-done t) (setq org-log-done 'time))
2738 ((and (listp org-log-done) (memq 'done org-log-done))
2739 (setq org-log-done 'note)))
2741 (defcustom org-log-reschedule nil
2742 "Information to record when the scheduling date of a tasks is modified.
2744 Possible values are:
2746 nil Don't add anything, just change the date
2747 time Add a time stamp to the task
2748 note Prompt for a note and add it with template `org-log-note-headings'
2750 This option can also be set with on a per-file-basis with
2752 #+STARTUP: nologreschedule
2753 #+STARTUP: logreschedule
2754 #+STARTUP: lognotereschedule"
2755 :group 'org-todo
2756 :group 'org-progress
2757 :type '(choice
2758 (const :tag "No logging" nil)
2759 (const :tag "Record timestamp" time)
2760 (const :tag "Record timestamp with note." note)))
2762 (defcustom org-log-redeadline nil
2763 "Information to record when the deadline date of a tasks is modified.
2765 Possible values are:
2767 nil Don't add anything, just change the date
2768 time Add a time stamp to the task
2769 note Prompt for a note and add it with template `org-log-note-headings'
2771 This option can also be set with on a per-file-basis with
2773 #+STARTUP: nologredeadline
2774 #+STARTUP: logredeadline
2775 #+STARTUP: lognoteredeadline
2777 You can have local logging settings for a subtree by setting the LOGGING
2778 property to one or more of these keywords."
2779 :group 'org-todo
2780 :group 'org-progress
2781 :type '(choice
2782 (const :tag "No logging" nil)
2783 (const :tag "Record timestamp" time)
2784 (const :tag "Record timestamp with note." note)))
2786 (defcustom org-log-note-clock-out nil
2787 "Non-nil means record a note when clocking out of an item.
2788 This can also be configured on a per-file basis by adding one of
2789 the following lines anywhere in the buffer:
2791 #+STARTUP: lognoteclock-out
2792 #+STARTUP: nolognoteclock-out"
2793 :group 'org-todo
2794 :group 'org-progress
2795 :type 'boolean)
2797 (defcustom org-log-done-with-time t
2798 "Non-nil means the CLOSED time stamp will contain date and time.
2799 When nil, only the date will be recorded."
2800 :group 'org-progress
2801 :type 'boolean)
2803 (defcustom org-log-note-headings
2804 '((done . "CLOSING NOTE %t")
2805 (state . "State %-12s from %-12S %t")
2806 (note . "Note taken on %t")
2807 (reschedule . "Rescheduled from %S on %t")
2808 (delschedule . "Not scheduled, was %S on %t")
2809 (redeadline . "New deadline from %S on %t")
2810 (deldeadline . "Removed deadline, was %S on %t")
2811 (refile . "Refiled on %t")
2812 (clock-out . ""))
2813 "Headings for notes added to entries.
2814 The value is an alist, with the car being a symbol indicating the note
2815 context, and the cdr is the heading to be used. The heading may also be the
2816 empty string.
2817 %t in the heading will be replaced by a time stamp.
2818 %T will be an active time stamp instead the default inactive one
2819 %d will be replaced by a short-format time stamp.
2820 %D will be replaced by an active short-format time stamp.
2821 %s will be replaced by the new TODO state, in double quotes.
2822 %S will be replaced by the old TODO state, in double quotes.
2823 %u will be replaced by the user name.
2824 %U will be replaced by the full user name.
2826 In fact, it is not a good idea to change the `state' entry, because
2827 agenda log mode depends on the format of these entries."
2828 :group 'org-todo
2829 :group 'org-progress
2830 :type '(list :greedy t
2831 (cons (const :tag "Heading when closing an item" done) string)
2832 (cons (const :tag
2833 "Heading when changing todo state (todo sequence only)"
2834 state) string)
2835 (cons (const :tag "Heading when just taking a note" note) string)
2836 (cons (const :tag "Heading when rescheduling" reschedule) string)
2837 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2838 (cons (const :tag "Heading when changing deadline" redeadline) string)
2839 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2840 (cons (const :tag "Heading when refiling" refile) string)
2841 (cons (const :tag "Heading when clocking out" clock-out) string)))
2843 (unless (assq 'note org-log-note-headings)
2844 (push '(note . "%t") org-log-note-headings))
2846 (defcustom org-log-into-drawer nil
2847 "Non-nil means insert state change notes and time stamps into a drawer.
2848 When nil, state changes notes will be inserted after the headline and
2849 any scheduling and clock lines, but not inside a drawer.
2851 The value of this variable should be the name of the drawer to use.
2852 LOGBOOK is proposed as the default drawer for this purpose, you can
2853 also set this to a string to define the drawer of your choice.
2855 A value of t is also allowed, representing \"LOGBOOK\".
2857 A value of t or nil can also be set with on a per-file-basis with
2859 #+STARTUP: logdrawer
2860 #+STARTUP: nologdrawer
2862 If this variable is set, `org-log-state-notes-insert-after-drawers'
2863 will be ignored.
2865 You can set the property LOG_INTO_DRAWER to overrule this setting for
2866 a subtree."
2867 :group 'org-todo
2868 :group 'org-progress
2869 :type '(choice
2870 (const :tag "Not into a drawer" nil)
2871 (const :tag "LOGBOOK" t)
2872 (string :tag "Other")))
2874 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2876 (defun org-log-into-drawer ()
2877 "Return the value of `org-log-into-drawer', but let properties overrule.
2878 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2879 used instead of the default value."
2880 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2881 (cond
2882 ((not p) org-log-into-drawer)
2883 ((equal p "nil") nil)
2884 ((equal p "t") "LOGBOOK")
2885 (t p))))
2887 (defcustom org-log-state-notes-insert-after-drawers nil
2888 "Non-nil means insert state change notes after any drawers in entry.
2889 Only the drawers that *immediately* follow the headline and the
2890 deadline/scheduled line are skipped.
2891 When nil, insert notes right after the heading and perhaps the line
2892 with deadline/scheduling if present.
2894 This variable will have no effect if `org-log-into-drawer' is
2895 set."
2896 :group 'org-todo
2897 :group 'org-progress
2898 :type 'boolean)
2900 (defcustom org-log-states-order-reversed t
2901 "Non-nil means the latest state note will be directly after heading.
2902 When nil, the state change notes will be ordered according to time.
2904 This option can also be set with on a per-file-basis with
2906 #+STARTUP: logstatesreversed
2907 #+STARTUP: nologstatesreversed"
2908 :group 'org-todo
2909 :group 'org-progress
2910 :type 'boolean)
2912 (defcustom org-todo-repeat-to-state nil
2913 "The TODO state to which a repeater should return the repeating task.
2914 By default this is the first task in a TODO sequence, or the previous state
2915 in a TODO_TYP set. But you can specify another task here.
2916 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2917 :group 'org-todo
2918 :version "24.1"
2919 :type '(choice (const :tag "Head of sequence" nil)
2920 (string :tag "Specific state")))
2922 (defcustom org-log-repeat 'time
2923 "Non-nil means record moving through the DONE state when triggering repeat.
2924 An auto-repeating task is immediately switched back to TODO when
2925 marked DONE. If you are not logging state changes (by adding \"@\"
2926 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2927 record a closing note, there will be no record of the task moving
2928 through DONE. This variable forces taking a note anyway.
2930 nil Don't force a record
2931 time Record a time stamp
2932 note Prompt for a note and add it with template `org-log-note-headings'
2934 This option can also be set with on a per-file-basis with
2936 #+STARTUP: nologrepeat
2937 #+STARTUP: logrepeat
2938 #+STARTUP: lognoterepeat
2940 You can have local logging settings for a subtree by setting the LOGGING
2941 property to one or more of these keywords."
2942 :group 'org-todo
2943 :group 'org-progress
2944 :type '(choice
2945 (const :tag "Don't force a record" nil)
2946 (const :tag "Force recording the DONE state" time)
2947 (const :tag "Force recording a note with the DONE state" note)))
2950 (defgroup org-priorities nil
2951 "Priorities in Org-mode."
2952 :tag "Org Priorities"
2953 :group 'org-todo)
2955 (defcustom org-enable-priority-commands t
2956 "Non-nil means priority commands are active.
2957 When nil, these commands will be disabled, so that you never accidentally
2958 set a priority."
2959 :group 'org-priorities
2960 :type 'boolean)
2962 (defcustom org-highest-priority ?A
2963 "The highest priority of TODO items. A character like ?A, ?B etc.
2964 Must have a smaller ASCII number than `org-lowest-priority'."
2965 :group 'org-priorities
2966 :type 'character)
2968 (defcustom org-lowest-priority ?C
2969 "The lowest priority of TODO items. A character like ?A, ?B etc.
2970 Must have a larger ASCII number than `org-highest-priority'."
2971 :group 'org-priorities
2972 :type 'character)
2974 (defcustom org-default-priority ?B
2975 "The default priority of TODO items.
2976 This is the priority an item gets if no explicit priority is given.
2977 When starting to cycle on an empty priority the first step in the cycle
2978 depends on `org-priority-start-cycle-with-default'. The resulting first
2979 step priority must not exceed the range from `org-highest-priority' to
2980 `org-lowest-priority' which means that `org-default-priority' has to be
2981 in this range exclusive or inclusive the range boundaries. Else the
2982 first step refuses to set the default and the second will fall back
2983 to (depending on the command used) the highest or lowest priority."
2984 :group 'org-priorities
2985 :type 'character)
2987 (defcustom org-priority-start-cycle-with-default t
2988 "Non-nil means start with default priority when starting to cycle.
2989 When this is nil, the first step in the cycle will be (depending on the
2990 command used) one higher or lower than the default priority.
2991 See also `org-default-priority'."
2992 :group 'org-priorities
2993 :type 'boolean)
2995 (defcustom org-get-priority-function nil
2996 "Function to extract the priority from a string.
2997 The string is normally the headline. If this is nil Org computes the
2998 priority from the priority cookie like [#A] in the headline. It returns
2999 an integer, increasing by 1000 for each priority level.
3000 The user can set a different function here, which should take a string
3001 as an argument and return the numeric priority."
3002 :group 'org-priorities
3003 :version "24.1"
3004 :type '(choice
3005 (const nil)
3006 (function)))
3008 (defgroup org-time nil
3009 "Options concerning time stamps and deadlines in Org-mode."
3010 :tag "Org Time"
3011 :group 'org)
3013 (defcustom org-insert-labeled-timestamps-at-point nil
3014 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3015 When nil, these labeled time stamps are forces into the second line of an
3016 entry, just after the headline. When scheduling from the global TODO list,
3017 the time stamp will always be forced into the second line."
3018 :group 'org-time
3019 :type 'boolean)
3021 (defcustom org-time-stamp-rounding-minutes '(0 5)
3022 "Number of minutes to round time stamps to.
3023 These are two values, the first applies when first creating a time stamp.
3024 The second applies when changing it with the commands `S-up' and `S-down'.
3025 When changing the time stamp, this means that it will change in steps
3026 of N minutes, as given by the second value.
3028 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3029 numbers should be factors of 60, so for example 5, 10, 15.
3031 When this is larger than 1, you can still force an exact time stamp by using
3032 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3033 and by using a prefix arg to `S-up/down' to specify the exact number
3034 of minutes to shift."
3035 :group 'org-time
3036 :get (lambda (var) ; Make sure both elements are there
3037 (if (integerp (default-value var))
3038 (list (default-value var) 5)
3039 (default-value var)))
3040 :type '(list
3041 (integer :tag "when inserting times")
3042 (integer :tag "when modifying times")))
3044 ;; Normalize old customizations of this variable.
3045 (when (integerp org-time-stamp-rounding-minutes)
3046 (setq org-time-stamp-rounding-minutes
3047 (list org-time-stamp-rounding-minutes
3048 org-time-stamp-rounding-minutes)))
3050 (defcustom org-display-custom-times nil
3051 "Non-nil means overlay custom formats over all time stamps.
3052 The formats are defined through the variable `org-time-stamp-custom-formats'.
3053 To turn this on on a per-file basis, insert anywhere in the file:
3054 #+STARTUP: customtime"
3055 :group 'org-time
3056 :set 'set-default
3057 :type 'sexp)
3058 (make-variable-buffer-local 'org-display-custom-times)
3060 (defcustom org-time-stamp-custom-formats
3061 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3062 "Custom formats for time stamps. See `format-time-string' for the syntax.
3063 These are overlaid over the default ISO format if the variable
3064 `org-display-custom-times' is set. Time like %H:%M should be at the
3065 end of the second format. The custom formats are also honored by export
3066 commands, if custom time display is turned on at the time of export."
3067 :group 'org-time
3068 :type 'sexp)
3070 (defun org-time-stamp-format (&optional long inactive)
3071 "Get the right format for a time string."
3072 (let ((f (if long (cdr org-time-stamp-formats)
3073 (car org-time-stamp-formats))))
3074 (if inactive
3075 (concat "[" (substring f 1 -1) "]")
3076 f)))
3078 (defcustom org-time-clocksum-format
3079 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3080 "The format string used when creating CLOCKSUM lines.
3081 This is also used when Org mode generates a time duration.
3083 The value can be a single format string containing two
3084 %-sequences, which will be filled with the number of hours and
3085 minutes in that order.
3087 Alternatively, the value can be a plist associating any of the
3088 keys :years, :months, :weeks, :days, :hours or :minutes with
3089 format strings. The time duration is formatted using only the
3090 time components that are needed and concatenating the results.
3091 If a time unit in absent, it falls back to the next smallest
3092 unit.
3094 The keys :require-years, :require-months, :require-days,
3095 :require-weeks, :require-hours, :require-minutes are also
3096 meaningful. A non-nil value for these keys indicates that the
3097 corresponding time component should always be included, even if
3098 its value is 0.
3101 For example,
3103 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3104 :require-minutes t)
3106 means durations longer than a day will be expressed in days,
3107 hours and minutes, and durations less than a day will always be
3108 expressed in hours and minutes (even for durations less than an
3109 hour).
3111 The value
3113 \(:days \"%dd\" :minutes \"%dm\")
3115 means durations longer than a day will be expressed in days and
3116 minutes, and durations less than a day will be expressed entirely
3117 in minutes (even for durations longer than an hour)."
3118 :group 'org-time
3119 :group 'org-clock
3120 :version "24.4"
3121 :package-version '(Org . "8.0")
3122 :type '(choice (string :tag "Format string")
3123 (set :tag "Plist"
3124 (group :inline t (const :tag "Years" :years)
3125 (string :tag "Format string"))
3126 (group :inline t
3127 (const :tag "Always show years" :require-years)
3128 (const t))
3129 (group :inline t (const :tag "Months" :months)
3130 (string :tag "Format string"))
3131 (group :inline t
3132 (const :tag "Always show months" :require-months)
3133 (const t))
3134 (group :inline t (const :tag "Weeks" :weeks)
3135 (string :tag "Format string"))
3136 (group :inline t
3137 (const :tag "Always show weeks" :require-weeks)
3138 (const t))
3139 (group :inline t (const :tag "Days" :days)
3140 (string :tag "Format string"))
3141 (group :inline t
3142 (const :tag "Always show days" :require-days)
3143 (const t))
3144 (group :inline t (const :tag "Hours" :hours)
3145 (string :tag "Format string"))
3146 (group :inline t
3147 (const :tag "Always show hours" :require-hours)
3148 (const t))
3149 (group :inline t (const :tag "Minutes" :minutes)
3150 (string :tag "Format string"))
3151 (group :inline t
3152 (const :tag "Always show minutes" :require-minutes)
3153 (const t)))))
3155 (defcustom org-time-clocksum-use-fractional nil
3156 "When non-nil, \\[org-clock-display] uses fractional times.
3157 See `org-time-clocksum-format' for more on time clock formats."
3158 :group 'org-time
3159 :group 'org-clock
3160 :version "24.3"
3161 :type 'boolean)
3163 (defcustom org-time-clocksum-use-effort-durations nil
3164 "When non-nil, \\[org-clock-display] uses effort durations.
3165 E.g. by default, one day is considered to be a 8 hours effort,
3166 so a task that has been clocked for 16 hours will be displayed
3167 as during 2 days in the clock display or in the clocktable.
3169 See `org-effort-durations' on how to set effort durations
3170 and `org-time-clocksum-format' for more on time clock formats."
3171 :group 'org-time
3172 :group 'org-clock
3173 :version "24.4"
3174 :package-version '(Org . "8.0")
3175 :type 'boolean)
3177 (defcustom org-time-clocksum-fractional-format "%.2f"
3178 "The format string used when creating CLOCKSUM lines,
3179 or when Org mode generates a time duration, if
3180 `org-time-clocksum-use-fractional' is enabled.
3182 The value can be a single format string containing one
3183 %-sequence, which will be filled with the number of hours as
3184 a float.
3186 Alternatively, the value can be a plist associating any of the
3187 keys :years, :months, :weeks, :days, :hours or :minutes with
3188 a format string. The time duration is formatted using the
3189 largest time unit which gives a non-zero integer part. If all
3190 specified formats have zero integer part, the smallest time unit
3191 is used."
3192 :group 'org-time
3193 :type '(choice (string :tag "Format string")
3194 (set (group :inline t (const :tag "Years" :years)
3195 (string :tag "Format string"))
3196 (group :inline t (const :tag "Months" :months)
3197 (string :tag "Format string"))
3198 (group :inline t (const :tag "Weeks" :weeks)
3199 (string :tag "Format string"))
3200 (group :inline t (const :tag "Days" :days)
3201 (string :tag "Format string"))
3202 (group :inline t (const :tag "Hours" :hours)
3203 (string :tag "Format string"))
3204 (group :inline t (const :tag "Minutes" :minutes)
3205 (string :tag "Format string")))))
3207 (defcustom org-deadline-warning-days 14
3208 "Number of days before expiration during which a deadline becomes active.
3209 This variable governs the display in sparse trees and in the agenda.
3210 When 0 or negative, it means use this number (the absolute value of it)
3211 even if a deadline has a different individual lead time specified.
3213 Custom commands can set this variable in the options section."
3214 :group 'org-time
3215 :group 'org-agenda-daily/weekly
3216 :type 'integer)
3218 (defcustom org-scheduled-delay-days 0
3219 "Number of days before a scheduled item becomes active.
3220 This variable governs the display in sparse trees and in the agenda.
3221 The default value (i.e. 0) means: don't delay scheduled item.
3222 When negative, it means use this number (the absolute value of it)
3223 even if a scheduled item has a different individual delay time
3224 specified.
3226 Custom commands can set this variable in the options section."
3227 :group 'org-time
3228 :group 'org-agenda-daily/weekly
3229 :version "24.4"
3230 :package-version '(Org . "8.0")
3231 :type 'integer)
3233 (defcustom org-read-date-prefer-future t
3234 "Non-nil means assume future for incomplete date input from user.
3235 This affects the following situations:
3236 1. The user gives a month but not a year.
3237 For example, if it is April and you enter \"feb 2\", this will be read
3238 as Feb 2, *next* year. \"May 5\", however, will be this year.
3239 2. The user gives a day, but no month.
3240 For example, if today is the 15th, and you enter \"3\", Org-mode will
3241 read this as the third of *next* month. However, if you enter \"17\",
3242 it will be considered as *this* month.
3244 If you set this variable to the symbol `time', then also the following
3245 will work:
3247 3. If the user gives a time.
3248 If the time is before now, it will be interpreted as tomorrow.
3250 Currently none of this works for ISO week specifications.
3252 When this option is nil, the current day, month and year will always be
3253 used as defaults.
3255 See also `org-agenda-jump-prefer-future'."
3256 :group 'org-time
3257 :type '(choice
3258 (const :tag "Never" nil)
3259 (const :tag "Check month and day" t)
3260 (const :tag "Check month, day, and time" time)))
3262 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3263 "Should the agenda jump command prefer the future for incomplete dates?
3264 The default is to do the same as configured in `org-read-date-prefer-future'.
3265 But you can also set a deviating value here.
3266 This may t or nil, or the symbol `org-read-date-prefer-future'."
3267 :group 'org-agenda
3268 :group 'org-time
3269 :version "24.1"
3270 :type '(choice
3271 (const :tag "Use org-read-date-prefer-future"
3272 org-read-date-prefer-future)
3273 (const :tag "Never" nil)
3274 (const :tag "Always" t)))
3276 (defcustom org-read-date-force-compatible-dates t
3277 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3279 Depending on the system Emacs is running on, certain dates cannot
3280 be represented with the type used internally to represent time.
3281 Dates between 1970-1-1 and 2038-1-1 can always be represented
3282 correctly. Some systems allow for earlier dates, some for later,
3283 some for both. One way to find out it to insert any date into an
3284 Org buffer, putting the cursor on the year and hitting S-up and
3285 S-down to test the range.
3287 When this variable is set to t, the date/time prompt will not let
3288 you specify dates outside the 1970-2037 range, so it is certain that
3289 these dates will work in whatever version of Emacs you are
3290 running, and also that you can move a file from one Emacs implementation
3291 to another. WHenever Org is forcing the year for you, it will display
3292 a message and beep.
3294 When this variable is nil, Org will check if the date is
3295 representable in the specific Emacs implementation you are using.
3296 If not, it will force a year, usually the current year, and beep
3297 to remind you. Currently this setting is not recommended because
3298 the likelihood that you will open your Org files in an Emacs that
3299 has limited date range is not negligible.
3301 A workaround for this problem is to use diary sexp dates for time
3302 stamps outside of this range."
3303 :group 'org-time
3304 :version "24.1"
3305 :type 'boolean)
3307 (defcustom org-read-date-display-live t
3308 "Non-nil means display current interpretation of date prompt live.
3309 This display will be in an overlay, in the minibuffer."
3310 :group 'org-time
3311 :type 'boolean)
3313 (defcustom org-read-date-popup-calendar t
3314 "Non-nil means pop up a calendar when prompting for a date.
3315 In the calendar, the date can be selected with mouse-1. However, the
3316 minibuffer will also be active, and you can simply enter the date as well.
3317 When nil, only the minibuffer will be available."
3318 :group 'org-time
3319 :type 'boolean)
3320 (org-defvaralias 'org-popup-calendar-for-date-prompt
3321 'org-read-date-popup-calendar)
3323 (make-obsolete-variable
3324 'org-read-date-minibuffer-setup-hook
3325 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3326 (defcustom org-read-date-minibuffer-setup-hook nil
3327 "Hook to be used to set up keys for the date/time interface.
3328 Add key definitions to `minibuffer-local-map', which will be a
3329 temporary copy.
3331 WARNING: This option is obsolete, you should use
3332 `org-read-date-minibuffer-local-map' to set up keys."
3333 :group 'org-time
3334 :type 'hook)
3336 (defcustom org-extend-today-until 0
3337 "The hour when your day really ends. Must be an integer.
3338 This has influence for the following applications:
3339 - When switching the agenda to \"today\". It it is still earlier than
3340 the time given here, the day recognized as TODAY is actually yesterday.
3341 - When a date is read from the user and it is still before the time given
3342 here, the current date and time will be assumed to be yesterday, 23:59.
3343 Also, timestamps inserted in capture templates follow this rule.
3345 IMPORTANT: This is a feature whose implementation is and likely will
3346 remain incomplete. Really, it is only here because past midnight seems to
3347 be the favorite working time of John Wiegley :-)"
3348 :group 'org-time
3349 :type 'integer)
3351 (defcustom org-use-effective-time nil
3352 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3353 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3354 \"effective time\" of any timestamps between midnight and 8am will be
3355 23:59 of the previous day."
3356 :group 'org-time
3357 :version "24.1"
3358 :type 'boolean)
3360 (defcustom org-use-last-clock-out-time-as-effective-time nil
3361 "When non-nil, use the last clock out time for `org-todo'.
3362 Note that this option has precedence over the combined use of
3363 `org-use-effective-time' and `org-extend-today-until'."
3364 :group 'org-time
3365 :version "24.4"
3366 :package-version '(Org . "8.0")
3367 :type 'boolean)
3369 (defcustom org-edit-timestamp-down-means-later nil
3370 "Non-nil means S-down will increase the time in a time stamp.
3371 When nil, S-up will increase."
3372 :group 'org-time
3373 :type 'boolean)
3375 (defcustom org-calendar-follow-timestamp-change t
3376 "Non-nil means make the calendar window follow timestamp changes.
3377 When a timestamp is modified and the calendar window is visible, it will be
3378 moved to the new date."
3379 :group 'org-time
3380 :type 'boolean)
3382 (defgroup org-tags nil
3383 "Options concerning tags in Org-mode."
3384 :tag "Org Tags"
3385 :group 'org)
3387 (defcustom org-tag-alist nil
3388 "List of tags allowed in Org-mode files.
3389 When this list is nil, Org-mode will base TAG input on what is already in the
3390 buffer.
3391 The value of this variable is an alist, the car of each entry must be a
3392 keyword as a string, the cdr may be a character that is used to select
3393 that tag through the fast-tag-selection interface.
3394 See the manual for details."
3395 :group 'org-tags
3396 :type '(repeat
3397 (choice
3398 (cons (string :tag "Tag name")
3399 (character :tag "Access char"))
3400 (list :tag "Start radio group"
3401 (const :startgroup)
3402 (option (string :tag "Group description")))
3403 (list :tag "Group tags delimiter"
3404 (const :grouptags))
3405 (list :tag "End radio group"
3406 (const :endgroup)
3407 (option (string :tag "Group description")))
3408 (const :tag "New line" (:newline)))))
3410 (defcustom org-tag-persistent-alist nil
3411 "List of tags that will always appear in all Org-mode files.
3412 This is in addition to any in buffer settings or customizations
3413 of `org-tag-alist'.
3414 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3415 The value of this variable is an alist, the car of each entry must be a
3416 keyword as a string, the cdr may be a character that is used to select
3417 that tag through the fast-tag-selection interface.
3418 See the manual for details.
3419 To disable these tags on a per-file basis, insert anywhere in the file:
3420 #+STARTUP: noptag"
3421 :group 'org-tags
3422 :type '(repeat
3423 (choice
3424 (cons (string :tag "Tag name")
3425 (character :tag "Access char"))
3426 (const :tag "Start radio group" (:startgroup))
3427 (const :tag "Group tags delimiter" (:grouptags))
3428 (const :tag "End radio group" (:endgroup))
3429 (const :tag "New line" (:newline)))))
3431 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3432 "If non-nil, always offer completion for all tags of all agenda files.
3433 Instead of customizing this variable directly, you might want to
3434 set it locally for capture buffers, because there no list of
3435 tags in that file can be created dynamically (there are none).
3437 (add-hook 'org-capture-mode-hook
3438 (lambda ()
3439 (set (make-local-variable
3440 'org-complete-tags-always-offer-all-agenda-tags)
3441 t)))"
3442 :group 'org-tags
3443 :version "24.1"
3444 :type 'boolean)
3446 (defvar org-file-tags nil
3447 "List of tags that can be inherited by all entries in the file.
3448 The tags will be inherited if the variable `org-use-tag-inheritance'
3449 says they should be.
3450 This variable is populated from #+FILETAGS lines.")
3452 (defcustom org-use-fast-tag-selection 'auto
3453 "Non-nil means use fast tag selection scheme.
3454 This is a special interface to select and deselect tags with single keys.
3455 When nil, fast selection is never used.
3456 When the symbol `auto', fast selection is used if and only if selection
3457 characters for tags have been configured, either through the variable
3458 `org-tag-alist' or through a #+TAGS line in the buffer.
3459 When t, fast selection is always used and selection keys are assigned
3460 automatically if necessary."
3461 :group 'org-tags
3462 :type '(choice
3463 (const :tag "Always" t)
3464 (const :tag "Never" nil)
3465 (const :tag "When selection characters are configured" auto)))
3467 (defcustom org-fast-tag-selection-single-key nil
3468 "Non-nil means fast tag selection exits after first change.
3469 When nil, you have to press RET to exit it.
3470 During fast tag selection, you can toggle this flag with `C-c'.
3471 This variable can also have the value `expert'. In this case, the window
3472 displaying the tags menu is not even shown, until you press C-c again."
3473 :group 'org-tags
3474 :type '(choice
3475 (const :tag "No" nil)
3476 (const :tag "Yes" t)
3477 (const :tag "Expert" expert)))
3479 (defvar org-fast-tag-selection-include-todo nil
3480 "Non-nil means fast tags selection interface will also offer TODO states.
3481 This is an undocumented feature, you should not rely on it.")
3483 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3484 "The column to which tags should be indented in a headline.
3485 If this number is positive, it specifies the column. If it is negative,
3486 it means that the tags should be flushright to that column. For example,
3487 -80 works well for a normal 80 character screen.
3488 When 0, place tags directly after headline text, with only one space in
3489 between."
3490 :group 'org-tags
3491 :type 'integer)
3493 (defcustom org-auto-align-tags t
3494 "Non-nil keeps tags aligned when modifying headlines.
3495 Some operations (i.e. demoting) change the length of a headline and
3496 therefore shift the tags around. With this option turned on, after
3497 each such operation the tags are again aligned to `org-tags-column'."
3498 :group 'org-tags
3499 :type 'boolean)
3501 (defcustom org-use-tag-inheritance t
3502 "Non-nil means tags in levels apply also for sublevels.
3503 When nil, only the tags directly given in a specific line apply there.
3504 This may also be a list of tags that should be inherited, or a regexp that
3505 matches tags that should be inherited. Additional control is possible
3506 with the variable `org-tags-exclude-from-inheritance' which gives an
3507 explicit list of tags to be excluded from inheritance, even if the value of
3508 `org-use-tag-inheritance' would select it for inheritance.
3510 If this option is t, a match early-on in a tree can lead to a large
3511 number of matches in the subtree when constructing the agenda or creating
3512 a sparse tree. If you only want to see the first match in a tree during
3513 a search, check out the variable `org-tags-match-list-sublevels'."
3514 :group 'org-tags
3515 :type '(choice
3516 (const :tag "Not" nil)
3517 (const :tag "Always" t)
3518 (repeat :tag "Specific tags" (string :tag "Tag"))
3519 (regexp :tag "Tags matched by regexp")))
3521 (defcustom org-tags-exclude-from-inheritance nil
3522 "List of tags that should never be inherited.
3523 This is a way to exclude a few tags from inheritance. For way to do
3524 the opposite, to actively allow inheritance for selected tags,
3525 see the variable `org-use-tag-inheritance'."
3526 :group 'org-tags
3527 :type '(repeat (string :tag "Tag")))
3529 (defun org-tag-inherit-p (tag)
3530 "Check if TAG is one that should be inherited."
3531 (cond
3532 ((member tag org-tags-exclude-from-inheritance) nil)
3533 ((eq org-use-tag-inheritance t) t)
3534 ((not org-use-tag-inheritance) nil)
3535 ((stringp org-use-tag-inheritance)
3536 (string-match org-use-tag-inheritance tag))
3537 ((listp org-use-tag-inheritance)
3538 (member tag org-use-tag-inheritance))
3539 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3541 (defcustom org-tags-match-list-sublevels t
3542 "Non-nil means list also sublevels of headlines matching a search.
3543 This variable applies to tags/property searches, and also to stuck
3544 projects because this search is based on a tags match as well.
3546 When set to the symbol `indented', sublevels are indented with
3547 leading dots.
3549 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3550 the sublevels of a headline matching a tag search often also match
3551 the same search. Listing all of them can create very long lists.
3552 Setting this variable to nil causes subtrees of a match to be skipped.
3554 This variable is semi-obsolete and probably should always be true. It
3555 is better to limit inheritance to certain tags using the variables
3556 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "No, don't list them" nil)
3560 (const :tag "Yes, do list them" t)
3561 (const :tag "List them, indented with leading dots" indented)))
3563 (defcustom org-tags-sort-function nil
3564 "When set, tags are sorted using this function as a comparator."
3565 :group 'org-tags
3566 :type '(choice
3567 (const :tag "No sorting" nil)
3568 (const :tag "Alphabetical" string<)
3569 (const :tag "Reverse alphabetical" string>)
3570 (function :tag "Custom function" nil)))
3572 (defvar org-tags-history nil
3573 "History of minibuffer reads for tags.")
3574 (defvar org-last-tags-completion-table nil
3575 "The last used completion table for tags.")
3576 (defvar org-after-tags-change-hook nil
3577 "Hook that is run after the tags in a line have changed.")
3579 (defgroup org-properties nil
3580 "Options concerning properties in Org-mode."
3581 :tag "Org Properties"
3582 :group 'org)
3584 (defcustom org-property-format "%-10s %s"
3585 "How property key/value pairs should be formatted by `indent-line'.
3586 When `indent-line' hits a property definition, it will format the line
3587 according to this format, mainly to make sure that the values are
3588 lined-up with respect to each other."
3589 :group 'org-properties
3590 :type 'string)
3592 (defcustom org-properties-postprocess-alist nil
3593 "Alist of properties and functions to adjust inserted values.
3594 Elements of this alist must be of the form
3596 ([string] [function])
3598 where [string] must be a property name and [function] must be a
3599 lambda expression: this lambda expression must take one argument,
3600 the value to adjust, and return the new value as a string.
3602 For example, this element will allow the property \"Remaining\"
3603 to be updated wrt the relation between the \"Effort\" property
3604 and the clock summary:
3606 ((\"Remaining\" (lambda(value)
3607 (let ((clocksum (org-clock-sum-current-item))
3608 (effort (org-duration-string-to-minutes
3609 (org-entry-get (point) \"Effort\"))))
3610 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3611 :group 'org-properties
3612 :version "24.1"
3613 :type '(alist :key-type (string :tag "Property")
3614 :value-type (function :tag "Function")))
3616 (defcustom org-use-property-inheritance nil
3617 "Non-nil means properties apply also for sublevels.
3619 This setting is chiefly used during property searches. Turning it on can
3620 cause significant overhead when doing a search, which is why it is not
3621 on by default.
3623 When nil, only the properties directly given in the current entry count.
3624 When t, every property is inherited. The value may also be a list of
3625 properties that should have inheritance, or a regular expression matching
3626 properties that should be inherited.
3628 However, note that some special properties use inheritance under special
3629 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3630 and the properties ending in \"_ALL\" when they are used as descriptor
3631 for valid values of a property.
3633 Note for programmers:
3634 When querying an entry with `org-entry-get', you can control if inheritance
3635 should be used. By default, `org-entry-get' looks only at the local
3636 properties. You can request inheritance by setting the inherit argument
3637 to t (to force inheritance) or to `selective' (to respect the setting
3638 in this variable)."
3639 :group 'org-properties
3640 :type '(choice
3641 (const :tag "Not" nil)
3642 (const :tag "Always" t)
3643 (repeat :tag "Specific properties" (string :tag "Property"))
3644 (regexp :tag "Properties matched by regexp")))
3646 (defun org-property-inherit-p (property)
3647 "Check if PROPERTY is one that should be inherited."
3648 (cond
3649 ((eq org-use-property-inheritance t) t)
3650 ((not org-use-property-inheritance) nil)
3651 ((stringp org-use-property-inheritance)
3652 (string-match org-use-property-inheritance property))
3653 ((listp org-use-property-inheritance)
3654 (member property org-use-property-inheritance))
3655 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3657 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3658 "The default column format, if no other format has been defined.
3659 This variable can be set on the per-file basis by inserting a line
3661 #+COLUMNS: %25ITEM ....."
3662 :group 'org-properties
3663 :type 'string)
3665 (defcustom org-columns-ellipses ".."
3666 "The ellipses to be used when a field in column view is truncated.
3667 When this is the empty string, as many characters as possible are shown,
3668 but then there will be no visual indication that the field has been truncated.
3669 When this is a string of length N, the last N characters of a truncated
3670 field are replaced by this string. If the column is narrower than the
3671 ellipses string, only part of the ellipses string will be shown."
3672 :group 'org-properties
3673 :type 'string)
3675 (defcustom org-columns-modify-value-for-display-function nil
3676 "Function that modifies values for display in column view.
3677 For example, it can be used to cut out a certain part from a time stamp.
3678 The function must take 2 arguments:
3680 column-title The title of the column (*not* the property name)
3681 value The value that should be modified.
3683 The function should return the value that should be displayed,
3684 or nil if the normal value should be used."
3685 :group 'org-properties
3686 :type '(choice (const nil) (function)))
3688 (defconst org-global-properties-fixed
3689 '(("VISIBILITY_ALL" . "folded children content all")
3690 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3691 "List of property/value pairs that can be inherited by any entry.
3693 These are fixed values, for the preset properties. The user variable
3694 that can be used to add to this list is `org-global-properties'.
3696 The entries in this list are cons cells where the car is a property
3697 name and cdr is a string with the value. If the value represents
3698 multiple items like an \"_ALL\" property, separate the items by
3699 spaces.")
3701 (defcustom org-global-properties nil
3702 "List of property/value pairs that can be inherited by any entry.
3704 This list will be combined with the constant `org-global-properties-fixed'.
3706 The entries in this list are cons cells where the car is a property
3707 name and cdr is a string with the value.
3709 You can set buffer-local values for the same purpose in the variable
3710 `org-file-properties' this by adding lines like
3712 #+PROPERTY: NAME VALUE"
3713 :group 'org-properties
3714 :type '(repeat
3715 (cons (string :tag "Property")
3716 (string :tag "Value"))))
3718 (defvar org-file-properties nil
3719 "List of property/value pairs that can be inherited by any entry.
3720 Valid for the current buffer.
3721 This variable is populated from #+PROPERTY lines.")
3722 (make-variable-buffer-local 'org-file-properties)
3724 (defgroup org-agenda nil
3725 "Options concerning agenda views in Org-mode."
3726 :tag "Org Agenda"
3727 :group 'org)
3729 (defvar org-category nil
3730 "Variable used by org files to set a category for agenda display.
3731 Such files should use a file variable to set it, for example
3733 # -*- mode: org; org-category: \"ELisp\"
3735 or contain a special line
3737 #+CATEGORY: ELisp
3739 If the file does not specify a category, then file's base name
3740 is used instead.")
3741 (make-variable-buffer-local 'org-category)
3742 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3744 (defcustom org-agenda-files nil
3745 "The files to be used for agenda display.
3746 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3747 \\[org-remove-file]. You can also use customize to edit the list.
3749 If an entry is a directory, all files in that directory that are matched by
3750 `org-agenda-file-regexp' will be part of the file list.
3752 If the value of the variable is not a list but a single file name, then
3753 the list of agenda files is actually stored and maintained in that file, one
3754 agenda file per line. In this file paths can be given relative to
3755 `org-directory'. Tilde expansion and environment variable substitution
3756 are also made."
3757 :group 'org-agenda
3758 :type '(choice
3759 (repeat :tag "List of files and directories" file)
3760 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3762 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3763 "Regular expression to match files for `org-agenda-files'.
3764 If any element in the list in that variable contains a directory instead
3765 of a normal file, all files in that directory that are matched by this
3766 regular expression will be included."
3767 :group 'org-agenda
3768 :type 'regexp)
3770 (defcustom org-agenda-text-search-extra-files nil
3771 "List of extra files to be searched by text search commands.
3772 These files will be searched in addition to the agenda files by the
3773 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3774 Note that these files will only be searched for text search commands,
3775 not for the other agenda views like todo lists, tag searches or the weekly
3776 agenda. This variable is intended to list notes and possibly archive files
3777 that should also be searched by these two commands.
3778 In fact, if the first element in the list is the symbol `agenda-archives',
3779 then all archive files of all agenda files will be added to the search
3780 scope."
3781 :group 'org-agenda
3782 :type '(set :greedy t
3783 (const :tag "Agenda Archives" agenda-archives)
3784 (repeat :inline t (file))))
3786 (org-defvaralias 'org-agenda-multi-occur-extra-files
3787 'org-agenda-text-search-extra-files)
3789 (defcustom org-agenda-skip-unavailable-files nil
3790 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3791 A nil value means to remove them, after a query, from the list."
3792 :group 'org-agenda
3793 :type 'boolean)
3795 (defcustom org-calendar-to-agenda-key [?c]
3796 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3797 The command `org-calendar-goto-agenda' will be bound to this key. The
3798 default is the character `c' because then `c' can be used to switch back and
3799 forth between agenda and calendar."
3800 :group 'org-agenda
3801 :type 'sexp)
3803 (defcustom org-calendar-insert-diary-entry-key [?i]
3804 "The key to be installed in `calendar-mode-map' for adding diary entries.
3805 This option is irrelevant until `org-agenda-diary-file' has been configured
3806 to point to an Org-mode file. When that is the case, the command
3807 `org-agenda-diary-entry' will be bound to the key given here, by default
3808 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3809 if you want to continue doing this, you need to change this to a different
3810 key."
3811 :group 'org-agenda
3812 :type 'sexp)
3814 (defcustom org-agenda-diary-file 'diary-file
3815 "File to which to add new entries with the `i' key in agenda and calendar.
3816 When this is the symbol `diary-file', the functionality in the Emacs
3817 calendar will be used to add entries to the `diary-file'. But when this
3818 points to a file, `org-agenda-diary-entry' will be used instead."
3819 :group 'org-agenda
3820 :type '(choice
3821 (const :tag "The standard Emacs diary file" diary-file)
3822 (file :tag "Special Org file diary entries")))
3824 (eval-after-load "calendar"
3825 '(progn
3826 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3827 'org-calendar-goto-agenda)
3828 (add-hook 'calendar-mode-hook
3829 (lambda ()
3830 (unless (eq org-agenda-diary-file 'diary-file)
3831 (define-key calendar-mode-map
3832 org-calendar-insert-diary-entry-key
3833 'org-agenda-diary-entry))))))
3835 (defgroup org-latex nil
3836 "Options for embedding LaTeX code into Org-mode."
3837 :tag "Org LaTeX"
3838 :group 'org)
3840 (defcustom org-format-latex-options
3841 '(:foreground default :background default :scale 1.0
3842 :html-foreground "Black" :html-background "Transparent"
3843 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3844 "Options for creating images from LaTeX fragments.
3845 This is a property list with the following properties:
3846 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3847 `default' means use the foreground of the default face.
3848 `auto' means use the foreground from the text face.
3849 :background the background color, or \"Transparent\".
3850 `default' means use the background of the default face.
3851 `auto' means use the background from the text face.
3852 :scale a scaling factor for the size of the images, to get more pixels
3853 :html-foreground, :html-background, :html-scale
3854 the same numbers for HTML export.
3855 :matchers a list indicating which matchers should be used to
3856 find LaTeX fragments. Valid members of this list are:
3857 \"begin\" find environments
3858 \"$1\" find single characters surrounded by $.$
3859 \"$\" find math expressions surrounded by $...$
3860 \"$$\" find math expressions surrounded by $$....$$
3861 \"\\(\" find math expressions surrounded by \\(...\\)
3862 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3863 :group 'org-latex
3864 :type 'plist)
3866 (defcustom org-format-latex-signal-error t
3867 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3868 When nil, just push out a message."
3869 :group 'org-latex
3870 :version "24.1"
3871 :type 'boolean)
3873 (defcustom org-latex-to-mathml-jar-file nil
3874 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3875 Use this to specify additional executable file say a jar file.
3877 When using MathToWeb as the converter, specify the full-path to
3878 your mathtoweb.jar file."
3879 :group 'org-latex
3880 :version "24.1"
3881 :type '(choice
3882 (const :tag "None" nil)
3883 (file :tag "JAR file" :must-match t)))
3885 (defcustom org-latex-to-mathml-convert-command nil
3886 "Command to convert LaTeX fragments to MathML.
3887 Replace format-specifiers in the command as noted below and use
3888 `shell-command' to convert LaTeX to MathML.
3889 %j: Executable file in fully expanded form as specified by
3890 `org-latex-to-mathml-jar-file'.
3891 %I: Input LaTeX file in fully expanded form
3892 %o: Output MathML file
3893 This command is used by `org-create-math-formula'.
3895 When using MathToWeb as the converter, set this to
3896 \"java -jar %j -unicode -force -df %o %I\"."
3897 :group 'org-latex
3898 :version "24.1"
3899 :type '(choice
3900 (const :tag "None" nil)
3901 (string :tag "\nShell command")))
3903 (defcustom org-latex-create-formula-image-program 'dvipng
3904 "Program to convert LaTeX fragments with.
3906 dvipng Process the LaTeX fragments to dvi file, then convert
3907 dvi files to png files using dvipng.
3908 This will also include processing of non-math environments.
3909 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3910 to convert pdf files to png files"
3911 :group 'org-latex
3912 :version "24.1"
3913 :type '(choice
3914 (const :tag "dvipng" dvipng)
3915 (const :tag "imagemagick" imagemagick)))
3917 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3918 "Path to store latex preview images.
3919 A relative path here creates many directories relative to the
3920 processed org files paths. An absolute path puts all preview
3921 images at the same place."
3922 :group 'org-latex
3923 :version "24.3"
3924 :type 'string)
3926 (defun org-format-latex-mathml-available-p ()
3927 "Return t if `org-latex-to-mathml-convert-command' is usable."
3928 (save-match-data
3929 (when (and (boundp 'org-latex-to-mathml-convert-command)
3930 org-latex-to-mathml-convert-command)
3931 (let ((executable (car (split-string
3932 org-latex-to-mathml-convert-command))))
3933 (when (executable-find executable)
3934 (if (string-match
3935 "%j" org-latex-to-mathml-convert-command)
3936 (file-readable-p org-latex-to-mathml-jar-file)
3937 t))))))
3939 (defcustom org-format-latex-header "\\documentclass{article}
3940 \\usepackage[usenames]{color}
3941 \[PACKAGES]
3942 \[DEFAULT-PACKAGES]
3943 \\pagestyle{empty} % do not remove
3944 % The settings below are copied from fullpage.sty
3945 \\setlength{\\textwidth}{\\paperwidth}
3946 \\addtolength{\\textwidth}{-3cm}
3947 \\setlength{\\oddsidemargin}{1.5cm}
3948 \\addtolength{\\oddsidemargin}{-2.54cm}
3949 \\setlength{\\evensidemargin}{\\oddsidemargin}
3950 \\setlength{\\textheight}{\\paperheight}
3951 \\addtolength{\\textheight}{-\\headheight}
3952 \\addtolength{\\textheight}{-\\headsep}
3953 \\addtolength{\\textheight}{-\\footskip}
3954 \\addtolength{\\textheight}{-3cm}
3955 \\setlength{\\topmargin}{1.5cm}
3956 \\addtolength{\\topmargin}{-2.54cm}"
3957 "The document header used for processing LaTeX fragments.
3958 It is imperative that this header make sure that no page number
3959 appears on the page. The package defined in the variables
3960 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3961 will either replace the placeholder \"[PACKAGES]\" in this
3962 header, or they will be appended."
3963 :group 'org-latex
3964 :type 'string)
3966 (defun org-set-packages-alist (var val)
3967 "Set the packages alist and make sure it has 3 elements per entry."
3968 (set var (mapcar (lambda (x)
3969 (if (and (consp x) (= (length x) 2))
3970 (list (car x) (nth 1 x) t)
3972 val)))
3974 (defun org-get-packages-alist (var)
3975 "Get the packages alist and make sure it has 3 elements per entry."
3976 (mapcar (lambda (x)
3977 (if (and (consp x) (= (length x) 2))
3978 (list (car x) (nth 1 x) t)
3980 (default-value var)))
3982 (defcustom org-latex-default-packages-alist
3983 '(("AUTO" "inputenc" t)
3984 ("T1" "fontenc" t)
3985 ("" "fixltx2e" nil)
3986 ("" "graphicx" t)
3987 ("" "longtable" nil)
3988 ("" "float" nil)
3989 ("" "wrapfig" nil)
3990 ("" "rotating" nil)
3991 ("normalem" "ulem" t)
3992 ("" "amsmath" t)
3993 ("" "textcomp" t)
3994 ("" "marvosym" t)
3995 ("" "wasysym" t)
3996 ("" "amssymb" t)
3997 ("" "hyperref" nil)
3998 "\\tolerance=1000")
3999 "Alist of default packages to be inserted in the header.
4001 Change this only if one of the packages here causes an
4002 incompatibility with another package you are using.
4004 The packages in this list are needed by one part or another of
4005 Org mode to function properly:
4007 - inputenc, fontenc: for basic font and character selection
4008 - fixltx2e: Important patches of LaTeX itself
4009 - graphicx: for including images
4010 - longtable: For multipage tables
4011 - float, wrapfig: for figure placement
4012 - rotating: for sideways figures and tables
4013 - ulem: for underline and strike-through
4014 - amsmath: for subscript and superscript and math environments
4015 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4016 for interpreting the entities in `org-entities'. You can skip
4017 some of these packages if you don't use any of their symbols.
4018 - hyperref: for cross references
4020 Therefore you should not modify this variable unless you know
4021 what you are doing. The one reason to change it anyway is that
4022 you might be loading some other package that conflicts with one
4023 of the default packages. Each element is either a cell or
4024 a string.
4026 A cell is of the format:
4028 \( \"options\" \"package\" SNIPPET-FLAG).
4030 If SNIPPET-FLAG is non-nil, the package also needs to be included
4031 when compiling LaTeX snippets into images for inclusion into
4032 non-LaTeX output.
4034 A string will be inserted as-is in the header of the document."
4035 :group 'org-latex
4036 :group 'org-export-latex
4037 :set 'org-set-packages-alist
4038 :get 'org-get-packages-alist
4039 :version "24.1"
4040 :type '(repeat
4041 (choice
4042 (list :tag "options/package pair"
4043 (string :tag "options")
4044 (string :tag "package")
4045 (boolean :tag "Snippet"))
4046 (string :tag "A line of LaTeX"))))
4048 (defcustom org-latex-packages-alist nil
4049 "Alist of packages to be inserted in every LaTeX header.
4051 These will be inserted after `org-latex-default-packages-alist'.
4052 Each element is either a cell or a string.
4054 A cell is of the format:
4056 \(\"options\" \"package\" SNIPPET-FLAG)
4058 SNIPPET-FLAG, when non-nil, indicates that this package is also
4059 needed when turning LaTeX snippets into images for inclusion into
4060 non-LaTeX output.
4062 A string will be inserted as-is in the header of the document.
4064 Make sure that you only list packages here which:
4066 - you want in every file;
4067 - do not conflict with the setup in `org-format-latex-header';
4068 - do not conflict with the default packages in
4069 `org-latex-default-packages-alist'."
4070 :group 'org-latex
4071 :group 'org-export-latex
4072 :set 'org-set-packages-alist
4073 :get 'org-get-packages-alist
4074 :type '(repeat
4075 (choice
4076 (list :tag "options/package pair"
4077 (string :tag "options")
4078 (string :tag "package")
4079 (boolean :tag "Snippet"))
4080 (string :tag "A line of LaTeX"))))
4082 (defgroup org-appearance nil
4083 "Settings for Org-mode appearance."
4084 :tag "Org Appearance"
4085 :group 'org)
4087 (defcustom org-level-color-stars-only nil
4088 "Non-nil means fontify only the stars in each headline.
4089 When nil, the entire headline is fontified.
4090 Changing it requires restart of `font-lock-mode' to become effective
4091 also in regions already fontified."
4092 :group 'org-appearance
4093 :type 'boolean)
4095 (defcustom org-hide-leading-stars nil
4096 "Non-nil means hide the first N-1 stars in a headline.
4097 This works by using the face `org-hide' for these stars. This
4098 face is white for a light background, and black for a dark
4099 background. You may have to customize the face `org-hide' to
4100 make this work.
4101 Changing it requires restart of `font-lock-mode' to become effective
4102 also in regions already fontified.
4103 You may also set this on a per-file basis by adding one of the following
4104 lines to the buffer:
4106 #+STARTUP: hidestars
4107 #+STARTUP: showstars"
4108 :group 'org-appearance
4109 :type 'boolean)
4111 (defcustom org-hidden-keywords nil
4112 "List of symbols corresponding to keywords to be hidden the org buffer.
4113 For example, a value '(title) for this list will make the document's title
4114 appear in the buffer without the initial #+TITLE: keyword."
4115 :group 'org-appearance
4116 :version "24.1"
4117 :type '(set (const :tag "#+AUTHOR" author)
4118 (const :tag "#+DATE" date)
4119 (const :tag "#+EMAIL" email)
4120 (const :tag "#+TITLE" title)))
4122 (defcustom org-custom-properties nil
4123 "List of properties (as strings) with a special meaning.
4124 The default use of these custom properties is to let the user
4125 hide them with `org-toggle-custom-properties-visibility'."
4126 :group 'org-properties
4127 :group 'org-appearance
4128 :version "24.3"
4129 :type '(repeat (string :tag "Property Name")))
4131 (defcustom org-fontify-done-headline nil
4132 "Non-nil means change the face of a headline if it is marked DONE.
4133 Normally, only the TODO/DONE keyword indicates the state of a headline.
4134 When this is non-nil, the headline after the keyword is set to the
4135 `org-headline-done' as an additional indication."
4136 :group 'org-appearance
4137 :type 'boolean)
4139 (defcustom org-fontify-emphasized-text t
4140 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4141 Changing this variable requires a restart of Emacs to take effect."
4142 :group 'org-appearance
4143 :type 'boolean)
4145 (defcustom org-fontify-whole-heading-line nil
4146 "Non-nil means fontify the whole line for headings.
4147 This is useful when setting a background color for the
4148 org-level-* faces."
4149 :group 'org-appearance
4150 :type 'boolean)
4152 (defcustom org-highlight-latex-and-related nil
4153 "Non-nil means highlight LaTeX related syntax in the buffer.
4154 When non nil, the value should be a list containing any of the
4155 following symbols:
4156 `latex' Highlight LaTeX snippets and environments.
4157 `script' Highlight subscript and superscript.
4158 `entities' Highlight entities."
4159 :group 'org-appearance
4160 :version "24.4"
4161 :package-version '(Org . "8.0")
4162 :type '(choice
4163 (const :tag "No highlighting" nil)
4164 (set :greedy t :tag "Highlight"
4165 (const :tag "LaTeX snippets and environments" latex)
4166 (const :tag "Subscript and superscript" script)
4167 (const :tag "Entities" entities))))
4169 (defcustom org-hide-emphasis-markers nil
4170 "Non-nil mean font-lock should hide the emphasis marker characters."
4171 :group 'org-appearance
4172 :type 'boolean)
4174 (defcustom org-hide-macro-markers nil
4175 "Non-nil mean font-lock should hide the brackets marking macro calls."
4176 :group 'org-appearance
4177 :type 'boolean)
4179 (defcustom org-pretty-entities nil
4180 "Non-nil means show entities as UTF8 characters.
4181 When nil, the \\name form remains in the buffer."
4182 :group 'org-appearance
4183 :version "24.1"
4184 :type 'boolean)
4186 (defcustom org-pretty-entities-include-sub-superscripts t
4187 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4188 :group 'org-appearance
4189 :version "24.1"
4190 :type 'boolean)
4192 (defvar org-emph-re nil
4193 "Regular expression for matching emphasis.
4194 After a match, the match groups contain these elements:
4195 0 The match of the full regular expression, including the characters
4196 before and after the proper match
4197 1 The character before the proper match, or empty at beginning of line
4198 2 The proper match, including the leading and trailing markers
4199 3 The leading marker like * or /, indicating the type of highlighting
4200 4 The text between the emphasis markers, not including the markers
4201 5 The character after the match, empty at the end of a line")
4202 (defvar org-verbatim-re nil
4203 "Regular expression for matching verbatim text.")
4204 (defvar org-emphasis-regexp-components) ; defined just below
4205 (defvar org-emphasis-alist) ; defined just below
4206 (defun org-set-emph-re (var val)
4207 "Set variable and compute the emphasis regular expression."
4208 (set var val)
4209 (when (and (boundp 'org-emphasis-alist)
4210 (boundp 'org-emphasis-regexp-components)
4211 org-emphasis-alist org-emphasis-regexp-components)
4212 (let* ((e org-emphasis-regexp-components)
4213 (pre (car e))
4214 (post (nth 1 e))
4215 (border (nth 2 e))
4216 (body (nth 3 e))
4217 (nl (nth 4 e))
4218 (body1 (concat body "*?"))
4219 (markers (mapconcat 'car org-emphasis-alist ""))
4220 (vmarkers (mapconcat
4221 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4222 org-emphasis-alist "")))
4223 ;; make sure special characters appear at the right position in the class
4224 (if (string-match "\\^" markers)
4225 (setq markers (concat (replace-match "" t t markers) "^")))
4226 (if (string-match "-" markers)
4227 (setq markers (concat (replace-match "" t t markers) "-")))
4228 (if (string-match "\\^" vmarkers)
4229 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4230 (if (string-match "-" vmarkers)
4231 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4232 (if (> nl 0)
4233 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4234 (int-to-string nl) "\\}")))
4235 ;; Make the regexp
4236 (setq org-emph-re
4237 (concat "\\([" pre "]\\|^\\)"
4238 "\\("
4239 "\\([" markers "]\\)"
4240 "\\("
4241 "[^" border "]\\|"
4242 "[^" border "]"
4243 body1
4244 "[^" border "]"
4245 "\\)"
4246 "\\3\\)"
4247 "\\([" post "]\\|$\\)"))
4248 (setq org-verbatim-re
4249 (concat "\\([" pre "]\\|^\\)"
4250 "\\("
4251 "\\([" vmarkers "]\\)"
4252 "\\("
4253 "[^" border "]\\|"
4254 "[^" border "]"
4255 body1
4256 "[^" border "]"
4257 "\\)"
4258 "\\3\\)"
4259 "\\([" post "]\\|$\\)")))))
4261 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4262 ;; set this option proved cumbersome. See this message/thread:
4263 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4264 (defvar org-emphasis-regexp-components
4265 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4266 "Components used to build the regular expression for emphasis.
4267 This is a list with five entries. Terminology: In an emphasis string
4268 like \" *strong word* \", we call the initial space PREMATCH, the final
4269 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4270 and \"trong wor\" is the body. The different components in this variable
4271 specify what is allowed/forbidden in each part:
4273 pre Chars allowed as prematch. Beginning of line will be allowed too.
4274 post Chars allowed as postmatch. End of line will be allowed too.
4275 border The chars *forbidden* as border characters.
4276 body-regexp A regexp like \".\" to match a body character. Don't use
4277 non-shy groups here, and don't allow newline here.
4278 newline The maximum number of newlines allowed in an emphasis exp.
4280 You need to reload Org or to restart Emacs after customizing this.")
4282 (defcustom org-emphasis-alist
4283 `(("*" bold)
4284 ("/" italic)
4285 ("_" underline)
4286 ("=" org-verbatim verbatim)
4287 ("~" org-code verbatim)
4288 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4289 "Alist of characters and faces to emphasize text.
4290 Text starting and ending with a special character will be emphasized,
4291 for example *bold*, _underlined_ and /italic/. This variable sets the
4292 marker characters and the face to be used by font-lock for highlighting
4293 in Org-mode Emacs buffers.
4295 You need to reload Org or to restart Emacs after customizing this."
4296 :group 'org-appearance
4297 :set 'org-set-emph-re
4298 :version "24.4"
4299 :package-version '(Org . "8.0")
4300 :type '(repeat
4301 (list
4302 (string :tag "Marker character")
4303 (choice
4304 (face :tag "Font-lock-face")
4305 (plist :tag "Face property list"))
4306 (option (const verbatim)))))
4308 (defvar org-protecting-blocks
4309 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4310 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4311 This is needed for font-lock setup.")
4313 ;;; Miscellaneous options
4315 (defgroup org-completion nil
4316 "Completion in Org-mode."
4317 :tag "Org Completion"
4318 :group 'org)
4320 (defcustom org-completion-use-ido nil
4321 "Non-nil means use ido completion wherever possible.
4322 Note that `ido-mode' must be active for this variable to be relevant.
4323 If you decide to turn this variable on, you might well want to turn off
4324 `org-outline-path-complete-in-steps'.
4325 See also `org-completion-use-iswitchb'."
4326 :group 'org-completion
4327 :type 'boolean)
4329 (defcustom org-completion-use-iswitchb nil
4330 "Non-nil means use iswitchb completion wherever possible.
4331 Note that `iswitchb-mode' must be active for this variable to be relevant.
4332 If you decide to turn this variable on, you might well want to turn off
4333 `org-outline-path-complete-in-steps'.
4334 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4335 :group 'org-completion
4336 :type 'boolean)
4338 (defcustom org-completion-fallback-command 'hippie-expand
4339 "The expansion command called by \\[pcomplete] in normal context.
4340 Normal means, no org-mode-specific context."
4341 :group 'org-completion
4342 :type 'function)
4344 ;;; Functions and variables from their packages
4345 ;; Declared here to avoid compiler warnings
4347 ;; XEmacs only
4348 (defvar outline-mode-menu-heading)
4349 (defvar outline-mode-menu-show)
4350 (defvar outline-mode-menu-hide)
4351 (defvar zmacs-regions) ; XEmacs regions
4353 ;; Emacs only
4354 (defvar mark-active)
4356 ;; Various packages
4357 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4358 (declare-function calendar-forward-day "cal-move" (arg))
4359 (declare-function calendar-goto-date "cal-move" (date))
4360 (declare-function calendar-goto-today "cal-move" ())
4361 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4362 (defvar calc-embedded-close-formula)
4363 (defvar calc-embedded-open-formula)
4364 (declare-function cdlatex-tab "ext:cdlatex" ())
4365 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4366 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4367 (defvar font-lock-unfontify-region-function)
4368 (declare-function iswitchb-read-buffer "iswitchb"
4369 (prompt &optional default require-match start matches-set))
4370 (defvar iswitchb-temp-buflist)
4371 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4372 (defvar org-agenda-tags-todo-honor-ignore-options)
4373 (declare-function org-agenda-skip "org-agenda" ())
4374 (declare-function
4375 org-agenda-format-item "org-agenda"
4376 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4377 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4378 (declare-function org-agenda-change-all-lines "org-agenda"
4379 (newhead hdmarker &optional fixface just-this))
4380 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4381 (declare-function org-agenda-maybe-redo "org-agenda" ())
4382 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4383 (beg end))
4384 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4385 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4386 "org-agenda" (&optional end))
4387 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4388 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4389 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4390 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4391 (declare-function org-indent-mode "org-indent" (&optional arg))
4392 (declare-function parse-time-string "parse-time" (string))
4393 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4394 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4395 (defvar remember-data-file)
4396 (defvar texmathp-why)
4397 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4398 (declare-function table--at-cell-p "table" (position &optional object at-column))
4399 (declare-function calc-eval "calc" (str &optional separator &rest args))
4401 ;;;###autoload
4402 (defun turn-on-orgtbl ()
4403 "Unconditionally turn on `orgtbl-mode'."
4404 (require 'org-table)
4405 (orgtbl-mode 1))
4407 (defun org-at-table-p (&optional table-type)
4408 "Return t if the cursor is inside an org-type table.
4409 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4410 (if org-enable-table-editor
4411 (save-excursion
4412 (beginning-of-line 1)
4413 (looking-at (if table-type org-table-any-line-regexp
4414 org-table-line-regexp)))
4415 nil))
4416 (defsubst org-table-p () (org-at-table-p))
4418 (defun org-at-table.el-p ()
4419 "Return t if and only if we are at a table.el table."
4420 (and (org-at-table-p 'any)
4421 (save-excursion
4422 (goto-char (org-table-begin 'any))
4423 (looking-at org-table1-hline-regexp))))
4425 (defun org-table-recognize-table.el ()
4426 "If there is a table.el table nearby, recognize it and move into it."
4427 (if org-table-tab-recognizes-table.el
4428 (if (org-at-table.el-p)
4429 (progn
4430 (beginning-of-line 1)
4431 (if (looking-at org-table-dataline-regexp)
4433 (if (looking-at org-table1-hline-regexp)
4434 (progn
4435 (beginning-of-line 2)
4436 (if (looking-at org-table-any-border-regexp)
4437 (beginning-of-line -1)))))
4438 (if (re-search-forward "|" (org-table-end t) t)
4439 (progn
4440 (require 'table)
4441 (if (table--at-cell-p (point))
4443 (message "recognizing table.el table...")
4444 (table-recognize-table)
4445 (message "recognizing table.el table...done")))
4446 (error "This should not happen"))
4448 nil)
4449 nil))
4451 (defun org-at-table-hline-p ()
4452 "Return t if the cursor is inside a hline in a table."
4453 (if org-enable-table-editor
4454 (save-excursion
4455 (beginning-of-line 1)
4456 (looking-at org-table-hline-regexp))
4457 nil))
4459 (defun org-table-map-tables (function &optional quietly)
4460 "Apply FUNCTION to the start of all tables in the buffer."
4461 (save-excursion
4462 (save-restriction
4463 (widen)
4464 (goto-char (point-min))
4465 (while (re-search-forward org-table-any-line-regexp nil t)
4466 (unless quietly
4467 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4468 (beginning-of-line 1)
4469 (when (and (looking-at org-table-line-regexp)
4470 ;; Exclude tables in src/example/verbatim/clocktable blocks
4471 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4472 (save-excursion (funcall function))
4473 (or (looking-at org-table-line-regexp)
4474 (forward-char 1)))
4475 (re-search-forward org-table-any-border-regexp nil 1))))
4476 (unless quietly (message "Mapping tables: done")))
4478 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4479 (declare-function org-clock-update-mode-line "org-clock" ())
4480 (declare-function org-resolve-clocks "org-clock"
4481 (&optional also-non-dangling-p prompt last-valid))
4483 (defun org-at-TBLFM-p (&optional pos)
4484 "Return t when point (or POS) is in #+TBLFM line."
4485 (save-excursion
4486 (let ((pos pos)))
4487 (goto-char (or pos (point)))
4488 (beginning-of-line 1)
4489 (looking-at org-TBLFM-regexp)))
4491 (defvar org-clock-start-time)
4492 (defvar org-clock-marker (make-marker)
4493 "Marker recording the last clock-in.")
4494 (defvar org-clock-hd-marker (make-marker)
4495 "Marker recording the last clock-in, but the headline position.")
4496 (defvar org-clock-heading ""
4497 "The heading of the current clock entry.")
4498 (defun org-clock-is-active ()
4499 "Return the buffer where the clock is currently running.
4500 Return nil if no clock is running."
4501 (marker-buffer org-clock-marker))
4503 (defun org-check-running-clock ()
4504 "Check if the current buffer contains the running clock.
4505 If yes, offer to stop it and to save the buffer with the changes."
4506 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4507 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4508 (buffer-name))))
4509 (org-clock-out)
4510 (when (y-or-n-p "Save changed buffer?")
4511 (save-buffer))))
4513 (defun org-clocktable-try-shift (dir n)
4514 "Check if this line starts a clock table, if yes, shift the time block."
4515 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4516 (org-clocktable-shift dir n)))
4518 ;;;###autoload
4519 (defun org-clock-persistence-insinuate ()
4520 "Set up hooks for clock persistence."
4521 (require 'org-clock)
4522 (add-hook 'org-mode-hook 'org-clock-load)
4523 (add-hook 'kill-emacs-hook 'org-clock-save))
4525 (defgroup org-archive nil
4526 "Options concerning archiving in Org-mode."
4527 :tag "Org Archive"
4528 :group 'org-structure)
4530 (defcustom org-archive-location "%s_archive::"
4531 "The location where subtrees should be archived.
4533 The value of this variable is a string, consisting of two parts,
4534 separated by a double-colon. The first part is a filename and
4535 the second part is a headline.
4537 When the filename is omitted, archiving happens in the same file.
4538 %s in the filename will be replaced by the current file
4539 name (without the directory part). Archiving to a different file
4540 is useful to keep archived entries from contributing to the
4541 Org-mode Agenda.
4543 The archived entries will be filed as subtrees of the specified
4544 headline. When the headline is omitted, the subtrees are simply
4545 filed away at the end of the file, as top-level entries. Also in
4546 the heading you can use %s to represent the file name, this can be
4547 useful when using the same archive for a number of different files.
4549 Here are a few examples:
4550 \"%s_archive::\"
4551 If the current file is Projects.org, archive in file
4552 Projects.org_archive, as top-level trees. This is the default.
4554 \"::* Archived Tasks\"
4555 Archive in the current file, under the top-level headline
4556 \"* Archived Tasks\".
4558 \"~/org/archive.org::\"
4559 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4561 \"~/org/archive.org::* From %s\"
4562 Archive in file ~/org/archive.org (absolute path), under headlines
4563 \"From FILENAME\" where file name is the current file name.
4565 \"~/org/datetree.org::datetree/* Finished Tasks\"
4566 The \"datetree/\" string is special, signifying to archive
4567 items to the datetree. Items are placed in either the CLOSED
4568 date of the item, or the current date if there is no CLOSED date.
4569 The heading will be a subentry to the current date. There doesn't
4570 need to be a heading, but there always needs to be a slash after
4571 datetree. For example, to store archived items directly in the
4572 datetree, use \"~/org/datetree.org::datetree/\".
4574 \"basement::** Finished Tasks\"
4575 Archive in file ./basement (relative path), as level 3 trees
4576 below the level 2 heading \"** Finished Tasks\".
4578 You may set this option on a per-file basis by adding to the buffer a
4579 line like
4581 #+ARCHIVE: basement::** Finished Tasks
4583 You may also define it locally for a subtree by setting an ARCHIVE property
4584 in the entry. If such a property is found in an entry, or anywhere up
4585 the hierarchy, it will be used."
4586 :group 'org-archive
4587 :type 'string)
4589 (defcustom org-agenda-skip-archived-trees t
4590 "Non-nil means the agenda will skip any items located in archived trees.
4591 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4592 variable is no longer recommended, you should leave it at the value t.
4593 Instead, use the key `v' to cycle the archives-mode in the agenda."
4594 :group 'org-archive
4595 :group 'org-agenda-skip
4596 :type 'boolean)
4598 (defcustom org-columns-skip-archived-trees t
4599 "Non-nil means ignore archived trees when creating column view."
4600 :group 'org-archive
4601 :group 'org-properties
4602 :type 'boolean)
4604 (defcustom org-cycle-open-archived-trees nil
4605 "Non-nil means `org-cycle' will open archived trees.
4606 An archived tree is a tree marked with the tag ARCHIVE.
4607 When nil, archived trees will stay folded. You can still open them with
4608 normal outline commands like `show-all', but not with the cycling commands."
4609 :group 'org-archive
4610 :group 'org-cycle
4611 :type 'boolean)
4613 (defcustom org-sparse-tree-open-archived-trees nil
4614 "Non-nil means sparse tree construction shows matches in archived trees.
4615 When nil, matches in these trees are highlighted, but the trees are kept in
4616 collapsed state."
4617 :group 'org-archive
4618 :group 'org-sparse-trees
4619 :type 'boolean)
4621 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4622 "The default date type when building a sparse tree.
4623 When this is nil, a date is a scheduled or a deadline timestamp.
4624 Otherwise, these types are allowed:
4626 all: all timestamps
4627 active: only active timestamps (<...>)
4628 inactive: only inactive timestamps (<...)
4629 scheduled: only scheduled timestamps
4630 deadline: only deadline timestamps"
4631 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4632 (const :tag "All timestamps" all)
4633 (const :tag "Only active timestamps" active)
4634 (const :tag "Only inactive timestamps" inactive)
4635 (const :tag "Only scheduled timestamps" scheduled)
4636 (const :tag "Only deadline timestamps" deadline)
4637 (const :tag "Only closed timestamps" closed))
4638 :version "24.3"
4639 :group 'org-sparse-trees)
4641 (defun org-cycle-hide-archived-subtrees (state)
4642 "Re-hide all archived subtrees after a visibility state change."
4643 (when (and (not org-cycle-open-archived-trees)
4644 (not (memq state '(overview folded))))
4645 (save-excursion
4646 (let* ((globalp (memq state '(contents all)))
4647 (beg (if globalp (point-min) (point)))
4648 (end (if globalp (point-max) (org-end-of-subtree t))))
4649 (org-hide-archived-subtrees beg end)
4650 (goto-char beg)
4651 (if (looking-at (concat ".*:" org-archive-tag ":"))
4652 (message "%s" (substitute-command-keys
4653 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4655 (defun org-force-cycle-archived ()
4656 "Cycle subtree even if it is archived."
4657 (interactive)
4658 (setq this-command 'org-cycle)
4659 (let ((org-cycle-open-archived-trees t))
4660 (call-interactively 'org-cycle)))
4662 (defun org-hide-archived-subtrees (beg end)
4663 "Re-hide all archived subtrees after a visibility state change."
4664 (save-excursion
4665 (let* ((re (concat ":" org-archive-tag ":")))
4666 (goto-char beg)
4667 (while (re-search-forward re end t)
4668 (when (org-at-heading-p)
4669 (org-flag-subtree t)
4670 (org-end-of-subtree t))))))
4672 (declare-function outline-end-of-heading "outline" ())
4673 (declare-function outline-flag-region "outline" (from to flag))
4674 (defun org-flag-subtree (flag)
4675 (save-excursion
4676 (org-back-to-heading t)
4677 (outline-end-of-heading)
4678 (outline-flag-region (point)
4679 (progn (org-end-of-subtree t) (point))
4680 flag)))
4682 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4684 ;; Declare Column View Code
4686 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4687 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4688 (declare-function org-columns-compute "org-colview" (property))
4690 ;; Declare ID code
4692 (declare-function org-id-store-link "org-id")
4693 (declare-function org-id-locations-load "org-id")
4694 (declare-function org-id-locations-save "org-id")
4695 (defvar org-id-track-globally)
4697 ;;; Variables for pre-computed regular expressions, all buffer local
4699 (defvar org-todo-regexp nil
4700 "Matches any of the TODO state keywords.")
4701 (make-variable-buffer-local 'org-todo-regexp)
4702 (defvar org-not-done-regexp nil
4703 "Matches any of the TODO state keywords except the last one.")
4704 (make-variable-buffer-local 'org-not-done-regexp)
4705 (defvar org-not-done-heading-regexp nil
4706 "Matches a TODO headline that is not done.")
4707 (make-variable-buffer-local 'org-not-done-regexp)
4708 (defvar org-todo-line-regexp nil
4709 "Matches a headline and puts TODO state into group 2 if present.")
4710 (make-variable-buffer-local 'org-todo-line-regexp)
4711 (defvar org-complex-heading-regexp nil
4712 "Matches a headline and puts everything into groups:
4713 group 1: the stars
4714 group 2: The todo keyword, maybe
4715 group 3: Priority cookie
4716 group 4: True headline
4717 group 5: Tags")
4718 (make-variable-buffer-local 'org-complex-heading-regexp)
4719 (defvar org-complex-heading-regexp-format nil
4720 "Printf format to make regexp to match an exact headline.
4721 This regexp will match the headline of any node which has the
4722 exact headline text that is put into the format, but may have any
4723 TODO state, priority and tags.")
4724 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4725 (defvar org-todo-line-tags-regexp nil
4726 "Matches a headline and puts TODO state into group 2 if present.
4727 Also put tags into group 4 if tags are present.")
4728 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4729 (defvar org-ds-keyword-length 12
4730 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4731 (make-variable-buffer-local 'org-ds-keyword-length)
4732 (defvar org-deadline-regexp nil
4733 "Matches the DEADLINE keyword.")
4734 (make-variable-buffer-local 'org-deadline-regexp)
4735 (defvar org-deadline-time-regexp nil
4736 "Matches the DEADLINE keyword together with a time stamp.")
4737 (make-variable-buffer-local 'org-deadline-time-regexp)
4738 (defvar org-deadline-time-hour-regexp nil
4739 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4740 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4741 (defvar org-deadline-line-regexp nil
4742 "Matches the DEADLINE keyword and the rest of the line.")
4743 (make-variable-buffer-local 'org-deadline-line-regexp)
4744 (defvar org-scheduled-regexp nil
4745 "Matches the SCHEDULED keyword.")
4746 (make-variable-buffer-local 'org-scheduled-regexp)
4747 (defvar org-scheduled-time-regexp nil
4748 "Matches the SCHEDULED keyword together with a time stamp.")
4749 (make-variable-buffer-local 'org-scheduled-time-regexp)
4750 (defvar org-scheduled-time-hour-regexp nil
4751 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4752 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4753 (defvar org-closed-time-regexp nil
4754 "Matches the CLOSED keyword together with a time stamp.")
4755 (make-variable-buffer-local 'org-closed-time-regexp)
4757 (defvar org-keyword-time-regexp nil
4758 "Matches any of the 4 keywords, together with the time stamp.")
4759 (make-variable-buffer-local 'org-keyword-time-regexp)
4760 (defvar org-keyword-time-not-clock-regexp nil
4761 "Matches any of the 3 keywords, together with the time stamp.")
4762 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4763 (defvar org-maybe-keyword-time-regexp nil
4764 "Matches a timestamp, possibly preceded by a keyword.")
4765 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4766 (defvar org-all-time-keywords nil
4767 "List of time keywords.")
4768 (make-variable-buffer-local 'org-all-time-keywords)
4770 (defconst org-plain-time-of-day-regexp
4771 (concat
4772 "\\(\\<[012]?[0-9]"
4773 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4774 "\\(--?"
4775 "\\(\\<[012]?[0-9]"
4776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4777 "\\)?")
4778 "Regular expression to match a plain time or time range.
4779 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4780 groups carry important information:
4781 0 the full match
4782 1 the first time, range or not
4783 8 the second time, if it is a range.")
4785 (defconst org-plain-time-extension-regexp
4786 (concat
4787 "\\(\\<[012]?[0-9]"
4788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4789 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4790 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4791 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4792 groups carry important information:
4793 0 the full match
4794 7 hours of duration
4795 9 minutes of duration")
4797 (defconst org-stamp-time-of-day-regexp
4798 (concat
4799 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4800 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4801 "\\(--?"
4802 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4803 "Regular expression to match a timestamp time or time range.
4804 After a match, the following groups carry important information:
4805 0 the full match
4806 1 date plus weekday, for back referencing to make sure both times are on the same day
4807 2 the first time, range or not
4808 4 the second time, if it is a range.")
4810 (defconst org-startup-options
4811 '(("fold" org-startup-folded t)
4812 ("overview" org-startup-folded t)
4813 ("nofold" org-startup-folded nil)
4814 ("showall" org-startup-folded nil)
4815 ("showeverything" org-startup-folded showeverything)
4816 ("content" org-startup-folded content)
4817 ("indent" org-startup-indented t)
4818 ("noindent" org-startup-indented nil)
4819 ("hidestars" org-hide-leading-stars t)
4820 ("showstars" org-hide-leading-stars nil)
4821 ("odd" org-odd-levels-only t)
4822 ("oddeven" org-odd-levels-only nil)
4823 ("align" org-startup-align-all-tables t)
4824 ("noalign" org-startup-align-all-tables nil)
4825 ("inlineimages" org-startup-with-inline-images t)
4826 ("noinlineimages" org-startup-with-inline-images nil)
4827 ("latexpreview" org-startup-with-latex-preview t)
4828 ("nolatexpreview" org-startup-with-latex-preview nil)
4829 ("customtime" org-display-custom-times t)
4830 ("logdone" org-log-done time)
4831 ("lognotedone" org-log-done note)
4832 ("nologdone" org-log-done nil)
4833 ("lognoteclock-out" org-log-note-clock-out t)
4834 ("nolognoteclock-out" org-log-note-clock-out nil)
4835 ("logrepeat" org-log-repeat state)
4836 ("lognoterepeat" org-log-repeat note)
4837 ("logdrawer" org-log-into-drawer t)
4838 ("nologdrawer" org-log-into-drawer nil)
4839 ("logstatesreversed" org-log-states-order-reversed t)
4840 ("nologstatesreversed" org-log-states-order-reversed nil)
4841 ("nologrepeat" org-log-repeat nil)
4842 ("logreschedule" org-log-reschedule time)
4843 ("lognotereschedule" org-log-reschedule note)
4844 ("nologreschedule" org-log-reschedule nil)
4845 ("logredeadline" org-log-redeadline time)
4846 ("lognoteredeadline" org-log-redeadline note)
4847 ("nologredeadline" org-log-redeadline nil)
4848 ("logrefile" org-log-refile time)
4849 ("lognoterefile" org-log-refile note)
4850 ("nologrefile" org-log-refile nil)
4851 ("fninline" org-footnote-define-inline t)
4852 ("nofninline" org-footnote-define-inline nil)
4853 ("fnlocal" org-footnote-section nil)
4854 ("fnauto" org-footnote-auto-label t)
4855 ("fnprompt" org-footnote-auto-label nil)
4856 ("fnconfirm" org-footnote-auto-label confirm)
4857 ("fnplain" org-footnote-auto-label plain)
4858 ("fnadjust" org-footnote-auto-adjust t)
4859 ("nofnadjust" org-footnote-auto-adjust nil)
4860 ("constcgs" constants-unit-system cgs)
4861 ("constSI" constants-unit-system SI)
4862 ("noptag" org-tag-persistent-alist nil)
4863 ("hideblocks" org-hide-block-startup t)
4864 ("nohideblocks" org-hide-block-startup nil)
4865 ("beamer" org-startup-with-beamer-mode t)
4866 ("entitiespretty" org-pretty-entities t)
4867 ("entitiesplain" org-pretty-entities nil))
4868 "Variable associated with STARTUP options for org-mode.
4869 Each element is a list of three items: the startup options (as written
4870 in the #+STARTUP line), the corresponding variable, and the value to set
4871 this variable to if the option is found. An optional forth element PUSH
4872 means to push this value onto the list in the variable.")
4874 (defun org-update-property-plist (key val props)
4875 "Update PROPS with KEY and VAL."
4876 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4877 (key (if appending (substring key 0 (- (length key) 1)) key))
4878 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4879 (previous (cdr (assoc key props))))
4880 (if appending
4881 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4882 (cons (cons key val) remainder))))
4884 (defcustom org-group-tags t
4885 "When non-nil (the default), use group tags.
4886 This can be turned on/off through `org-toggle-tags-groups'."
4887 :group 'org-tags
4888 :group 'org-startup
4889 :type 'boolean)
4891 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4893 (defun org-toggle-tags-groups ()
4894 "Toggle support for group tags.
4895 Support for group tags is controlled by the option
4896 `org-group-tags', which is non-nil by default."
4897 (interactive)
4898 (setq org-group-tags (not org-group-tags))
4899 (cond ((and (derived-mode-p 'org-agenda-mode)
4900 org-group-tags)
4901 (org-agenda-redo))
4902 ((derived-mode-p 'org-mode)
4903 (let ((org-inhibit-startup t)) (org-mode))))
4904 (message "Groups tags support has been turned %s"
4905 (if org-group-tags "on" "off")))
4907 (defun org-set-regexps-and-options-for-tags ()
4908 "Precompute variables used for tags."
4909 (when (derived-mode-p 'org-mode)
4910 (org-set-local 'org-file-tags nil)
4911 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4912 (splitre "[ \t]+")
4913 (start 0)
4914 tags ftags key value)
4915 (save-excursion
4916 (save-restriction
4917 (widen)
4918 (goto-char (point-min))
4919 (while (re-search-forward re nil t)
4920 (setq key (upcase (org-match-string-no-properties 1))
4921 value (org-match-string-no-properties 2))
4922 (if (stringp value) (setq value (org-trim value)))
4923 (cond
4924 ((equal key "TAGS")
4925 (setq tags (append tags (if tags '("\\n") nil)
4926 (org-split-string value splitre))))
4927 ((equal key "FILETAGS")
4928 (when (string-match "\\S-" value)
4929 (setq ftags
4930 (append
4931 ftags
4932 (apply 'append
4933 (mapcar (lambda (x) (org-split-string x ":"))
4934 (org-split-string value)))))))))))
4935 ;; Process the file tags.
4936 (and ftags (org-set-local 'org-file-tags
4937 (mapcar 'org-add-prop-inherited ftags)))
4938 (org-set-local 'org-tag-groups-alist nil)
4939 ;; Process the tags.
4940 (when (and (not tags) org-tag-alist)
4941 (setq tags
4942 (mapcar
4943 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4944 ((eq (car tg) :endgroup) "}")
4945 ((eq (car tg) :grouptags) ":")
4946 ((eq (car tg) :newline) "\n")
4947 (t (concat (car tg)
4948 (if (characterp (cdr tg))
4949 (format "(%s)" (char-to-string (cdr tg))) "")))))
4950 org-tag-alist)))
4951 (let (e tgs g)
4952 (while (setq e (pop tags))
4953 (cond
4954 ((equal e "{")
4955 (progn (push '(:startgroup) tgs)
4956 (when (equal (nth 1 tags) ":")
4957 (push (list (replace-regexp-in-string
4958 "(.+)$" "" (nth 0 tags)))
4959 org-tag-groups-alist)
4960 (setq g 0))))
4961 ((equal e ":") (push '(:grouptags) tgs))
4962 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4963 ((equal e "\\n") (push '(:newline) tgs))
4964 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4965 (push (cons (match-string 1 e)
4966 (string-to-char (match-string 2 e))) tgs)
4967 (if (and g (> g 0))
4968 (setcar org-tag-groups-alist
4969 (append (car org-tag-groups-alist)
4970 (list (match-string 1 e)))))
4971 (if g (setq g (1+ g))))
4972 (t (push (list e) tgs)
4973 (if (and g (> g 0))
4974 (setcar org-tag-groups-alist
4975 (append (car org-tag-groups-alist) (list e))))
4976 (if g (setq g (1+ g))))))
4977 (org-set-local 'org-tag-alist nil)
4978 (while (setq e (pop tgs))
4979 (or (and (stringp (car e))
4980 (assoc (car e) org-tag-alist))
4981 (push e org-tag-alist)))
4982 ;; Return a list with tag variables
4983 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4985 (defvar org-ota nil)
4986 (defun org-set-regexps-and-options ()
4987 "Precompute regular expressions used in the current buffer."
4988 (when (derived-mode-p 'org-mode)
4989 (org-set-local 'org-todo-kwd-alist nil)
4990 (org-set-local 'org-todo-key-alist nil)
4991 (org-set-local 'org-todo-key-trigger nil)
4992 (org-set-local 'org-todo-keywords-1 nil)
4993 (org-set-local 'org-done-keywords nil)
4994 (org-set-local 'org-todo-heads nil)
4995 (org-set-local 'org-todo-sets nil)
4996 (org-set-local 'org-todo-log-states nil)
4997 (org-set-local 'org-file-properties nil)
4998 (let ((re (org-make-options-regexp
4999 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5000 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5001 "SETUPFILE" "OPTIONS")
5002 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5003 (splitre "[ \t]+")
5004 (scripts org-use-sub-superscripts)
5005 kwds kws0 kwsa key log value cat arch const links hw dws
5006 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5007 (start 0))
5008 (save-excursion
5009 (save-restriction
5010 (widen)
5011 (goto-char (point-min))
5012 (while
5013 (or (and
5014 ext-setup-or-nil
5015 (not org-ota)
5016 (let (ret)
5017 (with-temp-buffer
5018 (insert ext-setup-or-nil)
5019 (let ((major-mode 'org-mode) org-ota)
5020 (setq ret (save-match-data
5021 (org-set-regexps-and-options-for-tags)))))
5022 ;; Append setupfile tags to existing tags
5023 (setq org-ota t)
5024 (setq org-file-tags
5025 (delq nil (append org-file-tags (nth 0 ret)))
5026 org-tag-alist
5027 (delq nil (append org-tag-alist (nth 1 ret)))
5028 org-tag-groups-alist
5029 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5030 (and ext-setup-or-nil
5031 (string-match re ext-setup-or-nil start)
5032 (setq start (match-end 0)))
5033 (and (setq ext-setup-or-nil nil start 0)
5034 (re-search-forward re nil t)))
5035 (setq key (upcase (match-string 1 ext-setup-or-nil))
5036 value (org-match-string-no-properties 2 ext-setup-or-nil))
5037 (if (stringp value) (setq value (org-trim value)))
5038 (cond
5039 ((equal key "CATEGORY")
5040 (setq cat value))
5041 ((member key '("SEQ_TODO" "TODO"))
5042 (push (cons 'sequence (org-split-string value splitre)) kwds))
5043 ((equal key "TYP_TODO")
5044 (push (cons 'type (org-split-string value splitre)) kwds))
5045 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5046 ;; general TODO-like setup
5047 (push (cons (intern (downcase (match-string 1 key)))
5048 (org-split-string value splitre)) kwds))
5049 ((equal key "COLUMNS")
5050 (org-set-local 'org-columns-default-format value))
5051 ((equal key "LINK")
5052 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5053 (push (cons (match-string 1 value)
5054 (org-trim (match-string 2 value)))
5055 links)))
5056 ((equal key "PRIORITIES")
5057 (setq prio (org-split-string value " +")))
5058 ((equal key "PROPERTY")
5059 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5060 (setq props (org-update-property-plist (match-string 1 value)
5061 (match-string 2 value)
5062 props))))
5063 ((equal key "CONSTANTS")
5064 (org-table-set-constants))
5065 ((equal key "STARTUP")
5066 (let ((opts (org-split-string value splitre))
5067 l var val)
5068 (while (setq l (pop opts))
5069 (when (setq l (assoc l org-startup-options))
5070 (setq var (nth 1 l) val (nth 2 l))
5071 (if (not (nth 3 l))
5072 (set (make-local-variable var) val)
5073 (if (not (listp (symbol-value var)))
5074 (set (make-local-variable var) nil))
5075 (set (make-local-variable var) (symbol-value var))
5076 (add-to-list var val))))))
5077 ((equal key "ARCHIVE")
5078 (setq arch value)
5079 (remove-text-properties 0 (length arch)
5080 '(face t fontified t) arch))
5081 ((equal key "OPTIONS")
5082 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5083 (setq scripts (read (match-string 2 value)))))
5084 ((and (equal key "SETUPFILE")
5085 ;; Prevent checking in Gnus messages
5086 (not buffer-read-only))
5087 (setq setup-contents (org-file-contents
5088 (expand-file-name
5089 (org-remove-double-quotes value))
5090 'noerror))
5091 (if (not ext-setup-or-nil)
5092 (setq ext-setup-or-nil setup-contents start 0)
5093 (setq ext-setup-or-nil
5094 (concat (substring ext-setup-or-nil 0 start)
5095 "\n" setup-contents "\n"
5096 (substring ext-setup-or-nil start)))))))
5097 ;; search for property blocks
5098 (goto-char (point-min))
5099 (while (re-search-forward org-block-regexp nil t)
5100 (when (equal "PROPERTY" (upcase (match-string 1)))
5101 (setq value (replace-regexp-in-string
5102 "[\n\r]" " " (match-string 4)))
5103 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5104 (setq props (org-update-property-plist (match-string 1 value)
5105 (match-string 2 value)
5106 props)))))))
5107 (org-set-local 'org-use-sub-superscripts scripts)
5108 (when cat
5109 (org-set-local 'org-category (intern cat))
5110 (push (cons "CATEGORY" cat) props))
5111 (when prio
5112 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5113 (setq prio (mapcar 'string-to-char prio))
5114 (org-set-local 'org-highest-priority (nth 0 prio))
5115 (org-set-local 'org-lowest-priority (nth 1 prio))
5116 (org-set-local 'org-default-priority (nth 2 prio)))
5117 (and props (org-set-local 'org-file-properties (nreverse props)))
5118 (and arch (org-set-local 'org-archive-location arch))
5119 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5120 ;; Process the TODO keywords
5121 (unless kwds
5122 ;; Use the global values as if they had been given locally.
5123 (setq kwds (default-value 'org-todo-keywords))
5124 (if (stringp (car kwds))
5125 (setq kwds (list (cons org-todo-interpretation
5126 (default-value 'org-todo-keywords)))))
5127 (setq kwds (reverse kwds)))
5128 (setq kwds (nreverse kwds))
5129 (let (inter kws kw)
5130 (while (setq kws (pop kwds))
5131 (let ((kws (or
5132 (run-hook-with-args-until-success
5133 'org-todo-setup-filter-hook kws)
5134 kws)))
5135 (setq inter (pop kws) sep (member "|" kws)
5136 kws0 (delete "|" (copy-sequence kws))
5137 kwsa nil
5138 kws1 (mapcar
5139 (lambda (x)
5140 ;; 1 2
5141 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5142 (progn
5143 (setq kw (match-string 1 x)
5144 key (and (match-end 2) (match-string 2 x))
5145 log (org-extract-log-state-settings x))
5146 (push (cons kw (and key (string-to-char key))) kwsa)
5147 (and log (push log org-todo-log-states))
5149 (error "Invalid TODO keyword %s" x)))
5150 kws0)
5151 kwsa (if kwsa (append '((:startgroup))
5152 (nreverse kwsa)
5153 '((:endgroup))))
5154 hw (car kws1)
5155 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5156 tail (list inter hw (car dws) (org-last dws))))
5157 (add-to-list 'org-todo-heads hw 'append)
5158 (push kws1 org-todo-sets)
5159 (setq org-done-keywords (append org-done-keywords dws nil))
5160 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5161 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5162 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5163 (setq org-todo-sets (nreverse org-todo-sets)
5164 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5165 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5166 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5167 ;; Compute the regular expressions and other local variables.
5168 ;; Using `org-outline-regexp-bol' would complicate them much,
5169 ;; because of the fixed white space at the end of that string.
5170 (if (not org-done-keywords)
5171 (setq org-done-keywords (and org-todo-keywords-1
5172 (list (org-last org-todo-keywords-1)))))
5173 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5174 (length org-scheduled-string)
5175 (length org-clock-string)
5176 (length org-closed-string)))
5177 org-not-done-keywords
5178 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5179 org-todo-regexp
5180 (concat "\\("
5181 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5182 "\\)")
5183 org-not-done-regexp
5184 (concat "\\("
5185 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5186 "\\)")
5187 org-not-done-heading-regexp
5188 (format org-heading-keyword-regexp-format org-not-done-regexp)
5189 org-todo-line-regexp
5190 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5191 org-complex-heading-regexp
5192 (concat "^\\(\\*+\\)"
5193 "\\(?: +" org-todo-regexp "\\)?"
5194 "\\(?: +\\(\\[#.\\]\\)\\)?"
5195 "\\(?: +\\(.*?\\)\\)??"
5196 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5197 "[ \t]*$")
5198 org-complex-heading-regexp-format
5199 (concat "^\\(\\*+\\)"
5200 "\\(?: +" org-todo-regexp "\\)?"
5201 "\\(?: +\\(\\[#.\\]\\)\\)?"
5202 "\\(?: +"
5203 ;; Stats cookies can be stuck to body.
5204 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5205 "\\(%s\\)"
5206 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5207 "\\)"
5208 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5209 "[ \t]*$")
5210 org-todo-line-tags-regexp
5211 (concat "^\\(\\*+\\)"
5212 "\\(?: +" org-todo-regexp "\\)?"
5213 "\\(?: +\\(.*?\\)\\)??"
5214 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5215 "[ \t]*$")
5216 org-deadline-regexp (concat "\\<" org-deadline-string)
5217 org-deadline-time-regexp
5218 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5219 org-deadline-time-hour-regexp
5220 (concat "\\<" org-deadline-string
5221 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5222 org-deadline-line-regexp
5223 (concat "\\<\\(" org-deadline-string "\\).*")
5224 org-scheduled-regexp
5225 (concat "\\<" org-scheduled-string)
5226 org-scheduled-time-regexp
5227 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5228 org-scheduled-time-hour-regexp
5229 (concat "\\<" org-scheduled-string
5230 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5231 org-closed-time-regexp
5232 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5233 org-keyword-time-regexp
5234 (concat "\\<\\(" org-scheduled-string
5235 "\\|" org-deadline-string
5236 "\\|" org-closed-string
5237 "\\|" org-clock-string "\\)"
5238 " *[[<]\\([^]>]+\\)[]>]")
5239 org-keyword-time-not-clock-regexp
5240 (concat "\\<\\(" org-scheduled-string
5241 "\\|" org-deadline-string
5242 "\\|" org-closed-string
5243 "\\)"
5244 " *[[<]\\([^]>]+\\)[]>]")
5245 org-maybe-keyword-time-regexp
5246 (concat "\\(\\<\\(" org-scheduled-string
5247 "\\|" org-deadline-string
5248 "\\|" org-closed-string
5249 "\\|" org-clock-string "\\)\\)?"
5250 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5251 org-all-time-keywords
5252 (mapcar (lambda (w) (substring w 0 -1))
5253 (list org-scheduled-string org-deadline-string
5254 org-clock-string org-closed-string)))
5255 (setq org-ota nil)
5256 (org-compute-latex-and-related-regexp))))
5258 (defun org-file-contents (file &optional noerror)
5259 "Return the contents of FILE, as a string."
5260 (if (and file (file-readable-p file))
5261 (with-temp-buffer
5262 (insert-file-contents file)
5263 (buffer-string))
5264 (funcall (if noerror 'message 'error)
5265 "Cannot read file \"%s\"%s"
5266 file
5267 (let ((from (buffer-file-name (buffer-base-buffer))))
5268 (if from (concat " (referenced in file \"" from "\")") "")))))
5270 (defun org-extract-log-state-settings (x)
5271 "Extract the log state setting from a TODO keyword string.
5272 This will extract info from a string like \"WAIT(w@/!)\"."
5273 (let (kw key log1 log2)
5274 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5275 (setq kw (match-string 1 x)
5276 key (and (match-end 2) (match-string 2 x))
5277 log1 (and (match-end 3) (match-string 3 x))
5278 log2 (and (match-end 4) (match-string 4 x)))
5279 (and (or log1 log2)
5280 (list kw
5281 (and log1 (if (equal log1 "!") 'time 'note))
5282 (and log2 (if (equal log2 "!") 'time 'note)))))))
5284 (defun org-remove-keyword-keys (list)
5285 "Remove a pair of parenthesis at the end of each string in LIST."
5286 (mapcar (lambda (x)
5287 (if (string-match "(.*)$" x)
5288 (substring x 0 (match-beginning 0))
5290 list))
5292 (defun org-assign-fast-keys (alist)
5293 "Assign fast keys to a keyword-key alist.
5294 Respect keys that are already there."
5295 (let (new e (alt ?0))
5296 (while (setq e (pop alist))
5297 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5298 (cdr e)) ;; Key already assigned.
5299 (push e new)
5300 (let ((clist (string-to-list (downcase (car e))))
5301 (used (append new alist)))
5302 (when (= (car clist) ?@)
5303 (pop clist))
5304 (while (and clist (rassoc (car clist) used))
5305 (pop clist))
5306 (unless clist
5307 (while (rassoc alt used)
5308 (incf alt)))
5309 (push (cons (car e) (or (car clist) alt)) new))))
5310 (nreverse new)))
5312 ;;; Some variables used in various places
5314 (defvar org-window-configuration nil
5315 "Used in various places to store a window configuration.")
5316 (defvar org-selected-window nil
5317 "Used in various places to store a window configuration.")
5318 (defvar org-finish-function nil
5319 "Function to be called when `C-c C-c' is used.
5320 This is for getting out of special buffers like capture.")
5323 ;; FIXME: Occasionally check by commenting these, to make sure
5324 ;; no other functions uses these, forgetting to let-bind them.
5325 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5326 (defvar org-last-state)
5327 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5329 ;; Defined somewhere in this file, but used before definition.
5330 (defvar org-entities) ;; defined in org-entities.el
5331 (defvar org-struct-menu)
5332 (defvar org-org-menu)
5333 (defvar org-tbl-menu)
5335 ;;;; Define the Org-mode
5337 ;; We use a before-change function to check if a table might need
5338 ;; an update.
5339 (defvar org-table-may-need-update t
5340 "Indicates that a table might need an update.
5341 This variable is set by `org-before-change-function'.
5342 `org-table-align' sets it back to nil.")
5343 (defun org-before-change-function (beg end)
5344 "Every change indicates that a table might need an update."
5345 (setq org-table-may-need-update t))
5346 (defvar org-mode-map)
5347 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5348 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5349 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5350 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5351 (defvar org-table-buffer-is-an nil)
5353 (defvar bidi-paragraph-direction)
5354 (defvar buffer-face-mode-face)
5356 (require 'outline)
5357 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5358 (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"))
5359 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5361 ;; Other stuff we need.
5362 (require 'time-date)
5363 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5364 (require 'easymenu)
5365 (require 'overlay)
5367 ;; (require 'org-macs) moved higher up in the file before it is first used
5368 (require 'org-entities)
5369 ;; (require 'org-compat) moved higher up in the file before it is first used
5370 (require 'org-faces)
5371 (require 'org-list)
5372 (require 'org-pcomplete)
5373 (require 'org-src)
5374 (require 'org-footnote)
5375 (require 'org-macro)
5377 ;; babel
5378 (require 'ob)
5380 ;;;###autoload
5381 (define-derived-mode org-mode outline-mode "Org"
5382 "Outline-based notes management and organizer, alias
5383 \"Carsten's outline-mode for keeping track of everything.\"
5385 Org-mode develops organizational tasks around a NOTES file which
5386 contains information about projects as plain text. Org-mode is
5387 implemented on top of outline-mode, which is ideal to keep the content
5388 of large files well structured. It supports ToDo items, deadlines and
5389 time stamps, which magically appear in the diary listing of the Emacs
5390 calendar. Tables are easily created with a built-in table editor.
5391 Plain text URL-like links connect to websites, emails (VM), Usenet
5392 messages (Gnus), BBDB entries, and any files related to the project.
5393 For printing and sharing of notes, an Org-mode file (or a part of it)
5394 can be exported as a structured ASCII or HTML file.
5396 The following commands are available:
5398 \\{org-mode-map}"
5400 ;; Get rid of Outline menus, they are not needed
5401 ;; Need to do this here because define-derived-mode sets up
5402 ;; the keymap so late. Still, it is a waste to call this each time
5403 ;; we switch another buffer into org-mode.
5404 (if (featurep 'xemacs)
5405 (when (boundp 'outline-mode-menu-heading)
5406 ;; Assume this is Greg's port, it uses easymenu
5407 (easy-menu-remove outline-mode-menu-heading)
5408 (easy-menu-remove outline-mode-menu-show)
5409 (easy-menu-remove outline-mode-menu-hide))
5410 (define-key org-mode-map [menu-bar headings] 'undefined)
5411 (define-key org-mode-map [menu-bar hide] 'undefined)
5412 (define-key org-mode-map [menu-bar show] 'undefined))
5414 (org-load-modules-maybe)
5415 (easy-menu-add org-org-menu)
5416 (easy-menu-add org-tbl-menu)
5417 (org-install-agenda-files-menu)
5418 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5419 (add-to-invisibility-spec '(org-cwidth))
5420 (add-to-invisibility-spec '(org-hide-block . t))
5421 (when (featurep 'xemacs)
5422 (org-set-local 'line-move-ignore-invisible t))
5423 (org-set-local 'outline-regexp org-outline-regexp)
5424 (org-set-local 'outline-level 'org-outline-level)
5425 (setq bidi-paragraph-direction 'left-to-right)
5426 (when (and org-ellipsis
5427 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5428 (fboundp 'make-glyph-code))
5429 (unless org-display-table
5430 (setq org-display-table (make-display-table)))
5431 (set-display-table-slot
5432 org-display-table 4
5433 (vconcat (mapcar
5434 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5435 org-ellipsis)))
5436 (if (stringp org-ellipsis) org-ellipsis "..."))))
5437 (setq buffer-display-table org-display-table))
5438 (org-set-regexps-and-options-for-tags)
5439 (org-set-regexps-and-options)
5440 (org-set-font-lock-defaults)
5441 (when (and org-tag-faces (not org-tags-special-faces-re))
5442 ;; tag faces set outside customize.... force initialization.
5443 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5444 ;; Calc embedded
5445 (org-set-local 'calc-embedded-open-mode "# ")
5446 ;; Modify a few syntax entries
5447 (modify-syntax-entry ?@ "w")
5448 (modify-syntax-entry ?\" "\"")
5449 (modify-syntax-entry ?\\ "_")
5450 (modify-syntax-entry ?~ "_")
5451 (if org-startup-truncated (setq truncate-lines t))
5452 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5453 (org-set-local 'font-lock-unfontify-region-function
5454 'org-unfontify-region)
5455 ;; Activate before-change-function
5456 (org-set-local 'org-table-may-need-update t)
5457 (org-add-hook 'before-change-functions 'org-before-change-function nil
5458 'local)
5459 ;; Check for running clock before killing a buffer
5460 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5461 ;; Initialize macros templates.
5462 (org-macro-initialize-templates)
5463 ;; Initialize radio targets.
5464 (org-update-radio-target-regexp)
5465 ;; Indentation.
5466 (org-set-local 'indent-line-function 'org-indent-line)
5467 (org-set-local 'indent-region-function 'org-indent-region)
5468 ;; Filling and auto-filling.
5469 (org-setup-filling)
5470 ;; Comments.
5471 (org-setup-comments-handling)
5472 ;; Initialize cache.
5473 (org-element-cache-reset)
5474 ;; Beginning/end of defun
5475 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5476 (org-set-local 'end-of-defun-function
5477 (lambda ()
5478 (if (not (org-at-heading-p))
5479 (org-forward-element)
5480 (org-forward-element)
5481 (forward-char -1))))
5482 ;; Next error for sparse trees
5483 (org-set-local 'next-error-function 'org-occur-next-match)
5484 ;; Make sure dependence stuff works reliably, even for users who set it
5485 ;; too late :-(
5486 (if org-enforce-todo-dependencies
5487 (add-hook 'org-blocker-hook
5488 'org-block-todo-from-children-or-siblings-or-parent)
5489 (remove-hook 'org-blocker-hook
5490 'org-block-todo-from-children-or-siblings-or-parent))
5491 (if org-enforce-todo-checkbox-dependencies
5492 (add-hook 'org-blocker-hook
5493 'org-block-todo-from-checkboxes)
5494 (remove-hook 'org-blocker-hook
5495 'org-block-todo-from-checkboxes))
5497 ;; Align options lines
5498 (org-set-local
5499 'align-mode-rules-list
5500 '((org-in-buffer-settings
5501 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5502 (modes . '(org-mode)))))
5504 ;; Imenu
5505 (org-set-local 'imenu-create-index-function
5506 'org-imenu-get-tree)
5508 ;; Make isearch reveal context
5509 (if (or (featurep 'xemacs)
5510 (not (boundp 'outline-isearch-open-invisible-function)))
5511 ;; Emacs 21 and XEmacs make use of the hook
5512 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5513 ;; Emacs 22 deals with this through a special variable
5514 (org-set-local 'outline-isearch-open-invisible-function
5515 (lambda (&rest ignore) (org-show-context 'isearch))))
5517 ;; Setup the pcomplete hooks
5518 (set (make-local-variable 'pcomplete-command-completion-function)
5519 'org-pcomplete-initial)
5520 (set (make-local-variable 'pcomplete-command-name-function)
5521 'org-command-at-point)
5522 (set (make-local-variable 'pcomplete-default-completion-function)
5523 'ignore)
5524 (set (make-local-variable 'pcomplete-parse-arguments-function)
5525 'org-parse-arguments)
5526 (set (make-local-variable 'pcomplete-termination-string) "")
5527 (when (>= emacs-major-version 23)
5528 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5530 ;; If empty file that did not turn on org-mode automatically, make it to.
5531 (if (and org-insert-mode-line-in-empty-file
5532 (org-called-interactively-p 'any)
5533 (= (point-min) (point-max)))
5534 (insert "# -*- mode: org -*-\n\n"))
5535 (unless org-inhibit-startup
5536 (org-unmodified
5537 (and org-startup-with-beamer-mode (org-beamer-mode))
5538 (when org-startup-align-all-tables
5539 (org-table-map-tables 'org-table-align 'quietly))
5540 (when org-startup-with-inline-images
5541 (org-display-inline-images))
5542 (when org-startup-with-latex-preview
5543 (org-toggle-latex-fragment))
5544 (unless org-inhibit-startup-visibility-stuff
5545 (org-set-startup-visibility))
5546 (org-refresh-effort-properties)))
5547 ;; Try to set org-hide correctly
5548 (let ((foreground (org-find-invisible-foreground)))
5549 (if foreground
5550 (set-face-foreground 'org-hide foreground))))
5552 ;; Update `customize-package-emacs-version-alist'
5553 (add-to-list 'customize-package-emacs-version-alist
5554 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5555 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5556 ("8.2.6" . "24.4")))
5558 (defvar org-mode-transpose-word-syntax-table
5559 (let ((st (make-syntax-table)))
5560 (mapc (lambda(c) (modify-syntax-entry
5561 (string-to-char (car c)) "w p" st))
5562 org-emphasis-alist)
5563 st))
5565 (when (fboundp 'abbrev-table-put)
5566 (abbrev-table-put org-mode-abbrev-table
5567 :parents (list text-mode-abbrev-table)))
5569 (defun org-find-invisible-foreground ()
5570 (let ((candidates (remove
5571 "unspecified-bg"
5572 (nconc
5573 (list (face-background 'default)
5574 (face-background 'org-default))
5575 (mapcar
5576 (lambda (alist)
5577 (when (boundp alist)
5578 (cdr (assoc 'background-color (symbol-value alist)))))
5579 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5580 (list (face-foreground 'org-hide))))))
5581 (car (remove nil candidates))))
5583 (defun org-current-time (&optional rounding-minutes past)
5584 "Current time, possibly rounded to ROUNDING-MINUTES.
5585 When ROUNDING-MINUTES is not an integer, fall back on the car of
5586 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5587 the rounding returns a past time."
5588 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5589 (car org-time-stamp-rounding-minutes)))
5590 (time (decode-time)) res)
5591 (if (< r 1)
5592 (current-time)
5593 (setq res
5594 (apply 'encode-time
5595 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5596 (nthcdr 2 time))))
5597 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5598 (seconds-to-time (- (org-float-time res) (* r 60)))
5599 res))))
5601 (defun org-today ()
5602 "Return today date, considering `org-extend-today-until'."
5603 (time-to-days
5604 (time-subtract (current-time)
5605 (list 0 (* 3600 org-extend-today-until) 0))))
5607 ;;;; Font-Lock stuff, including the activators
5609 (defvar org-mouse-map (make-sparse-keymap))
5610 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5611 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5612 (when org-mouse-1-follows-link
5613 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5614 (when org-tab-follows-link
5615 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5616 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5618 (require 'font-lock)
5620 (defconst org-non-link-chars "]\t\n\r<>")
5621 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5622 "file+sys" "news" "shell" "elisp" "doi" "message"
5623 "help"))
5624 (defvar org-link-types-re nil
5625 "Matches a link that has a url-like prefix like \"http:\"")
5626 (defvar org-link-re-with-space nil
5627 "Matches a link with spaces, optional angular brackets around it.")
5628 (defvar org-link-re-with-space2 nil
5629 "Matches a link with spaces, optional angular brackets around it.")
5630 (defvar org-link-re-with-space3 nil
5631 "Matches a link with spaces, only for internal part in bracket links.")
5632 (defvar org-angle-link-re nil
5633 "Matches link with angular brackets, spaces are allowed.")
5634 (defvar org-plain-link-re nil
5635 "Matches plain link, without spaces.")
5636 (defvar org-bracket-link-regexp nil
5637 "Matches a link in double brackets.")
5638 (defvar org-bracket-link-analytic-regexp nil
5639 "Regular expression used to analyze links.
5640 Here is what the match groups contain after a match:
5641 1: http:
5642 2: http
5643 3: path
5644 4: [desc]
5645 5: desc")
5646 (defvar org-bracket-link-analytic-regexp++ nil
5647 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5648 (defvar org-any-link-re nil
5649 "Regular expression matching any link.")
5651 (defconst org-match-sexp-depth 3
5652 "Number of stacked braces for sub/superscript matching.")
5654 (defun org-create-multibrace-regexp (left right n)
5655 "Create a regular expression which will match a balanced sexp.
5656 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5657 as single character strings.
5658 The regexp returned will match the entire expression including the
5659 delimiters. It will also define a single group which contains the
5660 match except for the outermost delimiters. The maximum depth of
5661 stacked delimiters is N. Escaping delimiters is not possible."
5662 (let* ((nothing (concat "[^" left right "]*?"))
5663 (or "\\|")
5664 (re nothing)
5665 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5666 (while (> n 1)
5667 (setq n (1- n)
5668 re (concat re or next)
5669 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5670 (concat left "\\(" re "\\)" right)))
5672 (defconst org-match-substring-regexp
5673 (concat
5674 "\\(\\S-\\)\\([_^]\\)\\("
5675 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5676 "\\|"
5677 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5678 "\\|"
5679 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5680 "The regular expression matching a sub- or superscript.")
5682 (defconst org-match-substring-with-braces-regexp
5683 (concat
5684 "\\(\\S-\\)\\([_^]\\)"
5685 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5686 "The regular expression matching a sub- or superscript, forcing braces.")
5688 (defun org-make-link-regexps ()
5689 "Update the link regular expressions.
5690 This should be called after the variable `org-link-types' has changed."
5691 (let ((types-re (regexp-opt org-link-types t)))
5692 (setq org-link-types-re
5693 (concat "\\`" types-re ":")
5694 org-link-re-with-space
5695 (concat "<?" types-re ":"
5696 "\\([^" org-non-link-chars " ]"
5697 "[^" org-non-link-chars "]*"
5698 "[^" org-non-link-chars " ]\\)>?")
5699 org-link-re-with-space2
5700 (concat "<?" types-re ":"
5701 "\\([^" org-non-link-chars " ]"
5702 "[^\t\n\r]*"
5703 "[^" org-non-link-chars " ]\\)>?")
5704 org-link-re-with-space3
5705 (concat "<?" types-re ":"
5706 "\\([^" org-non-link-chars " ]"
5707 "[^\t\n\r]*\\)")
5708 org-angle-link-re
5709 (concat "<" types-re ":"
5710 "\\([^" org-non-link-chars " ]"
5711 "[^" org-non-link-chars "]*"
5712 "\\)>")
5713 org-plain-link-re
5714 (concat
5715 "\\<" types-re ":"
5716 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5717 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5718 org-bracket-link-regexp
5719 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5720 org-bracket-link-analytic-regexp
5721 (concat
5722 "\\[\\["
5723 "\\(" types-re ":\\)?"
5724 "\\([^]]+\\)"
5725 "\\]"
5726 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5727 "\\]")
5728 org-bracket-link-analytic-regexp++
5729 (concat
5730 "\\[\\["
5731 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5732 "\\([^]]+\\)"
5733 "\\]"
5734 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5735 "\\]")
5736 org-any-link-re
5737 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5738 org-angle-link-re "\\)\\|\\("
5739 org-plain-link-re "\\)"))))
5741 (org-make-link-regexps)
5743 (defvar org-emph-face nil)
5745 (defun org-do-emphasis-faces (limit)
5746 "Run through the buffer and emphasize strings."
5747 (let (rtn a)
5748 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5749 (let* ((border (char-after (match-beginning 3)))
5750 (bre (regexp-quote (char-to-string border))))
5751 (if (and (not (= border (char-after (match-beginning 4))))
5752 (not (save-match-data
5753 (string-match (concat bre ".*" bre)
5754 (replace-regexp-in-string
5755 "\n" " "
5756 (substring (match-string 2) 1 -1))))))
5757 (progn
5758 (setq rtn t)
5759 (setq a (assoc (match-string 3) org-emphasis-alist))
5760 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5761 'face
5762 (nth 1 a))
5763 (and (nth 2 a)
5764 (org-remove-flyspell-overlays-in
5765 (match-beginning 0) (match-end 0)))
5766 (add-text-properties (match-beginning 2) (match-end 2)
5767 '(font-lock-multiline t org-emphasis t))
5768 (when org-hide-emphasis-markers
5769 (add-text-properties (match-end 4) (match-beginning 5)
5770 '(invisible org-link))
5771 (add-text-properties (match-beginning 3) (match-end 3)
5772 '(invisible org-link))))))
5773 (goto-char (1+ (match-beginning 0))))
5774 rtn))
5776 (defun org-emphasize (&optional char)
5777 "Insert or change an emphasis, i.e. a font like bold or italic.
5778 If there is an active region, change that region to a new emphasis.
5779 If there is no region, just insert the marker characters and position
5780 the cursor between them.
5781 CHAR should be the marker character. If it is a space, it means to
5782 remove the emphasis of the selected region.
5783 If CHAR is not given (for example in an interactive call) it will be
5784 prompted for."
5785 (interactive)
5786 (let ((erc org-emphasis-regexp-components)
5787 (prompt "")
5788 (string "") beg end move c s)
5789 (if (org-region-active-p)
5790 (setq beg (region-beginning) end (region-end)
5791 string (buffer-substring beg end))
5792 (setq move t))
5794 (unless char
5795 (message "Emphasis marker or tag: [%s]"
5796 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5797 (setq char (read-char-exclusive)))
5798 (if (equal char ?\ )
5799 (setq s "" move nil)
5800 (unless (assoc (char-to-string char) org-emphasis-alist)
5801 (user-error "No such emphasis marker: \"%c\"" char))
5802 (setq s (char-to-string char)))
5803 (while (and (> (length string) 1)
5804 (equal (substring string 0 1) (substring string -1))
5805 (assoc (substring string 0 1) org-emphasis-alist))
5806 (setq string (substring string 1 -1)))
5807 (setq string (concat s string s))
5808 (if beg (delete-region beg end))
5809 (unless (or (bolp)
5810 (string-match (concat "[" (nth 0 erc) "\n]")
5811 (char-to-string (char-before (point)))))
5812 (insert " "))
5813 (unless (or (eobp)
5814 (string-match (concat "[" (nth 1 erc) "\n]")
5815 (char-to-string (char-after (point)))))
5816 (insert " ") (backward-char 1))
5817 (insert string)
5818 (and move (backward-char 1))))
5820 (defconst org-nonsticky-props
5821 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5823 (defsubst org-rear-nonsticky-at (pos)
5824 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5826 (defun org-activate-plain-links (limit)
5827 "Add link properties for plain links."
5828 (let (f hl)
5829 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5830 (not (member 'org-tag
5831 (get-text-property (1- (match-beginning 0)) 'face)))
5832 (not (org-in-src-block-p)))
5833 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5834 (setq f (get-text-property (match-beginning 0) 'face))
5835 (setq hl (org-match-string-no-properties 0))
5836 (if (or (eq f 'org-tag)
5837 (and (listp f) (memq 'org-tag f)))
5839 (add-text-properties (match-beginning 0) (match-end 0)
5840 (list 'mouse-face 'highlight
5841 'face 'org-link
5842 'htmlize-link `(:uri ,hl)
5843 'keymap org-mouse-map))
5844 (org-rear-nonsticky-at (match-end 0)))
5845 t)))
5847 (defun org-activate-code (limit)
5848 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5849 (progn
5850 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5851 (remove-text-properties (match-beginning 0) (match-end 0)
5852 '(display t invisible t intangible t))
5853 t)))
5855 (defcustom org-src-fontify-natively t
5856 "When non-nil, fontify code in code blocks."
5857 :type 'boolean
5858 :version "24.4"
5859 :package-version '(Org . "8.3")
5860 :group 'org-appearance
5861 :group 'org-babel)
5863 (defcustom org-allow-promoting-top-level-subtree nil
5864 "When non-nil, allow promoting a top level subtree.
5865 The leading star of the top level headline will be replaced
5866 by a #."
5867 :type 'boolean
5868 :version "24.1"
5869 :group 'org-appearance)
5871 (defun org-fontify-meta-lines-and-blocks (limit)
5872 (condition-case nil
5873 (org-fontify-meta-lines-and-blocks-1 limit)
5874 (error (message "org-mode fontification error"))))
5876 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5877 "Fontify #+ lines and blocks."
5878 (let ((case-fold-search t))
5879 (if (re-search-forward
5880 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5881 limit t)
5882 (let ((beg (match-beginning 0))
5883 (block-start (match-end 0))
5884 (block-end nil)
5885 (lang (match-string 7))
5886 (beg1 (line-beginning-position 2))
5887 (dc1 (downcase (match-string 2)))
5888 (dc3 (downcase (match-string 3)))
5889 end end1 quoting block-type ovl)
5890 (cond
5891 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5892 ;; a single line of backend-specific content
5893 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5894 (remove-text-properties (match-beginning 0) (match-end 0)
5895 '(display t invisible t intangible t))
5896 (add-text-properties (match-beginning 1) (match-end 3)
5897 '(font-lock-fontified t face org-meta-line))
5898 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5899 '(font-lock-fontified t face org-block))
5900 ; for backend-specific code
5902 ((and (match-end 4) (equal dc3 "+begin"))
5903 ;; Truly a block
5904 (setq block-type (downcase (match-string 5))
5905 quoting (member block-type org-protecting-blocks))
5906 (when (re-search-forward
5907 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5908 nil t) ;; on purpose, we look further than LIMIT
5909 (setq end (min (point-max) (match-end 0))
5910 end1 (min (point-max) (1- (match-beginning 0))))
5911 (setq block-end (match-beginning 0))
5912 (when quoting
5913 (org-remove-flyspell-overlays-in beg1 end1)
5914 (remove-text-properties beg end
5915 '(display t invisible t intangible t)))
5916 (add-text-properties
5917 beg end '(font-lock-fontified t font-lock-multiline t))
5918 (add-text-properties beg beg1 '(face org-meta-line))
5919 (org-remove-flyspell-overlays-in beg beg1)
5920 (add-text-properties ; For end_src
5921 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5922 (org-remove-flyspell-overlays-in end1 end)
5923 (cond
5924 ((and lang (not (string= lang "")) org-src-fontify-natively)
5925 (org-src-font-lock-fontify-block lang block-start block-end)
5926 (add-text-properties beg1 block-end '(src-block t)))
5927 (quoting
5928 (add-text-properties beg1 (min (point-max) (1+ end1))
5929 '(face org-block))) ; end of source block
5930 ((not org-fontify-quote-and-verse-blocks))
5931 ((string= block-type "quote")
5932 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5933 ((string= block-type "verse")
5934 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5935 (add-text-properties beg beg1 '(face org-block-begin-line))
5936 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5937 '(face org-block-end-line))
5939 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5940 (org-remove-flyspell-overlays-in
5941 (match-beginning 0)
5942 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5943 (add-text-properties
5944 beg (match-end 3)
5945 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5946 '(font-lock-fontified t invisible t)
5947 '(font-lock-fontified t face org-document-info-keyword)))
5948 (add-text-properties
5949 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5950 (if (string-equal dc1 "+title:")
5951 '(font-lock-fontified t face org-document-title)
5952 '(font-lock-fontified t face org-document-info))))
5953 ((or (equal dc1 "+results")
5954 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5955 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5956 "+call:" "+header:" "+headers:" "+name:"))
5957 (and (match-end 4) (equal dc3 "+attr")))
5958 (org-remove-flyspell-overlays-in
5959 (match-beginning 0)
5960 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5961 (add-text-properties
5962 beg (match-end 0)
5963 '(font-lock-fontified t face org-meta-line))
5965 ((member dc3 '(" " ""))
5966 (org-remove-flyspell-overlays-in beg (match-end 0))
5967 (add-text-properties
5968 beg (match-end 0)
5969 '(font-lock-fontified t face font-lock-comment-face)))
5970 (t ;; just any other in-buffer setting, but not indented
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (add-text-properties
5973 beg (match-end 0)
5974 '(font-lock-fontified t face org-meta-line))
5975 t))))))
5977 (defun org-fontify-drawers (limit)
5978 "Fontify drawers."
5979 (when (re-search-forward org-drawer-regexp limit t)
5980 (add-text-properties
5981 (match-beginning 0) (match-end 0)
5982 '(font-lock-fontified t face org-special-keyword))
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5986 (defun org-fontify-macros (limit)
5987 "Fontify macros."
5988 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5989 (add-text-properties
5990 (match-beginning 0) (match-end 0)
5991 '(font-lock-fontified t face org-macro))
5992 (when org-hide-macro-markers
5993 (add-text-properties (match-end 2) (match-beginning 2)
5994 '(invisible t))
5995 (add-text-properties (match-beginning 1) (match-end 1)
5996 '(invisible t)))
5997 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6000 (defun org-activate-angle-links (limit)
6001 "Add text properties for angle links."
6002 (if (and (re-search-forward org-angle-link-re limit t)
6003 (not (org-in-src-block-p)))
6004 (progn
6005 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6006 (add-text-properties (match-beginning 0) (match-end 0)
6007 (list 'mouse-face 'highlight
6008 'keymap org-mouse-map))
6009 (org-rear-nonsticky-at (match-end 0))
6010 t)))
6012 (defun org-activate-footnote-links (limit)
6013 "Add text properties for footnotes."
6014 (let ((fn (org-footnote-next-reference-or-definition limit)))
6015 (when fn
6016 (let* ((beg (nth 1 fn))
6017 (end (nth 2 fn))
6018 (label (car fn))
6019 (referencep (/= (line-beginning-position) beg)))
6020 (when (and referencep (nth 3 fn))
6021 (save-excursion
6022 (goto-char beg)
6023 (search-forward (or label "fn:"))
6024 (org-remove-flyspell-overlays-in beg (match-end 0))))
6025 (add-text-properties beg end
6026 (list 'mouse-face 'highlight
6027 'keymap org-mouse-map
6028 'help-echo
6029 (if referencep "Footnote reference"
6030 "Footnote definition")
6031 'font-lock-fontified t
6032 'font-lock-multiline t
6033 'face 'org-footnote))))))
6035 (defun org-activate-bracket-links (limit)
6036 "Add text properties for bracketed links."
6037 (if (and (re-search-forward org-bracket-link-regexp limit t)
6038 (not (org-in-src-block-p)))
6039 (let* ((hl (org-match-string-no-properties 1))
6040 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6041 (ip (org-maybe-intangible
6042 (list 'invisible 'org-link
6043 'keymap org-mouse-map 'mouse-face 'highlight
6044 'font-lock-multiline t 'help-echo help
6045 'htmlize-link `(:uri ,hl))))
6046 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6047 'font-lock-multiline t 'help-echo help
6048 'htmlize-link `(:uri ,hl))))
6049 ;; We need to remove the invisible property here. Table narrowing
6050 ;; may have made some of this invisible.
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6052 (remove-text-properties (match-beginning 0) (match-end 0)
6053 '(invisible nil))
6054 (if (match-end 3)
6055 (progn
6056 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6057 (org-rear-nonsticky-at (match-beginning 3))
6058 (add-text-properties (match-beginning 3) (match-end 3) vp)
6059 (org-rear-nonsticky-at (match-end 3))
6060 (add-text-properties (match-end 3) (match-end 0) ip)
6061 (org-rear-nonsticky-at (match-end 0)))
6062 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6063 (org-rear-nonsticky-at (match-beginning 1))
6064 (add-text-properties (match-beginning 1) (match-end 1) vp)
6065 (org-rear-nonsticky-at (match-end 1))
6066 (add-text-properties (match-end 1) (match-end 0) ip)
6067 (org-rear-nonsticky-at (match-end 0)))
6068 t)))
6070 (defun org-activate-dates (limit)
6071 "Add text properties for dates."
6072 (if (and (re-search-forward org-tsr-regexp-both limit t)
6073 (not (equal (char-before (match-beginning 0)) 91)))
6074 (progn
6075 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6076 (add-text-properties (match-beginning 0) (match-end 0)
6077 (list 'mouse-face 'highlight
6078 'keymap org-mouse-map))
6079 (org-rear-nonsticky-at (match-end 0))
6080 (when org-display-custom-times
6081 (if (match-end 3)
6082 (org-display-custom-time (match-beginning 3) (match-end 3)))
6083 (org-display-custom-time (match-beginning 1) (match-end 1)))
6084 t)))
6086 (defvar org-target-link-regexp nil
6087 "Regular expression matching radio targets in plain text.")
6088 (make-variable-buffer-local 'org-target-link-regexp)
6090 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6091 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6092 border border border))
6093 "Regular expression matching a link target.")
6095 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6096 "Regular expression matching a radio target.")
6098 (defconst org-any-target-regexp
6099 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6100 "Regular expression matching any target.")
6102 (defun org-activate-target-links (limit)
6103 "Add text properties for target matches."
6104 (when org-target-link-regexp
6105 (let ((case-fold-search t))
6106 (if (re-search-forward org-target-link-regexp limit t)
6107 (progn
6108 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6109 (add-text-properties (match-beginning 1) (match-end 1)
6110 (list 'mouse-face 'highlight
6111 'keymap org-mouse-map
6112 'help-echo "Radio target link"
6113 'org-linked-text t))
6114 (org-rear-nonsticky-at (match-end 1))
6115 t)))))
6117 (defun org-update-radio-target-regexp ()
6118 "Find all radio targets in this file and update the regular expression.
6119 Also refresh fontification if needed."
6120 (interactive)
6121 (let ((old-regexp org-target-link-regexp)
6122 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6123 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6124 (targets
6125 (org-with-wide-buffer
6126 (goto-char (point-min))
6127 (let (rtn)
6128 (while (re-search-forward org-radio-target-regexp nil t)
6129 ;; Make sure point is really within the object.
6130 (backward-char)
6131 (let ((obj (org-element-context)))
6132 (when (eq (org-element-type obj) 'radio-target)
6133 (add-to-list 'rtn (org-element-property :value obj)))))
6134 rtn))))
6135 (setq org-target-link-regexp
6136 (and targets
6137 (concat before-re
6138 (mapconcat
6139 (lambda (x)
6140 (replace-regexp-in-string
6141 " +" "\\s-+" (regexp-quote x) t t))
6142 targets
6143 "\\|")
6144 after-re)))
6145 (unless (equal old-regexp org-target-link-regexp)
6146 ;; Clean-up cache.
6147 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6148 ((not org-target-link-regexp) old-regexp)
6150 (concat before-re
6151 (mapconcat
6152 (lambda (re)
6153 (substring re (length before-re)
6154 (- (length after-re))))
6155 (list old-regexp org-target-link-regexp)
6156 "\\|")
6157 after-re)))))
6158 (org-with-wide-buffer
6159 (goto-char (point-min))
6160 (while (re-search-forward regexp nil t)
6161 (org-element-cache-refresh (match-beginning 1)))))
6162 ;; Re fontify buffer.
6163 (when (memq 'radio org-highlight-links)
6164 (org-restart-font-lock)))))
6166 (defun org-hide-wide-columns (limit)
6167 (let (s e)
6168 (setq s (text-property-any (point) (or limit (point-max))
6169 'org-cwidth t))
6170 (when s
6171 (setq e (next-single-property-change s 'org-cwidth))
6172 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6173 (goto-char e)
6174 t)))
6176 (defvar org-latex-and-related-regexp nil
6177 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6179 (defun org-compute-latex-and-related-regexp ()
6180 "Compute regular expression for LaTeX, entities and sub/superscript.
6181 Result depends on variable `org-highlight-latex-and-related'."
6182 (org-set-local
6183 'org-latex-and-related-regexp
6184 (let* ((re-sub
6185 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6186 ((eq org-use-sub-superscripts '{})
6187 (list org-match-substring-with-braces-regexp))
6188 (org-use-sub-superscripts (list org-match-substring-regexp))))
6189 (re-latex
6190 (when (memq 'latex org-highlight-latex-and-related)
6191 (let ((matchers (plist-get org-format-latex-options :matchers)))
6192 (delq nil
6193 (mapcar (lambda (x)
6194 (and (member (car x) matchers) (nth 1 x)))
6195 org-latex-regexps)))))
6196 (re-entities
6197 (when (memq 'entities org-highlight-latex-and-related)
6198 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6199 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6201 (defun org-do-latex-and-related (limit)
6202 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6203 LIMIT bounds the search for syntax to highlight. Stop at first
6204 highlighted object, if any. Return t if some highlighting was
6205 done, nil otherwise."
6206 (when (org-string-nw-p org-latex-and-related-regexp)
6207 (catch 'found
6208 (while (re-search-forward org-latex-and-related-regexp limit t)
6209 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6210 'face))
6211 '(org-code org-verbatim underline))
6212 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6213 '(?_ ?^))
6215 0)))
6216 (font-lock-prepend-text-property
6217 (+ offset (match-beginning 0)) (match-end 0)
6218 'face 'org-latex-and-related)
6219 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6220 '(font-lock-multiline t)))
6221 (throw 'found t)))
6222 nil)))
6224 (defun org-restart-font-lock ()
6225 "Restart `font-lock-mode', to force refontification."
6226 (when (and (boundp 'font-lock-mode) font-lock-mode)
6227 (font-lock-mode -1)
6228 (font-lock-mode 1)))
6230 (defun org-activate-tags (limit)
6231 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6232 (progn
6233 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6234 (add-text-properties (match-beginning 1) (match-end 1)
6235 (list 'mouse-face 'highlight
6236 'keymap org-mouse-map))
6237 (org-rear-nonsticky-at (match-end 1))
6238 t)))
6240 (defun org-outline-level ()
6241 "Compute the outline level of the heading at point.
6242 If this is called at a normal headline, the level is the number of stars.
6243 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6244 (save-excursion
6245 (if (not (ignore-errors (org-back-to-heading t)))
6247 (looking-at org-outline-regexp)
6248 (1- (- (match-end 0) (match-beginning 0))))))
6250 (defvar org-font-lock-keywords nil)
6252 (defsubst org-re-property (property &optional literal allow-null)
6253 "Return a regexp matching a PROPERTY line.
6254 Match group 3 will be set to the value if it exists."
6255 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6256 (if literal property (regexp-quote property))
6257 "\\):\\)[ \t]+\\(?3:[^ \t\r\n]"
6258 (if allow-null "*")
6259 ".*?\\)\\(?5:[ \t]*\\)$"))
6261 (defconst org-property-re
6262 (org-re-property ".*?" 'literal t)
6263 "Regular expression matching a property line.
6264 There are four matching groups:
6265 1: :PROPKEY: including the leading and trailing colon,
6266 2: PROPKEY without the leading and trailing colon,
6267 3: PROPVAL without leading or trailing spaces,
6268 4: the indentation of the current line,
6269 5: trailing whitespace.")
6271 (defvar org-font-lock-hook nil
6272 "Functions to be called for special font lock stuff.")
6274 (defvar org-font-lock-set-keywords-hook nil
6275 "Functions that can manipulate `org-font-lock-extra-keywords'.
6276 This is called after `org-font-lock-extra-keywords' is defined, but before
6277 it is installed to be used by font lock. This can be useful if something
6278 needs to be inserted at a specific position in the font-lock sequence.")
6280 (defun org-font-lock-hook (limit)
6281 "Run `org-font-lock-hook' within LIMIT."
6282 (run-hook-with-args 'org-font-lock-hook limit))
6284 (defun org-set-font-lock-defaults ()
6285 "Set font lock defaults for the current buffer."
6286 (let* ((em org-fontify-emphasized-text)
6287 (lk org-highlight-links)
6288 (org-font-lock-extra-keywords
6289 (list
6290 ;; Call the hook
6291 '(org-font-lock-hook)
6292 ;; Headlines
6293 `(,(if org-fontify-whole-heading-line
6294 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6295 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6296 (1 (org-get-level-face 1))
6297 (2 (org-get-level-face 2))
6298 (3 (org-get-level-face 3)))
6299 ;; Table lines
6300 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6301 (1 'org-table t))
6302 ;; Table internals
6303 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6304 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6305 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6306 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6307 ;; Drawers
6308 '(org-fontify-drawers)
6309 ;; Properties
6310 (list org-property-re
6311 '(1 'org-special-keyword t)
6312 '(3 'org-property-value t))
6313 ;; Links
6314 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6315 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6316 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6317 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6318 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6319 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6320 (if (memq 'footnote lk) '(org-activate-footnote-links))
6321 ;; Targets.
6322 (list org-any-target-regexp '(0 'org-target t))
6323 ;; Diary sexps.
6324 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6325 ;; Macro
6326 '(org-fontify-macros)
6327 '(org-hide-wide-columns (0 nil append))
6328 ;; TODO keyword
6329 (list (format org-heading-keyword-regexp-format
6330 org-todo-regexp)
6331 '(2 (org-get-todo-face 2) t))
6332 ;; DONE
6333 (if org-fontify-done-headline
6334 (list (format org-heading-keyword-regexp-format
6335 (concat
6336 "\\(?:"
6337 (mapconcat 'regexp-quote org-done-keywords "\\|")
6338 "\\)"))
6339 '(2 'org-headline-done t))
6340 nil)
6341 ;; Priorities
6342 '(org-font-lock-add-priority-faces)
6343 ;; Tags
6344 '(org-font-lock-add-tag-faces)
6345 ;; Tags groups
6346 (if (and org-group-tags org-tag-groups-alist)
6347 (list (concat org-outline-regexp-bol ".+\\(:"
6348 (regexp-opt (mapcar 'car org-tag-groups-alist))
6349 ":\\).*$")
6350 '(1 'org-tag-group prepend)))
6351 ;; Special keywords
6352 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6353 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6354 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6355 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6356 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6357 ;; Emphasis
6358 (if em
6359 (if (featurep 'xemacs)
6360 '(org-do-emphasis-faces (0 nil append))
6361 '(org-do-emphasis-faces)))
6362 ;; Checkboxes
6363 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6364 1 'org-checkbox prepend)
6365 (if (cdr (assq 'checkbox org-list-automatic-rules))
6366 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6367 (0 (org-get-checkbox-statistics-face) t)))
6368 ;; Description list items
6369 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6370 1 'org-list-dt prepend)
6371 ;; ARCHIVEd headings
6372 (list (concat
6373 org-outline-regexp-bol
6374 "\\(.*:" org-archive-tag ":.*\\)")
6375 '(1 'org-archived prepend))
6376 ;; Specials
6377 '(org-do-latex-and-related)
6378 '(org-fontify-entities)
6379 '(org-raise-scripts)
6380 ;; Code
6381 '(org-activate-code (1 'org-code t))
6382 ;; COMMENT
6383 (list (format
6384 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6385 org-todo-regexp
6386 org-comment-string)
6387 '(9 'org-special-keyword t))
6388 ;; Blocks and meta lines
6389 '(org-fontify-meta-lines-and-blocks))))
6390 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6391 (run-hooks 'org-font-lock-set-keywords-hook)
6392 ;; Now set the full font-lock-keywords
6393 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6394 (org-set-local 'font-lock-defaults
6395 '(org-font-lock-keywords t nil nil backward-paragraph))
6396 (kill-local-variable 'font-lock-keywords) nil))
6398 (defun org-toggle-pretty-entities ()
6399 "Toggle the composition display of entities as UTF8 characters."
6400 (interactive)
6401 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6402 (org-restart-font-lock)
6403 (if org-pretty-entities
6404 (message "Entities are now displayed as UTF8 characters")
6405 (save-restriction
6406 (widen)
6407 (org-decompose-region (point-min) (point-max))
6408 (message "Entities are now displayed as plain text"))))
6410 (defvar org-custom-properties-overlays nil
6411 "List of overlays used for custom properties.")
6412 (make-variable-buffer-local 'org-custom-properties-overlays)
6414 (defun org-toggle-custom-properties-visibility ()
6415 "Display or hide properties in `org-custom-properties'."
6416 (interactive)
6417 (if org-custom-properties-overlays
6418 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6419 (setq org-custom-properties-overlays nil))
6420 (unless (not org-custom-properties)
6421 (save-excursion
6422 (save-restriction
6423 (widen)
6424 (goto-char (point-min))
6425 (while (re-search-forward org-property-re nil t)
6426 (mapc (lambda(p)
6427 (when (equal p (substring (match-string 1) 1 -1))
6428 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6429 (overlay-put o 'invisible t)
6430 (overlay-put o 'org-custom-property t)
6431 (push o org-custom-properties-overlays))))
6432 org-custom-properties)))))))
6434 (defun org-fontify-entities (limit)
6435 "Find an entity to fontify."
6436 (let (ee)
6437 (when org-pretty-entities
6438 (catch 'match
6439 (while (re-search-forward
6440 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6441 limit t)
6442 (if (and (not (org-at-comment-p))
6443 (setq ee (org-entity-get (match-string 1)))
6444 (= (length (nth 6 ee)) 1))
6445 (let*
6446 ((end (if (equal (match-string 2) "{}")
6447 (match-end 2)
6448 (match-end 1))))
6449 (add-text-properties
6450 (match-beginning 0) end
6451 (list 'font-lock-fontified t))
6452 (compose-region (match-beginning 0) end
6453 (nth 6 ee) nil)
6454 (backward-char 1)
6455 (throw 'match t))))
6456 nil))))
6458 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6459 "Fontify string S like in Org-mode."
6460 (with-temp-buffer
6461 (insert s)
6462 (let ((org-odd-levels-only odd-levels))
6463 (org-mode)
6464 (font-lock-ensure)
6465 (buffer-string))))
6467 (defvar org-m nil)
6468 (defvar org-l nil)
6469 (defvar org-f nil)
6470 (defun org-get-level-face (n)
6471 "Get the right face for match N in font-lock matching of headlines."
6472 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6473 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6474 (if org-cycle-level-faces
6475 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6476 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6477 (cond
6478 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6479 ((eq n 2) org-f)
6480 (t (if org-level-color-stars-only nil org-f))))
6483 (defun org-get-todo-face (kwd)
6484 "Get the right face for a TODO keyword KWD.
6485 If KWD is a number, get the corresponding match group."
6486 (if (numberp kwd) (setq kwd (match-string kwd)))
6487 (or (org-face-from-face-or-color
6488 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6489 (and (member kwd org-done-keywords) 'org-done)
6490 'org-todo))
6492 (defun org-face-from-face-or-color (context inherit face-or-color)
6493 "Create a face list that inherits INHERIT, but sets the foreground color.
6494 When FACE-OR-COLOR is not a string, just return it."
6495 (if (stringp face-or-color)
6496 (list :inherit inherit
6497 (cdr (assoc context org-faces-easy-properties))
6498 face-or-color)
6499 face-or-color))
6501 (defun org-font-lock-add-tag-faces (limit)
6502 "Add the special tag faces."
6503 (when (and org-tag-faces org-tags-special-faces-re)
6504 (while (re-search-forward org-tags-special-faces-re limit t)
6505 (add-text-properties (match-beginning 1) (match-end 1)
6506 (list 'face (org-get-tag-face 1)
6507 'font-lock-fontified t))
6508 (backward-char 1))))
6510 (defun org-font-lock-add-priority-faces (limit)
6511 "Add the special priority faces."
6512 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6513 (when (save-match-data (org-at-heading-p))
6514 (add-text-properties
6515 (match-beginning 0) (match-end 0)
6516 (list 'face (or (org-face-from-face-or-color
6517 'priority 'org-priority
6518 (cdr (assoc (char-after (match-beginning 1))
6519 org-priority-faces)))
6520 'org-priority)
6521 'font-lock-fontified t)))))
6523 (defun org-get-tag-face (kwd)
6524 "Get the right face for a TODO keyword KWD.
6525 If KWD is a number, get the corresponding match group."
6526 (if (numberp kwd) (setq kwd (match-string kwd)))
6527 (or (org-face-from-face-or-color
6528 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6529 'org-tag))
6531 (defun org-unfontify-region (beg end &optional maybe_loudly)
6532 "Remove fontification and activation overlays from links."
6533 (font-lock-default-unfontify-region beg end)
6534 (let* ((buffer-undo-list t)
6535 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6536 (inhibit-modification-hooks t)
6537 deactivate-mark buffer-file-name buffer-file-truename)
6538 (org-decompose-region beg end)
6539 (remove-text-properties beg end
6540 '(mouse-face t keymap t org-linked-text t
6541 invisible t intangible t
6542 org-emphasis t))
6543 (org-remove-font-lock-display-properties beg end)))
6545 (defconst org-script-display '(((raise -0.3) (height 0.7))
6546 ((raise 0.3) (height 0.7))
6547 ((raise -0.5))
6548 ((raise 0.5)))
6549 "Display properties for showing superscripts and subscripts.")
6551 (defun org-remove-font-lock-display-properties (beg end)
6552 "Remove specific display properties that have been added by font lock.
6553 The will remove the raise properties that are used to show superscripts
6554 and subscripts."
6555 (let (next prop)
6556 (while (< beg end)
6557 (setq next (next-single-property-change beg 'display nil end)
6558 prop (get-text-property beg 'display))
6559 (if (member prop org-script-display)
6560 (put-text-property beg next 'display nil))
6561 (setq beg next))))
6563 (defun org-raise-scripts (limit)
6564 "Add raise properties to sub/superscripts."
6565 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6566 (if (re-search-forward
6567 (if (eq org-use-sub-superscripts t)
6568 org-match-substring-regexp
6569 org-match-substring-with-braces-regexp)
6570 limit t)
6571 (let* ((pos (point)) table-p comment-p
6572 (mpos (match-beginning 3))
6573 (emph-p (get-text-property mpos 'org-emphasis))
6574 (link-p (get-text-property mpos 'mouse-face))
6575 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6576 (goto-char (point-at-bol))
6577 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6578 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6579 (goto-char pos)
6580 ;; Handle a_b^c
6581 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6582 (if (or comment-p emph-p link-p keyw-p)
6584 (put-text-property (match-beginning 3) (match-end 0)
6585 'display
6586 (if (equal (char-after (match-beginning 2)) ?^)
6587 (nth (if table-p 3 1) org-script-display)
6588 (nth (if table-p 2 0) org-script-display)))
6589 (add-text-properties (match-beginning 2) (match-end 2)
6590 (list 'invisible t
6591 'org-dwidth t 'org-dwidth-n 1))
6592 (if (and (eq (char-after (match-beginning 3)) ?{)
6593 (eq (char-before (match-end 3)) ?}))
6594 (progn
6595 (add-text-properties
6596 (match-beginning 3) (1+ (match-beginning 3))
6597 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6598 (add-text-properties
6599 (1- (match-end 3)) (match-end 3)
6600 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6601 t)))))
6603 ;;;; Visibility cycling, including org-goto and indirect buffer
6605 ;;; Cycling
6607 (defvar org-cycle-global-status nil)
6608 (make-variable-buffer-local 'org-cycle-global-status)
6609 (put 'org-cycle-global-status 'org-state t)
6610 (defvar org-cycle-subtree-status nil)
6611 (make-variable-buffer-local 'org-cycle-subtree-status)
6612 (put 'org-cycle-subtree-status 'org-state t)
6614 (defvar org-inlinetask-min-level)
6616 (defun org-unlogged-message (&rest args)
6617 "Display a message, but avoid logging it in the *Messages* buffer."
6618 (let ((message-log-max nil))
6619 (apply 'message args)))
6621 ;;;###autoload
6622 (defun org-cycle (&optional arg)
6623 "TAB-action and visibility cycling for Org-mode.
6625 This is the command invoked in Org-mode by the TAB key. Its main purpose
6626 is outline visibility cycling, but it also invokes other actions
6627 in special contexts.
6629 - When this function is called with a prefix argument, rotate the entire
6630 buffer through 3 states (global cycling)
6631 1. OVERVIEW: Show only top-level headlines.
6632 2. CONTENTS: Show all headlines of all levels, but no body text.
6633 3. SHOW ALL: Show everything.
6634 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6635 determined by the variable `org-startup-folded', and by any VISIBILITY
6636 properties in the buffer.
6637 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6638 including any drawers.
6640 - When inside a table, re-align the table and move to the next field.
6642 - When point is at the beginning of a headline, rotate the subtree started
6643 by this line through 3 different states (local cycling)
6644 1. FOLDED: Only the main headline is shown.
6645 2. CHILDREN: The main headline and the direct children are shown.
6646 From this state, you can move to one of the children
6647 and zoom in further.
6648 3. SUBTREE: Show the entire subtree, including body text.
6649 If there is no subtree, switch directly from CHILDREN to FOLDED.
6651 - When point is at the beginning of an empty headline and the variable
6652 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6653 of the headline by demoting and promoting it to likely levels. This
6654 speeds up creation document structure by pressing TAB once or several
6655 times right after creating a new headline.
6657 - When there is a numeric prefix, go up to a heading with level ARG, do
6658 a `show-subtree' and return to the previous cursor position. If ARG
6659 is negative, go up that many levels.
6661 - When point is not at the beginning of a headline, execute the global
6662 binding for TAB, which is re-indenting the line. See the option
6663 `org-cycle-emulate-tab' for details.
6665 - Special case: if point is at the beginning of the buffer and there is
6666 no headline in line 1, this function will act as if called with prefix arg
6667 (C-u TAB, same as S-TAB) also when called without prefix arg.
6668 But only if also the variable `org-cycle-global-at-bob' is t."
6669 (interactive "P")
6670 (org-load-modules-maybe)
6671 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6672 (and org-cycle-level-after-item/entry-creation
6673 (or (org-cycle-level)
6674 (org-cycle-item-indentation))))
6675 (let* ((limit-level
6676 (or org-cycle-max-level
6677 (and (boundp 'org-inlinetask-min-level)
6678 org-inlinetask-min-level
6679 (1- org-inlinetask-min-level))))
6680 (nstars (and limit-level
6681 (if org-odd-levels-only
6682 (and limit-level (1- (* limit-level 2)))
6683 limit-level)))
6684 (org-outline-regexp
6685 (if (not (derived-mode-p 'org-mode))
6686 outline-regexp
6687 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6688 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6689 (not (looking-at org-outline-regexp))))
6690 (org-cycle-hook
6691 (if bob-special
6692 (delq 'org-optimize-window-after-visibility-change
6693 (copy-sequence org-cycle-hook))
6694 org-cycle-hook))
6695 (pos (point)))
6697 (if (or bob-special (equal arg '(4)))
6698 ;; special case: use global cycling
6699 (setq arg t))
6701 (cond
6703 ((equal arg '(16))
6704 (setq last-command 'dummy)
6705 (org-set-startup-visibility)
6706 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6708 ((equal arg '(64))
6709 (show-all)
6710 (org-unlogged-message "Entire buffer visible, including drawers"))
6712 ;; Try cdlatex TAB completion
6713 ((org-try-cdlatex-tab))
6715 ;; Table: enter it or move to the next field.
6716 ((org-at-table-p 'any)
6717 (if (org-at-table.el-p)
6718 (message "Use C-c ' to edit table.el tables")
6719 (if arg (org-table-edit-field t)
6720 (org-table-justify-field-maybe)
6721 (call-interactively 'org-table-next-field))))
6723 ((run-hook-with-args-until-success
6724 'org-tab-after-check-for-table-hook))
6726 ;; Global cycling: delegate to `org-cycle-internal-global'.
6727 ((eq arg t) (org-cycle-internal-global))
6729 ;; Drawers: delegate to `org-flag-drawer'.
6730 ((save-excursion
6731 (beginning-of-line 1)
6732 (looking-at org-drawer-regexp))
6733 (org-flag-drawer ; toggle block visibility
6734 (not (get-char-property (match-end 0) 'invisible))))
6736 ;; Show-subtree, ARG levels up from here.
6737 ((integerp arg)
6738 (save-excursion
6739 (org-back-to-heading)
6740 (outline-up-heading (if (< arg 0) (- arg)
6741 (- (funcall outline-level) arg)))
6742 (org-show-subtree)))
6744 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6745 ((and (featurep 'org-inlinetask)
6746 (org-inlinetask-at-task-p)
6747 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6748 (org-inlinetask-toggle-visibility))
6750 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6751 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6752 (save-excursion (beginning-of-line 1)
6753 (looking-at org-outline-regexp)))
6754 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6755 (org-cycle-internal-local))
6757 ;; From there: TAB emulation and template completion.
6758 (buffer-read-only (org-back-to-heading))
6760 ((run-hook-with-args-until-success
6761 'org-tab-after-check-for-cycling-hook))
6763 ((org-try-structure-completion))
6765 ((run-hook-with-args-until-success
6766 'org-tab-before-tab-emulation-hook))
6768 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6769 (or (not (bolp))
6770 (not (looking-at org-outline-regexp))))
6771 (call-interactively (global-key-binding "\t")))
6773 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6774 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6775 (or (and (eq org-cycle-emulate-tab 'white)
6776 (= (match-end 0) (point-at-eol)))
6777 (and (eq org-cycle-emulate-tab 'whitestart)
6778 (>= (match-end 0) pos))))
6780 (eq org-cycle-emulate-tab t))
6781 (call-interactively (global-key-binding "\t")))
6783 (t (save-excursion
6784 (org-back-to-heading)
6785 (org-cycle)))))))
6787 (defun org-cycle-internal-global ()
6788 "Do the global cycling action."
6789 ;; Hack to avoid display of messages for .org attachments in Gnus
6790 (let ((ga (string-match "\\*fontification" (buffer-name))))
6791 (cond
6792 ((and (eq last-command this-command)
6793 (eq org-cycle-global-status 'overview))
6794 ;; We just created the overview - now do table of contents
6795 ;; This can be slow in very large buffers, so indicate action
6796 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6797 (unless ga (org-unlogged-message "CONTENTS..."))
6798 (org-content)
6799 (unless ga (org-unlogged-message "CONTENTS...done"))
6800 (setq org-cycle-global-status 'contents)
6801 (run-hook-with-args 'org-cycle-hook 'contents))
6803 ((and (eq last-command this-command)
6804 (eq org-cycle-global-status 'contents))
6805 ;; We just showed the table of contents - now show everything
6806 (run-hook-with-args 'org-pre-cycle-hook 'all)
6807 (show-all)
6808 (unless ga (org-unlogged-message "SHOW ALL"))
6809 (setq org-cycle-global-status 'all)
6810 (run-hook-with-args 'org-cycle-hook 'all))
6813 ;; Default action: go to overview
6814 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6815 (org-overview)
6816 (unless ga (org-unlogged-message "OVERVIEW"))
6817 (setq org-cycle-global-status 'overview)
6818 (run-hook-with-args 'org-cycle-hook 'overview)))))
6820 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6822 (defun org-cycle-internal-local ()
6823 "Do the local cycling action."
6824 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6825 ;; First, determine end of headline (EOH), end of subtree or item
6826 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6827 (save-excursion
6828 (if (org-at-item-p)
6829 (progn
6830 (beginning-of-line)
6831 (setq struct (org-list-struct))
6832 (setq eoh (point-at-eol))
6833 (setq eos (org-list-get-item-end-before-blank (point) struct))
6834 (setq has-children (org-list-has-child-p (point) struct)))
6835 (org-back-to-heading)
6836 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6837 (setq eos (save-excursion (org-end-of-subtree t t)
6838 (when (bolp) (backward-char)) (point)))
6839 (setq has-children
6840 (or (save-excursion
6841 (let ((level (funcall outline-level)))
6842 (outline-next-heading)
6843 (and (org-at-heading-p t)
6844 (> (funcall outline-level) level))))
6845 (save-excursion
6846 (org-list-search-forward (org-item-beginning-re) eos t)))))
6847 ;; Determine end invisible part of buffer (EOL)
6848 (beginning-of-line 2)
6849 ;; XEmacs doesn't have `next-single-char-property-change'
6850 (if (featurep 'xemacs)
6851 (while (and (not (eobp)) ;; this is like `next-line'
6852 (get-char-property (1- (point)) 'invisible))
6853 (beginning-of-line 2))
6854 (while (and (not (eobp)) ;; this is like `next-line'
6855 (get-char-property (1- (point)) 'invisible))
6856 (goto-char (next-single-char-property-change (point) 'invisible))
6857 (and (eolp) (beginning-of-line 2))))
6858 (setq eol (point)))
6859 ;; Find out what to do next and set `this-command'
6860 (cond
6861 ((= eos eoh)
6862 ;; Nothing is hidden behind this heading
6863 (unless (org-before-first-heading-p)
6864 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6865 (org-unlogged-message "EMPTY ENTRY")
6866 (setq org-cycle-subtree-status nil)
6867 (save-excursion
6868 (goto-char eos)
6869 (outline-next-heading)
6870 (if (outline-invisible-p) (org-flag-heading nil))))
6871 ((and (or (>= eol eos)
6872 (not (string-match "\\S-" (buffer-substring eol eos))))
6873 (or has-children
6874 (not (setq children-skipped
6875 org-cycle-skip-children-state-if-no-children))))
6876 ;; Entire subtree is hidden in one line: children view
6877 (unless (org-before-first-heading-p)
6878 (run-hook-with-args 'org-pre-cycle-hook 'children))
6879 (if (org-at-item-p)
6880 (org-list-set-item-visibility (point-at-bol) struct 'children)
6881 (org-show-entry)
6882 (org-with-limited-levels (show-children))
6883 ;; FIXME: This slows down the func way too much.
6884 ;; How keep drawers hidden in subtree anyway?
6885 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6886 ;; (org-cycle-hide-drawers 'subtree))
6888 ;; Fold every list in subtree to top-level items.
6889 (when (eq org-cycle-include-plain-lists 'integrate)
6890 (save-excursion
6891 (org-back-to-heading)
6892 (while (org-list-search-forward (org-item-beginning-re) eos t)
6893 (beginning-of-line 1)
6894 (let* ((struct (org-list-struct))
6895 (prevs (org-list-prevs-alist struct))
6896 (end (org-list-get-bottom-point struct)))
6897 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6898 (org-list-get-all-items (point) struct prevs))
6899 (goto-char (if (< end eos) end eos)))))))
6900 (org-unlogged-message "CHILDREN")
6901 (save-excursion
6902 (goto-char eos)
6903 (outline-next-heading)
6904 (if (outline-invisible-p) (org-flag-heading nil)))
6905 (setq org-cycle-subtree-status 'children)
6906 (unless (org-before-first-heading-p)
6907 (run-hook-with-args 'org-cycle-hook 'children)))
6908 ((or children-skipped
6909 (and (eq last-command this-command)
6910 (eq org-cycle-subtree-status 'children)))
6911 ;; We just showed the children, or no children are there,
6912 ;; now show everything.
6913 (unless (org-before-first-heading-p)
6914 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6915 (outline-flag-region eoh eos nil)
6916 (org-unlogged-message
6917 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6918 (setq org-cycle-subtree-status 'subtree)
6919 (unless (org-before-first-heading-p)
6920 (run-hook-with-args 'org-cycle-hook 'subtree)))
6922 ;; Default action: hide the subtree.
6923 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6924 (outline-flag-region eoh eos t)
6925 (org-unlogged-message "FOLDED")
6926 (setq org-cycle-subtree-status 'folded)
6927 (unless (org-before-first-heading-p)
6928 (run-hook-with-args 'org-cycle-hook 'folded))))))
6930 ;;;###autoload
6931 (defun org-global-cycle (&optional arg)
6932 "Cycle the global visibility. For details see `org-cycle'.
6933 With \\[universal-argument] prefix arg, switch to startup visibility.
6934 With a numeric prefix, show all headlines up to that level."
6935 (interactive "P")
6936 (let ((org-cycle-include-plain-lists
6937 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6938 (cond
6939 ((integerp arg)
6940 (show-all)
6941 (hide-sublevels arg)
6942 (setq org-cycle-global-status 'contents))
6943 ((equal arg '(4))
6944 (org-set-startup-visibility)
6945 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6947 (org-cycle '(4))))))
6949 (defun org-set-startup-visibility ()
6950 "Set the visibility required by startup options and properties."
6951 (cond
6952 ((eq org-startup-folded t)
6953 (org-overview))
6954 ((eq org-startup-folded 'content)
6955 (org-content))
6956 ((or (eq org-startup-folded 'showeverything)
6957 (eq org-startup-folded nil))
6958 (show-all)))
6959 (unless (eq org-startup-folded 'showeverything)
6960 (if org-hide-block-startup (org-hide-block-all))
6961 (org-set-visibility-according-to-property 'no-cleanup)
6962 (org-cycle-hide-archived-subtrees 'all)
6963 (org-cycle-hide-drawers 'all)
6964 (org-cycle-show-empty-lines t)))
6966 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6967 "Switch subtree visibilities according to :VISIBILITY: property."
6968 (interactive)
6969 (let (org-show-entry-below state)
6970 (save-excursion
6971 (goto-char (point-min))
6972 (while (re-search-forward
6973 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6974 nil t)
6975 (setq state (match-string 1))
6976 (save-excursion
6977 (org-back-to-heading t)
6978 (hide-subtree)
6979 (org-reveal)
6980 (cond
6981 ((equal state '("fold" "folded"))
6982 (hide-subtree))
6983 ((equal state "children")
6984 (org-show-hidden-entry)
6985 (show-children))
6986 ((equal state "content")
6987 (save-excursion
6988 (save-restriction
6989 (org-narrow-to-subtree)
6990 (org-content))))
6991 ((member state '("all" "showall"))
6992 (show-subtree)))))
6993 (unless no-cleanup
6994 (org-cycle-hide-archived-subtrees 'all)
6995 (org-cycle-hide-drawers 'all)
6996 (org-cycle-show-empty-lines 'all)))))
6998 ;; This function uses outline-regexp instead of the more fundamental
6999 ;; org-outline-regexp so that org-cycle-global works outside of Org
7000 ;; buffers, where outline-regexp is needed.
7001 (defun org-overview ()
7002 "Switch to overview mode, showing only top-level headlines.
7003 This shows all headlines with a level equal or greater than the level
7004 of the first headline in the buffer. This is important, because if the
7005 first headline is not level one, then (hide-sublevels 1) gives confusing
7006 results."
7007 (interactive)
7008 (save-excursion
7009 (let ((level
7010 (save-excursion
7011 (goto-char (point-min))
7012 (if (re-search-forward (concat "^" outline-regexp) nil t)
7013 (progn
7014 (goto-char (match-beginning 0))
7015 (funcall outline-level))))))
7016 (and level (hide-sublevels level)))))
7018 (defun org-content (&optional arg)
7019 "Show all headlines in the buffer, like a table of contents.
7020 With numerical argument N, show content up to level N."
7021 (interactive "P")
7022 (org-overview)
7023 (save-excursion
7024 ;; Visit all headings and show their offspring
7025 (and (integerp arg) (org-overview))
7026 (goto-char (point-max))
7027 (catch 'exit
7028 (while (and (progn (condition-case nil
7029 (outline-previous-visible-heading 1)
7030 (error (goto-char (point-min))))
7032 (looking-at org-outline-regexp))
7033 (if (integerp arg)
7034 (show-children (1- arg))
7035 (show-branches))
7036 (if (bobp) (throw 'exit nil))))))
7038 (defun org-optimize-window-after-visibility-change (state)
7039 "Adjust the window after a change in outline visibility.
7040 This function is the default value of the hook `org-cycle-hook'."
7041 (when (get-buffer-window (current-buffer))
7042 (cond
7043 ((eq state 'content) nil)
7044 ((eq state 'all) nil)
7045 ((eq state 'folded) nil)
7046 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7047 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7049 (defun org-remove-empty-overlays-at (pos)
7050 "Remove outline overlays that do not contain non-white stuff."
7051 (mapc
7052 (lambda (o)
7053 (and (eq 'outline (overlay-get o 'invisible))
7054 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7055 (overlay-end o))))
7056 (delete-overlay o)))
7057 (overlays-at pos)))
7059 (defun org-clean-visibility-after-subtree-move ()
7060 "Fix visibility issues after moving a subtree."
7061 ;; First, find a reasonable region to look at:
7062 ;; Start two siblings above, end three below
7063 (let* ((beg (save-excursion
7064 (and (org-get-last-sibling)
7065 (org-get-last-sibling))
7066 (point)))
7067 (end (save-excursion
7068 (and (org-get-next-sibling)
7069 (org-get-next-sibling)
7070 (org-get-next-sibling))
7071 (if (org-at-heading-p)
7072 (point-at-eol)
7073 (point))))
7074 (level (looking-at "\\*+"))
7075 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7076 (save-excursion
7077 (save-restriction
7078 (narrow-to-region beg end)
7079 (when re
7080 ;; Properly fold already folded siblings
7081 (goto-char (point-min))
7082 (while (re-search-forward re nil t)
7083 (if (and (not (outline-invisible-p))
7084 (save-excursion
7085 (goto-char (point-at-eol)) (outline-invisible-p)))
7086 (hide-entry))))
7087 (org-cycle-show-empty-lines 'overview)
7088 (org-cycle-hide-drawers 'overview)))))
7090 (defun org-cycle-show-empty-lines (state)
7091 "Show empty lines above all visible headlines.
7092 The region to be covered depends on STATE when called through
7093 `org-cycle-hook'. Lisp program can use t for STATE to get the
7094 entire buffer covered. Note that an empty line is only shown if there
7095 are at least `org-cycle-separator-lines' empty lines before the headline."
7096 (when (not (= org-cycle-separator-lines 0))
7097 (save-excursion
7098 (let* ((n (abs org-cycle-separator-lines))
7099 (re (cond
7100 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7101 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7102 (t (let ((ns (number-to-string (- n 2))))
7103 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7104 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7105 beg end b e)
7106 (cond
7107 ((memq state '(overview contents t))
7108 (setq beg (point-min) end (point-max)))
7109 ((memq state '(children folded))
7110 (setq beg (point) end (progn (org-end-of-subtree t t)
7111 (beginning-of-line 2)
7112 (point)))))
7113 (when beg
7114 (goto-char beg)
7115 (while (re-search-forward re end t)
7116 (unless (get-char-property (match-end 1) 'invisible)
7117 (setq e (match-end 1))
7118 (if (< org-cycle-separator-lines 0)
7119 (setq b (save-excursion
7120 (goto-char (match-beginning 0))
7121 (org-back-over-empty-lines)
7122 (if (save-excursion
7123 (goto-char (max (point-min) (1- (point))))
7124 (org-at-heading-p))
7125 (1- (point))
7126 (point))))
7127 (setq b (match-beginning 1)))
7128 (outline-flag-region b e nil)))))))
7129 ;; Never hide empty lines at the end of the file.
7130 (save-excursion
7131 (goto-char (point-max))
7132 (outline-previous-heading)
7133 (outline-end-of-heading)
7134 (if (and (looking-at "[ \t\n]+")
7135 (= (match-end 0) (point-max)))
7136 (outline-flag-region (point) (match-end 0) nil))))
7138 (defun org-show-empty-lines-in-parent ()
7139 "Move to the parent and re-show empty lines before visible headlines."
7140 (save-excursion
7141 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7142 (org-cycle-show-empty-lines context))))
7144 (defun org-files-list ()
7145 "Return `org-agenda-files' list, plus all open org-mode files.
7146 This is useful for operations that need to scan all of a user's
7147 open and agenda-wise Org files."
7148 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7149 (dolist (buf (buffer-list))
7150 (with-current-buffer buf
7151 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7152 (let ((file (expand-file-name (buffer-file-name))))
7153 (unless (member file files)
7154 (push file files))))))
7155 files))
7157 (defsubst org-entry-beginning-position ()
7158 "Return the beginning position of the current entry."
7159 (save-excursion (outline-back-to-heading t) (point)))
7161 (defsubst org-entry-end-position ()
7162 "Return the end position of the current entry."
7163 (save-excursion (outline-next-heading) (point)))
7165 (defun org-cycle-hide-drawers (state &optional exceptions)
7166 "Re-hide all drawers after a visibility state change.
7167 When non-nil, optional argument EXCEPTIONS is a list of strings
7168 specifying which drawers should not be hidden."
7169 (when (and (derived-mode-p 'org-mode)
7170 (not (memq state '(overview folded contents))))
7171 (save-excursion
7172 (let* ((globalp (memq state '(contents all)))
7173 (beg (if globalp (point-min) (point)))
7174 (end (if globalp (point-max)
7175 (if (eq state 'children)
7176 (save-excursion (outline-next-heading) (point))
7177 (org-end-of-subtree t)))))
7178 (goto-char beg)
7179 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7180 (unless (member-ignore-case (match-string 1) exceptions)
7181 (let ((drawer (org-element-at-point)))
7182 (when (memq (org-element-type drawer) '(drawer property-drawer))
7183 (org-flag-drawer t drawer)
7184 ;; Make sure to skip drawer entirely or we might flag
7185 ;; it another time when matching its ending line with
7186 ;; `org-drawer-regexp'.
7187 (goto-char (org-element-property :end drawer))))))))))
7189 (defun org-cycle-hide-inline-tasks (state)
7190 "Re-hide inline tasks when switching to 'contents or 'children
7191 visibility state."
7192 (case state
7193 (contents
7194 (when (org-bound-and-true-p org-inlinetask-min-level)
7195 (hide-sublevels (1- org-inlinetask-min-level))))
7196 (children
7197 (when (featurep 'org-inlinetask)
7198 (save-excursion
7199 (while (and (outline-next-heading)
7200 (org-inlinetask-at-task-p))
7201 (org-inlinetask-toggle-visibility)
7202 (org-inlinetask-goto-end)))))))
7204 (defun org-flag-drawer (flag &optional element)
7205 "When FLAG is non-nil, hide the drawer we are at.
7206 Otherwise make it visible. When optional argument ELEMENT is
7207 a parsed drawer, as returned by `org-element-at-point', hide or
7208 show that drawer instead."
7209 (when (save-excursion
7210 (beginning-of-line)
7211 (org-looking-at-p org-drawer-regexp))
7212 (let ((drawer (or element (org-element-at-point))))
7213 (when (memq (org-element-type drawer) '(drawer property-drawer))
7214 (let ((post (org-element-property :post-affiliated drawer)))
7215 (save-excursion
7216 (outline-flag-region
7217 (progn (goto-char post) (line-end-position))
7218 (progn (goto-char (org-element-property :end drawer))
7219 (skip-chars-backward " \r\t\n")
7220 (line-end-position))
7221 flag))
7222 ;; When the drawer is hidden away, make sure point lies in
7223 ;; a visible part of the buffer.
7224 (when (and flag (> (line-beginning-position) post))
7225 (goto-char post)))))))
7227 (defun org-subtree-end-visible-p ()
7228 "Is the end of the current subtree visible?"
7229 (pos-visible-in-window-p
7230 (save-excursion (org-end-of-subtree t) (point))))
7232 (defun org-first-headline-recenter ()
7233 "Move cursor to the first headline and recenter the headline."
7234 (goto-char (point-min))
7235 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7236 (set-window-start (selected-window) (point-at-bol))))
7238 ;;; Saving and restoring visibility
7240 (defun org-outline-overlay-data (&optional use-markers)
7241 "Return a list of the locations of all outline overlays.
7242 These are overlays with the `invisible' property value `outline'.
7243 The return value is a list of cons cells, with start and stop
7244 positions for each overlay.
7245 If USE-MARKERS is set, return the positions as markers."
7246 (let (beg end)
7247 (save-excursion
7248 (save-restriction
7249 (widen)
7250 (delq nil
7251 (mapcar (lambda (o)
7252 (when (eq (overlay-get o 'invisible) 'outline)
7253 (setq beg (overlay-start o)
7254 end (overlay-end o))
7255 (and beg end (> end beg)
7256 (if use-markers
7257 (cons (copy-marker beg)
7258 (copy-marker end t))
7259 (cons beg end)))))
7260 (overlays-in (point-min) (point-max))))))))
7262 (defun org-set-outline-overlay-data (data)
7263 "Create visibility overlays for all positions in DATA.
7264 DATA should have been made by `org-outline-overlay-data'."
7265 (let (o)
7266 (save-excursion
7267 (save-restriction
7268 (widen)
7269 (show-all)
7270 (mapc (lambda (c)
7271 (outline-flag-region (car c) (cdr c) t))
7272 data)))))
7274 ;;; Folding of blocks
7276 (defvar org-hide-block-overlays nil
7277 "Overlays hiding blocks.")
7278 (make-variable-buffer-local 'org-hide-block-overlays)
7280 (defun org-block-map (function &optional start end)
7281 "Call FUNCTION at the head of all source blocks in the current buffer.
7282 Optional arguments START and END can be used to limit the range."
7283 (let ((start (or start (point-min)))
7284 (end (or end (point-max))))
7285 (save-excursion
7286 (goto-char start)
7287 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7288 (save-excursion
7289 (save-match-data
7290 (goto-char (match-beginning 0))
7291 (funcall function)))))))
7293 (defun org-hide-block-toggle-all ()
7294 "Toggle the visibility of all blocks in the current buffer."
7295 (org-block-map 'org-hide-block-toggle))
7297 (defun org-hide-block-all ()
7298 "Fold all blocks in the current buffer."
7299 (interactive)
7300 (org-show-block-all)
7301 (org-block-map 'org-hide-block-toggle-maybe))
7303 (defun org-show-block-all ()
7304 "Unfold all blocks in the current buffer."
7305 (interactive)
7306 (mapc 'delete-overlay org-hide-block-overlays)
7307 (setq org-hide-block-overlays nil))
7309 (defun org-hide-block-toggle-maybe ()
7310 "Toggle visibility of block at point."
7311 (interactive)
7312 (let ((case-fold-search t))
7313 (if (save-excursion
7314 (beginning-of-line 1)
7315 (looking-at org-block-regexp))
7316 (progn (org-hide-block-toggle)
7317 t) ;; to signal that we took action
7318 nil))) ;; to signal that we did not
7320 (defun org-hide-block-toggle (&optional force)
7321 "Toggle the visibility of the current block.
7322 When optional argument FORCE is `off', make block visible. If it
7323 is non-nil, hide it unconditionally."
7324 (interactive)
7325 (let ((element (org-element-at-point)))
7326 (unless (memq (org-element-type element)
7327 '(center-block comment-block example-block quote-block
7328 src-block verse-block))
7329 (user-error "Not at a block"))
7330 (let* ((start (save-excursion
7331 (goto-char (org-element-property :post-affiliated element))
7332 (line-end-position)))
7333 (end (save-excursion
7334 (goto-char (org-element-property :end element))
7335 (skip-chars-backward " \r\t\n")
7336 (line-end-position)))
7337 (overlays (overlays-at start)))
7338 (cond
7339 ;; Do nothing when not before or at the block opening line or
7340 ;; at the block closing line.
7341 ((let ((eol (line-end-position)))
7342 (and (> eol start) (/= eol end))))
7343 ((and (not (eq force 'off))
7344 (not (memq t (mapcar
7345 (lambda (o)
7346 (eq (overlay-get o 'invisible) 'org-hide-block))
7347 overlays))))
7348 (let ((ov (make-overlay start end)))
7349 (overlay-put ov 'invisible 'org-hide-block)
7350 ;; Make the block accessible to `isearch'.
7351 (overlay-put
7352 ov 'isearch-open-invisible
7353 (lambda (ov)
7354 (when (memq ov org-hide-block-overlays)
7355 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7356 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7357 (delete-overlay ov))))
7358 (push ov org-hide-block-overlays)
7359 ;; When the block is hidden away, make sure point is left in
7360 ;; a visible part of the buffer.
7361 (when (> (line-beginning-position) start)
7362 (goto-char start)
7363 (beginning-of-line))))
7364 ((or (not force) (eq force 'off))
7365 (dolist (ov overlays)
7366 (when (memq ov org-hide-block-overlays)
7367 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7368 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7369 (delete-overlay ov))))))))
7371 ;; org-tab-after-check-for-cycling-hook
7372 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7373 ;; Remove overlays when changing major mode
7374 (add-hook 'org-mode-hook
7375 (lambda () (org-add-hook 'change-major-mode-hook
7376 'org-show-block-all 'append 'local)))
7378 ;;; Org-goto
7380 (defvar org-goto-window-configuration nil)
7381 (defvar org-goto-marker nil)
7382 (defvar org-goto-map)
7383 (defun org-goto-map ()
7384 "Set the keymap `org-goto'."
7385 (setq org-goto-map
7386 (let ((map (make-sparse-keymap)))
7387 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7388 mouse-drag-region universal-argument org-occur))
7389 cmd)
7390 (while (setq cmd (pop cmds))
7391 (substitute-key-definition cmd cmd map global-map)))
7392 (suppress-keymap map)
7393 (org-defkey map "\C-m" 'org-goto-ret)
7394 (org-defkey map [(return)] 'org-goto-ret)
7395 (org-defkey map [(left)] 'org-goto-left)
7396 (org-defkey map [(right)] 'org-goto-right)
7397 (org-defkey map [(control ?g)] 'org-goto-quit)
7398 (org-defkey map "\C-i" 'org-cycle)
7399 (org-defkey map [(tab)] 'org-cycle)
7400 (org-defkey map [(down)] 'outline-next-visible-heading)
7401 (org-defkey map [(up)] 'outline-previous-visible-heading)
7402 (if org-goto-auto-isearch
7403 (if (fboundp 'define-key-after)
7404 (define-key-after map [t] 'org-goto-local-auto-isearch)
7405 nil)
7406 (org-defkey map "q" 'org-goto-quit)
7407 (org-defkey map "n" 'outline-next-visible-heading)
7408 (org-defkey map "p" 'outline-previous-visible-heading)
7409 (org-defkey map "f" 'outline-forward-same-level)
7410 (org-defkey map "b" 'outline-backward-same-level)
7411 (org-defkey map "u" 'outline-up-heading))
7412 (org-defkey map "/" 'org-occur)
7413 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7414 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7415 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7416 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7417 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7418 map)))
7420 (defconst org-goto-help
7421 "Browse buffer copy, to find location or copy text.%s
7422 RET=jump to location C-g=quit and return to previous location
7423 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7425 (defvar org-goto-start-pos) ; dynamically scoped parameter
7427 (defun org-goto (&optional alternative-interface)
7428 "Look up a different location in the current file, keeping current visibility.
7430 When you want look-up or go to a different location in a
7431 document, the fastest way is often to fold the entire buffer and
7432 then dive into the tree. This method has the disadvantage, that
7433 the previous location will be folded, which may not be what you
7434 want.
7436 This command works around this by showing a copy of the current
7437 buffer in an indirect buffer, in overview mode. You can dive
7438 into the tree in that copy, use org-occur and incremental search
7439 to find a location. When pressing RET or `Q', the command
7440 returns to the original buffer in which the visibility is still
7441 unchanged. After RET it will also jump to the location selected
7442 in the indirect buffer and expose the headline hierarchy above.
7444 With a prefix argument, use the alternative interface: e.g. if
7445 `org-goto-interface' is 'outline use 'outline-path-completion."
7446 (interactive "P")
7447 (org-goto-map)
7448 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7449 (org-refile-use-outline-path t)
7450 (org-refile-target-verify-function nil)
7451 (interface
7452 (if (not alternative-interface)
7453 org-goto-interface
7454 (if (eq org-goto-interface 'outline)
7455 'outline-path-completion
7456 'outline)))
7457 (org-goto-start-pos (point))
7458 (selected-point
7459 (if (eq interface 'outline)
7460 (car (org-get-location (current-buffer) org-goto-help))
7461 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7462 (org-refile-check-position pa)
7463 (nth 3 pa)))))
7464 (if selected-point
7465 (progn
7466 (org-mark-ring-push org-goto-start-pos)
7467 (goto-char selected-point)
7468 (if (or (outline-invisible-p) (org-invisible-p2))
7469 (org-show-context 'org-goto)))
7470 (message "Quit"))))
7472 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7473 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7474 (defvar org-goto-local-auto-isearch-map) ; defined below
7476 (defun org-get-location (buf help)
7477 "Let the user select a location in the Org-mode buffer BUF.
7478 This function uses a recursive edit. It returns the selected position
7479 or nil."
7480 (org-no-popups
7481 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7482 (isearch-hide-immediately nil)
7483 (isearch-search-fun-function
7484 (lambda () 'org-goto-local-search-headings))
7485 (org-goto-selected-point org-goto-exit-command))
7486 (save-excursion
7487 (save-window-excursion
7488 (delete-other-windows)
7489 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7490 (org-pop-to-buffer-same-window
7491 (condition-case nil
7492 (make-indirect-buffer (current-buffer) "*org-goto*")
7493 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7494 (with-output-to-temp-buffer "*Org Help*"
7495 (princ (format help (if org-goto-auto-isearch
7496 " Just type for auto-isearch."
7497 " n/p/f/b/u to navigate, q to quit."))))
7498 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7499 (setq buffer-read-only nil)
7500 (let ((org-startup-truncated t)
7501 (org-startup-folded nil)
7502 (org-startup-align-all-tables nil))
7503 (org-mode)
7504 (org-overview))
7505 (setq buffer-read-only t)
7506 (if (and (boundp 'org-goto-start-pos)
7507 (integer-or-marker-p org-goto-start-pos))
7508 (let ((org-show-hierarchy-above t)
7509 (org-show-siblings t)
7510 (org-show-following-heading t))
7511 (goto-char org-goto-start-pos)
7512 (and (outline-invisible-p) (org-show-context)))
7513 (goto-char (point-min)))
7514 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7515 (message "Select location and press RET")
7516 (use-local-map org-goto-map)
7517 (recursive-edit)))
7518 (kill-buffer "*org-goto*")
7519 (cons org-goto-selected-point org-goto-exit-command))))
7521 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7522 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7523 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7524 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7526 (defun org-goto-local-search-headings (string bound noerror)
7527 "Search and make sure that any matches are in headlines."
7528 (catch 'return
7529 (while (if isearch-forward
7530 (search-forward string bound noerror)
7531 (search-backward string bound noerror))
7532 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7533 (and (member :headline context)
7534 (not (member :tags context))))
7535 (throw 'return (point))))))
7537 (defun org-goto-local-auto-isearch ()
7538 "Start isearch."
7539 (interactive)
7540 (goto-char (point-min))
7541 (let ((keys (this-command-keys)))
7542 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7543 (isearch-mode t)
7544 (isearch-process-search-char (string-to-char keys)))))
7546 (defun org-goto-ret (&optional arg)
7547 "Finish `org-goto' by going to the new location."
7548 (interactive "P")
7549 (setq org-goto-selected-point (point)
7550 org-goto-exit-command 'return)
7551 (throw 'exit nil))
7553 (defun org-goto-left ()
7554 "Finish `org-goto' by going to the new location."
7555 (interactive)
7556 (if (org-at-heading-p)
7557 (progn
7558 (beginning-of-line 1)
7559 (setq org-goto-selected-point (point)
7560 org-goto-exit-command 'left)
7561 (throw 'exit nil))
7562 (user-error "Not on a heading")))
7564 (defun org-goto-right ()
7565 "Finish `org-goto' by going to the new location."
7566 (interactive)
7567 (if (org-at-heading-p)
7568 (progn
7569 (setq org-goto-selected-point (point)
7570 org-goto-exit-command 'right)
7571 (throw 'exit nil))
7572 (user-error "Not on a heading")))
7574 (defun org-goto-quit ()
7575 "Finish `org-goto' without cursor motion."
7576 (interactive)
7577 (setq org-goto-selected-point nil)
7578 (setq org-goto-exit-command 'quit)
7579 (throw 'exit nil))
7581 ;;; Indirect buffer display of subtrees
7583 (defvar org-indirect-dedicated-frame nil
7584 "This is the frame being used for indirect tree display.")
7585 (defvar org-last-indirect-buffer nil)
7587 (defun org-tree-to-indirect-buffer (&optional arg)
7588 "Create indirect buffer and narrow it to current subtree.
7589 With a numerical prefix ARG, go up to this level and then take that tree.
7590 If ARG is negative, go up that many levels.
7592 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7593 indirect buffer previously made with this command, to avoid proliferation of
7594 indirect buffers. However, when you call the command with a \
7595 \\[universal-argument] prefix, or
7596 when `org-indirect-buffer-display' is `new-frame', the last buffer
7597 is kept so that you can work with several indirect buffers at the same time.
7598 If `org-indirect-buffer-display' is `dedicated-frame', the \
7599 \\[universal-argument] prefix also
7600 requests that a new frame be made for the new buffer, so that the dedicated
7601 frame is not changed."
7602 (interactive "P")
7603 (let ((cbuf (current-buffer))
7604 (cwin (selected-window))
7605 (pos (point))
7606 beg end level heading ibuf)
7607 (save-excursion
7608 (org-back-to-heading t)
7609 (when (numberp arg)
7610 (setq level (org-outline-level))
7611 (if (< arg 0) (setq arg (+ level arg)))
7612 (while (> (setq level (org-outline-level)) arg)
7613 (org-up-heading-safe)))
7614 (setq beg (point)
7615 heading (org-get-heading))
7616 (org-end-of-subtree t t)
7617 (if (org-at-heading-p) (backward-char 1))
7618 (setq end (point)))
7619 (if (and (buffer-live-p org-last-indirect-buffer)
7620 (not (eq org-indirect-buffer-display 'new-frame))
7621 (not arg))
7622 (kill-buffer org-last-indirect-buffer))
7623 (setq ibuf (org-get-indirect-buffer cbuf heading)
7624 org-last-indirect-buffer ibuf)
7625 (cond
7626 ((or (eq org-indirect-buffer-display 'new-frame)
7627 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7628 (select-frame (make-frame))
7629 (delete-other-windows)
7630 (org-pop-to-buffer-same-window ibuf)
7631 (org-set-frame-title heading))
7632 ((eq org-indirect-buffer-display 'dedicated-frame)
7633 (raise-frame
7634 (select-frame (or (and org-indirect-dedicated-frame
7635 (frame-live-p org-indirect-dedicated-frame)
7636 org-indirect-dedicated-frame)
7637 (setq org-indirect-dedicated-frame (make-frame)))))
7638 (delete-other-windows)
7639 (org-pop-to-buffer-same-window ibuf)
7640 (org-set-frame-title (concat "Indirect: " heading)))
7641 ((eq org-indirect-buffer-display 'current-window)
7642 (org-pop-to-buffer-same-window ibuf))
7643 ((eq org-indirect-buffer-display 'other-window)
7644 (pop-to-buffer ibuf))
7645 (t (error "Invalid value")))
7646 (if (featurep 'xemacs)
7647 (save-excursion (org-mode) (turn-on-font-lock)))
7648 (narrow-to-region beg end)
7649 (show-all)
7650 (goto-char pos)
7651 (run-hook-with-args 'org-cycle-hook 'all)
7652 (and (window-live-p cwin) (select-window cwin))))
7654 (defun org-get-indirect-buffer (&optional buffer heading)
7655 (setq buffer (or buffer (current-buffer)))
7656 (let ((n 1) (base (buffer-name buffer)) bname)
7657 (while (buffer-live-p
7658 (get-buffer
7659 (setq bname
7660 (concat base "-"
7661 (if heading (concat heading "-" (number-to-string n))
7662 (number-to-string n))))))
7663 (setq n (1+ n)))
7664 (condition-case nil
7665 (make-indirect-buffer buffer bname 'clone)
7666 (error (make-indirect-buffer buffer bname)))))
7668 (defun org-set-frame-title (title)
7669 "Set the title of the current frame to the string TITLE."
7670 ;; FIXME: how to name a single frame in XEmacs???
7671 (unless (featurep 'xemacs)
7672 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7674 ;;;; Structure editing
7676 ;;; Inserting headlines
7678 (defun org-previous-line-empty-p (&optional next)
7679 "Is the previous line a blank line?
7680 When NEXT is non-nil, check the next line instead."
7681 (save-excursion
7682 (and (not (bobp))
7683 (or (beginning-of-line (if next 2 0)) t)
7684 (save-match-data
7685 (looking-at "[ \t]*$")))))
7687 (defun org-insert-heading (&optional arg invisible-ok)
7688 "Insert a new heading or an item with the same depth at point.
7690 If point is at the beginning of a heading or a list item, insert
7691 a new heading or a new item above the current one. If point is
7692 at the beginning of a normal line, turn the line into a heading.
7694 If point is in the middle of a headline or a list item, split the
7695 headline or the item and create a new headline/item with the text
7696 in the current line after point \(see `org-M-RET-may-split-line'
7697 on how to modify this behavior).
7699 With one universal prefirx argument, set the user option
7700 `org-insert-heading-respect-content' to t for the duration of
7701 the command. This modifies the behavior described above in this
7702 ways: on list items and at the beginning of normal lines, force
7703 the insertion of a heading after the current subtree.
7705 With two universal prefix arguments, insert the heading at the
7706 end of the grandparent subtree. For example, if point is within
7707 a 2nd-level heading, then it will insert a 2nd-level heading at
7708 the end of the 1st-level parent heading.
7710 If point is at the beginning of a headline, insert a sibling
7711 before the current headline. If point is not at the beginning,
7712 split the line and create a new headline with the text in the
7713 current line after point \(see `org-M-RET-may-split-line' on how
7714 to modify this behavior).
7716 If point is at the beginning of a normal line, turn this line
7717 into a heading.
7719 When INVISIBLE-OK is set, stop at invisible headlines when going
7720 back. This is important for non-interactive uses of the
7721 command."
7722 (interactive "P")
7723 (if (org-called-interactively-p 'any) (org-reveal))
7724 (let ((itemp (org-in-item-p))
7725 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7726 (respect-content (or org-insert-heading-respect-content
7727 (equal arg '(4))))
7728 (initial-content "")
7729 (adjust-empty-lines t))
7731 (cond
7733 ((or (= (buffer-size) 0)
7734 (and (not (save-excursion
7735 (and (ignore-errors (org-back-to-heading invisible-ok))
7736 (org-at-heading-p))))
7737 (or arg (not itemp))))
7738 ;; At beginning of buffer or so high up that only a heading
7739 ;; makes sense.
7740 (cond ((and (bolp) (not respect-content)) (insert "* "))
7741 ((not respect-content)
7742 (unless may-split (end-of-line))
7743 (insert "\n* "))
7744 ((re-search-forward org-outline-regexp-bol nil t)
7745 (beginning-of-line)
7746 (insert "* \n")
7747 (backward-char))
7748 (t (goto-char (point-max))
7749 (insert "\n* ")))
7750 (run-hooks 'org-insert-heading-hook))
7752 ((and itemp (not (member arg '((4) (16)))))
7753 ;; Insert an item
7754 (org-insert-item))
7757 ;; Maybe move at the end of the subtree
7758 (when (equal arg '(16))
7759 (org-up-heading-safe)
7760 (org-end-of-subtree t))
7761 ;; Insert a heading
7762 (save-restriction
7763 (widen)
7764 (let* ((level nil)
7765 (on-heading (org-at-heading-p))
7766 (empty-line-p (if on-heading
7767 (org-previous-line-empty-p)
7768 ;; We will decide later
7769 nil))
7770 ;; Get a level string to fall back on
7771 (fix-level
7772 (if (org-before-first-heading-p) "*"
7773 (save-excursion
7774 (org-back-to-heading t)
7775 (if (org-previous-line-empty-p) (setq empty-line-p t))
7776 (looking-at org-outline-regexp)
7777 (make-string (1- (length (match-string 0))) ?*))))
7778 (stars
7779 (save-excursion
7780 (condition-case nil
7781 (progn
7782 (org-back-to-heading invisible-ok)
7783 (when (and (not on-heading)
7784 (featurep 'org-inlinetask)
7785 (integerp org-inlinetask-min-level)
7786 (>= (length (match-string 0))
7787 org-inlinetask-min-level))
7788 ;; Find a heading level before the inline task
7789 (while (and (setq level (org-up-heading-safe))
7790 (>= level org-inlinetask-min-level)))
7791 (if (org-at-heading-p)
7792 (org-back-to-heading invisible-ok)
7793 (error "This should not happen")))
7794 (unless (and (save-excursion
7795 (save-match-data
7796 (org-backward-heading-same-level
7797 1 invisible-ok))
7798 (= (point) (match-beginning 0)))
7799 (not (org-previous-line-empty-p t)))
7800 (setq empty-line-p (or empty-line-p
7801 (org-previous-line-empty-p))))
7802 (match-string 0))
7803 (error (or fix-level "* ")))))
7804 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7805 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7806 pos hide-previous previous-pos)
7808 ;; If we insert after content, move there and clean up whitespace
7809 (when (and respect-content
7810 (not (org-looking-at-p org-outline-regexp-bol)))
7811 (if (not (org-before-first-heading-p))
7812 (org-end-of-subtree nil t)
7813 (re-search-forward org-outline-regexp-bol)
7814 (beginning-of-line 0))
7815 (skip-chars-backward " \r\n")
7816 (and (not (looking-back "^\\*+"))
7817 (looking-at "[ \t]+") (replace-match ""))
7818 (unless (eobp) (forward-char 1))
7819 (when (looking-at "^\\*")
7820 (unless (bobp) (backward-char 1))
7821 (insert "\n")))
7823 ;; If we are splitting, grab the text that should be moved to the new headline
7824 (when may-split
7825 (if (org-on-heading-p)
7826 ;; This is a heading, we split intelligently (keeping tags)
7827 (let ((pos (point)))
7828 (goto-char (point-at-bol))
7829 (unless (looking-at org-complex-heading-regexp)
7830 (error "This should not happen"))
7831 (when (and (match-beginning 4)
7832 (> pos (match-beginning 4))
7833 (< pos (match-end 4)))
7834 (setq initial-content (buffer-substring pos (match-end 4)))
7835 (goto-char pos)
7836 (delete-region (point) (match-end 4))
7837 (if (looking-at "[ \t]*$")
7838 (replace-match "")
7839 (insert (make-string (length initial-content) ?\ )))
7840 (setq initial-content (org-trim initial-content)))
7841 (goto-char pos))
7842 ;; a normal line
7843 (setq initial-content
7844 (org-trim (buffer-substring (point) (point-at-eol))))
7845 (delete-region (point) (point-at-eol))))
7847 ;; If we are at the beginning of the line, insert before it. Else after
7848 (cond
7849 ((and (bolp) (looking-at "[ \t]*$")))
7850 ((and (bolp) (not (looking-at "[ \t]*$")))
7851 (open-line 1))
7853 (goto-char (point-at-eol))
7854 (insert "\n")))
7856 ;; Insert the new heading
7857 (insert stars)
7858 (just-one-space)
7859 (insert initial-content)
7860 (when adjust-empty-lines
7861 (if (or (not blank)
7862 (and blank (not (org-previous-line-empty-p))))
7863 (org-N-empty-lines-before-current (if blank 1 0))))
7864 (run-hooks 'org-insert-heading-hook)))))))
7866 (defun org-N-empty-lines-before-current (N)
7867 "Make the number of empty lines before current exactly N.
7868 So this will delete or add empty lines."
7869 (save-excursion
7870 (goto-char (point-at-bol))
7871 (if (looking-back "\\s-+" nil 'greedy)
7872 (replace-match ""))
7873 (or (bobp) (insert "\n"))
7874 (while (> N 0)
7875 (insert "\n")
7876 (setq N (1- N)))))
7878 (defun org-get-heading (&optional no-tags no-todo)
7879 "Return the heading of the current entry, without the stars.
7880 When NO-TAGS is non-nil, don't include tags.
7881 When NO-TODO is non-nil, don't include TODO keywords."
7882 (save-excursion
7883 (org-back-to-heading t)
7884 (cond
7885 ((and no-tags no-todo)
7886 (looking-at org-complex-heading-regexp)
7887 (match-string 4))
7888 (no-tags
7889 (looking-at (concat org-outline-regexp
7890 "\\(.*?\\)"
7891 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7892 (match-string 1))
7893 (no-todo
7894 (looking-at org-todo-line-regexp)
7895 (match-string 3))
7896 (t (looking-at org-heading-regexp)
7897 (match-string 2)))))
7899 (defvar orgstruct-mode) ; defined below
7901 (defun org-heading-components ()
7902 "Return the components of the current heading.
7903 This is a list with the following elements:
7904 - the level as an integer
7905 - the reduced level, different if `org-odd-levels-only' is set.
7906 - the TODO keyword, or nil
7907 - the priority character, like ?A, or nil if no priority is given
7908 - the headline text itself, or the tags string if no headline text
7909 - the tags string, or nil."
7910 (save-excursion
7911 (org-back-to-heading t)
7912 (if (let (case-fold-search)
7913 (looking-at
7914 (if orgstruct-mode
7915 org-heading-regexp
7916 org-complex-heading-regexp)))
7917 (if orgstruct-mode
7918 (list (length (match-string 1))
7919 (org-reduced-level (length (match-string 1)))
7922 (match-string 2)
7923 nil)
7924 (list (length (match-string 1))
7925 (org-reduced-level (length (match-string 1)))
7926 (org-match-string-no-properties 2)
7927 (and (match-end 3) (aref (match-string 3) 2))
7928 (org-match-string-no-properties 4)
7929 (org-match-string-no-properties 5))))))
7931 (defun org-get-entry ()
7932 "Get the entry text, after heading, entire subtree."
7933 (save-excursion
7934 (org-back-to-heading t)
7935 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7937 (defun org-insert-heading-after-current ()
7938 "Insert a new heading with same level as current, after current subtree."
7939 (interactive)
7940 (org-back-to-heading)
7941 (org-insert-heading)
7942 (org-move-subtree-down)
7943 (end-of-line 1))
7945 (defun org-insert-heading-respect-content (&optional invisible-ok)
7946 "Insert heading with `org-insert-heading-respect-content' set to t."
7947 (interactive)
7948 (org-insert-heading '(4) invisible-ok))
7950 (defun org-insert-todo-heading-respect-content (&optional force-state)
7951 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7952 (interactive)
7953 (org-insert-todo-heading force-state '(4)))
7955 (defun org-insert-todo-heading (arg &optional force-heading)
7956 "Insert a new heading with the same level and TODO state as current heading.
7957 If the heading has no TODO state, or if the state is DONE, use the first
7958 state (TODO by default). Also with one prefix arg, force first state. With
7959 two prefix args, force inserting at the end of the parent subtree."
7960 (interactive "P")
7961 (when (or force-heading (not (org-insert-item 'checkbox)))
7962 (org-insert-heading (or (and (equal arg '(16)) '(16))
7963 force-heading))
7964 (save-excursion
7965 (org-back-to-heading)
7966 (outline-previous-heading)
7967 (looking-at org-todo-line-regexp))
7968 (let*
7969 ((new-mark-x
7970 (if (or (equal arg '(4))
7971 (not (match-beginning 2))
7972 (member (match-string 2) org-done-keywords))
7973 (car org-todo-keywords-1)
7974 (match-string 2)))
7975 (new-mark
7977 (run-hook-with-args-until-success
7978 'org-todo-get-default-hook new-mark-x nil)
7979 new-mark-x)))
7980 (beginning-of-line 1)
7981 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7982 (if org-treat-insert-todo-heading-as-state-change
7983 (org-todo new-mark)
7984 (insert new-mark " "))))
7985 (when org-provide-todo-statistics
7986 (org-update-parent-todo-statistics))))
7988 (defun org-insert-subheading (arg)
7989 "Insert a new subheading and demote it.
7990 Works for outline headings and for plain lists alike."
7991 (interactive "P")
7992 (org-insert-heading arg)
7993 (cond
7994 ((org-at-heading-p) (org-do-demote))
7995 ((org-at-item-p) (org-indent-item))))
7997 (defun org-insert-todo-subheading (arg)
7998 "Insert a new subheading with TODO keyword or checkbox and demote it.
7999 Works for outline headings and for plain lists alike."
8000 (interactive "P")
8001 (org-insert-todo-heading arg)
8002 (cond
8003 ((org-at-heading-p) (org-do-demote))
8004 ((org-at-item-p) (org-indent-item))))
8006 ;;; Promotion and Demotion
8008 (defvar org-after-demote-entry-hook nil
8009 "Hook run after an entry has been demoted.
8010 The cursor will be at the beginning of the entry.
8011 When a subtree is being demoted, the hook will be called for each node.")
8013 (defvar org-after-promote-entry-hook nil
8014 "Hook run after an entry has been promoted.
8015 The cursor will be at the beginning of the entry.
8016 When a subtree is being promoted, the hook will be called for each node.")
8018 (defun org-promote-subtree ()
8019 "Promote the entire subtree.
8020 See also `org-promote'."
8021 (interactive)
8022 (save-excursion
8023 (org-with-limited-levels (org-map-tree 'org-promote)))
8024 (org-fix-position-after-promote))
8026 (defun org-demote-subtree ()
8027 "Demote the entire subtree. See `org-demote'.
8028 See also `org-promote'."
8029 (interactive)
8030 (save-excursion
8031 (org-with-limited-levels (org-map-tree 'org-demote)))
8032 (org-fix-position-after-promote))
8035 (defun org-do-promote ()
8036 "Promote the current heading higher up the tree.
8037 If the region is active in `transient-mark-mode', promote all headings
8038 in the region."
8039 (interactive)
8040 (save-excursion
8041 (if (org-region-active-p)
8042 (org-map-region 'org-promote (region-beginning) (region-end))
8043 (org-promote)))
8044 (org-fix-position-after-promote))
8046 (defun org-do-demote ()
8047 "Demote the current heading lower down the tree.
8048 If the region is active in `transient-mark-mode', demote all headings
8049 in the region."
8050 (interactive)
8051 (save-excursion
8052 (if (org-region-active-p)
8053 (org-map-region 'org-demote (region-beginning) (region-end))
8054 (org-demote)))
8055 (org-fix-position-after-promote))
8057 (defun org-fix-position-after-promote ()
8058 "Make sure that after pro/demotion cursor position is right."
8059 (let ((pos (point)))
8060 (when (save-excursion
8061 (beginning-of-line 1)
8062 (looking-at org-todo-line-regexp)
8063 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8064 (cond ((eobp) (insert " "))
8065 ((eolp) (insert " "))
8066 ((equal (char-after) ?\ ) (forward-char 1))))))
8068 (defun org-current-level ()
8069 "Return the level of the current entry, or nil if before the first headline.
8070 The level is the number of stars at the beginning of the headline."
8071 (save-excursion
8072 (org-with-limited-levels
8073 (if (ignore-errors (org-back-to-heading t))
8074 (funcall outline-level)))))
8076 (defun org-get-previous-line-level ()
8077 "Return the outline depth of the last headline before the current line.
8078 Returns 0 for the first headline in the buffer, and nil if before the
8079 first headline."
8080 (and (org-current-level)
8081 (or (and (/= (line-beginning-position) (point-min))
8082 (save-excursion (beginning-of-line 0) (org-current-level)))
8083 0)))
8085 (defun org-reduced-level (l)
8086 "Compute the effective level of a heading.
8087 This takes into account the setting of `org-odd-levels-only'."
8088 (cond
8089 ((zerop l) 0)
8090 (org-odd-levels-only (1+ (floor (/ l 2))))
8091 (t l)))
8093 (defun org-level-increment ()
8094 "Return the number of stars that will be added or removed at a
8095 time to headlines when structure editing, based on the value of
8096 `org-odd-levels-only'."
8097 (if org-odd-levels-only 2 1))
8099 (defun org-get-valid-level (level &optional change)
8100 "Rectify a level change under the influence of `org-odd-levels-only'
8101 LEVEL is a current level, CHANGE is by how much the level should be
8102 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8103 even level numbers will become the next higher odd number."
8104 (if org-odd-levels-only
8105 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8106 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8107 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8108 (max 1 (+ level (or change 0)))))
8110 (if (boundp 'define-obsolete-function-alias)
8111 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8112 (define-obsolete-function-alias 'org-get-legal-level
8113 'org-get-valid-level)
8114 (define-obsolete-function-alias 'org-get-legal-level
8115 'org-get-valid-level "23.1")))
8117 (defun org-promote ()
8118 "Promote the current heading higher up the tree.
8119 If the region is active in `transient-mark-mode', promote all headings
8120 in the region."
8121 (org-back-to-heading t)
8122 (let* ((level (save-match-data (funcall outline-level)))
8123 (after-change-functions (remove 'flyspell-after-change-function
8124 after-change-functions))
8125 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8126 (diff (abs (- level (length up-head) -1))))
8127 (cond ((and (= level 1) org-called-with-limited-levels
8128 org-allow-promoting-top-level-subtree)
8129 (replace-match "# " nil t))
8130 ((= level 1)
8131 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8132 (t (replace-match up-head nil t)))
8133 ;; Fixup tag positioning
8134 (unless (= level 1)
8135 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8136 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8137 (run-hooks 'org-after-promote-entry-hook)))
8139 (defun org-demote ()
8140 "Demote the current heading lower down the tree.
8141 If the region is active in `transient-mark-mode', demote all headings
8142 in the region."
8143 (org-back-to-heading t)
8144 (let* ((level (save-match-data (funcall outline-level)))
8145 (after-change-functions (remove 'flyspell-after-change-function
8146 after-change-functions))
8147 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8148 (diff (abs (- level (length down-head) -1))))
8149 (replace-match down-head nil t)
8150 ;; Fixup tag positioning
8151 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8152 (if org-adapt-indentation (org-fixup-indentation diff))
8153 (run-hooks 'org-after-demote-entry-hook)))
8155 (defun org-cycle-level ()
8156 "Cycle the level of an empty headline through possible states.
8157 This goes first to child, then to parent, level, then up the hierarchy.
8158 After top level, it switches back to sibling level."
8159 (interactive)
8160 (let ((org-adapt-indentation nil))
8161 (when (org-point-at-end-of-empty-headline)
8162 (setq this-command 'org-cycle-level) ; Only needed for caching
8163 (let ((cur-level (org-current-level))
8164 (prev-level (org-get-previous-line-level)))
8165 (cond
8166 ;; If first headline in file, promote to top-level.
8167 ((= prev-level 0)
8168 (loop repeat (/ (- cur-level 1) (org-level-increment))
8169 do (org-do-promote)))
8170 ;; If same level as prev, demote one.
8171 ((= prev-level cur-level)
8172 (org-do-demote))
8173 ;; If parent is top-level, promote to top level if not already.
8174 ((= prev-level 1)
8175 (loop repeat (/ (- cur-level 1) (org-level-increment))
8176 do (org-do-promote)))
8177 ;; If top-level, return to prev-level.
8178 ((= cur-level 1)
8179 (loop repeat (/ (- prev-level 1) (org-level-increment))
8180 do (org-do-demote)))
8181 ;; If less than prev-level, promote one.
8182 ((< cur-level prev-level)
8183 (org-do-promote))
8184 ;; If deeper than prev-level, promote until higher than
8185 ;; prev-level.
8186 ((> cur-level prev-level)
8187 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8188 do (org-do-promote))))
8189 t))))
8191 (defun org-map-tree (fun)
8192 "Call FUN for every heading underneath the current one."
8193 (org-back-to-heading)
8194 (let ((level (funcall outline-level)))
8195 (save-excursion
8196 (funcall fun)
8197 (while (and (progn
8198 (outline-next-heading)
8199 (> (funcall outline-level) level))
8200 (not (eobp)))
8201 (funcall fun)))))
8203 (defun org-map-region (fun beg end)
8204 "Call FUN for every heading between BEG and END."
8205 (let ((org-ignore-region t))
8206 (save-excursion
8207 (setq end (copy-marker end))
8208 (goto-char beg)
8209 (if (and (re-search-forward org-outline-regexp-bol nil t)
8210 (< (point) end))
8211 (funcall fun))
8212 (while (and (progn
8213 (outline-next-heading)
8214 (< (point) end))
8215 (not (eobp)))
8216 (funcall fun)))))
8218 (defvar org-property-end-re) ; silence byte-compiler
8219 (defun org-fixup-indentation (diff)
8220 "Change the indentation in the current entry by DIFF.
8221 However, if any line in the current entry has no indentation, or if it
8222 would end up with no indentation after the change, nothing at all is done."
8223 (save-excursion
8224 (let ((end (save-excursion (outline-next-heading)
8225 (point-marker)))
8226 (prohibit (if (> diff 0)
8227 "^\\S-"
8228 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8229 col)
8230 (unless (save-excursion (end-of-line 1)
8231 (re-search-forward prohibit end t))
8232 (while (and (< (point) end)
8233 (re-search-forward "^[ \t]+" end t))
8234 (goto-char (match-end 0))
8235 (setq col (current-column))
8236 (if (< diff 0) (replace-match ""))
8237 (org-indent-to-column (+ diff col))))
8238 (move-marker end nil))))
8240 (defun org-convert-to-odd-levels ()
8241 "Convert an org-mode file with all levels allowed to one with odd levels.
8242 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8243 level 5 etc."
8244 (interactive)
8245 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8246 (let ((outline-level 'org-outline-level)
8247 (org-odd-levels-only nil) n)
8248 (save-excursion
8249 (goto-char (point-min))
8250 (while (re-search-forward "^\\*\\*+ " nil t)
8251 (setq n (- (length (match-string 0)) 2))
8252 (while (>= (setq n (1- n)) 0)
8253 (org-demote))
8254 (end-of-line 1))))))
8256 (defun org-convert-to-oddeven-levels ()
8257 "Convert an org-mode file with only odd levels to one with odd/even levels.
8258 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8259 file contains a section with an even level, conversion would
8260 destroy the structure of the file. An error is signaled in this
8261 case."
8262 (interactive)
8263 (goto-char (point-min))
8264 ;; First check if there are no even levels
8265 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8266 (org-show-context t)
8267 (error "Not all levels are odd in this file. Conversion not possible"))
8268 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8269 (let ((outline-regexp org-outline-regexp)
8270 (outline-level 'org-outline-level)
8271 (org-odd-levels-only nil) n)
8272 (save-excursion
8273 (goto-char (point-min))
8274 (while (re-search-forward "^\\*\\*+ " nil t)
8275 (setq n (/ (1- (length (match-string 0))) 2))
8276 (while (>= (setq n (1- n)) 0)
8277 (org-promote))
8278 (end-of-line 1))))))
8280 (defun org-tr-level (n)
8281 "Make N odd if required."
8282 (if org-odd-levels-only (1+ (/ n 2)) n))
8284 ;;; Vertical tree motion, cutting and pasting of subtrees
8286 (defun org-move-subtree-up (&optional arg)
8287 "Move the current subtree up past ARG headlines of the same level."
8288 (interactive "p")
8289 (org-move-subtree-down (- (prefix-numeric-value arg))))
8291 (defun org-move-subtree-down (&optional arg)
8292 "Move the current subtree down past ARG headlines of the same level."
8293 (interactive "p")
8294 (setq arg (prefix-numeric-value arg))
8295 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8296 'org-get-last-sibling))
8297 (ins-point (make-marker))
8298 (cnt (abs arg))
8299 (col (current-column))
8300 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8301 ;; Select the tree
8302 (org-back-to-heading)
8303 (setq beg0 (point))
8304 (save-excursion
8305 (setq ne-beg (org-back-over-empty-lines))
8306 (setq beg (point)))
8307 (save-match-data
8308 (save-excursion (outline-end-of-heading)
8309 (setq folded (outline-invisible-p)))
8310 (progn (org-end-of-subtree nil t)
8311 (unless (eobp) (backward-char))))
8312 (outline-next-heading)
8313 (setq ne-end (org-back-over-empty-lines))
8314 (setq end (point))
8315 (goto-char beg0)
8316 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8317 ;; include less whitespace
8318 (save-excursion
8319 (goto-char beg)
8320 (forward-line (- ne-beg ne-end))
8321 (setq beg (point))))
8322 ;; Find insertion point, with error handling
8323 (while (> cnt 0)
8324 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8325 (progn (goto-char beg0)
8326 (user-error "Cannot move past superior level or buffer limit")))
8327 (setq cnt (1- cnt)))
8328 (if (> arg 0)
8329 ;; Moving forward - still need to move over subtree
8330 (progn (org-end-of-subtree t t)
8331 (save-excursion
8332 (org-back-over-empty-lines)
8333 (or (bolp) (newline)))))
8334 (setq ne-ins (org-back-over-empty-lines))
8335 (move-marker ins-point (point))
8336 (setq txt (buffer-substring beg end))
8337 (org-save-markers-in-region beg end)
8338 (delete-region beg end)
8339 (org-remove-empty-overlays-at beg)
8340 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8341 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8342 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8343 (let ((bbb (point)))
8344 (insert-before-markers txt)
8345 (org-reinstall-markers-in-region bbb)
8346 (move-marker ins-point bbb))
8347 (or (bolp) (insert "\n"))
8348 (setq ins-end (point))
8349 (goto-char ins-point)
8350 (org-skip-whitespace)
8351 (when (and (< arg 0)
8352 (org-first-sibling-p)
8353 (> ne-ins ne-beg))
8354 ;; Move whitespace back to beginning
8355 (save-excursion
8356 (goto-char ins-end)
8357 (let ((kill-whole-line t))
8358 (kill-line (- ne-ins ne-beg)) (point)))
8359 (insert (make-string (- ne-ins ne-beg) ?\n)))
8360 (move-marker ins-point nil)
8361 (if folded
8362 (hide-subtree)
8363 (org-show-entry)
8364 (show-children)
8365 (org-cycle-hide-drawers 'children))
8366 (org-clean-visibility-after-subtree-move)
8367 ;; move back to the initial column we were at
8368 (move-to-column col)))
8370 (defvar org-subtree-clip ""
8371 "Clipboard for cut and paste of subtrees.
8372 This is actually only a copy of the kill, because we use the normal kill
8373 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8375 (defvar org-subtree-clip-folded nil
8376 "Was the last copied subtree folded?
8377 This is used to fold the tree back after pasting.")
8379 (defun org-cut-subtree (&optional n)
8380 "Cut the current subtree into the clipboard.
8381 With prefix arg N, cut this many sequential subtrees.
8382 This is a short-hand for marking the subtree and then cutting it."
8383 (interactive "p")
8384 (org-copy-subtree n 'cut))
8386 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8387 "Copy the current subtree it in the clipboard.
8388 With prefix arg N, copy this many sequential subtrees.
8389 This is a short-hand for marking the subtree and then copying it.
8390 If CUT is non-nil, actually cut the subtree.
8391 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8392 of some markers in the region, even if CUT is non-nil. This is
8393 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8394 (interactive "p")
8395 (let (beg end folded (beg0 (point)))
8396 (if (org-called-interactively-p 'any)
8397 (org-back-to-heading nil) ; take what looks like a subtree
8398 (org-back-to-heading t)) ; take what is really there
8399 (setq beg (point))
8400 (skip-chars-forward " \t\r\n")
8401 (save-match-data
8402 (if nosubtrees
8403 (outline-next-heading)
8404 (save-excursion (outline-end-of-heading)
8405 (setq folded (outline-invisible-p)))
8406 (ignore-errors (org-forward-heading-same-level (1- n) t))
8407 (org-end-of-subtree t t)))
8408 (setq end (point))
8409 (goto-char beg0)
8410 (when (> end beg)
8411 (setq org-subtree-clip-folded folded)
8412 (when (or cut force-store-markers)
8413 (org-save-markers-in-region beg end))
8414 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8415 (setq org-subtree-clip (current-kill 0))
8416 (message "%s: Subtree(s) with %d characters"
8417 (if cut "Cut" "Copied")
8418 (length org-subtree-clip)))))
8420 (defun org-paste-subtree (&optional level tree for-yank remove)
8421 "Paste the clipboard as a subtree, with modification of headline level.
8422 The entire subtree is promoted or demoted in order to match a new headline
8423 level.
8425 If the cursor is at the beginning of a headline, the same level as
8426 that headline is used to paste the tree.
8428 If not, the new level is derived from the *visible* headings
8429 before and after the insertion point, and taken to be the inferior headline
8430 level of the two. So if the previous visible heading is level 3 and the
8431 next is level 4 (or vice versa), level 4 will be used for insertion.
8432 This makes sure that the subtree remains an independent subtree and does
8433 not swallow low level entries.
8435 You can also force a different level, either by using a numeric prefix
8436 argument, or by inserting the heading marker by hand. For example, if the
8437 cursor is after \"*****\", then the tree will be shifted to level 5.
8439 If optional TREE is given, use this text instead of the kill ring.
8441 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8442 move back over whitespace before inserting, and move point to the end of
8443 the inserted text when done.
8445 When REMOVE is non-nil, remove the subtree from the clipboard."
8446 (interactive "P")
8447 (setq tree (or tree (and kill-ring (current-kill 0))))
8448 (unless (org-kill-is-subtree-p tree)
8449 (user-error "%s"
8450 (substitute-command-keys
8451 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8452 (org-with-limited-levels
8453 (let* ((visp (not (outline-invisible-p)))
8454 (txt tree)
8455 (^re_ "\\(\\*+\\)[ \t]*")
8456 (old-level (if (string-match org-outline-regexp-bol txt)
8457 (- (match-end 0) (match-beginning 0) 1)
8458 -1))
8459 (force-level (cond (level (prefix-numeric-value level))
8460 ((and (looking-at "[ \t]*$")
8461 (string-match
8462 "^\\*+$" (buffer-substring
8463 (point-at-bol) (point))))
8464 (- (match-end 0) (match-beginning 0)))
8465 ((and (bolp)
8466 (looking-at org-outline-regexp))
8467 (- (match-end 0) (point) 1))))
8468 (previous-level (save-excursion
8469 (condition-case nil
8470 (progn
8471 (outline-previous-visible-heading 1)
8472 (if (looking-at ^re_)
8473 (- (match-end 0) (match-beginning 0) 1)
8475 (error 1))))
8476 (next-level (save-excursion
8477 (condition-case nil
8478 (progn
8479 (or (looking-at org-outline-regexp)
8480 (outline-next-visible-heading 1))
8481 (if (looking-at ^re_)
8482 (- (match-end 0) (match-beginning 0) 1)
8484 (error 1))))
8485 (new-level (or force-level (max previous-level next-level)))
8486 (shift (if (or (= old-level -1)
8487 (= new-level -1)
8488 (= old-level new-level))
8490 (- new-level old-level)))
8491 (delta (if (> shift 0) -1 1))
8492 (func (if (> shift 0) 'org-demote 'org-promote))
8493 (org-odd-levels-only nil)
8494 beg end newend)
8495 ;; Remove the forced level indicator
8496 (if force-level
8497 (delete-region (point-at-bol) (point)))
8498 ;; Paste
8499 (beginning-of-line (if (bolp) 1 2))
8500 (setq beg (point))
8501 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8502 (insert-before-markers txt)
8503 (unless (string-match "\n\\'" txt) (insert "\n"))
8504 (setq newend (point))
8505 (org-reinstall-markers-in-region beg)
8506 (setq end (point))
8507 (goto-char beg)
8508 (skip-chars-forward " \t\n\r")
8509 (setq beg (point))
8510 (if (and (outline-invisible-p) visp)
8511 (save-excursion (outline-show-heading)))
8512 ;; Shift if necessary
8513 (unless (= shift 0)
8514 (save-restriction
8515 (narrow-to-region beg end)
8516 (while (not (= shift 0))
8517 (org-map-region func (point-min) (point-max))
8518 (setq shift (+ delta shift)))
8519 (goto-char (point-min))
8520 (setq newend (point-max))))
8521 (when (or (org-called-interactively-p 'interactive) for-yank)
8522 (message "Clipboard pasted as level %d subtree" new-level))
8523 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8524 kill-ring
8525 (eq org-subtree-clip (current-kill 0))
8526 org-subtree-clip-folded)
8527 ;; The tree was folded before it was killed/copied
8528 (hide-subtree))
8529 (and for-yank (goto-char newend))
8530 (and remove (setq kill-ring (cdr kill-ring))))))
8532 (defun org-kill-is-subtree-p (&optional txt)
8533 "Check if the current kill is an outline subtree, or a set of trees.
8534 Returns nil if kill does not start with a headline, or if the first
8535 headline level is not the largest headline level in the tree.
8536 So this will actually accept several entries of equal levels as well,
8537 which is OK for `org-paste-subtree'.
8538 If optional TXT is given, check this string instead of the current kill."
8539 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8540 (re (org-get-limited-outline-regexp))
8541 (^re (concat "^" re))
8542 (start-level (and kill
8543 (string-match
8544 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8545 kill)
8546 (- (match-end 2) (match-beginning 2) 1)))
8547 (start (1+ (or (match-beginning 2) -1))))
8548 (if (not start-level)
8549 (progn
8550 nil) ;; does not even start with a heading
8551 (catch 'exit
8552 (while (setq start (string-match ^re kill (1+ start)))
8553 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8554 (throw 'exit nil)))
8555 t))))
8557 (defvar org-markers-to-move nil
8558 "Markers that should be moved with a cut-and-paste operation.
8559 Those markers are stored together with their positions relative to
8560 the start of the region.")
8562 (defun org-save-markers-in-region (beg end)
8563 "Check markers in region.
8564 If these markers are between BEG and END, record their position relative
8565 to BEG, so that after moving the block of text, we can put the markers back
8566 into place.
8567 This function gets called just before an entry or tree gets cut from the
8568 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8569 called immediately, to move the markers with the entries."
8570 (setq org-markers-to-move nil)
8571 (when (featurep 'org-clock)
8572 (org-clock-save-markers-for-cut-and-paste beg end))
8573 (when (featurep 'org-agenda)
8574 (org-agenda-save-markers-for-cut-and-paste beg end)))
8576 (defun org-check-and-save-marker (marker beg end)
8577 "Check if MARKER is between BEG and END.
8578 If yes, remember the marker and the distance to BEG."
8579 (when (and (marker-buffer marker)
8580 (equal (marker-buffer marker) (current-buffer)))
8581 (if (and (>= marker beg) (< marker end))
8582 (push (cons marker (- marker beg)) org-markers-to-move))))
8584 (defun org-reinstall-markers-in-region (beg)
8585 "Move all remembered markers to their position relative to BEG."
8586 (mapc (lambda (x)
8587 (move-marker (car x) (+ beg (cdr x))))
8588 org-markers-to-move)
8589 (setq org-markers-to-move nil))
8591 (defun org-narrow-to-subtree ()
8592 "Narrow buffer to the current subtree."
8593 (interactive)
8594 (save-excursion
8595 (save-match-data
8596 (org-with-limited-levels
8597 (narrow-to-region
8598 (progn (org-back-to-heading t) (point))
8599 (progn (org-end-of-subtree t t)
8600 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8601 (point)))))))
8603 (defun org-narrow-to-block ()
8604 "Narrow buffer to the current block."
8605 (interactive)
8606 (let* ((case-fold-search t)
8607 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8608 "^[ \t]*#\\+end_.*")))
8609 (if blockp
8610 (narrow-to-region (car blockp) (cdr blockp))
8611 (user-error "Not in a block"))))
8613 (eval-when-compile
8614 (defvar org-property-drawer-re))
8616 (defvar org-property-start-re) ;; defined below
8617 (defun org-clone-subtree-with-time-shift (n &optional shift)
8618 "Clone the task (subtree) at point N times.
8619 The clones will be inserted as siblings.
8621 In interactive use, the user will be prompted for the number of
8622 clones to be produced. If the entry has a timestamp, the user
8623 will also be prompted for a time shift, which may be a repeater
8624 as used in time stamps, for example `+3d'. To disable this,
8625 you can call the function with a universal prefix argument.
8627 When a valid repeater is given and the entry contains any time
8628 stamps, the clones will become a sequence in time, with time
8629 stamps in the subtree shifted for each clone produced. If SHIFT
8630 is nil or the empty string, time stamps will be left alone. The
8631 ID property of the original subtree is removed.
8633 If the original subtree did contain time stamps with a repeater,
8634 the following will happen:
8635 - the repeater will be removed in each clone
8636 - an additional clone will be produced, with the current, unshifted
8637 date(s) in the entry.
8638 - the original entry will be placed *after* all the clones, with
8639 repeater intact.
8640 - the start days in the repeater in the original entry will be shifted
8641 to past the last clone.
8642 In this way you can spell out a number of instances of a repeating task,
8643 and still retain the repeater to cover future instances of the task."
8644 (interactive "nNumber of clones to produce: ")
8645 (let ((shift
8646 (or shift
8647 (if (and (not (equal current-prefix-arg '(4)))
8648 (save-excursion
8649 (re-search-forward org-ts-regexp-both
8650 (save-excursion
8651 (org-end-of-subtree t)
8652 (point)) t)))
8653 (read-from-minibuffer
8654 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8655 ""))) ;; No time shift
8656 (n-no-remove -1)
8657 (drawer-re org-drawer-regexp)
8658 beg end template task idprop
8659 shift-n shift-what doshift nmin nmax)
8660 (if (not (and (integerp n) (> n 0)))
8661 (user-error "Invalid number of replications %s" n))
8662 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8663 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8664 shift)))
8665 (user-error "Invalid shift specification %s" shift))
8666 (when doshift
8667 (setq shift-n (string-to-number (match-string 1 shift))
8668 shift-what (cdr (assoc (match-string 2 shift)
8669 '(("d" . day) ("w" . week)
8670 ("m" . month) ("y" . year))))))
8671 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8672 (setq nmin 1 nmax n)
8673 (org-back-to-heading t)
8674 (setq beg (point))
8675 (setq idprop (org-entry-get nil "ID"))
8676 (org-end-of-subtree t t)
8677 (or (bolp) (insert "\n"))
8678 (setq end (point))
8679 (setq template (buffer-substring beg end))
8680 (when (and doshift
8681 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8682 (delete-region beg end)
8683 (setq end beg)
8684 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8685 (goto-char end)
8686 (loop for n from nmin to nmax do
8687 ;; prepare clone
8688 (with-temp-buffer
8689 (insert template)
8690 (org-mode)
8691 (goto-char (point-min))
8692 (org-show-subtree)
8693 (and idprop (if org-clone-delete-id
8694 (org-entry-delete nil "ID")
8695 (org-id-get-create t)))
8696 (unless (= n 0)
8697 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8698 (kill-whole-line))
8699 (goto-char (point-min))
8700 (while (re-search-forward drawer-re nil t)
8701 (org-remove-empty-drawer-at (point))))
8702 (goto-char (point-min))
8703 (when doshift
8704 (while (re-search-forward org-ts-regexp-both nil t)
8705 (org-timestamp-change (* n shift-n) shift-what))
8706 (unless (= n n-no-remove)
8707 (goto-char (point-min))
8708 (while (re-search-forward org-ts-regexp nil t)
8709 (save-excursion
8710 (goto-char (match-beginning 0))
8711 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8712 (delete-region (match-beginning 1) (match-end 1)))))))
8713 (setq task (buffer-string)))
8714 (insert task))
8715 (goto-char beg)))
8717 ;;; Outline Sorting
8719 (defun org-sort (with-case)
8720 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8721 Optional argument WITH-CASE means sort case-sensitively."
8722 (interactive "P")
8723 (cond
8724 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8725 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8727 (org-call-with-arg 'org-sort-entries with-case))))
8729 (defun org-sort-remove-invisible (s)
8730 "Remove invisible links from string S."
8731 (remove-text-properties 0 (length s) org-rm-props s)
8732 (while (string-match org-bracket-link-regexp s)
8733 (setq s (replace-match (if (match-end 2)
8734 (match-string 3 s)
8735 (match-string 1 s)) t t s)))
8736 (let ((st (format " %s " s)))
8737 (while (string-match org-emph-re st)
8738 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8739 (setq s (substring st 1 -1)))
8742 (defvar org-priority-regexp) ; defined later in the file
8744 (defvar org-after-sorting-entries-or-items-hook nil
8745 "Hook that is run after a bunch of entries or items have been sorted.
8746 When children are sorted, the cursor is in the parent line when this
8747 hook gets called. When a region or a plain list is sorted, the cursor
8748 will be in the first entry of the sorted region/list.")
8750 (defun org-sort-entries
8751 (&optional with-case sorting-type getkey-func compare-func property)
8752 "Sort entries on a certain level of an outline tree.
8753 If there is an active region, the entries in the region are sorted.
8754 Else, if the cursor is before the first entry, sort the top-level items.
8755 Else, the children of the entry at point are sorted.
8757 Sorting can be alphabetically, numerically, by date/time as given by
8758 a time stamp, by a property, by priority order, or by a custom function.
8760 The command prompts for the sorting type unless it has been given to the
8761 function through the SORTING-TYPE argument, which needs to be a character,
8762 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8763 the precise meaning of each character:
8765 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8766 c By creation time, which is assumed to be the first inactive time stamp
8767 at the beginning of a line.
8768 d By deadline date/time.
8769 k By clocking time.
8770 n Numerically, by converting the beginning of the entry/item to a number.
8771 o By order of TODO keywords.
8772 p By priority according to the cookie.
8773 r By the value of a property.
8774 s By scheduled date/time.
8775 t By date/time, either the first active time stamp in the entry, or, if
8776 none exist, by the first inactive one.
8778 Capital letters will reverse the sort order.
8780 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8781 called with point at the beginning of the record. It must return either
8782 a string or a number that should serve as the sorting key for that record.
8784 Comparing entries ignores case by default. However, with an optional argument
8785 WITH-CASE, the sorting considers case as well.
8787 Sorting is done against the visible part of the headlines, it ignores hidden
8788 links.
8790 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8791 (interactive "P")
8792 (let ((case-func (if with-case 'identity 'downcase))
8793 (cmstr
8794 ;; The clock marker is lost when using `sort-subr', let's
8795 ;; store the clocking string.
8796 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8797 (save-excursion
8798 (goto-char org-clock-marker)
8799 (looking-back "^.*") (match-string-no-properties 0))))
8800 start beg end stars re re2
8801 txt what tmp)
8802 ;; Find beginning and end of region to sort
8803 (cond
8804 ((org-region-active-p)
8805 ;; we will sort the region
8806 (setq end (region-end)
8807 what "region")
8808 (goto-char (region-beginning))
8809 (if (not (org-at-heading-p)) (outline-next-heading))
8810 (setq start (point)))
8811 ((or (org-at-heading-p)
8812 (ignore-errors (progn (org-back-to-heading) t)))
8813 ;; we will sort the children of the current headline
8814 (org-back-to-heading)
8815 (setq start (point)
8816 end (progn (org-end-of-subtree t t)
8817 (or (bolp) (insert "\n"))
8818 (when (>= (org-back-over-empty-lines) 1)
8819 (forward-line 1))
8820 (point))
8821 what "children")
8822 (goto-char start)
8823 (show-subtree)
8824 (outline-next-heading))
8826 ;; we will sort the top-level entries in this file
8827 (goto-char (point-min))
8828 (or (org-at-heading-p) (outline-next-heading))
8829 (setq start (point))
8830 (goto-char (point-max))
8831 (beginning-of-line 1)
8832 (when (looking-at ".*?\\S-")
8833 ;; File ends in a non-white line
8834 (end-of-line 1)
8835 (insert "\n"))
8836 (setq end (point-max))
8837 (setq what "top-level")
8838 (goto-char start)
8839 (show-all)))
8841 (setq beg (point))
8842 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8844 (looking-at "\\(\\*+\\)")
8845 (setq stars (match-string 1)
8846 re (concat "^" (regexp-quote stars) " +")
8847 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8848 txt (buffer-substring beg end))
8849 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8850 (if (and (not (equal stars "*")) (string-match re2 txt))
8851 (user-error "Region to sort contains a level above the first entry"))
8853 (unless sorting-type
8854 (message
8855 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8856 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8857 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8858 what)
8859 (setq sorting-type (read-char-exclusive))
8861 (unless getkey-func
8862 (and (= (downcase sorting-type) ?f)
8863 (setq getkey-func
8864 (org-icompleting-read "Sort using function: "
8865 obarray 'fboundp t nil nil))
8866 (setq getkey-func (intern getkey-func))))
8868 (and (= (downcase sorting-type) ?r)
8869 (not property)
8870 (setq property
8871 (org-icompleting-read "Property: "
8872 (mapcar 'list (org-buffer-property-keys t))
8873 nil t))))
8875 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8876 (message "Sorting entries...")
8878 (save-restriction
8879 (narrow-to-region start end)
8880 (let ((dcst (downcase sorting-type))
8881 (case-fold-search nil)
8882 (now (current-time)))
8883 (sort-subr
8884 (/= dcst sorting-type)
8885 ;; This function moves to the beginning character of the "record" to
8886 ;; be sorted.
8887 (lambda nil
8888 (if (re-search-forward re nil t)
8889 (goto-char (match-beginning 0))
8890 (goto-char (point-max))))
8891 ;; This function moves to the last character of the "record" being
8892 ;; sorted.
8893 (lambda nil
8894 (save-match-data
8895 (condition-case nil
8896 (outline-forward-same-level 1)
8897 (error
8898 (goto-char (point-max))))))
8899 ;; This function returns the value that gets sorted against.
8900 (lambda nil
8901 (cond
8902 ((= dcst ?n)
8903 (if (looking-at org-complex-heading-regexp)
8904 (string-to-number (org-sort-remove-invisible (match-string 4)))
8905 nil))
8906 ((= dcst ?a)
8907 (if (looking-at org-complex-heading-regexp)
8908 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8909 nil))
8910 ((= dcst ?k)
8911 (or (get-text-property (point) :org-clock-minutes) 0))
8912 ((= dcst ?t)
8913 (let ((end (save-excursion (outline-next-heading) (point))))
8914 (if (or (re-search-forward org-ts-regexp end t)
8915 (re-search-forward org-ts-regexp-both end t))
8916 (org-time-string-to-seconds (match-string 0))
8917 (org-float-time now))))
8918 ((= dcst ?c)
8919 (let ((end (save-excursion (outline-next-heading) (point))))
8920 (if (re-search-forward
8921 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8922 end t)
8923 (org-time-string-to-seconds (match-string 0))
8924 (org-float-time now))))
8925 ((= dcst ?s)
8926 (let ((end (save-excursion (outline-next-heading) (point))))
8927 (if (re-search-forward org-scheduled-time-regexp end t)
8928 (org-time-string-to-seconds (match-string 1))
8929 (org-float-time now))))
8930 ((= dcst ?d)
8931 (let ((end (save-excursion (outline-next-heading) (point))))
8932 (if (re-search-forward org-deadline-time-regexp end t)
8933 (org-time-string-to-seconds (match-string 1))
8934 (org-float-time now))))
8935 ((= dcst ?p)
8936 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8937 (string-to-char (match-string 2))
8938 org-default-priority))
8939 ((= dcst ?r)
8940 (or (org-entry-get nil property) ""))
8941 ((= dcst ?o)
8942 (if (looking-at org-complex-heading-regexp)
8943 (let* ((m (match-string 2))
8944 (s (if (member m org-done-keywords) '- '+)))
8945 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8946 ((= dcst ?f)
8947 (if getkey-func
8948 (progn
8949 (setq tmp (funcall getkey-func))
8950 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8951 tmp)
8952 (error "Invalid key function `%s'" getkey-func)))
8953 (t (error "Invalid sorting type `%c'" sorting-type))))
8955 (cond
8956 ((= dcst ?a) 'string<)
8957 ((= dcst ?f) compare-func)
8958 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8959 (run-hooks 'org-after-sorting-entries-or-items-hook)
8960 ;; Reset the clock marker if needed
8961 (when cmstr
8962 (save-excursion
8963 (goto-char start)
8964 (search-forward cmstr nil t)
8965 (move-marker org-clock-marker (point))))
8966 (message "Sorting entries...done")))
8968 (defun org-do-sort (table what &optional with-case sorting-type)
8969 "Sort TABLE of WHAT according to SORTING-TYPE.
8970 The user will be prompted for the SORTING-TYPE if the call to this
8971 function does not specify it.
8972 WHAT is only for the prompt, to indicate what is being sorted.
8973 The sorting key will be extracted from the car of the elements of
8974 the table.
8975 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8976 (unless sorting-type
8977 (message
8978 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8979 what)
8980 (setq sorting-type (read-char-exclusive)))
8981 (let ((dcst (downcase sorting-type))
8982 extractfun comparefun)
8983 ;; Define the appropriate functions
8984 (cond
8985 ((= dcst ?n)
8986 (setq extractfun 'string-to-number
8987 comparefun (if (= dcst sorting-type) '< '>)))
8988 ((= dcst ?a)
8989 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8990 (lambda(x) (downcase (org-sort-remove-invisible x))))
8991 comparefun (if (= dcst sorting-type)
8992 'string<
8993 (lambda (a b) (and (not (string< a b))
8994 (not (string= a b)))))))
8995 ((= dcst ?t)
8996 (setq extractfun
8997 (lambda (x)
8998 (cond ((or (string-match org-ts-regexp x)
8999 (string-match org-ts-regexp-both x))
9000 (org-float-time
9001 (org-time-string-to-time (match-string 0 x))))
9002 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9003 (org-hh:mm-string-to-minutes x))
9004 (t 0)))
9005 comparefun (if (= dcst sorting-type) '< '>)))
9006 (t (error "Invalid sorting type `%c'" sorting-type)))
9008 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9009 table)
9010 (lambda (a b) (funcall comparefun (car a) (car b))))))
9013 ;;; The orgstruct minor mode
9015 ;; Define a minor mode which can be used in other modes in order to
9016 ;; integrate the org-mode structure editing commands.
9018 ;; This is really a hack, because the org-mode structure commands use
9019 ;; keys which normally belong to the major mode. Here is how it
9020 ;; works: The minor mode defines all the keys necessary to operate the
9021 ;; structure commands, but wraps the commands into a function which
9022 ;; tests if the cursor is currently at a headline or a plain list
9023 ;; item. If that is the case, the structure command is used,
9024 ;; temporarily setting many Org-mode variables like regular
9025 ;; expressions for filling etc. However, when any of those keys is
9026 ;; used at a different location, function uses `key-binding' to look
9027 ;; up if the key has an associated command in another currently active
9028 ;; keymap (minor modes, major mode, global), and executes that
9029 ;; command. There might be problems if any of the keys is otherwise
9030 ;; used as a prefix key.
9032 (defcustom orgstruct-heading-prefix-regexp ""
9033 "Regexp that matches the custom prefix of Org headlines in
9034 orgstruct(++)-mode."
9035 :group 'org
9036 :version "24.4"
9037 :package-version '(Org . "8.3")
9038 :type 'regexp)
9039 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9041 (defcustom orgstruct-setup-hook nil
9042 "Hook run after orgstruct-mode-map is filled."
9043 :group 'org
9044 :version "24.4"
9045 :package-version '(Org . "8.0")
9046 :type 'hook)
9048 (defvar orgstruct-initialized nil)
9050 (defvar org-local-vars nil
9051 "List of local variables, for use by `orgstruct-mode'.")
9053 ;;;###autoload
9054 (define-minor-mode orgstruct-mode
9055 "Toggle the minor mode `orgstruct-mode'.
9056 This mode is for using Org-mode structure commands in other
9057 modes. The following keys behave as if Org-mode were active, if
9058 the cursor is on a headline, or on a plain list item (both as
9059 defined by Org-mode)."
9060 nil " OrgStruct" (make-sparse-keymap)
9061 (funcall (if orgstruct-mode
9062 'add-to-invisibility-spec
9063 'remove-from-invisibility-spec)
9064 '(outline . t))
9065 (when orgstruct-mode
9066 (org-load-modules-maybe)
9067 (unless orgstruct-initialized
9068 (orgstruct-setup)
9069 (setq orgstruct-initialized t))))
9071 ;;;###autoload
9072 (defun turn-on-orgstruct ()
9073 "Unconditionally turn on `orgstruct-mode'."
9074 (orgstruct-mode 1))
9076 (defvar org-fb-vars nil)
9077 (make-variable-buffer-local 'org-fb-vars)
9078 (defun orgstruct++-mode (&optional arg)
9079 "Toggle `orgstruct-mode', the enhanced version of it.
9080 In addition to setting orgstruct-mode, this also exports all
9081 indentation and autofilling variables from org-mode into the
9082 buffer. It will also recognize item context in multiline items."
9083 (interactive "P")
9084 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9085 (if (< arg 1)
9086 (progn (orgstruct-mode -1)
9087 (mapc (lambda(v)
9088 (org-set-local (car v)
9089 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9090 org-fb-vars))
9091 (orgstruct-mode 1)
9092 (setq org-fb-vars nil)
9093 (unless org-local-vars
9094 (setq org-local-vars (org-get-local-variables)))
9095 (let (var val)
9096 (mapc
9097 (lambda (x)
9098 (when (string-match
9099 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9100 (symbol-name (car x)))
9101 (setq var (car x) val (nth 1 x))
9102 (push (list var `(quote ,(eval var))) org-fb-vars)
9103 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9104 org-local-vars)
9105 (org-set-local 'orgstruct-is-++ t))))
9107 (defvar orgstruct-is-++ nil
9108 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9109 (make-variable-buffer-local 'orgstruct-is-++)
9111 ;;;###autoload
9112 (defun turn-on-orgstruct++ ()
9113 "Unconditionally turn on `orgstruct++-mode'."
9114 (orgstruct++-mode 1))
9116 (defun orgstruct-error ()
9117 "Error when there is no default binding for a structure key."
9118 (interactive)
9119 (funcall (if (fboundp 'user-error)
9120 'user-error
9121 'error)
9122 "This key has no function outside structure elements"))
9124 (defun orgstruct-setup ()
9125 "Setup orgstruct keymap."
9126 (dolist (cell '((org-demote . t)
9127 (org-metaleft . t)
9128 (org-metaright . t)
9129 (org-promote . t)
9130 (org-shiftmetaleft . t)
9131 (org-shiftmetaright . t)
9132 org-backward-element
9133 org-backward-heading-same-level
9134 org-ctrl-c-ret
9135 org-ctrl-c-minus
9136 org-ctrl-c-star
9137 org-cycle
9138 org-forward-heading-same-level
9139 org-insert-heading
9140 org-insert-heading-respect-content
9141 org-kill-note-or-show-branches
9142 org-mark-subtree
9143 org-meta-return
9144 org-metadown
9145 org-metaup
9146 org-narrow-to-subtree
9147 org-promote-subtree
9148 org-reveal
9149 org-shiftdown
9150 org-shiftleft
9151 org-shiftmetadown
9152 org-shiftmetaup
9153 org-shiftright
9154 org-shifttab
9155 org-shifttab
9156 org-shiftup
9157 org-show-subtree
9158 org-sort
9159 org-up-element
9160 outline-demote
9161 outline-next-visible-heading
9162 outline-previous-visible-heading
9163 outline-promote
9164 outline-up-heading
9165 show-children))
9166 (let ((f (or (car-safe cell) cell))
9167 (disable-when-heading-prefix (cdr-safe cell)))
9168 (when (fboundp f)
9169 (let ((new-bindings))
9170 (dolist (binding (nconc (where-is-internal f org-mode-map)
9171 (where-is-internal f outline-mode-map)))
9172 (push binding new-bindings)
9173 ;; TODO use local-function-key-map
9174 (dolist (rep '(("<tab>" . "TAB")
9175 ("<return>" . "RET")
9176 ("<escape>" . "ESC")
9177 ("<delete>" . "DEL")))
9178 (setq binding (read-kbd-macro
9179 (let ((case-fold-search))
9180 (replace-regexp-in-string
9181 (regexp-quote (cdr rep))
9182 (car rep)
9183 (key-description binding)))))
9184 (pushnew binding new-bindings :test 'equal)))
9185 (dolist (binding new-bindings)
9186 (let ((key (lookup-key orgstruct-mode-map binding)))
9187 (when (or (not key) (numberp key))
9188 (ignore-errors
9189 (org-defkey orgstruct-mode-map
9190 binding
9191 (orgstruct-make-binding
9192 f binding disable-when-heading-prefix))))))))))
9193 (run-hooks 'orgstruct-setup-hook))
9195 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9196 "Create a function for binding in the structure minor mode.
9197 FUN is the command to call inside a table. KEY is the key that
9198 should be checked in for a command to execute outside of tables.
9199 Non-nil `disable-when-heading-prefix' means to disable the command
9200 if `orgstruct-heading-prefix-regexp' is not empty."
9201 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9202 (let ((nname name)
9203 (i 0))
9204 (while (fboundp (intern nname))
9205 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9206 (setq name (intern nname)))
9207 (eval
9208 (let ((bindings '((org-heading-regexp
9209 (concat "^"
9210 orgstruct-heading-prefix-regexp
9211 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9212 (org-outline-regexp
9213 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9214 (org-outline-regexp-bol
9215 (concat "^" org-outline-regexp))
9216 (outline-regexp org-outline-regexp)
9217 (outline-heading-end-regexp "\n")
9218 (outline-level 'org-outline-level)
9219 (outline-heading-alist))))
9220 `(defun ,name (arg)
9221 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9222 "Outside of structure, run the binding of `"
9223 (key-description key) "'."
9224 (when disable-when-heading-prefix
9225 (concat
9226 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9227 "back to the default binding due to limitations of Org's implementation of\n"
9228 "`" (symbol-name fun) "'.")))
9229 (interactive "p")
9230 (let* ((disable
9231 ,(and disable-when-heading-prefix
9232 '(not (string= orgstruct-heading-prefix-regexp ""))))
9233 (fallback
9234 (or disable
9235 (not
9236 (let* ,bindings
9237 (org-context-p 'headline 'item
9238 ,(when (memq fun
9239 '(org-insert-heading
9240 org-insert-heading-respect-content
9241 org-meta-return))
9242 '(when orgstruct-is-++
9243 'item-body))))))))
9244 (if fallback
9245 (let* ((orgstruct-mode)
9246 (binding
9247 (loop with key = ,key
9248 for rep in
9249 '(nil
9250 ("<\\([^>]*\\)tab>" . "\\1TAB")
9251 ("<\\([^>]*\\)return>" . "\\1RET")
9252 ("<\\([^>]*\\)escape>" . "\\1ESC")
9253 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9255 (when rep
9256 (setq key (read-kbd-macro
9257 (let ((case-fold-search))
9258 (replace-regexp-in-string
9259 (car rep)
9260 (cdr rep)
9261 (key-description key))))))
9262 thereis (key-binding key))))
9263 (if (keymapp binding)
9264 (org-set-transient-map binding)
9265 (let ((func (or binding
9266 (unless disable
9267 'orgstruct-error))))
9268 (when func
9269 (call-interactively func)))))
9270 (org-run-like-in-org-mode
9271 (lambda ()
9272 (interactive)
9273 (let* ,bindings
9274 (call-interactively ',fun)))))))))
9275 name))
9277 (defun org-contextualize-keys (alist contexts)
9278 "Return valid elements in ALIST depending on CONTEXTS.
9280 `org-agenda-custom-commands' or `org-capture-templates' are the
9281 values used for ALIST, and `org-agenda-custom-commands-contexts'
9282 or `org-capture-templates-contexts' are the associated contexts
9283 definitions."
9284 (let ((contexts
9285 ;; normalize contexts
9286 (mapcar
9287 (lambda(c) (cond ((listp (cadr c))
9288 (list (car c) (car c) (cadr c)))
9289 ((string= "" (cadr c))
9290 (list (car c) (car c) (caddr c)))
9291 (t c))) contexts))
9292 (a alist) c r s)
9293 ;; loop over all commands or templates
9294 (while (setq c (pop a))
9295 (let (vrules repl)
9296 (cond
9297 ((not (assoc (car c) contexts))
9298 (push c r))
9299 ((and (assoc (car c) contexts)
9300 (setq vrules (org-contextualize-validate-key
9301 (car c) contexts)))
9302 (mapc (lambda (vr)
9303 (when (not (equal (car vr) (cadr vr)))
9304 (setq repl vr))) vrules)
9305 (if (not repl) (push c r)
9306 (push (cadr repl) s)
9307 (push
9308 (cons (car c)
9309 (cdr (or (assoc (cadr repl) alist)
9310 (error "Undefined key `%s' as contextual replacement for `%s'"
9311 (cadr repl) (car c)))))
9312 r))))))
9313 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9314 (delq
9316 (delete-dups
9317 (mapcar (lambda (x)
9318 (let ((tpl (car x)))
9319 (when (not (delq
9321 (mapcar (lambda(y)
9322 (equal y tpl)) s))) x)))
9323 (reverse r))))))
9325 (defun org-contextualize-validate-key (key contexts)
9326 "Check CONTEXTS for agenda or capture KEY."
9327 (let (r rr res)
9328 (while (setq r (pop contexts))
9329 (mapc
9330 (lambda (rr)
9331 (when
9332 (and (equal key (car r))
9333 (if (functionp rr) (funcall rr)
9334 (or (and (eq (car rr) 'in-file)
9335 (buffer-file-name)
9336 (string-match (cdr rr) (buffer-file-name)))
9337 (and (eq (car rr) 'in-mode)
9338 (string-match (cdr rr) (symbol-name major-mode)))
9339 (and (eq (car rr) 'in-buffer)
9340 (string-match (cdr rr) (buffer-name)))
9341 (when (and (eq (car rr) 'not-in-file)
9342 (buffer-file-name))
9343 (not (string-match (cdr rr) (buffer-file-name))))
9344 (when (eq (car rr) 'not-in-mode)
9345 (not (string-match (cdr rr) (symbol-name major-mode))))
9346 (when (eq (car rr) 'not-in-buffer)
9347 (not (string-match (cdr rr) (buffer-name)))))))
9348 (push r res)))
9349 (car (last r))))
9350 (delete-dups (delq nil res))))
9352 (defun org-context-p (&rest contexts)
9353 "Check if local context is any of CONTEXTS.
9354 Possible values in the list of contexts are `table', `headline', and `item'."
9355 (let ((pos (point)))
9356 (goto-char (point-at-bol))
9357 (prog1 (or (and (memq 'table contexts)
9358 (looking-at "[ \t]*|"))
9359 (and (memq 'headline contexts)
9360 (looking-at org-outline-regexp))
9361 (and (memq 'item contexts)
9362 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9363 (and (memq 'item-body contexts)
9364 (org-in-item-p)))
9365 (goto-char pos))))
9367 (defun org-get-local-variables ()
9368 "Return a list of all local variables in an Org mode buffer."
9369 (let (varlist)
9370 (with-current-buffer (get-buffer-create "*Org tmp*")
9371 (erase-buffer)
9372 (org-mode)
9373 (setq varlist (buffer-local-variables)))
9374 (kill-buffer "*Org tmp*")
9375 (delq nil
9376 (mapcar
9377 (lambda (x)
9378 (setq x
9379 (if (symbolp x)
9380 (list x)
9381 (list (car x) (cdr x))))
9382 (if (and (not (get (car x) 'org-state))
9383 (string-match
9384 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9385 (symbol-name (car x))))
9386 x nil))
9387 varlist))))
9389 (defun org-clone-local-variables (from-buffer &optional regexp)
9390 "Clone local variables from FROM-BUFFER.
9391 Optional argument REGEXP selects variables to clone."
9392 (mapc
9393 (lambda (pair)
9394 (and (symbolp (car pair))
9395 (or (null regexp)
9396 (string-match regexp (symbol-name (car pair))))
9397 (set (make-local-variable (car pair))
9398 (cdr pair))))
9399 (buffer-local-variables from-buffer)))
9401 ;;;###autoload
9402 (defun org-run-like-in-org-mode (cmd)
9403 "Run a command, pretending that the current buffer is in Org-mode.
9404 This will temporarily bind local variables that are typically bound in
9405 Org-mode to the values they have in Org-mode, and then interactively
9406 call CMD."
9407 (org-load-modules-maybe)
9408 (unless org-local-vars
9409 (setq org-local-vars (org-get-local-variables)))
9410 (let (binds)
9411 (dolist (var org-local-vars)
9412 (when (or (not (boundp (car var)))
9413 (eq (symbol-value (car var))
9414 (default-value (car var))))
9415 (push (list (car var) `(quote ,(cadr var))) binds)))
9416 (eval `(let ,binds
9417 (call-interactively (quote ,cmd))))))
9419 (defun org-get-category (&optional pos force-refresh)
9420 "Get the category applying to position POS."
9421 (save-match-data
9422 (if force-refresh (org-refresh-category-properties))
9423 (let ((pos (or pos (point))))
9424 (or (get-text-property pos 'org-category)
9425 (progn (org-refresh-category-properties)
9426 (get-text-property pos 'org-category))))))
9428 ;;; Refresh properties
9430 (defun org-refresh-properties (dprop tprop)
9431 "Refresh buffer text properties.
9432 DPROP is the drawer property and TPROP is either the
9433 corresponding text property to set, or an alist with each element
9434 being a text property (as a symbol) and a function to apply to
9435 the value of the drawer property."
9436 (let ((case-fold-search t)
9437 (inhibit-read-only t))
9438 (org-with-silent-modifications
9439 (save-excursion
9440 (save-restriction
9441 (widen)
9442 (goto-char (point-min))
9443 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9444 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9446 (defun org-refresh-property (tprop p)
9447 "Refresh the buffer text property TPROP from the drawer property P.
9448 The refresh happens only for the current tree (not subtree)."
9449 (save-excursion
9450 (org-back-to-heading t)
9451 ;; tprop is a text property symbol
9452 (if (symbolp tprop)
9453 (put-text-property
9454 (point) (or (outline-next-heading) (point-max)) tprop p)
9455 ;; tprop is an alist with (properties . function) elements
9456 (mapc (lambda(al)
9457 (save-excursion
9458 (put-text-property
9459 (point-at-bol) (or (outline-next-heading) (point-max))
9460 (car al)
9461 (funcall (cdr al) p))))
9462 tprop))))
9464 (defun org-refresh-category-properties ()
9465 "Refresh category text properties in the buffer."
9466 (let ((case-fold-search t)
9467 (inhibit-read-only t)
9468 (def-cat (cond
9469 ((null org-category)
9470 (if buffer-file-name
9471 (file-name-sans-extension
9472 (file-name-nondirectory buffer-file-name))
9473 "???"))
9474 ((symbolp org-category) (symbol-name org-category))
9475 (t org-category)))
9476 beg end cat pos optionp)
9477 (org-with-silent-modifications
9478 (save-excursion
9479 (save-restriction
9480 (widen)
9481 (goto-char (point-min))
9482 (put-text-property (point) (point-max) 'org-category def-cat)
9483 (while (re-search-forward
9484 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9485 (setq pos (match-end 0)
9486 optionp (equal (char-after (match-beginning 0)) ?#)
9487 cat (org-trim (match-string 2)))
9488 (if optionp
9489 (setq beg (point-at-bol) end (point-max))
9490 (org-back-to-heading t)
9491 (setq beg (point) end (org-end-of-subtree t t)))
9492 (put-text-property beg end 'org-category cat)
9493 (goto-char pos)))))))
9495 (defun org-refresh-stats-properties ()
9496 "Refresh stats text properties in the buffer."
9497 (let (stats)
9498 (org-with-silent-modifications
9499 (save-excursion
9500 (save-restriction
9501 (widen)
9502 (goto-char (point-min))
9503 (while (re-search-forward
9504 (concat org-outline-regexp-bol ".*"
9505 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9506 nil t)
9507 (setq stats (cond ((equal (match-string 3) "0") 0)
9508 ((match-string 2)
9509 (/ (* (string-to-number (match-string 2)) 100)
9510 (string-to-number (match-string 3))))
9511 (t (string-to-number (match-string 1)))))
9512 (org-back-to-heading t)
9513 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9514 'org-stats stats)))))))
9516 (defun org-refresh-effort-properties ()
9517 "Refresh effort properties"
9518 (org-refresh-properties
9519 org-effort-property
9520 '((effort . identity)
9521 (effort-minutes . org-duration-string-to-minutes))))
9523 ;;;; Link Stuff
9525 ;;; Link abbreviations
9527 (defun org-link-expand-abbrev (link)
9528 "Apply replacements as defined in `org-link-abbrev-alist'."
9529 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9530 (let* ((key (match-string 1 link))
9531 (as (or (assoc key org-link-abbrev-alist-local)
9532 (assoc key org-link-abbrev-alist)))
9533 (tag (and (match-end 2) (match-string 3 link)))
9534 rpl)
9535 (if (not as)
9536 link
9537 (setq rpl (cdr as))
9538 (cond
9539 ((symbolp rpl) (funcall rpl tag))
9540 ((string-match "%(\\([^)]+\\))" rpl)
9541 (replace-match
9542 (save-match-data
9543 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9544 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9545 ((string-match "%h" rpl)
9546 (replace-match (url-hexify-string (or tag "")) t t rpl))
9547 (t (concat rpl tag)))))
9548 link))
9550 ;;; Storing and inserting links
9552 (defvar org-insert-link-history nil
9553 "Minibuffer history for links inserted with `org-insert-link'.")
9555 (defvar org-stored-links nil
9556 "Contains the links stored with `org-store-link'.")
9558 (defvar org-store-link-plist nil
9559 "Plist with info about the most recently link created with `org-store-link'.")
9561 (defvar org-link-protocols nil
9562 "Link protocols added to Org-mode using `org-add-link-type'.")
9564 (defvar org-store-link-functions nil
9565 "List of functions that are called to create and store a link.
9566 Each function will be called in turn until one returns a non-nil
9567 value. Each function should check if it is responsible for creating
9568 this link (for example by looking at the major mode).
9569 If not, it must exit and return nil.
9570 If yes, it should return a non-nil value after a calling
9571 `org-store-link-props' with a list of properties and values.
9572 Special properties are:
9574 :type The link prefix, like \"http\". This must be given.
9575 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9576 This is obligatory as well.
9577 :description Optional default description for the second pair
9578 of brackets in an Org-mode link. The user can still change
9579 this when inserting this link into an Org-mode buffer.
9581 In addition to these, any additional properties can be specified
9582 and then used in capture templates.")
9584 (defun org-add-link-type (type &optional follow export)
9585 "Add TYPE to the list of `org-link-types'.
9586 Re-compute all regular expressions depending on `org-link-types'
9588 FOLLOW and EXPORT are two functions.
9590 FOLLOW should take the link path as the single argument and do whatever
9591 is necessary to follow the link, for example find a file or display
9592 a mail message.
9594 EXPORT should format the link path for export to one of the export formats.
9595 It should be a function accepting three arguments:
9597 path the path of the link, the text after the prefix (like \"http:\")
9598 desc the description of the link, if any, or a description added by
9599 org-export-normalize-links if there is none
9600 format the export format, a symbol like `html' or `latex' or `ascii'..
9602 The function may use the FORMAT information to return different values
9603 depending on the format. The return value will be put literally into
9604 the exported file. If the return value is nil, this means Org should
9605 do what it normally does with links which do not have EXPORT defined.
9607 Org-mode has a built-in default for exporting links. If you are happy with
9608 this default, there is no need to define an export function for the link
9609 type. For a simple example of an export function, see `org-bbdb.el'."
9610 (add-to-list 'org-link-types type t)
9611 (org-make-link-regexps)
9612 (if (assoc type org-link-protocols)
9613 (setcdr (assoc type org-link-protocols) (list follow export))
9614 (push (list type follow export) org-link-protocols)))
9616 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9617 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9619 ;;;###autoload
9620 (defun org-store-link (arg)
9621 "\\<org-mode-map>Store an org-link to the current location.
9622 This link is added to `org-stored-links' and can later be inserted
9623 into an org-buffer with \\[org-insert-link].
9625 For some link types, a prefix arg is interpreted.
9626 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9627 For file links, arg negates `org-context-in-file-links'.
9629 A double prefix arg force skipping storing functions that are not
9630 part of Org's core.
9632 A triple prefix arg force storing a link for each line in the
9633 active region."
9634 (interactive "P")
9635 (org-load-modules-maybe)
9636 (if (and (equal arg '(64)) (org-region-active-p))
9637 (save-excursion
9638 (let ((end (region-end)))
9639 (goto-char (region-beginning))
9640 (set-mark (point))
9641 (while (< (point-at-eol) end)
9642 (move-end-of-line 1) (activate-mark)
9643 (let (current-prefix-arg)
9644 (call-interactively 'org-store-link))
9645 (move-beginning-of-line 2)
9646 (set-mark (point)))))
9647 (org-with-limited-levels
9648 (setq org-store-link-plist nil)
9649 (let (link cpltxt desc description search
9650 txt custom-id agenda-link sfuns sfunsn)
9651 (cond
9653 ;; Store a link using an external link type
9654 ((and (not (equal arg '(16)))
9655 (setq sfuns
9656 (delq
9657 nil (mapcar (lambda (f)
9658 (let (fs) (if (funcall f) (push f fs))))
9659 org-store-link-functions))
9660 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9661 (or (and (cdr sfuns)
9662 (funcall (intern
9663 (completing-read
9664 "Which function for creating the link? "
9665 sfunsn nil t (car sfunsn)))))
9666 (funcall (caar sfuns)))
9667 (setq link (plist-get org-store-link-plist :link)
9668 desc (or (plist-get org-store-link-plist
9669 :description) link))))
9671 ;; Store a link from a source code buffer
9672 ((org-src-edit-buffer-p)
9673 (let (label gc)
9674 (while (or (not label)
9675 (save-excursion
9676 (save-restriction
9677 (widen)
9678 (goto-char (point-min))
9679 (re-search-forward
9680 (regexp-quote (format org-coderef-label-format label))
9681 nil t))))
9682 (when label (message "Label exists already") (sit-for 2))
9683 (setq label (read-string "Code line label: " label)))
9684 (end-of-line 1)
9685 (setq link (format org-coderef-label-format label))
9686 (setq gc (- 79 (length link)))
9687 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9688 (insert link)
9689 (setq link (concat "(" label ")") desc nil)))
9691 ;; We are in the agenda, link to referenced location
9692 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9693 (let ((m (or (get-text-property (point) 'org-hd-marker)
9694 (get-text-property (point) 'org-marker))))
9695 (when m
9696 (org-with-point-at m
9697 (setq agenda-link
9698 (if (org-called-interactively-p 'any)
9699 (call-interactively 'org-store-link)
9700 (org-store-link nil)))))))
9702 ((eq major-mode 'calendar-mode)
9703 (let ((cd (calendar-cursor-to-date)))
9704 (setq link
9705 (format-time-string
9706 (car org-time-stamp-formats)
9707 (apply 'encode-time
9708 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9709 nil nil nil))))
9710 (org-store-link-props :type "calendar" :date cd)))
9712 ((eq major-mode 'help-mode)
9713 (setq link (concat "help:" (save-excursion
9714 (goto-char (point-min))
9715 (looking-at "^[^ ]+")
9716 (match-string 0))))
9717 (org-store-link-props :type "help"))
9719 ((eq major-mode 'w3-mode)
9720 (setq cpltxt (if (and (buffer-name)
9721 (not (string-match "Untitled" (buffer-name))))
9722 (buffer-name)
9723 (url-view-url t))
9724 link (url-view-url t))
9725 (org-store-link-props :type "w3" :url (url-view-url t)))
9727 ((eq major-mode 'image-mode)
9728 (setq cpltxt (concat "file:"
9729 (abbreviate-file-name buffer-file-name))
9730 link cpltxt)
9731 (org-store-link-props :type "image" :file buffer-file-name))
9733 ;; In dired, store a link to the file of the current line
9734 ((derived-mode-p 'dired-mode)
9735 (let ((file (dired-get-filename nil t)))
9736 (setq file (if file
9737 (abbreviate-file-name
9738 (expand-file-name (dired-get-filename nil t)))
9739 ;; otherwise, no file so use current directory.
9740 default-directory))
9741 (setq cpltxt (concat "file:" file)
9742 link cpltxt)))
9744 ((setq search (run-hook-with-args-until-success
9745 'org-create-file-search-functions))
9746 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9747 "::" search))
9748 (setq cpltxt (or description link)))
9750 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9751 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9752 (cond
9753 ;; Store a link using the target at point
9754 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9755 (setq cpltxt
9756 (concat "file:"
9757 (abbreviate-file-name
9758 (buffer-file-name (buffer-base-buffer)))
9759 "::" (match-string 1))
9760 link cpltxt))
9761 ((and (featurep 'org-id)
9762 (or (eq org-id-link-to-org-use-id t)
9763 (and (org-called-interactively-p 'any)
9764 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9765 (and (eq org-id-link-to-org-use-id
9766 'create-if-interactive-and-no-custom-id)
9767 (not custom-id))))
9768 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9769 ;; Store a link using the ID at point
9770 (setq link (condition-case nil
9771 (prog1 (org-id-store-link)
9772 (setq desc (or (plist-get org-store-link-plist
9773 :description)
9774 "")))
9775 (error
9776 ;; Probably before first headline, link only to file
9777 (concat "file:"
9778 (abbreviate-file-name
9779 (buffer-file-name (buffer-base-buffer))))))))
9781 ;; Just link to current headline
9782 (setq cpltxt (concat "file:"
9783 (abbreviate-file-name
9784 (buffer-file-name (buffer-base-buffer)))))
9785 ;; Add a context search string
9786 (when (org-xor org-context-in-file-links arg)
9787 (let* ((ee (org-element-at-point))
9788 (et (org-element-type ee))
9789 (ev (plist-get (cadr ee) :value))
9790 (ek (plist-get (cadr ee) :key))
9791 (eok (and (stringp ek) (string-match "name" ek))))
9792 (setq txt (cond
9793 ((org-at-heading-p) nil)
9794 ((and (eq et 'keyword) eok) ev)
9795 ((org-region-active-p)
9796 (buffer-substring (region-beginning) (region-end)))))
9797 (when (or (null txt) (string-match "\\S-" txt))
9798 (setq cpltxt
9799 (concat cpltxt "::"
9800 (condition-case nil
9801 (org-make-org-heading-search-string txt)
9802 (error "")))
9803 desc (or (and (eq et 'keyword) eok ev)
9804 (nth 4 (ignore-errors (org-heading-components)))
9805 "NONE")))))
9806 (if (string-match "::\\'" cpltxt)
9807 (setq cpltxt (substring cpltxt 0 -2)))
9808 (setq link cpltxt))))
9810 ((buffer-file-name (buffer-base-buffer))
9811 ;; Just link to this file here.
9812 (setq cpltxt (concat "file:"
9813 (abbreviate-file-name
9814 (buffer-file-name (buffer-base-buffer)))))
9815 ;; Add a context string.
9816 (when (org-xor org-context-in-file-links arg)
9817 (setq txt (if (org-region-active-p)
9818 (buffer-substring (region-beginning) (region-end))
9819 (buffer-substring (point-at-bol) (point-at-eol))))
9820 ;; Only use search option if there is some text.
9821 (when (string-match "\\S-" txt)
9822 (setq cpltxt
9823 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9824 desc "NONE")))
9825 (setq link cpltxt))
9827 ((org-called-interactively-p 'interactive)
9828 (user-error "No method for storing a link from this buffer"))
9830 (t (setq link nil)))
9832 ;; We're done setting link and desc, clean up
9833 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9834 (setq link (or link cpltxt)
9835 desc (or desc cpltxt))
9836 (cond ((equal desc "NONE") (setq desc nil))
9837 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9838 (let ((d0 (match-string 3 desc))
9839 (p0 (match-string 5 desc)))
9840 (setq desc
9841 (replace-regexp-in-string
9842 org-bracket-link-regexp
9843 (concat (or p0 d0)
9844 (if (equal (length (match-string 0 desc))
9845 (length desc)) "*" "")) desc)))))
9847 ;; Return the link
9848 (if (not (and (or (org-called-interactively-p 'any)
9849 executing-kbd-macro) link))
9850 (or agenda-link (and link (org-make-link-string link desc)))
9851 (push (list link desc) org-stored-links)
9852 (message "Stored: %s" (or desc link))
9853 (when custom-id
9854 (setq link (concat "file:" (abbreviate-file-name
9855 (buffer-file-name)) "::#" custom-id))
9856 (push (list link desc) org-stored-links))
9857 (car org-stored-links))))))
9859 (defun org-store-link-props (&rest plist)
9860 "Store link properties, extract names and addresses."
9861 (let (x adr)
9862 (when (setq x (plist-get plist :from))
9863 (setq adr (mail-extract-address-components x))
9864 (setq plist (plist-put plist :fromname (car adr)))
9865 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9866 (when (setq x (plist-get plist :to))
9867 (setq adr (mail-extract-address-components x))
9868 (setq plist (plist-put plist :toname (car adr)))
9869 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9870 (let ((from (plist-get plist :from))
9871 (to (plist-get plist :to)))
9872 (when (and from to org-from-is-user-regexp)
9873 (setq plist
9874 (plist-put plist :fromto
9875 (if (string-match org-from-is-user-regexp from)
9876 (concat "to %t")
9877 (concat "from %f"))))))
9878 (setq org-store-link-plist plist))
9880 (defun org-add-link-props (&rest plist)
9881 "Add these properties to the link property list."
9882 (let (key value)
9883 (while plist
9884 (setq key (pop plist) value (pop plist))
9885 (setq org-store-link-plist
9886 (plist-put org-store-link-plist key value)))))
9888 (defun org-email-link-description (&optional fmt)
9889 "Return the description part of an email link.
9890 This takes information from `org-store-link-plist' and formats it
9891 according to FMT (default from `org-email-link-description-format')."
9892 (setq fmt (or fmt org-email-link-description-format))
9893 (let* ((p org-store-link-plist)
9894 (to (plist-get p :toaddress))
9895 (from (plist-get p :fromaddress))
9896 (table
9897 (list
9898 (cons "%c" (plist-get p :fromto))
9899 (cons "%F" (plist-get p :from))
9900 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9901 (cons "%T" (plist-get p :to))
9902 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9903 (cons "%s" (plist-get p :subject))
9904 (cons "%d" (plist-get p :date))
9905 (cons "%m" (plist-get p :message-id)))))
9906 (when (string-match "%c" fmt)
9907 ;; Check if the user wrote this message
9908 (if (and org-from-is-user-regexp from to
9909 (save-match-data (string-match org-from-is-user-regexp from)))
9910 (setq fmt (replace-match "to %t" t t fmt))
9911 (setq fmt (replace-match "from %f" t t fmt))))
9912 (org-replace-escapes fmt table)))
9914 (defun org-make-org-heading-search-string (&optional string)
9915 "Make search string for the current headline or STRING."
9916 (let ((s (or string
9917 (and (derived-mode-p 'org-mode)
9918 (save-excursion
9919 (org-back-to-heading t)
9920 (org-element-property :raw-value (org-element-at-point))))))
9921 (lines org-context-in-file-links))
9922 (or string (setq s (concat "*" s))) ; Add * for headlines
9923 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9924 (when (and string (integerp lines) (> lines 0))
9925 (let ((slines (org-split-string s "\n")))
9926 (when (< lines (length slines))
9927 (setq s (mapconcat
9928 'identity
9929 (reverse (nthcdr (- (length slines) lines)
9930 (reverse slines))) "\n")))))
9931 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9933 (defun org-make-link-string (link &optional description)
9934 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9935 (unless (string-match "\\S-" link)
9936 (error "Empty link"))
9937 (when (and description
9938 (stringp description)
9939 (not (string-match "\\S-" description)))
9940 (setq description nil))
9941 (when (stringp description)
9942 ;; Remove brackets from the description, they are fatal.
9943 (while (string-match "\\[" description)
9944 (setq description (replace-match "{" t t description)))
9945 (while (string-match "\\]" description)
9946 (setq description (replace-match "}" t t description))))
9947 (when (equal link description)
9948 ;; No description needed, it is identical
9949 (setq description nil))
9950 (when (and (not description)
9951 (not (string-match (org-image-file-name-regexp) link))
9952 (not (equal link (org-link-escape link))))
9953 (setq description (org-extract-attributes link)))
9954 (setq link
9955 (cond ((string-match (org-image-file-name-regexp) link) link)
9956 ((string-match org-link-types-re link)
9957 (concat (match-string 1 link)
9958 (org-link-escape (substring link (match-end 1)))))
9959 (t (org-link-escape link))))
9960 (concat "[[" link "]"
9961 (if description (concat "[" description "]") "")
9962 "]"))
9964 (defconst org-link-escape-chars
9965 ;;%20 %5B %5D
9966 '(?\ ?\[ ?\])
9967 "List of characters that should be escaped in a link when stored to Org.
9968 This is the list that is used for internal purposes.")
9970 (defconst org-link-escape-chars-browser
9971 ;;%20 %22
9972 '(?\ ?\")
9973 "List of characters to be escaped before handing over to the browser.
9974 If you consider using this constant then you probably want to use
9975 the function `org-link-escape-browser' instead. See there why
9976 this constant is a candidate to be removed once Org drops support
9977 for Emacs 24.1 and 24.2.")
9979 (defun org-link-escape (text &optional table merge)
9980 "Return percent escaped representation of TEXT.
9981 TEXT is a string with the text to escape.
9982 Optional argument TABLE is a list with characters that should be
9983 escaped. When nil, `org-link-escape-chars' is used.
9984 If optional argument MERGE is set, merge TABLE into
9985 `org-link-escape-chars'."
9986 ;; Don't escape chars in internal links
9987 (if (string-match "^\\*[[:alnum:]]+" text)
9988 text
9989 (cond
9990 ((and table merge)
9991 (mapc (lambda (defchr)
9992 (unless (member defchr table)
9993 (setq table (cons defchr table))))
9994 org-link-escape-chars))
9995 ((null table)
9996 (setq table org-link-escape-chars)))
9997 (mapconcat
9998 (lambda (char)
9999 (if (or (member char table)
10000 (and (or (< char 32) (= char ?\%) (> char 126))
10001 org-url-hexify-p))
10002 (mapconcat (lambda (sequence-element)
10003 (format "%%%.2X" sequence-element))
10004 (or (encode-coding-char char 'utf-8)
10005 (error "Unable to percent escape character: %s"
10006 (char-to-string char))) "")
10007 (char-to-string char))) text "")))
10009 (defun org-link-escape-browser (text)
10010 "Escape some characters before handing over to the browser.
10011 This function is a candidate to be removed together with the
10012 constant `org-link-escape-chars-browser' once Org drops support
10013 for Emacs 24.1 and 24.2. All calls to this function will have to
10014 be replaced with `url-encode-url' which is available since Emacs
10015 24.3.1."
10016 ;; Example with the Org link
10017 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10018 ;; to open the browser with +subject:"Release 8.2" filled into the
10019 ;; query field: In this case the variable TEXT contains the
10020 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10021 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10022 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10023 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10024 (if (fboundp 'url-encode-url)
10025 (url-encode-url text)
10026 (if (org-string-match-p
10027 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10028 text)
10029 (org-link-escape text org-link-escape-chars-browser)
10030 text)))
10032 (defun org-link-unescape (str)
10033 "Unhex hexified Unicode strings as returned from the JavaScript function
10034 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10035 (unless (and (null str) (string= "" str))
10036 (let ((pos 0) (case-fold-search t) unhexed)
10037 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10038 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10039 (setq str (replace-match unhexed t t str))
10040 (setq pos (+ pos (length unhexed))))))
10041 str)
10043 (defun org-link-unescape-compound (hex)
10044 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10045 Note: this function also decodes single byte encodings like
10046 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10047 (save-match-data
10048 (let* ((bytes (cdr (split-string hex "%")))
10049 (ret "")
10050 (eat 0)
10051 (sum 0))
10052 (while bytes
10053 (let* ((val (string-to-number (pop bytes) 16))
10054 (shift-xor
10055 (if (= 0 eat)
10056 (cond
10057 ((>= val 252) (cons 6 252))
10058 ((>= val 248) (cons 5 248))
10059 ((>= val 240) (cons 4 240))
10060 ((>= val 224) (cons 3 224))
10061 ((>= val 192) (cons 2 192))
10062 (t (cons 0 0)))
10063 (cons 6 128))))
10064 (if (>= val 192) (setq eat (car shift-xor)))
10065 (setq val (logxor val (cdr shift-xor)))
10066 (setq sum (+ (lsh sum (car shift-xor)) val))
10067 (if (> eat 0) (setq eat (- eat 1)))
10068 (cond
10069 ((= 0 eat) ;multi byte
10070 (setq ret (concat ret (org-char-to-string sum)))
10071 (setq sum 0))
10072 ((not bytes) ; single byte(s)
10073 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10074 ret)))
10076 (defun org-link-unescape-single-byte-sequence (hex)
10077 "Unhexify hex-encoded single byte character sequences."
10078 (mapconcat (lambda (byte)
10079 (char-to-string (string-to-number byte 16)))
10080 (cdr (split-string hex "%")) ""))
10082 (defun org-xor (a b)
10083 "Exclusive or."
10084 (if a (not b) b))
10086 (defun org-fixup-message-id-for-http (s)
10087 "Replace special characters in a message id, so it can be used in an http query."
10088 (when (string-match "%" s)
10089 (setq s (mapconcat (lambda (c)
10090 (if (eq c ?%)
10091 "%25"
10092 (char-to-string c)))
10093 s "")))
10094 (while (string-match "<" s)
10095 (setq s (replace-match "%3C" t t s)))
10096 (while (string-match ">" s)
10097 (setq s (replace-match "%3E" t t s)))
10098 (while (string-match "@" s)
10099 (setq s (replace-match "%40" t t s)))
10102 (defun org-link-prettify (link)
10103 "Return a human-readable representation of LINK.
10104 The car of LINK must be a raw link.
10105 The cdr of LINK must be either a link description or nil."
10106 (let ((desc (or (cadr link) "<no description>")))
10107 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10108 "<" (car link) ">")))
10110 ;;;###autoload
10111 (defun org-insert-link-global ()
10112 "Insert a link like Org-mode does.
10113 This command can be called in any mode to insert a link in Org-mode syntax."
10114 (interactive)
10115 (org-load-modules-maybe)
10116 (org-run-like-in-org-mode 'org-insert-link))
10118 (defun org-insert-all-links (arg &optional pre post)
10119 "Insert all links in `org-stored-links'.
10120 When a universal prefix, do not delete the links from `org-stored-links'.
10121 When `ARG' is a number, insert the last N link(s).
10122 `PRE' and `POST' are optional arguments to define a string to
10123 prepend or to append."
10124 (interactive "P")
10125 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10126 (links (copy-seq org-stored-links))
10127 (pr (or pre "- "))
10128 (po (or post "\n"))
10129 (cnt 1) l)
10130 (if (null org-stored-links)
10131 (message "No link to insert")
10132 (while (and (or (listp arg) (>= arg cnt))
10133 (setq l (if (listp arg)
10134 (pop links)
10135 (pop org-stored-links))))
10136 (setq cnt (1+ cnt))
10137 (insert pr)
10138 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10139 (insert po)))))
10141 (defun org-insert-last-stored-link (arg)
10142 "Insert the last link stored in `org-stored-links'."
10143 (interactive "p")
10144 (org-insert-all-links arg "" "\n"))
10146 (defun org-link-fontify-links-to-this-file ()
10147 "Fontify links to the current file in `org-stored-links'."
10148 (let ((f (buffer-file-name)) a b)
10149 (setq a (mapcar (lambda(l)
10150 (let ((ll (car l)))
10151 (when (and (string-match "^file:\\(.+\\)::" ll)
10152 (equal f (expand-file-name (match-string 1 ll))))
10153 ll)))
10154 org-stored-links))
10155 (when (featurep 'org-id)
10156 (setq b (mapcar (lambda(l)
10157 (let ((ll (car l)))
10158 (when (and (string-match "^id:\\(.+\\)$" ll)
10159 (equal f (expand-file-name
10160 (or (org-id-find-id-file
10161 (match-string 1 ll)) ""))))
10162 ll)))
10163 org-stored-links)))
10164 (mapcar (lambda(l)
10165 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10166 (delq nil (append a b)))))
10168 (defvar org-link-links-in-this-file nil)
10169 (defun org-insert-link (&optional complete-file link-location default-description)
10170 "Insert a link. At the prompt, enter the link.
10172 Completion can be used to insert any of the link protocol prefixes like
10173 http or ftp in use.
10175 The history can be used to select a link previously stored with
10176 `org-store-link'. When the empty string is entered (i.e. if you just
10177 press RET at the prompt), the link defaults to the most recently
10178 stored link. As SPC triggers completion in the minibuffer, you need to
10179 use M-SPC or C-q SPC to force the insertion of a space character.
10181 You will also be prompted for a description, and if one is given, it will
10182 be displayed in the buffer instead of the link.
10184 If there is already a link at point, this command will allow you to edit link
10185 and description parts.
10187 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10188 be selected using completion. The path to the file will be relative to the
10189 current directory if the file is in the current directory or a subdirectory.
10190 Otherwise, the link will be the absolute path as completed in the minibuffer
10191 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10192 option `org-link-file-path-type'.
10194 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10195 the current directory or below.
10197 With three \\[universal-argument] prefixes, negate the meaning of
10198 `org-keep-stored-link-after-insertion'.
10200 If `org-make-link-description-function' is non-nil, this function will be
10201 called with the link target, and the result will be the default
10202 link description.
10204 If the LINK-LOCATION parameter is non-nil, this value will be
10205 used as the link location instead of reading one interactively.
10207 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10208 be used as the default description."
10209 (interactive "P")
10210 (let* ((wcf (current-window-configuration))
10211 (origbuf (current-buffer))
10212 (region (if (org-region-active-p)
10213 (buffer-substring (region-beginning) (region-end))))
10214 (remove (and region (list (region-beginning) (region-end))))
10215 (desc region)
10216 tmphist ; byte-compile incorrectly complains about this
10217 (link link-location)
10218 (abbrevs org-link-abbrev-alist-local)
10219 entry file all-prefixes auto-desc)
10220 (cond
10221 (link-location) ; specified by arg, just use it.
10222 ((org-in-regexp org-bracket-link-regexp 1)
10223 ;; We do have a link at point, and we are going to edit it.
10224 (setq remove (list (match-beginning 0) (match-end 0)))
10225 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10226 (setq link (read-string "Link: "
10227 (org-link-unescape
10228 (org-match-string-no-properties 1)))))
10229 ((or (org-in-regexp org-angle-link-re)
10230 (org-in-regexp org-plain-link-re))
10231 ;; Convert to bracket link
10232 (setq remove (list (match-beginning 0) (match-end 0))
10233 link (read-string "Link: "
10234 (org-remove-angle-brackets (match-string 0)))))
10235 ((member complete-file '((4) (16)))
10236 ;; Completing read for file names.
10237 (setq link (org-file-complete-link complete-file)))
10239 ;; Read link, with completion for stored links.
10240 (org-link-fontify-links-to-this-file)
10241 (org-switch-to-buffer-other-window "*Org Links*")
10242 (with-current-buffer "*Org Links*"
10243 (erase-buffer)
10244 (insert "Insert a link.
10245 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10246 (when org-stored-links
10247 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10248 (insert (mapconcat 'org-link-prettify
10249 (reverse org-stored-links) "\n")))
10250 (goto-char (point-min)))
10251 (let ((cw (selected-window)))
10252 (select-window (get-buffer-window "*Org Links*" 'visible))
10253 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10254 (unless (pos-visible-in-window-p (point-max))
10255 (org-fit-window-to-buffer))
10256 (and (window-live-p cw) (select-window cw)))
10257 ;; Fake a link history, containing the stored links.
10258 (setq tmphist (append (mapcar 'car org-stored-links)
10259 org-insert-link-history))
10260 (setq all-prefixes (append (mapcar 'car abbrevs)
10261 (mapcar 'car org-link-abbrev-alist)
10262 org-link-types))
10263 (unwind-protect
10264 (progn
10265 (setq link
10266 (org-completing-read
10267 "Link: "
10268 (append
10269 (mapcar (lambda (x) (concat x ":"))
10270 all-prefixes)
10271 (mapcar 'car org-stored-links))
10272 nil nil nil
10273 'tmphist
10274 (caar org-stored-links)))
10275 (if (not (string-match "\\S-" link))
10276 (user-error "No link selected"))
10277 (mapc (lambda(l)
10278 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10279 org-stored-links)
10280 (if (or (member link all-prefixes)
10281 (and (equal ":" (substring link -1))
10282 (member (substring link 0 -1) all-prefixes)
10283 (setq link (substring link 0 -1))))
10284 (setq link (with-current-buffer origbuf
10285 (org-link-try-special-completion link)))))
10286 (set-window-configuration wcf)
10287 (kill-buffer "*Org Links*"))
10288 (setq entry (assoc link org-stored-links))
10289 (or entry (push link org-insert-link-history))
10290 (setq desc (or desc (nth 1 entry)))))
10292 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10293 (not org-keep-stored-link-after-insertion))
10294 (setq org-stored-links (delq (assoc link org-stored-links)
10295 org-stored-links)))
10297 (if (and (string-match org-plain-link-re link)
10298 (not (string-match org-ts-regexp link)))
10299 ;; URL-like link, normalize the use of angular brackets.
10300 (setq link (org-remove-angle-brackets link)))
10302 ;; Check if we are linking to the current file with a search
10303 ;; option If yes, simplify the link by using only the search
10304 ;; option.
10305 (when (and buffer-file-name
10306 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10307 (let* ((path (match-string 1 link))
10308 (case-fold-search nil)
10309 (search (match-string 2 link)))
10310 (save-match-data
10311 (if (equal (file-truename buffer-file-name) (file-truename path))
10312 ;; We are linking to this same file, with a search option
10313 (setq link search)))))
10315 ;; Check if we can/should use a relative path. If yes, simplify the link
10316 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10317 (let* ((type (match-string 1 link))
10318 (path (match-string 2 link))
10319 (origpath path)
10320 (case-fold-search nil))
10321 (cond
10322 ((or (eq org-link-file-path-type 'absolute)
10323 (equal complete-file '(16)))
10324 (setq path (abbreviate-file-name (expand-file-name path))))
10325 ((eq org-link-file-path-type 'noabbrev)
10326 (setq path (expand-file-name path)))
10327 ((eq org-link-file-path-type 'relative)
10328 (setq path (file-relative-name path)))
10330 (save-match-data
10331 (if (string-match (concat "^" (regexp-quote
10332 (expand-file-name
10333 (file-name-as-directory
10334 default-directory))))
10335 (expand-file-name path))
10336 ;; We are linking a file with relative path name.
10337 (setq path (substring (expand-file-name path)
10338 (match-end 0)))
10339 (setq path (abbreviate-file-name (expand-file-name path)))))))
10340 (setq link (concat type path))
10341 (if (equal desc origpath)
10342 (setq desc path))))
10344 (if org-make-link-description-function
10345 (setq desc
10346 (or (condition-case nil
10347 (funcall org-make-link-description-function link desc)
10348 (error (progn (message "Can't get link description from `%s'"
10349 (symbol-name org-make-link-description-function))
10350 (sit-for 2) nil)))
10351 (read-string "Description: " default-description)))
10352 (if default-description (setq desc default-description)
10353 (setq desc (or (and auto-desc desc)
10354 (read-string "Description: " desc)))))
10356 (unless (string-match "\\S-" desc) (setq desc nil))
10357 (if remove (apply 'delete-region remove))
10358 (insert (org-make-link-string link desc))))
10360 (defun org-link-try-special-completion (type)
10361 "If there is completion support for link type TYPE, offer it."
10362 (let ((fun (intern (concat "org-" type "-complete-link"))))
10363 (if (functionp fun)
10364 (funcall fun)
10365 (read-string "Link (no completion support): " (concat type ":")))))
10367 (defun org-file-complete-link (&optional arg)
10368 "Create a file link using completion."
10369 (let (file link)
10370 (setq file (org-iread-file-name "File: "))
10371 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10372 (pwd1 (file-name-as-directory (abbreviate-file-name
10373 (expand-file-name ".")))))
10374 (cond
10375 ((equal arg '(16))
10376 (setq link (concat
10377 "file:"
10378 (abbreviate-file-name (expand-file-name file)))))
10379 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10380 (setq link (concat "file:" (match-string 1 file))))
10381 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10382 (expand-file-name file))
10383 (setq link (concat
10384 "file:" (match-string 1 (expand-file-name file)))))
10385 (t (setq link (concat "file:" file)))))
10386 link))
10388 (defun org-iread-file-name (&rest args)
10389 "Read-file-name using `ido-mode' speedup if available.
10390 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10391 See `read-file-name' for a description of parameters."
10392 (org-without-partial-completion
10393 (if (and org-completion-use-ido
10394 (fboundp 'ido-read-file-name)
10395 (boundp 'ido-mode) ido-mode
10396 (listp (second args)))
10397 (let ((ido-enter-matching-directory nil))
10398 (apply 'ido-read-file-name args))
10399 (apply 'read-file-name args))))
10401 (defun org-completing-read (&rest args)
10402 "Completing-read with SPACE being a normal character."
10403 (let ((enable-recursive-minibuffers t)
10404 (minibuffer-local-completion-map
10405 (copy-keymap minibuffer-local-completion-map)))
10406 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10407 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10408 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10409 (apply 'org-icompleting-read args)))
10411 (defun org-completing-read-no-i (&rest args)
10412 (let (org-completion-use-ido org-completion-use-iswitchb)
10413 (apply 'org-completing-read args)))
10415 (defun org-iswitchb-completing-read (prompt choices &rest args)
10416 "Use iswitch as a completing-read replacement to choose from choices.
10417 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10418 from."
10419 (let* ((iswitchb-use-virtual-buffers nil)
10420 (iswitchb-make-buflist-hook
10421 (lambda ()
10422 (setq iswitchb-temp-buflist choices))))
10423 (iswitchb-read-buffer prompt)))
10425 (defun org-icompleting-read (&rest args)
10426 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10427 (org-without-partial-completion
10428 (if (and org-completion-use-ido
10429 (fboundp 'ido-completing-read)
10430 (boundp 'ido-mode) ido-mode
10431 (listp (second args)))
10432 (let ((ido-enter-matching-directory nil))
10433 (apply 'ido-completing-read (concat (car args))
10434 (if (consp (car (nth 1 args)))
10435 (mapcar 'car (nth 1 args))
10436 (nth 1 args))
10437 (cddr args)))
10438 (if (and org-completion-use-iswitchb
10439 (boundp 'iswitchb-mode) iswitchb-mode
10440 (listp (second args)))
10441 (apply 'org-iswitchb-completing-read (concat (car args))
10442 (if (consp (car (nth 1 args)))
10443 (mapcar 'car (nth 1 args))
10444 (nth 1 args))
10445 (cddr args))
10446 (apply 'completing-read args)))))
10448 (defun org-extract-attributes (s)
10449 "Extract the attributes cookie from a string and set as text property."
10450 (let (a attr (start 0) key value)
10451 (save-match-data
10452 (when (string-match "{{\\([^}]+\\)}}$" s)
10453 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10454 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10455 (setq key (match-string 1 a) value (match-string 2 a)
10456 start (match-end 0)
10457 attr (plist-put attr (intern key) value))))
10458 (org-add-props s nil 'org-attr attr))
10461 ;;; Opening/following a link
10463 (defvar org-link-search-failed nil)
10465 (defvar org-open-link-functions nil
10466 "Hook for functions finding a plain text link.
10467 These functions must take a single argument, the link content.
10468 They will be called for links that look like [[link text][description]]
10469 when LINK TEXT does not have a protocol like \"http:\" and does not look
10470 like a filename (e.g. \"./blue.png\").
10472 These functions will be called *before* Org attempts to resolve the
10473 link by doing text searches in the current buffer - so if you want a
10474 link \"[[target]]\" to still find \"<<target>>\", your function should
10475 handle this as a special case.
10477 When the function does handle the link, it must return a non-nil value.
10478 If it decides that it is not responsible for this link, it must return
10479 nil to indicate that that Org-mode can continue with other options
10480 like exact and fuzzy text search.")
10482 (defun org-next-link (&optional search-backward)
10483 "Move forward to the next link.
10484 If the link is in hidden text, expose it."
10485 (interactive "P")
10486 (when (and org-link-search-failed (eq this-command last-command))
10487 (goto-char (point-min))
10488 (message "Link search wrapped back to beginning of buffer"))
10489 (setq org-link-search-failed nil)
10490 (let* ((pos (point))
10491 (ct (org-context))
10492 (a (assoc :link ct))
10493 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10494 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10495 ((looking-at org-any-link-re)
10496 ;; Don't stay stuck at link without an org-link face
10497 (forward-char (if search-backward -1 1))))
10498 (if (funcall srch-fun org-any-link-re nil t)
10499 (progn
10500 (goto-char (match-beginning 0))
10501 (if (outline-invisible-p) (org-show-context)))
10502 (goto-char pos)
10503 (setq org-link-search-failed t)
10504 (message "No further link found"))))
10506 (defun org-previous-link ()
10507 "Move backward to the previous link.
10508 If the link is in hidden text, expose it."
10509 (interactive)
10510 (funcall 'org-next-link t))
10512 (defun org-translate-link (s)
10513 "Translate a link string if a translation function has been defined."
10514 (if (and org-link-translation-function
10515 (fboundp org-link-translation-function)
10516 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10517 (progn
10518 (setq s (funcall org-link-translation-function
10519 (match-string 1 s) (match-string 2 s)))
10520 (concat (car s) ":" (cdr s)))
10523 (defun org-translate-link-from-planner (type path)
10524 "Translate a link from Emacs Planner syntax so that Org can follow it.
10525 This is still an experimental function, your mileage may vary."
10526 (cond
10527 ((member type '("http" "https" "news" "ftp"))
10528 ;; standard Internet links are the same.
10529 nil)
10530 ((and (equal type "irc") (string-match "^//" path))
10531 ;; Planner has two / at the beginning of an irc link, we have 1.
10532 ;; We should have zero, actually....
10533 (setq path (substring path 1)))
10534 ((and (equal type "lisp") (string-match "^/" path))
10535 ;; Planner has a slash, we do not.
10536 (setq type "elisp" path (substring path 1)))
10537 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10538 ;; A typical message link. Planner has the id after the final slash,
10539 ;; we separate it with a hash mark
10540 (setq path (concat (match-string 1 path) "#"
10541 (org-remove-angle-brackets (match-string 2 path))))))
10542 (cons type path))
10544 (defun org-find-file-at-mouse (ev)
10545 "Open file link or URL at mouse."
10546 (interactive "e")
10547 (mouse-set-point ev)
10548 (org-open-at-point 'in-emacs))
10550 (defun org-open-at-mouse (ev)
10551 "Open file link or URL at mouse.
10552 See the docstring of `org-open-file' for details."
10553 (interactive "e")
10554 (mouse-set-point ev)
10555 (if (eq major-mode 'org-agenda-mode)
10556 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10557 (org-open-at-point))
10559 (defvar org-window-config-before-follow-link nil
10560 "The window configuration before following a link.
10561 This is saved in case the need arises to restore it.")
10563 (defvar org-open-link-marker (make-marker)
10564 "Marker pointing to the location where `org-open-at-point' was called.")
10566 ;;;###autoload
10567 (defun org-open-at-point-global ()
10568 "Follow a link like Org-mode does.
10569 This command can be called in any mode to follow a link that has
10570 Org-mode syntax."
10571 (interactive)
10572 (org-run-like-in-org-mode 'org-open-at-point))
10574 ;;;###autoload
10575 (defun org-open-link-from-string (s &optional arg reference-buffer)
10576 "Open a link in the string S, as if it was in Org-mode."
10577 (interactive "sLink: \nP")
10578 (let ((reference-buffer (or reference-buffer (current-buffer))))
10579 (with-temp-buffer
10580 (let ((org-inhibit-startup (not reference-buffer)))
10581 (org-mode)
10582 (insert s)
10583 (goto-char (point-min))
10584 (when reference-buffer
10585 (setq org-link-abbrev-alist-local
10586 (with-current-buffer reference-buffer
10587 org-link-abbrev-alist-local)))
10588 (org-open-at-point arg reference-buffer)))))
10590 (defvar org-open-at-point-functions nil
10591 "Hook that is run when following a link at point.
10593 Functions in this hook must return t if they identify and follow
10594 a link at point. If they don't find anything interesting at point,
10595 they must return nil.")
10597 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10598 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10599 (defun org-open-at-point (&optional arg reference-buffer)
10600 "Open link, timestamp, footnote or tags at point.
10602 When point is on a link, follow it. Normally, files will be
10603 opened by an appropriate application. If the optional prefix
10604 argument ARG is non-nil, Emacs will visit the file. With
10605 a double prefix argument, try to open outside of Emacs, in the
10606 application the system uses for this file type.
10608 When point is on a timestamp, open the agenda at the day
10609 specified.
10611 When point is a footnote definition, move to the first reference
10612 found. If it is on a reference, move to the associated
10613 definition.
10615 When point is on a headline, display a list of every link in the
10616 entry, so it is possible to pick one, or all, of them. If point
10617 is on a tag, call `org-tags-view' instead.
10619 When optional argument REFERENCE-BUFFER is non-nil, it should
10620 specify a buffer from where the link search should happen. This
10621 is used internally by `org-open-link-from-string'.
10623 On top of syntactically correct links, this function will open
10624 the link at point in comments or comment blocks and the first
10625 link in a property drawer line."
10626 (interactive "P")
10627 ;; On a code block, open block's results.
10628 (unless (call-interactively 'org-babel-open-src-block-result)
10629 (org-load-modules-maybe)
10630 (move-marker org-open-link-marker (point))
10631 (setq org-window-config-before-follow-link (current-window-configuration))
10632 (org-remove-occur-highlights nil nil t)
10633 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10634 (let* ((context (org-element-context)) type value)
10635 ;; On an unsupported type, check if point is contained within
10636 ;; a support one.
10637 (while (and (not (memq (setq type (org-element-type context))
10638 '(comment comment-block
10639 headline inlinetask link
10640 footnote-definition footnote-reference
10641 node-property timestamp)))
10642 (setq context (org-element-property :parent context))))
10643 (setq value (org-element-property :value context))
10644 (cond
10645 ;; Blank lines at the beginning of buffer: bail out.
10646 ((not context) (user-error "No link found"))
10647 ;; Exception n°1: links in property drawers
10648 ((eq type 'node-property)
10649 (org-open-link-from-string
10650 (and (string-match org-any-link-re value)
10651 (match-string-no-properties 0 value))))
10652 ;; Exception n°2: links in comments.
10653 ((memq type '(comment comment-block))
10654 (save-excursion
10655 (skip-chars-forward "\\S-" (point-at-eol))
10656 (let ((string-rear (replace-regexp-in-string
10657 "^[ \t]*# [ \t]*" ""
10658 (buffer-substring (point) (line-beginning-position))))
10659 (string-front (buffer-substring (point) (line-end-position))))
10660 (with-temp-buffer
10661 (let ((org-inhibit-startup t)) (org-mode))
10662 (insert value)
10663 (goto-char (point-min))
10664 (when (and (search-forward string-rear nil t)
10665 (search-forward string-front (line-end-position) t))
10666 (goto-char (match-beginning 0))
10667 (org-open-at-point)
10668 (when (string= string-rear "") (forward-char)))))))
10669 ;; On a headline or an inlinetask, but not on a timestamp,
10670 ;; a link, a footnote reference or on tags.
10671 ((and (memq type '(headline inlinetask))
10672 ;; Not on tags.
10673 (progn (save-excursion (beginning-of-line)
10674 (looking-at org-complex-heading-regexp))
10675 (or (not (match-beginning 5))
10676 (< (point) (match-beginning 5)))))
10677 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10678 (links (car data))
10679 (links-end (cdr data)))
10680 (if links
10681 (dolist (link (if (stringp links) (list links) links))
10682 (search-forward link nil links-end)
10683 (goto-char (match-beginning 0))
10684 (org-open-at-point))
10685 (require 'org-attach)
10686 (org-attach-reveal 'if-exists))))
10687 ;; Do nothing on white spaces after an object, unless point
10688 ;; is right after it.
10689 ((> (point)
10690 (save-excursion
10691 (goto-char (org-element-property :end context))
10692 (skip-chars-backward " \t")
10693 (point)))
10694 (user-error "No link found"))
10695 ((eq type 'timestamp) (org-follow-timestamp-link))
10696 ;; On tags within a headline or an inlinetask.
10697 ((and (memq type '(headline inlinetask))
10698 (progn (save-excursion (beginning-of-line)
10699 (looking-at org-complex-heading-regexp))
10700 (and (match-beginning 5)
10701 (>= (point) (match-beginning 5)))))
10702 (org-tags-view arg (substring (match-string 5) 0 -1)))
10703 ((eq type 'link)
10704 (let ((type (org-element-property :type context))
10705 (path (org-link-unescape (org-element-property :path context))))
10706 ;; Switch back to REFERENCE-BUFFER needed when called in
10707 ;; a temporary buffer through `org-open-link-from-string'.
10708 (with-current-buffer (or reference-buffer (current-buffer))
10709 (cond
10710 ((equal type "file")
10711 (if (string-match "[*?{]" (file-name-nondirectory path))
10712 (dired path)
10713 ;; Look into `org-link-protocols' in order to find
10714 ;; a DEDICATED-FUNCTION to open file. The function
10715 ;; will be applied on raw link instead of parsed
10716 ;; link due to the limitation in `org-add-link-type'
10717 ;; ("open" function called with a single argument).
10718 ;; If no such function is found, fallback to
10719 ;; `org-open-file'.
10721 ;; Note : "file+emacs" and "file+sys" types are
10722 ;; hard-coded in order to escape the previous
10723 ;; limitation.
10724 (let* ((option (org-element-property :search-option context))
10725 (app (org-element-property :application context))
10726 (dedicated-function
10727 (nth 1 (assoc app org-link-protocols))))
10728 (if dedicated-function
10729 (funcall dedicated-function
10730 (concat path
10731 (and option (concat "::" option))))
10732 (apply 'org-open-file
10733 path
10734 (cond (arg)
10735 ((equal app "emacs") 'emacs)
10736 ((equal app "sys") 'system))
10737 (cond ((not option) nil)
10738 ((org-string-match-p "\\`[0-9]+\\'" option)
10739 (list (string-to-number option)))
10740 (t (list nil
10741 (org-link-unescape option)))))))))
10742 ((assoc type org-link-protocols)
10743 (funcall (nth 1 (assoc type org-link-protocols)) path))
10744 ((equal type "help")
10745 (let ((f-or-v (intern path)))
10746 (cond ((fboundp f-or-v) (describe-function f-or-v))
10747 ((boundp f-or-v) (describe-variable f-or-v))
10748 (t (error "Not a known function or variable")))))
10749 ((member type '("http" "https" "ftp" "mailto" "news"))
10750 (browse-url (org-link-escape-browser (concat type ":" path))))
10751 ((equal type "doi")
10752 (browse-url
10753 (org-link-escape-browser (concat org-doi-server-url path))))
10754 ((equal type "message") (browse-url (concat type ":" path)))
10755 ((equal type "shell")
10756 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10757 (cmd path))
10758 (if (or (and (org-string-nw-p
10759 org-confirm-shell-link-not-regexp)
10760 (string-match
10761 org-confirm-shell-link-not-regexp cmd))
10762 (not org-confirm-shell-link-function)
10763 (funcall org-confirm-shell-link-function
10764 (format "Execute \"%s\" in shell? "
10765 (org-add-props cmd nil
10766 'face 'org-warning))))
10767 (progn
10768 (message "Executing %s" cmd)
10769 (shell-command cmd buf)
10770 (when (featurep 'midnight)
10771 (setq clean-buffer-list-kill-buffer-names
10772 (cons buf
10773 clean-buffer-list-kill-buffer-names))))
10774 (user-error "Abort"))))
10775 ((equal type "elisp")
10776 (let ((cmd path))
10777 (if (or (and (org-string-nw-p
10778 org-confirm-elisp-link-not-regexp)
10779 (org-string-match-p
10780 org-confirm-elisp-link-not-regexp cmd))
10781 (not org-confirm-elisp-link-function)
10782 (funcall org-confirm-elisp-link-function
10783 (format "Execute \"%s\" as elisp? "
10784 (org-add-props cmd nil
10785 'face 'org-warning))))
10786 (message "%s => %s" cmd
10787 (if (eq (string-to-char cmd) ?\()
10788 (eval (read cmd))
10789 (call-interactively (read cmd))))
10790 (user-error "Abort"))))
10791 ((equal type "id")
10792 (require 'ord-id)
10793 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10794 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10795 (unless (run-hook-with-args-until-success
10796 'org-open-link-functions path)
10797 (if (not arg) (org-mark-ring-push)
10798 (switch-to-buffer-other-window
10799 (org-get-buffer-for-internal-link (current-buffer))))
10800 (let ((cmd `(org-link-search
10801 ,(if (member type '("custom-id" "coderef"))
10802 (org-element-property :raw-link context)
10803 path)
10804 ,(cond ((equal arg '(4)) 'occur)
10805 ((equal arg '(16)) 'org-occur))
10806 ,(org-element-property :begin context))))
10807 (condition-case nil
10808 (let ((org-link-search-inhibit-query t))
10809 (eval cmd))
10810 (error (progn (widen) (eval cmd)))))))
10811 (t (browse-url-at-point))))))
10812 ;; On a footnote reference or at a footnote definition's label.
10813 ((or (eq type 'footnote-reference)
10814 (and (eq type 'footnote-definition)
10815 (save-excursion
10816 ;; Do not validate action when point is on the
10817 ;; spaces right after the footnote label, in
10818 ;; order to be on par with behaviour on links.
10819 (skip-chars-forward " \t")
10820 (let ((begin
10821 (org-element-property :contents-begin context)))
10822 (if begin (< (point) begin)
10823 (= (org-element-property :post-affiliated context)
10824 (line-beginning-position)))))))
10825 (org-footnote-action))
10826 (t (user-error "No link found")))))
10827 (move-marker org-open-link-marker nil)
10828 (run-hook-with-args 'org-follow-link-hook)))
10830 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10831 "Offer links in the current entry and return the selected link.
10832 If there is only one link, return it.
10833 If NTH is an integer, return the NTH link found.
10834 If ZERO is a string, check also this string for a link, and if
10835 there is one, return it."
10836 (with-current-buffer buffer
10837 (save-excursion
10838 (save-restriction
10839 (widen)
10840 (goto-char marker)
10841 (let ((cnt ?0)
10842 (in-emacs (if (integerp nth) nil nth))
10843 have-zero end links link c)
10844 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10845 (push (match-string 0 zero) links)
10846 (setq cnt (1- cnt) have-zero t))
10847 (save-excursion
10848 (org-back-to-heading t)
10849 (setq end (save-excursion (outline-next-heading) (point)))
10850 (while (re-search-forward org-any-link-re end t)
10851 (push (match-string 0) links))
10852 (setq links (org-uniquify (reverse links))))
10853 (cond
10854 ((null links)
10855 (message "No links"))
10856 ((equal (length links) 1)
10857 (setq link (car links)))
10858 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10859 (setq link (nth (if have-zero nth (1- nth)) links)))
10860 (t ; we have to select a link
10861 (save-excursion
10862 (save-window-excursion
10863 (delete-other-windows)
10864 (with-output-to-temp-buffer "*Select Link*"
10865 (mapc (lambda (l)
10866 (if (not (string-match org-bracket-link-regexp l))
10867 (princ (format "[%c] %s\n" (incf cnt)
10868 (org-remove-angle-brackets l)))
10869 (if (match-end 3)
10870 (princ (format "[%c] %s (%s)\n" (incf cnt)
10871 (match-string 3 l) (match-string 1 l)))
10872 (princ (format "[%c] %s\n" (incf cnt)
10873 (match-string 1 l))))))
10874 links))
10875 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10876 (message "Select link to open, RET to open all:")
10877 (setq c (read-char-exclusive))
10878 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10879 (when (equal c ?q) (user-error "Abort"))
10880 (if (equal c ?\C-m)
10881 (setq link links)
10882 (setq nth (- c ?0))
10883 (if have-zero (setq nth (1+ nth)))
10884 (unless (and (integerp nth) (>= (length links) nth))
10885 (user-error "Invalid link selection"))
10886 (setq link (nth (1- nth) links)))))
10887 (cons link end))))))
10889 ;; TODO: These functions are deprecated since `org-open-at-point'
10890 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10891 (defun org-open-file-with-system (path)
10892 "Open file at PATH using the system way of opening it."
10893 (org-open-file path 'system))
10894 (defun org-open-file-with-emacs (path)
10895 "Open file at PATH in Emacs."
10896 (org-open-file path 'emacs))
10899 ;;; File search
10901 (defvar org-create-file-search-functions nil
10902 "List of functions to construct the right search string for a file link.
10903 These functions are called in turn with point at the location to
10904 which the link should point.
10906 A function in the hook should first test if it would like to
10907 handle this file type, for example by checking the `major-mode'
10908 or the file extension. If it decides not to handle this file, it
10909 should just return nil to give other functions a chance. If it
10910 does handle the file, it must return the search string to be used
10911 when following the link. The search string will be part of the
10912 file link, given after a double colon, and `org-open-at-point'
10913 will automatically search for it. If special measures must be
10914 taken to make the search successful, another function should be
10915 added to the companion hook `org-execute-file-search-functions',
10916 which see.
10918 A function in this hook may also use `setq' to set the variable
10919 `description' to provide a suggestion for the descriptive text to
10920 be used for this link when it gets inserted into an Org-mode
10921 buffer with \\[org-insert-link].")
10923 (defvar org-execute-file-search-functions nil
10924 "List of functions to execute a file search triggered by a link.
10926 Functions added to this hook must accept a single argument, the
10927 search string that was part of the file link, the part after the
10928 double colon. The function must first check if it would like to
10929 handle this search, for example by checking the `major-mode' or
10930 the file extension. If it decides not to handle this search, it
10931 should just return nil to give other functions a chance. If it
10932 does handle the search, it must return a non-nil value to keep
10933 other functions from trying.
10935 Each function can access the current prefix argument through the
10936 variable `current-prefix-arg'. Note that a single prefix is used
10937 to force opening a link in Emacs, so it may be good to only use a
10938 numeric or double prefix to guide the search function.
10940 In case this is needed, a function in this hook can also restore
10941 the window configuration before `org-open-at-point' was called using:
10943 (set-window-configuration org-window-config-before-follow-link)")
10945 (defun org-link-search (s &optional type avoid-pos stealth)
10946 "Search for a link search option.
10947 If S is surrounded by forward slashes, it is interpreted as a
10948 regular expression. In org-mode files, this will create an `org-occur'
10949 sparse tree. In ordinary files, `occur' will be used to list matches.
10950 If the current buffer is in `dired-mode', grep will be used to search
10951 in all files. If AVOID-POS is given, ignore matches near that position.
10953 When optional argument STEALTH is non-nil, do not modify
10954 visibility around point, thus ignoring
10955 `org-show-hierarchy-above', `org-show-following-heading' and
10956 `org-show-siblings' variables."
10957 (let ((case-fold-search t)
10958 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10959 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10960 (append '(("") (" ") ("\t") ("\n"))
10961 org-emphasis-alist)
10962 "\\|") "\\)"))
10963 (pos (point))
10964 (pre nil) (post nil)
10965 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10966 (cond
10967 ;; First check if there are any special search functions
10968 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10969 ;; Now try the builtin stuff
10970 ((and (equal (string-to-char s0) ?#)
10971 (> (length s0) 1)
10972 (save-excursion
10973 (goto-char (point-min))
10974 (and
10975 (re-search-forward
10976 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10977 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10978 (setq type 'dedicated
10979 pos (match-beginning 0))))
10980 ;; There is an exact target for this
10981 (goto-char pos)
10982 (org-back-to-heading t)))
10983 ((save-excursion
10984 (goto-char (point-min))
10985 (and
10986 (re-search-forward
10987 (concat "<<" (regexp-quote s0) ">>") nil t)
10988 (setq type 'dedicated
10989 pos (match-beginning 0))))
10990 ;; There is an exact target for this
10991 (goto-char pos))
10992 ((save-excursion
10993 (goto-char (point-min))
10994 (and
10995 (re-search-forward
10996 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10997 (setq type 'dedicated pos (match-beginning 0))))
10998 ;; Found an element with a matching #+name affiliated keyword.
10999 (goto-char pos))
11000 ((and (string-match "^(\\(.*\\))$" s0)
11001 (save-excursion
11002 (goto-char (point-min))
11003 (and
11004 (re-search-forward
11005 (concat "[^[]" (regexp-quote
11006 (format org-coderef-label-format
11007 (match-string 1 s0))))
11008 nil t)
11009 (setq type 'dedicated
11010 pos (1+ (match-beginning 0))))))
11011 ;; There is a coderef target for this
11012 (goto-char pos))
11013 ((string-match "^/\\(.*\\)/$" s)
11014 ;; A regular expression
11015 (cond
11016 ((derived-mode-p 'org-mode)
11017 (org-occur (match-string 1 s)))
11018 (t (org-do-occur (match-string 1 s)))))
11019 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11020 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11021 (goto-char (point-min))
11022 (cond
11023 ((let (case-fold-search)
11024 (re-search-forward (format org-complex-heading-regexp-format
11025 (regexp-quote s))
11026 nil t))
11027 ;; OK, found a match
11028 (setq type 'dedicated)
11029 (goto-char (match-beginning 0)))
11030 ((and (not org-link-search-inhibit-query)
11031 (eq org-link-search-must-match-exact-headline 'query-to-create)
11032 (y-or-n-p "No match - create this as a new heading? "))
11033 (goto-char (point-max))
11034 (or (bolp) (newline))
11035 (insert "* " s "\n")
11036 (beginning-of-line 0))
11038 (goto-char pos)
11039 (error "No match"))))
11041 ;; A normal search string
11042 (when (equal (string-to-char s) ?*)
11043 ;; Anchor on headlines, post may include tags.
11044 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11045 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11046 s (substring s 1)))
11047 (remove-text-properties
11048 0 (length s)
11049 '(face nil mouse-face nil keymap nil fontified nil) s)
11050 ;; Make a series of regular expressions to find a match
11051 (setq words (org-split-string s "[ \n\r\t]+")
11053 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11054 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11055 "\\)" markers)
11056 re2a_ (concat "\\(" (mapconcat 'downcase words
11057 "[ \t\r\n]+") "\\)[ \t\r\n]")
11058 re2a (concat "[ \t\r\n]" re2a_)
11059 re4_ (concat "\\(" (mapconcat 'downcase words
11060 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11061 re4 (concat "[^a-zA-Z_]" re4_)
11063 re1 (concat pre re2 post)
11064 re3 (concat pre (if pre re4_ re4) post)
11065 re5 (concat pre ".*" re4)
11066 re2 (concat pre re2)
11067 re2a (concat pre (if pre re2a_ re2a))
11068 re4 (concat pre (if pre re4_ re4))
11069 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11070 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11071 re5 "\\)"))
11072 (cond
11073 ((eq type 'org-occur) (org-occur reall))
11074 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11075 (t (goto-char (point-min))
11076 (setq type 'fuzzy)
11077 (if (or (and (org-search-not-self 1 re0 nil t)
11078 (setq type 'dedicated))
11079 (org-search-not-self 1 re1 nil t)
11080 (org-search-not-self 1 re2 nil t)
11081 (org-search-not-self 1 re2a nil t)
11082 (org-search-not-self 1 re3 nil t)
11083 (org-search-not-self 1 re4 nil t)
11084 (org-search-not-self 1 re5 nil t))
11085 (goto-char (match-beginning 1))
11086 (goto-char pos)
11087 (error "No match"))))))
11088 (and (derived-mode-p 'org-mode)
11089 (not stealth)
11090 (org-show-context 'link-search))
11091 type))
11093 (defun org-search-not-self (group &rest args)
11094 "Execute `re-search-forward', but only accept matches that do not
11095 enclose the position of `org-open-link-marker'."
11096 (let ((m org-open-link-marker))
11097 (catch 'exit
11098 (while (apply 're-search-forward args)
11099 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11100 (goto-char (match-end group))
11101 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11102 (> (match-beginning 0) (marker-position m))
11103 (< (match-end 0) (marker-position m)))
11104 (save-match-data
11105 (or (not (org-in-regexp
11106 org-bracket-link-analytic-regexp 1))
11107 (not (match-end 4)) ; no description
11108 (and (<= (match-beginning 4) (point))
11109 (>= (match-end 4) (point))))))
11110 (throw 'exit (point))))))))
11112 (defun org-get-buffer-for-internal-link (buffer)
11113 "Return a buffer to be used for displaying the link target of internal links."
11114 (cond
11115 ((not org-display-internal-link-with-indirect-buffer)
11116 buffer)
11117 ((string-match "(Clone)$" (buffer-name buffer))
11118 (message "Buffer is already a clone, not making another one")
11119 ;; we also do not modify visibility in this case
11120 buffer)
11121 (t ; make a new indirect buffer for displaying the link
11122 (let* ((bn (buffer-name buffer))
11123 (ibn (concat bn "(Clone)"))
11124 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11125 (with-current-buffer ib (org-overview))
11126 ib))))
11128 (defun org-do-occur (regexp &optional cleanup)
11129 "Call the Emacs command `occur'.
11130 If CLEANUP is non-nil, remove the printout of the regular expression
11131 in the *Occur* buffer. This is useful if the regex is long and not useful
11132 to read."
11133 (occur regexp)
11134 (when cleanup
11135 (let ((cwin (selected-window)) win beg end)
11136 (when (setq win (get-buffer-window "*Occur*"))
11137 (select-window win))
11138 (goto-char (point-min))
11139 (when (re-search-forward "match[a-z]+" nil t)
11140 (setq beg (match-end 0))
11141 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11142 (setq end (1- (match-beginning 0)))))
11143 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11144 (goto-char (point-min))
11145 (select-window cwin))))
11147 ;;; The mark ring for links jumps
11149 (defvar org-mark-ring nil
11150 "Mark ring for positions before jumps in Org-mode.")
11151 (defvar org-mark-ring-last-goto nil
11152 "Last position in the mark ring used to go back.")
11153 ;; Fill and close the ring
11154 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11155 (loop for i from 1 to org-mark-ring-length do
11156 (push (make-marker) org-mark-ring))
11157 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11158 org-mark-ring)
11160 (defun org-mark-ring-push (&optional pos buffer)
11161 "Put the current position or POS into the mark ring and rotate it."
11162 (interactive)
11163 (setq pos (or pos (point)))
11164 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11165 (move-marker (car org-mark-ring)
11166 (or pos (point))
11167 (or buffer (current-buffer)))
11168 (message "%s"
11169 (substitute-command-keys
11170 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11172 (defun org-mark-ring-goto (&optional n)
11173 "Jump to the previous position in the mark ring.
11174 With prefix arg N, jump back that many stored positions. When
11175 called several times in succession, walk through the entire ring.
11176 Org-mode commands jumping to a different position in the current file,
11177 or to another Org-mode file, automatically push the old position
11178 onto the ring."
11179 (interactive "p")
11180 (let (p m)
11181 (if (eq last-command this-command)
11182 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11183 (setq p org-mark-ring))
11184 (setq org-mark-ring-last-goto p)
11185 (setq m (car p))
11186 (org-pop-to-buffer-same-window (marker-buffer m))
11187 (goto-char m)
11188 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11190 (defun org-remove-angle-brackets (s)
11191 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11192 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11194 (defun org-add-angle-brackets (s)
11195 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11196 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11198 (defun org-remove-double-quotes (s)
11199 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11200 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11203 ;;; Following specific links
11205 (defun org-follow-timestamp-link ()
11206 "Open an agenda view for the time-stamp date/range at point."
11207 (cond
11208 ((org-at-date-range-p t)
11209 (let ((org-agenda-start-on-weekday)
11210 (t1 (match-string 1))
11211 (t2 (match-string 2)) tt1 tt2)
11212 (setq tt1 (time-to-days (org-time-string-to-time t1))
11213 tt2 (time-to-days (org-time-string-to-time t2)))
11214 (let ((org-agenda-buffer-tmp-name
11215 (format "*Org Agenda(a:%s)"
11216 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11217 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11218 ((org-at-timestamp-p t)
11219 (let ((org-agenda-buffer-tmp-name
11220 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11221 (org-agenda-list nil (time-to-days (org-time-string-to-time
11222 (substring (match-string 1) 0 10)))
11223 1)))
11224 (t (error "This should not happen"))))
11227 ;;; Following file links
11228 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11229 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11230 (declare-function mailcap-mime-info
11231 "mailcap" (string &optional request no-decode))
11232 (defvar org-wait nil)
11233 (defun org-open-file (path &optional in-emacs line search)
11234 "Open the file at PATH.
11235 First, this expands any special file name abbreviations. Then the
11236 configuration variable `org-file-apps' is checked if it contains an
11237 entry for this file type, and if yes, the corresponding command is launched.
11239 If no application is found, Emacs simply visits the file.
11241 With optional prefix argument IN-EMACS, Emacs will visit the file.
11242 With a double \\[universal-argument] \\[universal-argument] \
11243 prefix arg, Org tries to avoid opening in Emacs
11244 and to use an external application to visit the file.
11246 Optional LINE specifies a line to go to, optional SEARCH a string
11247 to search for. If LINE or SEARCH is given, the file will be
11248 opened in Emacs, unless an entry from org-file-apps that makes
11249 use of groups in a regexp matches.
11251 If you want to change the way frames are used when following a
11252 link, please customize `org-link-frame-setup'.
11254 If the file does not exist, an error is thrown."
11255 (let* ((file (if (equal path "")
11256 buffer-file-name
11257 (substitute-in-file-name (expand-file-name path))))
11258 (file-apps (append org-file-apps (org-default-apps)))
11259 (apps (org-remove-if
11260 'org-file-apps-entry-match-against-dlink-p file-apps))
11261 (apps-dlink (org-remove-if-not
11262 'org-file-apps-entry-match-against-dlink-p file-apps))
11263 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11264 (dirp (if remp nil (file-directory-p file)))
11265 (file (if (and dirp org-open-directory-means-index-dot-org)
11266 (concat (file-name-as-directory file) "index.org")
11267 file))
11268 (a-m-a-p (assq 'auto-mode apps))
11269 (dfile (downcase file))
11270 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11271 (link (cond ((and (eq line nil)
11272 (eq search nil))
11273 file)
11274 (line
11275 (concat file "::" (number-to-string line)))
11276 (search
11277 (concat file "::" search))))
11278 (dlink (downcase link))
11279 (old-buffer (current-buffer))
11280 (old-pos (point))
11281 (old-mode major-mode)
11282 ext cmd link-match-data)
11283 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11284 (setq ext (match-string 1 dfile))
11285 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11286 (setq ext (match-string 1 dfile))))
11287 (cond
11288 ((member in-emacs '((16) system))
11289 (setq cmd (cdr (assoc 'system apps))))
11290 (in-emacs (setq cmd 'emacs))
11292 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11293 (and dirp (cdr (assoc 'directory apps)))
11294 ; first, try matching against apps-dlink
11295 ; if we get a match here, store the match data for later
11296 (let ((match (assoc-default dlink apps-dlink
11297 'string-match)))
11298 (if match
11299 (progn (setq link-match-data (match-data))
11300 match)
11301 (progn (setq in-emacs (or in-emacs line search))
11302 nil))) ; if we have no match in apps-dlink,
11303 ; always open the file in emacs if line or search
11304 ; is given (for backwards compatibility)
11305 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11306 'string-match)
11307 (cdr (assoc ext apps))
11308 (cdr (assoc t apps))))))
11309 (when (eq cmd 'system)
11310 (setq cmd (cdr (assoc 'system apps))))
11311 (when (eq cmd 'default)
11312 (setq cmd (cdr (assoc t apps))))
11313 (when (eq cmd 'mailcap)
11314 (require 'mailcap)
11315 (mailcap-parse-mailcaps)
11316 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11317 (command (mailcap-mime-info mime-type)))
11318 (if (stringp command)
11319 (setq cmd command)
11320 (setq cmd 'emacs))))
11321 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11322 (not (file-exists-p file))
11323 (not org-open-non-existing-files))
11324 (user-error "No such file: %s" file))
11325 (cond
11326 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11327 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11328 (while (string-match "['\"]%s['\"]" cmd)
11329 (setq cmd (replace-match "%s" t t cmd)))
11330 (while (string-match "%s" cmd)
11331 (setq cmd (replace-match
11332 (save-match-data
11333 (shell-quote-argument
11334 (convert-standard-filename file)))
11335 t t cmd)))
11337 ;; Replace "%1", "%2" etc. in command with group matches from regex
11338 (save-match-data
11339 (let ((match-index 1)
11340 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11341 (set-match-data link-match-data)
11342 (while (<= match-index number-of-groups)
11343 (let ((regex (concat "%" (number-to-string match-index)))
11344 (replace-with (match-string match-index dlink)))
11345 (while (string-match regex cmd)
11346 (setq cmd (replace-match replace-with t t cmd))))
11347 (setq match-index (+ match-index 1)))))
11349 (save-window-excursion
11350 (message "Running %s...done" cmd)
11351 (start-process-shell-command cmd nil cmd)
11352 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11353 ((or (stringp cmd)
11354 (eq cmd 'emacs))
11355 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11356 (widen)
11357 (if line (progn (org-goto-line line)
11358 (if (derived-mode-p 'org-mode)
11359 (org-reveal)))
11360 (if search (org-link-search search))))
11361 ((consp cmd)
11362 (let ((file (convert-standard-filename file)))
11363 (save-match-data
11364 (set-match-data link-match-data)
11365 (eval cmd))))
11366 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11367 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11368 (or (not (equal old-buffer (current-buffer)))
11369 (not (equal old-pos (point))))
11370 (org-mark-ring-push old-pos old-buffer))))
11372 (defun org-file-apps-entry-match-against-dlink-p (entry)
11373 "This function returns non-nil if `entry' uses a regular
11374 expression which should be matched against the whole link by
11375 org-open-file.
11377 It assumes that is the case when the entry uses a regular
11378 expression which has at least one grouping construct and the
11379 action is either a lisp form or a command string containing
11380 '%1', i.e. using at least one subexpression match as a
11381 parameter."
11382 (let ((selector (car entry))
11383 (action (cdr entry)))
11384 (if (stringp selector)
11385 (and (> (regexp-opt-depth selector) 0)
11386 (or (and (stringp action)
11387 (string-match "%[0-9]" action))
11388 (consp action)))
11389 nil)))
11391 (defun org-default-apps ()
11392 "Return the default applications for this operating system."
11393 (cond
11394 ((eq system-type 'darwin)
11395 org-file-apps-defaults-macosx)
11396 ((eq system-type 'windows-nt)
11397 org-file-apps-defaults-windowsnt)
11398 (t org-file-apps-defaults-gnu)))
11400 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11401 "Convert extensions to regular expressions in the cars of LIST.
11402 Also, weed out any non-string entries, because the return value is used
11403 only for regexp matching.
11404 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11405 point to the symbol `emacs', indicating that the file should
11406 be opened in Emacs."
11407 (append
11408 (delq nil
11409 (mapcar (lambda (x)
11410 (if (not (stringp (car x)))
11412 (if (string-match "\\W" (car x))
11414 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11415 list))
11416 (if add-auto-mode
11417 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11419 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11420 (defun org-file-remote-p (file)
11421 "Test whether FILE specifies a location on a remote system.
11422 Return non-nil if the location is indeed remote.
11424 For example, the filename \"/user@host:/foo\" specifies a location
11425 on the system \"/user@host:\"."
11426 (cond ((fboundp 'file-remote-p)
11427 (file-remote-p file))
11428 ((fboundp 'tramp-handle-file-remote-p)
11429 (tramp-handle-file-remote-p file))
11430 ((and (boundp 'ange-ftp-name-format)
11431 (string-match (car ange-ftp-name-format) file))
11432 t)))
11435 ;;;; Refiling
11437 (defun org-get-org-file ()
11438 "Read a filename, with default directory `org-directory'."
11439 (let ((default (or org-default-notes-file remember-data-file)))
11440 (read-file-name (format "File name [%s]: " default)
11441 (file-name-as-directory org-directory)
11442 default)))
11444 (defun org-notes-order-reversed-p ()
11445 "Check if the current file should receive notes in reversed order."
11446 (cond
11447 ((not org-reverse-note-order) nil)
11448 ((eq t org-reverse-note-order) t)
11449 ((not (listp org-reverse-note-order)) nil)
11450 (t (catch 'exit
11451 (let ((all org-reverse-note-order)
11452 entry)
11453 (while (setq entry (pop all))
11454 (if (string-match (car entry) buffer-file-name)
11455 (throw 'exit (cdr entry))))
11456 nil)))))
11458 (defvar org-refile-target-table nil
11459 "The list of refile targets, created by `org-refile'.")
11461 (defvar org-agenda-new-buffers nil
11462 "Buffers created to visit agenda files.")
11464 (defvar org-refile-cache nil
11465 "Cache for refile targets.")
11467 (defvar org-refile-markers nil
11468 "All the markers used for caching refile locations.")
11470 (defun org-refile-marker (pos)
11471 "Get a new refile marker, but only if caching is in use."
11472 (if (not org-refile-use-cache)
11474 (let ((m (make-marker)))
11475 (move-marker m pos)
11476 (push m org-refile-markers)
11477 m)))
11479 (defun org-refile-cache-clear ()
11480 "Clear the refile cache and disable all the markers."
11481 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11482 (setq org-refile-markers nil)
11483 (setq org-refile-cache nil)
11484 (message "Refile cache has been cleared"))
11486 (defun org-refile-cache-check-set (set)
11487 "Check if all the markers in the cache still have live buffers."
11488 (let (marker)
11489 (catch 'exit
11490 (while (and set (setq marker (nth 3 (pop set))))
11491 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11492 (when (and marker (null (marker-buffer marker)))
11493 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11494 (sit-for 3)
11495 (throw 'exit nil)))
11496 t)))
11498 (defun org-refile-cache-put (set &rest identifiers)
11499 "Push the refile targets SET into the cache, under IDENTIFIERS."
11500 (let* ((key (sha1 (prin1-to-string identifiers)))
11501 (entry (assoc key org-refile-cache)))
11502 (if entry
11503 (setcdr entry set)
11504 (push (cons key set) org-refile-cache))))
11506 (defun org-refile-cache-get (&rest identifiers)
11507 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11508 (cond
11509 ((not org-refile-cache) nil)
11510 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11512 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11513 org-refile-cache))))
11514 (and set (org-refile-cache-check-set set) set)))))
11516 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11517 "Produce a table with refile targets."
11518 (let ((case-fold-search nil)
11519 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11520 (entries (or org-refile-targets '((nil . (:level . 1)))))
11521 targets tgs txt re files f desc descre fast-path-p level pos0)
11522 (message "Getting targets...")
11523 (with-current-buffer (or default-buffer (current-buffer))
11524 (while (setq entry (pop entries))
11525 (setq files (car entry) desc (cdr entry))
11526 (setq fast-path-p nil)
11527 (cond
11528 ((null files) (setq files (list (current-buffer))))
11529 ((eq files 'org-agenda-files)
11530 (setq files (org-agenda-files 'unrestricted)))
11531 ((and (symbolp files) (fboundp files))
11532 (setq files (funcall files)))
11533 ((and (symbolp files) (boundp files))
11534 (setq files (symbol-value files))))
11535 (if (stringp files) (setq files (list files)))
11536 (cond
11537 ((eq (car desc) :tag)
11538 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11539 ((eq (car desc) :todo)
11540 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11541 ((eq (car desc) :regexp)
11542 (setq descre (cdr desc)))
11543 ((eq (car desc) :level)
11544 (setq descre (concat "^\\*\\{" (number-to-string
11545 (if org-odd-levels-only
11546 (1- (* 2 (cdr desc)))
11547 (cdr desc)))
11548 "\\}[ \t]")))
11549 ((eq (car desc) :maxlevel)
11550 (setq fast-path-p t)
11551 (setq descre (concat "^\\*\\{1," (number-to-string
11552 (if org-odd-levels-only
11553 (1- (* 2 (cdr desc)))
11554 (cdr desc)))
11555 "\\}[ \t]")))
11556 (t (error "Bad refiling target description %s" desc)))
11557 (while (setq f (pop files))
11558 (with-current-buffer
11559 (if (bufferp f) f (org-get-agenda-file-buffer f))
11561 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11562 (progn
11563 (if (bufferp f) (setq f (buffer-file-name
11564 (buffer-base-buffer f))))
11565 (setq f (and f (expand-file-name f)))
11566 (if (eq org-refile-use-outline-path 'file)
11567 (push (list (file-name-nondirectory f) f nil nil) tgs))
11568 (save-excursion
11569 (save-restriction
11570 (widen)
11571 (goto-char (point-min))
11572 (while (re-search-forward descre nil t)
11573 (goto-char (setq pos0 (point-at-bol)))
11574 (catch 'next
11575 (when org-refile-target-verify-function
11576 (save-match-data
11577 (or (funcall org-refile-target-verify-function)
11578 (throw 'next t))))
11579 (when (and (looking-at org-complex-heading-regexp)
11580 (not (member (match-string 4) excluded-entries))
11581 (match-string 4))
11582 (setq level (org-reduced-level
11583 (- (match-end 1) (match-beginning 1)))
11584 txt (org-link-display-format (match-string 4))
11585 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11586 re (format org-complex-heading-regexp-format
11587 (regexp-quote (match-string 4))))
11588 (when org-refile-use-outline-path
11589 (setq txt (mapconcat
11590 'org-protect-slash
11591 (append
11592 (if (eq org-refile-use-outline-path
11593 'file)
11594 (list (file-name-nondirectory
11595 (buffer-file-name
11596 (buffer-base-buffer))))
11597 (if (eq org-refile-use-outline-path
11598 'full-file-path)
11599 (list (buffer-file-name
11600 (buffer-base-buffer)))))
11601 (org-get-outline-path fast-path-p
11602 level txt)
11603 (list txt))
11604 "/")))
11605 (push (list txt f re (org-refile-marker (point)))
11606 tgs)))
11607 (when (= (point) pos0)
11608 ;; verification function has not moved point
11609 (goto-char (point-at-eol))))))))
11610 (when org-refile-use-cache
11611 (org-refile-cache-put tgs (buffer-file-name) descre))
11612 (setq targets (append tgs targets))))))
11613 (message "Getting targets...done")
11614 (nreverse targets)))
11616 (defun org-protect-slash (s)
11617 (while (string-match "/" s)
11618 (setq s (replace-match "\\" t t s)))
11621 (defvar org-olpa (make-vector 20 nil))
11623 (defun org-get-outline-path (&optional fastp level heading)
11624 "Return the outline path to the current entry, as a list.
11626 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11627 routine which makes outline path derivations for an entire file,
11628 avoiding backtracing. Refile target collection makes use of that."
11629 (if fastp
11630 (progn
11631 (if (> level 19)
11632 (error "Outline path failure, more than 19 levels"))
11633 (loop for i from level upto 19 do
11634 (aset org-olpa i nil))
11635 (prog1
11636 (delq nil (append org-olpa nil))
11637 (aset org-olpa level heading)))
11638 (let (rtn case-fold-search)
11639 (save-excursion
11640 (save-restriction
11641 (widen)
11642 (while (org-up-heading-safe)
11643 (when (looking-at org-complex-heading-regexp)
11644 (push (org-trim
11645 (replace-regexp-in-string
11646 ;; Remove statistical/checkboxes cookies
11647 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11648 (org-match-string-no-properties 4)))
11649 rtn)))
11650 rtn)))))
11652 (defun org-format-outline-path (path &optional width prefix separator)
11653 "Format the outline path PATH for display.
11654 WIDTH is the maximum number of characters that is available.
11655 PREFIX is a prefix to be included in the returned string,
11656 such as the file name.
11657 SEPARATOR is inserted between the different parts of the path,
11658 the default is \"/\"."
11659 (setq width (or width 79))
11660 (if prefix (setq width (- width (length prefix))))
11661 (if (not path)
11662 (or prefix "")
11663 (let* ((nsteps (length path))
11664 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11665 (maxwidth (if (<= total-width width)
11666 10000 ;; everything fits
11667 ;; we need to shorten the level headings
11668 (/ (- width nsteps) nsteps)))
11669 (org-odd-levels-only nil)
11670 (n 0)
11671 (total (1+ (length prefix))))
11672 (setq maxwidth (max maxwidth 10))
11673 (concat prefix
11674 (if prefix (or separator "/"))
11675 (mapconcat
11676 (lambda (h)
11677 (setq n (1+ n))
11678 (if (and (= n nsteps) (< maxwidth 10000))
11679 (setq maxwidth (- total-width total)))
11680 (if (< (length h) maxwidth)
11681 (progn (setq total (+ total (length h) 1)) h)
11682 (setq h (substring h 0 (- maxwidth 2))
11683 total (+ total maxwidth 1))
11684 (if (string-match "[ \t]+\\'" h)
11685 (setq h (substring h 0 (match-beginning 0))))
11686 (setq h (concat h "..")))
11687 (org-add-props h nil 'face
11688 (nth (% (1- n) org-n-level-faces)
11689 org-level-faces))
11691 path (or separator "/"))))))
11693 (defun org-display-outline-path (&optional file current separator just-return-string)
11694 "Display the current outline path in the echo area.
11696 If FILE is non-nil, prepend the output with the file name.
11697 If CURRENT is non-nil, append the current heading to the output.
11698 SEPARATOR is passed through to `org-format-outline-path'. It separates
11699 the different parts of the path and defaults to \"/\".
11700 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11701 (interactive "P")
11702 (let* (case-fold-search
11703 (bfn (buffer-file-name (buffer-base-buffer)))
11704 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11705 res)
11706 (if current (setq path (append path
11707 (save-excursion
11708 (org-back-to-heading t)
11709 (if (looking-at org-complex-heading-regexp)
11710 (list (match-string 4)))))))
11711 (setq res
11712 (org-format-outline-path
11713 path
11714 (1- (frame-width))
11715 (and file bfn (concat (file-name-nondirectory bfn) separator))
11716 separator))
11717 (if just-return-string
11718 (org-no-properties res)
11719 (org-unlogged-message "%s" res))))
11721 (defvar org-refile-history nil
11722 "History for refiling operations.")
11724 (defvar org-after-refile-insert-hook nil
11725 "Hook run after `org-refile' has inserted its stuff at the new location.
11726 Note that this is still *before* the stuff will be removed from
11727 the *old* location.")
11729 (defvar org-capture-last-stored-marker)
11730 (defvar org-refile-keep nil
11731 "Non-nil means `org-refile' will copy instead of refile.")
11733 (defun org-copy ()
11734 "Like `org-refile', but copy."
11735 (interactive)
11736 (let ((org-refile-keep t))
11737 (funcall 'org-refile nil nil nil "Copy")))
11739 (defun org-refile (&optional arg default-buffer rfloc msg)
11740 "Move the entry or entries at point to another heading.
11741 The list of target headings is compiled using the information in
11742 `org-refile-targets', which see.
11744 At the target location, the entry is filed as a subitem of the
11745 target heading. Depending on `org-reverse-note-order', the new
11746 subitem will either be the first or the last subitem.
11748 If there is an active region, all entries in that region will be
11749 refiled. However, the region must fulfill the requirement that
11750 the first heading sets the top-level of the moved text.
11752 With prefix arg ARG, the command will only visit the target
11753 location and not actually move anything.
11755 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11756 refiling operation has put the subtree.
11758 With a numeric prefix argument of `2', refile to the running clock.
11760 With a numeric prefix argument of `3', emulate `org-refile-keep'
11761 being set to `t' and copy to the target location, don't move it.
11762 Beware that keeping refiled entries may result in duplicated ID
11763 properties.
11765 RFLOC can be a refile location obtained in a different way.
11767 MSG is a string to replace \"Refile\" in the default prompt with
11768 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11770 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11772 If you are using target caching (see `org-refile-use-cache'), you
11773 have to clear the target cache in order to find new targets.
11774 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11775 prefix argument (`C-u C-u C-u C-c C-w')."
11776 (interactive "P")
11777 (if (member arg '(0 (64)))
11778 (org-refile-cache-clear)
11779 (let* ((actionmsg (cond (msg msg)
11780 ((equal arg 3) "Refile (and keep)")
11781 (t "Refile")))
11782 (cbuf (current-buffer))
11783 (regionp (org-region-active-p))
11784 (region-start (and regionp (region-beginning)))
11785 (region-end (and regionp (region-end)))
11786 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11787 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11788 pos it nbuf file re level reversed)
11789 (setq last-command nil)
11790 (when regionp
11791 (goto-char region-start)
11792 (or (bolp) (goto-char (point-at-bol)))
11793 (setq region-start (point))
11794 (unless (or (org-kill-is-subtree-p
11795 (buffer-substring region-start region-end))
11796 (prog1 org-refile-active-region-within-subtree
11797 (let ((s (point-at-eol)))
11798 (org-toggle-heading)
11799 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11800 (user-error "The region is not a (sequence of) subtree(s)")))
11801 (if (equal arg '(16))
11802 (org-refile-goto-last-stored)
11803 (when (or
11804 (and (equal arg 2)
11805 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11806 (prog1
11807 (setq it (list (or org-clock-heading "running clock")
11808 (buffer-file-name
11809 (marker-buffer org-clock-hd-marker))
11811 (marker-position org-clock-hd-marker)))
11812 (setq arg nil)))
11813 (setq it (or rfloc
11814 (let (heading-text)
11815 (save-excursion
11816 (unless (and arg (listp arg))
11817 (org-back-to-heading t)
11818 (setq heading-text
11819 (replace-regexp-in-string
11820 org-bracket-link-regexp
11821 "\\3"
11822 (nth 4 (org-heading-components)))))
11823 (org-refile-get-location
11824 (cond ((and arg (listp arg)) "Goto")
11825 (regionp (concat actionmsg " region to"))
11826 (t (concat actionmsg " subtree \""
11827 heading-text "\" to")))
11828 default-buffer
11829 (and (not (equal '(4) arg))
11830 org-refile-allow-creating-parent-nodes)
11831 arg))))))
11832 (setq file (nth 1 it)
11833 re (nth 2 it)
11834 pos (nth 3 it))
11835 (if (and (not arg)
11837 (equal (buffer-file-name) file)
11838 (if regionp
11839 (and (>= pos region-start)
11840 (<= pos region-end))
11841 (and (>= pos (point))
11842 (< pos (save-excursion
11843 (org-end-of-subtree t t))))))
11844 (error "Cannot refile to position inside the tree or region"))
11845 (setq nbuf (or (find-buffer-visiting file)
11846 (find-file-noselect file)))
11847 (if (and arg (not (equal arg 3)))
11848 (progn
11849 (org-pop-to-buffer-same-window nbuf)
11850 (goto-char pos)
11851 (org-show-context 'org-goto))
11852 (if regionp
11853 (progn
11854 (org-kill-new (buffer-substring region-start region-end))
11855 (org-save-markers-in-region region-start region-end))
11856 (org-copy-subtree 1 nil t))
11857 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11858 (find-file-noselect file)))
11859 (setq reversed (org-notes-order-reversed-p))
11860 (save-excursion
11861 (save-restriction
11862 (widen)
11863 (if pos
11864 (progn
11865 (goto-char pos)
11866 (looking-at org-outline-regexp)
11867 (setq level (org-get-valid-level (funcall outline-level) 1))
11868 (goto-char
11869 (if reversed
11870 (or (outline-next-heading) (point-max))
11871 (or (save-excursion (org-get-next-sibling))
11872 (org-end-of-subtree t t)
11873 (point-max)))))
11874 (setq level 1)
11875 (if (not reversed)
11876 (goto-char (point-max))
11877 (goto-char (point-min))
11878 (or (outline-next-heading) (goto-char (point-max)))))
11879 (if (not (bolp)) (newline))
11880 (org-paste-subtree level nil nil t)
11881 (when org-log-refile
11882 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11883 (unless (eq org-log-refile 'note)
11884 (save-excursion (org-add-log-note))))
11885 (and org-auto-align-tags
11886 (let ((org-loop-over-headlines-in-active-region nil))
11887 (org-set-tags nil t)))
11888 (let ((bookmark-name (plist-get org-bookmark-names-plist
11889 :last-refile)))
11890 (when bookmark-name
11891 (with-demoted-errors
11892 (bookmark-set bookmark-name))))
11893 ;; If we are refiling for capture, make sure that the
11894 ;; last-capture pointers point here
11895 (when (org-bound-and-true-p org-refile-for-capture)
11896 (let ((bookmark-name (plist-get org-bookmark-names-plist
11897 :last-capture-marker)))
11898 (when bookmark-name
11899 (with-demoted-errors
11900 (bookmark-set bookmark-name))))
11901 (move-marker org-capture-last-stored-marker (point)))
11902 (if (fboundp 'deactivate-mark) (deactivate-mark))
11903 (run-hooks 'org-after-refile-insert-hook))))
11904 (unless org-refile-keep
11905 (if regionp
11906 (delete-region (point) (+ (point) (- region-end region-start)))
11907 (delete-region
11908 (and (org-back-to-heading t) (point))
11909 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11910 (when (featurep 'org-inlinetask)
11911 (org-inlinetask-remove-END-maybe))
11912 (setq org-markers-to-move nil)
11913 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11915 (defun org-refile-goto-last-stored ()
11916 "Go to the location where the last refile was stored."
11917 (interactive)
11918 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11919 (message "This is the location of the last refile"))
11921 (defun org-refile--get-location (refloc tbl)
11922 "When user refile to REFLOC, find the associated target in TBL.
11923 Also check `org-refile-target-table'."
11924 (car (delq
11926 (mapcar
11927 (lambda (r) (or (assoc r tbl)
11928 (assoc r org-refile-target-table)))
11929 (list (replace-regexp-in-string "/$" "" refloc)
11930 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11932 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11933 no-exclude)
11934 "Prompt the user for a refile location, using PROMPT.
11935 PROMPT should not be suffixed with a colon and a space, because
11936 this function appends the default value from
11937 `org-refile-history' automatically, if that is not empty.
11938 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11939 this is used for the GOTO interface."
11940 (let ((org-refile-targets org-refile-targets)
11941 (org-refile-use-outline-path org-refile-use-outline-path)
11942 excluded-entries)
11943 (when (and (derived-mode-p 'org-mode)
11944 (not org-refile-use-cache)
11945 (not no-exclude))
11946 (org-map-tree
11947 (lambda()
11948 (setq excluded-entries
11949 (append excluded-entries (list (org-get-heading t t)))))))
11950 (setq org-refile-target-table
11951 (org-refile-get-targets default-buffer excluded-entries)))
11952 (unless org-refile-target-table
11953 (user-error "No refile targets"))
11954 (let* ((cbuf (current-buffer))
11955 (partial-completion-mode nil)
11956 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11957 (cfunc (if (and org-refile-use-outline-path
11958 org-outline-path-complete-in-steps)
11959 'org-olpath-completing-read
11960 'org-icompleting-read))
11961 (extra (if org-refile-use-outline-path "/" ""))
11962 (cbnex (concat (buffer-name) extra))
11963 (filename (and cfn (expand-file-name cfn)))
11964 (tbl (mapcar
11965 (lambda (x)
11966 (if (and (not (member org-refile-use-outline-path
11967 '(file full-file-path)))
11968 (not (equal filename (nth 1 x))))
11969 (cons (concat (car x) extra " ("
11970 (file-name-nondirectory (nth 1 x)) ")")
11971 (cdr x))
11972 (cons (concat (car x) extra) (cdr x))))
11973 org-refile-target-table))
11974 (completion-ignore-case t)
11975 cdef
11976 (prompt (concat prompt
11977 (or (and (car org-refile-history)
11978 (concat " (default " (car org-refile-history) ")"))
11979 (and (assoc cbnex tbl) (setq cdef cbnex)
11980 (concat " (default " cbnex ")"))) ": "))
11981 pa answ parent-target child parent old-hist)
11982 (setq old-hist org-refile-history)
11983 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11984 nil 'org-refile-history (or cdef (car org-refile-history))))
11985 (if (setq pa (org-refile--get-location answ tbl))
11986 (progn
11987 (org-refile-check-position pa)
11988 (when (or (not org-refile-history)
11989 (not (eq old-hist org-refile-history))
11990 (not (equal (car pa) (car org-refile-history))))
11991 (setq org-refile-history
11992 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11993 org-refile-history
11994 (cdr org-refile-history))))
11995 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11996 (pop org-refile-history)))
11998 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11999 (progn
12000 (setq parent (match-string 1 answ)
12001 child (match-string 2 answ))
12002 (setq parent-target (org-refile--get-location parent tbl))
12003 (when (and parent-target
12004 (or (eq new-nodes t)
12005 (and (eq new-nodes 'confirm)
12006 (y-or-n-p (format "Create new node \"%s\"? "
12007 child)))))
12008 (org-refile-new-child parent-target child)))
12009 (user-error "Invalid target location")))))
12011 (declare-function org-string-nw-p "org-macs" (s))
12012 (defun org-refile-check-position (refile-pointer)
12013 "Check if the refile pointer matches the headline to which it points."
12014 (let* ((file (nth 1 refile-pointer))
12015 (re (nth 2 refile-pointer))
12016 (pos (nth 3 refile-pointer))
12017 buffer)
12018 (if (and (not (markerp pos)) (not file))
12019 (user-error "Please indicate a target file in the refile path")
12020 (when (org-string-nw-p re)
12021 (setq buffer (if (markerp pos)
12022 (marker-buffer pos)
12023 (or (find-buffer-visiting file)
12024 (find-file-noselect file))))
12025 (with-current-buffer buffer
12026 (save-excursion
12027 (save-restriction
12028 (widen)
12029 (goto-char pos)
12030 (beginning-of-line 1)
12031 (unless (org-looking-at-p re)
12032 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12034 (defun org-refile-new-child (parent-target child)
12035 "Use refile target PARENT-TARGET to add new CHILD below it."
12036 (unless parent-target
12037 (error "Cannot find parent for new node"))
12038 (let ((file (nth 1 parent-target))
12039 (pos (nth 3 parent-target))
12040 level)
12041 (with-current-buffer (or (find-buffer-visiting file)
12042 (find-file-noselect file))
12043 (save-excursion
12044 (save-restriction
12045 (widen)
12046 (if pos
12047 (goto-char pos)
12048 (goto-char (point-max))
12049 (if (not (bolp)) (newline)))
12050 (when (looking-at org-outline-regexp)
12051 (setq level (funcall outline-level))
12052 (org-end-of-subtree t t))
12053 (org-back-over-empty-lines)
12054 (insert "\n" (make-string
12055 (if pos (org-get-valid-level level 1) 1) ?*)
12056 " " child "\n")
12057 (beginning-of-line 0)
12058 (list (concat (car parent-target) "/" child) file "" (point)))))))
12060 (defun org-olpath-completing-read (prompt collection &rest args)
12061 "Read an outline path like a file name."
12062 (let ((thetable collection)
12063 (org-completion-use-ido nil) ; does not work with ido.
12064 (org-completion-use-iswitchb nil)) ; or iswitchb
12065 (apply
12066 'org-icompleting-read prompt
12067 (lambda (string predicate &optional flag)
12068 (let (rtn r f (l (length string)))
12069 (cond
12070 ((eq flag nil)
12071 ;; try completion
12072 (try-completion string thetable))
12073 ((eq flag t)
12074 ;; all-completions
12075 (setq rtn (all-completions string thetable predicate))
12076 (mapcar
12077 (lambda (x)
12078 (setq r (substring x l))
12079 (if (string-match " ([^)]*)$" x)
12080 (setq f (match-string 0 x))
12081 (setq f ""))
12082 (if (string-match "/" r)
12083 (concat string (substring r 0 (match-end 0)) f)
12085 rtn))
12086 ((eq flag 'lambda)
12087 ;; exact match?
12088 (assoc string thetable)))))
12089 args)))
12091 ;;;; Dynamic blocks
12093 (defun org-find-dblock (name)
12094 "Find the first dynamic block with name NAME in the buffer.
12095 If not found, stay at current position and return nil."
12096 (let ((case-fold-search t) pos)
12097 (save-excursion
12098 (goto-char (point-min))
12099 (setq pos (and (re-search-forward
12100 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12101 (match-beginning 0))))
12102 (if pos (goto-char pos))
12103 pos))
12105 (defun org-create-dblock (plist)
12106 "Create a dynamic block section, with parameters taken from PLIST.
12107 PLIST must contain a :name entry which is used as the name of the block."
12108 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12109 (end-of-line 1)
12110 (newline))
12111 (let ((col (current-column))
12112 (name (plist-get plist :name)))
12113 (insert "#+BEGIN: " name)
12114 (while plist
12115 (if (eq (car plist) :name)
12116 (setq plist (cddr plist))
12117 (insert " " (prin1-to-string (pop plist)))))
12118 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12119 (beginning-of-line -2)))
12121 (defun org-prepare-dblock ()
12122 "Prepare dynamic block for refresh.
12123 This empties the block, puts the cursor at the insert position and returns
12124 the property list including an extra property :name with the block name."
12125 (unless (looking-at org-dblock-start-re)
12126 (user-error "Not at a dynamic block"))
12127 (let* ((begdel (1+ (match-end 0)))
12128 (name (org-no-properties (match-string 1)))
12129 (params (append (list :name name)
12130 (read (concat "(" (match-string 3) ")")))))
12131 (save-excursion
12132 (beginning-of-line 1)
12133 (skip-chars-forward " \t")
12134 (setq params (plist-put params :indentation-column (current-column))))
12135 (unless (re-search-forward org-dblock-end-re nil t)
12136 (error "Dynamic block not terminated"))
12137 (setq params
12138 (append params
12139 (list :content (buffer-substring
12140 begdel (match-beginning 0)))))
12141 (delete-region begdel (match-beginning 0))
12142 (goto-char begdel)
12143 (open-line 1)
12144 params))
12146 (defun org-map-dblocks (&optional command)
12147 "Apply COMMAND to all dynamic blocks in the current buffer.
12148 If COMMAND is not given, use `org-update-dblock'."
12149 (let ((cmd (or command 'org-update-dblock)))
12150 (save-excursion
12151 (goto-char (point-min))
12152 (while (re-search-forward org-dblock-start-re nil t)
12153 (goto-char (match-beginning 0))
12154 (save-excursion
12155 (condition-case nil
12156 (funcall cmd)
12157 (error (message "Error during update of dynamic block"))))
12158 (unless (re-search-forward org-dblock-end-re nil t)
12159 (error "Dynamic block not terminated"))))))
12161 (defun org-dblock-update (&optional arg)
12162 "User command for updating dynamic blocks.
12163 Update the dynamic block at point. With prefix ARG, update all dynamic
12164 blocks in the buffer."
12165 (interactive "P")
12166 (if arg
12167 (org-update-all-dblocks)
12168 (or (looking-at org-dblock-start-re)
12169 (org-beginning-of-dblock))
12170 (org-update-dblock)))
12172 (defun org-update-dblock ()
12173 "Update the dynamic block at point.
12174 This means to empty the block, parse for parameters and then call
12175 the correct writing function."
12176 (interactive)
12177 (save-excursion
12178 (let* ((win (selected-window))
12179 (pos (point))
12180 (line (org-current-line))
12181 (params (org-prepare-dblock))
12182 (name (plist-get params :name))
12183 (indent (plist-get params :indentation-column))
12184 (cmd (intern (concat "org-dblock-write:" name))))
12185 (message "Updating dynamic block `%s' at line %d..." name line)
12186 (funcall cmd params)
12187 (message "Updating dynamic block `%s' at line %d...done" name line)
12188 (goto-char pos)
12189 (when (and indent (> indent 0))
12190 (setq indent (make-string indent ?\ ))
12191 (save-excursion
12192 (select-window win)
12193 (org-beginning-of-dblock)
12194 (forward-line 1)
12195 (while (not (looking-at org-dblock-end-re))
12196 (insert indent)
12197 (beginning-of-line 2))
12198 (when (looking-at org-dblock-end-re)
12199 (and (looking-at "[ \t]+")
12200 (replace-match ""))
12201 (insert indent)))))))
12203 (defun org-beginning-of-dblock ()
12204 "Find the beginning of the dynamic block at point.
12205 Error if there is no such block at point."
12206 (let ((pos (point))
12207 beg)
12208 (end-of-line 1)
12209 (if (and (re-search-backward org-dblock-start-re nil t)
12210 (setq beg (match-beginning 0))
12211 (re-search-forward org-dblock-end-re nil t)
12212 (> (match-end 0) pos))
12213 (goto-char beg)
12214 (goto-char pos)
12215 (error "Not in a dynamic block"))))
12217 (defun org-update-all-dblocks ()
12218 "Update all dynamic blocks in the buffer.
12219 This function can be used in a hook."
12220 (interactive)
12221 (when (derived-mode-p 'org-mode)
12222 (org-map-dblocks 'org-update-dblock)))
12225 ;;;; Completion
12227 (declare-function org-export-backend-name "org-export" (cl-x))
12228 (declare-function org-export-backend-options "org-export" (cl-x))
12229 (defun org-get-export-keywords ()
12230 "Return a list of all currently understood export keywords.
12231 Export keywords include options, block names, attributes and
12232 keywords relative to each registered export back-end."
12233 (let (keywords)
12234 (dolist (backend
12235 (org-bound-and-true-p org-export--registered-backends)
12236 (delq nil keywords))
12237 ;; Back-end name (for keywords, like #+LATEX:)
12238 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12239 (dolist (option-entry (org-export-backend-options backend))
12240 ;; Back-end options.
12241 (push (nth 1 option-entry) keywords)))))
12243 (defconst org-options-keywords
12244 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12245 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12246 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12247 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12248 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12250 (defcustom org-structure-template-alist
12251 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12252 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12253 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12254 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12255 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12256 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12257 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12258 ("L" "#+LaTeX: ")
12259 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12260 ("H" "#+HTML: ")
12261 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12262 ("A" "#+ASCII: ")
12263 ("i" "#+INDEX: ?")
12264 ("I" "#+INCLUDE: %file ?"))
12265 "Structure completion elements.
12266 This is a list of abbreviation keys and values. The value gets inserted
12267 if you type `<' followed by the key and then press the completion key,
12268 usually `TAB'. %file will be replaced by a file name after prompting
12269 for the file using completion. The cursor will be placed at the position
12270 of the `?` in the template.
12271 There are two templates for each key, the first uses the original Org syntax,
12272 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12273 the default when the /org-mtags.el/ module has been loaded. See also the
12274 variable `org-mtags-prefer-muse-templates'."
12275 :group 'org-completion
12276 :type '(repeat
12277 (list
12278 (string :tag "Key")
12279 (string :tag "Template")))
12280 :version 24.4
12281 :package-version '(Org . "8.3"))
12283 (defun org-try-structure-completion ()
12284 "Try to complete a structure template before point.
12285 This looks for strings like \"<e\" on an otherwise empty line and
12286 expands them."
12287 (let ((l (buffer-substring (point-at-bol) (point)))
12289 (when (and (looking-at "[ \t]*$")
12290 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12291 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12292 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12293 (match-beginning 1)) a)
12294 t)))
12296 (defun org-complete-expand-structure-template (start cell)
12297 "Expand a structure template."
12298 (let ((rpl (nth 1 cell))
12299 (ind ""))
12300 (delete-region start (point))
12301 (when (string-match "\\`[ \t]*#\\+" rpl)
12302 (cond
12303 ((bolp))
12304 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12305 (setq ind (buffer-substring (point-at-bol) (point))))
12306 (t (newline))))
12307 (setq start (point))
12308 (if (string-match "%file" rpl)
12309 (setq rpl (replace-match
12310 (concat
12311 "\""
12312 (save-match-data
12313 (abbreviate-file-name (read-file-name "Include file: ")))
12314 "\"")
12315 t t rpl)))
12316 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12317 (concat "\n" ind)))
12318 (insert rpl)
12319 (if (re-search-backward "\\?" start t) (delete-char 1))))
12321 ;;;; TODO, DEADLINE, Comments
12323 (defun org-toggle-comment ()
12324 "Change the COMMENT state of an entry."
12325 (interactive)
12326 (save-excursion
12327 (org-back-to-heading)
12328 (looking-at org-complex-heading-regexp)
12329 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12330 (skip-chars-forward " \t")
12331 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12332 (if (org-in-commented-heading-p t)
12333 (delete-region (point)
12334 (progn (search-forward " " (line-end-position) 'move)
12335 (skip-chars-forward " \t")
12336 (point)))
12337 (insert org-comment-string)
12338 (unless (eolp) (insert " ")))))
12340 (defvar org-last-todo-state-is-todo nil
12341 "This is non-nil when the last TODO state change led to a TODO state.
12342 If the last change removed the TODO tag or switched to DONE, then
12343 this is nil.")
12345 (defvar org-setting-tags nil) ; dynamically skipped
12347 (defvar org-todo-setup-filter-hook nil
12348 "Hook for functions that pre-filter todo specs.
12349 Each function takes a todo spec and returns either nil or the spec
12350 transformed into canonical form." )
12352 (defvar org-todo-get-default-hook nil
12353 "Hook for functions that get a default item for todo.
12354 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12355 nil or a string to be used for the todo mark." )
12357 (defvar org-agenda-headline-snapshot-before-repeat)
12359 (defun org-current-effective-time ()
12360 "Return current time adjusted for `org-extend-today-until' variable."
12361 (let* ((ct (org-current-time))
12362 (dct (decode-time ct))
12363 (ct1
12364 (cond
12365 (org-use-last-clock-out-time-as-effective-time
12366 (or (org-clock-get-last-clock-out-time) ct))
12367 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12368 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12369 (t ct))))
12370 ct1))
12372 (defun org-todo-yesterday (&optional arg)
12373 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12374 (interactive "P")
12375 (if (eq major-mode 'org-agenda-mode)
12376 (apply 'org-agenda-todo-yesterday arg)
12377 (let* ((hour (third (decode-time
12378 (org-current-time))))
12379 (org-extend-today-until (1+ hour)))
12380 (org-todo arg))))
12382 (defvar org-block-entry-blocking ""
12383 "First entry preventing the TODO state change.")
12385 (defun org-cancel-repeater ()
12386 "Cancel a repeater by setting its numeric value to zero."
12387 (interactive)
12388 (save-excursion
12389 (org-back-to-heading t)
12390 (let ((bound1 (point))
12391 (bound0 (save-excursion (outline-next-heading) (point))))
12392 (when (re-search-forward
12393 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12394 org-deadline-time-regexp "\\)\\|\\("
12395 org-ts-regexp "\\)")
12396 bound0 t)
12397 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12398 (replace-match "0" t nil nil 1))))))
12400 (defun org-todo (&optional arg)
12401 "Change the TODO state of an item.
12402 The state of an item is given by a keyword at the start of the heading,
12403 like
12404 *** TODO Write paper
12405 *** DONE Call mom
12407 The different keywords are specified in the variable `org-todo-keywords'.
12408 By default the available states are \"TODO\" and \"DONE\".
12409 So for this example: when the item starts with TODO, it is changed to DONE.
12410 When it starts with DONE, the DONE is removed. And when neither TODO nor
12411 DONE are present, add TODO at the beginning of the heading.
12413 With \\[universal-argument] prefix arg, use completion to determine the new \
12414 state.
12415 With numeric prefix arg, switch to that state.
12416 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12417 keywords (nextset).
12418 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12419 With a numeric prefix arg of 0, inhibit note taking for the change.
12420 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12422 When called through ELisp, arg is also interpreted in the following way:
12423 'none -> empty state
12424 \"\"(empty string) -> switch to empty state
12425 'done -> switch to DONE
12426 'nextset -> switch to the next set of keywords
12427 'previousset -> switch to the previous set of keywords
12428 \"WAITING\" -> switch to the specified keyword, but only if it
12429 really is a member of `org-todo-keywords'."
12430 (interactive "P")
12431 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12432 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12433 'region-start-level 'region))
12434 org-loop-over-headlines-in-active-region)
12435 (org-map-entries
12436 `(org-todo ,arg)
12437 org-loop-over-headlines-in-active-region
12438 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12439 (if (equal arg '(16)) (setq arg 'nextset))
12440 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12441 (let ((org-blocker-hook org-blocker-hook)
12442 commentp
12443 case-fold-search)
12444 (when (equal arg '(64))
12445 (setq arg nil org-blocker-hook nil))
12446 (when (and org-blocker-hook
12447 (or org-inhibit-blocking
12448 (org-entry-get nil "NOBLOCKING")))
12449 (setq org-blocker-hook nil))
12450 (save-excursion
12451 (catch 'exit
12452 (org-back-to-heading t)
12453 (when (org-in-commented-heading-p t)
12454 (org-toggle-comment)
12455 (setq commentp t))
12456 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12457 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12458 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12459 (let* ((match-data (match-data))
12460 (startpos (point-at-bol))
12461 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12462 (org-log-done org-log-done)
12463 (org-log-repeat org-log-repeat)
12464 (org-todo-log-states org-todo-log-states)
12465 (org-inhibit-logging
12466 (if (equal arg 0)
12467 (progn (setq arg nil) 'note) org-inhibit-logging))
12468 (this (match-string 1))
12469 (hl-pos (match-beginning 0))
12470 (head (org-get-todo-sequence-head this))
12471 (ass (assoc head org-todo-kwd-alist))
12472 (interpret (nth 1 ass))
12473 (done-word (nth 3 ass))
12474 (final-done-word (nth 4 ass))
12475 (org-last-state (or this ""))
12476 (completion-ignore-case t)
12477 (member (member this org-todo-keywords-1))
12478 (tail (cdr member))
12479 (org-state (cond
12480 ((and org-todo-key-trigger
12481 (or (and (equal arg '(4))
12482 (eq org-use-fast-todo-selection 'prefix))
12483 (and (not arg) org-use-fast-todo-selection
12484 (not (eq org-use-fast-todo-selection
12485 'prefix)))))
12486 ;; Use fast selection
12487 (org-fast-todo-selection))
12488 ((and (equal arg '(4))
12489 (or (not org-use-fast-todo-selection)
12490 (not org-todo-key-trigger)))
12491 ;; Read a state with completion
12492 (org-icompleting-read
12493 "State: " (mapcar 'list org-todo-keywords-1)
12494 nil t))
12495 ((eq arg 'right)
12496 (if this
12497 (if tail (car tail) nil)
12498 (car org-todo-keywords-1)))
12499 ((eq arg 'left)
12500 (if (equal member org-todo-keywords-1)
12502 (if this
12503 (nth (- (length org-todo-keywords-1)
12504 (length tail) 2)
12505 org-todo-keywords-1)
12506 (org-last org-todo-keywords-1))))
12507 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12508 (setq arg nil))) ; hack to fall back to cycling
12509 (arg
12510 ;; user or caller requests a specific state
12511 (cond
12512 ((equal arg "") nil)
12513 ((eq arg 'none) nil)
12514 ((eq arg 'done) (or done-word (car org-done-keywords)))
12515 ((eq arg 'nextset)
12516 (or (car (cdr (member head org-todo-heads)))
12517 (car org-todo-heads)))
12518 ((eq arg 'previousset)
12519 (let ((org-todo-heads (reverse org-todo-heads)))
12520 (or (car (cdr (member head org-todo-heads)))
12521 (car org-todo-heads))))
12522 ((car (member arg org-todo-keywords-1)))
12523 ((stringp arg)
12524 (user-error "State `%s' not valid in this file" arg))
12525 ((nth (1- (prefix-numeric-value arg))
12526 org-todo-keywords-1))))
12527 ((null member) (or head (car org-todo-keywords-1)))
12528 ((equal this final-done-word) nil) ;; -> make empty
12529 ((null tail) nil) ;; -> first entry
12530 ((memq interpret '(type priority))
12531 (if (eq this-command last-command)
12532 (car tail)
12533 (if (> (length tail) 0)
12534 (or done-word (car org-done-keywords))
12535 nil)))
12537 (car tail))))
12538 (org-state (or
12539 (run-hook-with-args-until-success
12540 'org-todo-get-default-hook org-state org-last-state)
12541 org-state))
12542 (next (if org-state (concat " " org-state " ") " "))
12543 (change-plist (list :type 'todo-state-change :from this :to org-state
12544 :position startpos))
12545 dolog now-done-p)
12546 (when org-blocker-hook
12547 (setq org-last-todo-state-is-todo
12548 (not (member this org-done-keywords)))
12549 (unless (save-excursion
12550 (save-match-data
12551 (org-with-wide-buffer
12552 (run-hook-with-args-until-failure
12553 'org-blocker-hook change-plist))))
12554 (if (org-called-interactively-p 'interactive)
12555 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12556 this org-state org-block-entry-blocking)
12557 ;; fail silently
12558 (message "TODO state change from %s to %s blocked (by \"%s\")"
12559 this org-state org-block-entry-blocking)
12560 (throw 'exit nil))))
12561 (store-match-data match-data)
12562 (replace-match next t t)
12563 (cond ((equal this org-state)
12564 (message "TODO state was already %s" (org-trim next)))
12565 ((pos-visible-in-window-p hl-pos)
12566 (message "TODO state changed to %s" (org-trim next))))
12567 (unless head
12568 (setq head (org-get-todo-sequence-head org-state)
12569 ass (assoc head org-todo-kwd-alist)
12570 interpret (nth 1 ass)
12571 done-word (nth 3 ass)
12572 final-done-word (nth 4 ass)))
12573 (when (memq arg '(nextset previousset))
12574 (message "Keyword-Set %d/%d: %s"
12575 (- (length org-todo-sets) -1
12576 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12577 (length org-todo-sets)
12578 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12579 (setq org-last-todo-state-is-todo
12580 (not (member org-state org-done-keywords)))
12581 (setq now-done-p (and (member org-state org-done-keywords)
12582 (not (member this org-done-keywords))))
12583 (and logging (org-local-logging logging))
12584 (when (and (or org-todo-log-states org-log-done)
12585 (not (eq org-inhibit-logging t))
12586 (not (memq arg '(nextset previousset))))
12587 ;; we need to look at recording a time and note
12588 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12589 (nth 2 (assoc this org-todo-log-states))))
12590 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12591 (setq dolog 'time))
12592 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12593 (and org-state
12594 (member org-state org-not-done-keywords)
12595 (not (member this org-not-done-keywords))))
12596 ;; This is now a todo state and was not one before
12597 ;; If there was a CLOSED time stamp, get rid of it.
12598 (org-add-planning-info nil nil 'closed))
12599 (when (and now-done-p org-log-done)
12600 ;; It is now done, and it was not done before
12601 (org-add-planning-info 'closed (org-current-effective-time))
12602 (if (and (not dolog) (eq 'note org-log-done))
12603 (org-add-log-setup 'done org-state this 'findpos 'note)))
12604 (when (and org-state dolog)
12605 ;; This is a non-nil state, and we need to log it
12606 (org-add-log-setup 'state org-state this 'findpos dolog)))
12607 ;; Fixup tag positioning
12608 (org-todo-trigger-tag-changes org-state)
12609 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12610 (when org-provide-todo-statistics
12611 (org-update-parent-todo-statistics))
12612 (run-hooks 'org-after-todo-state-change-hook)
12613 (if (and arg (not (member org-state org-done-keywords)))
12614 (setq head (org-get-todo-sequence-head org-state)))
12615 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12616 ;; Do we need to trigger a repeat?
12617 (when now-done-p
12618 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12619 ;; This is for the agenda, take a snapshot of the headline.
12620 (save-match-data
12621 (setq org-agenda-headline-snapshot-before-repeat
12622 (org-get-heading))))
12623 (org-auto-repeat-maybe org-state))
12624 ;; Fixup cursor location if close to the keyword
12625 (if (and (outline-on-heading-p)
12626 (not (bolp))
12627 (save-excursion (beginning-of-line 1)
12628 (looking-at org-todo-line-regexp))
12629 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12630 (progn
12631 (goto-char (or (match-end 2) (match-end 1)))
12632 (and (looking-at " ") (just-one-space))))
12633 (when org-trigger-hook
12634 (save-excursion
12635 (run-hook-with-args 'org-trigger-hook change-plist)))
12636 (when commentp (org-toggle-comment))))))))
12638 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12639 "Block turning an entry into a TODO, using the hierarchy.
12640 This checks whether the current task should be blocked from state
12641 changes. Such blocking occurs when:
12643 1. The task has children which are not all in a completed state.
12645 2. A task has a parent with the property :ORDERED:, and there
12646 are siblings prior to the current task with incomplete
12647 status.
12649 3. The parent of the task is blocked because it has siblings that should
12650 be done first, or is child of a block grandparent TODO entry."
12652 (if (not org-enforce-todo-dependencies)
12653 t ; if locally turned off don't block
12654 (catch 'dont-block
12655 ;; If this is not a todo state change, or if this entry is already DONE,
12656 ;; do not block
12657 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12658 (member (plist-get change-plist :from)
12659 (cons 'done org-done-keywords))
12660 (member (plist-get change-plist :to)
12661 (cons 'todo org-not-done-keywords))
12662 (not (plist-get change-plist :to)))
12663 (throw 'dont-block t))
12664 ;; If this task has children, and any are undone, it's blocked
12665 (save-excursion
12666 (org-back-to-heading t)
12667 (let ((this-level (funcall outline-level)))
12668 (outline-next-heading)
12669 (let ((child-level (funcall outline-level)))
12670 (while (and (not (eobp))
12671 (> child-level this-level))
12672 ;; this todo has children, check whether they are all
12673 ;; completed
12674 (if (and (not (org-entry-is-done-p))
12675 (org-entry-is-todo-p))
12676 (progn (setq org-block-entry-blocking (org-get-heading))
12677 (throw 'dont-block nil)))
12678 (outline-next-heading)
12679 (setq child-level (funcall outline-level))))))
12680 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12681 ;; any previous siblings are undone, it's blocked
12682 (save-excursion
12683 (org-back-to-heading t)
12684 (let* ((pos (point))
12685 (parent-pos (and (org-up-heading-safe) (point))))
12686 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12687 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12688 (forward-line 1)
12689 (re-search-forward org-not-done-heading-regexp pos t))
12690 (setq org-block-entry-blocking (match-string 0))
12691 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12692 ;; Search further up the hierarchy, to see if an ancestor is blocked
12693 (while t
12694 (goto-char parent-pos)
12695 (if (not (looking-at org-not-done-heading-regexp))
12696 (throw 'dont-block t)) ; do not block, parent is not a TODO
12697 (setq pos (point))
12698 (setq parent-pos (and (org-up-heading-safe) (point)))
12699 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12700 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12701 (forward-line 1)
12702 (re-search-forward org-not-done-heading-regexp pos t)
12703 (setq org-block-entry-blocking (org-get-heading)))
12704 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12706 (defcustom org-track-ordered-property-with-tag nil
12707 "Should the ORDERED property also be shown as a tag?
12708 The ORDERED property decides if an entry should require subtasks to be
12709 completed in sequence. Since a property is not very visible, setting
12710 this option means that toggling the ORDERED property with the command
12711 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12712 not relevant for the behavior, but it makes things more visible.
12714 Note that toggling the tag with tags commands will not change the property
12715 and therefore not influence behavior!
12717 This can be t, meaning the tag ORDERED should be used, It can also be a
12718 string to select a different tag for this task."
12719 :group 'org-todo
12720 :type '(choice
12721 (const :tag "No tracking" nil)
12722 (const :tag "Track with ORDERED tag" t)
12723 (string :tag "Use other tag")))
12725 (defun org-toggle-ordered-property ()
12726 "Toggle the ORDERED property of the current entry.
12727 For better visibility, you can track the value of this property with a tag.
12728 See variable `org-track-ordered-property-with-tag'."
12729 (interactive)
12730 (let* ((t1 org-track-ordered-property-with-tag)
12731 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12732 (save-excursion
12733 (org-back-to-heading)
12734 (if (org-entry-get nil "ORDERED")
12735 (progn
12736 (org-delete-property "ORDERED")
12737 (and tag (org-toggle-tag tag 'off))
12738 (message "Subtasks can be completed in arbitrary order"))
12739 (org-entry-put nil "ORDERED" "t")
12740 (and tag (org-toggle-tag tag 'on))
12741 (message "Subtasks must be completed in sequence")))))
12743 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12744 (defun org-block-todo-from-checkboxes (change-plist)
12745 "Block turning an entry into a TODO, using checkboxes.
12746 This checks whether the current task should be blocked from state
12747 changes because there are unchecked boxes in this entry."
12748 (if (not org-enforce-todo-checkbox-dependencies)
12749 t ; if locally turned off don't block
12750 (catch 'dont-block
12751 ;; If this is not a todo state change, or if this entry is already DONE,
12752 ;; do not block
12753 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12754 (member (plist-get change-plist :from)
12755 (cons 'done org-done-keywords))
12756 (member (plist-get change-plist :to)
12757 (cons 'todo org-not-done-keywords))
12758 (not (plist-get change-plist :to)))
12759 (throw 'dont-block t))
12760 ;; If this task has checkboxes that are not checked, it's blocked
12761 (save-excursion
12762 (org-back-to-heading t)
12763 (let ((beg (point)) end)
12764 (outline-next-heading)
12765 (setq end (point))
12766 (goto-char beg)
12767 (if (org-list-search-forward
12768 (concat (org-item-beginning-re)
12769 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12770 "\\[[- ]\\]")
12771 end t)
12772 (progn
12773 (if (boundp 'org-blocked-by-checkboxes)
12774 (setq org-blocked-by-checkboxes t))
12775 (throw 'dont-block nil)))))
12776 t))) ; do not block
12778 (defun org-entry-blocked-p ()
12779 "Is the current entry blocked?"
12780 (org-with-silent-modifications
12781 (if (org-entry-get nil "NOBLOCKING")
12782 nil ;; Never block this entry
12783 (not (run-hook-with-args-until-failure
12784 'org-blocker-hook
12785 (list :type 'todo-state-change
12786 :position (point)
12787 :from 'todo
12788 :to 'done))))))
12790 (defun org-update-statistics-cookies (all)
12791 "Update the statistics cookie, either from TODO or from checkboxes.
12792 This should be called with the cursor in a line with a statistics cookie."
12793 (interactive "P")
12794 (if all
12795 (progn
12796 (org-update-checkbox-count 'all)
12797 (org-map-entries 'org-update-parent-todo-statistics))
12798 (if (not (org-at-heading-p))
12799 (org-update-checkbox-count)
12800 (let ((pos (point-marker))
12801 end l1 l2)
12802 (ignore-errors (org-back-to-heading t))
12803 (if (not (org-at-heading-p))
12804 (org-update-checkbox-count)
12805 (setq l1 (org-outline-level))
12806 (setq end (save-excursion
12807 (outline-next-heading)
12808 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12809 (point)))
12810 (if (and (save-excursion
12811 (re-search-forward
12812 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12813 (not (save-excursion (re-search-forward
12814 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12815 (org-update-checkbox-count)
12816 (if (and l2 (> l2 l1))
12817 (progn
12818 (goto-char end)
12819 (org-update-parent-todo-statistics))
12820 (goto-char pos)
12821 (beginning-of-line 1)
12822 (while (re-search-forward
12823 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12824 (point-at-eol) t)
12825 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12826 (goto-char pos)
12827 (move-marker pos nil)))))
12829 (defvar org-entry-property-inherited-from) ;; defined below
12830 (defun org-update-parent-todo-statistics ()
12831 "Update any statistics cookie in the parent of the current headline.
12832 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12833 the entire subtree and this will travel up the hierarchy and update
12834 statistics everywhere."
12835 (let* ((prop (save-excursion (org-up-heading-safe)
12836 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12837 (recursive (or (not org-hierarchical-todo-statistics)
12838 (and prop (string-match "\\<recursive\\>" prop))))
12839 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12841 (first t)
12842 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12843 level ltoggle l1 new ndel
12844 (cnt-all 0) (cnt-done 0) is-percent kwd
12845 checkbox-beg ov ovs ove cookie-present)
12846 (catch 'exit
12847 (save-excursion
12848 (beginning-of-line 1)
12849 (setq ltoggle (funcall outline-level))
12850 ;; Three situations are to consider:
12852 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12853 ;; to the top-level ancestor on the headline;
12855 ;; 2. If parent has "recursive" property, repeat up to the
12856 ;; headline setting that property, taking inheritance into
12857 ;; account;
12859 ;; 3. Else, move up to direct parent and proceed only once.
12860 (while (and (setq level (org-up-heading-safe))
12861 (or recursive first)
12862 (>= (point) lim))
12863 (setq first nil cookie-present nil)
12864 (unless (and level
12865 (not (string-match
12866 "\\<checkbox\\>"
12867 (downcase (or (org-entry-get nil "COOKIE_DATA")
12868 "")))))
12869 (throw 'exit nil))
12870 (while (re-search-forward box-re (point-at-eol) t)
12871 (setq cnt-all 0 cnt-done 0 cookie-present t)
12872 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12873 (save-match-data
12874 (unless (outline-next-heading) (throw 'exit nil))
12875 (while (and (looking-at org-complex-heading-regexp)
12876 (> (setq l1 (length (match-string 1))) level))
12877 (setq kwd (and (or recursive (= l1 ltoggle))
12878 (match-string 2)))
12879 (if (or (eq org-provide-todo-statistics 'all-headlines)
12880 (and (eq org-provide-todo-statistics t)
12881 (or (member kwd org-done-keywords)))
12882 (and (listp org-provide-todo-statistics)
12883 (stringp (car org-provide-todo-statistics))
12884 (or (member kwd org-provide-todo-statistics)
12885 (member kwd org-done-keywords)))
12886 (and (listp org-provide-todo-statistics)
12887 (listp (car org-provide-todo-statistics))
12888 (or (member kwd (car org-provide-todo-statistics))
12889 (and (member kwd org-done-keywords)
12890 (member kwd (cadr org-provide-todo-statistics))))))
12891 (setq cnt-all (1+ cnt-all))
12892 (if (eq org-provide-todo-statistics t)
12893 (and kwd (setq cnt-all (1+ cnt-all)))))
12894 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12895 (member kwd org-done-keywords))
12896 (and (listp org-provide-todo-statistics)
12897 (listp (car org-provide-todo-statistics))
12898 (member kwd org-done-keywords)
12899 (member kwd (cadr org-provide-todo-statistics)))
12900 (and (listp org-provide-todo-statistics)
12901 (stringp (car org-provide-todo-statistics))
12902 (member kwd org-done-keywords)))
12903 (setq cnt-done (1+ cnt-done)))
12904 (outline-next-heading)))
12905 (setq new
12906 (if is-percent
12907 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12908 (format "[%d/%d]" cnt-done cnt-all))
12909 ndel (- (match-end 0) checkbox-beg))
12910 ;; handle overlays when updating cookie from column view
12911 (when (setq ov (car (overlays-at checkbox-beg)))
12912 (setq ovs (overlay-start ov) ove (overlay-end ov))
12913 (delete-overlay ov))
12914 (goto-char checkbox-beg)
12915 (insert new)
12916 (delete-region (point) (+ (point) ndel))
12917 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12918 (when ov (move-overlay ov ovs ove)))
12919 (when cookie-present
12920 (run-hook-with-args 'org-after-todo-statistics-hook
12921 cnt-done (- cnt-all cnt-done))))))
12922 (run-hooks 'org-todo-statistics-hook)))
12924 (defvar org-after-todo-statistics-hook nil
12925 "Hook that is called after a TODO statistics cookie has been updated.
12926 Each function is called with two arguments: the number of not-done entries
12927 and the number of done entries.
12929 For example, the following function, when added to this hook, will switch
12930 an entry to DONE when all children are done, and back to TODO when new
12931 entries are set to a TODO status. Note that this hook is only called
12932 when there is a statistics cookie in the headline!
12934 (defun org-summary-todo (n-done n-not-done)
12935 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12936 (let (org-log-done org-log-states) ; turn off logging
12937 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12940 (defvar org-todo-statistics-hook nil
12941 "Hook that is run whenever Org thinks TODO statistics should be updated.
12942 This hook runs even if there is no statistics cookie present, in which case
12943 `org-after-todo-statistics-hook' would not run.")
12945 (defun org-todo-trigger-tag-changes (state)
12946 "Apply the changes defined in `org-todo-state-tags-triggers'."
12947 (let ((l org-todo-state-tags-triggers)
12948 changes)
12949 (when (or (not state) (equal state ""))
12950 (setq changes (append changes (cdr (assoc "" l)))))
12951 (when (and (stringp state) (> (length state) 0))
12952 (setq changes (append changes (cdr (assoc state l)))))
12953 (when (member state org-not-done-keywords)
12954 (setq changes (append changes (cdr (assoc 'todo l)))))
12955 (when (member state org-done-keywords)
12956 (setq changes (append changes (cdr (assoc 'done l)))))
12957 (dolist (c changes)
12958 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12960 (defun org-local-logging (value)
12961 "Get logging settings from a property VALUE."
12962 (let* (words w a)
12963 ;; directly set the variables, they are already local.
12964 (setq org-log-done nil
12965 org-log-repeat nil
12966 org-todo-log-states nil)
12967 (setq words (org-split-string value))
12968 (while (setq w (pop words))
12969 (cond
12970 ((setq a (assoc w org-startup-options))
12971 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12972 (set (nth 1 a) (nth 2 a))))
12973 ((setq a (org-extract-log-state-settings w))
12974 (and (member (car a) org-todo-keywords-1)
12975 (push a org-todo-log-states)))))))
12977 (defun org-get-todo-sequence-head (kwd)
12978 "Return the head of the TODO sequence to which KWD belongs.
12979 If KWD is not set, check if there is a text property remembering the
12980 right sequence."
12981 (let (p)
12982 (cond
12983 ((not kwd)
12984 (or (get-text-property (point-at-bol) 'org-todo-head)
12985 (progn
12986 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12987 nil (point-at-eol)))
12988 (get-text-property p 'org-todo-head))))
12989 ((not (member kwd org-todo-keywords-1))
12990 (car org-todo-keywords-1))
12991 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12993 (defun org-fast-todo-selection ()
12994 "Fast TODO keyword selection with single keys.
12995 Returns the new TODO keyword, or nil if no state change should occur."
12996 (let* ((fulltable org-todo-key-alist)
12997 (done-keywords org-done-keywords) ;; needed for the faces.
12998 (maxlen (apply 'max (mapcar
12999 (lambda (x)
13000 (if (stringp (car x)) (string-width (car x)) 0))
13001 fulltable)))
13002 (expert nil)
13003 (fwidth (+ maxlen 3 1 3))
13004 (ncol (/ (- (window-width) 4) fwidth))
13005 tg cnt e c tbl
13006 groups ingroup)
13007 (save-excursion
13008 (save-window-excursion
13009 (if expert
13010 (set-buffer (get-buffer-create " *Org todo*"))
13011 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13012 (erase-buffer)
13013 (org-set-local 'org-done-keywords done-keywords)
13014 (setq tbl fulltable cnt 0)
13015 (while (setq e (pop tbl))
13016 (cond
13017 ((equal e '(:startgroup))
13018 (push '() groups) (setq ingroup t)
13019 (when (not (= cnt 0))
13020 (setq cnt 0)
13021 (insert "\n"))
13022 (insert "{ "))
13023 ((equal e '(:endgroup))
13024 (setq ingroup nil cnt 0)
13025 (insert "}\n"))
13026 ((equal e '(:newline))
13027 (when (not (= cnt 0))
13028 (setq cnt 0)
13029 (insert "\n")
13030 (setq e (car tbl))
13031 (while (equal (car tbl) '(:newline))
13032 (insert "\n")
13033 (setq tbl (cdr tbl)))))
13035 (setq tg (car e) c (cdr e))
13036 (if ingroup (push tg (car groups)))
13037 (setq tg (org-add-props tg nil 'face
13038 (org-get-todo-face tg)))
13039 (if (and (= cnt 0) (not ingroup)) (insert " "))
13040 (insert "[" c "] " tg (make-string
13041 (- fwidth 4 (length tg)) ?\ ))
13042 (when (= (setq cnt (1+ cnt)) ncol)
13043 (insert "\n")
13044 (if ingroup (insert " "))
13045 (setq cnt 0)))))
13046 (insert "\n")
13047 (goto-char (point-min))
13048 (if (not expert) (org-fit-window-to-buffer))
13049 (message "[a-z..]:Set [SPC]:clear")
13050 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13051 (cond
13052 ((or (= c ?\C-g)
13053 (and (= c ?q) (not (rassoc c fulltable))))
13054 (setq quit-flag t))
13055 ((= c ?\ ) nil)
13056 ((setq e (rassoc c fulltable) tg (car e))
13058 (t (setq quit-flag t)))))))
13060 (defun org-entry-is-todo-p ()
13061 (member (org-get-todo-state) org-not-done-keywords))
13063 (defun org-entry-is-done-p ()
13064 (member (org-get-todo-state) org-done-keywords))
13066 (defun org-get-todo-state ()
13067 "Return the TODO keyword of the current subtree."
13068 (save-excursion
13069 (org-back-to-heading t)
13070 (and (looking-at org-todo-line-regexp)
13071 (match-end 2)
13072 (match-string 2))))
13074 (defun org-at-date-range-p (&optional inactive-ok)
13075 "Is the cursor inside a date range?"
13076 (interactive)
13077 (save-excursion
13078 (catch 'exit
13079 (let ((pos (point)))
13080 (skip-chars-backward "^[<\r\n")
13081 (skip-chars-backward "<[")
13082 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13083 (>= (match-end 0) pos)
13084 (throw 'exit t))
13085 (skip-chars-backward "^<[\r\n")
13086 (skip-chars-backward "<[")
13087 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13088 (>= (match-end 0) pos)
13089 (throw 'exit t)))
13090 nil)))
13092 (defun org-get-repeat (&optional tagline)
13093 "Check if there is a deadline/schedule with repeater in this entry."
13094 (save-match-data
13095 (save-excursion
13096 (org-back-to-heading t)
13097 (and (re-search-forward (if tagline
13098 (concat tagline "\\s-*" org-repeat-re)
13099 org-repeat-re)
13100 (org-entry-end-position) t)
13101 (match-string-no-properties 1)))))
13103 (defvar org-last-changed-timestamp)
13104 (defvar org-last-inserted-timestamp)
13105 (defvar org-log-post-message)
13106 (defvar org-log-note-purpose)
13107 (defvar org-log-note-how nil)
13108 (defvar org-log-note-extra)
13109 (defun org-auto-repeat-maybe (done-word)
13110 "Check if the current headline contains a repeated deadline/schedule.
13111 If yes, set TODO state back to what it was and change the base date
13112 of repeating deadline/scheduled time stamps to new date.
13113 This function is run automatically after each state change to a DONE state."
13114 ;; last-state is dynamically scoped into this function
13115 (let* ((repeat (org-get-repeat))
13116 (aa (assoc org-last-state org-todo-kwd-alist))
13117 (interpret (nth 1 aa))
13118 (head (nth 2 aa))
13119 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13120 (msg "Entry repeats: ")
13121 (org-log-done nil)
13122 (org-todo-log-states nil)
13123 re type n what ts time to-state)
13124 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13125 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13126 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13127 org-todo-repeat-to-state))
13128 (unless (and to-state (member to-state org-todo-keywords-1))
13129 (setq to-state (if (eq interpret 'type) org-last-state head)))
13130 (org-todo to-state)
13131 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13132 (org-entry-put nil "LAST_REPEAT" (format-time-string
13133 (org-time-stamp-format t t))))
13134 (when org-log-repeat
13135 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13136 (memq 'org-add-log-note post-command-hook))
13137 ;; OK, we are already setup for some record
13138 (if (eq org-log-repeat 'note)
13139 ;; make sure we take a note, not only a time stamp
13140 (setq org-log-note-how 'note))
13141 ;; Set up for taking a record
13142 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13143 org-last-state
13144 'findpos org-log-repeat)))
13145 (org-back-to-heading t)
13146 (org-add-planning-info nil nil 'closed)
13147 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13148 org-deadline-time-regexp "\\)\\|\\("
13149 org-ts-regexp "\\)"))
13150 (while (re-search-forward
13151 re (save-excursion (outline-next-heading) (point)) t)
13152 (setq type (if (match-end 1) org-scheduled-string
13153 (if (match-end 3) org-deadline-string "Plain:"))
13154 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13155 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13156 (setq n (string-to-number (match-string 2 ts))
13157 what (match-string 3 ts))
13158 (if (equal what "w") (setq n (* n 7) what "d"))
13159 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13160 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13161 ;; Preparation, see if we need to modify the start date for the change
13162 (when (match-end 1)
13163 (setq time (save-match-data (org-time-string-to-time ts)))
13164 (cond
13165 ((equal (match-string 1 ts) ".")
13166 ;; Shift starting date to today
13167 (org-timestamp-change
13168 (- (org-today) (time-to-days time))
13169 'day))
13170 ((equal (match-string 1 ts) "+")
13171 (let ((nshiftmax 10) (nshift 0))
13172 (while (or (= nshift 0)
13173 (<= (time-to-days time)
13174 (time-to-days (current-time))))
13175 (when (= (incf nshift) nshiftmax)
13176 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13177 (user-error "Abort")))
13178 (org-timestamp-change n (cdr (assoc what whata)))
13179 (org-at-timestamp-p t)
13180 (setq ts (match-string 1))
13181 (setq time (save-match-data (org-time-string-to-time ts)))))
13182 (org-timestamp-change (- n) (cdr (assoc what whata)))
13183 ;; rematch, so that we have everything in place for the real shift
13184 (org-at-timestamp-p t)
13185 (setq ts (match-string 1))
13186 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13187 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13188 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13189 (setq org-log-post-message msg)
13190 (message "%s" msg))))
13192 (defun org-show-todo-tree (arg)
13193 "Make a compact tree which shows all headlines marked with TODO.
13194 The tree will show the lines where the regexp matches, and all higher
13195 headlines above the match.
13196 With a \\[universal-argument] prefix, prompt for a regexp to match.
13197 With a numeric prefix N, construct a sparse tree for the Nth element
13198 of `org-todo-keywords-1'."
13199 (interactive "P")
13200 (let ((case-fold-search nil)
13201 (kwd-re
13202 (cond ((null arg) org-not-done-regexp)
13203 ((equal arg '(4))
13204 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13205 (mapcar 'list org-todo-keywords-1))))
13206 (concat "\\("
13207 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13208 "\\)\\>")))
13209 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13210 (regexp-quote (nth (1- (prefix-numeric-value arg))
13211 org-todo-keywords-1)))
13212 (t (user-error "Invalid prefix argument: %s" arg)))))
13213 (message "%d TODO entries found"
13214 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13216 (defun org-deadline (arg &optional time)
13217 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13218 With one universal prefix argument, remove any deadline from the item.
13219 With two universal prefix arguments, prompt for a warning delay.
13220 With argument TIME, set the deadline at the corresponding date. TIME
13221 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13222 (interactive "P")
13223 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13224 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13225 'region-start-level 'region))
13226 org-loop-over-headlines-in-active-region)
13227 (org-map-entries
13228 `(org-deadline ',arg ,time)
13229 org-loop-over-headlines-in-active-region
13230 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13231 (let* ((old-date (org-entry-get nil "DEADLINE"))
13232 (old-date-time (if old-date (org-time-string-to-time old-date)))
13233 (repeater (and old-date
13234 (string-match
13235 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13236 old-date)
13237 (match-string 1 old-date))))
13238 (cond
13239 ((equal arg '(4))
13240 (when (and old-date org-log-redeadline)
13241 (org-add-log-setup 'deldeadline nil old-date 'findpos
13242 org-log-redeadline))
13243 (org-remove-timestamp-with-keyword org-deadline-string)
13244 (message "Item no longer has a deadline."))
13245 ((equal arg '(16))
13246 (save-excursion
13247 (org-back-to-heading t)
13248 (if (re-search-forward
13249 org-deadline-time-regexp
13250 (save-excursion (outline-next-heading) (point)) t)
13251 (let* ((rpl0 (match-string 1))
13252 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13253 (replace-match
13254 (concat org-deadline-string
13255 " <" rpl
13256 (format " -%dd"
13257 (abs
13258 (- (time-to-days
13259 (save-match-data
13260 (org-read-date nil t nil "Warn starting from" old-date-time)))
13261 (time-to-days old-date-time))))
13262 ">") t t))
13263 (user-error "No deadline information to update"))))
13265 (org-add-planning-info 'deadline time 'closed)
13266 (when (and old-date org-log-redeadline
13267 (not (equal old-date
13268 (substring org-last-inserted-timestamp 1 -1))))
13269 (org-add-log-setup 'redeadline nil old-date 'findpos
13270 org-log-redeadline))
13271 (when repeater
13272 (save-excursion
13273 (org-back-to-heading t)
13274 (when (re-search-forward (concat org-deadline-string " "
13275 org-last-inserted-timestamp)
13276 (save-excursion
13277 (outline-next-heading) (point)) t)
13278 (goto-char (1- (match-end 0)))
13279 (insert " " repeater)
13280 (setq org-last-inserted-timestamp
13281 (concat (substring org-last-inserted-timestamp 0 -1)
13282 " " repeater
13283 (substring org-last-inserted-timestamp -1))))))
13284 (message "Deadline on %s" org-last-inserted-timestamp))))))
13286 (defun org-schedule (arg &optional time)
13287 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13288 With one universal prefix argument, remove any scheduling date from the item.
13289 With two universal prefix arguments, prompt for a delay cookie.
13290 With argument TIME, scheduled at the corresponding date. TIME can
13291 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13292 (interactive "P")
13293 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13294 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13295 'region-start-level 'region))
13296 org-loop-over-headlines-in-active-region)
13297 (org-map-entries
13298 `(org-schedule ',arg ,time)
13299 org-loop-over-headlines-in-active-region
13300 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13301 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13302 (old-date-time (if old-date (org-time-string-to-time old-date)))
13303 (repeater (and old-date
13304 (string-match
13305 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13306 old-date)
13307 (match-string 1 old-date))))
13308 (cond
13309 ((equal arg '(4))
13310 (progn
13311 (when (and old-date org-log-reschedule)
13312 (org-add-log-setup 'delschedule nil old-date 'findpos
13313 org-log-reschedule))
13314 (org-remove-timestamp-with-keyword org-scheduled-string)
13315 (message "Item is no longer scheduled.")))
13316 ((equal arg '(16))
13317 (save-excursion
13318 (org-back-to-heading t)
13319 (if (re-search-forward
13320 org-scheduled-time-regexp
13321 (save-excursion (outline-next-heading) (point)) t)
13322 (let* ((rpl0 (match-string 1))
13323 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13324 (replace-match
13325 (concat org-scheduled-string
13326 " <" rpl
13327 (format " -%dd"
13328 (abs
13329 (- (time-to-days
13330 (save-match-data
13331 (org-read-date nil t nil "Delay until" old-date-time)))
13332 (time-to-days old-date-time))))
13333 ">") t t))
13334 (user-error "No scheduled information to update"))))
13336 (org-add-planning-info 'scheduled time 'closed)
13337 (when (and old-date org-log-reschedule
13338 (not (equal old-date
13339 (substring org-last-inserted-timestamp 1 -1))))
13340 (org-add-log-setup 'reschedule nil old-date 'findpos
13341 org-log-reschedule))
13342 (when repeater
13343 (save-excursion
13344 (org-back-to-heading t)
13345 (when (re-search-forward (concat org-scheduled-string " "
13346 org-last-inserted-timestamp)
13347 (save-excursion
13348 (outline-next-heading) (point)) t)
13349 (goto-char (1- (match-end 0)))
13350 (insert " " repeater)
13351 (setq org-last-inserted-timestamp
13352 (concat (substring org-last-inserted-timestamp 0 -1)
13353 " " repeater
13354 (substring org-last-inserted-timestamp -1))))))
13355 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13357 (defun org-get-scheduled-time (pom &optional inherit)
13358 "Get the scheduled time as a time tuple, of a format suitable
13359 for calling org-schedule with, or if there is no scheduling,
13360 returns nil."
13361 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13362 (when time
13363 (apply 'encode-time (org-parse-time-string time)))))
13365 (defun org-get-deadline-time (pom &optional inherit)
13366 "Get the deadline as a time tuple, of a format suitable for
13367 calling org-deadline with, or if there is no scheduling, returns
13368 nil."
13369 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13370 (when time
13371 (apply 'encode-time (org-parse-time-string time)))))
13373 (defun org-remove-timestamp-with-keyword (keyword)
13374 "Remove all time stamps with KEYWORD in the current entry."
13375 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13376 beg)
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (setq beg (point))
13380 (outline-next-heading)
13381 (while (re-search-backward re beg t)
13382 (replace-match "")
13383 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13384 (equal (char-before) ?\ ))
13385 (backward-delete-char 1)
13386 (if (string-match "^[ \t]*$" (buffer-substring
13387 (point-at-bol) (point-at-eol)))
13388 (delete-region (point-at-bol)
13389 (min (point-max) (1+ (point-at-eol))))))))))
13391 (defvar org-time-was-given) ; dynamically scoped parameter
13392 (defvar org-end-time-was-given) ; dynamically scoped parameter
13394 (defun org-add-planning-info (what &optional time &rest remove)
13395 "Insert new timestamp with keyword in the line directly after the headline.
13396 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13397 If non is given, the user is prompted for a date.
13398 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13399 be removed."
13400 (interactive)
13401 (let (org-time-was-given org-end-time-was-given ts
13402 end default-time default-input)
13404 (catch 'exit
13405 (when (and (memq what '(scheduled deadline))
13406 (or (not time)
13407 (and (stringp time)
13408 (string-match "^[-+]+[0-9]" time))))
13409 ;; Try to get a default date/time from existing timestamp
13410 (save-excursion
13411 (org-back-to-heading t)
13412 (setq end (save-excursion (outline-next-heading) (point)))
13413 (when (re-search-forward (if (eq what 'scheduled)
13414 org-scheduled-time-regexp
13415 org-deadline-time-regexp)
13416 end t)
13417 (setq ts (match-string 1)
13418 default-time
13419 (apply 'encode-time (org-parse-time-string ts))
13420 default-input (and ts (org-get-compact-tod ts))))))
13421 (when what
13422 (setq time
13423 (if (stringp time)
13424 ;; This is a string (relative or absolute), set proper date
13425 (apply 'encode-time
13426 (org-read-date-analyze
13427 time default-time (decode-time default-time)))
13428 ;; If necessary, get the time from the user
13429 (or time (org-read-date nil 'to-time nil nil
13430 default-time default-input)))))
13432 (when (and org-insert-labeled-timestamps-at-point
13433 (member what '(scheduled deadline)))
13434 (insert
13435 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13436 (org-insert-time-stamp time org-time-was-given
13437 nil nil nil (list org-end-time-was-given))
13438 (setq what nil))
13439 (save-excursion
13440 (save-restriction
13441 (let (col list elt ts buffer-invisibility-spec)
13442 (org-back-to-heading t)
13443 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13444 (goto-char (match-end 1))
13445 (setq col (current-column))
13446 (goto-char (match-end 0))
13447 (if (eobp) (insert "\n") (forward-char 1))
13448 (when (and (not what)
13449 (not (looking-at
13450 (concat "[ \t]*"
13451 org-keyword-time-not-clock-regexp))))
13452 ;; Nothing to add, nothing to remove...... :-)
13453 (throw 'exit nil))
13454 (if (and (not (looking-at org-outline-regexp))
13455 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13456 "[^\r\n]*"))
13457 (not (equal (match-string 1) org-clock-string)))
13458 (narrow-to-region (match-beginning 0) (match-end 0))
13459 (insert-before-markers "\n")
13460 (backward-char 1)
13461 (narrow-to-region (point) (point))
13462 (and org-adapt-indentation (org-indent-to-column col)))
13463 ;; Check if we have to remove something.
13464 (setq list (cons what remove))
13465 (while list
13466 (setq elt (pop list))
13467 (when (or (and (eq elt 'scheduled)
13468 (re-search-forward org-scheduled-time-regexp nil t))
13469 (and (eq elt 'deadline)
13470 (re-search-forward org-deadline-time-regexp nil t))
13471 (and (eq elt 'closed)
13472 (re-search-forward org-closed-time-regexp nil t)))
13473 (replace-match "")
13474 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13475 (and (looking-at "[ \t]+") (replace-match ""))
13476 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13477 (when what
13478 (insert
13479 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13480 (cond ((eq what 'scheduled) org-scheduled-string)
13481 ((eq what 'deadline) org-deadline-string)
13482 ((eq what 'closed) org-closed-string))
13483 " ")
13484 (setq ts (org-insert-time-stamp
13485 time
13486 (or org-time-was-given
13487 (and (eq what 'closed) org-log-done-with-time))
13488 (eq what 'closed)
13489 nil nil (list org-end-time-was-given)))
13490 (insert
13491 (if (not (or (bolp) (eq (char-before) ?\ )
13492 (memq (char-after) '(32 10))
13493 (eobp))) " " ""))
13494 (end-of-line 1))
13495 (goto-char (point-min))
13496 (widen)
13497 (if (and (looking-at "[ \t]*\n")
13498 (equal (char-before) ?\n))
13499 (delete-region (1- (point)) (point-at-eol)))
13500 ts))))))
13502 (defvar org-log-note-marker (make-marker))
13503 (defvar org-log-note-purpose nil)
13504 (defvar org-log-note-state nil)
13505 (defvar org-log-note-previous-state nil)
13506 (defvar org-log-note-extra nil)
13507 (defvar org-log-note-window-configuration nil)
13508 (defvar org-log-note-return-to (make-marker))
13509 (defvar org-log-note-effective-time nil
13510 "Remembered current time so that dynamically scoped
13511 `org-extend-today-until' affects tha timestamps in state change
13512 log")
13514 (defvar org-log-post-message nil
13515 "Message to be displayed after a log note has been stored.
13516 The auto-repeater uses this.")
13518 (defun org-add-note ()
13519 "Add a note to the current entry.
13520 This is done in the same way as adding a state change note."
13521 (interactive)
13522 (org-add-log-setup 'note nil nil 'findpos nil))
13524 (defvar org-property-end-re)
13525 (defun org-add-log-setup (&optional purpose state prev-state
13526 findpos how extra)
13527 "Set up the post command hook to take a note.
13528 If this is about to TODO state change, the new state is expected in STATE.
13529 When FINDPOS is non-nil, find the correct position for the note in
13530 the current entry. If not, assume that it can be inserted at point.
13531 HOW is an indicator what kind of note should be created.
13532 EXTRA is additional text that will be inserted into the notes buffer."
13533 (let* ((org-log-into-drawer (org-log-into-drawer))
13534 (drawer (cond ((stringp org-log-into-drawer)
13535 org-log-into-drawer)
13536 (org-log-into-drawer "LOGBOOK"))))
13537 (save-restriction
13538 (save-excursion
13539 (when findpos
13540 (org-back-to-heading t)
13541 (narrow-to-region (point) (save-excursion
13542 (outline-next-heading) (point)))
13543 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13544 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13545 "[^\r\n]*\\)?"))
13546 (goto-char (match-end 0))
13547 (cond
13548 (drawer
13549 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13550 nil t)
13551 (progn
13552 (goto-char (match-end 0))
13553 (or org-log-states-order-reversed
13554 (and (re-search-forward org-property-end-re nil t)
13555 (goto-char (1- (match-beginning 0))))))
13556 (insert "\n:" drawer ":\n:END:")
13557 (beginning-of-line 0)
13558 (org-indent-line)
13559 (beginning-of-line 2)
13560 (org-indent-line)
13561 (end-of-line 0)))
13562 ((and org-log-state-notes-insert-after-drawers
13563 (save-excursion
13564 (forward-line) (looking-at org-drawer-regexp)))
13565 (forward-line)
13566 (while (looking-at org-drawer-regexp)
13567 (goto-char (match-end 0))
13568 (re-search-forward org-property-end-re (point-max) t)
13569 (forward-line))
13570 (forward-line -1)))
13571 (unless org-log-states-order-reversed
13572 (and (= (char-after) ?\n) (forward-char 1))
13573 (org-skip-over-state-notes)
13574 (skip-chars-backward " \t\n\r")))
13575 (move-marker org-log-note-marker (point))
13576 (setq org-log-note-purpose purpose
13577 org-log-note-state state
13578 org-log-note-previous-state prev-state
13579 org-log-note-how how
13580 org-log-note-extra extra
13581 org-log-note-effective-time (org-current-effective-time))
13582 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13584 (defun org-skip-over-state-notes ()
13585 "Skip past the list of State notes in an entry."
13586 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13587 (when (ignore-errors (goto-char (org-in-item-p)))
13588 (let* ((struct (org-list-struct))
13589 (prevs (org-list-prevs-alist struct)))
13590 (while (looking-at "[ \t]*- State")
13591 (goto-char (or (org-list-get-next-item (point) struct prevs)
13592 (org-list-get-item-end (point) struct)))))))
13594 (defun org-add-log-note (&optional purpose)
13595 "Pop up a window for taking a note, and add this note later at point."
13596 (remove-hook 'post-command-hook 'org-add-log-note)
13597 (setq org-log-note-window-configuration (current-window-configuration))
13598 (delete-other-windows)
13599 (move-marker org-log-note-return-to (point))
13600 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13601 (goto-char org-log-note-marker)
13602 (org-switch-to-buffer-other-window "*Org Note*")
13603 (erase-buffer)
13604 (if (memq org-log-note-how '(time state))
13605 (let (current-prefix-arg) (org-store-log-note))
13606 (let ((org-inhibit-startup t)) (org-mode))
13607 (insert (format "# Insert note for %s.
13608 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13609 (cond
13610 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13611 ((eq org-log-note-purpose 'done) "closed todo item")
13612 ((eq org-log-note-purpose 'state)
13613 (format "state change from \"%s\" to \"%s\""
13614 (or org-log-note-previous-state "")
13615 (or org-log-note-state "")))
13616 ((eq org-log-note-purpose 'reschedule)
13617 "rescheduling")
13618 ((eq org-log-note-purpose 'delschedule)
13619 "no longer scheduled")
13620 ((eq org-log-note-purpose 'redeadline)
13621 "changing deadline")
13622 ((eq org-log-note-purpose 'deldeadline)
13623 "removing deadline")
13624 ((eq org-log-note-purpose 'refile)
13625 "refiling")
13626 ((eq org-log-note-purpose 'note)
13627 "this entry")
13628 (t (error "This should not happen")))))
13629 (if org-log-note-extra (insert org-log-note-extra))
13630 (org-set-local 'org-finish-function 'org-store-log-note)
13631 (run-hooks 'org-log-buffer-setup-hook)))
13633 (defvar org-note-abort nil) ; dynamically scoped
13634 (defun org-store-log-note ()
13635 "Finish taking a log note, and insert it to where it belongs."
13636 (let ((txt (buffer-string)))
13637 (kill-buffer (current-buffer))
13638 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13639 lines ind bul)
13640 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13641 (setq txt (replace-match "" t t txt)))
13642 (if (string-match "\\s-+\\'" txt)
13643 (setq txt (replace-match "" t t txt)))
13644 (setq lines (org-split-string txt "\n"))
13645 (when (and note (string-match "\\S-" note))
13646 (setq note
13647 (org-replace-escapes
13648 note
13649 (list (cons "%u" (user-login-name))
13650 (cons "%U" user-full-name)
13651 (cons "%t" (format-time-string
13652 (org-time-stamp-format 'long 'inactive)
13653 org-log-note-effective-time))
13654 (cons "%T" (format-time-string
13655 (org-time-stamp-format 'long nil)
13656 org-log-note-effective-time))
13657 (cons "%d" (format-time-string
13658 (org-time-stamp-format nil 'inactive)
13659 org-log-note-effective-time))
13660 (cons "%D" (format-time-string
13661 (org-time-stamp-format nil nil)
13662 org-log-note-effective-time))
13663 (cons "%s" (if org-log-note-state
13664 (concat "\"" org-log-note-state "\"")
13665 ""))
13666 (cons "%S" (if org-log-note-previous-state
13667 (concat "\"" org-log-note-previous-state "\"")
13668 "\"\"")))))
13669 (if lines (setq note (concat note " \\\\")))
13670 (push note lines))
13671 (when (or current-prefix-arg org-note-abort)
13672 (when org-log-into-drawer
13673 (org-remove-empty-drawer-at org-log-note-marker))
13674 (setq lines nil))
13675 (when lines
13676 (with-current-buffer (marker-buffer org-log-note-marker)
13677 (save-excursion
13678 (goto-char org-log-note-marker)
13679 (move-marker org-log-note-marker nil)
13680 (end-of-line 1)
13681 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13682 (setq ind (save-excursion
13683 (if (ignore-errors (goto-char (org-in-item-p)))
13684 (let ((struct (org-list-struct)))
13685 (org-list-get-ind
13686 (org-list-get-top-point struct) struct))
13687 (skip-chars-backward " \r\t\n")
13688 (cond
13689 ((and (org-at-heading-p)
13690 org-adapt-indentation)
13691 (1+ (org-current-level)))
13692 ((org-at-heading-p) 0)
13693 (t (org-get-indentation))))))
13694 (setq bul (org-list-bullet-string "-"))
13695 (org-indent-line-to ind)
13696 (insert bul (pop lines))
13697 (let ((ind-body (+ (length bul) ind)))
13698 (while lines
13699 (insert "\n")
13700 (org-indent-line-to ind-body)
13701 (insert (pop lines))))
13702 (message "Note stored")
13703 (org-back-to-heading t)
13704 (org-cycle-hide-drawers 'children))
13705 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13706 ;; from within `org-add-log-note' because `buffer-undo-list'
13707 ;; is then modified outside of `org-with-remote-undo'.
13708 (when (eq this-command 'org-agenda-todo)
13709 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13710 ;; Don't add undo information when called from `org-agenda-todo'
13711 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13712 (set-window-configuration org-log-note-window-configuration)
13713 (with-current-buffer (marker-buffer org-log-note-return-to)
13714 (goto-char org-log-note-return-to))
13715 (move-marker org-log-note-return-to nil)
13716 (and org-log-post-message (message "%s" org-log-post-message))))
13718 (defun org-remove-empty-drawer-at (pos)
13719 "Remove an empty drawer at position POS.
13720 POS may also be a marker."
13721 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13722 (org-with-wide-buffer
13723 (goto-char pos)
13724 (let ((drawer (org-element-at-point)))
13725 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13726 (not (org-element-property :contents-begin drawer)))
13727 (delete-region (org-element-property :begin drawer)
13728 (progn (goto-char (org-element-property :end drawer))
13729 (skip-chars-backward " \r\t\n")
13730 (forward-line)
13731 (point))))))))
13733 (defvar org-ts-type nil)
13734 (defun org-sparse-tree (&optional arg type)
13735 "Create a sparse tree, prompt for the details.
13736 This command can create sparse trees. You first need to select the type
13737 of match used to create the tree:
13739 t Show all TODO entries.
13740 T Show entries with a specific TODO keyword.
13741 m Show entries selected by a tags/property match.
13742 p Enter a property name and its value (both with completion on existing
13743 names/values) and show entries with that property.
13744 r Show entries matching a regular expression (`/' can be used as well).
13745 b Show deadlines and scheduled items before a date.
13746 a Show deadlines and scheduled items after a date.
13747 d Show deadlines due within `org-deadline-warning-days'.
13748 D Show deadlines and scheduled items between a date range."
13749 (interactive "P")
13750 (setq type (or type org-sparse-tree-default-date-type))
13751 (setq org-ts-type type)
13752 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13753 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13754 [c]ycle through date types: %s"
13755 (case type
13756 (all "all timestamps")
13757 (scheduled "only scheduled")
13758 (deadline "only deadline")
13759 (active "only active timestamps")
13760 (inactive "only inactive timestamps")
13761 (scheduled-or-deadline "scheduled/deadline")
13762 (closed "with a closed time-stamp")
13763 (otherwise "scheduled/deadline")))
13764 (let ((answer (read-char-exclusive)))
13765 (case answer
13767 (org-sparse-tree
13769 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13770 inactive closed)))))
13771 (?d (call-interactively 'org-check-deadlines))
13772 (?b (call-interactively 'org-check-before-date))
13773 (?a (call-interactively 'org-check-after-date))
13774 (?D (call-interactively 'org-check-dates-range))
13775 (?t (call-interactively 'org-show-todo-tree))
13776 (?T (org-show-todo-tree '(4)))
13777 (?m (call-interactively 'org-match-sparse-tree))
13778 ((?p ?P)
13779 (let* ((kwd (org-icompleting-read
13780 "Property: " (mapcar 'list (org-buffer-property-keys))))
13781 (value (org-icompleting-read
13782 "Value: " (mapcar 'list (org-property-values kwd)))))
13783 (unless (string-match "\\`{.*}\\'" value)
13784 (setq value (concat "\"" value "\"")))
13785 (org-match-sparse-tree arg (concat kwd "=" value))))
13786 ((?r ?R ?/) (call-interactively 'org-occur))
13787 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13789 (defvar org-occur-highlights nil
13790 "List of overlays used for occur matches.")
13791 (make-variable-buffer-local 'org-occur-highlights)
13792 (defvar org-occur-parameters nil
13793 "Parameters of the active org-occur calls.
13794 This is a list, each call to org-occur pushes as cons cell,
13795 containing the regular expression and the callback, onto the list.
13796 The list can contain several entries if `org-occur' has been called
13797 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13798 will only contain one set of parameters. When the highlights are
13799 removed (for example with `C-c C-c', or with the next edit (depending
13800 on `org-remove-highlights-with-change'), this variable is emptied
13801 as well.")
13802 (make-variable-buffer-local 'org-occur-parameters)
13804 (defun org-occur (regexp &optional keep-previous callback)
13805 "Make a compact tree which shows all matches of REGEXP.
13806 The tree will show the lines where the regexp matches, and all higher
13807 headlines above the match. It will also show the heading after the match,
13808 to make sure editing the matching entry is easy.
13809 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13810 call to `org-occur' will be kept, to allow stacking of calls to this
13811 command.
13812 If CALLBACK is non-nil, it is a function which is called to confirm
13813 that the match should indeed be shown."
13814 (interactive "sRegexp: \nP")
13815 (when (equal regexp "")
13816 (user-error "Regexp cannot be empty"))
13817 (unless keep-previous
13818 (org-remove-occur-highlights nil nil t))
13819 (push (cons regexp callback) org-occur-parameters)
13820 (let ((cnt 0))
13821 (save-excursion
13822 (goto-char (point-min))
13823 (if (or (not keep-previous) ; do not want to keep
13824 (not org-occur-highlights)) ; no previous matches
13825 ;; hide everything
13826 (org-overview))
13827 (while (re-search-forward regexp nil t)
13828 (when (or (not callback)
13829 (save-match-data (funcall callback)))
13830 (setq cnt (1+ cnt))
13831 (when org-highlight-sparse-tree-matches
13832 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13833 (org-show-context 'occur-tree))))
13834 (when org-remove-highlights-with-change
13835 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13836 nil 'local))
13837 (unless org-sparse-tree-open-archived-trees
13838 (org-hide-archived-subtrees (point-min) (point-max)))
13839 (run-hooks 'org-occur-hook)
13840 (if (org-called-interactively-p 'interactive)
13841 (message "%d match(es) for regexp %s" cnt regexp))
13842 cnt))
13844 (defun org-occur-next-match (&optional n reset)
13845 "Function for `next-error-function' to find sparse tree matches.
13846 N is the number of matches to move, when negative move backwards.
13847 RESET is entirely ignored - this function always goes back to the
13848 starting point when no match is found."
13849 (let* ((limit (if (< n 0) (point-min) (point-max)))
13850 (search-func (if (< n 0)
13851 'previous-single-char-property-change
13852 'next-single-char-property-change))
13853 (n (abs n))
13854 (pos (point))
13856 (catch 'exit
13857 (while (setq p1 (funcall search-func (point) 'org-type))
13858 (when (equal p1 limit)
13859 (goto-char pos)
13860 (user-error "No more matches"))
13861 (when (equal (get-char-property p1 'org-type) 'org-occur)
13862 (setq n (1- n))
13863 (when (= n 0)
13864 (goto-char p1)
13865 (throw 'exit (point))))
13866 (goto-char p1))
13867 (goto-char p1)
13868 (user-error "No more matches"))))
13870 (defun org-show-context (&optional key)
13871 "Make sure point and context are visible.
13872 How much context is shown depends upon the variables
13873 `org-show-hierarchy-above', `org-show-following-heading',
13874 `org-show-entry-below' and `org-show-siblings'."
13875 (let ((heading-p (org-at-heading-p t))
13876 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13877 (following-p (org-get-alist-option org-show-following-heading key))
13878 (entry-p (org-get-alist-option org-show-entry-below key))
13879 (siblings-p (org-get-alist-option org-show-siblings key)))
13880 ;; Show heading or entry text
13881 (if (and heading-p (not entry-p))
13882 (org-flag-heading nil) ; only show the heading
13883 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13884 (org-show-hidden-entry))) ; show entire entry
13885 (when following-p
13886 ;; Show next sibling, or heading below text
13887 (save-excursion
13888 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13889 (org-flag-heading nil))))
13890 (when siblings-p (org-show-siblings))
13891 (when hierarchy-p
13892 ;; show all higher headings, possibly with siblings
13893 (save-excursion
13894 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13895 (not (bobp)))
13896 (org-flag-heading nil)
13897 (when siblings-p (org-show-siblings)))))))
13899 (defvar org-reveal-start-hook nil
13900 "Hook run before revealing a location.")
13902 (defun org-reveal (&optional siblings)
13903 "Show current entry, hierarchy above it, and the following headline.
13904 This can be used to show a consistent set of context around locations
13905 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13906 not t for the search context.
13908 With optional argument SIBLINGS, on each level of the hierarchy all
13909 siblings are shown. This repairs the tree structure to what it would
13910 look like when opened with hierarchical calls to `org-cycle'.
13911 With double optional argument \\[universal-argument] \\[universal-argument], \
13912 go to the parent and show the
13913 entire tree."
13914 (interactive "P")
13915 (run-hooks 'org-reveal-start-hook)
13916 (let ((org-show-hierarchy-above t)
13917 (org-show-following-heading t)
13918 (org-show-siblings (if siblings t org-show-siblings)))
13919 (org-show-context nil))
13920 (when (equal siblings '(16))
13921 (save-excursion
13922 (when (org-up-heading-safe)
13923 (org-show-subtree)
13924 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13926 (defun org-highlight-new-match (beg end)
13927 "Highlight from BEG to END and mark the highlight is an occur headline."
13928 (let ((ov (make-overlay beg end)))
13929 (overlay-put ov 'face 'secondary-selection)
13930 (overlay-put ov 'org-type 'org-occur)
13931 (push ov org-occur-highlights)))
13933 (defun org-remove-occur-highlights (&optional beg end noremove)
13934 "Remove the occur highlights from the buffer.
13935 BEG and END are ignored. If NOREMOVE is nil, remove this function
13936 from the `before-change-functions' in the current buffer."
13937 (interactive)
13938 (unless org-inhibit-highlight-removal
13939 (mapc 'delete-overlay org-occur-highlights)
13940 (setq org-occur-highlights nil)
13941 (setq org-occur-parameters nil)
13942 (unless noremove
13943 (remove-hook 'before-change-functions
13944 'org-remove-occur-highlights 'local))))
13946 ;;;; Priorities
13948 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13949 "Regular expression matching the priority indicator.")
13951 (defvar org-remove-priority-next-time nil)
13953 (defun org-priority-up ()
13954 "Increase the priority of the current item."
13955 (interactive)
13956 (org-priority 'up))
13958 (defun org-priority-down ()
13959 "Decrease the priority of the current item."
13960 (interactive)
13961 (org-priority 'down))
13963 (defun org-priority (&optional action show)
13964 "Change the priority of an item.
13965 ACTION can be `set', `up', `down', or a character."
13966 (interactive "P")
13967 (if (equal action '(4))
13968 (org-show-priority)
13969 (unless org-enable-priority-commands
13970 (user-error "Priority commands are disabled"))
13971 (setq action (or action 'set))
13972 (let (current new news have remove)
13973 (save-excursion
13974 (org-back-to-heading t)
13975 (if (looking-at org-priority-regexp)
13976 (setq current (string-to-char (match-string 2))
13977 have t))
13978 (cond
13979 ((eq action 'remove)
13980 (setq remove t new ?\ ))
13981 ((or (eq action 'set)
13982 (if (featurep 'xemacs) (characterp action) (integerp action)))
13983 (if (not (eq action 'set))
13984 (setq new action)
13985 (message "Priority %c-%c, SPC to remove: "
13986 org-highest-priority org-lowest-priority)
13987 (save-match-data
13988 (setq new (read-char-exclusive))))
13989 (if (and (= (upcase org-highest-priority) org-highest-priority)
13990 (= (upcase org-lowest-priority) org-lowest-priority))
13991 (setq new (upcase new)))
13992 (cond ((equal new ?\ ) (setq remove t))
13993 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13994 (user-error "Priority must be between `%c' and `%c'"
13995 org-highest-priority org-lowest-priority))))
13996 ((eq action 'up)
13997 (setq new (if have
13998 (1- current) ; normal cycling
13999 ;; last priority was empty
14000 (if (eq last-command this-command)
14001 org-lowest-priority ; wrap around empty to lowest
14002 ;; default
14003 (if org-priority-start-cycle-with-default
14004 org-default-priority
14005 (1- org-default-priority))))))
14006 ((eq action 'down)
14007 (setq new (if have
14008 (1+ current) ; normal cycling
14009 ;; last priority was empty
14010 (if (eq last-command this-command)
14011 org-highest-priority ; wrap around empty to highest
14012 ;; default
14013 (if org-priority-start-cycle-with-default
14014 org-default-priority
14015 (1+ org-default-priority))))))
14016 (t (user-error "Invalid action")))
14017 (if (or (< (upcase new) org-highest-priority)
14018 (> (upcase new) org-lowest-priority))
14019 (if (and (memq action '(up down))
14020 (not have) (not (eq last-command this-command)))
14021 ;; `new' is from default priority
14022 (error
14023 "The default can not be set, see `org-default-priority' why")
14024 ;; normal cycling: `new' is beyond highest/lowest priority
14025 ;; and is wrapped around to the empty priority
14026 (setq remove t)))
14027 (setq news (format "%c" new))
14028 (if have
14029 (if remove
14030 (replace-match "" t t nil 1)
14031 (replace-match news t t nil 2))
14032 (if remove
14033 (user-error "No priority cookie found in line")
14034 (let ((case-fold-search nil))
14035 (looking-at org-todo-line-regexp))
14036 (if (match-end 2)
14037 (progn
14038 (goto-char (match-end 2))
14039 (insert " [#" news "]"))
14040 (goto-char (match-beginning 3))
14041 (insert "[#" news "] "))))
14042 (org-set-tags nil 'align))
14043 (if remove
14044 (message "Priority removed")
14045 (message "Priority of current item set to %s" news)))))
14047 (defun org-show-priority ()
14048 "Show the priority of the current item.
14049 This priority is composed of the main priority given with the [#A] cookies,
14050 and by additional input from the age of a schedules or deadline entry."
14051 (interactive)
14052 (let ((pri (if (eq major-mode 'org-agenda-mode)
14053 (org-get-at-bol 'priority)
14054 (save-excursion
14055 (save-match-data
14056 (beginning-of-line)
14057 (and (looking-at org-heading-regexp)
14058 (org-get-priority (match-string 0))))))))
14059 (message "Priority is %d" (if pri pri -1000))))
14061 (defun org-get-priority (s)
14062 "Find priority cookie and return priority."
14063 (save-match-data
14064 (if (functionp org-get-priority-function)
14065 (funcall org-get-priority-function)
14066 (if (not (string-match org-priority-regexp s))
14067 (* 1000 (- org-lowest-priority org-default-priority))
14068 (* 1000 (- org-lowest-priority
14069 (string-to-char (match-string 2 s))))))))
14071 ;;;; Tags
14073 (defvar org-agenda-archives-mode)
14074 (defvar org-map-continue-from nil
14075 "Position from where mapping should continue.
14076 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14078 (defvar org-scanner-tags nil
14079 "The current tag list while the tags scanner is running.")
14080 (defvar org-trust-scanner-tags nil
14081 "Should `org-get-tags-at' use the tags for the scanner.
14082 This is for internal dynamical scoping only.
14083 When this is non-nil, the function `org-get-tags-at' will return the value
14084 of `org-scanner-tags' instead of building the list by itself. This
14085 can lead to large speed-ups when the tags scanner is used in a file with
14086 many entries, and when the list of tags is retrieved, for example to
14087 obtain a list of properties. Building the tags list for each entry in such
14088 a file becomes an N^2 operation - but with this variable set, it scales
14089 as N.")
14091 (defun org-scan-tags (action matcher todo-only &optional start-level)
14092 "Scan headline tags with inheritance and produce output ACTION.
14094 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14095 or `agenda' to produce an entry list for an agenda view. It can also be
14096 a Lisp form or a function that should be called at each matched headline, in
14097 this case the return value is a list of all return values from these calls.
14099 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14100 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14101 only lines with a not-done TODO keyword are included in the output.
14102 This should be the same variable that was scoped into
14103 and set by `org-make-tags-matcher' when it constructed MATCHER.
14105 START-LEVEL can be a string with asterisks, reducing the scope to
14106 headlines matching this string."
14107 (require 'org-agenda)
14108 (let* ((re (concat "^"
14109 (if start-level
14110 ;; Get the correct level to match
14111 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14112 org-outline-regexp)
14113 " *\\(\\<\\("
14114 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14115 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14116 (props (list 'face 'default
14117 'done-face 'org-agenda-done
14118 'undone-face 'default
14119 'mouse-face 'highlight
14120 'org-not-done-regexp org-not-done-regexp
14121 'org-todo-regexp org-todo-regexp
14122 'org-complex-heading-regexp org-complex-heading-regexp
14123 'help-echo
14124 (format "mouse-2 or RET jump to org file %s"
14125 (abbreviate-file-name
14126 (or (buffer-file-name (buffer-base-buffer))
14127 (buffer-name (buffer-base-buffer)))))))
14128 (org-map-continue-from nil)
14129 lspos tags tags-list
14130 (tags-alist (list (cons 0 org-file-tags)))
14131 (llast 0) rtn rtn1 level category i txt
14132 todo marker entry priority)
14133 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14134 (setq action (list 'lambda nil action)))
14135 (save-excursion
14136 (goto-char (point-min))
14137 (when (eq action 'sparse-tree)
14138 (org-overview)
14139 (org-remove-occur-highlights))
14140 (while (let (case-fold-search)
14141 (re-search-forward re nil t))
14142 (setq org-map-continue-from nil)
14143 (catch :skip
14144 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14145 tags (if (match-end 4) (org-match-string-no-properties 4)))
14146 (goto-char (setq lspos (match-beginning 0)))
14147 (setq level (org-reduced-level (org-outline-level))
14148 category (org-get-category))
14149 (setq i llast llast level)
14150 ;; remove tag lists from same and sublevels
14151 (while (>= i level)
14152 (when (setq entry (assoc i tags-alist))
14153 (setq tags-alist (delete entry tags-alist)))
14154 (setq i (1- i)))
14155 ;; add the next tags
14156 (when tags
14157 (setq tags (org-split-string tags ":")
14158 tags-alist
14159 (cons (cons level tags) tags-alist)))
14160 ;; compile tags for current headline
14161 (setq tags-list
14162 (if org-use-tag-inheritance
14163 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14164 tags)
14165 org-scanner-tags tags-list)
14166 (when org-use-tag-inheritance
14167 (setcdr (car tags-alist)
14168 (mapcar (lambda (x)
14169 (setq x (copy-sequence x))
14170 (org-add-prop-inherited x))
14171 (cdar tags-alist))))
14172 (when (and tags org-use-tag-inheritance
14173 (or (not (eq t org-use-tag-inheritance))
14174 org-tags-exclude-from-inheritance))
14175 ;; selective inheritance, remove uninherited ones
14176 (setcdr (car tags-alist)
14177 (org-remove-uninherited-tags (cdar tags-alist))))
14178 (when (and
14180 ;; eval matcher only when the todo condition is OK
14181 (and (or (not todo-only) (member todo org-not-done-keywords))
14182 (let ((case-fold-search t) (org-trust-scanner-tags t))
14183 (eval matcher)))
14185 ;; Call the skipper, but return t if it does not skip,
14186 ;; so that the `and' form continues evaluating
14187 (progn
14188 (unless (eq action 'sparse-tree) (org-agenda-skip))
14191 ;; Check if timestamps are deselecting this entry
14192 (or (not todo-only)
14193 (and (member todo org-not-done-keywords)
14194 (or (not org-agenda-tags-todo-honor-ignore-options)
14195 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14197 ;; select this headline
14198 (cond
14199 ((eq action 'sparse-tree)
14200 (and org-highlight-sparse-tree-matches
14201 (org-get-heading) (match-end 0)
14202 (org-highlight-new-match
14203 (match-beginning 1) (match-end 1)))
14204 (org-show-context 'tags-tree))
14205 ((eq action 'agenda)
14206 (setq txt (org-agenda-format-item
14208 (concat
14209 (if (eq org-tags-match-list-sublevels 'indented)
14210 (make-string (1- level) ?.) "")
14211 (org-get-heading))
14212 level category
14213 tags-list)
14214 priority (org-get-priority txt))
14215 (goto-char lspos)
14216 (setq marker (org-agenda-new-marker))
14217 (org-add-props txt props
14218 'org-marker marker 'org-hd-marker marker 'org-category category
14219 'todo-state todo
14220 'priority priority 'type "tagsmatch")
14221 (push txt rtn))
14222 ((functionp action)
14223 (setq org-map-continue-from nil)
14224 (save-excursion
14225 (setq rtn1 (funcall action))
14226 (push rtn1 rtn)))
14227 (t (user-error "Invalid action")))
14229 ;; if we are to skip sublevels, jump to end of subtree
14230 (unless org-tags-match-list-sublevels
14231 (org-end-of-subtree t)
14232 (backward-char 1))))
14233 ;; Get the correct position from where to continue
14234 (if org-map-continue-from
14235 (goto-char org-map-continue-from)
14236 (and (= (point) lspos) (end-of-line 1)))))
14237 (when (and (eq action 'sparse-tree)
14238 (not org-sparse-tree-open-archived-trees))
14239 (org-hide-archived-subtrees (point-min) (point-max)))
14240 (nreverse rtn)))
14242 (defun org-remove-uninherited-tags (tags)
14243 "Remove all tags that are not inherited from the list TAGS."
14244 (cond
14245 ((eq org-use-tag-inheritance t)
14246 (if org-tags-exclude-from-inheritance
14247 (org-delete-all org-tags-exclude-from-inheritance tags)
14248 tags))
14249 ((not org-use-tag-inheritance) nil)
14250 ((stringp org-use-tag-inheritance)
14251 (delq nil (mapcar
14252 (lambda (x)
14253 (if (and (string-match org-use-tag-inheritance x)
14254 (not (member x org-tags-exclude-from-inheritance)))
14255 x nil))
14256 tags)))
14257 ((listp org-use-tag-inheritance)
14258 (delq nil (mapcar
14259 (lambda (x)
14260 (if (member x org-use-tag-inheritance) x nil))
14261 tags)))))
14263 (defun org-match-sparse-tree (&optional todo-only match)
14264 "Create a sparse tree according to tags string MATCH.
14265 MATCH can contain positive and negative selection of tags, like
14266 \"+WORK+URGENT-WITHBOSS\".
14267 If optional argument TODO-ONLY is non-nil, only select lines that are
14268 also TODO lines."
14269 (interactive "P")
14270 (org-agenda-prepare-buffers (list (current-buffer)))
14271 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14273 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14275 (defvar org-cached-props nil)
14276 (defun org-cached-entry-get (pom property)
14277 (if (or (eq t org-use-property-inheritance)
14278 (and (stringp org-use-property-inheritance)
14279 (string-match org-use-property-inheritance property))
14280 (and (listp org-use-property-inheritance)
14281 (member property org-use-property-inheritance)))
14282 ;; Caching is not possible, check it directly
14283 (org-entry-get pom property 'inherit)
14284 ;; Get all properties, so that we can do complicated checks easily
14285 (cdr (assoc property (or org-cached-props
14286 (setq org-cached-props
14287 (org-entry-properties pom)))))))
14289 (defun org-global-tags-completion-table (&optional files)
14290 "Return the list of all tags in all agenda buffer/files.
14291 Optional FILES argument is a list of files which can be used
14292 instead of the agenda files."
14293 (save-excursion
14294 (org-uniquify
14295 (delq nil
14296 (apply 'append
14297 (mapcar
14298 (lambda (file)
14299 (set-buffer (find-file-noselect file))
14300 (append (org-get-buffer-tags)
14301 (mapcar (lambda (x) (if (stringp (car-safe x))
14302 (list (car-safe x)) nil))
14303 org-tag-alist)))
14304 (if (and files (car files))
14305 files
14306 (org-agenda-files))))))))
14308 (defun org-make-tags-matcher (match)
14309 "Create the TAGS/TODO matcher form for the selection string MATCH.
14311 The variable `todo-only' is scoped dynamically into this function.
14312 It will be set to t if the matcher restricts matching to TODO entries,
14313 otherwise will not be touched.
14315 Returns a cons of the selection string MATCH and the constructed
14316 lisp form implementing the matcher. The matcher is to be evaluated
14317 at an Org entry, with point on the headline, and returns t if the
14318 entry matches the selection string MATCH. The returned lisp form
14319 references two variables with information about the entry, which
14320 must be bound around the form's evaluation: todo, the TODO keyword
14321 at the entry (or nil of none); and tags-list, the list of all tags
14322 at the entry including inherited ones. Additionally, the category
14323 of the entry (if any) must be specified as the text property
14324 'org-category on the headline.
14326 See also `org-scan-tags'.
14328 (declare (special todo-only))
14329 (unless (boundp 'todo-only)
14330 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14331 (unless match
14332 ;; Get a new match request, with completion against the global
14333 ;; tags table and the local tags in current buffer
14334 (let ((org-last-tags-completion-table
14335 (org-uniquify
14336 (delq nil (append (org-get-buffer-tags)
14337 (org-global-tags-completion-table))))))
14338 (setq match (org-completing-read-no-i
14339 "Match: " 'org-tags-completion-function nil nil nil
14340 'org-tags-history))))
14342 ;; Parse the string and create a lisp form
14343 (let ((match0 match)
14344 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14345 minus tag mm
14346 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14347 orterms term orlist re-p str-p level-p level-op time-p
14348 prop-p pn pv po gv rest (start 0) (ss 0))
14349 ;; Expand group tags
14350 (setq match (org-tags-expand match))
14352 ;; Check if there is a TODO part of this match, which would be the
14353 ;; part after a "/". TO make sure that this slash is not part of
14354 ;; a property value to be matched against, we also check that there
14355 ;; is no " after that slash.
14356 ;; First, find the last slash
14357 (while (string-match "/+" match ss)
14358 (setq start (match-beginning 0) ss (match-end 0)))
14359 (if (and (string-match "/+" match start)
14360 (not (save-match-data (string-match "\"" match start))))
14361 ;; match contains also a todo-matching request
14362 (progn
14363 (setq tagsmatch (substring match 0 (match-beginning 0))
14364 todomatch (substring match (match-end 0)))
14365 (if (string-match "^!" todomatch)
14366 (setq todo-only t todomatch (substring todomatch 1)))
14367 (if (string-match "^\\s-*$" todomatch)
14368 (setq todomatch nil)))
14369 ;; only matching tags
14370 (setq tagsmatch match todomatch nil))
14372 ;; Make the tags matcher
14373 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14374 (setq tagsmatcher t)
14375 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14376 (while (setq term (pop orterms))
14377 (while (and (equal (substring term -1) "\\") orterms)
14378 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14379 (while (string-match re term)
14380 (setq rest (substring term (match-end 0))
14381 minus (and (match-end 1)
14382 (equal (match-string 1 term) "-"))
14383 tag (save-match-data (replace-regexp-in-string
14384 "\\\\-" "-"
14385 (match-string 2 term)))
14386 re-p (equal (string-to-char tag) ?{)
14387 level-p (match-end 4)
14388 prop-p (match-end 5)
14389 mm (cond
14390 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14391 (level-p
14392 (setq level-op (org-op-to-function (match-string 3 term)))
14393 `(,level-op level ,(string-to-number
14394 (match-string 4 term))))
14395 (prop-p
14396 (setq pn (match-string 5 term)
14397 po (match-string 6 term)
14398 pv (match-string 7 term)
14399 re-p (equal (string-to-char pv) ?{)
14400 str-p (equal (string-to-char pv) ?\")
14401 time-p (save-match-data
14402 (string-match "^\"[[<].*[]>]\"$" pv))
14403 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14404 (if time-p (setq pv (org-matcher-time pv)))
14405 (setq po (org-op-to-function po (if time-p 'time str-p)))
14406 (cond
14407 ((equal pn "CATEGORY")
14408 (setq gv '(get-text-property (point) 'org-category)))
14409 ((equal pn "TODO")
14410 (setq gv 'todo))
14412 (setq gv `(org-cached-entry-get nil ,pn))))
14413 (if re-p
14414 (if (eq po 'org<>)
14415 `(not (string-match ,pv (or ,gv "")))
14416 `(string-match ,pv (or ,gv "")))
14417 (if str-p
14418 `(,po (or ,gv "") ,pv)
14419 `(,po (string-to-number (or ,gv ""))
14420 ,(string-to-number pv) ))))
14421 (t `(member ,tag tags-list)))
14422 mm (if minus (list 'not mm) mm)
14423 term rest)
14424 (push mm tagsmatcher))
14425 (push (if (> (length tagsmatcher) 1)
14426 (cons 'and tagsmatcher)
14427 (car tagsmatcher))
14428 orlist)
14429 (setq tagsmatcher nil))
14430 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14431 (setq tagsmatcher
14432 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14433 ;; Make the todo matcher
14434 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14435 (setq todomatcher t)
14436 (setq orterms (org-split-string todomatch "|") orlist nil)
14437 (while (setq term (pop orterms))
14438 (while (string-match re term)
14439 (setq minus (and (match-end 1)
14440 (equal (match-string 1 term) "-"))
14441 kwd (match-string 2 term)
14442 re-p (equal (string-to-char kwd) ?{)
14443 term (substring term (match-end 0))
14444 mm (if re-p
14445 `(string-match ,(substring kwd 1 -1) todo)
14446 (list 'equal 'todo kwd))
14447 mm (if minus (list 'not mm) mm))
14448 (push mm todomatcher))
14449 (push (if (> (length todomatcher) 1)
14450 (cons 'and todomatcher)
14451 (car todomatcher))
14452 orlist)
14453 (setq todomatcher nil))
14454 (setq todomatcher (if (> (length orlist) 1)
14455 (cons 'or orlist) (car orlist))))
14457 ;; Return the string and lisp forms of the matcher
14458 (setq matcher (if todomatcher
14459 (list 'and tagsmatcher todomatcher)
14460 tagsmatcher))
14461 (when todo-only
14462 (setq matcher (list 'and '(member todo org-not-done-keywords)
14463 matcher)))
14464 (cons match0 matcher)))
14466 (defun org-tags-expand (match &optional single-as-list downcased)
14467 "Expand group tags in MATCH.
14469 This replaces every group tag in MATCH with a regexp tag search.
14470 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14471 will be replaced like this:
14473 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14474 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14475 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14477 Replacing by a regexp preserves the structure of the match.
14478 E.g., this expansion
14480 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14482 will match anything tagged with \"Lab\" and \"Home\", or tagged
14483 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14485 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14486 assumed to be a single group tag, and the function will return
14487 the list of tags in this group.
14489 When DOWNCASE is non-nil, expand downcased TAGS."
14490 (if org-group-tags
14491 (let* ((case-fold-search t)
14492 (stable org-mode-syntax-table)
14493 (tal (or org-tag-groups-alist-for-agenda
14494 org-tag-groups-alist))
14495 (tal (if downcased
14496 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14497 (tml (mapcar 'car tal))
14498 (rtnmatch match) rpl)
14499 ;; @ and _ are allowed as word-components in tags
14500 (modify-syntax-entry ?@ "w" stable)
14501 (modify-syntax-entry ?_ "w" stable)
14502 (while (and tml
14503 (with-syntax-table stable
14504 (string-match
14505 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14506 (regexp-opt tml) "\\>\\)") rtnmatch)))
14507 (let* ((dir (match-string 1 rtnmatch))
14508 (tag (match-string 2 rtnmatch))
14509 (tag (if downcased (downcase tag) tag)))
14510 (setq tml (delete tag tml))
14511 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14512 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14513 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14514 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14515 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14516 (if single-as-list
14517 (or (reverse rpl) (list rtnmatch))
14518 rtnmatch))
14519 (if single-as-list (list (if downcased (downcase match) match))
14520 match)))
14522 (defun org-op-to-function (op &optional stringp)
14523 "Turn an operator into the appropriate function."
14524 (setq op
14525 (cond
14526 ((equal op "<" ) '(< string< org-time<))
14527 ((equal op ">" ) '(> org-string> org-time>))
14528 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14529 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14530 ((member op '("=" "==")) '(= string= org-time=))
14531 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14532 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14534 (defun org<> (a b) (not (= a b)))
14535 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14536 (defun org-string>= (a b) (not (string< a b)))
14537 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14538 (defun org-string<> (a b) (not (string= a b)))
14539 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14540 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14541 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14542 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14543 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14544 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14545 (defun org-2ft (s)
14546 "Convert S to a floating point time.
14547 If S is already a number, just return it. If it is a string, parse
14548 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14549 (cond
14550 ((numberp s) s)
14551 ((stringp s)
14552 (condition-case nil
14553 (float-time (apply 'encode-time (org-parse-time-string s)))
14554 (error 0.)))
14555 (t 0.)))
14557 (defun org-time-today ()
14558 "Time in seconds today at 0:00.
14559 Returns the float number of seconds since the beginning of the
14560 epoch to the beginning of today (00:00)."
14561 (float-time (apply 'encode-time
14562 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14564 (defun org-matcher-time (s)
14565 "Interpret a time comparison value."
14566 (save-match-data
14567 (cond
14568 ((string= s "<now>") (float-time))
14569 ((string= s "<today>") (org-time-today))
14570 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14571 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14572 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14573 (+ (org-time-today)
14574 (* (string-to-number (match-string 1 s))
14575 (cdr (assoc (match-string 2 s)
14576 '(("d" . 86400.0) ("w" . 604800.0)
14577 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14578 (t (org-2ft s)))))
14580 (defun org-match-any-p (re list)
14581 "Does re match any element of list?"
14582 (setq list (mapcar (lambda (x) (string-match re x)) list))
14583 (delq nil list))
14585 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14586 (defvar org-tags-overlay (make-overlay 1 1))
14587 (org-detach-overlay org-tags-overlay)
14589 (defun org-get-local-tags-at (&optional pos)
14590 "Get a list of tags defined in the current headline."
14591 (org-get-tags-at pos 'local))
14593 (defun org-get-local-tags ()
14594 "Get a list of tags defined in the current headline."
14595 (org-get-tags-at nil 'local))
14597 (defun org-get-tags-at (&optional pos local)
14598 "Get a list of all headline tags applicable at POS.
14599 POS defaults to point. If tags are inherited, the list contains
14600 the targets in the same sequence as the headlines appear, i.e.
14601 the tags of the current headline come last.
14602 When LOCAL is non-nil, only return tags from the current headline,
14603 ignore inherited ones."
14604 (interactive)
14605 (if (and org-trust-scanner-tags
14606 (or (not pos) (equal pos (point)))
14607 (not local))
14608 org-scanner-tags
14609 (let (tags ltags lastpos parent)
14610 (save-excursion
14611 (save-restriction
14612 (widen)
14613 (goto-char (or pos (point)))
14614 (save-match-data
14615 (catch 'done
14616 (condition-case nil
14617 (progn
14618 (org-back-to-heading t)
14619 (while (not (equal lastpos (point)))
14620 (setq lastpos (point))
14621 (when (looking-at
14622 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14623 (setq ltags (org-split-string
14624 (org-match-string-no-properties 1) ":"))
14625 (when parent
14626 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14627 (setq tags (append
14628 (if parent
14629 (org-remove-uninherited-tags ltags)
14630 ltags)
14631 tags)))
14632 (or org-use-tag-inheritance (throw 'done t))
14633 (if local (throw 'done t))
14634 (or (org-up-heading-safe) (error nil))
14635 (setq parent t)))
14636 (error nil)))))
14637 (if local
14638 tags
14639 (reverse (delete-dups
14640 (reverse (append
14641 (org-remove-uninherited-tags
14642 org-file-tags) tags)))))))))
14644 (defun org-add-prop-inherited (s)
14645 (add-text-properties 0 (length s) '(inherited t) s)
14648 (defun org-toggle-tag (tag &optional onoff)
14649 "Toggle the tag TAG for the current line.
14650 If ONOFF is `on' or `off', don't toggle but set to this state."
14651 (let (res current)
14652 (save-excursion
14653 (org-back-to-heading t)
14654 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14655 (point-at-eol) t)
14656 (progn
14657 (setq current (match-string 1))
14658 (replace-match ""))
14659 (setq current ""))
14660 (setq current (nreverse (org-split-string current ":")))
14661 (cond
14662 ((eq onoff 'on)
14663 (setq res t)
14664 (or (member tag current) (push tag current)))
14665 ((eq onoff 'off)
14666 (or (not (member tag current)) (setq current (delete tag current))))
14667 (t (if (member tag current)
14668 (setq current (delete tag current))
14669 (setq res t)
14670 (push tag current))))
14671 (end-of-line 1)
14672 (if current
14673 (progn
14674 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14675 (org-set-tags nil t))
14676 (delete-horizontal-space))
14677 (run-hooks 'org-after-tags-change-hook))
14678 res))
14680 (defun org-align-tags-here (to-col)
14681 ;; Assumes that this is a headline
14682 "Align tags on the current headline to TO-COL."
14683 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14684 (beginning-of-line 1)
14685 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14686 (< pos (match-beginning 2)))
14687 (progn
14688 (setq tags-l (- (match-end 2) (match-beginning 2)))
14689 (goto-char (match-beginning 1))
14690 (insert " ")
14691 (delete-region (point) (1+ (match-beginning 2)))
14692 (setq ncol (max (current-column)
14693 (1+ col)
14694 (if (> to-col 0)
14695 to-col
14696 (- (abs to-col) tags-l))))
14697 (setq p (point))
14698 (insert (make-string (- ncol (current-column)) ?\ ))
14699 (setq ncol (current-column))
14700 (when indent-tabs-mode (tabify p (point-at-eol)))
14701 (org-move-to-column (min ncol col)))
14702 (goto-char pos))))
14704 (defun org-set-tags-command (&optional arg just-align)
14705 "Call the set-tags command for the current entry."
14706 (interactive "P")
14707 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14708 (org-set-tags arg just-align)
14709 (save-excursion
14710 (unless (and (org-region-active-p)
14711 org-loop-over-headlines-in-active-region)
14712 (org-back-to-heading t))
14713 (org-set-tags arg just-align))))
14715 (defun org-set-tags-to (data)
14716 "Set the tags of the current entry to DATA, replacing the current tags.
14717 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14718 If DATA is nil or the empty string, any tags will be removed."
14719 (interactive "sTags: ")
14720 (setq data
14721 (cond
14722 ((eq data nil) "")
14723 ((equal data "") "")
14724 ((stringp data)
14725 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14726 ":"))
14727 ((listp data)
14728 (concat ":" (mapconcat 'identity data ":") ":"))))
14729 (when data
14730 (save-excursion
14731 (org-back-to-heading t)
14732 (when (looking-at org-complex-heading-regexp)
14733 (if (match-end 5)
14734 (progn
14735 (goto-char (match-beginning 5))
14736 (insert data)
14737 (delete-region (point) (point-at-eol))
14738 (org-set-tags nil 'align))
14739 (goto-char (point-at-eol))
14740 (insert " " data)
14741 (org-set-tags nil 'align)))
14742 (beginning-of-line 1)
14743 (if (looking-at ".*?\\([ \t]+\\)$")
14744 (delete-region (match-beginning 1) (match-end 1))))))
14746 (defun org-align-all-tags ()
14747 "Align the tags i all headings."
14748 (interactive)
14749 (save-excursion
14750 (or (ignore-errors (org-back-to-heading t))
14751 (outline-next-heading))
14752 (if (org-at-heading-p)
14753 (org-set-tags t)
14754 (message "No headings"))))
14756 (defvar org-indent-indentation-per-level)
14757 (defun org-set-tags (&optional arg just-align)
14758 "Set the tags for the current headline.
14759 With prefix ARG, realign all tags in headings in the current buffer.
14760 When JUST-ALIGN is non-nil, only align tags."
14761 (interactive "P")
14762 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14763 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14764 'region-start-level 'region))
14765 org-loop-over-headlines-in-active-region)
14766 (org-map-entries
14767 ;; We don't use ARG and JUST-ALIGN here because these args
14768 ;; are not useful when looping over headlines.
14769 `(org-set-tags)
14770 org-loop-over-headlines-in-active-region
14771 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14772 (let* ((re org-outline-regexp-bol)
14773 (current (unless arg (org-get-tags-string)))
14774 (col (current-column))
14775 (org-setting-tags t)
14776 table current-tags inherited-tags ; computed below when needed
14777 tags p0 c0 c1 rpl di tc level)
14778 (if arg
14779 (save-excursion
14780 (goto-char (point-min))
14781 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14782 (while (re-search-forward re nil t)
14783 (org-set-tags nil t)
14784 (end-of-line 1)))
14785 (message "All tags realigned to column %d" org-tags-column))
14786 (if just-align
14787 (setq tags current)
14788 ;; Get a new set of tags from the user
14789 (save-excursion
14790 (setq table (append org-tag-persistent-alist
14791 (or org-tag-alist (org-get-buffer-tags))
14792 (and
14793 org-complete-tags-always-offer-all-agenda-tags
14794 (org-global-tags-completion-table
14795 (org-agenda-files))))
14796 org-last-tags-completion-table table
14797 current-tags (org-split-string current ":")
14798 inherited-tags (nreverse
14799 (nthcdr (length current-tags)
14800 (nreverse (org-get-tags-at))))
14801 tags
14802 (if (or (eq t org-use-fast-tag-selection)
14803 (and org-use-fast-tag-selection
14804 (delq nil (mapcar 'cdr table))))
14805 (org-fast-tag-selection
14806 current-tags inherited-tags table
14807 (if org-fast-tag-selection-include-todo
14808 org-todo-key-alist))
14809 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14810 (org-trim
14811 (org-icompleting-read "Tags: "
14812 'org-tags-completion-function
14813 nil nil current 'org-tags-history))))))
14814 (while (string-match "[-+&]+" tags)
14815 ;; No boolean logic, just a list
14816 (setq tags (replace-match ":" t t tags))))
14818 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14820 (if org-tags-sort-function
14821 (setq tags (mapconcat 'identity
14822 (sort (org-split-string
14823 tags (org-re "[^[:alnum:]_@#%]+"))
14824 org-tags-sort-function) ":")))
14826 (if (string-match "\\`[\t ]*\\'" tags)
14827 (setq tags "")
14828 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14829 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14831 ;; Insert new tags at the correct column
14832 (beginning-of-line 1)
14833 (setq level (or (and (looking-at org-outline-regexp)
14834 (- (match-end 0) (point) 1))
14836 (cond
14837 ((and (equal current "") (equal tags "")))
14838 ((re-search-forward
14839 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14840 (point-at-eol) t)
14841 (if (equal tags "")
14842 (setq rpl "")
14843 (goto-char (match-beginning 0))
14844 (setq c0 (current-column)
14845 ;; compute offset for the case of org-indent-mode active
14846 di (if (org-bound-and-true-p org-indent-mode)
14847 (* (1- org-indent-indentation-per-level) (1- level))
14849 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14850 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14851 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14852 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14853 (replace-match rpl t t)
14854 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14855 tags)
14856 (t (error "Tags alignment failed")))
14857 (org-move-to-column col)
14858 (unless just-align
14859 (run-hooks 'org-after-tags-change-hook))))))
14861 (defun org-change-tag-in-region (beg end tag off)
14862 "Add or remove TAG for each entry in the region.
14863 This works in the agenda, and also in an org-mode buffer."
14864 (interactive
14865 (list (region-beginning) (region-end)
14866 (let ((org-last-tags-completion-table
14867 (if (derived-mode-p 'org-mode)
14868 (org-uniquify
14869 (delq nil (append (org-get-buffer-tags)
14870 (org-global-tags-completion-table))))
14871 (org-global-tags-completion-table))))
14872 (org-icompleting-read
14873 "Tag: " 'org-tags-completion-function nil nil nil
14874 'org-tags-history))
14875 (progn
14876 (message "[s]et or [r]emove? ")
14877 (equal (read-char-exclusive) ?r))))
14878 (if (fboundp 'deactivate-mark) (deactivate-mark))
14879 (let ((agendap (equal major-mode 'org-agenda-mode))
14880 l1 l2 m buf pos newhead (cnt 0))
14881 (goto-char end)
14882 (setq l2 (1- (org-current-line)))
14883 (goto-char beg)
14884 (setq l1 (org-current-line))
14885 (loop for l from l1 to l2 do
14886 (org-goto-line l)
14887 (setq m (get-text-property (point) 'org-hd-marker))
14888 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14889 (and agendap m))
14890 (setq buf (if agendap (marker-buffer m) (current-buffer))
14891 pos (if agendap m (point)))
14892 (with-current-buffer buf
14893 (save-excursion
14894 (save-restriction
14895 (goto-char pos)
14896 (setq cnt (1+ cnt))
14897 (org-toggle-tag tag (if off 'off 'on))
14898 (setq newhead (org-get-heading)))))
14899 (and agendap (org-agenda-change-all-lines newhead m))))
14900 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14902 (defun org-tags-completion-function (string predicate &optional flag)
14903 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14904 (confirm (lambda (x) (stringp (car x)))))
14905 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14906 (setq s1 (match-string 1 string)
14907 s2 (match-string 2 string))
14908 (setq s1 "" s2 string))
14909 (cond
14910 ((eq flag nil)
14911 ;; try completion
14912 (setq rtn (try-completion s2 ctable confirm))
14913 (if (stringp rtn)
14914 (setq rtn
14915 (concat s1 s2 (substring rtn (length s2))
14916 (if (and org-add-colon-after-tag-completion
14917 (assoc rtn ctable))
14918 ":" ""))))
14919 rtn)
14920 ((eq flag t)
14921 ;; all-completions
14922 (all-completions s2 ctable confirm))
14923 ((eq flag 'lambda)
14924 ;; exact match?
14925 (assoc s2 ctable)))))
14927 (defun org-fast-tag-insert (kwd tags face &optional end)
14928 "Insert KDW, and the TAGS, the latter with face FACE.
14929 Also insert END."
14930 (insert (format "%-12s" (concat kwd ":"))
14931 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14932 (or end "")))
14934 (defun org-fast-tag-show-exit (flag)
14935 (save-excursion
14936 (org-goto-line 3)
14937 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14938 (replace-match ""))
14939 (when flag
14940 (end-of-line 1)
14941 (org-move-to-column (- (window-width) 19) t)
14942 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14944 (defun org-set-current-tags-overlay (current prefix)
14945 "Add an overlay to CURRENT tag with PREFIX."
14946 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14947 (if (featurep 'xemacs)
14948 (org-overlay-display org-tags-overlay (concat prefix s)
14949 'secondary-selection)
14950 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14951 (org-overlay-display org-tags-overlay (concat prefix s)))))
14953 (defvar org-last-tag-selection-key nil)
14954 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14955 "Fast tag selection with single keys.
14956 CURRENT is the current list of tags in the headline, INHERITED is the
14957 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14958 possibly with grouping information. TODO-TABLE is a similar table with
14959 TODO keywords, should these have keys assigned to them.
14960 If the keys are nil, a-z are automatically assigned.
14961 Returns the new tags string, or nil to not change the current settings."
14962 (let* ((fulltable (append table todo-table))
14963 (maxlen (apply 'max (mapcar
14964 (lambda (x)
14965 (if (stringp (car x)) (string-width (car x)) 0))
14966 fulltable)))
14967 (buf (current-buffer))
14968 (expert (eq org-fast-tag-selection-single-key 'expert))
14969 (buffer-tags nil)
14970 (fwidth (+ maxlen 3 1 3))
14971 (ncol (/ (- (window-width) 4) fwidth))
14972 (i-face 'org-done)
14973 (c-face 'org-todo)
14974 tg cnt e c char c1 c2 ntable tbl rtn
14975 ov-start ov-end ov-prefix
14976 (exit-after-next org-fast-tag-selection-single-key)
14977 (done-keywords org-done-keywords)
14978 groups ingroup)
14979 (save-excursion
14980 (beginning-of-line 1)
14981 (if (looking-at
14982 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14983 (setq ov-start (match-beginning 1)
14984 ov-end (match-end 1)
14985 ov-prefix "")
14986 (setq ov-start (1- (point-at-eol))
14987 ov-end (1+ ov-start))
14988 (skip-chars-forward "^\n\r")
14989 (setq ov-prefix
14990 (concat
14991 (buffer-substring (1- (point)) (point))
14992 (if (> (current-column) org-tags-column)
14994 (make-string (- org-tags-column (current-column)) ?\ ))))))
14995 (move-overlay org-tags-overlay ov-start ov-end)
14996 (save-window-excursion
14997 (if expert
14998 (set-buffer (get-buffer-create " *Org tags*"))
14999 (delete-other-windows)
15000 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15001 (org-switch-to-buffer-other-window " *Org tags*"))
15002 (erase-buffer)
15003 (org-set-local 'org-done-keywords done-keywords)
15004 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15005 (org-fast-tag-insert "Current" current c-face "\n\n")
15006 (org-fast-tag-show-exit exit-after-next)
15007 (org-set-current-tags-overlay current ov-prefix)
15008 (setq tbl fulltable char ?a cnt 0)
15009 (while (setq e (pop tbl))
15010 (cond
15011 ((equal (car e) :startgroup)
15012 (push '() groups) (setq ingroup t)
15013 (when (not (= cnt 0))
15014 (setq cnt 0)
15015 (insert "\n"))
15016 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15017 ((equal (car e) :endgroup)
15018 (setq ingroup nil cnt 0)
15019 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15020 ((equal e '(:newline))
15021 (when (not (= cnt 0))
15022 (setq cnt 0)
15023 (insert "\n")
15024 (setq e (car tbl))
15025 (while (equal (car tbl) '(:newline))
15026 (insert "\n")
15027 (setq tbl (cdr tbl)))))
15028 ((equal e '(:grouptags)) nil)
15030 (setq tg (copy-sequence (car e)) c2 nil)
15031 (if (cdr e)
15032 (setq c (cdr e))
15033 ;; automatically assign a character.
15034 (setq c1 (string-to-char
15035 (downcase (substring
15036 tg (if (= (string-to-char tg) ?@) 1 0)))))
15037 (if (or (rassoc c1 ntable) (rassoc c1 table))
15038 (while (or (rassoc char ntable) (rassoc char table))
15039 (setq char (1+ char)))
15040 (setq c2 c1))
15041 (setq c (or c2 char)))
15042 (if ingroup (push tg (car groups)))
15043 (setq tg (org-add-props tg nil 'face
15044 (cond
15045 ((not (assoc tg table))
15046 (org-get-todo-face tg))
15047 ((member tg current) c-face)
15048 ((member tg inherited) i-face))))
15049 (if (equal (caar tbl) :grouptags)
15050 (org-add-props tg nil 'face 'org-tag-group))
15051 (if (and (= cnt 0) (not ingroup)) (insert " "))
15052 (insert "[" c "] " tg (make-string
15053 (- fwidth 4 (length tg)) ?\ ))
15054 (push (cons tg c) ntable)
15055 (when (= (setq cnt (1+ cnt)) ncol)
15056 (insert "\n")
15057 (if ingroup (insert " "))
15058 (setq cnt 0)))))
15059 (setq ntable (nreverse ntable))
15060 (insert "\n")
15061 (goto-char (point-min))
15062 (if (not expert) (org-fit-window-to-buffer))
15063 (setq rtn
15064 (catch 'exit
15065 (while t
15066 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15067 (if (not groups) "no " "")
15068 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15069 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15070 (setq org-last-tag-selection-key c)
15071 (cond
15072 ((= c ?\r) (throw 'exit t))
15073 ((= c ?!)
15074 (setq groups (not groups))
15075 (goto-char (point-min))
15076 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15077 ((= c ?\C-c)
15078 (if (not expert)
15079 (org-fast-tag-show-exit
15080 (setq exit-after-next (not exit-after-next)))
15081 (setq expert nil)
15082 (delete-other-windows)
15083 (set-window-buffer (split-window-vertically) " *Org tags*")
15084 (org-switch-to-buffer-other-window " *Org tags*")
15085 (org-fit-window-to-buffer)))
15086 ((or (= c ?\C-g)
15087 (and (= c ?q) (not (rassoc c ntable))))
15088 (org-detach-overlay org-tags-overlay)
15089 (setq quit-flag t))
15090 ((= c ?\ )
15091 (setq current nil)
15092 (if exit-after-next (setq exit-after-next 'now)))
15093 ((= c ?\t)
15094 (condition-case nil
15095 (setq tg (org-icompleting-read
15096 "Tag: "
15097 (or buffer-tags
15098 (with-current-buffer buf
15099 (org-get-buffer-tags)))))
15100 (quit (setq tg "")))
15101 (when (string-match "\\S-" tg)
15102 (add-to-list 'buffer-tags (list tg))
15103 (if (member tg current)
15104 (setq current (delete tg current))
15105 (push tg current)))
15106 (if exit-after-next (setq exit-after-next 'now)))
15107 ((setq e (rassoc c todo-table) tg (car e))
15108 (with-current-buffer buf
15109 (save-excursion (org-todo tg)))
15110 (if exit-after-next (setq exit-after-next 'now)))
15111 ((setq e (rassoc c ntable) tg (car e))
15112 (if (member tg current)
15113 (setq current (delete tg current))
15114 (loop for g in groups do
15115 (if (member tg g)
15116 (mapc (lambda (x)
15117 (setq current (delete x current)))
15118 g)))
15119 (push tg current))
15120 (if exit-after-next (setq exit-after-next 'now))))
15122 ;; Create a sorted list
15123 (setq current
15124 (sort current
15125 (lambda (a b)
15126 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15127 (if (eq exit-after-next 'now) (throw 'exit t))
15128 (goto-char (point-min))
15129 (beginning-of-line 2)
15130 (delete-region (point) (point-at-eol))
15131 (org-fast-tag-insert "Current" current c-face)
15132 (org-set-current-tags-overlay current ov-prefix)
15133 (while (re-search-forward
15134 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15135 (setq tg (match-string 1))
15136 (add-text-properties
15137 (match-beginning 1) (match-end 1)
15138 (list 'face
15139 (cond
15140 ((member tg current) c-face)
15141 ((member tg inherited) i-face)
15142 (t (get-text-property (match-beginning 1) 'face))))))
15143 (goto-char (point-min)))))
15144 (org-detach-overlay org-tags-overlay)
15145 (if rtn
15146 (mapconcat 'identity current ":")
15147 nil))))
15149 (defun org-get-tags-string ()
15150 "Get the TAGS string in the current headline."
15151 (unless (org-at-heading-p t)
15152 (user-error "Not on a heading"))
15153 (save-excursion
15154 (beginning-of-line 1)
15155 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15156 (org-match-string-no-properties 1)
15157 "")))
15159 (defun org-get-tags ()
15160 "Get the list of tags specified in the current headline."
15161 (org-split-string (org-get-tags-string) ":"))
15163 (defun org-get-buffer-tags ()
15164 "Get a table of all tags used in the buffer, for completion."
15165 (let (tags)
15166 (save-excursion
15167 (goto-char (point-min))
15168 (while (re-search-forward
15169 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15170 (when (equal (char-after (point-at-bol 0)) ?*)
15171 (mapc (lambda (x) (add-to-list 'tags x))
15172 (org-split-string (org-match-string-no-properties 1) ":")))))
15173 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15174 (mapcar 'list tags)))
15176 ;;;; The mapping API
15178 (defun org-map-entries (func &optional match scope &rest skip)
15179 "Call FUNC at each headline selected by MATCH in SCOPE.
15181 FUNC is a function or a lisp form. The function will be called without
15182 arguments, with the cursor positioned at the beginning of the headline.
15183 The return values of all calls to the function will be collected and
15184 returned as a list.
15186 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15187 does not need to preserve point. After evaluation, the cursor will be
15188 moved to the end of the line (presumably of the headline of the
15189 processed entry) and search continues from there. Under some
15190 circumstances, this may not produce the wanted results. For example,
15191 if you have removed (e.g. archived) the current (sub)tree it could
15192 mean that the next entry will be skipped entirely. In such cases, you
15193 can specify the position from where search should continue by making
15194 FUNC set the variable `org-map-continue-from' to the desired buffer
15195 position.
15197 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15198 Only headlines that are matched by this query will be considered during
15199 the iteration. When MATCH is nil or t, all headlines will be
15200 visited by the iteration.
15202 SCOPE determines the scope of this command. It can be any of:
15204 nil The current buffer, respecting the restriction if any
15205 tree The subtree started with the entry at point
15206 region The entries within the active region, if any
15207 region-start-level
15208 The entries within the active region, but only those at
15209 the same level than the first one.
15210 file The current buffer, without restriction
15211 file-with-archives
15212 The current buffer, and any archives associated with it
15213 agenda All agenda files
15214 agenda-with-archives
15215 All agenda files with any archive files associated with them
15216 \(file1 file2 ...)
15217 If this is a list, all files in the list will be scanned
15219 The remaining args are treated as settings for the skipping facilities of
15220 the scanner. The following items can be given here:
15222 archive skip trees with the archive tag
15223 comment skip trees with the COMMENT keyword
15224 function or Emacs Lisp form:
15225 will be used as value for `org-agenda-skip-function', so
15226 whenever the function returns a position, FUNC will not be
15227 called for that entry and search will continue from the
15228 position returned
15230 If your function needs to retrieve the tags including inherited tags
15231 at the *current* entry, you can use the value of the variable
15232 `org-scanner-tags' which will be much faster than getting the value
15233 with `org-get-tags-at'. If your function gets properties with
15234 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15235 to t around the call to `org-entry-properties' to get the same speedup.
15236 Note that if your function moves around to retrieve tags and properties at
15237 a *different* entry, you cannot use these techniques."
15238 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15239 (not (org-region-active-p)))
15240 (let* ((org-agenda-archives-mode nil) ; just to make sure
15241 (org-agenda-skip-archived-trees (memq 'archive skip))
15242 (org-agenda-skip-comment-trees (memq 'comment skip))
15243 (org-agenda-skip-function
15244 (car (org-delete-all '(comment archive) skip)))
15245 (org-tags-match-list-sublevels t)
15246 (start-level (eq scope 'region-start-level))
15247 matcher file res
15248 org-todo-keywords-for-agenda
15249 org-done-keywords-for-agenda
15250 org-todo-keyword-alist-for-agenda
15251 org-tag-alist-for-agenda
15252 todo-only)
15254 (cond
15255 ((eq match t) (setq matcher t))
15256 ((eq match nil) (setq matcher t))
15257 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15259 (save-excursion
15260 (save-restriction
15261 (cond ((eq scope 'tree)
15262 (org-back-to-heading t)
15263 (org-narrow-to-subtree)
15264 (setq scope nil))
15265 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15266 (org-region-active-p))
15267 ;; If needed, set start-level to a string like "2"
15268 (when start-level
15269 (save-excursion
15270 (goto-char (region-beginning))
15271 (unless (org-at-heading-p) (outline-next-heading))
15272 (setq start-level (org-current-level))))
15273 (narrow-to-region (region-beginning)
15274 (save-excursion
15275 (goto-char (region-end))
15276 (unless (and (bolp) (org-at-heading-p))
15277 (outline-next-heading))
15278 (point)))
15279 (setq scope nil)))
15281 (if (not scope)
15282 (progn
15283 (org-agenda-prepare-buffers
15284 (list (buffer-file-name (current-buffer))))
15285 (setq res (org-scan-tags func matcher todo-only start-level)))
15286 ;; Get the right scope
15287 (cond
15288 ((and scope (listp scope) (symbolp (car scope)))
15289 (setq scope (eval scope)))
15290 ((eq scope 'agenda)
15291 (setq scope (org-agenda-files t)))
15292 ((eq scope 'agenda-with-archives)
15293 (setq scope (org-agenda-files t))
15294 (setq scope (org-add-archive-files scope)))
15295 ((eq scope 'file)
15296 (setq scope (list (buffer-file-name))))
15297 ((eq scope 'file-with-archives)
15298 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15299 (org-agenda-prepare-buffers scope)
15300 (while (setq file (pop scope))
15301 (with-current-buffer (org-find-base-buffer-visiting file)
15302 (save-excursion
15303 (save-restriction
15304 (widen)
15305 (goto-char (point-min))
15306 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15307 res)))
15309 ;;;; Properties
15311 ;;; Setting and retrieving properties
15313 (defconst org-special-properties
15314 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15315 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15316 "The special properties valid in Org-mode.
15318 These are properties that are not defined in the property drawer,
15319 but in some other way.")
15321 (defconst org-default-properties
15322 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15323 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15324 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15325 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15326 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15327 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15328 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15329 "Some properties that are used by Org-mode for various purposes.
15330 Being in this list makes sure that they are offered for completion.")
15332 (defun org-property-action ()
15333 "Do an action on properties."
15334 (interactive)
15335 (let (c)
15336 (org-at-property-p)
15337 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15338 (setq c (read-char-exclusive))
15339 (cond
15340 ((equal c ?s)
15341 (call-interactively 'org-set-property))
15342 ((equal c ?d)
15343 (call-interactively 'org-delete-property))
15344 ((equal c ?D)
15345 (call-interactively 'org-delete-property-globally))
15346 ((equal c ?c)
15347 (call-interactively 'org-compute-property-at-point))
15348 (t (user-error "No such property action %c" c)))))
15350 (defun org-inc-effort ()
15351 "Increment the value of the effort property in the current entry."
15352 (interactive)
15353 (org-set-effort nil t))
15355 (defvar org-clock-effort) ;; Defined in org-clock.el
15356 (defvar org-clock-current-task) ;; Defined in org-clock.el
15357 (defun org-set-effort (&optional value increment)
15358 "Set the effort property of the current entry.
15359 With numerical prefix arg, use the nth allowed value, 0 stands for the
15360 10th allowed value.
15362 When INCREMENT is non-nil, set the property to the next allowed value."
15363 (interactive "P")
15364 (if (equal value 0) (setq value 10))
15365 (let* ((completion-ignore-case t)
15366 (prop org-effort-property)
15367 (cur (org-entry-get nil prop))
15368 (allowed (org-property-get-allowed-values nil prop 'table))
15369 (existing (mapcar 'list (org-property-values prop)))
15370 (heading (nth 4 (org-heading-components)))
15372 (val (cond
15373 ((stringp value) value)
15374 ((and allowed (integerp value))
15375 (or (car (nth (1- value) allowed))
15376 (car (org-last allowed))))
15377 ((and allowed increment)
15378 (or (caadr (member (list cur) allowed))
15379 (user-error "Allowed effort values are not set")))
15380 (allowed
15381 (message "Select 1-9,0, [RET%s]: %s"
15382 (if cur (concat "=" cur) "")
15383 (mapconcat 'car allowed " "))
15384 (setq rpl (read-char-exclusive))
15385 (if (equal rpl ?\r)
15387 (setq rpl (- rpl ?0))
15388 (if (equal rpl 0) (setq rpl 10))
15389 (if (and (> rpl 0) (<= rpl (length allowed)))
15390 (car (nth (1- rpl) allowed))
15391 (org-completing-read "Effort: " allowed nil))))
15393 (let (org-completion-use-ido org-completion-use-iswitchb)
15394 (org-completing-read
15395 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15396 (concat "[" cur "]") "")
15397 ": ")
15398 existing nil nil "" nil cur))))))
15399 (unless (equal (org-entry-get nil prop) val)
15400 (org-entry-put nil prop val))
15401 (org-refresh-property
15402 '((effort . identity)
15403 (effort-minutes . org-duration-string-to-minutes))
15404 val)
15405 (when (string= heading org-clock-current-task)
15406 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15407 (org-clock-update-mode-line))
15408 (message "%s is now %s" prop val)))
15410 (defun org-at-property-p ()
15411 "Non-nil when point is inside a property drawer.
15412 See `org-property-re' for match data, if applicable."
15413 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15414 (save-excursion
15415 (beginning-of-line)
15416 (looking-at org-property-re))))
15418 (defun org-get-property-block (&optional beg end force)
15419 "Return the (beg . end) range of the body of the property drawer.
15420 BEG and END are the beginning and end of the current subtree, or of
15421 the part before the first headline. If they are not given, they will
15422 be found. If the drawer does not exist and FORCE is non-nil, create
15423 the drawer."
15424 (catch 'exit
15425 (save-excursion
15426 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15427 (progn (org-back-to-heading t) (point))))
15428 (end (or end (and (not (outline-next-heading)) (point-max))
15429 (point))))
15430 (goto-char beg)
15431 (if (re-search-forward org-property-start-re end t)
15432 (setq beg (1+ (match-end 0)))
15433 (if force
15434 (save-excursion
15435 (org-insert-property-drawer)
15436 (setq end (progn (outline-next-heading) (point))))
15437 (throw 'exit nil))
15438 (goto-char beg)
15439 (if (re-search-forward org-property-start-re end t)
15440 (setq beg (1+ (match-end 0)))))
15441 (if (re-search-forward org-property-end-re end t)
15442 (setq end (match-beginning 0))
15443 (or force (throw 'exit nil))
15444 (goto-char beg)
15445 (setq end beg)
15446 (org-indent-line)
15447 (insert ":END:\n"))
15448 (cons beg end)))))
15450 (defun org-entry-properties (&optional pom which specific)
15451 "Get all properties of the entry at point-or-marker POM.
15452 This includes the TODO keyword, the tags, time strings for deadline,
15453 scheduled, and clocking, and any additional properties defined in the
15454 entry. The return value is an alist, keys may occur multiple times
15455 if the property key was used several times.
15456 POM may also be nil, in which case the current entry is used.
15457 If WHICH is nil or `all', get all properties. If WHICH is
15458 `special' or `standard', only get that subclass. If WHICH
15459 is a string only get exactly this property. SPECIFIC can be a string, the
15460 specific property we are interested in. Specifying it can speed
15461 things up because then unnecessary parsing is avoided."
15462 (setq which (or which 'all))
15463 (org-with-wide-buffer
15464 (org-with-point-at pom
15465 (let ((clockstr (substring org-clock-string 0 -1))
15466 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15467 (case-fold-search nil)
15468 beg end range props sum-props key key1 value string clocksum clocksumt)
15469 (when (and (derived-mode-p 'org-mode)
15470 (ignore-errors (org-back-to-heading t)))
15471 (setq beg (point))
15472 (setq sum-props (get-text-property (point) 'org-summaries))
15473 (setq clocksum (get-text-property (point) :org-clock-minutes)
15474 clocksumt (get-text-property (point) :org-clock-minutes-today))
15475 (outline-next-heading)
15476 (setq end (point))
15477 (when (memq which '(all special))
15478 ;; Get the special properties, like TODO and tags
15479 (goto-char beg)
15480 (when (and (or (not specific) (string= specific "TODO"))
15481 (looking-at org-todo-line-regexp) (match-end 2))
15482 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15483 (when (and (or (not specific) (string= specific "PRIORITY"))
15484 (looking-at org-priority-regexp))
15485 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15486 (when (or (not specific) (string= specific "FILE"))
15487 (push (cons "FILE" buffer-file-name) props))
15488 (when (and (or (not specific) (string= specific "TAGS"))
15489 (setq value (org-get-tags-string))
15490 (string-match "\\S-" value))
15491 (push (cons "TAGS" value) props))
15492 (when (and (or (not specific) (string= specific "ALLTAGS"))
15493 (setq value (org-get-tags-at)))
15494 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15495 ":"))
15496 props))
15497 (when (or (not specific) (string= specific "BLOCKED"))
15498 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15499 (when (or (not specific)
15500 (member specific
15501 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15502 "TIMESTAMP" "TIMESTAMP_IA")))
15503 (catch 'match
15504 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15505 (not (text-property-any 0 (length (match-string 0))
15506 'face 'font-lock-comment-face
15507 (match-string 0))))
15508 (setq key (if (match-end 1)
15509 (substring (org-match-string-no-properties 1)
15510 0 -1))
15511 string (if (equal key clockstr)
15512 (org-trim
15513 (buffer-substring-no-properties
15514 (match-beginning 3) (goto-char
15515 (point-at-eol))))
15516 (substring (org-match-string-no-properties 3)
15517 1 -1)))
15518 ;; Get the correct property name from the key. This is
15519 ;; necessary if the user has configured time keywords.
15520 (setq key1 (concat key ":"))
15521 (cond
15522 ((not key)
15523 (setq key
15524 (if (= (char-after (match-beginning 3)) ?\[)
15525 "TIMESTAMP_IA" "TIMESTAMP")))
15526 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15527 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15528 ((equal key1 org-closed-string) (setq key "CLOSED"))
15529 ((equal key1 org-clock-string) (setq key "CLOCK")))
15530 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15531 (progn
15532 (push (cons key string) props)
15533 ;; no need to search further if match is found
15534 (throw 'match t))
15535 (when (or (equal key "CLOCK") (not (assoc key props)))
15536 (push (cons key string) props)))))))
15538 (when (memq which '(all standard))
15539 ;; Get the standard properties, like :PROP: ...
15540 (setq range (org-get-property-block beg end))
15541 (when range
15542 (goto-char (car range))
15543 (while (re-search-forward org-property-re
15544 (cdr range) t)
15545 (setq key (org-match-string-no-properties 2)
15546 value (org-trim (or (org-match-string-no-properties 3) "")))
15547 (unless (member key excluded)
15548 (push (cons key (or value "")) props)))))
15549 (if clocksum
15550 (push (cons "CLOCKSUM"
15551 (org-columns-number-to-string (/ (float clocksum) 60.)
15552 'add_times))
15553 props))
15554 (if clocksumt
15555 (push (cons "CLOCKSUM_T"
15556 (org-columns-number-to-string (/ (float clocksumt) 60.)
15557 'add_times))
15558 props))
15559 (unless (assoc "CATEGORY" props)
15560 (push (cons "CATEGORY" (org-get-category)) props))
15561 (append sum-props (nreverse props)))))))
15563 (defun org-entry-get (pom property &optional inherit literal-nil)
15564 "Get value of PROPERTY for entry or content at point-or-marker POM.
15565 If INHERIT is non-nil and the entry does not have the property,
15566 then also check higher levels of the hierarchy.
15567 If INHERIT is the symbol `selective', use inheritance only if the setting
15568 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15569 If the property is present but empty, the return value is the empty string.
15570 If the property is not present at all, nil is returned.
15572 Return the value as a string.
15574 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15575 do not interpret it as the list atom nil. This is used for inheritance
15576 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15577 (org-with-point-at pom
15578 (if (and inherit (if (eq inherit 'selective)
15579 (org-property-inherit-p property)
15581 (org-entry-get-with-inheritance property literal-nil)
15582 (if (member property org-special-properties)
15583 ;; We need a special property. Use `org-entry-properties'
15584 ;; to retrieve it, but specify the wanted property
15585 (cdr (assoc property (org-entry-properties nil 'special property)))
15586 (org-with-wide-buffer
15587 (let ((range (org-get-property-block)))
15588 (when (and range (not (eq (car range) (cdr range)))
15589 (save-excursion
15590 (goto-char (car range))
15591 (re-search-forward
15592 (concat (org-re-property property) "\\|"
15593 (org-re-property (concat property "+")))
15594 (cdr range) t)))
15595 (let* ((props
15596 (list (or (assoc property org-file-properties)
15597 (assoc property org-global-properties)
15598 (assoc property org-global-properties-fixed))))
15599 (ap (lambda (key)
15600 (when (re-search-forward
15601 (org-re-property key) (cdr range) t)
15602 (setq props
15603 (org-update-property-plist
15605 (if (match-end 3)
15606 (org-match-string-no-properties 3) "")
15607 props)))))
15608 val)
15609 (goto-char (car range))
15610 (funcall ap property)
15611 (goto-char (car range))
15612 (while (funcall ap (concat property "+")))
15613 (setq val (cdr (assoc property props)))
15614 (when val (if literal-nil val (org-not-nil val)))))))))))
15616 (defun org-property-or-variable-value (var &optional inherit)
15617 "Check if there is a property fixing the value of VAR.
15618 If yes, return this value. If not, return the current value of the variable."
15619 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15620 (if (and prop (stringp prop) (string-match "\\S-" prop))
15621 (read prop)
15622 (symbol-value var))))
15624 (defun org-entry-delete (pom property)
15625 "Delete the property PROPERTY from entry at point-or-marker POM."
15626 (unless (member property org-special-properties)
15627 (org-with-point-at pom
15628 (let ((range (org-get-property-block)))
15629 (if (and range
15630 (goto-char (car range))
15631 (re-search-forward
15632 (org-re-property property nil t)
15633 (cdr range) t))
15634 (progn
15635 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15636 (org-remove-empty-drawer-at (car range))
15638 nil)))))
15640 ;; Multi-values properties are properties that contain multiple values
15641 ;; These values are assumed to be single words, separated by whitespace.
15642 (defun org-entry-add-to-multivalued-property (pom property value)
15643 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15644 (let* ((old (org-entry-get pom property))
15645 (values (and old (org-split-string old "[ \t]"))))
15646 (setq value (org-entry-protect-space value))
15647 (unless (member value values)
15648 (setq values (append values (list value)))
15649 (org-entry-put pom property
15650 (mapconcat 'identity values " ")))))
15652 (defun org-entry-remove-from-multivalued-property (pom property value)
15653 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15654 (let* ((old (org-entry-get pom property))
15655 (values (and old (org-split-string old "[ \t]"))))
15656 (setq value (org-entry-protect-space value))
15657 (when (member value values)
15658 (setq values (delete value values))
15659 (org-entry-put pom property
15660 (mapconcat 'identity values " ")))))
15662 (defun org-entry-member-in-multivalued-property (pom property value)
15663 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15664 (let* ((old (org-entry-get pom property))
15665 (values (and old (org-split-string old "[ \t]"))))
15666 (setq value (org-entry-protect-space value))
15667 (member value values)))
15669 (defun org-entry-get-multivalued-property (pom property)
15670 "Return a list of values in a multivalued property."
15671 (let* ((value (org-entry-get pom property))
15672 (values (and value (org-split-string value "[ \t]"))))
15673 (mapcar 'org-entry-restore-space values)))
15675 (defun org-entry-put-multivalued-property (pom property &rest values)
15676 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15677 VALUES should be a list of strings. Spaces will be protected."
15678 (org-entry-put pom property
15679 (mapconcat 'org-entry-protect-space values " "))
15680 (let* ((value (org-entry-get pom property))
15681 (values (and value (org-split-string value "[ \t]"))))
15682 (mapcar 'org-entry-restore-space values)))
15684 (defun org-entry-protect-space (s)
15685 "Protect spaces and newline in string S."
15686 (while (string-match " " s)
15687 (setq s (replace-match "%20" t t s)))
15688 (while (string-match "\n" s)
15689 (setq s (replace-match "%0A" t t s)))
15692 (defun org-entry-restore-space (s)
15693 "Restore spaces and newline in string S."
15694 (while (string-match "%20" s)
15695 (setq s (replace-match " " t t s)))
15696 (while (string-match "%0A" s)
15697 (setq s (replace-match "\n" t t s)))
15700 (defvar org-entry-property-inherited-from (make-marker)
15701 "Marker pointing to the entry from where a property was inherited.
15702 Each call to `org-entry-get-with-inheritance' will set this marker to the
15703 location of the entry where the inheritance search matched. If there was
15704 no match, the marker will point nowhere.
15705 Note that also `org-entry-get' calls this function, if the INHERIT flag
15706 is set.")
15708 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15709 "Get PROPERTY of entry or content at point, search higher levels if needed.
15710 The search will stop at the first ancestor which has the property defined.
15711 If the value found is \"nil\", return nil to show that the property
15712 should be considered as undefined (this is the meaning of nil here).
15713 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15714 (move-marker org-entry-property-inherited-from nil)
15715 (let (tmp)
15716 (save-excursion
15717 (save-restriction
15718 (widen)
15719 (catch 'ex
15720 (while t
15721 (when (setq tmp (org-entry-get nil property nil literal-nil))
15722 (or (ignore-errors (org-back-to-heading t))
15723 (goto-char (point-min)))
15724 (move-marker org-entry-property-inherited-from (point))
15725 (throw 'ex tmp))
15726 (or (ignore-errors (org-up-heading-safe))
15727 (throw 'ex nil))))))
15728 (setq tmp (or tmp
15729 (cdr (assoc property org-file-properties))
15730 (cdr (assoc property org-global-properties))
15731 (cdr (assoc property org-global-properties-fixed))))
15732 (if literal-nil tmp (org-not-nil tmp))))
15734 (defvar org-property-changed-functions nil
15735 "Hook called when the value of a property has changed.
15736 Each hook function should accept two arguments, the name of the property
15737 and the new value.")
15739 (defun org-entry-put (pom property value)
15740 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15741 If the value is `nil', it is converted to the empty string.
15742 If it is not a string, an error is raised."
15743 (cond ((null value) (setq value ""))
15744 ((not (stringp value))
15745 (error "Properties values should be strings.")))
15746 (org-with-point-at pom
15747 (org-back-to-heading t)
15748 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15749 range)
15750 (cond
15751 ((equal property "TODO")
15752 (when (and (string-match "\\S-" value)
15753 (not (member value org-todo-keywords-1)))
15754 (user-error "\"%s\" is not a valid TODO state" value))
15755 (if (or (not value)
15756 (not (string-match "\\S-" value)))
15757 (setq value 'none))
15758 (org-todo value)
15759 (org-set-tags nil 'align))
15760 ((equal property "PRIORITY")
15761 (org-priority (if (and value (string-match "\\S-" value))
15762 (string-to-char value) ?\ ))
15763 (org-set-tags nil 'align))
15764 ((equal property "CLOCKSUM")
15765 (if (not (re-search-forward
15766 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15767 (error "Cannot find a clock log")
15768 (goto-char (- (match-end 1) 2))
15769 (cond
15770 ((eq value 'earlier) (org-timestamp-down))
15771 ((eq value 'later) (org-timestamp-up)))
15772 (org-clock-sum-current-item)))
15773 ((equal property "SCHEDULED")
15774 (if (re-search-forward org-scheduled-time-regexp end t)
15775 (cond
15776 ((eq value 'earlier) (org-timestamp-change -1 'day))
15777 ((eq value 'later) (org-timestamp-change 1 'day))
15778 (t (call-interactively 'org-schedule)))
15779 (call-interactively 'org-schedule)))
15780 ((equal property "DEADLINE")
15781 (if (re-search-forward org-deadline-time-regexp end t)
15782 (cond
15783 ((eq value 'earlier) (org-timestamp-change -1 'day))
15784 ((eq value 'later) (org-timestamp-change 1 'day))
15785 (t (call-interactively 'org-deadline)))
15786 (call-interactively 'org-deadline)))
15787 ((member property org-special-properties)
15788 (error "The %s property can not yet be set with `org-entry-put'"
15789 property))
15790 (t ; a non-special property
15791 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15792 (setq range (org-get-property-block beg end 'force))
15793 (goto-char (car range))
15794 (if (re-search-forward
15795 (org-re-property property nil t) (cdr range) t)
15796 (progn
15797 (delete-region (match-beginning 0) (match-end 0))
15798 (goto-char (match-beginning 0)))
15799 (goto-char (cdr range))
15800 (insert "\n")
15801 (backward-char 1)
15802 (org-indent-line))
15803 (insert ":" property ":")
15804 (and value (insert " " value))
15805 (org-indent-line)))))
15806 (run-hook-with-args 'org-property-changed-functions property value)))
15808 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15809 "Get all property keys in the current buffer.
15810 With INCLUDE-SPECIALS, also list the special properties that reflect things
15811 like tags and TODO state.
15812 With INCLUDE-DEFAULTS, also include properties that has special meaning
15813 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15814 and others.
15815 With INCLUDE-COLUMNS, also include property names given in COLUMN
15816 formats in the current buffer."
15817 (let (rtn range cfmt s p)
15818 (save-excursion
15819 (save-restriction
15820 (widen)
15821 (goto-char (point-min))
15822 (while (re-search-forward org-property-start-re nil t)
15823 (catch 'cont
15824 (setq range (or (org-get-property-block)
15825 (if (y-or-n-p
15826 (format "Malformed drawer at %d, repair?" (point)))
15827 (org-get-property-block nil nil t)
15828 (throw 'cont nil))))
15829 (goto-char (car range))
15830 (while (re-search-forward org-property-re
15831 (cdr range) t)
15832 (add-to-list 'rtn (org-match-string-no-properties 2)))
15833 (outline-next-heading)))))
15835 (when include-specials
15836 (setq rtn (append org-special-properties rtn)))
15838 (when include-defaults
15839 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15840 (add-to-list 'rtn org-effort-property))
15842 (when include-columns
15843 (save-excursion
15844 (save-restriction
15845 (widen)
15846 (goto-char (point-min))
15847 (while (re-search-forward
15848 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15849 nil t)
15850 (setq cfmt (match-string 2) s 0)
15851 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15852 cfmt s)
15853 (setq s (match-end 0)
15854 p (match-string 1 cfmt))
15855 (unless (or (equal p "ITEM")
15856 (member p org-special-properties))
15857 (add-to-list 'rtn (match-string 1 cfmt))))))))
15859 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15861 (defun org-property-values (key)
15862 "Return a list of all values of property KEY in the current buffer."
15863 (save-excursion
15864 (save-restriction
15865 (widen)
15866 (goto-char (point-min))
15867 (let ((re (org-re-property key))
15868 values)
15869 (while (re-search-forward re nil t)
15870 (add-to-list 'values (org-trim (match-string 3))))
15871 (delete "" values)))))
15873 (defun org-insert-property-drawer ()
15874 "Insert a property drawer into the current entry."
15875 (org-back-to-heading t)
15876 (looking-at org-outline-regexp)
15877 (let ((indent (if org-adapt-indentation
15878 (- (match-end 0) (match-beginning 0))
15880 (beg (point))
15881 (re (concat "^[ \t]*" org-keyword-time-regexp))
15882 end hiddenp)
15883 (outline-next-heading)
15884 (setq end (point))
15885 (goto-char beg)
15886 (while (re-search-forward re end t))
15887 (setq hiddenp (outline-invisible-p))
15888 (end-of-line 1)
15889 (and (equal (char-after) ?\n) (forward-char 1))
15890 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15891 (if (member (match-string 1) '("CLOCK:" ":END:"))
15892 ;; just skip this line
15893 (beginning-of-line 2)
15894 ;; Drawer start, find the end
15895 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15896 (beginning-of-line 1)))
15897 (org-skip-over-state-notes)
15898 (skip-chars-backward " \t\n\r")
15899 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15900 (forward-char 1))
15901 (goto-char (point-at-eol))
15902 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15903 (beginning-of-line 0)
15904 (org-indent-to-column indent)
15905 (beginning-of-line 2)
15906 (org-indent-to-column indent)
15907 (beginning-of-line 0)
15908 (if hiddenp
15909 (save-excursion
15910 (org-back-to-heading t)
15911 (hide-entry))
15912 (org-flag-drawer t))))
15914 (defun org-insert-drawer (&optional arg drawer)
15915 "Insert a drawer at point.
15917 Optional argument DRAWER, when non-nil, is a string representing
15918 drawer's name. Otherwise, the user is prompted for a name.
15920 If a region is active, insert the drawer around that region
15921 instead.
15923 Point is left between drawer's boundaries."
15924 (interactive "P")
15925 (let* ((drawer (if arg "PROPERTIES"
15926 (or drawer (read-from-minibuffer "Drawer: ")))))
15927 (cond
15928 ;; With C-u, fall back on `org-insert-property-drawer'
15929 (arg (org-insert-property-drawer))
15931 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15932 (user-error "Invalid drawer name"))
15933 ;; With an active region, insert a drawer at point.
15934 ((not (org-region-active-p))
15935 (progn
15936 (unless (bolp) (insert "\n"))
15937 (insert (format ":%s:\n\n:END:\n" drawer))
15938 (forward-line -2)))
15939 ;; Otherwise, insert the drawer at point
15941 (let ((rbeg (region-beginning))
15942 (rend (copy-marker (region-end))))
15943 (unwind-protect
15944 (progn
15945 (goto-char rbeg)
15946 (beginning-of-line)
15947 (when (save-excursion
15948 (re-search-forward org-outline-regexp-bol rend t))
15949 (user-error "Drawers cannot contain headlines"))
15950 ;; Position point at the beginning of the first
15951 ;; non-blank line in region. Insert drawer's opening
15952 ;; there, then indent it.
15953 (org-skip-whitespace)
15954 (beginning-of-line)
15955 (insert ":" drawer ":\n")
15956 (forward-line -1)
15957 (indent-for-tab-command)
15958 ;; Move point to the beginning of the first blank line
15959 ;; after the last non-blank line in region. Insert
15960 ;; drawer's closing, then indent it.
15961 (goto-char rend)
15962 (skip-chars-backward " \r\t\n")
15963 (insert "\n:END:")
15964 (deactivate-mark t)
15965 (indent-for-tab-command)
15966 (unless (eolp) (insert "\n")))
15967 ;; Clear marker, whatever the outcome of insertion is.
15968 (set-marker rend nil)))))))
15970 (defvar org-property-set-functions-alist nil
15971 "Property set function alist.
15972 Each entry should have the following format:
15974 (PROPERTY . READ-FUNCTION)
15976 The read function will be called with the same argument as
15977 `org-completing-read'.")
15979 (defun org-set-property-function (property)
15980 "Get the function that should be used to set PROPERTY.
15981 This is computed according to `org-property-set-functions-alist'."
15982 (or (cdr (assoc property org-property-set-functions-alist))
15983 'org-completing-read))
15985 (defun org-read-property-value (property)
15986 "Read PROPERTY value from user."
15987 (let* ((completion-ignore-case t)
15988 (allowed (org-property-get-allowed-values nil property 'table))
15989 (cur (org-entry-get nil property))
15990 (prompt (concat property " value"
15991 (if (and cur (string-match "\\S-" cur))
15992 (concat " [" cur "]") "") ": "))
15993 (set-function (org-set-property-function property))
15994 (val (if allowed
15995 (funcall set-function prompt allowed nil
15996 (not (get-text-property 0 'org-unrestricted
15997 (caar allowed))))
15998 (let (org-completion-use-ido org-completion-use-iswitchb)
15999 (funcall set-function prompt
16000 (mapcar 'list (org-property-values property))
16001 nil nil "" nil cur)))))
16002 (org-trim val)))
16004 (defvar org-last-set-property nil)
16005 (defvar org-last-set-property-value nil)
16006 (defun org-read-property-name ()
16007 "Read a property name."
16008 (let* ((completion-ignore-case t)
16009 (keys (org-buffer-property-keys nil t t))
16010 (default-prop (or (save-excursion
16011 (save-match-data
16012 (beginning-of-line)
16013 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16014 (null (string= (match-string 1) "END"))
16015 (match-string 1))))
16016 org-last-set-property))
16017 (property (org-icompleting-read
16018 (concat "Property"
16019 (if default-prop (concat " [" default-prop "]") "")
16020 ": ")
16021 (mapcar 'list keys)
16022 nil nil nil nil
16023 default-prop)))
16024 (if (member property keys)
16025 property
16026 (or (cdr (assoc (downcase property)
16027 (mapcar (lambda (x) (cons (downcase x) x))
16028 keys)))
16029 property))))
16031 (defun org-set-property-and-value (use-last)
16032 "Allow to set [PROPERTY]: [value] direction from prompt.
16033 When use-default, don't even ask, just use the last
16034 \"[PROPERTY]: [value]\" string from the history."
16035 (interactive "P")
16036 (let* ((completion-ignore-case t)
16037 (pv (or (and use-last org-last-set-property-value)
16038 (org-completing-read
16039 "Enter a \"[Property]: [value]\" pair: "
16040 nil nil nil nil nil
16041 org-last-set-property-value)))
16042 prop val)
16043 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16044 (setq prop (match-string 1 pv)
16045 val (match-string 2 pv))
16046 (org-set-property prop val))))
16048 (defun org-set-property (property value)
16049 "In the current entry, set PROPERTY to VALUE.
16050 When called interactively, this will prompt for a property name, offering
16051 completion on existing and default properties. And then it will prompt
16052 for a value, offering completion either on allowed values (via an inherited
16053 xxx_ALL property) or on existing values in other instances of this property
16054 in the current file."
16055 (interactive (list nil nil))
16056 (let* ((property (or property (org-read-property-name)))
16057 (value (or value (org-read-property-value property)))
16058 (fn (cdr (assoc property org-properties-postprocess-alist))))
16059 (setq org-last-set-property property)
16060 (setq org-last-set-property-value (concat property ": " value))
16061 ;; Possibly postprocess the inserted value:
16062 (when fn (setq value (funcall fn value)))
16063 (unless (equal (org-entry-get nil property) value)
16064 (org-entry-put nil property value))))
16066 (defun org-delete-property (property)
16067 "In the current entry, delete PROPERTY."
16068 (interactive
16069 (let* ((completion-ignore-case t)
16070 (cat (org-entry-get (point) "CATEGORY"))
16071 (props0 (org-entry-properties nil 'standard))
16072 (props (if cat props0
16073 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16074 (prop (if (< 1 (length props))
16075 (org-icompleting-read "Property: " props nil t)
16076 (caar props))))
16077 (list prop)))
16078 (if (not property)
16079 (message "No property to delete in this entry")
16080 (org-entry-delete nil property)
16081 (message "Property \"%s\" deleted" property)))
16083 (defun org-delete-property-globally (property)
16084 "Remove PROPERTY globally, from all entries."
16085 (interactive
16086 (let* ((completion-ignore-case t)
16087 (prop (org-icompleting-read
16088 "Globally remove property: "
16089 (mapcar 'list (org-buffer-property-keys)))))
16090 (list prop)))
16091 (save-excursion
16092 (save-restriction
16093 (widen)
16094 (goto-char (point-min))
16095 (let ((cnt 0))
16096 (while (re-search-forward
16097 (org-re-property property)
16098 nil t)
16099 (setq cnt (1+ cnt))
16100 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16101 (message "Property \"%s\" removed from %d entries" property cnt)))))
16103 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16105 (defun org-compute-property-at-point ()
16106 "Compute the property at point.
16107 This looks for an enclosing column format, extracts the operator and
16108 then applies it to the property in the column format's scope."
16109 (interactive)
16110 (unless (org-at-property-p)
16111 (user-error "Not at a property"))
16112 (let ((prop (org-match-string-no-properties 2)))
16113 (org-columns-get-format-and-top-level)
16114 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16115 (user-error "No operator defined for property %s" prop))
16116 (org-columns-compute prop)))
16118 (defvar org-property-allowed-value-functions nil
16119 "Hook for functions supplying allowed values for a specific property.
16120 The functions must take a single argument, the name of the property, and
16121 return a flat list of allowed values. If \":ETC\" is one of
16122 the values, this means that these values are intended as defaults for
16123 completion, but that other values should be allowed too.
16124 The functions must return nil if they are not responsible for this
16125 property.")
16127 (defun org-property-get-allowed-values (pom property &optional table)
16128 "Get allowed values for the property PROPERTY.
16129 When TABLE is non-nil, return an alist that can directly be used for
16130 completion."
16131 (let (vals)
16132 (cond
16133 ((equal property "TODO")
16134 (setq vals (org-with-point-at pom
16135 (append org-todo-keywords-1 '("")))))
16136 ((equal property "PRIORITY")
16137 (let ((n org-lowest-priority))
16138 (while (>= n org-highest-priority)
16139 (push (char-to-string n) vals)
16140 (setq n (1- n)))))
16141 ((member property org-special-properties))
16142 ((setq vals (run-hook-with-args-until-success
16143 'org-property-allowed-value-functions property)))
16145 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16146 (when (and vals (string-match "\\S-" vals))
16147 (setq vals (car (read-from-string (concat "(" vals ")"))))
16148 (setq vals (mapcar (lambda (x)
16149 (cond ((stringp x) x)
16150 ((numberp x) (number-to-string x))
16151 ((symbolp x) (symbol-name x))
16152 (t "???")))
16153 vals)))))
16154 (when (member ":ETC" vals)
16155 (setq vals (remove ":ETC" vals))
16156 (org-add-props (car vals) '(org-unrestricted t)))
16157 (if table (mapcar 'list vals) vals)))
16159 (defun org-property-previous-allowed-value (&optional previous)
16160 "Switch to the next allowed value for this property."
16161 (interactive)
16162 (org-property-next-allowed-value t))
16164 (defun org-property-next-allowed-value (&optional previous)
16165 "Switch to the next allowed value for this property."
16166 (interactive)
16167 (unless (org-at-property-p)
16168 (user-error "Not at a property"))
16169 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16170 (key (match-string 2))
16171 (value (match-string 3))
16172 (allowed (or (org-property-get-allowed-values (point) key)
16173 (and (member value '("[ ]" "[-]" "[X]"))
16174 '("[ ]" "[X]"))))
16175 (heading (save-match-data (nth 4 (org-heading-components))))
16176 nval)
16177 (unless allowed
16178 (user-error "Allowed values for this property have not been defined"))
16179 (if previous (setq allowed (reverse allowed)))
16180 (if (member value allowed)
16181 (setq nval (car (cdr (member value allowed)))))
16182 (setq nval (or nval (car allowed)))
16183 (if (equal nval value)
16184 (user-error "Only one allowed value for this property"))
16185 (org-at-property-p)
16186 (replace-match (concat " :" key ": " nval) t t)
16187 (org-indent-line)
16188 (beginning-of-line 1)
16189 (skip-chars-forward " \t")
16190 (when (equal prop org-effort-property)
16191 (org-refresh-property
16192 '((effort . identity)
16193 (effort-minutes . org-duration-string-to-minutes))
16194 nval)
16195 (when (string= org-clock-current-task heading)
16196 (setq org-clock-effort nval)
16197 (org-clock-update-mode-line)))
16198 (run-hook-with-args 'org-property-changed-functions key nval)))
16200 (defun org-find-olp (path &optional this-buffer)
16201 "Return a marker pointing to the entry at outline path OLP.
16202 If anything goes wrong, throw an error.
16203 You can wrap this call to catch the error like this:
16205 (condition-case msg
16206 (org-mobile-locate-entry (match-string 4))
16207 (error (nth 1 msg)))
16209 The return value will then be either a string with the error message,
16210 or a marker if everything is OK.
16212 If THIS-BUFFER is set, the outline path does not contain a file,
16213 only headings."
16214 (let* ((file (if this-buffer buffer-file-name (pop path)))
16215 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16216 (level 1)
16217 (lmin 1)
16218 (lmax 1)
16219 limit re end found pos heading cnt flevel)
16220 (unless buffer (error "File not found :%s" file))
16221 (with-current-buffer buffer
16222 (save-excursion
16223 (save-restriction
16224 (widen)
16225 (setq limit (point-max))
16226 (goto-char (point-min))
16227 (while (setq heading (pop path))
16228 (setq re (format org-complex-heading-regexp-format
16229 (regexp-quote heading)))
16230 (setq cnt 0 pos (point))
16231 (while (re-search-forward re end t)
16232 (setq level (- (match-end 1) (match-beginning 1)))
16233 (if (and (>= level lmin) (<= level lmax))
16234 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16235 (when (= cnt 0) (error "Heading not found on level %d: %s"
16236 lmax heading))
16237 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16238 lmax heading))
16239 (goto-char found)
16240 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16241 (setq end (save-excursion (org-end-of-subtree t t))))
16242 (when (org-at-heading-p)
16243 (point-marker)))))))
16245 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16246 "Find node HEADING in BUFFER.
16247 Return a marker to the heading if it was found, or nil if not.
16248 If POS-ONLY is set, return just the position instead of a marker.
16250 The heading text must match exact, but it may have a TODO keyword,
16251 a priority cookie and tags in the standard locations."
16252 (with-current-buffer (or buffer (current-buffer))
16253 (save-excursion
16254 (save-restriction
16255 (widen)
16256 (goto-char (point-min))
16257 (let (case-fold-search)
16258 (if (re-search-forward
16259 (format org-complex-heading-regexp-format
16260 (regexp-quote heading)) nil t)
16261 (if pos-only
16262 (match-beginning 0)
16263 (move-marker (make-marker) (match-beginning 0)))))))))
16265 (defun org-find-exact-heading-in-directory (heading &optional dir)
16266 "Find Org node headline HEADING in all .org files in directory DIR.
16267 When the target headline is found, return a marker to this location."
16268 (let ((files (directory-files (or dir default-directory)
16269 t "\\`[^.#].*\\.org\\'"))
16270 file visiting m buffer)
16271 (catch 'found
16272 (while (setq file (pop files))
16273 (message "trying %s" file)
16274 (setq visiting (org-find-base-buffer-visiting file))
16275 (setq buffer (or visiting (find-file-noselect file)))
16276 (setq m (org-find-exact-headline-in-buffer
16277 heading buffer))
16278 (when (and (not m) (not visiting)) (kill-buffer buffer))
16279 (and m (throw 'found m))))))
16281 (defun org-find-entry-with-id (ident)
16282 "Locate the entry that contains the ID property with exact value IDENT.
16283 IDENT can be a string, a symbol or a number, this function will search for
16284 the string representation of it.
16285 Return the position where this entry starts, or nil if there is no such entry."
16286 (interactive "sID: ")
16287 (let ((id (cond
16288 ((stringp ident) ident)
16289 ((symbol-name ident) (symbol-name ident))
16290 ((numberp ident) (number-to-string ident))
16291 (t (error "IDENT %s must be a string, symbol or number" ident))))
16292 (case-fold-search nil))
16293 (save-excursion
16294 (save-restriction
16295 (widen)
16296 (goto-char (point-min))
16297 (when (re-search-forward
16298 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16299 nil t)
16300 (org-back-to-heading t)
16301 (point))))))
16303 ;;;; Timestamps
16305 (defvar org-last-changed-timestamp nil)
16306 (defvar org-last-inserted-timestamp nil
16307 "The last time stamp inserted with `org-insert-time-stamp'.")
16308 (defvar org-ts-what) ; dynamically scoped parameter
16310 (defun org-time-stamp (arg &optional inactive)
16311 "Prompt for a date/time and insert a time stamp.
16312 If the user specifies a time like HH:MM or if this command is
16313 called with at least one prefix argument, the time stamp contains
16314 the date and the time. Otherwise, only the date is be included.
16316 All parts of a date not specified by the user is filled in from
16317 the current date/time. So if you just press return without
16318 typing anything, the time stamp will represent the current
16319 date/time.
16321 If there is already a timestamp at the cursor, it will be
16322 modified.
16324 With two universal prefix arguments, insert an active timestamp
16325 with the current time without prompting the user.
16327 When called from lisp, the timestamp is inactive if INACTIVE is
16328 non-nil."
16329 (interactive "P")
16330 (let* ((ts nil)
16331 (default-time
16332 ;; Default time is either today, or, when entering a range,
16333 ;; the range start.
16334 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16335 (save-excursion
16336 (re-search-backward
16337 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16338 (- (point) 20) t)))
16339 (apply 'encode-time (org-parse-time-string (match-string 1)))
16340 (current-time)))
16341 (default-input (and ts (org-get-compact-tod ts)))
16342 (repeater (save-excursion
16343 (save-match-data
16344 (beginning-of-line)
16345 (when (re-search-forward
16346 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16347 (save-excursion (progn (end-of-line) (point))) t)
16348 (match-string 0)))))
16349 org-time-was-given org-end-time-was-given time)
16350 (cond
16351 ((and (org-at-timestamp-p t)
16352 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16353 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16354 (insert "--")
16355 (setq time (let ((this-command this-command))
16356 (org-read-date arg 'totime nil nil
16357 default-time default-input inactive)))
16358 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16359 ((org-at-timestamp-p t)
16360 (setq time (let ((this-command this-command))
16361 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16362 (when (org-at-timestamp-p t) ; just to get the match data
16363 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16364 (replace-match "")
16365 (setq org-last-changed-timestamp
16366 (org-insert-time-stamp
16367 time (or org-time-was-given arg)
16368 inactive nil nil (list org-end-time-was-given)))
16369 (when repeater (goto-char (1- (point))) (insert " " repeater)
16370 (setq org-last-changed-timestamp
16371 (concat (substring org-last-inserted-timestamp 0 -1)
16372 " " repeater ">"))))
16373 (message "Timestamp updated"))
16374 ((equal arg '(16))
16375 (org-insert-time-stamp (current-time) t inactive))
16377 (setq time (let ((this-command this-command))
16378 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16379 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16380 nil nil (list org-end-time-was-given))))))
16382 ;; FIXME: can we use this for something else, like computing time differences?
16383 (defun org-get-compact-tod (s)
16384 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16385 (let* ((t1 (match-string 1 s))
16386 (h1 (string-to-number (match-string 2 s)))
16387 (m1 (string-to-number (match-string 3 s)))
16388 (t2 (and (match-end 4) (match-string 5 s)))
16389 (h2 (and t2 (string-to-number (match-string 6 s))))
16390 (m2 (and t2 (string-to-number (match-string 7 s))))
16391 dh dm)
16392 (if (not t2)
16394 (setq dh (- h2 h1) dm (- m2 m1))
16395 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16396 (concat t1 "+" (number-to-string dh)
16397 (and (/= 0 dm) (format ":%02d" dm)))))))
16399 (defun org-time-stamp-inactive (&optional arg)
16400 "Insert an inactive time stamp.
16401 An inactive time stamp is enclosed in square brackets instead of angle
16402 brackets. It is inactive in the sense that it does not trigger agenda entries,
16403 does not link to the calendar and cannot be changed with the S-cursor keys.
16404 So these are more for recording a certain time/date."
16405 (interactive "P")
16406 (org-time-stamp arg 'inactive))
16408 (defvar org-date-ovl (make-overlay 1 1))
16409 (overlay-put org-date-ovl 'face 'org-date-selected)
16410 (org-detach-overlay org-date-ovl)
16412 (defvar org-ans1) ; dynamically scoped parameter
16413 (defvar org-ans2) ; dynamically scoped parameter
16415 (defvar org-plain-time-of-day-regexp) ; defined below
16417 (defvar org-overriding-default-time nil) ; dynamically scoped
16418 (defvar org-read-date-overlay nil)
16419 (defvar org-dcst nil) ; dynamically scoped
16420 (defvar org-read-date-history nil)
16421 (defvar org-read-date-final-answer nil)
16422 (defvar org-read-date-analyze-futurep nil)
16423 (defvar org-read-date-analyze-forced-year nil)
16424 (defvar org-read-date-inactive)
16426 (defvar org-read-date-minibuffer-local-map
16427 (let* ((org-replace-disputed-keys nil)
16428 (map (make-sparse-keymap)))
16429 (set-keymap-parent map minibuffer-local-map)
16430 (org-defkey map (kbd ".")
16431 (lambda () (interactive)
16432 ;; Are we at the beginning of the prompt?
16433 (if (looking-back "^[^:]+: ")
16434 (org-eval-in-calendar '(calendar-goto-today))
16435 (insert "."))))
16436 (org-defkey map (kbd "C-.")
16437 (lambda () (interactive)
16438 (org-eval-in-calendar '(calendar-goto-today))))
16439 (org-defkey map [(meta shift left)]
16440 (lambda () (interactive)
16441 (org-eval-in-calendar '(calendar-backward-month 1))))
16442 (org-defkey map [(meta shift right)]
16443 (lambda () (interactive)
16444 (org-eval-in-calendar '(calendar-forward-month 1))))
16445 (org-defkey map [(meta shift up)]
16446 (lambda () (interactive)
16447 (org-eval-in-calendar '(calendar-backward-year 1))))
16448 (org-defkey map [(meta shift down)]
16449 (lambda () (interactive)
16450 (org-eval-in-calendar '(calendar-forward-year 1))))
16451 (org-defkey map [?\e (shift left)]
16452 (lambda () (interactive)
16453 (org-eval-in-calendar '(calendar-backward-month 1))))
16454 (org-defkey map [?\e (shift right)]
16455 (lambda () (interactive)
16456 (org-eval-in-calendar '(calendar-forward-month 1))))
16457 (org-defkey map [?\e (shift up)]
16458 (lambda () (interactive)
16459 (org-eval-in-calendar '(calendar-backward-year 1))))
16460 (org-defkey map [?\e (shift down)]
16461 (lambda () (interactive)
16462 (org-eval-in-calendar '(calendar-forward-year 1))))
16463 (org-defkey map [(shift up)]
16464 (lambda () (interactive)
16465 (org-eval-in-calendar '(calendar-backward-week 1))))
16466 (org-defkey map [(shift down)]
16467 (lambda () (interactive)
16468 (org-eval-in-calendar '(calendar-forward-week 1))))
16469 (org-defkey map [(shift left)]
16470 (lambda () (interactive)
16471 (org-eval-in-calendar '(calendar-backward-day 1))))
16472 (org-defkey map [(shift right)]
16473 (lambda () (interactive)
16474 (org-eval-in-calendar '(calendar-forward-day 1))))
16475 (org-defkey map "!"
16476 (lambda () (interactive)
16477 (org-eval-in-calendar '(diary-view-entries))
16478 (message "")))
16479 (org-defkey map ">"
16480 (lambda () (interactive)
16481 (org-eval-in-calendar '(scroll-calendar-left 1))))
16482 (org-defkey map "<"
16483 (lambda () (interactive)
16484 (org-eval-in-calendar '(scroll-calendar-right 1))))
16485 (org-defkey map "\C-v"
16486 (lambda () (interactive)
16487 (org-eval-in-calendar
16488 '(calendar-scroll-left-three-months 1))))
16489 (org-defkey map "\M-v"
16490 (lambda () (interactive)
16491 (org-eval-in-calendar
16492 '(calendar-scroll-right-three-months 1))))
16493 map)
16494 "Keymap for minibuffer commands when using `org-read-date'.")
16496 (defvar org-def)
16497 (defvar org-defdecode)
16498 (defvar org-with-time)
16500 (defun org-read-date (&optional org-with-time to-time from-string prompt
16501 default-time default-input inactive)
16502 "Read a date, possibly a time, and make things smooth for the user.
16503 The prompt will suggest to enter an ISO date, but you can also enter anything
16504 which will at least partially be understood by `parse-time-string'.
16505 Unrecognized parts of the date will default to the current day, month, year,
16506 hour and minute. If this command is called to replace a timestamp at point,
16507 or to enter the second timestamp of a range, the default time is taken
16508 from the existing stamp. Furthermore, the command prefers the future,
16509 so if you are giving a date where the year is not given, and the day-month
16510 combination is already past in the current year, it will assume you
16511 mean next year. For details, see the manual. A few examples:
16513 3-2-5 --> 2003-02-05
16514 feb 15 --> currentyear-02-15
16515 2/15 --> currentyear-02-15
16516 sep 12 9 --> 2009-09-12
16517 12:45 --> today 12:45
16518 22 sept 0:34 --> currentyear-09-22 0:34
16519 12 --> currentyear-currentmonth-12
16520 Fri --> nearest Friday after today
16521 -Tue --> last Tuesday
16522 etc.
16524 Furthermore you can specify a relative date by giving, as the *first* thing
16525 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16526 change in days weeks, months, years.
16527 With a single plus or minus, the date is relative to today. With a double
16528 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16529 +4d --> four days from today
16530 +4 --> same as above
16531 +2w --> two weeks from today
16532 ++5 --> five days from default date
16534 The function understands only English month and weekday abbreviations.
16536 While prompting, a calendar is popped up - you can also select the
16537 date with the mouse (button 1). The calendar shows a period of three
16538 months. To scroll it to other months, use the keys `>' and `<'.
16539 If you don't like the calendar, turn it off with
16540 \(setq org-read-date-popup-calendar nil)
16542 With optional argument TO-TIME, the date will immediately be converted
16543 to an internal time.
16544 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16545 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16546 still enter a time, and this function will inform the calling routine
16547 about this change. The calling routine may then choose to change the
16548 format used to insert the time stamp into the buffer to include the time.
16549 With optional argument FROM-STRING, read from this string instead from
16550 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16551 the time/date that is used for everything that is not specified by the
16552 user."
16553 (require 'parse-time)
16554 (let* ((org-time-stamp-rounding-minutes
16555 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16556 (org-dcst org-display-custom-times)
16557 (ct (org-current-time))
16558 (org-def (or org-overriding-default-time default-time ct))
16559 (org-defdecode (decode-time org-def))
16560 (dummy (progn
16561 (when (< (nth 2 org-defdecode) org-extend-today-until)
16562 (setcar (nthcdr 2 org-defdecode) -1)
16563 (setcar (nthcdr 1 org-defdecode) 59)
16564 (setq org-def (apply 'encode-time org-defdecode)
16565 org-defdecode (decode-time org-def)))))
16566 (mouse-autoselect-window nil) ; Don't let the mouse jump
16567 (calendar-frame-setup nil)
16568 (calendar-setup nil)
16569 (calendar-move-hook nil)
16570 (calendar-view-diary-initially-flag nil)
16571 (calendar-view-holidays-initially-flag nil)
16572 (timestr (format-time-string
16573 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16574 (prompt (concat (if prompt (concat prompt " ") "")
16575 (format "Date+time [%s]: " timestr)))
16576 ans (org-ans0 "") org-ans1 org-ans2 final)
16578 (cond
16579 (from-string (setq ans from-string))
16580 (org-read-date-popup-calendar
16581 (save-excursion
16582 (save-window-excursion
16583 (calendar)
16584 (org-eval-in-calendar '(setq cursor-type nil) t)
16585 (unwind-protect
16586 (progn
16587 (calendar-forward-day (- (time-to-days org-def)
16588 (calendar-absolute-from-gregorian
16589 (calendar-current-date))))
16590 (org-eval-in-calendar nil t)
16591 (let* ((old-map (current-local-map))
16592 (map (copy-keymap calendar-mode-map))
16593 (minibuffer-local-map
16594 (copy-keymap org-read-date-minibuffer-local-map)))
16595 (org-defkey map (kbd "RET") 'org-calendar-select)
16596 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16597 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16598 (unwind-protect
16599 (progn
16600 (use-local-map map)
16601 (setq org-read-date-inactive inactive)
16602 (add-hook 'post-command-hook 'org-read-date-display)
16603 (setq org-ans0 (read-string prompt default-input
16604 'org-read-date-history nil))
16605 ;; org-ans0: from prompt
16606 ;; org-ans1: from mouse click
16607 ;; org-ans2: from calendar motion
16608 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16609 (remove-hook 'post-command-hook 'org-read-date-display)
16610 (use-local-map old-map)
16611 (when org-read-date-overlay
16612 (delete-overlay org-read-date-overlay)
16613 (setq org-read-date-overlay nil)))))
16614 (bury-buffer "*Calendar*")))))
16616 (t ; Naked prompt only
16617 (unwind-protect
16618 (setq ans (read-string prompt default-input
16619 'org-read-date-history timestr))
16620 (when org-read-date-overlay
16621 (delete-overlay org-read-date-overlay)
16622 (setq org-read-date-overlay nil)))))
16624 (setq final (org-read-date-analyze ans org-def org-defdecode))
16626 (when org-read-date-analyze-forced-year
16627 (message "Year was forced into %s"
16628 (if org-read-date-force-compatible-dates
16629 "compatible range (1970-2037)"
16630 "range representable on this machine"))
16631 (ding))
16633 ;; One round trip to get rid of 34th of August and stuff like that....
16634 (setq final (decode-time (apply 'encode-time final)))
16636 (setq org-read-date-final-answer ans)
16638 (if to-time
16639 (apply 'encode-time final)
16640 (if (and (boundp 'org-time-was-given) org-time-was-given)
16641 (format "%04d-%02d-%02d %02d:%02d"
16642 (nth 5 final) (nth 4 final) (nth 3 final)
16643 (nth 2 final) (nth 1 final))
16644 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16646 (defun org-read-date-display ()
16647 "Display the current date prompt interpretation in the minibuffer."
16648 (when org-read-date-display-live
16649 (when org-read-date-overlay
16650 (delete-overlay org-read-date-overlay))
16651 (when (minibufferp (current-buffer))
16652 (save-excursion
16653 (end-of-line 1)
16654 (while (not (equal (buffer-substring
16655 (max (point-min) (- (point) 4)) (point))
16656 " "))
16657 (insert " ")))
16658 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16659 " " (or org-ans1 org-ans2)))
16660 (org-end-time-was-given nil)
16661 (f (org-read-date-analyze ans org-def org-defdecode))
16662 (fmts (if org-dcst
16663 org-time-stamp-custom-formats
16664 org-time-stamp-formats))
16665 (fmt (if (or org-with-time
16666 (and (boundp 'org-time-was-given) org-time-was-given))
16667 (cdr fmts)
16668 (car fmts)))
16669 (txt (format-time-string fmt (apply 'encode-time f)))
16670 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16671 (txt (concat "=> " txt)))
16672 (when (and org-end-time-was-given
16673 (string-match org-plain-time-of-day-regexp txt))
16674 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16675 org-end-time-was-given
16676 (substring txt (match-end 0)))))
16677 (when org-read-date-analyze-futurep
16678 (setq txt (concat txt " (=>F)")))
16679 (setq org-read-date-overlay
16680 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16681 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16683 (defun org-read-date-analyze (ans org-def org-defdecode)
16684 "Analyze the combined answer of the date prompt."
16685 ;; FIXME: cleanup and comment
16686 (let ((nowdecode (decode-time (current-time)))
16687 delta deltan deltaw deltadef year month day
16688 hour minute second wday pm h2 m2 tl wday1
16689 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16690 (setq org-read-date-analyze-futurep nil
16691 org-read-date-analyze-forced-year nil)
16692 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16693 (setq ans "+0"))
16695 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16696 (setq ans (replace-match "" t t ans)
16697 deltan (car delta)
16698 deltaw (nth 1 delta)
16699 deltadef (nth 2 delta)))
16701 ;; Check if there is an iso week date in there. If yes, store the
16702 ;; info and postpone interpreting it until the rest of the parsing
16703 ;; is done.
16704 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16705 (setq iso-year (if (match-end 1)
16706 (org-small-year-to-year
16707 (string-to-number (match-string 1 ans))))
16708 iso-weekday (if (match-end 3)
16709 (string-to-number (match-string 3 ans)))
16710 iso-week (string-to-number (match-string 2 ans)))
16711 (setq ans (replace-match "" t t ans)))
16713 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16714 (when (string-match
16715 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16716 (setq year (if (match-end 2)
16717 (string-to-number (match-string 2 ans))
16718 (progn (setq kill-year t)
16719 (string-to-number (format-time-string "%Y"))))
16720 month (string-to-number (match-string 3 ans))
16721 day (string-to-number (match-string 4 ans)))
16722 (if (< year 100) (setq year (+ 2000 year)))
16723 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16724 t nil ans)))
16726 ;; Help matching dotted european dates
16727 (when (string-match
16728 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16729 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16730 (setq kill-year t)
16731 (string-to-number (format-time-string "%Y")))
16732 day (string-to-number (match-string 1 ans))
16733 month (string-to-number (match-string 2 ans))
16734 ans (replace-match (format "%04d-%02d-%02d" year month day)
16735 t nil ans)))
16737 ;; Help matching american dates, like 5/30 or 5/30/7
16738 (when (string-match
16739 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16740 (setq year (if (match-end 4)
16741 (string-to-number (match-string 4 ans))
16742 (progn (setq kill-year t)
16743 (string-to-number (format-time-string "%Y"))))
16744 month (string-to-number (match-string 1 ans))
16745 day (string-to-number (match-string 2 ans)))
16746 (if (< year 100) (setq year (+ 2000 year)))
16747 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16748 t nil ans)))
16749 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16750 ;; If there is a time with am/pm, and *no* time without it, we convert
16751 ;; so that matching will be successful.
16752 (loop for i from 1 to 2 do ; twice, for end time as well
16753 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16754 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16755 (setq hour (string-to-number (match-string 1 ans))
16756 minute (if (match-end 3)
16757 (string-to-number (match-string 3 ans))
16759 pm (equal ?p
16760 (string-to-char (downcase (match-string 4 ans)))))
16761 (if (and (= hour 12) (not pm))
16762 (setq hour 0)
16763 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16764 (setq ans (replace-match (format "%02d:%02d" hour minute)
16765 t t ans))))
16767 ;; Check if a time range is given as a duration
16768 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16769 (setq hour (string-to-number (match-string 1 ans))
16770 h2 (+ hour (string-to-number (match-string 3 ans)))
16771 minute (string-to-number (match-string 2 ans))
16772 m2 (+ minute (if (match-end 5) (string-to-number
16773 (match-string 5 ans))0)))
16774 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16775 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16776 t t ans)))
16778 ;; Check if there is a time range
16779 (when (boundp 'org-end-time-was-given)
16780 (setq org-time-was-given nil)
16781 (when (and (string-match org-plain-time-of-day-regexp ans)
16782 (match-end 8))
16783 (setq org-end-time-was-given (match-string 8 ans))
16784 (setq ans (concat (substring ans 0 (match-beginning 7))
16785 (substring ans (match-end 7))))))
16787 (setq tl (parse-time-string ans)
16788 day (or (nth 3 tl) (nth 3 org-defdecode))
16789 month (or (nth 4 tl)
16790 (if (and org-read-date-prefer-future
16791 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16792 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16793 (nth 4 org-defdecode)))
16794 year (or (and (not kill-year) (nth 5 tl))
16795 (if (and org-read-date-prefer-future
16796 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16797 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16798 (nth 5 org-defdecode)))
16799 hour (or (nth 2 tl) (nth 2 org-defdecode))
16800 minute (or (nth 1 tl) (nth 1 org-defdecode))
16801 second (or (nth 0 tl) 0)
16802 wday (nth 6 tl))
16804 (when (and (eq org-read-date-prefer-future 'time)
16805 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16806 (equal day (nth 3 nowdecode))
16807 (equal month (nth 4 nowdecode))
16808 (equal year (nth 5 nowdecode))
16809 (nth 2 tl)
16810 (or (< (nth 2 tl) (nth 2 nowdecode))
16811 (and (= (nth 2 tl) (nth 2 nowdecode))
16812 (nth 1 tl)
16813 (< (nth 1 tl) (nth 1 nowdecode)))))
16814 (setq day (1+ day)
16815 futurep t))
16817 ;; Special date definitions below
16818 (cond
16819 (iso-week
16820 ;; There was an iso week
16821 (require 'cal-iso)
16822 (setq futurep nil)
16823 (setq year (or iso-year year)
16824 day (or iso-weekday wday 1)
16825 wday nil ; to make sure that the trigger below does not match
16826 iso-date (calendar-gregorian-from-absolute
16827 (calendar-absolute-from-iso
16828 (list iso-week day year))))
16829 ; FIXME: Should we also push ISO weeks into the future?
16830 ; (when (and org-read-date-prefer-future
16831 ; (not iso-year)
16832 ; (< (calendar-absolute-from-gregorian iso-date)
16833 ; (time-to-days (current-time))))
16834 ; (setq year (1+ year)
16835 ; iso-date (calendar-gregorian-from-absolute
16836 ; (calendar-absolute-from-iso
16837 ; (list iso-week day year)))))
16838 (setq month (car iso-date)
16839 year (nth 2 iso-date)
16840 day (nth 1 iso-date)))
16841 (deltan
16842 (setq futurep nil)
16843 (unless deltadef
16844 (let ((now (decode-time (current-time))))
16845 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16846 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16847 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16848 ((equal deltaw "m") (setq month (+ month deltan)))
16849 ((equal deltaw "y") (setq year (+ year deltan)))))
16850 ((and wday (not (nth 3 tl)))
16851 ;; Weekday was given, but no day, so pick that day in the week
16852 ;; on or after the derived date.
16853 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16854 (unless (equal wday wday1)
16855 (setq day (+ day (% (- wday wday1 -7) 7))))))
16856 (if (and (boundp 'org-time-was-given)
16857 (nth 2 tl))
16858 (setq org-time-was-given t))
16859 (if (< year 100) (setq year (+ 2000 year)))
16860 ;; Check of the date is representable
16861 (if org-read-date-force-compatible-dates
16862 (progn
16863 (if (< year 1970)
16864 (setq year 1970 org-read-date-analyze-forced-year t))
16865 (if (> year 2037)
16866 (setq year 2037 org-read-date-analyze-forced-year t)))
16867 (condition-case nil
16868 (ignore (encode-time second minute hour day month year))
16869 (error
16870 (setq year (nth 5 org-defdecode))
16871 (setq org-read-date-analyze-forced-year t))))
16872 (setq org-read-date-analyze-futurep futurep)
16873 (list second minute hour day month year)))
16875 (defvar parse-time-weekdays)
16876 (defun org-read-date-get-relative (s today default)
16877 "Check string S for special relative date string.
16878 TODAY and DEFAULT are internal times, for today and for a default.
16879 Return shift list (N what def-flag)
16880 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16881 N is the number of WHATs to shift.
16882 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16883 the DEFAULT date rather than TODAY."
16884 (require 'parse-time)
16885 (when (and
16886 (string-match
16887 (concat
16888 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16889 "\\([0-9]+\\)?"
16890 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16891 "\\([ \t]\\|$\\)") s)
16892 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16893 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16894 (string-to-char (substring (match-string 1 s) -1))
16895 ?+))
16896 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16897 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16898 (what (if (match-end 3) (match-string 3 s) "d"))
16899 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16900 (date (if rel default today))
16901 (wday (nth 6 (decode-time date)))
16902 delta)
16903 (if wday1
16904 (progn
16905 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16906 (if (= delta 0) (setq delta 7))
16907 (if (= dir ?-)
16908 (progn
16909 (setq delta (- delta 7))
16910 (if (= delta 0) (setq delta -7))))
16911 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16912 (list delta "d" rel))
16913 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16915 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16916 "Turn a user-specified date into the internal representation.
16917 The internal representation needed by the calendar is (month day year).
16918 This is a wrapper to handle the brain-dead convention in calendar that
16919 user function argument order change dependent on argument order."
16920 (if (boundp 'calendar-date-style)
16921 (cond
16922 ((eq calendar-date-style 'american)
16923 (list arg1 arg2 arg3))
16924 ((eq calendar-date-style 'european)
16925 (list arg2 arg1 arg3))
16926 ((eq calendar-date-style 'iso)
16927 (list arg2 arg3 arg1)))
16928 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16929 (if (org-bound-and-true-p european-calendar-style)
16930 (list arg2 arg1 arg3)
16931 (list arg1 arg2 arg3)))))
16933 (defun org-eval-in-calendar (form &optional keepdate)
16934 "Eval FORM in the calendar window and return to current window.
16935 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16936 otherwise stick to the current value of `org-ans2'."
16937 (let ((sf (selected-frame))
16938 (sw (selected-window)))
16939 (select-window (get-buffer-window "*Calendar*" t))
16940 (eval form)
16941 (when (and (not keepdate) (calendar-cursor-to-date))
16942 (let* ((date (calendar-cursor-to-date))
16943 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16944 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16945 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16946 (select-window sw)
16947 (org-select-frame-set-input-focus sf)))
16949 (defun org-calendar-select ()
16950 "Return to `org-read-date' with the date currently selected.
16951 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16952 (interactive)
16953 (when (calendar-cursor-to-date)
16954 (let* ((date (calendar-cursor-to-date))
16955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16956 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16957 (if (active-minibuffer-window) (exit-minibuffer))))
16959 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16960 "Insert a date stamp for the date given by the internal TIME.
16961 WITH-HM means use the stamp format that includes the time of the day.
16962 INACTIVE means use square brackets instead of angular ones, so that the
16963 stamp will not contribute to the agenda.
16964 PRE and POST are optional strings to be inserted before and after the
16965 stamp.
16966 The command returns the inserted time stamp."
16967 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16968 stamp)
16969 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16970 (insert-before-markers (or pre ""))
16971 (when (listp extra)
16972 (setq extra (car extra))
16973 (if (and (stringp extra)
16974 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16975 (setq extra (format "-%02d:%02d"
16976 (string-to-number (match-string 1 extra))
16977 (string-to-number (match-string 2 extra))))
16978 (setq extra nil)))
16979 (when extra
16980 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16981 (insert-before-markers (setq stamp (format-time-string fmt time)))
16982 (insert-before-markers (or post ""))
16983 (setq org-last-inserted-timestamp stamp)))
16985 (defun org-toggle-time-stamp-overlays ()
16986 "Toggle the use of custom time stamp formats."
16987 (interactive)
16988 (setq org-display-custom-times (not org-display-custom-times))
16989 (unless org-display-custom-times
16990 (let ((p (point-min)) (bmp (buffer-modified-p)))
16991 (while (setq p (next-single-property-change p 'display))
16992 (if (and (get-text-property p 'display)
16993 (eq (get-text-property p 'face) 'org-date))
16994 (remove-text-properties
16995 p (setq p (next-single-property-change p 'display))
16996 '(display t))))
16997 (set-buffer-modified-p bmp)))
16998 (if (featurep 'xemacs)
16999 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17000 (org-restart-font-lock)
17001 (setq org-table-may-need-update t)
17002 (if org-display-custom-times
17003 (message "Time stamps are overlaid with custom format")
17004 (message "Time stamp overlays removed")))
17006 (defun org-display-custom-time (beg end)
17007 "Overlay modified time stamp format over timestamp between BEG and END."
17008 (let* ((ts (buffer-substring beg end))
17009 t1 w1 with-hm tf time str w2 (off 0))
17010 (save-match-data
17011 (setq t1 (org-parse-time-string ts t))
17012 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17013 (setq off (- (match-end 0) (match-beginning 0)))))
17014 (setq end (- end off))
17015 (setq w1 (- end beg)
17016 with-hm (and (nth 1 t1) (nth 2 t1))
17017 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17018 time (org-fix-decoded-time t1)
17019 str (org-add-props
17020 (format-time-string
17021 (substring tf 1 -1) (apply 'encode-time time))
17022 nil 'mouse-face 'highlight)
17023 w2 (length str))
17024 (if (not (= w2 w1))
17025 (add-text-properties (1+ beg) (+ 2 beg)
17026 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17027 (if (featurep 'xemacs)
17028 (progn
17029 (put-text-property beg end 'invisible t)
17030 (put-text-property beg end 'end-glyph (make-glyph str)))
17031 (put-text-property beg end 'display str))))
17033 (defun org-translate-time (string)
17034 "Translate all timestamps in STRING to custom format.
17035 But do this only if the variable `org-display-custom-times' is set."
17036 (when org-display-custom-times
17037 (save-match-data
17038 (let* ((start 0)
17039 (re org-ts-regexp-both)
17040 t1 with-hm inactive tf time str beg end)
17041 (while (setq start (string-match re string start))
17042 (setq beg (match-beginning 0)
17043 end (match-end 0)
17044 t1 (save-match-data
17045 (org-parse-time-string (substring string beg end) t))
17046 with-hm (and (nth 1 t1) (nth 2 t1))
17047 inactive (equal (substring string beg (1+ beg)) "[")
17048 tf (funcall (if with-hm 'cdr 'car)
17049 org-time-stamp-custom-formats)
17050 time (org-fix-decoded-time t1)
17051 str (format-time-string
17052 (concat
17053 (if inactive "[" "<") (substring tf 1 -1)
17054 (if inactive "]" ">"))
17055 (apply 'encode-time time))
17056 string (replace-match str t t string)
17057 start (+ start (length str)))))))
17058 string)
17060 (defun org-fix-decoded-time (time)
17061 "Set 0 instead of nil for the first 6 elements of time.
17062 Don't touch the rest."
17063 (let ((n 0))
17064 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17066 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17068 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17069 "Difference between TIMESTAMP-STRING and now in days.
17070 If SECONDS is non-nil, return the difference in seconds."
17071 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17072 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17073 (funcall fdiff (current-time)))))
17075 (defun org-deadline-close (timestamp-string &optional ndays)
17076 "Is the time in TIMESTAMP-STRING close to the current date?"
17077 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17078 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17079 (not (org-entry-is-done-p))))
17081 (defun org-get-wdays (ts &optional delay zero-delay)
17082 "Get the deadline lead time appropriate for timestring TS.
17083 When DELAY is non-nil, get the delay time for scheduled items
17084 instead of the deadline lead time. When ZERO-DELAY is non-nil
17085 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17086 don't try to find the delay cookie in the scheduled timestamp."
17087 (let ((tv (if delay org-scheduled-delay-days
17088 org-deadline-warning-days)))
17089 (cond
17090 ((or (and delay (< tv 0))
17091 (and delay zero-delay (<= tv 0))
17092 (and (not delay) (<= tv 0)))
17093 ;; Enforce this value no matter what
17094 (- tv))
17095 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17096 ;; lead time is specified.
17097 (floor (* (string-to-number (match-string 1 ts))
17098 (cdr (assoc (match-string 2 ts)
17099 '(("d" . 1) ("w" . 7)
17100 ("m" . 30.4) ("y" . 365.25)
17101 ("h" . 0.041667)))))))
17102 ;; go for the default.
17103 (t tv))))
17105 (defun org-calendar-select-mouse (ev)
17106 "Return to `org-read-date' with the date currently selected.
17107 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17108 (interactive "e")
17109 (mouse-set-point ev)
17110 (when (calendar-cursor-to-date)
17111 (let* ((date (calendar-cursor-to-date))
17112 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17113 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17114 (if (active-minibuffer-window) (exit-minibuffer))))
17116 (defun org-check-deadlines (ndays)
17117 "Check if there are any deadlines due or past due.
17118 A deadline is considered due if it happens within `org-deadline-warning-days'
17119 days from today's date. If the deadline appears in an entry marked DONE,
17120 it is not shown. The prefix arg NDAYS can be used to test that many
17121 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17122 (interactive "P")
17123 (let* ((org-warn-days
17124 (cond
17125 ((equal ndays '(4)) 100000)
17126 (ndays (prefix-numeric-value ndays))
17127 (t (abs org-deadline-warning-days))))
17128 (case-fold-search nil)
17129 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17130 (callback
17131 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17133 (message "%d deadlines past-due or due within %d days"
17134 (org-occur regexp nil callback)
17135 org-warn-days)))
17137 (defsubst org-re-timestamp (type)
17138 "Return a regexp for timestamp TYPE.
17139 Allowed values for TYPE are:
17141 all: all timestamps
17142 active: only active timestamps (<...>)
17143 inactive: only inactive timestamps ([...])
17144 scheduled: only scheduled timestamps
17145 deadline: only deadline timestamps
17146 closed: only closed time-stamps
17148 When TYPE is nil, fall back on returning a regexp that matches
17149 both scheduled and deadline timestamps."
17150 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17151 ((eq type 'active) org-ts-regexp)
17152 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17153 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17154 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17155 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17156 ((eq type 'scheduled-or-deadline)
17157 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17159 (defun org-check-before-date (date)
17160 "Check if there are deadlines or scheduled entries before DATE."
17161 (interactive (list (org-read-date)))
17162 (let ((case-fold-search nil)
17163 (regexp (org-re-timestamp org-ts-type))
17164 (callback
17165 (lambda () (time-less-p
17166 (org-time-string-to-time (match-string 1))
17167 (org-time-string-to-time date)))))
17168 (message "%d entries before %s"
17169 (org-occur regexp nil callback) date)))
17171 (defun org-check-after-date (date)
17172 "Check if there are deadlines or scheduled entries after DATE."
17173 (interactive (list (org-read-date)))
17174 (let ((case-fold-search nil)
17175 (regexp (org-re-timestamp org-ts-type))
17176 (callback
17177 (lambda () (not
17178 (time-less-p
17179 (org-time-string-to-time (match-string 1))
17180 (org-time-string-to-time date))))))
17181 (message "%d entries after %s"
17182 (org-occur regexp nil callback) date)))
17184 (defun org-check-dates-range (start-date end-date)
17185 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17186 (interactive (list (org-read-date nil nil nil "Range starts")
17187 (org-read-date nil nil nil "Range end")))
17188 (let ((case-fold-search nil)
17189 (regexp (org-re-timestamp org-ts-type))
17190 (callback
17191 (lambda ()
17192 (let ((match (match-string 1)))
17193 (and
17194 (not (time-less-p
17195 (org-time-string-to-time match)
17196 (org-time-string-to-time start-date)))
17197 (time-less-p
17198 (org-time-string-to-time match)
17199 (org-time-string-to-time end-date)))))))
17200 (message "%d entries between %s and %s"
17201 (org-occur regexp nil callback) start-date end-date)))
17203 (defun org-evaluate-time-range (&optional to-buffer)
17204 "Evaluate a time range by computing the difference between start and end.
17205 Normally the result is just printed in the echo area, but with prefix arg
17206 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17207 If the time range is actually in a table, the result is inserted into the
17208 next column.
17209 For time difference computation, a year is assumed to be exactly 365
17210 days in order to avoid rounding problems."
17211 (interactive "P")
17213 (org-clock-update-time-maybe)
17214 (save-excursion
17215 (unless (org-at-date-range-p t)
17216 (goto-char (point-at-bol))
17217 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17218 (if (not (org-at-date-range-p t))
17219 (user-error "Not at a time-stamp range, and none found in current line")))
17220 (let* ((ts1 (match-string 1))
17221 (ts2 (match-string 2))
17222 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17223 (match-end (match-end 0))
17224 (time1 (org-time-string-to-time ts1))
17225 (time2 (org-time-string-to-time ts2))
17226 (t1 (org-float-time time1))
17227 (t2 (org-float-time time2))
17228 (diff (abs (- t2 t1)))
17229 (negative (< (- t2 t1) 0))
17230 ;; (ys (floor (* 365 24 60 60)))
17231 (ds (* 24 60 60))
17232 (hs (* 60 60))
17233 (fy "%dy %dd %02d:%02d")
17234 (fy1 "%dy %dd")
17235 (fd "%dd %02d:%02d")
17236 (fd1 "%dd")
17237 (fh "%02d:%02d")
17238 y d h m align)
17239 (if havetime
17240 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17242 d (floor (/ diff ds)) diff (mod diff ds)
17243 h (floor (/ diff hs)) diff (mod diff hs)
17244 m (floor (/ diff 60)))
17245 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17247 d (floor (+ (/ diff ds) 0.5))
17248 h 0 m 0))
17249 (if (not to-buffer)
17250 (message "%s" (org-make-tdiff-string y d h m))
17251 (if (org-at-table-p)
17252 (progn
17253 (goto-char match-end)
17254 (setq align t)
17255 (and (looking-at " *|") (goto-char (match-end 0))))
17256 (goto-char match-end))
17257 (if (looking-at
17258 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17259 (replace-match ""))
17260 (if negative (insert " -"))
17261 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17262 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17263 (insert " " (format fh h m))))
17264 (if align (org-table-align))
17265 (message "Time difference inserted")))))
17267 (defun org-make-tdiff-string (y d h m)
17268 (let ((fmt "")
17269 (l nil))
17270 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17271 l (push y l)))
17272 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17273 l (push d l)))
17274 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17275 l (push h l)))
17276 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17277 l (push m l)))
17278 (apply 'format fmt (nreverse l))))
17280 (defun org-time-string-to-time (s &optional buffer pos)
17281 "Convert a timestamp string into internal time."
17282 (condition-case errdata
17283 (apply 'encode-time (org-parse-time-string s))
17284 (error (error "Bad timestamp `%s'%s\nError was: %s"
17285 s (if (not (and buffer pos))
17287 (format " at %d in buffer `%s'" pos buffer))
17288 (cdr errdata)))))
17290 (defun org-time-string-to-seconds (s)
17291 "Convert a timestamp string to a number of seconds."
17292 (org-float-time (org-time-string-to-time s)))
17294 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17295 "Convert a time stamp to an absolute day number.
17296 If there is a specifier for a cyclic time stamp, get the closest
17297 date to DAYNR.
17298 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17299 The variable `date' is bound by the calendar when this is called."
17300 (cond
17301 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17302 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17303 daynr
17304 (+ daynr 1000)))
17305 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17306 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17307 (time-to-days (current-time))) (match-string 0 s)
17308 prefer show-all))
17309 (t (time-to-days
17310 (condition-case errdata
17311 (apply 'encode-time (org-parse-time-string s))
17312 (error (error "Bad timestamp `%s'%s\nError was: %s"
17313 s (if (not (and buffer pos))
17315 (format " at %d in buffer `%s'" pos buffer))
17316 (cdr errdata))))))))
17318 (defun org-days-to-iso-week (days)
17319 "Return the iso week number."
17320 (require 'cal-iso)
17321 (car (calendar-iso-from-absolute days)))
17323 (defun org-small-year-to-year (year)
17324 "Convert 2-digit years into 4-digit years.
17325 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17326 The year 2000 cannot be abbreviated. Any year larger than 99
17327 is returned unchanged."
17328 (if (< year 38)
17329 (setq year (+ 2000 year))
17330 (if (< year 100)
17331 (setq year (+ 1900 year))))
17332 year)
17334 (defun org-time-from-absolute (d)
17335 "Return the time corresponding to date D.
17336 D may be an absolute day number, or a calendar-type list (month day year)."
17337 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17338 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17340 (defun org-calendar-holiday ()
17341 "List of holidays, for Diary display in Org-mode."
17342 (require 'holidays)
17343 (let ((hl (funcall
17344 (if (fboundp 'calendar-check-holidays)
17345 'calendar-check-holidays 'check-calendar-holidays) date)))
17346 (if hl (mapconcat 'identity hl "; "))))
17348 (defun org-diary-sexp-entry (sexp entry date)
17349 "Process a SEXP diary ENTRY for DATE."
17350 (require 'diary-lib)
17351 (let ((result (if calendar-debug-sexp
17352 (let ((stack-trace-on-error t))
17353 (eval (car (read-from-string sexp))))
17354 (condition-case nil
17355 (eval (car (read-from-string sexp)))
17356 (error
17357 (beep)
17358 (message "Bad sexp at line %d in %s: %s"
17359 (org-current-line)
17360 (buffer-file-name) sexp)
17361 (sleep-for 2))))))
17362 (cond ((stringp result) (split-string result "; "))
17363 ((and (consp result)
17364 (not (consp (cdr result)))
17365 (stringp (cdr result))) (cdr result))
17366 ((and (consp result)
17367 (stringp (car result))) result)
17368 (result entry))))
17370 (defun org-diary-to-ical-string (frombuf)
17371 "Get iCalendar entries from diary entries in buffer FROMBUF.
17372 This uses the icalendar.el library."
17373 (let* ((tmpdir (if (featurep 'xemacs)
17374 (temp-directory)
17375 temporary-file-directory))
17376 (tmpfile (make-temp-name
17377 (expand-file-name "orgics" tmpdir)))
17378 buf rtn b e)
17379 (with-current-buffer frombuf
17380 (icalendar-export-region (point-min) (point-max) tmpfile)
17381 (setq buf (find-buffer-visiting tmpfile))
17382 (set-buffer buf)
17383 (goto-char (point-min))
17384 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17385 (setq b (match-beginning 0)))
17386 (goto-char (point-max))
17387 (if (re-search-backward "^END:VEVENT" nil t)
17388 (setq e (match-end 0)))
17389 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17390 (kill-buffer buf)
17391 (delete-file tmpfile)
17392 rtn))
17394 (defun org-closest-date (start current change prefer show-all)
17395 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17396 When PREFER is `past', return a date that is either CURRENT or past.
17397 When PREFER is `future', return a date that is either CURRENT or future.
17398 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17399 ;; Make the proper lists from the dates
17400 (catch 'exit
17401 (let ((a1 '(("h" . hour)
17402 ("d" . day)
17403 ("w" . week)
17404 ("m" . month)
17405 ("y" . year)))
17406 (shour (nth 2 (org-parse-time-string start)))
17407 dn dw sday cday n1 n2 n0
17408 d m y y1 y2 date1 date2 nmonths nm ny m2)
17410 (setq start (org-date-to-gregorian start)
17411 current (org-date-to-gregorian
17412 (if show-all
17413 current
17414 (time-to-days (current-time))))
17415 sday (calendar-absolute-from-gregorian start)
17416 cday (calendar-absolute-from-gregorian current))
17418 (if (<= cday sday) (throw 'exit sday))
17420 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17421 (setq dn (string-to-number (match-string 1 change))
17422 dw (cdr (assoc (match-string 2 change) a1)))
17423 (user-error "Invalid change specifier: %s" change))
17424 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17425 (cond
17426 ((eq dw 'hour)
17427 (let ((missing-hours
17428 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17429 dn)))
17430 (setq n1 (if (zerop missing-hours) cday
17431 (- cday (1+ (floor (/ missing-hours 24)))))
17432 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17433 ((eq dw 'day)
17434 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17435 n2 (+ n1 dn)))
17436 ((eq dw 'year)
17437 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17438 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17439 (setq date1 (list m d y1)
17440 n1 (calendar-absolute-from-gregorian date1)
17441 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17442 n2 (calendar-absolute-from-gregorian date2)))
17443 ((eq dw 'month)
17444 ;; approx number of month between the two dates
17445 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17446 ;; How often does dn fit in there?
17447 (setq d (nth 1 start) m (car start) y (nth 2 start)
17448 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17449 m (+ m nm)
17450 ny (floor (/ m 12))
17451 y (+ y ny)
17452 m (- m (* ny 12)))
17453 (while (> m 12) (setq m (- m 12) y (1+ y)))
17454 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17455 (setq m2 (+ m dn) y2 y)
17456 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17457 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17458 (while (<= n2 cday)
17459 (setq n1 n2 m m2 y y2)
17460 (setq m2 (+ m dn) y2 y)
17461 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17462 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17463 ;; Make sure n1 is the earlier date
17464 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17465 (if show-all
17466 (cond
17467 ((eq prefer 'past) (if (= cday n2) n2 n1))
17468 ((eq prefer 'future) (if (= cday n1) n1 n2))
17469 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17470 (cond
17471 ((eq prefer 'past) (if (= cday n2) n2 n1))
17472 ((eq prefer 'future) (if (= cday n1) n1 n2))
17473 (t (if (= cday n1) n1 n2)))))))
17475 (defun org-date-to-gregorian (date)
17476 "Turn any specification of DATE into a Gregorian date for the calendar."
17477 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17478 ((and (listp date) (= (length date) 3)) date)
17479 ((stringp date)
17480 (setq date (org-parse-time-string date))
17481 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17482 ((listp date)
17483 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17485 (defun org-parse-time-string (s &optional nodefault)
17486 "Parse the standard Org-mode time string.
17487 This should be a lot faster than the normal `parse-time-string'.
17488 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17489 hour and minute fields will be nil if not given."
17490 (cond ((string-match org-ts-regexp0 s)
17491 (list 0
17492 (if (or (match-beginning 8) (not nodefault))
17493 (string-to-number (or (match-string 8 s) "0")))
17494 (if (or (match-beginning 7) (not nodefault))
17495 (string-to-number (or (match-string 7 s) "0")))
17496 (string-to-number (match-string 4 s))
17497 (string-to-number (match-string 3 s))
17498 (string-to-number (match-string 2 s))
17499 nil nil nil))
17500 ((string-match "^<[^>]+>$" s)
17501 (decode-time (seconds-to-time (org-matcher-time s))))
17502 (t (error "Not a standard Org-mode time string: %s" s))))
17504 (defun org-timestamp-up (&optional arg)
17505 "Increase the date item at the cursor by one.
17506 If the cursor is on the year, change the year. If it is on the month,
17507 the day or the time, change that.
17508 With prefix ARG, change by that many units."
17509 (interactive "p")
17510 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17512 (defun org-timestamp-down (&optional arg)
17513 "Decrease the date item at the cursor by one.
17514 If the cursor is on the year, change the year. If it is on the month,
17515 the day or the time, change that.
17516 With prefix ARG, change by that many units."
17517 (interactive "p")
17518 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17520 (defun org-timestamp-up-day (&optional arg)
17521 "Increase the date in the time stamp by one day.
17522 With prefix ARG, change that many days."
17523 (interactive "p")
17524 (if (and (not (org-at-timestamp-p t))
17525 (org-at-heading-p))
17526 (org-todo 'up)
17527 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17529 (defun org-timestamp-down-day (&optional arg)
17530 "Decrease the date in the time stamp by one day.
17531 With prefix ARG, change that many days."
17532 (interactive "p")
17533 (if (and (not (org-at-timestamp-p t))
17534 (org-at-heading-p))
17535 (org-todo 'down)
17536 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17538 (defun org-at-timestamp-p (&optional inactive-ok)
17539 "Determine if the cursor is in or at a timestamp."
17540 (interactive)
17541 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17542 (pos (point))
17543 (ans (or (looking-at tsr)
17544 (save-excursion
17545 (skip-chars-backward "^[<\n\r\t")
17546 (if (> (point) (point-min)) (backward-char 1))
17547 (and (looking-at tsr)
17548 (> (- (match-end 0) pos) -1))))))
17549 (and ans
17550 (boundp 'org-ts-what)
17551 (setq org-ts-what
17552 (cond
17553 ((= pos (match-beginning 0)) 'bracket)
17554 ;; Point is considered to be "on the bracket" whether
17555 ;; it's really on it or right after it.
17556 ((= pos (1- (match-end 0))) 'bracket)
17557 ((= pos (match-end 0)) 'after)
17558 ((org-pos-in-match-range pos 2) 'year)
17559 ((org-pos-in-match-range pos 3) 'month)
17560 ((org-pos-in-match-range pos 7) 'hour)
17561 ((org-pos-in-match-range pos 8) 'minute)
17562 ((or (org-pos-in-match-range pos 4)
17563 (org-pos-in-match-range pos 5)) 'day)
17564 ((and (> pos (or (match-end 8) (match-end 5)))
17565 (< pos (match-end 0)))
17566 (- pos (or (match-end 8) (match-end 5))))
17567 (t 'day))))
17568 ans))
17570 (defun org-toggle-timestamp-type ()
17571 "Toggle the type (<active> or [inactive]) of a time stamp."
17572 (interactive)
17573 (when (org-at-timestamp-p t)
17574 (let ((beg (match-beginning 0)) (end (match-end 0))
17575 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17576 (save-excursion
17577 (goto-char beg)
17578 (while (re-search-forward "[][<>]" end t)
17579 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17580 t t)))
17581 (message "Timestamp is now %sactive"
17582 (if (equal (char-after beg) ?<) "" "in")))))
17584 (defun org-at-clock-log-p nil
17585 "Is the cursor on the clock log line?"
17586 (save-excursion
17587 (move-beginning-of-line 1)
17588 (looking-at "^[ \t]*CLOCK:")))
17590 (defvar org-clock-history) ; defined in org-clock.el
17591 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17592 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17593 "Change the date in the time stamp at point.
17594 The date will be changed by N times WHAT. WHAT can be `day', `month',
17595 `year', `minute', `second'. If WHAT is not given, the cursor position
17596 in the timestamp determines what will be changed.
17597 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17598 (let ((origin (point)) origin-cat
17599 with-hm inactive
17600 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17601 org-ts-what
17602 extra rem
17603 ts time time0 fixnext clrgx)
17604 (if (not (org-at-timestamp-p t))
17605 (user-error "Not at a timestamp"))
17606 (if (and (not what) (eq org-ts-what 'bracket))
17607 (org-toggle-timestamp-type)
17608 ;; Point isn't on brackets. Remember the part of the time-stamp
17609 ;; the point was in. Indeed, size of time-stamps may change,
17610 ;; but point must be kept in the same category nonetheless.
17611 (setq origin-cat org-ts-what)
17612 (if (and (not what) (not (eq org-ts-what 'day))
17613 org-display-custom-times
17614 (get-text-property (point) 'display)
17615 (not (get-text-property (1- (point)) 'display)))
17616 (setq org-ts-what 'day))
17617 (setq org-ts-what (or what org-ts-what)
17618 inactive (= (char-after (match-beginning 0)) ?\[)
17619 ts (match-string 0))
17620 (replace-match "")
17621 (when (string-match
17622 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17624 (setq extra (match-string 1 ts))
17625 (if suppress-tmp-delay
17626 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17627 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17628 (setq with-hm t))
17629 (setq time0 (org-parse-time-string ts))
17630 (when (and updown
17631 (eq org-ts-what 'minute)
17632 (not current-prefix-arg))
17633 ;; This looks like s-up and s-down. Change by one rounding step.
17634 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17635 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17636 (setcar (cdr time0) (+ (nth 1 time0)
17637 (if (> n 0) (- rem) (- dm rem))))))
17638 (setq time
17639 (encode-time (or (car time0) 0)
17640 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17641 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17642 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17643 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17644 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17645 (nthcdr 6 time0)))
17646 (when (and (member org-ts-what '(hour minute))
17647 extra
17648 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17649 (setq extra (org-modify-ts-extra
17650 extra
17651 (if (eq org-ts-what 'hour) 2 5)
17652 n dm)))
17653 (when (integerp org-ts-what)
17654 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17655 (if (eq what 'calendar)
17656 (let ((cal-date (org-get-date-from-calendar)))
17657 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17658 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17659 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17660 (setcar time0 (or (car time0) 0))
17661 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17662 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17663 (setq time (apply 'encode-time time0))))
17664 ;; Insert the new time-stamp, and ensure point stays in the same
17665 ;; category as before (i.e. not after the last position in that
17666 ;; category).
17667 (let ((pos (point)))
17668 ;; Stay before inserted string. `save-excursion' is of no use.
17669 (setq org-last-changed-timestamp
17670 (org-insert-time-stamp time with-hm inactive nil nil extra))
17671 (goto-char pos))
17672 (save-match-data
17673 (looking-at org-ts-regexp3)
17674 (goto-char (cond
17675 ;; `day' category ends before `hour' if any, or at
17676 ;; the end of the day name.
17677 ((eq origin-cat 'day)
17678 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17679 ((eq origin-cat 'hour) (min (match-end 7) origin))
17680 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17681 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17682 ;; `year' and `month' have both fixed size: point
17683 ;; couldn't have moved into another part.
17684 (t origin))))
17685 ;; Update clock if on a CLOCK line.
17686 (org-clock-update-time-maybe)
17687 ;; Maybe adjust the closest clock in `org-clock-history'
17688 (when org-clock-adjust-closest
17689 (if (not (and (org-at-clock-log-p)
17690 (< 1 (length (delq nil (mapcar 'marker-position
17691 org-clock-history))))))
17692 (message "No clock to adjust")
17693 (cond ((save-excursion ; fix previous clock?
17694 (re-search-backward org-ts-regexp0 nil t)
17695 (org-looking-back (concat org-clock-string " \\[")))
17696 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17697 ((save-excursion ; fix next clock?
17698 (re-search-backward org-ts-regexp0 nil t)
17699 (looking-at (concat org-ts-regexp0 "\\] =>")))
17700 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17701 (save-window-excursion
17702 ;; Find closest clock to point, adjust the previous/next one in history
17703 (let* ((p (save-excursion (org-back-to-heading t)))
17704 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17705 (clfixnth
17706 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17707 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17708 (if (not clfixpos)
17709 (message "No clock to adjust")
17710 (save-excursion
17711 (org-goto-marker-or-bmk clfixpos)
17712 (org-show-subtree)
17713 (when (re-search-forward clrgx nil t)
17714 (goto-char (match-beginning 1))
17715 (let (org-clock-adjust-closest)
17716 (org-timestamp-change n org-ts-what updown))
17717 (message "Clock adjusted in %s for heading: %s"
17718 (file-name-nondirectory (buffer-file-name))
17719 (org-get-heading t t)))))))))
17720 ;; Try to recenter the calendar window, if any.
17721 (if (and org-calendar-follow-timestamp-change
17722 (get-buffer-window "*Calendar*" t)
17723 (memq org-ts-what '(day month year)))
17724 (org-recenter-calendar (time-to-days time))))))
17726 (defun org-modify-ts-extra (s pos n dm)
17727 "Change the different parts of the lead-time and repeat fields in timestamp."
17728 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17729 ng h m new rem)
17730 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17731 (cond
17732 ((or (org-pos-in-match-range pos 2)
17733 (org-pos-in-match-range pos 3))
17734 (setq m (string-to-number (match-string 3 s))
17735 h (string-to-number (match-string 2 s)))
17736 (if (org-pos-in-match-range pos 2)
17737 (setq h (+ h n))
17738 (setq n (* dm (org-no-warnings (signum n))))
17739 (when (not (= 0 (setq rem (% m dm))))
17740 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17741 (setq m (+ m n)))
17742 (if (< m 0) (setq m (+ m 60) h (1- h)))
17743 (if (> m 59) (setq m (- m 60) h (1+ h)))
17744 (setq h (min 24 (max 0 h)))
17745 (setq ng 1 new (format "-%02d:%02d" h m)))
17746 ((org-pos-in-match-range pos 6)
17747 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17748 ((org-pos-in-match-range pos 5)
17749 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17751 ((org-pos-in-match-range pos 9)
17752 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17753 ((org-pos-in-match-range pos 8)
17754 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17756 (when ng
17757 (setq s (concat
17758 (substring s 0 (match-beginning ng))
17760 (substring s (match-end ng))))))
17763 (defun org-recenter-calendar (date)
17764 "If the calendar is visible, recenter it to DATE."
17765 (let ((cwin (get-buffer-window "*Calendar*" t)))
17766 (when cwin
17767 (let ((calendar-move-hook nil))
17768 (with-selected-window cwin
17769 (calendar-goto-date (if (listp date) date
17770 (calendar-gregorian-from-absolute date))))))))
17772 (defun org-goto-calendar (&optional arg)
17773 "Go to the Emacs calendar at the current date.
17774 If there is a time stamp in the current line, go to that date.
17775 A prefix ARG can be used to force the current date."
17776 (interactive "P")
17777 (let ((tsr org-ts-regexp) diff
17778 (calendar-move-hook nil)
17779 (calendar-view-holidays-initially-flag nil)
17780 (calendar-view-diary-initially-flag nil))
17781 (if (or (org-at-timestamp-p)
17782 (save-excursion
17783 (beginning-of-line 1)
17784 (looking-at (concat ".*" tsr))))
17785 (let ((d1 (time-to-days (current-time)))
17786 (d2 (time-to-days
17787 (org-time-string-to-time (match-string 1)))))
17788 (setq diff (- d2 d1))))
17789 (calendar)
17790 (calendar-goto-today)
17791 (if (and diff (not arg)) (calendar-forward-day diff))))
17793 (defun org-get-date-from-calendar ()
17794 "Return a list (month day year) of date at point in calendar."
17795 (with-current-buffer "*Calendar*"
17796 (save-match-data
17797 (calendar-cursor-to-date))))
17799 (defun org-date-from-calendar ()
17800 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17801 If there is already a time stamp at the cursor position, update it."
17802 (interactive)
17803 (if (org-at-timestamp-p t)
17804 (org-timestamp-change 0 'calendar)
17805 (let ((cal-date (org-get-date-from-calendar)))
17806 (org-insert-time-stamp
17807 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17809 (defcustom org-effort-durations
17810 `(("h" . 60)
17811 ("d" . ,(* 60 8))
17812 ("w" . ,(* 60 8 5))
17813 ("m" . ,(* 60 8 5 4))
17814 ("y" . ,(* 60 8 5 40)))
17815 "Conversion factor to minutes for an effort modifier.
17817 Each entry has the form (MODIFIER . MINUTES).
17819 In an effort string, a number followed by MODIFIER is multiplied
17820 by the specified number of MINUTES to obtain an effort in
17821 minutes.
17823 For example, if the value of this variable is ((\"hours\" . 60)), then an
17824 effort string \"2hours\" is equivalent to 120 minutes."
17825 :group 'org-agenda
17826 :version "24.1"
17827 :type '(alist :key-type (string :tag "Modifier")
17828 :value-type (number :tag "Minutes")))
17830 (defun org-minutes-to-clocksum-string (m)
17831 "Format number of minutes as a clocksum string.
17832 The format is determined by `org-time-clocksum-format',
17833 `org-time-clocksum-use-fractional' and
17834 `org-time-clocksum-fractional-format' and
17835 `org-time-clocksum-use-effort-durations'."
17836 (let ((clocksum "")
17837 (m (round m)) ; Don't allow fractions of minutes
17838 h d w mo y fmt n)
17839 (setq h (if org-time-clocksum-use-effort-durations
17840 (cdr (assoc "h" org-effort-durations)) 60)
17841 d (if org-time-clocksum-use-effort-durations
17842 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17843 w (if org-time-clocksum-use-effort-durations
17844 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17845 mo (if org-time-clocksum-use-effort-durations
17846 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17847 y (if org-time-clocksum-use-effort-durations
17848 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17849 ;; fractional format
17850 (if org-time-clocksum-use-fractional
17851 (cond
17852 ;; single format string
17853 ((stringp org-time-clocksum-fractional-format)
17854 (format org-time-clocksum-fractional-format (/ m (float h))))
17855 ;; choice of fractional formats for different time units
17856 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17857 (> (/ (truncate m) (* y d h)) 0))
17858 (format fmt (/ m (* y d (float h)))))
17859 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17860 (> (/ (truncate m) (* mo d h)) 0))
17861 (format fmt (/ m (* mo d (float h)))))
17862 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17863 (> (/ (truncate m) (* w d h)) 0))
17864 (format fmt (/ m (* w d (float h)))))
17865 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17866 (> (/ (truncate m) (* d h)) 0))
17867 (format fmt (/ m (* d (float h)))))
17868 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17869 (> (/ (truncate m) h) 0))
17870 (format fmt (/ m (float h))))
17871 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17872 (format fmt m))
17873 ;; fall back to smallest time unit with a format
17874 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17875 (format fmt (/ m (float h))))
17876 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17877 (format fmt (/ m (* d (float h)))))
17878 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17879 (format fmt (/ m (* w d (float h)))))
17880 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17881 (format fmt (/ m (* mo d (float h)))))
17882 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17883 (format fmt (/ m (* y d (float h))))))
17884 ;; standard (non-fractional) format, with single format string
17885 (if (stringp org-time-clocksum-format)
17886 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17887 ;; separate formats components
17888 (and (setq fmt (plist-get org-time-clocksum-format :years))
17889 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17890 (plist-get org-time-clocksum-format :require-years))
17891 (setq clocksum (concat clocksum (format fmt n))
17892 m (- m (* n y d h))))
17893 (and (setq fmt (plist-get org-time-clocksum-format :months))
17894 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17895 (plist-get org-time-clocksum-format :require-months))
17896 (setq clocksum (concat clocksum (format fmt n))
17897 m (- m (* n mo d h))))
17898 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17899 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17900 (plist-get org-time-clocksum-format :require-weeks))
17901 (setq clocksum (concat clocksum (format fmt n))
17902 m (- m (* n w d h))))
17903 (and (setq fmt (plist-get org-time-clocksum-format :days))
17904 (or (> (setq n (/ (truncate m) (* d h))) 0)
17905 (plist-get org-time-clocksum-format :require-days))
17906 (setq clocksum (concat clocksum (format fmt n))
17907 m (- m (* n d h))))
17908 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17909 (or (> (setq n (/ (truncate m) h)) 0)
17910 (plist-get org-time-clocksum-format :require-hours))
17911 (setq clocksum (concat clocksum (format fmt n))
17912 m (- m (* n h))))
17913 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17914 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17915 (setq clocksum (concat clocksum (format fmt m))))
17916 ;; return formatted time duration
17917 clocksum))))
17919 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17920 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17921 "Org mode version 8.0")
17923 (defun org-hours-to-clocksum-string (n)
17924 (org-minutes-to-clocksum-string (* n 60)))
17926 (defun org-hh:mm-string-to-minutes (s)
17927 "Convert a string H:MM to a number of minutes.
17928 If the string is just a number, interpret it as minutes.
17929 In fact, the first hh:mm or number in the string will be taken,
17930 there can be extra stuff in the string.
17931 If no number is found, the return value is 0."
17932 (cond
17933 ((integerp s) s)
17934 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17935 (+ (* (string-to-number (match-string 1 s)) 60)
17936 (string-to-number (match-string 2 s))))
17937 ((string-match "\\([0-9]+\\)" s)
17938 (string-to-number (match-string 1 s)))
17939 (t 0)))
17941 (defcustom org-image-actual-width t
17942 "Should we use the actual width of images when inlining them?
17944 When set to `t', always use the image width.
17946 When set to a number, use imagemagick (when available) to set
17947 the image's width to this value.
17949 When set to a number in a list, try to get the width from any
17950 #+ATTR.* keyword if it matches a width specification like
17952 #+ATTR_HTML: :width 300px
17954 and fall back on that number if none is found.
17956 When set to nil, try to get the width from an #+ATTR.* keyword
17957 and fall back on the original width if none is found.
17959 This requires Emacs >= 24.1, build with imagemagick support."
17960 :group 'org-appearance
17961 :version "24.4"
17962 :package-version '(Org . "8.0")
17963 :type '(choice
17964 (const :tag "Use the image width" t)
17965 (integer :tag "Use a number of pixels")
17966 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17967 (const :tag "Use #+ATTR* or don't resize" nil)))
17969 (defcustom org-agenda-inhibit-startup nil
17970 "Inhibit startup when preparing agenda buffers.
17971 When this variable is `t', the initialization of the Org agenda
17972 buffers is inhibited: e.g. the visibility state is not set, the
17973 tables are not re-aligned, etc."
17974 :type 'boolean
17975 :version "24.3"
17976 :group 'org-agenda)
17978 (define-obsolete-variable-alias
17979 'org-agenda-ignore-drawer-properties
17980 'org-agenda-ignore-properties "24.5")
17982 (defcustom org-agenda-ignore-properties nil
17983 "Avoid updating text properties when building the agenda.
17984 Properties are used to prepare buffers for effort estimates,
17985 appointments, statistics and subtree-local categories.
17986 If you don't use these in the agenda, you can add them to this
17987 list and agenda building will be a bit faster.
17988 The value is a list, with zero or more of the symbols `effort', `appt',
17989 `stats' or `category'."
17990 :type '(set :greedy t
17991 (const effort)
17992 (const appt)
17993 (const stats)
17994 (const category))
17995 :version "24.5"
17996 :package-version '(Org . "8.3")
17997 :group 'org-agenda)
17999 (defun org-duration-string-to-minutes (s &optional output-to-string)
18000 "Convert a duration string S to minutes.
18002 A bare number is interpreted as minutes, modifiers can be set by
18003 customizing `org-effort-durations' (which see).
18005 Entries containing a colon are interpreted as H:MM by
18006 `org-hh:mm-string-to-minutes'."
18007 (let ((result 0)
18008 (re (concat "\\([0-9.]+\\) *\\("
18009 (regexp-opt (mapcar 'car org-effort-durations))
18010 "\\)")))
18011 (while (string-match re s)
18012 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18013 (string-to-number (match-string 1 s))))
18014 (setq s (replace-match "" nil t s)))
18015 (setq result (floor result))
18016 (incf result (org-hh:mm-string-to-minutes s))
18017 (if output-to-string (number-to-string result) result)))
18019 ;;;; Files
18021 (defun org-save-all-org-buffers ()
18022 "Save all Org-mode buffers without user confirmation."
18023 (interactive)
18024 (message "Saving all Org-mode buffers...")
18025 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18026 (when (featurep 'org-id) (org-id-locations-save))
18027 (message "Saving all Org-mode buffers... done"))
18029 (defun org-revert-all-org-buffers ()
18030 "Revert all Org-mode buffers.
18031 Prompt for confirmation when there are unsaved changes.
18032 Be sure you know what you are doing before letting this function
18033 overwrite your changes.
18035 This function is useful in a setup where one tracks org files
18036 with a version control system, to revert on one machine after pulling
18037 changes from another. I believe the procedure must be like this:
18039 1. M-x org-save-all-org-buffers
18040 2. Pull changes from the other machine, resolve conflicts
18041 3. M-x org-revert-all-org-buffers"
18042 (interactive)
18043 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18044 (user-error "Abort"))
18045 (save-excursion
18046 (save-window-excursion
18047 (mapc
18048 (lambda (b)
18049 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18050 (with-current-buffer b buffer-file-name))
18051 (org-pop-to-buffer-same-window b)
18052 (revert-buffer t 'no-confirm)))
18053 (buffer-list))
18054 (when (and (featurep 'org-id) org-id-track-globally)
18055 (org-id-locations-load)))))
18057 ;;;; Agenda files
18059 ;;;###autoload
18060 (defun org-switchb (&optional arg)
18061 "Switch between Org buffers.
18062 With one prefix argument, restrict available buffers to files.
18063 With two prefix arguments, restrict available buffers to agenda files.
18065 Defaults to `iswitchb' for buffer name completion.
18066 Set `org-completion-use-ido' to make it use ido instead."
18067 (interactive "P")
18068 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18069 ((equal arg '(16)) (org-buffer-list 'agenda))
18070 (t (org-buffer-list))))
18071 (org-completion-use-iswitchb org-completion-use-iswitchb)
18072 (org-completion-use-ido org-completion-use-ido))
18073 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18074 (setq org-completion-use-iswitchb t))
18075 (org-pop-to-buffer-same-window
18076 (org-icompleting-read "Org buffer: "
18077 (mapcar 'list (mapcar 'buffer-name blist))
18078 nil t))))
18080 ;;; Define some older names previously used for this functionality
18081 ;;;###autoload
18082 (defalias 'org-ido-switchb 'org-switchb)
18083 ;;;###autoload
18084 (defalias 'org-iswitchb 'org-switchb)
18086 (defun org-buffer-list (&optional predicate exclude-tmp)
18087 "Return a list of Org buffers.
18088 PREDICATE can be `export', `files' or `agenda'.
18090 export restrict the list to Export buffers.
18091 files restrict the list to buffers visiting Org files.
18092 agenda restrict the list to buffers visiting agenda files.
18094 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18095 (let* ((bfn nil)
18096 (agenda-files (and (eq predicate 'agenda)
18097 (mapcar 'file-truename (org-agenda-files t))))
18098 (filter
18099 (cond
18100 ((eq predicate 'files)
18101 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18102 ((eq predicate 'export)
18103 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18104 ((eq predicate 'agenda)
18105 (lambda (b)
18106 (with-current-buffer b
18107 (and (derived-mode-p 'org-mode)
18108 (setq bfn (buffer-file-name b))
18109 (member (file-truename bfn) agenda-files)))))
18110 (t (lambda (b) (with-current-buffer b
18111 (or (derived-mode-p 'org-mode)
18112 (string-match "\*Org .*Export"
18113 (buffer-name b)))))))))
18114 (delq nil
18115 (mapcar
18116 (lambda(b)
18117 (if (and (funcall filter b)
18118 (or (not exclude-tmp)
18119 (not (string-match "tmp" (buffer-name b)))))
18121 nil))
18122 (buffer-list)))))
18124 (defun org-agenda-files (&optional unrestricted archives)
18125 "Get the list of agenda files.
18126 Optional UNRESTRICTED means return the full list even if a restriction
18127 is currently in place.
18128 When ARCHIVES is t, include all archive files that are really being
18129 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18130 `org-agenda-archives-mode' is t."
18131 (let ((files
18132 (cond
18133 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18134 ((stringp org-agenda-files) (org-read-agenda-file-list))
18135 ((listp org-agenda-files) org-agenda-files)
18136 (t (error "Invalid value of `org-agenda-files'")))))
18137 (setq files (apply 'append
18138 (mapcar (lambda (f)
18139 (if (file-directory-p f)
18140 (directory-files
18141 f t org-agenda-file-regexp)
18142 (list f)))
18143 files)))
18144 (when org-agenda-skip-unavailable-files
18145 (setq files (delq nil
18146 (mapcar (function
18147 (lambda (file)
18148 (and (file-readable-p file) file)))
18149 files))))
18150 (when (or (eq archives t)
18151 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18152 (setq files (org-add-archive-files files)))
18153 files))
18155 (defun org-agenda-file-p (&optional file)
18156 "Return non-nil, if FILE is an agenda file.
18157 If FILE is omitted, use the file associated with the current
18158 buffer."
18159 (member (or file (buffer-file-name))
18160 (org-agenda-files t)))
18162 (defun org-edit-agenda-file-list ()
18163 "Edit the list of agenda files.
18164 Depending on setup, this either uses customize to edit the variable
18165 `org-agenda-files', or it visits the file that is holding the list. In the
18166 latter case, the buffer is set up in a way that saving it automatically kills
18167 the buffer and restores the previous window configuration."
18168 (interactive)
18169 (if (stringp org-agenda-files)
18170 (let ((cw (current-window-configuration)))
18171 (find-file org-agenda-files)
18172 (org-set-local 'org-window-configuration cw)
18173 (org-add-hook 'after-save-hook
18174 (lambda ()
18175 (set-window-configuration
18176 (prog1 org-window-configuration
18177 (kill-buffer (current-buffer))))
18178 (org-install-agenda-files-menu)
18179 (message "New agenda file list installed"))
18180 nil 'local)
18181 (message "%s" (substitute-command-keys
18182 "Edit list and finish with \\[save-buffer]")))
18183 (customize-variable 'org-agenda-files)))
18185 (defun org-store-new-agenda-file-list (list)
18186 "Set new value for the agenda file list and save it correctly."
18187 (if (stringp org-agenda-files)
18188 (let ((fe (org-read-agenda-file-list t)) b u)
18189 (while (setq b (find-buffer-visiting org-agenda-files))
18190 (kill-buffer b))
18191 (with-temp-file org-agenda-files
18192 (insert
18193 (mapconcat
18194 (lambda (f) ;; Keep un-expanded entries.
18195 (if (setq u (assoc f fe))
18196 (cdr u)
18198 list "\n")
18199 "\n")))
18200 (let ((org-mode-hook nil) (org-inhibit-startup t)
18201 (org-insert-mode-line-in-empty-file nil))
18202 (setq org-agenda-files list)
18203 (customize-save-variable 'org-agenda-files org-agenda-files))))
18205 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18206 "Read the list of agenda files from a file.
18207 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18208 filenames, used by `org-store-new-agenda-file-list' to write back
18209 un-expanded file names."
18210 (when (file-directory-p org-agenda-files)
18211 (error "`org-agenda-files' cannot be a single directory"))
18212 (when (stringp org-agenda-files)
18213 (with-temp-buffer
18214 (insert-file-contents org-agenda-files)
18215 (mapcar
18216 (lambda (f)
18217 (let ((e (expand-file-name (substitute-in-file-name f)
18218 org-directory)))
18219 (if pair-with-expansion
18220 (cons e f)
18221 e)))
18222 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18224 ;;;###autoload
18225 (defun org-cycle-agenda-files ()
18226 "Cycle through the files in `org-agenda-files'.
18227 If the current buffer visits an agenda file, find the next one in the list.
18228 If the current buffer does not, find the first agenda file."
18229 (interactive)
18230 (let* ((fs (org-agenda-files t))
18231 (files (append fs (list (car fs))))
18232 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18233 file)
18234 (unless files (user-error "No agenda files"))
18235 (catch 'exit
18236 (while (setq file (pop files))
18237 (if (equal (file-truename file) tcf)
18238 (when (car files)
18239 (find-file (car files))
18240 (throw 'exit t))))
18241 (find-file (car fs)))
18242 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18244 (defun org-agenda-file-to-front (&optional to-end)
18245 "Move/add the current file to the top of the agenda file list.
18246 If the file is not present in the list, it is added to the front. If it is
18247 present, it is moved there. With optional argument TO-END, add/move to the
18248 end of the list."
18249 (interactive "P")
18250 (let ((org-agenda-skip-unavailable-files nil)
18251 (file-alist (mapcar (lambda (x)
18252 (cons (file-truename x) x))
18253 (org-agenda-files t)))
18254 (ctf (file-truename
18255 (or buffer-file-name
18256 (user-error "Please save the current buffer to a file"))))
18257 x had)
18258 (setq x (assoc ctf file-alist) had x)
18260 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18261 (if to-end
18262 (setq file-alist (append (delq x file-alist) (list x)))
18263 (setq file-alist (cons x (delq x file-alist))))
18264 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18265 (org-install-agenda-files-menu)
18266 (message "File %s to %s of agenda file list"
18267 (if had "moved" "added") (if to-end "end" "front"))))
18269 (defun org-remove-file (&optional file)
18270 "Remove current file from the list of files in variable `org-agenda-files'.
18271 These are the files which are being checked for agenda entries.
18272 Optional argument FILE means use this file instead of the current."
18273 (interactive)
18274 (let* ((org-agenda-skip-unavailable-files nil)
18275 (file (or file buffer-file-name
18276 (user-error "Current buffer does not visit a file")))
18277 (true-file (file-truename file))
18278 (afile (abbreviate-file-name file))
18279 (files (delq nil (mapcar
18280 (lambda (x)
18281 (if (equal true-file
18282 (file-truename x))
18283 nil x))
18284 (org-agenda-files t)))))
18285 (if (not (= (length files) (length (org-agenda-files t))))
18286 (progn
18287 (org-store-new-agenda-file-list files)
18288 (org-install-agenda-files-menu)
18289 (message "Removed file: %s" afile))
18290 (message "File was not in list: %s (not removed)" afile))))
18292 (defun org-file-menu-entry (file)
18293 (vector file (list 'find-file file) t))
18295 (defun org-check-agenda-file (file)
18296 "Make sure FILE exists. If not, ask user what to do."
18297 (when (not (file-exists-p file))
18298 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18299 (abbreviate-file-name file))
18300 (let ((r (downcase (read-char-exclusive))))
18301 (cond
18302 ((equal r ?r)
18303 (org-remove-file file)
18304 (throw 'nextfile t))
18305 (t (user-error "Abort"))))))
18307 (defun org-get-agenda-file-buffer (file)
18308 "Get an agenda buffer visiting FILE.
18309 If the buffer needs to be created, add it to the list of buffers
18310 which might be released later."
18311 (let ((buf (org-find-base-buffer-visiting file)))
18312 (if buf
18313 buf ; just return it
18314 ;; Make a new buffer and remember it
18315 (setq buf (find-file-noselect file))
18316 (if buf (push buf org-agenda-new-buffers))
18317 buf)))
18319 (defun org-release-buffers (blist)
18320 "Release all buffers in list, asking the user for confirmation when needed.
18321 When a buffer is unmodified, it is just killed. When modified, it is saved
18322 \(if the user agrees) and then killed."
18323 (let (buf file)
18324 (while (setq buf (pop blist))
18325 (setq file (buffer-file-name buf))
18326 (when (and (buffer-modified-p buf)
18327 file
18328 (y-or-n-p (format "Save file %s? " file)))
18329 (with-current-buffer buf (save-buffer)))
18330 (kill-buffer buf))))
18332 (defun org-agenda-prepare-buffers (files)
18333 "Create buffers for all agenda files, protect archived trees and comments."
18334 (interactive)
18335 (let ((pa '(:org-archived t))
18336 (pc '(:org-comment t))
18337 (pall '(:org-archived t :org-comment t))
18338 (inhibit-read-only t)
18339 (org-inhibit-startup org-agenda-inhibit-startup)
18340 (rea (concat ":" org-archive-tag ":"))
18341 file re pos)
18342 (setq org-tag-alist-for-agenda nil
18343 org-tag-groups-alist-for-agenda nil)
18344 (save-excursion
18345 (save-restriction
18346 (while (setq file (pop files))
18347 (catch 'nextfile
18348 (if (bufferp file)
18349 (set-buffer file)
18350 (org-check-agenda-file file)
18351 (set-buffer (org-get-agenda-file-buffer file)))
18352 (widen)
18353 (org-set-regexps-and-options-for-tags)
18354 (setq pos (point))
18355 (goto-char (point-min))
18356 (let ((case-fold-search t))
18357 (when (search-forward "#+setupfile" nil t)
18358 ;; Don't set all regexps and options systematically as
18359 ;; this is only run for setting agenda tags from setup
18360 ;; file
18361 (org-set-regexps-and-options)))
18362 (or (memq 'category org-agenda-ignore-properties)
18363 (org-refresh-category-properties))
18364 (or (memq 'stats org-agenda-ignore-properties)
18365 (org-refresh-stats-properties))
18366 (or (memq 'effort org-agenda-ignore-properties)
18367 (org-refresh-effort-properties))
18368 (or (memq 'appt org-agenda-ignore-properties)
18369 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18370 (setq org-todo-keywords-for-agenda
18371 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18372 (setq org-done-keywords-for-agenda
18373 (append org-done-keywords-for-agenda org-done-keywords))
18374 (setq org-todo-keyword-alist-for-agenda
18375 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18376 (setq org-tag-alist-for-agenda
18377 (org-uniquify
18378 (append org-tag-alist-for-agenda
18379 org-tag-alist
18380 org-tag-persistent-alist)))
18381 (if org-group-tags
18382 (setq org-tag-groups-alist-for-agenda
18383 (org-uniquify-alist
18384 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18385 (org-with-silent-modifications
18386 (save-excursion
18387 (remove-text-properties (point-min) (point-max) pall)
18388 (when org-agenda-skip-archived-trees
18389 (goto-char (point-min))
18390 (while (re-search-forward rea nil t)
18391 (if (org-at-heading-p t)
18392 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18393 (goto-char (point-min))
18394 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18395 (while (re-search-forward re nil t)
18396 (when (save-match-data (org-in-commented-heading-p t))
18397 (add-text-properties
18398 (match-beginning 0) (org-end-of-subtree t) pc)))))
18399 (goto-char pos)))))
18400 (setq org-todo-keywords-for-agenda
18401 (org-uniquify org-todo-keywords-for-agenda))
18402 (setq org-todo-keyword-alist-for-agenda
18403 (org-uniquify org-todo-keyword-alist-for-agenda))))
18406 ;;;; CDLaTeX minor mode
18408 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18409 "Keymap for the minor `org-cdlatex-mode'.")
18411 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18412 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18413 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18414 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18415 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18417 (defvar org-cdlatex-texmathp-advice-is-done nil
18418 "Flag remembering if we have applied the advice to texmathp already.")
18420 (define-minor-mode org-cdlatex-mode
18421 "Toggle the minor `org-cdlatex-mode'.
18422 This mode supports entering LaTeX environment and math in LaTeX fragments
18423 in Org-mode.
18424 \\{org-cdlatex-mode-map}"
18425 nil " OCDL" nil
18426 (when org-cdlatex-mode
18427 (require 'cdlatex)
18428 (run-hooks 'cdlatex-mode-hook)
18429 (cdlatex-compute-tables))
18430 (unless org-cdlatex-texmathp-advice-is-done
18431 (setq org-cdlatex-texmathp-advice-is-done t)
18432 (defadvice texmathp (around org-math-always-on activate)
18433 "Always return t in org-mode buffers.
18434 This is because we want to insert math symbols without dollars even outside
18435 the LaTeX math segments. If Orgmode thinks that point is actually inside
18436 an embedded LaTeX fragment, let texmathp do its job.
18437 \\[org-cdlatex-mode-map]"
18438 (interactive)
18439 (let (p)
18440 (cond
18441 ((not (derived-mode-p 'org-mode)) ad-do-it)
18442 ((eq this-command 'cdlatex-math-symbol)
18443 (setq ad-return-value t
18444 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18446 (let ((p (org-inside-LaTeX-fragment-p)))
18447 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18448 (setq ad-return-value t
18449 texmathp-why '("Org-mode embedded math" . 0))
18450 (if p ad-do-it)))))))))
18452 (defun turn-on-org-cdlatex ()
18453 "Unconditionally turn on `org-cdlatex-mode'."
18454 (org-cdlatex-mode 1))
18456 (defun org-try-cdlatex-tab ()
18457 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18458 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18459 - inside a LaTeX fragment, or
18460 - after the first word in a line, where an abbreviation expansion could
18461 insert a LaTeX environment."
18462 (when org-cdlatex-mode
18463 (cond
18464 ;; Before any word on the line: No expansion possible.
18465 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18466 ;; Just after first word on the line: Expand it. Make sure it
18467 ;; cannot happen on headlines, though.
18468 ((save-excursion
18469 (skip-chars-backward "a-zA-Z0-9*")
18470 (skip-chars-backward " \t")
18471 (and (bolp) (not (org-at-heading-p))))
18472 (cdlatex-tab) t)
18473 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18475 (defun org-cdlatex-underscore-caret (&optional arg)
18476 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18477 Revert to the normal definition outside of these fragments."
18478 (interactive "P")
18479 (if (org-inside-LaTeX-fragment-p)
18480 (call-interactively 'cdlatex-sub-superscript)
18481 (let (org-cdlatex-mode)
18482 (call-interactively (key-binding (vector last-input-event))))))
18484 (defun org-cdlatex-math-modify (&optional arg)
18485 "Execute `cdlatex-math-modify' in LaTeX fragments.
18486 Revert to the normal definition outside of these fragments."
18487 (interactive "P")
18488 (if (org-inside-LaTeX-fragment-p)
18489 (call-interactively 'cdlatex-math-modify)
18490 (let (org-cdlatex-mode)
18491 (call-interactively (key-binding (vector last-input-event))))))
18495 ;;;; LaTeX fragments
18497 (defun org-inside-LaTeX-fragment-p ()
18498 "Test if point is inside a LaTeX fragment.
18499 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18500 sequence appearing also before point.
18501 Even though the matchers for math are configurable, this function assumes
18502 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18503 delimiters are skipped when they have been removed by customization.
18504 The return value is nil, or a cons cell with the delimiter and the
18505 position of this delimiter.
18507 This function does a reasonably good job, but can locally be fooled by
18508 for example currency specifications. For example it will assume being in
18509 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18510 fragments that are properly closed, but during editing, we have to live
18511 with the uncertainty caused by missing closing delimiters. This function
18512 looks only before point, not after."
18513 (catch 'exit
18514 (let ((pos (point))
18515 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18516 (lim (progn
18517 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18518 (point)))
18519 dd-on str (start 0) m re)
18520 (goto-char pos)
18521 (when dodollar
18522 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18523 re (nth 1 (assoc "$" org-latex-regexps)))
18524 (while (string-match re str start)
18525 (cond
18526 ((= (match-end 0) (length str))
18527 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18528 ((= (match-end 0) (- (length str) 5))
18529 (throw 'exit nil))
18530 (t (setq start (match-end 0))))))
18531 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18532 (goto-char pos)
18533 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18534 (and (match-beginning 2) (throw 'exit nil))
18535 ;; count $$
18536 (while (re-search-backward "\\$\\$" lim t)
18537 (setq dd-on (not dd-on)))
18538 (goto-char pos)
18539 (if dd-on (cons "$$" m))))))
18541 (defun org-inside-latex-macro-p ()
18542 "Is point inside a LaTeX macro or its arguments?"
18543 (save-match-data
18544 (org-in-regexp
18545 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18547 (defvar org-latex-fragment-image-overlays nil
18548 "List of overlays carrying the images of latex fragments.")
18549 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18551 (defun org-remove-latex-fragment-image-overlays ()
18552 "Remove all overlays with LaTeX fragment images in current buffer."
18553 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18554 (setq org-latex-fragment-image-overlays nil))
18556 (define-obsolete-function-alias
18557 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18558 (defun org-toggle-latex-fragment (&optional subtree)
18559 "Preview the LaTeX fragment at point, or all locally or globally.
18560 If the cursor is in a LaTeX fragment, create the image and overlay
18561 it over the source code. If there is no fragment at point, display
18562 all fragments in the current text, from one headline to the next. With
18563 prefix SUBTREE, display all fragments in the current subtree. With a
18564 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18565 the cursor is before the first headline,
18566 display all fragments in the buffer.
18567 The images can be removed again with \\[org-toggle-latex-fragment]."
18568 (interactive "P")
18569 (unless buffer-file-name
18570 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18571 (if org-latex-fragment-image-overlays
18572 (progn (org-remove-latex-fragment-image-overlays)
18573 (message "LaTeX fragments images removed"))
18574 (when (display-graphic-p)
18575 (org-remove-latex-fragment-image-overlays)
18576 (save-excursion
18577 (save-restriction
18578 (let (beg end at msg)
18579 (cond
18580 ((or (equal subtree '(16))
18581 (not (save-excursion
18582 (re-search-backward org-outline-regexp-bol nil t))))
18583 (setq beg (point-min) end (point-max)
18584 msg "Creating images for buffer...%s"))
18585 ((equal subtree '(4))
18586 (org-back-to-heading)
18587 (setq beg (point) end (org-end-of-subtree t)
18588 msg "Creating images for subtree...%s"))
18590 (if (setq at (org-inside-LaTeX-fragment-p))
18591 (goto-char (max (point-min) (- (cdr at) 2)))
18592 (org-back-to-heading))
18593 (setq beg (point) end (progn (outline-next-heading) (point))
18594 msg (if at "Creating image...%s"
18595 "Creating images for entry...%s"))))
18596 (message msg "")
18597 (narrow-to-region beg end)
18598 (goto-char beg)
18599 (org-format-latex
18600 (concat org-latex-preview-ltxpng-directory
18601 (file-name-sans-extension
18602 (file-name-nondirectory buffer-file-name)))
18603 default-directory 'overlays msg at 'forbuffer
18604 org-latex-create-formula-image-program)
18605 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18607 (defun org-format-latex (prefix &optional dir overlays msg at
18608 forbuffer processing-type)
18609 "Replace LaTeX fragments with links to an image, and produce images.
18610 Some of the options can be changed using the variable
18611 `org-format-latex-options'."
18612 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18613 (let* ((prefixnodir (file-name-nondirectory prefix))
18614 (absprefix (expand-file-name prefix dir))
18615 (todir (file-name-directory absprefix))
18616 (opt org-format-latex-options)
18617 (optnew org-format-latex-options)
18618 (matchers (plist-get opt :matchers))
18619 (re-list org-latex-regexps)
18620 (cnt 0) txt hash link beg end re e checkdir
18621 string
18622 m n block-type block linkfile movefile ov)
18623 ;; Check the different regular expressions
18624 (while (setq e (pop re-list))
18625 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18626 block (if block-type "\n\n" ""))
18627 (when (member m matchers)
18628 (goto-char (point-min))
18629 (while (re-search-forward re nil t)
18630 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18631 (or (not overlays)
18632 (not (eq (get-char-property (match-beginning n)
18633 'org-overlay-type)
18634 'org-latex-overlay))))
18635 (cond
18636 ((eq processing-type 'verbatim))
18637 ((eq processing-type 'mathjax)
18638 ;; Prepare for MathJax processing.
18639 (setq string (match-string n))
18640 (when (member m '("$" "$1"))
18641 (save-excursion
18642 (delete-region (match-beginning n) (match-end n))
18643 (goto-char (match-beginning n))
18644 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18645 ((or (eq processing-type 'dvipng)
18646 (eq processing-type 'imagemagick))
18647 ;; Process to an image.
18648 (setq txt (match-string n)
18649 beg (match-beginning n) end (match-end n)
18650 cnt (1+ cnt))
18651 (let ((face (face-at-point))
18652 (fg (plist-get opt :foreground))
18653 (bg (plist-get opt :background))
18654 ;; Ensure full list is printed.
18655 print-length print-level)
18656 (when forbuffer
18657 ;; Get the colors from the face at point.
18658 (goto-char beg)
18659 (when (eq fg 'auto)
18660 (setq fg (face-attribute face :foreground nil 'default)))
18661 (when (eq bg 'auto)
18662 (setq bg (face-attribute face :background nil 'default)))
18663 (setq optnew (copy-sequence opt))
18664 (plist-put optnew :foreground fg)
18665 (plist-put optnew :background bg))
18666 (setq hash (sha1 (prin1-to-string
18667 (list org-format-latex-header
18668 org-latex-default-packages-alist
18669 org-latex-packages-alist
18670 org-format-latex-options
18671 forbuffer txt fg bg)))
18672 linkfile (format "%s_%s.png" prefix hash)
18673 movefile (format "%s_%s.png" absprefix hash)))
18674 (setq link (concat block "[[file:" linkfile "]]" block))
18675 (if msg (message msg cnt))
18676 (goto-char beg)
18677 (unless checkdir ; Ensure the directory exists.
18678 (setq checkdir t)
18679 (or (file-directory-p todir) (make-directory todir t)))
18680 (unless (file-exists-p movefile)
18681 (org-create-formula-image
18682 txt movefile optnew forbuffer processing-type))
18683 (if overlays
18684 (progn
18685 (mapc (lambda (o)
18686 (if (eq (overlay-get o 'org-overlay-type)
18687 'org-latex-overlay)
18688 (delete-overlay o)))
18689 (overlays-in beg end))
18690 (setq ov (make-overlay beg end))
18691 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18692 (if (featurep 'xemacs)
18693 (progn
18694 (overlay-put ov 'invisible t)
18695 (overlay-put
18696 ov 'end-glyph
18697 (make-glyph (vector 'png :file movefile))))
18698 (overlay-put
18699 ov 'display
18700 (list 'image :type 'png :file movefile :ascent 'center)))
18701 (push ov org-latex-fragment-image-overlays)
18702 (goto-char end))
18703 (delete-region beg end)
18704 (insert (org-add-props link
18705 (list 'org-latex-src
18706 (replace-regexp-in-string
18707 "\"" "" txt)
18708 'org-latex-src-embed-type
18709 (if block-type 'paragraph 'character))))))
18710 ((eq processing-type 'mathml)
18711 ;; Process to MathML
18712 (unless (save-match-data (org-format-latex-mathml-available-p))
18713 (user-error "LaTeX to MathML converter not configured"))
18714 (setq txt (match-string n)
18715 beg (match-beginning n) end (match-end n)
18716 cnt (1+ cnt))
18717 (if msg (message msg cnt))
18718 (goto-char beg)
18719 (delete-region beg end)
18720 (insert (org-format-latex-as-mathml
18721 txt block-type prefix dir)))
18723 (error "Unknown conversion type %s for LaTeX fragments"
18724 processing-type)))))))))
18726 (defun org-create-math-formula (latex-frag &optional mathml-file)
18727 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18728 Use `org-latex-to-mathml-convert-command'. If the conversion is
18729 sucessful, return the portion between \"<math...> </math>\"
18730 elements otherwise return nil. When MATHML-FILE is specified,
18731 write the results in to that file. When invoked as an
18732 interactive command, prompt for LATEX-FRAG, with initial value
18733 set to the current active region and echo the results for user
18734 inspection."
18735 (interactive (list (let ((frag (when (org-region-active-p)
18736 (buffer-substring-no-properties
18737 (region-beginning) (region-end)))))
18738 (read-string "LaTeX Fragment: " frag nil frag))))
18739 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18740 (let* ((tmp-in-file (file-relative-name
18741 (make-temp-name (expand-file-name "ltxmathml-in"))))
18742 (ignore (write-region latex-frag nil tmp-in-file))
18743 (tmp-out-file (file-relative-name
18744 (make-temp-name (expand-file-name "ltxmathml-out"))))
18745 (cmd (format-spec
18746 org-latex-to-mathml-convert-command
18747 `((?j . ,(shell-quote-argument
18748 (expand-file-name org-latex-to-mathml-jar-file)))
18749 (?I . ,(shell-quote-argument tmp-in-file))
18750 (?o . ,(shell-quote-argument tmp-out-file)))))
18751 mathml shell-command-output)
18752 (when (org-called-interactively-p 'any)
18753 (unless (org-format-latex-mathml-available-p)
18754 (user-error "LaTeX to MathML converter not configured")))
18755 (message "Running %s" cmd)
18756 (setq shell-command-output (shell-command-to-string cmd))
18757 (setq mathml
18758 (when (file-readable-p tmp-out-file)
18759 (with-current-buffer (find-file-noselect tmp-out-file t)
18760 (goto-char (point-min))
18761 (when (re-search-forward
18762 (concat
18763 (regexp-quote
18764 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18765 "\\(.\\|\n\\)*"
18766 (regexp-quote "</math>")) nil t)
18767 (prog1 (match-string 0) (kill-buffer))))))
18768 (cond
18769 (mathml
18770 (setq mathml
18771 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18772 (when mathml-file
18773 (write-region mathml nil mathml-file))
18774 (when (org-called-interactively-p 'any)
18775 (message mathml)))
18776 ((message "LaTeX to MathML conversion failed")
18777 (message shell-command-output)))
18778 (delete-file tmp-in-file)
18779 (when (file-exists-p tmp-out-file)
18780 (delete-file tmp-out-file))
18781 mathml))
18783 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18784 prefix &optional dir)
18785 "Use `org-create-math-formula' but check local cache first."
18786 (let* ((absprefix (expand-file-name prefix dir))
18787 (print-length nil) (print-level nil)
18788 (formula-id (concat
18789 "formula-"
18790 (sha1
18791 (prin1-to-string
18792 (list latex-frag
18793 org-latex-to-mathml-convert-command)))))
18794 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18795 (formula-cache-dir (file-name-directory formula-cache)))
18797 (unless (file-directory-p formula-cache-dir)
18798 (make-directory formula-cache-dir t))
18800 (unless (file-exists-p formula-cache)
18801 (org-create-math-formula latex-frag formula-cache))
18803 (if (file-exists-p formula-cache)
18804 ;; Successful conversion. Return the link to MathML file.
18805 (org-add-props
18806 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18807 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18808 'org-latex-src-embed-type (if latex-frag-type
18809 'paragraph 'character)))
18810 ;; Failed conversion. Return the LaTeX fragment verbatim
18811 latex-frag)))
18813 (defun org-create-formula-image (string tofile options buffer &optional type)
18814 "Create an image from LaTeX source using dvipng or convert.
18815 This function calls either `org-create-formula-image-with-dvipng'
18816 or `org-create-formula-image-with-imagemagick' depending on the
18817 value of `org-latex-create-formula-image-program' or on the value
18818 of the optional TYPE variable.
18820 Note: ultimately these two function should be combined as they
18821 share a good deal of logic."
18822 (org-check-external-command
18823 "latex" "needed to convert LaTeX fragments to images")
18824 (funcall
18825 (case (or type org-latex-create-formula-image-program)
18826 ('dvipng
18827 (org-check-external-command
18828 "dvipng" "needed to convert LaTeX fragments to images")
18829 'org-create-formula-image-with-dvipng)
18830 ('imagemagick
18831 (org-check-external-command
18832 "convert" "you need to install imagemagick")
18833 'org-create-formula-image-with-imagemagick)
18834 (t (error
18835 "Invalid value of `org-latex-create-formula-image-program'")))
18836 string tofile options buffer))
18838 (declare-function org-export-get-backend "ox" (name))
18839 (declare-function org-export--get-global-options "ox" (&optional backend))
18840 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18841 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18842 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18843 (defun org-create-formula--latex-header ()
18844 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18845 (let ((info (org-combine-plists (org-export--get-global-options
18846 (org-export-get-backend 'latex))
18847 (org-export--get-inbuffer-options
18848 (org-export-get-backend 'latex)))))
18849 (org-latex-guess-babel-language
18850 (org-latex-guess-inputenc
18851 (org-splice-latex-header
18852 org-format-latex-header
18853 org-latex-default-packages-alist
18854 org-latex-packages-alist t
18855 (plist-get info :latex-header)))
18856 info)))
18858 ;; This function borrows from Ganesh Swami's latex2png.el
18859 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18860 "This calls dvipng."
18861 (require 'ox-latex)
18862 (let* ((tmpdir (if (featurep 'xemacs)
18863 (temp-directory)
18864 temporary-file-directory))
18865 (texfilebase (make-temp-name
18866 (expand-file-name "orgtex" tmpdir)))
18867 (texfile (concat texfilebase ".tex"))
18868 (dvifile (concat texfilebase ".dvi"))
18869 (pngfile (concat texfilebase ".png"))
18870 (fnh (if (featurep 'xemacs)
18871 (font-height (face-font 'default))
18872 (face-attribute 'default :height nil)))
18873 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18874 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18875 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18876 "Black"))
18877 (bg (or (plist-get options (if buffer :background :html-background))
18878 "Transparent")))
18879 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18880 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18881 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18882 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18883 (let ((latex-header (org-create-formula--latex-header)))
18884 (with-temp-file texfile
18885 (insert latex-header)
18886 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18887 (let ((dir default-directory))
18888 (ignore-errors
18889 (cd tmpdir)
18890 (call-process "latex" nil nil nil texfile))
18891 (cd dir))
18892 (if (not (file-exists-p dvifile))
18893 (progn (message "Failed to create dvi file from %s" texfile) nil)
18894 (ignore-errors
18895 (if (featurep 'xemacs)
18896 (call-process "dvipng" nil nil nil
18897 "-fg" fg "-bg" bg
18898 "-T" "tight"
18899 "-o" pngfile
18900 dvifile)
18901 (call-process "dvipng" nil nil nil
18902 "-fg" fg "-bg" bg
18903 "-D" dpi
18904 ;;"-x" scale "-y" scale
18905 "-T" "tight"
18906 "-o" pngfile
18907 dvifile)))
18908 (if (not (file-exists-p pngfile))
18909 (if org-format-latex-signal-error
18910 (error "Failed to create png file from %s" texfile)
18911 (message "Failed to create png file from %s" texfile)
18912 nil)
18913 ;; Use the requested file name and clean up
18914 (copy-file pngfile tofile 'replace)
18915 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18916 (if (file-exists-p (concat texfilebase e))
18917 (delete-file (concat texfilebase e))))
18918 pngfile))))
18920 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18921 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18922 "This calls convert, which is included into imagemagick."
18923 (require 'ox-latex)
18924 (let* ((tmpdir (if (featurep 'xemacs)
18925 (temp-directory)
18926 temporary-file-directory))
18927 (texfilebase (make-temp-name
18928 (expand-file-name "orgtex" tmpdir)))
18929 (texfile (concat texfilebase ".tex"))
18930 (pdffile (concat texfilebase ".pdf"))
18931 (pngfile (concat texfilebase ".png"))
18932 (fnh (if (featurep 'xemacs)
18933 (font-height (face-font 'default))
18934 (face-attribute 'default :height nil)))
18935 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18936 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18937 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18938 "black"))
18939 (bg (or (plist-get options (if buffer :background :html-background))
18940 "white")))
18941 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18942 (setq fg (org-latex-color-format fg)))
18943 (if (eq bg 'default) (setq bg (org-latex-color :background))
18944 (setq bg (org-latex-color-format
18945 (if (string= bg "Transparent") "white" bg))))
18946 (let ((latex-header (org-create-formula--latex-header)))
18947 (with-temp-file texfile
18948 (insert latex-header)
18949 (insert "\n\\begin{document}\n"
18950 "\\definecolor{fg}{rgb}{" fg "}\n"
18951 "\\definecolor{bg}{rgb}{" bg "}\n"
18952 "\n\\pagecolor{bg}\n"
18953 "\n{\\color{fg}\n"
18954 string
18955 "\n}\n"
18956 "\n\\end{document}\n")))
18957 (org-latex-compile texfile t)
18958 (if (not (file-exists-p pdffile))
18959 (progn (message "Failed to create pdf file from %s" texfile) nil)
18960 (ignore-errors
18961 (if (featurep 'xemacs)
18962 (call-process "convert" nil nil nil
18963 "-density" "96"
18964 "-trim"
18965 "-antialias"
18966 pdffile
18967 "-quality" "100"
18968 ;; "-sharpen" "0x1.0"
18969 pngfile)
18970 (call-process "convert" nil nil nil
18971 "-density" dpi
18972 "-trim"
18973 "-antialias"
18974 pdffile
18975 "-quality" "100"
18976 ;; "-sharpen" "0x1.0"
18977 pngfile)))
18978 (if (not (file-exists-p pngfile))
18979 (if org-format-latex-signal-error
18980 (error "Failed to create png file from %s" texfile)
18981 (message "Failed to create png file from %s" texfile)
18982 nil)
18983 ;; Use the requested file name and clean up
18984 (copy-file pngfile tofile 'replace)
18985 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18986 (if (file-exists-p (concat texfilebase e))
18987 (delete-file (concat texfilebase e))))
18988 pngfile))))
18990 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18991 "Fill a LaTeX header template TPL.
18992 In the template, the following place holders will be recognized:
18994 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18995 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18996 [PACKAGES] \\usepackage statements for PKG
18997 [NO-PACKAGES] do not include PKG
18998 [EXTRA] the string EXTRA
18999 [NO-EXTRA] do not include EXTRA
19001 For backward compatibility, if both the positive and the negative place
19002 holder is missing, the positive one (without the \"NO-\") will be
19003 assumed to be present at the end of the template.
19004 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19005 EXTRA is a string.
19006 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19007 (let (rpl (end ""))
19008 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19009 (setq rpl (if (or (match-end 1) (not def-pkg))
19010 "" (org-latex-packages-to-string def-pkg snippets-p t))
19011 tpl (replace-match rpl t t tpl))
19012 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19014 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19015 (setq rpl (if (or (match-end 1) (not pkg))
19016 "" (org-latex-packages-to-string pkg snippets-p t))
19017 tpl (replace-match rpl t t tpl))
19018 (if pkg (setq end
19019 (concat end "\n"
19020 (org-latex-packages-to-string pkg snippets-p)))))
19022 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19023 (setq rpl (if (or (match-end 1) (not extra))
19024 "" (concat extra "\n"))
19025 tpl (replace-match rpl t t tpl))
19026 (if (and extra (string-match "\\S-" extra))
19027 (setq end (concat end "\n" extra))))
19029 (if (string-match "\\S-" end)
19030 (concat tpl "\n" end)
19031 tpl)))
19033 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19034 "Turn an alist of packages into a string with the \\usepackage macros."
19035 (setq pkg (mapconcat (lambda(p)
19036 (cond
19037 ((stringp p) p)
19038 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19039 (format "%% Package %s omitted" (cadr p)))
19040 ((equal "" (car p))
19041 (format "\\usepackage{%s}" (cadr p)))
19043 (format "\\usepackage[%s]{%s}"
19044 (car p) (cadr p)))))
19046 "\n"))
19047 (if newline (concat pkg "\n") pkg))
19049 (defun org-dvipng-color (attr)
19050 "Return a RGB color specification for dvipng."
19051 (apply 'format "rgb %s %s %s"
19052 (mapcar 'org-normalize-color
19053 (if (featurep 'xemacs)
19054 (color-rgb-components
19055 (face-property 'default
19056 (cond ((eq attr :foreground) 'foreground)
19057 ((eq attr :background) 'background))))
19058 (color-values (face-attribute 'default attr nil))))))
19060 (defun org-dvipng-color-format (color-name)
19061 "Convert COLOR-NAME to a RGB color value for dvipng."
19062 (apply 'format "rgb %s %s %s"
19063 (mapcar 'org-normalize-color
19064 (color-values color-name))))
19066 (defun org-latex-color (attr)
19067 "Return a RGB color for the LaTeX color package."
19068 (apply 'format "%s,%s,%s"
19069 (mapcar 'org-normalize-color
19070 (if (featurep 'xemacs)
19071 (color-rgb-components
19072 (face-property 'default
19073 (cond ((eq attr :foreground) 'foreground)
19074 ((eq attr :background) 'background))))
19075 (color-values (face-attribute 'default attr nil))))))
19077 (defun org-latex-color-format (color-name)
19078 "Convert COLOR-NAME to a RGB color value."
19079 (apply 'format "%s,%s,%s"
19080 (mapcar 'org-normalize-color
19081 (color-values color-name))))
19083 (defun org-normalize-color (value)
19084 "Return string to be used as color value for an RGB component."
19085 (format "%g" (/ value 65535.0)))
19089 ;; Image display
19091 (defvar org-inline-image-overlays nil)
19092 (make-variable-buffer-local 'org-inline-image-overlays)
19094 (defun org-toggle-inline-images (&optional include-linked)
19095 "Toggle the display of inline images.
19096 INCLUDE-LINKED is passed to `org-display-inline-images'."
19097 (interactive "P")
19098 (if org-inline-image-overlays
19099 (progn
19100 (org-remove-inline-images)
19101 (message "Inline image display turned off"))
19102 (org-display-inline-images include-linked)
19103 (if (and (org-called-interactively-p)
19104 org-inline-image-overlays)
19105 (message "%d images displayed inline"
19106 (length org-inline-image-overlays))
19107 (message "No images to display inline"))))
19109 (defun org-redisplay-inline-images ()
19110 "Refresh the display of inline images."
19111 (interactive)
19112 (if (not org-inline-image-overlays)
19113 (org-toggle-inline-images)
19114 (org-toggle-inline-images)
19115 (org-toggle-inline-images)))
19117 (defun org-display-inline-images (&optional include-linked refresh beg end)
19118 "Display inline images.
19120 An inline image is a link which follows either of these
19121 conventions:
19123 1. Its path is a file with an extension matching return value
19124 from `image-file-name-regexp' and it has no contents.
19126 2. Its description consists in a single link of the previous
19127 type.
19129 When optional argument INCLUDE-LINKED is non-nil, also links with
19130 a text description part will be inlined. This can be nice for
19131 a quick look at those images, but it does not reflect what
19132 exported files will look like.
19134 When optional argument REFRESH is non-nil, refresh existing
19135 images between BEG and END. This will create new image displays
19136 only if necessary. BEG and END default to the buffer
19137 boundaries."
19138 (interactive "P")
19139 (when (display-graphic-p)
19140 (unless refresh
19141 (org-remove-inline-images)
19142 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19143 (org-with-wide-buffer
19144 (goto-char (or beg (point-min)))
19145 (let ((case-fold-search t)
19146 (file-extension-re (org-image-file-name-regexp)))
19147 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19148 (let ((link (save-match-data (org-element-context))))
19149 ;; Check if we're at an inline image.
19150 (when (and (equal (org-element-property :type link) "file")
19151 (or include-linked
19152 (not (org-element-property :contents-begin link)))
19153 (let ((parent (org-element-property :parent link)))
19154 (or (not (eq (org-element-type parent) 'link))
19155 (not (cdr (org-element-contents parent)))))
19156 (org-string-match-p file-extension-re
19157 (org-element-property :path link)))
19158 (let ((file (expand-file-name (org-element-property :path link))))
19159 (when (file-exists-p file)
19160 (let ((width
19161 ;; Apply `org-image-actual-width' specifications.
19162 (cond
19163 ((not (image-type-available-p 'imagemagick)) nil)
19164 ((eq org-image-actual-width t) nil)
19165 ((listp org-image-actual-width)
19167 ;; First try to find a width among
19168 ;; attributes associated to the paragraph
19169 ;; containing link.
19170 (let ((paragraph
19171 (let ((e link))
19172 (while (and (setq e (org-element-property
19173 :parent e))
19174 (not (eq (org-element-type e)
19175 'paragraph))))
19176 e)))
19177 (when paragraph
19178 (save-excursion
19179 (goto-char (org-element-property :begin paragraph))
19180 (when (save-match-data
19181 (re-search-forward
19182 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19183 (org-element-property
19184 :post-affiliated paragraph)
19186 (string-to-number (match-string 1))))))
19187 ;; Otherwise, fall-back to provided number.
19188 (car org-image-actual-width)))
19189 ((numberp org-image-actual-width)
19190 org-image-actual-width)))
19191 (old (get-char-property-and-overlay
19192 (org-element-property :begin link)
19193 'org-image-overlay)))
19194 (if (and (car-safe old) refresh)
19195 (image-refresh (overlay-get (cdr old) 'display))
19196 (let ((image (save-match-data
19197 (create-image file
19198 (and width 'imagemagick)
19200 :width width))))
19201 (when image
19202 (let* ((link
19203 ;; If inline image is the description
19204 ;; of another link, be sure to
19205 ;; consider the latter as the one to
19206 ;; apply the overlay on.
19207 (let ((parent
19208 (org-element-property :parent link)))
19209 (if (eq (org-element-type parent) 'link)
19210 parent
19211 link)))
19212 (ov (make-overlay
19213 (org-element-property :begin link)
19214 (progn
19215 (goto-char
19216 (org-element-property :end link))
19217 (skip-chars-backward " \t")
19218 (point)))))
19219 (overlay-put ov 'display image)
19220 (overlay-put ov 'face 'default)
19221 (overlay-put ov 'org-image-overlay t)
19222 (overlay-put
19223 ov 'modification-hooks
19224 (list 'org-display-inline-remove-overlay))
19225 (push ov org-inline-image-overlays)))))))))))))))
19227 (define-obsolete-function-alias
19228 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19230 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19231 "Remove inline-display overlay if a corresponding region is modified."
19232 (let ((inhibit-modification-hooks t))
19233 (when (and ov after)
19234 (delete ov org-inline-image-overlays)
19235 (delete-overlay ov))))
19237 (defun org-remove-inline-images ()
19238 "Remove inline display of images."
19239 (interactive)
19240 (mapc 'delete-overlay org-inline-image-overlays)
19241 (setq org-inline-image-overlays nil))
19243 ;;;; Key bindings
19245 ;; Outline functions from `outline-mode-prefix-map'
19246 ;; that can be remapped in Org:
19247 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19248 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19249 (define-key org-mode-map [remap outline-forward-same-level]
19250 'org-forward-heading-same-level)
19251 (define-key org-mode-map [remap outline-backward-same-level]
19252 'org-backward-heading-same-level)
19253 (define-key org-mode-map [remap show-branches]
19254 'org-kill-note-or-show-branches)
19255 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19256 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19257 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19259 ;; Outline functions from `outline-mode-prefix-map' that can not
19260 ;; be remapped in Org:
19262 ;; - the column "key binding" shows whether the Outline function is still
19263 ;; available in Org mode on the same key that it has been bound to in
19264 ;; Outline mode:
19265 ;; - "overridden": key used for a different functionality in Org mode
19266 ;; - else: key still bound to the same Outline function in Org mode
19268 ;; | Outline function | key binding | Org replacement |
19269 ;; |------------------------------------+-------------+-----------------------|
19270 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19271 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19272 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19273 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19274 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19275 ;; | `show-entry' | overridden | no replacement |
19276 ;; | `show-children' | `C-c C-i' | visibility cycling |
19277 ;; | `show-branches' | `C-c C-k' | still same function |
19278 ;; | `show-subtree' | overridden | visibility cycling |
19279 ;; | `show-all' | overridden | no replacement |
19280 ;; | `hide-subtree' | overridden | visibility cycling |
19281 ;; | `hide-body' | overridden | no replacement |
19282 ;; | `hide-entry' | overridden | visibility cycling |
19283 ;; | `hide-leaves' | overridden | no replacement |
19284 ;; | `hide-sublevels' | overridden | no replacement |
19285 ;; | `hide-other' | overridden | no replacement |
19287 ;; Make `C-c C-x' a prefix key
19288 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19290 ;; TAB key with modifiers
19291 (org-defkey org-mode-map "\C-i" 'org-cycle)
19292 (org-defkey org-mode-map [(tab)] 'org-cycle)
19293 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19294 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19295 ;; The following line is necessary under Suse GNU/Linux
19296 (unless (featurep 'xemacs)
19297 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19298 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19299 (define-key org-mode-map [backtab] 'org-shifttab)
19301 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19302 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19303 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19305 ;; Cursor keys with modifiers
19306 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19307 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19308 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19309 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19311 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19312 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19313 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19314 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19315 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19316 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19318 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19319 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19320 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19321 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19323 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19324 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19325 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19326 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19328 ;; Babel keys
19329 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19330 (mapc (lambda (pair)
19331 (define-key org-babel-map (car pair) (cdr pair)))
19332 org-babel-key-bindings)
19334 ;;; Extra keys for tty access.
19335 ;; We only set them when really needed because otherwise the
19336 ;; menus don't show the simple keys
19338 (when (or org-use-extra-keys
19339 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19340 (not window-system))
19341 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19342 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19343 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19344 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19345 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19346 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19347 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19348 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19349 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19350 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19351 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19352 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19353 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19354 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19355 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19356 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19357 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19358 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19359 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19360 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19361 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19362 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19363 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19364 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19365 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19366 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19367 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19368 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19370 ;; All the other keys
19372 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19373 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19374 (if (boundp 'narrow-map)
19375 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19376 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19377 (if (boundp 'narrow-map)
19378 (org-defkey narrow-map "b" 'org-narrow-to-block)
19379 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19380 (if (boundp 'narrow-map)
19381 (org-defkey narrow-map "e" 'org-narrow-to-element)
19382 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19383 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19384 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19385 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19386 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19387 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19388 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19389 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19390 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19391 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19392 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19393 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19394 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19395 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19396 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19397 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19398 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19399 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19400 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19401 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19402 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19403 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19404 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19405 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19406 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19407 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19408 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19409 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19410 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19411 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19412 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19413 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19414 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19415 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19416 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19417 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19418 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19419 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19420 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19421 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19422 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19423 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19424 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19425 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19426 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19427 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19428 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19429 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19430 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19431 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19432 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19433 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19434 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19435 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19436 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19437 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19438 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19439 (org-defkey org-mode-map "\C-c^" 'org-sort)
19440 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19441 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19442 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19443 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19444 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19445 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19446 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19447 (org-defkey org-mode-map "\C-m" 'org-return)
19448 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19449 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19450 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19451 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19452 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19453 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19454 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19455 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19456 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19457 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19458 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19459 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19460 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19461 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19462 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19463 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19464 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19465 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19466 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19467 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19468 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19469 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19470 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19472 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19473 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19474 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19476 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19477 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19478 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19479 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19480 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19481 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19482 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19483 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19484 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19485 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19486 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19487 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19488 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19489 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19490 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19491 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19492 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19493 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19494 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19495 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19496 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19497 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19498 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19500 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19501 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19502 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19503 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19504 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19506 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19508 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19510 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19511 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19513 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19516 (when (featurep 'xemacs)
19517 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19520 (defconst org-speed-commands-default
19522 ("Outline Navigation")
19523 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19524 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19525 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19526 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19527 ("F" . org-next-block)
19528 ("B" . org-previous-block)
19529 ("u" . (org-speed-move-safe 'outline-up-heading))
19530 ("j" . org-goto)
19531 ("g" . (org-refile t))
19532 ("Outline Visibility")
19533 ("c" . org-cycle)
19534 ("C" . org-shifttab)
19535 (" " . org-display-outline-path)
19536 ("s" . org-narrow-to-subtree)
19537 ("=" . org-columns)
19538 ("Outline Structure Editing")
19539 ("U" . org-metaup)
19540 ("D" . org-metadown)
19541 ("r" . org-metaright)
19542 ("l" . org-metaleft)
19543 ("R" . org-shiftmetaright)
19544 ("L" . org-shiftmetaleft)
19545 ("i" . (progn (forward-char 1) (call-interactively
19546 'org-insert-heading-respect-content)))
19547 ("^" . org-sort)
19548 ("w" . org-refile)
19549 ("a" . org-archive-subtree-default-with-confirmation)
19550 ("@" . org-mark-subtree)
19551 ("#" . org-toggle-comment)
19552 ("Clock Commands")
19553 ("I" . org-clock-in)
19554 ("O" . org-clock-out)
19555 ("Meta Data Editing")
19556 ("t" . org-todo)
19557 ("," . (org-priority))
19558 ("0" . (org-priority ?\ ))
19559 ("1" . (org-priority ?A))
19560 ("2" . (org-priority ?B))
19561 ("3" . (org-priority ?C))
19562 (":" . org-set-tags-command)
19563 ("e" . org-set-effort)
19564 ("E" . org-inc-effort)
19565 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19566 (org-entry-put (point) "APPT_WARNTIME" m)))
19567 ("Agenda Views etc")
19568 ("v" . org-agenda)
19569 ("/" . org-sparse-tree)
19570 ("Misc")
19571 ("o" . org-open-at-point)
19572 ("?" . org-speed-command-help)
19573 ("<" . (org-agenda-set-restriction-lock 'subtree))
19574 (">" . (org-agenda-remove-restriction-lock))
19576 "The default speed commands.")
19578 (defun org-print-speed-command (e)
19579 (if (> (length (car e)) 1)
19580 (progn
19581 (princ "\n")
19582 (princ (car e))
19583 (princ "\n")
19584 (princ (make-string (length (car e)) ?-))
19585 (princ "\n"))
19586 (princ (car e))
19587 (princ " ")
19588 (if (symbolp (cdr e))
19589 (princ (symbol-name (cdr e)))
19590 (prin1 (cdr e)))
19591 (princ "\n")))
19593 (defun org-speed-command-help ()
19594 "Show the available speed commands."
19595 (interactive)
19596 (if (not org-use-speed-commands)
19597 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19598 (with-output-to-temp-buffer "*Help*"
19599 (princ "User-defined Speed commands\n===========================\n")
19600 (mapc 'org-print-speed-command org-speed-commands-user)
19601 (princ "\n")
19602 (princ "Built-in Speed commands\n=======================\n")
19603 (mapc 'org-print-speed-command org-speed-commands-default))
19604 (with-current-buffer "*Help*"
19605 (setq truncate-lines t))))
19607 (defun org-speed-move-safe (cmd)
19608 "Execute CMD, but make sure that the cursor always ends up in a headline.
19609 If not, return to the original position and throw an error."
19610 (interactive)
19611 (let ((pos (point)))
19612 (call-interactively cmd)
19613 (unless (and (bolp) (org-at-heading-p))
19614 (goto-char pos)
19615 (error "Boundary reached while executing %s" cmd))))
19617 (defvar org-self-insert-command-undo-counter 0)
19619 (defvar org-table-auto-blank-field) ; defined in org-table.el
19620 (defvar org-speed-command nil)
19622 (define-obsolete-function-alias
19623 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19625 (defun org-speed-command-activate (keys)
19626 "Hook for activating single-letter speed commands.
19627 `org-speed-commands-default' specifies a minimal command set.
19628 Use `org-speed-commands-user' for further customization."
19629 (when (or (and (bolp) (looking-at org-outline-regexp))
19630 (and (functionp org-use-speed-commands)
19631 (funcall org-use-speed-commands)))
19632 (cdr (assoc keys (append org-speed-commands-user
19633 org-speed-commands-default)))))
19635 (define-obsolete-function-alias
19636 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19638 (defun org-babel-speed-command-activate (keys)
19639 "Hook for activating single-letter code block commands."
19640 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19641 (cdr (assoc keys org-babel-key-bindings))))
19643 (defcustom org-speed-command-hook
19644 '(org-speed-command-default-hook org-babel-speed-command-hook)
19645 "Hook for activating speed commands at strategic locations.
19646 Hook functions are called in sequence until a valid handler is
19647 found.
19649 Each hook takes a single argument, a user-pressed command key
19650 which is also a `self-insert-command' from the global map.
19652 Within the hook, examine the cursor position and the command key
19653 and return nil or a valid handler as appropriate. Handler could
19654 be one of an interactive command, a function, or a form.
19656 Set `org-use-speed-commands' to non-nil value to enable this
19657 hook. The default setting is `org-speed-command-activate'."
19658 :group 'org-structure
19659 :version "24.1"
19660 :type 'hook)
19662 (defun org-self-insert-command (N)
19663 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19664 If the cursor is in a table looking at whitespace, the whitespace is
19665 overwritten, and the table is not marked as requiring realignment."
19666 (interactive "p")
19667 (org-check-before-invisible-edit 'insert)
19668 (cond
19669 ((and org-use-speed-commands
19670 (setq org-speed-command
19671 (run-hook-with-args-until-success
19672 'org-speed-command-hook (this-command-keys))))
19673 (cond
19674 ((commandp org-speed-command)
19675 (setq this-command org-speed-command)
19676 (call-interactively org-speed-command))
19677 ((functionp org-speed-command)
19678 (funcall org-speed-command))
19679 ((and org-speed-command (listp org-speed-command))
19680 (eval org-speed-command))
19681 (t (let (org-use-speed-commands)
19682 (call-interactively 'org-self-insert-command)))))
19683 ((and
19684 (org-table-p)
19685 (progn
19686 ;; check if we blank the field, and if that triggers align
19687 (and (featurep 'org-table) org-table-auto-blank-field
19688 (member last-command
19689 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19690 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19691 ;; got extra space, this field does not determine column width
19692 (let (org-table-may-need-update) (org-table-blank-field))
19693 ;; no extra space, this field may determine column width
19694 (org-table-blank-field)))
19696 (eq N 1)
19697 (looking-at "[^|\n]* |"))
19698 (let (org-table-may-need-update)
19699 (goto-char (1- (match-end 0)))
19700 (backward-delete-char 1)
19701 (goto-char (match-beginning 0))
19702 (self-insert-command N)))
19704 (setq org-table-may-need-update t)
19705 (self-insert-command N)
19706 (org-fix-tags-on-the-fly)
19707 (if org-self-insert-cluster-for-undo
19708 (if (not (eq last-command 'org-self-insert-command))
19709 (setq org-self-insert-command-undo-counter 1)
19710 (if (>= org-self-insert-command-undo-counter 20)
19711 (setq org-self-insert-command-undo-counter 1)
19712 (and (> org-self-insert-command-undo-counter 0)
19713 buffer-undo-list (listp buffer-undo-list)
19714 (not (cadr buffer-undo-list)) ; remove nil entry
19715 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19716 (setq org-self-insert-command-undo-counter
19717 (1+ org-self-insert-command-undo-counter))))))))
19719 (defun org-check-before-invisible-edit (kind)
19720 "Check is editing if kind KIND would be dangerous with invisible text around.
19721 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19722 ;; First, try to get out of here as quickly as possible, to reduce overhead
19723 (if (and org-catch-invisible-edits
19724 (or (not (boundp 'visible-mode)) (not visible-mode))
19725 (or (get-char-property (point) 'invisible)
19726 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19727 ;; OK, we need to take a closer look
19728 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19729 (invisible-before-point (if (bobp) nil (get-char-property
19730 (1- (point)) 'invisible)))
19731 (border-and-ok-direction
19733 ;; Check if we are acting predictably before invisible text
19734 (and invisible-at-point (not invisible-before-point)
19735 (memq kind '(insert delete-backward)))
19736 ;; Check if we are acting predictably after invisible text
19737 ;; This works not well, and I have turned it off. It seems
19738 ;; better to always show and stop after invisible text.
19739 ;; (and (not invisible-at-point) invisible-before-point
19740 ;; (memq kind '(insert delete)))
19742 (when (or (memq invisible-at-point '(outline org-hide-block t))
19743 (memq invisible-before-point '(outline org-hide-block t)))
19744 (if (eq org-catch-invisible-edits 'error)
19745 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19746 (if (and org-custom-properties-overlays
19747 (y-or-n-p "Display invisible properties in this buffer? "))
19748 (org-toggle-custom-properties-visibility)
19749 ;; Make the area visible
19750 (save-excursion
19751 (if invisible-before-point
19752 (goto-char (previous-single-char-property-change
19753 (point) 'invisible)))
19754 (show-subtree))
19755 (cond
19756 ((eq org-catch-invisible-edits 'show)
19757 ;; That's it, we do the edit after showing
19758 (message
19759 "Unfolding invisible region around point before editing")
19760 (sit-for 1))
19761 ((and (eq org-catch-invisible-edits 'smart)
19762 border-and-ok-direction)
19763 (message "Unfolding invisible region around point before editing"))
19765 ;; Don't do the edit, make the user repeat it in full visibility
19766 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19768 (defun org-fix-tags-on-the-fly ()
19769 (when (and (equal (char-after (point-at-bol)) ?*)
19770 (org-at-heading-p))
19771 (org-align-tags-here org-tags-column)))
19773 (defun org-delete-backward-char (N)
19774 "Like `delete-backward-char', insert whitespace at field end in tables.
19775 When deleting backwards, in tables this function will insert whitespace in
19776 front of the next \"|\" separator, to keep the table aligned. The table will
19777 still be marked for re-alignment if the field did fill the entire column,
19778 because, in this case the deletion might narrow the column."
19779 (interactive "p")
19780 (save-match-data
19781 (org-check-before-invisible-edit 'delete-backward)
19782 (if (and (org-table-p)
19783 (eq N 1)
19784 (string-match "|" (buffer-substring (point-at-bol) (point)))
19785 (looking-at ".*?|"))
19786 (let ((pos (point))
19787 (noalign (looking-at "[^|\n\r]* |"))
19788 (c org-table-may-need-update))
19789 (backward-delete-char N)
19790 (if (not overwrite-mode)
19791 (progn
19792 (skip-chars-forward "^|")
19793 (insert " ")
19794 (goto-char (1- pos))))
19795 ;; noalign: if there were two spaces at the end, this field
19796 ;; does not determine the width of the column.
19797 (if noalign (setq org-table-may-need-update c)))
19798 (backward-delete-char N)
19799 (org-fix-tags-on-the-fly))))
19801 (defun org-delete-char (N)
19802 "Like `delete-char', but insert whitespace at field end in tables.
19803 When deleting characters, in tables this function will insert whitespace in
19804 front of the next \"|\" separator, to keep the table aligned. The table will
19805 still be marked for re-alignment if the field did fill the entire column,
19806 because, in this case the deletion might narrow the column."
19807 (interactive "p")
19808 (save-match-data
19809 (org-check-before-invisible-edit 'delete)
19810 (if (and (org-table-p)
19811 (not (bolp))
19812 (not (= (char-after) ?|))
19813 (eq N 1))
19814 (if (looking-at ".*?|")
19815 (let ((pos (point))
19816 (noalign (looking-at "[^|\n\r]* |"))
19817 (c org-table-may-need-update))
19818 (replace-match
19819 (concat (substring (match-string 0) 1 -1) " |") nil t)
19820 (goto-char pos)
19821 ;; noalign: if there were two spaces at the end, this field
19822 ;; does not determine the width of the column.
19823 (if noalign (setq org-table-may-need-update c)))
19824 (delete-char N))
19825 (delete-char N)
19826 (org-fix-tags-on-the-fly))))
19828 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19829 (put 'org-self-insert-command 'delete-selection
19830 (lambda ()
19831 (not (run-hook-with-args-until-success
19832 'self-insert-uses-region-functions))))
19833 (put 'orgtbl-self-insert-command 'delete-selection
19834 (lambda ()
19835 (not (run-hook-with-args-until-success
19836 'self-insert-uses-region-functions))))
19837 (put 'org-delete-char 'delete-selection 'supersede)
19838 (put 'org-delete-backward-char 'delete-selection 'supersede)
19839 (put 'org-yank 'delete-selection 'yank)
19841 ;; Make `flyspell-mode' delay after some commands
19842 (put 'org-self-insert-command 'flyspell-delayed t)
19843 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19844 (put 'org-delete-char 'flyspell-delayed t)
19845 (put 'org-delete-backward-char 'flyspell-delayed t)
19847 ;; Make pabbrev-mode expand after org-mode commands
19848 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19849 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19851 (defun org-remap (map &rest commands)
19852 "In MAP, remap the functions given in COMMANDS.
19853 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19854 (let (new old)
19855 (while commands
19856 (setq old (pop commands) new (pop commands))
19857 (if (fboundp 'command-remapping)
19858 (org-defkey map (vector 'remap old) new)
19859 (substitute-key-definition old new map global-map)))))
19861 (defun org-transpose-words ()
19862 "Transpose words for Org.
19863 This uses the `org-mode-transpose-word-syntax-table' syntax
19864 table, which interprets characters in `org-emphasis-alist' as
19865 word constituents."
19866 (interactive)
19867 (with-syntax-table org-mode-transpose-word-syntax-table
19868 (call-interactively 'transpose-words)))
19869 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19871 (when (eq org-enable-table-editor 'optimized)
19872 ;; If the user wants maximum table support, we need to hijack
19873 ;; some standard editing functions
19874 (org-remap org-mode-map
19875 'self-insert-command 'org-self-insert-command
19876 'delete-char 'org-delete-char
19877 'delete-backward-char 'org-delete-backward-char)
19878 (org-defkey org-mode-map "|" 'org-force-self-insert))
19880 (defvar org-ctrl-c-ctrl-c-hook nil
19881 "Hook for functions attaching themselves to `C-c C-c'.
19883 This can be used to add additional functionality to the C-c C-c
19884 key which executes context-dependent commands. This hook is run
19885 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19886 run after the last test.
19888 Each function will be called with no arguments. The function
19889 must check if the context is appropriate for it to act. If yes,
19890 it should do its thing and then return a non-nil value. If the
19891 context is wrong, just do nothing and return nil.")
19893 (defvar org-ctrl-c-ctrl-c-final-hook nil
19894 "Hook for functions attaching themselves to `C-c C-c'.
19896 This can be used to add additional functionality to the C-c C-c
19897 key which executes context-dependent commands. This hook is run
19898 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19899 before the first test.
19901 Each function will be called with no arguments. The function
19902 must check if the context is appropriate for it to act. If yes,
19903 it should do its thing and then return a non-nil value. If the
19904 context is wrong, just do nothing and return nil.")
19906 (defvar org-tab-first-hook nil
19907 "Hook for functions to attach themselves to TAB.
19908 See `org-ctrl-c-ctrl-c-hook' for more information.
19909 This hook runs as the first action when TAB is pressed, even before
19910 `org-cycle' messes around with the `outline-regexp' to cater for
19911 inline tasks and plain list item folding.
19912 If any function in this hook returns t, any other actions that
19913 would have been caused by TAB (such as table field motion or visibility
19914 cycling) will not occur.")
19916 (defvar org-tab-after-check-for-table-hook nil
19917 "Hook for functions to attach themselves to TAB.
19918 See `org-ctrl-c-ctrl-c-hook' for more information.
19919 This hook runs after it has been established that the cursor is not in a
19920 table, but before checking if the cursor is in a headline or if global cycling
19921 should be done.
19922 If any function in this hook returns t, not other actions like visibility
19923 cycling will be done.")
19925 (defvar org-tab-after-check-for-cycling-hook nil
19926 "Hook for functions to attach themselves to TAB.
19927 See `org-ctrl-c-ctrl-c-hook' for more information.
19928 This hook runs after it has been established that not table field motion and
19929 not visibility should be done because of current context. This is probably
19930 the place where a package like yasnippets can hook in.")
19932 (defvar org-tab-before-tab-emulation-hook nil
19933 "Hook for functions to attach themselves to TAB.
19934 See `org-ctrl-c-ctrl-c-hook' for more information.
19935 This hook runs after every other options for TAB have been exhausted, but
19936 before indentation and \t insertion takes place.")
19938 (defvar org-metaleft-hook nil
19939 "Hook for functions attaching themselves to `M-left'.
19940 See `org-ctrl-c-ctrl-c-hook' for more information.")
19941 (defvar org-metaright-hook nil
19942 "Hook for functions attaching themselves to `M-right'.
19943 See `org-ctrl-c-ctrl-c-hook' for more information.")
19944 (defvar org-metaup-hook nil
19945 "Hook for functions attaching themselves to `M-up'.
19946 See `org-ctrl-c-ctrl-c-hook' for more information.")
19947 (defvar org-metadown-hook nil
19948 "Hook for functions attaching themselves to `M-down'.
19949 See `org-ctrl-c-ctrl-c-hook' for more information.")
19950 (defvar org-shiftmetaleft-hook nil
19951 "Hook for functions attaching themselves to `M-S-left'.
19952 See `org-ctrl-c-ctrl-c-hook' for more information.")
19953 (defvar org-shiftmetaright-hook nil
19954 "Hook for functions attaching themselves to `M-S-right'.
19955 See `org-ctrl-c-ctrl-c-hook' for more information.")
19956 (defvar org-shiftmetaup-hook nil
19957 "Hook for functions attaching themselves to `M-S-up'.
19958 See `org-ctrl-c-ctrl-c-hook' for more information.")
19959 (defvar org-shiftmetadown-hook nil
19960 "Hook for functions attaching themselves to `M-S-down'.
19961 See `org-ctrl-c-ctrl-c-hook' for more information.")
19962 (defvar org-metareturn-hook nil
19963 "Hook for functions attaching themselves to `M-RET'.
19964 See `org-ctrl-c-ctrl-c-hook' for more information.")
19965 (defvar org-shiftup-hook nil
19966 "Hook for functions attaching themselves to `S-up'.
19967 See `org-ctrl-c-ctrl-c-hook' for more information.")
19968 (defvar org-shiftup-final-hook nil
19969 "Hook for functions attaching themselves to `S-up'.
19970 This one runs after all other options except shift-select have been excluded.
19971 See `org-ctrl-c-ctrl-c-hook' for more information.")
19972 (defvar org-shiftdown-hook nil
19973 "Hook for functions attaching themselves to `S-down'.
19974 See `org-ctrl-c-ctrl-c-hook' for more information.")
19975 (defvar org-shiftdown-final-hook nil
19976 "Hook for functions attaching themselves to `S-down'.
19977 This one runs after all other options except shift-select have been excluded.
19978 See `org-ctrl-c-ctrl-c-hook' for more information.")
19979 (defvar org-shiftleft-hook nil
19980 "Hook for functions attaching themselves to `S-left'.
19981 See `org-ctrl-c-ctrl-c-hook' for more information.")
19982 (defvar org-shiftleft-final-hook nil
19983 "Hook for functions attaching themselves to `S-left'.
19984 This one runs after all other options except shift-select have been excluded.
19985 See `org-ctrl-c-ctrl-c-hook' for more information.")
19986 (defvar org-shiftright-hook nil
19987 "Hook for functions attaching themselves to `S-right'.
19988 See `org-ctrl-c-ctrl-c-hook' for more information.")
19989 (defvar org-shiftright-final-hook nil
19990 "Hook for functions attaching themselves to `S-right'.
19991 This one runs after all other options except shift-select have been excluded.
19992 See `org-ctrl-c-ctrl-c-hook' for more information.")
19994 (defun org-modifier-cursor-error ()
19995 "Throw an error, a modified cursor command was applied in wrong context."
19996 (user-error "This command is active in special context like tables, headlines or items"))
19998 (defun org-shiftselect-error ()
19999 "Throw an error because Shift-Cursor command was applied in wrong context."
20000 (if (and (boundp 'shift-select-mode) shift-select-mode)
20001 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20002 (user-error "This command works only in special context like headlines or timestamps")))
20004 (defun org-call-for-shift-select (cmd)
20005 (let ((this-command-keys-shift-translated t))
20006 (call-interactively cmd)))
20008 (defun org-shifttab (&optional arg)
20009 "Global visibility cycling or move to previous table field.
20010 Call `org-table-previous-field' within a table.
20011 When ARG is nil, cycle globally through visibility states.
20012 When ARG is a numeric prefix, show contents of this level."
20013 (interactive "P")
20014 (cond
20015 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20016 ((integerp arg)
20017 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20018 (message "Content view to level: %d" arg)
20019 (org-content (prefix-numeric-value arg2))
20020 (org-cycle-show-empty-lines t)
20021 (setq org-cycle-global-status 'overview)))
20022 (t (call-interactively 'org-global-cycle))))
20024 (defun org-shiftmetaleft ()
20025 "Promote subtree or delete table column.
20026 Calls `org-promote-subtree', `org-outdent-item-tree', or
20027 `org-table-delete-column', depending on context. See the
20028 individual commands for more information."
20029 (interactive)
20030 (cond
20031 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20032 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20033 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20034 ((if (not (org-region-active-p)) (org-at-item-p)
20035 (save-excursion (goto-char (region-beginning))
20036 (org-at-item-p)))
20037 (call-interactively 'org-outdent-item-tree))
20038 (t (org-modifier-cursor-error))))
20040 (defun org-shiftmetaright ()
20041 "Demote subtree or insert table column.
20042 Calls `org-demote-subtree', `org-indent-item-tree', or
20043 `org-table-insert-column', depending on context. See the
20044 individual commands for more information."
20045 (interactive)
20046 (cond
20047 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20048 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20049 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20050 ((if (not (org-region-active-p)) (org-at-item-p)
20051 (save-excursion (goto-char (region-beginning))
20052 (org-at-item-p)))
20053 (call-interactively 'org-indent-item-tree))
20054 (t (org-modifier-cursor-error))))
20056 (defun org-shiftmetaup (&optional arg)
20057 "Drag the line at point up.
20058 In a table, kill the current row.
20059 On a clock timestamp, update the value of the timestamp like `S-<up>'
20060 but also adjust the previous clocked item in the clock history.
20061 Everywhere else, drag the line at point up."
20062 (interactive "P")
20063 (cond
20064 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20065 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20066 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20067 (call-interactively 'org-timestamp-up)))
20068 (t (call-interactively 'org-drag-line-backward))))
20070 (defun org-shiftmetadown (&optional arg)
20071 "Drag the line at point down.
20072 In a table, insert an empty row at the current line.
20073 On a clock timestamp, update the value of the timestamp like `S-<down>'
20074 but also adjust the previous clocked item in the clock history.
20075 Everywhere else, drag the line at point down."
20076 (interactive "P")
20077 (cond
20078 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20079 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20080 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20081 (call-interactively 'org-timestamp-down)))
20082 (t (call-interactively 'org-drag-line-forward))))
20084 (defsubst org-hidden-tree-error ()
20085 (user-error
20086 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20088 (defun org-metaleft (&optional arg)
20089 "Promote heading or move table column to left.
20090 Calls `org-do-promote' or `org-table-move-column', depending on context.
20091 With no specific context, calls the Emacs default `backward-word'.
20092 See the individual commands for more information."
20093 (interactive "P")
20094 (cond
20095 ((run-hook-with-args-until-success 'org-metaleft-hook))
20096 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20097 ((org-with-limited-levels
20098 (or (org-at-heading-p)
20099 (and (org-region-active-p)
20100 (save-excursion
20101 (goto-char (region-beginning))
20102 (org-at-heading-p)))))
20103 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20104 (call-interactively 'org-do-promote))
20105 ;; At an inline task.
20106 ((org-at-heading-p)
20107 (call-interactively 'org-inlinetask-promote))
20108 ((or (org-at-item-p)
20109 (and (org-region-active-p)
20110 (save-excursion
20111 (goto-char (region-beginning))
20112 (org-at-item-p))))
20113 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20114 (call-interactively 'org-outdent-item))
20115 (t (call-interactively 'backward-word))))
20117 (defun org-metaright (&optional arg)
20118 "Demote a subtree, a list item or move table column to right.
20119 In front of a drawer or a block keyword, indent it correctly.
20120 With no specific context, calls the Emacs default `forward-word'.
20121 See the individual commands for more information."
20122 (interactive "P")
20123 (cond
20124 ((run-hook-with-args-until-success 'org-metaright-hook))
20125 ((org-at-table-p) (call-interactively 'org-table-move-column))
20126 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20127 ((org-at-block-p) (call-interactively 'org-indent-block))
20128 ((org-with-limited-levels
20129 (or (org-at-heading-p)
20130 (and (org-region-active-p)
20131 (save-excursion
20132 (goto-char (region-beginning))
20133 (org-at-heading-p)))))
20134 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20135 (call-interactively 'org-do-demote))
20136 ;; At an inline task.
20137 ((org-at-heading-p)
20138 (call-interactively 'org-inlinetask-demote))
20139 ((or (org-at-item-p)
20140 (and (org-region-active-p)
20141 (save-excursion
20142 (goto-char (region-beginning))
20143 (org-at-item-p))))
20144 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20145 (call-interactively 'org-indent-item))
20146 (t (call-interactively 'forward-word))))
20148 (defun org-check-for-hidden (what)
20149 "Check if there are hidden headlines/items in the current visual line.
20150 WHAT can be either `headlines' or `items'. If the current line is
20151 an outline or item heading and it has a folded subtree below it,
20152 this function returns t, nil otherwise."
20153 (let ((re (cond
20154 ((eq what 'headlines) org-outline-regexp-bol)
20155 ((eq what 'items) (org-item-beginning-re))
20156 (t (error "This should not happen"))))
20157 beg end)
20158 (save-excursion
20159 (catch 'exit
20160 (unless (org-region-active-p)
20161 (setq beg (point-at-bol))
20162 (beginning-of-line 2)
20163 (while (and (not (eobp)) ;; this is like `next-line'
20164 (get-char-property (1- (point)) 'invisible))
20165 (beginning-of-line 2))
20166 (setq end (point))
20167 (goto-char beg)
20168 (goto-char (point-at-eol))
20169 (setq end (max end (point)))
20170 (while (re-search-forward re end t)
20171 (if (get-char-property (match-beginning 0) 'invisible)
20172 (throw 'exit t))))
20173 nil))))
20175 (defun org-metaup (&optional arg)
20176 "Move subtree up or move table row up.
20177 Calls `org-move-subtree-up' or `org-table-move-row' or
20178 `org-move-item-up', depending on context. See the individual commands
20179 for more information."
20180 (interactive "P")
20181 (cond
20182 ((run-hook-with-args-until-success 'org-metaup-hook))
20183 ((org-region-active-p)
20184 (let* ((a (min (region-beginning) (region-end)))
20185 (b (1- (max (region-beginning) (region-end))))
20186 (c (save-excursion (goto-char a)
20187 (move-beginning-of-line 0)))
20188 (d (save-excursion (goto-char a)
20189 (move-end-of-line 0) (point))))
20190 (transpose-regions a b c d)
20191 (goto-char c)))
20192 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20193 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20194 ((org-at-item-p) (call-interactively 'org-move-item-up))
20195 (t (org-drag-element-backward))))
20197 (defun org-metadown (&optional arg)
20198 "Move subtree down or move table row down.
20199 Calls `org-move-subtree-down' or `org-table-move-row' or
20200 `org-move-item-down', depending on context. See the individual
20201 commands for more information."
20202 (interactive "P")
20203 (cond
20204 ((run-hook-with-args-until-success 'org-metadown-hook))
20205 ((org-region-active-p)
20206 (let* ((a (min (region-beginning) (region-end)))
20207 (b (max (region-beginning) (region-end)))
20208 (c (save-excursion (goto-char b)
20209 (move-beginning-of-line 1)))
20210 (d (save-excursion (goto-char b)
20211 (move-end-of-line 1) (1+ (point)))))
20212 (transpose-regions a b c d)
20213 (goto-char d)))
20214 ((org-at-table-p) (call-interactively 'org-table-move-row))
20215 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20216 ((org-at-item-p) (call-interactively 'org-move-item-down))
20217 (t (org-drag-element-forward))))
20219 (defun org-shiftup (&optional arg)
20220 "Increase item in timestamp or increase priority of current headline.
20221 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20222 depending on context. See the individual commands for more information."
20223 (interactive "P")
20224 (cond
20225 ((run-hook-with-args-until-success 'org-shiftup-hook))
20226 ((and org-support-shift-select (org-region-active-p))
20227 (org-call-for-shift-select 'previous-line))
20228 ((org-at-timestamp-p t)
20229 (call-interactively (if org-edit-timestamp-down-means-later
20230 'org-timestamp-down 'org-timestamp-up)))
20231 ((and (not (eq org-support-shift-select 'always))
20232 org-enable-priority-commands
20233 (org-at-heading-p))
20234 (call-interactively 'org-priority-up))
20235 ((and (not org-support-shift-select) (org-at-item-p))
20236 (call-interactively 'org-previous-item))
20237 ((org-clocktable-try-shift 'up arg))
20238 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20239 (org-support-shift-select
20240 (org-call-for-shift-select 'previous-line))
20241 (t (org-shiftselect-error))))
20243 (defun org-shiftdown (&optional arg)
20244 "Decrease item in timestamp or decrease priority of current headline.
20245 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20246 depending on context. See the individual commands for more information."
20247 (interactive "P")
20248 (cond
20249 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20250 ((and org-support-shift-select (org-region-active-p))
20251 (org-call-for-shift-select 'next-line))
20252 ((org-at-timestamp-p t)
20253 (call-interactively (if org-edit-timestamp-down-means-later
20254 'org-timestamp-up 'org-timestamp-down)))
20255 ((and (not (eq org-support-shift-select 'always))
20256 org-enable-priority-commands
20257 (org-at-heading-p))
20258 (call-interactively 'org-priority-down))
20259 ((and (not org-support-shift-select) (org-at-item-p))
20260 (call-interactively 'org-next-item))
20261 ((org-clocktable-try-shift 'down arg))
20262 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20263 (org-support-shift-select
20264 (org-call-for-shift-select 'next-line))
20265 (t (org-shiftselect-error))))
20267 (defun org-shiftright (&optional arg)
20268 "Cycle the thing at point or in the current line, depending on context.
20269 Depending on context, this does one of the following:
20271 - switch a timestamp at point one day into the future
20272 - on a headline, switch to the next TODO keyword.
20273 - on an item, switch entire list to the next bullet type
20274 - on a property line, switch to the next allowed value
20275 - on a clocktable definition line, move time block into the future"
20276 (interactive "P")
20277 (cond
20278 ((run-hook-with-args-until-success 'org-shiftright-hook))
20279 ((and org-support-shift-select (org-region-active-p))
20280 (org-call-for-shift-select 'forward-char))
20281 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20282 ((and (not (eq org-support-shift-select 'always))
20283 (org-at-heading-p))
20284 (let ((org-inhibit-logging
20285 (not org-treat-S-cursor-todo-selection-as-state-change))
20286 (org-inhibit-blocking
20287 (not org-treat-S-cursor-todo-selection-as-state-change)))
20288 (org-call-with-arg 'org-todo 'right)))
20289 ((or (and org-support-shift-select
20290 (not (eq org-support-shift-select 'always))
20291 (org-at-item-bullet-p))
20292 (and (not org-support-shift-select) (org-at-item-p)))
20293 (org-call-with-arg 'org-cycle-list-bullet nil))
20294 ((and (not (eq org-support-shift-select 'always))
20295 (org-at-property-p))
20296 (call-interactively 'org-property-next-allowed-value))
20297 ((org-clocktable-try-shift 'right arg))
20298 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20299 (org-support-shift-select
20300 (org-call-for-shift-select 'forward-char))
20301 (t (org-shiftselect-error))))
20303 (defun org-shiftleft (&optional arg)
20304 "Cycle the thing at point or in the current line, depending on context.
20305 Depending on context, this does one of the following:
20307 - switch a timestamp at point one day into the past
20308 - on a headline, switch to the previous TODO keyword.
20309 - on an item, switch entire list to the previous bullet type
20310 - on a property line, switch to the previous allowed value
20311 - on a clocktable definition line, move time block into the past"
20312 (interactive "P")
20313 (cond
20314 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20315 ((and org-support-shift-select (org-region-active-p))
20316 (org-call-for-shift-select 'backward-char))
20317 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20318 ((and (not (eq org-support-shift-select 'always))
20319 (org-at-heading-p))
20320 (let ((org-inhibit-logging
20321 (not org-treat-S-cursor-todo-selection-as-state-change))
20322 (org-inhibit-blocking
20323 (not org-treat-S-cursor-todo-selection-as-state-change)))
20324 (org-call-with-arg 'org-todo 'left)))
20325 ((or (and org-support-shift-select
20326 (not (eq org-support-shift-select 'always))
20327 (org-at-item-bullet-p))
20328 (and (not org-support-shift-select) (org-at-item-p)))
20329 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20330 ((and (not (eq org-support-shift-select 'always))
20331 (org-at-property-p))
20332 (call-interactively 'org-property-previous-allowed-value))
20333 ((org-clocktable-try-shift 'left arg))
20334 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20335 (org-support-shift-select
20336 (org-call-for-shift-select 'backward-char))
20337 (t (org-shiftselect-error))))
20339 (defun org-shiftcontrolright ()
20340 "Switch to next TODO set."
20341 (interactive)
20342 (cond
20343 ((and org-support-shift-select (org-region-active-p))
20344 (org-call-for-shift-select 'forward-word))
20345 ((and (not (eq org-support-shift-select 'always))
20346 (org-at-heading-p))
20347 (org-call-with-arg 'org-todo 'nextset))
20348 (org-support-shift-select
20349 (org-call-for-shift-select 'forward-word))
20350 (t (org-shiftselect-error))))
20352 (defun org-shiftcontrolleft ()
20353 "Switch to previous TODO set."
20354 (interactive)
20355 (cond
20356 ((and org-support-shift-select (org-region-active-p))
20357 (org-call-for-shift-select 'backward-word))
20358 ((and (not (eq org-support-shift-select 'always))
20359 (org-at-heading-p))
20360 (org-call-with-arg 'org-todo 'previousset))
20361 (org-support-shift-select
20362 (org-call-for-shift-select 'backward-word))
20363 (t (org-shiftselect-error))))
20365 (defun org-shiftcontrolup (&optional n)
20366 "Change timestamps synchronously up in CLOCK log lines.
20367 Optional argument N tells to change by that many units."
20368 (interactive "P")
20369 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20370 (let (org-support-shift-select)
20371 (org-clock-timestamps-up n))
20372 (user-error "Not at a clock log")))
20374 (defun org-shiftcontroldown (&optional n)
20375 "Change timestamps synchronously down in CLOCK log lines.
20376 Optional argument N tells to change by that many units."
20377 (interactive "P")
20378 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20379 (let (org-support-shift-select)
20380 (org-clock-timestamps-down n))
20381 (user-error "Not at a clock log")))
20383 (defun org-increase-number-at-point (&optional inc)
20384 "Increment the number at point.
20385 With an optional prefix numeric argument INC, increment using
20386 this numeric value."
20387 (interactive "p")
20388 (if (not (number-at-point))
20389 (user-error "Not on a number")
20390 (unless inc (setq inc 1))
20391 (let ((pos (point))
20392 (beg (skip-chars-backward "-+^/*0-9eE."))
20393 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20394 (setq nap (buffer-substring-no-properties
20395 (+ pos beg) (+ pos beg end)))
20396 (delete-region (+ pos beg) (+ pos beg end))
20397 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20398 (when (org-at-table-p)
20399 (org-table-align)
20400 (org-table-end-of-field 1))))
20402 (defun org-decrease-number-at-point (&optional inc)
20403 "Decrement the number at point.
20404 With an optional prefix numeric argument INC, decrement using
20405 this numeric value."
20406 (interactive "p")
20407 (org-increase-number-at-point (- inc)))
20409 (defun org-ctrl-c-ret ()
20410 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20411 (interactive)
20412 (cond
20413 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20414 (t (call-interactively 'org-insert-heading))))
20416 (defun org-find-visible ()
20417 (let ((s (point)))
20418 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20419 (get-char-property s 'invisible)))
20421 (defun org-find-invisible ()
20422 (let ((s (point)))
20423 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20424 (not (get-char-property s 'invisible))))
20427 (defun org-copy-visible (beg end)
20428 "Copy the visible parts of the region."
20429 (interactive "r")
20430 (let (snippets s)
20431 (save-excursion
20432 (save-restriction
20433 (narrow-to-region beg end)
20434 (setq s (goto-char (point-min)))
20435 (while (not (= (point) (point-max)))
20436 (goto-char (org-find-invisible))
20437 (push (buffer-substring s (point)) snippets)
20438 (setq s (goto-char (org-find-visible))))))
20439 (kill-new (apply 'concat (nreverse snippets)))))
20441 (defun org-copy-special ()
20442 "Copy region in table or copy current subtree.
20443 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20444 See the individual commands for more information."
20445 (interactive)
20446 (call-interactively
20447 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20449 (defun org-cut-special ()
20450 "Cut region in table or cut current subtree.
20451 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20452 See the individual commands for more information."
20453 (interactive)
20454 (call-interactively
20455 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20457 (defun org-paste-special (arg)
20458 "Paste rectangular region into table, or past subtree relative to level.
20459 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20460 See the individual commands for more information."
20461 (interactive "P")
20462 (if (org-at-table-p)
20463 (org-table-paste-rectangle)
20464 (org-paste-subtree arg)))
20466 (defsubst org-in-fixed-width-region-p ()
20467 "Is point in a fixed-width region?"
20468 (save-match-data
20469 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20471 (defun org-edit-special (&optional arg)
20472 "Call a special editor for the element at point.
20473 When at a table, call the formula editor with `org-table-edit-formulas'.
20474 When in a source code block, call `org-edit-src-code'.
20475 When in a fixed-width region, call `org-edit-fixed-width-region'.
20476 When at an #+INCLUDE keyword, visit the included file.
20477 On a link, call `ffap' to visit the link at point.
20478 Otherwise, return a user error."
20479 (interactive "P")
20480 (let ((element (org-element-at-point)))
20481 (assert (not buffer-read-only) nil
20482 "Buffer is read-only: %s" (buffer-name))
20483 (case (org-element-type element)
20484 (src-block
20485 (if (not arg) (org-edit-src-code)
20486 (let* ((info (org-babel-get-src-block-info))
20487 (lang (nth 0 info))
20488 (params (nth 2 info))
20489 (session (cdr (assq :session params))))
20490 (if (not session) (org-edit-src-code)
20491 ;; At a src-block with a session and function called with
20492 ;; an ARG: switch to the buffer related to the inferior
20493 ;; process.
20494 (switch-to-buffer
20495 (funcall (intern (concat "org-babel-prep-session:" lang))
20496 session params))))))
20497 (keyword
20498 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20499 (find-file-other-window
20500 (org-remove-double-quotes
20501 (car (org-split-string (org-element-property :value element)))))
20502 (user-error "No special environment to edit here")))
20503 (table
20504 (if (eq (org-element-property :type element) 'table.el)
20505 (org-edit-src-code)
20506 (call-interactively 'org-table-edit-formulas)))
20507 ;; Only Org tables contain `table-row' type elements.
20508 (table-row (call-interactively 'org-table-edit-formulas))
20509 ((example-block export-block) (org-edit-src-code))
20510 (fixed-width (org-edit-fixed-width-region))
20511 (otherwise
20512 ;; No notable element at point. Though, we may be at a link,
20513 ;; which is an object. Thus, scan deeper.
20514 (if (eq (org-element-type (org-element-context element)) 'link)
20515 (call-interactively 'ffap)
20516 (user-error "No special environment to edit here"))))))
20518 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20519 (defun org-ctrl-c-ctrl-c (&optional arg)
20520 "Set tags in headline, or update according to changed information at point.
20522 This command does many different things, depending on context:
20524 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20525 this is what we do.
20527 - If the cursor is on a statistics cookie, update it.
20529 - If the cursor is in a headline, prompt for tags and insert them
20530 into the current line, aligned to `org-tags-column'. When called
20531 with prefix arg, realign all tags in the current buffer.
20533 - If the cursor is in one of the special #+KEYWORD lines, this
20534 triggers scanning the buffer for these lines and updating the
20535 information.
20537 - If the cursor is inside a table, realign the table. This command
20538 works even if the automatic table editor has been turned off.
20540 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20541 the entire table.
20543 - If the cursor is at a footnote reference or definition, jump to
20544 the corresponding definition or references, respectively.
20546 - If the cursor is a the beginning of a dynamic block, update it.
20548 - If the current buffer is a capture buffer, close note and file it.
20550 - If the cursor is on a <<<target>>>, update radio targets and
20551 corresponding links in this buffer.
20553 - If the cursor is on a numbered item in a plain list, renumber the
20554 ordered list.
20556 - If the cursor is on a checkbox, toggle it.
20558 - If the cursor is on a code block, evaluate it. The variable
20559 `org-confirm-babel-evaluate' can be used to control prompting
20560 before code block evaluation, by default every code block
20561 evaluation requires confirmation. Code block evaluation can be
20562 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20563 (interactive "P")
20564 (cond
20565 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20566 org-occur-highlights)
20567 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20568 (org-remove-occur-highlights)
20569 (message "Temporary highlights/overlays removed from current buffer"))
20570 ((and (local-variable-p 'org-finish-function (current-buffer))
20571 (fboundp org-finish-function))
20572 (funcall org-finish-function))
20573 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20575 (let* ((context (org-element-context)) (type (org-element-type context)))
20576 ;; Test if point is within a blank line.
20577 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20578 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20579 (user-error "C-c C-c can do nothing useful at this location"))
20580 (case type
20581 ;; When at a link, act according to the parent instead.
20582 (link (setq context (org-element-property :parent context))
20583 (setq type (org-element-type context)))
20584 ;; Unsupported object types: refer to the first supported
20585 ;; element or object containing it.
20586 ((bold code entity export-snippet inline-babel-call inline-src-block
20587 italic latex-fragment line-break macro strike-through subscript
20588 superscript underline verbatim)
20589 (while (and (setq context (org-element-property :parent context))
20590 (not (memq (setq type (org-element-type context))
20591 '(radio-target paragraph verse-block
20592 table-cell)))))))
20593 ;; For convenience: at the first line of a paragraph on the
20594 ;; same line as an item, apply function on that item instead.
20595 (when (eq type 'paragraph)
20596 (let ((parent (org-element-property :parent context)))
20597 (when (and (eq (org-element-type parent) 'item)
20598 (= (point-at-bol) (org-element-property :begin parent)))
20599 (setq context parent type 'item))))
20600 ;; Act according to type of element or object at point.
20601 (case type
20602 (clock (org-clock-update-time-maybe))
20603 (dynamic-block
20604 (save-excursion
20605 (goto-char (org-element-property :post-affiliated context))
20606 (org-update-dblock)))
20607 (footnote-definition
20608 (goto-char (org-element-property :post-affiliated context))
20609 (call-interactively 'org-footnote-action))
20610 (footnote-reference (call-interactively 'org-footnote-action))
20611 ((headline inlinetask)
20612 (save-excursion (goto-char (org-element-property :begin context))
20613 (call-interactively 'org-set-tags)))
20614 (item
20615 ;; At an item: a double C-u set checkbox to "[-]"
20616 ;; unconditionally, whereas a single one will toggle its
20617 ;; presence. Without an universal argument, if the item
20618 ;; has a checkbox, toggle it. Otherwise repair the list.
20619 (let* ((box (org-element-property :checkbox context))
20620 (struct (org-element-property :structure context))
20621 (old-struct (copy-tree struct))
20622 (parents (org-list-parents-alist struct))
20623 (prevs (org-list-prevs-alist struct))
20624 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20625 (org-list-set-checkbox
20626 (org-element-property :begin context) struct
20627 (cond ((equal arg '(16)) "[-]")
20628 ((and (not box) (equal arg '(4))) "[ ]")
20629 ((or (not box) (equal arg '(4))) nil)
20630 ((eq box 'on) "[ ]")
20631 (t "[X]")))
20632 ;; Mimic `org-list-write-struct' but with grabbing
20633 ;; a return value from `org-list-struct-fix-box'.
20634 (org-list-struct-fix-ind struct parents 2)
20635 (org-list-struct-fix-item-end struct)
20636 (org-list-struct-fix-bul struct prevs)
20637 (org-list-struct-fix-ind struct parents)
20638 (let ((block-item
20639 (org-list-struct-fix-box struct parents prevs orderedp)))
20640 (if (and box (equal struct old-struct))
20641 (if (equal arg '(16))
20642 (message "Checkboxes already reset")
20643 (user-error "Cannot toggle this checkbox: %s"
20644 (if (eq box 'on)
20645 "all subitems checked"
20646 "unchecked subitems")))
20647 (org-list-struct-apply-struct struct old-struct)
20648 (org-update-checkbox-count-maybe))
20649 (when block-item
20650 (message "Checkboxes were removed due to empty box at line %d"
20651 (org-current-line block-item))))))
20652 (keyword
20653 (let ((org-inhibit-startup-visibility-stuff t)
20654 (org-startup-align-all-tables nil))
20655 (when (boundp 'org-table-coordinate-overlays)
20656 (mapc 'delete-overlay org-table-coordinate-overlays)
20657 (setq org-table-coordinate-overlays nil))
20658 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20659 (message "Local setup has been refreshed"))
20660 (plain-list
20661 ;; At a plain list, with a double C-u argument, set
20662 ;; checkboxes of each item to "[-]", whereas a single one
20663 ;; will toggle their presence according to the state of the
20664 ;; first item in the list. Without an argument, repair the
20665 ;; list.
20666 (let* ((begin (org-element-property :contents-begin context))
20667 (beginm (move-marker (make-marker) begin))
20668 (struct (org-element-property :structure context))
20669 (old-struct (copy-tree struct))
20670 (first-box (save-excursion
20671 (goto-char begin)
20672 (looking-at org-list-full-item-re)
20673 (match-string-no-properties 3)))
20674 (new-box (cond ((equal arg '(16)) "[-]")
20675 ((equal arg '(4)) (unless first-box "[ ]"))
20676 ((equal first-box "[X]") "[ ]")
20677 (t "[X]"))))
20678 (cond
20679 (arg
20680 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20681 (org-list-get-all-items
20682 begin struct (org-list-prevs-alist struct))))
20683 ((and first-box (eq (point) begin))
20684 ;; For convenience, when point is at bol on the first
20685 ;; item of the list and no argument is provided, simply
20686 ;; toggle checkbox of that item, if any.
20687 (org-list-set-checkbox begin struct new-box)))
20688 (org-list-write-struct
20689 struct (org-list-parents-alist struct) old-struct)
20690 (org-update-checkbox-count-maybe)
20691 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20692 ((property-drawer node-property)
20693 (call-interactively 'org-property-action))
20694 ((radio-target target)
20695 (call-interactively 'org-update-radio-target-regexp))
20696 (statistics-cookie
20697 (call-interactively 'org-update-statistics-cookies))
20698 ((table table-cell table-row)
20699 ;; At a table, recalculate every field and align it. Also
20700 ;; send the table if necessary. If the table has
20701 ;; a `table.el' type, just give up. At a table row or
20702 ;; cell, maybe recalculate line but always align table.
20703 (if (eq (org-element-property :type context) 'table.el)
20704 (message "Use C-c ' to edit table.el tables")
20705 (let ((org-enable-table-editor t))
20706 (if (or (eq type 'table)
20707 ;; Check if point is at a TBLFM line.
20708 (and (eq type 'table-row)
20709 (= (point) (org-element-property :end context))))
20710 (save-excursion
20711 (if (org-at-TBLFM-p)
20712 (progn (require 'org-table)
20713 (org-table-calc-current-TBLFM))
20714 (goto-char (org-element-property :contents-begin context))
20715 (org-call-with-arg 'org-table-recalculate (or arg t))
20716 (orgtbl-send-table 'maybe)))
20717 (org-table-maybe-eval-formula)
20718 (cond (arg (call-interactively 'org-table-recalculate))
20719 ((org-table-maybe-recalculate-line))
20720 (t (org-table-align)))))))
20721 (timestamp (org-timestamp-change 0 'day))
20722 (otherwise
20723 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20724 (user-error
20725 "C-c C-c can do nothing useful at this location")))))))))
20727 (defun org-mode-restart ()
20728 (interactive)
20729 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20730 (funcall major-mode)
20731 (hack-local-variables)
20732 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20733 (org-indent-mode -1)))
20734 (message "%s restarted" major-mode))
20736 (defun org-kill-note-or-show-branches ()
20737 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20738 (interactive)
20739 (if (not org-finish-function)
20740 (progn
20741 (hide-subtree)
20742 (call-interactively 'show-branches))
20743 (let ((org-note-abort t))
20744 (funcall org-finish-function))))
20746 (defun org-open-line (n)
20747 "Insert a new row in tables, call `open-line' elsewhere.
20748 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20749 (interactive "*p")
20750 (cond
20751 ((not org-special-ctrl-o)
20752 (open-line n))
20753 ((org-at-table-p)
20754 (org-table-insert-row))
20756 (open-line n))))
20758 (defun org-return (&optional indent)
20759 "Goto next table row or insert a newline.
20760 Calls `org-table-next-row' or `newline', depending on context.
20761 See the individual commands for more information."
20762 (interactive)
20763 (let (org-ts-what)
20764 (cond
20765 ((or (bobp) (org-in-src-block-p))
20766 (if indent (newline-and-indent) (newline)))
20767 ((org-at-table-p)
20768 (org-table-justify-field-maybe)
20769 (call-interactively 'org-table-next-row))
20770 ;; when `newline-and-indent' is called within a list, make sure
20771 ;; text moved stays inside the item.
20772 ((and (org-in-item-p) indent)
20773 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20774 (progn
20775 (save-match-data (newline))
20776 (org-indent-line-to (length (match-string 0))))
20777 (let ((ind (org-get-indentation)))
20778 (newline)
20779 (if (org-looking-back org-list-end-re)
20780 (org-indent-line)
20781 (org-indent-line-to ind)))))
20782 ((and org-return-follows-link
20783 (org-at-timestamp-p t)
20784 (not (eq org-ts-what 'after)))
20785 (org-follow-timestamp-link))
20786 ((and org-return-follows-link
20787 (let ((tprop (get-text-property (point) 'face)))
20788 (or (eq tprop 'org-link)
20789 (and (listp tprop) (memq 'org-link tprop)))))
20790 (call-interactively 'org-open-at-point))
20791 ((and (org-at-heading-p)
20792 (looking-at
20793 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20794 (org-show-entry)
20795 (end-of-line 1)
20796 (newline))
20797 (t (if indent (newline-and-indent) (newline))))))
20799 (defun org-return-indent ()
20800 "Goto next table row or insert a newline and indent.
20801 Calls `org-table-next-row' or `newline-and-indent', depending on
20802 context. See the individual commands for more information."
20803 (interactive)
20804 (org-return t))
20806 (defun org-ctrl-c-star ()
20807 "Compute table, or change heading status of lines.
20808 Calls `org-table-recalculate' or `org-toggle-heading',
20809 depending on context."
20810 (interactive)
20811 (cond
20812 ((org-at-table-p)
20813 (call-interactively 'org-table-recalculate))
20815 ;; Convert all lines in region to list items
20816 (call-interactively 'org-toggle-heading))))
20818 (defun org-ctrl-c-minus ()
20819 "Insert separator line in table or modify bullet status of line.
20820 Also turns a plain line or a region of lines into list items.
20821 Calls `org-table-insert-hline', `org-toggle-item', or
20822 `org-cycle-list-bullet', depending on context."
20823 (interactive)
20824 (cond
20825 ((org-at-table-p)
20826 (call-interactively 'org-table-insert-hline))
20827 ((org-region-active-p)
20828 (call-interactively 'org-toggle-item))
20829 ((org-in-item-p)
20830 (call-interactively 'org-cycle-list-bullet))
20832 (call-interactively 'org-toggle-item))))
20834 (defun org-toggle-item (arg)
20835 "Convert headings or normal lines to items, items to normal lines.
20836 If there is no active region, only the current line is considered.
20838 If the first non blank line in the region is a headline, convert
20839 all headlines to items, shifting text accordingly.
20841 If it is an item, convert all items to normal lines.
20843 If it is normal text, change region into a list of items.
20844 With a prefix argument ARG, change the region in a single item."
20845 (interactive "P")
20846 (let ((shift-text
20847 (function
20848 ;; Shift text in current section to IND, from point to END.
20849 ;; The function leaves point to END line.
20850 (lambda (ind end)
20851 (let ((min-i 1000) (end (copy-marker end)))
20852 ;; First determine the minimum indentation (MIN-I) of
20853 ;; the text.
20854 (save-excursion
20855 (catch 'exit
20856 (while (< (point) end)
20857 (let ((i (org-get-indentation)))
20858 (cond
20859 ;; Skip blank lines and inline tasks.
20860 ((looking-at "^[ \t]*$"))
20861 ((looking-at org-outline-regexp-bol))
20862 ;; We can't find less than 0 indentation.
20863 ((zerop i) (throw 'exit (setq min-i 0)))
20864 ((< i min-i) (setq min-i i))))
20865 (forward-line))))
20866 ;; Then indent each line so that a line indented to
20867 ;; MIN-I becomes indented to IND. Ignore blank lines
20868 ;; and inline tasks in the process.
20869 (let ((delta (- ind min-i)))
20870 (while (< (point) end)
20871 (unless (or (looking-at "^[ \t]*$")
20872 (looking-at org-outline-regexp-bol))
20873 (org-indent-line-to (+ (org-get-indentation) delta)))
20874 (forward-line)))))))
20875 (skip-blanks
20876 (function
20877 ;; Return beginning of first non-blank line, starting from
20878 ;; line at POS.
20879 (lambda (pos)
20880 (save-excursion
20881 (goto-char pos)
20882 (skip-chars-forward " \r\t\n")
20883 (point-at-bol)))))
20884 beg end)
20885 ;; Determine boundaries of changes.
20886 (if (org-region-active-p)
20887 (setq beg (funcall skip-blanks (region-beginning))
20888 end (copy-marker (region-end)))
20889 (setq beg (funcall skip-blanks (point-at-bol))
20890 end (copy-marker (point-at-eol))))
20891 ;; Depending on the starting line, choose an action on the text
20892 ;; between BEG and END.
20893 (org-with-limited-levels
20894 (save-excursion
20895 (goto-char beg)
20896 (cond
20897 ;; Case 1. Start at an item: de-itemize. Note that it only
20898 ;; happens when a region is active: `org-ctrl-c-minus'
20899 ;; would call `org-cycle-list-bullet' otherwise.
20900 ((org-at-item-p)
20901 (while (< (point) end)
20902 (when (org-at-item-p)
20903 (skip-chars-forward " \t")
20904 (delete-region (point) (match-end 0)))
20905 (forward-line)))
20906 ;; Case 2. Start at an heading: convert to items.
20907 ((org-at-heading-p)
20908 (let* ((bul (org-list-bullet-string "-"))
20909 (bul-len (length bul))
20910 (done (org-entry-is-done-p))
20911 (todo (org-entry-is-todo-p))
20912 ;; Indentation of the first heading. It should be
20913 ;; relative to the indentation of its parent, if any.
20914 (start-ind (save-excursion
20915 (cond
20916 ((not org-adapt-indentation) 0)
20917 ((not (outline-previous-heading)) 0)
20918 (t (length (match-string 0))))))
20919 ;; Level of first heading. Further headings will be
20920 ;; compared to it to determine hierarchy in the list.
20921 (ref-level (org-reduced-level (org-outline-level))))
20922 (when (or done todo) (org-todo ""))
20923 (while (< (point) end)
20924 (let* ((level (org-reduced-level (org-outline-level)))
20925 (delta (max 0 (- level ref-level))))
20926 ;; If current headline is less indented than the first
20927 ;; one, set it as reference, in order to preserve
20928 ;; subtrees.
20929 (when (< level ref-level) (setq ref-level level))
20930 (replace-match bul t t)
20931 (org-indent-line-to (+ start-ind (* delta bul-len)))
20932 (when (or done todo)
20933 (let* ((struct (org-list-struct))
20934 (old (copy-tree struct)))
20935 (org-list-set-checkbox (line-beginning-position)
20936 struct
20937 (if done "[X]" "[ ]"))
20938 (org-list-write-struct struct
20939 (org-list-parents-alist struct)
20940 old)))
20941 ;; Ensure all text down to END (or SECTION-END) belongs
20942 ;; to the newly created item.
20943 (let ((section-end (save-excursion
20944 (or (outline-next-heading) (point)))))
20945 (forward-line)
20946 (funcall shift-text
20947 (+ start-ind (* (1+ delta) bul-len))
20948 (min end section-end)))))))
20949 ;; Case 3. Normal line with ARG: make the first line of region
20950 ;; an item, and shift indentation of others lines to
20951 ;; set them as item's body.
20952 (arg (let* ((bul (org-list-bullet-string "-"))
20953 (bul-len (length bul))
20954 (ref-ind (org-get-indentation)))
20955 (skip-chars-forward " \t")
20956 (insert bul)
20957 (forward-line)
20958 (while (< (point) end)
20959 ;; Ensure that lines less indented than first one
20960 ;; still get included in item body.
20961 (funcall shift-text
20962 (+ ref-ind bul-len)
20963 (min end (save-excursion (or (outline-next-heading)
20964 (point)))))
20965 (forward-line))))
20966 ;; Case 4. Normal line without ARG: turn each non-item line
20967 ;; into an item.
20969 (while (< (point) end)
20970 (unless (or (org-at-heading-p) (org-at-item-p))
20971 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20972 (replace-match
20973 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20974 (forward-line))))))))
20976 (defun org-toggle-heading (&optional nstars)
20977 "Convert headings to normal text, or items or text to headings.
20978 If there is no active region, only convert the current line.
20980 With a \\[universal-argument] prefix, convert the whole list at
20981 point into heading.
20983 In a region:
20985 - If the first non blank line is a headline, remove the stars
20986 from all headlines in the region.
20988 - If it is a normal line, turn each and every normal line (i.e.,
20989 not an heading or an item) in the region into headings. If you
20990 want to convert only the first line of this region, use one
20991 universal prefix argument.
20993 - If it is a plain list item, turn all plain list items into headings.
20995 When converting a line into a heading, the number of stars is chosen
20996 such that the lines become children of the current entry. However,
20997 when a numeric prefix argument is given, its value determines the
20998 number of stars to add."
20999 (interactive "P")
21000 (let ((skip-blanks
21001 (function
21002 ;; Return beginning of first non-blank line, starting from
21003 ;; line at POS.
21004 (lambda (pos)
21005 (save-excursion
21006 (goto-char pos)
21007 (while (org-at-comment-p) (forward-line))
21008 (skip-chars-forward " \r\t\n")
21009 (point-at-bol)))))
21010 beg end toggled)
21011 ;; Determine boundaries of changes. If a universal prefix has
21012 ;; been given, put the list in a region. If region ends at a bol,
21013 ;; do not consider the last line to be in the region.
21015 (when (and current-prefix-arg (org-at-item-p))
21016 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21017 (org-mark-element))
21019 (if (org-region-active-p)
21020 (setq beg (funcall skip-blanks (region-beginning))
21021 end (copy-marker (save-excursion
21022 (goto-char (region-end))
21023 (if (bolp) (point) (point-at-eol)))))
21024 (setq beg (funcall skip-blanks (point-at-bol))
21025 end (copy-marker (point-at-eol))))
21026 ;; Ensure inline tasks don't count as headings.
21027 (org-with-limited-levels
21028 (save-excursion
21029 (goto-char beg)
21030 (cond
21031 ;; Case 1. Started at an heading: de-star headings.
21032 ((org-at-heading-p)
21033 (while (< (point) end)
21034 (when (org-at-heading-p t)
21035 (looking-at org-outline-regexp) (replace-match "")
21036 (setq toggled t))
21037 (forward-line)))
21038 ;; Case 2. Started at an item: change items into headlines.
21039 ;; One star will be added by `org-list-to-subtree'.
21040 ((org-at-item-p)
21041 (let* ((stars (make-string
21042 ;; subtract the star that will be added again by
21043 ;; `org-list-to-subtree'
21044 (if (numberp nstars) (1- nstars)
21045 (or (org-current-level) 0))
21046 ?*))
21047 (add-stars
21048 (cond (nstars "") ; stars from prefix only
21049 ((equal stars "") "") ; before first heading
21050 (org-odd-levels-only "*") ; inside heading, odd
21051 (t "")))) ; inside heading, oddeven
21052 (while (< (point) end)
21053 (when (org-at-item-p)
21054 ;; Pay attention to cases when region ends before list.
21055 (let* ((struct (org-list-struct))
21056 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21057 (save-restriction
21058 (narrow-to-region (point) list-end)
21059 (insert
21060 (org-list-to-subtree
21061 (org-list-parse-list t)
21062 '(:istart (concat stars add-stars (funcall get-stars depth))
21063 :icount (concat stars add-stars (funcall get-stars depth)))))))
21064 (setq toggled t))
21065 (forward-line))))
21066 ;; Case 3. Started at normal text: make every line an heading,
21067 ;; skipping headlines and items.
21068 (t (let* ((stars
21069 (make-string
21070 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21071 (add-stars
21072 (cond (nstars "") ; stars from prefix only
21073 ((equal stars "") "*") ; before first heading
21074 (org-odd-levels-only "**") ; inside heading, odd
21075 (t "*"))) ; inside heading, oddeven
21076 (rpl (concat stars add-stars " "))
21077 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21078 (while (< (point) (if (equal nstars '(4)) lend end))
21079 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21080 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21081 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21082 (forward-line)))))))
21083 (unless toggled (message "Cannot toggle heading from here"))))
21085 (defun org-meta-return (&optional arg)
21086 "Insert a new heading or wrap a region in a table.
21087 Calls `org-insert-heading' or `org-table-wrap-region', depending
21088 on context. See the individual commands for more information."
21089 (interactive "P")
21090 (org-check-before-invisible-edit 'insert)
21091 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21092 (let* ((element (org-element-at-point))
21093 (type (org-element-type element)))
21094 (when (eq type 'table-row)
21095 (setq element (org-element-property :parent element))
21096 (setq type 'table))
21097 (if (and (eq type 'table)
21098 (eq (org-element-property :type element) 'org)
21099 (>= (point) (org-element-property :contents-begin element))
21100 (< (point) (org-element-property :contents-end element)))
21101 (call-interactively 'org-table-wrap-region)
21102 (call-interactively 'org-insert-heading)))))
21104 ;;; Menu entries
21106 (defsubst org-in-subtree-not-table-p ()
21107 "Are we in a subtree and not in a table?"
21108 (and (not (org-before-first-heading-p))
21109 (not (org-at-table-p))))
21111 ;; Define the Org-mode menus
21112 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21113 '("Tbl"
21114 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21115 ["Next Field" org-cycle (org-at-table-p)]
21116 ["Previous Field" org-shifttab (org-at-table-p)]
21117 ["Next Row" org-return (org-at-table-p)]
21118 "--"
21119 ["Blank Field" org-table-blank-field (org-at-table-p)]
21120 ["Edit Field" org-table-edit-field (org-at-table-p)]
21121 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21122 "--"
21123 ("Column"
21124 ["Move Column Left" org-metaleft (org-at-table-p)]
21125 ["Move Column Right" org-metaright (org-at-table-p)]
21126 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21127 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21128 ("Row"
21129 ["Move Row Up" org-metaup (org-at-table-p)]
21130 ["Move Row Down" org-metadown (org-at-table-p)]
21131 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21132 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21133 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21134 "--"
21135 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21136 ("Rectangle"
21137 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21138 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21139 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21140 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21141 "--"
21142 ("Calculate"
21143 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21144 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21145 ["Edit Formulas" org-edit-special (org-at-table-p)]
21146 "--"
21147 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21148 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21149 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21150 "--"
21151 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21152 "--"
21153 ["Sum Column/Rectangle" org-table-sum
21154 (or (org-at-table-p) (org-region-active-p))]
21155 ["Which Column?" org-table-current-column (org-at-table-p)])
21156 ["Debug Formulas"
21157 org-table-toggle-formula-debugger
21158 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21159 ["Show Col/Row Numbers"
21160 org-table-toggle-coordinate-overlays
21161 :style toggle
21162 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21163 "--"
21164 ["Create" org-table-create (and (not (org-at-table-p))
21165 org-enable-table-editor)]
21166 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21167 ["Import from File" org-table-import (not (org-at-table-p))]
21168 ["Export to File" org-table-export (org-at-table-p)]
21169 "--"
21170 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21172 (easy-menu-define org-org-menu org-mode-map "Org menu"
21173 '("Org"
21174 ("Show/Hide"
21175 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21176 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21177 ["Sparse Tree..." org-sparse-tree t]
21178 ["Reveal Context" org-reveal t]
21179 ["Show All" show-all t]
21180 "--"
21181 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21182 "--"
21183 ["New Heading" org-insert-heading t]
21184 ("Navigate Headings"
21185 ["Up" outline-up-heading t]
21186 ["Next" outline-next-visible-heading t]
21187 ["Previous" outline-previous-visible-heading t]
21188 ["Next Same Level" outline-forward-same-level t]
21189 ["Previous Same Level" outline-backward-same-level t]
21190 "--"
21191 ["Jump" org-goto t])
21192 ("Edit Structure"
21193 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21194 "--"
21195 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21196 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21197 "--"
21198 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21199 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21200 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21201 "--"
21202 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21203 "--"
21204 ["Copy visible text" org-copy-visible t]
21205 "--"
21206 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21207 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21208 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21209 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21210 "--"
21211 ["Sort Region/Children" org-sort t]
21212 "--"
21213 ["Convert to odd levels" org-convert-to-odd-levels t]
21214 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21215 ("Editing"
21216 ["Emphasis..." org-emphasize t]
21217 ["Edit Source Example" org-edit-special t]
21218 "--"
21219 ["Footnote new/jump" org-footnote-action t]
21220 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21221 ("Archive"
21222 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21223 "--"
21224 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21225 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21226 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21228 "--"
21229 ("Hyperlinks"
21230 ["Store Link (Global)" org-store-link t]
21231 ["Find existing link to here" org-occur-link-in-agenda-files t]
21232 ["Insert Link" org-insert-link t]
21233 ["Follow Link" org-open-at-point t]
21234 "--"
21235 ["Next link" org-next-link t]
21236 ["Previous link" org-previous-link t]
21237 "--"
21238 ["Descriptive Links"
21239 org-toggle-link-display
21240 :style radio
21241 :selected org-descriptive-links
21243 ["Literal Links"
21244 org-toggle-link-display
21245 :style radio
21246 :selected (not org-descriptive-links)])
21247 "--"
21248 ("TODO Lists"
21249 ["TODO/DONE/-" org-todo t]
21250 ("Select keyword"
21251 ["Next keyword" org-shiftright (org-at-heading-p)]
21252 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21253 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21254 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21255 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21256 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21257 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21258 "--"
21259 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21260 :selected org-enforce-todo-dependencies :style toggle :active t]
21261 "Settings for tree at point"
21262 ["Do Children sequentially" org-toggle-ordered-property :style radio
21263 :selected (org-entry-get nil "ORDERED")
21264 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21265 ["Do Children parallel" org-toggle-ordered-property :style radio
21266 :selected (not (org-entry-get nil "ORDERED"))
21267 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21268 "--"
21269 ["Set Priority" org-priority t]
21270 ["Priority Up" org-shiftup t]
21271 ["Priority Down" org-shiftdown t]
21272 "--"
21273 ["Get news from all feeds" org-feed-update-all t]
21274 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21275 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21276 ("TAGS and Properties"
21277 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21278 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21279 "--"
21280 ["Set property" org-set-property (not (org-before-first-heading-p))]
21281 ["Column view of properties" org-columns t]
21282 ["Insert Column View DBlock" org-insert-columns-dblock t])
21283 ("Dates and Scheduling"
21284 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21285 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21286 ("Change Date"
21287 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21288 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21289 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21290 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21291 ["Compute Time Range" org-evaluate-time-range t]
21292 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21293 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21294 "--"
21295 ["Custom time format" org-toggle-time-stamp-overlays
21296 :style radio :selected org-display-custom-times]
21297 "--"
21298 ["Goto Calendar" org-goto-calendar t]
21299 ["Date from Calendar" org-date-from-calendar t]
21300 "--"
21301 ["Start/Restart Timer" org-timer-start t]
21302 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21303 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21304 ["Insert Timer String" org-timer t]
21305 ["Insert Timer Item" org-timer-item t])
21306 ("Logging work"
21307 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21308 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21309 ["Clock out" org-clock-out t]
21310 ["Clock cancel" org-clock-cancel t]
21311 "--"
21312 ["Mark as default task" org-clock-mark-default-task t]
21313 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21314 ["Goto running clock" org-clock-goto t]
21315 "--"
21316 ["Display times" org-clock-display t]
21317 ["Create clock table" org-clock-report t]
21318 "--"
21319 ["Record DONE time"
21320 (progn (setq org-log-done (not org-log-done))
21321 (message "Switching to %s will %s record a timestamp"
21322 (car org-done-keywords)
21323 (if org-log-done "automatically" "not")))
21324 :style toggle :selected org-log-done])
21325 "--"
21326 ["Agenda Command..." org-agenda t]
21327 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21328 ("File List for Agenda")
21329 ("Special views current file"
21330 ["TODO Tree" org-show-todo-tree t]
21331 ["Check Deadlines" org-check-deadlines t]
21332 ["Timeline" org-timeline t]
21333 ["Tags/Property tree" org-match-sparse-tree t])
21334 "--"
21335 ["Export/Publish..." org-export-dispatch t]
21336 ("LaTeX"
21337 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21338 :selected org-cdlatex-mode]
21339 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21340 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21341 ["Modify math symbol" org-cdlatex-math-modify
21342 (org-inside-LaTeX-fragment-p)]
21343 ["Insert citation" org-reftex-citation t]
21344 "--"
21345 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21346 "--"
21347 ("MobileOrg"
21348 ["Push Files and Views" org-mobile-push t]
21349 ["Get Captured and Flagged" org-mobile-pull t]
21350 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21351 "--"
21352 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21353 "--"
21354 ("Documentation"
21355 ["Show Version" org-version t]
21356 ["Info Documentation" org-info t])
21357 ("Customize"
21358 ["Browse Org Group" org-customize t]
21359 "--"
21360 ["Expand This Menu" org-create-customize-menu
21361 (fboundp 'customize-menu-create)])
21362 ["Send bug report" org-submit-bug-report t]
21363 "--"
21364 ("Refresh/Reload"
21365 ["Refresh setup current buffer" org-mode-restart t]
21366 ["Reload Org (after update)" org-reload t]
21367 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21370 (defun org-info (&optional node)
21371 "Read documentation for Org-mode in the info system.
21372 With optional NODE, go directly to that node."
21373 (interactive)
21374 (info (format "(org)%s" (or node ""))))
21376 ;;;###autoload
21377 (defun org-submit-bug-report ()
21378 "Submit a bug report on Org-mode via mail.
21380 Don't hesitate to report any problems or inaccurate documentation.
21382 If you don't have setup sending mail from (X)Emacs, please copy the
21383 output buffer into your mail program, as it gives us important
21384 information about your Org-mode version and configuration."
21385 (interactive)
21386 (require 'reporter)
21387 (org-load-modules-maybe)
21388 (org-require-autoloaded-modules)
21389 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21390 (reporter-submit-bug-report
21391 "emacs-orgmode@gnu.org"
21392 (org-version nil 'full)
21393 (let (list)
21394 (save-window-excursion
21395 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21396 (delete-other-windows)
21397 (erase-buffer)
21398 (insert "You are about to submit a bug report to the Org-mode mailing list.
21400 We would like to add your full Org-mode and Outline configuration to the
21401 bug report. This greatly simplifies the work of the maintainer and
21402 other experts on the mailing list.
21404 HOWEVER, some variables you have customized may contain private
21405 information. The names of customers, colleagues, or friends, might
21406 appear in the form of file names, tags, todo states, or search strings.
21407 If you answer yes to the prompt, you might want to check and remove
21408 such private information before sending the email.")
21409 (add-text-properties (point-min) (point-max) '(face org-warning))
21410 (when (yes-or-no-p "Include your Org-mode configuration ")
21411 (mapatoms
21412 (lambda (v)
21413 (and (boundp v)
21414 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21415 (or (and (symbol-value v)
21416 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21417 (and
21418 (get v 'custom-type) (get v 'standard-value)
21419 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21420 (push v list)))))
21421 (kill-buffer (get-buffer "*Warn about privacy*"))
21422 list))
21423 nil nil
21424 "Remember to cover the basics, that is, what you expected to happen and
21425 what in fact did happen. You don't know how to make a good report? See
21427 http://orgmode.org/manual/Feedback.html#Feedback
21429 Your bug report will be posted to the Org-mode mailing list.
21430 ------------------------------------------------------------------------")
21431 (save-excursion
21432 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21433 (replace-match "\\1Bug: \\3 [\\2]")))))
21436 (defun org-install-agenda-files-menu ()
21437 (let ((bl (buffer-list)))
21438 (save-excursion
21439 (while bl
21440 (set-buffer (pop bl))
21441 (if (derived-mode-p 'org-mode) (setq bl nil)))
21442 (when (derived-mode-p 'org-mode)
21443 (easy-menu-change
21444 '("Org") "File List for Agenda"
21445 (append
21446 (list
21447 ["Edit File List" (org-edit-agenda-file-list) t]
21448 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21449 ["Remove Current File from List" org-remove-file t]
21450 ["Cycle through agenda files" org-cycle-agenda-files t]
21451 ["Occur in all agenda files" org-occur-in-agenda-files t]
21452 "--")
21453 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21455 ;;;; Documentation
21457 (defun org-require-autoloaded-modules ()
21458 (interactive)
21459 (mapc 'require
21460 '(org-agenda org-archive org-attach org-clock org-colview org-id
21461 org-table org-timer)))
21463 ;;;###autoload
21464 (defun org-reload (&optional uncompiled)
21465 "Reload all org lisp files.
21466 With prefix arg UNCOMPILED, load the uncompiled versions."
21467 (interactive "P")
21468 (require 'loadhist)
21469 (let* ((org-dir (org-find-library-dir "org"))
21470 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21471 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21472 (remove-re (mapconcat 'identity
21473 (mapcar (lambda (f) (concat "^" f "$"))
21474 (list (if (featurep 'xemacs)
21475 "org-colview"
21476 "org-colview-xemacs")
21477 "org" "org-loaddefs" "org-version"))
21478 "\\|"))
21479 (feats (delete-dups
21480 (mapcar 'file-name-sans-extension
21481 (mapcar 'file-name-nondirectory
21482 (delq nil
21483 (mapcar 'feature-file
21484 features))))))
21485 (lfeat (append
21486 (sort
21487 (setq feats
21488 (delq nil (mapcar
21489 (lambda (f)
21490 (if (and (string-match feature-re f)
21491 (not (string-match remove-re f)))
21492 f nil))
21493 feats)))
21494 'string-lessp)
21495 (list "org-version" "org")))
21496 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21497 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21498 load-uncore load-misses)
21499 (setq load-misses
21500 (delq 't
21501 (mapcar (lambda (f)
21502 (or (org-load-noerror-mustsuffix (concat org-dir f))
21503 (and (string= org-dir contrib-dir)
21504 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21505 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21506 (add-to-list 'load-uncore f 'append)
21509 lfeat)))
21510 (if load-uncore
21511 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21512 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21513 (if load-misses
21514 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21515 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21516 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21518 ;;;###autoload
21519 (defun org-customize ()
21520 "Call the customize function with org as argument."
21521 (interactive)
21522 (org-load-modules-maybe)
21523 (org-require-autoloaded-modules)
21524 (customize-browse 'org))
21526 (defun org-create-customize-menu ()
21527 "Create a full customization menu for Org-mode, insert it into the menu."
21528 (interactive)
21529 (org-load-modules-maybe)
21530 (org-require-autoloaded-modules)
21531 (if (fboundp 'customize-menu-create)
21532 (progn
21533 (easy-menu-change
21534 '("Org") "Customize"
21535 `(["Browse Org group" org-customize t]
21536 "--"
21537 ,(customize-menu-create 'org)
21538 ["Set" Custom-set t]
21539 ["Save" Custom-save t]
21540 ["Reset to Current" Custom-reset-current t]
21541 ["Reset to Saved" Custom-reset-saved t]
21542 ["Reset to Standard Settings" Custom-reset-standard t]))
21543 (message "\"Org\"-menu now contains full customization menu"))
21544 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21546 ;;;; Miscellaneous stuff
21548 ;;; Generally useful functions
21550 (defsubst org-get-at-eol (property n)
21551 "Get text property PROPERTY at the end of line less N characters."
21552 (get-text-property (- (point-at-eol) n) property))
21554 (defun org-find-text-property-in-string (prop s)
21555 "Return the first non-nil value of property PROP in string S."
21556 (or (get-text-property 0 prop s)
21557 (get-text-property (or (next-single-property-change 0 prop s) 0)
21558 prop s)))
21560 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21561 "Display the given MESSAGE as a warning."
21562 (if (fboundp 'display-warning)
21563 (display-warning 'org message
21564 (if (featurep 'xemacs) 'warning :warning))
21565 (let ((buf (get-buffer-create "*Org warnings*")))
21566 (with-current-buffer buf
21567 (goto-char (point-max))
21568 (insert "Warning (Org): " message)
21569 (unless (bolp)
21570 (newline)))
21571 (display-buffer buf)
21572 (sit-for 0))))
21574 (defun org-eval (form)
21575 "Eval FORM and return result."
21576 (condition-case error
21577 (eval form)
21578 (error (format "%%![Error: %s]" error))))
21580 (defun org-in-clocktable-p ()
21581 "Check if the cursor is in a clocktable."
21582 (let ((pos (point)) start)
21583 (save-excursion
21584 (end-of-line 1)
21585 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21586 (setq start (match-beginning 0))
21587 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21588 (>= (match-end 0) pos)
21589 start))))
21591 (defun org-in-verbatim-emphasis ()
21592 (save-match-data
21593 (and (org-in-regexp org-emph-re 2)
21594 (>= (point) (match-beginning 3))
21595 (<= (point) (match-end 4))
21596 (member (match-string 3) '("=" "~")))))
21598 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21599 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21600 (if (and marker (marker-buffer marker)
21601 (buffer-live-p (marker-buffer marker)))
21602 (progn
21603 (org-pop-to-buffer-same-window (marker-buffer marker))
21604 (if (or (> marker (point-max)) (< marker (point-min)))
21605 (widen))
21606 (goto-char marker)
21607 (org-show-context 'org-goto))
21608 (if bookmark
21609 (bookmark-jump bookmark)
21610 (error "Cannot find location"))))
21612 (defun org-quote-csv-field (s)
21613 "Quote field for inclusion in CSV material."
21614 (if (string-match "[\",]" s)
21615 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21618 (defun org-force-self-insert (N)
21619 "Needed to enforce self-insert under remapping."
21620 (interactive "p")
21621 (self-insert-command N))
21623 (defun org-string-width (s)
21624 "Compute width of string, ignoring invisible characters.
21625 This ignores character with invisibility property `org-link', and also
21626 characters with property `org-cwidth', because these will become invisible
21627 upon the next fontification round."
21628 (let (b l)
21629 (when (or (eq t buffer-invisibility-spec)
21630 (assq 'org-link buffer-invisibility-spec))
21631 (while (setq b (text-property-any 0 (length s)
21632 'invisible 'org-link s))
21633 (setq s (concat (substring s 0 b)
21634 (substring s (or (next-single-property-change
21635 b 'invisible s) (length s)))))))
21636 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21637 (setq s (concat (substring s 0 b)
21638 (substring s (or (next-single-property-change
21639 b 'org-cwidth s) (length s))))))
21640 (setq l (string-width s) b -1)
21641 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21642 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21645 (defun org-shorten-string (s maxlength)
21646 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21647 If the string is shorter or has length MAXLENGTH, just return the
21648 original string. If it is longer, the functions finds a space in the
21649 string, breaks this string off at that locations and adds three dots
21650 as ellipsis. Including the ellipsis, the string will not be longer
21651 than MAXLENGTH. If finding a good breaking point in the string does
21652 not work, the string is just chopped off in the middle of a word
21653 if necessary."
21654 (if (<= (length s) maxlength)
21656 (let* ((n (max (- maxlength 4) 1))
21657 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21658 (if (string-match re s)
21659 (concat (match-string 1 s) "...")
21660 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21662 (defun org-get-indentation (&optional line)
21663 "Get the indentation of the current line, interpreting tabs.
21664 When LINE is given, assume it represents a line and compute its indentation."
21665 (if line
21666 (if (string-match "^ *" (org-remove-tabs line))
21667 (match-end 0))
21668 (save-excursion
21669 (beginning-of-line 1)
21670 (skip-chars-forward " \t")
21671 (current-column))))
21673 (defun org-get-string-indentation (s)
21674 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21675 (let ((n -1) (i 0) (w tab-width) c)
21676 (catch 'exit
21677 (while (< (setq n (1+ n)) (length s))
21678 (setq c (aref s n))
21679 (cond ((= c ?\ ) (setq i (1+ i)))
21680 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21681 (t (throw 'exit t)))))
21684 (defun org-remove-tabs (s &optional width)
21685 "Replace tabulators in S with spaces.
21686 Assumes that s is a single line, starting in column 0."
21687 (setq width (or width tab-width))
21688 (while (string-match "\t" s)
21689 (setq s (replace-match
21690 (make-string
21691 (- (* width (/ (+ (match-beginning 0) width) width))
21692 (match-beginning 0)) ?\ )
21693 t t s)))
21696 (defun org-fix-indentation (line ind)
21697 "Fix indentation in LINE.
21698 IND is a cons cell with target and minimum indentation.
21699 If the current indentation in LINE is smaller than the minimum,
21700 leave it alone. If it is larger than ind, set it to the target."
21701 (let* ((l (org-remove-tabs line))
21702 (i (org-get-indentation l))
21703 (i1 (car ind)) (i2 (cdr ind)))
21704 (if (>= i i2) (setq l (substring line i2)))
21705 (if (> i1 0)
21706 (concat (make-string i1 ?\ ) l)
21707 l)))
21709 (defun org-remove-indentation (code &optional n)
21710 "Remove the maximum common indentation from the lines in CODE.
21711 N may optionally be the number of spaces to remove."
21712 (with-temp-buffer
21713 (insert code)
21714 (org-do-remove-indentation n)
21715 (buffer-string)))
21717 (defun org-do-remove-indentation (&optional n)
21718 "Remove the maximum common indentation from the buffer."
21719 (untabify (point-min) (point-max))
21720 (let ((min 10000) re)
21721 (if n
21722 (setq min n)
21723 (goto-char (point-min))
21724 (while (re-search-forward "^ *[^ \n]" nil t)
21725 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21726 (unless (or (= min 0) (= min 10000))
21727 (setq re (format "^ \\{%d\\}" min))
21728 (goto-char (point-min))
21729 (while (re-search-forward re nil t)
21730 (replace-match "")
21731 (end-of-line 1))
21732 min)))
21734 (defun org-fill-template (template alist)
21735 "Find each %key of ALIST in TEMPLATE and replace it."
21736 (let ((case-fold-search nil)
21737 entry key value)
21738 (setq alist (sort (copy-sequence alist)
21739 (lambda (a b) (< (length (car a)) (length (car b))))))
21740 (while (setq entry (pop alist))
21741 (setq template
21742 (replace-regexp-in-string
21743 (concat "%" (regexp-quote (car entry)))
21744 (or (cdr entry) "") template t t)))
21745 template))
21747 (defun org-base-buffer (buffer)
21748 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21749 (if (not buffer)
21750 buffer
21751 (or (buffer-base-buffer buffer)
21752 buffer)))
21754 (defun org-wrap (string &optional width lines)
21755 "Wrap string to either a number of lines, or a width in characters.
21756 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21757 that costs. If there is a word longer than WIDTH, the text is actually
21758 wrapped to the length of that word.
21759 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21760 many lines, whatever width that takes.
21761 The return value is a list of lines, without newlines at the end."
21762 (let* ((words (org-split-string string "[ \t\n]+"))
21763 (maxword (apply 'max (mapcar 'org-string-width words)))
21764 w ll)
21765 (cond (width
21766 (org-do-wrap words (max maxword width)))
21767 (lines
21768 (setq w maxword)
21769 (setq ll (org-do-wrap words maxword))
21770 (if (<= (length ll) lines)
21772 (setq ll words)
21773 (while (> (length ll) lines)
21774 (setq w (1+ w))
21775 (setq ll (org-do-wrap words w)))
21776 ll))
21777 (t (error "Cannot wrap this")))))
21779 (defun org-do-wrap (words width)
21780 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21781 (let (lines line)
21782 (while words
21783 (setq line (pop words))
21784 (while (and words (< (+ (length line) (length (car words))) width))
21785 (setq line (concat line " " (pop words))))
21786 (setq lines (push line lines)))
21787 (nreverse lines)))
21789 (defun org-split-string (string &optional separators)
21790 "Splits STRING into substrings at SEPARATORS.
21791 No empty strings are returned if there are matches at the beginning
21792 and end of string."
21793 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21794 (start 0)
21795 notfirst
21796 (list nil))
21797 (while (and (string-match rexp string
21798 (if (and notfirst
21799 (= start (match-beginning 0))
21800 (< start (length string)))
21801 (1+ start) start))
21802 (< (match-beginning 0) (length string)))
21803 (setq notfirst t)
21804 (or (eq (match-beginning 0) 0)
21805 (and (eq (match-beginning 0) (match-end 0))
21806 (eq (match-beginning 0) start))
21807 (setq list
21808 (cons (substring string start (match-beginning 0))
21809 list)))
21810 (setq start (match-end 0)))
21811 (or (eq start (length string))
21812 (setq list
21813 (cons (substring string start)
21814 list)))
21815 (nreverse list)))
21817 (defun org-quote-vert (s)
21818 "Replace \"|\" with \"\\vert\"."
21819 (while (string-match "|" s)
21820 (setq s (replace-match "\\vert" t t s)))
21823 (defun org-uuidgen-p (s)
21824 "Is S an ID created by UUIDGEN?"
21825 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21827 (defun org-in-src-block-p (&optional inside)
21828 "Whether point is in a code source block.
21829 When INSIDE is non-nil, don't consider we are within a src block
21830 when point is at #+BEGIN_SRC or #+END_SRC."
21831 (let ((case-fold-search t) ov)
21832 (or (and (eq (get-char-property (point) 'src-block) t))
21833 (and (not inside)
21834 (save-match-data
21835 (save-excursion
21836 (beginning-of-line)
21837 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21839 (defun org-context ()
21840 "Return a list of contexts of the current cursor position.
21841 If several contexts apply, all are returned.
21842 Each context entry is a list with a symbol naming the context, and
21843 two positions indicating start and end of the context. Possible
21844 contexts are:
21846 :headline anywhere in a headline
21847 :headline-stars on the leading stars in a headline
21848 :todo-keyword on a TODO keyword (including DONE) in a headline
21849 :tags on the TAGS in a headline
21850 :priority on the priority cookie in a headline
21851 :item on the first line of a plain list item
21852 :item-bullet on the bullet/number of a plain list item
21853 :checkbox on the checkbox in a plain list item
21854 :table in an org-mode table
21855 :table-special on a special filed in a table
21856 :table-table in a table.el table
21857 :clocktable in a clocktable
21858 :src-block in a source block
21859 :link on a hyperlink
21860 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21861 :target on a <<target>>
21862 :radio-target on a <<<radio-target>>>
21863 :latex-fragment on a LaTeX fragment
21864 :latex-preview on a LaTeX fragment with overlaid preview image
21866 This function expects the position to be visible because it uses font-lock
21867 faces as a help to recognize the following contexts: :table-special, :link,
21868 and :keyword."
21869 (let* ((f (get-text-property (point) 'face))
21870 (faces (if (listp f) f (list f)))
21871 (case-fold-search t)
21872 (p (point)) clist o)
21873 ;; First the large context
21874 (cond
21875 ((org-at-heading-p t)
21876 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21877 (when (progn
21878 (beginning-of-line 1)
21879 (looking-at org-todo-line-tags-regexp))
21880 (push (org-point-in-group p 1 :headline-stars) clist)
21881 (push (org-point-in-group p 2 :todo-keyword) clist)
21882 (push (org-point-in-group p 4 :tags) clist))
21883 (goto-char p)
21884 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21885 (if (looking-at "\\[#[A-Z0-9]\\]")
21886 (push (org-point-in-group p 0 :priority) clist)))
21888 ((org-at-item-p)
21889 (push (org-point-in-group p 2 :item-bullet) clist)
21890 (push (list :item (point-at-bol)
21891 (save-excursion (org-end-of-item) (point)))
21892 clist)
21893 (and (org-at-item-checkbox-p)
21894 (push (org-point-in-group p 0 :checkbox) clist)))
21896 ((org-at-table-p)
21897 (push (list :table (org-table-begin) (org-table-end)) clist)
21898 (if (memq 'org-formula faces)
21899 (push (list :table-special
21900 (previous-single-property-change p 'face)
21901 (next-single-property-change p 'face)) clist)))
21902 ((org-at-table-p 'any)
21903 (push (list :table-table) clist)))
21904 (goto-char p)
21906 (let ((case-fold-search t))
21907 ;; New the "medium" contexts: clocktables, source blocks
21908 (cond ((org-in-clocktable-p)
21909 (push (list :clocktable
21910 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21911 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21912 (match-beginning 1))
21913 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21914 (match-end 0))) clist))
21915 ((org-in-src-block-p)
21916 (push (list :src-block
21917 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21918 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21919 (match-beginning 1))
21920 (and (search-forward "#+END_SRC" nil t)
21921 (match-beginning 0))) clist))))
21922 (goto-char p)
21924 ;; Now the small context
21925 (cond
21926 ((org-at-timestamp-p)
21927 (push (org-point-in-group p 0 :timestamp) clist))
21928 ((memq 'org-link faces)
21929 (push (list :link
21930 (previous-single-property-change p 'face)
21931 (next-single-property-change p 'face)) clist))
21932 ((memq 'org-special-keyword faces)
21933 (push (list :keyword
21934 (previous-single-property-change p 'face)
21935 (next-single-property-change p 'face)) clist))
21936 ((org-at-target-p)
21937 (push (org-point-in-group p 0 :target) clist)
21938 (goto-char (1- (match-beginning 0)))
21939 (if (looking-at org-radio-target-regexp)
21940 (push (org-point-in-group p 0 :radio-target) clist))
21941 (goto-char p))
21942 ((setq o (car (delq nil
21943 (mapcar
21944 (lambda (x)
21945 (if (memq x org-latex-fragment-image-overlays) x))
21946 (overlays-at (point))))))
21947 (push (list :latex-fragment
21948 (overlay-start o) (overlay-end o)) clist)
21949 (push (list :latex-preview
21950 (overlay-start o) (overlay-end o)) clist))
21951 ((org-inside-LaTeX-fragment-p)
21952 ;; FIXME: positions wrong.
21953 (push (list :latex-fragment (point) (point)) clist)))
21955 (setq clist (nreverse (delq nil clist)))
21956 clist))
21958 ;; FIXME: Compare with at-regexp-p Do we need both?
21959 (defun org-in-regexp (re &optional nlines visually)
21960 "Check if point is inside a match of regexp.
21961 Normally only the current line is checked, but you can include NLINES extra
21962 lines both before and after point into the search.
21963 If VISUALLY is set, require that the cursor is not after the match but
21964 really on, so that the block visually is on the match."
21965 (catch 'exit
21966 (let ((pos (point))
21967 (eol (point-at-eol (+ 1 (or nlines 0))))
21968 (inc (if visually 1 0)))
21969 (save-excursion
21970 (beginning-of-line (- 1 (or nlines 0)))
21971 (while (re-search-forward re eol t)
21972 (if (and (<= (match-beginning 0) pos)
21973 (>= (+ inc (match-end 0)) pos))
21974 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21976 (defun org-at-regexp-p (regexp)
21977 "Is point inside a match of REGEXP in the current line?"
21978 (catch 'exit
21979 (save-excursion
21980 (let ((pos (point)) (end (point-at-eol)))
21981 (beginning-of-line 1)
21982 (while (re-search-forward regexp end t)
21983 (if (and (<= (match-beginning 0) pos)
21984 (>= (match-end 0) pos))
21985 (throw 'exit t)))
21986 nil))))
21988 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21989 "Non-nil when point is between matches of START-RE and END-RE.
21991 Also return a non-nil value when point is on one of the matches.
21993 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21994 buffer positions. Default values are the positions of headlines
21995 surrounding the point.
21997 The functions returns a cons cell whose car (resp. cdr) is the
21998 position before START-RE (resp. after END-RE)."
21999 (save-match-data
22000 (let ((pos (point))
22001 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22002 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22003 beg end)
22004 (save-excursion
22005 ;; Point is on a block when on START-RE or if START-RE can be
22006 ;; found before it...
22007 (and (or (org-at-regexp-p start-re)
22008 (re-search-backward start-re limit-up t))
22009 (setq beg (match-beginning 0))
22010 ;; ... and END-RE after it...
22011 (goto-char (match-end 0))
22012 (re-search-forward end-re limit-down t)
22013 (> (setq end (match-end 0)) pos)
22014 ;; ... without another START-RE in-between.
22015 (goto-char (match-beginning 0))
22016 (not (re-search-backward start-re (1+ beg) t))
22017 ;; Return value.
22018 (cons beg end))))))
22020 (defun org-in-block-p (names)
22021 "Non-nil when point belongs to a block whose name belongs to NAMES.
22023 NAMES is a list of strings containing names of blocks.
22025 Return first block name matched, or nil. Beware that in case of
22026 nested blocks, the returned name may not belong to the closest
22027 block from point."
22028 (save-match-data
22029 (catch 'exit
22030 (let ((case-fold-search t)
22031 (lim-up (save-excursion (outline-previous-heading)))
22032 (lim-down (save-excursion (outline-next-heading))))
22033 (mapc (lambda (name)
22034 (let ((n (regexp-quote name)))
22035 (when (org-between-regexps-p
22036 (concat "^[ \t]*#\\+begin_" n)
22037 (concat "^[ \t]*#\\+end_" n)
22038 lim-up lim-down)
22039 (throw 'exit n))))
22040 names))
22041 nil)))
22043 (defun org-in-drawer-p ()
22044 "Non-nil if point is within a drawer.
22045 If point is within a drawer, return it, as parsed data."
22046 (let ((element (save-match-data (org-element-at-point))))
22047 (while (and element (not (memq (org-element-type element)
22048 '(drawer property-drawer))))
22049 (setq element (org-element-property :parent element)))
22050 element))
22052 (defun org-occur-in-agenda-files (regexp &optional nlines)
22053 "Call `multi-occur' with buffers for all agenda files."
22054 (interactive "sOrg-files matching: \np")
22055 (let* ((files (org-agenda-files))
22056 (tnames (mapcar 'file-truename files))
22057 (extra org-agenda-text-search-extra-files)
22059 (when (eq (car extra) 'agenda-archives)
22060 (setq extra (cdr extra))
22061 (setq files (org-add-archive-files files)))
22062 (while (setq f (pop extra))
22063 (unless (member (file-truename f) tnames)
22064 (add-to-list 'files f 'append)
22065 (add-to-list 'tnames (file-truename f) 'append)))
22066 (multi-occur
22067 (mapcar (lambda (x)
22068 (with-current-buffer
22069 (or (get-file-buffer x) (find-file-noselect x))
22070 (widen)
22071 (current-buffer)))
22072 files)
22073 regexp)))
22075 (if (boundp 'occur-mode-find-occurrence-hook)
22076 ;; Emacs 23
22077 (add-hook 'occur-mode-find-occurrence-hook
22078 (lambda ()
22079 (when (derived-mode-p 'org-mode)
22080 (org-reveal))))
22081 ;; Emacs 22
22082 (defadvice occur-mode-goto-occurrence
22083 (after org-occur-reveal activate)
22084 (and (derived-mode-p 'org-mode) (org-reveal)))
22085 (defadvice occur-mode-goto-occurrence-other-window
22086 (after org-occur-reveal activate)
22087 (and (derived-mode-p 'org-mode) (org-reveal)))
22088 (defadvice occur-mode-display-occurrence
22089 (after org-occur-reveal activate)
22090 (when (derived-mode-p 'org-mode)
22091 (let ((pos (occur-mode-find-occurrence)))
22092 (with-current-buffer (marker-buffer pos)
22093 (save-excursion
22094 (goto-char pos)
22095 (org-reveal)))))))
22097 (defun org-occur-link-in-agenda-files ()
22098 "Create a link and search for it in the agendas.
22099 The link is not stored in `org-stored-links', it is just created
22100 for the search purpose."
22101 (interactive)
22102 (let ((link (condition-case nil
22103 (org-store-link nil)
22104 (error "Unable to create a link to here"))))
22105 (org-occur-in-agenda-files (regexp-quote link))))
22107 (defun org-reverse-string (string)
22108 "Return the reverse of STRING."
22109 (apply 'string (reverse (string-to-list string))))
22111 ;; defsubst org-uniquify must be defined before first use
22113 (defun org-uniquify-alist (alist)
22114 "Merge elements of ALIST with the same key.
22116 For example, in this alist:
22118 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22119 => '((a 1 3) (b 2))
22121 merge (a 1) and (a 3) into (a 1 3).
22123 The function returns the new ALIST."
22124 (let (rtn)
22125 (mapc
22126 (lambda (e)
22127 (let (n)
22128 (if (not (assoc (car e) rtn))
22129 (push e rtn)
22130 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22131 (setq rtn (assq-delete-all (car e) rtn))
22132 (push n rtn))))
22133 alist)
22134 rtn))
22136 (defun org-delete-all (elts list)
22137 "Remove all elements in ELTS from LIST."
22138 (while elts
22139 (setq list (delete (pop elts) list)))
22140 list)
22142 (defun org-count (cl-item cl-seq)
22143 "Count the number of occurrences of ITEM in SEQ.
22144 Taken from `count' in cl-seq.el with all keyword arguments removed."
22145 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22146 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22147 (while (< cl-start cl-end)
22148 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22149 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22150 (setq cl-start (1+ cl-start)))
22151 cl-count))
22153 (defun org-remove-if (predicate seq)
22154 "Remove everything from SEQ that fulfills PREDICATE."
22155 (let (res e)
22156 (while seq
22157 (setq e (pop seq))
22158 (if (not (funcall predicate e)) (push e res)))
22159 (nreverse res)))
22161 (defun org-remove-if-not (predicate seq)
22162 "Remove everything from SEQ that does not fulfill PREDICATE."
22163 (let (res e)
22164 (while seq
22165 (setq e (pop seq))
22166 (if (funcall predicate e) (push e res)))
22167 (nreverse res)))
22169 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22170 "Reduce two-argument FUNCTION across SEQ.
22171 Taken from `reduce' in cl-seq.el with all keyword arguments but
22172 \":initial-value\" removed."
22173 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22174 (cadr (memq :initial-value cl-keys)))
22175 (cl-seq (pop cl-seq))
22176 (t (funcall cl-func)))))
22177 (while cl-seq
22178 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22179 cl-accum))
22181 (defun org-every (pred seq)
22182 "Return true if PREDICATE is true of every element of SEQ.
22183 Adapted from `every' in cl.el."
22184 (catch 'org-every
22185 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22188 (defun org-some (pred seq)
22189 "Return true if PREDICATE is true of any element of SEQ.
22190 Adapted from `some' in cl.el."
22191 (catch 'org-some
22192 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22193 nil))
22195 (defun org-back-over-empty-lines ()
22196 "Move backwards over whitespace, to the beginning of the first empty line.
22197 Returns the number of empty lines passed."
22198 (let ((pos (point)))
22199 (if (cdr (assoc 'heading org-blank-before-new-entry))
22200 (skip-chars-backward " \t\n\r")
22201 (unless (eobp)
22202 (forward-line -1)))
22203 (beginning-of-line 2)
22204 (goto-char (min (point) pos))
22205 (count-lines (point) pos)))
22207 (defun org-skip-whitespace ()
22208 (skip-chars-forward " \t\n\r"))
22210 (defun org-point-in-group (point group &optional context)
22211 "Check if POINT is in match-group GROUP.
22212 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22213 match. If the match group does not exist or point is not inside it,
22214 return nil."
22215 (and (match-beginning group)
22216 (>= point (match-beginning group))
22217 (<= point (match-end group))
22218 (if context
22219 (list context (match-beginning group) (match-end group))
22220 t)))
22222 (defun org-switch-to-buffer-other-window (&rest args)
22223 "Switch to buffer in a second window on the current frame.
22224 In particular, do not allow pop-up frames.
22225 Returns the newly created buffer."
22226 (org-no-popups
22227 (apply 'switch-to-buffer-other-window args)))
22229 (defun org-combine-plists (&rest plists)
22230 "Create a single property list from all plists in PLISTS.
22231 The process starts by copying the first list, and then setting properties
22232 from the other lists. Settings in the last list are the most significant
22233 ones and overrule settings in the other lists."
22234 (let ((rtn (copy-sequence (pop plists)))
22235 p v ls)
22236 (while plists
22237 (setq ls (pop plists))
22238 (while ls
22239 (setq p (pop ls) v (pop ls))
22240 (setq rtn (plist-put rtn p v))))
22241 rtn))
22243 (defun org-replace-escapes (string table)
22244 "Replace %-escapes in STRING with values in TABLE.
22245 TABLE is an association list with keys like \"%a\" and string values.
22246 The sequences in STRING may contain normal field width and padding information,
22247 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22248 so values can contain further %-escapes if they are define later in TABLE."
22249 (let ((tbl (copy-alist table))
22250 (case-fold-search nil)
22251 (pchg 0)
22252 e re rpl)
22253 (while (setq e (pop tbl))
22254 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22255 (when (and (cdr e) (string-match re (cdr e)))
22256 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22257 (safe "SREF"))
22258 (add-text-properties 0 3 (list 'sref sref) safe)
22259 (setcdr e (replace-match safe t t (cdr e)))))
22260 (while (string-match re string)
22261 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22262 (cdr e)))
22263 (setq string (replace-match rpl t t string))))
22264 (while (setq pchg (next-property-change pchg string))
22265 (let ((sref (get-text-property pchg 'sref string)))
22266 (when (and sref (string-match "SREF" string pchg))
22267 (setq string (replace-match sref t t string)))))
22268 string))
22270 (defun org-sublist (list start end)
22271 "Return a section of LIST, from START to END.
22272 Counting starts at 1."
22273 (let (rtn (c start))
22274 (setq list (nthcdr (1- start) list))
22275 (while (and list (<= c end))
22276 (push (pop list) rtn)
22277 (setq c (1+ c)))
22278 (nreverse rtn)))
22280 (defun org-find-base-buffer-visiting (file)
22281 "Like `find-buffer-visiting' but always return the base buffer and
22282 not an indirect buffer."
22283 (let ((buf (or (get-file-buffer file)
22284 (find-buffer-visiting file))))
22285 (if buf
22286 (or (buffer-base-buffer buf) buf)
22287 nil)))
22289 (defun org-image-file-name-regexp (&optional extensions)
22290 "Return regexp matching the file names of images.
22291 If EXTENSIONS is given, only match these."
22292 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22293 (image-file-name-regexp)
22294 (let ((image-file-name-extensions
22295 (or extensions
22296 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22297 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22298 (concat "\\."
22299 (regexp-opt (nconc (mapcar 'upcase
22300 image-file-name-extensions)
22301 image-file-name-extensions)
22303 "\\'"))))
22305 (defun org-file-image-p (file &optional extensions)
22306 "Return non-nil if FILE is an image."
22307 (save-match-data
22308 (string-match (org-image-file-name-regexp extensions) file)))
22310 (defun org-get-cursor-date (&optional with-time)
22311 "Return the date at cursor in as a time.
22312 This works in the calendar and in the agenda, anywhere else it just
22313 returns the current time.
22314 If WITH-TIME is non-nil, returns the time of the event at point (in
22315 the agenda) or the current time of the day."
22316 (let (date day defd tp tm hod mod)
22317 (when with-time
22318 (setq tp (get-text-property (point) 'time))
22319 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22320 (setq hod (string-to-number (match-string 1 tp))
22321 mod (string-to-number (match-string 2 tp))))
22322 (or tp (setq hod (nth 2 (decode-time (current-time)))
22323 mod (nth 1 (decode-time (current-time))))))
22324 (cond
22325 ((eq major-mode 'calendar-mode)
22326 (setq date (calendar-cursor-to-date)
22327 defd (encode-time 0 (or mod 0) (or hod 0)
22328 (nth 1 date) (nth 0 date) (nth 2 date))))
22329 ((eq major-mode 'org-agenda-mode)
22330 (setq day (get-text-property (point) 'day))
22331 (if day
22332 (setq date (calendar-gregorian-from-absolute day)
22333 defd (encode-time 0 (or mod 0) (or hod 0)
22334 (nth 1 date) (nth 0 date) (nth 2 date))))))
22335 (or defd (current-time))))
22337 (defun org-mark-subtree (&optional up)
22338 "Mark the current subtree.
22339 This puts point at the start of the current subtree, and mark at
22340 the end. If a numeric prefix UP is given, move up into the
22341 hierarchy of headlines by UP levels before marking the subtree."
22342 (interactive "P")
22343 (org-with-limited-levels
22344 (cond ((org-at-heading-p) (beginning-of-line))
22345 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22346 (t (outline-previous-visible-heading 1))))
22347 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22348 (if (org-called-interactively-p 'any)
22349 (call-interactively 'org-mark-element)
22350 (org-mark-element)))
22353 ;;; Indentation
22355 (defun org--get-expected-indentation (element contentsp)
22356 "Expected indentation column for current line, according to ELEMENT.
22357 ELEMENT is an element containing point. CONTENTSP is non-nil
22358 when indentation is to be computed according to contents of
22359 ELEMENT."
22360 (let ((type (org-element-type element))
22361 (start (org-element-property :begin element)))
22362 (org-with-wide-buffer
22363 (cond
22364 (contentsp
22365 (case type
22366 (footnote-definition 0)
22367 ((headline inlinetask nil)
22368 (if (not org-adapt-indentation) 0
22369 (let ((level (org-current-level)))
22370 (if level (1+ level) 0))))
22371 ((item plain list)
22372 (org-list-item-body-column
22373 (or (org-element-property :post-affiliated element) start)))
22374 (otherwise
22375 (goto-char start)
22376 (org-get-indentation))))
22377 ((memq type '(headline inlinetask nil))
22378 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22379 (org--get-expected-indentation element t)
22381 ((eq type 'footnote-definition) 0)
22382 ;; First paragraph of a footnote definition or an item.
22383 ;; Indent like parent.
22384 ((< (line-beginning-position) start)
22385 (org--get-expected-indentation
22386 (org-element-property :parent element) t))
22387 ;; At first line: indent according to previous sibling, if any,
22388 ;; ignoring footnote definitions and inline tasks, or parent's
22389 ;; contents.
22390 ((= (line-beginning-position) start)
22391 (catch 'exit
22392 (while t
22393 (if (= (point-min) start) (throw 'exit 0)
22394 (goto-char (1- start))
22395 (let ((previous (org-element-at-point)))
22396 (while (let ((parent (org-element-property :parent previous)))
22397 (and parent
22398 (setq previous parent)
22399 (<= (org-element-property :end parent) start))))
22400 (cond ((or (not previous)
22401 (> (org-element-property :end previous) start))
22402 (throw 'exit (org--get-expected-indentation previous t)))
22403 ((memq (org-element-type previous)
22404 '(footnote-definition inlinetask))
22405 (setq start (org-element-property :begin previous)))
22406 (t (goto-char (org-element-property :begin previous))
22407 (throw 'exit (org-get-indentation)))))))))
22408 ;; Otherwise, move to the first non-blank line above.
22410 (beginning-of-line)
22411 (let ((pos (point)))
22412 (skip-chars-backward " \r\t\n")
22413 (cond
22414 ;; Two blank lines end a footnote definition or a plain
22415 ;; list. When we indent an empty line after them, the
22416 ;; containing list or footnote definition is over, so it
22417 ;; qualifies as a previous sibling. Therefore, we indent
22418 ;; like its first line.
22419 ((and (memq type '(footnote-definition plain-list))
22420 (> (count-lines (point) pos) 2))
22421 (goto-char start)
22422 (org-get-indentation))
22423 ;; Line above is the first one of a paragraph at the
22424 ;; beginning of an item or a footnote definition. Indent
22425 ;; like parent.
22426 ((< (line-beginning-position) start)
22427 (org--get-expected-indentation
22428 (org-element-property :parent element) t))
22429 ;; POS is after contents in a greater element. Indent like
22430 ;; the beginning of the element.
22432 ;; As a special case, if point is at the end of a footnote
22433 ;; definition or an item, indent like the very last element
22434 ;; within.
22435 ((let ((cend (org-element-property :contents-end element)))
22436 (and cend (<= cend pos)))
22437 (if (memq type '(footnote-definition item plain-list))
22438 (org--get-expected-indentation (org-element-at-point) nil)
22439 (goto-char start)
22440 (org-get-indentation)))
22441 ;; In any other case, indent like the current line.
22442 (t (org-get-indentation)))))))))
22444 (defun org--align-node-property ()
22445 "Align node property at point.
22446 Alignment is done according to `org-property-format', which see."
22447 (when (save-excursion
22448 (beginning-of-line)
22449 (looking-at org-property-re))
22450 (replace-match
22451 (concat (match-string 4)
22452 (format org-property-format (match-string 1) (match-string 3)))
22453 t t)))
22455 (defun org-indent-line ()
22456 "Indent line depending on context.
22458 Indentation is done according to the following rules:
22460 - Footnote definitions, headlines and inline tasks have to
22461 start at column 0.
22463 - On the very first line of an element, consider, in order, the
22464 next rules until one matches:
22466 1. If there's a sibling element before, ignoring footnote
22467 definitions and inline tasks, indent like its first line.
22469 2. If element has a parent, indent like its contents. More
22470 precisely, if parent is an item, indent after the
22471 description part, if any, or the bullet (see
22472 ``org-list-description-max-indent'). Else, indent like
22473 parent's first line.
22475 3. Otherwise, indent relatively to current level, if
22476 `org-adapt-indentation' is non-nil, or to left margin.
22478 - On a blank line at the end of a plain list, an item, or
22479 a footnote definition, indent like the very last element
22480 within.
22482 - In the code part of a source block, use language major mode
22483 to indent current line if `org-src-tab-acts-natively' is
22484 non-nil. If it is nil, do nothing.
22486 - Otherwise, indent like the first non-blank line above.
22488 The function doesn't indent an item as it could break the whole
22489 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22490 \\[org-shiftmetaright].
22492 Also align node properties according to `org-property-format'."
22493 (interactive)
22494 (cond
22495 (orgstruct-is-++
22496 (let ((indent-line-function
22497 (cadadr (assq 'indent-line-function org-fb-vars))))
22498 (indent-according-to-mode)))
22499 ((org-at-heading-p) 'noindent)
22501 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22502 (type (org-element-type element)))
22503 (cond ((and (memq type '(plain-list item))
22504 (= (line-beginning-position)
22505 (or (org-element-property :post-affiliated element)
22506 (org-element-property :begin element))))
22507 'noindent)
22508 ((and (eq type 'src-block)
22509 org-src-tab-acts-natively
22510 (> (line-beginning-position)
22511 (org-element-property :post-affiliated element))
22512 (< (line-beginning-position)
22513 (org-with-wide-buffer
22514 (goto-char (org-element-property :end element))
22515 (skip-chars-backward " \r\t\n")
22516 (line-beginning-position))))
22517 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22518 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22520 (let ((column (org--get-expected-indentation element nil)))
22521 ;; Preserve current column.
22522 (if (<= (current-column) (current-indentation))
22523 (org-indent-line-to column)
22524 (save-excursion (org-indent-line-to column))))
22525 ;; Align node property. Also preserve current column.
22526 (when (eq type 'node-property)
22527 (let ((column (current-column)))
22528 (org--align-node-property)
22529 (org-move-to-column column)))))))))
22531 (defun org-indent-region (start end)
22532 "Indent each non-blank line in the region.
22533 Called from a program, START and END specify the region to
22534 indent. The function will not indent contents of example blocks,
22535 verse blocks and export blocks as leading white spaces are
22536 assumed to be significant there."
22537 (interactive "r")
22538 (save-excursion
22539 (goto-char start)
22540 (beginning-of-line)
22541 (let ((indent-to
22542 (lambda (ind pos)
22543 ;; Set IND as indentation for all lines between point and
22544 ;; POS or END, whichever comes first. Blank lines are
22545 ;; ignored. Leave point after POS once done.
22546 (let ((limit (copy-marker (min end pos))))
22547 (while (< (point) limit)
22548 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22549 (forward-line))
22550 (set-marker limit nil))))
22551 (end (copy-marker end)))
22552 (while (< (point) end)
22553 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22554 (let* ((element (org-element-at-point))
22555 (type (org-element-type element))
22556 (element-end (copy-marker (org-element-property :end element)))
22557 (ind (org--get-expected-indentation element nil)))
22558 (if (or (memq type '(paragraph table table-row))
22559 (not (or (org-element-property :contents-begin element)
22560 (memq type
22561 '(example-block export-block src-block)))))
22562 ;; Elements here are indented as a single block. Also
22563 ;; align node properties.
22564 (progn
22565 (when (eq type 'node-property)
22566 (org--align-node-property)
22567 (beginning-of-line))
22568 (funcall indent-to ind element-end))
22569 ;; Elements in this category consist of three parts:
22570 ;; before the contents, the contents, and after the
22571 ;; contents. The contents are treated specially,
22572 ;; according to the element type, or not indented at
22573 ;; all. Other parts are indented as a single block.
22574 (let* ((post (copy-marker
22575 (or (org-element-property :post-affiliated element)
22576 (org-element-property :begin element))))
22577 (cbeg
22578 (copy-marker
22579 (cond
22580 ((not (org-element-property :contents-begin element))
22581 ;; Fake contents for source blocks.
22582 (org-with-wide-buffer
22583 (goto-char post)
22584 (forward-line)
22585 (point)))
22586 ((memq type '(footnote-definition item plain-list))
22587 ;; Contents in these elements could start on
22588 ;; the same line as the beginning of the
22589 ;; element. Make sure we start indenting
22590 ;; from the second line.
22591 (org-with-wide-buffer
22592 (goto-char post)
22593 (forward-line)
22594 (point)))
22595 (t (org-element-property :contents-begin element)))))
22596 (cend (copy-marker
22597 (or (org-element-property :contents-end element)
22598 ;; Fake contents for source blocks.
22599 (org-with-wide-buffer
22600 (goto-char element-end)
22601 (skip-chars-backward " \r\t\n")
22602 (line-beginning-position))))))
22603 (funcall indent-to ind cbeg)
22604 (when (< (point) end)
22605 (case type
22606 ((example-block export-block verse-block))
22607 (src-block
22608 ;; In a source block, indent source code according
22609 ;; to language major mode, but only if
22610 ;; `org-src-tab-acts-natively' is non-nil.
22611 (when (and (< (point) end) org-src-tab-acts-natively)
22612 (ignore-errors
22613 (let (org-src-strip-leading-and-trailing-blank-lines
22614 ;; Region boundaries in edit buffer.
22615 (start (1+ (- (point) cbeg)))
22616 (end (- (min cend end) cbeg)))
22617 (org-babel-do-in-edit-buffer
22618 (indent-region start end))))))
22619 (t (org-indent-region (point) (min cend end))))
22620 (goto-char (min cend end))
22621 (when (< (point) end) (funcall indent-to ind element-end)))
22622 (set-marker post nil)
22623 (set-marker cbeg nil)
22624 (set-marker cend nil)))
22625 (set-marker element-end nil))))
22626 (set-marker end nil))))
22628 (defun org-indent-drawer ()
22629 "Indent the drawer at point."
22630 (interactive)
22631 (unless (save-excursion
22632 (beginning-of-line)
22633 (org-looking-at-p org-drawer-regexp))
22634 (user-error "Not at a drawer"))
22635 (let ((element (org-element-at-point)))
22636 (unless (memq (org-element-type element) '(drawer property-drawer))
22637 (user-error "Not at a drawer"))
22638 (org-with-wide-buffer
22639 (org-indent-region (org-element-property :begin element)
22640 (org-element-property :end element))))
22641 (message "Drawer at point indented"))
22643 (defun org-indent-block ()
22644 "Indent the block at point."
22645 (interactive)
22646 (unless (save-excursion
22647 (beginning-of-line)
22648 (let ((case-fold-search t))
22649 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22650 (user-error "Not at a block"))
22651 (let ((element (org-element-at-point)))
22652 (unless (memq (org-element-type element)
22653 '(comment-block center-block example-block export-block
22654 quote-block special-block src-block
22655 verse-block))
22656 (user-error "Not at a block"))
22657 (org-with-wide-buffer
22658 (org-indent-region (org-element-property :begin element)
22659 (org-element-property :end element))))
22660 (message "Block at point indented"))
22663 ;;; Filling
22665 ;; We use our own fill-paragraph and auto-fill functions.
22667 ;; `org-fill-paragraph' relies on adaptive filling and context
22668 ;; checking. Appropriate `fill-prefix' is computed with
22669 ;; `org-adaptive-fill-function'.
22671 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22672 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22673 ;; `org-adaptive-fill-function' value. Internally,
22674 ;; `org-comment-line-break-function' breaks the line.
22676 ;; `org-setup-filling' installs filling and auto-filling related
22677 ;; variables during `org-mode' initialization.
22679 (defvar org-element-paragraph-separate) ; org-element.el
22680 (defun org-setup-filling ()
22681 (require 'org-element)
22682 ;; Prevent auto-fill from inserting unwanted new items.
22683 (when (boundp 'fill-nobreak-predicate)
22684 (org-set-local
22685 'fill-nobreak-predicate
22686 (org-uniquify
22687 (append fill-nobreak-predicate
22688 '(org-fill-line-break-nobreak-p
22689 org-fill-paragraph-with-timestamp-nobreak-p)))))
22690 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22691 (org-set-local 'paragraph-start paragraph-ending)
22692 (org-set-local 'paragraph-separate paragraph-ending))
22693 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22694 (org-set-local 'auto-fill-inhibit-regexp nil)
22695 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22696 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22697 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22699 (defun org-fill-line-break-nobreak-p ()
22700 "Non-nil when a new line at point would create an Org line break."
22701 (save-excursion
22702 (skip-chars-backward "[ \t]")
22703 (skip-chars-backward "\\\\")
22704 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22706 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22707 "Non-nil when a new line at point would split a timestamp."
22708 (and (org-at-timestamp-p t)
22709 (not (looking-at org-ts-regexp-both))))
22711 (declare-function message-in-body-p "message" ())
22712 (defvar orgtbl-line-start-regexp) ; From org-table.el
22713 (defun org-adaptive-fill-function ()
22714 "Compute a fill prefix for the current line.
22715 Return fill prefix, as a string, or nil if current line isn't
22716 meant to be filled. For convenience, if `adaptive-fill-regexp'
22717 matches in paragraphs or comments, use it."
22718 (catch 'exit
22719 (when (derived-mode-p 'message-mode)
22720 (save-excursion
22721 (beginning-of-line)
22722 (cond ((or (not (message-in-body-p))
22723 (looking-at orgtbl-line-start-regexp))
22724 (throw 'exit nil))
22725 ((looking-at message-cite-prefix-regexp)
22726 (throw 'exit (match-string-no-properties 0)))
22727 ((looking-at org-outline-regexp)
22728 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22729 (org-with-wide-buffer
22730 (unless (org-at-heading-p)
22731 (let* ((p (line-beginning-position))
22732 (element (save-excursion
22733 (beginning-of-line)
22734 (org-element-at-point)))
22735 (type (org-element-type element))
22736 (post-affiliated (org-element-property :post-affiliated element)))
22737 (unless (and post-affiliated (< p post-affiliated))
22738 (case type
22739 (comment
22740 (save-excursion
22741 (beginning-of-line)
22742 (looking-at "[ \t]*")
22743 (concat (match-string 0) "# ")))
22744 (footnote-definition "")
22745 ((item plain-list)
22746 (make-string (org-list-item-body-column
22747 (or post-affiliated
22748 (org-element-property :begin element)))
22749 ?\s))
22750 (paragraph
22751 ;; Fill prefix is usually the same as the current line,
22752 ;; unless the paragraph is at the beginning of an item.
22753 (let ((parent (org-element-property :parent element)))
22754 (save-excursion
22755 (beginning-of-line)
22756 (cond ((eq (org-element-type parent) 'item)
22757 (make-string (org-list-item-body-column
22758 (org-element-property :begin parent))
22759 ?\s))
22760 ((and adaptive-fill-regexp
22761 ;; Locally disable
22762 ;; `adaptive-fill-function' to let
22763 ;; `fill-context-prefix' handle
22764 ;; `adaptive-fill-regexp' variable.
22765 (let (adaptive-fill-function)
22766 (fill-context-prefix
22767 post-affiliated
22768 (org-element-property :end element)))))
22769 ((looking-at "[ \t]+") (match-string 0))
22770 (t "")))))
22771 (comment-block
22772 ;; Only fill contents if P is within block boundaries.
22773 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22774 (forward-line)
22775 (point)))
22776 (cend (save-excursion
22777 (goto-char (org-element-property :end element))
22778 (skip-chars-backward " \r\t\n")
22779 (line-beginning-position))))
22780 (when (and (>= p cbeg) (< p cend))
22781 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22782 (match-string 0)
22783 "")))))))))))
22785 (declare-function message-goto-body "message" ())
22786 (defvar message-cite-prefix-regexp) ; From message.el
22787 (defun org-fill-paragraph (&optional justify)
22788 "Fill element at point, when applicable.
22790 This function only applies to comment blocks, comments, example
22791 blocks and paragraphs. Also, as a special case, re-align table
22792 when point is at one.
22794 If JUSTIFY is non-nil (interactively, with prefix argument),
22795 justify as well. If `sentence-end-double-space' is non-nil, then
22796 period followed by one space does not end a sentence, so don't
22797 break a line there. The variable `fill-column' controls the
22798 width for filling.
22800 For convenience, when point is at a plain list, an item or
22801 a footnote definition, try to fill the first paragraph within."
22802 (interactive)
22803 (if (and (derived-mode-p 'message-mode)
22804 (or (not (message-in-body-p))
22805 (save-excursion (move-beginning-of-line 1)
22806 (looking-at message-cite-prefix-regexp))))
22807 ;; First ensure filling is correct in message-mode.
22808 (let ((fill-paragraph-function
22809 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22810 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22811 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22812 (paragraph-separate
22813 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22814 (fill-paragraph nil))
22815 (with-syntax-table org-mode-transpose-word-syntax-table
22816 ;; Move to end of line in order to get the first paragraph
22817 ;; within a plain list or a footnote definition.
22818 (let ((element (save-excursion
22819 (end-of-line)
22820 (or (ignore-errors (org-element-at-point))
22821 (user-error "An element cannot be parsed line %d"
22822 (line-number-at-pos (point)))))))
22823 ;; First check if point is in a blank line at the beginning of
22824 ;; the buffer. In that case, ignore filling.
22825 (case (org-element-type element)
22826 ;; Use major mode filling function is src blocks.
22827 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22828 ;; Align Org tables, leave table.el tables as-is.
22829 (table-row (org-table-align) t)
22830 (table
22831 (when (eq (org-element-property :type element) 'org)
22832 (save-excursion
22833 (goto-char (org-element-property :post-affiliated element))
22834 (org-table-align)))
22836 (paragraph
22837 ;; Paragraphs may contain `line-break' type objects.
22838 (let ((beg (max (point-min)
22839 (org-element-property :contents-begin element)))
22840 (end (min (point-max)
22841 (org-element-property :contents-end element))))
22842 ;; Do nothing if point is at an affiliated keyword.
22843 (if (< (line-end-position) beg) t
22844 (when (derived-mode-p 'message-mode)
22845 ;; In `message-mode', do not fill following citation
22846 ;; in current paragraph nor text before message body.
22847 (let ((body-start (save-excursion (message-goto-body))))
22848 (when body-start (setq beg (max body-start beg))))
22849 (when (save-excursion
22850 (re-search-forward
22851 (concat "^" message-cite-prefix-regexp) end t))
22852 (setq end (match-beginning 0))))
22853 ;; Fill paragraph, taking line breaks into account.
22854 ;; For that, insert hard newline characters after line
22855 ;; breaks and activate `use-hard-newlines'.
22856 (save-excursion
22857 (goto-char beg)
22858 (while (re-search-forward "\\\\\\\\[ \t]*\\(\n\\)" end t)
22859 (when (eq 'line-break
22860 (org-element-type
22861 (progn (backward-char)
22862 (save-match-data (org-element-context)))))
22863 (replace-match hard-newline nil nil nil 1)))
22864 (let ((use-hard-newlines t)) (fill-region beg end justify)))
22865 t)))
22866 ;; Contents of `comment-block' type elements should be
22867 ;; filled as plain text, but only if point is within block
22868 ;; markers.
22869 (comment-block
22870 (let* ((case-fold-search t)
22871 (beg (save-excursion
22872 (goto-char (org-element-property :begin element))
22873 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22874 (forward-line)
22875 (point)))
22876 (end (save-excursion
22877 (goto-char (org-element-property :end element))
22878 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22879 (line-beginning-position))))
22880 (if (or (< (point) beg) (> (point) end)) t
22881 (fill-region-as-paragraph
22882 (save-excursion (end-of-line)
22883 (re-search-backward "^[ \t]*$" beg 'move)
22884 (line-beginning-position))
22885 (save-excursion (beginning-of-line)
22886 (re-search-forward "^[ \t]*$" end 'move)
22887 (line-beginning-position))
22888 justify))))
22889 ;; Fill comments.
22890 (comment
22891 (let ((begin (org-element-property :post-affiliated element))
22892 (end (org-element-property :end element)))
22893 (when (and (>= (point) begin) (<= (point) end))
22894 (let ((begin (save-excursion
22895 (end-of-line)
22896 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22897 (progn (forward-line) (point))
22898 begin)))
22899 (end (save-excursion
22900 (end-of-line)
22901 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22902 (1- (line-beginning-position))
22903 (skip-chars-backward " \r\t\n")
22904 (line-end-position)))))
22905 ;; Do not fill comments when at a blank line.
22906 (when (> end begin)
22907 (let ((fill-prefix
22908 (save-excursion
22909 (beginning-of-line)
22910 (looking-at "[ \t]*#")
22911 (let ((comment-prefix (match-string 0)))
22912 (goto-char (match-end 0))
22913 (if (looking-at adaptive-fill-regexp)
22914 (concat comment-prefix (match-string 0))
22915 (concat comment-prefix " "))))))
22916 (save-excursion
22917 (fill-region-as-paragraph begin end justify))))))
22919 ;; Ignore every other element.
22920 (otherwise t))))))
22922 (defun org-auto-fill-function ()
22923 "Auto-fill function."
22924 ;; Check if auto-filling is meaningful.
22925 (let ((fc (current-fill-column)))
22926 (when (and fc (> (current-column) fc))
22927 (let* ((fill-prefix (org-adaptive-fill-function))
22928 ;; Enforce empty fill prefix, if required. Otherwise, it
22929 ;; will be computed again.
22930 (adaptive-fill-mode (not (equal fill-prefix ""))))
22931 (when fill-prefix (do-auto-fill))))))
22933 (defun org-comment-line-break-function (&optional soft)
22934 "Break line at point and indent, continuing comment if within one.
22935 The inserted newline is marked hard if variable
22936 `use-hard-newlines' is true, unless optional argument SOFT is
22937 non-nil."
22938 (if soft (insert-and-inherit ?\n) (newline 1))
22939 (save-excursion (forward-char -1) (delete-horizontal-space))
22940 (delete-horizontal-space)
22941 (indent-to-left-margin)
22942 (insert-before-markers-and-inherit fill-prefix))
22945 ;;; Fixed Width Areas
22947 (defun org-toggle-fixed-width ()
22948 "Toggle fixed-width markup.
22950 Add or remove fixed-width markup on current line, whenever it
22951 makes sense. Return an error otherwise.
22953 If a region is active and if it contains only fixed-width areas
22954 or blank lines, remove all fixed-width markup in it. If the
22955 region contains anything else, convert all non-fixed-width lines
22956 to fixed-width ones.
22958 Blank lines at the end of the region are ignored unless the
22959 region only contains such lines."
22960 (interactive)
22961 (if (not (org-region-active-p))
22962 ;; No region:
22964 ;; Remove fixed width marker only in a fixed-with element.
22966 ;; Add fixed width maker in paragraphs, in blank lines after
22967 ;; elements or at the beginning of a headline or an inlinetask,
22968 ;; and before any one-line elements (e.g., a clock).
22969 (progn
22970 (beginning-of-line)
22971 (let* ((element (org-element-at-point))
22972 (type (org-element-type element)))
22973 (cond
22974 ((and (eq type 'fixed-width)
22975 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22976 (replace-match
22977 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22978 ((and (memq type '(babel-call clock comment diary-sexp headline
22979 horizontal-rule keyword paragraph
22980 planning))
22981 (or (not (org-element-property :post-affiliated element))
22982 (<= (org-element-property :post-affiliated element)
22983 (point))))
22984 (skip-chars-forward " \t")
22985 (insert ": "))
22986 ((and (org-looking-at-p "[ \t]*$")
22987 (or (eq type 'inlinetask)
22988 (save-excursion
22989 (skip-chars-forward " \r\t\n")
22990 (<= (org-element-property :end element) (point)))))
22991 (delete-region (point) (line-end-position))
22992 (org-indent-line)
22993 (insert ": "))
22994 (t (user-error "Cannot insert a fixed-width line here")))))
22995 ;; Region active.
22996 (let* ((begin (save-excursion
22997 (goto-char (region-beginning))
22998 (line-beginning-position)))
22999 (end (copy-marker
23000 (save-excursion
23001 (goto-char (region-end))
23002 (unless (eolp) (beginning-of-line))
23003 (if (save-excursion (re-search-backward "\\S-" begin t))
23004 (progn (skip-chars-backward " \r\t\n") (point))
23005 (point)))))
23006 (all-fixed-width-p
23007 (catch 'not-all-p
23008 (save-excursion
23009 (goto-char begin)
23010 (skip-chars-forward " \r\t\n")
23011 (when (eobp) (throw 'not-all-p nil))
23012 (while (< (point) end)
23013 (let ((element (org-element-at-point)))
23014 (if (eq (org-element-type element) 'fixed-width)
23015 (goto-char (org-element-property :end element))
23016 (throw 'not-all-p nil))))
23017 t))))
23018 (if all-fixed-width-p
23019 (save-excursion
23020 (goto-char begin)
23021 (while (< (point) end)
23022 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23023 (replace-match
23024 "" nil nil nil
23025 (if (= (line-end-position) (match-end 0)) 0 1)))
23026 (forward-line)))
23027 (let ((min-ind (point-max)))
23028 ;; Find minimum indentation across all lines.
23029 (save-excursion
23030 (goto-char begin)
23031 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23032 (setq min-ind 0)
23033 (catch 'zerop
23034 (while (< (point) end)
23035 (unless (org-looking-at-p "[ \t]*$")
23036 (let ((ind (org-get-indentation)))
23037 (setq min-ind (min min-ind ind))
23038 (when (zerop ind) (throw 'zerop t))))
23039 (forward-line)))))
23040 ;; Loop over all lines and add fixed-width markup everywhere
23041 ;; but in fixed-width lines.
23042 (save-excursion
23043 (goto-char begin)
23044 (while (< (point) end)
23045 (cond
23046 ((org-at-heading-p)
23047 (insert ": ")
23048 (forward-line)
23049 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23050 (insert ":")
23051 (forward-line)))
23052 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23053 (let* ((element (org-element-at-point))
23054 (element-end (org-element-property :end element)))
23055 (if (eq (org-element-type element) 'fixed-width)
23056 (progn (goto-char element-end)
23057 (skip-chars-backward " \r\t\n")
23058 (forward-line))
23059 (let ((limit (min end element-end)))
23060 (while (< (point) limit)
23061 (org-move-to-column min-ind t)
23062 (insert ": ")
23063 (forward-line))))))
23065 (org-move-to-column min-ind t)
23066 (insert ": ")
23067 (forward-line)))))))
23068 (set-marker end nil))))
23071 ;;; Comments
23073 ;; Org comments syntax is quite complex. It requires the entire line
23074 ;; to be just a comment. Also, even with the right syntax at the
23075 ;; beginning of line, some some elements (i.e. verse-block or
23076 ;; example-block) don't accept comments. Usual Emacs comment commands
23077 ;; cannot cope with those requirements. Therefore, Org replaces them.
23079 ;; Org still relies on `comment-dwim', but cannot trust
23080 ;; `comment-only-p'. So, `comment-region-function' and
23081 ;; `uncomment-region-function' both point
23082 ;; to`org-comment-or-uncomment-region'. Eventually,
23083 ;; `org-insert-comment' takes care of insertion of comments at the
23084 ;; beginning of line.
23086 ;; `org-setup-comments-handling' install comments related variables
23087 ;; during `org-mode' initialization.
23089 (defun org-setup-comments-handling ()
23090 (interactive)
23091 (org-set-local 'comment-use-syntax nil)
23092 (org-set-local 'comment-start "# ")
23093 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23094 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23095 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23096 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23098 (defun org-insert-comment ()
23099 "Insert an empty comment above current line.
23100 If the line is empty, insert comment at its beginning. When
23101 point is within a source block, comment according to the related
23102 major mode."
23103 (if (let ((element (org-element-at-point)))
23104 (and (eq (org-element-type element) 'src-block)
23105 (< (save-excursion
23106 (goto-char (org-element-property :post-affiliated element))
23107 (line-end-position))
23108 (point))
23109 (> (save-excursion
23110 (goto-char (org-element-property :end element))
23111 (skip-chars-backward " \r\t\n")
23112 (line-beginning-position))
23113 (point))))
23114 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23115 (beginning-of-line)
23116 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23117 (open-line 1))
23118 (org-indent-line)
23119 (insert "# ")))
23121 (defvar comment-empty-lines) ; From newcomment.el.
23122 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23123 "Comment or uncomment each non-blank line in the region.
23124 Uncomment each non-blank line between BEG and END if it only
23125 contains commented lines. Otherwise, comment them. If region is
23126 strictly within a source block, use appropriate comment syntax."
23127 (if (let ((element (org-element-at-point)))
23128 (and (eq (org-element-type element) 'src-block)
23129 (< (save-excursion
23130 (goto-char (org-element-property :post-affiliated element))
23131 (line-end-position))
23132 beg)
23133 (>= (save-excursion
23134 (goto-char (org-element-property :end element))
23135 (skip-chars-backward " \r\t\n")
23136 (line-beginning-position))
23137 end)))
23138 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23139 (save-restriction
23140 ;; Restrict region
23141 (narrow-to-region (save-excursion (goto-char beg)
23142 (skip-chars-forward " \r\t\n" end)
23143 (line-beginning-position))
23144 (save-excursion (goto-char end)
23145 (skip-chars-backward " \r\t\n" beg)
23146 (line-end-position)))
23147 (let ((uncommentp
23148 ;; UNCOMMENTP is non-nil when every non blank line between
23149 ;; BEG and END is a comment.
23150 (save-excursion
23151 (goto-char (point-min))
23152 (while (and (not (eobp))
23153 (let ((element (org-element-at-point)))
23154 (and (eq (org-element-type element) 'comment)
23155 (goto-char (min (point-max)
23156 (org-element-property
23157 :end element)))))))
23158 (eobp))))
23159 (if uncommentp
23160 ;; Only blank lines and comments in region: uncomment it.
23161 (save-excursion
23162 (goto-char (point-min))
23163 (while (not (eobp))
23164 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23165 (replace-match "" nil nil nil 1))
23166 (forward-line)))
23167 ;; Comment each line in region.
23168 (let ((min-indent (point-max)))
23169 ;; First find the minimum indentation across all lines.
23170 (save-excursion
23171 (goto-char (point-min))
23172 (while (and (not (eobp)) (not (zerop min-indent)))
23173 (unless (looking-at "[ \t]*$")
23174 (setq min-indent (min min-indent (current-indentation))))
23175 (forward-line)))
23176 ;; Then loop over all lines.
23177 (save-excursion
23178 (goto-char (point-min))
23179 (while (not (eobp))
23180 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23181 ;; Don't get fooled by invisible text (e.g. link path)
23182 ;; when moving to column MIN-INDENT.
23183 (let ((buffer-invisibility-spec nil))
23184 (org-move-to-column min-indent t))
23185 (insert comment-start))
23186 (forward-line)))))))))
23188 (defun org-comment-dwim (arg)
23189 "Call `comment-dwim' within a source edit buffer if needed."
23190 (interactive "*P")
23191 (if (org-in-src-block-p)
23192 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23193 (call-interactively 'comment-dwim)))
23196 ;;; Planning
23198 ;; This section contains tools to operate on timestamp objects, as
23199 ;; returned by, e.g. `org-element-context'.
23201 (defun org-timestamp-has-time-p (timestamp)
23202 "Non-nil when TIMESTAMP has a time specified."
23203 (org-element-property :hour-start timestamp))
23205 (defun org-timestamp-format (timestamp format &optional end utc)
23206 "Format a TIMESTAMP element into a string.
23208 FORMAT is a format specifier to be passed to
23209 `format-time-string'.
23211 When optional argument END is non-nil, use end of date-range or
23212 time-range, if possible.
23214 When optional argument UTC is non-nil, time will be expressed as
23215 Universal Time."
23216 (format-time-string
23217 format
23218 (apply 'encode-time
23219 (cons 0
23220 (mapcar
23221 (lambda (prop) (or (org-element-property prop timestamp) 0))
23222 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23223 '(:minute-start :hour-start :day-start :month-start
23224 :year-start)))))
23225 utc))
23227 (defun org-timestamp-split-range (timestamp &optional end)
23228 "Extract a timestamp object from a date or time range.
23230 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23231 the end of the range. Otherwise, extract its start.
23233 Return a new timestamp object sharing the same parent as
23234 TIMESTAMP."
23235 (let ((type (org-element-property :type timestamp)))
23236 (if (memq type '(active inactive diary)) timestamp
23237 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23238 ;; Set new type.
23239 (org-element-put-property
23240 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23241 ;; Copy start properties over end properties if END is
23242 ;; non-nil. Otherwise, copy end properties over `start' ones.
23243 (let ((p-alist '((:minute-start . :minute-end)
23244 (:hour-start . :hour-end)
23245 (:day-start . :day-end)
23246 (:month-start . :month-end)
23247 (:year-start . :year-end))))
23248 (dolist (p-cell p-alist)
23249 (org-element-put-property
23250 split-ts
23251 (funcall (if end 'car 'cdr) p-cell)
23252 (org-element-property
23253 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23254 ;; Eventually refresh `:raw-value'.
23255 (org-element-put-property split-ts :raw-value nil)
23256 (org-element-put-property
23257 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23259 (defun org-timestamp-translate (timestamp &optional boundary)
23260 "Apply `org-translate-time' on a TIMESTAMP object.
23261 When optional argument BOUNDARY is non-nil, it is either the
23262 symbol `start' or `end'. In this case, only translate the
23263 starting or ending part of TIMESTAMP if it is a date or time
23264 range. Otherwise, translate both parts."
23265 (if (and (not boundary)
23266 (memq (org-element-property :type timestamp)
23267 '(active-range inactive-range)))
23268 (concat
23269 (org-translate-time
23270 (org-element-property :raw-value
23271 (org-timestamp-split-range timestamp)))
23272 "--"
23273 (org-translate-time
23274 (org-element-property :raw-value
23275 (org-timestamp-split-range timestamp t))))
23276 (org-translate-time
23277 (org-element-property
23278 :raw-value
23279 (if (not boundary) timestamp
23280 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23284 ;;; Other stuff.
23286 (defun org-reftex-citation ()
23287 "Use reftex-citation to insert a citation into the buffer.
23288 This looks for a line like
23290 #+BIBLIOGRAPHY: foo plain option:-d
23292 and derives from it that foo.bib is the bibliography file relevant
23293 for this document. It then installs the necessary environment for RefTeX
23294 to work in this buffer and calls `reftex-citation' to insert a citation
23295 into the buffer.
23297 Export of such citations to both LaTeX and HTML is handled by the contributed
23298 package ox-bibtex by Taru Karttunen."
23299 (interactive)
23300 (let ((reftex-docstruct-symbol 'rds)
23301 (reftex-cite-format "\\cite{%l}")
23302 rds bib)
23303 (save-excursion
23304 (save-restriction
23305 (widen)
23306 (let ((case-fold-search t)
23307 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23308 (if (not (save-excursion
23309 (or (re-search-forward re nil t)
23310 (re-search-backward re nil t))))
23311 (user-error "No bibliography defined in file")
23312 (setq bib (concat (match-string 1) ".bib")
23313 rds (list (list 'bib bib)))))))
23314 (call-interactively 'reftex-citation)))
23316 ;;;; Functions extending outline functionality
23318 (defun org-beginning-of-line (&optional arg)
23319 "Go to the beginning of the current line. If that is invisible, continue
23320 to a visible line beginning. This makes the function of C-a more intuitive.
23321 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23322 first attempt, and only move to after the tags when the cursor is already
23323 beyond the end of the headline."
23324 (interactive "P")
23325 (let ((pos (point))
23326 (special (if (consp org-special-ctrl-a/e)
23327 (car org-special-ctrl-a/e)
23328 org-special-ctrl-a/e))
23329 deactivate-mark refpos)
23330 (if (org-bound-and-true-p visual-line-mode)
23331 (beginning-of-visual-line 1)
23332 (beginning-of-line 1))
23333 (if (and arg (fboundp 'move-beginning-of-line))
23334 (call-interactively 'move-beginning-of-line)
23335 (if (bobp)
23337 (backward-char 1)
23338 (if (org-truely-invisible-p)
23339 (while (and (not (bobp)) (org-truely-invisible-p))
23340 (backward-char 1)
23341 (beginning-of-line 1))
23342 (forward-char 1))))
23343 (when special
23344 (cond
23345 ((and (looking-at org-complex-heading-regexp)
23346 (= (char-after (match-end 1)) ?\ ))
23347 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23348 (point-at-eol)))
23349 (goto-char
23350 (if (eq special t)
23351 (cond ((> pos refpos) refpos)
23352 ((= pos (point)) refpos)
23353 (t (point)))
23354 (cond ((> pos (point)) (point))
23355 ((not (eq last-command this-command)) (point))
23356 (t refpos)))))
23357 ((org-at-item-p)
23358 ;; Being at an item and not looking at an the item means point
23359 ;; was previously moved to beginning of a visual line, which
23360 ;; doesn't contain the item. Therefore, do nothing special,
23361 ;; just stay here.
23362 (when (looking-at org-list-full-item-re)
23363 ;; Set special position at first white space character after
23364 ;; bullet, and check-box, if any.
23365 (let ((after-bullet
23366 (let ((box (match-end 3)))
23367 (if (not box) (match-end 1)
23368 (let ((after (char-after box)))
23369 (if (and after (= after ? )) (1+ box) box))))))
23370 ;; Special case: Move point to special position when
23371 ;; currently after it or at beginning of line.
23372 (if (eq special t)
23373 (when (or (> pos after-bullet) (= (point) pos))
23374 (goto-char after-bullet))
23375 ;; Reversed case: Move point to special position when
23376 ;; point was already at beginning of line and command is
23377 ;; repeated.
23378 (when (and (= (point) pos) (eq last-command this-command))
23379 (goto-char after-bullet))))))))
23380 (org-no-warnings
23381 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23382 (setq disable-point-adjustment
23383 (or (not (invisible-p (point)))
23384 (not (invisible-p (max (point-min) (1- (point))))))))
23386 (defun org-end-of-line (&optional arg)
23387 "Go to the end of the line.
23388 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23389 tags on the first attempt, and only move to after the tags when
23390 the cursor is already beyond the end of the headline."
23391 (interactive "P")
23392 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23393 org-special-ctrl-a/e))
23394 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23395 'end-of-visual-line)
23396 ((fboundp 'move-end-of-line) 'move-end-of-line)
23397 (t 'end-of-line)))
23398 deactivate-mark)
23399 (if (or (not special) arg) (call-interactively move-fun)
23400 (let* ((element (save-excursion (beginning-of-line)
23401 (org-element-at-point)))
23402 (type (org-element-type element)))
23403 (cond
23404 ((memq type '(headline inlinetask))
23405 (let ((pos (point)))
23406 (beginning-of-line 1)
23407 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23408 (if (eq special t)
23409 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23410 (goto-char (match-beginning 1))
23411 (goto-char (match-end 0)))
23412 (if (or (< pos (match-end 0))
23413 (not (eq this-command last-command)))
23414 (goto-char (match-end 0))
23415 (goto-char (match-beginning 1))))
23416 (call-interactively move-fun))))
23417 ((outline-invisible-p (line-end-position))
23418 ;; If element is hidden, `move-end-of-line' would put point
23419 ;; after it. Use `end-of-line' to stay on current line.
23420 (call-interactively 'end-of-line))
23421 (t (call-interactively move-fun)))))
23422 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23423 (setq disable-point-adjustment
23424 (or (not (invisible-p (point)))
23425 (not (invisible-p (max (point-min) (1- (point))))))))
23427 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23428 (define-key org-mode-map "\C-e" 'org-end-of-line)
23430 (defun org-backward-sentence (&optional arg)
23431 "Go to beginning of sentence, or beginning of table field.
23432 This will call `backward-sentence' or `org-table-beginning-of-field',
23433 depending on context."
23434 (interactive "P")
23435 (cond
23436 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23437 (t (call-interactively 'backward-sentence))))
23439 (defun org-forward-sentence (&optional arg)
23440 "Go to end of sentence, or end of table field.
23441 This will call `forward-sentence' or `org-table-end-of-field',
23442 depending on context."
23443 (interactive "P")
23444 (cond
23445 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23446 (t (call-interactively 'forward-sentence))))
23448 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23449 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23451 (defun org-kill-line (&optional arg)
23452 "Kill line, to tags or end of line."
23453 (interactive "P")
23454 (cond
23455 ((or (not org-special-ctrl-k)
23456 (bolp)
23457 (not (org-at-heading-p)))
23458 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23459 org-ctrl-k-protect-subtree)
23460 (if (or (eq org-ctrl-k-protect-subtree 'error)
23461 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23462 (user-error "C-k aborted as it would kill a hidden subtree")))
23463 (call-interactively
23464 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23465 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23466 (kill-region (point) (match-beginning 1))
23467 (org-set-tags nil t))
23468 (t (kill-region (point) (point-at-eol)))))
23470 (define-key org-mode-map "\C-k" 'org-kill-line)
23472 (defun org-yank (&optional arg)
23473 "Yank. If the kill is a subtree, treat it specially.
23474 This command will look at the current kill and check if is a single
23475 subtree, or a series of subtrees[1]. If it passes the test, and if the
23476 cursor is at the beginning of a line or after the stars of a currently
23477 empty headline, then the yank is handled specially. How exactly depends
23478 on the value of the following variables, both set by default.
23480 `org-yank-folded-subtrees'
23481 When set, the subtree(s) will be folded after insertion, but only
23482 if doing so would now swallow text after the yanked text.
23484 `org-yank-adjusted-subtrees'
23485 When set, the subtree will be promoted or demoted in order to
23486 fit into the local outline tree structure, which means that the
23487 level will be adjusted so that it becomes the smaller one of the
23488 two *visible* surrounding headings.
23490 Any prefix to this command will cause `yank' to be called directly with
23491 no special treatment. In particular, a simple \\[universal-argument] prefix \
23492 will just
23493 plainly yank the text as it is.
23495 \[1] The test checks if the first non-white line is a heading
23496 and if there are no other headings with fewer stars."
23497 (interactive "P")
23498 (org-yank-generic 'yank arg))
23500 (defun org-yank-generic (command arg)
23501 "Perform some yank-like command.
23503 This function implements the behavior described in the `org-yank'
23504 documentation. However, it has been generalized to work for any
23505 interactive command with similar behavior."
23507 ;; pretend to be command COMMAND
23508 (setq this-command command)
23510 (if arg
23511 (call-interactively command)
23513 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23514 (and (org-kill-is-subtree-p)
23515 (or (bolp)
23516 (and (looking-at "[ \t]*$")
23517 (string-match
23518 "\\`\\*+\\'"
23519 (buffer-substring (point-at-bol) (point)))))))
23520 swallowp)
23521 (cond
23522 ((and subtreep org-yank-folded-subtrees)
23523 (let ((beg (point))
23524 end)
23525 (if (and subtreep org-yank-adjusted-subtrees)
23526 (org-paste-subtree nil nil 'for-yank)
23527 (call-interactively command))
23529 (setq end (point))
23530 (goto-char beg)
23531 (when (and (bolp) subtreep
23532 (not (setq swallowp
23533 (org-yank-folding-would-swallow-text beg end))))
23534 (org-with-limited-levels
23535 (or (looking-at org-outline-regexp)
23536 (re-search-forward org-outline-regexp-bol end t))
23537 (while (and (< (point) end) (looking-at org-outline-regexp))
23538 (hide-subtree)
23539 (org-cycle-show-empty-lines 'folded)
23540 (condition-case nil
23541 (outline-forward-same-level 1)
23542 (error (goto-char end))))))
23543 (when swallowp
23544 (message
23545 "Inserted text not folded because that would swallow text"))
23547 (goto-char end)
23548 (skip-chars-forward " \t\n\r")
23549 (beginning-of-line 1)
23550 (push-mark beg 'nomsg)))
23551 ((and subtreep org-yank-adjusted-subtrees)
23552 (let ((beg (point-at-bol)))
23553 (org-paste-subtree nil nil 'for-yank)
23554 (push-mark beg 'nomsg)))
23556 (call-interactively command))))))
23558 (defun org-yank-folding-would-swallow-text (beg end)
23559 "Would hide-subtree at BEG swallow any text after END?"
23560 (let (level)
23561 (org-with-limited-levels
23562 (save-excursion
23563 (goto-char beg)
23564 (when (or (looking-at org-outline-regexp)
23565 (re-search-forward org-outline-regexp-bol end t))
23566 (setq level (org-outline-level)))
23567 (goto-char end)
23568 (skip-chars-forward " \t\r\n\v\f")
23569 (if (or (eobp)
23570 (and (bolp) (looking-at org-outline-regexp)
23571 (<= (org-outline-level) level)))
23572 nil ; Nothing would be swallowed
23573 t))))) ; something would swallow
23575 (define-key org-mode-map "\C-y" 'org-yank)
23577 (defun org-truely-invisible-p ()
23578 "Check if point is at a character currently not visible.
23579 This version does not only check the character property, but also
23580 `visible-mode'."
23581 ;; Early versions of noutline don't have `outline-invisible-p'.
23582 (if (org-bound-and-true-p visible-mode)
23584 (outline-invisible-p)))
23586 (defun org-invisible-p2 ()
23587 "Check if point is at a character currently not visible."
23588 (save-excursion
23589 (if (and (eolp) (not (bobp))) (backward-char 1))
23590 ;; Early versions of noutline don't have `outline-invisible-p'.
23591 (outline-invisible-p)))
23593 (defun org-back-to-heading (&optional invisible-ok)
23594 "Call `outline-back-to-heading', but provide a better error message."
23595 (condition-case nil
23596 (outline-back-to-heading invisible-ok)
23597 (error (error "Before first headline at position %d in buffer %s"
23598 (point) (current-buffer)))))
23600 (defun org-before-first-heading-p ()
23601 "Before first heading?"
23602 (save-excursion
23603 (end-of-line)
23604 (null (re-search-backward org-outline-regexp-bol nil t))))
23606 (defun org-at-heading-p (&optional ignored)
23607 (outline-on-heading-p t))
23608 ;; Compatibility alias with Org versions < 7.8.03
23609 (defalias 'org-on-heading-p 'org-at-heading-p)
23611 (defun org-in-commented-heading-p (&optional no-inheritance)
23612 "Non-nil if point is under a commented heading.
23613 This function also checks ancestors of the current headline,
23614 unless optional argument NO-INHERITANCE is non-nil."
23615 (cond
23616 ((org-before-first-heading-p) nil)
23617 ((let ((headline (nth 4 (org-heading-components))))
23618 (and headline
23619 (let ((case-fold-search nil))
23620 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23621 headline)))))
23622 (no-inheritance nil)
23624 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23626 (defun org-at-comment-p nil
23627 "Is cursor in a commented line?"
23628 (save-excursion
23629 (save-match-data
23630 (beginning-of-line)
23631 (looking-at "^[ \t]*# "))))
23633 (defun org-at-drawer-p nil
23634 "Is cursor at a drawer keyword?"
23635 (save-excursion
23636 (move-beginning-of-line 1)
23637 (looking-at org-drawer-regexp)))
23639 (defun org-at-block-p nil
23640 "Is cursor at a block keyword?"
23641 (save-excursion
23642 (move-beginning-of-line 1)
23643 (looking-at org-block-regexp)))
23645 (defun org-point-at-end-of-empty-headline ()
23646 "If point is at the end of an empty headline, return t, else nil.
23647 If the heading only contains a TODO keyword, it is still still considered
23648 empty."
23649 (and (looking-at "[ \t]*$")
23650 (when org-todo-line-regexp
23651 (save-excursion
23652 (beginning-of-line 1)
23653 (let ((case-fold-search nil))
23654 (looking-at org-todo-line-regexp)
23655 (string= (match-string 3) ""))))))
23657 (defun org-at-heading-or-item-p ()
23658 (or (org-at-heading-p) (org-at-item-p)))
23660 (defun org-at-target-p ()
23661 (or (org-in-regexp org-radio-target-regexp)
23662 (org-in-regexp org-target-regexp)))
23663 ;; Compatibility alias with Org versions < 7.8.03
23664 (defalias 'org-on-target-p 'org-at-target-p)
23666 (defun org-up-heading-all (arg)
23667 "Move to the heading line of which the present line is a subheading.
23668 This function considers both visible and invisible heading lines.
23669 With argument, move up ARG levels."
23670 (if (fboundp 'outline-up-heading-all)
23671 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23672 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23674 (defun org-up-heading-safe ()
23675 "Move to the heading line of which the present line is a subheading.
23676 This version will not throw an error. It will return the level of the
23677 headline found, or nil if no higher level is found.
23679 Also, this function will be a lot faster than `outline-up-heading',
23680 because it relies on stars being the outline starters. This can really
23681 make a significant difference in outlines with very many siblings."
23682 (let (start-level re)
23683 (org-back-to-heading t)
23684 (setq start-level (funcall outline-level))
23685 (if (equal start-level 1)
23687 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23688 (if (re-search-backward re nil t)
23689 (funcall outline-level)))))
23691 (defun org-first-sibling-p ()
23692 "Is this heading the first child of its parents?"
23693 (interactive)
23694 (let ((re org-outline-regexp-bol)
23695 level l)
23696 (unless (org-at-heading-p t)
23697 (user-error "Not at a heading"))
23698 (setq level (funcall outline-level))
23699 (save-excursion
23700 (if (not (re-search-backward re nil t))
23702 (setq l (funcall outline-level))
23703 (< l level)))))
23705 (defun org-goto-sibling (&optional previous)
23706 "Goto the next sibling, even if it is invisible.
23707 When PREVIOUS is set, go to the previous sibling instead. Returns t
23708 when a sibling was found. When none is found, return nil and don't
23709 move point."
23710 (let ((fun (if previous 're-search-backward 're-search-forward))
23711 (pos (point))
23712 (re org-outline-regexp-bol)
23713 level l)
23714 (when (ignore-errors (org-back-to-heading t))
23715 (setq level (funcall outline-level))
23716 (catch 'exit
23717 (or previous (forward-char 1))
23718 (while (funcall fun re nil t)
23719 (setq l (funcall outline-level))
23720 (when (< l level) (goto-char pos) (throw 'exit nil))
23721 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23722 (goto-char pos)
23723 nil))))
23725 (defun org-show-siblings ()
23726 "Show all siblings of the current headline."
23727 (save-excursion
23728 (while (org-goto-sibling) (org-flag-heading nil)))
23729 (save-excursion
23730 (while (org-goto-sibling 'previous)
23731 (org-flag-heading nil))))
23733 (defun org-goto-first-child ()
23734 "Goto the first child, even if it is invisible.
23735 Return t when a child was found. Otherwise don't move point and
23736 return nil."
23737 (let (level (pos (point)) (re org-outline-regexp-bol))
23738 (when (ignore-errors (org-back-to-heading t))
23739 (setq level (outline-level))
23740 (forward-char 1)
23741 (if (and (re-search-forward re nil t) (> (outline-level) level))
23742 (progn (goto-char (match-beginning 0)) t)
23743 (goto-char pos) nil))))
23745 (defun org-show-hidden-entry ()
23746 "Show an entry where even the heading is hidden."
23747 (save-excursion
23748 (org-show-entry)))
23750 (defun org-flag-heading (flag &optional entry)
23751 "Flag the current heading. FLAG non-nil means make invisible.
23752 When ENTRY is non-nil, show the entire entry."
23753 (save-excursion
23754 (org-back-to-heading t)
23755 ;; Check if we should show the entire entry
23756 (if entry
23757 (progn
23758 (org-show-entry)
23759 (save-excursion
23760 (and (outline-next-heading)
23761 (org-flag-heading nil))))
23762 (outline-flag-region (max (point-min) (1- (point)))
23763 (save-excursion (outline-end-of-heading) (point))
23764 flag))))
23766 (defun org-get-next-sibling ()
23767 "Move to next heading of the same level, and return point.
23768 If there is no such heading, return nil.
23769 This is like outline-next-sibling, but invisible headings are ok."
23770 (let ((level (funcall outline-level)))
23771 (outline-next-heading)
23772 (while (and (not (eobp)) (> (funcall outline-level) level))
23773 (outline-next-heading))
23774 (if (or (eobp) (< (funcall outline-level) level))
23776 (point))))
23778 (defun org-get-last-sibling ()
23779 "Move to previous heading of the same level, and return point.
23780 If there is no such heading, return nil."
23781 (let ((opoint (point))
23782 (level (funcall outline-level)))
23783 (outline-previous-heading)
23784 (when (and (/= (point) opoint) (outline-on-heading-p t))
23785 (while (and (> (funcall outline-level) level)
23786 (not (bobp)))
23787 (outline-previous-heading))
23788 (if (< (funcall outline-level) level)
23790 (point)))))
23792 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23793 "Goto to the end of a subtree."
23794 ;; This contains an exact copy of the original function, but it uses
23795 ;; `org-back-to-heading', to make it work also in invisible
23796 ;; trees. And is uses an invisible-ok argument.
23797 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23798 ;; Furthermore, when used inside Org, finding the end of a large subtree
23799 ;; with many children and grandchildren etc, this can be much faster
23800 ;; than the outline version.
23801 (org-back-to-heading invisible-ok)
23802 (let ((first t)
23803 (level (funcall outline-level)))
23804 (if (and (derived-mode-p 'org-mode) (< level 1000))
23805 ;; A true heading (not a plain list item), in Org-mode
23806 ;; This means we can easily find the end by looking
23807 ;; only for the right number of stars. Using a regexp to do
23808 ;; this is so much faster than using a Lisp loop.
23809 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23810 (forward-char 1)
23811 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23812 ;; something else, do it the slow way
23813 (while (and (not (eobp))
23814 (or first (> (funcall outline-level) level)))
23815 (setq first nil)
23816 (outline-next-heading)))
23817 (unless to-heading
23818 (if (memq (preceding-char) '(?\n ?\^M))
23819 (progn
23820 ;; Go to end of line before heading
23821 (forward-char -1)
23822 (if (memq (preceding-char) '(?\n ?\^M))
23823 ;; leave blank line before heading
23824 (forward-char -1))))))
23825 (point))
23827 (defun org-end-of-meta-data-and-drawers ()
23828 "Jump to the first text after meta data and drawers in the current entry.
23829 This will move over empty lines, lines with planning time stamps,
23830 clocking lines, and drawers."
23831 (org-back-to-heading t)
23832 (let ((end (save-excursion (outline-next-heading) (point)))
23833 (re (concat "\\(" org-drawer-regexp "\\)"
23834 "\\|" "[ \t]*" org-keyword-time-regexp)))
23835 (forward-line 1)
23836 (while (re-search-forward re end t)
23837 (if (not (match-end 1))
23838 ;; empty or planning line
23839 (forward-line 1)
23840 ;; a drawer, find the end
23841 (re-search-forward "^[ \t]*:END:" end 'move)
23842 (forward-line 1)))
23843 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23844 (point)))
23846 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23847 "Move forward to the ARG'th subheading at same level as this one.
23848 Stop at the first and last subheadings of a superior heading.
23849 Normally this only looks at visible headings, but when INVISIBLE-OK is
23850 non-nil it will also look at invisible ones."
23851 (interactive "p")
23852 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23853 (if (and arg (< arg 0))
23854 (goto-char (point-min))
23855 (outline-next-heading))
23856 (org-at-heading-p)
23857 (let ((level (- (match-end 0) (match-beginning 0) 1))
23858 (f (if (and arg (< arg 0))
23859 're-search-backward
23860 're-search-forward))
23861 (count (if arg (abs arg) 1))
23862 (result (point)))
23863 (while (and (prog1 (> count 0)
23864 (forward-char (if (and arg (< arg 0)) -1 1)))
23865 (funcall f org-outline-regexp-bol nil 'move))
23866 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23867 (cond ((< l level) (setq count 0))
23868 ((and (= l level)
23869 (or invisible-ok
23870 (progn
23871 (goto-char (line-beginning-position))
23872 (not (outline-invisible-p)))))
23873 (setq count (1- count))
23874 (when (eq l level)
23875 (setq result (point)))))))
23876 (goto-char result))
23877 (beginning-of-line 1)))
23879 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23880 "Move backward to the ARG'th subheading at same level as this one.
23881 Stop at the first and last subheadings of a superior heading."
23882 (interactive "p")
23883 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23885 (defun org-next-block (arg &optional backward block-regexp)
23886 "Jump to the next block.
23887 With a prefix argument ARG, jump forward ARG many source blocks.
23888 When BACKWARD is non-nil, jump to the previous block.
23889 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23890 (interactive "p")
23891 (let ((re (or block-regexp org-block-regexp))
23892 (re-search-fn (or (and backward 're-search-backward)
23893 're-search-forward)))
23894 (if (looking-at re) (forward-char 1))
23895 (condition-case nil
23896 (funcall re-search-fn re nil nil arg)
23897 (error (user-error "No %s code blocks"
23898 (if backward "previous" "further" ))))
23899 (goto-char (match-beginning 0)) (org-show-context)))
23901 (defun org-previous-block (arg &optional block-regexp)
23902 "Jump to the previous block.
23903 With a prefix argument ARG, jump backward ARG many source blocks.
23904 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23905 (interactive "p")
23906 (org-next-block arg t block-regexp))
23908 (defun org-forward-paragraph ()
23909 "Move forward to beginning of next paragraph or equivalent.
23911 The function moves point to the beginning of the next visible
23912 structural element, which can be a paragraph, a table, a list
23913 item, etc. It also provides some special moves for convenience:
23915 - On an affiliated keyword, jump to the beginning of the
23916 relative element.
23917 - On an item or a footnote definition, move to the second
23918 element inside, if any.
23919 - On a table or a property drawer, jump after it.
23920 - On a verse or source block, stop after blank lines."
23921 (interactive)
23922 (when (eobp) (user-error "Cannot move further down"))
23923 (let* ((deactivate-mark nil)
23924 (element (org-element-at-point))
23925 (type (org-element-type element))
23926 (post-affiliated (org-element-property :post-affiliated element))
23927 (contents-begin (org-element-property :contents-begin element))
23928 (contents-end (org-element-property :contents-end element))
23929 (end (let ((end (org-element-property :end element)) (parent element))
23930 (while (and (setq parent (org-element-property :parent parent))
23931 (= (org-element-property :contents-end parent) end))
23932 (setq end (org-element-property :end parent)))
23933 end)))
23934 (cond ((not element)
23935 (skip-chars-forward " \r\t\n")
23936 (or (eobp) (beginning-of-line)))
23937 ;; On affiliated keywords, move to element's beginning.
23938 ((and post-affiliated (< (point) post-affiliated))
23939 (goto-char post-affiliated))
23940 ;; At a table row, move to the end of the table. Similarly,
23941 ;; at a node property, move to the end of the property
23942 ;; drawer.
23943 ((memq type '(node-property table-row))
23944 (goto-char (org-element-property
23945 :end (org-element-property :parent element))))
23946 ((memq type '(property-drawer table)) (goto-char end))
23947 ;; Consider blank lines as separators in verse and source
23948 ;; blocks to ease editing.
23949 ((memq type '(src-block verse-block))
23950 (when (eq type 'src-block)
23951 (setq contents-end
23952 (save-excursion (goto-char end)
23953 (skip-chars-backward " \r\t\n")
23954 (line-beginning-position))))
23955 (beginning-of-line)
23956 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23957 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23958 (goto-char end)
23959 (skip-chars-forward " \r\t\n")
23960 (if (= (point) contents-end) (goto-char end)
23961 (beginning-of-line))))
23962 ;; With no contents, just skip element.
23963 ((not contents-begin) (goto-char end))
23964 ;; If contents are invisible, skip the element altogether.
23965 ((outline-invisible-p (line-end-position))
23966 (case type
23967 (headline
23968 (org-with-limited-levels (outline-next-visible-heading 1)))
23969 ;; At a plain list, make sure we move to the next item
23970 ;; instead of skipping the whole list.
23971 (plain-list (forward-char)
23972 (org-forward-paragraph))
23973 (otherwise (goto-char end))))
23974 ((>= (point) contents-end) (goto-char end))
23975 ((>= (point) contents-begin)
23976 ;; This can only happen on paragraphs and plain lists.
23977 (case type
23978 (paragraph (goto-char end))
23979 ;; At a plain list, try to move to second element in
23980 ;; first item, if possible.
23981 (plain-list (end-of-line)
23982 (org-forward-paragraph))))
23983 ;; When contents start on the middle of a line (e.g. in
23984 ;; items and footnote definitions), try to reach first
23985 ;; element starting after current line.
23986 ((> (line-end-position) contents-begin)
23987 (end-of-line)
23988 (org-forward-paragraph))
23989 (t (goto-char contents-begin)))))
23991 (defun org-backward-paragraph ()
23992 "Move backward to start of previous paragraph or equivalent.
23994 The function moves point to the beginning of the current
23995 structural element, which can be a paragraph, a table, a list
23996 item, etc., or to the beginning of the previous visible one if
23997 point is already there. It also provides some special moves for
23998 convenience:
24000 - On an affiliated keyword, jump to the first one.
24001 - On a table or a property drawer, move to its beginning.
24002 - On a verse or source block, stop before blank lines."
24003 (interactive)
24004 (when (bobp) (user-error "Cannot move further up"))
24005 (let* ((deactivate-mark nil)
24006 (element (org-element-at-point))
24007 (type (org-element-type element))
24008 (contents-begin (org-element-property :contents-begin element))
24009 (contents-end (org-element-property :contents-end element))
24010 (post-affiliated (org-element-property :post-affiliated element))
24011 (begin (org-element-property :begin element)))
24012 (cond
24013 ((not element) (goto-char (point-min)))
24014 ((= (point) begin)
24015 (backward-char)
24016 (org-backward-paragraph))
24017 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
24018 ((memq type '(node-property table-row))
24019 (goto-char (org-element-property
24020 :post-affiliated (org-element-property :parent element))))
24021 ((memq type '(property-drawer table)) (goto-char begin))
24022 ((memq type '(src-block verse-block))
24023 (when (eq type 'src-block)
24024 (setq contents-begin
24025 (save-excursion (goto-char begin) (forward-line) (point))))
24026 (if (= (point) contents-begin) (goto-char post-affiliated)
24027 ;; Inside a verse block, see blank lines as paragraph
24028 ;; separators.
24029 (let ((origin (point)))
24030 (skip-chars-backward " \r\t\n" contents-begin)
24031 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24032 (skip-chars-forward " \r\t\n" origin)
24033 (if (= (point) origin) (goto-char contents-begin)
24034 (beginning-of-line))))))
24035 ((not contents-begin) (goto-char (or post-affiliated begin)))
24036 ((eq type 'paragraph)
24037 (goto-char contents-begin)
24038 ;; When at first paragraph in an item or a footnote definition,
24039 ;; move directly to beginning of line.
24040 (let ((parent-contents
24041 (org-element-property
24042 :contents-begin (org-element-property :parent element))))
24043 (when (and parent-contents (= parent-contents contents-begin))
24044 (beginning-of-line))))
24045 ;; At the end of a greater element, move to the beginning of the
24046 ;; last element within.
24047 ((>= (point) contents-end)
24048 (goto-char (1- contents-end))
24049 (org-backward-paragraph))
24050 (t (goto-char (or post-affiliated begin))))
24051 ;; Ensure we never leave point invisible.
24052 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24054 (defun org-forward-element ()
24055 "Move forward by one element.
24056 Move to the next element at the same level, when possible."
24057 (interactive)
24058 (cond ((eobp) (user-error "Cannot move further down"))
24059 ((org-with-limited-levels (org-at-heading-p))
24060 (let ((origin (point)))
24061 (goto-char (org-end-of-subtree nil t))
24062 (unless (org-with-limited-levels (org-at-heading-p))
24063 (goto-char origin)
24064 (user-error "Cannot move further down"))))
24066 (let* ((elem (org-element-at-point))
24067 (end (org-element-property :end elem))
24068 (parent (org-element-property :parent elem)))
24069 (cond ((and parent (= (org-element-property :contents-end parent) end))
24070 (goto-char (org-element-property :end parent)))
24071 ((integer-or-marker-p end) (goto-char end))
24072 (t (message "No element at point")))))))
24074 (defun org-backward-element ()
24075 "Move backward by one element.
24076 Move to the previous element at the same level, when possible."
24077 (interactive)
24078 (cond ((bobp) (user-error "Cannot move further up"))
24079 ((org-with-limited-levels (org-at-heading-p))
24080 ;; At a headline, move to the previous one, if any, or stay
24081 ;; here.
24082 (let ((origin (point)))
24083 (org-with-limited-levels (org-backward-heading-same-level 1))
24084 ;; When current headline has no sibling above, move to its
24085 ;; parent.
24086 (when (= (point) origin)
24087 (or (org-with-limited-levels (org-up-heading-safe))
24088 (progn (goto-char origin)
24089 (user-error "Cannot move further up"))))))
24091 (let* ((elem (org-element-at-point))
24092 (beg (org-element-property :begin elem)))
24093 (cond
24094 ;; Move to beginning of current element if point isn't
24095 ;; there already.
24096 ((null beg) (message "No element at point"))
24097 ((/= (point) beg) (goto-char beg))
24098 (t (goto-char beg)
24099 (skip-chars-backward " \r\t\n")
24100 (unless (bobp)
24101 (let ((prev (org-element-at-point)))
24102 (goto-char (org-element-property :begin prev))
24103 (while (and (setq prev (org-element-property :parent prev))
24104 (<= (org-element-property :end prev) beg))
24105 (goto-char (org-element-property :begin prev)))))))))))
24107 (defun org-up-element ()
24108 "Move to upper element."
24109 (interactive)
24110 (if (org-with-limited-levels (org-at-heading-p))
24111 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24112 (let* ((elem (org-element-at-point))
24113 (parent (org-element-property :parent elem)))
24114 (if parent (goto-char (org-element-property :begin parent))
24115 (if (org-with-limited-levels (org-before-first-heading-p))
24116 (user-error "No surrounding element")
24117 (org-with-limited-levels (org-back-to-heading)))))))
24119 (defvar org-element-greater-elements)
24120 (defun org-down-element ()
24121 "Move to inner element."
24122 (interactive)
24123 (let ((element (org-element-at-point)))
24124 (cond
24125 ((memq (org-element-type element) '(plain-list table))
24126 (goto-char (org-element-property :contents-begin element))
24127 (forward-char))
24128 ((memq (org-element-type element) org-element-greater-elements)
24129 ;; If contents are hidden, first disclose them.
24130 (when (outline-invisible-p (line-end-position)) (org-cycle))
24131 (goto-char (or (org-element-property :contents-begin element)
24132 (user-error "No content for this element"))))
24133 (t (user-error "No inner element")))))
24135 (defun org-drag-element-backward ()
24136 "Move backward element at point."
24137 (interactive)
24138 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24139 (let* ((elem (org-element-at-point))
24140 (prev-elem
24141 (save-excursion
24142 (goto-char (org-element-property :begin elem))
24143 (skip-chars-backward " \r\t\n")
24144 (unless (bobp)
24145 (let* ((beg (org-element-property :begin elem))
24146 (prev (org-element-at-point))
24147 (up prev))
24148 (while (and (setq up (org-element-property :parent up))
24149 (<= (org-element-property :end up) beg))
24150 (setq prev up))
24151 prev)))))
24152 ;; Error out if no previous element or previous element is
24153 ;; a parent of the current one.
24154 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24155 (user-error "Cannot drag element backward")
24156 (let ((pos (point)))
24157 (org-element-swap-A-B prev-elem elem)
24158 (goto-char (+ (org-element-property :begin prev-elem)
24159 (- pos (org-element-property :begin elem)))))))))
24161 (defun org-drag-element-forward ()
24162 "Move forward element at point."
24163 (interactive)
24164 (let* ((pos (point))
24165 (elem (org-element-at-point)))
24166 (when (= (point-max) (org-element-property :end elem))
24167 (user-error "Cannot drag element forward"))
24168 (goto-char (org-element-property :end elem))
24169 (let ((next-elem (org-element-at-point)))
24170 (when (or (org-element-nested-p elem next-elem)
24171 (and (eq (org-element-type next-elem) 'headline)
24172 (not (eq (org-element-type elem) 'headline))))
24173 (goto-char pos)
24174 (user-error "Cannot drag element forward"))
24175 ;; Compute new position of point: it's shifted by NEXT-ELEM
24176 ;; body's length (without final blanks) and by the length of
24177 ;; blanks between ELEM and NEXT-ELEM.
24178 (let ((size-next (- (save-excursion
24179 (goto-char (org-element-property :end next-elem))
24180 (skip-chars-backward " \r\t\n")
24181 (forward-line)
24182 ;; Small correction if buffer doesn't end
24183 ;; with a newline character.
24184 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24185 (org-element-property :begin next-elem)))
24186 (size-blank (- (org-element-property :end elem)
24187 (save-excursion
24188 (goto-char (org-element-property :end elem))
24189 (skip-chars-backward " \r\t\n")
24190 (forward-line)
24191 (point)))))
24192 (org-element-swap-A-B elem next-elem)
24193 (goto-char (+ pos size-next size-blank))))))
24195 (defun org-drag-line-forward (arg)
24196 "Drag the line at point ARG lines forward."
24197 (interactive "p")
24198 (dotimes (n (abs arg))
24199 (let ((c (current-column)))
24200 (if (< 0 arg)
24201 (progn
24202 (beginning-of-line 2)
24203 (transpose-lines 1)
24204 (beginning-of-line 0))
24205 (transpose-lines 1)
24206 (beginning-of-line -1))
24207 (org-move-to-column c))))
24209 (defun org-drag-line-backward (arg)
24210 "Drag the line at point ARG lines backward."
24211 (interactive "p")
24212 (org-drag-line-forward (- arg)))
24214 (defun org-mark-element ()
24215 "Put point at beginning of this element, mark at end.
24217 Interactively, if this command is repeated or (in Transient Mark
24218 mode) if the mark is active, it marks the next element after the
24219 ones already marked."
24220 (interactive)
24221 (let (deactivate-mark)
24222 (if (and (org-called-interactively-p 'any)
24223 (or (and (eq last-command this-command) (mark t))
24224 (and transient-mark-mode mark-active)))
24225 (set-mark
24226 (save-excursion
24227 (goto-char (mark))
24228 (goto-char (org-element-property :end (org-element-at-point)))))
24229 (let ((element (org-element-at-point)))
24230 (end-of-line)
24231 (push-mark (org-element-property :end element) t t)
24232 (goto-char (org-element-property :begin element))))))
24234 (defun org-narrow-to-element ()
24235 "Narrow buffer to current element."
24236 (interactive)
24237 (let ((elem (org-element-at-point)))
24238 (cond
24239 ((eq (car elem) 'headline)
24240 (narrow-to-region
24241 (org-element-property :begin elem)
24242 (org-element-property :end elem)))
24243 ((memq (car elem) org-element-greater-elements)
24244 (narrow-to-region
24245 (org-element-property :contents-begin elem)
24246 (org-element-property :contents-end elem)))
24248 (narrow-to-region
24249 (org-element-property :begin elem)
24250 (org-element-property :end elem))))))
24252 (defun org-transpose-element ()
24253 "Transpose current and previous elements, keeping blank lines between.
24254 Point is moved after both elements."
24255 (interactive)
24256 (org-skip-whitespace)
24257 (let ((end (org-element-property :end (org-element-at-point))))
24258 (org-drag-element-backward)
24259 (goto-char end)))
24261 (defun org-unindent-buffer ()
24262 "Un-indent the visible part of the buffer.
24263 Relative indentation (between items, inside blocks, etc.) isn't
24264 modified."
24265 (interactive)
24266 (unless (eq major-mode 'org-mode)
24267 (user-error "Cannot un-indent a buffer not in Org mode"))
24268 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24269 unindent-tree ; For byte-compiler.
24270 (unindent-tree
24271 (function
24272 (lambda (contents)
24273 (mapc
24274 (lambda (element)
24275 (if (memq (org-element-type element) '(headline section))
24276 (funcall unindent-tree (org-element-contents element))
24277 (save-excursion
24278 (save-restriction
24279 (narrow-to-region
24280 (org-element-property :begin element)
24281 (org-element-property :end element))
24282 (org-do-remove-indentation)))))
24283 (reverse contents))))))
24284 (funcall unindent-tree (org-element-contents parse-tree))))
24286 (defun org-show-subtree ()
24287 "Show everything after this heading at deeper levels."
24288 (interactive)
24289 (outline-flag-region
24290 (point)
24291 (save-excursion
24292 (org-end-of-subtree t t))
24293 nil))
24295 (defun org-show-entry ()
24296 "Show the body directly following this heading.
24297 Show the heading too, if it is currently invisible."
24298 (interactive)
24299 (save-excursion
24300 (ignore-errors
24301 (org-back-to-heading t)
24302 (outline-flag-region
24303 (max (point-min) (1- (point)))
24304 (save-excursion
24305 (if (re-search-forward
24306 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24307 (match-beginning 1)
24308 (point-max)))
24309 nil)
24310 (org-cycle-hide-drawers 'children))))
24312 (defun org-make-options-regexp (kwds &optional extra)
24313 "Make a regular expression for keyword lines."
24314 (concat
24315 "^[ \t]*#\\+\\("
24316 (mapconcat 'regexp-quote kwds "\\|")
24317 (if extra (concat "\\|" extra))
24318 "\\):[ \t]*\\(.*\\)"))
24320 ;; Make isearch reveal the necessary context
24321 (defun org-isearch-end ()
24322 "Reveal context after isearch exits."
24323 (when isearch-success ; only if search was successful
24324 (if (featurep 'xemacs)
24325 ;; Under XEmacs, the hook is run in the correct place,
24326 ;; we directly show the context.
24327 (org-show-context 'isearch)
24328 ;; In Emacs the hook runs *before* restoring the overlays.
24329 ;; So we have to use a one-time post-command-hook to do this.
24330 ;; (Emacs 22 has a special variable, see function `org-mode')
24331 (unless (and (boundp 'isearch-mode-end-hook-quit)
24332 isearch-mode-end-hook-quit)
24333 ;; Only when the isearch was not quitted.
24334 (org-add-hook 'post-command-hook 'org-isearch-post-command
24335 'append 'local)))))
24337 (defun org-isearch-post-command ()
24338 "Remove self from hook, and show context."
24339 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24340 (org-show-context 'isearch))
24343 ;;;; Integration with and fixes for other packages
24345 ;;; Imenu support
24347 (defvar org-imenu-markers nil
24348 "All markers currently used by Imenu.")
24349 (make-variable-buffer-local 'org-imenu-markers)
24351 (defun org-imenu-new-marker (&optional pos)
24352 "Return a new marker for use by Imenu, and remember the marker."
24353 (let ((m (make-marker)))
24354 (move-marker m (or pos (point)))
24355 (push m org-imenu-markers)
24358 (defun org-imenu-get-tree ()
24359 "Produce the index for Imenu."
24360 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24361 (setq org-imenu-markers nil)
24362 (let* ((n org-imenu-depth)
24363 (re (concat "^" (org-get-limited-outline-regexp)))
24364 (subs (make-vector (1+ n) nil))
24365 (last-level 0)
24366 m level head0 head)
24367 (save-excursion
24368 (save-restriction
24369 (widen)
24370 (goto-char (point-max))
24371 (while (re-search-backward re nil t)
24372 (setq level (org-reduced-level (funcall outline-level)))
24373 (when (and (<= level n)
24374 (looking-at org-complex-heading-regexp)
24375 (setq head0 (org-match-string-no-properties 4)))
24376 (setq head (org-link-display-format head0)
24377 m (org-imenu-new-marker))
24378 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24379 (if (>= level last-level)
24380 (push (cons head m) (aref subs level))
24381 (push (cons head (aref subs (1+ level))) (aref subs level))
24382 (loop for i from (1+ level) to n do (aset subs i nil)))
24383 (setq last-level level)))))
24384 (aref subs 1)))
24386 (eval-after-load "imenu"
24387 '(progn
24388 (add-hook 'imenu-after-jump-hook
24389 (lambda ()
24390 (if (derived-mode-p 'org-mode)
24391 (org-show-context 'org-goto))))))
24393 (defun org-link-display-format (link)
24394 "Replace a link with its the description.
24395 If there is no description, use the link target."
24396 (save-match-data
24397 (if (string-match org-bracket-link-analytic-regexp link)
24398 (replace-match (if (match-end 5)
24399 (match-string 5 link)
24400 (concat (match-string 1 link)
24401 (match-string 3 link)))
24402 nil t link)
24403 link)))
24405 (defun org-toggle-link-display ()
24406 "Toggle the literal or descriptive display of links."
24407 (interactive)
24408 (if org-descriptive-links
24409 (progn (org-remove-from-invisibility-spec '(org-link))
24410 (org-restart-font-lock)
24411 (setq org-descriptive-links nil))
24412 (progn (add-to-invisibility-spec '(org-link))
24413 (org-restart-font-lock)
24414 (setq org-descriptive-links t))))
24416 ;; Speedbar support
24418 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24419 "Overlay marking the agenda restriction line in speedbar.")
24420 (overlay-put org-speedbar-restriction-lock-overlay
24421 'face 'org-agenda-restriction-lock)
24422 (overlay-put org-speedbar-restriction-lock-overlay
24423 'help-echo "Agendas are currently limited to this item.")
24424 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24426 (defun org-speedbar-set-agenda-restriction ()
24427 "Restrict future agenda commands to the location at point in speedbar.
24428 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24429 (interactive)
24430 (require 'org-agenda)
24431 (let (p m tp np dir txt)
24432 (cond
24433 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24434 'org-imenu t))
24435 (setq m (get-text-property p 'org-imenu-marker))
24436 (with-current-buffer (marker-buffer m)
24437 (goto-char m)
24438 (org-agenda-set-restriction-lock 'subtree)))
24439 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24440 'speedbar-function 'speedbar-find-file))
24441 (setq tp (previous-single-property-change
24442 (1+ p) 'speedbar-function)
24443 np (next-single-property-change
24444 tp 'speedbar-function)
24445 dir (speedbar-line-directory)
24446 txt (buffer-substring-no-properties (or tp (point-min))
24447 (or np (point-max))))
24448 (with-current-buffer (find-file-noselect
24449 (let ((default-directory dir))
24450 (expand-file-name txt)))
24451 (unless (derived-mode-p 'org-mode)
24452 (user-error "Cannot restrict to non-Org-mode file"))
24453 (org-agenda-set-restriction-lock 'file)))
24454 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24455 (move-overlay org-speedbar-restriction-lock-overlay
24456 (point-at-bol) (point-at-eol))
24457 (setq current-prefix-arg nil)
24458 (org-agenda-maybe-redo)))
24460 (defvar speedbar-file-key-map)
24461 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24462 (eval-after-load "speedbar"
24463 '(progn
24464 (speedbar-add-supported-extension ".org")
24465 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24466 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24467 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24468 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24469 (add-hook 'speedbar-visiting-tag-hook
24470 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24472 ;;; Fixes and Hacks for problems with other packages
24474 (defun org-mode-flyspell-verify ()
24475 "Function used for `flyspell-generic-check-word-predicate'."
24476 (if (org-at-heading-p)
24477 ;; At a headline or an inlinetask, check title only. This is
24478 ;; faster than relying on `org-element-at-point'.
24479 (and (save-excursion (beginning-of-line)
24480 (and (let ((case-fold-search t))
24481 (not (looking-at "\\*+ END[ \t]*$")))
24482 (looking-at org-complex-heading-regexp)))
24483 (match-beginning 4)
24484 (>= (point) (match-beginning 4))
24485 (or (not (match-beginning 5))
24486 (< (point) (match-beginning 5))))
24487 (let* ((element (org-element-at-point))
24488 (post-affiliated (org-element-property :post-affiliated element))
24489 (object-check
24490 (function
24491 ;; Non-nil if checks can be done for object at point.
24492 (lambda ()
24493 (let ((object (save-excursion
24494 (when (org-looking-at-p "\\>") (backward-char))
24495 (org-element-context element))))
24496 (case (org-element-type object)
24497 ;; Prevent checks in links due to keybinding conflict
24498 ;; with Flyspell.
24499 ((code entity export-snippet inline-babel-call
24500 inline-src-block line-break latex-fragment link macro
24501 statistics-cookie target timestamp verbatim)
24502 nil)
24503 (footnote-reference
24504 ;; Only in inline footnotes, within the definition.
24505 (and (eq (org-element-property :type object) 'inline)
24506 (< (save-excursion
24507 (goto-char (org-element-property :begin object))
24508 (search-forward ":" nil t 2))
24509 (point))))
24510 (otherwise t)))))))
24511 (cond
24512 ;; Ignore checks in all affiliated keywords but captions.
24513 ((and post-affiliated (< (point) post-affiliated))
24514 (and (save-excursion
24515 (beginning-of-line)
24516 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24517 (> (point) (match-end 0))
24518 (funcall object-check)))
24519 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24520 ((and org-log-into-drawer
24521 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24522 (parent element))
24523 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24524 (setq parent (org-element-property :parent parent)))
24525 (and parent
24526 (eq (compare-strings
24527 log nil nil
24528 (org-element-property :drawer-name parent) nil nil t)
24529 t))))
24530 nil)
24532 (case (org-element-type element)
24533 ((comment quote-section) t)
24534 (comment-block
24535 ;; Allow checks between block markers, not on them.
24536 (and (> (line-beginning-position)
24537 (org-element-property :post-affiliated element))
24538 (save-excursion
24539 (end-of-line)
24540 (skip-chars-forward " \r\t\n")
24541 (< (point) (org-element-property :end element)))))
24542 ;; Arbitrary list of keywords where checks are meaningful.
24543 ;; Make sure point is on the value part of the element.
24544 (keyword
24545 (and (member (org-element-property :key element)
24546 '("DESCRIPTION" "TITLE"))
24547 (< (save-excursion
24548 (beginning-of-line) (search-forward ":") (point))
24549 (point))))
24550 ;; Check is globally allowed in paragraphs verse blocks and
24551 ;; table rows (after affiliated keywords) but some objects
24552 ;; must not be affected.
24553 ((paragraph table-row verse-block)
24554 (and (>= (point) (org-element-property :contents-begin element))
24555 (< (point) (org-element-property :contents-end element))
24556 (funcall object-check)))))))))
24557 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24559 (defun org-remove-flyspell-overlays-in (beg end)
24560 "Remove flyspell overlays in region."
24561 (and (org-bound-and-true-p flyspell-mode)
24562 (fboundp 'flyspell-delete-region-overlays)
24563 (flyspell-delete-region-overlays beg end)))
24565 (defvar flyspell-delayed-commands)
24566 (eval-after-load "flyspell"
24567 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24569 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24570 (eval-after-load "bookmark"
24571 '(if (boundp 'bookmark-after-jump-hook)
24572 ;; We can use the hook
24573 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24574 ;; Hook not available, use advice
24575 (defadvice bookmark-jump (after org-make-visible activate)
24576 "Make the position visible."
24577 (org-bookmark-jump-unhide))))
24579 ;; Make sure saveplace shows the location if it was hidden
24580 (eval-after-load "saveplace"
24581 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24582 "Make the position visible."
24583 (org-bookmark-jump-unhide)))
24585 ;; Make sure ecb shows the location if it was hidden
24586 (eval-after-load "ecb"
24587 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24588 "Make hierarchy visible when jumping into location from ECB tree buffer."
24589 (if (derived-mode-p 'org-mode)
24590 (org-show-context))))
24592 (defun org-bookmark-jump-unhide ()
24593 "Unhide the current position, to show the bookmark location."
24594 (and (derived-mode-p 'org-mode)
24595 (or (outline-invisible-p)
24596 (save-excursion (goto-char (max (point-min) (1- (point))))
24597 (outline-invisible-p)))
24598 (org-show-context 'bookmark-jump)))
24600 (defun org-mark-jump-unhide ()
24601 "Make the point visible with `org-show-context' after jumping to the mark."
24602 (when (and (derived-mode-p 'org-mode)
24603 (outline-invisible-p))
24604 (org-show-context 'mark-goto)))
24606 (eval-after-load "simple"
24607 '(defadvice pop-to-mark-command (after org-make-visible activate)
24608 "Make the point visible with `org-show-context'."
24609 (org-mark-jump-unhide)))
24611 (eval-after-load "simple"
24612 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24613 "Make the point visible with `org-show-context'."
24614 (org-mark-jump-unhide)))
24616 (eval-after-load "simple"
24617 '(defadvice pop-global-mark (after org-make-visible activate)
24618 "Make the point visible with `org-show-context'."
24619 (org-mark-jump-unhide)))
24621 ;; Make session.el ignore our circular variable
24622 (defvar session-globals-exclude)
24623 (eval-after-load "session"
24624 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24626 ;;;; Finish up
24628 (provide 'org)
24630 (run-hooks 'org-load-hook)
24632 ;;; org.el ends here