Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob9a4cf31181245997aa88b2a7294bfb3e12cd7677
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--parse-objects "org-element"
166 (beg end acc restriction))
167 (declare-function org-element-at-point "org-element" ())
168 (declare-function org-element-cache-reset "org-element" (&optional all))
169 (declare-function org-element-cache-refresh "org-element" (pos))
170 (declare-function org-element-contents "org-element" (element))
171 (declare-function org-element-context "org-element" (&optional element))
172 (declare-function org-element-interpret-data "org-element"
173 (data &optional parent))
174 (declare-function org-element-map "org-element"
175 (data types fun &optional info first-match no-recursion))
176 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
177 (declare-function org-element-parse-buffer "org-element"
178 (&optional granularity visible-only))
179 (declare-function org-element-property "org-element" (property element))
180 (declare-function org-element-put-property "org-element"
181 (element property value))
182 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
183 (declare-function org-element--parse-objects "org-element"
184 (beg end acc restriction))
185 (declare-function org-element-parse-buffer "org-element"
186 (&optional granularity visible-only))
187 (declare-function org-element-restriction "org-element" (element))
188 (declare-function org-element-type "org-element" (element))
190 (defsubst org-uniquify (list)
191 "Non-destructively remove duplicate elements from LIST."
192 (let ((res (copy-sequence list))) (delete-dups res)))
194 (defsubst org-get-at-bol (property)
195 "Get text property PROPERTY at the beginning of line."
196 (get-text-property (point-at-bol) property))
198 (defsubst org-trim (s)
199 "Remove whitespace at the beginning and the end of string S."
200 (replace-regexp-in-string
201 "\\`[ \t\n\r]+" ""
202 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
204 ;; load languages based on value of `org-babel-load-languages'
205 (defvar org-babel-load-languages)
207 ;;;###autoload
208 (defun org-babel-do-load-languages (sym value)
209 "Load the languages defined in `org-babel-load-languages'."
210 (set-default sym value)
211 (mapc (lambda (pair)
212 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
213 (if active
214 (progn
215 (require (intern (concat "ob-" lang))))
216 (progn
217 (funcall 'fmakunbound
218 (intern (concat "org-babel-execute:" lang)))
219 (funcall 'fmakunbound
220 (intern (concat "org-babel-expand-body:" lang)))))))
221 org-babel-load-languages))
223 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
224 ;;;###autoload
225 (defun org-babel-load-file (file &optional compile)
226 "Load Emacs Lisp source code blocks in the Org-mode FILE.
227 This function exports the source code using `org-babel-tangle'
228 and then loads the resulting file using `load-file'. With prefix
229 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
230 file to byte-code before it is loaded."
231 (interactive "fFile to load: \nP")
232 (let* ((age (lambda (file)
233 (float-time
234 (time-subtract (current-time)
235 (nth 5 (or (file-attributes (file-truename file))
236 (file-attributes file)))))))
237 (base-name (file-name-sans-extension file))
238 (exported-file (concat base-name ".el")))
239 ;; tangle if the org-mode file is newer than the elisp file
240 (unless (and (file-exists-p exported-file)
241 (> (funcall age file) (funcall age exported-file)))
242 (setq exported-file
243 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
244 (message "%s %s"
245 (if compile
246 (progn (byte-compile-file exported-file 'load)
247 "Compiled and loaded")
248 (progn (load-file exported-file) "Loaded"))
249 exported-file)))
251 (defcustom org-babel-load-languages '((emacs-lisp . t))
252 "Languages which can be evaluated in Org-mode buffers.
253 This list can be used to load support for any of the languages
254 below, note that each language will depend on a different set of
255 system executables and/or Emacs modes. When a language is
256 \"loaded\", then code blocks in that language can be evaluated
257 with `org-babel-execute-src-block' bound by default to C-c
258 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
259 be set to remove code block evaluation from the C-c C-c
260 keybinding. By default only Emacs Lisp (which has no
261 requirements) is loaded."
262 :group 'org-babel
263 :set 'org-babel-do-load-languages
264 :version "24.1"
265 :type '(alist :tag "Babel Languages"
266 :key-type
267 (choice
268 (const :tag "Awk" awk)
269 (const :tag "C" C)
270 (const :tag "R" R)
271 (const :tag "Asymptote" asymptote)
272 (const :tag "Calc" calc)
273 (const :tag "Clojure" clojure)
274 (const :tag "CSS" css)
275 (const :tag "Ditaa" ditaa)
276 (const :tag "Dot" dot)
277 (const :tag "Emacs Lisp" emacs-lisp)
278 (const :tag "Fortran" fortran)
279 (const :tag "Gnuplot" gnuplot)
280 (const :tag "Haskell" haskell)
281 (const :tag "IO" io)
282 (const :tag "J" J)
283 (const :tag "Java" java)
284 (const :tag "Javascript" js)
285 (const :tag "LaTeX" latex)
286 (const :tag "Ledger" ledger)
287 (const :tag "Lilypond" lilypond)
288 (const :tag "Lisp" lisp)
289 (const :tag "Makefile" makefile)
290 (const :tag "Maxima" maxima)
291 (const :tag "Matlab" matlab)
292 (const :tag "Mscgen" mscgen)
293 (const :tag "Ocaml" ocaml)
294 (const :tag "Octave" octave)
295 (const :tag "Org" org)
296 (const :tag "Perl" perl)
297 (const :tag "Pico Lisp" picolisp)
298 (const :tag "PlantUML" plantuml)
299 (const :tag "Python" python)
300 (const :tag "Ruby" ruby)
301 (const :tag "Sass" sass)
302 (const :tag "Scala" scala)
303 (const :tag "Scheme" scheme)
304 (const :tag "Screen" screen)
305 (const :tag "Shell Script" shell)
306 (const :tag "Shen" shen)
307 (const :tag "Sql" sql)
308 (const :tag "Sqlite" sqlite)
309 (const :tag "ebnf2ps" ebnf2ps))
310 :value-type (boolean :tag "Activate" :value t)))
312 ;;;; Customization variables
313 (defcustom org-clone-delete-id nil
314 "Remove ID property of clones of a subtree.
315 When non-nil, clones of a subtree don't inherit the ID property.
316 Otherwise they inherit the ID property with a new unique
317 identifier."
318 :type 'boolean
319 :version "24.1"
320 :group 'org-id)
322 ;;; Version
323 (org-check-version)
325 ;;;###autoload
326 (defun org-version (&optional here full message)
327 "Show the org-mode version.
328 Interactively, or when MESSAGE is non-nil, show it in echo area.
329 With prefix argument, or when HERE is non-nil, insert it at point.
330 In non-interactive uses, a reduced version string is output unless
331 FULL is given."
332 (interactive (list current-prefix-arg t (not current-prefix-arg)))
333 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
334 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
335 (load-suffixes (list ".el"))
336 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
337 (org-trash (or
338 (and (fboundp 'org-release) (fboundp 'org-git-version))
339 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
340 (load-suffixes save-load-suffixes)
341 (org-version (org-release))
342 (git-version (org-git-version))
343 (version (format "Org-mode version %s (%s @ %s)"
344 org-version
345 git-version
346 (if org-install-dir
347 (if (string= org-dir org-install-dir)
348 org-install-dir
349 (concat "mixed installation! " org-install-dir " and " org-dir))
350 "org-loaddefs.el can not be found!")))
351 (version1 (if full version org-version)))
352 (when here (insert version1))
353 (when message (message "%s" version1))
354 version1))
356 (defconst org-version (org-version))
359 ;;; Syntax Constants
361 ;;;; Block
363 (defconst org-block-regexp
364 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
365 "Regular expression for hiding blocks.")
367 (defconst org-dblock-start-re
368 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
369 "Matches the start line of a dynamic block, with parameters.")
371 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
372 "Matches the end of a dynamic block.")
374 ;;;; Clock and Planning
376 (defconst org-clock-string "CLOCK:"
377 "String used as prefix for timestamps clocking work hours on an item.")
379 (defconst org-closed-string "CLOSED:"
380 "String used as the prefix for timestamps logging closing a TODO entry.")
382 (defconst org-deadline-string "DEADLINE:"
383 "String to mark deadline entries.
384 A deadline is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-deadline].")
388 (defconst org-scheduled-string "SCHEDULED:"
389 "String to mark scheduled TODO entries.
390 A schedule is this string, followed by a time stamp. Should be a word,
391 terminated by a colon. You can insert a schedule keyword and
392 a timestamp with \\[org-schedule].")
394 (defconst org-planning-or-clock-line-re
395 (concat "^[ \t]*"
396 (regexp-opt
397 (list org-clock-string org-closed-string org-deadline-string
398 org-scheduled-string)
400 "Matches a line with planning or clock info.
401 Matched keyword is in group 1.")
403 ;;;; Drawer
405 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
406 "Matches first or last line of a hidden block.
407 Group 1 contains drawer's name or \"END\".")
409 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
410 "Regular expression matching the first line of a property drawer.")
412 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
413 "Regular expression matching the last line of a property drawer.")
415 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
416 "Regular expression matching the first line of a clock drawer.")
418 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
419 "Regular expression matching the last line of a clock drawer.")
421 (defconst org-property-drawer-re
422 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
423 org-property-end-re "\\)\n?")
424 "Matches an entire property drawer.")
426 (defconst org-clock-drawer-re
427 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
428 org-clock-drawer-end-re "\\)\n?")
429 "Matches an entire clock drawer.")
431 ;;;; Headline
433 (defconst org-heading-keyword-regexp-format
434 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
435 "Printf format for a regexp matching a headline with some keyword.
436 This regexp will match the headline of any node which has the
437 exact keyword that is put into the format. The keyword isn't in
438 any group by default, but the stars and the body are.")
440 (defconst org-heading-keyword-maybe-regexp-format
441 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
442 "Printf format for a regexp matching a headline, possibly with some keyword.
443 This regexp can match any headline with the specified keyword, or
444 without a keyword. The keyword isn't in any group by default,
445 but the stars and the body are.")
447 (defconst org-archive-tag "ARCHIVE"
448 "The tag that marks a subtree as archived.
449 An archived subtree does not open during visibility cycling, and does
450 not contribute to the agenda listings.")
452 (defconst org-comment-string "COMMENT"
453 "Entries starting with this keyword will never be exported.
454 An entry can be toggled between COMMENT and normal with
455 \\[org-toggle-comment].")
458 ;;;; LaTeX Environments and Fragments
460 (defconst org-latex-regexps
461 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
462 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
463 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
464 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
465 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
466 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
467 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
468 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
469 "Regular expressions for matching embedded LaTeX.")
471 ;;;; Node Property
473 (defconst org-effort-property "Effort"
474 "The property that is being used to keep track of effort estimates.
475 Effort estimates given in this property need to have the format H:MM.")
477 ;;;; Table
479 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
480 "Detect an org-type or table-type table.")
482 (defconst org-table-line-regexp "^[ \t]*|"
483 "Detect an org-type table line.")
485 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
486 "Detect an org-type table line.")
488 (defconst org-table-hline-regexp "^[ \t]*|-"
489 "Detect an org-type table hline.")
491 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
492 "Detect a table-type table hline.")
494 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
495 "Detect the first line outside a table when searching from within it.
496 This works for both table types.")
498 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
499 "Detect a #+TBLFM line.")
501 ;;;; Timestamp
503 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
504 "Regular expression for fast time stamp matching.")
506 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
507 "Regular expression for fast time stamp matching.")
509 (defconst org-ts-regexp0
510 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
511 "Regular expression matching time strings for analysis.
512 This one does not require the space after the date, so it can be used
513 on a string that terminates immediately after the date.")
515 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
516 "Regular expression matching time strings for analysis.")
518 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
519 "Regular expression matching time stamps, with groups.")
521 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
522 "Regular expression matching time stamps (also [..]), with groups.")
524 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
525 "Regular expression matching a time stamp range.")
527 (defconst org-tr-regexp-both
528 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
529 "Regular expression matching a time stamp range.")
531 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
532 org-ts-regexp "\\)?")
533 "Regular expression matching a time stamp or time stamp range.")
535 (defconst org-tsr-regexp-both
536 (concat org-ts-regexp-both "\\(--?-?"
537 org-ts-regexp-both "\\)?")
538 "Regular expression matching a time stamp or time stamp range.
539 The time stamps may be either active or inactive.")
541 (defconst org-repeat-re
542 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
543 "Regular expression for specifying repeated events.
544 After a match, group 1 contains the repeat expression.")
546 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
547 "Formats for `format-time-string' which are used for time stamps.")
550 ;;; The custom variables
552 (defgroup org nil
553 "Outline-based notes management and organizer."
554 :tag "Org"
555 :group 'outlines
556 :group 'calendar)
558 (defcustom org-mode-hook nil
559 "Mode hook for Org-mode, run after the mode was turned on."
560 :group 'org
561 :type 'hook)
563 (defcustom org-load-hook nil
564 "Hook that is run after org.el has been loaded."
565 :group 'org
566 :type 'hook)
568 (defcustom org-log-buffer-setup-hook nil
569 "Hook that is run after an Org log buffer is created."
570 :group 'org
571 :version "24.1"
572 :type 'hook)
574 (defvar org-modules) ; defined below
575 (defvar org-modules-loaded nil
576 "Have the modules been loaded already?")
578 (defun org-load-modules-maybe (&optional force)
579 "Load all extensions listed in `org-modules'."
580 (when (or force (not org-modules-loaded))
581 (mapc (lambda (ext)
582 (condition-case nil (require ext)
583 (error (message "Problems while trying to load feature `%s'" ext))))
584 org-modules)
585 (setq org-modules-loaded t)))
587 (defun org-set-modules (var value)
588 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
589 (set var value)
590 (when (featurep 'org)
591 (org-load-modules-maybe 'force)
592 (org-element-cache-reset 'all)))
594 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
595 "Modules that should always be loaded together with org.el.
597 If a description starts with <C>, the file is not part of Emacs
598 and loading it will require that you have downloaded and properly
599 installed the Org mode distribution.
601 You can also use this system to load external packages (i.e. neither Org
602 core modules, nor modules from the CONTRIB directory). Just add symbols
603 to the end of the list. If the package is called org-xyz.el, then you need
604 to add the symbol `xyz', and the package must have a call to:
606 \(provide 'org-xyz)
608 For export specific modules, see also `org-export-backends'."
609 :group 'org
610 :set 'org-set-modules
611 :version "24.4"
612 :package-version '(Org . "8.0")
613 :type
614 '(set :greedy t
615 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
616 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
617 (const :tag " crypt: Encryption of subtrees" org-crypt)
618 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
619 (const :tag " docview: Links to doc-view buffers" org-docview)
620 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
621 (const :tag " habit: Track your consistency with habits" org-habit)
622 (const :tag " id: Global IDs for identifying entries" org-id)
623 (const :tag " info: Links to Info nodes" org-info)
624 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
625 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
626 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
627 (const :tag " mouse: Additional mouse support" org-mouse)
628 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
629 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
630 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
632 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
633 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
634 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
635 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
636 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
637 (const :tag "C collector: Collect properties into tables" org-collector)
638 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
639 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
640 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
641 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
642 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
643 (const :tag "C eval: Include command output as text" org-eval)
644 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
645 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
646 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
647 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
648 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
649 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
650 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
651 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
652 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
653 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
654 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
655 (const :tag "C mew: Links to Mew folders/messages" org-mew)
656 (const :tag "C mtags: Support for muse-like tags" org-mtags)
657 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
658 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
659 (const :tag "C registry: A registry for Org-mode links" org-registry)
660 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
661 (const :tag "C secretary: Team management with org-mode" org-secretary)
662 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
663 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
664 (const :tag "C track: Keep up with Org-mode development" org-track)
665 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
666 (const :tag "C vm: Links to VM folders/messages" org-vm)
667 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
668 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
669 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
671 (defvar org-export--registered-backends) ; From ox.el.
672 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
673 (declare-function org-export-backend-name "ox" (backend))
674 (defcustom org-export-backends '(ascii html icalendar latex)
675 "List of export back-ends that should be always available.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 Unlike to `org-modules', libraries in this list will not be
682 loaded along with Org, but only once the export framework is
683 needed.
685 This variable needs to be set before org.el is loaded. If you
686 need to make a change while Emacs is running, use the customize
687 interface or run the following code, where VAL stands for the new
688 value of the variable, after updating it:
690 \(progn
691 \(setq org-export--registered-backends
692 \(org-remove-if-not
693 \(lambda (backend)
694 \(let ((name (org-export-backend-name backend)))
695 \(or (memq name val)
696 \(catch 'parentp
697 \(dolist (b val)
698 \(and (org-export-derived-backend-p b name)
699 \(throw 'parentp t)))))))
700 org-export--registered-backends))
701 \(let ((new-list (mapcar 'org-export-backend-name
702 org-export--registered-backends)))
703 \(dolist (backend val)
704 \(cond
705 \((not (load (format \"ox-%s\" backend) t t))
706 \(message \"Problems while trying to load export back-end `%s'\"
707 backend))
708 \((not (memq backend new-list)) (push backend new-list))))
709 \(set-default 'org-export-backends new-list)))
711 Adding a back-end to this list will also pull the back-end it
712 depends on, if any."
713 :group 'org
714 :group 'org-export
715 :version "24.4"
716 :package-version '(Org . "8.0")
717 :initialize 'custom-initialize-set
718 :set (lambda (var val)
719 (if (not (featurep 'ox)) (set-default var val)
720 ;; Any back-end not required anymore (not present in VAL and not
721 ;; a parent of any back-end in the new value) is removed from the
722 ;; list of registered back-ends.
723 (setq org-export--registered-backends
724 (org-remove-if-not
725 (lambda (backend)
726 (let ((name (org-export-backend-name backend)))
727 (or (memq name val)
728 (catch 'parentp
729 (dolist (b val)
730 (and (org-export-derived-backend-p b name)
731 (throw 'parentp t)))))))
732 org-export--registered-backends))
733 ;; Now build NEW-LIST of both new back-ends and required
734 ;; parents.
735 (let ((new-list (mapcar 'org-export-backend-name
736 org-export--registered-backends)))
737 (dolist (backend val)
738 (cond
739 ((not (load (format "ox-%s" backend) t t))
740 (message "Problems while trying to load export back-end `%s'"
741 backend))
742 ((not (memq backend new-list)) (push backend new-list))))
743 ;; Set VAR to that list with fixed dependencies.
744 (set-default var new-list))))
745 :type '(set :greedy t
746 (const :tag " ascii Export buffer to ASCII format" ascii)
747 (const :tag " beamer Export buffer to Beamer presentation" beamer)
748 (const :tag " html Export buffer to HTML format" html)
749 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
750 (const :tag " latex Export buffer to LaTeX format" latex)
751 (const :tag " man Export buffer to MAN format" man)
752 (const :tag " md Export buffer to Markdown format" md)
753 (const :tag " odt Export buffer to ODT format" odt)
754 (const :tag " org Export buffer to Org format" org)
755 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
756 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
757 (const :tag "C deck Export buffer to deck.js presentations" deck)
758 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
759 (const :tag "C groff Export buffer to Groff format" groff)
760 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
761 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
762 (const :tag "C s5 Export buffer to s5 presentations" s5)
763 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
765 (eval-after-load 'ox
766 '(mapc
767 (lambda (backend)
768 (condition-case nil (require (intern (format "ox-%s" backend)))
769 (error (message "Problems while trying to load export back-end `%s'"
770 backend))))
771 org-export-backends))
773 (defcustom org-support-shift-select nil
774 "Non-nil means make shift-cursor commands select text when possible.
776 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
777 start selecting a region, or enlarge regions started in this way.
778 In Org-mode, in special contexts, these same keys are used for
779 other purposes, important enough to compete with shift selection.
780 Org tries to balance these needs by supporting `shift-select-mode'
781 outside these special contexts, under control of this variable.
783 The default of this variable is nil, to avoid confusing behavior. Shifted
784 cursor keys will then execute Org commands in the following contexts:
785 - on a headline, changing TODO state (left/right) and priority (up/down)
786 - on a time stamp, changing the time
787 - in a plain list item, changing the bullet type
788 - in a property definition line, switching between allowed values
789 - in the BEGIN line of a clock table (changing the time block).
790 Outside these contexts, the commands will throw an error.
792 When this variable is t and the cursor is not in a special
793 context, Org-mode will support shift-selection for making and
794 enlarging regions. To make this more effective, the bullet
795 cycling will no longer happen anywhere in an item line, but only
796 if the cursor is exactly on the bullet.
798 If you set this variable to the symbol `always', then the keys
799 will not be special in headlines, property lines, and item lines,
800 to make shift selection work there as well. If this is what you
801 want, you can use the following alternative commands: `C-c C-t'
802 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
803 can be used to switch TODO sets, `C-c -' to cycle item bullet
804 types, and properties can be edited by hand or in column view.
806 However, when the cursor is on a timestamp, shift-cursor commands
807 will still edit the time stamp - this is just too good to give up.
809 XEmacs user should have this variable set to nil, because
810 `shift-select-mode' is in Emacs 23 or later only."
811 :group 'org
812 :type '(choice
813 (const :tag "Never" nil)
814 (const :tag "When outside special context" t)
815 (const :tag "Everywhere except timestamps" always)))
817 (defcustom org-loop-over-headlines-in-active-region nil
818 "Shall some commands act upon headlines in the active region?
820 When set to `t', some commands will be performed in all headlines
821 within the active region.
823 When set to `start-level', some commands will be performed in all
824 headlines within the active region, provided that these headlines
825 are of the same level than the first one.
827 When set to a string, those commands will be performed on the
828 matching headlines within the active region. Such string must be
829 a tags/property/todo match as it is used in the agenda tags view.
831 The list of commands is: `org-schedule', `org-deadline',
832 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
833 `org-archive-to-archive-sibling'. The archiving commands skip
834 already archived entries."
835 :type '(choice (const :tag "Don't loop" nil)
836 (const :tag "All headlines in active region" t)
837 (const :tag "In active region, headlines at the same level than the first one" start-level)
838 (string :tag "Tags/Property/Todo matcher"))
839 :version "24.1"
840 :group 'org-todo
841 :group 'org-archive)
843 (defgroup org-startup nil
844 "Options concerning startup of Org-mode."
845 :tag "Org Startup"
846 :group 'org)
848 (defcustom org-startup-folded t
849 "Non-nil means entering Org-mode will switch to OVERVIEW.
850 This can also be configured on a per-file basis by adding one of
851 the following lines anywhere in the buffer:
853 #+STARTUP: fold (or `overview', this is equivalent)
854 #+STARTUP: nofold (or `showall', this is equivalent)
855 #+STARTUP: content
856 #+STARTUP: showeverything
858 By default, this option is ignored when Org opens agenda files
859 for the first time. If you want the agenda to honor the startup
860 option, set `org-agenda-inhibit-startup' to nil."
861 :group 'org-startup
862 :type '(choice
863 (const :tag "nofold: show all" nil)
864 (const :tag "fold: overview" t)
865 (const :tag "content: all headlines" content)
866 (const :tag "show everything, even drawers" showeverything)))
868 (defcustom org-startup-truncated t
869 "Non-nil means entering Org-mode will set `truncate-lines'.
870 This is useful since some lines containing links can be very long and
871 uninteresting. Also tables look terrible when wrapped."
872 :group 'org-startup
873 :type 'boolean)
875 (defcustom org-startup-indented nil
876 "Non-nil means turn on `org-indent-mode' on startup.
877 This can also be configured on a per-file basis by adding one of
878 the following lines anywhere in the buffer:
880 #+STARTUP: indent
881 #+STARTUP: noindent"
882 :group 'org-structure
883 :type '(choice
884 (const :tag "Not" nil)
885 (const :tag "Globally (slow on startup in large files)" t)))
887 (defcustom org-use-sub-superscripts t
888 "Non-nil means interpret \"_\" and \"^\" for display.
890 If you want to control how Org exports those characters, see
891 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
892 used to be an alias for `org-export-with-sub-superscripts' in
893 Org <8.0, it is not anymore.
895 When this option is turned on, you can use TeX-like syntax for
896 sub- and superscripts within the buffer. Several characters after
897 \"_\" or \"^\" will be considered as a single item - so grouping
898 with {} is normally not needed. For example, the following things
899 will be parsed as single sub- or superscripts:
901 10^24 or 10^tau several digits will be considered 1 item.
902 10^-12 or 10^-tau a leading sign with digits or a word
903 x^2-y^3 will be read as x^2 - y^3, because items are
904 terminated by almost any nonword/nondigit char.
905 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
907 Still, ambiguity is possible. So when in doubt, use {} to enclose
908 the sub/superscript. If you set this variable to the symbol `{}',
909 the braces are *required* in order to trigger interpretations as
910 sub/superscript. This can be helpful in documents that need \"_\"
911 frequently in plain text."
912 :group 'org-startup
913 :version "24.4"
914 :package-version '(Org . "8.0")
915 :type '(choice
916 (const :tag "Always interpret" t)
917 (const :tag "Only with braces" {})
918 (const :tag "Never interpret" nil)))
920 (defcustom org-startup-with-beamer-mode nil
921 "Non-nil means turn on `org-beamer-mode' on startup.
922 This can also be configured on a per-file basis by adding one of
923 the following lines anywhere in the buffer:
925 #+STARTUP: beamer"
926 :group 'org-startup
927 :version "24.1"
928 :type 'boolean)
930 (defcustom org-startup-align-all-tables nil
931 "Non-nil means align all tables when visiting a file.
932 This is useful when the column width in tables is forced with <N> cookies
933 in table fields. Such tables will look correct only after the first re-align.
934 This can also be configured on a per-file basis by adding one of
935 the following lines anywhere in the buffer:
936 #+STARTUP: align
937 #+STARTUP: noalign"
938 :group 'org-startup
939 :type 'boolean)
941 (defcustom org-startup-with-inline-images nil
942 "Non-nil means show inline images when loading a new Org file.
943 This can also be configured on a per-file basis by adding one of
944 the following lines anywhere in the buffer:
945 #+STARTUP: inlineimages
946 #+STARTUP: noinlineimages"
947 :group 'org-startup
948 :version "24.1"
949 :type 'boolean)
951 (defcustom org-startup-with-latex-preview nil
952 "Non-nil means preview LaTeX fragments when loading a new Org file.
954 This can also be configured on a per-file basis by adding one of
955 the following lines anywhere in the buffer:
956 #+STARTUP: latexpreview
957 #+STARTUP: nolatexpreview"
958 :group 'org-startup
959 :version "24.4"
960 :package-version '(Org . "8.0")
961 :type 'boolean)
963 (defcustom org-insert-mode-line-in-empty-file nil
964 "Non-nil means insert the first line setting Org-mode in empty files.
965 When the function `org-mode' is called interactively in an empty file, this
966 normally means that the file name does not automatically trigger Org-mode.
967 To ensure that the file will always be in Org-mode in the future, a
968 line enforcing Org-mode will be inserted into the buffer, if this option
969 has been set."
970 :group 'org-startup
971 :type 'boolean)
973 (defcustom org-replace-disputed-keys nil
974 "Non-nil means use alternative key bindings for some keys.
975 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
976 These keys are also used by other packages like shift-selection-mode'
977 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
978 If you want to use Org-mode together with one of these other modes,
979 or more generally if you would like to move some Org-mode commands to
980 other keys, set this variable and configure the keys with the variable
981 `org-disputed-keys'.
983 This option is only relevant at load-time of Org-mode, and must be set
984 *before* org.el is loaded. Changing it requires a restart of Emacs to
985 become effective."
986 :group 'org-startup
987 :type 'boolean)
989 (defcustom org-use-extra-keys nil
990 "Non-nil means use extra key sequence definitions for certain commands.
991 This happens automatically if you run XEmacs or if `window-system'
992 is nil. This variable lets you do the same manually. You must
993 set it before loading org.
995 Example: on Carbon Emacs 22 running graphically, with an external
996 keyboard on a Powerbook, the default way of setting M-left might
997 not work for either Alt or ESC. Setting this variable will make
998 it work for ESC."
999 :group 'org-startup
1000 :type 'boolean)
1002 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1004 (defcustom org-disputed-keys
1005 '(([(shift up)] . [(meta p)])
1006 ([(shift down)] . [(meta n)])
1007 ([(shift left)] . [(meta -)])
1008 ([(shift right)] . [(meta +)])
1009 ([(control shift right)] . [(meta shift +)])
1010 ([(control shift left)] . [(meta shift -)]))
1011 "Keys for which Org-mode and other modes compete.
1012 This is an alist, cars are the default keys, second element specifies
1013 the alternative to use when `org-replace-disputed-keys' is t.
1015 Keys can be specified in any syntax supported by `define-key'.
1016 The value of this option takes effect only at Org-mode's startup,
1017 therefore you'll have to restart Emacs to apply it after changing."
1018 :group 'org-startup
1019 :type 'alist)
1021 (defun org-key (key)
1022 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1023 Or return the original if not disputed.
1024 Also apply the translations defined in `org-xemacs-key-equivalents'."
1025 (when org-replace-disputed-keys
1026 (let* ((nkey (key-description key))
1027 (x (org-find-if (lambda (x)
1028 (equal (key-description (car x)) nkey))
1029 org-disputed-keys)))
1030 (setq key (if x (cdr x) key))))
1031 (when (featurep 'xemacs)
1032 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1033 key)
1035 (defun org-find-if (predicate seq)
1036 (catch 'exit
1037 (while seq
1038 (if (funcall predicate (car seq))
1039 (throw 'exit (car seq))
1040 (pop seq)))))
1042 (defun org-defkey (keymap key def)
1043 "Define a key, possibly translated, as returned by `org-key'."
1044 (define-key keymap (org-key key) def))
1046 (defcustom org-ellipsis nil
1047 "The ellipsis to use in the Org-mode outline.
1048 When nil, just use the standard three dots.
1049 When a string, use that string instead.
1050 When a face, use the standard 3 dots, but with the specified face.
1051 The change affects only Org-mode (which will then use its own display table).
1052 Changing this requires executing `M-x org-mode RET' in a buffer to become
1053 effective."
1054 :group 'org-startup
1055 :type '(choice (const :tag "Default" nil)
1056 (face :tag "Face" :value org-warning)
1057 (string :tag "String" :value "...#")))
1059 (defvar org-display-table nil
1060 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1062 (defgroup org-keywords nil
1063 "Keywords in Org-mode."
1064 :tag "Org Keywords"
1065 :group 'org)
1067 (defcustom org-closed-keep-when-no-todo nil
1068 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1069 :group 'org-todo
1070 :group 'org-keywords
1071 :version "24.4"
1072 :package-version '(Org . "8.0")
1073 :type 'boolean)
1075 (defgroup org-structure nil
1076 "Options concerning the general structure of Org-mode files."
1077 :tag "Org Structure"
1078 :group 'org)
1080 (defgroup org-reveal-location nil
1081 "Options about how to make context of a location visible."
1082 :tag "Org Reveal Location"
1083 :group 'org-structure)
1085 (defconst org-context-choice
1086 '(choice
1087 (const :tag "Always" t)
1088 (const :tag "Never" nil)
1089 (repeat :greedy t :tag "Individual contexts"
1090 (cons
1091 (choice :tag "Context"
1092 (const agenda)
1093 (const org-goto)
1094 (const occur-tree)
1095 (const tags-tree)
1096 (const link-search)
1097 (const mark-goto)
1098 (const bookmark-jump)
1099 (const isearch)
1100 (const default))
1101 (boolean))))
1102 "Contexts for the reveal options.")
1104 (defcustom org-show-hierarchy-above '((default . t))
1105 "Non-nil means show full hierarchy when revealing a location.
1106 Org-mode often shows locations in an org-mode file which might have
1107 been invisible before. When this is set, the hierarchy of headings
1108 above the exposed location is shown.
1109 Turning this off for example for sparse trees makes them very compact.
1110 Instead of t, this can also be an alist specifying this option for different
1111 contexts. Valid contexts are
1112 agenda when exposing an entry from the agenda
1113 org-goto when using the command `org-goto' on key C-c C-j
1114 occur-tree when using the command `org-occur' on key C-c /
1115 tags-tree when constructing a sparse tree based on tags matches
1116 link-search when exposing search matches associated with a link
1117 mark-goto when exposing the jump goal of a mark
1118 bookmark-jump when exposing a bookmark location
1119 isearch when exiting from an incremental search
1120 default default for all contexts not set explicitly"
1121 :group 'org-reveal-location
1122 :type org-context-choice)
1124 (defcustom org-show-following-heading '((default . nil))
1125 "Non-nil means show following heading when revealing a location.
1126 Org-mode often shows locations in an org-mode file which might have
1127 been invisible before. When this is set, the heading following the
1128 match is shown.
1129 Turning this off for example for sparse trees makes them very compact,
1130 but makes it harder to edit the location of the match. In such a case,
1131 use the command \\[org-reveal] to show more context.
1132 Instead of t, this can also be an alist specifying this option for different
1133 contexts. See `org-show-hierarchy-above' for valid contexts."
1134 :group 'org-reveal-location
1135 :type org-context-choice)
1137 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1138 "Non-nil means show all sibling heading when revealing a location.
1139 Org-mode often shows locations in an org-mode file which might have
1140 been invisible before. When this is set, the sibling of the current entry
1141 heading are all made visible. If `org-show-hierarchy-above' is t,
1142 the same happens on each level of the hierarchy above the current entry.
1144 By default this is on for the isearch context, off for all other contexts.
1145 Turning this off for example for sparse trees makes them very compact,
1146 but makes it harder to edit the location of the match. In such a case,
1147 use the command \\[org-reveal] to show more context.
1148 Instead of t, this can also be an alist specifying this option for different
1149 contexts. See `org-show-hierarchy-above' for valid contexts."
1150 :group 'org-reveal-location
1151 :type org-context-choice
1152 :version "24.4"
1153 :package-version '(Org . "8.0"))
1155 (defcustom org-show-entry-below '((default . nil))
1156 "Non-nil means show the entry below a headline when revealing a location.
1157 Org-mode often shows locations in an org-mode file which might have
1158 been invisible before. When this is set, the text below the headline that is
1159 exposed is also shown.
1161 By default this is off for all contexts.
1162 Instead of t, this can also be an alist specifying this option for different
1163 contexts. See `org-show-hierarchy-above' for valid contexts."
1164 :group 'org-reveal-location
1165 :type org-context-choice)
1167 (defcustom org-indirect-buffer-display 'other-window
1168 "How should indirect tree buffers be displayed?
1169 This applies to indirect buffers created with the commands
1170 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1171 Valid values are:
1172 current-window Display in the current window
1173 other-window Just display in another window.
1174 dedicated-frame Create one new frame, and re-use it each time.
1175 new-frame Make a new frame each time. Note that in this case
1176 previously-made indirect buffers are kept, and you need to
1177 kill these buffers yourself."
1178 :group 'org-structure
1179 :group 'org-agenda-windows
1180 :type '(choice
1181 (const :tag "In current window" current-window)
1182 (const :tag "In current frame, other window" other-window)
1183 (const :tag "Each time a new frame" new-frame)
1184 (const :tag "One dedicated frame" dedicated-frame)))
1186 (defcustom org-use-speed-commands nil
1187 "Non-nil means activate single letter commands at beginning of a headline.
1188 This may also be a function to test for appropriate locations where speed
1189 commands should be active.
1191 For example, to activate speed commands when the point is on any
1192 star at the beginning of the headline, you can do this:
1194 (setq org-use-speed-commands
1195 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1196 :group 'org-structure
1197 :type '(choice
1198 (const :tag "Never" nil)
1199 (const :tag "At beginning of headline stars" t)
1200 (function)))
1202 (defcustom org-speed-commands-user nil
1203 "Alist of additional speed commands.
1204 This list will be checked before `org-speed-commands-default'
1205 when the variable `org-use-speed-commands' is non-nil
1206 and when the cursor is at the beginning of a headline.
1207 The car if each entry is a string with a single letter, which must
1208 be assigned to `self-insert-command' in the global map.
1209 The cdr is either a command to be called interactively, a function
1210 to be called, or a form to be evaluated.
1211 An entry that is just a list with a single string will be interpreted
1212 as a descriptive headline that will be added when listing the speed
1213 commands in the Help buffer using the `?' speed command."
1214 :group 'org-structure
1215 :type '(repeat :value ("k" . ignore)
1216 (choice :value ("k" . ignore)
1217 (list :tag "Descriptive Headline" (string :tag "Headline"))
1218 (cons :tag "Letter and Command"
1219 (string :tag "Command letter")
1220 (choice
1221 (function)
1222 (sexp))))))
1224 (defcustom org-bookmark-names-plist
1225 '(:last-capture "org-capture-last-stored"
1226 :last-refile "org-refile-last-stored"
1227 :last-capture-marker "org-capture-last-stored-marker")
1228 "Names for bookmarks automatically set by some Org commands.
1229 This can provide strings as names for a number of bookmarks Org sets
1230 automatically. The following keys are currently implemented:
1231 :last-capture
1232 :last-capture-marker
1233 :last-refile
1234 When a key does not show up in the property list, the corresponding bookmark
1235 is not set."
1236 :group 'org-structure
1237 :type 'plist)
1239 (defgroup org-cycle nil
1240 "Options concerning visibility cycling in Org-mode."
1241 :tag "Org Cycle"
1242 :group 'org-structure)
1244 (defcustom org-cycle-skip-children-state-if-no-children t
1245 "Non-nil means skip CHILDREN state in entries that don't have any."
1246 :group 'org-cycle
1247 :type 'boolean)
1249 (defcustom org-cycle-max-level nil
1250 "Maximum level which should still be subject to visibility cycling.
1251 Levels higher than this will, for cycling, be treated as text, not a headline.
1252 When `org-odd-levels-only' is set, a value of N in this variable actually
1253 means 2N-1 stars as the limiting headline.
1254 When nil, cycle all levels.
1255 Note that the limiting level of cycling is also influenced by
1256 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1257 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1258 than its value."
1259 :group 'org-cycle
1260 :type '(choice
1261 (const :tag "No limit" nil)
1262 (integer :tag "Maximum level")))
1264 (defcustom org-hide-block-startup nil
1265 "Non-nil means entering Org-mode will fold all blocks.
1266 This can also be set in on a per-file basis with
1268 #+STARTUP: hideblocks
1269 #+STARTUP: showblocks"
1270 :group 'org-startup
1271 :group 'org-cycle
1272 :type 'boolean)
1274 (defcustom org-cycle-global-at-bob nil
1275 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1276 This makes it possible to do global cycling without having to use S-TAB or
1277 \\[universal-argument] TAB. For this special case to work, the first line
1278 of the buffer must not be a headline -- it may be empty or some other text.
1279 When used in this way, `org-cycle-hook' is disabled temporarily to make
1280 sure the cursor stays at the beginning of the buffer. When this option is
1281 nil, don't do anything special at the beginning of the buffer."
1282 :group 'org-cycle
1283 :type 'boolean)
1285 (defcustom org-cycle-level-after-item/entry-creation t
1286 "Non-nil means cycle entry level or item indentation in new empty entries.
1288 When the cursor is at the end of an empty headline, i.e., with only stars
1289 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1290 and then all possible ancestor states, before returning to the original state.
1291 This makes data entry extremely fast: M-RET to create a new headline,
1292 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1294 When the cursor is at the end of an empty plain list item, one TAB will
1295 make it a subitem, two or more tabs will back up to make this an item
1296 higher up in the item hierarchy."
1297 :group 'org-cycle
1298 :type 'boolean)
1300 (defcustom org-cycle-emulate-tab t
1301 "Where should `org-cycle' emulate TAB.
1302 nil Never
1303 white Only in completely white lines
1304 whitestart Only at the beginning of lines, before the first non-white char
1305 t Everywhere except in headlines
1306 exc-hl-bol Everywhere except at the start of a headline
1307 If TAB is used in a place where it does not emulate TAB, the current subtree
1308 visibility is cycled."
1309 :group 'org-cycle
1310 :type '(choice (const :tag "Never" nil)
1311 (const :tag "Only in completely white lines" white)
1312 (const :tag "Before first char in a line" whitestart)
1313 (const :tag "Everywhere except in headlines" t)
1314 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1316 (defcustom org-cycle-separator-lines 2
1317 "Number of empty lines needed to keep an empty line between collapsed trees.
1318 If you leave an empty line between the end of a subtree and the following
1319 headline, this empty line is hidden when the subtree is folded.
1320 Org-mode will leave (exactly) one empty line visible if the number of
1321 empty lines is equal or larger to the number given in this variable.
1322 So the default 2 means at least 2 empty lines after the end of a subtree
1323 are needed to produce free space between a collapsed subtree and the
1324 following headline.
1326 If the number is negative, and the number of empty lines is at least -N,
1327 all empty lines are shown.
1329 Special case: when 0, never leave empty lines in collapsed view."
1330 :group 'org-cycle
1331 :type 'integer)
1332 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1334 (defcustom org-pre-cycle-hook nil
1335 "Hook that is run before visibility cycling is happening.
1336 The function(s) in this hook must accept a single argument which indicates
1337 the new state that will be set right after running this hook. The
1338 argument is a symbol. Before a global state change, it can have the values
1339 `overview', `content', or `all'. Before a local state change, it can have
1340 the values `folded', `children', or `subtree'."
1341 :group 'org-cycle
1342 :type 'hook)
1344 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1345 org-cycle-hide-drawers
1346 org-cycle-hide-inline-tasks
1347 org-cycle-show-empty-lines
1348 org-optimize-window-after-visibility-change)
1349 "Hook that is run after `org-cycle' has changed the buffer visibility.
1350 The function(s) in this hook must accept a single argument which indicates
1351 the new state that was set by the most recent `org-cycle' command. The
1352 argument is a symbol. After a global state change, it can have the values
1353 `overview', `contents', or `all'. After a local state change, it can have
1354 the values `folded', `children', or `subtree'."
1355 :group 'org-cycle
1356 :type 'hook)
1358 (defgroup org-edit-structure nil
1359 "Options concerning structure editing in Org-mode."
1360 :tag "Org Edit Structure"
1361 :group 'org-structure)
1363 (defcustom org-odd-levels-only nil
1364 "Non-nil means skip even levels and only use odd levels for the outline.
1365 This has the effect that two stars are being added/taken away in
1366 promotion/demotion commands. It also influences how levels are
1367 handled by the exporters.
1368 Changing it requires restart of `font-lock-mode' to become effective
1369 for fontification also in regions already fontified.
1370 You may also set this on a per-file basis by adding one of the following
1371 lines to the buffer:
1373 #+STARTUP: odd
1374 #+STARTUP: oddeven"
1375 :group 'org-edit-structure
1376 :group 'org-appearance
1377 :type 'boolean)
1379 (defcustom org-adapt-indentation t
1380 "Non-nil means adapt indentation to outline node level.
1382 When this variable is set, Org assumes that you write outlines by
1383 indenting text in each node to align with the headline (after the stars).
1384 The following issues are influenced by this variable:
1386 - When this is set and the *entire* text in an entry is indented, the
1387 indentation is increased by one space in a demotion command, and
1388 decreased by one in a promotion command. If any line in the entry
1389 body starts with text at column 0, indentation is not changed at all.
1391 - Property drawers and planning information is inserted indented when
1392 this variable s set. When nil, they will not be indented.
1394 - TAB indents a line relative to context. The lines below a headline
1395 will be indented when this variable is set.
1397 Note that this is all about true indentation, by adding and removing
1398 space characters. See also `org-indent.el' which does level-dependent
1399 indentation in a virtual way, i.e. at display time in Emacs."
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defcustom org-special-ctrl-a/e nil
1404 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1406 When t, `C-a' will bring back the cursor to the beginning of the
1407 headline text, i.e. after the stars and after a possible TODO
1408 keyword. In an item, this will be the position after bullet and
1409 check-box, if any. When the cursor is already at that position,
1410 another `C-a' will bring it to the beginning of the line.
1412 `C-e' will jump to the end of the headline, ignoring the presence
1413 of tags in the headline. A second `C-e' will then jump to the
1414 true end of the line, after any tags. This also means that, when
1415 this variable is non-nil, `C-e' also will never jump beyond the
1416 end of the heading of a folded section, i.e. not after the
1417 ellipses.
1419 When set to the symbol `reversed', the first `C-a' or `C-e' works
1420 normally, going to the true line boundary first. Only a directly
1421 following, identical keypress will bring the cursor to the
1422 special positions.
1424 This may also be a cons cell where the behavior for `C-a' and
1425 `C-e' is set separately."
1426 :group 'org-edit-structure
1427 :type '(choice
1428 (const :tag "off" nil)
1429 (const :tag "on: after stars/bullet and before tags first" t)
1430 (const :tag "reversed: true line boundary first" reversed)
1431 (cons :tag "Set C-a and C-e separately"
1432 (choice :tag "Special C-a"
1433 (const :tag "off" nil)
1434 (const :tag "on: after stars/bullet first" t)
1435 (const :tag "reversed: before stars/bullet first" reversed))
1436 (choice :tag "Special C-e"
1437 (const :tag "off" nil)
1438 (const :tag "on: before tags first" t)
1439 (const :tag "reversed: after tags first" reversed)))))
1440 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1442 (defcustom org-special-ctrl-k nil
1443 "Non-nil means `C-k' will behave specially in headlines.
1444 When nil, `C-k' will call the default `kill-line' command.
1445 When t, the following will happen while the cursor is in the headline:
1447 - When the cursor is at the beginning of a headline, kill the entire
1448 line and possible the folded subtree below the line.
1449 - When in the middle of the headline text, kill the headline up to the tags.
1450 - When after the headline text, kill the tags."
1451 :group 'org-edit-structure
1452 :type 'boolean)
1454 (defcustom org-ctrl-k-protect-subtree nil
1455 "Non-nil means, do not delete a hidden subtree with C-k.
1456 When set to the symbol `error', simply throw an error when C-k is
1457 used to kill (part-of) a headline that has hidden text behind it.
1458 Any other non-nil value will result in a query to the user, if it is
1459 OK to kill that hidden subtree. When nil, kill without remorse."
1460 :group 'org-edit-structure
1461 :version "24.1"
1462 :type '(choice
1463 (const :tag "Do not protect hidden subtrees" nil)
1464 (const :tag "Protect hidden subtrees with a security query" t)
1465 (const :tag "Never kill a hidden subtree with C-k" error)))
1467 (defcustom org-special-ctrl-o t
1468 "Non-nil means, make `C-o' insert a row in tables."
1469 :group 'org-edit-structure
1470 :type 'boolean)
1472 (defcustom org-catch-invisible-edits nil
1473 "Check if in invisible region before inserting or deleting a character.
1474 Valid values are:
1476 nil Do not check, so just do invisible edits.
1477 error Throw an error and do nothing.
1478 show Make point visible, and do the requested edit.
1479 show-and-error Make point visible, then throw an error and abort the edit.
1480 smart Make point visible, and do insertion/deletion if it is
1481 adjacent to visible text and the change feels predictable.
1482 Never delete a previously invisible character or add in the
1483 middle or right after an invisible region. Basically, this
1484 allows insertion and backward-delete right before ellipses.
1485 FIXME: maybe in this case we should not even show?"
1486 :group 'org-edit-structure
1487 :version "24.1"
1488 :type '(choice
1489 (const :tag "Do not check" nil)
1490 (const :tag "Throw error when trying to edit" error)
1491 (const :tag "Unhide, but do not do the edit" show-and-error)
1492 (const :tag "Show invisible part and do the edit" show)
1493 (const :tag "Be smart and do the right thing" smart)))
1495 (defcustom org-yank-folded-subtrees t
1496 "Non-nil means when yanking subtrees, fold them.
1497 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1498 it starts with a heading and all other headings in it are either children
1499 or siblings, then fold all the subtrees. However, do this only if no
1500 text after the yank would be swallowed into a folded tree by this action."
1501 :group 'org-edit-structure
1502 :type 'boolean)
1504 (defcustom org-yank-adjusted-subtrees nil
1505 "Non-nil means when yanking subtrees, adjust the level.
1506 With this setting, `org-paste-subtree' is used to insert the subtree, see
1507 this function for details."
1508 :group 'org-edit-structure
1509 :type 'boolean)
1511 (defcustom org-M-RET-may-split-line '((default . t))
1512 "Non-nil means M-RET will split the line at the cursor position.
1513 When nil, it will go to the end of the line before making a
1514 new line.
1515 You may also set this option in a different way for different
1516 contexts. Valid contexts are:
1518 headline when creating a new headline
1519 item when creating a new item
1520 table in a table field
1521 default the value to be used for all contexts not explicitly
1522 customized"
1523 :group 'org-structure
1524 :group 'org-table
1525 :type '(choice
1526 (const :tag "Always" t)
1527 (const :tag "Never" nil)
1528 (repeat :greedy t :tag "Individual contexts"
1529 (cons
1530 (choice :tag "Context"
1531 (const headline)
1532 (const item)
1533 (const table)
1534 (const default))
1535 (boolean)))))
1538 (defcustom org-insert-heading-respect-content nil
1539 "Non-nil means insert new headings after the current subtree.
1540 When nil, the new heading is created directly after the current line.
1541 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1542 this variable on for the duration of the command."
1543 :group 'org-structure
1544 :type 'boolean)
1546 (defcustom org-blank-before-new-entry '((heading . auto)
1547 (plain-list-item . auto))
1548 "Should `org-insert-heading' leave a blank line before new heading/item?
1549 The value is an alist, with `heading' and `plain-list-item' as CAR,
1550 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1551 which case Org will look at the surrounding headings/items and try to
1552 make an intelligent decision whether to insert a blank line or not.
1554 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1555 the setting here is ignored and no empty line is inserted to avoid breaking
1556 the list structure."
1557 :group 'org-edit-structure
1558 :type '(list
1559 (cons (const heading)
1560 (choice (const :tag "Never" nil)
1561 (const :tag "Always" t)
1562 (const :tag "Auto" auto)))
1563 (cons (const plain-list-item)
1564 (choice (const :tag "Never" nil)
1565 (const :tag "Always" t)
1566 (const :tag "Auto" auto)))))
1568 (defcustom org-insert-heading-hook nil
1569 "Hook being run after inserting a new heading."
1570 :group 'org-edit-structure
1571 :type 'hook)
1573 (defcustom org-enable-fixed-width-editor t
1574 "Non-nil means lines starting with \":\" are treated as fixed-width.
1575 This currently only means they are never auto-wrapped.
1576 When nil, such lines will be treated like ordinary lines."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-goto-auto-isearch t
1581 "Non-nil means typing characters in `org-goto' starts incremental search.
1582 When nil, you can use these keybindings to navigate the buffer:
1584 q Quit the org-goto interface
1585 n Go to the next visible heading
1586 p Go to the previous visible heading
1587 f Go one heading forward on same level
1588 b Go one heading backward on same level
1589 u Go one heading up"
1590 :group 'org-edit-structure
1591 :type 'boolean)
1593 (defgroup org-sparse-trees nil
1594 "Options concerning sparse trees in Org-mode."
1595 :tag "Org Sparse Trees"
1596 :group 'org-structure)
1598 (defcustom org-highlight-sparse-tree-matches t
1599 "Non-nil means highlight all matches that define a sparse tree.
1600 The highlights will automatically disappear the next time the buffer is
1601 changed by an edit command."
1602 :group 'org-sparse-trees
1603 :type 'boolean)
1605 (defcustom org-remove-highlights-with-change t
1606 "Non-nil means any change to the buffer will remove temporary highlights.
1607 Such highlights are created by `org-occur' and `org-clock-display'.
1608 When nil, `C-c C-c needs to be used to get rid of the highlights.
1609 The highlights created by `org-preview-latex-fragment' always need
1610 `C-c C-c' to be removed."
1611 :group 'org-sparse-trees
1612 :group 'org-time
1613 :type 'boolean)
1616 (defcustom org-occur-hook '(org-first-headline-recenter)
1617 "Hook that is run after `org-occur' has constructed a sparse tree.
1618 This can be used to recenter the window to show as much of the structure
1619 as possible."
1620 :group 'org-sparse-trees
1621 :type 'hook)
1623 (defgroup org-imenu-and-speedbar nil
1624 "Options concerning imenu and speedbar in Org-mode."
1625 :tag "Org Imenu and Speedbar"
1626 :group 'org-structure)
1628 (defcustom org-imenu-depth 2
1629 "The maximum level for Imenu access to Org-mode headlines.
1630 This also applied for speedbar access."
1631 :group 'org-imenu-and-speedbar
1632 :type 'integer)
1634 (defgroup org-table nil
1635 "Options concerning tables in Org-mode."
1636 :tag "Org Table"
1637 :group 'org)
1639 (defcustom org-enable-table-editor 'optimized
1640 "Non-nil means lines starting with \"|\" are handled by the table editor.
1641 When nil, such lines will be treated like ordinary lines.
1643 When equal to the symbol `optimized', the table editor will be optimized to
1644 do the following:
1645 - Automatic overwrite mode in front of whitespace in table fields.
1646 This makes the structure of the table stay in tact as long as the edited
1647 field does not exceed the column width.
1648 - Minimize the number of realigns. Normally, the table is aligned each time
1649 TAB or RET are pressed to move to another field. With optimization this
1650 happens only if changes to a field might have changed the column width.
1651 Optimization requires replacing the functions `self-insert-command',
1652 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1653 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1654 very good at guessing when a re-align will be necessary, but you can always
1655 force one with \\[org-ctrl-c-ctrl-c].
1657 If you would like to use the optimized version in Org-mode, but the
1658 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1660 This variable can be used to turn on and off the table editor during a session,
1661 but in order to toggle optimization, a restart is required.
1663 See also the variable `org-table-auto-blank-field'."
1664 :group 'org-table
1665 :type '(choice
1666 (const :tag "off" nil)
1667 (const :tag "on" t)
1668 (const :tag "on, optimized" optimized)))
1670 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1671 (version<= emacs-version "24.1"))
1672 "Non-nil means cluster self-insert commands for undo when possible.
1673 If this is set, then, like in the Emacs command loop, 20 consecutive
1674 characters will be undone together.
1675 This is configurable, because there is some impact on typing performance."
1676 :group 'org-table
1677 :type 'boolean)
1679 (defcustom org-table-tab-recognizes-table.el t
1680 "Non-nil means TAB will automatically notice a table.el table.
1681 When it sees such a table, it moves point into it and - if necessary -
1682 calls `table-recognize-table'."
1683 :group 'org-table-editing
1684 :type 'boolean)
1686 (defgroup org-link nil
1687 "Options concerning links in Org-mode."
1688 :tag "Org Link"
1689 :group 'org)
1691 (defvar org-link-abbrev-alist-local nil
1692 "Buffer-local version of `org-link-abbrev-alist', which see.
1693 The value of this is taken from the #+LINK lines.")
1694 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1696 (defcustom org-link-abbrev-alist nil
1697 "Alist of link abbreviations.
1698 The car of each element is a string, to be replaced at the start of a link.
1699 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1700 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1702 [[linkkey:tag][description]]
1704 The 'linkkey' must be a word word, starting with a letter, followed
1705 by letters, numbers, '-' or '_'.
1707 If REPLACE is a string, the tag will simply be appended to create the link.
1708 If the string contains \"%s\", the tag will be inserted there. If the string
1709 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1710 at that point (see the function `url-hexify-string'). If the string contains
1711 the specifier \"%(my-function)\", then the custom function `my-function' will
1712 be invoked: this function takes the tag as its only argument and must return
1713 a string.
1715 REPLACE may also be a function that will be called with the tag as the
1716 only argument to create the link, which should be returned as a string.
1718 See the manual for examples."
1719 :group 'org-link
1720 :type '(repeat
1721 (cons
1722 (string :tag "Protocol")
1723 (choice
1724 (string :tag "Format")
1725 (function)))))
1727 (defcustom org-descriptive-links t
1728 "Non-nil means Org will display descriptive links.
1729 E.g. [[http://orgmode.org][Org website]] will be displayed as
1730 \"Org Website\", hiding the link itself and just displaying its
1731 description. When set to `nil', Org will display the full links
1732 literally.
1734 You can interactively set the value of this variable by calling
1735 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1736 :group 'org-link
1737 :type 'boolean)
1739 (defcustom org-link-file-path-type 'adaptive
1740 "How the path name in file links should be stored.
1741 Valid values are:
1743 relative Relative to the current directory, i.e. the directory of the file
1744 into which the link is being inserted.
1745 absolute Absolute path, if possible with ~ for home directory.
1746 noabbrev Absolute path, no abbreviation of home directory.
1747 adaptive Use relative path for files in the current directory and sub-
1748 directories of it. For other files, use an absolute path."
1749 :group 'org-link
1750 :type '(choice
1751 (const relative)
1752 (const absolute)
1753 (const noabbrev)
1754 (const adaptive)))
1756 (defvaralias 'org-activate-links 'org-highlight-links)
1757 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1758 "Types of links that should be highlighted in Org-mode files.
1760 This is a list of symbols, each one of them leading to the
1761 highlighting of a certain link type.
1763 You can still open links that are not highlighted.
1765 In principle, it does not hurt to turn on highlighting for all
1766 link types. There may be a small gain when turning off unused
1767 link types. The types are:
1769 bracket The recommended [[link][description]] or [[link]] links with hiding.
1770 angle Links in angular brackets that may contain whitespace like
1771 <bbdb:Carsten Dominik>.
1772 plain Plain links in normal text, no whitespace, like http://google.com.
1773 radio Text that is matched by a radio target, see manual for details.
1774 tag Tag settings in a headline (link to tag search).
1775 date Time stamps (link to calendar).
1776 footnote Footnote labels.
1778 If you set this variable during an Emacs session, use `org-mode-restart'
1779 in the Org buffer so that the change takes effect."
1780 :group 'org-link
1781 :group 'org-appearance
1782 :type '(set :greedy t
1783 (const :tag "Double bracket links" bracket)
1784 (const :tag "Angular bracket links" angle)
1785 (const :tag "Plain text links" plain)
1786 (const :tag "Radio target matches" radio)
1787 (const :tag "Tags" tag)
1788 (const :tag "Timestamps" date)
1789 (const :tag "Footnotes" footnote)))
1791 (defcustom org-make-link-description-function nil
1792 "Function to use for generating link descriptions from links.
1793 When nil, the link location will be used. This function must take
1794 two parameters: the first one is the link, the second one is the
1795 description generated by `org-insert-link'. The function should
1796 return the description to use."
1797 :group 'org-link
1798 :type '(choice (const nil) (function)))
1800 (defgroup org-link-store nil
1801 "Options concerning storing links in Org-mode."
1802 :tag "Org Store Link"
1803 :group 'org-link)
1805 (defcustom org-url-hexify-p t
1806 "When non-nil, hexify URL when creating a link."
1807 :type 'boolean
1808 :version "24.3"
1809 :group 'org-link-store)
1811 (defcustom org-email-link-description-format "Email %c: %.30s"
1812 "Format of the description part of a link to an email or usenet message.
1813 The following %-escapes will be replaced by corresponding information:
1815 %F full \"From\" field
1816 %f name, taken from \"From\" field, address if no name
1817 %T full \"To\" field
1818 %t first name in \"To\" field, address if no name
1819 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1820 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1821 %s subject
1822 %d date
1823 %m message-id.
1825 You may use normal field width specification between the % and the letter.
1826 This is for example useful to limit the length of the subject.
1828 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1829 :group 'org-link-store
1830 :type 'string)
1832 (defcustom org-from-is-user-regexp
1833 (let (r1 r2)
1834 (when (and user-mail-address (not (string= user-mail-address "")))
1835 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1836 (when (and user-full-name (not (string= user-full-name "")))
1837 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1838 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1839 "Regexp matched against the \"From:\" header of an email or usenet message.
1840 It should match if the message is from the user him/herself."
1841 :group 'org-link-store
1842 :type 'regexp)
1844 (defcustom org-context-in-file-links t
1845 "Non-nil means file links from `org-store-link' contain context.
1846 A search string will be added to the file name with :: as separator and
1847 used to find the context when the link is activated by the command
1848 `org-open-at-point'. When this option is t, the entire active region
1849 will be placed in the search string of the file link. If set to a
1850 positive integer, only the first n lines of context will be stored.
1852 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1853 negates this setting for the duration of the command."
1854 :group 'org-link-store
1855 :type '(choice boolean integer))
1857 (defcustom org-keep-stored-link-after-insertion nil
1858 "Non-nil means keep link in list for entire session.
1860 The command `org-store-link' adds a link pointing to the current
1861 location to an internal list. These links accumulate during a session.
1862 The command `org-insert-link' can be used to insert links into any
1863 Org-mode file (offering completion for all stored links). When this
1864 option is nil, every link which has been inserted once using \\[org-insert-link]
1865 will be removed from the list, to make completing the unused links
1866 more efficient."
1867 :group 'org-link-store
1868 :type 'boolean)
1870 (defgroup org-link-follow nil
1871 "Options concerning following links in Org-mode."
1872 :tag "Org Follow Link"
1873 :group 'org-link)
1875 (defcustom org-link-translation-function nil
1876 "Function to translate links with different syntax to Org syntax.
1877 This can be used to translate links created for example by the Planner
1878 or emacs-wiki packages to Org syntax.
1879 The function must accept two parameters, a TYPE containing the link
1880 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1881 which is everything after the link protocol. It should return a cons
1882 with possibly modified values of type and path.
1883 Org contains a function for this, so if you set this variable to
1884 `org-translate-link-from-planner', you should be able follow many
1885 links created by planner."
1886 :group 'org-link-follow
1887 :type '(choice (const nil) (function)))
1889 (defcustom org-follow-link-hook nil
1890 "Hook that is run after a link has been followed."
1891 :group 'org-link-follow
1892 :type 'hook)
1894 (defcustom org-tab-follows-link nil
1895 "Non-nil means on links TAB will follow the link.
1896 Needs to be set before org.el is loaded.
1897 This really should not be used, it does not make sense, and the
1898 implementation is bad."
1899 :group 'org-link-follow
1900 :type 'boolean)
1902 (defcustom org-return-follows-link nil
1903 "Non-nil means on links RET will follow the link.
1904 In tables, the special behavior of RET has precedence."
1905 :group 'org-link-follow
1906 :type 'boolean)
1908 (defcustom org-mouse-1-follows-link
1909 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1910 "Non-nil means mouse-1 on a link will follow the link.
1911 A longer mouse click will still set point. Does not work on XEmacs.
1912 Needs to be set before org.el is loaded."
1913 :group 'org-link-follow
1914 :version "24.4"
1915 :package-version '(Org . "8.3")
1916 :type '(choice
1917 (const :tag "A double click follows the link" double)
1918 (const :tag "Unconditionally follow the link with mouse-1" t)
1919 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1921 (defcustom org-mark-ring-length 4
1922 "Number of different positions to be recorded in the ring.
1923 Changing this requires a restart of Emacs to work correctly."
1924 :group 'org-link-follow
1925 :type 'integer)
1927 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1928 "Non-nil means internal links in Org files must exactly match a headline.
1929 When nil, the link search tries to match a phrase with all words
1930 in the search text."
1931 :group 'org-link-follow
1932 :version "24.1"
1933 :type '(choice
1934 (const :tag "Use fuzzy text search" nil)
1935 (const :tag "Match only exact headline" t)
1936 (const :tag "Match exact headline or query to create it"
1937 query-to-create)))
1939 (defcustom org-link-frame-setup
1940 '((vm . vm-visit-folder-other-frame)
1941 (vm-imap . vm-visit-imap-folder-other-frame)
1942 (gnus . org-gnus-no-new-news)
1943 (file . find-file-other-window)
1944 (wl . wl-other-frame))
1945 "Setup the frame configuration for following links.
1946 When following a link with Emacs, it may often be useful to display
1947 this link in another window or frame. This variable can be used to
1948 set this up for the different types of links.
1949 For VM, use any of
1950 `vm-visit-folder'
1951 `vm-visit-folder-other-window'
1952 `vm-visit-folder-other-frame'
1953 For Gnus, use any of
1954 `gnus'
1955 `gnus-other-frame'
1956 `org-gnus-no-new-news'
1957 For FILE, use any of
1958 `find-file'
1959 `find-file-other-window'
1960 `find-file-other-frame'
1961 For Wanderlust use any of
1962 `wl'
1963 `wl-other-frame'
1964 For the calendar, use the variable `calendar-setup'.
1965 For BBDB, it is currently only possible to display the matches in
1966 another window."
1967 :group 'org-link-follow
1968 :type '(list
1969 (cons (const vm)
1970 (choice
1971 (const vm-visit-folder)
1972 (const vm-visit-folder-other-window)
1973 (const vm-visit-folder-other-frame)))
1974 (cons (const vm-imap)
1975 (choice
1976 (const vm-visit-imap-folder)
1977 (const vm-visit-imap-folder-other-window)
1978 (const vm-visit-imap-folder-other-frame)))
1979 (cons (const gnus)
1980 (choice
1981 (const gnus)
1982 (const gnus-other-frame)
1983 (const org-gnus-no-new-news)))
1984 (cons (const file)
1985 (choice
1986 (const find-file)
1987 (const find-file-other-window)
1988 (const find-file-other-frame)))
1989 (cons (const wl)
1990 (choice
1991 (const wl)
1992 (const wl-other-frame)))))
1994 (defcustom org-display-internal-link-with-indirect-buffer nil
1995 "Non-nil means use indirect buffer to display infile links.
1996 Activating internal links (from one location in a file to another location
1997 in the same file) normally just jumps to the location. When the link is
1998 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1999 is displayed in
2000 another window. When this option is set, the other window actually displays
2001 an indirect buffer clone of the current buffer, to avoid any visibility
2002 changes to the current buffer."
2003 :group 'org-link-follow
2004 :type 'boolean)
2006 (defcustom org-open-non-existing-files nil
2007 "Non-nil means `org-open-file' will open non-existing files.
2008 When nil, an error will be generated.
2009 This variable applies only to external applications because they
2010 might choke on non-existing files. If the link is to a file that
2011 will be opened in Emacs, the variable is ignored."
2012 :group 'org-link-follow
2013 :type 'boolean)
2015 (defcustom org-open-directory-means-index-dot-org nil
2016 "Non-nil means a link to a directory really means to index.org.
2017 When nil, following a directory link will run dired or open a finder/explorer
2018 window on that directory."
2019 :group 'org-link-follow
2020 :type 'boolean)
2022 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2023 "Non-nil means ask for confirmation before executing shell links.
2024 Shell links can be dangerous: just think about a link
2026 [[shell:rm -rf ~/*][Google Search]]
2028 This link would show up in your Org-mode document as \"Google Search\",
2029 but really it would remove your entire home directory.
2030 Therefore we advise against setting this variable to nil.
2031 Just change it to `y-or-n-p' if you want to confirm with a
2032 single keystroke rather than having to type \"yes\"."
2033 :group 'org-link-follow
2034 :type '(choice
2035 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2036 (const :tag "with y-or-n (faster)" y-or-n-p)
2037 (const :tag "no confirmation (dangerous)" nil)))
2038 (put 'org-confirm-shell-link-function
2039 'safe-local-variable
2040 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2042 (defcustom org-confirm-shell-link-not-regexp ""
2043 "A regexp to skip confirmation for shell links."
2044 :group 'org-link-follow
2045 :version "24.1"
2046 :type 'regexp)
2048 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2049 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2050 Elisp links can be dangerous: just think about a link
2052 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2054 This link would show up in your Org-mode document as \"Google Search\",
2055 but really it would remove your entire home directory.
2056 Therefore we advise against setting this variable to nil.
2057 Just change it to `y-or-n-p' if you want to confirm with a
2058 single keystroke rather than having to type \"yes\"."
2059 :group 'org-link-follow
2060 :type '(choice
2061 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2062 (const :tag "with y-or-n (faster)" y-or-n-p)
2063 (const :tag "no confirmation (dangerous)" nil)))
2064 (put 'org-confirm-shell-link-function
2065 'safe-local-variable
2066 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2068 (defcustom org-confirm-elisp-link-not-regexp ""
2069 "A regexp to skip confirmation for Elisp links."
2070 :group 'org-link-follow
2071 :version "24.1"
2072 :type 'regexp)
2074 (defconst org-file-apps-defaults-gnu
2075 '((remote . emacs)
2076 (system . mailcap)
2077 (t . mailcap))
2078 "Default file applications on a UNIX or GNU/Linux system.
2079 See `org-file-apps'.")
2081 (defconst org-file-apps-defaults-macosx
2082 '((remote . emacs)
2083 (t . "open %s")
2084 (system . "open %s")
2085 ("ps.gz" . "gv %s")
2086 ("eps.gz" . "gv %s")
2087 ("dvi" . "xdvi %s")
2088 ("fig" . "xfig %s"))
2089 "Default file applications on a MacOS X system.
2090 The system \"open\" is known as a default, but we use X11 applications
2091 for some files for which the OS does not have a good default.
2092 See `org-file-apps'.")
2094 (defconst org-file-apps-defaults-windowsnt
2095 (list
2096 '(remote . emacs)
2097 (cons t
2098 (list (if (featurep 'xemacs)
2099 'mswindows-shell-execute
2100 'w32-shell-execute)
2101 "open" 'file))
2102 (cons 'system
2103 (list (if (featurep 'xemacs)
2104 'mswindows-shell-execute
2105 'w32-shell-execute)
2106 "open" 'file)))
2107 "Default file applications on a Windows NT system.
2108 The system \"open\" is used for most files.
2109 See `org-file-apps'.")
2111 (defcustom org-file-apps
2112 '((auto-mode . emacs)
2113 ("\\.mm\\'" . default)
2114 ("\\.x?html?\\'" . default)
2115 ("\\.pdf\\'" . default))
2116 "External applications for opening `file:path' items in a document.
2117 Org-mode uses system defaults for different file types, but
2118 you can use this variable to set the application for a given file
2119 extension. The entries in this list are cons cells where the car identifies
2120 files and the cdr the corresponding command. Possible values for the
2121 file identifier are
2122 \"string\" A string as a file identifier can be interpreted in different
2123 ways, depending on its contents:
2125 - Alphanumeric characters only:
2126 Match links with this file extension.
2127 Example: (\"pdf\" . \"evince %s\")
2128 to open PDFs with evince.
2130 - Regular expression: Match links where the
2131 filename matches the regexp. If you want to
2132 use groups here, use shy groups.
2134 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2135 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2136 to open *.html and *.xhtml with firefox.
2138 - Regular expression which contains (non-shy) groups:
2139 Match links where the whole link, including \"::\", and
2140 anything after that, matches the regexp.
2141 In a custom command string, %1, %2, etc. are replaced with
2142 the parts of the link that were matched by the groups.
2143 For backwards compatibility, if a command string is given
2144 that does not use any of the group matches, this case is
2145 handled identically to the second one (i.e. match against
2146 file name only).
2147 In a custom lisp form, you can access the group matches with
2148 (match-string n link).
2150 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2151 to open [[file:document.pdf::5]] with evince at page 5.
2153 `directory' Matches a directory
2154 `remote' Matches a remote file, accessible through tramp or efs.
2155 Remote files most likely should be visited through Emacs
2156 because external applications cannot handle such paths.
2157 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2158 so all files Emacs knows how to handle. Using this with
2159 command `emacs' will open most files in Emacs. Beware that this
2160 will also open html files inside Emacs, unless you add
2161 (\"html\" . default) to the list as well.
2162 t Default for files not matched by any of the other options.
2163 `system' The system command to open files, like `open' on Windows
2164 and Mac OS X, and mailcap under GNU/Linux. This is the command
2165 that will be selected if you call `C-c C-o' with a double
2166 \\[universal-argument] \\[universal-argument] prefix.
2168 Possible values for the command are:
2169 `emacs' The file will be visited by the current Emacs process.
2170 `default' Use the default application for this file type, which is the
2171 association for t in the list, most likely in the system-specific
2172 part.
2173 This can be used to overrule an unwanted setting in the
2174 system-specific variable.
2175 `system' Use the system command for opening files, like \"open\".
2176 This command is specified by the entry whose car is `system'.
2177 Most likely, the system-specific version of this variable
2178 does define this command, but you can overrule/replace it
2179 here.
2180 string A command to be executed by a shell; %s will be replaced
2181 by the path to the file.
2182 sexp A Lisp form which will be evaluated. The file path will
2183 be available in the Lisp variable `file'.
2184 For more examples, see the system specific constants
2185 `org-file-apps-defaults-macosx'
2186 `org-file-apps-defaults-windowsnt'
2187 `org-file-apps-defaults-gnu'."
2188 :group 'org-link-follow
2189 :type '(repeat
2190 (cons (choice :value ""
2191 (string :tag "Extension")
2192 (const :tag "System command to open files" system)
2193 (const :tag "Default for unrecognized files" t)
2194 (const :tag "Remote file" remote)
2195 (const :tag "Links to a directory" directory)
2196 (const :tag "Any files that have Emacs modes"
2197 auto-mode))
2198 (choice :value ""
2199 (const :tag "Visit with Emacs" emacs)
2200 (const :tag "Use default" default)
2201 (const :tag "Use the system command" system)
2202 (string :tag "Command")
2203 (sexp :tag "Lisp form")))))
2205 (defcustom org-doi-server-url "http://dx.doi.org/"
2206 "The URL of the DOI server."
2207 :type 'string
2208 :version "24.3"
2209 :group 'org-link-follow)
2211 (defgroup org-refile nil
2212 "Options concerning refiling entries in Org-mode."
2213 :tag "Org Refile"
2214 :group 'org)
2216 (defcustom org-directory "~/org"
2217 "Directory with org files.
2218 This is just a default location to look for Org files. There is no need
2219 at all to put your files into this directory. It is only used in the
2220 following situations:
2222 1. When a capture template specifies a target file that is not an
2223 absolute path. The path will then be interpreted relative to
2224 `org-directory'
2225 2. When a capture note is filed away in an interactive way (when exiting the
2226 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2227 with `org-directory' as the default path."
2228 :group 'org-refile
2229 :group 'org-capture
2230 :type 'directory)
2232 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2233 "Default target for storing notes.
2234 Used as a fall back file for org-capture.el, for templates that
2235 do not specify a target file."
2236 :group 'org-refile
2237 :group 'org-capture
2238 :type '(choice
2239 (const :tag "Default from remember-data-file" nil)
2240 file))
2242 (defcustom org-goto-interface 'outline
2243 "The default interface to be used for `org-goto'.
2244 Allowed values are:
2245 outline The interface shows an outline of the relevant file
2246 and the correct heading is found by moving through
2247 the outline or by searching with incremental search.
2248 outline-path-completion Headlines in the current buffer are offered via
2249 completion. This is the interface also used by
2250 the refile command."
2251 :group 'org-refile
2252 :type '(choice
2253 (const :tag "Outline" outline)
2254 (const :tag "Outline-path-completion" outline-path-completion)))
2256 (defcustom org-goto-max-level 5
2257 "Maximum target level when running `org-goto' with refile interface."
2258 :group 'org-refile
2259 :type 'integer)
2261 (defcustom org-reverse-note-order nil
2262 "Non-nil means store new notes at the beginning of a file or entry.
2263 When nil, new notes will be filed to the end of a file or entry.
2264 This can also be a list with cons cells of regular expressions that
2265 are matched against file names, and values."
2266 :group 'org-capture
2267 :group 'org-refile
2268 :type '(choice
2269 (const :tag "Reverse always" t)
2270 (const :tag "Reverse never" nil)
2271 (repeat :tag "By file name regexp"
2272 (cons regexp boolean))))
2274 (defcustom org-log-refile nil
2275 "Information to record when a task is refiled.
2277 Possible values are:
2279 nil Don't add anything
2280 time Add a time stamp to the task
2281 note Prompt for a note and add it with template `org-log-note-headings'
2283 This option can also be set with on a per-file-basis with
2285 #+STARTUP: nologrefile
2286 #+STARTUP: logrefile
2287 #+STARTUP: lognoterefile
2289 You can have local logging settings for a subtree by setting the LOGGING
2290 property to one or more of these keywords.
2292 When bulk-refiling from the agenda, the value `note' is forbidden and
2293 will temporarily be changed to `time'."
2294 :group 'org-refile
2295 :group 'org-progress
2296 :version "24.1"
2297 :type '(choice
2298 (const :tag "No logging" nil)
2299 (const :tag "Record timestamp" time)
2300 (const :tag "Record timestamp with note." note)))
2302 (defcustom org-refile-targets nil
2303 "Targets for refiling entries with \\[org-refile].
2304 This is a list of cons cells. Each cell contains:
2305 - a specification of the files to be considered, either a list of files,
2306 or a symbol whose function or variable value will be used to retrieve
2307 a file name or a list of file names. If you use `org-agenda-files' for
2308 that, all agenda files will be scanned for targets. Nil means consider
2309 headings in the current buffer.
2310 - A specification of how to find candidate refile targets. This may be
2311 any of:
2312 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2313 This tag has to be present in all target headlines, inheritance will
2314 not be considered.
2315 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2316 todo keyword.
2317 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2318 headlines that are refiling targets.
2319 - a cons cell (:level . N). Any headline of level N is considered a target.
2320 Note that, when `org-odd-levels-only' is set, level corresponds to
2321 order in hierarchy, not to the number of stars.
2322 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2323 Note that, when `org-odd-levels-only' is set, level corresponds to
2324 order in hierarchy, not to the number of stars.
2326 Each element of this list generates a set of possible targets.
2327 The union of these sets is presented (with completion) to
2328 the user by `org-refile'.
2330 You can set the variable `org-refile-target-verify-function' to a function
2331 to verify each headline found by the simple criteria above.
2333 When this variable is nil, all top-level headlines in the current buffer
2334 are used, equivalent to the value `((nil . (:level . 1))'."
2335 :group 'org-refile
2336 :type '(repeat
2337 (cons
2338 (choice :value org-agenda-files
2339 (const :tag "All agenda files" org-agenda-files)
2340 (const :tag "Current buffer" nil)
2341 (function) (variable) (file))
2342 (choice :tag "Identify target headline by"
2343 (cons :tag "Specific tag" (const :value :tag) (string))
2344 (cons :tag "TODO keyword" (const :value :todo) (string))
2345 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2346 (cons :tag "Level number" (const :value :level) (integer))
2347 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2349 (defcustom org-refile-target-verify-function nil
2350 "Function to verify if the headline at point should be a refile target.
2351 The function will be called without arguments, with point at the
2352 beginning of the headline. It should return t and leave point
2353 where it is if the headline is a valid target for refiling.
2355 If the target should not be selected, the function must return nil.
2356 In addition to this, it may move point to a place from where the search
2357 should be continued. For example, the function may decide that the entire
2358 subtree of the current entry should be excluded and move point to the end
2359 of the subtree."
2360 :group 'org-refile
2361 :type '(choice
2362 (const nil)
2363 (function)))
2365 (defcustom org-refile-use-cache nil
2366 "Non-nil means cache refile targets to speed up the process.
2367 The cache for a particular file will be updated automatically when
2368 the buffer has been killed, or when any of the marker used for flagging
2369 refile targets no longer points at a live buffer.
2370 If you have added new entries to a buffer that might themselves be targets,
2371 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2372 find that easier, `C-u C-u C-u C-c C-w'."
2373 :group 'org-refile
2374 :version "24.1"
2375 :type 'boolean)
2377 (defcustom org-refile-use-outline-path nil
2378 "Non-nil means provide refile targets as paths.
2379 So a level 3 headline will be available as level1/level2/level3.
2381 When the value is `file', also include the file name (without directory)
2382 into the path. In this case, you can also stop the completion after
2383 the file name, to get entries inserted as top level in the file.
2385 When `full-file-path', include the full file path."
2386 :group 'org-refile
2387 :type '(choice
2388 (const :tag "Not" nil)
2389 (const :tag "Yes" t)
2390 (const :tag "Start with file name" file)
2391 (const :tag "Start with full file path" full-file-path)))
2393 (defcustom org-outline-path-complete-in-steps t
2394 "Non-nil means complete the outline path in hierarchical steps.
2395 When Org-mode uses the refile interface to select an outline path
2396 \(see variable `org-refile-use-outline-path'), the completion of
2397 the path can be done is a single go, or if can be done in steps down
2398 the headline hierarchy. Going in steps is probably the best if you
2399 do not use a special completion package like `ido' or `icicles'.
2400 However, when using these packages, going in one step can be very
2401 fast, while still showing the whole path to the entry."
2402 :group 'org-refile
2403 :type 'boolean)
2405 (defcustom org-refile-allow-creating-parent-nodes nil
2406 "Non-nil means allow to create new nodes as refile targets.
2407 New nodes are then created by adding \"/new node name\" to the completion
2408 of an existing node. When the value of this variable is `confirm',
2409 new node creation must be confirmed by the user (recommended).
2410 When nil, the completion must match an existing entry.
2412 Note that, if the new heading is not seen by the criteria
2413 listed in `org-refile-targets', multiple instances of the same
2414 heading would be created by trying again to file under the new
2415 heading."
2416 :group 'org-refile
2417 :type '(choice
2418 (const :tag "Never" nil)
2419 (const :tag "Always" t)
2420 (const :tag "Prompt for confirmation" confirm)))
2422 (defcustom org-refile-active-region-within-subtree nil
2423 "Non-nil means also refile active region within a subtree.
2425 By default `org-refile' doesn't allow refiling regions if they
2426 don't contain a set of subtrees, but it might be convenient to
2427 do so sometimes: in that case, the first line of the region is
2428 converted to a headline before refiling."
2429 :group 'org-refile
2430 :version "24.1"
2431 :type 'boolean)
2433 (defgroup org-todo nil
2434 "Options concerning TODO items in Org-mode."
2435 :tag "Org TODO"
2436 :group 'org)
2438 (defgroup org-progress nil
2439 "Options concerning Progress logging in Org-mode."
2440 :tag "Org Progress"
2441 :group 'org-time)
2443 (defvar org-todo-interpretation-widgets
2444 '((:tag "Sequence (cycling hits every state)" sequence)
2445 (:tag "Type (cycling directly to DONE)" type))
2446 "The available interpretation symbols for customizing `org-todo-keywords'.
2447 Interested libraries should add to this list.")
2449 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2450 "List of TODO entry keyword sequences and their interpretation.
2451 \\<org-mode-map>This is a list of sequences.
2453 Each sequence starts with a symbol, either `sequence' or `type',
2454 indicating if the keywords should be interpreted as a sequence of
2455 action steps, or as different types of TODO items. The first
2456 keywords are states requiring action - these states will select a headline
2457 for inclusion into the global TODO list Org-mode produces. If one of
2458 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2459 signify that no further action is necessary. If \"|\" is not found,
2460 the last keyword is treated as the only DONE state of the sequence.
2462 The command \\[org-todo] cycles an entry through these states, and one
2463 additional state where no keyword is present. For details about this
2464 cycling, see the manual.
2466 TODO keywords and interpretation can also be set on a per-file basis with
2467 the special #+SEQ_TODO and #+TYP_TODO lines.
2469 Each keyword can optionally specify a character for fast state selection
2470 \(in combination with the variable `org-use-fast-todo-selection')
2471 and specifiers for state change logging, using the same syntax that
2472 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2473 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2474 indicates to record a time stamp each time this state is selected.
2476 Each keyword may also specify if a timestamp or a note should be
2477 recorded when entering or leaving the state, by adding additional
2478 characters in the parenthesis after the keyword. This looks like this:
2479 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2480 record only the time of the state change. With X and Y being either
2481 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2482 Y when leaving the state if and only if the *target* state does not
2483 define X. You may omit any of the fast-selection key or X or /Y,
2484 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2486 For backward compatibility, this variable may also be just a list
2487 of keywords. In this case the interpretation (sequence or type) will be
2488 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2489 :group 'org-todo
2490 :group 'org-keywords
2491 :type '(choice
2492 (repeat :tag "Old syntax, just keywords"
2493 (string :tag "Keyword"))
2494 (repeat :tag "New syntax"
2495 (cons
2496 (choice
2497 :tag "Interpretation"
2498 ;;Quick and dirty way to see
2499 ;;`org-todo-interpretations'. This takes the
2500 ;;place of item arguments
2501 :convert-widget
2502 (lambda (widget)
2503 (widget-put widget
2504 :args (mapcar
2505 (lambda (x)
2506 (widget-convert
2507 (cons 'const x)))
2508 org-todo-interpretation-widgets))
2509 widget))
2510 (repeat
2511 (string :tag "Keyword"))))))
2513 (defvar org-todo-keywords-1 nil
2514 "All TODO and DONE keywords active in a buffer.")
2515 (make-variable-buffer-local 'org-todo-keywords-1)
2516 (defvar org-todo-keywords-for-agenda nil)
2517 (defvar org-done-keywords-for-agenda nil)
2518 (defvar org-todo-keyword-alist-for-agenda nil)
2519 (defvar org-tag-alist-for-agenda nil
2520 "Alist of all tags from all agenda files.")
2521 (defvar org-tag-groups-alist-for-agenda nil
2522 "Alist of all groups tags from all current agenda files.")
2523 (defvar org-tag-groups-alist nil)
2524 (make-variable-buffer-local 'org-tag-groups-alist)
2525 (defvar org-agenda-contributing-files nil)
2526 (defvar org-not-done-keywords nil)
2527 (make-variable-buffer-local 'org-not-done-keywords)
2528 (defvar org-done-keywords nil)
2529 (make-variable-buffer-local 'org-done-keywords)
2530 (defvar org-todo-heads nil)
2531 (make-variable-buffer-local 'org-todo-heads)
2532 (defvar org-todo-sets nil)
2533 (make-variable-buffer-local 'org-todo-sets)
2534 (defvar org-todo-log-states nil)
2535 (make-variable-buffer-local 'org-todo-log-states)
2536 (defvar org-todo-kwd-alist nil)
2537 (make-variable-buffer-local 'org-todo-kwd-alist)
2538 (defvar org-todo-key-alist nil)
2539 (make-variable-buffer-local 'org-todo-key-alist)
2540 (defvar org-todo-key-trigger nil)
2541 (make-variable-buffer-local 'org-todo-key-trigger)
2543 (defcustom org-todo-interpretation 'sequence
2544 "Controls how TODO keywords are interpreted.
2545 This variable is in principle obsolete and is only used for
2546 backward compatibility, if the interpretation of todo keywords is
2547 not given already in `org-todo-keywords'. See that variable for
2548 more information."
2549 :group 'org-todo
2550 :group 'org-keywords
2551 :type '(choice (const sequence)
2552 (const type)))
2554 (defcustom org-use-fast-todo-selection t
2555 "Non-nil means use the fast todo selection scheme with C-c C-t.
2556 This variable describes if and under what circumstances the cycling
2557 mechanism for TODO keywords will be replaced by a single-key, direct
2558 selection scheme.
2560 When nil, fast selection is never used.
2562 When the symbol `prefix', it will be used when `org-todo' is called
2563 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2564 `C-u t' in an agenda buffer.
2566 When t, fast selection is used by default. In this case, the prefix
2567 argument forces cycling instead.
2569 In all cases, the special interface is only used if access keys have
2570 actually been assigned by the user, i.e. if keywords in the configuration
2571 are followed by a letter in parenthesis, like TODO(t)."
2572 :group 'org-todo
2573 :type '(choice
2574 (const :tag "Never" nil)
2575 (const :tag "By default" t)
2576 (const :tag "Only with C-u C-c C-t" prefix)))
2578 (defcustom org-provide-todo-statistics t
2579 "Non-nil means update todo statistics after insert and toggle.
2580 ALL-HEADLINES means update todo statistics by including headlines
2581 with no TODO keyword as well, counting them as not done.
2582 A list of TODO keywords means the same, but skip keywords that are
2583 not in this list.
2584 When set to a list of two lists, the first list contains keywords
2585 to consider as TODO keywords, the second list contains keywords
2586 to consider as DONE keywords.
2588 When this is set, todo statistics is updated in the parent of the
2589 current entry each time a todo state is changed."
2590 :group 'org-todo
2591 :type '(choice
2592 (const :tag "Yes, only for TODO entries" t)
2593 (const :tag "Yes, including all entries" all-headlines)
2594 (repeat :tag "Yes, for TODOs in this list"
2595 (string :tag "TODO keyword"))
2596 (list :tag "Yes, for TODOs and DONEs in these lists"
2597 (repeat (string :tag "TODO keyword"))
2598 (repeat (string :tag "DONE keyword")))
2599 (other :tag "No TODO statistics" nil)))
2601 (defcustom org-hierarchical-todo-statistics t
2602 "Non-nil means TODO statistics covers just direct children.
2603 When nil, all entries in the subtree are considered.
2604 This has only an effect if `org-provide-todo-statistics' is set.
2605 To set this to nil for only a single subtree, use a COOKIE_DATA
2606 property and include the word \"recursive\" into the value."
2607 :group 'org-todo
2608 :type 'boolean)
2610 (defcustom org-after-todo-state-change-hook nil
2611 "Hook which is run after the state of a TODO item was changed.
2612 The new state (a string with a TODO keyword, or nil) is available in the
2613 Lisp variable `org-state'."
2614 :group 'org-todo
2615 :type 'hook)
2617 (defvar org-blocker-hook nil
2618 "Hook for functions that are allowed to block a state change.
2620 Functions in this hook should not modify the buffer.
2621 Each function gets as its single argument a property list,
2622 see `org-trigger-hook' for more information about this list.
2624 If any of the functions in this hook returns nil, the state change
2625 is blocked.")
2627 (defvar org-trigger-hook nil
2628 "Hook for functions that are triggered by a state change.
2630 Each function gets as its single argument a property list with at
2631 least the following elements:
2633 (:type type-of-change :position pos-at-entry-start
2634 :from old-state :to new-state)
2636 Depending on the type, more properties may be present.
2638 This mechanism is currently implemented for:
2640 TODO state changes
2641 ------------------
2642 :type todo-state-change
2643 :from previous state (keyword as a string), or nil, or a symbol
2644 'todo' or 'done', to indicate the general type of state.
2645 :to new state, like in :from")
2647 (defcustom org-enforce-todo-dependencies nil
2648 "Non-nil means undone TODO entries will block switching the parent to DONE.
2649 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2650 be blocked if any prior sibling is not yet done.
2651 Finally, if the parent is blocked because of ordered siblings of its own,
2652 the child will also be blocked."
2653 :set (lambda (var val)
2654 (set var val)
2655 (if val
2656 (add-hook 'org-blocker-hook
2657 'org-block-todo-from-children-or-siblings-or-parent)
2658 (remove-hook 'org-blocker-hook
2659 'org-block-todo-from-children-or-siblings-or-parent)))
2660 :group 'org-todo
2661 :type 'boolean)
2663 (defcustom org-enforce-todo-checkbox-dependencies nil
2664 "Non-nil means unchecked boxes will block switching the parent to DONE.
2665 When this is nil, checkboxes have no influence on switching TODO states.
2666 When non-nil, you first need to check off all check boxes before the TODO
2667 entry can be switched to DONE.
2668 This variable needs to be set before org.el is loaded, and you need to
2669 restart Emacs after a change to make the change effective. The only way
2670 to change is while Emacs is running is through the customize interface."
2671 :set (lambda (var val)
2672 (set var val)
2673 (if val
2674 (add-hook 'org-blocker-hook
2675 'org-block-todo-from-checkboxes)
2676 (remove-hook 'org-blocker-hook
2677 'org-block-todo-from-checkboxes)))
2678 :group 'org-todo
2679 :type 'boolean)
2681 (defcustom org-treat-insert-todo-heading-as-state-change nil
2682 "Non-nil means inserting a TODO heading is treated as state change.
2683 So when the command \\[org-insert-todo-heading] is used, state change
2684 logging will apply if appropriate. When nil, the new TODO item will
2685 be inserted directly, and no logging will take place."
2686 :group 'org-todo
2687 :type 'boolean)
2689 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2690 "Non-nil means switching TODO states with S-cursor counts as state change.
2691 This is the default behavior. However, setting this to nil allows a
2692 convenient way to select a TODO state and bypass any logging associated
2693 with that."
2694 :group 'org-todo
2695 :type 'boolean)
2697 (defcustom org-todo-state-tags-triggers nil
2698 "Tag changes that should be triggered by TODO state changes.
2699 This is a list. Each entry is
2701 (state-change (tag . flag) .......)
2703 State-change can be a string with a state, and empty string to indicate the
2704 state that has no TODO keyword, or it can be one of the symbols `todo'
2705 or `done', meaning any not-done or done state, respectively."
2706 :group 'org-todo
2707 :group 'org-tags
2708 :type '(repeat
2709 (cons (choice :tag "When changing to"
2710 (const :tag "Not-done state" todo)
2711 (const :tag "Done state" done)
2712 (string :tag "State"))
2713 (repeat
2714 (cons :tag "Tag action"
2715 (string :tag "Tag")
2716 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2718 (defcustom org-log-done nil
2719 "Information to record when a task moves to the DONE state.
2721 Possible values are:
2723 nil Don't add anything, just change the keyword
2724 time Add a time stamp to the task
2725 note Prompt for a note and add it with template `org-log-note-headings'
2727 This option can also be set with on a per-file-basis with
2729 #+STARTUP: nologdone
2730 #+STARTUP: logdone
2731 #+STARTUP: lognotedone
2733 You can have local logging settings for a subtree by setting the LOGGING
2734 property to one or more of these keywords."
2735 :group 'org-todo
2736 :group 'org-progress
2737 :type '(choice
2738 (const :tag "No logging" nil)
2739 (const :tag "Record CLOSED timestamp" time)
2740 (const :tag "Record CLOSED timestamp with note." note)))
2742 ;; Normalize old uses of org-log-done.
2743 (cond
2744 ((eq org-log-done t) (setq org-log-done 'time))
2745 ((and (listp org-log-done) (memq 'done org-log-done))
2746 (setq org-log-done 'note)))
2748 (defcustom org-log-reschedule nil
2749 "Information to record when the scheduling date of a tasks is modified.
2751 Possible values are:
2753 nil Don't add anything, just change the date
2754 time Add a time stamp to the task
2755 note Prompt for a note and add it with template `org-log-note-headings'
2757 This option can also be set with on a per-file-basis with
2759 #+STARTUP: nologreschedule
2760 #+STARTUP: logreschedule
2761 #+STARTUP: lognotereschedule"
2762 :group 'org-todo
2763 :group 'org-progress
2764 :type '(choice
2765 (const :tag "No logging" nil)
2766 (const :tag "Record timestamp" time)
2767 (const :tag "Record timestamp with note." note)))
2769 (defcustom org-log-redeadline nil
2770 "Information to record when the deadline date of a tasks is modified.
2772 Possible values are:
2774 nil Don't add anything, just change the date
2775 time Add a time stamp to the task
2776 note Prompt for a note and add it with template `org-log-note-headings'
2778 This option can also be set with on a per-file-basis with
2780 #+STARTUP: nologredeadline
2781 #+STARTUP: logredeadline
2782 #+STARTUP: lognoteredeadline
2784 You can have local logging settings for a subtree by setting the LOGGING
2785 property to one or more of these keywords."
2786 :group 'org-todo
2787 :group 'org-progress
2788 :type '(choice
2789 (const :tag "No logging" nil)
2790 (const :tag "Record timestamp" time)
2791 (const :tag "Record timestamp with note." note)))
2793 (defcustom org-log-note-clock-out nil
2794 "Non-nil means record a note when clocking out of an item.
2795 This can also be configured on a per-file basis by adding one of
2796 the following lines anywhere in the buffer:
2798 #+STARTUP: lognoteclock-out
2799 #+STARTUP: nolognoteclock-out"
2800 :group 'org-todo
2801 :group 'org-progress
2802 :type 'boolean)
2804 (defcustom org-log-done-with-time t
2805 "Non-nil means the CLOSED time stamp will contain date and time.
2806 When nil, only the date will be recorded."
2807 :group 'org-progress
2808 :type 'boolean)
2810 (defcustom org-log-note-headings
2811 '((done . "CLOSING NOTE %t")
2812 (state . "State %-12s from %-12S %t")
2813 (note . "Note taken on %t")
2814 (reschedule . "Rescheduled from %S on %t")
2815 (delschedule . "Not scheduled, was %S on %t")
2816 (redeadline . "New deadline from %S on %t")
2817 (deldeadline . "Removed deadline, was %S on %t")
2818 (refile . "Refiled on %t")
2819 (clock-out . ""))
2820 "Headings for notes added to entries.
2821 The value is an alist, with the car being a symbol indicating the note
2822 context, and the cdr is the heading to be used. The heading may also be the
2823 empty string.
2824 %t in the heading will be replaced by a time stamp.
2825 %T will be an active time stamp instead the default inactive one
2826 %d will be replaced by a short-format time stamp.
2827 %D will be replaced by an active short-format time stamp.
2828 %s will be replaced by the new TODO state, in double quotes.
2829 %S will be replaced by the old TODO state, in double quotes.
2830 %u will be replaced by the user name.
2831 %U will be replaced by the full user name.
2833 In fact, it is not a good idea to change the `state' entry, because
2834 agenda log mode depends on the format of these entries."
2835 :group 'org-todo
2836 :group 'org-progress
2837 :type '(list :greedy t
2838 (cons (const :tag "Heading when closing an item" done) string)
2839 (cons (const :tag
2840 "Heading when changing todo state (todo sequence only)"
2841 state) string)
2842 (cons (const :tag "Heading when just taking a note" note) string)
2843 (cons (const :tag "Heading when rescheduling" reschedule) string)
2844 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2845 (cons (const :tag "Heading when changing deadline" redeadline) string)
2846 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2847 (cons (const :tag "Heading when refiling" refile) string)
2848 (cons (const :tag "Heading when clocking out" clock-out) string)))
2850 (unless (assq 'note org-log-note-headings)
2851 (push '(note . "%t") org-log-note-headings))
2853 (defcustom org-log-into-drawer nil
2854 "Non-nil means insert state change notes and time stamps into a drawer.
2855 When nil, state changes notes will be inserted after the headline and
2856 any scheduling and clock lines, but not inside a drawer.
2858 The value of this variable should be the name of the drawer to use.
2859 LOGBOOK is proposed as the default drawer for this purpose, you can
2860 also set this to a string to define the drawer of your choice.
2862 A value of t is also allowed, representing \"LOGBOOK\".
2864 A value of t or nil can also be set with on a per-file-basis with
2866 #+STARTUP: logdrawer
2867 #+STARTUP: nologdrawer
2869 If this variable is set, `org-log-state-notes-insert-after-drawers'
2870 will be ignored.
2872 You can set the property LOG_INTO_DRAWER to overrule this setting for
2873 a subtree."
2874 :group 'org-todo
2875 :group 'org-progress
2876 :type '(choice
2877 (const :tag "Not into a drawer" nil)
2878 (const :tag "LOGBOOK" t)
2879 (string :tag "Other")))
2881 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2883 (defun org-log-into-drawer ()
2884 "Return the value of `org-log-into-drawer', but let properties overrule.
2885 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2886 used instead of the default value."
2887 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2888 (cond
2889 ((not p) org-log-into-drawer)
2890 ((equal p "nil") nil)
2891 ((equal p "t") "LOGBOOK")
2892 (t p))))
2894 (defcustom org-log-state-notes-insert-after-drawers nil
2895 "Non-nil means insert state change notes after any drawers in entry.
2896 Only the drawers that *immediately* follow the headline and the
2897 deadline/scheduled line are skipped.
2898 When nil, insert notes right after the heading and perhaps the line
2899 with deadline/scheduling if present.
2901 This variable will have no effect if `org-log-into-drawer' is
2902 set."
2903 :group 'org-todo
2904 :group 'org-progress
2905 :type 'boolean)
2907 (defcustom org-log-states-order-reversed t
2908 "Non-nil means the latest state note will be directly after heading.
2909 When nil, the state change notes will be ordered according to time.
2911 This option can also be set with on a per-file-basis with
2913 #+STARTUP: logstatesreversed
2914 #+STARTUP: nologstatesreversed"
2915 :group 'org-todo
2916 :group 'org-progress
2917 :type 'boolean)
2919 (defcustom org-todo-repeat-to-state nil
2920 "The TODO state to which a repeater should return the repeating task.
2921 By default this is the first task in a TODO sequence, or the previous state
2922 in a TODO_TYP set. But you can specify another task here.
2923 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2924 :group 'org-todo
2925 :version "24.1"
2926 :type '(choice (const :tag "Head of sequence" nil)
2927 (string :tag "Specific state")))
2929 (defcustom org-log-repeat 'time
2930 "Non-nil means record moving through the DONE state when triggering repeat.
2931 An auto-repeating task is immediately switched back to TODO when
2932 marked DONE. If you are not logging state changes (by adding \"@\"
2933 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2934 record a closing note, there will be no record of the task moving
2935 through DONE. This variable forces taking a note anyway.
2937 nil Don't force a record
2938 time Record a time stamp
2939 note Prompt for a note and add it with template `org-log-note-headings'
2941 This option can also be set with on a per-file-basis with
2943 #+STARTUP: nologrepeat
2944 #+STARTUP: logrepeat
2945 #+STARTUP: lognoterepeat
2947 You can have local logging settings for a subtree by setting the LOGGING
2948 property to one or more of these keywords."
2949 :group 'org-todo
2950 :group 'org-progress
2951 :type '(choice
2952 (const :tag "Don't force a record" nil)
2953 (const :tag "Force recording the DONE state" time)
2954 (const :tag "Force recording a note with the DONE state" note)))
2957 (defgroup org-priorities nil
2958 "Priorities in Org-mode."
2959 :tag "Org Priorities"
2960 :group 'org-todo)
2962 (defcustom org-enable-priority-commands t
2963 "Non-nil means priority commands are active.
2964 When nil, these commands will be disabled, so that you never accidentally
2965 set a priority."
2966 :group 'org-priorities
2967 :type 'boolean)
2969 (defcustom org-highest-priority ?A
2970 "The highest priority of TODO items. A character like ?A, ?B etc.
2971 Must have a smaller ASCII number than `org-lowest-priority'."
2972 :group 'org-priorities
2973 :type 'character)
2975 (defcustom org-lowest-priority ?C
2976 "The lowest priority of TODO items. A character like ?A, ?B etc.
2977 Must have a larger ASCII number than `org-highest-priority'."
2978 :group 'org-priorities
2979 :type 'character)
2981 (defcustom org-default-priority ?B
2982 "The default priority of TODO items.
2983 This is the priority an item gets if no explicit priority is given.
2984 When starting to cycle on an empty priority the first step in the cycle
2985 depends on `org-priority-start-cycle-with-default'. The resulting first
2986 step priority must not exceed the range from `org-highest-priority' to
2987 `org-lowest-priority' which means that `org-default-priority' has to be
2988 in this range exclusive or inclusive the range boundaries. Else the
2989 first step refuses to set the default and the second will fall back
2990 to (depending on the command used) the highest or lowest priority."
2991 :group 'org-priorities
2992 :type 'character)
2994 (defcustom org-priority-start-cycle-with-default t
2995 "Non-nil means start with default priority when starting to cycle.
2996 When this is nil, the first step in the cycle will be (depending on the
2997 command used) one higher or lower than the default priority.
2998 See also `org-default-priority'."
2999 :group 'org-priorities
3000 :type 'boolean)
3002 (defcustom org-get-priority-function nil
3003 "Function to extract the priority from a string.
3004 The string is normally the headline. If this is nil Org computes the
3005 priority from the priority cookie like [#A] in the headline. It returns
3006 an integer, increasing by 1000 for each priority level.
3007 The user can set a different function here, which should take a string
3008 as an argument and return the numeric priority."
3009 :group 'org-priorities
3010 :version "24.1"
3011 :type '(choice
3012 (const nil)
3013 (function)))
3015 (defgroup org-time nil
3016 "Options concerning time stamps and deadlines in Org-mode."
3017 :tag "Org Time"
3018 :group 'org)
3020 (defcustom org-insert-labeled-timestamps-at-point nil
3021 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3022 When nil, these labeled time stamps are forces into the second line of an
3023 entry, just after the headline. When scheduling from the global TODO list,
3024 the time stamp will always be forced into the second line."
3025 :group 'org-time
3026 :type 'boolean)
3028 (defcustom org-time-stamp-rounding-minutes '(0 5)
3029 "Number of minutes to round time stamps to.
3030 These are two values, the first applies when first creating a time stamp.
3031 The second applies when changing it with the commands `S-up' and `S-down'.
3032 When changing the time stamp, this means that it will change in steps
3033 of N minutes, as given by the second value.
3035 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3036 numbers should be factors of 60, so for example 5, 10, 15.
3038 When this is larger than 1, you can still force an exact time stamp by using
3039 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3040 and by using a prefix arg to `S-up/down' to specify the exact number
3041 of minutes to shift."
3042 :group 'org-time
3043 :get (lambda (var) ; Make sure both elements are there
3044 (if (integerp (default-value var))
3045 (list (default-value var) 5)
3046 (default-value var)))
3047 :type '(list
3048 (integer :tag "when inserting times")
3049 (integer :tag "when modifying times")))
3051 ;; Normalize old customizations of this variable.
3052 (when (integerp org-time-stamp-rounding-minutes)
3053 (setq org-time-stamp-rounding-minutes
3054 (list org-time-stamp-rounding-minutes
3055 org-time-stamp-rounding-minutes)))
3057 (defcustom org-display-custom-times nil
3058 "Non-nil means overlay custom formats over all time stamps.
3059 The formats are defined through the variable `org-time-stamp-custom-formats'.
3060 To turn this on on a per-file basis, insert anywhere in the file:
3061 #+STARTUP: customtime"
3062 :group 'org-time
3063 :set 'set-default
3064 :type 'sexp)
3065 (make-variable-buffer-local 'org-display-custom-times)
3067 (defcustom org-time-stamp-custom-formats
3068 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3069 "Custom formats for time stamps. See `format-time-string' for the syntax.
3070 These are overlaid over the default ISO format if the variable
3071 `org-display-custom-times' is set. Time like %H:%M should be at the
3072 end of the second format. The custom formats are also honored by export
3073 commands, if custom time display is turned on at the time of export."
3074 :group 'org-time
3075 :type 'sexp)
3077 (defun org-time-stamp-format (&optional long inactive)
3078 "Get the right format for a time string."
3079 (let ((f (if long (cdr org-time-stamp-formats)
3080 (car org-time-stamp-formats))))
3081 (if inactive
3082 (concat "[" (substring f 1 -1) "]")
3083 f)))
3085 (defcustom org-time-clocksum-format
3086 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3087 "The format string used when creating CLOCKSUM lines.
3088 This is also used when Org mode generates a time duration.
3090 The value can be a single format string containing two
3091 %-sequences, which will be filled with the number of hours and
3092 minutes in that order.
3094 Alternatively, the value can be a plist associating any of the
3095 keys :years, :months, :weeks, :days, :hours or :minutes with
3096 format strings. The time duration is formatted using only the
3097 time components that are needed and concatenating the results.
3098 If a time unit in absent, it falls back to the next smallest
3099 unit.
3101 The keys :require-years, :require-months, :require-days,
3102 :require-weeks, :require-hours, :require-minutes are also
3103 meaningful. A non-nil value for these keys indicates that the
3104 corresponding time component should always be included, even if
3105 its value is 0.
3108 For example,
3110 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3111 :require-minutes t)
3113 means durations longer than a day will be expressed in days,
3114 hours and minutes, and durations less than a day will always be
3115 expressed in hours and minutes (even for durations less than an
3116 hour).
3118 The value
3120 \(:days \"%dd\" :minutes \"%dm\")
3122 means durations longer than a day will be expressed in days and
3123 minutes, and durations less than a day will be expressed entirely
3124 in minutes (even for durations longer than an hour)."
3125 :group 'org-time
3126 :group 'org-clock
3127 :version "24.4"
3128 :package-version '(Org . "8.0")
3129 :type '(choice (string :tag "Format string")
3130 (set :tag "Plist"
3131 (group :inline t (const :tag "Years" :years)
3132 (string :tag "Format string"))
3133 (group :inline t
3134 (const :tag "Always show years" :require-years)
3135 (const t))
3136 (group :inline t (const :tag "Months" :months)
3137 (string :tag "Format string"))
3138 (group :inline t
3139 (const :tag "Always show months" :require-months)
3140 (const t))
3141 (group :inline t (const :tag "Weeks" :weeks)
3142 (string :tag "Format string"))
3143 (group :inline t
3144 (const :tag "Always show weeks" :require-weeks)
3145 (const t))
3146 (group :inline t (const :tag "Days" :days)
3147 (string :tag "Format string"))
3148 (group :inline t
3149 (const :tag "Always show days" :require-days)
3150 (const t))
3151 (group :inline t (const :tag "Hours" :hours)
3152 (string :tag "Format string"))
3153 (group :inline t
3154 (const :tag "Always show hours" :require-hours)
3155 (const t))
3156 (group :inline t (const :tag "Minutes" :minutes)
3157 (string :tag "Format string"))
3158 (group :inline t
3159 (const :tag "Always show minutes" :require-minutes)
3160 (const t)))))
3162 (defcustom org-time-clocksum-use-fractional nil
3163 "When non-nil, \\[org-clock-display] uses fractional times.
3164 See `org-time-clocksum-format' for more on time clock formats."
3165 :group 'org-time
3166 :group 'org-clock
3167 :version "24.3"
3168 :type 'boolean)
3170 (defcustom org-time-clocksum-use-effort-durations nil
3171 "When non-nil, \\[org-clock-display] uses effort durations.
3172 E.g. by default, one day is considered to be a 8 hours effort,
3173 so a task that has been clocked for 16 hours will be displayed
3174 as during 2 days in the clock display or in the clocktable.
3176 See `org-effort-durations' on how to set effort durations
3177 and `org-time-clocksum-format' for more on time clock formats."
3178 :group 'org-time
3179 :group 'org-clock
3180 :version "24.4"
3181 :package-version '(Org . "8.0")
3182 :type 'boolean)
3184 (defcustom org-time-clocksum-fractional-format "%.2f"
3185 "The format string used when creating CLOCKSUM lines,
3186 or when Org mode generates a time duration, if
3187 `org-time-clocksum-use-fractional' is enabled.
3189 The value can be a single format string containing one
3190 %-sequence, which will be filled with the number of hours as
3191 a float.
3193 Alternatively, the value can be a plist associating any of the
3194 keys :years, :months, :weeks, :days, :hours or :minutes with
3195 a format string. The time duration is formatted using the
3196 largest time unit which gives a non-zero integer part. If all
3197 specified formats have zero integer part, the smallest time unit
3198 is used."
3199 :group 'org-time
3200 :type '(choice (string :tag "Format string")
3201 (set (group :inline t (const :tag "Years" :years)
3202 (string :tag "Format string"))
3203 (group :inline t (const :tag "Months" :months)
3204 (string :tag "Format string"))
3205 (group :inline t (const :tag "Weeks" :weeks)
3206 (string :tag "Format string"))
3207 (group :inline t (const :tag "Days" :days)
3208 (string :tag "Format string"))
3209 (group :inline t (const :tag "Hours" :hours)
3210 (string :tag "Format string"))
3211 (group :inline t (const :tag "Minutes" :minutes)
3212 (string :tag "Format string")))))
3214 (defcustom org-deadline-warning-days 14
3215 "Number of days before expiration during which a deadline becomes active.
3216 This variable governs the display in sparse trees and in the agenda.
3217 When 0 or negative, it means use this number (the absolute value of it)
3218 even if a deadline has a different individual lead time specified.
3220 Custom commands can set this variable in the options section."
3221 :group 'org-time
3222 :group 'org-agenda-daily/weekly
3223 :type 'integer)
3225 (defcustom org-scheduled-delay-days 0
3226 "Number of days before a scheduled item becomes active.
3227 This variable governs the display in sparse trees and in the agenda.
3228 The default value (i.e. 0) means: don't delay scheduled item.
3229 When negative, it means use this number (the absolute value of it)
3230 even if a scheduled item has a different individual delay time
3231 specified.
3233 Custom commands can set this variable in the options section."
3234 :group 'org-time
3235 :group 'org-agenda-daily/weekly
3236 :version "24.4"
3237 :package-version '(Org . "8.0")
3238 :type 'integer)
3240 (defcustom org-read-date-prefer-future t
3241 "Non-nil means assume future for incomplete date input from user.
3242 This affects the following situations:
3243 1. The user gives a month but not a year.
3244 For example, if it is April and you enter \"feb 2\", this will be read
3245 as Feb 2, *next* year. \"May 5\", however, will be this year.
3246 2. The user gives a day, but no month.
3247 For example, if today is the 15th, and you enter \"3\", Org-mode will
3248 read this as the third of *next* month. However, if you enter \"17\",
3249 it will be considered as *this* month.
3251 If you set this variable to the symbol `time', then also the following
3252 will work:
3254 3. If the user gives a time.
3255 If the time is before now, it will be interpreted as tomorrow.
3257 Currently none of this works for ISO week specifications.
3259 When this option is nil, the current day, month and year will always be
3260 used as defaults.
3262 See also `org-agenda-jump-prefer-future'."
3263 :group 'org-time
3264 :type '(choice
3265 (const :tag "Never" nil)
3266 (const :tag "Check month and day" t)
3267 (const :tag "Check month, day, and time" time)))
3269 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3270 "Should the agenda jump command prefer the future for incomplete dates?
3271 The default is to do the same as configured in `org-read-date-prefer-future'.
3272 But you can also set a deviating value here.
3273 This may t or nil, or the symbol `org-read-date-prefer-future'."
3274 :group 'org-agenda
3275 :group 'org-time
3276 :version "24.1"
3277 :type '(choice
3278 (const :tag "Use org-read-date-prefer-future"
3279 org-read-date-prefer-future)
3280 (const :tag "Never" nil)
3281 (const :tag "Always" t)))
3283 (defcustom org-read-date-force-compatible-dates t
3284 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3286 Depending on the system Emacs is running on, certain dates cannot
3287 be represented with the type used internally to represent time.
3288 Dates between 1970-1-1 and 2038-1-1 can always be represented
3289 correctly. Some systems allow for earlier dates, some for later,
3290 some for both. One way to find out it to insert any date into an
3291 Org buffer, putting the cursor on the year and hitting S-up and
3292 S-down to test the range.
3294 When this variable is set to t, the date/time prompt will not let
3295 you specify dates outside the 1970-2037 range, so it is certain that
3296 these dates will work in whatever version of Emacs you are
3297 running, and also that you can move a file from one Emacs implementation
3298 to another. WHenever Org is forcing the year for you, it will display
3299 a message and beep.
3301 When this variable is nil, Org will check if the date is
3302 representable in the specific Emacs implementation you are using.
3303 If not, it will force a year, usually the current year, and beep
3304 to remind you. Currently this setting is not recommended because
3305 the likelihood that you will open your Org files in an Emacs that
3306 has limited date range is not negligible.
3308 A workaround for this problem is to use diary sexp dates for time
3309 stamps outside of this range."
3310 :group 'org-time
3311 :version "24.1"
3312 :type 'boolean)
3314 (defcustom org-read-date-display-live t
3315 "Non-nil means display current interpretation of date prompt live.
3316 This display will be in an overlay, in the minibuffer."
3317 :group 'org-time
3318 :type 'boolean)
3320 (defcustom org-read-date-popup-calendar t
3321 "Non-nil means pop up a calendar when prompting for a date.
3322 In the calendar, the date can be selected with mouse-1. However, the
3323 minibuffer will also be active, and you can simply enter the date as well.
3324 When nil, only the minibuffer will be available."
3325 :group 'org-time
3326 :type 'boolean)
3327 (org-defvaralias 'org-popup-calendar-for-date-prompt
3328 'org-read-date-popup-calendar)
3330 (make-obsolete-variable
3331 'org-read-date-minibuffer-setup-hook
3332 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3333 (defcustom org-read-date-minibuffer-setup-hook nil
3334 "Hook to be used to set up keys for the date/time interface.
3335 Add key definitions to `minibuffer-local-map', which will be a
3336 temporary copy.
3338 WARNING: This option is obsolete, you should use
3339 `org-read-date-minibuffer-local-map' to set up keys."
3340 :group 'org-time
3341 :type 'hook)
3343 (defcustom org-extend-today-until 0
3344 "The hour when your day really ends. Must be an integer.
3345 This has influence for the following applications:
3346 - When switching the agenda to \"today\". It it is still earlier than
3347 the time given here, the day recognized as TODAY is actually yesterday.
3348 - When a date is read from the user and it is still before the time given
3349 here, the current date and time will be assumed to be yesterday, 23:59.
3350 Also, timestamps inserted in capture templates follow this rule.
3352 IMPORTANT: This is a feature whose implementation is and likely will
3353 remain incomplete. Really, it is only here because past midnight seems to
3354 be the favorite working time of John Wiegley :-)"
3355 :group 'org-time
3356 :type 'integer)
3358 (defcustom org-use-effective-time nil
3359 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3360 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3361 \"effective time\" of any timestamps between midnight and 8am will be
3362 23:59 of the previous day."
3363 :group 'org-time
3364 :version "24.1"
3365 :type 'boolean)
3367 (defcustom org-use-last-clock-out-time-as-effective-time nil
3368 "When non-nil, use the last clock out time for `org-todo'.
3369 Note that this option has precedence over the combined use of
3370 `org-use-effective-time' and `org-extend-today-until'."
3371 :group 'org-time
3372 :version "24.4"
3373 :package-version '(Org . "8.0")
3374 :type 'boolean)
3376 (defcustom org-edit-timestamp-down-means-later nil
3377 "Non-nil means S-down will increase the time in a time stamp.
3378 When nil, S-up will increase."
3379 :group 'org-time
3380 :type 'boolean)
3382 (defcustom org-calendar-follow-timestamp-change t
3383 "Non-nil means make the calendar window follow timestamp changes.
3384 When a timestamp is modified and the calendar window is visible, it will be
3385 moved to the new date."
3386 :group 'org-time
3387 :type 'boolean)
3389 (defgroup org-tags nil
3390 "Options concerning tags in Org-mode."
3391 :tag "Org Tags"
3392 :group 'org)
3394 (defcustom org-tag-alist nil
3395 "List of tags allowed in Org-mode files.
3396 When this list is nil, Org-mode will base TAG input on what is already in the
3397 buffer.
3398 The value of this variable is an alist, the car of each entry must be a
3399 keyword as a string, the cdr may be a character that is used to select
3400 that tag through the fast-tag-selection interface.
3401 See the manual for details."
3402 :group 'org-tags
3403 :type '(repeat
3404 (choice
3405 (cons (string :tag "Tag name")
3406 (character :tag "Access char"))
3407 (list :tag "Start radio group"
3408 (const :startgroup)
3409 (option (string :tag "Group description")))
3410 (list :tag "Group tags delimiter"
3411 (const :grouptags))
3412 (list :tag "End radio group"
3413 (const :endgroup)
3414 (option (string :tag "Group description")))
3415 (const :tag "New line" (:newline)))))
3417 (defcustom org-tag-persistent-alist nil
3418 "List of tags that will always appear in all Org-mode files.
3419 This is in addition to any in buffer settings or customizations
3420 of `org-tag-alist'.
3421 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3422 The value of this variable is an alist, the car of each entry must be a
3423 keyword as a string, the cdr may be a character that is used to select
3424 that tag through the fast-tag-selection interface.
3425 See the manual for details.
3426 To disable these tags on a per-file basis, insert anywhere in the file:
3427 #+STARTUP: noptag"
3428 :group 'org-tags
3429 :type '(repeat
3430 (choice
3431 (cons (string :tag "Tag name")
3432 (character :tag "Access char"))
3433 (const :tag "Start radio group" (:startgroup))
3434 (const :tag "Group tags delimiter" (:grouptags))
3435 (const :tag "End radio group" (:endgroup))
3436 (const :tag "New line" (:newline)))))
3438 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3439 "If non-nil, always offer completion for all tags of all agenda files.
3440 Instead of customizing this variable directly, you might want to
3441 set it locally for capture buffers, because there no list of
3442 tags in that file can be created dynamically (there are none).
3444 (add-hook 'org-capture-mode-hook
3445 (lambda ()
3446 (set (make-local-variable
3447 'org-complete-tags-always-offer-all-agenda-tags)
3448 t)))"
3449 :group 'org-tags
3450 :version "24.1"
3451 :type 'boolean)
3453 (defvar org-file-tags nil
3454 "List of tags that can be inherited by all entries in the file.
3455 The tags will be inherited if the variable `org-use-tag-inheritance'
3456 says they should be.
3457 This variable is populated from #+FILETAGS lines.")
3459 (defcustom org-use-fast-tag-selection 'auto
3460 "Non-nil means use fast tag selection scheme.
3461 This is a special interface to select and deselect tags with single keys.
3462 When nil, fast selection is never used.
3463 When the symbol `auto', fast selection is used if and only if selection
3464 characters for tags have been configured, either through the variable
3465 `org-tag-alist' or through a #+TAGS line in the buffer.
3466 When t, fast selection is always used and selection keys are assigned
3467 automatically if necessary."
3468 :group 'org-tags
3469 :type '(choice
3470 (const :tag "Always" t)
3471 (const :tag "Never" nil)
3472 (const :tag "When selection characters are configured" auto)))
3474 (defcustom org-fast-tag-selection-single-key nil
3475 "Non-nil means fast tag selection exits after first change.
3476 When nil, you have to press RET to exit it.
3477 During fast tag selection, you can toggle this flag with `C-c'.
3478 This variable can also have the value `expert'. In this case, the window
3479 displaying the tags menu is not even shown, until you press C-c again."
3480 :group 'org-tags
3481 :type '(choice
3482 (const :tag "No" nil)
3483 (const :tag "Yes" t)
3484 (const :tag "Expert" expert)))
3486 (defvar org-fast-tag-selection-include-todo nil
3487 "Non-nil means fast tags selection interface will also offer TODO states.
3488 This is an undocumented feature, you should not rely on it.")
3490 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3491 "The column to which tags should be indented in a headline.
3492 If this number is positive, it specifies the column. If it is negative,
3493 it means that the tags should be flushright to that column. For example,
3494 -80 works well for a normal 80 character screen.
3495 When 0, place tags directly after headline text, with only one space in
3496 between."
3497 :group 'org-tags
3498 :type 'integer)
3500 (defcustom org-auto-align-tags t
3501 "Non-nil keeps tags aligned when modifying headlines.
3502 Some operations (i.e. demoting) change the length of a headline and
3503 therefore shift the tags around. With this option turned on, after
3504 each such operation the tags are again aligned to `org-tags-column'."
3505 :group 'org-tags
3506 :type 'boolean)
3508 (defcustom org-use-tag-inheritance t
3509 "Non-nil means tags in levels apply also for sublevels.
3510 When nil, only the tags directly given in a specific line apply there.
3511 This may also be a list of tags that should be inherited, or a regexp that
3512 matches tags that should be inherited. Additional control is possible
3513 with the variable `org-tags-exclude-from-inheritance' which gives an
3514 explicit list of tags to be excluded from inheritance, even if the value of
3515 `org-use-tag-inheritance' would select it for inheritance.
3517 If this option is t, a match early-on in a tree can lead to a large
3518 number of matches in the subtree when constructing the agenda or creating
3519 a sparse tree. If you only want to see the first match in a tree during
3520 a search, check out the variable `org-tags-match-list-sublevels'."
3521 :group 'org-tags
3522 :type '(choice
3523 (const :tag "Not" nil)
3524 (const :tag "Always" t)
3525 (repeat :tag "Specific tags" (string :tag "Tag"))
3526 (regexp :tag "Tags matched by regexp")))
3528 (defcustom org-tags-exclude-from-inheritance nil
3529 "List of tags that should never be inherited.
3530 This is a way to exclude a few tags from inheritance. For way to do
3531 the opposite, to actively allow inheritance for selected tags,
3532 see the variable `org-use-tag-inheritance'."
3533 :group 'org-tags
3534 :type '(repeat (string :tag "Tag")))
3536 (defun org-tag-inherit-p (tag)
3537 "Check if TAG is one that should be inherited."
3538 (cond
3539 ((member tag org-tags-exclude-from-inheritance) nil)
3540 ((eq org-use-tag-inheritance t) t)
3541 ((not org-use-tag-inheritance) nil)
3542 ((stringp org-use-tag-inheritance)
3543 (string-match org-use-tag-inheritance tag))
3544 ((listp org-use-tag-inheritance)
3545 (member tag org-use-tag-inheritance))
3546 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3548 (defcustom org-tags-match-list-sublevels t
3549 "Non-nil means list also sublevels of headlines matching a search.
3550 This variable applies to tags/property searches, and also to stuck
3551 projects because this search is based on a tags match as well.
3553 When set to the symbol `indented', sublevels are indented with
3554 leading dots.
3556 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3557 the sublevels of a headline matching a tag search often also match
3558 the same search. Listing all of them can create very long lists.
3559 Setting this variable to nil causes subtrees of a match to be skipped.
3561 This variable is semi-obsolete and probably should always be true. It
3562 is better to limit inheritance to certain tags using the variables
3563 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3564 :group 'org-tags
3565 :type '(choice
3566 (const :tag "No, don't list them" nil)
3567 (const :tag "Yes, do list them" t)
3568 (const :tag "List them, indented with leading dots" indented)))
3570 (defcustom org-tags-sort-function nil
3571 "When set, tags are sorted using this function as a comparator."
3572 :group 'org-tags
3573 :type '(choice
3574 (const :tag "No sorting" nil)
3575 (const :tag "Alphabetical" string<)
3576 (const :tag "Reverse alphabetical" string>)
3577 (function :tag "Custom function" nil)))
3579 (defvar org-tags-history nil
3580 "History of minibuffer reads for tags.")
3581 (defvar org-last-tags-completion-table nil
3582 "The last used completion table for tags.")
3583 (defvar org-after-tags-change-hook nil
3584 "Hook that is run after the tags in a line have changed.")
3586 (defgroup org-properties nil
3587 "Options concerning properties in Org-mode."
3588 :tag "Org Properties"
3589 :group 'org)
3591 (defcustom org-property-format "%-10s %s"
3592 "How property key/value pairs should be formatted by `indent-line'.
3593 When `indent-line' hits a property definition, it will format the line
3594 according to this format, mainly to make sure that the values are
3595 lined-up with respect to each other."
3596 :group 'org-properties
3597 :type 'string)
3599 (defcustom org-properties-postprocess-alist nil
3600 "Alist of properties and functions to adjust inserted values.
3601 Elements of this alist must be of the form
3603 ([string] [function])
3605 where [string] must be a property name and [function] must be a
3606 lambda expression: this lambda expression must take one argument,
3607 the value to adjust, and return the new value as a string.
3609 For example, this element will allow the property \"Remaining\"
3610 to be updated wrt the relation between the \"Effort\" property
3611 and the clock summary:
3613 ((\"Remaining\" (lambda(value)
3614 (let ((clocksum (org-clock-sum-current-item))
3615 (effort (org-duration-string-to-minutes
3616 (org-entry-get (point) \"Effort\"))))
3617 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3618 :group 'org-properties
3619 :version "24.1"
3620 :type '(alist :key-type (string :tag "Property")
3621 :value-type (function :tag "Function")))
3623 (defcustom org-use-property-inheritance nil
3624 "Non-nil means properties apply also for sublevels.
3626 This setting is chiefly used during property searches. Turning it on can
3627 cause significant overhead when doing a search, which is why it is not
3628 on by default.
3630 When nil, only the properties directly given in the current entry count.
3631 When t, every property is inherited. The value may also be a list of
3632 properties that should have inheritance, or a regular expression matching
3633 properties that should be inherited.
3635 However, note that some special properties use inheritance under special
3636 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3637 and the properties ending in \"_ALL\" when they are used as descriptor
3638 for valid values of a property.
3640 Note for programmers:
3641 When querying an entry with `org-entry-get', you can control if inheritance
3642 should be used. By default, `org-entry-get' looks only at the local
3643 properties. You can request inheritance by setting the inherit argument
3644 to t (to force inheritance) or to `selective' (to respect the setting
3645 in this variable)."
3646 :group 'org-properties
3647 :type '(choice
3648 (const :tag "Not" nil)
3649 (const :tag "Always" t)
3650 (repeat :tag "Specific properties" (string :tag "Property"))
3651 (regexp :tag "Properties matched by regexp")))
3653 (defun org-property-inherit-p (property)
3654 "Check if PROPERTY is one that should be inherited."
3655 (cond
3656 ((eq org-use-property-inheritance t) t)
3657 ((not org-use-property-inheritance) nil)
3658 ((stringp org-use-property-inheritance)
3659 (string-match org-use-property-inheritance property))
3660 ((listp org-use-property-inheritance)
3661 (member property org-use-property-inheritance))
3662 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3664 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3665 "The default column format, if no other format has been defined.
3666 This variable can be set on the per-file basis by inserting a line
3668 #+COLUMNS: %25ITEM ....."
3669 :group 'org-properties
3670 :type 'string)
3672 (defcustom org-columns-ellipses ".."
3673 "The ellipses to be used when a field in column view is truncated.
3674 When this is the empty string, as many characters as possible are shown,
3675 but then there will be no visual indication that the field has been truncated.
3676 When this is a string of length N, the last N characters of a truncated
3677 field are replaced by this string. If the column is narrower than the
3678 ellipses string, only part of the ellipses string will be shown."
3679 :group 'org-properties
3680 :type 'string)
3682 (defcustom org-columns-modify-value-for-display-function nil
3683 "Function that modifies values for display in column view.
3684 For example, it can be used to cut out a certain part from a time stamp.
3685 The function must take 2 arguments:
3687 column-title The title of the column (*not* the property name)
3688 value The value that should be modified.
3690 The function should return the value that should be displayed,
3691 or nil if the normal value should be used."
3692 :group 'org-properties
3693 :type '(choice (const nil) (function)))
3695 (defconst org-global-properties-fixed
3696 '(("VISIBILITY_ALL" . "folded children content all")
3697 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3698 "List of property/value pairs that can be inherited by any entry.
3700 These are fixed values, for the preset properties. The user variable
3701 that can be used to add to this list is `org-global-properties'.
3703 The entries in this list are cons cells where the car is a property
3704 name and cdr is a string with the value. If the value represents
3705 multiple items like an \"_ALL\" property, separate the items by
3706 spaces.")
3708 (defcustom org-global-properties nil
3709 "List of property/value pairs that can be inherited by any entry.
3711 This list will be combined with the constant `org-global-properties-fixed'.
3713 The entries in this list are cons cells where the car is a property
3714 name and cdr is a string with the value.
3716 You can set buffer-local values for the same purpose in the variable
3717 `org-file-properties' this by adding lines like
3719 #+PROPERTY: NAME VALUE"
3720 :group 'org-properties
3721 :type '(repeat
3722 (cons (string :tag "Property")
3723 (string :tag "Value"))))
3725 (defvar org-file-properties nil
3726 "List of property/value pairs that can be inherited by any entry.
3727 Valid for the current buffer.
3728 This variable is populated from #+PROPERTY lines.")
3729 (make-variable-buffer-local 'org-file-properties)
3731 (defgroup org-agenda nil
3732 "Options concerning agenda views in Org-mode."
3733 :tag "Org Agenda"
3734 :group 'org)
3736 (defvar org-category nil
3737 "Variable used by org files to set a category for agenda display.
3738 Such files should use a file variable to set it, for example
3740 # -*- mode: org; org-category: \"ELisp\"
3742 or contain a special line
3744 #+CATEGORY: ELisp
3746 If the file does not specify a category, then file's base name
3747 is used instead.")
3748 (make-variable-buffer-local 'org-category)
3749 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3751 (defcustom org-agenda-files nil
3752 "The files to be used for agenda display.
3753 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3754 \\[org-remove-file]. You can also use customize to edit the list.
3756 If an entry is a directory, all files in that directory that are matched by
3757 `org-agenda-file-regexp' will be part of the file list.
3759 If the value of the variable is not a list but a single file name, then
3760 the list of agenda files is actually stored and maintained in that file, one
3761 agenda file per line. In this file paths can be given relative to
3762 `org-directory'. Tilde expansion and environment variable substitution
3763 are also made."
3764 :group 'org-agenda
3765 :type '(choice
3766 (repeat :tag "List of files and directories" file)
3767 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3769 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3770 "Regular expression to match files for `org-agenda-files'.
3771 If any element in the list in that variable contains a directory instead
3772 of a normal file, all files in that directory that are matched by this
3773 regular expression will be included."
3774 :group 'org-agenda
3775 :type 'regexp)
3777 (defcustom org-agenda-text-search-extra-files nil
3778 "List of extra files to be searched by text search commands.
3779 These files will be searched in addition to the agenda files by the
3780 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3781 Note that these files will only be searched for text search commands,
3782 not for the other agenda views like todo lists, tag searches or the weekly
3783 agenda. This variable is intended to list notes and possibly archive files
3784 that should also be searched by these two commands.
3785 In fact, if the first element in the list is the symbol `agenda-archives',
3786 then all archive files of all agenda files will be added to the search
3787 scope."
3788 :group 'org-agenda
3789 :type '(set :greedy t
3790 (const :tag "Agenda Archives" agenda-archives)
3791 (repeat :inline t (file))))
3793 (org-defvaralias 'org-agenda-multi-occur-extra-files
3794 'org-agenda-text-search-extra-files)
3796 (defcustom org-agenda-skip-unavailable-files nil
3797 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3798 A nil value means to remove them, after a query, from the list."
3799 :group 'org-agenda
3800 :type 'boolean)
3802 (defcustom org-calendar-to-agenda-key [?c]
3803 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3804 The command `org-calendar-goto-agenda' will be bound to this key. The
3805 default is the character `c' because then `c' can be used to switch back and
3806 forth between agenda and calendar."
3807 :group 'org-agenda
3808 :type 'sexp)
3810 (defcustom org-calendar-insert-diary-entry-key [?i]
3811 "The key to be installed in `calendar-mode-map' for adding diary entries.
3812 This option is irrelevant until `org-agenda-diary-file' has been configured
3813 to point to an Org-mode file. When that is the case, the command
3814 `org-agenda-diary-entry' will be bound to the key given here, by default
3815 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3816 if you want to continue doing this, you need to change this to a different
3817 key."
3818 :group 'org-agenda
3819 :type 'sexp)
3821 (defcustom org-agenda-diary-file 'diary-file
3822 "File to which to add new entries with the `i' key in agenda and calendar.
3823 When this is the symbol `diary-file', the functionality in the Emacs
3824 calendar will be used to add entries to the `diary-file'. But when this
3825 points to a file, `org-agenda-diary-entry' will be used instead."
3826 :group 'org-agenda
3827 :type '(choice
3828 (const :tag "The standard Emacs diary file" diary-file)
3829 (file :tag "Special Org file diary entries")))
3831 (eval-after-load "calendar"
3832 '(progn
3833 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3834 'org-calendar-goto-agenda)
3835 (add-hook 'calendar-mode-hook
3836 (lambda ()
3837 (unless (eq org-agenda-diary-file 'diary-file)
3838 (define-key calendar-mode-map
3839 org-calendar-insert-diary-entry-key
3840 'org-agenda-diary-entry))))))
3842 (defgroup org-latex nil
3843 "Options for embedding LaTeX code into Org-mode."
3844 :tag "Org LaTeX"
3845 :group 'org)
3847 (defcustom org-format-latex-options
3848 '(:foreground default :background default :scale 1.0
3849 :html-foreground "Black" :html-background "Transparent"
3850 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3851 "Options for creating images from LaTeX fragments.
3852 This is a property list with the following properties:
3853 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3854 `default' means use the foreground of the default face.
3855 `auto' means use the foreground from the text face.
3856 :background the background color, or \"Transparent\".
3857 `default' means use the background of the default face.
3858 `auto' means use the background from the text face.
3859 :scale a scaling factor for the size of the images, to get more pixels
3860 :html-foreground, :html-background, :html-scale
3861 the same numbers for HTML export.
3862 :matchers a list indicating which matchers should be used to
3863 find LaTeX fragments. Valid members of this list are:
3864 \"begin\" find environments
3865 \"$1\" find single characters surrounded by $.$
3866 \"$\" find math expressions surrounded by $...$
3867 \"$$\" find math expressions surrounded by $$....$$
3868 \"\\(\" find math expressions surrounded by \\(...\\)
3869 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3870 :group 'org-latex
3871 :type 'plist)
3873 (defcustom org-format-latex-signal-error t
3874 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3875 When nil, just push out a message."
3876 :group 'org-latex
3877 :version "24.1"
3878 :type 'boolean)
3880 (defcustom org-latex-to-mathml-jar-file nil
3881 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3882 Use this to specify additional executable file say a jar file.
3884 When using MathToWeb as the converter, specify the full-path to
3885 your mathtoweb.jar file."
3886 :group 'org-latex
3887 :version "24.1"
3888 :type '(choice
3889 (const :tag "None" nil)
3890 (file :tag "JAR file" :must-match t)))
3892 (defcustom org-latex-to-mathml-convert-command nil
3893 "Command to convert LaTeX fragments to MathML.
3894 Replace format-specifiers in the command as noted below and use
3895 `shell-command' to convert LaTeX to MathML.
3896 %j: Executable file in fully expanded form as specified by
3897 `org-latex-to-mathml-jar-file'.
3898 %I: Input LaTeX file in fully expanded form
3899 %o: Output MathML file
3900 This command is used by `org-create-math-formula'.
3902 When using MathToWeb as the converter, set this to
3903 \"java -jar %j -unicode -force -df %o %I\"."
3904 :group 'org-latex
3905 :version "24.1"
3906 :type '(choice
3907 (const :tag "None" nil)
3908 (string :tag "\nShell command")))
3910 (defcustom org-latex-create-formula-image-program 'dvipng
3911 "Program to convert LaTeX fragments with.
3913 dvipng Process the LaTeX fragments to dvi file, then convert
3914 dvi files to png files using dvipng.
3915 This will also include processing of non-math environments.
3916 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3917 to convert pdf files to png files"
3918 :group 'org-latex
3919 :version "24.1"
3920 :type '(choice
3921 (const :tag "dvipng" dvipng)
3922 (const :tag "imagemagick" imagemagick)))
3924 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3925 "Path to store latex preview images.
3926 A relative path here creates many directories relative to the
3927 processed org files paths. An absolute path puts all preview
3928 images at the same place."
3929 :group 'org-latex
3930 :version "24.3"
3931 :type 'string)
3933 (defun org-format-latex-mathml-available-p ()
3934 "Return t if `org-latex-to-mathml-convert-command' is usable."
3935 (save-match-data
3936 (when (and (boundp 'org-latex-to-mathml-convert-command)
3937 org-latex-to-mathml-convert-command)
3938 (let ((executable (car (split-string
3939 org-latex-to-mathml-convert-command))))
3940 (when (executable-find executable)
3941 (if (string-match
3942 "%j" org-latex-to-mathml-convert-command)
3943 (file-readable-p org-latex-to-mathml-jar-file)
3944 t))))))
3946 (defcustom org-format-latex-header "\\documentclass{article}
3947 \\usepackage[usenames]{color}
3948 \[PACKAGES]
3949 \[DEFAULT-PACKAGES]
3950 \\pagestyle{empty} % do not remove
3951 % The settings below are copied from fullpage.sty
3952 \\setlength{\\textwidth}{\\paperwidth}
3953 \\addtolength{\\textwidth}{-3cm}
3954 \\setlength{\\oddsidemargin}{1.5cm}
3955 \\addtolength{\\oddsidemargin}{-2.54cm}
3956 \\setlength{\\evensidemargin}{\\oddsidemargin}
3957 \\setlength{\\textheight}{\\paperheight}
3958 \\addtolength{\\textheight}{-\\headheight}
3959 \\addtolength{\\textheight}{-\\headsep}
3960 \\addtolength{\\textheight}{-\\footskip}
3961 \\addtolength{\\textheight}{-3cm}
3962 \\setlength{\\topmargin}{1.5cm}
3963 \\addtolength{\\topmargin}{-2.54cm}"
3964 "The document header used for processing LaTeX fragments.
3965 It is imperative that this header make sure that no page number
3966 appears on the page. The package defined in the variables
3967 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3968 will either replace the placeholder \"[PACKAGES]\" in this
3969 header, or they will be appended."
3970 :group 'org-latex
3971 :type 'string)
3973 (defun org-set-packages-alist (var val)
3974 "Set the packages alist and make sure it has 3 elements per entry."
3975 (set var (mapcar (lambda (x)
3976 (if (and (consp x) (= (length x) 2))
3977 (list (car x) (nth 1 x) t)
3979 val)))
3981 (defun org-get-packages-alist (var)
3982 "Get the packages alist and make sure it has 3 elements per entry."
3983 (mapcar (lambda (x)
3984 (if (and (consp x) (= (length x) 2))
3985 (list (car x) (nth 1 x) t)
3987 (default-value var)))
3989 (defcustom org-latex-default-packages-alist
3990 '(("AUTO" "inputenc" t)
3991 ("T1" "fontenc" t)
3992 ("" "fixltx2e" nil)
3993 ("" "graphicx" t)
3994 ("" "longtable" nil)
3995 ("" "float" nil)
3996 ("" "wrapfig" nil)
3997 ("" "rotating" nil)
3998 ("normalem" "ulem" t)
3999 ("" "amsmath" t)
4000 ("" "textcomp" t)
4001 ("" "marvosym" t)
4002 ("" "wasysym" t)
4003 ("" "amssymb" t)
4004 ("" "hyperref" nil)
4005 "\\tolerance=1000")
4006 "Alist of default packages to be inserted in the header.
4008 Change this only if one of the packages here causes an
4009 incompatibility with another package you are using.
4011 The packages in this list are needed by one part or another of
4012 Org mode to function properly:
4014 - inputenc, fontenc: for basic font and character selection
4015 - fixltx2e: Important patches of LaTeX itself
4016 - graphicx: for including images
4017 - longtable: For multipage tables
4018 - float, wrapfig: for figure placement
4019 - rotating: for sideways figures and tables
4020 - ulem: for underline and strike-through
4021 - amsmath: for subscript and superscript and math environments
4022 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4023 for interpreting the entities in `org-entities'. You can skip
4024 some of these packages if you don't use any of their symbols.
4025 - hyperref: for cross references
4027 Therefore you should not modify this variable unless you know
4028 what you are doing. The one reason to change it anyway is that
4029 you might be loading some other package that conflicts with one
4030 of the default packages. Each element is either a cell or
4031 a string.
4033 A cell is of the format:
4035 \( \"options\" \"package\" SNIPPET-FLAG).
4037 If SNIPPET-FLAG is non-nil, the package also needs to be included
4038 when compiling LaTeX snippets into images for inclusion into
4039 non-LaTeX output.
4041 A string will be inserted as-is in the header of the document."
4042 :group 'org-latex
4043 :group 'org-export-latex
4044 :set 'org-set-packages-alist
4045 :get 'org-get-packages-alist
4046 :version "24.1"
4047 :type '(repeat
4048 (choice
4049 (list :tag "options/package pair"
4050 (string :tag "options")
4051 (string :tag "package")
4052 (boolean :tag "Snippet"))
4053 (string :tag "A line of LaTeX"))))
4055 (defcustom org-latex-packages-alist nil
4056 "Alist of packages to be inserted in every LaTeX header.
4058 These will be inserted after `org-latex-default-packages-alist'.
4059 Each element is either a cell or a string.
4061 A cell is of the format:
4063 \(\"options\" \"package\" SNIPPET-FLAG)
4065 SNIPPET-FLAG, when non-nil, indicates that this package is also
4066 needed when turning LaTeX snippets into images for inclusion into
4067 non-LaTeX output.
4069 A string will be inserted as-is in the header of the document.
4071 Make sure that you only list packages here which:
4073 - you want in every file;
4074 - do not conflict with the setup in `org-format-latex-header';
4075 - do not conflict with the default packages in
4076 `org-latex-default-packages-alist'."
4077 :group 'org-latex
4078 :group 'org-export-latex
4079 :set 'org-set-packages-alist
4080 :get 'org-get-packages-alist
4081 :type '(repeat
4082 (choice
4083 (list :tag "options/package pair"
4084 (string :tag "options")
4085 (string :tag "package")
4086 (boolean :tag "Snippet"))
4087 (string :tag "A line of LaTeX"))))
4089 (defgroup org-appearance nil
4090 "Settings for Org-mode appearance."
4091 :tag "Org Appearance"
4092 :group 'org)
4094 (defcustom org-level-color-stars-only nil
4095 "Non-nil means fontify only the stars in each headline.
4096 When nil, the entire headline is fontified.
4097 Changing it requires restart of `font-lock-mode' to become effective
4098 also in regions already fontified."
4099 :group 'org-appearance
4100 :type 'boolean)
4102 (defcustom org-hide-leading-stars nil
4103 "Non-nil means hide the first N-1 stars in a headline.
4104 This works by using the face `org-hide' for these stars. This
4105 face is white for a light background, and black for a dark
4106 background. You may have to customize the face `org-hide' to
4107 make this work.
4108 Changing it requires restart of `font-lock-mode' to become effective
4109 also in regions already fontified.
4110 You may also set this on a per-file basis by adding one of the following
4111 lines to the buffer:
4113 #+STARTUP: hidestars
4114 #+STARTUP: showstars"
4115 :group 'org-appearance
4116 :type 'boolean)
4118 (defcustom org-hidden-keywords nil
4119 "List of symbols corresponding to keywords to be hidden the org buffer.
4120 For example, a value '(title) for this list will make the document's title
4121 appear in the buffer without the initial #+TITLE: keyword."
4122 :group 'org-appearance
4123 :version "24.1"
4124 :type '(set (const :tag "#+AUTHOR" author)
4125 (const :tag "#+DATE" date)
4126 (const :tag "#+EMAIL" email)
4127 (const :tag "#+TITLE" title)))
4129 (defcustom org-custom-properties nil
4130 "List of properties (as strings) with a special meaning.
4131 The default use of these custom properties is to let the user
4132 hide them with `org-toggle-custom-properties-visibility'."
4133 :group 'org-properties
4134 :group 'org-appearance
4135 :version "24.3"
4136 :type '(repeat (string :tag "Property Name")))
4138 (defcustom org-fontify-done-headline nil
4139 "Non-nil means change the face of a headline if it is marked DONE.
4140 Normally, only the TODO/DONE keyword indicates the state of a headline.
4141 When this is non-nil, the headline after the keyword is set to the
4142 `org-headline-done' as an additional indication."
4143 :group 'org-appearance
4144 :type 'boolean)
4146 (defcustom org-fontify-emphasized-text t
4147 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4148 Changing this variable requires a restart of Emacs to take effect."
4149 :group 'org-appearance
4150 :type 'boolean)
4152 (defcustom org-fontify-whole-heading-line nil
4153 "Non-nil means fontify the whole line for headings.
4154 This is useful when setting a background color for the
4155 org-level-* faces."
4156 :group 'org-appearance
4157 :type 'boolean)
4159 (defcustom org-highlight-latex-and-related nil
4160 "Non-nil means highlight LaTeX related syntax in the buffer.
4161 When non nil, the value should be a list containing any of the
4162 following symbols:
4163 `latex' Highlight LaTeX snippets and environments.
4164 `script' Highlight subscript and superscript.
4165 `entities' Highlight entities."
4166 :group 'org-appearance
4167 :version "24.4"
4168 :package-version '(Org . "8.0")
4169 :type '(choice
4170 (const :tag "No highlighting" nil)
4171 (set :greedy t :tag "Highlight"
4172 (const :tag "LaTeX snippets and environments" latex)
4173 (const :tag "Subscript and superscript" script)
4174 (const :tag "Entities" entities))))
4176 (defcustom org-hide-emphasis-markers nil
4177 "Non-nil mean font-lock should hide the emphasis marker characters."
4178 :group 'org-appearance
4179 :type 'boolean)
4181 (defcustom org-hide-macro-markers nil
4182 "Non-nil mean font-lock should hide the brackets marking macro calls."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-pretty-entities nil
4187 "Non-nil means show entities as UTF8 characters.
4188 When nil, the \\name form remains in the buffer."
4189 :group 'org-appearance
4190 :version "24.1"
4191 :type 'boolean)
4193 (defcustom org-pretty-entities-include-sub-superscripts t
4194 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4195 :group 'org-appearance
4196 :version "24.1"
4197 :type 'boolean)
4199 (defvar org-emph-re nil
4200 "Regular expression for matching emphasis.
4201 After a match, the match groups contain these elements:
4202 0 The match of the full regular expression, including the characters
4203 before and after the proper match
4204 1 The character before the proper match, or empty at beginning of line
4205 2 The proper match, including the leading and trailing markers
4206 3 The leading marker like * or /, indicating the type of highlighting
4207 4 The text between the emphasis markers, not including the markers
4208 5 The character after the match, empty at the end of a line")
4209 (defvar org-verbatim-re nil
4210 "Regular expression for matching verbatim text.")
4211 (defvar org-emphasis-regexp-components) ; defined just below
4212 (defvar org-emphasis-alist) ; defined just below
4213 (defun org-set-emph-re (var val)
4214 "Set variable and compute the emphasis regular expression."
4215 (set var val)
4216 (when (and (boundp 'org-emphasis-alist)
4217 (boundp 'org-emphasis-regexp-components)
4218 org-emphasis-alist org-emphasis-regexp-components)
4219 (let* ((e org-emphasis-regexp-components)
4220 (pre (car e))
4221 (post (nth 1 e))
4222 (border (nth 2 e))
4223 (body (nth 3 e))
4224 (nl (nth 4 e))
4225 (body1 (concat body "*?"))
4226 (markers (mapconcat 'car org-emphasis-alist ""))
4227 (vmarkers (mapconcat
4228 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4229 org-emphasis-alist "")))
4230 ;; make sure special characters appear at the right position in the class
4231 (if (string-match "\\^" markers)
4232 (setq markers (concat (replace-match "" t t markers) "^")))
4233 (if (string-match "-" markers)
4234 (setq markers (concat (replace-match "" t t markers) "-")))
4235 (if (string-match "\\^" vmarkers)
4236 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4237 (if (string-match "-" vmarkers)
4238 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4239 (if (> nl 0)
4240 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4241 (int-to-string nl) "\\}")))
4242 ;; Make the regexp
4243 (setq org-emph-re
4244 (concat "\\([" pre "]\\|^\\)"
4245 "\\("
4246 "\\([" markers "]\\)"
4247 "\\("
4248 "[^" border "]\\|"
4249 "[^" border "]"
4250 body1
4251 "[^" border "]"
4252 "\\)"
4253 "\\3\\)"
4254 "\\([" post "]\\|$\\)"))
4255 (setq org-verbatim-re
4256 (concat "\\([" pre "]\\|^\\)"
4257 "\\("
4258 "\\([" vmarkers "]\\)"
4259 "\\("
4260 "[^" border "]\\|"
4261 "[^" border "]"
4262 body1
4263 "[^" border "]"
4264 "\\)"
4265 "\\3\\)"
4266 "\\([" post "]\\|$\\)")))))
4268 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4269 ;; set this option proved cumbersome. See this message/thread:
4270 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4271 (defvar org-emphasis-regexp-components
4272 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4273 "Components used to build the regular expression for emphasis.
4274 This is a list with five entries. Terminology: In an emphasis string
4275 like \" *strong word* \", we call the initial space PREMATCH, the final
4276 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4277 and \"trong wor\" is the body. The different components in this variable
4278 specify what is allowed/forbidden in each part:
4280 pre Chars allowed as prematch. Beginning of line will be allowed too.
4281 post Chars allowed as postmatch. End of line will be allowed too.
4282 border The chars *forbidden* as border characters.
4283 body-regexp A regexp like \".\" to match a body character. Don't use
4284 non-shy groups here, and don't allow newline here.
4285 newline The maximum number of newlines allowed in an emphasis exp.
4287 You need to reload Org or to restart Emacs after customizing this.")
4289 (defcustom org-emphasis-alist
4290 `(("*" bold)
4291 ("/" italic)
4292 ("_" underline)
4293 ("=" org-verbatim verbatim)
4294 ("~" org-code verbatim)
4295 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4296 "Alist of characters and faces to emphasize text.
4297 Text starting and ending with a special character will be emphasized,
4298 for example *bold*, _underlined_ and /italic/. This variable sets the
4299 marker characters and the face to be used by font-lock for highlighting
4300 in Org-mode Emacs buffers.
4302 You need to reload Org or to restart Emacs after customizing this."
4303 :group 'org-appearance
4304 :set 'org-set-emph-re
4305 :version "24.4"
4306 :package-version '(Org . "8.0")
4307 :type '(repeat
4308 (list
4309 (string :tag "Marker character")
4310 (choice
4311 (face :tag "Font-lock-face")
4312 (plist :tag "Face property list"))
4313 (option (const verbatim)))))
4315 (defvar org-protecting-blocks
4316 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4317 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4318 This is needed for font-lock setup.")
4320 ;;; Miscellaneous options
4322 (defgroup org-completion nil
4323 "Completion in Org-mode."
4324 :tag "Org Completion"
4325 :group 'org)
4327 (defcustom org-completion-use-ido nil
4328 "Non-nil means use ido completion wherever possible.
4329 Note that `ido-mode' must be active for this variable to be relevant.
4330 If you decide to turn this variable on, you might well want to turn off
4331 `org-outline-path-complete-in-steps'.
4332 See also `org-completion-use-iswitchb'."
4333 :group 'org-completion
4334 :type 'boolean)
4336 (defcustom org-completion-use-iswitchb nil
4337 "Non-nil means use iswitchb completion wherever possible.
4338 Note that `iswitchb-mode' must be active for this variable to be relevant.
4339 If you decide to turn this variable on, you might well want to turn off
4340 `org-outline-path-complete-in-steps'.
4341 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4342 :group 'org-completion
4343 :type 'boolean)
4345 (defcustom org-completion-fallback-command 'hippie-expand
4346 "The expansion command called by \\[pcomplete] in normal context.
4347 Normal means, no org-mode-specific context."
4348 :group 'org-completion
4349 :type 'function)
4351 ;;; Functions and variables from their packages
4352 ;; Declared here to avoid compiler warnings
4354 ;; XEmacs only
4355 (defvar outline-mode-menu-heading)
4356 (defvar outline-mode-menu-show)
4357 (defvar outline-mode-menu-hide)
4358 (defvar zmacs-regions) ; XEmacs regions
4360 ;; Emacs only
4361 (defvar mark-active)
4363 ;; Various packages
4364 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4365 (declare-function calendar-forward-day "cal-move" (arg))
4366 (declare-function calendar-goto-date "cal-move" (date))
4367 (declare-function calendar-goto-today "cal-move" ())
4368 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4369 (defvar calc-embedded-close-formula)
4370 (defvar calc-embedded-open-formula)
4371 (declare-function cdlatex-tab "ext:cdlatex" ())
4372 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4373 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4374 (defvar font-lock-unfontify-region-function)
4375 (declare-function iswitchb-read-buffer "iswitchb"
4376 (prompt &optional default require-match start matches-set))
4377 (defvar iswitchb-temp-buflist)
4378 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4379 (defvar org-agenda-tags-todo-honor-ignore-options)
4380 (declare-function org-agenda-skip "org-agenda" ())
4381 (declare-function
4382 org-agenda-format-item "org-agenda"
4383 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4384 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4385 (declare-function org-agenda-change-all-lines "org-agenda"
4386 (newhead hdmarker &optional fixface just-this))
4387 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4388 (declare-function org-agenda-maybe-redo "org-agenda" ())
4389 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4390 (beg end))
4391 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4392 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4393 "org-agenda" (&optional end))
4394 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4395 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4396 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4397 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4398 (declare-function org-indent-mode "org-indent" (&optional arg))
4399 (declare-function parse-time-string "parse-time" (string))
4400 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4401 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4402 (defvar remember-data-file)
4403 (defvar texmathp-why)
4404 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4405 (declare-function table--at-cell-p "table" (position &optional object at-column))
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4408 ;;;###autoload
4409 (defun turn-on-orgtbl ()
4410 "Unconditionally turn on `orgtbl-mode'."
4411 (require 'org-table)
4412 (orgtbl-mode 1))
4414 (defun org-at-table-p (&optional table-type)
4415 "Return t if the cursor is inside an org-type table.
4416 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4417 (if org-enable-table-editor
4418 (save-excursion
4419 (beginning-of-line 1)
4420 (looking-at (if table-type org-table-any-line-regexp
4421 org-table-line-regexp)))
4422 nil))
4423 (defsubst org-table-p () (org-at-table-p))
4425 (defun org-at-table.el-p ()
4426 "Return t if and only if we are at a table.el table."
4427 (and (org-at-table-p 'any)
4428 (save-excursion
4429 (goto-char (org-table-begin 'any))
4430 (looking-at org-table1-hline-regexp))))
4432 (defun org-table-recognize-table.el ()
4433 "If there is a table.el table nearby, recognize it and move into it."
4434 (if org-table-tab-recognizes-table.el
4435 (if (org-at-table.el-p)
4436 (progn
4437 (beginning-of-line 1)
4438 (if (looking-at org-table-dataline-regexp)
4440 (if (looking-at org-table1-hline-regexp)
4441 (progn
4442 (beginning-of-line 2)
4443 (if (looking-at org-table-any-border-regexp)
4444 (beginning-of-line -1)))))
4445 (if (re-search-forward "|" (org-table-end t) t)
4446 (progn
4447 (require 'table)
4448 (if (table--at-cell-p (point))
4450 (message "recognizing table.el table...")
4451 (table-recognize-table)
4452 (message "recognizing table.el table...done")))
4453 (error "This should not happen"))
4455 nil)
4456 nil))
4458 (defun org-at-table-hline-p ()
4459 "Return t if the cursor is inside a hline in a table."
4460 (if org-enable-table-editor
4461 (save-excursion
4462 (beginning-of-line 1)
4463 (looking-at org-table-hline-regexp))
4464 nil))
4466 (defun org-table-map-tables (function &optional quietly)
4467 "Apply FUNCTION to the start of all tables in the buffer."
4468 (save-excursion
4469 (save-restriction
4470 (widen)
4471 (goto-char (point-min))
4472 (while (re-search-forward org-table-any-line-regexp nil t)
4473 (unless quietly
4474 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4475 (beginning-of-line 1)
4476 (when (and (looking-at org-table-line-regexp)
4477 ;; Exclude tables in src/example/verbatim/clocktable blocks
4478 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4479 (save-excursion (funcall function))
4480 (or (looking-at org-table-line-regexp)
4481 (forward-char 1)))
4482 (re-search-forward org-table-any-border-regexp nil 1))))
4483 (unless quietly (message "Mapping tables: done")))
4485 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4486 (declare-function org-clock-update-mode-line "org-clock" ())
4487 (declare-function org-resolve-clocks "org-clock"
4488 (&optional also-non-dangling-p prompt last-valid))
4490 (defun org-at-TBLFM-p (&optional pos)
4491 "Return t when point (or POS) is in #+TBLFM line."
4492 (save-excursion
4493 (let ((pos pos)))
4494 (goto-char (or pos (point)))
4495 (beginning-of-line 1)
4496 (looking-at org-TBLFM-regexp)))
4498 (defvar org-clock-start-time)
4499 (defvar org-clock-marker (make-marker)
4500 "Marker recording the last clock-in.")
4501 (defvar org-clock-hd-marker (make-marker)
4502 "Marker recording the last clock-in, but the headline position.")
4503 (defvar org-clock-heading ""
4504 "The heading of the current clock entry.")
4505 (defun org-clock-is-active ()
4506 "Return the buffer where the clock is currently running.
4507 Return nil if no clock is running."
4508 (marker-buffer org-clock-marker))
4510 (defun org-check-running-clock ()
4511 "Check if the current buffer contains the running clock.
4512 If yes, offer to stop it and to save the buffer with the changes."
4513 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4514 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4515 (buffer-name))))
4516 (org-clock-out)
4517 (when (y-or-n-p "Save changed buffer?")
4518 (save-buffer))))
4520 (defun org-clocktable-try-shift (dir n)
4521 "Check if this line starts a clock table, if yes, shift the time block."
4522 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4523 (org-clocktable-shift dir n)))
4525 ;;;###autoload
4526 (defun org-clock-persistence-insinuate ()
4527 "Set up hooks for clock persistence."
4528 (require 'org-clock)
4529 (add-hook 'org-mode-hook 'org-clock-load)
4530 (add-hook 'kill-emacs-hook 'org-clock-save))
4532 (defgroup org-archive nil
4533 "Options concerning archiving in Org-mode."
4534 :tag "Org Archive"
4535 :group 'org-structure)
4537 (defcustom org-archive-location "%s_archive::"
4538 "The location where subtrees should be archived.
4540 The value of this variable is a string, consisting of two parts,
4541 separated by a double-colon. The first part is a filename and
4542 the second part is a headline.
4544 When the filename is omitted, archiving happens in the same file.
4545 %s in the filename will be replaced by the current file
4546 name (without the directory part). Archiving to a different file
4547 is useful to keep archived entries from contributing to the
4548 Org-mode Agenda.
4550 The archived entries will be filed as subtrees of the specified
4551 headline. When the headline is omitted, the subtrees are simply
4552 filed away at the end of the file, as top-level entries. Also in
4553 the heading you can use %s to represent the file name, this can be
4554 useful when using the same archive for a number of different files.
4556 Here are a few examples:
4557 \"%s_archive::\"
4558 If the current file is Projects.org, archive in file
4559 Projects.org_archive, as top-level trees. This is the default.
4561 \"::* Archived Tasks\"
4562 Archive in the current file, under the top-level headline
4563 \"* Archived Tasks\".
4565 \"~/org/archive.org::\"
4566 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4568 \"~/org/archive.org::* From %s\"
4569 Archive in file ~/org/archive.org (absolute path), under headlines
4570 \"From FILENAME\" where file name is the current file name.
4572 \"~/org/datetree.org::datetree/* Finished Tasks\"
4573 The \"datetree/\" string is special, signifying to archive
4574 items to the datetree. Items are placed in either the CLOSED
4575 date of the item, or the current date if there is no CLOSED date.
4576 The heading will be a subentry to the current date. There doesn't
4577 need to be a heading, but there always needs to be a slash after
4578 datetree. For example, to store archived items directly in the
4579 datetree, use \"~/org/datetree.org::datetree/\".
4581 \"basement::** Finished Tasks\"
4582 Archive in file ./basement (relative path), as level 3 trees
4583 below the level 2 heading \"** Finished Tasks\".
4585 You may set this option on a per-file basis by adding to the buffer a
4586 line like
4588 #+ARCHIVE: basement::** Finished Tasks
4590 You may also define it locally for a subtree by setting an ARCHIVE property
4591 in the entry. If such a property is found in an entry, or anywhere up
4592 the hierarchy, it will be used."
4593 :group 'org-archive
4594 :type 'string)
4596 (defcustom org-agenda-skip-archived-trees t
4597 "Non-nil means the agenda will skip any items located in archived trees.
4598 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4599 variable is no longer recommended, you should leave it at the value t.
4600 Instead, use the key `v' to cycle the archives-mode in the agenda."
4601 :group 'org-archive
4602 :group 'org-agenda-skip
4603 :type 'boolean)
4605 (defcustom org-columns-skip-archived-trees t
4606 "Non-nil means ignore archived trees when creating column view."
4607 :group 'org-archive
4608 :group 'org-properties
4609 :type 'boolean)
4611 (defcustom org-cycle-open-archived-trees nil
4612 "Non-nil means `org-cycle' will open archived trees.
4613 An archived tree is a tree marked with the tag ARCHIVE.
4614 When nil, archived trees will stay folded. You can still open them with
4615 normal outline commands like `show-all', but not with the cycling commands."
4616 :group 'org-archive
4617 :group 'org-cycle
4618 :type 'boolean)
4620 (defcustom org-sparse-tree-open-archived-trees nil
4621 "Non-nil means sparse tree construction shows matches in archived trees.
4622 When nil, matches in these trees are highlighted, but the trees are kept in
4623 collapsed state."
4624 :group 'org-archive
4625 :group 'org-sparse-trees
4626 :type 'boolean)
4628 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4629 "The default date type when building a sparse tree.
4630 When this is nil, a date is a scheduled or a deadline timestamp.
4631 Otherwise, these types are allowed:
4633 all: all timestamps
4634 active: only active timestamps (<...>)
4635 inactive: only inactive timestamps (<...)
4636 scheduled: only scheduled timestamps
4637 deadline: only deadline timestamps"
4638 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4639 (const :tag "All timestamps" all)
4640 (const :tag "Only active timestamps" active)
4641 (const :tag "Only inactive timestamps" inactive)
4642 (const :tag "Only scheduled timestamps" scheduled)
4643 (const :tag "Only deadline timestamps" deadline)
4644 (const :tag "Only closed timestamps" closed))
4645 :version "24.3"
4646 :group 'org-sparse-trees)
4648 (defun org-cycle-hide-archived-subtrees (state)
4649 "Re-hide all archived subtrees after a visibility state change."
4650 (when (and (not org-cycle-open-archived-trees)
4651 (not (memq state '(overview folded))))
4652 (save-excursion
4653 (let* ((globalp (memq state '(contents all)))
4654 (beg (if globalp (point-min) (point)))
4655 (end (if globalp (point-max) (org-end-of-subtree t))))
4656 (org-hide-archived-subtrees beg end)
4657 (goto-char beg)
4658 (if (looking-at (concat ".*:" org-archive-tag ":"))
4659 (message "%s" (substitute-command-keys
4660 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4662 (defun org-force-cycle-archived ()
4663 "Cycle subtree even if it is archived."
4664 (interactive)
4665 (setq this-command 'org-cycle)
4666 (let ((org-cycle-open-archived-trees t))
4667 (call-interactively 'org-cycle)))
4669 (defun org-hide-archived-subtrees (beg end)
4670 "Re-hide all archived subtrees after a visibility state change."
4671 (save-excursion
4672 (let* ((re (concat ":" org-archive-tag ":")))
4673 (goto-char beg)
4674 (while (re-search-forward re end t)
4675 (when (org-at-heading-p)
4676 (org-flag-subtree t)
4677 (org-end-of-subtree t))))))
4679 (declare-function outline-end-of-heading "outline" ())
4680 (declare-function outline-flag-region "outline" (from to flag))
4681 (defun org-flag-subtree (flag)
4682 (save-excursion
4683 (org-back-to-heading t)
4684 (outline-end-of-heading)
4685 (outline-flag-region (point)
4686 (progn (org-end-of-subtree t) (point))
4687 flag)))
4689 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4691 ;; Declare Column View Code
4693 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4694 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4695 (declare-function org-columns-compute "org-colview" (property))
4697 ;; Declare ID code
4699 (declare-function org-id-store-link "org-id")
4700 (declare-function org-id-locations-load "org-id")
4701 (declare-function org-id-locations-save "org-id")
4702 (defvar org-id-track-globally)
4704 ;;; Variables for pre-computed regular expressions, all buffer local
4706 (defvar org-todo-regexp nil
4707 "Matches any of the TODO state keywords.")
4708 (make-variable-buffer-local 'org-todo-regexp)
4709 (defvar org-not-done-regexp nil
4710 "Matches any of the TODO state keywords except the last one.")
4711 (make-variable-buffer-local 'org-not-done-regexp)
4712 (defvar org-not-done-heading-regexp nil
4713 "Matches a TODO headline that is not done.")
4714 (make-variable-buffer-local 'org-not-done-regexp)
4715 (defvar org-todo-line-regexp nil
4716 "Matches a headline and puts TODO state into group 2 if present.")
4717 (make-variable-buffer-local 'org-todo-line-regexp)
4718 (defvar org-complex-heading-regexp nil
4719 "Matches a headline and puts everything into groups:
4720 group 1: the stars
4721 group 2: The todo keyword, maybe
4722 group 3: Priority cookie
4723 group 4: True headline
4724 group 5: Tags")
4725 (make-variable-buffer-local 'org-complex-heading-regexp)
4726 (defvar org-complex-heading-regexp-format nil
4727 "Printf format to make regexp to match an exact headline.
4728 This regexp will match the headline of any node which has the
4729 exact headline text that is put into the format, but may have any
4730 TODO state, priority and tags.")
4731 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4732 (defvar org-todo-line-tags-regexp nil
4733 "Matches a headline and puts TODO state into group 2 if present.
4734 Also put tags into group 4 if tags are present.")
4735 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4736 (defvar org-ds-keyword-length 12
4737 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4738 (make-variable-buffer-local 'org-ds-keyword-length)
4739 (defvar org-deadline-regexp nil
4740 "Matches the DEADLINE keyword.")
4741 (make-variable-buffer-local 'org-deadline-regexp)
4742 (defvar org-deadline-time-regexp nil
4743 "Matches the DEADLINE keyword together with a time stamp.")
4744 (make-variable-buffer-local 'org-deadline-time-regexp)
4745 (defvar org-deadline-time-hour-regexp nil
4746 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4747 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4748 (defvar org-deadline-line-regexp nil
4749 "Matches the DEADLINE keyword and the rest of the line.")
4750 (make-variable-buffer-local 'org-deadline-line-regexp)
4751 (defvar org-scheduled-regexp nil
4752 "Matches the SCHEDULED keyword.")
4753 (make-variable-buffer-local 'org-scheduled-regexp)
4754 (defvar org-scheduled-time-regexp nil
4755 "Matches the SCHEDULED keyword together with a time stamp.")
4756 (make-variable-buffer-local 'org-scheduled-time-regexp)
4757 (defvar org-scheduled-time-hour-regexp nil
4758 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4759 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4760 (defvar org-closed-time-regexp nil
4761 "Matches the CLOSED keyword together with a time stamp.")
4762 (make-variable-buffer-local 'org-closed-time-regexp)
4764 (defvar org-keyword-time-regexp nil
4765 "Matches any of the 4 keywords, together with the time stamp.")
4766 (make-variable-buffer-local 'org-keyword-time-regexp)
4767 (defvar org-keyword-time-not-clock-regexp nil
4768 "Matches any of the 3 keywords, together with the time stamp.")
4769 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4770 (defvar org-maybe-keyword-time-regexp nil
4771 "Matches a timestamp, possibly preceded by a keyword.")
4772 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4773 (defvar org-all-time-keywords nil
4774 "List of time keywords.")
4775 (make-variable-buffer-local 'org-all-time-keywords)
4777 (defconst org-plain-time-of-day-regexp
4778 (concat
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\(--?"
4782 "\\(\\<[012]?[0-9]"
4783 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "\\)?")
4785 "Regular expression to match a plain time or time range.
4786 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4787 groups carry important information:
4788 0 the full match
4789 1 the first time, range or not
4790 8 the second time, if it is a range.")
4792 (defconst org-plain-time-extension-regexp
4793 (concat
4794 "\\(\\<[012]?[0-9]"
4795 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4796 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4797 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4798 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4799 groups carry important information:
4800 0 the full match
4801 7 hours of duration
4802 9 minutes of duration")
4804 (defconst org-stamp-time-of-day-regexp
4805 (concat
4806 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4807 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4808 "\\(--?"
4809 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4810 "Regular expression to match a timestamp time or time range.
4811 After a match, the following groups carry important information:
4812 0 the full match
4813 1 date plus weekday, for back referencing to make sure both times are on the same day
4814 2 the first time, range or not
4815 4 the second time, if it is a range.")
4817 (defconst org-startup-options
4818 '(("fold" org-startup-folded t)
4819 ("overview" org-startup-folded t)
4820 ("nofold" org-startup-folded nil)
4821 ("showall" org-startup-folded nil)
4822 ("showeverything" org-startup-folded showeverything)
4823 ("content" org-startup-folded content)
4824 ("indent" org-startup-indented t)
4825 ("noindent" org-startup-indented nil)
4826 ("hidestars" org-hide-leading-stars t)
4827 ("showstars" org-hide-leading-stars nil)
4828 ("odd" org-odd-levels-only t)
4829 ("oddeven" org-odd-levels-only nil)
4830 ("align" org-startup-align-all-tables t)
4831 ("noalign" org-startup-align-all-tables nil)
4832 ("inlineimages" org-startup-with-inline-images t)
4833 ("noinlineimages" org-startup-with-inline-images nil)
4834 ("latexpreview" org-startup-with-latex-preview t)
4835 ("nolatexpreview" org-startup-with-latex-preview nil)
4836 ("customtime" org-display-custom-times t)
4837 ("logdone" org-log-done time)
4838 ("lognotedone" org-log-done note)
4839 ("nologdone" org-log-done nil)
4840 ("lognoteclock-out" org-log-note-clock-out t)
4841 ("nolognoteclock-out" org-log-note-clock-out nil)
4842 ("logrepeat" org-log-repeat state)
4843 ("lognoterepeat" org-log-repeat note)
4844 ("logdrawer" org-log-into-drawer t)
4845 ("nologdrawer" org-log-into-drawer nil)
4846 ("logstatesreversed" org-log-states-order-reversed t)
4847 ("nologstatesreversed" org-log-states-order-reversed nil)
4848 ("nologrepeat" org-log-repeat nil)
4849 ("logreschedule" org-log-reschedule time)
4850 ("lognotereschedule" org-log-reschedule note)
4851 ("nologreschedule" org-log-reschedule nil)
4852 ("logredeadline" org-log-redeadline time)
4853 ("lognoteredeadline" org-log-redeadline note)
4854 ("nologredeadline" org-log-redeadline nil)
4855 ("logrefile" org-log-refile time)
4856 ("lognoterefile" org-log-refile note)
4857 ("nologrefile" org-log-refile nil)
4858 ("fninline" org-footnote-define-inline t)
4859 ("nofninline" org-footnote-define-inline nil)
4860 ("fnlocal" org-footnote-section nil)
4861 ("fnauto" org-footnote-auto-label t)
4862 ("fnprompt" org-footnote-auto-label nil)
4863 ("fnconfirm" org-footnote-auto-label confirm)
4864 ("fnplain" org-footnote-auto-label plain)
4865 ("fnadjust" org-footnote-auto-adjust t)
4866 ("nofnadjust" org-footnote-auto-adjust nil)
4867 ("constcgs" constants-unit-system cgs)
4868 ("constSI" constants-unit-system SI)
4869 ("noptag" org-tag-persistent-alist nil)
4870 ("hideblocks" org-hide-block-startup t)
4871 ("nohideblocks" org-hide-block-startup nil)
4872 ("beamer" org-startup-with-beamer-mode t)
4873 ("entitiespretty" org-pretty-entities t)
4874 ("entitiesplain" org-pretty-entities nil))
4875 "Variable associated with STARTUP options for org-mode.
4876 Each element is a list of three items: the startup options (as written
4877 in the #+STARTUP line), the corresponding variable, and the value to set
4878 this variable to if the option is found. An optional forth element PUSH
4879 means to push this value onto the list in the variable.")
4881 (defun org-update-property-plist (key val props)
4882 "Update PROPS with KEY and VAL."
4883 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4884 (key (if appending (substring key 0 (- (length key) 1)) key))
4885 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4886 (previous (cdr (assoc key props))))
4887 (if appending
4888 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4889 (cons (cons key val) remainder))))
4891 (defcustom org-group-tags t
4892 "When non-nil (the default), use group tags.
4893 This can be turned on/off through `org-toggle-tags-groups'."
4894 :group 'org-tags
4895 :group 'org-startup
4896 :type 'boolean)
4898 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4900 (defun org-toggle-tags-groups ()
4901 "Toggle support for group tags.
4902 Support for group tags is controlled by the option
4903 `org-group-tags', which is non-nil by default."
4904 (interactive)
4905 (setq org-group-tags (not org-group-tags))
4906 (cond ((and (derived-mode-p 'org-agenda-mode)
4907 org-group-tags)
4908 (org-agenda-redo))
4909 ((derived-mode-p 'org-mode)
4910 (let ((org-inhibit-startup t)) (org-mode))))
4911 (message "Groups tags support has been turned %s"
4912 (if org-group-tags "on" "off")))
4914 (defun org-set-regexps-and-options-for-tags ()
4915 "Precompute variables used for tags."
4916 (when (derived-mode-p 'org-mode)
4917 (org-set-local 'org-file-tags nil)
4918 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4919 (splitre "[ \t]+")
4920 (start 0)
4921 tags ftags key value)
4922 (save-excursion
4923 (save-restriction
4924 (widen)
4925 (goto-char (point-min))
4926 (while (re-search-forward re nil t)
4927 (setq key (upcase (org-match-string-no-properties 1))
4928 value (org-match-string-no-properties 2))
4929 (if (stringp value) (setq value (org-trim value)))
4930 (cond
4931 ((equal key "TAGS")
4932 (setq tags (append tags (if tags '("\\n") nil)
4933 (org-split-string value splitre))))
4934 ((equal key "FILETAGS")
4935 (when (string-match "\\S-" value)
4936 (setq ftags
4937 (append
4938 ftags
4939 (apply 'append
4940 (mapcar (lambda (x) (org-split-string x ":"))
4941 (org-split-string value)))))))))))
4942 ;; Process the file tags.
4943 (and ftags (org-set-local 'org-file-tags
4944 (mapcar 'org-add-prop-inherited ftags)))
4945 (org-set-local 'org-tag-groups-alist nil)
4946 ;; Process the tags.
4947 (when (and (not tags) org-tag-alist)
4948 (setq tags
4949 (mapcar
4950 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4951 ((eq (car tg) :endgroup) "}")
4952 ((eq (car tg) :grouptags) ":")
4953 ((eq (car tg) :newline) "\n")
4954 (t (concat (car tg)
4955 (if (characterp (cdr tg))
4956 (format "(%s)" (char-to-string (cdr tg))) "")))))
4957 org-tag-alist)))
4958 (let (e tgs g)
4959 (while (setq e (pop tags))
4960 (cond
4961 ((equal e "{")
4962 (progn (push '(:startgroup) tgs)
4963 (when (equal (nth 1 tags) ":")
4964 (push (list (replace-regexp-in-string
4965 "(.+)$" "" (nth 0 tags)))
4966 org-tag-groups-alist)
4967 (setq g 0))))
4968 ((equal e ":") (push '(:grouptags) tgs))
4969 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4970 ((equal e "\\n") (push '(:newline) tgs))
4971 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4972 (push (cons (match-string 1 e)
4973 (string-to-char (match-string 2 e))) tgs)
4974 (if (and g (> g 0))
4975 (setcar org-tag-groups-alist
4976 (append (car org-tag-groups-alist)
4977 (list (match-string 1 e)))))
4978 (if g (setq g (1+ g))))
4979 (t (push (list e) tgs)
4980 (if (and g (> g 0))
4981 (setcar org-tag-groups-alist
4982 (append (car org-tag-groups-alist) (list e))))
4983 (if g (setq g (1+ g))))))
4984 (org-set-local 'org-tag-alist nil)
4985 (while (setq e (pop tgs))
4986 (or (and (stringp (car e))
4987 (assoc (car e) org-tag-alist))
4988 (push e org-tag-alist)))
4989 ;; Return a list with tag variables
4990 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4992 (defvar org-ota nil)
4993 (defun org-set-regexps-and-options ()
4994 "Precompute regular expressions used in the current buffer."
4995 (when (derived-mode-p 'org-mode)
4996 (org-set-local 'org-todo-kwd-alist nil)
4997 (org-set-local 'org-todo-key-alist nil)
4998 (org-set-local 'org-todo-key-trigger nil)
4999 (org-set-local 'org-todo-keywords-1 nil)
5000 (org-set-local 'org-done-keywords nil)
5001 (org-set-local 'org-todo-heads nil)
5002 (org-set-local 'org-todo-sets nil)
5003 (org-set-local 'org-todo-log-states nil)
5004 (org-set-local 'org-file-properties nil)
5005 (let ((re (org-make-options-regexp
5006 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5007 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5008 "SETUPFILE" "OPTIONS")
5009 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5010 (splitre "[ \t]+")
5011 (scripts org-use-sub-superscripts)
5012 kwds kws0 kwsa key log value cat arch const links hw dws
5013 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5014 (start 0))
5015 (save-excursion
5016 (save-restriction
5017 (widen)
5018 (goto-char (point-min))
5019 (while
5020 (or (and
5021 ext-setup-or-nil
5022 (not org-ota)
5023 (let (ret)
5024 (with-temp-buffer
5025 (insert ext-setup-or-nil)
5026 (let ((major-mode 'org-mode) org-ota)
5027 (setq ret (save-match-data
5028 (org-set-regexps-and-options-for-tags)))))
5029 ;; Append setupfile tags to existing tags
5030 (setq org-ota t)
5031 (setq org-file-tags
5032 (delq nil (append org-file-tags (nth 0 ret)))
5033 org-tag-alist
5034 (delq nil (append org-tag-alist (nth 1 ret)))
5035 org-tag-groups-alist
5036 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5037 (and ext-setup-or-nil
5038 (string-match re ext-setup-or-nil start)
5039 (setq start (match-end 0)))
5040 (and (setq ext-setup-or-nil nil start 0)
5041 (re-search-forward re nil t)))
5042 (setq key (upcase (match-string 1 ext-setup-or-nil))
5043 value (org-match-string-no-properties 2 ext-setup-or-nil))
5044 (if (stringp value) (setq value (org-trim value)))
5045 (cond
5046 ((equal key "CATEGORY")
5047 (setq cat value))
5048 ((member key '("SEQ_TODO" "TODO"))
5049 (push (cons 'sequence (org-split-string value splitre)) kwds))
5050 ((equal key "TYP_TODO")
5051 (push (cons 'type (org-split-string value splitre)) kwds))
5052 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5053 ;; general TODO-like setup
5054 (push (cons (intern (downcase (match-string 1 key)))
5055 (org-split-string value splitre)) kwds))
5056 ((equal key "COLUMNS")
5057 (org-set-local 'org-columns-default-format value))
5058 ((equal key "LINK")
5059 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5060 (push (cons (match-string 1 value)
5061 (org-trim (match-string 2 value)))
5062 links)))
5063 ((equal key "PRIORITIES")
5064 (setq prio (org-split-string value " +")))
5065 ((equal key "PROPERTY")
5066 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5067 (setq props (org-update-property-plist (match-string 1 value)
5068 (match-string 2 value)
5069 props))))
5070 ((equal key "CONSTANTS")
5071 (org-table-set-constants))
5072 ((equal key "STARTUP")
5073 (let ((opts (org-split-string value splitre))
5074 l var val)
5075 (while (setq l (pop opts))
5076 (when (setq l (assoc l org-startup-options))
5077 (setq var (nth 1 l) val (nth 2 l))
5078 (if (not (nth 3 l))
5079 (set (make-local-variable var) val)
5080 (if (not (listp (symbol-value var)))
5081 (set (make-local-variable var) nil))
5082 (set (make-local-variable var) (symbol-value var))
5083 (add-to-list var val))))))
5084 ((equal key "ARCHIVE")
5085 (setq arch value)
5086 (remove-text-properties 0 (length arch)
5087 '(face t fontified t) arch))
5088 ((equal key "OPTIONS")
5089 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5090 (setq scripts (read (match-string 2 value)))))
5091 ((and (equal key "SETUPFILE")
5092 ;; Prevent checking in Gnus messages
5093 (not buffer-read-only))
5094 (setq setup-contents (org-file-contents
5095 (expand-file-name
5096 (org-remove-double-quotes value))
5097 'noerror))
5098 (if (not ext-setup-or-nil)
5099 (setq ext-setup-or-nil setup-contents start 0)
5100 (setq ext-setup-or-nil
5101 (concat (substring ext-setup-or-nil 0 start)
5102 "\n" setup-contents "\n"
5103 (substring ext-setup-or-nil start)))))))
5104 ;; search for property blocks
5105 (goto-char (point-min))
5106 (while (re-search-forward org-block-regexp nil t)
5107 (when (equal "PROPERTY" (upcase (match-string 1)))
5108 (setq value (replace-regexp-in-string
5109 "[\n\r]" " " (match-string 4)))
5110 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5111 (setq props (org-update-property-plist (match-string 1 value)
5112 (match-string 2 value)
5113 props)))))))
5114 (org-set-local 'org-use-sub-superscripts scripts)
5115 (when cat
5116 (org-set-local 'org-category (intern cat))
5117 (push (cons "CATEGORY" cat) props))
5118 (when prio
5119 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5120 (setq prio (mapcar 'string-to-char prio))
5121 (org-set-local 'org-highest-priority (nth 0 prio))
5122 (org-set-local 'org-lowest-priority (nth 1 prio))
5123 (org-set-local 'org-default-priority (nth 2 prio)))
5124 (and props (org-set-local 'org-file-properties (nreverse props)))
5125 (and arch (org-set-local 'org-archive-location arch))
5126 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5127 ;; Process the TODO keywords
5128 (unless kwds
5129 ;; Use the global values as if they had been given locally.
5130 (setq kwds (default-value 'org-todo-keywords))
5131 (if (stringp (car kwds))
5132 (setq kwds (list (cons org-todo-interpretation
5133 (default-value 'org-todo-keywords)))))
5134 (setq kwds (reverse kwds)))
5135 (setq kwds (nreverse kwds))
5136 (let (inter kws kw)
5137 (while (setq kws (pop kwds))
5138 (let ((kws (or
5139 (run-hook-with-args-until-success
5140 'org-todo-setup-filter-hook kws)
5141 kws)))
5142 (setq inter (pop kws) sep (member "|" kws)
5143 kws0 (delete "|" (copy-sequence kws))
5144 kwsa nil
5145 kws1 (mapcar
5146 (lambda (x)
5147 ;; 1 2
5148 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5149 (progn
5150 (setq kw (match-string 1 x)
5151 key (and (match-end 2) (match-string 2 x))
5152 log (org-extract-log-state-settings x))
5153 (push (cons kw (and key (string-to-char key))) kwsa)
5154 (and log (push log org-todo-log-states))
5156 (error "Invalid TODO keyword %s" x)))
5157 kws0)
5158 kwsa (if kwsa (append '((:startgroup))
5159 (nreverse kwsa)
5160 '((:endgroup))))
5161 hw (car kws1)
5162 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5163 tail (list inter hw (car dws) (org-last dws))))
5164 (add-to-list 'org-todo-heads hw 'append)
5165 (push kws1 org-todo-sets)
5166 (setq org-done-keywords (append org-done-keywords dws nil))
5167 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5168 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5169 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5170 (setq org-todo-sets (nreverse org-todo-sets)
5171 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5172 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5173 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5174 ;; Compute the regular expressions and other local variables.
5175 ;; Using `org-outline-regexp-bol' would complicate them much,
5176 ;; because of the fixed white space at the end of that string.
5177 (if (not org-done-keywords)
5178 (setq org-done-keywords (and org-todo-keywords-1
5179 (list (org-last org-todo-keywords-1)))))
5180 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5181 (length org-scheduled-string)
5182 (length org-clock-string)
5183 (length org-closed-string)))
5184 org-not-done-keywords
5185 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5186 org-todo-regexp
5187 (concat "\\("
5188 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5189 "\\)")
5190 org-not-done-regexp
5191 (concat "\\("
5192 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5193 "\\)")
5194 org-not-done-heading-regexp
5195 (format org-heading-keyword-regexp-format org-not-done-regexp)
5196 org-todo-line-regexp
5197 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5198 org-complex-heading-regexp
5199 (concat "^\\(\\*+\\)"
5200 "\\(?: +" org-todo-regexp "\\)?"
5201 "\\(?: +\\(\\[#.\\]\\)\\)?"
5202 "\\(?: +\\(.*?\\)\\)??"
5203 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5204 "[ \t]*$")
5205 org-complex-heading-regexp-format
5206 (concat "^\\(\\*+\\)"
5207 "\\(?: +" org-todo-regexp "\\)?"
5208 "\\(?: +\\(\\[#.\\]\\)\\)?"
5209 "\\(?: +"
5210 ;; Stats cookies can be stuck to body.
5211 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5212 "\\(%s\\)"
5213 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5214 "\\)"
5215 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5216 "[ \t]*$")
5217 org-todo-line-tags-regexp
5218 (concat "^\\(\\*+\\)"
5219 "\\(?: +" org-todo-regexp "\\)?"
5220 "\\(?: +\\(.*?\\)\\)??"
5221 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5222 "[ \t]*$")
5223 org-deadline-regexp (concat "\\<" org-deadline-string)
5224 org-deadline-time-regexp
5225 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5226 org-deadline-time-hour-regexp
5227 (concat "\\<" org-deadline-string
5228 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5229 org-deadline-line-regexp
5230 (concat "\\<\\(" org-deadline-string "\\).*")
5231 org-scheduled-regexp
5232 (concat "\\<" org-scheduled-string)
5233 org-scheduled-time-regexp
5234 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5235 org-scheduled-time-hour-regexp
5236 (concat "\\<" org-scheduled-string
5237 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5238 org-closed-time-regexp
5239 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5240 org-keyword-time-regexp
5241 (concat "\\<\\(" org-scheduled-string
5242 "\\|" org-deadline-string
5243 "\\|" org-closed-string
5244 "\\|" org-clock-string "\\)"
5245 " *[[<]\\([^]>]+\\)[]>]")
5246 org-keyword-time-not-clock-regexp
5247 (concat "\\<\\(" org-scheduled-string
5248 "\\|" org-deadline-string
5249 "\\|" org-closed-string
5250 "\\)"
5251 " *[[<]\\([^]>]+\\)[]>]")
5252 org-maybe-keyword-time-regexp
5253 (concat "\\(\\<\\(" org-scheduled-string
5254 "\\|" org-deadline-string
5255 "\\|" org-closed-string
5256 "\\|" org-clock-string "\\)\\)?"
5257 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5258 org-all-time-keywords
5259 (mapcar (lambda (w) (substring w 0 -1))
5260 (list org-scheduled-string org-deadline-string
5261 org-clock-string org-closed-string)))
5262 (setq org-ota nil)
5263 (org-compute-latex-and-related-regexp))))
5265 (defun org-file-contents (file &optional noerror)
5266 "Return the contents of FILE, as a string."
5267 (if (and file (file-readable-p file))
5268 (with-temp-buffer
5269 (insert-file-contents file)
5270 (buffer-string))
5271 (funcall (if noerror 'message 'error)
5272 "Cannot read file \"%s\"%s"
5273 file
5274 (let ((from (buffer-file-name (buffer-base-buffer))))
5275 (if from (concat " (referenced in file \"" from "\")") "")))))
5277 (defun org-extract-log-state-settings (x)
5278 "Extract the log state setting from a TODO keyword string.
5279 This will extract info from a string like \"WAIT(w@/!)\"."
5280 (let (kw key log1 log2)
5281 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5282 (setq kw (match-string 1 x)
5283 key (and (match-end 2) (match-string 2 x))
5284 log1 (and (match-end 3) (match-string 3 x))
5285 log2 (and (match-end 4) (match-string 4 x)))
5286 (and (or log1 log2)
5287 (list kw
5288 (and log1 (if (equal log1 "!") 'time 'note))
5289 (and log2 (if (equal log2 "!") 'time 'note)))))))
5291 (defun org-remove-keyword-keys (list)
5292 "Remove a pair of parenthesis at the end of each string in LIST."
5293 (mapcar (lambda (x)
5294 (if (string-match "(.*)$" x)
5295 (substring x 0 (match-beginning 0))
5297 list))
5299 (defun org-assign-fast-keys (alist)
5300 "Assign fast keys to a keyword-key alist.
5301 Respect keys that are already there."
5302 (let (new e (alt ?0))
5303 (while (setq e (pop alist))
5304 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5305 (cdr e)) ;; Key already assigned.
5306 (push e new)
5307 (let ((clist (string-to-list (downcase (car e))))
5308 (used (append new alist)))
5309 (when (= (car clist) ?@)
5310 (pop clist))
5311 (while (and clist (rassoc (car clist) used))
5312 (pop clist))
5313 (unless clist
5314 (while (rassoc alt used)
5315 (incf alt)))
5316 (push (cons (car e) (or (car clist) alt)) new))))
5317 (nreverse new)))
5319 ;;; Some variables used in various places
5321 (defvar org-window-configuration nil
5322 "Used in various places to store a window configuration.")
5323 (defvar org-selected-window nil
5324 "Used in various places to store a window configuration.")
5325 (defvar org-finish-function nil
5326 "Function to be called when `C-c C-c' is used.
5327 This is for getting out of special buffers like capture.")
5330 ;; FIXME: Occasionally check by commenting these, to make sure
5331 ;; no other functions uses these, forgetting to let-bind them.
5332 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5333 (defvar org-last-state)
5334 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5336 ;; Defined somewhere in this file, but used before definition.
5337 (defvar org-entities) ;; defined in org-entities.el
5338 (defvar org-struct-menu)
5339 (defvar org-org-menu)
5340 (defvar org-tbl-menu)
5342 ;;;; Define the Org-mode
5344 ;; We use a before-change function to check if a table might need
5345 ;; an update.
5346 (defvar org-table-may-need-update t
5347 "Indicates that a table might need an update.
5348 This variable is set by `org-before-change-function'.
5349 `org-table-align' sets it back to nil.")
5350 (defun org-before-change-function (beg end)
5351 "Every change indicates that a table might need an update."
5352 (setq org-table-may-need-update t))
5353 (defvar org-mode-map)
5354 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5355 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5357 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5358 (defvar org-table-buffer-is-an nil)
5360 (defvar bidi-paragraph-direction)
5361 (defvar buffer-face-mode-face)
5363 (require 'outline)
5364 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5365 (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"))
5366 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5368 ;; Other stuff we need.
5369 (require 'time-date)
5370 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5371 (require 'easymenu)
5372 (require 'overlay)
5374 ;; (require 'org-macs) moved higher up in the file before it is first used
5375 (require 'org-entities)
5376 ;; (require 'org-compat) moved higher up in the file before it is first used
5377 (require 'org-faces)
5378 (require 'org-list)
5379 (require 'org-pcomplete)
5380 (require 'org-src)
5381 (require 'org-footnote)
5382 (require 'org-macro)
5384 ;; babel
5385 (require 'ob)
5387 ;;;###autoload
5388 (define-derived-mode org-mode outline-mode "Org"
5389 "Outline-based notes management and organizer, alias
5390 \"Carsten's outline-mode for keeping track of everything.\"
5392 Org-mode develops organizational tasks around a NOTES file which
5393 contains information about projects as plain text. Org-mode is
5394 implemented on top of outline-mode, which is ideal to keep the content
5395 of large files well structured. It supports ToDo items, deadlines and
5396 time stamps, which magically appear in the diary listing of the Emacs
5397 calendar. Tables are easily created with a built-in table editor.
5398 Plain text URL-like links connect to websites, emails (VM), Usenet
5399 messages (Gnus), BBDB entries, and any files related to the project.
5400 For printing and sharing of notes, an Org-mode file (or a part of it)
5401 can be exported as a structured ASCII or HTML file.
5403 The following commands are available:
5405 \\{org-mode-map}"
5407 ;; Get rid of Outline menus, they are not needed
5408 ;; Need to do this here because define-derived-mode sets up
5409 ;; the keymap so late. Still, it is a waste to call this each time
5410 ;; we switch another buffer into org-mode.
5411 (if (featurep 'xemacs)
5412 (when (boundp 'outline-mode-menu-heading)
5413 ;; Assume this is Greg's port, it uses easymenu
5414 (easy-menu-remove outline-mode-menu-heading)
5415 (easy-menu-remove outline-mode-menu-show)
5416 (easy-menu-remove outline-mode-menu-hide))
5417 (define-key org-mode-map [menu-bar headings] 'undefined)
5418 (define-key org-mode-map [menu-bar hide] 'undefined)
5419 (define-key org-mode-map [menu-bar show] 'undefined))
5421 (org-load-modules-maybe)
5422 (easy-menu-add org-org-menu)
5423 (easy-menu-add org-tbl-menu)
5424 (org-install-agenda-files-menu)
5425 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5426 (add-to-invisibility-spec '(org-cwidth))
5427 (add-to-invisibility-spec '(org-hide-block . t))
5428 (when (featurep 'xemacs)
5429 (org-set-local 'line-move-ignore-invisible t))
5430 (org-set-local 'outline-regexp org-outline-regexp)
5431 (org-set-local 'outline-level 'org-outline-level)
5432 (setq bidi-paragraph-direction 'left-to-right)
5433 (when (and org-ellipsis
5434 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5435 (fboundp 'make-glyph-code))
5436 (unless org-display-table
5437 (setq org-display-table (make-display-table)))
5438 (set-display-table-slot
5439 org-display-table 4
5440 (vconcat (mapcar
5441 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5442 org-ellipsis)))
5443 (if (stringp org-ellipsis) org-ellipsis "..."))))
5444 (setq buffer-display-table org-display-table))
5445 (org-set-regexps-and-options-for-tags)
5446 (org-set-regexps-and-options)
5447 (org-set-font-lock-defaults)
5448 (when (and org-tag-faces (not org-tags-special-faces-re))
5449 ;; tag faces set outside customize.... force initialization.
5450 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5451 ;; Calc embedded
5452 (org-set-local 'calc-embedded-open-mode "# ")
5453 ;; Modify a few syntax entries
5454 (modify-syntax-entry ?@ "w")
5455 (modify-syntax-entry ?\" "\"")
5456 (modify-syntax-entry ?\\ "_")
5457 (modify-syntax-entry ?~ "_")
5458 (if org-startup-truncated (setq truncate-lines t))
5459 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5460 (org-set-local 'font-lock-unfontify-region-function
5461 'org-unfontify-region)
5462 ;; Activate before-change-function
5463 (org-set-local 'org-table-may-need-update t)
5464 (org-add-hook 'before-change-functions 'org-before-change-function nil
5465 'local)
5466 ;; Check for running clock before killing a buffer
5467 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5468 ;; Initialize macros templates.
5469 (org-macro-initialize-templates)
5470 ;; Initialize radio targets.
5471 (org-update-radio-target-regexp)
5472 ;; Indentation.
5473 (org-set-local 'indent-line-function 'org-indent-line)
5474 (org-set-local 'indent-region-function 'org-indent-region)
5475 ;; Filling and auto-filling.
5476 (org-setup-filling)
5477 ;; Comments.
5478 (org-setup-comments-handling)
5479 ;; Initialize cache.
5480 (org-element-cache-reset)
5481 ;; Beginning/end of defun
5482 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5483 (org-set-local 'end-of-defun-function
5484 (lambda ()
5485 (if (not (org-at-heading-p))
5486 (org-forward-element)
5487 (org-forward-element)
5488 (forward-char -1))))
5489 ;; Next error for sparse trees
5490 (org-set-local 'next-error-function 'org-occur-next-match)
5491 ;; Make sure dependence stuff works reliably, even for users who set it
5492 ;; too late :-(
5493 (if org-enforce-todo-dependencies
5494 (add-hook 'org-blocker-hook
5495 'org-block-todo-from-children-or-siblings-or-parent)
5496 (remove-hook 'org-blocker-hook
5497 'org-block-todo-from-children-or-siblings-or-parent))
5498 (if org-enforce-todo-checkbox-dependencies
5499 (add-hook 'org-blocker-hook
5500 'org-block-todo-from-checkboxes)
5501 (remove-hook 'org-blocker-hook
5502 'org-block-todo-from-checkboxes))
5504 ;; Align options lines
5505 (org-set-local
5506 'align-mode-rules-list
5507 '((org-in-buffer-settings
5508 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5509 (modes . '(org-mode)))))
5511 ;; Imenu
5512 (org-set-local 'imenu-create-index-function
5513 'org-imenu-get-tree)
5515 ;; Make isearch reveal context
5516 (if (or (featurep 'xemacs)
5517 (not (boundp 'outline-isearch-open-invisible-function)))
5518 ;; Emacs 21 and XEmacs make use of the hook
5519 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5520 ;; Emacs 22 deals with this through a special variable
5521 (org-set-local 'outline-isearch-open-invisible-function
5522 (lambda (&rest ignore) (org-show-context 'isearch)))
5523 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5525 ;; Setup the pcomplete hooks
5526 (set (make-local-variable 'pcomplete-command-completion-function)
5527 'org-pcomplete-initial)
5528 (set (make-local-variable 'pcomplete-command-name-function)
5529 'org-command-at-point)
5530 (set (make-local-variable 'pcomplete-default-completion-function)
5531 'ignore)
5532 (set (make-local-variable 'pcomplete-parse-arguments-function)
5533 'org-parse-arguments)
5534 (set (make-local-variable 'pcomplete-termination-string) "")
5535 (when (>= emacs-major-version 23)
5536 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5538 ;; If empty file that did not turn on org-mode automatically, make it to.
5539 (if (and org-insert-mode-line-in-empty-file
5540 (org-called-interactively-p 'any)
5541 (= (point-min) (point-max)))
5542 (insert "# -*- mode: org -*-\n\n"))
5543 (unless org-inhibit-startup
5544 (org-unmodified
5545 (and org-startup-with-beamer-mode (org-beamer-mode))
5546 (when org-startup-align-all-tables
5547 (org-table-map-tables 'org-table-align 'quietly))
5548 (when org-startup-with-inline-images
5549 (org-display-inline-images))
5550 (when org-startup-with-latex-preview
5551 (org-preview-latex-fragment))
5552 (unless org-inhibit-startup-visibility-stuff
5553 (org-set-startup-visibility))
5554 (org-refresh-effort-properties)))
5555 ;; Try to set org-hide correctly
5556 (let ((foreground (org-find-invisible-foreground)))
5557 (if foreground
5558 (set-face-foreground 'org-hide foreground))))
5560 ;; Update `customize-package-emacs-version-alist'
5561 (add-to-list 'customize-package-emacs-version-alist
5562 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5563 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5564 ("8.2.6" . "24.4")))
5566 (defvar org-mode-transpose-word-syntax-table
5567 (let ((st (make-syntax-table)))
5568 (mapc (lambda(c) (modify-syntax-entry
5569 (string-to-char (car c)) "w p" st))
5570 org-emphasis-alist)
5571 st))
5573 (when (fboundp 'abbrev-table-put)
5574 (abbrev-table-put org-mode-abbrev-table
5575 :parents (list text-mode-abbrev-table)))
5577 (defsubst org-fix-ellipsis-at-bol ()
5578 (save-excursion (goto-char (window-start)) (recenter 0)))
5580 (defun org-find-invisible-foreground ()
5581 (let ((candidates (remove
5582 "unspecified-bg"
5583 (nconc
5584 (list (face-background 'default)
5585 (face-background 'org-default))
5586 (mapcar
5587 (lambda (alist)
5588 (when (boundp alist)
5589 (cdr (assoc 'background-color (symbol-value alist)))))
5590 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5591 (list (face-foreground 'org-hide))))))
5592 (car (remove nil candidates))))
5594 (defun org-current-time (&optional rounding-minutes past)
5595 "Current time, possibly rounded to ROUNDING-MINUTES.
5596 When ROUNDING-MINUTES is not an integer, fall back on the car of
5597 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5598 the rounding returns a past time."
5599 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5600 (car org-time-stamp-rounding-minutes)))
5601 (time (decode-time)) res)
5602 (if (< r 1)
5603 (current-time)
5604 (setq res
5605 (apply 'encode-time
5606 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5607 (nthcdr 2 time))))
5608 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5609 (seconds-to-time (- (org-float-time res) (* r 60)))
5610 res))))
5612 (defun org-today ()
5613 "Return today date, considering `org-extend-today-until'."
5614 (time-to-days
5615 (time-subtract (current-time)
5616 (list 0 (* 3600 org-extend-today-until) 0))))
5618 ;;;; Font-Lock stuff, including the activators
5620 (defvar org-mouse-map (make-sparse-keymap))
5621 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5622 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5623 (when org-mouse-1-follows-link
5624 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5625 (when org-tab-follows-link
5626 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5627 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5629 (require 'font-lock)
5631 (defconst org-non-link-chars "]\t\n\r<>")
5632 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5633 "file+sys" "news" "shell" "elisp" "doi" "message"
5634 "help"))
5635 (defvar org-link-types-re nil
5636 "Matches a link that has a url-like prefix like \"http:\"")
5637 (defvar org-link-re-with-space nil
5638 "Matches a link with spaces, optional angular brackets around it.")
5639 (defvar org-link-re-with-space2 nil
5640 "Matches a link with spaces, optional angular brackets around it.")
5641 (defvar org-link-re-with-space3 nil
5642 "Matches a link with spaces, only for internal part in bracket links.")
5643 (defvar org-angle-link-re nil
5644 "Matches link with angular brackets, spaces are allowed.")
5645 (defvar org-plain-link-re nil
5646 "Matches plain link, without spaces.")
5647 (defvar org-bracket-link-regexp nil
5648 "Matches a link in double brackets.")
5649 (defvar org-bracket-link-analytic-regexp nil
5650 "Regular expression used to analyze links.
5651 Here is what the match groups contain after a match:
5652 1: http:
5653 2: http
5654 3: path
5655 4: [desc]
5656 5: desc")
5657 (defvar org-bracket-link-analytic-regexp++ nil
5658 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5659 (defvar org-any-link-re nil
5660 "Regular expression matching any link.")
5662 (defconst org-match-sexp-depth 3
5663 "Number of stacked braces for sub/superscript matching.")
5665 (defun org-create-multibrace-regexp (left right n)
5666 "Create a regular expression which will match a balanced sexp.
5667 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5668 as single character strings.
5669 The regexp returned will match the entire expression including the
5670 delimiters. It will also define a single group which contains the
5671 match except for the outermost delimiters. The maximum depth of
5672 stacked delimiters is N. Escaping delimiters is not possible."
5673 (let* ((nothing (concat "[^" left right "]*?"))
5674 (or "\\|")
5675 (re nothing)
5676 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5677 (while (> n 1)
5678 (setq n (1- n)
5679 re (concat re or next)
5680 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5681 (concat left "\\(" re "\\)" right)))
5683 (defconst org-match-substring-regexp
5684 (concat
5685 "\\(\\S-\\)\\([_^]\\)\\("
5686 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5687 "\\|"
5688 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5689 "\\|"
5690 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5691 "The regular expression matching a sub- or superscript.")
5693 (defconst org-match-substring-with-braces-regexp
5694 (concat
5695 "\\(\\S-\\)\\([_^]\\)"
5696 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5697 "The regular expression matching a sub- or superscript, forcing braces.")
5699 (defun org-make-link-regexps ()
5700 "Update the link regular expressions.
5701 This should be called after the variable `org-link-types' has changed."
5702 (let ((types-re (regexp-opt org-link-types t)))
5703 (setq org-link-types-re
5704 (concat "\\`" types-re ":")
5705 org-link-re-with-space
5706 (concat "<?" types-re ":"
5707 "\\([^" org-non-link-chars " ]"
5708 "[^" org-non-link-chars "]*"
5709 "[^" org-non-link-chars " ]\\)>?")
5710 org-link-re-with-space2
5711 (concat "<?" types-re ":"
5712 "\\([^" org-non-link-chars " ]"
5713 "[^\t\n\r]*"
5714 "[^" org-non-link-chars " ]\\)>?")
5715 org-link-re-with-space3
5716 (concat "<?" types-re ":"
5717 "\\([^" org-non-link-chars " ]"
5718 "[^\t\n\r]*\\)")
5719 org-angle-link-re
5720 (concat "<" types-re ":"
5721 "\\([^" org-non-link-chars " ]"
5722 "[^" org-non-link-chars "]*"
5723 "\\)>")
5724 org-plain-link-re
5725 (concat
5726 "\\<" types-re ":"
5727 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5728 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5729 org-bracket-link-regexp
5730 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5731 org-bracket-link-analytic-regexp
5732 (concat
5733 "\\[\\["
5734 "\\(" types-re ":\\)?"
5735 "\\([^]]+\\)"
5736 "\\]"
5737 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5738 "\\]")
5739 org-bracket-link-analytic-regexp++
5740 (concat
5741 "\\[\\["
5742 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5743 "\\([^]]+\\)"
5744 "\\]"
5745 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5746 "\\]")
5747 org-any-link-re
5748 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5749 org-angle-link-re "\\)\\|\\("
5750 org-plain-link-re "\\)"))))
5752 (org-make-link-regexps)
5754 (defvar org-emph-face nil)
5756 (defun org-do-emphasis-faces (limit)
5757 "Run through the buffer and emphasize strings."
5758 (let (rtn a)
5759 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5760 (let* ((border (char-after (match-beginning 3)))
5761 (bre (regexp-quote (char-to-string border))))
5762 (if (and (not (= border (char-after (match-beginning 4))))
5763 (not (save-match-data
5764 (string-match (concat bre ".*" bre)
5765 (replace-regexp-in-string
5766 "\n" " "
5767 (substring (match-string 2) 1 -1))))))
5768 (progn
5769 (setq rtn t)
5770 (setq a (assoc (match-string 3) org-emphasis-alist))
5771 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5772 'face
5773 (nth 1 a))
5774 (and (nth 2 a)
5775 (org-remove-flyspell-overlays-in
5776 (match-beginning 0) (match-end 0)))
5777 (add-text-properties (match-beginning 2) (match-end 2)
5778 '(font-lock-multiline t org-emphasis t))
5779 (when org-hide-emphasis-markers
5780 (add-text-properties (match-end 4) (match-beginning 5)
5781 '(invisible org-link))
5782 (add-text-properties (match-beginning 3) (match-end 3)
5783 '(invisible org-link))))))
5784 (goto-char (1+ (match-beginning 0))))
5785 rtn))
5787 (defun org-emphasize (&optional char)
5788 "Insert or change an emphasis, i.e. a font like bold or italic.
5789 If there is an active region, change that region to a new emphasis.
5790 If there is no region, just insert the marker characters and position
5791 the cursor between them.
5792 CHAR should be the marker character. If it is a space, it means to
5793 remove the emphasis of the selected region.
5794 If CHAR is not given (for example in an interactive call) it will be
5795 prompted for."
5796 (interactive)
5797 (let ((erc org-emphasis-regexp-components)
5798 (prompt "")
5799 (string "") beg end move c s)
5800 (if (org-region-active-p)
5801 (setq beg (region-beginning) end (region-end)
5802 string (buffer-substring beg end))
5803 (setq move t))
5805 (unless char
5806 (message "Emphasis marker or tag: [%s]"
5807 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5808 (setq char (read-char-exclusive)))
5809 (if (equal char ?\ )
5810 (setq s "" move nil)
5811 (unless (assoc (char-to-string char) org-emphasis-alist)
5812 (user-error "No such emphasis marker: \"%c\"" char))
5813 (setq s (char-to-string char)))
5814 (while (and (> (length string) 1)
5815 (equal (substring string 0 1) (substring string -1))
5816 (assoc (substring string 0 1) org-emphasis-alist))
5817 (setq string (substring string 1 -1)))
5818 (setq string (concat s string s))
5819 (if beg (delete-region beg end))
5820 (unless (or (bolp)
5821 (string-match (concat "[" (nth 0 erc) "\n]")
5822 (char-to-string (char-before (point)))))
5823 (insert " "))
5824 (unless (or (eobp)
5825 (string-match (concat "[" (nth 1 erc) "\n]")
5826 (char-to-string (char-after (point)))))
5827 (insert " ") (backward-char 1))
5828 (insert string)
5829 (and move (backward-char 1))))
5831 (defconst org-nonsticky-props
5832 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5834 (defsubst org-rear-nonsticky-at (pos)
5835 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5837 (defun org-activate-plain-links (limit)
5838 "Run through the buffer and add overlays to links."
5839 (let (f hl)
5840 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5841 (not (org-in-src-block-p)))
5842 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5843 (setq f (get-text-property (match-beginning 0) 'face))
5844 (setq hl (org-match-string-no-properties 0))
5845 (if (or (eq f 'org-tag)
5846 (and (listp f) (memq 'org-tag f)))
5848 (add-text-properties (match-beginning 0) (match-end 0)
5849 (list 'mouse-face 'highlight
5850 'face 'org-link
5851 'htmlize-link `(:uri ,hl)
5852 'keymap org-mouse-map))
5853 (org-rear-nonsticky-at (match-end 0)))
5854 t)))
5856 (defun org-activate-code (limit)
5857 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5858 (progn
5859 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5860 (remove-text-properties (match-beginning 0) (match-end 0)
5861 '(display t invisible t intangible t))
5862 t)))
5864 (defcustom org-src-fontify-natively t
5865 "When non-nil, fontify code in code blocks."
5866 :type 'boolean
5867 :version "24.4"
5868 :package-version '(Org . "8.3")
5869 :group 'org-appearance
5870 :group 'org-babel)
5872 (defcustom org-allow-promoting-top-level-subtree nil
5873 "When non-nil, allow promoting a top level subtree.
5874 The leading star of the top level headline will be replaced
5875 by a #."
5876 :type 'boolean
5877 :version "24.1"
5878 :group 'org-appearance)
5880 (defun org-fontify-meta-lines-and-blocks (limit)
5881 (condition-case nil
5882 (org-fontify-meta-lines-and-blocks-1 limit)
5883 (error (message "org-mode fontification error"))))
5885 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5886 "Fontify #+ lines and blocks."
5887 (let ((case-fold-search t))
5888 (if (re-search-forward
5889 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5890 limit t)
5891 (let ((beg (match-beginning 0))
5892 (block-start (match-end 0))
5893 (block-end nil)
5894 (lang (match-string 7))
5895 (beg1 (line-beginning-position 2))
5896 (dc1 (downcase (match-string 2)))
5897 (dc3 (downcase (match-string 3)))
5898 end end1 quoting block-type ovl)
5899 (cond
5900 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5901 ;; a single line of backend-specific content
5902 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5903 (remove-text-properties (match-beginning 0) (match-end 0)
5904 '(display t invisible t intangible t))
5905 (add-text-properties (match-beginning 1) (match-end 3)
5906 '(font-lock-fontified t face org-meta-line))
5907 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5908 '(font-lock-fontified t face org-block))
5909 ; for backend-specific code
5911 ((and (match-end 4) (equal dc3 "+begin"))
5912 ;; Truly a block
5913 (setq block-type (downcase (match-string 5))
5914 quoting (member block-type org-protecting-blocks))
5915 (when (re-search-forward
5916 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5917 nil t) ;; on purpose, we look further than LIMIT
5918 (setq end (min (point-max) (match-end 0))
5919 end1 (min (point-max) (1- (match-beginning 0))))
5920 (setq block-end (match-beginning 0))
5921 (when quoting
5922 (org-remove-flyspell-overlays-in beg1 end1)
5923 (remove-text-properties beg end
5924 '(display t invisible t intangible t)))
5925 (add-text-properties
5926 beg end '(font-lock-fontified t font-lock-multiline t))
5927 (add-text-properties beg beg1 '(face org-meta-line))
5928 (org-remove-flyspell-overlays-in beg beg1)
5929 (add-text-properties ; For end_src
5930 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5931 (org-remove-flyspell-overlays-in end1 end)
5932 (cond
5933 ((and lang (not (string= lang "")) org-src-fontify-natively)
5934 (org-src-font-lock-fontify-block lang block-start block-end)
5935 ;; remove old background overlays
5936 (mapc (lambda (ov)
5937 (if (eq (overlay-get ov 'face) 'org-block-background)
5938 (delete-overlay ov)))
5939 (overlays-at (/ (+ beg1 block-end) 2)))
5940 ;; add a background overlay
5941 (setq ovl (make-overlay beg1 block-end))
5942 (overlay-put ovl 'face 'org-block-background)
5943 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5944 (quoting
5945 (add-text-properties beg1 (min (point-max) (1+ end1))
5946 '(face org-block))) ; end of source block
5947 ((not org-fontify-quote-and-verse-blocks))
5948 ((string= block-type "quote")
5949 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5950 ((string= block-type "verse")
5951 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5952 (add-text-properties beg beg1 '(face org-block-begin-line))
5953 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5954 '(face org-block-end-line))
5956 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5957 (org-remove-flyspell-overlays-in
5958 (match-beginning 0)
5959 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5960 (add-text-properties
5961 beg (match-end 3)
5962 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5963 '(font-lock-fontified t invisible t)
5964 '(font-lock-fontified t face org-document-info-keyword)))
5965 (add-text-properties
5966 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5967 (if (string-equal dc1 "+title:")
5968 '(font-lock-fontified t face org-document-title)
5969 '(font-lock-fontified t face org-document-info))))
5970 ((or (equal dc1 "+results")
5971 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5972 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5973 "+call:" "+header:" "+headers:" "+name:"))
5974 (and (match-end 4) (equal dc3 "+attr")))
5975 (org-remove-flyspell-overlays-in
5976 (match-beginning 0)
5977 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5978 (add-text-properties
5979 beg (match-end 0)
5980 '(font-lock-fontified t face org-meta-line))
5982 ((member dc3 '(" " ""))
5983 (org-remove-flyspell-overlays-in beg (match-end 0))
5984 (add-text-properties
5985 beg (match-end 0)
5986 '(font-lock-fontified t face font-lock-comment-face)))
5987 (t ;; just any other in-buffer setting, but not indented
5988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (add-text-properties
5990 beg (match-end 0)
5991 '(font-lock-fontified t face org-meta-line))
5992 t))))))
5994 (defun org-fontify-drawers (limit)
5995 "Fontify drawers."
5996 (when (re-search-forward org-drawer-regexp limit t)
5997 (add-text-properties
5998 (match-beginning 0) (match-end 0)
5999 '(font-lock-fontified t face org-special-keyword))
6000 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6003 (defun org-fontify-macros (limit)
6004 "Fontify macros."
6005 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6006 (add-text-properties
6007 (match-beginning 0) (match-end 0)
6008 '(font-lock-fontified t face org-macro))
6009 (when org-hide-macro-markers
6010 (add-text-properties (match-end 2) (match-beginning 2)
6011 '(invisible t))
6012 (add-text-properties (match-beginning 1) (match-end 1)
6013 '(invisible t)))
6014 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6017 (defun org-activate-angle-links (limit)
6018 "Run through the buffer and add overlays to links."
6019 (if (and (re-search-forward org-angle-link-re limit t)
6020 (not (org-in-src-block-p)))
6021 (progn
6022 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6023 (add-text-properties (match-beginning 0) (match-end 0)
6024 (list 'mouse-face 'highlight
6025 'keymap org-mouse-map))
6026 (org-rear-nonsticky-at (match-end 0))
6027 t)))
6029 (defun org-activate-footnote-links (limit)
6030 "Run through the buffer and add overlays to footnotes."
6031 (let ((fn (org-footnote-next-reference-or-definition limit)))
6032 (when fn
6033 (let* ((beg (nth 1 fn))
6034 (end (nth 2 fn))
6035 (label (car fn))
6036 (referencep (/= (line-beginning-position) beg)))
6037 (when (and referencep (nth 3 fn))
6038 (save-excursion
6039 (goto-char beg)
6040 (search-forward (or label "fn:"))
6041 (org-remove-flyspell-overlays-in beg (match-end 0))))
6042 (add-text-properties beg end
6043 (list 'mouse-face 'highlight
6044 'keymap org-mouse-map
6045 'help-echo
6046 (if referencep "Footnote reference"
6047 "Footnote definition")
6048 'font-lock-fontified t
6049 'font-lock-multiline t
6050 'face 'org-footnote))))))
6052 (defun org-activate-bracket-links (limit)
6053 "Run through the buffer and add overlays to bracketed links."
6054 (if (and (re-search-forward org-bracket-link-regexp limit t)
6055 (not (org-in-src-block-p)))
6056 (let* ((hl (org-match-string-no-properties 1))
6057 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6058 (ip (org-maybe-intangible
6059 (list 'invisible 'org-link
6060 'keymap org-mouse-map 'mouse-face 'highlight
6061 'font-lock-multiline t 'help-echo help
6062 'htmlize-link `(:uri ,hl))))
6063 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6064 'font-lock-multiline t 'help-echo help
6065 'htmlize-link `(:uri ,hl))))
6066 ;; We need to remove the invisible property here. Table narrowing
6067 ;; may have made some of this invisible.
6068 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6069 (remove-text-properties (match-beginning 0) (match-end 0)
6070 '(invisible nil))
6071 (if (match-end 3)
6072 (progn
6073 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6074 (org-rear-nonsticky-at (match-beginning 3))
6075 (add-text-properties (match-beginning 3) (match-end 3) vp)
6076 (org-rear-nonsticky-at (match-end 3))
6077 (add-text-properties (match-end 3) (match-end 0) ip)
6078 (org-rear-nonsticky-at (match-end 0)))
6079 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6080 (org-rear-nonsticky-at (match-beginning 1))
6081 (add-text-properties (match-beginning 1) (match-end 1) vp)
6082 (org-rear-nonsticky-at (match-end 1))
6083 (add-text-properties (match-end 1) (match-end 0) ip)
6084 (org-rear-nonsticky-at (match-end 0)))
6085 t)))
6087 (defun org-activate-dates (limit)
6088 "Run through the buffer and add overlays to dates."
6089 (if (and (re-search-forward org-tsr-regexp-both limit t)
6090 (not (equal (char-before (match-beginning 0)) 91)))
6091 (progn
6092 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6093 (add-text-properties (match-beginning 0) (match-end 0)
6094 (list 'mouse-face 'highlight
6095 'keymap org-mouse-map))
6096 (org-rear-nonsticky-at (match-end 0))
6097 (when org-display-custom-times
6098 (if (match-end 3)
6099 (org-display-custom-time (match-beginning 3) (match-end 3)))
6100 (org-display-custom-time (match-beginning 1) (match-end 1)))
6101 t)))
6103 (defvar org-target-link-regexp nil
6104 "Regular expression matching radio targets in plain text.")
6105 (make-variable-buffer-local 'org-target-link-regexp)
6107 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6108 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6109 border border border))
6110 "Regular expression matching a link target.")
6112 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6113 "Regular expression matching a radio target.")
6115 (defconst org-any-target-regexp
6116 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6117 "Regular expression matching any target.")
6119 (defun org-activate-target-links (limit)
6120 "Run through the buffer and add overlays to target matches."
6121 (when org-target-link-regexp
6122 (let ((case-fold-search t))
6123 (if (re-search-forward org-target-link-regexp limit t)
6124 (progn
6125 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6126 (add-text-properties (match-beginning 1) (match-end 1)
6127 (list 'mouse-face 'highlight
6128 'keymap org-mouse-map
6129 'help-echo "Radio target link"
6130 'org-linked-text t))
6131 (org-rear-nonsticky-at (match-end 1))
6132 t)))))
6134 (defun org-update-radio-target-regexp ()
6135 "Find all radio targets in this file and update the regular expression.
6136 Also refresh fontification if needed."
6137 (interactive)
6138 (let ((old-regexp org-target-link-regexp)
6139 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6140 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6141 (targets
6142 (org-with-wide-buffer
6143 (goto-char (point-min))
6144 (let (rtn)
6145 (while (re-search-forward org-radio-target-regexp nil t)
6146 ;; Make sure point is really within the object.
6147 (backward-char)
6148 (let ((obj (org-element-context)))
6149 (when (eq (org-element-type obj) 'radio-target)
6150 (add-to-list 'rtn (org-element-property :value obj)))))
6151 rtn))))
6152 (setq org-target-link-regexp
6153 (and targets
6154 (concat before-re
6155 (mapconcat
6156 (lambda (x)
6157 (replace-regexp-in-string
6158 " +" "\\s-+" (regexp-quote x) t t))
6159 targets
6160 "\\|")
6161 after-re)))
6162 (unless (equal old-regexp org-target-link-regexp)
6163 ;; Clean-up cache.
6164 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6165 ((not org-target-link-regexp) old-regexp)
6167 (concat before-re
6168 (mapconcat
6169 (lambda (re)
6170 (substring re (length before-re)
6171 (- (length after-re))))
6172 (list old-regexp org-target-link-regexp)
6173 "\\|")
6174 after-re)))))
6175 (org-with-wide-buffer
6176 (goto-char (point-min))
6177 (while (re-search-forward regexp nil t)
6178 (org-element-cache-refresh (match-beginning 1)))))
6179 ;; Re fontify buffer.
6180 (when (memq 'radio org-highlight-links)
6181 (org-restart-font-lock)))))
6183 (defun org-hide-wide-columns (limit)
6184 (let (s e)
6185 (setq s (text-property-any (point) (or limit (point-max))
6186 'org-cwidth t))
6187 (when s
6188 (setq e (next-single-property-change s 'org-cwidth))
6189 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6190 (goto-char e)
6191 t)))
6193 (defvar org-latex-and-related-regexp nil
6194 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6196 (defun org-compute-latex-and-related-regexp ()
6197 "Compute regular expression for LaTeX, entities and sub/superscript.
6198 Result depends on variable `org-highlight-latex-and-related'."
6199 (org-set-local
6200 'org-latex-and-related-regexp
6201 (let* ((re-sub
6202 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6203 ((eq org-use-sub-superscripts '{})
6204 (list org-match-substring-with-braces-regexp))
6205 (org-use-sub-superscripts (list org-match-substring-regexp))))
6206 (re-latex
6207 (when (memq 'latex org-highlight-latex-and-related)
6208 (let ((matchers (plist-get org-format-latex-options :matchers)))
6209 (delq nil
6210 (mapcar (lambda (x)
6211 (and (member (car x) matchers) (nth 1 x)))
6212 org-latex-regexps)))))
6213 (re-entities
6214 (when (memq 'entities org-highlight-latex-and-related)
6215 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6216 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6218 (defun org-do-latex-and-related (limit)
6219 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6220 LIMIT bounds the search for syntax to highlight. Stop at first
6221 highlighted object, if any. Return t if some highlighting was
6222 done, nil otherwise."
6223 (when (org-string-nw-p org-latex-and-related-regexp)
6224 (catch 'found
6225 (while (re-search-forward org-latex-and-related-regexp limit t)
6226 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6227 'face))
6228 '(org-code org-verbatim underline))
6229 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6230 '(?_ ?^))
6232 0)))
6233 (font-lock-prepend-text-property
6234 (+ offset (match-beginning 0)) (match-end 0)
6235 'face 'org-latex-and-related)
6236 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6237 '(font-lock-multiline t)))
6238 (throw 'found t)))
6239 nil)))
6241 (defun org-restart-font-lock ()
6242 "Restart `font-lock-mode', to force refontification."
6243 (when (and (boundp 'font-lock-mode) font-lock-mode)
6244 (font-lock-mode -1)
6245 (font-lock-mode 1)))
6247 (defun org-activate-tags (limit)
6248 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6249 (progn
6250 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6251 (add-text-properties (match-beginning 1) (match-end 1)
6252 (list 'mouse-face 'highlight
6253 'keymap org-mouse-map))
6254 (org-rear-nonsticky-at (match-end 1))
6255 t)))
6257 (defun org-outline-level ()
6258 "Compute the outline level of the heading at point.
6259 If this is called at a normal headline, the level is the number of stars.
6260 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6261 (save-excursion
6262 (if (not (ignore-errors (org-back-to-heading t)))
6264 (looking-at org-outline-regexp)
6265 (1- (- (match-end 0) (match-beginning 0))))))
6267 (defvar org-font-lock-keywords nil)
6269 (defsubst org-re-property (property &optional literal allow-null)
6270 "Return a regexp matching a PROPERTY line.
6271 Match group 3 will be set to the value if it exists."
6272 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6273 (if literal property (regexp-quote property))
6274 "\\):\\)[ \t]+\\(?3:[^ \t\r\n]"
6275 (if allow-null "*")
6276 ".*?\\)\\(?5:[ \t]*\\)$"))
6278 (defconst org-property-re
6279 (org-re-property ".*?" 'literal t)
6280 "Regular expression matching a property line.
6281 There are four matching groups:
6282 1: :PROPKEY: including the leading and trailing colon,
6283 2: PROPKEY without the leading and trailing colon,
6284 3: PROPVAL without leading or trailing spaces,
6285 4: the indentation of the current line,
6286 5: trailing whitespace.")
6288 (defvar org-font-lock-hook nil
6289 "Functions to be called for special font lock stuff.")
6291 (defvar org-font-lock-set-keywords-hook nil
6292 "Functions that can manipulate `org-font-lock-extra-keywords'.
6293 This is called after `org-font-lock-extra-keywords' is defined, but before
6294 it is installed to be used by font lock. This can be useful if something
6295 needs to be inserted at a specific position in the font-lock sequence.")
6297 (defun org-font-lock-hook (limit)
6298 "Run `org-font-lock-hook' within LIMIT."
6299 (run-hook-with-args 'org-font-lock-hook limit))
6301 (defun org-set-font-lock-defaults ()
6302 "Set font lock defaults for the current buffer."
6303 (let* ((em org-fontify-emphasized-text)
6304 (lk org-highlight-links)
6305 (org-font-lock-extra-keywords
6306 (list
6307 ;; Call the hook
6308 '(org-font-lock-hook)
6309 ;; Headlines
6310 `(,(if org-fontify-whole-heading-line
6311 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6312 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6313 (1 (org-get-level-face 1))
6314 (2 (org-get-level-face 2))
6315 (3 (org-get-level-face 3)))
6316 ;; Table lines
6317 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6318 (1 'org-table t))
6319 ;; Table internals
6320 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6321 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6322 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6323 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6324 ;; Drawers
6325 '(org-fontify-drawers)
6326 ;; Properties
6327 (list org-property-re
6328 '(1 'org-special-keyword t)
6329 '(3 'org-property-value t))
6330 ;; Links
6331 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6332 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6333 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6334 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6335 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6336 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6337 (if (memq 'footnote lk) '(org-activate-footnote-links))
6338 ;; Targets.
6339 (list org-any-target-regexp '(0 'org-target t))
6340 ;; Diary sexps.
6341 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6342 ;; Macro
6343 '(org-fontify-macros)
6344 '(org-hide-wide-columns (0 nil append))
6345 ;; TODO keyword
6346 (list (format org-heading-keyword-regexp-format
6347 org-todo-regexp)
6348 '(2 (org-get-todo-face 2) t))
6349 ;; DONE
6350 (if org-fontify-done-headline
6351 (list (format org-heading-keyword-regexp-format
6352 (concat
6353 "\\(?:"
6354 (mapconcat 'regexp-quote org-done-keywords "\\|")
6355 "\\)"))
6356 '(2 'org-headline-done t))
6357 nil)
6358 ;; Priorities
6359 '(org-font-lock-add-priority-faces)
6360 ;; Tags
6361 '(org-font-lock-add-tag-faces)
6362 ;; Tags groups
6363 (if (and org-group-tags org-tag-groups-alist)
6364 (list (concat org-outline-regexp-bol ".+\\(:"
6365 (regexp-opt (mapcar 'car org-tag-groups-alist))
6366 ":\\).*$")
6367 '(1 'org-tag-group prepend)))
6368 ;; Special keywords
6369 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6370 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6371 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6372 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6373 ;; Emphasis
6374 (if em
6375 (if (featurep 'xemacs)
6376 '(org-do-emphasis-faces (0 nil append))
6377 '(org-do-emphasis-faces)))
6378 ;; Checkboxes
6379 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6380 1 'org-checkbox prepend)
6381 (if (cdr (assq 'checkbox org-list-automatic-rules))
6382 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6383 (0 (org-get-checkbox-statistics-face) t)))
6384 ;; Description list items
6385 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6386 1 'org-list-dt prepend)
6387 ;; ARCHIVEd headings
6388 (list (concat
6389 org-outline-regexp-bol
6390 "\\(.*:" org-archive-tag ":.*\\)")
6391 '(1 'org-archived prepend))
6392 ;; Specials
6393 '(org-do-latex-and-related)
6394 '(org-fontify-entities)
6395 '(org-raise-scripts)
6396 ;; Code
6397 '(org-activate-code (1 'org-code t))
6398 ;; COMMENT
6399 (list (format
6400 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6401 org-todo-regexp
6402 org-comment-string)
6403 '(9 'org-special-keyword t))
6404 ;; Blocks and meta lines
6405 '(org-fontify-meta-lines-and-blocks))))
6406 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6407 (run-hooks 'org-font-lock-set-keywords-hook)
6408 ;; Now set the full font-lock-keywords
6409 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6410 (org-set-local 'font-lock-defaults
6411 '(org-font-lock-keywords t nil nil backward-paragraph))
6412 (kill-local-variable 'font-lock-keywords) nil))
6414 (defun org-toggle-pretty-entities ()
6415 "Toggle the composition display of entities as UTF8 characters."
6416 (interactive)
6417 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6418 (org-restart-font-lock)
6419 (if org-pretty-entities
6420 (message "Entities are now displayed as UTF8 characters")
6421 (save-restriction
6422 (widen)
6423 (org-decompose-region (point-min) (point-max))
6424 (message "Entities are now displayed as plain text"))))
6426 (defvar org-custom-properties-overlays nil
6427 "List of overlays used for custom properties.")
6428 (make-variable-buffer-local 'org-custom-properties-overlays)
6430 (defun org-toggle-custom-properties-visibility ()
6431 "Display or hide properties in `org-custom-properties'."
6432 (interactive)
6433 (if org-custom-properties-overlays
6434 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6435 (setq org-custom-properties-overlays nil))
6436 (unless (not org-custom-properties)
6437 (save-excursion
6438 (save-restriction
6439 (widen)
6440 (goto-char (point-min))
6441 (while (re-search-forward org-property-re nil t)
6442 (mapc (lambda(p)
6443 (when (equal p (substring (match-string 1) 1 -1))
6444 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6445 (overlay-put o 'invisible t)
6446 (overlay-put o 'org-custom-property t)
6447 (push o org-custom-properties-overlays))))
6448 org-custom-properties)))))))
6450 (defun org-fontify-entities (limit)
6451 "Find an entity to fontify."
6452 (let (ee)
6453 (when org-pretty-entities
6454 (catch 'match
6455 (while (re-search-forward
6456 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6457 limit t)
6458 (if (and (not (org-at-comment-p))
6459 (setq ee (org-entity-get (match-string 1)))
6460 (= (length (nth 6 ee)) 1))
6461 (let*
6462 ((end (if (equal (match-string 2) "{}")
6463 (match-end 2)
6464 (match-end 1))))
6465 (add-text-properties
6466 (match-beginning 0) end
6467 (list 'font-lock-fontified t))
6468 (compose-region (match-beginning 0) end
6469 (nth 6 ee) nil)
6470 (backward-char 1)
6471 (throw 'match t))))
6472 nil))))
6474 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6475 "Fontify string S like in Org-mode."
6476 (with-temp-buffer
6477 (insert s)
6478 (let ((org-odd-levels-only odd-levels))
6479 (org-mode)
6480 (font-lock-ensure)
6481 (buffer-string))))
6483 (defvar org-m nil)
6484 (defvar org-l nil)
6485 (defvar org-f nil)
6486 (defun org-get-level-face (n)
6487 "Get the right face for match N in font-lock matching of headlines."
6488 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6489 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6490 (if org-cycle-level-faces
6491 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6492 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6493 (cond
6494 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6495 ((eq n 2) org-f)
6496 (t (if org-level-color-stars-only nil org-f))))
6499 (defun org-get-todo-face (kwd)
6500 "Get the right face for a TODO keyword KWD.
6501 If KWD is a number, get the corresponding match group."
6502 (if (numberp kwd) (setq kwd (match-string kwd)))
6503 (or (org-face-from-face-or-color
6504 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6505 (and (member kwd org-done-keywords) 'org-done)
6506 'org-todo))
6508 (defun org-face-from-face-or-color (context inherit face-or-color)
6509 "Create a face list that inherits INHERIT, but sets the foreground color.
6510 When FACE-OR-COLOR is not a string, just return it."
6511 (if (stringp face-or-color)
6512 (list :inherit inherit
6513 (cdr (assoc context org-faces-easy-properties))
6514 face-or-color)
6515 face-or-color))
6517 (defun org-font-lock-add-tag-faces (limit)
6518 "Add the special tag faces."
6519 (when (and org-tag-faces org-tags-special-faces-re)
6520 (while (re-search-forward org-tags-special-faces-re limit t)
6521 (add-text-properties (match-beginning 1) (match-end 1)
6522 (list 'face (org-get-tag-face 1)
6523 'font-lock-fontified t))
6524 (backward-char 1))))
6526 (defun org-font-lock-add-priority-faces (limit)
6527 "Add the special priority faces."
6528 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6529 (when (save-match-data (org-at-heading-p))
6530 (add-text-properties
6531 (match-beginning 0) (match-end 0)
6532 (list 'face (or (org-face-from-face-or-color
6533 'priority 'org-priority
6534 (cdr (assoc (char-after (match-beginning 1))
6535 org-priority-faces)))
6536 'org-priority)
6537 'font-lock-fontified t)))))
6539 (defun org-get-tag-face (kwd)
6540 "Get the right face for a TODO keyword KWD.
6541 If KWD is a number, get the corresponding match group."
6542 (if (numberp kwd) (setq kwd (match-string kwd)))
6543 (or (org-face-from-face-or-color
6544 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6545 'org-tag))
6547 (defun org-unfontify-region (beg end &optional maybe_loudly)
6548 "Remove fontification and activation overlays from links."
6549 (font-lock-default-unfontify-region beg end)
6550 (let* ((buffer-undo-list t)
6551 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6552 (inhibit-modification-hooks t)
6553 deactivate-mark buffer-file-name buffer-file-truename)
6554 (org-decompose-region beg end)
6555 (remove-text-properties beg end
6556 '(mouse-face t keymap t org-linked-text t
6557 invisible t intangible t
6558 org-emphasis t))
6559 (org-remove-font-lock-display-properties beg end)))
6561 (defconst org-script-display '(((raise -0.3) (height 0.7))
6562 ((raise 0.3) (height 0.7))
6563 ((raise -0.5))
6564 ((raise 0.5)))
6565 "Display properties for showing superscripts and subscripts.")
6567 (defun org-remove-font-lock-display-properties (beg end)
6568 "Remove specific display properties that have been added by font lock.
6569 The will remove the raise properties that are used to show superscripts
6570 and subscripts."
6571 (let (next prop)
6572 (while (< beg end)
6573 (setq next (next-single-property-change beg 'display nil end)
6574 prop (get-text-property beg 'display))
6575 (if (member prop org-script-display)
6576 (put-text-property beg next 'display nil))
6577 (setq beg next))))
6579 (defun org-raise-scripts (limit)
6580 "Add raise properties to sub/superscripts."
6581 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6582 (if (re-search-forward
6583 (if (eq org-use-sub-superscripts t)
6584 org-match-substring-regexp
6585 org-match-substring-with-braces-regexp)
6586 limit t)
6587 (let* ((pos (point)) table-p comment-p
6588 (mpos (match-beginning 3))
6589 (emph-p (get-text-property mpos 'org-emphasis))
6590 (link-p (get-text-property mpos 'mouse-face))
6591 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6592 (goto-char (point-at-bol))
6593 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6594 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6595 (goto-char pos)
6596 ;; Handle a_b^c
6597 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6598 (if (or comment-p emph-p link-p keyw-p)
6600 (put-text-property (match-beginning 3) (match-end 0)
6601 'display
6602 (if (equal (char-after (match-beginning 2)) ?^)
6603 (nth (if table-p 3 1) org-script-display)
6604 (nth (if table-p 2 0) org-script-display)))
6605 (add-text-properties (match-beginning 2) (match-end 2)
6606 (list 'invisible t
6607 'org-dwidth t 'org-dwidth-n 1))
6608 (if (and (eq (char-after (match-beginning 3)) ?{)
6609 (eq (char-before (match-end 3)) ?}))
6610 (progn
6611 (add-text-properties
6612 (match-beginning 3) (1+ (match-beginning 3))
6613 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6614 (add-text-properties
6615 (1- (match-end 3)) (match-end 3)
6616 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6617 t)))))
6619 ;;;; Visibility cycling, including org-goto and indirect buffer
6621 ;;; Cycling
6623 (defvar org-cycle-global-status nil)
6624 (make-variable-buffer-local 'org-cycle-global-status)
6625 (put 'org-cycle-global-status 'org-state t)
6626 (defvar org-cycle-subtree-status nil)
6627 (make-variable-buffer-local 'org-cycle-subtree-status)
6628 (put 'org-cycle-subtree-status 'org-state t)
6630 (defvar org-inlinetask-min-level)
6632 (defun org-unlogged-message (&rest args)
6633 "Display a message, but avoid logging it in the *Messages* buffer."
6634 (let ((message-log-max nil))
6635 (apply 'message args)))
6637 ;;;###autoload
6638 (defun org-cycle (&optional arg)
6639 "TAB-action and visibility cycling for Org-mode.
6641 This is the command invoked in Org-mode by the TAB key. Its main purpose
6642 is outline visibility cycling, but it also invokes other actions
6643 in special contexts.
6645 - When this function is called with a prefix argument, rotate the entire
6646 buffer through 3 states (global cycling)
6647 1. OVERVIEW: Show only top-level headlines.
6648 2. CONTENTS: Show all headlines of all levels, but no body text.
6649 3. SHOW ALL: Show everything.
6650 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6651 determined by the variable `org-startup-folded', and by any VISIBILITY
6652 properties in the buffer.
6653 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6654 including any drawers.
6656 - When inside a table, re-align the table and move to the next field.
6658 - When point is at the beginning of a headline, rotate the subtree started
6659 by this line through 3 different states (local cycling)
6660 1. FOLDED: Only the main headline is shown.
6661 2. CHILDREN: The main headline and the direct children are shown.
6662 From this state, you can move to one of the children
6663 and zoom in further.
6664 3. SUBTREE: Show the entire subtree, including body text.
6665 If there is no subtree, switch directly from CHILDREN to FOLDED.
6667 - When point is at the beginning of an empty headline and the variable
6668 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6669 of the headline by demoting and promoting it to likely levels. This
6670 speeds up creation document structure by pressing TAB once or several
6671 times right after creating a new headline.
6673 - When there is a numeric prefix, go up to a heading with level ARG, do
6674 a `show-subtree' and return to the previous cursor position. If ARG
6675 is negative, go up that many levels.
6677 - When point is not at the beginning of a headline, execute the global
6678 binding for TAB, which is re-indenting the line. See the option
6679 `org-cycle-emulate-tab' for details.
6681 - Special case: if point is at the beginning of the buffer and there is
6682 no headline in line 1, this function will act as if called with prefix arg
6683 (C-u TAB, same as S-TAB) also when called without prefix arg.
6684 But only if also the variable `org-cycle-global-at-bob' is t."
6685 (interactive "P")
6686 (org-load-modules-maybe)
6687 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6688 (and org-cycle-level-after-item/entry-creation
6689 (or (org-cycle-level)
6690 (org-cycle-item-indentation))))
6691 (let* ((limit-level
6692 (or org-cycle-max-level
6693 (and (boundp 'org-inlinetask-min-level)
6694 org-inlinetask-min-level
6695 (1- org-inlinetask-min-level))))
6696 (nstars (and limit-level
6697 (if org-odd-levels-only
6698 (and limit-level (1- (* limit-level 2)))
6699 limit-level)))
6700 (org-outline-regexp
6701 (if (not (derived-mode-p 'org-mode))
6702 outline-regexp
6703 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6704 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6705 (not (looking-at org-outline-regexp))))
6706 (org-cycle-hook
6707 (if bob-special
6708 (delq 'org-optimize-window-after-visibility-change
6709 (copy-sequence org-cycle-hook))
6710 org-cycle-hook))
6711 (pos (point)))
6713 (if (or bob-special (equal arg '(4)))
6714 ;; special case: use global cycling
6715 (setq arg t))
6717 (cond
6719 ((equal arg '(16))
6720 (setq last-command 'dummy)
6721 (org-set-startup-visibility)
6722 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6724 ((equal arg '(64))
6725 (show-all)
6726 (org-unlogged-message "Entire buffer visible, including drawers"))
6728 ;; Try cdlatex TAB completion
6729 ((org-try-cdlatex-tab))
6731 ;; Table: enter it or move to the next field.
6732 ((org-at-table-p 'any)
6733 (if (org-at-table.el-p)
6734 (message "Use C-c ' to edit table.el tables")
6735 (if arg (org-table-edit-field t)
6736 (org-table-justify-field-maybe)
6737 (call-interactively 'org-table-next-field))))
6739 ((run-hook-with-args-until-success
6740 'org-tab-after-check-for-table-hook))
6742 ;; Global cycling: delegate to `org-cycle-internal-global'.
6743 ((eq arg t) (org-cycle-internal-global))
6745 ;; Drawers: delegate to `org-flag-drawer'.
6746 ((save-excursion
6747 (beginning-of-line 1)
6748 (looking-at org-drawer-regexp))
6749 (org-flag-drawer ; toggle block visibility
6750 (not (get-char-property (match-end 0) 'invisible))))
6752 ;; Show-subtree, ARG levels up from here.
6753 ((integerp arg)
6754 (save-excursion
6755 (org-back-to-heading)
6756 (outline-up-heading (if (< arg 0) (- arg)
6757 (- (funcall outline-level) arg)))
6758 (org-show-subtree)))
6760 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6761 ((and (featurep 'org-inlinetask)
6762 (org-inlinetask-at-task-p)
6763 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6764 (org-inlinetask-toggle-visibility))
6766 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6767 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6768 (save-excursion (beginning-of-line 1)
6769 (looking-at org-outline-regexp)))
6770 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6771 (org-cycle-internal-local))
6773 ;; From there: TAB emulation and template completion.
6774 (buffer-read-only (org-back-to-heading))
6776 ((run-hook-with-args-until-success
6777 'org-tab-after-check-for-cycling-hook))
6779 ((org-try-structure-completion))
6781 ((run-hook-with-args-until-success
6782 'org-tab-before-tab-emulation-hook))
6784 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6785 (or (not (bolp))
6786 (not (looking-at org-outline-regexp))))
6787 (call-interactively (global-key-binding "\t")))
6789 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6790 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6791 (or (and (eq org-cycle-emulate-tab 'white)
6792 (= (match-end 0) (point-at-eol)))
6793 (and (eq org-cycle-emulate-tab 'whitestart)
6794 (>= (match-end 0) pos))))
6796 (eq org-cycle-emulate-tab t))
6797 (call-interactively (global-key-binding "\t")))
6799 (t (save-excursion
6800 (org-back-to-heading)
6801 (org-cycle)))))))
6803 (defun org-cycle-internal-global ()
6804 "Do the global cycling action."
6805 ;; Hack to avoid display of messages for .org attachments in Gnus
6806 (let ((ga (string-match "\\*fontification" (buffer-name))))
6807 (cond
6808 ((and (eq last-command this-command)
6809 (eq org-cycle-global-status 'overview))
6810 ;; We just created the overview - now do table of contents
6811 ;; This can be slow in very large buffers, so indicate action
6812 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6813 (unless ga (org-unlogged-message "CONTENTS..."))
6814 (org-content)
6815 (unless ga (org-unlogged-message "CONTENTS...done"))
6816 (setq org-cycle-global-status 'contents)
6817 (run-hook-with-args 'org-cycle-hook 'contents))
6819 ((and (eq last-command this-command)
6820 (eq org-cycle-global-status 'contents))
6821 ;; We just showed the table of contents - now show everything
6822 (run-hook-with-args 'org-pre-cycle-hook 'all)
6823 (show-all)
6824 (unless ga (org-unlogged-message "SHOW ALL"))
6825 (setq org-cycle-global-status 'all)
6826 (run-hook-with-args 'org-cycle-hook 'all))
6829 ;; Default action: go to overview
6830 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6831 (org-overview)
6832 (unless ga (org-unlogged-message "OVERVIEW"))
6833 (setq org-cycle-global-status 'overview)
6834 (run-hook-with-args 'org-cycle-hook 'overview)))))
6836 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6838 (defun org-cycle-internal-local ()
6839 "Do the local cycling action."
6840 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6841 ;; First, determine end of headline (EOH), end of subtree or item
6842 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6843 (save-excursion
6844 (if (org-at-item-p)
6845 (progn
6846 (beginning-of-line)
6847 (setq struct (org-list-struct))
6848 (setq eoh (point-at-eol))
6849 (setq eos (org-list-get-item-end-before-blank (point) struct))
6850 (setq has-children (org-list-has-child-p (point) struct)))
6851 (org-back-to-heading)
6852 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6853 (setq eos (save-excursion (org-end-of-subtree t t)
6854 (when (bolp) (backward-char)) (point)))
6855 (setq has-children
6856 (or (save-excursion
6857 (let ((level (funcall outline-level)))
6858 (outline-next-heading)
6859 (and (org-at-heading-p t)
6860 (> (funcall outline-level) level))))
6861 (save-excursion
6862 (org-list-search-forward (org-item-beginning-re) eos t)))))
6863 ;; Determine end invisible part of buffer (EOL)
6864 (beginning-of-line 2)
6865 ;; XEmacs doesn't have `next-single-char-property-change'
6866 (if (featurep 'xemacs)
6867 (while (and (not (eobp)) ;; this is like `next-line'
6868 (get-char-property (1- (point)) 'invisible))
6869 (beginning-of-line 2))
6870 (while (and (not (eobp)) ;; this is like `next-line'
6871 (get-char-property (1- (point)) 'invisible))
6872 (goto-char (next-single-char-property-change (point) 'invisible))
6873 (and (eolp) (beginning-of-line 2))))
6874 (setq eol (point)))
6875 ;; Find out what to do next and set `this-command'
6876 (cond
6877 ((= eos eoh)
6878 ;; Nothing is hidden behind this heading
6879 (unless (org-before-first-heading-p)
6880 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6881 (org-unlogged-message "EMPTY ENTRY")
6882 (setq org-cycle-subtree-status nil)
6883 (save-excursion
6884 (goto-char eos)
6885 (outline-next-heading)
6886 (if (outline-invisible-p) (org-flag-heading nil))))
6887 ((and (or (>= eol eos)
6888 (not (string-match "\\S-" (buffer-substring eol eos))))
6889 (or has-children
6890 (not (setq children-skipped
6891 org-cycle-skip-children-state-if-no-children))))
6892 ;; Entire subtree is hidden in one line: children view
6893 (unless (org-before-first-heading-p)
6894 (run-hook-with-args 'org-pre-cycle-hook 'children))
6895 (if (org-at-item-p)
6896 (org-list-set-item-visibility (point-at-bol) struct 'children)
6897 (org-show-entry)
6898 (org-with-limited-levels (show-children))
6899 ;; FIXME: This slows down the func way too much.
6900 ;; How keep drawers hidden in subtree anyway?
6901 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6902 ;; (org-cycle-hide-drawers 'subtree))
6904 ;; Fold every list in subtree to top-level items.
6905 (when (eq org-cycle-include-plain-lists 'integrate)
6906 (save-excursion
6907 (org-back-to-heading)
6908 (while (org-list-search-forward (org-item-beginning-re) eos t)
6909 (beginning-of-line 1)
6910 (let* ((struct (org-list-struct))
6911 (prevs (org-list-prevs-alist struct))
6912 (end (org-list-get-bottom-point struct)))
6913 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6914 (org-list-get-all-items (point) struct prevs))
6915 (goto-char (if (< end eos) end eos)))))))
6916 (org-unlogged-message "CHILDREN")
6917 (save-excursion
6918 (goto-char eos)
6919 (outline-next-heading)
6920 (if (outline-invisible-p) (org-flag-heading nil)))
6921 (setq org-cycle-subtree-status 'children)
6922 (unless (org-before-first-heading-p)
6923 (run-hook-with-args 'org-cycle-hook 'children)))
6924 ((or children-skipped
6925 (and (eq last-command this-command)
6926 (eq org-cycle-subtree-status 'children)))
6927 ;; We just showed the children, or no children are there,
6928 ;; now show everything.
6929 (unless (org-before-first-heading-p)
6930 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6931 (outline-flag-region eoh eos nil)
6932 (org-unlogged-message
6933 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6934 (setq org-cycle-subtree-status 'subtree)
6935 (unless (org-before-first-heading-p)
6936 (run-hook-with-args 'org-cycle-hook 'subtree)))
6938 ;; Default action: hide the subtree.
6939 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6940 (outline-flag-region eoh eos t)
6941 (org-unlogged-message "FOLDED")
6942 (setq org-cycle-subtree-status 'folded)
6943 (unless (org-before-first-heading-p)
6944 (run-hook-with-args 'org-cycle-hook 'folded))))))
6946 ;;;###autoload
6947 (defun org-global-cycle (&optional arg)
6948 "Cycle the global visibility. For details see `org-cycle'.
6949 With \\[universal-argument] prefix arg, switch to startup visibility.
6950 With a numeric prefix, show all headlines up to that level."
6951 (interactive "P")
6952 (let ((org-cycle-include-plain-lists
6953 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6954 (cond
6955 ((integerp arg)
6956 (show-all)
6957 (hide-sublevels arg)
6958 (setq org-cycle-global-status 'contents))
6959 ((equal arg '(4))
6960 (org-set-startup-visibility)
6961 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6963 (org-cycle '(4))))))
6965 (defun org-set-startup-visibility ()
6966 "Set the visibility required by startup options and properties."
6967 (cond
6968 ((eq org-startup-folded t)
6969 (org-overview))
6970 ((eq org-startup-folded 'content)
6971 (org-content))
6972 ((or (eq org-startup-folded 'showeverything)
6973 (eq org-startup-folded nil))
6974 (show-all)))
6975 (unless (eq org-startup-folded 'showeverything)
6976 (if org-hide-block-startup (org-hide-block-all))
6977 (org-set-visibility-according-to-property 'no-cleanup)
6978 (org-cycle-hide-archived-subtrees 'all)
6979 (org-cycle-hide-drawers 'all)
6980 (org-cycle-show-empty-lines t)))
6982 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6983 "Switch subtree visibilities according to :VISIBILITY: property."
6984 (interactive)
6985 (let (org-show-entry-below state)
6986 (save-excursion
6987 (goto-char (point-min))
6988 (while (re-search-forward
6989 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6990 nil t)
6991 (setq state (match-string 1))
6992 (save-excursion
6993 (org-back-to-heading t)
6994 (hide-subtree)
6995 (org-reveal)
6996 (cond
6997 ((equal state '("fold" "folded"))
6998 (hide-subtree))
6999 ((equal state "children")
7000 (org-show-hidden-entry)
7001 (show-children))
7002 ((equal state "content")
7003 (save-excursion
7004 (save-restriction
7005 (org-narrow-to-subtree)
7006 (org-content))))
7007 ((member state '("all" "showall"))
7008 (show-subtree)))))
7009 (unless no-cleanup
7010 (org-cycle-hide-archived-subtrees 'all)
7011 (org-cycle-hide-drawers 'all)
7012 (org-cycle-show-empty-lines 'all)))))
7014 ;; This function uses outline-regexp instead of the more fundamental
7015 ;; org-outline-regexp so that org-cycle-global works outside of Org
7016 ;; buffers, where outline-regexp is needed.
7017 (defun org-overview ()
7018 "Switch to overview mode, showing only top-level headlines.
7019 This shows all headlines with a level equal or greater than the level
7020 of the first headline in the buffer. This is important, because if the
7021 first headline is not level one, then (hide-sublevels 1) gives confusing
7022 results."
7023 (interactive)
7024 (save-excursion
7025 (let ((level
7026 (save-excursion
7027 (goto-char (point-min))
7028 (if (re-search-forward (concat "^" outline-regexp) nil t)
7029 (progn
7030 (goto-char (match-beginning 0))
7031 (funcall outline-level))))))
7032 (and level (hide-sublevels level)))))
7034 (defun org-content (&optional arg)
7035 "Show all headlines in the buffer, like a table of contents.
7036 With numerical argument N, show content up to level N."
7037 (interactive "P")
7038 (org-overview)
7039 (save-excursion
7040 ;; Visit all headings and show their offspring
7041 (and (integerp arg) (org-overview))
7042 (goto-char (point-max))
7043 (catch 'exit
7044 (while (and (progn (condition-case nil
7045 (outline-previous-visible-heading 1)
7046 (error (goto-char (point-min))))
7048 (looking-at org-outline-regexp))
7049 (if (integerp arg)
7050 (show-children (1- arg))
7051 (show-branches))
7052 (if (bobp) (throw 'exit nil))))))
7054 (defun org-optimize-window-after-visibility-change (state)
7055 "Adjust the window after a change in outline visibility.
7056 This function is the default value of the hook `org-cycle-hook'."
7057 (when (get-buffer-window (current-buffer))
7058 (cond
7059 ((eq state 'content) nil)
7060 ((eq state 'all) nil)
7061 ((eq state 'folded) nil)
7062 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7063 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7065 (defun org-remove-empty-overlays-at (pos)
7066 "Remove outline overlays that do not contain non-white stuff."
7067 (mapc
7068 (lambda (o)
7069 (and (eq 'outline (overlay-get o 'invisible))
7070 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7071 (overlay-end o))))
7072 (delete-overlay o)))
7073 (overlays-at pos)))
7075 (defun org-clean-visibility-after-subtree-move ()
7076 "Fix visibility issues after moving a subtree."
7077 ;; First, find a reasonable region to look at:
7078 ;; Start two siblings above, end three below
7079 (let* ((beg (save-excursion
7080 (and (org-get-last-sibling)
7081 (org-get-last-sibling))
7082 (point)))
7083 (end (save-excursion
7084 (and (org-get-next-sibling)
7085 (org-get-next-sibling)
7086 (org-get-next-sibling))
7087 (if (org-at-heading-p)
7088 (point-at-eol)
7089 (point))))
7090 (level (looking-at "\\*+"))
7091 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7092 (save-excursion
7093 (save-restriction
7094 (narrow-to-region beg end)
7095 (when re
7096 ;; Properly fold already folded siblings
7097 (goto-char (point-min))
7098 (while (re-search-forward re nil t)
7099 (if (and (not (outline-invisible-p))
7100 (save-excursion
7101 (goto-char (point-at-eol)) (outline-invisible-p)))
7102 (hide-entry))))
7103 (org-cycle-show-empty-lines 'overview)
7104 (org-cycle-hide-drawers 'overview)))))
7106 (defun org-cycle-show-empty-lines (state)
7107 "Show empty lines above all visible headlines.
7108 The region to be covered depends on STATE when called through
7109 `org-cycle-hook'. Lisp program can use t for STATE to get the
7110 entire buffer covered. Note that an empty line is only shown if there
7111 are at least `org-cycle-separator-lines' empty lines before the headline."
7112 (when (not (= org-cycle-separator-lines 0))
7113 (save-excursion
7114 (let* ((n (abs org-cycle-separator-lines))
7115 (re (cond
7116 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7117 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7118 (t (let ((ns (number-to-string (- n 2))))
7119 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7120 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7121 beg end b e)
7122 (cond
7123 ((memq state '(overview contents t))
7124 (setq beg (point-min) end (point-max)))
7125 ((memq state '(children folded))
7126 (setq beg (point) end (progn (org-end-of-subtree t t)
7127 (beginning-of-line 2)
7128 (point)))))
7129 (when beg
7130 (goto-char beg)
7131 (while (re-search-forward re end t)
7132 (unless (get-char-property (match-end 1) 'invisible)
7133 (setq e (match-end 1))
7134 (if (< org-cycle-separator-lines 0)
7135 (setq b (save-excursion
7136 (goto-char (match-beginning 0))
7137 (org-back-over-empty-lines)
7138 (if (save-excursion
7139 (goto-char (max (point-min) (1- (point))))
7140 (org-at-heading-p))
7141 (1- (point))
7142 (point))))
7143 (setq b (match-beginning 1)))
7144 (outline-flag-region b e nil)))))))
7145 ;; Never hide empty lines at the end of the file.
7146 (save-excursion
7147 (goto-char (point-max))
7148 (outline-previous-heading)
7149 (outline-end-of-heading)
7150 (if (and (looking-at "[ \t\n]+")
7151 (= (match-end 0) (point-max)))
7152 (outline-flag-region (point) (match-end 0) nil))))
7154 (defun org-show-empty-lines-in-parent ()
7155 "Move to the parent and re-show empty lines before visible headlines."
7156 (save-excursion
7157 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7158 (org-cycle-show-empty-lines context))))
7160 (defun org-files-list ()
7161 "Return `org-agenda-files' list, plus all open org-mode files.
7162 This is useful for operations that need to scan all of a user's
7163 open and agenda-wise Org files."
7164 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7165 (dolist (buf (buffer-list))
7166 (with-current-buffer buf
7167 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7168 (let ((file (expand-file-name (buffer-file-name))))
7169 (unless (member file files)
7170 (push file files))))))
7171 files))
7173 (defsubst org-entry-beginning-position ()
7174 "Return the beginning position of the current entry."
7175 (save-excursion (outline-back-to-heading t) (point)))
7177 (defsubst org-entry-end-position ()
7178 "Return the end position of the current entry."
7179 (save-excursion (outline-next-heading) (point)))
7181 (defun org-cycle-hide-drawers (state &optional exceptions)
7182 "Re-hide all drawers after a visibility state change.
7183 When non-nil, optional argument EXCEPTIONS is a list of strings
7184 specifying which drawers should not be hidden."
7185 (when (and (derived-mode-p 'org-mode)
7186 (not (memq state '(overview folded contents))))
7187 (save-excursion
7188 (let* ((globalp (memq state '(contents all)))
7189 (beg (if globalp (point-min) (point)))
7190 (end (if globalp (point-max)
7191 (if (eq state 'children)
7192 (save-excursion (outline-next-heading) (point))
7193 (org-end-of-subtree t)))))
7194 (goto-char beg)
7195 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7196 (unless (member-ignore-case (match-string 1) exceptions)
7197 (let ((drawer (org-element-at-point)))
7198 (when (memq (org-element-type drawer) '(drawer property-drawer))
7199 (org-flag-drawer t drawer)
7200 ;; Make sure to skip drawer entirely or we might flag
7201 ;; it another time when matching its ending line with
7202 ;; `org-drawer-regexp'.
7203 (goto-char (org-element-property :end drawer))))))))))
7205 (defun org-cycle-hide-inline-tasks (state)
7206 "Re-hide inline tasks when switching to 'contents or 'children
7207 visibility state."
7208 (case state
7209 (contents
7210 (when (org-bound-and-true-p org-inlinetask-min-level)
7211 (hide-sublevels (1- org-inlinetask-min-level))))
7212 (children
7213 (when (featurep 'org-inlinetask)
7214 (save-excursion
7215 (while (and (outline-next-heading)
7216 (org-inlinetask-at-task-p))
7217 (org-inlinetask-toggle-visibility)
7218 (org-inlinetask-goto-end)))))))
7220 (defun org-flag-drawer (flag &optional element)
7221 "When FLAG is non-nil, hide the drawer we are at.
7222 Otherwise make it visible. When optional argument ELEMENT is
7223 a parsed drawer, as returned by `org-element-at-point', hide or
7224 show that drawer instead."
7225 (when (save-excursion
7226 (beginning-of-line)
7227 (org-looking-at-p org-drawer-regexp))
7228 (let ((drawer (or element (org-element-at-point))))
7229 (when (memq (org-element-type drawer) '(drawer property-drawer))
7230 (let ((post (org-element-property :post-affiliated drawer)))
7231 (save-excursion
7232 (outline-flag-region
7233 (progn (goto-char post) (line-end-position))
7234 (progn (goto-char (org-element-property :end drawer))
7235 (skip-chars-backward " \r\t\n")
7236 (line-end-position))
7237 flag))
7238 ;; When the drawer is hidden away, make sure point lies in
7239 ;; a visible part of the buffer.
7240 (when (and flag (> (line-beginning-position) post))
7241 (goto-char post)))))))
7243 (defun org-subtree-end-visible-p ()
7244 "Is the end of the current subtree visible?"
7245 (pos-visible-in-window-p
7246 (save-excursion (org-end-of-subtree t) (point))))
7248 (defun org-first-headline-recenter (&optional N)
7249 "Move cursor to the first headline and recenter the headline.
7250 Optional argument N means put the headline into the Nth line of the window."
7251 (goto-char (point-min))
7252 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7253 (beginning-of-line)
7254 (recenter (prefix-numeric-value N))))
7256 ;;; Saving and restoring visibility
7258 (defun org-outline-overlay-data (&optional use-markers)
7259 "Return a list of the locations of all outline overlays.
7260 These are overlays with the `invisible' property value `outline'.
7261 The return value is a list of cons cells, with start and stop
7262 positions for each overlay.
7263 If USE-MARKERS is set, return the positions as markers."
7264 (let (beg end)
7265 (save-excursion
7266 (save-restriction
7267 (widen)
7268 (delq nil
7269 (mapcar (lambda (o)
7270 (when (eq (overlay-get o 'invisible) 'outline)
7271 (setq beg (overlay-start o)
7272 end (overlay-end o))
7273 (and beg end (> end beg)
7274 (if use-markers
7275 (cons (copy-marker beg)
7276 (copy-marker end t))
7277 (cons beg end)))))
7278 (overlays-in (point-min) (point-max))))))))
7280 (defun org-set-outline-overlay-data (data)
7281 "Create visibility overlays for all positions in DATA.
7282 DATA should have been made by `org-outline-overlay-data'."
7283 (let (o)
7284 (save-excursion
7285 (save-restriction
7286 (widen)
7287 (show-all)
7288 (mapc (lambda (c)
7289 (outline-flag-region (car c) (cdr c) t))
7290 data)))))
7292 ;;; Folding of blocks
7294 (defvar org-hide-block-overlays nil
7295 "Overlays hiding blocks.")
7296 (make-variable-buffer-local 'org-hide-block-overlays)
7298 (defun org-block-map (function &optional start end)
7299 "Call FUNCTION at the head of all source blocks in the current buffer.
7300 Optional arguments START and END can be used to limit the range."
7301 (let ((start (or start (point-min)))
7302 (end (or end (point-max))))
7303 (save-excursion
7304 (goto-char start)
7305 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7306 (save-excursion
7307 (save-match-data
7308 (goto-char (match-beginning 0))
7309 (funcall function)))))))
7311 (defun org-hide-block-toggle-all ()
7312 "Toggle the visibility of all blocks in the current buffer."
7313 (org-block-map 'org-hide-block-toggle))
7315 (defun org-hide-block-all ()
7316 "Fold all blocks in the current buffer."
7317 (interactive)
7318 (org-show-block-all)
7319 (org-block-map 'org-hide-block-toggle-maybe))
7321 (defun org-show-block-all ()
7322 "Unfold all blocks in the current buffer."
7323 (interactive)
7324 (mapc 'delete-overlay org-hide-block-overlays)
7325 (setq org-hide-block-overlays nil))
7327 (defun org-hide-block-toggle-maybe ()
7328 "Toggle visibility of block at point."
7329 (interactive)
7330 (let ((case-fold-search t))
7331 (if (save-excursion
7332 (beginning-of-line 1)
7333 (looking-at org-block-regexp))
7334 (progn (org-hide-block-toggle)
7335 t) ;; to signal that we took action
7336 nil))) ;; to signal that we did not
7338 (defun org-hide-block-toggle (&optional force)
7339 "Toggle the visibility of the current block."
7340 (interactive)
7341 (save-excursion
7342 (beginning-of-line)
7343 (if (re-search-forward org-block-regexp nil t)
7344 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7345 (end (match-end 0)) ;; end of entire body
7347 (if (memq t (mapcar (lambda (overlay)
7348 (eq (overlay-get overlay 'invisible)
7349 'org-hide-block))
7350 (overlays-at start)))
7351 (if (or (not force) (eq force 'off))
7352 (mapc (lambda (ov)
7353 (when (member ov org-hide-block-overlays)
7354 (setq org-hide-block-overlays
7355 (delq ov org-hide-block-overlays)))
7356 (when (eq (overlay-get ov 'invisible)
7357 'org-hide-block)
7358 (delete-overlay ov)))
7359 (overlays-at start)))
7360 (setq ov (make-overlay start end))
7361 (overlay-put ov 'invisible 'org-hide-block)
7362 ;; make the block accessible to isearch
7363 (overlay-put
7364 ov 'isearch-open-invisible
7365 (lambda (ov)
7366 (when (member ov org-hide-block-overlays)
7367 (setq org-hide-block-overlays
7368 (delq ov org-hide-block-overlays)))
7369 (when (eq (overlay-get ov 'invisible)
7370 'org-hide-block)
7371 (delete-overlay ov))))
7372 (push ov org-hide-block-overlays)))
7373 (user-error "Not looking at a source block"))))
7375 ;; org-tab-after-check-for-cycling-hook
7376 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7377 ;; Remove overlays when changing major mode
7378 (add-hook 'org-mode-hook
7379 (lambda () (org-add-hook 'change-major-mode-hook
7380 'org-show-block-all 'append 'local)))
7382 ;;; Org-goto
7384 (defvar org-goto-window-configuration nil)
7385 (defvar org-goto-marker nil)
7386 (defvar org-goto-map)
7387 (defun org-goto-map ()
7388 "Set the keymap `org-goto'."
7389 (setq org-goto-map
7390 (let ((map (make-sparse-keymap)))
7391 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7392 mouse-drag-region universal-argument org-occur))
7393 cmd)
7394 (while (setq cmd (pop cmds))
7395 (substitute-key-definition cmd cmd map global-map)))
7396 (suppress-keymap map)
7397 (org-defkey map "\C-m" 'org-goto-ret)
7398 (org-defkey map [(return)] 'org-goto-ret)
7399 (org-defkey map [(left)] 'org-goto-left)
7400 (org-defkey map [(right)] 'org-goto-right)
7401 (org-defkey map [(control ?g)] 'org-goto-quit)
7402 (org-defkey map "\C-i" 'org-cycle)
7403 (org-defkey map [(tab)] 'org-cycle)
7404 (org-defkey map [(down)] 'outline-next-visible-heading)
7405 (org-defkey map [(up)] 'outline-previous-visible-heading)
7406 (if org-goto-auto-isearch
7407 (if (fboundp 'define-key-after)
7408 (define-key-after map [t] 'org-goto-local-auto-isearch)
7409 nil)
7410 (org-defkey map "q" 'org-goto-quit)
7411 (org-defkey map "n" 'outline-next-visible-heading)
7412 (org-defkey map "p" 'outline-previous-visible-heading)
7413 (org-defkey map "f" 'outline-forward-same-level)
7414 (org-defkey map "b" 'outline-backward-same-level)
7415 (org-defkey map "u" 'outline-up-heading))
7416 (org-defkey map "/" 'org-occur)
7417 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7418 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7419 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7420 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7421 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7422 map)))
7424 (defconst org-goto-help
7425 "Browse buffer copy, to find location or copy text.%s
7426 RET=jump to location C-g=quit and return to previous location
7427 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7429 (defvar org-goto-start-pos) ; dynamically scoped parameter
7431 (defun org-goto (&optional alternative-interface)
7432 "Look up a different location in the current file, keeping current visibility.
7434 When you want look-up or go to a different location in a
7435 document, the fastest way is often to fold the entire buffer and
7436 then dive into the tree. This method has the disadvantage, that
7437 the previous location will be folded, which may not be what you
7438 want.
7440 This command works around this by showing a copy of the current
7441 buffer in an indirect buffer, in overview mode. You can dive
7442 into the tree in that copy, use org-occur and incremental search
7443 to find a location. When pressing RET or `Q', the command
7444 returns to the original buffer in which the visibility is still
7445 unchanged. After RET it will also jump to the location selected
7446 in the indirect buffer and expose the headline hierarchy above.
7448 With a prefix argument, use the alternative interface: e.g. if
7449 `org-goto-interface' is 'outline use 'outline-path-completion."
7450 (interactive "P")
7451 (org-goto-map)
7452 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7453 (org-refile-use-outline-path t)
7454 (org-refile-target-verify-function nil)
7455 (interface
7456 (if (not alternative-interface)
7457 org-goto-interface
7458 (if (eq org-goto-interface 'outline)
7459 'outline-path-completion
7460 'outline)))
7461 (org-goto-start-pos (point))
7462 (selected-point
7463 (if (eq interface 'outline)
7464 (car (org-get-location (current-buffer) org-goto-help))
7465 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7466 (org-refile-check-position pa)
7467 (nth 3 pa)))))
7468 (if selected-point
7469 (progn
7470 (org-mark-ring-push org-goto-start-pos)
7471 (goto-char selected-point)
7472 (if (or (outline-invisible-p) (org-invisible-p2))
7473 (org-show-context 'org-goto)))
7474 (message "Quit"))))
7476 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7477 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7478 (defvar org-goto-local-auto-isearch-map) ; defined below
7480 (defun org-get-location (buf help)
7481 "Let the user select a location in the Org-mode buffer BUF.
7482 This function uses a recursive edit. It returns the selected position
7483 or nil."
7484 (org-no-popups
7485 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7486 (isearch-hide-immediately nil)
7487 (isearch-search-fun-function
7488 (lambda () 'org-goto-local-search-headings))
7489 (org-goto-selected-point org-goto-exit-command))
7490 (save-excursion
7491 (save-window-excursion
7492 (delete-other-windows)
7493 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7494 (org-pop-to-buffer-same-window
7495 (condition-case nil
7496 (make-indirect-buffer (current-buffer) "*org-goto*")
7497 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7498 (with-output-to-temp-buffer "*Org Help*"
7499 (princ (format help (if org-goto-auto-isearch
7500 " Just type for auto-isearch."
7501 " n/p/f/b/u to navigate, q to quit."))))
7502 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7503 (setq buffer-read-only nil)
7504 (let ((org-startup-truncated t)
7505 (org-startup-folded nil)
7506 (org-startup-align-all-tables nil))
7507 (org-mode)
7508 (org-overview))
7509 (setq buffer-read-only t)
7510 (if (and (boundp 'org-goto-start-pos)
7511 (integer-or-marker-p org-goto-start-pos))
7512 (let ((org-show-hierarchy-above t)
7513 (org-show-siblings t)
7514 (org-show-following-heading t))
7515 (goto-char org-goto-start-pos)
7516 (and (outline-invisible-p) (org-show-context)))
7517 (goto-char (point-min)))
7518 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7519 (message "Select location and press RET")
7520 (use-local-map org-goto-map)
7521 (recursive-edit)))
7522 (kill-buffer "*org-goto*")
7523 (cons org-goto-selected-point org-goto-exit-command))))
7525 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7526 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7527 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7528 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7530 (defun org-goto-local-search-headings (string bound noerror)
7531 "Search and make sure that any matches are in headlines."
7532 (catch 'return
7533 (while (if isearch-forward
7534 (search-forward string bound noerror)
7535 (search-backward string bound noerror))
7536 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7537 (and (member :headline context)
7538 (not (member :tags context))))
7539 (throw 'return (point))))))
7541 (defun org-goto-local-auto-isearch ()
7542 "Start isearch."
7543 (interactive)
7544 (goto-char (point-min))
7545 (let ((keys (this-command-keys)))
7546 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7547 (isearch-mode t)
7548 (isearch-process-search-char (string-to-char keys)))))
7550 (defun org-goto-ret (&optional arg)
7551 "Finish `org-goto' by going to the new location."
7552 (interactive "P")
7553 (setq org-goto-selected-point (point)
7554 org-goto-exit-command 'return)
7555 (throw 'exit nil))
7557 (defun org-goto-left ()
7558 "Finish `org-goto' by going to the new location."
7559 (interactive)
7560 (if (org-at-heading-p)
7561 (progn
7562 (beginning-of-line 1)
7563 (setq org-goto-selected-point (point)
7564 org-goto-exit-command 'left)
7565 (throw 'exit nil))
7566 (user-error "Not on a heading")))
7568 (defun org-goto-right ()
7569 "Finish `org-goto' by going to the new location."
7570 (interactive)
7571 (if (org-at-heading-p)
7572 (progn
7573 (setq org-goto-selected-point (point)
7574 org-goto-exit-command 'right)
7575 (throw 'exit nil))
7576 (user-error "Not on a heading")))
7578 (defun org-goto-quit ()
7579 "Finish `org-goto' without cursor motion."
7580 (interactive)
7581 (setq org-goto-selected-point nil)
7582 (setq org-goto-exit-command 'quit)
7583 (throw 'exit nil))
7585 ;;; Indirect buffer display of subtrees
7587 (defvar org-indirect-dedicated-frame nil
7588 "This is the frame being used for indirect tree display.")
7589 (defvar org-last-indirect-buffer nil)
7591 (defun org-tree-to-indirect-buffer (&optional arg)
7592 "Create indirect buffer and narrow it to current subtree.
7593 With a numerical prefix ARG, go up to this level and then take that tree.
7594 If ARG is negative, go up that many levels.
7596 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7597 indirect buffer previously made with this command, to avoid proliferation of
7598 indirect buffers. However, when you call the command with a \
7599 \\[universal-argument] prefix, or
7600 when `org-indirect-buffer-display' is `new-frame', the last buffer
7601 is kept so that you can work with several indirect buffers at the same time.
7602 If `org-indirect-buffer-display' is `dedicated-frame', the \
7603 \\[universal-argument] prefix also
7604 requests that a new frame be made for the new buffer, so that the dedicated
7605 frame is not changed."
7606 (interactive "P")
7607 (let ((cbuf (current-buffer))
7608 (cwin (selected-window))
7609 (pos (point))
7610 beg end level heading ibuf)
7611 (save-excursion
7612 (org-back-to-heading t)
7613 (when (numberp arg)
7614 (setq level (org-outline-level))
7615 (if (< arg 0) (setq arg (+ level arg)))
7616 (while (> (setq level (org-outline-level)) arg)
7617 (org-up-heading-safe)))
7618 (setq beg (point)
7619 heading (org-get-heading))
7620 (org-end-of-subtree t t)
7621 (if (org-at-heading-p) (backward-char 1))
7622 (setq end (point)))
7623 (if (and (buffer-live-p org-last-indirect-buffer)
7624 (not (eq org-indirect-buffer-display 'new-frame))
7625 (not arg))
7626 (kill-buffer org-last-indirect-buffer))
7627 (setq ibuf (org-get-indirect-buffer cbuf heading)
7628 org-last-indirect-buffer ibuf)
7629 (cond
7630 ((or (eq org-indirect-buffer-display 'new-frame)
7631 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7632 (select-frame (make-frame))
7633 (delete-other-windows)
7634 (org-pop-to-buffer-same-window ibuf)
7635 (org-set-frame-title heading))
7636 ((eq org-indirect-buffer-display 'dedicated-frame)
7637 (raise-frame
7638 (select-frame (or (and org-indirect-dedicated-frame
7639 (frame-live-p org-indirect-dedicated-frame)
7640 org-indirect-dedicated-frame)
7641 (setq org-indirect-dedicated-frame (make-frame)))))
7642 (delete-other-windows)
7643 (org-pop-to-buffer-same-window ibuf)
7644 (org-set-frame-title (concat "Indirect: " heading)))
7645 ((eq org-indirect-buffer-display 'current-window)
7646 (org-pop-to-buffer-same-window ibuf))
7647 ((eq org-indirect-buffer-display 'other-window)
7648 (pop-to-buffer ibuf))
7649 (t (error "Invalid value")))
7650 (if (featurep 'xemacs)
7651 (save-excursion (org-mode) (turn-on-font-lock)))
7652 (narrow-to-region beg end)
7653 (show-all)
7654 (goto-char pos)
7655 (run-hook-with-args 'org-cycle-hook 'all)
7656 (and (window-live-p cwin) (select-window cwin))))
7658 (defun org-get-indirect-buffer (&optional buffer heading)
7659 (setq buffer (or buffer (current-buffer)))
7660 (let ((n 1) (base (buffer-name buffer)) bname)
7661 (while (buffer-live-p
7662 (get-buffer
7663 (setq bname
7664 (concat base "-"
7665 (if heading (concat heading "-" (number-to-string n))
7666 (number-to-string n))))))
7667 (setq n (1+ n)))
7668 (condition-case nil
7669 (make-indirect-buffer buffer bname 'clone)
7670 (error (make-indirect-buffer buffer bname)))))
7672 (defun org-set-frame-title (title)
7673 "Set the title of the current frame to the string TITLE."
7674 ;; FIXME: how to name a single frame in XEmacs???
7675 (unless (featurep 'xemacs)
7676 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7678 ;;;; Structure editing
7680 ;;; Inserting headlines
7682 (defun org-previous-line-empty-p (&optional next)
7683 "Is the previous line a blank line?
7684 When NEXT is non-nil, check the next line instead."
7685 (save-excursion
7686 (and (not (bobp))
7687 (or (beginning-of-line (if next 2 0)) t)
7688 (save-match-data
7689 (looking-at "[ \t]*$")))))
7691 (defun org-insert-heading (&optional arg invisible-ok)
7692 "Insert a new heading or an item with the same depth at point.
7694 If point is at the beginning of a heading or a list item, insert
7695 a new heading or a new item above the current one. If point is
7696 at the beginning of a normal line, turn the line into a heading.
7698 If point is in the middle of a headline or a list item, split the
7699 headline or the item and create a new headline/item with the text
7700 in the current line after point \(see `org-M-RET-may-split-line'
7701 on how to modify this behavior).
7703 With one universal prefirx argument, set the user option
7704 `org-insert-heading-respect-content' to t for the duration of
7705 the command. This modifies the behavior described above in this
7706 ways: on list items and at the beginning of normal lines, force
7707 the insertion of a heading after the current subtree.
7709 With two universal prefix arguments, insert the heading at the
7710 end of the grandparent subtree. For example, if point is within
7711 a 2nd-level heading, then it will insert a 2nd-level heading at
7712 the end of the 1st-level parent heading.
7714 If point is at the beginning of a headline, insert a sibling
7715 before the current headline. If point is not at the beginning,
7716 split the line and create a new headline with the text in the
7717 current line after point \(see `org-M-RET-may-split-line' on how
7718 to modify this behavior).
7720 If point is at the beginning of a normal line, turn this line
7721 into a heading.
7723 When INVISIBLE-OK is set, stop at invisible headlines when going
7724 back. This is important for non-interactive uses of the
7725 command."
7726 (interactive "P")
7727 (if (org-called-interactively-p 'any) (org-reveal))
7728 (let ((itemp (org-in-item-p))
7729 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7730 (respect-content (or org-insert-heading-respect-content
7731 (equal arg '(4))))
7732 (initial-content "")
7733 (adjust-empty-lines t))
7735 (cond
7737 ((or (= (buffer-size) 0)
7738 (and (not (save-excursion
7739 (and (ignore-errors (org-back-to-heading invisible-ok))
7740 (org-at-heading-p))))
7741 (or arg (not itemp))))
7742 ;; At beginning of buffer or so high up that only a heading
7743 ;; makes sense.
7744 (cond ((and (bolp) (not respect-content)) (insert "* "))
7745 ((not respect-content)
7746 (unless may-split (end-of-line))
7747 (insert "\n* "))
7748 ((re-search-forward org-outline-regexp-bol nil t)
7749 (beginning-of-line)
7750 (insert "* \n")
7751 (backward-char))
7752 (t (goto-char (point-max))
7753 (insert "\n* ")))
7754 (run-hooks 'org-insert-heading-hook))
7756 ((and itemp (not (member arg '((4) (16)))))
7757 ;; Insert an item
7758 (org-insert-item))
7761 ;; Maybe move at the end of the subtree
7762 (when (equal arg '(16))
7763 (org-up-heading-safe)
7764 (org-end-of-subtree t))
7765 ;; Insert a heading
7766 (save-restriction
7767 (widen)
7768 (let* ((level nil)
7769 (on-heading (org-at-heading-p))
7770 (empty-line-p (if on-heading
7771 (org-previous-line-empty-p)
7772 ;; We will decide later
7773 nil))
7774 ;; Get a level string to fall back on
7775 (fix-level
7776 (if (org-before-first-heading-p) "*"
7777 (save-excursion
7778 (org-back-to-heading t)
7779 (if (org-previous-line-empty-p) (setq empty-line-p t))
7780 (looking-at org-outline-regexp)
7781 (make-string (1- (length (match-string 0))) ?*))))
7782 (stars
7783 (save-excursion
7784 (condition-case nil
7785 (progn
7786 (org-back-to-heading invisible-ok)
7787 (when (and (not on-heading)
7788 (featurep 'org-inlinetask)
7789 (integerp org-inlinetask-min-level)
7790 (>= (length (match-string 0))
7791 org-inlinetask-min-level))
7792 ;; Find a heading level before the inline task
7793 (while (and (setq level (org-up-heading-safe))
7794 (>= level org-inlinetask-min-level)))
7795 (if (org-at-heading-p)
7796 (org-back-to-heading invisible-ok)
7797 (error "This should not happen")))
7798 (unless (and (save-excursion
7799 (save-match-data
7800 (org-backward-heading-same-level
7801 1 invisible-ok))
7802 (= (point) (match-beginning 0)))
7803 (not (org-previous-line-empty-p t)))
7804 (setq empty-line-p (or empty-line-p
7805 (org-previous-line-empty-p))))
7806 (match-string 0))
7807 (error (or fix-level "* ")))))
7808 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7809 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7810 pos hide-previous previous-pos)
7812 ;; If we insert after content, move there and clean up whitespace
7813 (when (and respect-content
7814 (not (org-looking-at-p org-outline-regexp-bol)))
7815 (if (not (org-before-first-heading-p))
7816 (org-end-of-subtree nil t)
7817 (re-search-forward org-outline-regexp-bol)
7818 (beginning-of-line 0))
7819 (skip-chars-backward " \r\n")
7820 (and (not (looking-back "^\\*+"))
7821 (looking-at "[ \t]+") (replace-match ""))
7822 (unless (eobp) (forward-char 1))
7823 (when (looking-at "^\\*")
7824 (unless (bobp) (backward-char 1))
7825 (insert "\n")))
7827 ;; If we are splitting, grab the text that should be moved to the new headline
7828 (when may-split
7829 (if (org-on-heading-p)
7830 ;; This is a heading, we split intelligently (keeping tags)
7831 (let ((pos (point)))
7832 (goto-char (point-at-bol))
7833 (unless (looking-at org-complex-heading-regexp)
7834 (error "This should not happen"))
7835 (when (and (match-beginning 4)
7836 (> pos (match-beginning 4))
7837 (< pos (match-end 4)))
7838 (setq initial-content (buffer-substring pos (match-end 4)))
7839 (goto-char pos)
7840 (delete-region (point) (match-end 4))
7841 (if (looking-at "[ \t]*$")
7842 (replace-match "")
7843 (insert (make-string (length initial-content) ?\ )))
7844 (setq initial-content (org-trim initial-content)))
7845 (goto-char pos))
7846 ;; a normal line
7847 (setq initial-content
7848 (org-trim (buffer-substring (point) (point-at-eol))))
7849 (delete-region (point) (point-at-eol))))
7851 ;; If we are at the beginning of the line, insert before it. Else after
7852 (cond
7853 ((and (bolp) (looking-at "[ \t]*$")))
7854 ((and (bolp) (not (looking-at "[ \t]*$")))
7855 (open-line 1))
7857 (goto-char (point-at-eol))
7858 (insert "\n")))
7860 ;; Insert the new heading
7861 (insert stars)
7862 (just-one-space)
7863 (insert initial-content)
7864 (when adjust-empty-lines
7865 (if (or (not blank)
7866 (and blank (not (org-previous-line-empty-p))))
7867 (org-N-empty-lines-before-current (if blank 1 0))))
7868 (run-hooks 'org-insert-heading-hook)))))))
7870 (defun org-N-empty-lines-before-current (N)
7871 "Make the number of empty lines before current exactly N.
7872 So this will delete or add empty lines."
7873 (save-excursion
7874 (goto-char (point-at-bol))
7875 (if (looking-back "\\s-+" nil 'greedy)
7876 (replace-match ""))
7877 (or (bobp) (insert "\n"))
7878 (while (> N 0)
7879 (insert "\n")
7880 (setq N (1- N)))))
7882 (defun org-get-heading (&optional no-tags no-todo)
7883 "Return the heading of the current entry, without the stars.
7884 When NO-TAGS is non-nil, don't include tags.
7885 When NO-TODO is non-nil, don't include TODO keywords."
7886 (save-excursion
7887 (org-back-to-heading t)
7888 (cond
7889 ((and no-tags no-todo)
7890 (looking-at org-complex-heading-regexp)
7891 (match-string 4))
7892 (no-tags
7893 (looking-at (concat org-outline-regexp
7894 "\\(.*?\\)"
7895 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7896 (match-string 1))
7897 (no-todo
7898 (looking-at org-todo-line-regexp)
7899 (match-string 3))
7900 (t (looking-at org-heading-regexp)
7901 (match-string 2)))))
7903 (defvar orgstruct-mode) ; defined below
7905 (defun org-heading-components ()
7906 "Return the components of the current heading.
7907 This is a list with the following elements:
7908 - the level as an integer
7909 - the reduced level, different if `org-odd-levels-only' is set.
7910 - the TODO keyword, or nil
7911 - the priority character, like ?A, or nil if no priority is given
7912 - the headline text itself, or the tags string if no headline text
7913 - the tags string, or nil."
7914 (save-excursion
7915 (org-back-to-heading t)
7916 (if (let (case-fold-search)
7917 (looking-at
7918 (if orgstruct-mode
7919 org-heading-regexp
7920 org-complex-heading-regexp)))
7921 (if orgstruct-mode
7922 (list (length (match-string 1))
7923 (org-reduced-level (length (match-string 1)))
7926 (match-string 2)
7927 nil)
7928 (list (length (match-string 1))
7929 (org-reduced-level (length (match-string 1)))
7930 (org-match-string-no-properties 2)
7931 (and (match-end 3) (aref (match-string 3) 2))
7932 (org-match-string-no-properties 4)
7933 (org-match-string-no-properties 5))))))
7935 (defun org-get-entry ()
7936 "Get the entry text, after heading, entire subtree."
7937 (save-excursion
7938 (org-back-to-heading t)
7939 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7941 (defun org-insert-heading-after-current ()
7942 "Insert a new heading with same level as current, after current subtree."
7943 (interactive)
7944 (org-back-to-heading)
7945 (org-insert-heading)
7946 (org-move-subtree-down)
7947 (end-of-line 1))
7949 (defun org-insert-heading-respect-content (&optional invisible-ok)
7950 "Insert heading with `org-insert-heading-respect-content' set to t."
7951 (interactive)
7952 (org-insert-heading '(4) invisible-ok))
7954 (defun org-insert-todo-heading-respect-content (&optional force-state)
7955 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7956 (interactive)
7957 (org-insert-todo-heading force-state '(4)))
7959 (defun org-insert-todo-heading (arg &optional force-heading)
7960 "Insert a new heading with the same level and TODO state as current heading.
7961 If the heading has no TODO state, or if the state is DONE, use the first
7962 state (TODO by default). Also with one prefix arg, force first state. With
7963 two prefix args, force inserting at the end of the parent subtree."
7964 (interactive "P")
7965 (when (or force-heading (not (org-insert-item 'checkbox)))
7966 (org-insert-heading (or (and (equal arg '(16)) '(16))
7967 force-heading))
7968 (save-excursion
7969 (org-back-to-heading)
7970 (outline-previous-heading)
7971 (looking-at org-todo-line-regexp))
7972 (let*
7973 ((new-mark-x
7974 (if (or (equal arg '(4))
7975 (not (match-beginning 2))
7976 (member (match-string 2) org-done-keywords))
7977 (car org-todo-keywords-1)
7978 (match-string 2)))
7979 (new-mark
7981 (run-hook-with-args-until-success
7982 'org-todo-get-default-hook new-mark-x nil)
7983 new-mark-x)))
7984 (beginning-of-line 1)
7985 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7986 (if org-treat-insert-todo-heading-as-state-change
7987 (org-todo new-mark)
7988 (insert new-mark " "))))
7989 (when org-provide-todo-statistics
7990 (org-update-parent-todo-statistics))))
7992 (defun org-insert-subheading (arg)
7993 "Insert a new subheading and demote it.
7994 Works for outline headings and for plain lists alike."
7995 (interactive "P")
7996 (org-insert-heading arg)
7997 (cond
7998 ((org-at-heading-p) (org-do-demote))
7999 ((org-at-item-p) (org-indent-item))))
8001 (defun org-insert-todo-subheading (arg)
8002 "Insert a new subheading with TODO keyword or checkbox and demote it.
8003 Works for outline headings and for plain lists alike."
8004 (interactive "P")
8005 (org-insert-todo-heading arg)
8006 (cond
8007 ((org-at-heading-p) (org-do-demote))
8008 ((org-at-item-p) (org-indent-item))))
8010 ;;; Promotion and Demotion
8012 (defvar org-after-demote-entry-hook nil
8013 "Hook run after an entry has been demoted.
8014 The cursor will be at the beginning of the entry.
8015 When a subtree is being demoted, the hook will be called for each node.")
8017 (defvar org-after-promote-entry-hook nil
8018 "Hook run after an entry has been promoted.
8019 The cursor will be at the beginning of the entry.
8020 When a subtree is being promoted, the hook will be called for each node.")
8022 (defun org-promote-subtree ()
8023 "Promote the entire subtree.
8024 See also `org-promote'."
8025 (interactive)
8026 (save-excursion
8027 (org-with-limited-levels (org-map-tree 'org-promote)))
8028 (org-fix-position-after-promote))
8030 (defun org-demote-subtree ()
8031 "Demote the entire subtree. See `org-demote'.
8032 See also `org-promote'."
8033 (interactive)
8034 (save-excursion
8035 (org-with-limited-levels (org-map-tree 'org-demote)))
8036 (org-fix-position-after-promote))
8039 (defun org-do-promote ()
8040 "Promote the current heading higher up the tree.
8041 If the region is active in `transient-mark-mode', promote all headings
8042 in the region."
8043 (interactive)
8044 (save-excursion
8045 (if (org-region-active-p)
8046 (org-map-region 'org-promote (region-beginning) (region-end))
8047 (org-promote)))
8048 (org-fix-position-after-promote))
8050 (defun org-do-demote ()
8051 "Demote the current heading lower down the tree.
8052 If the region is active in `transient-mark-mode', demote all headings
8053 in the region."
8054 (interactive)
8055 (save-excursion
8056 (if (org-region-active-p)
8057 (org-map-region 'org-demote (region-beginning) (region-end))
8058 (org-demote)))
8059 (org-fix-position-after-promote))
8061 (defun org-fix-position-after-promote ()
8062 "Make sure that after pro/demotion cursor position is right."
8063 (let ((pos (point)))
8064 (when (save-excursion
8065 (beginning-of-line 1)
8066 (looking-at org-todo-line-regexp)
8067 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8068 (cond ((eobp) (insert " "))
8069 ((eolp) (insert " "))
8070 ((equal (char-after) ?\ ) (forward-char 1))))))
8072 (defun org-current-level ()
8073 "Return the level of the current entry, or nil if before the first headline.
8074 The level is the number of stars at the beginning of the headline."
8075 (save-excursion
8076 (org-with-limited-levels
8077 (if (ignore-errors (org-back-to-heading t))
8078 (funcall outline-level)))))
8080 (defun org-get-previous-line-level ()
8081 "Return the outline depth of the last headline before the current line.
8082 Returns 0 for the first headline in the buffer, and nil if before the
8083 first headline."
8084 (and (org-current-level)
8085 (or (and (/= (line-beginning-position) (point-min))
8086 (save-excursion (beginning-of-line 0) (org-current-level)))
8087 0)))
8089 (defun org-reduced-level (l)
8090 "Compute the effective level of a heading.
8091 This takes into account the setting of `org-odd-levels-only'."
8092 (cond
8093 ((zerop l) 0)
8094 (org-odd-levels-only (1+ (floor (/ l 2))))
8095 (t l)))
8097 (defun org-level-increment ()
8098 "Return the number of stars that will be added or removed at a
8099 time to headlines when structure editing, based on the value of
8100 `org-odd-levels-only'."
8101 (if org-odd-levels-only 2 1))
8103 (defun org-get-valid-level (level &optional change)
8104 "Rectify a level change under the influence of `org-odd-levels-only'
8105 LEVEL is a current level, CHANGE is by how much the level should be
8106 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8107 even level numbers will become the next higher odd number."
8108 (if org-odd-levels-only
8109 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8110 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8111 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8112 (max 1 (+ level (or change 0)))))
8114 (if (boundp 'define-obsolete-function-alias)
8115 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8116 (define-obsolete-function-alias 'org-get-legal-level
8117 'org-get-valid-level)
8118 (define-obsolete-function-alias 'org-get-legal-level
8119 'org-get-valid-level "23.1")))
8121 (defun org-promote ()
8122 "Promote the current heading higher up the tree.
8123 If the region is active in `transient-mark-mode', promote all headings
8124 in the region."
8125 (org-back-to-heading t)
8126 (let* ((level (save-match-data (funcall outline-level)))
8127 (after-change-functions (remove 'flyspell-after-change-function
8128 after-change-functions))
8129 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8130 (diff (abs (- level (length up-head) -1))))
8131 (cond ((and (= level 1) org-called-with-limited-levels
8132 org-allow-promoting-top-level-subtree)
8133 (replace-match "# " nil t))
8134 ((= level 1)
8135 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8136 (t (replace-match up-head nil t)))
8137 ;; Fixup tag positioning
8138 (unless (= level 1)
8139 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8140 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8141 (run-hooks 'org-after-promote-entry-hook)))
8143 (defun org-demote ()
8144 "Demote the current heading lower down the tree.
8145 If the region is active in `transient-mark-mode', demote all headings
8146 in the region."
8147 (org-back-to-heading t)
8148 (let* ((level (save-match-data (funcall outline-level)))
8149 (after-change-functions (remove 'flyspell-after-change-function
8150 after-change-functions))
8151 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8152 (diff (abs (- level (length down-head) -1))))
8153 (replace-match down-head nil t)
8154 ;; Fixup tag positioning
8155 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8156 (if org-adapt-indentation (org-fixup-indentation diff))
8157 (run-hooks 'org-after-demote-entry-hook)))
8159 (defun org-cycle-level ()
8160 "Cycle the level of an empty headline through possible states.
8161 This goes first to child, then to parent, level, then up the hierarchy.
8162 After top level, it switches back to sibling level."
8163 (interactive)
8164 (let ((org-adapt-indentation nil))
8165 (when (org-point-at-end-of-empty-headline)
8166 (setq this-command 'org-cycle-level) ; Only needed for caching
8167 (let ((cur-level (org-current-level))
8168 (prev-level (org-get-previous-line-level)))
8169 (cond
8170 ;; If first headline in file, promote to top-level.
8171 ((= prev-level 0)
8172 (loop repeat (/ (- cur-level 1) (org-level-increment))
8173 do (org-do-promote)))
8174 ;; If same level as prev, demote one.
8175 ((= prev-level cur-level)
8176 (org-do-demote))
8177 ;; If parent is top-level, promote to top level if not already.
8178 ((= prev-level 1)
8179 (loop repeat (/ (- cur-level 1) (org-level-increment))
8180 do (org-do-promote)))
8181 ;; If top-level, return to prev-level.
8182 ((= cur-level 1)
8183 (loop repeat (/ (- prev-level 1) (org-level-increment))
8184 do (org-do-demote)))
8185 ;; If less than prev-level, promote one.
8186 ((< cur-level prev-level)
8187 (org-do-promote))
8188 ;; If deeper than prev-level, promote until higher than
8189 ;; prev-level.
8190 ((> cur-level prev-level)
8191 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8192 do (org-do-promote))))
8193 t))))
8195 (defun org-map-tree (fun)
8196 "Call FUN for every heading underneath the current one."
8197 (org-back-to-heading)
8198 (let ((level (funcall outline-level)))
8199 (save-excursion
8200 (funcall fun)
8201 (while (and (progn
8202 (outline-next-heading)
8203 (> (funcall outline-level) level))
8204 (not (eobp)))
8205 (funcall fun)))))
8207 (defun org-map-region (fun beg end)
8208 "Call FUN for every heading between BEG and END."
8209 (let ((org-ignore-region t))
8210 (save-excursion
8211 (setq end (copy-marker end))
8212 (goto-char beg)
8213 (if (and (re-search-forward org-outline-regexp-bol nil t)
8214 (< (point) end))
8215 (funcall fun))
8216 (while (and (progn
8217 (outline-next-heading)
8218 (< (point) end))
8219 (not (eobp)))
8220 (funcall fun)))))
8222 (defvar org-property-end-re) ; silence byte-compiler
8223 (defun org-fixup-indentation (diff)
8224 "Change the indentation in the current entry by DIFF.
8225 However, if any line in the current entry has no indentation, or if it
8226 would end up with no indentation after the change, nothing at all is done."
8227 (save-excursion
8228 (let ((end (save-excursion (outline-next-heading)
8229 (point-marker)))
8230 (prohibit (if (> diff 0)
8231 "^\\S-"
8232 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8233 col)
8234 (unless (save-excursion (end-of-line 1)
8235 (re-search-forward prohibit end t))
8236 (while (and (< (point) end)
8237 (re-search-forward "^[ \t]+" end t))
8238 (goto-char (match-end 0))
8239 (setq col (current-column))
8240 (if (< diff 0) (replace-match ""))
8241 (org-indent-to-column (+ diff col))))
8242 (move-marker end nil))))
8244 (defun org-convert-to-odd-levels ()
8245 "Convert an org-mode file with all levels allowed to one with odd levels.
8246 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8247 level 5 etc."
8248 (interactive)
8249 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8250 (let ((outline-level 'org-outline-level)
8251 (org-odd-levels-only nil) n)
8252 (save-excursion
8253 (goto-char (point-min))
8254 (while (re-search-forward "^\\*\\*+ " nil t)
8255 (setq n (- (length (match-string 0)) 2))
8256 (while (>= (setq n (1- n)) 0)
8257 (org-demote))
8258 (end-of-line 1))))))
8260 (defun org-convert-to-oddeven-levels ()
8261 "Convert an org-mode file with only odd levels to one with odd/even levels.
8262 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8263 file contains a section with an even level, conversion would
8264 destroy the structure of the file. An error is signaled in this
8265 case."
8266 (interactive)
8267 (goto-char (point-min))
8268 ;; First check if there are no even levels
8269 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8270 (org-show-context t)
8271 (error "Not all levels are odd in this file. Conversion not possible"))
8272 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8273 (let ((outline-regexp org-outline-regexp)
8274 (outline-level 'org-outline-level)
8275 (org-odd-levels-only nil) n)
8276 (save-excursion
8277 (goto-char (point-min))
8278 (while (re-search-forward "^\\*\\*+ " nil t)
8279 (setq n (/ (1- (length (match-string 0))) 2))
8280 (while (>= (setq n (1- n)) 0)
8281 (org-promote))
8282 (end-of-line 1))))))
8284 (defun org-tr-level (n)
8285 "Make N odd if required."
8286 (if org-odd-levels-only (1+ (/ n 2)) n))
8288 ;;; Vertical tree motion, cutting and pasting of subtrees
8290 (defun org-move-subtree-up (&optional arg)
8291 "Move the current subtree up past ARG headlines of the same level."
8292 (interactive "p")
8293 (org-move-subtree-down (- (prefix-numeric-value arg))))
8295 (defun org-move-subtree-down (&optional arg)
8296 "Move the current subtree down past ARG headlines of the same level."
8297 (interactive "p")
8298 (setq arg (prefix-numeric-value arg))
8299 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8300 'org-get-last-sibling))
8301 (ins-point (make-marker))
8302 (cnt (abs arg))
8303 (col (current-column))
8304 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8305 ;; Select the tree
8306 (org-back-to-heading)
8307 (setq beg0 (point))
8308 (save-excursion
8309 (setq ne-beg (org-back-over-empty-lines))
8310 (setq beg (point)))
8311 (save-match-data
8312 (save-excursion (outline-end-of-heading)
8313 (setq folded (outline-invisible-p)))
8314 (progn (org-end-of-subtree nil t)
8315 (unless (eobp) (backward-char))))
8316 (outline-next-heading)
8317 (setq ne-end (org-back-over-empty-lines))
8318 (setq end (point))
8319 (goto-char beg0)
8320 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8321 ;; include less whitespace
8322 (save-excursion
8323 (goto-char beg)
8324 (forward-line (- ne-beg ne-end))
8325 (setq beg (point))))
8326 ;; Find insertion point, with error handling
8327 (while (> cnt 0)
8328 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8329 (progn (goto-char beg0)
8330 (user-error "Cannot move past superior level or buffer limit")))
8331 (setq cnt (1- cnt)))
8332 (if (> arg 0)
8333 ;; Moving forward - still need to move over subtree
8334 (progn (org-end-of-subtree t t)
8335 (save-excursion
8336 (org-back-over-empty-lines)
8337 (or (bolp) (newline)))))
8338 (setq ne-ins (org-back-over-empty-lines))
8339 (move-marker ins-point (point))
8340 (setq txt (buffer-substring beg end))
8341 (org-save-markers-in-region beg end)
8342 (delete-region beg end)
8343 (org-remove-empty-overlays-at beg)
8344 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8345 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8346 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8347 (let ((bbb (point)))
8348 (insert-before-markers txt)
8349 (org-reinstall-markers-in-region bbb)
8350 (move-marker ins-point bbb))
8351 (or (bolp) (insert "\n"))
8352 (setq ins-end (point))
8353 (goto-char ins-point)
8354 (org-skip-whitespace)
8355 (when (and (< arg 0)
8356 (org-first-sibling-p)
8357 (> ne-ins ne-beg))
8358 ;; Move whitespace back to beginning
8359 (save-excursion
8360 (goto-char ins-end)
8361 (let ((kill-whole-line t))
8362 (kill-line (- ne-ins ne-beg)) (point)))
8363 (insert (make-string (- ne-ins ne-beg) ?\n)))
8364 (move-marker ins-point nil)
8365 (if folded
8366 (hide-subtree)
8367 (org-show-entry)
8368 (show-children)
8369 (org-cycle-hide-drawers 'children))
8370 (org-clean-visibility-after-subtree-move)
8371 ;; move back to the initial column we were at
8372 (move-to-column col)))
8374 (defvar org-subtree-clip ""
8375 "Clipboard for cut and paste of subtrees.
8376 This is actually only a copy of the kill, because we use the normal kill
8377 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8379 (defvar org-subtree-clip-folded nil
8380 "Was the last copied subtree folded?
8381 This is used to fold the tree back after pasting.")
8383 (defun org-cut-subtree (&optional n)
8384 "Cut the current subtree into the clipboard.
8385 With prefix arg N, cut this many sequential subtrees.
8386 This is a short-hand for marking the subtree and then cutting it."
8387 (interactive "p")
8388 (org-copy-subtree n 'cut))
8390 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8391 "Copy the current subtree it in the clipboard.
8392 With prefix arg N, copy this many sequential subtrees.
8393 This is a short-hand for marking the subtree and then copying it.
8394 If CUT is non-nil, actually cut the subtree.
8395 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8396 of some markers in the region, even if CUT is non-nil. This is
8397 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8398 (interactive "p")
8399 (let (beg end folded (beg0 (point)))
8400 (if (org-called-interactively-p 'any)
8401 (org-back-to-heading nil) ; take what looks like a subtree
8402 (org-back-to-heading t)) ; take what is really there
8403 (setq beg (point))
8404 (skip-chars-forward " \t\r\n")
8405 (save-match-data
8406 (if nosubtrees
8407 (outline-next-heading)
8408 (save-excursion (outline-end-of-heading)
8409 (setq folded (outline-invisible-p)))
8410 (ignore-errors (org-forward-heading-same-level (1- n) t))
8411 (org-end-of-subtree t t)))
8412 (setq end (point))
8413 (goto-char beg0)
8414 (when (> end beg)
8415 (setq org-subtree-clip-folded folded)
8416 (when (or cut force-store-markers)
8417 (org-save-markers-in-region beg end))
8418 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8419 (setq org-subtree-clip (current-kill 0))
8420 (message "%s: Subtree(s) with %d characters"
8421 (if cut "Cut" "Copied")
8422 (length org-subtree-clip)))))
8424 (defun org-paste-subtree (&optional level tree for-yank)
8425 "Paste the clipboard as a subtree, with modification of headline level.
8426 The entire subtree is promoted or demoted in order to match a new headline
8427 level.
8429 If the cursor is at the beginning of a headline, the same level as
8430 that headline is used to paste the tree.
8432 If not, the new level is derived from the *visible* headings
8433 before and after the insertion point, and taken to be the inferior headline
8434 level of the two. So if the previous visible heading is level 3 and the
8435 next is level 4 (or vice versa), level 4 will be used for insertion.
8436 This makes sure that the subtree remains an independent subtree and does
8437 not swallow low level entries.
8439 You can also force a different level, either by using a numeric prefix
8440 argument, or by inserting the heading marker by hand. For example, if the
8441 cursor is after \"*****\", then the tree will be shifted to level 5.
8443 If optional TREE is given, use this text instead of the kill ring.
8445 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8446 move back over whitespace before inserting, and move point to the end of
8447 the inserted text when done."
8448 (interactive "P")
8449 (setq tree (or tree (and kill-ring (current-kill 0))))
8450 (unless (org-kill-is-subtree-p tree)
8451 (user-error "%s"
8452 (substitute-command-keys
8453 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8454 (org-with-limited-levels
8455 (let* ((visp (not (outline-invisible-p)))
8456 (txt tree)
8457 (^re_ "\\(\\*+\\)[ \t]*")
8458 (old-level (if (string-match org-outline-regexp-bol txt)
8459 (- (match-end 0) (match-beginning 0) 1)
8460 -1))
8461 (force-level (cond (level (prefix-numeric-value level))
8462 ((and (looking-at "[ \t]*$")
8463 (string-match
8464 "^\\*+$" (buffer-substring
8465 (point-at-bol) (point))))
8466 (- (match-end 1) (match-beginning 1)))
8467 ((and (bolp)
8468 (looking-at org-outline-regexp))
8469 (- (match-end 0) (point) 1))))
8470 (previous-level (save-excursion
8471 (condition-case nil
8472 (progn
8473 (outline-previous-visible-heading 1)
8474 (if (looking-at ^re_)
8475 (- (match-end 0) (match-beginning 0) 1)
8477 (error 1))))
8478 (next-level (save-excursion
8479 (condition-case nil
8480 (progn
8481 (or (looking-at org-outline-regexp)
8482 (outline-next-visible-heading 1))
8483 (if (looking-at ^re_)
8484 (- (match-end 0) (match-beginning 0) 1)
8486 (error 1))))
8487 (new-level (or force-level (max previous-level next-level)))
8488 (shift (if (or (= old-level -1)
8489 (= new-level -1)
8490 (= old-level new-level))
8492 (- new-level old-level)))
8493 (delta (if (> shift 0) -1 1))
8494 (func (if (> shift 0) 'org-demote 'org-promote))
8495 (org-odd-levels-only nil)
8496 beg end newend)
8497 ;; Remove the forced level indicator
8498 (if force-level
8499 (delete-region (point-at-bol) (point)))
8500 ;; Paste
8501 (beginning-of-line (if (bolp) 1 2))
8502 (setq beg (point))
8503 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8504 (insert-before-markers txt)
8505 (unless (string-match "\n\\'" txt) (insert "\n"))
8506 (setq newend (point))
8507 (org-reinstall-markers-in-region beg)
8508 (setq end (point))
8509 (goto-char beg)
8510 (skip-chars-forward " \t\n\r")
8511 (setq beg (point))
8512 (if (and (outline-invisible-p) visp)
8513 (save-excursion (outline-show-heading)))
8514 ;; Shift if necessary
8515 (unless (= shift 0)
8516 (save-restriction
8517 (narrow-to-region beg end)
8518 (while (not (= shift 0))
8519 (org-map-region func (point-min) (point-max))
8520 (setq shift (+ delta shift)))
8521 (goto-char (point-min))
8522 (setq newend (point-max))))
8523 (when (or (org-called-interactively-p 'interactive) for-yank)
8524 (message "Clipboard pasted as level %d subtree" new-level))
8525 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8526 kill-ring
8527 (eq org-subtree-clip (current-kill 0))
8528 org-subtree-clip-folded)
8529 ;; The tree was folded before it was killed/copied
8530 (hide-subtree))
8531 (and for-yank (goto-char newend)))))
8533 (defun org-kill-is-subtree-p (&optional txt)
8534 "Check if the current kill is an outline subtree, or a set of trees.
8535 Returns nil if kill does not start with a headline, or if the first
8536 headline level is not the largest headline level in the tree.
8537 So this will actually accept several entries of equal levels as well,
8538 which is OK for `org-paste-subtree'.
8539 If optional TXT is given, check this string instead of the current kill."
8540 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8541 (re (org-get-limited-outline-regexp))
8542 (^re (concat "^" re))
8543 (start-level (and kill
8544 (string-match
8545 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8546 kill)
8547 (- (match-end 2) (match-beginning 2) 1)))
8548 (start (1+ (or (match-beginning 2) -1))))
8549 (if (not start-level)
8550 (progn
8551 nil) ;; does not even start with a heading
8552 (catch 'exit
8553 (while (setq start (string-match ^re kill (1+ start)))
8554 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8555 (throw 'exit nil)))
8556 t))))
8558 (defvar org-markers-to-move nil
8559 "Markers that should be moved with a cut-and-paste operation.
8560 Those markers are stored together with their positions relative to
8561 the start of the region.")
8563 (defun org-save-markers-in-region (beg end)
8564 "Check markers in region.
8565 If these markers are between BEG and END, record their position relative
8566 to BEG, so that after moving the block of text, we can put the markers back
8567 into place.
8568 This function gets called just before an entry or tree gets cut from the
8569 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8570 called immediately, to move the markers with the entries."
8571 (setq org-markers-to-move nil)
8572 (when (featurep 'org-clock)
8573 (org-clock-save-markers-for-cut-and-paste beg end))
8574 (when (featurep 'org-agenda)
8575 (org-agenda-save-markers-for-cut-and-paste beg end)))
8577 (defun org-check-and-save-marker (marker beg end)
8578 "Check if MARKER is between BEG and END.
8579 If yes, remember the marker and the distance to BEG."
8580 (when (and (marker-buffer marker)
8581 (equal (marker-buffer marker) (current-buffer)))
8582 (if (and (>= marker beg) (< marker end))
8583 (push (cons marker (- marker beg)) org-markers-to-move))))
8585 (defun org-reinstall-markers-in-region (beg)
8586 "Move all remembered markers to their position relative to BEG."
8587 (mapc (lambda (x)
8588 (move-marker (car x) (+ beg (cdr x))))
8589 org-markers-to-move)
8590 (setq org-markers-to-move nil))
8592 (defun org-narrow-to-subtree ()
8593 "Narrow buffer to the current subtree."
8594 (interactive)
8595 (save-excursion
8596 (save-match-data
8597 (org-with-limited-levels
8598 (narrow-to-region
8599 (progn (org-back-to-heading t) (point))
8600 (progn (org-end-of-subtree t t)
8601 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8602 (point)))))))
8604 (defun org-narrow-to-block ()
8605 "Narrow buffer to the current block."
8606 (interactive)
8607 (let* ((case-fold-search t)
8608 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8609 "^[ \t]*#\\+end_.*")))
8610 (if blockp
8611 (narrow-to-region (car blockp) (cdr blockp))
8612 (user-error "Not in a block"))))
8614 (eval-when-compile
8615 (defvar org-property-drawer-re))
8617 (defvar org-property-start-re) ;; defined below
8618 (defun org-clone-subtree-with-time-shift (n &optional shift)
8619 "Clone the task (subtree) at point N times.
8620 The clones will be inserted as siblings.
8622 In interactive use, the user will be prompted for the number of
8623 clones to be produced. If the entry has a timestamp, the user
8624 will also be prompted for a time shift, which may be a repeater
8625 as used in time stamps, for example `+3d'. To disable this,
8626 you can call the function with a universal prefix argument.
8628 When a valid repeater is given and the entry contains any time
8629 stamps, the clones will become a sequence in time, with time
8630 stamps in the subtree shifted for each clone produced. If SHIFT
8631 is nil or the empty string, time stamps will be left alone. The
8632 ID property of the original subtree is removed.
8634 If the original subtree did contain time stamps with a repeater,
8635 the following will happen:
8636 - the repeater will be removed in each clone
8637 - an additional clone will be produced, with the current, unshifted
8638 date(s) in the entry.
8639 - the original entry will be placed *after* all the clones, with
8640 repeater intact.
8641 - the start days in the repeater in the original entry will be shifted
8642 to past the last clone.
8643 In this way you can spell out a number of instances of a repeating task,
8644 and still retain the repeater to cover future instances of the task."
8645 (interactive "nNumber of clones to produce: ")
8646 (let ((shift
8647 (or shift
8648 (if (and (not (equal current-prefix-arg '(4)))
8649 (save-excursion
8650 (re-search-forward org-ts-regexp-both
8651 (save-excursion
8652 (org-end-of-subtree t)
8653 (point)) t)))
8654 (read-from-minibuffer
8655 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8656 ""))) ;; No time shift
8657 (n-no-remove -1)
8658 (drawer-re org-drawer-regexp)
8659 beg end template task idprop
8660 shift-n shift-what doshift nmin nmax)
8661 (if (not (and (integerp n) (> n 0)))
8662 (user-error "Invalid number of replications %s" n))
8663 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8664 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8665 shift)))
8666 (user-error "Invalid shift specification %s" shift))
8667 (when doshift
8668 (setq shift-n (string-to-number (match-string 1 shift))
8669 shift-what (cdr (assoc (match-string 2 shift)
8670 '(("d" . day) ("w" . week)
8671 ("m" . month) ("y" . year))))))
8672 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8673 (setq nmin 1 nmax n)
8674 (org-back-to-heading t)
8675 (setq beg (point))
8676 (setq idprop (org-entry-get nil "ID"))
8677 (org-end-of-subtree t t)
8678 (or (bolp) (insert "\n"))
8679 (setq end (point))
8680 (setq template (buffer-substring beg end))
8681 (when (and doshift
8682 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8683 (delete-region beg end)
8684 (setq end beg)
8685 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8686 (goto-char end)
8687 (loop for n from nmin to nmax do
8688 ;; prepare clone
8689 (with-temp-buffer
8690 (insert template)
8691 (org-mode)
8692 (goto-char (point-min))
8693 (org-show-subtree)
8694 (and idprop (if org-clone-delete-id
8695 (org-entry-delete nil "ID")
8696 (org-id-get-create t)))
8697 (unless (= n 0)
8698 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8699 (kill-whole-line))
8700 (goto-char (point-min))
8701 (while (re-search-forward drawer-re nil t)
8702 (org-remove-empty-drawer-at (point))))
8703 (goto-char (point-min))
8704 (when doshift
8705 (while (re-search-forward org-ts-regexp-both nil t)
8706 (org-timestamp-change (* n shift-n) shift-what))
8707 (unless (= n n-no-remove)
8708 (goto-char (point-min))
8709 (while (re-search-forward org-ts-regexp nil t)
8710 (save-excursion
8711 (goto-char (match-beginning 0))
8712 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8713 (delete-region (match-beginning 1) (match-end 1)))))))
8714 (setq task (buffer-string)))
8715 (insert task))
8716 (goto-char beg)))
8718 ;;; Outline Sorting
8720 (defun org-sort (with-case)
8721 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8722 Optional argument WITH-CASE means sort case-sensitively."
8723 (interactive "P")
8724 (cond
8725 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8726 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8728 (org-call-with-arg 'org-sort-entries with-case))))
8730 (defun org-sort-remove-invisible (s)
8731 "Remove invisible links from string S."
8732 (remove-text-properties 0 (length s) org-rm-props s)
8733 (while (string-match org-bracket-link-regexp s)
8734 (setq s (replace-match (if (match-end 2)
8735 (match-string 3 s)
8736 (match-string 1 s)) t t s)))
8737 (let ((st (format " %s " s)))
8738 (while (string-match org-emph-re st)
8739 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8740 (setq s (substring st 1 -1)))
8743 (defvar org-priority-regexp) ; defined later in the file
8745 (defvar org-after-sorting-entries-or-items-hook nil
8746 "Hook that is run after a bunch of entries or items have been sorted.
8747 When children are sorted, the cursor is in the parent line when this
8748 hook gets called. When a region or a plain list is sorted, the cursor
8749 will be in the first entry of the sorted region/list.")
8751 (defun org-sort-entries
8752 (&optional with-case sorting-type getkey-func compare-func property)
8753 "Sort entries on a certain level of an outline tree.
8754 If there is an active region, the entries in the region are sorted.
8755 Else, if the cursor is before the first entry, sort the top-level items.
8756 Else, the children of the entry at point are sorted.
8758 Sorting can be alphabetically, numerically, by date/time as given by
8759 a time stamp, by a property, by priority order, or by a custom function.
8761 The command prompts for the sorting type unless it has been given to the
8762 function through the SORTING-TYPE argument, which needs to be a character,
8763 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8764 the precise meaning of each character:
8766 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8767 c By creation time, which is assumed to be the first inactive time stamp
8768 at the beginning of a line.
8769 d By deadline date/time.
8770 k By clocking time.
8771 n Numerically, by converting the beginning of the entry/item to a number.
8772 o By order of TODO keywords.
8773 p By priority according to the cookie.
8774 r By the value of a property.
8775 s By scheduled date/time.
8776 t By date/time, either the first active time stamp in the entry, or, if
8777 none exist, by the first inactive one.
8779 Capital letters will reverse the sort order.
8781 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8782 called with point at the beginning of the record. It must return either
8783 a string or a number that should serve as the sorting key for that record.
8785 Comparing entries ignores case by default. However, with an optional argument
8786 WITH-CASE, the sorting considers case as well.
8788 Sorting is done against the visible part of the headlines, it ignores hidden
8789 links.
8791 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8792 (interactive "P")
8793 (let ((case-func (if with-case 'identity 'downcase))
8794 (cmstr
8795 ;; The clock marker is lost when using `sort-subr', let's
8796 ;; store the clocking string.
8797 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8798 (save-excursion
8799 (goto-char org-clock-marker)
8800 (looking-back "^.*") (match-string-no-properties 0))))
8801 start beg end stars re re2
8802 txt what tmp)
8803 ;; Find beginning and end of region to sort
8804 (cond
8805 ((org-region-active-p)
8806 ;; we will sort the region
8807 (setq end (region-end)
8808 what "region")
8809 (goto-char (region-beginning))
8810 (if (not (org-at-heading-p)) (outline-next-heading))
8811 (setq start (point)))
8812 ((or (org-at-heading-p)
8813 (ignore-errors (progn (org-back-to-heading) t)))
8814 ;; we will sort the children of the current headline
8815 (org-back-to-heading)
8816 (setq start (point)
8817 end (progn (org-end-of-subtree t t)
8818 (or (bolp) (insert "\n"))
8819 (when (>= (org-back-over-empty-lines) 1)
8820 (forward-line 1))
8821 (point))
8822 what "children")
8823 (goto-char start)
8824 (show-subtree)
8825 (outline-next-heading))
8827 ;; we will sort the top-level entries in this file
8828 (goto-char (point-min))
8829 (or (org-at-heading-p) (outline-next-heading))
8830 (setq start (point))
8831 (goto-char (point-max))
8832 (beginning-of-line 1)
8833 (when (looking-at ".*?\\S-")
8834 ;; File ends in a non-white line
8835 (end-of-line 1)
8836 (insert "\n"))
8837 (setq end (point-max))
8838 (setq what "top-level")
8839 (goto-char start)
8840 (show-all)))
8842 (setq beg (point))
8843 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8845 (looking-at "\\(\\*+\\)")
8846 (setq stars (match-string 1)
8847 re (concat "^" (regexp-quote stars) " +")
8848 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8849 txt (buffer-substring beg end))
8850 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8851 (if (and (not (equal stars "*")) (string-match re2 txt))
8852 (user-error "Region to sort contains a level above the first entry"))
8854 (unless sorting-type
8855 (message
8856 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8857 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8858 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8859 what)
8860 (setq sorting-type (read-char-exclusive))
8862 (unless getkey-func
8863 (and (= (downcase sorting-type) ?f)
8864 (setq getkey-func
8865 (org-icompleting-read "Sort using function: "
8866 obarray 'fboundp t nil nil))
8867 (setq getkey-func (intern getkey-func))))
8869 (and (= (downcase sorting-type) ?r)
8870 (not property)
8871 (setq property
8872 (org-icompleting-read "Property: "
8873 (mapcar 'list (org-buffer-property-keys t))
8874 nil t))))
8876 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8877 (message "Sorting entries...")
8879 (save-restriction
8880 (narrow-to-region start end)
8881 (let ((dcst (downcase sorting-type))
8882 (case-fold-search nil)
8883 (now (current-time)))
8884 (sort-subr
8885 (/= dcst sorting-type)
8886 ;; This function moves to the beginning character of the "record" to
8887 ;; be sorted.
8888 (lambda nil
8889 (if (re-search-forward re nil t)
8890 (goto-char (match-beginning 0))
8891 (goto-char (point-max))))
8892 ;; This function moves to the last character of the "record" being
8893 ;; sorted.
8894 (lambda nil
8895 (save-match-data
8896 (condition-case nil
8897 (outline-forward-same-level 1)
8898 (error
8899 (goto-char (point-max))))))
8900 ;; This function returns the value that gets sorted against.
8901 (lambda nil
8902 (cond
8903 ((= dcst ?n)
8904 (if (looking-at org-complex-heading-regexp)
8905 (string-to-number (org-sort-remove-invisible (match-string 4)))
8906 nil))
8907 ((= dcst ?a)
8908 (if (looking-at org-complex-heading-regexp)
8909 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8910 nil))
8911 ((= dcst ?k)
8912 (or (get-text-property (point) :org-clock-minutes) 0))
8913 ((= dcst ?t)
8914 (let ((end (save-excursion (outline-next-heading) (point))))
8915 (if (or (re-search-forward org-ts-regexp end t)
8916 (re-search-forward org-ts-regexp-both end t))
8917 (org-time-string-to-seconds (match-string 0))
8918 (org-float-time now))))
8919 ((= dcst ?c)
8920 (let ((end (save-excursion (outline-next-heading) (point))))
8921 (if (re-search-forward
8922 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8923 end t)
8924 (org-time-string-to-seconds (match-string 0))
8925 (org-float-time now))))
8926 ((= dcst ?s)
8927 (let ((end (save-excursion (outline-next-heading) (point))))
8928 (if (re-search-forward org-scheduled-time-regexp end t)
8929 (org-time-string-to-seconds (match-string 1))
8930 (org-float-time now))))
8931 ((= dcst ?d)
8932 (let ((end (save-excursion (outline-next-heading) (point))))
8933 (if (re-search-forward org-deadline-time-regexp end t)
8934 (org-time-string-to-seconds (match-string 1))
8935 (org-float-time now))))
8936 ((= dcst ?p)
8937 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8938 (string-to-char (match-string 2))
8939 org-default-priority))
8940 ((= dcst ?r)
8941 (or (org-entry-get nil property) ""))
8942 ((= dcst ?o)
8943 (if (looking-at org-complex-heading-regexp)
8944 (let* ((m (match-string 2))
8945 (s (if (member m org-done-keywords) '- '+)))
8946 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8947 ((= dcst ?f)
8948 (if getkey-func
8949 (progn
8950 (setq tmp (funcall getkey-func))
8951 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8952 tmp)
8953 (error "Invalid key function `%s'" getkey-func)))
8954 (t (error "Invalid sorting type `%c'" sorting-type))))
8956 (cond
8957 ((= dcst ?a) 'string<)
8958 ((= dcst ?f) compare-func)
8959 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8960 (run-hooks 'org-after-sorting-entries-or-items-hook)
8961 ;; Reset the clock marker if needed
8962 (when cmstr
8963 (save-excursion
8964 (goto-char start)
8965 (search-forward cmstr nil t)
8966 (move-marker org-clock-marker (point))))
8967 (message "Sorting entries...done")))
8969 (defun org-do-sort (table what &optional with-case sorting-type)
8970 "Sort TABLE of WHAT according to SORTING-TYPE.
8971 The user will be prompted for the SORTING-TYPE if the call to this
8972 function does not specify it.
8973 WHAT is only for the prompt, to indicate what is being sorted.
8974 The sorting key will be extracted from the car of the elements of
8975 the table.
8976 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8977 (unless sorting-type
8978 (message
8979 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8980 what)
8981 (setq sorting-type (read-char-exclusive)))
8982 (let ((dcst (downcase sorting-type))
8983 extractfun comparefun)
8984 ;; Define the appropriate functions
8985 (cond
8986 ((= dcst ?n)
8987 (setq extractfun 'string-to-number
8988 comparefun (if (= dcst sorting-type) '< '>)))
8989 ((= dcst ?a)
8990 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8991 (lambda(x) (downcase (org-sort-remove-invisible x))))
8992 comparefun (if (= dcst sorting-type)
8993 'string<
8994 (lambda (a b) (and (not (string< a b))
8995 (not (string= a b)))))))
8996 ((= dcst ?t)
8997 (setq extractfun
8998 (lambda (x)
8999 (cond ((or (string-match org-ts-regexp x)
9000 (string-match org-ts-regexp-both x))
9001 (org-float-time
9002 (org-time-string-to-time (match-string 0 x))))
9003 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9004 (org-hh:mm-string-to-minutes x))
9005 (t 0)))
9006 comparefun (if (= dcst sorting-type) '< '>)))
9007 (t (error "Invalid sorting type `%c'" sorting-type)))
9009 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9010 table)
9011 (lambda (a b) (funcall comparefun (car a) (car b))))))
9014 ;;; The orgstruct minor mode
9016 ;; Define a minor mode which can be used in other modes in order to
9017 ;; integrate the org-mode structure editing commands.
9019 ;; This is really a hack, because the org-mode structure commands use
9020 ;; keys which normally belong to the major mode. Here is how it
9021 ;; works: The minor mode defines all the keys necessary to operate the
9022 ;; structure commands, but wraps the commands into a function which
9023 ;; tests if the cursor is currently at a headline or a plain list
9024 ;; item. If that is the case, the structure command is used,
9025 ;; temporarily setting many Org-mode variables like regular
9026 ;; expressions for filling etc. However, when any of those keys is
9027 ;; used at a different location, function uses `key-binding' to look
9028 ;; up if the key has an associated command in another currently active
9029 ;; keymap (minor modes, major mode, global), and executes that
9030 ;; command. There might be problems if any of the keys is otherwise
9031 ;; used as a prefix key.
9033 (defcustom orgstruct-heading-prefix-regexp ""
9034 "Regexp that matches the custom prefix of Org headlines in
9035 orgstruct(++)-mode."
9036 :group 'org
9037 :version "24.4"
9038 :package-version '(Org . "8.3")
9039 :type 'regexp)
9040 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9042 (defcustom orgstruct-setup-hook nil
9043 "Hook run after orgstruct-mode-map is filled."
9044 :group 'org
9045 :version "24.4"
9046 :package-version '(Org . "8.0")
9047 :type 'hook)
9049 (defvar orgstruct-initialized nil)
9051 (defvar org-local-vars nil
9052 "List of local variables, for use by `orgstruct-mode'.")
9054 ;;;###autoload
9055 (define-minor-mode orgstruct-mode
9056 "Toggle the minor mode `orgstruct-mode'.
9057 This mode is for using Org-mode structure commands in other
9058 modes. The following keys behave as if Org-mode were active, if
9059 the cursor is on a headline, or on a plain list item (both as
9060 defined by Org-mode)."
9061 nil " OrgStruct" (make-sparse-keymap)
9062 (funcall (if orgstruct-mode
9063 'add-to-invisibility-spec
9064 'remove-from-invisibility-spec)
9065 '(outline . t))
9066 (when orgstruct-mode
9067 (org-load-modules-maybe)
9068 (unless orgstruct-initialized
9069 (orgstruct-setup)
9070 (setq orgstruct-initialized t))))
9072 ;;;###autoload
9073 (defun turn-on-orgstruct ()
9074 "Unconditionally turn on `orgstruct-mode'."
9075 (orgstruct-mode 1))
9077 (defvar org-fb-vars nil)
9078 (make-variable-buffer-local 'org-fb-vars)
9079 (defun orgstruct++-mode (&optional arg)
9080 "Toggle `orgstruct-mode', the enhanced version of it.
9081 In addition to setting orgstruct-mode, this also exports all
9082 indentation and autofilling variables from org-mode into the
9083 buffer. It will also recognize item context in multiline items."
9084 (interactive "P")
9085 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9086 (if (< arg 1)
9087 (progn (orgstruct-mode -1)
9088 (mapc (lambda(v)
9089 (org-set-local (car v)
9090 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9091 org-fb-vars))
9092 (orgstruct-mode 1)
9093 (setq org-fb-vars nil)
9094 (unless org-local-vars
9095 (setq org-local-vars (org-get-local-variables)))
9096 (let (var val)
9097 (mapc
9098 (lambda (x)
9099 (when (string-match
9100 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9101 (symbol-name (car x)))
9102 (setq var (car x) val (nth 1 x))
9103 (push (list var `(quote ,(eval var))) org-fb-vars)
9104 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9105 org-local-vars)
9106 (org-set-local 'orgstruct-is-++ t))))
9108 (defvar orgstruct-is-++ nil
9109 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9110 (make-variable-buffer-local 'orgstruct-is-++)
9112 ;;;###autoload
9113 (defun turn-on-orgstruct++ ()
9114 "Unconditionally turn on `orgstruct++-mode'."
9115 (orgstruct++-mode 1))
9117 (defun orgstruct-error ()
9118 "Error when there is no default binding for a structure key."
9119 (interactive)
9120 (funcall (if (fboundp 'user-error)
9121 'user-error
9122 'error)
9123 "This key has no function outside structure elements"))
9125 (defun orgstruct-setup ()
9126 "Setup orgstruct keymap."
9127 (dolist (cell '((org-demote . t)
9128 (org-metaleft . t)
9129 (org-metaright . t)
9130 (org-promote . t)
9131 (org-shiftmetaleft . t)
9132 (org-shiftmetaright . t)
9133 org-backward-element
9134 org-backward-heading-same-level
9135 org-ctrl-c-ret
9136 org-ctrl-c-minus
9137 org-ctrl-c-star
9138 org-cycle
9139 org-forward-heading-same-level
9140 org-insert-heading
9141 org-insert-heading-respect-content
9142 org-kill-note-or-show-branches
9143 org-mark-subtree
9144 org-meta-return
9145 org-metadown
9146 org-metaup
9147 org-narrow-to-subtree
9148 org-promote-subtree
9149 org-reveal
9150 org-shiftdown
9151 org-shiftleft
9152 org-shiftmetadown
9153 org-shiftmetaup
9154 org-shiftright
9155 org-shifttab
9156 org-shifttab
9157 org-shiftup
9158 org-show-subtree
9159 org-sort
9160 org-up-element
9161 outline-demote
9162 outline-next-visible-heading
9163 outline-previous-visible-heading
9164 outline-promote
9165 outline-up-heading
9166 show-children))
9167 (let ((f (or (car-safe cell) cell))
9168 (disable-when-heading-prefix (cdr-safe cell)))
9169 (when (fboundp f)
9170 (let ((new-bindings))
9171 (dolist (binding (nconc (where-is-internal f org-mode-map)
9172 (where-is-internal f outline-mode-map)))
9173 (push binding new-bindings)
9174 ;; TODO use local-function-key-map
9175 (dolist (rep '(("<tab>" . "TAB")
9176 ("<return>" . "RET")
9177 ("<escape>" . "ESC")
9178 ("<delete>" . "DEL")))
9179 (setq binding (read-kbd-macro
9180 (let ((case-fold-search))
9181 (replace-regexp-in-string
9182 (regexp-quote (cdr rep))
9183 (car rep)
9184 (key-description binding)))))
9185 (pushnew binding new-bindings :test 'equal)))
9186 (dolist (binding new-bindings)
9187 (let ((key (lookup-key orgstruct-mode-map binding)))
9188 (when (or (not key) (numberp key))
9189 (ignore-errors
9190 (org-defkey orgstruct-mode-map
9191 binding
9192 (orgstruct-make-binding
9193 f binding disable-when-heading-prefix))))))))))
9194 (run-hooks 'orgstruct-setup-hook))
9196 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9197 "Create a function for binding in the structure minor mode.
9198 FUN is the command to call inside a table. KEY is the key that
9199 should be checked in for a command to execute outside of tables.
9200 Non-nil `disable-when-heading-prefix' means to disable the command
9201 if `orgstruct-heading-prefix-regexp' is not empty."
9202 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9203 (let ((nname name)
9204 (i 0))
9205 (while (fboundp (intern nname))
9206 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9207 (setq name (intern nname)))
9208 (eval
9209 (let ((bindings '((org-heading-regexp
9210 (concat "^"
9211 orgstruct-heading-prefix-regexp
9212 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9213 (org-outline-regexp
9214 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9215 (org-outline-regexp-bol
9216 (concat "^" org-outline-regexp))
9217 (outline-regexp org-outline-regexp)
9218 (outline-heading-end-regexp "\n")
9219 (outline-level 'org-outline-level)
9220 (outline-heading-alist))))
9221 `(defun ,name (arg)
9222 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9223 "Outside of structure, run the binding of `"
9224 (key-description key) "'."
9225 (when disable-when-heading-prefix
9226 (concat
9227 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9228 "back to the default binding due to limitations of Org's implementation of\n"
9229 "`" (symbol-name fun) "'.")))
9230 (interactive "p")
9231 (let* ((disable
9232 ,(and disable-when-heading-prefix
9233 '(not (string= orgstruct-heading-prefix-regexp ""))))
9234 (fallback
9235 (or disable
9236 (not
9237 (let* ,bindings
9238 (org-context-p 'headline 'item
9239 ,(when (memq fun
9240 '(org-insert-heading
9241 org-insert-heading-respect-content
9242 org-meta-return))
9243 '(when orgstruct-is-++
9244 'item-body))))))))
9245 (if fallback
9246 (let* ((orgstruct-mode)
9247 (binding
9248 (loop with key = ,key
9249 for rep in
9250 '(nil
9251 ("<\\([^>]*\\)tab>" . "\\1TAB")
9252 ("<\\([^>]*\\)return>" . "\\1RET")
9253 ("<\\([^>]*\\)escape>" . "\\1ESC")
9254 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9256 (when rep
9257 (setq key (read-kbd-macro
9258 (let ((case-fold-search))
9259 (replace-regexp-in-string
9260 (car rep)
9261 (cdr rep)
9262 (key-description key))))))
9263 thereis (key-binding key))))
9264 (if (keymapp binding)
9265 (org-set-transient-map binding)
9266 (let ((func (or binding
9267 (unless disable
9268 'orgstruct-error))))
9269 (when func
9270 (call-interactively func)))))
9271 (org-run-like-in-org-mode
9272 (lambda ()
9273 (interactive)
9274 (let* ,bindings
9275 (call-interactively ',fun)))))))))
9276 name))
9278 (defun org-contextualize-keys (alist contexts)
9279 "Return valid elements in ALIST depending on CONTEXTS.
9281 `org-agenda-custom-commands' or `org-capture-templates' are the
9282 values used for ALIST, and `org-agenda-custom-commands-contexts'
9283 or `org-capture-templates-contexts' are the associated contexts
9284 definitions."
9285 (let ((contexts
9286 ;; normalize contexts
9287 (mapcar
9288 (lambda(c) (cond ((listp (cadr c))
9289 (list (car c) (car c) (cadr c)))
9290 ((string= "" (cadr c))
9291 (list (car c) (car c) (caddr c)))
9292 (t c))) contexts))
9293 (a alist) c r s)
9294 ;; loop over all commands or templates
9295 (while (setq c (pop a))
9296 (let (vrules repl)
9297 (cond
9298 ((not (assoc (car c) contexts))
9299 (push c r))
9300 ((and (assoc (car c) contexts)
9301 (setq vrules (org-contextualize-validate-key
9302 (car c) contexts)))
9303 (mapc (lambda (vr)
9304 (when (not (equal (car vr) (cadr vr)))
9305 (setq repl vr))) vrules)
9306 (if (not repl) (push c r)
9307 (push (cadr repl) s)
9308 (push
9309 (cons (car c)
9310 (cdr (or (assoc (cadr repl) alist)
9311 (error "Undefined key `%s' as contextual replacement for `%s'"
9312 (cadr repl) (car c)))))
9313 r))))))
9314 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9315 (delq
9317 (delete-dups
9318 (mapcar (lambda (x)
9319 (let ((tpl (car x)))
9320 (when (not (delq
9322 (mapcar (lambda(y)
9323 (equal y tpl)) s))) x)))
9324 (reverse r))))))
9326 (defun org-contextualize-validate-key (key contexts)
9327 "Check CONTEXTS for agenda or capture KEY."
9328 (let (r rr res)
9329 (while (setq r (pop contexts))
9330 (mapc
9331 (lambda (rr)
9332 (when
9333 (and (equal key (car r))
9334 (if (functionp rr) (funcall rr)
9335 (or (and (eq (car rr) 'in-file)
9336 (buffer-file-name)
9337 (string-match (cdr rr) (buffer-file-name)))
9338 (and (eq (car rr) 'in-mode)
9339 (string-match (cdr rr) (symbol-name major-mode)))
9340 (and (eq (car rr) 'in-buffer)
9341 (string-match (cdr rr) (buffer-name)))
9342 (when (and (eq (car rr) 'not-in-file)
9343 (buffer-file-name))
9344 (not (string-match (cdr rr) (buffer-file-name))))
9345 (when (eq (car rr) 'not-in-mode)
9346 (not (string-match (cdr rr) (symbol-name major-mode))))
9347 (when (eq (car rr) 'not-in-buffer)
9348 (not (string-match (cdr rr) (buffer-name)))))))
9349 (push r res)))
9350 (car (last r))))
9351 (delete-dups (delq nil res))))
9353 (defun org-context-p (&rest contexts)
9354 "Check if local context is any of CONTEXTS.
9355 Possible values in the list of contexts are `table', `headline', and `item'."
9356 (let ((pos (point)))
9357 (goto-char (point-at-bol))
9358 (prog1 (or (and (memq 'table contexts)
9359 (looking-at "[ \t]*|"))
9360 (and (memq 'headline contexts)
9361 (looking-at org-outline-regexp))
9362 (and (memq 'item contexts)
9363 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9364 (and (memq 'item-body contexts)
9365 (org-in-item-p)))
9366 (goto-char pos))))
9368 (defun org-get-local-variables ()
9369 "Return a list of all local variables in an Org mode buffer."
9370 (let (varlist)
9371 (with-current-buffer (get-buffer-create "*Org tmp*")
9372 (erase-buffer)
9373 (org-mode)
9374 (setq varlist (buffer-local-variables)))
9375 (kill-buffer "*Org tmp*")
9376 (delq nil
9377 (mapcar
9378 (lambda (x)
9379 (setq x
9380 (if (symbolp x)
9381 (list x)
9382 (list (car x) (cdr x))))
9383 (if (and (not (get (car x) 'org-state))
9384 (string-match
9385 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9386 (symbol-name (car x))))
9387 x nil))
9388 varlist))))
9390 (defun org-clone-local-variables (from-buffer &optional regexp)
9391 "Clone local variables from FROM-BUFFER.
9392 Optional argument REGEXP selects variables to clone."
9393 (mapc
9394 (lambda (pair)
9395 (and (symbolp (car pair))
9396 (or (null regexp)
9397 (string-match regexp (symbol-name (car pair))))
9398 (set (make-local-variable (car pair))
9399 (cdr pair))))
9400 (buffer-local-variables from-buffer)))
9402 ;;;###autoload
9403 (defun org-run-like-in-org-mode (cmd)
9404 "Run a command, pretending that the current buffer is in Org-mode.
9405 This will temporarily bind local variables that are typically bound in
9406 Org-mode to the values they have in Org-mode, and then interactively
9407 call CMD."
9408 (org-load-modules-maybe)
9409 (unless org-local-vars
9410 (setq org-local-vars (org-get-local-variables)))
9411 (let (binds)
9412 (dolist (var org-local-vars)
9413 (when (or (not (boundp (car var)))
9414 (eq (symbol-value (car var))
9415 (default-value (car var))))
9416 (push (list (car var) `(quote ,(cadr var))) binds)))
9417 (eval `(let ,binds
9418 (call-interactively (quote ,cmd))))))
9420 (defun org-get-category (&optional pos force-refresh)
9421 "Get the category applying to position POS."
9422 (save-match-data
9423 (if force-refresh (org-refresh-category-properties))
9424 (let ((pos (or pos (point))))
9425 (or (get-text-property pos 'org-category)
9426 (progn (org-refresh-category-properties)
9427 (get-text-property pos 'org-category))))))
9429 ;;; Refresh properties
9431 (defun org-refresh-properties (dprop tprop)
9432 "Refresh buffer text properties.
9433 DPROP is the drawer property and TPROP is either the
9434 corresponding text property to set, or an alist with each element
9435 being a text property (as a symbol) and a function to apply to
9436 the value of the drawer property."
9437 (let ((case-fold-search t)
9438 (inhibit-read-only t))
9439 (org-with-silent-modifications
9440 (save-excursion
9441 (save-restriction
9442 (widen)
9443 (goto-char (point-min))
9444 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9445 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9447 (defun org-refresh-property (tprop p)
9448 "Refresh the buffer text property TPROP from the drawer property P.
9449 The refresh happens only for the current tree (not subtree)."
9450 (save-excursion
9451 (org-back-to-heading t)
9452 ;; tprop is a text property symbol
9453 (if (symbolp tprop)
9454 (put-text-property
9455 (point) (or (outline-next-heading) (point-max)) tprop p)
9456 ;; tprop is an alist with (properties . function) elements
9457 (mapc (lambda(al)
9458 (save-excursion
9459 (put-text-property
9460 (point-at-bol) (or (outline-next-heading) (point-max))
9461 (car al)
9462 (funcall (cdr al) p))))
9463 tprop))))
9465 (defun org-refresh-category-properties ()
9466 "Refresh category text properties in the buffer."
9467 (let ((case-fold-search t)
9468 (inhibit-read-only t)
9469 (def-cat (cond
9470 ((null org-category)
9471 (if buffer-file-name
9472 (file-name-sans-extension
9473 (file-name-nondirectory buffer-file-name))
9474 "???"))
9475 ((symbolp org-category) (symbol-name org-category))
9476 (t org-category)))
9477 beg end cat pos optionp)
9478 (org-with-silent-modifications
9479 (save-excursion
9480 (save-restriction
9481 (widen)
9482 (goto-char (point-min))
9483 (put-text-property (point) (point-max) 'org-category def-cat)
9484 (while (re-search-forward
9485 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9486 (setq pos (match-end 0)
9487 optionp (equal (char-after (match-beginning 0)) ?#)
9488 cat (org-trim (match-string 2)))
9489 (if optionp
9490 (setq beg (point-at-bol) end (point-max))
9491 (org-back-to-heading t)
9492 (setq beg (point) end (org-end-of-subtree t t)))
9493 (put-text-property beg end 'org-category cat)
9494 (goto-char pos)))))))
9496 (defun org-refresh-stats-properties ()
9497 "Refresh stats text properties in the buffer."
9498 (let (stats)
9499 (org-with-silent-modifications
9500 (save-excursion
9501 (save-restriction
9502 (widen)
9503 (goto-char (point-min))
9504 (while (re-search-forward
9505 (concat org-outline-regexp-bol ".*"
9506 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9507 nil t)
9508 (setq stats (cond ((equal (match-string 3) "0") 0)
9509 ((match-string 2)
9510 (/ (* (string-to-number (match-string 2)) 100)
9511 (string-to-number (match-string 3))))
9512 (t (string-to-number (match-string 1)))))
9513 (org-back-to-heading t)
9514 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9515 'org-stats stats)))))))
9517 (defun org-refresh-effort-properties ()
9518 "Refresh effort properties"
9519 (org-refresh-properties
9520 org-effort-property
9521 '((effort . identity)
9522 (effort-minutes . org-duration-string-to-minutes))))
9524 ;;;; Link Stuff
9526 ;;; Link abbreviations
9528 (defun org-link-expand-abbrev (link)
9529 "Apply replacements as defined in `org-link-abbrev-alist'."
9530 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9531 (let* ((key (match-string 1 link))
9532 (as (or (assoc key org-link-abbrev-alist-local)
9533 (assoc key org-link-abbrev-alist)))
9534 (tag (and (match-end 2) (match-string 3 link)))
9535 rpl)
9536 (if (not as)
9537 link
9538 (setq rpl (cdr as))
9539 (cond
9540 ((symbolp rpl) (funcall rpl tag))
9541 ((string-match "%(\\([^)]+\\))" rpl)
9542 (replace-match
9543 (save-match-data
9544 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9545 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9546 ((string-match "%h" rpl)
9547 (replace-match (url-hexify-string (or tag "")) t t rpl))
9548 (t (concat rpl tag)))))
9549 link))
9551 ;;; Storing and inserting links
9553 (defvar org-insert-link-history nil
9554 "Minibuffer history for links inserted with `org-insert-link'.")
9556 (defvar org-stored-links nil
9557 "Contains the links stored with `org-store-link'.")
9559 (defvar org-store-link-plist nil
9560 "Plist with info about the most recently link created with `org-store-link'.")
9562 (defvar org-link-protocols nil
9563 "Link protocols added to Org-mode using `org-add-link-type'.")
9565 (defvar org-store-link-functions nil
9566 "List of functions that are called to create and store a link.
9567 Each function will be called in turn until one returns a non-nil
9568 value. Each function should check if it is responsible for creating
9569 this link (for example by looking at the major mode).
9570 If not, it must exit and return nil.
9571 If yes, it should return a non-nil value after a calling
9572 `org-store-link-props' with a list of properties and values.
9573 Special properties are:
9575 :type The link prefix, like \"http\". This must be given.
9576 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9577 This is obligatory as well.
9578 :description Optional default description for the second pair
9579 of brackets in an Org-mode link. The user can still change
9580 this when inserting this link into an Org-mode buffer.
9582 In addition to these, any additional properties can be specified
9583 and then used in capture templates.")
9585 (defun org-add-link-type (type &optional follow export)
9586 "Add TYPE to the list of `org-link-types'.
9587 Re-compute all regular expressions depending on `org-link-types'
9589 FOLLOW and EXPORT are two functions.
9591 FOLLOW should take the link path as the single argument and do whatever
9592 is necessary to follow the link, for example find a file or display
9593 a mail message.
9595 EXPORT should format the link path for export to one of the export formats.
9596 It should be a function accepting three arguments:
9598 path the path of the link, the text after the prefix (like \"http:\")
9599 desc the description of the link, if any, or a description added by
9600 org-export-normalize-links if there is none
9601 format the export format, a symbol like `html' or `latex' or `ascii'..
9603 The function may use the FORMAT information to return different values
9604 depending on the format. The return value will be put literally into
9605 the exported file. If the return value is nil, this means Org should
9606 do what it normally does with links which do not have EXPORT defined.
9608 Org-mode has a built-in default for exporting links. If you are happy with
9609 this default, there is no need to define an export function for the link
9610 type. For a simple example of an export function, see `org-bbdb.el'."
9611 (add-to-list 'org-link-types type t)
9612 (org-make-link-regexps)
9613 (if (assoc type org-link-protocols)
9614 (setcdr (assoc type org-link-protocols) (list follow export))
9615 (push (list type follow export) org-link-protocols)))
9617 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9618 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9620 ;;;###autoload
9621 (defun org-store-link (arg)
9622 "\\<org-mode-map>Store an org-link to the current location.
9623 This link is added to `org-stored-links' and can later be inserted
9624 into an org-buffer with \\[org-insert-link].
9626 For some link types, a prefix arg is interpreted.
9627 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9628 For file links, arg negates `org-context-in-file-links'.
9630 A double prefix arg force skipping storing functions that are not
9631 part of Org's core.
9633 A triple prefix arg force storing a link for each line in the
9634 active region."
9635 (interactive "P")
9636 (org-load-modules-maybe)
9637 (if (and (equal arg '(64)) (org-region-active-p))
9638 (save-excursion
9639 (let ((end (region-end)))
9640 (goto-char (region-beginning))
9641 (set-mark (point))
9642 (while (< (point-at-eol) end)
9643 (move-end-of-line 1) (activate-mark)
9644 (let (current-prefix-arg)
9645 (call-interactively 'org-store-link))
9646 (move-beginning-of-line 2)
9647 (set-mark (point)))))
9648 (org-with-limited-levels
9649 (setq org-store-link-plist nil)
9650 (let (link cpltxt desc description search
9651 txt custom-id agenda-link sfuns sfunsn)
9652 (cond
9654 ;; Store a link using an external link type
9655 ((and (not (equal arg '(16)))
9656 (setq sfuns
9657 (delq
9658 nil (mapcar (lambda (f)
9659 (let (fs) (if (funcall f) (push f fs))))
9660 org-store-link-functions))
9661 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9662 (or (and (cdr sfuns)
9663 (funcall (intern
9664 (completing-read
9665 "Which function for creating the link? "
9666 sfunsn nil t (car sfunsn)))))
9667 (funcall (caar sfuns)))
9668 (setq link (plist-get org-store-link-plist :link)
9669 desc (or (plist-get org-store-link-plist
9670 :description) link))))
9672 ;; Store a link from a source code buffer
9673 ((org-src-edit-buffer-p)
9674 (let (label gc)
9675 (while (or (not label)
9676 (save-excursion
9677 (save-restriction
9678 (widen)
9679 (goto-char (point-min))
9680 (re-search-forward
9681 (regexp-quote (format org-coderef-label-format label))
9682 nil t))))
9683 (when label (message "Label exists already") (sit-for 2))
9684 (setq label (read-string "Code line label: " label)))
9685 (end-of-line 1)
9686 (setq link (format org-coderef-label-format label))
9687 (setq gc (- 79 (length link)))
9688 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9689 (insert link)
9690 (setq link (concat "(" label ")") desc nil)))
9692 ;; We are in the agenda, link to referenced location
9693 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9694 (let ((m (or (get-text-property (point) 'org-hd-marker)
9695 (get-text-property (point) 'org-marker))))
9696 (when m
9697 (org-with-point-at m
9698 (setq agenda-link
9699 (if (org-called-interactively-p 'any)
9700 (call-interactively 'org-store-link)
9701 (org-store-link nil)))))))
9703 ((eq major-mode 'calendar-mode)
9704 (let ((cd (calendar-cursor-to-date)))
9705 (setq link
9706 (format-time-string
9707 (car org-time-stamp-formats)
9708 (apply 'encode-time
9709 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9710 nil nil nil))))
9711 (org-store-link-props :type "calendar" :date cd)))
9713 ((eq major-mode 'help-mode)
9714 (setq link (concat "help:" (save-excursion
9715 (goto-char (point-min))
9716 (looking-at "^[^ ]+")
9717 (match-string 0))))
9718 (org-store-link-props :type "help"))
9720 ((eq major-mode 'w3-mode)
9721 (setq cpltxt (if (and (buffer-name)
9722 (not (string-match "Untitled" (buffer-name))))
9723 (buffer-name)
9724 (url-view-url t))
9725 link (url-view-url t))
9726 (org-store-link-props :type "w3" :url (url-view-url t)))
9728 ((eq major-mode 'image-mode)
9729 (setq cpltxt (concat "file:"
9730 (abbreviate-file-name buffer-file-name))
9731 link cpltxt)
9732 (org-store-link-props :type "image" :file buffer-file-name))
9734 ;; In dired, store a link to the file of the current line
9735 ((derived-mode-p 'dired-mode)
9736 (let ((file (dired-get-filename nil t)))
9737 (setq file (if file
9738 (abbreviate-file-name
9739 (expand-file-name (dired-get-filename nil t)))
9740 ;; otherwise, no file so use current directory.
9741 default-directory))
9742 (setq cpltxt (concat "file:" file)
9743 link cpltxt)))
9745 ((setq search (run-hook-with-args-until-success
9746 'org-create-file-search-functions))
9747 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9748 "::" search))
9749 (setq cpltxt (or description link)))
9751 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9752 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9753 (cond
9754 ;; Store a link using the target at point
9755 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9756 (setq cpltxt
9757 (concat "file:"
9758 (abbreviate-file-name
9759 (buffer-file-name (buffer-base-buffer)))
9760 "::" (match-string 1))
9761 link cpltxt))
9762 ((and (featurep 'org-id)
9763 (or (eq org-id-link-to-org-use-id t)
9764 (and (org-called-interactively-p 'any)
9765 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9766 (and (eq org-id-link-to-org-use-id
9767 'create-if-interactive-and-no-custom-id)
9768 (not custom-id))))
9769 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9770 ;; Store a link using the ID at point
9771 (setq link (condition-case nil
9772 (prog1 (org-id-store-link)
9773 (setq desc (or (plist-get org-store-link-plist
9774 :description)
9775 "")))
9776 (error
9777 ;; Probably before first headline, link only to file
9778 (concat "file:"
9779 (abbreviate-file-name
9780 (buffer-file-name (buffer-base-buffer))))))))
9782 ;; Just link to current headline
9783 (setq cpltxt (concat "file:"
9784 (abbreviate-file-name
9785 (buffer-file-name (buffer-base-buffer)))))
9786 ;; Add a context search string
9787 (when (org-xor org-context-in-file-links arg)
9788 (let* ((ee (org-element-at-point))
9789 (et (org-element-type ee))
9790 (ev (plist-get (cadr ee) :value))
9791 (ek (plist-get (cadr ee) :key))
9792 (eok (and (stringp ek) (string-match "name" ek))))
9793 (setq txt (cond
9794 ((org-at-heading-p) nil)
9795 ((and (eq et 'keyword) eok) ev)
9796 ((org-region-active-p)
9797 (buffer-substring (region-beginning) (region-end)))))
9798 (when (or (null txt) (string-match "\\S-" txt))
9799 (setq cpltxt
9800 (concat cpltxt "::"
9801 (condition-case nil
9802 (org-make-org-heading-search-string txt)
9803 (error "")))
9804 desc (or (and (eq et 'keyword) eok ev)
9805 (nth 4 (ignore-errors (org-heading-components)))
9806 "NONE")))))
9807 (if (string-match "::\\'" cpltxt)
9808 (setq cpltxt (substring cpltxt 0 -2)))
9809 (setq link cpltxt))))
9811 ((buffer-file-name (buffer-base-buffer))
9812 ;; Just link to this file here.
9813 (setq cpltxt (concat "file:"
9814 (abbreviate-file-name
9815 (buffer-file-name (buffer-base-buffer)))))
9816 ;; Add a context string.
9817 (when (org-xor org-context-in-file-links arg)
9818 (setq txt (if (org-region-active-p)
9819 (buffer-substring (region-beginning) (region-end))
9820 (buffer-substring (point-at-bol) (point-at-eol))))
9821 ;; Only use search option if there is some text.
9822 (when (string-match "\\S-" txt)
9823 (setq cpltxt
9824 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9825 desc "NONE")))
9826 (setq link cpltxt))
9828 ((org-called-interactively-p 'interactive)
9829 (user-error "No method for storing a link from this buffer"))
9831 (t (setq link nil)))
9833 ;; We're done setting link and desc, clean up
9834 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9835 (setq link (or link cpltxt)
9836 desc (or desc cpltxt))
9837 (cond ((equal desc "NONE") (setq desc nil))
9838 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9839 (let ((d0 (match-string 3 desc))
9840 (p0 (match-string 5 desc)))
9841 (setq desc
9842 (replace-regexp-in-string
9843 org-bracket-link-regexp
9844 (concat (or p0 d0)
9845 (if (equal (length (match-string 0 desc))
9846 (length desc)) "*" "")) desc)))))
9848 ;; Return the link
9849 (if (not (and (or (org-called-interactively-p 'any)
9850 executing-kbd-macro) link))
9851 (or agenda-link (and link (org-make-link-string link desc)))
9852 (push (list link desc) org-stored-links)
9853 (message "Stored: %s" (or desc link))
9854 (when custom-id
9855 (setq link (concat "file:" (abbreviate-file-name
9856 (buffer-file-name)) "::#" custom-id))
9857 (push (list link desc) org-stored-links))
9858 (car org-stored-links))))))
9860 (defun org-store-link-props (&rest plist)
9861 "Store link properties, extract names and addresses."
9862 (let (x adr)
9863 (when (setq x (plist-get plist :from))
9864 (setq adr (mail-extract-address-components x))
9865 (setq plist (plist-put plist :fromname (car adr)))
9866 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9867 (when (setq x (plist-get plist :to))
9868 (setq adr (mail-extract-address-components x))
9869 (setq plist (plist-put plist :toname (car adr)))
9870 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9871 (let ((from (plist-get plist :from))
9872 (to (plist-get plist :to)))
9873 (when (and from to org-from-is-user-regexp)
9874 (setq plist
9875 (plist-put plist :fromto
9876 (if (string-match org-from-is-user-regexp from)
9877 (concat "to %t")
9878 (concat "from %f"))))))
9879 (setq org-store-link-plist plist))
9881 (defun org-add-link-props (&rest plist)
9882 "Add these properties to the link property list."
9883 (let (key value)
9884 (while plist
9885 (setq key (pop plist) value (pop plist))
9886 (setq org-store-link-plist
9887 (plist-put org-store-link-plist key value)))))
9889 (defun org-email-link-description (&optional fmt)
9890 "Return the description part of an email link.
9891 This takes information from `org-store-link-plist' and formats it
9892 according to FMT (default from `org-email-link-description-format')."
9893 (setq fmt (or fmt org-email-link-description-format))
9894 (let* ((p org-store-link-plist)
9895 (to (plist-get p :toaddress))
9896 (from (plist-get p :fromaddress))
9897 (table
9898 (list
9899 (cons "%c" (plist-get p :fromto))
9900 (cons "%F" (plist-get p :from))
9901 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9902 (cons "%T" (plist-get p :to))
9903 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9904 (cons "%s" (plist-get p :subject))
9905 (cons "%d" (plist-get p :date))
9906 (cons "%m" (plist-get p :message-id)))))
9907 (when (string-match "%c" fmt)
9908 ;; Check if the user wrote this message
9909 (if (and org-from-is-user-regexp from to
9910 (save-match-data (string-match org-from-is-user-regexp from)))
9911 (setq fmt (replace-match "to %t" t t fmt))
9912 (setq fmt (replace-match "from %f" t t fmt))))
9913 (org-replace-escapes fmt table)))
9915 (defun org-make-org-heading-search-string (&optional string)
9916 "Make search string for the current headline or STRING."
9917 (let ((s (or string
9918 (and (derived-mode-p 'org-mode)
9919 (save-excursion
9920 (org-back-to-heading t)
9921 (org-element-property :raw-value (org-element-at-point))))))
9922 (lines org-context-in-file-links))
9923 (or string (setq s (concat "*" s))) ; Add * for headlines
9924 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9925 (when (and string (integerp lines) (> lines 0))
9926 (let ((slines (org-split-string s "\n")))
9927 (when (< lines (length slines))
9928 (setq s (mapconcat
9929 'identity
9930 (reverse (nthcdr (- (length slines) lines)
9931 (reverse slines))) "\n")))))
9932 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9934 (defun org-make-link-string (link &optional description)
9935 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9936 (unless (string-match "\\S-" link)
9937 (error "Empty link"))
9938 (when (and description
9939 (stringp description)
9940 (not (string-match "\\S-" description)))
9941 (setq description nil))
9942 (when (stringp description)
9943 ;; Remove brackets from the description, they are fatal.
9944 (while (string-match "\\[" description)
9945 (setq description (replace-match "{" t t description)))
9946 (while (string-match "\\]" description)
9947 (setq description (replace-match "}" t t description))))
9948 (when (equal link description)
9949 ;; No description needed, it is identical
9950 (setq description nil))
9951 (when (and (not description)
9952 (not (string-match (org-image-file-name-regexp) link))
9953 (not (equal link (org-link-escape link))))
9954 (setq description (org-extract-attributes link)))
9955 (setq link
9956 (cond ((string-match (org-image-file-name-regexp) link) link)
9957 ((string-match org-link-types-re link)
9958 (concat (match-string 1 link)
9959 (org-link-escape (substring link (match-end 1)))))
9960 (t (org-link-escape link))))
9961 (concat "[[" link "]"
9962 (if description (concat "[" description "]") "")
9963 "]"))
9965 (defconst org-link-escape-chars
9966 ;;%20 %5B %5D
9967 '(?\ ?\[ ?\])
9968 "List of characters that should be escaped in a link when stored to Org.
9969 This is the list that is used for internal purposes.")
9971 (defconst org-link-escape-chars-browser
9972 ;;%20 %22
9973 '(?\ ?\")
9974 "List of characters to be escaped before handing over to the browser.
9975 If you consider using this constant then you probably want to use
9976 the function `org-link-escape-browser' instead. See there why
9977 this constant is a candidate to be removed once Org drops support
9978 for Emacs 24.1 and 24.2.")
9980 (defun org-link-escape (text &optional table merge)
9981 "Return percent escaped representation of TEXT.
9982 TEXT is a string with the text to escape.
9983 Optional argument TABLE is a list with characters that should be
9984 escaped. When nil, `org-link-escape-chars' is used.
9985 If optional argument MERGE is set, merge TABLE into
9986 `org-link-escape-chars'."
9987 ;; Don't escape chars in internal links
9988 (if (string-match "^\\*[[:alnum:]]+" text)
9989 text
9990 (cond
9991 ((and table merge)
9992 (mapc (lambda (defchr)
9993 (unless (member defchr table)
9994 (setq table (cons defchr table))))
9995 org-link-escape-chars))
9996 ((null table)
9997 (setq table org-link-escape-chars)))
9998 (mapconcat
9999 (lambda (char)
10000 (if (or (member char table)
10001 (and (or (< char 32) (= char ?\%) (> char 126))
10002 org-url-hexify-p))
10003 (mapconcat (lambda (sequence-element)
10004 (format "%%%.2X" sequence-element))
10005 (or (encode-coding-char char 'utf-8)
10006 (error "Unable to percent escape character: %s"
10007 (char-to-string char))) "")
10008 (char-to-string char))) text "")))
10010 (defun org-link-escape-browser (text)
10011 "Escape some characters before handing over to the browser.
10012 This function is a candidate to be removed together with the
10013 constant `org-link-escape-chars-browser' once Org drops support
10014 for Emacs 24.1 and 24.2. All calls to this function will have to
10015 be replaced with `url-encode-url' which is available since Emacs
10016 24.3.1."
10017 ;; Example with the Org link
10018 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10019 ;; to open the browser with +subject:"Release 8.2" filled into the
10020 ;; query field: In this case the variable TEXT contains the
10021 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10022 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10023 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10024 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10025 (if (fboundp 'url-encode-url)
10026 (url-encode-url text)
10027 (if (org-string-match-p
10028 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10029 text)
10030 (org-link-escape text org-link-escape-chars-browser)
10031 text)))
10033 (defun org-link-unescape (str)
10034 "Unhex hexified Unicode strings as returned from the JavaScript function
10035 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10036 (unless (and (null str) (string= "" str))
10037 (let ((pos 0) (case-fold-search t) unhexed)
10038 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10039 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10040 (setq str (replace-match unhexed t t str))
10041 (setq pos (+ pos (length unhexed))))))
10042 str)
10044 (defun org-link-unescape-compound (hex)
10045 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10046 Note: this function also decodes single byte encodings like
10047 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10048 (save-match-data
10049 (let* ((bytes (cdr (split-string hex "%")))
10050 (ret "")
10051 (eat 0)
10052 (sum 0))
10053 (while bytes
10054 (let* ((val (string-to-number (pop bytes) 16))
10055 (shift-xor
10056 (if (= 0 eat)
10057 (cond
10058 ((>= val 252) (cons 6 252))
10059 ((>= val 248) (cons 5 248))
10060 ((>= val 240) (cons 4 240))
10061 ((>= val 224) (cons 3 224))
10062 ((>= val 192) (cons 2 192))
10063 (t (cons 0 0)))
10064 (cons 6 128))))
10065 (if (>= val 192) (setq eat (car shift-xor)))
10066 (setq val (logxor val (cdr shift-xor)))
10067 (setq sum (+ (lsh sum (car shift-xor)) val))
10068 (if (> eat 0) (setq eat (- eat 1)))
10069 (cond
10070 ((= 0 eat) ;multi byte
10071 (setq ret (concat ret (org-char-to-string sum)))
10072 (setq sum 0))
10073 ((not bytes) ; single byte(s)
10074 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10075 ret)))
10077 (defun org-link-unescape-single-byte-sequence (hex)
10078 "Unhexify hex-encoded single byte character sequences."
10079 (mapconcat (lambda (byte)
10080 (char-to-string (string-to-number byte 16)))
10081 (cdr (split-string hex "%")) ""))
10083 (defun org-xor (a b)
10084 "Exclusive or."
10085 (if a (not b) b))
10087 (defun org-fixup-message-id-for-http (s)
10088 "Replace special characters in a message id, so it can be used in an http query."
10089 (when (string-match "%" s)
10090 (setq s (mapconcat (lambda (c)
10091 (if (eq c ?%)
10092 "%25"
10093 (char-to-string c)))
10094 s "")))
10095 (while (string-match "<" s)
10096 (setq s (replace-match "%3C" t t s)))
10097 (while (string-match ">" s)
10098 (setq s (replace-match "%3E" t t s)))
10099 (while (string-match "@" s)
10100 (setq s (replace-match "%40" t t s)))
10103 (defun org-link-prettify (link)
10104 "Return a human-readable representation of LINK.
10105 The car of LINK must be a raw link.
10106 The cdr of LINK must be either a link description or nil."
10107 (let ((desc (or (cadr link) "<no description>")))
10108 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10109 "<" (car link) ">")))
10111 ;;;###autoload
10112 (defun org-insert-link-global ()
10113 "Insert a link like Org-mode does.
10114 This command can be called in any mode to insert a link in Org-mode syntax."
10115 (interactive)
10116 (org-load-modules-maybe)
10117 (org-run-like-in-org-mode 'org-insert-link))
10119 (defun org-insert-all-links (arg &optional pre post)
10120 "Insert all links in `org-stored-links'.
10121 When a universal prefix, do not delete the links from `org-stored-links'.
10122 When `ARG' is a number, insert the last N link(s).
10123 `PRE' and `POST' are optional arguments to define a string to
10124 prepend or to append."
10125 (interactive "P")
10126 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10127 (links (copy-seq org-stored-links))
10128 (pr (or pre "- "))
10129 (po (or post "\n"))
10130 (cnt 1) l)
10131 (if (null org-stored-links)
10132 (message "No link to insert")
10133 (while (and (or (listp arg) (>= arg cnt))
10134 (setq l (if (listp arg)
10135 (pop links)
10136 (pop org-stored-links))))
10137 (setq cnt (1+ cnt))
10138 (insert pr)
10139 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10140 (insert po)))))
10142 (defun org-insert-last-stored-link (arg)
10143 "Insert the last link stored in `org-stored-links'."
10144 (interactive "p")
10145 (org-insert-all-links arg "" "\n"))
10147 (defun org-link-fontify-links-to-this-file ()
10148 "Fontify links to the current file in `org-stored-links'."
10149 (let ((f (buffer-file-name)) a b)
10150 (setq a (mapcar (lambda(l)
10151 (let ((ll (car l)))
10152 (when (and (string-match "^file:\\(.+\\)::" ll)
10153 (equal f (expand-file-name (match-string 1 ll))))
10154 ll)))
10155 org-stored-links))
10156 (when (featurep 'org-id)
10157 (setq b (mapcar (lambda(l)
10158 (let ((ll (car l)))
10159 (when (and (string-match "^id:\\(.+\\)$" ll)
10160 (equal f (expand-file-name
10161 (or (org-id-find-id-file
10162 (match-string 1 ll)) ""))))
10163 ll)))
10164 org-stored-links)))
10165 (mapcar (lambda(l)
10166 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10167 (delq nil (append a b)))))
10169 (defvar org-link-links-in-this-file nil)
10170 (defun org-insert-link (&optional complete-file link-location default-description)
10171 "Insert a link. At the prompt, enter the link.
10173 Completion can be used to insert any of the link protocol prefixes like
10174 http or ftp in use.
10176 The history can be used to select a link previously stored with
10177 `org-store-link'. When the empty string is entered (i.e. if you just
10178 press RET at the prompt), the link defaults to the most recently
10179 stored link. As SPC triggers completion in the minibuffer, you need to
10180 use M-SPC or C-q SPC to force the insertion of a space character.
10182 You will also be prompted for a description, and if one is given, it will
10183 be displayed in the buffer instead of the link.
10185 If there is already a link at point, this command will allow you to edit link
10186 and description parts.
10188 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10189 be selected using completion. The path to the file will be relative to the
10190 current directory if the file is in the current directory or a subdirectory.
10191 Otherwise, the link will be the absolute path as completed in the minibuffer
10192 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10193 option `org-link-file-path-type'.
10195 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10196 the current directory or below.
10198 With three \\[universal-argument] prefixes, negate the meaning of
10199 `org-keep-stored-link-after-insertion'.
10201 If `org-make-link-description-function' is non-nil, this function will be
10202 called with the link target, and the result will be the default
10203 link description.
10205 If the LINK-LOCATION parameter is non-nil, this value will be
10206 used as the link location instead of reading one interactively.
10208 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10209 be used as the default description."
10210 (interactive "P")
10211 (let* ((wcf (current-window-configuration))
10212 (origbuf (current-buffer))
10213 (region (if (org-region-active-p)
10214 (buffer-substring (region-beginning) (region-end))))
10215 (remove (and region (list (region-beginning) (region-end))))
10216 (desc region)
10217 tmphist ; byte-compile incorrectly complains about this
10218 (link link-location)
10219 (abbrevs org-link-abbrev-alist-local)
10220 entry file all-prefixes auto-desc)
10221 (cond
10222 (link-location) ; specified by arg, just use it.
10223 ((org-in-regexp org-bracket-link-regexp 1)
10224 ;; We do have a link at point, and we are going to edit it.
10225 (setq remove (list (match-beginning 0) (match-end 0)))
10226 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10227 (setq link (read-string "Link: "
10228 (org-link-unescape
10229 (org-match-string-no-properties 1)))))
10230 ((or (org-in-regexp org-angle-link-re)
10231 (org-in-regexp org-plain-link-re))
10232 ;; Convert to bracket link
10233 (setq remove (list (match-beginning 0) (match-end 0))
10234 link (read-string "Link: "
10235 (org-remove-angle-brackets (match-string 0)))))
10236 ((member complete-file '((4) (16)))
10237 ;; Completing read for file names.
10238 (setq link (org-file-complete-link complete-file)))
10240 ;; Read link, with completion for stored links.
10241 (org-link-fontify-links-to-this-file)
10242 (org-switch-to-buffer-other-window "*Org Links*")
10243 (with-current-buffer "*Org Links*"
10244 (erase-buffer)
10245 (insert "Insert a link.
10246 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10247 (when org-stored-links
10248 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10249 (insert (mapconcat 'org-link-prettify
10250 (reverse org-stored-links) "\n")))
10251 (goto-char (point-min)))
10252 (let ((cw (selected-window)))
10253 (select-window (get-buffer-window "*Org Links*" 'visible))
10254 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10255 (unless (pos-visible-in-window-p (point-max))
10256 (org-fit-window-to-buffer))
10257 (and (window-live-p cw) (select-window cw)))
10258 ;; Fake a link history, containing the stored links.
10259 (setq tmphist (append (mapcar 'car org-stored-links)
10260 org-insert-link-history))
10261 (setq all-prefixes (append (mapcar 'car abbrevs)
10262 (mapcar 'car org-link-abbrev-alist)
10263 org-link-types))
10264 (unwind-protect
10265 (progn
10266 (setq link
10267 (org-completing-read
10268 "Link: "
10269 (append
10270 (mapcar (lambda (x) (concat x ":"))
10271 all-prefixes)
10272 (mapcar 'car org-stored-links))
10273 nil nil nil
10274 'tmphist
10275 (caar org-stored-links)))
10276 (if (not (string-match "\\S-" link))
10277 (user-error "No link selected"))
10278 (mapc (lambda(l)
10279 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10280 org-stored-links)
10281 (if (or (member link all-prefixes)
10282 (and (equal ":" (substring link -1))
10283 (member (substring link 0 -1) all-prefixes)
10284 (setq link (substring link 0 -1))))
10285 (setq link (with-current-buffer origbuf
10286 (org-link-try-special-completion link)))))
10287 (set-window-configuration wcf)
10288 (kill-buffer "*Org Links*"))
10289 (setq entry (assoc link org-stored-links))
10290 (or entry (push link org-insert-link-history))
10291 (setq desc (or desc (nth 1 entry)))))
10293 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10294 (not org-keep-stored-link-after-insertion))
10295 (setq org-stored-links (delq (assoc link org-stored-links)
10296 org-stored-links)))
10298 (if (and (string-match org-plain-link-re link)
10299 (not (string-match org-ts-regexp link)))
10300 ;; URL-like link, normalize the use of angular brackets.
10301 (setq link (org-remove-angle-brackets link)))
10303 ;; Check if we are linking to the current file with a search
10304 ;; option If yes, simplify the link by using only the search
10305 ;; option.
10306 (when (and buffer-file-name
10307 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10308 (let* ((path (match-string 1 link))
10309 (case-fold-search nil)
10310 (search (match-string 2 link)))
10311 (save-match-data
10312 (if (equal (file-truename buffer-file-name) (file-truename path))
10313 ;; We are linking to this same file, with a search option
10314 (setq link search)))))
10316 ;; Check if we can/should use a relative path. If yes, simplify the link
10317 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10318 (let* ((type (match-string 1 link))
10319 (path (match-string 2 link))
10320 (origpath path)
10321 (case-fold-search nil))
10322 (cond
10323 ((or (eq org-link-file-path-type 'absolute)
10324 (equal complete-file '(16)))
10325 (setq path (abbreviate-file-name (expand-file-name path))))
10326 ((eq org-link-file-path-type 'noabbrev)
10327 (setq path (expand-file-name path)))
10328 ((eq org-link-file-path-type 'relative)
10329 (setq path (file-relative-name path)))
10331 (save-match-data
10332 (if (string-match (concat "^" (regexp-quote
10333 (expand-file-name
10334 (file-name-as-directory
10335 default-directory))))
10336 (expand-file-name path))
10337 ;; We are linking a file with relative path name.
10338 (setq path (substring (expand-file-name path)
10339 (match-end 0)))
10340 (setq path (abbreviate-file-name (expand-file-name path)))))))
10341 (setq link (concat type path))
10342 (if (equal desc origpath)
10343 (setq desc path))))
10345 (if org-make-link-description-function
10346 (setq desc
10347 (or (condition-case nil
10348 (funcall org-make-link-description-function link desc)
10349 (error (progn (message "Can't get link description from `%s'"
10350 (symbol-name org-make-link-description-function))
10351 (sit-for 2) nil)))
10352 (read-string "Description: " default-description)))
10353 (if default-description (setq desc default-description)
10354 (setq desc (or (and auto-desc desc)
10355 (read-string "Description: " desc)))))
10357 (unless (string-match "\\S-" desc) (setq desc nil))
10358 (if remove (apply 'delete-region remove))
10359 (insert (org-make-link-string link desc))))
10361 (defun org-link-try-special-completion (type)
10362 "If there is completion support for link type TYPE, offer it."
10363 (let ((fun (intern (concat "org-" type "-complete-link"))))
10364 (if (functionp fun)
10365 (funcall fun)
10366 (read-string "Link (no completion support): " (concat type ":")))))
10368 (defun org-file-complete-link (&optional arg)
10369 "Create a file link using completion."
10370 (let (file link)
10371 (setq file (org-iread-file-name "File: "))
10372 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10373 (pwd1 (file-name-as-directory (abbreviate-file-name
10374 (expand-file-name ".")))))
10375 (cond
10376 ((equal arg '(16))
10377 (setq link (concat
10378 "file:"
10379 (abbreviate-file-name (expand-file-name file)))))
10380 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10381 (setq link (concat "file:" (match-string 1 file))))
10382 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10383 (expand-file-name file))
10384 (setq link (concat
10385 "file:" (match-string 1 (expand-file-name file)))))
10386 (t (setq link (concat "file:" file)))))
10387 link))
10389 (defun org-iread-file-name (&rest args)
10390 "Read-file-name using `ido-mode' speedup if available.
10391 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10392 See `read-file-name' for a description of parameters."
10393 (org-without-partial-completion
10394 (if (and org-completion-use-ido
10395 (fboundp 'ido-read-file-name)
10396 (boundp 'ido-mode) ido-mode
10397 (listp (second args)))
10398 (let ((ido-enter-matching-directory nil))
10399 (apply 'ido-read-file-name args))
10400 (apply 'read-file-name args))))
10402 (defun org-completing-read (&rest args)
10403 "Completing-read with SPACE being a normal character."
10404 (let ((enable-recursive-minibuffers t)
10405 (minibuffer-local-completion-map
10406 (copy-keymap minibuffer-local-completion-map)))
10407 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10408 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10409 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10410 (apply 'org-icompleting-read args)))
10412 (defun org-completing-read-no-i (&rest args)
10413 (let (org-completion-use-ido org-completion-use-iswitchb)
10414 (apply 'org-completing-read args)))
10416 (defun org-iswitchb-completing-read (prompt choices &rest args)
10417 "Use iswitch as a completing-read replacement to choose from choices.
10418 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10419 from."
10420 (let* ((iswitchb-use-virtual-buffers nil)
10421 (iswitchb-make-buflist-hook
10422 (lambda ()
10423 (setq iswitchb-temp-buflist choices))))
10424 (iswitchb-read-buffer prompt)))
10426 (defun org-icompleting-read (&rest args)
10427 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10428 (org-without-partial-completion
10429 (if (and org-completion-use-ido
10430 (fboundp 'ido-completing-read)
10431 (boundp 'ido-mode) ido-mode
10432 (listp (second args)))
10433 (let ((ido-enter-matching-directory nil))
10434 (apply 'ido-completing-read (concat (car args))
10435 (if (consp (car (nth 1 args)))
10436 (mapcar 'car (nth 1 args))
10437 (nth 1 args))
10438 (cddr args)))
10439 (if (and org-completion-use-iswitchb
10440 (boundp 'iswitchb-mode) iswitchb-mode
10441 (listp (second args)))
10442 (apply 'org-iswitchb-completing-read (concat (car args))
10443 (if (consp (car (nth 1 args)))
10444 (mapcar 'car (nth 1 args))
10445 (nth 1 args))
10446 (cddr args))
10447 (apply 'completing-read args)))))
10449 (defun org-extract-attributes (s)
10450 "Extract the attributes cookie from a string and set as text property."
10451 (let (a attr (start 0) key value)
10452 (save-match-data
10453 (when (string-match "{{\\([^}]+\\)}}$" s)
10454 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10455 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10456 (setq key (match-string 1 a) value (match-string 2 a)
10457 start (match-end 0)
10458 attr (plist-put attr (intern key) value))))
10459 (org-add-props s nil 'org-attr attr))
10462 ;;; Opening/following a link
10464 (defvar org-link-search-failed nil)
10466 (defvar org-open-link-functions nil
10467 "Hook for functions finding a plain text link.
10468 These functions must take a single argument, the link content.
10469 They will be called for links that look like [[link text][description]]
10470 when LINK TEXT does not have a protocol like \"http:\" and does not look
10471 like a filename (e.g. \"./blue.png\").
10473 These functions will be called *before* Org attempts to resolve the
10474 link by doing text searches in the current buffer - so if you want a
10475 link \"[[target]]\" to still find \"<<target>>\", your function should
10476 handle this as a special case.
10478 When the function does handle the link, it must return a non-nil value.
10479 If it decides that it is not responsible for this link, it must return
10480 nil to indicate that that Org-mode can continue with other options
10481 like exact and fuzzy text search.")
10483 (defun org-next-link (&optional search-backward)
10484 "Move forward to the next link.
10485 If the link is in hidden text, expose it."
10486 (interactive "P")
10487 (when (and org-link-search-failed (eq this-command last-command))
10488 (goto-char (point-min))
10489 (message "Link search wrapped back to beginning of buffer"))
10490 (setq org-link-search-failed nil)
10491 (let* ((pos (point))
10492 (ct (org-context))
10493 (a (assoc :link ct))
10494 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10495 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10496 ((looking-at org-any-link-re)
10497 ;; Don't stay stuck at link without an org-link face
10498 (forward-char (if search-backward -1 1))))
10499 (if (funcall srch-fun org-any-link-re nil t)
10500 (progn
10501 (goto-char (match-beginning 0))
10502 (if (outline-invisible-p) (org-show-context)))
10503 (goto-char pos)
10504 (setq org-link-search-failed t)
10505 (message "No further link found"))))
10507 (defun org-previous-link ()
10508 "Move backward to the previous link.
10509 If the link is in hidden text, expose it."
10510 (interactive)
10511 (funcall 'org-next-link t))
10513 (defun org-translate-link (s)
10514 "Translate a link string if a translation function has been defined."
10515 (if (and org-link-translation-function
10516 (fboundp org-link-translation-function)
10517 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10518 (progn
10519 (setq s (funcall org-link-translation-function
10520 (match-string 1 s) (match-string 2 s)))
10521 (concat (car s) ":" (cdr s)))
10524 (defun org-translate-link-from-planner (type path)
10525 "Translate a link from Emacs Planner syntax so that Org can follow it.
10526 This is still an experimental function, your mileage may vary."
10527 (cond
10528 ((member type '("http" "https" "news" "ftp"))
10529 ;; standard Internet links are the same.
10530 nil)
10531 ((and (equal type "irc") (string-match "^//" path))
10532 ;; Planner has two / at the beginning of an irc link, we have 1.
10533 ;; We should have zero, actually....
10534 (setq path (substring path 1)))
10535 ((and (equal type "lisp") (string-match "^/" path))
10536 ;; Planner has a slash, we do not.
10537 (setq type "elisp" path (substring path 1)))
10538 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10539 ;; A typical message link. Planner has the id after the final slash,
10540 ;; we separate it with a hash mark
10541 (setq path (concat (match-string 1 path) "#"
10542 (org-remove-angle-brackets (match-string 2 path))))))
10543 (cons type path))
10545 (defun org-find-file-at-mouse (ev)
10546 "Open file link or URL at mouse."
10547 (interactive "e")
10548 (mouse-set-point ev)
10549 (org-open-at-point 'in-emacs))
10551 (defun org-open-at-mouse (ev)
10552 "Open file link or URL at mouse.
10553 See the docstring of `org-open-file' for details."
10554 (interactive "e")
10555 (mouse-set-point ev)
10556 (if (eq major-mode 'org-agenda-mode)
10557 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10558 (org-open-at-point))
10560 (defvar org-window-config-before-follow-link nil
10561 "The window configuration before following a link.
10562 This is saved in case the need arises to restore it.")
10564 (defvar org-open-link-marker (make-marker)
10565 "Marker pointing to the location where `org-open-at-point' was called.")
10567 ;;;###autoload
10568 (defun org-open-at-point-global ()
10569 "Follow a link like Org-mode does.
10570 This command can be called in any mode to follow a link that has
10571 Org-mode syntax."
10572 (interactive)
10573 (org-run-like-in-org-mode 'org-open-at-point))
10575 ;;;###autoload
10576 (defun org-open-link-from-string (s &optional arg reference-buffer)
10577 "Open a link in the string S, as if it was in Org-mode."
10578 (interactive "sLink: \nP")
10579 (let ((reference-buffer (or reference-buffer (current-buffer))))
10580 (with-temp-buffer
10581 (let ((org-inhibit-startup (not reference-buffer)))
10582 (org-mode)
10583 (insert s)
10584 (goto-char (point-min))
10585 (when reference-buffer
10586 (setq org-link-abbrev-alist-local
10587 (with-current-buffer reference-buffer
10588 org-link-abbrev-alist-local)))
10589 (org-open-at-point arg reference-buffer)))))
10591 (defvar org-open-at-point-functions nil
10592 "Hook that is run when following a link at point.
10594 Functions in this hook must return t if they identify and follow
10595 a link at point. If they don't find anything interesting at point,
10596 they must return nil.")
10598 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10599 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10600 (defun org-open-at-point (&optional arg reference-buffer)
10601 "Open link, timestamp, footnote or tags at point.
10603 When point is on a link, follow it. Normally, files will be
10604 opened by an appropriate application. If the optional prefix
10605 argument ARG is non-nil, Emacs will visit the file. With
10606 a double prefix argument, try to open outside of Emacs, in the
10607 application the system uses for this file type.
10609 When point is on a timestamp, open the agenda at the day
10610 specified.
10612 When point is a footnote definition, move to the first reference
10613 found. If it is on a reference, move to the associated
10614 definition.
10616 When point is on a headline, display a list of every link in the
10617 entry, so it is possible to pick one, or all, of them. If point
10618 is on a tag, call `org-tags-view' instead.
10620 When optional argument REFERENCE-BUFFER is non-nil, it should
10621 specify a buffer from where the link search should happen. This
10622 is used internally by `org-open-link-from-string'.
10624 On top of syntactically correct links, this function will open
10625 the link at point in comments and the first link in a property
10626 drawer line."
10627 (interactive "P")
10628 ;; On a code block, open block's results.
10629 (unless (call-interactively 'org-babel-open-src-block-result)
10630 (org-load-modules-maybe)
10631 (move-marker org-open-link-marker (point))
10632 (setq org-window-config-before-follow-link (current-window-configuration))
10633 (org-remove-occur-highlights nil nil t)
10634 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10635 (let* ((context (org-element-context)) type value)
10636 ;; On an unsupported type, check if point is contained within
10637 ;; a support one.
10638 (while (and (not (memq (setq type (org-element-type context))
10639 '(comment 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 ((eq type 'comment)
10654 (let ((string-rear (replace-regexp-in-string
10655 "^[ \t]*# [ \t]*" ""
10656 (buffer-substring (point) (line-beginning-position))))
10657 (string-front (buffer-substring (point) (line-end-position))))
10658 (with-temp-buffer
10659 (let ((org-inhibit-startup t)) (org-mode))
10660 (insert value)
10661 (goto-char (point-min))
10662 (when (and (search-forward string-rear nil t)
10663 (search-forward string-front (line-end-position) t))
10664 (goto-char (match-beginning 0))
10665 (org-open-at-point)
10666 (when (string= string-rear "") (forward-char))))))
10667 ;; On a headline or an inlinetask, but not on a timestamp,
10668 ;; a link, a footnote reference or on tags.
10669 ((and (memq type '(headline inlinetask))
10670 ;; Not on tags.
10671 (progn (save-excursion (beginning-of-line)
10672 (looking-at org-complex-heading-regexp))
10673 (or (not (match-beginning 5))
10674 (< (point) (match-beginning 5)))))
10675 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10676 (links (car data))
10677 (links-end (cdr data)))
10678 (if links
10679 (dolist (link (if (stringp links) (list links) links))
10680 (search-forward link nil links-end)
10681 (goto-char (match-beginning 0))
10682 (org-open-at-point))
10683 (require 'org-attach)
10684 (org-attach-reveal 'if-exists))))
10685 ;; Do nothing on white spaces after an object, unless point
10686 ;; is right after it.
10687 ((> (point)
10688 (save-excursion
10689 (goto-char (org-element-property :end context))
10690 (skip-chars-backward " \t")
10691 (point)))
10692 (user-error "No link found"))
10693 ((eq type 'timestamp) (org-follow-timestamp-link))
10694 ;; On tags within a headline or an inlinetask.
10695 ((and (memq type '(headline inlinetask))
10696 (progn (save-excursion (beginning-of-line)
10697 (looking-at org-complex-heading-regexp))
10698 (and (match-beginning 5)
10699 (>= (point) (match-beginning 5)))))
10700 (org-tags-view arg (substring (match-string 5) 0 -1)))
10701 ((eq type 'link)
10702 (let ((type (org-element-property :type context))
10703 (path (org-link-unescape (org-element-property :path context))))
10704 ;; Switch back to REFERENCE-BUFFER needed when called in
10705 ;; a temporary buffer through `org-open-link-from-string'.
10706 (with-current-buffer (or reference-buffer (current-buffer))
10707 (cond
10708 ((equal type "file")
10709 (if (string-match "[*?{]" (file-name-nondirectory path))
10710 (dired path)
10711 ;; Look into `org-link-protocols' in order to find
10712 ;; a DEDICATED-FUNCTION to open file. The function
10713 ;; will be applied on raw link instead of parsed
10714 ;; link due to the limitation in `org-add-link-type'
10715 ;; ("open" function called with a single argument).
10716 ;; If no such function is found, fallback to
10717 ;; `org-open-file'.
10719 ;; Note : "file+emacs" and "file+sys" types are
10720 ;; hard-coded in order to escape the previous
10721 ;; limitation.
10722 (let* ((option (org-element-property :search-option context))
10723 (app (org-element-property :application context))
10724 (dedicated-function
10725 (nth 1 (assoc app org-link-protocols))))
10726 (if dedicated-function
10727 (funcall dedicated-function
10728 (concat path
10729 (and option (concat "::" option))))
10730 (apply 'org-open-file
10731 path
10732 (cond (arg)
10733 ((equal app "emacs") 'emacs)
10734 ((equal app "sys") 'system))
10735 (cond ((not option) nil)
10736 ((org-string-match-p "\\`[0-9]+\\'" option)
10737 (list (string-to-number option)))
10738 (t (list nil
10739 (org-link-unescape option)))))))))
10740 ((assoc type org-link-protocols)
10741 (funcall (nth 1 (assoc type org-link-protocols)) path))
10742 ((equal type "help")
10743 (let ((f-or-v (intern path)))
10744 (cond ((fboundp f-or-v) (describe-function f-or-v))
10745 ((boundp f-or-v) (describe-variable f-or-v))
10746 (t (error "Not a known function or variable")))))
10747 ((member type '("http" "https" "ftp" "mailto" "news"))
10748 (browse-url (org-link-escape-browser (concat type ":" path))))
10749 ((equal type "doi")
10750 (browse-url
10751 (org-link-escape-browser (concat org-doi-server-url path))))
10752 ((equal type "message") (browse-url (concat type ":" path)))
10753 ((equal type "shell")
10754 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10755 (cmd path))
10756 (if (or (and (org-string-nw-p
10757 org-confirm-shell-link-not-regexp)
10758 (string-match
10759 org-confirm-shell-link-not-regexp cmd))
10760 (not org-confirm-shell-link-function)
10761 (funcall org-confirm-shell-link-function
10762 (format "Execute \"%s\" in shell? "
10763 (org-add-props cmd nil
10764 'face 'org-warning))))
10765 (progn
10766 (message "Executing %s" cmd)
10767 (shell-command cmd buf)
10768 (when (featurep 'midnight)
10769 (setq clean-buffer-list-kill-buffer-names
10770 (cons buf
10771 clean-buffer-list-kill-buffer-names))))
10772 (user-error "Abort"))))
10773 ((equal type "elisp")
10774 (let ((cmd path))
10775 (if (or (and (org-string-nw-p
10776 org-confirm-elisp-link-not-regexp)
10777 (org-string-match-p
10778 org-confirm-elisp-link-not-regexp cmd))
10779 (not org-confirm-elisp-link-function)
10780 (funcall org-confirm-elisp-link-function
10781 (format "Execute \"%s\" as elisp? "
10782 (org-add-props cmd nil
10783 'face 'org-warning))))
10784 (message "%s => %s" cmd
10785 (if (eq (string-to-char cmd) ?\()
10786 (eval (read cmd))
10787 (call-interactively (read cmd))))
10788 (user-error "Abort"))))
10789 ((equal type "id")
10790 (require 'ord-id)
10791 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10792 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10793 (unless (run-hook-with-args-until-success
10794 'org-open-link-functions path)
10795 (if (not arg) (org-mark-ring-push)
10796 (switch-to-buffer-other-window
10797 (org-get-buffer-for-internal-link (current-buffer))))
10798 (let ((cmd `(org-link-search
10799 ,(if (member type '("custom-id" "coderef"))
10800 (org-element-property :raw-link context)
10801 path)
10802 ,(cond ((equal arg '(4)) 'occur)
10803 ((equal arg '(16)) 'org-occur))
10804 ,(org-element-property :begin context))))
10805 (condition-case nil
10806 (let ((org-link-search-inhibit-query t))
10807 (eval cmd))
10808 (error (progn (widen) (eval cmd)))))))
10809 (t (browse-url-at-point))))))
10810 ;; On a footnote reference or at a footnote definition's label.
10811 ((or (eq type 'footnote-reference)
10812 (and (eq type 'footnote-definition)
10813 (save-excursion
10814 ;; Do not validate action when point is on the
10815 ;; spaces right after the footnote label, in
10816 ;; order to be on par with behaviour on links.
10817 (skip-chars-forward " \t")
10818 (let ((begin
10819 (org-element-property :contents-begin context)))
10820 (if begin (< (point) begin)
10821 (= (org-element-property :post-affiliated context)
10822 (line-beginning-position)))))))
10823 (org-footnote-action))
10824 (t (user-error "No link found")))))
10825 (move-marker org-open-link-marker nil)
10826 (run-hook-with-args 'org-follow-link-hook)))
10828 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10829 "Offer links in the current entry and return the selected link.
10830 If there is only one link, return it.
10831 If NTH is an integer, return the NTH link found.
10832 If ZERO is a string, check also this string for a link, and if
10833 there is one, return it."
10834 (with-current-buffer buffer
10835 (save-excursion
10836 (save-restriction
10837 (widen)
10838 (goto-char marker)
10839 (let ((cnt ?0)
10840 (in-emacs (if (integerp nth) nil nth))
10841 have-zero end links link c)
10842 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10843 (push (match-string 0 zero) links)
10844 (setq cnt (1- cnt) have-zero t))
10845 (save-excursion
10846 (org-back-to-heading t)
10847 (setq end (save-excursion (outline-next-heading) (point)))
10848 (while (re-search-forward org-any-link-re end t)
10849 (push (match-string 0) links))
10850 (setq links (org-uniquify (reverse links))))
10851 (cond
10852 ((null links)
10853 (message "No links"))
10854 ((equal (length links) 1)
10855 (setq link (car links)))
10856 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10857 (setq link (nth (if have-zero nth (1- nth)) links)))
10858 (t ; we have to select a link
10859 (save-excursion
10860 (save-window-excursion
10861 (delete-other-windows)
10862 (with-output-to-temp-buffer "*Select Link*"
10863 (mapc (lambda (l)
10864 (if (not (string-match org-bracket-link-regexp l))
10865 (princ (format "[%c] %s\n" (incf cnt)
10866 (org-remove-angle-brackets l)))
10867 (if (match-end 3)
10868 (princ (format "[%c] %s (%s)\n" (incf cnt)
10869 (match-string 3 l) (match-string 1 l)))
10870 (princ (format "[%c] %s\n" (incf cnt)
10871 (match-string 1 l))))))
10872 links))
10873 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10874 (message "Select link to open, RET to open all:")
10875 (setq c (read-char-exclusive))
10876 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10877 (when (equal c ?q) (user-error "Abort"))
10878 (if (equal c ?\C-m)
10879 (setq link links)
10880 (setq nth (- c ?0))
10881 (if have-zero (setq nth (1+ nth)))
10882 (unless (and (integerp nth) (>= (length links) nth))
10883 (user-error "Invalid link selection"))
10884 (setq link (nth (1- nth) links)))))
10885 (cons link end))))))
10887 ;; TODO: These functions are deprecated since `org-open-at-point'
10888 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10889 (defun org-open-file-with-system (path)
10890 "Open file at PATH using the system way of opening it."
10891 (org-open-file path 'system))
10892 (defun org-open-file-with-emacs (path)
10893 "Open file at PATH in Emacs."
10894 (org-open-file path 'emacs))
10897 ;;; File search
10899 (defvar org-create-file-search-functions nil
10900 "List of functions to construct the right search string for a file link.
10901 These functions are called in turn with point at the location to
10902 which the link should point.
10904 A function in the hook should first test if it would like to
10905 handle this file type, for example by checking the `major-mode'
10906 or the file extension. If it decides not to handle this file, it
10907 should just return nil to give other functions a chance. If it
10908 does handle the file, it must return the search string to be used
10909 when following the link. The search string will be part of the
10910 file link, given after a double colon, and `org-open-at-point'
10911 will automatically search for it. If special measures must be
10912 taken to make the search successful, another function should be
10913 added to the companion hook `org-execute-file-search-functions',
10914 which see.
10916 A function in this hook may also use `setq' to set the variable
10917 `description' to provide a suggestion for the descriptive text to
10918 be used for this link when it gets inserted into an Org-mode
10919 buffer with \\[org-insert-link].")
10921 (defvar org-execute-file-search-functions nil
10922 "List of functions to execute a file search triggered by a link.
10924 Functions added to this hook must accept a single argument, the
10925 search string that was part of the file link, the part after the
10926 double colon. The function must first check if it would like to
10927 handle this search, for example by checking the `major-mode' or
10928 the file extension. If it decides not to handle this search, it
10929 should just return nil to give other functions a chance. If it
10930 does handle the search, it must return a non-nil value to keep
10931 other functions from trying.
10933 Each function can access the current prefix argument through the
10934 variable `current-prefix-arg'. Note that a single prefix is used
10935 to force opening a link in Emacs, so it may be good to only use a
10936 numeric or double prefix to guide the search function.
10938 In case this is needed, a function in this hook can also restore
10939 the window configuration before `org-open-at-point' was called using:
10941 (set-window-configuration org-window-config-before-follow-link)")
10943 (defun org-link-search (s &optional type avoid-pos stealth)
10944 "Search for a link search option.
10945 If S is surrounded by forward slashes, it is interpreted as a
10946 regular expression. In org-mode files, this will create an `org-occur'
10947 sparse tree. In ordinary files, `occur' will be used to list matches.
10948 If the current buffer is in `dired-mode', grep will be used to search
10949 in all files. If AVOID-POS is given, ignore matches near that position.
10951 When optional argument STEALTH is non-nil, do not modify
10952 visibility around point, thus ignoring
10953 `org-show-hierarchy-above', `org-show-following-heading' and
10954 `org-show-siblings' variables."
10955 (let ((case-fold-search t)
10956 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10957 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10958 (append '(("") (" ") ("\t") ("\n"))
10959 org-emphasis-alist)
10960 "\\|") "\\)"))
10961 (pos (point))
10962 (pre nil) (post nil)
10963 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10964 (cond
10965 ;; First check if there are any special search functions
10966 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10967 ;; Now try the builtin stuff
10968 ((and (equal (string-to-char s0) ?#)
10969 (> (length s0) 1)
10970 (save-excursion
10971 (goto-char (point-min))
10972 (and
10973 (re-search-forward
10974 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10975 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10976 (setq type 'dedicated
10977 pos (match-beginning 0))))
10978 ;; There is an exact target for this
10979 (goto-char pos)
10980 (org-back-to-heading t)))
10981 ((save-excursion
10982 (goto-char (point-min))
10983 (and
10984 (re-search-forward
10985 (concat "<<" (regexp-quote s0) ">>") nil t)
10986 (setq type 'dedicated
10987 pos (match-beginning 0))))
10988 ;; There is an exact target for this
10989 (goto-char pos))
10990 ((save-excursion
10991 (goto-char (point-min))
10992 (and
10993 (re-search-forward
10994 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10995 (setq type 'dedicated pos (match-beginning 0))))
10996 ;; Found an element with a matching #+name affiliated keyword.
10997 (goto-char pos))
10998 ((and (string-match "^(\\(.*\\))$" s0)
10999 (save-excursion
11000 (goto-char (point-min))
11001 (and
11002 (re-search-forward
11003 (concat "[^[]" (regexp-quote
11004 (format org-coderef-label-format
11005 (match-string 1 s0))))
11006 nil t)
11007 (setq type 'dedicated
11008 pos (1+ (match-beginning 0))))))
11009 ;; There is a coderef target for this
11010 (goto-char pos))
11011 ((string-match "^/\\(.*\\)/$" s)
11012 ;; A regular expression
11013 (cond
11014 ((derived-mode-p 'org-mode)
11015 (org-occur (match-string 1 s)))
11016 (t (org-do-occur (match-string 1 s)))))
11017 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11018 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11019 (goto-char (point-min))
11020 (cond
11021 ((let (case-fold-search)
11022 (re-search-forward (format org-complex-heading-regexp-format
11023 (regexp-quote s))
11024 nil t))
11025 ;; OK, found a match
11026 (setq type 'dedicated)
11027 (goto-char (match-beginning 0)))
11028 ((and (not org-link-search-inhibit-query)
11029 (eq org-link-search-must-match-exact-headline 'query-to-create)
11030 (y-or-n-p "No match - create this as a new heading? "))
11031 (goto-char (point-max))
11032 (or (bolp) (newline))
11033 (insert "* " s "\n")
11034 (beginning-of-line 0))
11036 (goto-char pos)
11037 (error "No match"))))
11039 ;; A normal search string
11040 (when (equal (string-to-char s) ?*)
11041 ;; Anchor on headlines, post may include tags.
11042 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11043 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11044 s (substring s 1)))
11045 (remove-text-properties
11046 0 (length s)
11047 '(face nil mouse-face nil keymap nil fontified nil) s)
11048 ;; Make a series of regular expressions to find a match
11049 (setq words (org-split-string s "[ \n\r\t]+")
11051 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11052 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11053 "\\)" markers)
11054 re2a_ (concat "\\(" (mapconcat 'downcase words
11055 "[ \t\r\n]+") "\\)[ \t\r\n]")
11056 re2a (concat "[ \t\r\n]" re2a_)
11057 re4_ (concat "\\(" (mapconcat 'downcase words
11058 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11059 re4 (concat "[^a-zA-Z_]" re4_)
11061 re1 (concat pre re2 post)
11062 re3 (concat pre (if pre re4_ re4) post)
11063 re5 (concat pre ".*" re4)
11064 re2 (concat pre re2)
11065 re2a (concat pre (if pre re2a_ re2a))
11066 re4 (concat pre (if pre re4_ re4))
11067 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11068 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11069 re5 "\\)"))
11070 (cond
11071 ((eq type 'org-occur) (org-occur reall))
11072 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11073 (t (goto-char (point-min))
11074 (setq type 'fuzzy)
11075 (if (or (and (org-search-not-self 1 re0 nil t)
11076 (setq type 'dedicated))
11077 (org-search-not-self 1 re1 nil t)
11078 (org-search-not-self 1 re2 nil t)
11079 (org-search-not-self 1 re2a nil t)
11080 (org-search-not-self 1 re3 nil t)
11081 (org-search-not-self 1 re4 nil t)
11082 (org-search-not-self 1 re5 nil t))
11083 (goto-char (match-beginning 1))
11084 (goto-char pos)
11085 (error "No match"))))))
11086 (and (derived-mode-p 'org-mode)
11087 (not stealth)
11088 (org-show-context 'link-search))
11089 type))
11091 (defun org-search-not-self (group &rest args)
11092 "Execute `re-search-forward', but only accept matches that do not
11093 enclose the position of `org-open-link-marker'."
11094 (let ((m org-open-link-marker))
11095 (catch 'exit
11096 (while (apply 're-search-forward args)
11097 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11098 (goto-char (match-end group))
11099 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11100 (> (match-beginning 0) (marker-position m))
11101 (< (match-end 0) (marker-position m)))
11102 (save-match-data
11103 (or (not (org-in-regexp
11104 org-bracket-link-analytic-regexp 1))
11105 (not (match-end 4)) ; no description
11106 (and (<= (match-beginning 4) (point))
11107 (>= (match-end 4) (point))))))
11108 (throw 'exit (point))))))))
11110 (defun org-get-buffer-for-internal-link (buffer)
11111 "Return a buffer to be used for displaying the link target of internal links."
11112 (cond
11113 ((not org-display-internal-link-with-indirect-buffer)
11114 buffer)
11115 ((string-match "(Clone)$" (buffer-name buffer))
11116 (message "Buffer is already a clone, not making another one")
11117 ;; we also do not modify visibility in this case
11118 buffer)
11119 (t ; make a new indirect buffer for displaying the link
11120 (let* ((bn (buffer-name buffer))
11121 (ibn (concat bn "(Clone)"))
11122 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11123 (with-current-buffer ib (org-overview))
11124 ib))))
11126 (defun org-do-occur (regexp &optional cleanup)
11127 "Call the Emacs command `occur'.
11128 If CLEANUP is non-nil, remove the printout of the regular expression
11129 in the *Occur* buffer. This is useful if the regex is long and not useful
11130 to read."
11131 (occur regexp)
11132 (when cleanup
11133 (let ((cwin (selected-window)) win beg end)
11134 (when (setq win (get-buffer-window "*Occur*"))
11135 (select-window win))
11136 (goto-char (point-min))
11137 (when (re-search-forward "match[a-z]+" nil t)
11138 (setq beg (match-end 0))
11139 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11140 (setq end (1- (match-beginning 0)))))
11141 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11142 (goto-char (point-min))
11143 (select-window cwin))))
11145 ;;; The mark ring for links jumps
11147 (defvar org-mark-ring nil
11148 "Mark ring for positions before jumps in Org-mode.")
11149 (defvar org-mark-ring-last-goto nil
11150 "Last position in the mark ring used to go back.")
11151 ;; Fill and close the ring
11152 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11153 (loop for i from 1 to org-mark-ring-length do
11154 (push (make-marker) org-mark-ring))
11155 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11156 org-mark-ring)
11158 (defun org-mark-ring-push (&optional pos buffer)
11159 "Put the current position or POS into the mark ring and rotate it."
11160 (interactive)
11161 (setq pos (or pos (point)))
11162 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11163 (move-marker (car org-mark-ring)
11164 (or pos (point))
11165 (or buffer (current-buffer)))
11166 (message "%s"
11167 (substitute-command-keys
11168 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11170 (defun org-mark-ring-goto (&optional n)
11171 "Jump to the previous position in the mark ring.
11172 With prefix arg N, jump back that many stored positions. When
11173 called several times in succession, walk through the entire ring.
11174 Org-mode commands jumping to a different position in the current file,
11175 or to another Org-mode file, automatically push the old position
11176 onto the ring."
11177 (interactive "p")
11178 (let (p m)
11179 (if (eq last-command this-command)
11180 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11181 (setq p org-mark-ring))
11182 (setq org-mark-ring-last-goto p)
11183 (setq m (car p))
11184 (org-pop-to-buffer-same-window (marker-buffer m))
11185 (goto-char m)
11186 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11188 (defun org-remove-angle-brackets (s)
11189 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11190 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11192 (defun org-add-angle-brackets (s)
11193 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11194 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11196 (defun org-remove-double-quotes (s)
11197 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11198 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11201 ;;; Following specific links
11203 (defun org-follow-timestamp-link ()
11204 "Open an agenda view for the time-stamp date/range at point."
11205 (cond
11206 ((org-at-date-range-p t)
11207 (let ((org-agenda-start-on-weekday)
11208 (t1 (match-string 1))
11209 (t2 (match-string 2)) tt1 tt2)
11210 (setq tt1 (time-to-days (org-time-string-to-time t1))
11211 tt2 (time-to-days (org-time-string-to-time t2)))
11212 (let ((org-agenda-buffer-tmp-name
11213 (format "*Org Agenda(a:%s)"
11214 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11215 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11216 ((org-at-timestamp-p t)
11217 (let ((org-agenda-buffer-tmp-name
11218 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11219 (org-agenda-list nil (time-to-days (org-time-string-to-time
11220 (substring (match-string 1) 0 10)))
11221 1)))
11222 (t (error "This should not happen"))))
11225 ;;; Following file links
11226 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11227 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11228 (declare-function mailcap-mime-info
11229 "mailcap" (string &optional request no-decode))
11230 (defvar org-wait nil)
11231 (defun org-open-file (path &optional in-emacs line search)
11232 "Open the file at PATH.
11233 First, this expands any special file name abbreviations. Then the
11234 configuration variable `org-file-apps' is checked if it contains an
11235 entry for this file type, and if yes, the corresponding command is launched.
11237 If no application is found, Emacs simply visits the file.
11239 With optional prefix argument IN-EMACS, Emacs will visit the file.
11240 With a double \\[universal-argument] \\[universal-argument] \
11241 prefix arg, Org tries to avoid opening in Emacs
11242 and to use an external application to visit the file.
11244 Optional LINE specifies a line to go to, optional SEARCH a string
11245 to search for. If LINE or SEARCH is given, the file will be
11246 opened in Emacs, unless an entry from org-file-apps that makes
11247 use of groups in a regexp matches.
11249 If you want to change the way frames are used when following a
11250 link, please customize `org-link-frame-setup'.
11252 If the file does not exist, an error is thrown."
11253 (let* ((file (if (equal path "")
11254 buffer-file-name
11255 (substitute-in-file-name (expand-file-name path))))
11256 (file-apps (append org-file-apps (org-default-apps)))
11257 (apps (org-remove-if
11258 'org-file-apps-entry-match-against-dlink-p file-apps))
11259 (apps-dlink (org-remove-if-not
11260 'org-file-apps-entry-match-against-dlink-p file-apps))
11261 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11262 (dirp (if remp nil (file-directory-p file)))
11263 (file (if (and dirp org-open-directory-means-index-dot-org)
11264 (concat (file-name-as-directory file) "index.org")
11265 file))
11266 (a-m-a-p (assq 'auto-mode apps))
11267 (dfile (downcase file))
11268 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11269 (link (cond ((and (eq line nil)
11270 (eq search nil))
11271 file)
11272 (line
11273 (concat file "::" (number-to-string line)))
11274 (search
11275 (concat file "::" search))))
11276 (dlink (downcase link))
11277 (old-buffer (current-buffer))
11278 (old-pos (point))
11279 (old-mode major-mode)
11280 ext cmd link-match-data)
11281 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11282 (setq ext (match-string 1 dfile))
11283 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11284 (setq ext (match-string 1 dfile))))
11285 (cond
11286 ((member in-emacs '((16) system))
11287 (setq cmd (cdr (assoc 'system apps))))
11288 (in-emacs (setq cmd 'emacs))
11290 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11291 (and dirp (cdr (assoc 'directory apps)))
11292 ; first, try matching against apps-dlink
11293 ; if we get a match here, store the match data for later
11294 (let ((match (assoc-default dlink apps-dlink
11295 'string-match)))
11296 (if match
11297 (progn (setq link-match-data (match-data))
11298 match)
11299 (progn (setq in-emacs (or in-emacs line search))
11300 nil))) ; if we have no match in apps-dlink,
11301 ; always open the file in emacs if line or search
11302 ; is given (for backwards compatibility)
11303 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11304 'string-match)
11305 (cdr (assoc ext apps))
11306 (cdr (assoc t apps))))))
11307 (when (eq cmd 'system)
11308 (setq cmd (cdr (assoc 'system apps))))
11309 (when (eq cmd 'default)
11310 (setq cmd (cdr (assoc t apps))))
11311 (when (eq cmd 'mailcap)
11312 (require 'mailcap)
11313 (mailcap-parse-mailcaps)
11314 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11315 (command (mailcap-mime-info mime-type)))
11316 (if (stringp command)
11317 (setq cmd command)
11318 (setq cmd 'emacs))))
11319 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11320 (not (file-exists-p file))
11321 (not org-open-non-existing-files))
11322 (user-error "No such file: %s" file))
11323 (cond
11324 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11325 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11326 (while (string-match "['\"]%s['\"]" cmd)
11327 (setq cmd (replace-match "%s" t t cmd)))
11328 (while (string-match "%s" cmd)
11329 (setq cmd (replace-match
11330 (save-match-data
11331 (shell-quote-argument
11332 (convert-standard-filename file)))
11333 t t cmd)))
11335 ;; Replace "%1", "%2" etc. in command with group matches from regex
11336 (save-match-data
11337 (let ((match-index 1)
11338 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11339 (set-match-data link-match-data)
11340 (while (<= match-index number-of-groups)
11341 (let ((regex (concat "%" (number-to-string match-index)))
11342 (replace-with (match-string match-index dlink)))
11343 (while (string-match regex cmd)
11344 (setq cmd (replace-match replace-with t t cmd))))
11345 (setq match-index (+ match-index 1)))))
11347 (save-window-excursion
11348 (message "Running %s...done" cmd)
11349 (start-process-shell-command cmd nil cmd)
11350 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11351 ((or (stringp cmd)
11352 (eq cmd 'emacs))
11353 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11354 (widen)
11355 (if line (progn (org-goto-line line)
11356 (if (derived-mode-p 'org-mode)
11357 (org-reveal)))
11358 (if search (org-link-search search))))
11359 ((consp cmd)
11360 (let ((file (convert-standard-filename file)))
11361 (save-match-data
11362 (set-match-data link-match-data)
11363 (eval cmd))))
11364 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11365 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11366 (or (not (equal old-buffer (current-buffer)))
11367 (not (equal old-pos (point))))
11368 (org-mark-ring-push old-pos old-buffer))))
11370 (defun org-file-apps-entry-match-against-dlink-p (entry)
11371 "This function returns non-nil if `entry' uses a regular
11372 expression which should be matched against the whole link by
11373 org-open-file.
11375 It assumes that is the case when the entry uses a regular
11376 expression which has at least one grouping construct and the
11377 action is either a lisp form or a command string containing
11378 '%1', i.e. using at least one subexpression match as a
11379 parameter."
11380 (let ((selector (car entry))
11381 (action (cdr entry)))
11382 (if (stringp selector)
11383 (and (> (regexp-opt-depth selector) 0)
11384 (or (and (stringp action)
11385 (string-match "%[0-9]" action))
11386 (consp action)))
11387 nil)))
11389 (defun org-default-apps ()
11390 "Return the default applications for this operating system."
11391 (cond
11392 ((eq system-type 'darwin)
11393 org-file-apps-defaults-macosx)
11394 ((eq system-type 'windows-nt)
11395 org-file-apps-defaults-windowsnt)
11396 (t org-file-apps-defaults-gnu)))
11398 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11399 "Convert extensions to regular expressions in the cars of LIST.
11400 Also, weed out any non-string entries, because the return value is used
11401 only for regexp matching.
11402 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11403 point to the symbol `emacs', indicating that the file should
11404 be opened in Emacs."
11405 (append
11406 (delq nil
11407 (mapcar (lambda (x)
11408 (if (not (stringp (car x)))
11410 (if (string-match "\\W" (car x))
11412 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11413 list))
11414 (if add-auto-mode
11415 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11417 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11418 (defun org-file-remote-p (file)
11419 "Test whether FILE specifies a location on a remote system.
11420 Return non-nil if the location is indeed remote.
11422 For example, the filename \"/user@host:/foo\" specifies a location
11423 on the system \"/user@host:\"."
11424 (cond ((fboundp 'file-remote-p)
11425 (file-remote-p file))
11426 ((fboundp 'tramp-handle-file-remote-p)
11427 (tramp-handle-file-remote-p file))
11428 ((and (boundp 'ange-ftp-name-format)
11429 (string-match (car ange-ftp-name-format) file))
11430 t)))
11433 ;;;; Refiling
11435 (defun org-get-org-file ()
11436 "Read a filename, with default directory `org-directory'."
11437 (let ((default (or org-default-notes-file remember-data-file)))
11438 (read-file-name (format "File name [%s]: " default)
11439 (file-name-as-directory org-directory)
11440 default)))
11442 (defun org-notes-order-reversed-p ()
11443 "Check if the current file should receive notes in reversed order."
11444 (cond
11445 ((not org-reverse-note-order) nil)
11446 ((eq t org-reverse-note-order) t)
11447 ((not (listp org-reverse-note-order)) nil)
11448 (t (catch 'exit
11449 (let ((all org-reverse-note-order)
11450 entry)
11451 (while (setq entry (pop all))
11452 (if (string-match (car entry) buffer-file-name)
11453 (throw 'exit (cdr entry))))
11454 nil)))))
11456 (defvar org-refile-target-table nil
11457 "The list of refile targets, created by `org-refile'.")
11459 (defvar org-agenda-new-buffers nil
11460 "Buffers created to visit agenda files.")
11462 (defvar org-refile-cache nil
11463 "Cache for refile targets.")
11465 (defvar org-refile-markers nil
11466 "All the markers used for caching refile locations.")
11468 (defun org-refile-marker (pos)
11469 "Get a new refile marker, but only if caching is in use."
11470 (if (not org-refile-use-cache)
11472 (let ((m (make-marker)))
11473 (move-marker m pos)
11474 (push m org-refile-markers)
11475 m)))
11477 (defun org-refile-cache-clear ()
11478 "Clear the refile cache and disable all the markers."
11479 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11480 (setq org-refile-markers nil)
11481 (setq org-refile-cache nil)
11482 (message "Refile cache has been cleared"))
11484 (defun org-refile-cache-check-set (set)
11485 "Check if all the markers in the cache still have live buffers."
11486 (let (marker)
11487 (catch 'exit
11488 (while (and set (setq marker (nth 3 (pop set))))
11489 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11490 (when (and marker (null (marker-buffer marker)))
11491 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11492 (sit-for 3)
11493 (throw 'exit nil)))
11494 t)))
11496 (defun org-refile-cache-put (set &rest identifiers)
11497 "Push the refile targets SET into the cache, under IDENTIFIERS."
11498 (let* ((key (sha1 (prin1-to-string identifiers)))
11499 (entry (assoc key org-refile-cache)))
11500 (if entry
11501 (setcdr entry set)
11502 (push (cons key set) org-refile-cache))))
11504 (defun org-refile-cache-get (&rest identifiers)
11505 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11506 (cond
11507 ((not org-refile-cache) nil)
11508 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11510 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11511 org-refile-cache))))
11512 (and set (org-refile-cache-check-set set) set)))))
11514 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11515 "Produce a table with refile targets."
11516 (let ((case-fold-search nil)
11517 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11518 (entries (or org-refile-targets '((nil . (:level . 1)))))
11519 targets tgs txt re files f desc descre fast-path-p level pos0)
11520 (message "Getting targets...")
11521 (with-current-buffer (or default-buffer (current-buffer))
11522 (while (setq entry (pop entries))
11523 (setq files (car entry) desc (cdr entry))
11524 (setq fast-path-p nil)
11525 (cond
11526 ((null files) (setq files (list (current-buffer))))
11527 ((eq files 'org-agenda-files)
11528 (setq files (org-agenda-files 'unrestricted)))
11529 ((and (symbolp files) (fboundp files))
11530 (setq files (funcall files)))
11531 ((and (symbolp files) (boundp files))
11532 (setq files (symbol-value files))))
11533 (if (stringp files) (setq files (list files)))
11534 (cond
11535 ((eq (car desc) :tag)
11536 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11537 ((eq (car desc) :todo)
11538 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11539 ((eq (car desc) :regexp)
11540 (setq descre (cdr desc)))
11541 ((eq (car desc) :level)
11542 (setq descre (concat "^\\*\\{" (number-to-string
11543 (if org-odd-levels-only
11544 (1- (* 2 (cdr desc)))
11545 (cdr desc)))
11546 "\\}[ \t]")))
11547 ((eq (car desc) :maxlevel)
11548 (setq fast-path-p t)
11549 (setq descre (concat "^\\*\\{1," (number-to-string
11550 (if org-odd-levels-only
11551 (1- (* 2 (cdr desc)))
11552 (cdr desc)))
11553 "\\}[ \t]")))
11554 (t (error "Bad refiling target description %s" desc)))
11555 (while (setq f (pop files))
11556 (with-current-buffer
11557 (if (bufferp f) f (org-get-agenda-file-buffer f))
11559 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11560 (progn
11561 (if (bufferp f) (setq f (buffer-file-name
11562 (buffer-base-buffer f))))
11563 (setq f (and f (expand-file-name f)))
11564 (if (eq org-refile-use-outline-path 'file)
11565 (push (list (file-name-nondirectory f) f nil nil) tgs))
11566 (save-excursion
11567 (save-restriction
11568 (widen)
11569 (goto-char (point-min))
11570 (while (re-search-forward descre nil t)
11571 (goto-char (setq pos0 (point-at-bol)))
11572 (catch 'next
11573 (when org-refile-target-verify-function
11574 (save-match-data
11575 (or (funcall org-refile-target-verify-function)
11576 (throw 'next t))))
11577 (when (and (looking-at org-complex-heading-regexp)
11578 (not (member (match-string 4) excluded-entries))
11579 (match-string 4))
11580 (setq level (org-reduced-level
11581 (- (match-end 1) (match-beginning 1)))
11582 txt (org-link-display-format (match-string 4))
11583 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11584 re (format org-complex-heading-regexp-format
11585 (regexp-quote (match-string 4))))
11586 (when org-refile-use-outline-path
11587 (setq txt (mapconcat
11588 'org-protect-slash
11589 (append
11590 (if (eq org-refile-use-outline-path
11591 'file)
11592 (list (file-name-nondirectory
11593 (buffer-file-name
11594 (buffer-base-buffer))))
11595 (if (eq org-refile-use-outline-path
11596 'full-file-path)
11597 (list (buffer-file-name
11598 (buffer-base-buffer)))))
11599 (org-get-outline-path fast-path-p
11600 level txt)
11601 (list txt))
11602 "/")))
11603 (push (list txt f re (org-refile-marker (point)))
11604 tgs)))
11605 (when (= (point) pos0)
11606 ;; verification function has not moved point
11607 (goto-char (point-at-eol))))))))
11608 (when org-refile-use-cache
11609 (org-refile-cache-put tgs (buffer-file-name) descre))
11610 (setq targets (append tgs targets))))))
11611 (message "Getting targets...done")
11612 (nreverse targets)))
11614 (defun org-protect-slash (s)
11615 (while (string-match "/" s)
11616 (setq s (replace-match "\\" t t s)))
11619 (defvar org-olpa (make-vector 20 nil))
11621 (defun org-get-outline-path (&optional fastp level heading)
11622 "Return the outline path to the current entry, as a list.
11624 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11625 routine which makes outline path derivations for an entire file,
11626 avoiding backtracing. Refile target collection makes use of that."
11627 (if fastp
11628 (progn
11629 (if (> level 19)
11630 (error "Outline path failure, more than 19 levels"))
11631 (loop for i from level upto 19 do
11632 (aset org-olpa i nil))
11633 (prog1
11634 (delq nil (append org-olpa nil))
11635 (aset org-olpa level heading)))
11636 (let (rtn case-fold-search)
11637 (save-excursion
11638 (save-restriction
11639 (widen)
11640 (while (org-up-heading-safe)
11641 (when (looking-at org-complex-heading-regexp)
11642 (push (org-trim
11643 (replace-regexp-in-string
11644 ;; Remove statistical/checkboxes cookies
11645 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11646 (org-match-string-no-properties 4)))
11647 rtn)))
11648 rtn)))))
11650 (defun org-format-outline-path (path &optional width prefix separator)
11651 "Format the outline path PATH for display.
11652 WIDTH is the maximum number of characters that is available.
11653 PREFIX is a prefix to be included in the returned string,
11654 such as the file name.
11655 SEPARATOR is inserted between the different parts of the path,
11656 the default is \"/\"."
11657 (setq width (or width 79))
11658 (if prefix (setq width (- width (length prefix))))
11659 (if (not path)
11660 (or prefix "")
11661 (let* ((nsteps (length path))
11662 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11663 (maxwidth (if (<= total-width width)
11664 10000 ;; everything fits
11665 ;; we need to shorten the level headings
11666 (/ (- width nsteps) nsteps)))
11667 (org-odd-levels-only nil)
11668 (n 0)
11669 (total (1+ (length prefix))))
11670 (setq maxwidth (max maxwidth 10))
11671 (concat prefix
11672 (if prefix (or separator "/"))
11673 (mapconcat
11674 (lambda (h)
11675 (setq n (1+ n))
11676 (if (and (= n nsteps) (< maxwidth 10000))
11677 (setq maxwidth (- total-width total)))
11678 (if (< (length h) maxwidth)
11679 (progn (setq total (+ total (length h) 1)) h)
11680 (setq h (substring h 0 (- maxwidth 2))
11681 total (+ total maxwidth 1))
11682 (if (string-match "[ \t]+\\'" h)
11683 (setq h (substring h 0 (match-beginning 0))))
11684 (setq h (concat h "..")))
11685 (org-add-props h nil 'face
11686 (nth (% (1- n) org-n-level-faces)
11687 org-level-faces))
11689 path (or separator "/"))))))
11691 (defun org-display-outline-path (&optional file current separator just-return-string)
11692 "Display the current outline path in the echo area.
11694 If FILE is non-nil, prepend the output with the file name.
11695 If CURRENT is non-nil, append the current heading to the output.
11696 SEPARATOR is passed through to `org-format-outline-path'. It separates
11697 the different parts of the path and defaults to \"/\".
11698 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11699 (interactive "P")
11700 (let* (case-fold-search
11701 (bfn (buffer-file-name (buffer-base-buffer)))
11702 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11703 res)
11704 (if current (setq path (append path
11705 (save-excursion
11706 (org-back-to-heading t)
11707 (if (looking-at org-complex-heading-regexp)
11708 (list (match-string 4)))))))
11709 (setq res
11710 (org-format-outline-path
11711 path
11712 (1- (frame-width))
11713 (and file bfn (concat (file-name-nondirectory bfn) separator))
11714 separator))
11715 (if just-return-string
11716 (org-no-properties res)
11717 (org-unlogged-message "%s" res))))
11719 (defvar org-refile-history nil
11720 "History for refiling operations.")
11722 (defvar org-after-refile-insert-hook nil
11723 "Hook run after `org-refile' has inserted its stuff at the new location.
11724 Note that this is still *before* the stuff will be removed from
11725 the *old* location.")
11727 (defvar org-capture-last-stored-marker)
11728 (defvar org-refile-keep nil
11729 "Non-nil means `org-refile' will copy instead of refile.")
11731 (defun org-copy ()
11732 "Like `org-refile', but copy."
11733 (interactive)
11734 (let ((org-refile-keep t))
11735 (funcall 'org-refile nil nil nil "Copy")))
11737 (defun org-refile (&optional arg default-buffer rfloc msg)
11738 "Move the entry or entries at point to another heading.
11739 The list of target headings is compiled using the information in
11740 `org-refile-targets', which see.
11742 At the target location, the entry is filed as a subitem of the
11743 target heading. Depending on `org-reverse-note-order', the new
11744 subitem will either be the first or the last subitem.
11746 If there is an active region, all entries in that region will be
11747 refiled. However, the region must fulfill the requirement that
11748 the first heading sets the top-level of the moved text.
11750 With prefix arg ARG, the command will only visit the target
11751 location and not actually move anything.
11753 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11754 refiling operation has put the subtree.
11756 With a numeric prefix argument of `2', refile to the running clock.
11758 With a numeric prefix argument of `3', emulate `org-refile-keep'
11759 being set to `t' and copy to the target location, don't move it.
11760 Beware that keeping refiled entries may result in duplicated ID
11761 properties.
11763 RFLOC can be a refile location obtained in a different way.
11765 MSG is a string to replace \"Refile\" in the default prompt with
11766 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11768 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11770 If you are using target caching (see `org-refile-use-cache'), you
11771 have to clear the target cache in order to find new targets.
11772 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11773 prefix argument (`C-u C-u C-u C-c C-w')."
11774 (interactive "P")
11775 (if (member arg '(0 (64)))
11776 (org-refile-cache-clear)
11777 (let* ((actionmsg (cond (msg msg)
11778 ((equal arg 3) "Refile (and keep)")
11779 (t "Refile")))
11780 (cbuf (current-buffer))
11781 (regionp (org-region-active-p))
11782 (region-start (and regionp (region-beginning)))
11783 (region-end (and regionp (region-end)))
11784 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11785 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11786 pos it nbuf file re level reversed)
11787 (setq last-command nil)
11788 (when regionp
11789 (goto-char region-start)
11790 (or (bolp) (goto-char (point-at-bol)))
11791 (setq region-start (point))
11792 (unless (or (org-kill-is-subtree-p
11793 (buffer-substring region-start region-end))
11794 (prog1 org-refile-active-region-within-subtree
11795 (let ((s (point-at-eol)))
11796 (org-toggle-heading)
11797 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11798 (user-error "The region is not a (sequence of) subtree(s)")))
11799 (if (equal arg '(16))
11800 (org-refile-goto-last-stored)
11801 (when (or
11802 (and (equal arg 2)
11803 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11804 (prog1
11805 (setq it (list (or org-clock-heading "running clock")
11806 (buffer-file-name
11807 (marker-buffer org-clock-hd-marker))
11809 (marker-position org-clock-hd-marker)))
11810 (setq arg nil)))
11811 (setq it (or rfloc
11812 (let (heading-text)
11813 (save-excursion
11814 (unless (and arg (listp arg))
11815 (org-back-to-heading t)
11816 (setq heading-text
11817 (replace-regexp-in-string
11818 org-bracket-link-regexp
11819 "\\3"
11820 (nth 4 (org-heading-components)))))
11821 (org-refile-get-location
11822 (cond ((and arg (listp arg)) "Goto")
11823 (regionp (concat actionmsg " region to"))
11824 (t (concat actionmsg " subtree \""
11825 heading-text "\" to")))
11826 default-buffer
11827 (and (not (equal '(4) arg))
11828 org-refile-allow-creating-parent-nodes)
11829 arg))))))
11830 (setq file (nth 1 it)
11831 re (nth 2 it)
11832 pos (nth 3 it))
11833 (if (and (not arg)
11835 (equal (buffer-file-name) file)
11836 (if regionp
11837 (and (>= pos region-start)
11838 (<= pos region-end))
11839 (and (>= pos (point))
11840 (< pos (save-excursion
11841 (org-end-of-subtree t t))))))
11842 (error "Cannot refile to position inside the tree or region"))
11843 (setq nbuf (or (find-buffer-visiting file)
11844 (find-file-noselect file)))
11845 (if (and arg (not (equal arg 3)))
11846 (progn
11847 (org-pop-to-buffer-same-window nbuf)
11848 (goto-char pos)
11849 (org-show-context 'org-goto))
11850 (if regionp
11851 (progn
11852 (org-kill-new (buffer-substring region-start region-end))
11853 (org-save-markers-in-region region-start region-end))
11854 (org-copy-subtree 1 nil t))
11855 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11856 (find-file-noselect file)))
11857 (setq reversed (org-notes-order-reversed-p))
11858 (save-excursion
11859 (save-restriction
11860 (widen)
11861 (if pos
11862 (progn
11863 (goto-char pos)
11864 (looking-at org-outline-regexp)
11865 (setq level (org-get-valid-level (funcall outline-level) 1))
11866 (goto-char
11867 (if reversed
11868 (or (outline-next-heading) (point-max))
11869 (or (save-excursion (org-get-next-sibling))
11870 (org-end-of-subtree t t)
11871 (point-max)))))
11872 (setq level 1)
11873 (if (not reversed)
11874 (goto-char (point-max))
11875 (goto-char (point-min))
11876 (or (outline-next-heading) (goto-char (point-max)))))
11877 (if (not (bolp)) (newline))
11878 (org-paste-subtree level)
11879 (when org-log-refile
11880 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11881 (unless (eq org-log-refile 'note)
11882 (save-excursion (org-add-log-note))))
11883 (and org-auto-align-tags
11884 (let ((org-loop-over-headlines-in-active-region nil))
11885 (org-set-tags nil t)))
11886 (let ((bookmark-name (plist-get org-bookmark-names-plist
11887 :last-refile)))
11888 (when bookmark-name
11889 (with-demoted-errors
11890 (bookmark-set bookmark-name))))
11891 ;; If we are refiling for capture, make sure that the
11892 ;; last-capture pointers point here
11893 (when (org-bound-and-true-p org-refile-for-capture)
11894 (let ((bookmark-name (plist-get org-bookmark-names-plist
11895 :last-capture-marker)))
11896 (when bookmark-name
11897 (with-demoted-errors
11898 (bookmark-set bookmark-name))))
11899 (move-marker org-capture-last-stored-marker (point)))
11900 (if (fboundp 'deactivate-mark) (deactivate-mark))
11901 (run-hooks 'org-after-refile-insert-hook))))
11902 (unless org-refile-keep
11903 (if regionp
11904 (delete-region (point) (+ (point) (- region-end region-start)))
11905 (delete-region
11906 (and (org-back-to-heading t) (point))
11907 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11908 (when (featurep 'org-inlinetask)
11909 (org-inlinetask-remove-END-maybe))
11910 (setq org-markers-to-move nil)
11911 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11913 (defun org-refile-goto-last-stored ()
11914 "Go to the location where the last refile was stored."
11915 (interactive)
11916 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11917 (message "This is the location of the last refile"))
11919 (defun org-refile--get-location (refloc tbl)
11920 "When user refile to REFLOC, find the associated target in TBL.
11921 Also check `org-refile-target-table'."
11922 (car (delq
11924 (mapcar
11925 (lambda (r) (or (assoc r tbl)
11926 (assoc r org-refile-target-table)))
11927 (list (replace-regexp-in-string "/$" "" refloc)
11928 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11930 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11931 no-exclude)
11932 "Prompt the user for a refile location, using PROMPT.
11933 PROMPT should not be suffixed with a colon and a space, because
11934 this function appends the default value from
11935 `org-refile-history' automatically, if that is not empty.
11936 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11937 this is used for the GOTO interface."
11938 (let ((org-refile-targets org-refile-targets)
11939 (org-refile-use-outline-path org-refile-use-outline-path)
11940 excluded-entries)
11941 (when (and (derived-mode-p 'org-mode)
11942 (not org-refile-use-cache)
11943 (not no-exclude))
11944 (org-map-tree
11945 (lambda()
11946 (setq excluded-entries
11947 (append excluded-entries (list (org-get-heading t t)))))))
11948 (setq org-refile-target-table
11949 (org-refile-get-targets default-buffer excluded-entries)))
11950 (unless org-refile-target-table
11951 (user-error "No refile targets"))
11952 (let* ((cbuf (current-buffer))
11953 (partial-completion-mode nil)
11954 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11955 (cfunc (if (and org-refile-use-outline-path
11956 org-outline-path-complete-in-steps)
11957 'org-olpath-completing-read
11958 'org-icompleting-read))
11959 (extra (if org-refile-use-outline-path "/" ""))
11960 (cbnex (concat (buffer-name) extra))
11961 (filename (and cfn (expand-file-name cfn)))
11962 (tbl (mapcar
11963 (lambda (x)
11964 (if (and (not (member org-refile-use-outline-path
11965 '(file full-file-path)))
11966 (not (equal filename (nth 1 x))))
11967 (cons (concat (car x) extra " ("
11968 (file-name-nondirectory (nth 1 x)) ")")
11969 (cdr x))
11970 (cons (concat (car x) extra) (cdr x))))
11971 org-refile-target-table))
11972 (completion-ignore-case t)
11973 cdef
11974 (prompt (concat prompt
11975 (or (and (car org-refile-history)
11976 (concat " (default " (car org-refile-history) ")"))
11977 (and (assoc cbnex tbl) (setq cdef cbnex)
11978 (concat " (default " cbnex ")"))) ": "))
11979 pa answ parent-target child parent old-hist)
11980 (setq old-hist org-refile-history)
11981 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11982 nil 'org-refile-history (or cdef (car org-refile-history))))
11983 (if (setq pa (org-refile--get-location answ tbl))
11984 (progn
11985 (org-refile-check-position pa)
11986 (when (or (not org-refile-history)
11987 (not (eq old-hist org-refile-history))
11988 (not (equal (car pa) (car org-refile-history))))
11989 (setq org-refile-history
11990 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11991 org-refile-history
11992 (cdr org-refile-history))))
11993 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11994 (pop org-refile-history)))
11996 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11997 (progn
11998 (setq parent (match-string 1 answ)
11999 child (match-string 2 answ))
12000 (setq parent-target (org-refile--get-location parent tbl))
12001 (when (and parent-target
12002 (or (eq new-nodes t)
12003 (and (eq new-nodes 'confirm)
12004 (y-or-n-p (format "Create new node \"%s\"? "
12005 child)))))
12006 (org-refile-new-child parent-target child)))
12007 (user-error "Invalid target location")))))
12009 (declare-function org-string-nw-p "org-macs" (s))
12010 (defun org-refile-check-position (refile-pointer)
12011 "Check if the refile pointer matches the headline to which it points."
12012 (let* ((file (nth 1 refile-pointer))
12013 (re (nth 2 refile-pointer))
12014 (pos (nth 3 refile-pointer))
12015 buffer)
12016 (if (and (not (markerp pos)) (not file))
12017 (user-error "Please indicate a target file in the refile path")
12018 (when (org-string-nw-p re)
12019 (setq buffer (if (markerp pos)
12020 (marker-buffer pos)
12021 (or (find-buffer-visiting file)
12022 (find-file-noselect file))))
12023 (with-current-buffer buffer
12024 (save-excursion
12025 (save-restriction
12026 (widen)
12027 (goto-char pos)
12028 (beginning-of-line 1)
12029 (unless (org-looking-at-p re)
12030 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12032 (defun org-refile-new-child (parent-target child)
12033 "Use refile target PARENT-TARGET to add new CHILD below it."
12034 (unless parent-target
12035 (error "Cannot find parent for new node"))
12036 (let ((file (nth 1 parent-target))
12037 (pos (nth 3 parent-target))
12038 level)
12039 (with-current-buffer (or (find-buffer-visiting file)
12040 (find-file-noselect file))
12041 (save-excursion
12042 (save-restriction
12043 (widen)
12044 (if pos
12045 (goto-char pos)
12046 (goto-char (point-max))
12047 (if (not (bolp)) (newline)))
12048 (when (looking-at org-outline-regexp)
12049 (setq level (funcall outline-level))
12050 (org-end-of-subtree t t))
12051 (org-back-over-empty-lines)
12052 (insert "\n" (make-string
12053 (if pos (org-get-valid-level level 1) 1) ?*)
12054 " " child "\n")
12055 (beginning-of-line 0)
12056 (list (concat (car parent-target) "/" child) file "" (point)))))))
12058 (defun org-olpath-completing-read (prompt collection &rest args)
12059 "Read an outline path like a file name."
12060 (let ((thetable collection)
12061 (org-completion-use-ido nil) ; does not work with ido.
12062 (org-completion-use-iswitchb nil)) ; or iswitchb
12063 (apply
12064 'org-icompleting-read prompt
12065 (lambda (string predicate &optional flag)
12066 (let (rtn r f (l (length string)))
12067 (cond
12068 ((eq flag nil)
12069 ;; try completion
12070 (try-completion string thetable))
12071 ((eq flag t)
12072 ;; all-completions
12073 (setq rtn (all-completions string thetable predicate))
12074 (mapcar
12075 (lambda (x)
12076 (setq r (substring x l))
12077 (if (string-match " ([^)]*)$" x)
12078 (setq f (match-string 0 x))
12079 (setq f ""))
12080 (if (string-match "/" r)
12081 (concat string (substring r 0 (match-end 0)) f)
12083 rtn))
12084 ((eq flag 'lambda)
12085 ;; exact match?
12086 (assoc string thetable)))))
12087 args)))
12089 ;;;; Dynamic blocks
12091 (defun org-find-dblock (name)
12092 "Find the first dynamic block with name NAME in the buffer.
12093 If not found, stay at current position and return nil."
12094 (let ((case-fold-search t) pos)
12095 (save-excursion
12096 (goto-char (point-min))
12097 (setq pos (and (re-search-forward
12098 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12099 (match-beginning 0))))
12100 (if pos (goto-char pos))
12101 pos))
12103 (defun org-create-dblock (plist)
12104 "Create a dynamic block section, with parameters taken from PLIST.
12105 PLIST must contain a :name entry which is used as the name of the block."
12106 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12107 (end-of-line 1)
12108 (newline))
12109 (let ((col (current-column))
12110 (name (plist-get plist :name)))
12111 (insert "#+BEGIN: " name)
12112 (while plist
12113 (if (eq (car plist) :name)
12114 (setq plist (cddr plist))
12115 (insert " " (prin1-to-string (pop plist)))))
12116 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12117 (beginning-of-line -2)))
12119 (defun org-prepare-dblock ()
12120 "Prepare dynamic block for refresh.
12121 This empties the block, puts the cursor at the insert position and returns
12122 the property list including an extra property :name with the block name."
12123 (unless (looking-at org-dblock-start-re)
12124 (user-error "Not at a dynamic block"))
12125 (let* ((begdel (1+ (match-end 0)))
12126 (name (org-no-properties (match-string 1)))
12127 (params (append (list :name name)
12128 (read (concat "(" (match-string 3) ")")))))
12129 (save-excursion
12130 (beginning-of-line 1)
12131 (skip-chars-forward " \t")
12132 (setq params (plist-put params :indentation-column (current-column))))
12133 (unless (re-search-forward org-dblock-end-re nil t)
12134 (error "Dynamic block not terminated"))
12135 (setq params
12136 (append params
12137 (list :content (buffer-substring
12138 begdel (match-beginning 0)))))
12139 (delete-region begdel (match-beginning 0))
12140 (goto-char begdel)
12141 (open-line 1)
12142 params))
12144 (defun org-map-dblocks (&optional command)
12145 "Apply COMMAND to all dynamic blocks in the current buffer.
12146 If COMMAND is not given, use `org-update-dblock'."
12147 (let ((cmd (or command 'org-update-dblock)))
12148 (save-excursion
12149 (goto-char (point-min))
12150 (while (re-search-forward org-dblock-start-re nil t)
12151 (goto-char (match-beginning 0))
12152 (save-excursion
12153 (condition-case nil
12154 (funcall cmd)
12155 (error (message "Error during update of dynamic block"))))
12156 (unless (re-search-forward org-dblock-end-re nil t)
12157 (error "Dynamic block not terminated"))))))
12159 (defun org-dblock-update (&optional arg)
12160 "User command for updating dynamic blocks.
12161 Update the dynamic block at point. With prefix ARG, update all dynamic
12162 blocks in the buffer."
12163 (interactive "P")
12164 (if arg
12165 (org-update-all-dblocks)
12166 (or (looking-at org-dblock-start-re)
12167 (org-beginning-of-dblock))
12168 (org-update-dblock)))
12170 (defun org-update-dblock ()
12171 "Update the dynamic block at point.
12172 This means to empty the block, parse for parameters and then call
12173 the correct writing function."
12174 (interactive)
12175 (save-excursion
12176 (let* ((win (selected-window))
12177 (pos (point))
12178 (line (org-current-line))
12179 (params (org-prepare-dblock))
12180 (name (plist-get params :name))
12181 (indent (plist-get params :indentation-column))
12182 (cmd (intern (concat "org-dblock-write:" name))))
12183 (message "Updating dynamic block `%s' at line %d..." name line)
12184 (funcall cmd params)
12185 (message "Updating dynamic block `%s' at line %d...done" name line)
12186 (goto-char pos)
12187 (when (and indent (> indent 0))
12188 (setq indent (make-string indent ?\ ))
12189 (save-excursion
12190 (select-window win)
12191 (org-beginning-of-dblock)
12192 (forward-line 1)
12193 (while (not (looking-at org-dblock-end-re))
12194 (insert indent)
12195 (beginning-of-line 2))
12196 (when (looking-at org-dblock-end-re)
12197 (and (looking-at "[ \t]+")
12198 (replace-match ""))
12199 (insert indent)))))))
12201 (defun org-beginning-of-dblock ()
12202 "Find the beginning of the dynamic block at point.
12203 Error if there is no such block at point."
12204 (let ((pos (point))
12205 beg)
12206 (end-of-line 1)
12207 (if (and (re-search-backward org-dblock-start-re nil t)
12208 (setq beg (match-beginning 0))
12209 (re-search-forward org-dblock-end-re nil t)
12210 (> (match-end 0) pos))
12211 (goto-char beg)
12212 (goto-char pos)
12213 (error "Not in a dynamic block"))))
12215 (defun org-update-all-dblocks ()
12216 "Update all dynamic blocks in the buffer.
12217 This function can be used in a hook."
12218 (interactive)
12219 (when (derived-mode-p 'org-mode)
12220 (org-map-dblocks 'org-update-dblock)))
12223 ;;;; Completion
12225 (declare-function org-export-backend-name "org-export" (cl-x))
12226 (declare-function org-export-backend-options "org-export" (cl-x))
12227 (defun org-get-export-keywords ()
12228 "Return a list of all currently understood export keywords.
12229 Export keywords include options, block names, attributes and
12230 keywords relative to each registered export back-end."
12231 (let (keywords)
12232 (dolist (backend
12233 (org-bound-and-true-p org-export--registered-backends)
12234 (delq nil keywords))
12235 ;; Back-end name (for keywords, like #+LATEX:)
12236 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12237 (dolist (option-entry (org-export-backend-options backend))
12238 ;; Back-end options.
12239 (push (nth 1 option-entry) keywords)))))
12241 (defconst org-options-keywords
12242 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12243 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12244 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12245 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12246 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12248 (defcustom org-structure-template-alist
12249 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12250 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12251 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12252 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12253 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12254 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12255 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12256 "<literal style=\"latex\">\n?\n</literal>")
12257 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12258 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12259 "<literal style=\"html\">\n?\n</literal>")
12260 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12261 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12262 ("A" "#+ASCII: " "")
12263 ("i" "#+INDEX: ?" "#+INDEX: ?")
12264 ("I" "#+INCLUDE: %file ?"
12265 "<include file=%file markup=\"?\">"))
12266 "Structure completion elements.
12267 This is a list of abbreviation keys and values. The value gets inserted
12268 if you type `<' followed by the key and then press the completion key,
12269 usually `M-TAB'. %file will be replaced by a file name after prompting
12270 for the file using completion. The cursor will be placed at the position
12271 of the `?` in the template.
12272 There are two templates for each key, the first uses the original Org syntax,
12273 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12274 the default when the /org-mtags.el/ module has been loaded. See also the
12275 variable `org-mtags-prefer-muse-templates'."
12276 :group 'org-completion
12277 :type '(repeat
12278 (list
12279 (string :tag "Key")
12280 (string :tag "Template")
12281 (string :tag "Muse Template"))))
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* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12299 (rpl (nth (if musep 2 1) cell))
12300 (ind ""))
12301 (delete-region start (point))
12302 (when (string-match "\\`[ \t]*#\\+" rpl)
12303 (cond
12304 ((bolp))
12305 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12306 (setq ind (buffer-substring (point-at-bol) (point))))
12307 (t (newline))))
12308 (setq start (point))
12309 (if (string-match "%file" rpl)
12310 (setq rpl (replace-match
12311 (concat
12312 "\""
12313 (save-match-data
12314 (abbreviate-file-name (read-file-name "Include file: ")))
12315 "\"")
12316 t t rpl)))
12317 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12318 (concat "\n" ind)))
12319 (insert rpl)
12320 (if (re-search-backward "\\?" start t) (delete-char 1))))
12322 ;;;; TODO, DEADLINE, Comments
12324 (defun org-toggle-comment ()
12325 "Change the COMMENT state of an entry."
12326 (interactive)
12327 (save-excursion
12328 (org-back-to-heading)
12329 (looking-at org-complex-heading-regexp)
12330 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12331 (skip-chars-forward " \t")
12332 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12333 (if (org-in-commented-heading-p t)
12334 (delete-region (point)
12335 (progn (search-forward " " (line-end-position) 'move)
12336 (skip-chars-forward " \t")
12337 (point)))
12338 (insert org-comment-string)
12339 (unless (eolp) (insert " ")))))
12341 (defvar org-last-todo-state-is-todo nil
12342 "This is non-nil when the last TODO state change led to a TODO state.
12343 If the last change removed the TODO tag or switched to DONE, then
12344 this is nil.")
12346 (defvar org-setting-tags nil) ; dynamically skipped
12348 (defvar org-todo-setup-filter-hook nil
12349 "Hook for functions that pre-filter todo specs.
12350 Each function takes a todo spec and returns either nil or the spec
12351 transformed into canonical form." )
12353 (defvar org-todo-get-default-hook nil
12354 "Hook for functions that get a default item for todo.
12355 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12356 nil or a string to be used for the todo mark." )
12358 (defvar org-agenda-headline-snapshot-before-repeat)
12360 (defun org-current-effective-time ()
12361 "Return current time adjusted for `org-extend-today-until' variable."
12362 (let* ((ct (org-current-time))
12363 (dct (decode-time ct))
12364 (ct1
12365 (cond
12366 (org-use-last-clock-out-time-as-effective-time
12367 (or (org-clock-get-last-clock-out-time) ct))
12368 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12369 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12370 (t ct))))
12371 ct1))
12373 (defun org-todo-yesterday (&optional arg)
12374 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12375 (interactive "P")
12376 (if (eq major-mode 'org-agenda-mode)
12377 (apply 'org-agenda-todo-yesterday arg)
12378 (let* ((hour (third (decode-time
12379 (org-current-time))))
12380 (org-extend-today-until (1+ hour)))
12381 (org-todo arg))))
12383 (defvar org-block-entry-blocking ""
12384 "First entry preventing the TODO state change.")
12386 (defun org-cancel-repeater ()
12387 "Cancel a repeater by setting its numeric value to zero."
12388 (interactive)
12389 (save-excursion
12390 (org-back-to-heading t)
12391 (let ((bound1 (point))
12392 (bound0 (save-excursion (outline-next-heading) (point))))
12393 (when (re-search-forward
12394 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12395 org-deadline-time-regexp "\\)\\|\\("
12396 org-ts-regexp "\\)")
12397 bound0 t)
12398 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12399 (replace-match "0" t nil nil 1))))))
12401 (defun org-todo (&optional arg)
12402 "Change the TODO state of an item.
12403 The state of an item is given by a keyword at the start of the heading,
12404 like
12405 *** TODO Write paper
12406 *** DONE Call mom
12408 The different keywords are specified in the variable `org-todo-keywords'.
12409 By default the available states are \"TODO\" and \"DONE\".
12410 So for this example: when the item starts with TODO, it is changed to DONE.
12411 When it starts with DONE, the DONE is removed. And when neither TODO nor
12412 DONE are present, add TODO at the beginning of the heading.
12414 With \\[universal-argument] prefix arg, use completion to determine the new \
12415 state.
12416 With numeric prefix arg, switch to that state.
12417 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12418 keywords (nextset).
12419 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12420 With a numeric prefix arg of 0, inhibit note taking for the change.
12421 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12423 When called through ELisp, arg is also interpreted in the following way:
12424 'none -> empty state
12425 \"\"(empty string) -> switch to empty state
12426 'done -> switch to DONE
12427 'nextset -> switch to the next set of keywords
12428 'previousset -> switch to the previous set of keywords
12429 \"WAITING\" -> switch to the specified keyword, but only if it
12430 really is a member of `org-todo-keywords'."
12431 (interactive "P")
12432 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12433 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12434 'region-start-level 'region))
12435 org-loop-over-headlines-in-active-region)
12436 (org-map-entries
12437 `(org-todo ,arg)
12438 org-loop-over-headlines-in-active-region
12439 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12440 (if (equal arg '(16)) (setq arg 'nextset))
12441 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12442 (let ((org-blocker-hook org-blocker-hook)
12443 commentp
12444 case-fold-search)
12445 (when (equal arg '(64))
12446 (setq arg nil org-blocker-hook nil))
12447 (when (and org-blocker-hook
12448 (or org-inhibit-blocking
12449 (org-entry-get nil "NOBLOCKING")))
12450 (setq org-blocker-hook nil))
12451 (save-excursion
12452 (catch 'exit
12453 (org-back-to-heading t)
12454 (when (org-in-commented-heading-p t)
12455 (org-toggle-comment)
12456 (setq commentp t))
12457 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12458 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12459 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12460 (let* ((match-data (match-data))
12461 (startpos (point-at-bol))
12462 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12463 (org-log-done org-log-done)
12464 (org-log-repeat org-log-repeat)
12465 (org-todo-log-states org-todo-log-states)
12466 (org-inhibit-logging
12467 (if (equal arg 0)
12468 (progn (setq arg nil) 'note) org-inhibit-logging))
12469 (this (match-string 1))
12470 (hl-pos (match-beginning 0))
12471 (head (org-get-todo-sequence-head this))
12472 (ass (assoc head org-todo-kwd-alist))
12473 (interpret (nth 1 ass))
12474 (done-word (nth 3 ass))
12475 (final-done-word (nth 4 ass))
12476 (org-last-state (or this ""))
12477 (completion-ignore-case t)
12478 (member (member this org-todo-keywords-1))
12479 (tail (cdr member))
12480 (org-state (cond
12481 ((and org-todo-key-trigger
12482 (or (and (equal arg '(4))
12483 (eq org-use-fast-todo-selection 'prefix))
12484 (and (not arg) org-use-fast-todo-selection
12485 (not (eq org-use-fast-todo-selection
12486 'prefix)))))
12487 ;; Use fast selection
12488 (org-fast-todo-selection))
12489 ((and (equal arg '(4))
12490 (or (not org-use-fast-todo-selection)
12491 (not org-todo-key-trigger)))
12492 ;; Read a state with completion
12493 (org-icompleting-read
12494 "State: " (mapcar 'list org-todo-keywords-1)
12495 nil t))
12496 ((eq arg 'right)
12497 (if this
12498 (if tail (car tail) nil)
12499 (car org-todo-keywords-1)))
12500 ((eq arg 'left)
12501 (if (equal member org-todo-keywords-1)
12503 (if this
12504 (nth (- (length org-todo-keywords-1)
12505 (length tail) 2)
12506 org-todo-keywords-1)
12507 (org-last org-todo-keywords-1))))
12508 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12509 (setq arg nil))) ; hack to fall back to cycling
12510 (arg
12511 ;; user or caller requests a specific state
12512 (cond
12513 ((equal arg "") nil)
12514 ((eq arg 'none) nil)
12515 ((eq arg 'done) (or done-word (car org-done-keywords)))
12516 ((eq arg 'nextset)
12517 (or (car (cdr (member head org-todo-heads)))
12518 (car org-todo-heads)))
12519 ((eq arg 'previousset)
12520 (let ((org-todo-heads (reverse org-todo-heads)))
12521 (or (car (cdr (member head org-todo-heads)))
12522 (car org-todo-heads))))
12523 ((car (member arg org-todo-keywords-1)))
12524 ((stringp arg)
12525 (user-error "State `%s' not valid in this file" arg))
12526 ((nth (1- (prefix-numeric-value arg))
12527 org-todo-keywords-1))))
12528 ((null member) (or head (car org-todo-keywords-1)))
12529 ((equal this final-done-word) nil) ;; -> make empty
12530 ((null tail) nil) ;; -> first entry
12531 ((memq interpret '(type priority))
12532 (if (eq this-command last-command)
12533 (car tail)
12534 (if (> (length tail) 0)
12535 (or done-word (car org-done-keywords))
12536 nil)))
12538 (car tail))))
12539 (org-state (or
12540 (run-hook-with-args-until-success
12541 'org-todo-get-default-hook org-state org-last-state)
12542 org-state))
12543 (next (if org-state (concat " " org-state " ") " "))
12544 (change-plist (list :type 'todo-state-change :from this :to org-state
12545 :position startpos))
12546 dolog now-done-p)
12547 (when org-blocker-hook
12548 (setq org-last-todo-state-is-todo
12549 (not (member this org-done-keywords)))
12550 (unless (save-excursion
12551 (save-match-data
12552 (org-with-wide-buffer
12553 (run-hook-with-args-until-failure
12554 'org-blocker-hook change-plist))))
12555 (if (org-called-interactively-p 'interactive)
12556 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12557 this org-state org-block-entry-blocking)
12558 ;; fail silently
12559 (message "TODO state change from %s to %s blocked (by \"%s\")"
12560 this org-state org-block-entry-blocking)
12561 (throw 'exit nil))))
12562 (store-match-data match-data)
12563 (replace-match next t t)
12564 (cond ((equal this org-state)
12565 (message "TODO state was already %s" (org-trim next)))
12566 ((pos-visible-in-window-p hl-pos)
12567 (message "TODO state changed to %s" (org-trim next))))
12568 (unless head
12569 (setq head (org-get-todo-sequence-head org-state)
12570 ass (assoc head org-todo-kwd-alist)
12571 interpret (nth 1 ass)
12572 done-word (nth 3 ass)
12573 final-done-word (nth 4 ass)))
12574 (when (memq arg '(nextset previousset))
12575 (message "Keyword-Set %d/%d: %s"
12576 (- (length org-todo-sets) -1
12577 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12578 (length org-todo-sets)
12579 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12580 (setq org-last-todo-state-is-todo
12581 (not (member org-state org-done-keywords)))
12582 (setq now-done-p (and (member org-state org-done-keywords)
12583 (not (member this org-done-keywords))))
12584 (and logging (org-local-logging logging))
12585 (when (and (or org-todo-log-states org-log-done)
12586 (not (eq org-inhibit-logging t))
12587 (not (memq arg '(nextset previousset))))
12588 ;; we need to look at recording a time and note
12589 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12590 (nth 2 (assoc this org-todo-log-states))))
12591 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12592 (setq dolog 'time))
12593 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12594 (and org-state
12595 (member org-state org-not-done-keywords)
12596 (not (member this org-not-done-keywords))))
12597 ;; This is now a todo state and was not one before
12598 ;; If there was a CLOSED time stamp, get rid of it.
12599 (org-add-planning-info nil nil 'closed))
12600 (when (and now-done-p org-log-done)
12601 ;; It is now done, and it was not done before
12602 (org-add-planning-info 'closed (org-current-effective-time))
12603 (if (and (not dolog) (eq 'note org-log-done))
12604 (org-add-log-setup 'done org-state this 'findpos 'note)))
12605 (when (and org-state dolog)
12606 ;; This is a non-nil state, and we need to log it
12607 (org-add-log-setup 'state org-state this 'findpos dolog)))
12608 ;; Fixup tag positioning
12609 (org-todo-trigger-tag-changes org-state)
12610 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12611 (when org-provide-todo-statistics
12612 (org-update-parent-todo-statistics))
12613 (run-hooks 'org-after-todo-state-change-hook)
12614 (if (and arg (not (member org-state org-done-keywords)))
12615 (setq head (org-get-todo-sequence-head org-state)))
12616 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12617 ;; Do we need to trigger a repeat?
12618 (when now-done-p
12619 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12620 ;; This is for the agenda, take a snapshot of the headline.
12621 (save-match-data
12622 (setq org-agenda-headline-snapshot-before-repeat
12623 (org-get-heading))))
12624 (org-auto-repeat-maybe org-state))
12625 ;; Fixup cursor location if close to the keyword
12626 (if (and (outline-on-heading-p)
12627 (not (bolp))
12628 (save-excursion (beginning-of-line 1)
12629 (looking-at org-todo-line-regexp))
12630 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12631 (progn
12632 (goto-char (or (match-end 2) (match-end 1)))
12633 (and (looking-at " ") (just-one-space))))
12634 (when org-trigger-hook
12635 (save-excursion
12636 (run-hook-with-args 'org-trigger-hook change-plist)))
12637 (when commentp (org-toggle-comment))))))))
12639 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12640 "Block turning an entry into a TODO, using the hierarchy.
12641 This checks whether the current task should be blocked from state
12642 changes. Such blocking occurs when:
12644 1. The task has children which are not all in a completed state.
12646 2. A task has a parent with the property :ORDERED:, and there
12647 are siblings prior to the current task with incomplete
12648 status.
12650 3. The parent of the task is blocked because it has siblings that should
12651 be done first, or is child of a block grandparent TODO entry."
12653 (if (not org-enforce-todo-dependencies)
12654 t ; if locally turned off don't block
12655 (catch 'dont-block
12656 ;; If this is not a todo state change, or if this entry is already DONE,
12657 ;; do not block
12658 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12659 (member (plist-get change-plist :from)
12660 (cons 'done org-done-keywords))
12661 (member (plist-get change-plist :to)
12662 (cons 'todo org-not-done-keywords))
12663 (not (plist-get change-plist :to)))
12664 (throw 'dont-block t))
12665 ;; If this task has children, and any are undone, it's blocked
12666 (save-excursion
12667 (org-back-to-heading t)
12668 (let ((this-level (funcall outline-level)))
12669 (outline-next-heading)
12670 (let ((child-level (funcall outline-level)))
12671 (while (and (not (eobp))
12672 (> child-level this-level))
12673 ;; this todo has children, check whether they are all
12674 ;; completed
12675 (if (and (not (org-entry-is-done-p))
12676 (org-entry-is-todo-p))
12677 (progn (setq org-block-entry-blocking (org-get-heading))
12678 (throw 'dont-block nil)))
12679 (outline-next-heading)
12680 (setq child-level (funcall outline-level))))))
12681 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12682 ;; any previous siblings are undone, it's blocked
12683 (save-excursion
12684 (org-back-to-heading t)
12685 (let* ((pos (point))
12686 (parent-pos (and (org-up-heading-safe) (point))))
12687 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12688 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12689 (forward-line 1)
12690 (re-search-forward org-not-done-heading-regexp pos t))
12691 (setq org-block-entry-blocking (match-string 0))
12692 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12693 ;; Search further up the hierarchy, to see if an ancestor is blocked
12694 (while t
12695 (goto-char parent-pos)
12696 (if (not (looking-at org-not-done-heading-regexp))
12697 (throw 'dont-block t)) ; do not block, parent is not a TODO
12698 (setq pos (point))
12699 (setq parent-pos (and (org-up-heading-safe) (point)))
12700 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12701 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12702 (forward-line 1)
12703 (re-search-forward org-not-done-heading-regexp pos t)
12704 (setq org-block-entry-blocking (org-get-heading)))
12705 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12707 (defcustom org-track-ordered-property-with-tag nil
12708 "Should the ORDERED property also be shown as a tag?
12709 The ORDERED property decides if an entry should require subtasks to be
12710 completed in sequence. Since a property is not very visible, setting
12711 this option means that toggling the ORDERED property with the command
12712 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12713 not relevant for the behavior, but it makes things more visible.
12715 Note that toggling the tag with tags commands will not change the property
12716 and therefore not influence behavior!
12718 This can be t, meaning the tag ORDERED should be used, It can also be a
12719 string to select a different tag for this task."
12720 :group 'org-todo
12721 :type '(choice
12722 (const :tag "No tracking" nil)
12723 (const :tag "Track with ORDERED tag" t)
12724 (string :tag "Use other tag")))
12726 (defun org-toggle-ordered-property ()
12727 "Toggle the ORDERED property of the current entry.
12728 For better visibility, you can track the value of this property with a tag.
12729 See variable `org-track-ordered-property-with-tag'."
12730 (interactive)
12731 (let* ((t1 org-track-ordered-property-with-tag)
12732 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12733 (save-excursion
12734 (org-back-to-heading)
12735 (if (org-entry-get nil "ORDERED")
12736 (progn
12737 (org-delete-property "ORDERED")
12738 (and tag (org-toggle-tag tag 'off))
12739 (message "Subtasks can be completed in arbitrary order"))
12740 (org-entry-put nil "ORDERED" "t")
12741 (and tag (org-toggle-tag tag 'on))
12742 (message "Subtasks must be completed in sequence")))))
12744 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12745 (defun org-block-todo-from-checkboxes (change-plist)
12746 "Block turning an entry into a TODO, using checkboxes.
12747 This checks whether the current task should be blocked from state
12748 changes because there are unchecked boxes in this entry."
12749 (if (not org-enforce-todo-checkbox-dependencies)
12750 t ; if locally turned off don't block
12751 (catch 'dont-block
12752 ;; If this is not a todo state change, or if this entry is already DONE,
12753 ;; do not block
12754 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12755 (member (plist-get change-plist :from)
12756 (cons 'done org-done-keywords))
12757 (member (plist-get change-plist :to)
12758 (cons 'todo org-not-done-keywords))
12759 (not (plist-get change-plist :to)))
12760 (throw 'dont-block t))
12761 ;; If this task has checkboxes that are not checked, it's blocked
12762 (save-excursion
12763 (org-back-to-heading t)
12764 (let ((beg (point)) end)
12765 (outline-next-heading)
12766 (setq end (point))
12767 (goto-char beg)
12768 (if (org-list-search-forward
12769 (concat (org-item-beginning-re)
12770 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12771 "\\[[- ]\\]")
12772 end t)
12773 (progn
12774 (if (boundp 'org-blocked-by-checkboxes)
12775 (setq org-blocked-by-checkboxes t))
12776 (throw 'dont-block nil)))))
12777 t))) ; do not block
12779 (defun org-entry-blocked-p ()
12780 "Is the current entry blocked?"
12781 (org-with-silent-modifications
12782 (if (org-entry-get nil "NOBLOCKING")
12783 nil ;; Never block this entry
12784 (not (run-hook-with-args-until-failure
12785 'org-blocker-hook
12786 (list :type 'todo-state-change
12787 :position (point)
12788 :from 'todo
12789 :to 'done))))))
12791 (defun org-update-statistics-cookies (all)
12792 "Update the statistics cookie, either from TODO or from checkboxes.
12793 This should be called with the cursor in a line with a statistics cookie."
12794 (interactive "P")
12795 (if all
12796 (progn
12797 (org-update-checkbox-count 'all)
12798 (org-map-entries 'org-update-parent-todo-statistics))
12799 (if (not (org-at-heading-p))
12800 (org-update-checkbox-count)
12801 (let ((pos (point-marker))
12802 end l1 l2)
12803 (ignore-errors (org-back-to-heading t))
12804 (if (not (org-at-heading-p))
12805 (org-update-checkbox-count)
12806 (setq l1 (org-outline-level))
12807 (setq end (save-excursion
12808 (outline-next-heading)
12809 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12810 (point)))
12811 (if (and (save-excursion
12812 (re-search-forward
12813 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12814 (not (save-excursion (re-search-forward
12815 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12816 (org-update-checkbox-count)
12817 (if (and l2 (> l2 l1))
12818 (progn
12819 (goto-char end)
12820 (org-update-parent-todo-statistics))
12821 (goto-char pos)
12822 (beginning-of-line 1)
12823 (while (re-search-forward
12824 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12825 (point-at-eol) t)
12826 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12827 (goto-char pos)
12828 (move-marker pos nil)))))
12830 (defvar org-entry-property-inherited-from) ;; defined below
12831 (defun org-update-parent-todo-statistics ()
12832 "Update any statistics cookie in the parent of the current headline.
12833 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12834 the entire subtree and this will travel up the hierarchy and update
12835 statistics everywhere."
12836 (let* ((prop (save-excursion (org-up-heading-safe)
12837 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12838 (recursive (or (not org-hierarchical-todo-statistics)
12839 (and prop (string-match "\\<recursive\\>" prop))))
12840 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12842 (first t)
12843 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12844 level ltoggle l1 new ndel
12845 (cnt-all 0) (cnt-done 0) is-percent kwd
12846 checkbox-beg ov ovs ove cookie-present)
12847 (catch 'exit
12848 (save-excursion
12849 (beginning-of-line 1)
12850 (setq ltoggle (funcall outline-level))
12851 ;; Three situations are to consider:
12853 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12854 ;; to the top-level ancestor on the headline;
12856 ;; 2. If parent has "recursive" property, repeat up to the
12857 ;; headline setting that property, taking inheritance into
12858 ;; account;
12860 ;; 3. Else, move up to direct parent and proceed only once.
12861 (while (and (setq level (org-up-heading-safe))
12862 (or recursive first)
12863 (>= (point) lim))
12864 (setq first nil cookie-present nil)
12865 (unless (and level
12866 (not (string-match
12867 "\\<checkbox\\>"
12868 (downcase (or (org-entry-get nil "COOKIE_DATA")
12869 "")))))
12870 (throw 'exit nil))
12871 (while (re-search-forward box-re (point-at-eol) t)
12872 (setq cnt-all 0 cnt-done 0 cookie-present t)
12873 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12874 (save-match-data
12875 (unless (outline-next-heading) (throw 'exit nil))
12876 (while (and (looking-at org-complex-heading-regexp)
12877 (> (setq l1 (length (match-string 1))) level))
12878 (setq kwd (and (or recursive (= l1 ltoggle))
12879 (match-string 2)))
12880 (if (or (eq org-provide-todo-statistics 'all-headlines)
12881 (and (eq org-provide-todo-statistics t)
12882 (or (member kwd org-done-keywords)))
12883 (and (listp org-provide-todo-statistics)
12884 (stringp (car org-provide-todo-statistics))
12885 (or (member kwd org-provide-todo-statistics)
12886 (member kwd org-done-keywords)))
12887 (and (listp org-provide-todo-statistics)
12888 (listp (car org-provide-todo-statistics))
12889 (or (member kwd (car org-provide-todo-statistics))
12890 (and (member kwd org-done-keywords)
12891 (member kwd (cadr org-provide-todo-statistics))))))
12892 (setq cnt-all (1+ cnt-all))
12893 (if (eq org-provide-todo-statistics t)
12894 (and kwd (setq cnt-all (1+ cnt-all)))))
12895 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12896 (member kwd org-done-keywords))
12897 (and (listp org-provide-todo-statistics)
12898 (listp (car org-provide-todo-statistics))
12899 (member kwd org-done-keywords)
12900 (member kwd (cadr org-provide-todo-statistics)))
12901 (and (listp org-provide-todo-statistics)
12902 (stringp (car org-provide-todo-statistics))
12903 (member kwd org-done-keywords)))
12904 (setq cnt-done (1+ cnt-done)))
12905 (outline-next-heading)))
12906 (setq new
12907 (if is-percent
12908 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12909 (format "[%d/%d]" cnt-done cnt-all))
12910 ndel (- (match-end 0) checkbox-beg))
12911 ;; handle overlays when updating cookie from column view
12912 (when (setq ov (car (overlays-at checkbox-beg)))
12913 (setq ovs (overlay-start ov) ove (overlay-end ov))
12914 (delete-overlay ov))
12915 (goto-char checkbox-beg)
12916 (insert new)
12917 (delete-region (point) (+ (point) ndel))
12918 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12919 (when ov (move-overlay ov ovs ove)))
12920 (when cookie-present
12921 (run-hook-with-args 'org-after-todo-statistics-hook
12922 cnt-done (- cnt-all cnt-done))))))
12923 (run-hooks 'org-todo-statistics-hook)))
12925 (defvar org-after-todo-statistics-hook nil
12926 "Hook that is called after a TODO statistics cookie has been updated.
12927 Each function is called with two arguments: the number of not-done entries
12928 and the number of done entries.
12930 For example, the following function, when added to this hook, will switch
12931 an entry to DONE when all children are done, and back to TODO when new
12932 entries are set to a TODO status. Note that this hook is only called
12933 when there is a statistics cookie in the headline!
12935 (defun org-summary-todo (n-done n-not-done)
12936 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12937 (let (org-log-done org-log-states) ; turn off logging
12938 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12941 (defvar org-todo-statistics-hook nil
12942 "Hook that is run whenever Org thinks TODO statistics should be updated.
12943 This hook runs even if there is no statistics cookie present, in which case
12944 `org-after-todo-statistics-hook' would not run.")
12946 (defun org-todo-trigger-tag-changes (state)
12947 "Apply the changes defined in `org-todo-state-tags-triggers'."
12948 (let ((l org-todo-state-tags-triggers)
12949 changes)
12950 (when (or (not state) (equal state ""))
12951 (setq changes (append changes (cdr (assoc "" l)))))
12952 (when (and (stringp state) (> (length state) 0))
12953 (setq changes (append changes (cdr (assoc state l)))))
12954 (when (member state org-not-done-keywords)
12955 (setq changes (append changes (cdr (assoc 'todo l)))))
12956 (when (member state org-done-keywords)
12957 (setq changes (append changes (cdr (assoc 'done l)))))
12958 (dolist (c changes)
12959 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12961 (defun org-local-logging (value)
12962 "Get logging settings from a property VALUE."
12963 (let* (words w a)
12964 ;; directly set the variables, they are already local.
12965 (setq org-log-done nil
12966 org-log-repeat nil
12967 org-todo-log-states nil)
12968 (setq words (org-split-string value))
12969 (while (setq w (pop words))
12970 (cond
12971 ((setq a (assoc w org-startup-options))
12972 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12973 (set (nth 1 a) (nth 2 a))))
12974 ((setq a (org-extract-log-state-settings w))
12975 (and (member (car a) org-todo-keywords-1)
12976 (push a org-todo-log-states)))))))
12978 (defun org-get-todo-sequence-head (kwd)
12979 "Return the head of the TODO sequence to which KWD belongs.
12980 If KWD is not set, check if there is a text property remembering the
12981 right sequence."
12982 (let (p)
12983 (cond
12984 ((not kwd)
12985 (or (get-text-property (point-at-bol) 'org-todo-head)
12986 (progn
12987 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12988 nil (point-at-eol)))
12989 (get-text-property p 'org-todo-head))))
12990 ((not (member kwd org-todo-keywords-1))
12991 (car org-todo-keywords-1))
12992 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12994 (defun org-fast-todo-selection ()
12995 "Fast TODO keyword selection with single keys.
12996 Returns the new TODO keyword, or nil if no state change should occur."
12997 (let* ((fulltable org-todo-key-alist)
12998 (done-keywords org-done-keywords) ;; needed for the faces.
12999 (maxlen (apply 'max (mapcar
13000 (lambda (x)
13001 (if (stringp (car x)) (string-width (car x)) 0))
13002 fulltable)))
13003 (expert nil)
13004 (fwidth (+ maxlen 3 1 3))
13005 (ncol (/ (- (window-width) 4) fwidth))
13006 tg cnt e c tbl
13007 groups ingroup)
13008 (save-excursion
13009 (save-window-excursion
13010 (if expert
13011 (set-buffer (get-buffer-create " *Org todo*"))
13012 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13013 (erase-buffer)
13014 (org-set-local 'org-done-keywords done-keywords)
13015 (setq tbl fulltable cnt 0)
13016 (while (setq e (pop tbl))
13017 (cond
13018 ((equal e '(:startgroup))
13019 (push '() groups) (setq ingroup t)
13020 (when (not (= cnt 0))
13021 (setq cnt 0)
13022 (insert "\n"))
13023 (insert "{ "))
13024 ((equal e '(:endgroup))
13025 (setq ingroup nil cnt 0)
13026 (insert "}\n"))
13027 ((equal e '(:newline))
13028 (when (not (= cnt 0))
13029 (setq cnt 0)
13030 (insert "\n")
13031 (setq e (car tbl))
13032 (while (equal (car tbl) '(:newline))
13033 (insert "\n")
13034 (setq tbl (cdr tbl)))))
13036 (setq tg (car e) c (cdr e))
13037 (if ingroup (push tg (car groups)))
13038 (setq tg (org-add-props tg nil 'face
13039 (org-get-todo-face tg)))
13040 (if (and (= cnt 0) (not ingroup)) (insert " "))
13041 (insert "[" c "] " tg (make-string
13042 (- fwidth 4 (length tg)) ?\ ))
13043 (when (= (setq cnt (1+ cnt)) ncol)
13044 (insert "\n")
13045 (if ingroup (insert " "))
13046 (setq cnt 0)))))
13047 (insert "\n")
13048 (goto-char (point-min))
13049 (if (not expert) (org-fit-window-to-buffer))
13050 (message "[a-z..]:Set [SPC]:clear")
13051 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13052 (cond
13053 ((or (= c ?\C-g)
13054 (and (= c ?q) (not (rassoc c fulltable))))
13055 (setq quit-flag t))
13056 ((= c ?\ ) nil)
13057 ((setq e (rassoc c fulltable) tg (car e))
13059 (t (setq quit-flag t)))))))
13061 (defun org-entry-is-todo-p ()
13062 (member (org-get-todo-state) org-not-done-keywords))
13064 (defun org-entry-is-done-p ()
13065 (member (org-get-todo-state) org-done-keywords))
13067 (defun org-get-todo-state ()
13068 "Return the TODO keyword of the current subtree."
13069 (save-excursion
13070 (org-back-to-heading t)
13071 (and (looking-at org-todo-line-regexp)
13072 (match-end 2)
13073 (match-string 2))))
13075 (defun org-at-date-range-p (&optional inactive-ok)
13076 "Is the cursor inside a date range?"
13077 (interactive)
13078 (save-excursion
13079 (catch 'exit
13080 (let ((pos (point)))
13081 (skip-chars-backward "^[<\r\n")
13082 (skip-chars-backward "<[")
13083 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13084 (>= (match-end 0) pos)
13085 (throw 'exit t))
13086 (skip-chars-backward "^<[\r\n")
13087 (skip-chars-backward "<[")
13088 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13089 (>= (match-end 0) pos)
13090 (throw 'exit t)))
13091 nil)))
13093 (defun org-get-repeat (&optional tagline)
13094 "Check if there is a deadline/schedule with repeater in this entry."
13095 (save-match-data
13096 (save-excursion
13097 (org-back-to-heading t)
13098 (and (re-search-forward (if tagline
13099 (concat tagline "\\s-*" org-repeat-re)
13100 org-repeat-re)
13101 (org-entry-end-position) t)
13102 (match-string-no-properties 1)))))
13104 (defvar org-last-changed-timestamp)
13105 (defvar org-last-inserted-timestamp)
13106 (defvar org-log-post-message)
13107 (defvar org-log-note-purpose)
13108 (defvar org-log-note-how)
13109 (defvar org-log-note-extra)
13110 (defun org-auto-repeat-maybe (done-word)
13111 "Check if the current headline contains a repeated deadline/schedule.
13112 If yes, set TODO state back to what it was and change the base date
13113 of repeating deadline/scheduled time stamps to new date.
13114 This function is run automatically after each state change to a DONE state."
13115 ;; last-state is dynamically scoped into this function
13116 (let* ((repeat (org-get-repeat))
13117 (aa (assoc org-last-state org-todo-kwd-alist))
13118 (interpret (nth 1 aa))
13119 (head (nth 2 aa))
13120 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13121 (msg "Entry repeats: ")
13122 (org-log-done nil)
13123 (org-todo-log-states nil)
13124 re type n what ts time to-state)
13125 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13126 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13127 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13128 org-todo-repeat-to-state))
13129 (unless (and to-state (member to-state org-todo-keywords-1))
13130 (setq to-state (if (eq interpret 'type) org-last-state head)))
13131 (org-todo to-state)
13132 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13133 (org-entry-put nil "LAST_REPEAT" (format-time-string
13134 (org-time-stamp-format t t))))
13135 (when org-log-repeat
13136 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13137 (memq 'org-add-log-note post-command-hook))
13138 ;; OK, we are already setup for some record
13139 (if (eq org-log-repeat 'note)
13140 ;; make sure we take a note, not only a time stamp
13141 (setq org-log-note-how 'note))
13142 ;; Set up for taking a record
13143 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13144 org-last-state
13145 'findpos org-log-repeat)))
13146 (org-back-to-heading t)
13147 (org-add-planning-info nil nil 'closed)
13148 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13149 org-deadline-time-regexp "\\)\\|\\("
13150 org-ts-regexp "\\)"))
13151 (while (re-search-forward
13152 re (save-excursion (outline-next-heading) (point)) t)
13153 (setq type (if (match-end 1) org-scheduled-string
13154 (if (match-end 3) org-deadline-string "Plain:"))
13155 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13156 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13157 (setq n (string-to-number (match-string 2 ts))
13158 what (match-string 3 ts))
13159 (if (equal what "w") (setq n (* n 7) what "d"))
13160 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13161 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13162 ;; Preparation, see if we need to modify the start date for the change
13163 (when (match-end 1)
13164 (setq time (save-match-data (org-time-string-to-time ts)))
13165 (cond
13166 ((equal (match-string 1 ts) ".")
13167 ;; Shift starting date to today
13168 (org-timestamp-change
13169 (- (org-today) (time-to-days time))
13170 'day))
13171 ((equal (match-string 1 ts) "+")
13172 (let ((nshiftmax 10) (nshift 0))
13173 (while (or (= nshift 0)
13174 (<= (time-to-days time)
13175 (time-to-days (current-time))))
13176 (when (= (incf nshift) nshiftmax)
13177 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13178 (user-error "Abort")))
13179 (org-timestamp-change n (cdr (assoc what whata)))
13180 (org-at-timestamp-p t)
13181 (setq ts (match-string 1))
13182 (setq time (save-match-data (org-time-string-to-time ts)))))
13183 (org-timestamp-change (- n) (cdr (assoc what whata)))
13184 ;; rematch, so that we have everything in place for the real shift
13185 (org-at-timestamp-p t)
13186 (setq ts (match-string 1))
13187 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13188 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13189 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13190 (setq org-log-post-message msg)
13191 (message "%s" msg))))
13193 (defun org-show-todo-tree (arg)
13194 "Make a compact tree which shows all headlines marked with TODO.
13195 The tree will show the lines where the regexp matches, and all higher
13196 headlines above the match.
13197 With a \\[universal-argument] prefix, prompt for a regexp to match.
13198 With a numeric prefix N, construct a sparse tree for the Nth element
13199 of `org-todo-keywords-1'."
13200 (interactive "P")
13201 (let ((case-fold-search nil)
13202 (kwd-re
13203 (cond ((null arg) org-not-done-regexp)
13204 ((equal arg '(4))
13205 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13206 (mapcar 'list org-todo-keywords-1))))
13207 (concat "\\("
13208 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13209 "\\)\\>")))
13210 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13211 (regexp-quote (nth (1- (prefix-numeric-value arg))
13212 org-todo-keywords-1)))
13213 (t (user-error "Invalid prefix argument: %s" arg)))))
13214 (message "%d TODO entries found"
13215 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13217 (defun org-deadline (arg &optional time)
13218 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13219 With one universal prefix argument, remove any deadline from the item.
13220 With two universal prefix arguments, prompt for a warning delay.
13221 With argument TIME, set the deadline at the corresponding date. TIME
13222 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13223 (interactive "P")
13224 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13225 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13226 'region-start-level 'region))
13227 org-loop-over-headlines-in-active-region)
13228 (org-map-entries
13229 `(org-deadline ',arg ,time)
13230 org-loop-over-headlines-in-active-region
13231 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13232 (let* ((old-date (org-entry-get nil "DEADLINE"))
13233 (old-date-time (if old-date (org-time-string-to-time old-date)))
13234 (repeater (and old-date
13235 (string-match
13236 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13237 old-date)
13238 (match-string 1 old-date))))
13239 (cond
13240 ((equal arg '(4))
13241 (when (and old-date org-log-redeadline)
13242 (org-add-log-setup 'deldeadline nil old-date 'findpos
13243 org-log-redeadline))
13244 (org-remove-timestamp-with-keyword org-deadline-string)
13245 (message "Item no longer has a deadline."))
13246 ((equal arg '(16))
13247 (save-excursion
13248 (org-back-to-heading t)
13249 (if (re-search-forward
13250 org-deadline-time-regexp
13251 (save-excursion (outline-next-heading) (point)) t)
13252 (let* ((rpl0 (match-string 1))
13253 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13254 (replace-match
13255 (concat org-deadline-string
13256 " <" rpl
13257 (format " -%dd"
13258 (abs
13259 (- (time-to-days
13260 (save-match-data
13261 (org-read-date nil t nil "Warn starting from" old-date-time)))
13262 (time-to-days old-date-time))))
13263 ">") t t))
13264 (user-error "No deadline information to update"))))
13266 (org-add-planning-info 'deadline time 'closed)
13267 (when (and old-date org-log-redeadline
13268 (not (equal old-date
13269 (substring org-last-inserted-timestamp 1 -1))))
13270 (org-add-log-setup 'redeadline nil old-date 'findpos
13271 org-log-redeadline))
13272 (when repeater
13273 (save-excursion
13274 (org-back-to-heading t)
13275 (when (re-search-forward (concat org-deadline-string " "
13276 org-last-inserted-timestamp)
13277 (save-excursion
13278 (outline-next-heading) (point)) t)
13279 (goto-char (1- (match-end 0)))
13280 (insert " " repeater)
13281 (setq org-last-inserted-timestamp
13282 (concat (substring org-last-inserted-timestamp 0 -1)
13283 " " repeater
13284 (substring org-last-inserted-timestamp -1))))))
13285 (message "Deadline on %s" org-last-inserted-timestamp))))))
13287 (defun org-schedule (arg &optional time)
13288 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13289 With one universal prefix argument, remove any scheduling date from the item.
13290 With two universal prefix arguments, prompt for a delay cookie.
13291 With argument TIME, scheduled at the corresponding date. TIME can
13292 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13293 (interactive "P")
13294 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13295 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13296 'region-start-level 'region))
13297 org-loop-over-headlines-in-active-region)
13298 (org-map-entries
13299 `(org-schedule ',arg ,time)
13300 org-loop-over-headlines-in-active-region
13301 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13302 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13303 (old-date-time (if old-date (org-time-string-to-time old-date)))
13304 (repeater (and old-date
13305 (string-match
13306 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13307 old-date)
13308 (match-string 1 old-date))))
13309 (cond
13310 ((equal arg '(4))
13311 (progn
13312 (when (and old-date org-log-reschedule)
13313 (org-add-log-setup 'delschedule nil old-date 'findpos
13314 org-log-reschedule))
13315 (org-remove-timestamp-with-keyword org-scheduled-string)
13316 (message "Item is no longer scheduled.")))
13317 ((equal arg '(16))
13318 (save-excursion
13319 (org-back-to-heading t)
13320 (if (re-search-forward
13321 org-scheduled-time-regexp
13322 (save-excursion (outline-next-heading) (point)) t)
13323 (let* ((rpl0 (match-string 1))
13324 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13325 (replace-match
13326 (concat org-scheduled-string
13327 " <" rpl
13328 (format " -%dd"
13329 (abs
13330 (- (time-to-days
13331 (save-match-data
13332 (org-read-date nil t nil "Delay until" old-date-time)))
13333 (time-to-days old-date-time))))
13334 ">") t t))
13335 (user-error "No scheduled information to update"))))
13337 (org-add-planning-info 'scheduled time 'closed)
13338 (when (and old-date org-log-reschedule
13339 (not (equal old-date
13340 (substring org-last-inserted-timestamp 1 -1))))
13341 (org-add-log-setup 'reschedule nil old-date 'findpos
13342 org-log-reschedule))
13343 (when repeater
13344 (save-excursion
13345 (org-back-to-heading t)
13346 (when (re-search-forward (concat org-scheduled-string " "
13347 org-last-inserted-timestamp)
13348 (save-excursion
13349 (outline-next-heading) (point)) t)
13350 (goto-char (1- (match-end 0)))
13351 (insert " " repeater)
13352 (setq org-last-inserted-timestamp
13353 (concat (substring org-last-inserted-timestamp 0 -1)
13354 " " repeater
13355 (substring org-last-inserted-timestamp -1))))))
13356 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13358 (defun org-get-scheduled-time (pom &optional inherit)
13359 "Get the scheduled time as a time tuple, of a format suitable
13360 for calling org-schedule with, or if there is no scheduling,
13361 returns nil."
13362 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13363 (when time
13364 (apply 'encode-time (org-parse-time-string time)))))
13366 (defun org-get-deadline-time (pom &optional inherit)
13367 "Get the deadline as a time tuple, of a format suitable for
13368 calling org-deadline with, or if there is no scheduling, returns
13369 nil."
13370 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13371 (when time
13372 (apply 'encode-time (org-parse-time-string time)))))
13374 (defun org-remove-timestamp-with-keyword (keyword)
13375 "Remove all time stamps with KEYWORD in the current entry."
13376 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13377 beg)
13378 (save-excursion
13379 (org-back-to-heading t)
13380 (setq beg (point))
13381 (outline-next-heading)
13382 (while (re-search-backward re beg t)
13383 (replace-match "")
13384 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13385 (equal (char-before) ?\ ))
13386 (backward-delete-char 1)
13387 (if (string-match "^[ \t]*$" (buffer-substring
13388 (point-at-bol) (point-at-eol)))
13389 (delete-region (point-at-bol)
13390 (min (point-max) (1+ (point-at-eol))))))))))
13392 (defvar org-time-was-given) ; dynamically scoped parameter
13393 (defvar org-end-time-was-given) ; dynamically scoped parameter
13395 (defun org-add-planning-info (what &optional time &rest remove)
13396 "Insert new timestamp with keyword in the line directly after the headline.
13397 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13398 If non is given, the user is prompted for a date.
13399 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13400 be removed."
13401 (interactive)
13402 (let (org-time-was-given org-end-time-was-given ts
13403 end default-time default-input)
13405 (catch 'exit
13406 (when (and (memq what '(scheduled deadline))
13407 (or (not time)
13408 (and (stringp time)
13409 (string-match "^[-+]+[0-9]" time))))
13410 ;; Try to get a default date/time from existing timestamp
13411 (save-excursion
13412 (org-back-to-heading t)
13413 (setq end (save-excursion (outline-next-heading) (point)))
13414 (when (re-search-forward (if (eq what 'scheduled)
13415 org-scheduled-time-regexp
13416 org-deadline-time-regexp)
13417 end t)
13418 (setq ts (match-string 1)
13419 default-time
13420 (apply 'encode-time (org-parse-time-string ts))
13421 default-input (and ts (org-get-compact-tod ts))))))
13422 (when what
13423 (setq time
13424 (if (stringp time)
13425 ;; This is a string (relative or absolute), set proper date
13426 (apply 'encode-time
13427 (org-read-date-analyze
13428 time default-time (decode-time default-time)))
13429 ;; If necessary, get the time from the user
13430 (or time (org-read-date nil 'to-time nil nil
13431 default-time default-input)))))
13433 (when (and org-insert-labeled-timestamps-at-point
13434 (member what '(scheduled deadline)))
13435 (insert
13436 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13437 (org-insert-time-stamp time org-time-was-given
13438 nil nil nil (list org-end-time-was-given))
13439 (setq what nil))
13440 (save-excursion
13441 (save-restriction
13442 (let (col list elt ts buffer-invisibility-spec)
13443 (org-back-to-heading t)
13444 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13445 (goto-char (match-end 1))
13446 (setq col (current-column))
13447 (goto-char (match-end 0))
13448 (if (eobp) (insert "\n") (forward-char 1))
13449 (when (and (not what)
13450 (not (looking-at
13451 (concat "[ \t]*"
13452 org-keyword-time-not-clock-regexp))))
13453 ;; Nothing to add, nothing to remove...... :-)
13454 (throw 'exit nil))
13455 (if (and (not (looking-at org-outline-regexp))
13456 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13457 "[^\r\n]*"))
13458 (not (equal (match-string 1) org-clock-string)))
13459 (narrow-to-region (match-beginning 0) (match-end 0))
13460 (insert-before-markers "\n")
13461 (backward-char 1)
13462 (narrow-to-region (point) (point))
13463 (and org-adapt-indentation (org-indent-to-column col)))
13464 ;; Check if we have to remove something.
13465 (setq list (cons what remove))
13466 (while list
13467 (setq elt (pop list))
13468 (when (or (and (eq elt 'scheduled)
13469 (re-search-forward org-scheduled-time-regexp nil t))
13470 (and (eq elt 'deadline)
13471 (re-search-forward org-deadline-time-regexp nil t))
13472 (and (eq elt 'closed)
13473 (re-search-forward org-closed-time-regexp nil t)))
13474 (replace-match "")
13475 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13476 (and (looking-at "[ \t]+") (replace-match ""))
13477 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13478 (when what
13479 (insert
13480 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13481 (cond ((eq what 'scheduled) org-scheduled-string)
13482 ((eq what 'deadline) org-deadline-string)
13483 ((eq what 'closed) org-closed-string))
13484 " ")
13485 (setq ts (org-insert-time-stamp
13486 time
13487 (or org-time-was-given
13488 (and (eq what 'closed) org-log-done-with-time))
13489 (eq what 'closed)
13490 nil nil (list org-end-time-was-given)))
13491 (insert
13492 (if (not (or (bolp) (eq (char-before) ?\ )
13493 (memq (char-after) '(32 10))
13494 (eobp))) " " ""))
13495 (end-of-line 1))
13496 (goto-char (point-min))
13497 (widen)
13498 (if (and (looking-at "[ \t]*\n")
13499 (equal (char-before) ?\n))
13500 (delete-region (1- (point)) (point-at-eol)))
13501 ts))))))
13503 (defvar org-log-note-marker (make-marker))
13504 (defvar org-log-note-purpose nil)
13505 (defvar org-log-note-state nil)
13506 (defvar org-log-note-previous-state nil)
13507 (defvar org-log-note-how nil)
13508 (defvar org-log-note-extra nil)
13509 (defvar org-log-note-window-configuration nil)
13510 (defvar org-log-note-return-to (make-marker))
13511 (defvar org-log-note-effective-time nil
13512 "Remembered current time so that dynamically scoped
13513 `org-extend-today-until' affects tha timestamps in state change
13514 log")
13516 (defvar org-log-post-message nil
13517 "Message to be displayed after a log note has been stored.
13518 The auto-repeater uses this.")
13520 (defun org-add-note ()
13521 "Add a note to the current entry.
13522 This is done in the same way as adding a state change note."
13523 (interactive)
13524 (org-add-log-setup 'note nil nil 'findpos nil))
13526 (defvar org-property-end-re)
13527 (defun org-add-log-setup (&optional purpose state prev-state
13528 findpos how extra)
13529 "Set up the post command hook to take a note.
13530 If this is about to TODO state change, the new state is expected in STATE.
13531 When FINDPOS is non-nil, find the correct position for the note in
13532 the current entry. If not, assume that it can be inserted at point.
13533 HOW is an indicator what kind of note should be created.
13534 EXTRA is additional text that will be inserted into the notes buffer."
13535 (let* ((org-log-into-drawer (org-log-into-drawer))
13536 (drawer (cond ((stringp org-log-into-drawer)
13537 org-log-into-drawer)
13538 (org-log-into-drawer "LOGBOOK"))))
13539 (save-restriction
13540 (save-excursion
13541 (when findpos
13542 (org-back-to-heading t)
13543 (narrow-to-region (point) (save-excursion
13544 (outline-next-heading) (point)))
13545 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13546 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13547 "[^\r\n]*\\)?"))
13548 (goto-char (match-end 0))
13549 (cond
13550 (drawer
13551 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13552 nil t)
13553 (progn
13554 (goto-char (match-end 0))
13555 (or org-log-states-order-reversed
13556 (and (re-search-forward org-property-end-re nil t)
13557 (goto-char (1- (match-beginning 0))))))
13558 (insert "\n:" drawer ":\n:END:")
13559 (beginning-of-line 0)
13560 (org-indent-line)
13561 (beginning-of-line 2)
13562 (org-indent-line)
13563 (end-of-line 0)))
13564 ((and org-log-state-notes-insert-after-drawers
13565 (save-excursion
13566 (forward-line) (looking-at org-drawer-regexp)))
13567 (forward-line)
13568 (while (looking-at org-drawer-regexp)
13569 (goto-char (match-end 0))
13570 (re-search-forward org-property-end-re (point-max) t)
13571 (forward-line))
13572 (forward-line -1)))
13573 (unless org-log-states-order-reversed
13574 (and (= (char-after) ?\n) (forward-char 1))
13575 (org-skip-over-state-notes)
13576 (skip-chars-backward " \t\n\r")))
13577 (move-marker org-log-note-marker (point))
13578 (setq org-log-note-purpose purpose
13579 org-log-note-state state
13580 org-log-note-previous-state prev-state
13581 org-log-note-how how
13582 org-log-note-extra extra
13583 org-log-note-effective-time (org-current-effective-time))
13584 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13586 (defun org-skip-over-state-notes ()
13587 "Skip past the list of State notes in an entry."
13588 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13589 (when (ignore-errors (goto-char (org-in-item-p)))
13590 (let* ((struct (org-list-struct))
13591 (prevs (org-list-prevs-alist struct)))
13592 (while (looking-at "[ \t]*- State")
13593 (goto-char (or (org-list-get-next-item (point) struct prevs)
13594 (org-list-get-item-end (point) struct)))))))
13596 (defun org-add-log-note (&optional purpose)
13597 "Pop up a window for taking a note, and add this note later at point."
13598 (remove-hook 'post-command-hook 'org-add-log-note)
13599 (setq org-log-note-window-configuration (current-window-configuration))
13600 (delete-other-windows)
13601 (move-marker org-log-note-return-to (point))
13602 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13603 (goto-char org-log-note-marker)
13604 (org-switch-to-buffer-other-window "*Org Note*")
13605 (erase-buffer)
13606 (if (memq org-log-note-how '(time state))
13607 (let (current-prefix-arg) (org-store-log-note))
13608 (let ((org-inhibit-startup t)) (org-mode))
13609 (insert (format "# Insert note for %s.
13610 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13611 (cond
13612 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13613 ((eq org-log-note-purpose 'done) "closed todo item")
13614 ((eq org-log-note-purpose 'state)
13615 (format "state change from \"%s\" to \"%s\""
13616 (or org-log-note-previous-state "")
13617 (or org-log-note-state "")))
13618 ((eq org-log-note-purpose 'reschedule)
13619 "rescheduling")
13620 ((eq org-log-note-purpose 'delschedule)
13621 "no longer scheduled")
13622 ((eq org-log-note-purpose 'redeadline)
13623 "changing deadline")
13624 ((eq org-log-note-purpose 'deldeadline)
13625 "removing deadline")
13626 ((eq org-log-note-purpose 'refile)
13627 "refiling")
13628 ((eq org-log-note-purpose 'note)
13629 "this entry")
13630 (t (error "This should not happen")))))
13631 (if org-log-note-extra (insert org-log-note-extra))
13632 (org-set-local 'org-finish-function 'org-store-log-note)
13633 (run-hooks 'org-log-buffer-setup-hook)))
13635 (defvar org-note-abort nil) ; dynamically scoped
13636 (defun org-store-log-note ()
13637 "Finish taking a log note, and insert it to where it belongs."
13638 (let ((txt (buffer-string)))
13639 (kill-buffer (current-buffer))
13640 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13641 lines ind bul)
13642 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13643 (setq txt (replace-match "" t t txt)))
13644 (if (string-match "\\s-+\\'" txt)
13645 (setq txt (replace-match "" t t txt)))
13646 (setq lines (org-split-string txt "\n"))
13647 (when (and note (string-match "\\S-" note))
13648 (setq note
13649 (org-replace-escapes
13650 note
13651 (list (cons "%u" (user-login-name))
13652 (cons "%U" user-full-name)
13653 (cons "%t" (format-time-string
13654 (org-time-stamp-format 'long 'inactive)
13655 org-log-note-effective-time))
13656 (cons "%T" (format-time-string
13657 (org-time-stamp-format 'long nil)
13658 org-log-note-effective-time))
13659 (cons "%d" (format-time-string
13660 (org-time-stamp-format nil 'inactive)
13661 org-log-note-effective-time))
13662 (cons "%D" (format-time-string
13663 (org-time-stamp-format nil nil)
13664 org-log-note-effective-time))
13665 (cons "%s" (if org-log-note-state
13666 (concat "\"" org-log-note-state "\"")
13667 ""))
13668 (cons "%S" (if org-log-note-previous-state
13669 (concat "\"" org-log-note-previous-state "\"")
13670 "\"\"")))))
13671 (if lines (setq note (concat note " \\\\")))
13672 (push note lines))
13673 (when (or current-prefix-arg org-note-abort)
13674 (when org-log-into-drawer
13675 (org-remove-empty-drawer-at org-log-note-marker))
13676 (setq lines nil))
13677 (when lines
13678 (with-current-buffer (marker-buffer org-log-note-marker)
13679 (save-excursion
13680 (goto-char org-log-note-marker)
13681 (move-marker org-log-note-marker nil)
13682 (end-of-line 1)
13683 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13684 (setq ind (save-excursion
13685 (if (ignore-errors (goto-char (org-in-item-p)))
13686 (let ((struct (org-list-struct)))
13687 (org-list-get-ind
13688 (org-list-get-top-point struct) struct))
13689 (skip-chars-backward " \r\t\n")
13690 (cond
13691 ((and (org-at-heading-p)
13692 org-adapt-indentation)
13693 (1+ (org-current-level)))
13694 ((org-at-heading-p) 0)
13695 (t (org-get-indentation))))))
13696 (setq bul (org-list-bullet-string "-"))
13697 (org-indent-line-to ind)
13698 (insert bul (pop lines))
13699 (let ((ind-body (+ (length bul) ind)))
13700 (while lines
13701 (insert "\n")
13702 (org-indent-line-to ind-body)
13703 (insert (pop lines))))
13704 (message "Note stored")
13705 (org-back-to-heading t)
13706 (org-cycle-hide-drawers 'children))
13707 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13708 ;; from within `org-add-log-note' because `buffer-undo-list'
13709 ;; is then modified outside of `org-with-remote-undo'.
13710 (when (eq this-command 'org-agenda-todo)
13711 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13712 ;; Don't add undo information when called from `org-agenda-todo'
13713 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13714 (set-window-configuration org-log-note-window-configuration)
13715 (with-current-buffer (marker-buffer org-log-note-return-to)
13716 (goto-char org-log-note-return-to))
13717 (move-marker org-log-note-return-to nil)
13718 (and org-log-post-message (message "%s" org-log-post-message))))
13720 (defun org-remove-empty-drawer-at (pos)
13721 "Remove an empty drawer at position POS.
13722 POS may also be a marker."
13723 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13724 (org-with-wide-buffer
13725 (goto-char pos)
13726 (let ((drawer (org-element-at-point)))
13727 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13728 (not (org-element-property :contents-begin drawer)))
13729 (delete-region (org-element-property :begin drawer)
13730 (progn (goto-char (org-element-property :end drawer))
13731 (skip-chars-backward " \r\t\n")
13732 (forward-line)
13733 (point))))))))
13735 (defvar org-ts-type nil)
13736 (defun org-sparse-tree (&optional arg type)
13737 "Create a sparse tree, prompt for the details.
13738 This command can create sparse trees. You first need to select the type
13739 of match used to create the tree:
13741 t Show all TODO entries.
13742 T Show entries with a specific TODO keyword.
13743 m Show entries selected by a tags/property match.
13744 p Enter a property name and its value (both with completion on existing
13745 names/values) and show entries with that property.
13746 r Show entries matching a regular expression (`/' can be used as well).
13747 b Show deadlines and scheduled items before a date.
13748 a Show deadlines and scheduled items after a date.
13749 d Show deadlines due within `org-deadline-warning-days'.
13750 D Show deadlines and scheduled items between a date range."
13751 (interactive "P")
13752 (setq type (or type org-sparse-tree-default-date-type))
13753 (setq org-ts-type type)
13754 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13755 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13756 [c]ycle through date types: %s"
13757 (case type
13758 (all "all timestamps")
13759 (scheduled "only scheduled")
13760 (deadline "only deadline")
13761 (active "only active timestamps")
13762 (inactive "only inactive timestamps")
13763 (scheduled-or-deadline "scheduled/deadline")
13764 (closed "with a closed time-stamp")
13765 (otherwise "scheduled/deadline")))
13766 (let ((answer (read-char-exclusive)))
13767 (case answer
13769 (org-sparse-tree
13771 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13772 inactive closed)))))
13773 (?d (call-interactively 'org-check-deadlines))
13774 (?b (call-interactively 'org-check-before-date))
13775 (?a (call-interactively 'org-check-after-date))
13776 (?D (call-interactively 'org-check-dates-range))
13777 (?t (call-interactively 'org-show-todo-tree))
13778 (?T (org-show-todo-tree '(4)))
13779 (?m (call-interactively 'org-match-sparse-tree))
13780 ((?p ?P)
13781 (let* ((kwd (org-icompleting-read
13782 "Property: " (mapcar 'list (org-buffer-property-keys))))
13783 (value (org-icompleting-read
13784 "Value: " (mapcar 'list (org-property-values kwd)))))
13785 (unless (string-match "\\`{.*}\\'" value)
13786 (setq value (concat "\"" value "\"")))
13787 (org-match-sparse-tree arg (concat kwd "=" value))))
13788 ((?r ?R ?/) (call-interactively 'org-occur))
13789 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13791 (defvar org-occur-highlights nil
13792 "List of overlays used for occur matches.")
13793 (make-variable-buffer-local 'org-occur-highlights)
13794 (defvar org-occur-parameters nil
13795 "Parameters of the active org-occur calls.
13796 This is a list, each call to org-occur pushes as cons cell,
13797 containing the regular expression and the callback, onto the list.
13798 The list can contain several entries if `org-occur' has been called
13799 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13800 will only contain one set of parameters. When the highlights are
13801 removed (for example with `C-c C-c', or with the next edit (depending
13802 on `org-remove-highlights-with-change'), this variable is emptied
13803 as well.")
13804 (make-variable-buffer-local 'org-occur-parameters)
13806 (defun org-occur (regexp &optional keep-previous callback)
13807 "Make a compact tree which shows all matches of REGEXP.
13808 The tree will show the lines where the regexp matches, and all higher
13809 headlines above the match. It will also show the heading after the match,
13810 to make sure editing the matching entry is easy.
13811 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13812 call to `org-occur' will be kept, to allow stacking of calls to this
13813 command.
13814 If CALLBACK is non-nil, it is a function which is called to confirm
13815 that the match should indeed be shown."
13816 (interactive "sRegexp: \nP")
13817 (when (equal regexp "")
13818 (user-error "Regexp cannot be empty"))
13819 (unless keep-previous
13820 (org-remove-occur-highlights nil nil t))
13821 (push (cons regexp callback) org-occur-parameters)
13822 (let ((cnt 0))
13823 (save-excursion
13824 (goto-char (point-min))
13825 (if (or (not keep-previous) ; do not want to keep
13826 (not org-occur-highlights)) ; no previous matches
13827 ;; hide everything
13828 (org-overview))
13829 (while (re-search-forward regexp nil t)
13830 (when (or (not callback)
13831 (save-match-data (funcall callback)))
13832 (setq cnt (1+ cnt))
13833 (when org-highlight-sparse-tree-matches
13834 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13835 (org-show-context 'occur-tree))))
13836 (when org-remove-highlights-with-change
13837 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13838 nil 'local))
13839 (unless org-sparse-tree-open-archived-trees
13840 (org-hide-archived-subtrees (point-min) (point-max)))
13841 (run-hooks 'org-occur-hook)
13842 (if (org-called-interactively-p 'interactive)
13843 (message "%d match(es) for regexp %s" cnt regexp))
13844 cnt))
13846 (defun org-occur-next-match (&optional n reset)
13847 "Function for `next-error-function' to find sparse tree matches.
13848 N is the number of matches to move, when negative move backwards.
13849 RESET is entirely ignored - this function always goes back to the
13850 starting point when no match is found."
13851 (let* ((limit (if (< n 0) (point-min) (point-max)))
13852 (search-func (if (< n 0)
13853 'previous-single-char-property-change
13854 'next-single-char-property-change))
13855 (n (abs n))
13856 (pos (point))
13858 (catch 'exit
13859 (while (setq p1 (funcall search-func (point) 'org-type))
13860 (when (equal p1 limit)
13861 (goto-char pos)
13862 (user-error "No more matches"))
13863 (when (equal (get-char-property p1 'org-type) 'org-occur)
13864 (setq n (1- n))
13865 (when (= n 0)
13866 (goto-char p1)
13867 (throw 'exit (point))))
13868 (goto-char p1))
13869 (goto-char p1)
13870 (user-error "No more matches"))))
13872 (defun org-show-context (&optional key)
13873 "Make sure point and context are visible.
13874 How much context is shown depends upon the variables
13875 `org-show-hierarchy-above', `org-show-following-heading',
13876 `org-show-entry-below' and `org-show-siblings'."
13877 (let ((heading-p (org-at-heading-p t))
13878 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13879 (following-p (org-get-alist-option org-show-following-heading key))
13880 (entry-p (org-get-alist-option org-show-entry-below key))
13881 (siblings-p (org-get-alist-option org-show-siblings key)))
13882 ;; Show heading or entry text
13883 (if (and heading-p (not entry-p))
13884 (org-flag-heading nil) ; only show the heading
13885 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13886 (org-show-hidden-entry))) ; show entire entry
13887 (when following-p
13888 ;; Show next sibling, or heading below text
13889 (save-excursion
13890 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13891 (org-flag-heading nil))))
13892 (when siblings-p (org-show-siblings))
13893 (when hierarchy-p
13894 ;; show all higher headings, possibly with siblings
13895 (save-excursion
13896 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13897 (not (bobp)))
13898 (org-flag-heading nil)
13899 (when siblings-p (org-show-siblings)))))
13900 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13902 (defvar org-reveal-start-hook nil
13903 "Hook run before revealing a location.")
13905 (defun org-reveal (&optional siblings)
13906 "Show current entry, hierarchy above it, and the following headline.
13907 This can be used to show a consistent set of context around locations
13908 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13909 not t for the search context.
13911 With optional argument SIBLINGS, on each level of the hierarchy all
13912 siblings are shown. This repairs the tree structure to what it would
13913 look like when opened with hierarchical calls to `org-cycle'.
13914 With double optional argument \\[universal-argument] \\[universal-argument], \
13915 go to the parent and show the
13916 entire tree."
13917 (interactive "P")
13918 (run-hooks 'org-reveal-start-hook)
13919 (let ((org-show-hierarchy-above t)
13920 (org-show-following-heading t)
13921 (org-show-siblings (if siblings t org-show-siblings)))
13922 (org-show-context nil))
13923 (when (equal siblings '(16))
13924 (save-excursion
13925 (when (org-up-heading-safe)
13926 (org-show-subtree)
13927 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13929 (defun org-highlight-new-match (beg end)
13930 "Highlight from BEG to END and mark the highlight is an occur headline."
13931 (let ((ov (make-overlay beg end)))
13932 (overlay-put ov 'face 'secondary-selection)
13933 (overlay-put ov 'org-type 'org-occur)
13934 (push ov org-occur-highlights)))
13936 (defun org-remove-occur-highlights (&optional beg end noremove)
13937 "Remove the occur highlights from the buffer.
13938 BEG and END are ignored. If NOREMOVE is nil, remove this function
13939 from the `before-change-functions' in the current buffer."
13940 (interactive)
13941 (unless org-inhibit-highlight-removal
13942 (mapc 'delete-overlay org-occur-highlights)
13943 (setq org-occur-highlights nil)
13944 (setq org-occur-parameters nil)
13945 (unless noremove
13946 (remove-hook 'before-change-functions
13947 'org-remove-occur-highlights 'local))))
13949 ;;;; Priorities
13951 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13952 "Regular expression matching the priority indicator.")
13954 (defvar org-remove-priority-next-time nil)
13956 (defun org-priority-up ()
13957 "Increase the priority of the current item."
13958 (interactive)
13959 (org-priority 'up))
13961 (defun org-priority-down ()
13962 "Decrease the priority of the current item."
13963 (interactive)
13964 (org-priority 'down))
13966 (defun org-priority (&optional action show)
13967 "Change the priority of an item.
13968 ACTION can be `set', `up', `down', or a character."
13969 (interactive "P")
13970 (if (equal action '(4))
13971 (org-show-priority)
13972 (unless org-enable-priority-commands
13973 (user-error "Priority commands are disabled"))
13974 (setq action (or action 'set))
13975 (let (current new news have remove)
13976 (save-excursion
13977 (org-back-to-heading t)
13978 (if (looking-at org-priority-regexp)
13979 (setq current (string-to-char (match-string 2))
13980 have t))
13981 (cond
13982 ((eq action 'remove)
13983 (setq remove t new ?\ ))
13984 ((or (eq action 'set)
13985 (if (featurep 'xemacs) (characterp action) (integerp action)))
13986 (if (not (eq action 'set))
13987 (setq new action)
13988 (message "Priority %c-%c, SPC to remove: "
13989 org-highest-priority org-lowest-priority)
13990 (save-match-data
13991 (setq new (read-char-exclusive))))
13992 (if (and (= (upcase org-highest-priority) org-highest-priority)
13993 (= (upcase org-lowest-priority) org-lowest-priority))
13994 (setq new (upcase new)))
13995 (cond ((equal new ?\ ) (setq remove t))
13996 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13997 (user-error "Priority must be between `%c' and `%c'"
13998 org-highest-priority org-lowest-priority))))
13999 ((eq action 'up)
14000 (setq new (if have
14001 (1- current) ; normal cycling
14002 ;; last priority was empty
14003 (if (eq last-command this-command)
14004 org-lowest-priority ; wrap around empty to lowest
14005 ;; default
14006 (if org-priority-start-cycle-with-default
14007 org-default-priority
14008 (1- org-default-priority))))))
14009 ((eq action 'down)
14010 (setq new (if have
14011 (1+ current) ; normal cycling
14012 ;; last priority was empty
14013 (if (eq last-command this-command)
14014 org-highest-priority ; wrap around empty to highest
14015 ;; default
14016 (if org-priority-start-cycle-with-default
14017 org-default-priority
14018 (1+ org-default-priority))))))
14019 (t (user-error "Invalid action")))
14020 (if (or (< (upcase new) org-highest-priority)
14021 (> (upcase new) org-lowest-priority))
14022 (if (and (memq action '(up down))
14023 (not have) (not (eq last-command this-command)))
14024 ;; `new' is from default priority
14025 (error
14026 "The default can not be set, see `org-default-priority' why")
14027 ;; normal cycling: `new' is beyond highest/lowest priority
14028 ;; and is wrapped around to the empty priority
14029 (setq remove t)))
14030 (setq news (format "%c" new))
14031 (if have
14032 (if remove
14033 (replace-match "" t t nil 1)
14034 (replace-match news t t nil 2))
14035 (if remove
14036 (user-error "No priority cookie found in line")
14037 (let ((case-fold-search nil))
14038 (looking-at org-todo-line-regexp))
14039 (if (match-end 2)
14040 (progn
14041 (goto-char (match-end 2))
14042 (insert " [#" news "]"))
14043 (goto-char (match-beginning 3))
14044 (insert "[#" news "] "))))
14045 (org-set-tags nil 'align))
14046 (if remove
14047 (message "Priority removed")
14048 (message "Priority of current item set to %s" news)))))
14050 (defun org-show-priority ()
14051 "Show the priority of the current item.
14052 This priority is composed of the main priority given with the [#A] cookies,
14053 and by additional input from the age of a schedules or deadline entry."
14054 (interactive)
14055 (let ((pri (if (eq major-mode 'org-agenda-mode)
14056 (org-get-at-bol 'priority)
14057 (save-excursion
14058 (save-match-data
14059 (beginning-of-line)
14060 (and (looking-at org-heading-regexp)
14061 (org-get-priority (match-string 0))))))))
14062 (message "Priority is %d" (if pri pri -1000))))
14064 (defun org-get-priority (s)
14065 "Find priority cookie and return priority."
14066 (save-match-data
14067 (if (functionp org-get-priority-function)
14068 (funcall org-get-priority-function)
14069 (if (not (string-match org-priority-regexp s))
14070 (* 1000 (- org-lowest-priority org-default-priority))
14071 (* 1000 (- org-lowest-priority
14072 (string-to-char (match-string 2 s))))))))
14074 ;;;; Tags
14076 (defvar org-agenda-archives-mode)
14077 (defvar org-map-continue-from nil
14078 "Position from where mapping should continue.
14079 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14081 (defvar org-scanner-tags nil
14082 "The current tag list while the tags scanner is running.")
14083 (defvar org-trust-scanner-tags nil
14084 "Should `org-get-tags-at' use the tags for the scanner.
14085 This is for internal dynamical scoping only.
14086 When this is non-nil, the function `org-get-tags-at' will return the value
14087 of `org-scanner-tags' instead of building the list by itself. This
14088 can lead to large speed-ups when the tags scanner is used in a file with
14089 many entries, and when the list of tags is retrieved, for example to
14090 obtain a list of properties. Building the tags list for each entry in such
14091 a file becomes an N^2 operation - but with this variable set, it scales
14092 as N.")
14094 (defun org-scan-tags (action matcher todo-only &optional start-level)
14095 "Scan headline tags with inheritance and produce output ACTION.
14097 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14098 or `agenda' to produce an entry list for an agenda view. It can also be
14099 a Lisp form or a function that should be called at each matched headline, in
14100 this case the return value is a list of all return values from these calls.
14102 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14103 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14104 only lines with a not-done TODO keyword are included in the output.
14105 This should be the same variable that was scoped into
14106 and set by `org-make-tags-matcher' when it constructed MATCHER.
14108 START-LEVEL can be a string with asterisks, reducing the scope to
14109 headlines matching this string."
14110 (require 'org-agenda)
14111 (let* ((re (concat "^"
14112 (if start-level
14113 ;; Get the correct level to match
14114 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14115 org-outline-regexp)
14116 " *\\(\\<\\("
14117 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14118 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14119 (props (list 'face 'default
14120 'done-face 'org-agenda-done
14121 'undone-face 'default
14122 'mouse-face 'highlight
14123 'org-not-done-regexp org-not-done-regexp
14124 'org-todo-regexp org-todo-regexp
14125 'org-complex-heading-regexp org-complex-heading-regexp
14126 'help-echo
14127 (format "mouse-2 or RET jump to org file %s"
14128 (abbreviate-file-name
14129 (or (buffer-file-name (buffer-base-buffer))
14130 (buffer-name (buffer-base-buffer)))))))
14131 (org-map-continue-from nil)
14132 lspos tags tags-list
14133 (tags-alist (list (cons 0 org-file-tags)))
14134 (llast 0) rtn rtn1 level category i txt
14135 todo marker entry priority)
14136 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14137 (setq action (list 'lambda nil action)))
14138 (save-excursion
14139 (goto-char (point-min))
14140 (when (eq action 'sparse-tree)
14141 (org-overview)
14142 (org-remove-occur-highlights))
14143 (while (let (case-fold-search)
14144 (re-search-forward re nil t))
14145 (setq org-map-continue-from nil)
14146 (catch :skip
14147 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14148 tags (if (match-end 4) (org-match-string-no-properties 4)))
14149 (goto-char (setq lspos (match-beginning 0)))
14150 (setq level (org-reduced-level (org-outline-level))
14151 category (org-get-category))
14152 (setq i llast llast level)
14153 ;; remove tag lists from same and sublevels
14154 (while (>= i level)
14155 (when (setq entry (assoc i tags-alist))
14156 (setq tags-alist (delete entry tags-alist)))
14157 (setq i (1- i)))
14158 ;; add the next tags
14159 (when tags
14160 (setq tags (org-split-string tags ":")
14161 tags-alist
14162 (cons (cons level tags) tags-alist)))
14163 ;; compile tags for current headline
14164 (setq tags-list
14165 (if org-use-tag-inheritance
14166 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14167 tags)
14168 org-scanner-tags tags-list)
14169 (when org-use-tag-inheritance
14170 (setcdr (car tags-alist)
14171 (mapcar (lambda (x)
14172 (setq x (copy-sequence x))
14173 (org-add-prop-inherited x))
14174 (cdar tags-alist))))
14175 (when (and tags org-use-tag-inheritance
14176 (or (not (eq t org-use-tag-inheritance))
14177 org-tags-exclude-from-inheritance))
14178 ;; selective inheritance, remove uninherited ones
14179 (setcdr (car tags-alist)
14180 (org-remove-uninherited-tags (cdar tags-alist))))
14181 (when (and
14183 ;; eval matcher only when the todo condition is OK
14184 (and (or (not todo-only) (member todo org-not-done-keywords))
14185 (let ((case-fold-search t) (org-trust-scanner-tags t))
14186 (eval matcher)))
14188 ;; Call the skipper, but return t if it does not skip,
14189 ;; so that the `and' form continues evaluating
14190 (progn
14191 (unless (eq action 'sparse-tree) (org-agenda-skip))
14194 ;; Check if timestamps are deselecting this entry
14195 (or (not todo-only)
14196 (and (member todo org-not-done-keywords)
14197 (or (not org-agenda-tags-todo-honor-ignore-options)
14198 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14200 ;; select this headline
14201 (cond
14202 ((eq action 'sparse-tree)
14203 (and org-highlight-sparse-tree-matches
14204 (org-get-heading) (match-end 0)
14205 (org-highlight-new-match
14206 (match-beginning 1) (match-end 1)))
14207 (org-show-context 'tags-tree))
14208 ((eq action 'agenda)
14209 (setq txt (org-agenda-format-item
14211 (concat
14212 (if (eq org-tags-match-list-sublevels 'indented)
14213 (make-string (1- level) ?.) "")
14214 (org-get-heading))
14215 level category
14216 tags-list)
14217 priority (org-get-priority txt))
14218 (goto-char lspos)
14219 (setq marker (org-agenda-new-marker))
14220 (org-add-props txt props
14221 'org-marker marker 'org-hd-marker marker 'org-category category
14222 'todo-state todo
14223 'priority priority 'type "tagsmatch")
14224 (push txt rtn))
14225 ((functionp action)
14226 (setq org-map-continue-from nil)
14227 (save-excursion
14228 (setq rtn1 (funcall action))
14229 (push rtn1 rtn)))
14230 (t (user-error "Invalid action")))
14232 ;; if we are to skip sublevels, jump to end of subtree
14233 (unless org-tags-match-list-sublevels
14234 (org-end-of-subtree t)
14235 (backward-char 1))))
14236 ;; Get the correct position from where to continue
14237 (if org-map-continue-from
14238 (goto-char org-map-continue-from)
14239 (and (= (point) lspos) (end-of-line 1)))))
14240 (when (and (eq action 'sparse-tree)
14241 (not org-sparse-tree-open-archived-trees))
14242 (org-hide-archived-subtrees (point-min) (point-max)))
14243 (nreverse rtn)))
14245 (defun org-remove-uninherited-tags (tags)
14246 "Remove all tags that are not inherited from the list TAGS."
14247 (cond
14248 ((eq org-use-tag-inheritance t)
14249 (if org-tags-exclude-from-inheritance
14250 (org-delete-all org-tags-exclude-from-inheritance tags)
14251 tags))
14252 ((not org-use-tag-inheritance) nil)
14253 ((stringp org-use-tag-inheritance)
14254 (delq nil (mapcar
14255 (lambda (x)
14256 (if (and (string-match org-use-tag-inheritance x)
14257 (not (member x org-tags-exclude-from-inheritance)))
14258 x nil))
14259 tags)))
14260 ((listp org-use-tag-inheritance)
14261 (delq nil (mapcar
14262 (lambda (x)
14263 (if (member x org-use-tag-inheritance) x nil))
14264 tags)))))
14266 (defun org-match-sparse-tree (&optional todo-only match)
14267 "Create a sparse tree according to tags string MATCH.
14268 MATCH can contain positive and negative selection of tags, like
14269 \"+WORK+URGENT-WITHBOSS\".
14270 If optional argument TODO-ONLY is non-nil, only select lines that are
14271 also TODO lines."
14272 (interactive "P")
14273 (org-agenda-prepare-buffers (list (current-buffer)))
14274 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14276 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14278 (defvar org-cached-props nil)
14279 (defun org-cached-entry-get (pom property)
14280 (if (or (eq t org-use-property-inheritance)
14281 (and (stringp org-use-property-inheritance)
14282 (string-match org-use-property-inheritance property))
14283 (and (listp org-use-property-inheritance)
14284 (member property org-use-property-inheritance)))
14285 ;; Caching is not possible, check it directly
14286 (org-entry-get pom property 'inherit)
14287 ;; Get all properties, so that we can do complicated checks easily
14288 (cdr (assoc property (or org-cached-props
14289 (setq org-cached-props
14290 (org-entry-properties pom)))))))
14292 (defun org-global-tags-completion-table (&optional files)
14293 "Return the list of all tags in all agenda buffer/files.
14294 Optional FILES argument is a list of files which can be used
14295 instead of the agenda files."
14296 (save-excursion
14297 (org-uniquify
14298 (delq nil
14299 (apply 'append
14300 (mapcar
14301 (lambda (file)
14302 (set-buffer (find-file-noselect file))
14303 (append (org-get-buffer-tags)
14304 (mapcar (lambda (x) (if (stringp (car-safe x))
14305 (list (car-safe x)) nil))
14306 org-tag-alist)))
14307 (if (and files (car files))
14308 files
14309 (org-agenda-files))))))))
14311 (defun org-make-tags-matcher (match)
14312 "Create the TAGS/TODO matcher form for the selection string MATCH.
14314 The variable `todo-only' is scoped dynamically into this function.
14315 It will be set to t if the matcher restricts matching to TODO entries,
14316 otherwise will not be touched.
14318 Returns a cons of the selection string MATCH and the constructed
14319 lisp form implementing the matcher. The matcher is to be evaluated
14320 at an Org entry, with point on the headline, and returns t if the
14321 entry matches the selection string MATCH. The returned lisp form
14322 references two variables with information about the entry, which
14323 must be bound around the form's evaluation: todo, the TODO keyword
14324 at the entry (or nil of none); and tags-list, the list of all tags
14325 at the entry including inherited ones. Additionally, the category
14326 of the entry (if any) must be specified as the text property
14327 'org-category on the headline.
14329 See also `org-scan-tags'.
14331 (declare (special todo-only))
14332 (unless (boundp 'todo-only)
14333 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14334 (unless match
14335 ;; Get a new match request, with completion against the global
14336 ;; tags table and the local tags in current buffer
14337 (let ((org-last-tags-completion-table
14338 (org-uniquify
14339 (delq nil (append (org-get-buffer-tags)
14340 (org-global-tags-completion-table))))))
14341 (setq match (org-completing-read-no-i
14342 "Match: " 'org-tags-completion-function nil nil nil
14343 'org-tags-history))))
14345 ;; Parse the string and create a lisp form
14346 (let ((match0 match)
14347 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14348 minus tag mm
14349 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14350 orterms term orlist re-p str-p level-p level-op time-p
14351 prop-p pn pv po gv rest (start 0) (ss 0))
14352 ;; Expand group tags
14353 (setq match (org-tags-expand match))
14355 ;; Check if there is a TODO part of this match, which would be the
14356 ;; part after a "/". TO make sure that this slash is not part of
14357 ;; a property value to be matched against, we also check that there
14358 ;; is no " after that slash.
14359 ;; First, find the last slash
14360 (while (string-match "/+" match ss)
14361 (setq start (match-beginning 0) ss (match-end 0)))
14362 (if (and (string-match "/+" match start)
14363 (not (save-match-data (string-match "\"" match start))))
14364 ;; match contains also a todo-matching request
14365 (progn
14366 (setq tagsmatch (substring match 0 (match-beginning 0))
14367 todomatch (substring match (match-end 0)))
14368 (if (string-match "^!" todomatch)
14369 (setq todo-only t todomatch (substring todomatch 1)))
14370 (if (string-match "^\\s-*$" todomatch)
14371 (setq todomatch nil)))
14372 ;; only matching tags
14373 (setq tagsmatch match todomatch nil))
14375 ;; Make the tags matcher
14376 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14377 (setq tagsmatcher t)
14378 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14379 (while (setq term (pop orterms))
14380 (while (and (equal (substring term -1) "\\") orterms)
14381 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14382 (while (string-match re term)
14383 (setq rest (substring term (match-end 0))
14384 minus (and (match-end 1)
14385 (equal (match-string 1 term) "-"))
14386 tag (save-match-data (replace-regexp-in-string
14387 "\\\\-" "-"
14388 (match-string 2 term)))
14389 re-p (equal (string-to-char tag) ?{)
14390 level-p (match-end 4)
14391 prop-p (match-end 5)
14392 mm (cond
14393 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14394 (level-p
14395 (setq level-op (org-op-to-function (match-string 3 term)))
14396 `(,level-op level ,(string-to-number
14397 (match-string 4 term))))
14398 (prop-p
14399 (setq pn (match-string 5 term)
14400 po (match-string 6 term)
14401 pv (match-string 7 term)
14402 re-p (equal (string-to-char pv) ?{)
14403 str-p (equal (string-to-char pv) ?\")
14404 time-p (save-match-data
14405 (string-match "^\"[[<].*[]>]\"$" pv))
14406 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14407 (if time-p (setq pv (org-matcher-time pv)))
14408 (setq po (org-op-to-function po (if time-p 'time str-p)))
14409 (cond
14410 ((equal pn "CATEGORY")
14411 (setq gv '(get-text-property (point) 'org-category)))
14412 ((equal pn "TODO")
14413 (setq gv 'todo))
14415 (setq gv `(org-cached-entry-get nil ,pn))))
14416 (if re-p
14417 (if (eq po 'org<>)
14418 `(not (string-match ,pv (or ,gv "")))
14419 `(string-match ,pv (or ,gv "")))
14420 (if str-p
14421 `(,po (or ,gv "") ,pv)
14422 `(,po (string-to-number (or ,gv ""))
14423 ,(string-to-number pv) ))))
14424 (t `(member ,tag tags-list)))
14425 mm (if minus (list 'not mm) mm)
14426 term rest)
14427 (push mm tagsmatcher))
14428 (push (if (> (length tagsmatcher) 1)
14429 (cons 'and tagsmatcher)
14430 (car tagsmatcher))
14431 orlist)
14432 (setq tagsmatcher nil))
14433 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14434 (setq tagsmatcher
14435 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14436 ;; Make the todo matcher
14437 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14438 (setq todomatcher t)
14439 (setq orterms (org-split-string todomatch "|") orlist nil)
14440 (while (setq term (pop orterms))
14441 (while (string-match re term)
14442 (setq minus (and (match-end 1)
14443 (equal (match-string 1 term) "-"))
14444 kwd (match-string 2 term)
14445 re-p (equal (string-to-char kwd) ?{)
14446 term (substring term (match-end 0))
14447 mm (if re-p
14448 `(string-match ,(substring kwd 1 -1) todo)
14449 (list 'equal 'todo kwd))
14450 mm (if minus (list 'not mm) mm))
14451 (push mm todomatcher))
14452 (push (if (> (length todomatcher) 1)
14453 (cons 'and todomatcher)
14454 (car todomatcher))
14455 orlist)
14456 (setq todomatcher nil))
14457 (setq todomatcher (if (> (length orlist) 1)
14458 (cons 'or orlist) (car orlist))))
14460 ;; Return the string and lisp forms of the matcher
14461 (setq matcher (if todomatcher
14462 (list 'and tagsmatcher todomatcher)
14463 tagsmatcher))
14464 (when todo-only
14465 (setq matcher (list 'and '(member todo org-not-done-keywords)
14466 matcher)))
14467 (cons match0 matcher)))
14469 (defun org-tags-expand (match &optional single-as-list downcased)
14470 "Expand group tags in MATCH.
14472 This replaces every group tag in MATCH with a regexp tag search.
14473 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14474 will be replaced like this:
14476 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14477 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14478 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14480 Replacing by a regexp preserves the structure of the match.
14481 E.g., this expansion
14483 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14485 will match anything tagged with \"Lab\" and \"Home\", or tagged
14486 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14488 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14489 assumed to be a single group tag, and the function will return
14490 the list of tags in this group.
14492 When DOWNCASE is non-nil, expand downcased TAGS."
14493 (if org-group-tags
14494 (let* ((case-fold-search t)
14495 (stable org-mode-syntax-table)
14496 (tal (or org-tag-groups-alist-for-agenda
14497 org-tag-groups-alist))
14498 (tal (if downcased
14499 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14500 (tml (mapcar 'car tal))
14501 (rtnmatch match) rpl)
14502 ;; @ and _ are allowed as word-components in tags
14503 (modify-syntax-entry ?@ "w" stable)
14504 (modify-syntax-entry ?_ "w" stable)
14505 (while (and tml
14506 (with-syntax-table stable
14507 (string-match
14508 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14509 (regexp-opt tml) "\\>\\)") rtnmatch)))
14510 (let* ((dir (match-string 1 rtnmatch))
14511 (tag (match-string 2 rtnmatch))
14512 (tag (if downcased (downcase tag) tag)))
14513 (setq tml (delete tag tml))
14514 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14515 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14516 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14517 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14518 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14519 (if single-as-list
14520 (or (reverse rpl) (list rtnmatch))
14521 rtnmatch))
14522 (if single-as-list (list (if downcased (downcase match) match))
14523 match)))
14525 (defun org-op-to-function (op &optional stringp)
14526 "Turn an operator into the appropriate function."
14527 (setq op
14528 (cond
14529 ((equal op "<" ) '(< string< org-time<))
14530 ((equal op ">" ) '(> org-string> org-time>))
14531 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14532 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14533 ((member op '("=" "==")) '(= string= org-time=))
14534 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14535 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14537 (defun org<> (a b) (not (= a b)))
14538 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14539 (defun org-string>= (a b) (not (string< a b)))
14540 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14541 (defun org-string<> (a b) (not (string= 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) (<= a b)))
14545 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14546 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14547 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14548 (defun org-2ft (s)
14549 "Convert S to a floating point time.
14550 If S is already a number, just return it. If it is a string, parse
14551 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14552 (cond
14553 ((numberp s) s)
14554 ((stringp s)
14555 (condition-case nil
14556 (float-time (apply 'encode-time (org-parse-time-string s)))
14557 (error 0.)))
14558 (t 0.)))
14560 (defun org-time-today ()
14561 "Time in seconds today at 0:00.
14562 Returns the float number of seconds since the beginning of the
14563 epoch to the beginning of today (00:00)."
14564 (float-time (apply 'encode-time
14565 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14567 (defun org-matcher-time (s)
14568 "Interpret a time comparison value."
14569 (save-match-data
14570 (cond
14571 ((string= s "<now>") (float-time))
14572 ((string= s "<today>") (org-time-today))
14573 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14574 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14575 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14576 (+ (org-time-today)
14577 (* (string-to-number (match-string 1 s))
14578 (cdr (assoc (match-string 2 s)
14579 '(("d" . 86400.0) ("w" . 604800.0)
14580 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14581 (t (org-2ft s)))))
14583 (defun org-match-any-p (re list)
14584 "Does re match any element of list?"
14585 (setq list (mapcar (lambda (x) (string-match re x)) list))
14586 (delq nil list))
14588 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14589 (defvar org-tags-overlay (make-overlay 1 1))
14590 (org-detach-overlay org-tags-overlay)
14592 (defun org-get-local-tags-at (&optional pos)
14593 "Get a list of tags defined in the current headline."
14594 (org-get-tags-at pos 'local))
14596 (defun org-get-local-tags ()
14597 "Get a list of tags defined in the current headline."
14598 (org-get-tags-at nil 'local))
14600 (defun org-get-tags-at (&optional pos local)
14601 "Get a list of all headline tags applicable at POS.
14602 POS defaults to point. If tags are inherited, the list contains
14603 the targets in the same sequence as the headlines appear, i.e.
14604 the tags of the current headline come last.
14605 When LOCAL is non-nil, only return tags from the current headline,
14606 ignore inherited ones."
14607 (interactive)
14608 (if (and org-trust-scanner-tags
14609 (or (not pos) (equal pos (point)))
14610 (not local))
14611 org-scanner-tags
14612 (let (tags ltags lastpos parent)
14613 (save-excursion
14614 (save-restriction
14615 (widen)
14616 (goto-char (or pos (point)))
14617 (save-match-data
14618 (catch 'done
14619 (condition-case nil
14620 (progn
14621 (org-back-to-heading t)
14622 (while (not (equal lastpos (point)))
14623 (setq lastpos (point))
14624 (when (looking-at
14625 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14626 (setq ltags (org-split-string
14627 (org-match-string-no-properties 1) ":"))
14628 (when parent
14629 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14630 (setq tags (append
14631 (if parent
14632 (org-remove-uninherited-tags ltags)
14633 ltags)
14634 tags)))
14635 (or org-use-tag-inheritance (throw 'done t))
14636 (if local (throw 'done t))
14637 (or (org-up-heading-safe) (error nil))
14638 (setq parent t)))
14639 (error nil)))))
14640 (if local
14641 tags
14642 (reverse (delete-dups
14643 (reverse (append
14644 (org-remove-uninherited-tags
14645 org-file-tags) tags)))))))))
14647 (defun org-add-prop-inherited (s)
14648 (add-text-properties 0 (length s) '(inherited t) s)
14651 (defun org-toggle-tag (tag &optional onoff)
14652 "Toggle the tag TAG for the current line.
14653 If ONOFF is `on' or `off', don't toggle but set to this state."
14654 (let (res current)
14655 (save-excursion
14656 (org-back-to-heading t)
14657 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14658 (point-at-eol) t)
14659 (progn
14660 (setq current (match-string 1))
14661 (replace-match ""))
14662 (setq current ""))
14663 (setq current (nreverse (org-split-string current ":")))
14664 (cond
14665 ((eq onoff 'on)
14666 (setq res t)
14667 (or (member tag current) (push tag current)))
14668 ((eq onoff 'off)
14669 (or (not (member tag current)) (setq current (delete tag current))))
14670 (t (if (member tag current)
14671 (setq current (delete tag current))
14672 (setq res t)
14673 (push tag current))))
14674 (end-of-line 1)
14675 (if current
14676 (progn
14677 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14678 (org-set-tags nil t))
14679 (delete-horizontal-space))
14680 (run-hooks 'org-after-tags-change-hook))
14681 res))
14683 (defun org-align-tags-here (to-col)
14684 ;; Assumes that this is a headline
14685 "Align tags on the current headline to TO-COL."
14686 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14687 (beginning-of-line 1)
14688 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14689 (< pos (match-beginning 2)))
14690 (progn
14691 (setq tags-l (- (match-end 2) (match-beginning 2)))
14692 (goto-char (match-beginning 1))
14693 (insert " ")
14694 (delete-region (point) (1+ (match-beginning 2)))
14695 (setq ncol (max (current-column)
14696 (1+ col)
14697 (if (> to-col 0)
14698 to-col
14699 (- (abs to-col) tags-l))))
14700 (setq p (point))
14701 (insert (make-string (- ncol (current-column)) ?\ ))
14702 (setq ncol (current-column))
14703 (when indent-tabs-mode (tabify p (point-at-eol)))
14704 (org-move-to-column (min ncol col)))
14705 (goto-char pos))))
14707 (defun org-set-tags-command (&optional arg just-align)
14708 "Call the set-tags command for the current entry."
14709 (interactive "P")
14710 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14711 (org-set-tags arg just-align)
14712 (save-excursion
14713 (unless (and (org-region-active-p)
14714 org-loop-over-headlines-in-active-region)
14715 (org-back-to-heading t))
14716 (org-set-tags arg just-align))))
14718 (defun org-set-tags-to (data)
14719 "Set the tags of the current entry to DATA, replacing the current tags.
14720 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14721 If DATA is nil or the empty string, any tags will be removed."
14722 (interactive "sTags: ")
14723 (setq data
14724 (cond
14725 ((eq data nil) "")
14726 ((equal data "") "")
14727 ((stringp data)
14728 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14729 ":"))
14730 ((listp data)
14731 (concat ":" (mapconcat 'identity data ":") ":"))))
14732 (when data
14733 (save-excursion
14734 (org-back-to-heading t)
14735 (when (looking-at org-complex-heading-regexp)
14736 (if (match-end 5)
14737 (progn
14738 (goto-char (match-beginning 5))
14739 (insert data)
14740 (delete-region (point) (point-at-eol))
14741 (org-set-tags nil 'align))
14742 (goto-char (point-at-eol))
14743 (insert " " data)
14744 (org-set-tags nil 'align)))
14745 (beginning-of-line 1)
14746 (if (looking-at ".*?\\([ \t]+\\)$")
14747 (delete-region (match-beginning 1) (match-end 1))))))
14749 (defun org-align-all-tags ()
14750 "Align the tags i all headings."
14751 (interactive)
14752 (save-excursion
14753 (or (ignore-errors (org-back-to-heading t))
14754 (outline-next-heading))
14755 (if (org-at-heading-p)
14756 (org-set-tags t)
14757 (message "No headings"))))
14759 (defvar org-indent-indentation-per-level)
14760 (defun org-set-tags (&optional arg just-align)
14761 "Set the tags for the current headline.
14762 With prefix ARG, realign all tags in headings in the current buffer.
14763 When JUST-ALIGN is non-nil, only align tags."
14764 (interactive "P")
14765 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14766 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14767 'region-start-level 'region))
14768 org-loop-over-headlines-in-active-region)
14769 (org-map-entries
14770 ;; We don't use ARG and JUST-ALIGN here because these args
14771 ;; are not useful when looping over headlines.
14772 `(org-set-tags)
14773 org-loop-over-headlines-in-active-region
14774 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14775 (let* ((re org-outline-regexp-bol)
14776 (current (unless arg (org-get-tags-string)))
14777 (col (current-column))
14778 (org-setting-tags t)
14779 table current-tags inherited-tags ; computed below when needed
14780 tags p0 c0 c1 rpl di tc level)
14781 (if arg
14782 (save-excursion
14783 (goto-char (point-min))
14784 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14785 (while (re-search-forward re nil t)
14786 (org-set-tags nil t)
14787 (end-of-line 1)))
14788 (message "All tags realigned to column %d" org-tags-column))
14789 (if just-align
14790 (setq tags current)
14791 ;; Get a new set of tags from the user
14792 (save-excursion
14793 (setq table (append org-tag-persistent-alist
14794 (or org-tag-alist (org-get-buffer-tags))
14795 (and
14796 org-complete-tags-always-offer-all-agenda-tags
14797 (org-global-tags-completion-table
14798 (org-agenda-files))))
14799 org-last-tags-completion-table table
14800 current-tags (org-split-string current ":")
14801 inherited-tags (nreverse
14802 (nthcdr (length current-tags)
14803 (nreverse (org-get-tags-at))))
14804 tags
14805 (if (or (eq t org-use-fast-tag-selection)
14806 (and org-use-fast-tag-selection
14807 (delq nil (mapcar 'cdr table))))
14808 (org-fast-tag-selection
14809 current-tags inherited-tags table
14810 (if org-fast-tag-selection-include-todo
14811 org-todo-key-alist))
14812 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14813 (org-trim
14814 (org-icompleting-read "Tags: "
14815 'org-tags-completion-function
14816 nil nil current 'org-tags-history))))))
14817 (while (string-match "[-+&]+" tags)
14818 ;; No boolean logic, just a list
14819 (setq tags (replace-match ":" t t tags))))
14821 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14823 (if org-tags-sort-function
14824 (setq tags (mapconcat 'identity
14825 (sort (org-split-string
14826 tags (org-re "[^[:alnum:]_@#%]+"))
14827 org-tags-sort-function) ":")))
14829 (if (string-match "\\`[\t ]*\\'" tags)
14830 (setq tags "")
14831 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14832 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14834 ;; Insert new tags at the correct column
14835 (beginning-of-line 1)
14836 (setq level (or (and (looking-at org-outline-regexp)
14837 (- (match-end 0) (point) 1))
14839 (cond
14840 ((and (equal current "") (equal tags "")))
14841 ((re-search-forward
14842 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14843 (point-at-eol) t)
14844 (if (equal tags "")
14845 (setq rpl "")
14846 (goto-char (match-beginning 0))
14847 (setq c0 (current-column)
14848 ;; compute offset for the case of org-indent-mode active
14849 di (if (org-bound-and-true-p org-indent-mode)
14850 (* (1- org-indent-indentation-per-level) (1- level))
14852 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14853 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14854 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14855 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14856 (replace-match rpl t t)
14857 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14858 tags)
14859 (t (error "Tags alignment failed")))
14860 (org-move-to-column col)
14861 (unless just-align
14862 (run-hooks 'org-after-tags-change-hook))))))
14864 (defun org-change-tag-in-region (beg end tag off)
14865 "Add or remove TAG for each entry in the region.
14866 This works in the agenda, and also in an org-mode buffer."
14867 (interactive
14868 (list (region-beginning) (region-end)
14869 (let ((org-last-tags-completion-table
14870 (if (derived-mode-p 'org-mode)
14871 (org-uniquify
14872 (delq nil (append (org-get-buffer-tags)
14873 (org-global-tags-completion-table))))
14874 (org-global-tags-completion-table))))
14875 (org-icompleting-read
14876 "Tag: " 'org-tags-completion-function nil nil nil
14877 'org-tags-history))
14878 (progn
14879 (message "[s]et or [r]emove? ")
14880 (equal (read-char-exclusive) ?r))))
14881 (if (fboundp 'deactivate-mark) (deactivate-mark))
14882 (let ((agendap (equal major-mode 'org-agenda-mode))
14883 l1 l2 m buf pos newhead (cnt 0))
14884 (goto-char end)
14885 (setq l2 (1- (org-current-line)))
14886 (goto-char beg)
14887 (setq l1 (org-current-line))
14888 (loop for l from l1 to l2 do
14889 (org-goto-line l)
14890 (setq m (get-text-property (point) 'org-hd-marker))
14891 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14892 (and agendap m))
14893 (setq buf (if agendap (marker-buffer m) (current-buffer))
14894 pos (if agendap m (point)))
14895 (with-current-buffer buf
14896 (save-excursion
14897 (save-restriction
14898 (goto-char pos)
14899 (setq cnt (1+ cnt))
14900 (org-toggle-tag tag (if off 'off 'on))
14901 (setq newhead (org-get-heading)))))
14902 (and agendap (org-agenda-change-all-lines newhead m))))
14903 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14905 (defun org-tags-completion-function (string predicate &optional flag)
14906 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14907 (confirm (lambda (x) (stringp (car x)))))
14908 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14909 (setq s1 (match-string 1 string)
14910 s2 (match-string 2 string))
14911 (setq s1 "" s2 string))
14912 (cond
14913 ((eq flag nil)
14914 ;; try completion
14915 (setq rtn (try-completion s2 ctable confirm))
14916 (if (stringp rtn)
14917 (setq rtn
14918 (concat s1 s2 (substring rtn (length s2))
14919 (if (and org-add-colon-after-tag-completion
14920 (assoc rtn ctable))
14921 ":" ""))))
14922 rtn)
14923 ((eq flag t)
14924 ;; all-completions
14925 (all-completions s2 ctable confirm))
14926 ((eq flag 'lambda)
14927 ;; exact match?
14928 (assoc s2 ctable)))))
14930 (defun org-fast-tag-insert (kwd tags face &optional end)
14931 "Insert KDW, and the TAGS, the latter with face FACE.
14932 Also insert END."
14933 (insert (format "%-12s" (concat kwd ":"))
14934 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14935 (or end "")))
14937 (defun org-fast-tag-show-exit (flag)
14938 (save-excursion
14939 (org-goto-line 3)
14940 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14941 (replace-match ""))
14942 (when flag
14943 (end-of-line 1)
14944 (org-move-to-column (- (window-width) 19) t)
14945 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14947 (defun org-set-current-tags-overlay (current prefix)
14948 "Add an overlay to CURRENT tag with PREFIX."
14949 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14950 (if (featurep 'xemacs)
14951 (org-overlay-display org-tags-overlay (concat prefix s)
14952 'secondary-selection)
14953 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14954 (org-overlay-display org-tags-overlay (concat prefix s)))))
14956 (defvar org-last-tag-selection-key nil)
14957 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14958 "Fast tag selection with single keys.
14959 CURRENT is the current list of tags in the headline, INHERITED is the
14960 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14961 possibly with grouping information. TODO-TABLE is a similar table with
14962 TODO keywords, should these have keys assigned to them.
14963 If the keys are nil, a-z are automatically assigned.
14964 Returns the new tags string, or nil to not change the current settings."
14965 (let* ((fulltable (append table todo-table))
14966 (maxlen (apply 'max (mapcar
14967 (lambda (x)
14968 (if (stringp (car x)) (string-width (car x)) 0))
14969 fulltable)))
14970 (buf (current-buffer))
14971 (expert (eq org-fast-tag-selection-single-key 'expert))
14972 (buffer-tags nil)
14973 (fwidth (+ maxlen 3 1 3))
14974 (ncol (/ (- (window-width) 4) fwidth))
14975 (i-face 'org-done)
14976 (c-face 'org-todo)
14977 tg cnt e c char c1 c2 ntable tbl rtn
14978 ov-start ov-end ov-prefix
14979 (exit-after-next org-fast-tag-selection-single-key)
14980 (done-keywords org-done-keywords)
14981 groups ingroup)
14982 (save-excursion
14983 (beginning-of-line 1)
14984 (if (looking-at
14985 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14986 (setq ov-start (match-beginning 1)
14987 ov-end (match-end 1)
14988 ov-prefix "")
14989 (setq ov-start (1- (point-at-eol))
14990 ov-end (1+ ov-start))
14991 (skip-chars-forward "^\n\r")
14992 (setq ov-prefix
14993 (concat
14994 (buffer-substring (1- (point)) (point))
14995 (if (> (current-column) org-tags-column)
14997 (make-string (- org-tags-column (current-column)) ?\ ))))))
14998 (move-overlay org-tags-overlay ov-start ov-end)
14999 (save-window-excursion
15000 (if expert
15001 (set-buffer (get-buffer-create " *Org tags*"))
15002 (delete-other-windows)
15003 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15004 (org-switch-to-buffer-other-window " *Org tags*"))
15005 (erase-buffer)
15006 (org-set-local 'org-done-keywords done-keywords)
15007 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15008 (org-fast-tag-insert "Current" current c-face "\n\n")
15009 (org-fast-tag-show-exit exit-after-next)
15010 (org-set-current-tags-overlay current ov-prefix)
15011 (setq tbl fulltable char ?a cnt 0)
15012 (while (setq e (pop tbl))
15013 (cond
15014 ((equal (car e) :startgroup)
15015 (push '() groups) (setq ingroup t)
15016 (when (not (= cnt 0))
15017 (setq cnt 0)
15018 (insert "\n"))
15019 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15020 ((equal (car e) :endgroup)
15021 (setq ingroup nil cnt 0)
15022 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15023 ((equal e '(:newline))
15024 (when (not (= cnt 0))
15025 (setq cnt 0)
15026 (insert "\n")
15027 (setq e (car tbl))
15028 (while (equal (car tbl) '(:newline))
15029 (insert "\n")
15030 (setq tbl (cdr tbl)))))
15031 ((equal e '(:grouptags)) nil)
15033 (setq tg (copy-sequence (car e)) c2 nil)
15034 (if (cdr e)
15035 (setq c (cdr e))
15036 ;; automatically assign a character.
15037 (setq c1 (string-to-char
15038 (downcase (substring
15039 tg (if (= (string-to-char tg) ?@) 1 0)))))
15040 (if (or (rassoc c1 ntable) (rassoc c1 table))
15041 (while (or (rassoc char ntable) (rassoc char table))
15042 (setq char (1+ char)))
15043 (setq c2 c1))
15044 (setq c (or c2 char)))
15045 (if ingroup (push tg (car groups)))
15046 (setq tg (org-add-props tg nil 'face
15047 (cond
15048 ((not (assoc tg table))
15049 (org-get-todo-face tg))
15050 ((member tg current) c-face)
15051 ((member tg inherited) i-face))))
15052 (if (equal (caar tbl) :grouptags)
15053 (org-add-props tg nil 'face 'org-tag-group))
15054 (if (and (= cnt 0) (not ingroup)) (insert " "))
15055 (insert "[" c "] " tg (make-string
15056 (- fwidth 4 (length tg)) ?\ ))
15057 (push (cons tg c) ntable)
15058 (when (= (setq cnt (1+ cnt)) ncol)
15059 (insert "\n")
15060 (if ingroup (insert " "))
15061 (setq cnt 0)))))
15062 (setq ntable (nreverse ntable))
15063 (insert "\n")
15064 (goto-char (point-min))
15065 (if (not expert) (org-fit-window-to-buffer))
15066 (setq rtn
15067 (catch 'exit
15068 (while t
15069 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15070 (if (not groups) "no " "")
15071 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15072 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15073 (setq org-last-tag-selection-key c)
15074 (cond
15075 ((= c ?\r) (throw 'exit t))
15076 ((= c ?!)
15077 (setq groups (not groups))
15078 (goto-char (point-min))
15079 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15080 ((= c ?\C-c)
15081 (if (not expert)
15082 (org-fast-tag-show-exit
15083 (setq exit-after-next (not exit-after-next)))
15084 (setq expert nil)
15085 (delete-other-windows)
15086 (set-window-buffer (split-window-vertically) " *Org tags*")
15087 (org-switch-to-buffer-other-window " *Org tags*")
15088 (org-fit-window-to-buffer)))
15089 ((or (= c ?\C-g)
15090 (and (= c ?q) (not (rassoc c ntable))))
15091 (org-detach-overlay org-tags-overlay)
15092 (setq quit-flag t))
15093 ((= c ?\ )
15094 (setq current nil)
15095 (if exit-after-next (setq exit-after-next 'now)))
15096 ((= c ?\t)
15097 (condition-case nil
15098 (setq tg (org-icompleting-read
15099 "Tag: "
15100 (or buffer-tags
15101 (with-current-buffer buf
15102 (org-get-buffer-tags)))))
15103 (quit (setq tg "")))
15104 (when (string-match "\\S-" tg)
15105 (add-to-list 'buffer-tags (list tg))
15106 (if (member tg current)
15107 (setq current (delete tg current))
15108 (push tg current)))
15109 (if exit-after-next (setq exit-after-next 'now)))
15110 ((setq e (rassoc c todo-table) tg (car e))
15111 (with-current-buffer buf
15112 (save-excursion (org-todo tg)))
15113 (if exit-after-next (setq exit-after-next 'now)))
15114 ((setq e (rassoc c ntable) tg (car e))
15115 (if (member tg current)
15116 (setq current (delete tg current))
15117 (loop for g in groups do
15118 (if (member tg g)
15119 (mapc (lambda (x)
15120 (setq current (delete x current)))
15121 g)))
15122 (push tg current))
15123 (if exit-after-next (setq exit-after-next 'now))))
15125 ;; Create a sorted list
15126 (setq current
15127 (sort current
15128 (lambda (a b)
15129 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15130 (if (eq exit-after-next 'now) (throw 'exit t))
15131 (goto-char (point-min))
15132 (beginning-of-line 2)
15133 (delete-region (point) (point-at-eol))
15134 (org-fast-tag-insert "Current" current c-face)
15135 (org-set-current-tags-overlay current ov-prefix)
15136 (while (re-search-forward
15137 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15138 (setq tg (match-string 1))
15139 (add-text-properties
15140 (match-beginning 1) (match-end 1)
15141 (list 'face
15142 (cond
15143 ((member tg current) c-face)
15144 ((member tg inherited) i-face)
15145 (t (get-text-property (match-beginning 1) 'face))))))
15146 (goto-char (point-min)))))
15147 (org-detach-overlay org-tags-overlay)
15148 (if rtn
15149 (mapconcat 'identity current ":")
15150 nil))))
15152 (defun org-get-tags-string ()
15153 "Get the TAGS string in the current headline."
15154 (unless (org-at-heading-p t)
15155 (user-error "Not on a heading"))
15156 (save-excursion
15157 (beginning-of-line 1)
15158 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15159 (org-match-string-no-properties 1)
15160 "")))
15162 (defun org-get-tags ()
15163 "Get the list of tags specified in the current headline."
15164 (org-split-string (org-get-tags-string) ":"))
15166 (defun org-get-buffer-tags ()
15167 "Get a table of all tags used in the buffer, for completion."
15168 (let (tags)
15169 (save-excursion
15170 (goto-char (point-min))
15171 (while (re-search-forward
15172 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15173 (when (equal (char-after (point-at-bol 0)) ?*)
15174 (mapc (lambda (x) (add-to-list 'tags x))
15175 (org-split-string (org-match-string-no-properties 1) ":")))))
15176 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15177 (mapcar 'list tags)))
15179 ;;;; The mapping API
15181 (defun org-map-entries (func &optional match scope &rest skip)
15182 "Call FUNC at each headline selected by MATCH in SCOPE.
15184 FUNC is a function or a lisp form. The function will be called without
15185 arguments, with the cursor positioned at the beginning of the headline.
15186 The return values of all calls to the function will be collected and
15187 returned as a list.
15189 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15190 does not need to preserve point. After evaluation, the cursor will be
15191 moved to the end of the line (presumably of the headline of the
15192 processed entry) and search continues from there. Under some
15193 circumstances, this may not produce the wanted results. For example,
15194 if you have removed (e.g. archived) the current (sub)tree it could
15195 mean that the next entry will be skipped entirely. In such cases, you
15196 can specify the position from where search should continue by making
15197 FUNC set the variable `org-map-continue-from' to the desired buffer
15198 position.
15200 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15201 Only headlines that are matched by this query will be considered during
15202 the iteration. When MATCH is nil or t, all headlines will be
15203 visited by the iteration.
15205 SCOPE determines the scope of this command. It can be any of:
15207 nil The current buffer, respecting the restriction if any
15208 tree The subtree started with the entry at point
15209 region The entries within the active region, if any
15210 region-start-level
15211 The entries within the active region, but only those at
15212 the same level than the first one.
15213 file The current buffer, without restriction
15214 file-with-archives
15215 The current buffer, and any archives associated with it
15216 agenda All agenda files
15217 agenda-with-archives
15218 All agenda files with any archive files associated with them
15219 \(file1 file2 ...)
15220 If this is a list, all files in the list will be scanned
15222 The remaining args are treated as settings for the skipping facilities of
15223 the scanner. The following items can be given here:
15225 archive skip trees with the archive tag
15226 comment skip trees with the COMMENT keyword
15227 function or Emacs Lisp form:
15228 will be used as value for `org-agenda-skip-function', so
15229 whenever the function returns a position, FUNC will not be
15230 called for that entry and search will continue from the
15231 position returned
15233 If your function needs to retrieve the tags including inherited tags
15234 at the *current* entry, you can use the value of the variable
15235 `org-scanner-tags' which will be much faster than getting the value
15236 with `org-get-tags-at'. If your function gets properties with
15237 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15238 to t around the call to `org-entry-properties' to get the same speedup.
15239 Note that if your function moves around to retrieve tags and properties at
15240 a *different* entry, you cannot use these techniques."
15241 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15242 (not (org-region-active-p)))
15243 (let* ((org-agenda-archives-mode nil) ; just to make sure
15244 (org-agenda-skip-archived-trees (memq 'archive skip))
15245 (org-agenda-skip-comment-trees (memq 'comment skip))
15246 (org-agenda-skip-function
15247 (car (org-delete-all '(comment archive) skip)))
15248 (org-tags-match-list-sublevels t)
15249 (start-level (eq scope 'region-start-level))
15250 matcher file res
15251 org-todo-keywords-for-agenda
15252 org-done-keywords-for-agenda
15253 org-todo-keyword-alist-for-agenda
15254 org-tag-alist-for-agenda
15255 todo-only)
15257 (cond
15258 ((eq match t) (setq matcher t))
15259 ((eq match nil) (setq matcher t))
15260 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15262 (save-excursion
15263 (save-restriction
15264 (cond ((eq scope 'tree)
15265 (org-back-to-heading t)
15266 (org-narrow-to-subtree)
15267 (setq scope nil))
15268 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15269 (org-region-active-p))
15270 ;; If needed, set start-level to a string like "2"
15271 (when start-level
15272 (save-excursion
15273 (goto-char (region-beginning))
15274 (unless (org-at-heading-p) (outline-next-heading))
15275 (setq start-level (org-current-level))))
15276 (narrow-to-region (region-beginning)
15277 (save-excursion
15278 (goto-char (region-end))
15279 (unless (and (bolp) (org-at-heading-p))
15280 (outline-next-heading))
15281 (point)))
15282 (setq scope nil)))
15284 (if (not scope)
15285 (progn
15286 (org-agenda-prepare-buffers
15287 (list (buffer-file-name (current-buffer))))
15288 (setq res (org-scan-tags func matcher todo-only start-level)))
15289 ;; Get the right scope
15290 (cond
15291 ((and scope (listp scope) (symbolp (car scope)))
15292 (setq scope (eval scope)))
15293 ((eq scope 'agenda)
15294 (setq scope (org-agenda-files t)))
15295 ((eq scope 'agenda-with-archives)
15296 (setq scope (org-agenda-files t))
15297 (setq scope (org-add-archive-files scope)))
15298 ((eq scope 'file)
15299 (setq scope (list (buffer-file-name))))
15300 ((eq scope 'file-with-archives)
15301 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15302 (org-agenda-prepare-buffers scope)
15303 (while (setq file (pop scope))
15304 (with-current-buffer (org-find-base-buffer-visiting file)
15305 (save-excursion
15306 (save-restriction
15307 (widen)
15308 (goto-char (point-min))
15309 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15310 res)))
15312 ;;;; Properties
15314 ;;; Setting and retrieving properties
15316 (defconst org-special-properties
15317 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15318 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15319 "The special properties valid in Org-mode.
15321 These are properties that are not defined in the property drawer,
15322 but in some other way.")
15324 (defconst org-default-properties
15325 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15326 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15327 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15328 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15329 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15330 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15331 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15332 "Some properties that are used by Org-mode for various purposes.
15333 Being in this list makes sure that they are offered for completion.")
15335 (defun org-property-action ()
15336 "Do an action on properties."
15337 (interactive)
15338 (let (c)
15339 (org-at-property-p)
15340 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15341 (setq c (read-char-exclusive))
15342 (cond
15343 ((equal c ?s)
15344 (call-interactively 'org-set-property))
15345 ((equal c ?d)
15346 (call-interactively 'org-delete-property))
15347 ((equal c ?D)
15348 (call-interactively 'org-delete-property-globally))
15349 ((equal c ?c)
15350 (call-interactively 'org-compute-property-at-point))
15351 (t (user-error "No such property action %c" c)))))
15353 (defun org-inc-effort ()
15354 "Increment the value of the effort property in the current entry."
15355 (interactive)
15356 (org-set-effort nil t))
15358 (defvar org-clock-effort) ;; Defined in org-clock.el
15359 (defvar org-clock-current-task) ;; Defined in org-clock.el
15360 (defun org-set-effort (&optional value increment)
15361 "Set the effort property of the current entry.
15362 With numerical prefix arg, use the nth allowed value, 0 stands for the
15363 10th allowed value.
15365 When INCREMENT is non-nil, set the property to the next allowed value."
15366 (interactive "P")
15367 (if (equal value 0) (setq value 10))
15368 (let* ((completion-ignore-case t)
15369 (prop org-effort-property)
15370 (cur (org-entry-get nil prop))
15371 (allowed (org-property-get-allowed-values nil prop 'table))
15372 (existing (mapcar 'list (org-property-values prop)))
15373 (heading (nth 4 (org-heading-components)))
15375 (val (cond
15376 ((stringp value) value)
15377 ((and allowed (integerp value))
15378 (or (car (nth (1- value) allowed))
15379 (car (org-last allowed))))
15380 ((and allowed increment)
15381 (or (caadr (member (list cur) allowed))
15382 (user-error "Allowed effort values are not set")))
15383 (allowed
15384 (message "Select 1-9,0, [RET%s]: %s"
15385 (if cur (concat "=" cur) "")
15386 (mapconcat 'car allowed " "))
15387 (setq rpl (read-char-exclusive))
15388 (if (equal rpl ?\r)
15390 (setq rpl (- rpl ?0))
15391 (if (equal rpl 0) (setq rpl 10))
15392 (if (and (> rpl 0) (<= rpl (length allowed)))
15393 (car (nth (1- rpl) allowed))
15394 (org-completing-read "Effort: " allowed nil))))
15396 (let (org-completion-use-ido org-completion-use-iswitchb)
15397 (org-completing-read
15398 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15399 (concat "[" cur "]") "")
15400 ": ")
15401 existing nil nil "" nil cur))))))
15402 (unless (equal (org-entry-get nil prop) val)
15403 (org-entry-put nil prop val))
15404 (org-refresh-property
15405 '((effort . identity)
15406 (effort-minutes . org-duration-string-to-minutes))
15407 val)
15408 (when (string= heading org-clock-current-task)
15409 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15410 (org-clock-update-mode-line))
15411 (message "%s is now %s" prop val)))
15413 (defun org-at-property-p ()
15414 "Non-nil when point is inside a property drawer.
15415 See `org-property-re' for match data, if applicable."
15416 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15417 (save-excursion
15418 (beginning-of-line)
15419 (looking-at org-property-re))))
15421 (defun org-get-property-block (&optional beg end force)
15422 "Return the (beg . end) range of the body of the property drawer.
15423 BEG and END are the beginning and end of the current subtree, or of
15424 the part before the first headline. If they are not given, they will
15425 be found. If the drawer does not exist and FORCE is non-nil, create
15426 the drawer."
15427 (catch 'exit
15428 (save-excursion
15429 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15430 (progn (org-back-to-heading t) (point))))
15431 (end (or end (and (not (outline-next-heading)) (point-max))
15432 (point))))
15433 (goto-char beg)
15434 (if (re-search-forward org-property-start-re end t)
15435 (setq beg (1+ (match-end 0)))
15436 (if force
15437 (save-excursion
15438 (org-insert-property-drawer)
15439 (setq end (progn (outline-next-heading) (point))))
15440 (throw 'exit nil))
15441 (goto-char beg)
15442 (if (re-search-forward org-property-start-re end t)
15443 (setq beg (1+ (match-end 0)))))
15444 (if (re-search-forward org-property-end-re end t)
15445 (setq end (match-beginning 0))
15446 (or force (throw 'exit nil))
15447 (goto-char beg)
15448 (setq end beg)
15449 (org-indent-line)
15450 (insert ":END:\n"))
15451 (cons beg end)))))
15453 (defun org-entry-properties (&optional pom which specific)
15454 "Get all properties of the entry at point-or-marker POM.
15455 This includes the TODO keyword, the tags, time strings for deadline,
15456 scheduled, and clocking, and any additional properties defined in the
15457 entry. The return value is an alist, keys may occur multiple times
15458 if the property key was used several times.
15459 POM may also be nil, in which case the current entry is used.
15460 If WHICH is nil or `all', get all properties. If WHICH is
15461 `special' or `standard', only get that subclass. If WHICH
15462 is a string only get exactly this property. SPECIFIC can be a string, the
15463 specific property we are interested in. Specifying it can speed
15464 things up because then unnecessary parsing is avoided."
15465 (setq which (or which 'all))
15466 (org-with-wide-buffer
15467 (org-with-point-at pom
15468 (let ((clockstr (substring org-clock-string 0 -1))
15469 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15470 (case-fold-search nil)
15471 beg end range props sum-props key key1 value string clocksum clocksumt)
15472 (when (and (derived-mode-p 'org-mode)
15473 (ignore-errors (org-back-to-heading t)))
15474 (setq beg (point))
15475 (setq sum-props (get-text-property (point) 'org-summaries))
15476 (setq clocksum (get-text-property (point) :org-clock-minutes)
15477 clocksumt (get-text-property (point) :org-clock-minutes-today))
15478 (outline-next-heading)
15479 (setq end (point))
15480 (when (memq which '(all special))
15481 ;; Get the special properties, like TODO and tags
15482 (goto-char beg)
15483 (when (and (or (not specific) (string= specific "TODO"))
15484 (looking-at org-todo-line-regexp) (match-end 2))
15485 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15486 (when (and (or (not specific) (string= specific "PRIORITY"))
15487 (looking-at org-priority-regexp))
15488 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15489 (when (or (not specific) (string= specific "FILE"))
15490 (push (cons "FILE" buffer-file-name) props))
15491 (when (and (or (not specific) (string= specific "TAGS"))
15492 (setq value (org-get-tags-string))
15493 (string-match "\\S-" value))
15494 (push (cons "TAGS" value) props))
15495 (when (and (or (not specific) (string= specific "ALLTAGS"))
15496 (setq value (org-get-tags-at)))
15497 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15498 ":"))
15499 props))
15500 (when (or (not specific) (string= specific "BLOCKED"))
15501 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15502 (when (or (not specific)
15503 (member specific
15504 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15505 "TIMESTAMP" "TIMESTAMP_IA")))
15506 (catch 'match
15507 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15508 (not (text-property-any 0 (length (match-string 0))
15509 'face 'font-lock-comment-face
15510 (match-string 0))))
15511 (setq key (if (match-end 1)
15512 (substring (org-match-string-no-properties 1)
15513 0 -1))
15514 string (if (equal key clockstr)
15515 (org-trim
15516 (buffer-substring-no-properties
15517 (match-beginning 3) (goto-char
15518 (point-at-eol))))
15519 (substring (org-match-string-no-properties 3)
15520 1 -1)))
15521 ;; Get the correct property name from the key. This is
15522 ;; necessary if the user has configured time keywords.
15523 (setq key1 (concat key ":"))
15524 (cond
15525 ((not key)
15526 (setq key
15527 (if (= (char-after (match-beginning 3)) ?\[)
15528 "TIMESTAMP_IA" "TIMESTAMP")))
15529 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15530 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15531 ((equal key1 org-closed-string) (setq key "CLOSED"))
15532 ((equal key1 org-clock-string) (setq key "CLOCK")))
15533 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15534 (progn
15535 (push (cons key string) props)
15536 ;; no need to search further if match is found
15537 (throw 'match t))
15538 (when (or (equal key "CLOCK") (not (assoc key props)))
15539 (push (cons key string) props)))))))
15541 (when (memq which '(all standard))
15542 ;; Get the standard properties, like :PROP: ...
15543 (setq range (org-get-property-block beg end))
15544 (when range
15545 (goto-char (car range))
15546 (while (re-search-forward org-property-re
15547 (cdr range) t)
15548 (setq key (org-match-string-no-properties 2)
15549 value (org-trim (or (org-match-string-no-properties 3) "")))
15550 (unless (member key excluded)
15551 (push (cons key (or value "")) props)))))
15552 (if clocksum
15553 (push (cons "CLOCKSUM"
15554 (org-columns-number-to-string (/ (float clocksum) 60.)
15555 'add_times))
15556 props))
15557 (if clocksumt
15558 (push (cons "CLOCKSUM_T"
15559 (org-columns-number-to-string (/ (float clocksumt) 60.)
15560 'add_times))
15561 props))
15562 (unless (assoc "CATEGORY" props)
15563 (push (cons "CATEGORY" (org-get-category)) props))
15564 (append sum-props (nreverse props)))))))
15566 (defun org-entry-get (pom property &optional inherit literal-nil)
15567 "Get value of PROPERTY for entry or content at point-or-marker POM.
15568 If INHERIT is non-nil and the entry does not have the property,
15569 then also check higher levels of the hierarchy.
15570 If INHERIT is the symbol `selective', use inheritance only if the setting
15571 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15572 If the property is present but empty, the return value is the empty string.
15573 If the property is not present at all, nil is returned.
15575 Return the value as a string.
15577 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15578 do not interpret it as the list atom nil. This is used for inheritance
15579 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15580 (org-with-point-at pom
15581 (if (and inherit (if (eq inherit 'selective)
15582 (org-property-inherit-p property)
15584 (org-entry-get-with-inheritance property literal-nil)
15585 (if (member property org-special-properties)
15586 ;; We need a special property. Use `org-entry-properties'
15587 ;; to retrieve it, but specify the wanted property
15588 (cdr (assoc property (org-entry-properties nil 'special property)))
15589 (org-with-wide-buffer
15590 (let ((range (org-get-property-block)))
15591 (when (and range (not (eq (car range) (cdr range)))
15592 (save-excursion
15593 (goto-char (car range))
15594 (re-search-forward
15595 (concat (org-re-property property) "\\|"
15596 (org-re-property (concat property "+")))
15597 (cdr range) t)))
15598 (let* ((props
15599 (list (or (assoc property org-file-properties)
15600 (assoc property org-global-properties)
15601 (assoc property org-global-properties-fixed))))
15602 (ap (lambda (key)
15603 (when (re-search-forward
15604 (org-re-property key) (cdr range) t)
15605 (setq props
15606 (org-update-property-plist
15608 (if (match-end 3)
15609 (org-match-string-no-properties 3) "")
15610 props)))))
15611 val)
15612 (goto-char (car range))
15613 (funcall ap property)
15614 (goto-char (car range))
15615 (while (funcall ap (concat property "+")))
15616 (setq val (cdr (assoc property props)))
15617 (when val (if literal-nil val (org-not-nil val)))))))))))
15619 (defun org-property-or-variable-value (var &optional inherit)
15620 "Check if there is a property fixing the value of VAR.
15621 If yes, return this value. If not, return the current value of the variable."
15622 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15623 (if (and prop (stringp prop) (string-match "\\S-" prop))
15624 (read prop)
15625 (symbol-value var))))
15627 (defun org-entry-delete (pom property)
15628 "Delete the property PROPERTY from entry at point-or-marker POM."
15629 (unless (member property org-special-properties)
15630 (org-with-point-at pom
15631 (let ((range (org-get-property-block)))
15632 (if (and range
15633 (goto-char (car range))
15634 (re-search-forward
15635 (org-re-property property nil t)
15636 (cdr range) t))
15637 (progn
15638 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15639 (org-remove-empty-drawer-at (car range))
15641 nil)))))
15643 ;; Multi-values properties are properties that contain multiple values
15644 ;; These values are assumed to be single words, separated by whitespace.
15645 (defun org-entry-add-to-multivalued-property (pom property value)
15646 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15647 (let* ((old (org-entry-get pom property))
15648 (values (and old (org-split-string old "[ \t]"))))
15649 (setq value (org-entry-protect-space value))
15650 (unless (member value values)
15651 (setq values (append values (list value)))
15652 (org-entry-put pom property
15653 (mapconcat 'identity values " ")))))
15655 (defun org-entry-remove-from-multivalued-property (pom property value)
15656 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15657 (let* ((old (org-entry-get pom property))
15658 (values (and old (org-split-string old "[ \t]"))))
15659 (setq value (org-entry-protect-space value))
15660 (when (member value values)
15661 (setq values (delete value values))
15662 (org-entry-put pom property
15663 (mapconcat 'identity values " ")))))
15665 (defun org-entry-member-in-multivalued-property (pom property value)
15666 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15667 (let* ((old (org-entry-get pom property))
15668 (values (and old (org-split-string old "[ \t]"))))
15669 (setq value (org-entry-protect-space value))
15670 (member value values)))
15672 (defun org-entry-get-multivalued-property (pom property)
15673 "Return a list of values in a multivalued property."
15674 (let* ((value (org-entry-get pom property))
15675 (values (and value (org-split-string value "[ \t]"))))
15676 (mapcar 'org-entry-restore-space values)))
15678 (defun org-entry-put-multivalued-property (pom property &rest values)
15679 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15680 VALUES should be a list of strings. Spaces will be protected."
15681 (org-entry-put pom property
15682 (mapconcat 'org-entry-protect-space values " "))
15683 (let* ((value (org-entry-get pom property))
15684 (values (and value (org-split-string value "[ \t]"))))
15685 (mapcar 'org-entry-restore-space values)))
15687 (defun org-entry-protect-space (s)
15688 "Protect spaces and newline in string S."
15689 (while (string-match " " s)
15690 (setq s (replace-match "%20" t t s)))
15691 (while (string-match "\n" s)
15692 (setq s (replace-match "%0A" t t s)))
15695 (defun org-entry-restore-space (s)
15696 "Restore spaces and newline in string S."
15697 (while (string-match "%20" s)
15698 (setq s (replace-match " " t t s)))
15699 (while (string-match "%0A" s)
15700 (setq s (replace-match "\n" t t s)))
15703 (defvar org-entry-property-inherited-from (make-marker)
15704 "Marker pointing to the entry from where a property was inherited.
15705 Each call to `org-entry-get-with-inheritance' will set this marker to the
15706 location of the entry where the inheritance search matched. If there was
15707 no match, the marker will point nowhere.
15708 Note that also `org-entry-get' calls this function, if the INHERIT flag
15709 is set.")
15711 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15712 "Get PROPERTY of entry or content at point, search higher levels if needed.
15713 The search will stop at the first ancestor which has the property defined.
15714 If the value found is \"nil\", return nil to show that the property
15715 should be considered as undefined (this is the meaning of nil here).
15716 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15717 (move-marker org-entry-property-inherited-from nil)
15718 (let (tmp)
15719 (save-excursion
15720 (save-restriction
15721 (widen)
15722 (catch 'ex
15723 (while t
15724 (when (setq tmp (org-entry-get nil property nil literal-nil))
15725 (or (ignore-errors (org-back-to-heading t))
15726 (goto-char (point-min)))
15727 (move-marker org-entry-property-inherited-from (point))
15728 (throw 'ex tmp))
15729 (or (ignore-errors (org-up-heading-safe))
15730 (throw 'ex nil))))))
15731 (setq tmp (or tmp
15732 (cdr (assoc property org-file-properties))
15733 (cdr (assoc property org-global-properties))
15734 (cdr (assoc property org-global-properties-fixed))))
15735 (if literal-nil tmp (org-not-nil tmp))))
15737 (defvar org-property-changed-functions nil
15738 "Hook called when the value of a property has changed.
15739 Each hook function should accept two arguments, the name of the property
15740 and the new value.")
15742 (defun org-entry-put (pom property value)
15743 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15744 If the value is `nil', it is converted to the empty string.
15745 If it is not a string, an error is raised."
15746 (cond ((null value) (setq value ""))
15747 ((not (stringp value))
15748 (error "Properties values should be strings.")))
15749 (org-with-point-at pom
15750 (org-back-to-heading t)
15751 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15752 range)
15753 (cond
15754 ((equal property "TODO")
15755 (when (and (string-match "\\S-" value)
15756 (not (member value org-todo-keywords-1)))
15757 (user-error "\"%s\" is not a valid TODO state" value))
15758 (if (or (not value)
15759 (not (string-match "\\S-" value)))
15760 (setq value 'none))
15761 (org-todo value)
15762 (org-set-tags nil 'align))
15763 ((equal property "PRIORITY")
15764 (org-priority (if (and value (string-match "\\S-" value))
15765 (string-to-char value) ?\ ))
15766 (org-set-tags nil 'align))
15767 ((equal property "CLOCKSUM")
15768 (if (not (re-search-forward
15769 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15770 (error "Cannot find a clock log")
15771 (goto-char (- (match-end 1) 2))
15772 (cond
15773 ((eq value 'earlier) (org-timestamp-down))
15774 ((eq value 'later) (org-timestamp-up)))
15775 (org-clock-sum-current-item)))
15776 ((equal property "SCHEDULED")
15777 (if (re-search-forward org-scheduled-time-regexp end t)
15778 (cond
15779 ((eq value 'earlier) (org-timestamp-change -1 'day))
15780 ((eq value 'later) (org-timestamp-change 1 'day))
15781 (t (call-interactively 'org-schedule)))
15782 (call-interactively 'org-schedule)))
15783 ((equal property "DEADLINE")
15784 (if (re-search-forward org-deadline-time-regexp end t)
15785 (cond
15786 ((eq value 'earlier) (org-timestamp-change -1 'day))
15787 ((eq value 'later) (org-timestamp-change 1 'day))
15788 (t (call-interactively 'org-deadline)))
15789 (call-interactively 'org-deadline)))
15790 ((member property org-special-properties)
15791 (error "The %s property can not yet be set with `org-entry-put'"
15792 property))
15793 (t ; a non-special property
15794 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15795 (setq range (org-get-property-block beg end 'force))
15796 (goto-char (car range))
15797 (if (re-search-forward
15798 (org-re-property property nil t) (cdr range) t)
15799 (progn
15800 (delete-region (match-beginning 0) (match-end 0))
15801 (goto-char (match-beginning 0)))
15802 (goto-char (cdr range))
15803 (insert "\n")
15804 (backward-char 1)
15805 (org-indent-line))
15806 (insert ":" property ":")
15807 (and value (insert " " value))
15808 (org-indent-line)))))
15809 (run-hook-with-args 'org-property-changed-functions property value)))
15811 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15812 "Get all property keys in the current buffer.
15813 With INCLUDE-SPECIALS, also list the special properties that reflect things
15814 like tags and TODO state.
15815 With INCLUDE-DEFAULTS, also include properties that has special meaning
15816 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15817 and others.
15818 With INCLUDE-COLUMNS, also include property names given in COLUMN
15819 formats in the current buffer."
15820 (let (rtn range cfmt s p)
15821 (save-excursion
15822 (save-restriction
15823 (widen)
15824 (goto-char (point-min))
15825 (while (re-search-forward org-property-start-re nil t)
15826 (catch 'cont
15827 (setq range (or (org-get-property-block)
15828 (if (y-or-n-p
15829 (format "Malformed drawer at %d, repair?" (point)))
15830 (org-get-property-block nil nil t)
15831 (throw 'cont nil))))
15832 (goto-char (car range))
15833 (while (re-search-forward org-property-re
15834 (cdr range) t)
15835 (add-to-list 'rtn (org-match-string-no-properties 2)))
15836 (outline-next-heading)))))
15838 (when include-specials
15839 (setq rtn (append org-special-properties rtn)))
15841 (when include-defaults
15842 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15843 (add-to-list 'rtn org-effort-property))
15845 (when include-columns
15846 (save-excursion
15847 (save-restriction
15848 (widen)
15849 (goto-char (point-min))
15850 (while (re-search-forward
15851 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15852 nil t)
15853 (setq cfmt (match-string 2) s 0)
15854 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15855 cfmt s)
15856 (setq s (match-end 0)
15857 p (match-string 1 cfmt))
15858 (unless (or (equal p "ITEM")
15859 (member p org-special-properties))
15860 (add-to-list 'rtn (match-string 1 cfmt))))))))
15862 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15864 (defun org-property-values (key)
15865 "Return a list of all values of property KEY in the current buffer."
15866 (save-excursion
15867 (save-restriction
15868 (widen)
15869 (goto-char (point-min))
15870 (let ((re (org-re-property key))
15871 values)
15872 (while (re-search-forward re nil t)
15873 (add-to-list 'values (org-trim (match-string 3))))
15874 (delete "" values)))))
15876 (defun org-insert-property-drawer ()
15877 "Insert a property drawer into the current entry."
15878 (org-back-to-heading t)
15879 (looking-at org-outline-regexp)
15880 (let ((indent (if org-adapt-indentation
15881 (- (match-end 0) (match-beginning 0))
15883 (beg (point))
15884 (re (concat "^[ \t]*" org-keyword-time-regexp))
15885 end hiddenp)
15886 (outline-next-heading)
15887 (setq end (point))
15888 (goto-char beg)
15889 (while (re-search-forward re end t))
15890 (setq hiddenp (outline-invisible-p))
15891 (end-of-line 1)
15892 (and (equal (char-after) ?\n) (forward-char 1))
15893 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15894 (if (member (match-string 1) '("CLOCK:" ":END:"))
15895 ;; just skip this line
15896 (beginning-of-line 2)
15897 ;; Drawer start, find the end
15898 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15899 (beginning-of-line 1)))
15900 (org-skip-over-state-notes)
15901 (skip-chars-backward " \t\n\r")
15902 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15903 (forward-char 1))
15904 (goto-char (point-at-eol))
15905 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15906 (beginning-of-line 0)
15907 (org-indent-to-column indent)
15908 (beginning-of-line 2)
15909 (org-indent-to-column indent)
15910 (beginning-of-line 0)
15911 (if hiddenp
15912 (save-excursion
15913 (org-back-to-heading t)
15914 (hide-entry))
15915 (org-flag-drawer t))))
15917 (defun org-insert-drawer (&optional arg drawer)
15918 "Insert a drawer at point.
15920 Optional argument DRAWER, when non-nil, is a string representing
15921 drawer's name. Otherwise, the user is prompted for a name.
15923 If a region is active, insert the drawer around that region
15924 instead.
15926 Point is left between drawer's boundaries."
15927 (interactive "P")
15928 (let* ((drawer (if arg "PROPERTIES"
15929 (or drawer (read-from-minibuffer "Drawer: ")))))
15930 (cond
15931 ;; With C-u, fall back on `org-insert-property-drawer'
15932 (arg (org-insert-property-drawer))
15934 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15935 (user-error "Invalid drawer name"))
15936 ;; With an active region, insert a drawer at point.
15937 ((not (org-region-active-p))
15938 (progn
15939 (unless (bolp) (insert "\n"))
15940 (insert (format ":%s:\n\n:END:\n" drawer))
15941 (forward-line -2)))
15942 ;; Otherwise, insert the drawer at point
15944 (let ((rbeg (region-beginning))
15945 (rend (copy-marker (region-end))))
15946 (unwind-protect
15947 (progn
15948 (goto-char rbeg)
15949 (beginning-of-line)
15950 (when (save-excursion
15951 (re-search-forward org-outline-regexp-bol rend t))
15952 (user-error "Drawers cannot contain headlines"))
15953 ;; Position point at the beginning of the first
15954 ;; non-blank line in region. Insert drawer's opening
15955 ;; there, then indent it.
15956 (org-skip-whitespace)
15957 (beginning-of-line)
15958 (insert ":" drawer ":\n")
15959 (forward-line -1)
15960 (indent-for-tab-command)
15961 ;; Move point to the beginning of the first blank line
15962 ;; after the last non-blank line in region. Insert
15963 ;; drawer's closing, then indent it.
15964 (goto-char rend)
15965 (skip-chars-backward " \r\t\n")
15966 (insert "\n:END:")
15967 (deactivate-mark t)
15968 (indent-for-tab-command)
15969 (unless (eolp) (insert "\n")))
15970 ;; Clear marker, whatever the outcome of insertion is.
15971 (set-marker rend nil)))))))
15973 (defvar org-property-set-functions-alist nil
15974 "Property set function alist.
15975 Each entry should have the following format:
15977 (PROPERTY . READ-FUNCTION)
15979 The read function will be called with the same argument as
15980 `org-completing-read'.")
15982 (defun org-set-property-function (property)
15983 "Get the function that should be used to set PROPERTY.
15984 This is computed according to `org-property-set-functions-alist'."
15985 (or (cdr (assoc property org-property-set-functions-alist))
15986 'org-completing-read))
15988 (defun org-read-property-value (property)
15989 "Read PROPERTY value from user."
15990 (let* ((completion-ignore-case t)
15991 (allowed (org-property-get-allowed-values nil property 'table))
15992 (cur (org-entry-get nil property))
15993 (prompt (concat property " value"
15994 (if (and cur (string-match "\\S-" cur))
15995 (concat " [" cur "]") "") ": "))
15996 (set-function (org-set-property-function property))
15997 (val (if allowed
15998 (funcall set-function prompt allowed nil
15999 (not (get-text-property 0 'org-unrestricted
16000 (caar allowed))))
16001 (let (org-completion-use-ido org-completion-use-iswitchb)
16002 (funcall set-function prompt
16003 (mapcar 'list (org-property-values property))
16004 nil nil "" nil cur)))))
16005 (org-trim val)))
16007 (defvar org-last-set-property nil)
16008 (defvar org-last-set-property-value nil)
16009 (defun org-read-property-name ()
16010 "Read a property name."
16011 (let* ((completion-ignore-case t)
16012 (keys (org-buffer-property-keys nil t t))
16013 (default-prop (or (save-excursion
16014 (save-match-data
16015 (beginning-of-line)
16016 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16017 (null (string= (match-string 1) "END"))
16018 (match-string 1))))
16019 org-last-set-property))
16020 (property (org-icompleting-read
16021 (concat "Property"
16022 (if default-prop (concat " [" default-prop "]") "")
16023 ": ")
16024 (mapcar 'list keys)
16025 nil nil nil nil
16026 default-prop)))
16027 (if (member property keys)
16028 property
16029 (or (cdr (assoc (downcase property)
16030 (mapcar (lambda (x) (cons (downcase x) x))
16031 keys)))
16032 property))))
16034 (defun org-set-property-and-value (use-last)
16035 "Allow to set [PROPERTY]: [value] direction from prompt.
16036 When use-default, don't even ask, just use the last
16037 \"[PROPERTY]: [value]\" string from the history."
16038 (interactive "P")
16039 (let* ((completion-ignore-case t)
16040 (pv (or (and use-last org-last-set-property-value)
16041 (org-completing-read
16042 "Enter a \"[Property]: [value]\" pair: "
16043 nil nil nil nil nil
16044 org-last-set-property-value)))
16045 prop val)
16046 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16047 (setq prop (match-string 1 pv)
16048 val (match-string 2 pv))
16049 (org-set-property prop val))))
16051 (defun org-set-property (property value)
16052 "In the current entry, set PROPERTY to VALUE.
16053 When called interactively, this will prompt for a property name, offering
16054 completion on existing and default properties. And then it will prompt
16055 for a value, offering completion either on allowed values (via an inherited
16056 xxx_ALL property) or on existing values in other instances of this property
16057 in the current file."
16058 (interactive (list nil nil))
16059 (let* ((property (or property (org-read-property-name)))
16060 (value (or value (org-read-property-value property)))
16061 (fn (cdr (assoc property org-properties-postprocess-alist))))
16062 (setq org-last-set-property property)
16063 (setq org-last-set-property-value (concat property ": " value))
16064 ;; Possibly postprocess the inserted value:
16065 (when fn (setq value (funcall fn value)))
16066 (unless (equal (org-entry-get nil property) value)
16067 (org-entry-put nil property value))))
16069 (defun org-delete-property (property)
16070 "In the current entry, delete PROPERTY."
16071 (interactive
16072 (let* ((completion-ignore-case t)
16073 (cat (org-entry-get (point) "CATEGORY"))
16074 (props0 (org-entry-properties nil 'standard))
16075 (props (if cat props0
16076 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16077 (prop (if (< 1 (length props))
16078 (org-icompleting-read "Property: " props nil t)
16079 (caar props))))
16080 (list prop)))
16081 (if (not property)
16082 (message "No property to delete in this entry")
16083 (org-entry-delete nil property)
16084 (message "Property \"%s\" deleted" property)))
16086 (defun org-delete-property-globally (property)
16087 "Remove PROPERTY globally, from all entries."
16088 (interactive
16089 (let* ((completion-ignore-case t)
16090 (prop (org-icompleting-read
16091 "Globally remove property: "
16092 (mapcar 'list (org-buffer-property-keys)))))
16093 (list prop)))
16094 (save-excursion
16095 (save-restriction
16096 (widen)
16097 (goto-char (point-min))
16098 (let ((cnt 0))
16099 (while (re-search-forward
16100 (org-re-property property)
16101 nil t)
16102 (setq cnt (1+ cnt))
16103 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16104 (message "Property \"%s\" removed from %d entries" property cnt)))))
16106 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16108 (defun org-compute-property-at-point ()
16109 "Compute the property at point.
16110 This looks for an enclosing column format, extracts the operator and
16111 then applies it to the property in the column format's scope."
16112 (interactive)
16113 (unless (org-at-property-p)
16114 (user-error "Not at a property"))
16115 (let ((prop (org-match-string-no-properties 2)))
16116 (org-columns-get-format-and-top-level)
16117 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16118 (user-error "No operator defined for property %s" prop))
16119 (org-columns-compute prop)))
16121 (defvar org-property-allowed-value-functions nil
16122 "Hook for functions supplying allowed values for a specific property.
16123 The functions must take a single argument, the name of the property, and
16124 return a flat list of allowed values. If \":ETC\" is one of
16125 the values, this means that these values are intended as defaults for
16126 completion, but that other values should be allowed too.
16127 The functions must return nil if they are not responsible for this
16128 property.")
16130 (defun org-property-get-allowed-values (pom property &optional table)
16131 "Get allowed values for the property PROPERTY.
16132 When TABLE is non-nil, return an alist that can directly be used for
16133 completion."
16134 (let (vals)
16135 (cond
16136 ((equal property "TODO")
16137 (setq vals (org-with-point-at pom
16138 (append org-todo-keywords-1 '("")))))
16139 ((equal property "PRIORITY")
16140 (let ((n org-lowest-priority))
16141 (while (>= n org-highest-priority)
16142 (push (char-to-string n) vals)
16143 (setq n (1- n)))))
16144 ((member property org-special-properties))
16145 ((setq vals (run-hook-with-args-until-success
16146 'org-property-allowed-value-functions property)))
16148 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16149 (when (and vals (string-match "\\S-" vals))
16150 (setq vals (car (read-from-string (concat "(" vals ")"))))
16151 (setq vals (mapcar (lambda (x)
16152 (cond ((stringp x) x)
16153 ((numberp x) (number-to-string x))
16154 ((symbolp x) (symbol-name x))
16155 (t "???")))
16156 vals)))))
16157 (when (member ":ETC" vals)
16158 (setq vals (remove ":ETC" vals))
16159 (org-add-props (car vals) '(org-unrestricted t)))
16160 (if table (mapcar 'list vals) vals)))
16162 (defun org-property-previous-allowed-value (&optional previous)
16163 "Switch to the next allowed value for this property."
16164 (interactive)
16165 (org-property-next-allowed-value t))
16167 (defun org-property-next-allowed-value (&optional previous)
16168 "Switch to the next allowed value for this property."
16169 (interactive)
16170 (unless (org-at-property-p)
16171 (user-error "Not at a property"))
16172 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16173 (key (match-string 2))
16174 (value (match-string 3))
16175 (allowed (or (org-property-get-allowed-values (point) key)
16176 (and (member value '("[ ]" "[-]" "[X]"))
16177 '("[ ]" "[X]"))))
16178 (heading (save-match-data (nth 4 (org-heading-components))))
16179 nval)
16180 (unless allowed
16181 (user-error "Allowed values for this property have not been defined"))
16182 (if previous (setq allowed (reverse allowed)))
16183 (if (member value allowed)
16184 (setq nval (car (cdr (member value allowed)))))
16185 (setq nval (or nval (car allowed)))
16186 (if (equal nval value)
16187 (user-error "Only one allowed value for this property"))
16188 (org-at-property-p)
16189 (replace-match (concat " :" key ": " nval) t t)
16190 (org-indent-line)
16191 (beginning-of-line 1)
16192 (skip-chars-forward " \t")
16193 (when (equal prop org-effort-property)
16194 (org-refresh-property
16195 '((effort . identity)
16196 (effort-minutes . org-duration-string-to-minutes))
16197 nval)
16198 (when (string= org-clock-current-task heading)
16199 (setq org-clock-effort nval)
16200 (org-clock-update-mode-line)))
16201 (run-hook-with-args 'org-property-changed-functions key nval)))
16203 (defun org-find-olp (path &optional this-buffer)
16204 "Return a marker pointing to the entry at outline path OLP.
16205 If anything goes wrong, throw an error.
16206 You can wrap this call to catch the error like this:
16208 (condition-case msg
16209 (org-mobile-locate-entry (match-string 4))
16210 (error (nth 1 msg)))
16212 The return value will then be either a string with the error message,
16213 or a marker if everything is OK.
16215 If THIS-BUFFER is set, the outline path does not contain a file,
16216 only headings."
16217 (let* ((file (if this-buffer buffer-file-name (pop path)))
16218 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16219 (level 1)
16220 (lmin 1)
16221 (lmax 1)
16222 limit re end found pos heading cnt flevel)
16223 (unless buffer (error "File not found :%s" file))
16224 (with-current-buffer buffer
16225 (save-excursion
16226 (save-restriction
16227 (widen)
16228 (setq limit (point-max))
16229 (goto-char (point-min))
16230 (while (setq heading (pop path))
16231 (setq re (format org-complex-heading-regexp-format
16232 (regexp-quote heading)))
16233 (setq cnt 0 pos (point))
16234 (while (re-search-forward re end t)
16235 (setq level (- (match-end 1) (match-beginning 1)))
16236 (if (and (>= level lmin) (<= level lmax))
16237 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16238 (when (= cnt 0) (error "Heading not found on level %d: %s"
16239 lmax heading))
16240 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16241 lmax heading))
16242 (goto-char found)
16243 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16244 (setq end (save-excursion (org-end-of-subtree t t))))
16245 (when (org-at-heading-p)
16246 (point-marker)))))))
16248 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16249 "Find node HEADING in BUFFER.
16250 Return a marker to the heading if it was found, or nil if not.
16251 If POS-ONLY is set, return just the position instead of a marker.
16253 The heading text must match exact, but it may have a TODO keyword,
16254 a priority cookie and tags in the standard locations."
16255 (with-current-buffer (or buffer (current-buffer))
16256 (save-excursion
16257 (save-restriction
16258 (widen)
16259 (goto-char (point-min))
16260 (let (case-fold-search)
16261 (if (re-search-forward
16262 (format org-complex-heading-regexp-format
16263 (regexp-quote heading)) nil t)
16264 (if pos-only
16265 (match-beginning 0)
16266 (move-marker (make-marker) (match-beginning 0)))))))))
16268 (defun org-find-exact-heading-in-directory (heading &optional dir)
16269 "Find Org node headline HEADING in all .org files in directory DIR.
16270 When the target headline is found, return a marker to this location."
16271 (let ((files (directory-files (or dir default-directory)
16272 t "\\`[^.#].*\\.org\\'"))
16273 file visiting m buffer)
16274 (catch 'found
16275 (while (setq file (pop files))
16276 (message "trying %s" file)
16277 (setq visiting (org-find-base-buffer-visiting file))
16278 (setq buffer (or visiting (find-file-noselect file)))
16279 (setq m (org-find-exact-headline-in-buffer
16280 heading buffer))
16281 (when (and (not m) (not visiting)) (kill-buffer buffer))
16282 (and m (throw 'found m))))))
16284 (defun org-find-entry-with-id (ident)
16285 "Locate the entry that contains the ID property with exact value IDENT.
16286 IDENT can be a string, a symbol or a number, this function will search for
16287 the string representation of it.
16288 Return the position where this entry starts, or nil if there is no such entry."
16289 (interactive "sID: ")
16290 (let ((id (cond
16291 ((stringp ident) ident)
16292 ((symbol-name ident) (symbol-name ident))
16293 ((numberp ident) (number-to-string ident))
16294 (t (error "IDENT %s must be a string, symbol or number" ident))))
16295 (case-fold-search nil))
16296 (save-excursion
16297 (save-restriction
16298 (widen)
16299 (goto-char (point-min))
16300 (when (re-search-forward
16301 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16302 nil t)
16303 (org-back-to-heading t)
16304 (point))))))
16306 ;;;; Timestamps
16308 (defvar org-last-changed-timestamp nil)
16309 (defvar org-last-inserted-timestamp nil
16310 "The last time stamp inserted with `org-insert-time-stamp'.")
16311 (defvar org-ts-what) ; dynamically scoped parameter
16313 (defun org-time-stamp (arg &optional inactive)
16314 "Prompt for a date/time and insert a time stamp.
16315 If the user specifies a time like HH:MM or if this command is
16316 called with at least one prefix argument, the time stamp contains
16317 the date and the time. Otherwise, only the date is be included.
16319 All parts of a date not specified by the user is filled in from
16320 the current date/time. So if you just press return without
16321 typing anything, the time stamp will represent the current
16322 date/time.
16324 If there is already a timestamp at the cursor, it will be
16325 modified.
16327 With two universal prefix arguments, insert an active timestamp
16328 with the current time without prompting the user.
16330 When called from lisp, the timestamp is inactive if INACTIVE is
16331 non-nil."
16332 (interactive "P")
16333 (let* ((ts nil)
16334 (default-time
16335 ;; Default time is either today, or, when entering a range,
16336 ;; the range start.
16337 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16338 (save-excursion
16339 (re-search-backward
16340 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16341 (- (point) 20) t)))
16342 (apply 'encode-time (org-parse-time-string (match-string 1)))
16343 (current-time)))
16344 (default-input (and ts (org-get-compact-tod ts)))
16345 (repeater (save-excursion
16346 (save-match-data
16347 (beginning-of-line)
16348 (when (re-search-forward
16349 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16350 (save-excursion (progn (end-of-line) (point))) t)
16351 (match-string 0)))))
16352 org-time-was-given org-end-time-was-given time)
16353 (cond
16354 ((and (org-at-timestamp-p t)
16355 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16356 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16357 (insert "--")
16358 (setq time (let ((this-command this-command))
16359 (org-read-date arg 'totime nil nil
16360 default-time default-input inactive)))
16361 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16362 ((org-at-timestamp-p t)
16363 (setq time (let ((this-command this-command))
16364 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16365 (when (org-at-timestamp-p t) ; just to get the match data
16366 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16367 (replace-match "")
16368 (setq org-last-changed-timestamp
16369 (org-insert-time-stamp
16370 time (or org-time-was-given arg)
16371 inactive nil nil (list org-end-time-was-given)))
16372 (when repeater (goto-char (1- (point))) (insert " " repeater)
16373 (setq org-last-changed-timestamp
16374 (concat (substring org-last-inserted-timestamp 0 -1)
16375 " " repeater ">"))))
16376 (message "Timestamp updated"))
16377 ((equal arg '(16))
16378 (org-insert-time-stamp (current-time) t inactive))
16380 (setq time (let ((this-command this-command))
16381 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16382 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16383 nil nil (list org-end-time-was-given))))))
16385 ;; FIXME: can we use this for something else, like computing time differences?
16386 (defun org-get-compact-tod (s)
16387 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16388 (let* ((t1 (match-string 1 s))
16389 (h1 (string-to-number (match-string 2 s)))
16390 (m1 (string-to-number (match-string 3 s)))
16391 (t2 (and (match-end 4) (match-string 5 s)))
16392 (h2 (and t2 (string-to-number (match-string 6 s))))
16393 (m2 (and t2 (string-to-number (match-string 7 s))))
16394 dh dm)
16395 (if (not t2)
16397 (setq dh (- h2 h1) dm (- m2 m1))
16398 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16399 (concat t1 "+" (number-to-string dh)
16400 (and (/= 0 dm) (format ":%02d" dm)))))))
16402 (defun org-time-stamp-inactive (&optional arg)
16403 "Insert an inactive time stamp.
16404 An inactive time stamp is enclosed in square brackets instead of angle
16405 brackets. It is inactive in the sense that it does not trigger agenda entries,
16406 does not link to the calendar and cannot be changed with the S-cursor keys.
16407 So these are more for recording a certain time/date."
16408 (interactive "P")
16409 (org-time-stamp arg 'inactive))
16411 (defvar org-date-ovl (make-overlay 1 1))
16412 (overlay-put org-date-ovl 'face 'org-date-selected)
16413 (org-detach-overlay org-date-ovl)
16415 (defvar org-ans1) ; dynamically scoped parameter
16416 (defvar org-ans2) ; dynamically scoped parameter
16418 (defvar org-plain-time-of-day-regexp) ; defined below
16420 (defvar org-overriding-default-time nil) ; dynamically scoped
16421 (defvar org-read-date-overlay nil)
16422 (defvar org-dcst nil) ; dynamically scoped
16423 (defvar org-read-date-history nil)
16424 (defvar org-read-date-final-answer nil)
16425 (defvar org-read-date-analyze-futurep nil)
16426 (defvar org-read-date-analyze-forced-year nil)
16427 (defvar org-read-date-inactive)
16429 (defvar org-read-date-minibuffer-local-map
16430 (let* ((org-replace-disputed-keys nil)
16431 (map (make-sparse-keymap)))
16432 (set-keymap-parent map minibuffer-local-map)
16433 (org-defkey map (kbd ".")
16434 (lambda () (interactive)
16435 ;; Are we at the beginning of the prompt?
16436 (if (looking-back "^[^:]+: ")
16437 (org-eval-in-calendar '(calendar-goto-today))
16438 (insert "."))))
16439 (org-defkey map (kbd "C-.")
16440 (lambda () (interactive)
16441 (org-eval-in-calendar '(calendar-goto-today))))
16442 (org-defkey map [(meta shift left)]
16443 (lambda () (interactive)
16444 (org-eval-in-calendar '(calendar-backward-month 1))))
16445 (org-defkey map [(meta shift right)]
16446 (lambda () (interactive)
16447 (org-eval-in-calendar '(calendar-forward-month 1))))
16448 (org-defkey map [(meta shift up)]
16449 (lambda () (interactive)
16450 (org-eval-in-calendar '(calendar-backward-year 1))))
16451 (org-defkey map [(meta shift down)]
16452 (lambda () (interactive)
16453 (org-eval-in-calendar '(calendar-forward-year 1))))
16454 (org-defkey map [?\e (shift left)]
16455 (lambda () (interactive)
16456 (org-eval-in-calendar '(calendar-backward-month 1))))
16457 (org-defkey map [?\e (shift right)]
16458 (lambda () (interactive)
16459 (org-eval-in-calendar '(calendar-forward-month 1))))
16460 (org-defkey map [?\e (shift up)]
16461 (lambda () (interactive)
16462 (org-eval-in-calendar '(calendar-backward-year 1))))
16463 (org-defkey map [?\e (shift down)]
16464 (lambda () (interactive)
16465 (org-eval-in-calendar '(calendar-forward-year 1))))
16466 (org-defkey map [(shift up)]
16467 (lambda () (interactive)
16468 (org-eval-in-calendar '(calendar-backward-week 1))))
16469 (org-defkey map [(shift down)]
16470 (lambda () (interactive)
16471 (org-eval-in-calendar '(calendar-forward-week 1))))
16472 (org-defkey map [(shift left)]
16473 (lambda () (interactive)
16474 (org-eval-in-calendar '(calendar-backward-day 1))))
16475 (org-defkey map [(shift right)]
16476 (lambda () (interactive)
16477 (org-eval-in-calendar '(calendar-forward-day 1))))
16478 (org-defkey map "!"
16479 (lambda () (interactive)
16480 (org-eval-in-calendar '(diary-view-entries))
16481 (message "")))
16482 (org-defkey map ">"
16483 (lambda () (interactive)
16484 (org-eval-in-calendar '(scroll-calendar-left 1))))
16485 (org-defkey map "<"
16486 (lambda () (interactive)
16487 (org-eval-in-calendar '(scroll-calendar-right 1))))
16488 (org-defkey map "\C-v"
16489 (lambda () (interactive)
16490 (org-eval-in-calendar
16491 '(calendar-scroll-left-three-months 1))))
16492 (org-defkey map "\M-v"
16493 (lambda () (interactive)
16494 (org-eval-in-calendar
16495 '(calendar-scroll-right-three-months 1))))
16496 map)
16497 "Keymap for minibuffer commands when using `org-read-date'.")
16499 (defvar org-def)
16500 (defvar org-defdecode)
16501 (defvar org-with-time)
16503 (defun org-read-date (&optional org-with-time to-time from-string prompt
16504 default-time default-input inactive)
16505 "Read a date, possibly a time, and make things smooth for the user.
16506 The prompt will suggest to enter an ISO date, but you can also enter anything
16507 which will at least partially be understood by `parse-time-string'.
16508 Unrecognized parts of the date will default to the current day, month, year,
16509 hour and minute. If this command is called to replace a timestamp at point,
16510 or to enter the second timestamp of a range, the default time is taken
16511 from the existing stamp. Furthermore, the command prefers the future,
16512 so if you are giving a date where the year is not given, and the day-month
16513 combination is already past in the current year, it will assume you
16514 mean next year. For details, see the manual. A few examples:
16516 3-2-5 --> 2003-02-05
16517 feb 15 --> currentyear-02-15
16518 2/15 --> currentyear-02-15
16519 sep 12 9 --> 2009-09-12
16520 12:45 --> today 12:45
16521 22 sept 0:34 --> currentyear-09-22 0:34
16522 12 --> currentyear-currentmonth-12
16523 Fri --> nearest Friday after today
16524 -Tue --> last Tuesday
16525 etc.
16527 Furthermore you can specify a relative date by giving, as the *first* thing
16528 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16529 change in days weeks, months, years.
16530 With a single plus or minus, the date is relative to today. With a double
16531 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16532 +4d --> four days from today
16533 +4 --> same as above
16534 +2w --> two weeks from today
16535 ++5 --> five days from default date
16537 The function understands only English month and weekday abbreviations.
16539 While prompting, a calendar is popped up - you can also select the
16540 date with the mouse (button 1). The calendar shows a period of three
16541 months. To scroll it to other months, use the keys `>' and `<'.
16542 If you don't like the calendar, turn it off with
16543 \(setq org-read-date-popup-calendar nil)
16545 With optional argument TO-TIME, the date will immediately be converted
16546 to an internal time.
16547 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16548 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16549 still enter a time, and this function will inform the calling routine
16550 about this change. The calling routine may then choose to change the
16551 format used to insert the time stamp into the buffer to include the time.
16552 With optional argument FROM-STRING, read from this string instead from
16553 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16554 the time/date that is used for everything that is not specified by the
16555 user."
16556 (require 'parse-time)
16557 (let* ((org-time-stamp-rounding-minutes
16558 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16559 (org-dcst org-display-custom-times)
16560 (ct (org-current-time))
16561 (org-def (or org-overriding-default-time default-time ct))
16562 (org-defdecode (decode-time org-def))
16563 (dummy (progn
16564 (when (< (nth 2 org-defdecode) org-extend-today-until)
16565 (setcar (nthcdr 2 org-defdecode) -1)
16566 (setcar (nthcdr 1 org-defdecode) 59)
16567 (setq org-def (apply 'encode-time org-defdecode)
16568 org-defdecode (decode-time org-def)))))
16569 (mouse-autoselect-window nil) ; Don't let the mouse jump
16570 (calendar-frame-setup nil)
16571 (calendar-setup nil)
16572 (calendar-move-hook nil)
16573 (calendar-view-diary-initially-flag nil)
16574 (calendar-view-holidays-initially-flag nil)
16575 (timestr (format-time-string
16576 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16577 (prompt (concat (if prompt (concat prompt " ") "")
16578 (format "Date+time [%s]: " timestr)))
16579 ans (org-ans0 "") org-ans1 org-ans2 final)
16581 (cond
16582 (from-string (setq ans from-string))
16583 (org-read-date-popup-calendar
16584 (save-excursion
16585 (save-window-excursion
16586 (calendar)
16587 (org-eval-in-calendar '(setq cursor-type nil) t)
16588 (unwind-protect
16589 (progn
16590 (calendar-forward-day (- (time-to-days org-def)
16591 (calendar-absolute-from-gregorian
16592 (calendar-current-date))))
16593 (org-eval-in-calendar nil t)
16594 (let* ((old-map (current-local-map))
16595 (map (copy-keymap calendar-mode-map))
16596 (minibuffer-local-map
16597 (copy-keymap org-read-date-minibuffer-local-map)))
16598 (org-defkey map (kbd "RET") 'org-calendar-select)
16599 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16600 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16601 (unwind-protect
16602 (progn
16603 (use-local-map map)
16604 (setq org-read-date-inactive inactive)
16605 (add-hook 'post-command-hook 'org-read-date-display)
16606 (setq org-ans0 (read-string prompt default-input
16607 'org-read-date-history nil))
16608 ;; org-ans0: from prompt
16609 ;; org-ans1: from mouse click
16610 ;; org-ans2: from calendar motion
16611 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16612 (remove-hook 'post-command-hook 'org-read-date-display)
16613 (use-local-map old-map)
16614 (when org-read-date-overlay
16615 (delete-overlay org-read-date-overlay)
16616 (setq org-read-date-overlay nil)))))
16617 (bury-buffer "*Calendar*")))))
16619 (t ; Naked prompt only
16620 (unwind-protect
16621 (setq ans (read-string prompt default-input
16622 'org-read-date-history timestr))
16623 (when org-read-date-overlay
16624 (delete-overlay org-read-date-overlay)
16625 (setq org-read-date-overlay nil)))))
16627 (setq final (org-read-date-analyze ans org-def org-defdecode))
16629 (when org-read-date-analyze-forced-year
16630 (message "Year was forced into %s"
16631 (if org-read-date-force-compatible-dates
16632 "compatible range (1970-2037)"
16633 "range representable on this machine"))
16634 (ding))
16636 ;; One round trip to get rid of 34th of August and stuff like that....
16637 (setq final (decode-time (apply 'encode-time final)))
16639 (setq org-read-date-final-answer ans)
16641 (if to-time
16642 (apply 'encode-time final)
16643 (if (and (boundp 'org-time-was-given) org-time-was-given)
16644 (format "%04d-%02d-%02d %02d:%02d"
16645 (nth 5 final) (nth 4 final) (nth 3 final)
16646 (nth 2 final) (nth 1 final))
16647 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16649 (defun org-read-date-display ()
16650 "Display the current date prompt interpretation in the minibuffer."
16651 (when org-read-date-display-live
16652 (when org-read-date-overlay
16653 (delete-overlay org-read-date-overlay))
16654 (when (minibufferp (current-buffer))
16655 (save-excursion
16656 (end-of-line 1)
16657 (while (not (equal (buffer-substring
16658 (max (point-min) (- (point) 4)) (point))
16659 " "))
16660 (insert " ")))
16661 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16662 " " (or org-ans1 org-ans2)))
16663 (org-end-time-was-given nil)
16664 (f (org-read-date-analyze ans org-def org-defdecode))
16665 (fmts (if org-dcst
16666 org-time-stamp-custom-formats
16667 org-time-stamp-formats))
16668 (fmt (if (or org-with-time
16669 (and (boundp 'org-time-was-given) org-time-was-given))
16670 (cdr fmts)
16671 (car fmts)))
16672 (txt (format-time-string fmt (apply 'encode-time f)))
16673 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16674 (txt (concat "=> " txt)))
16675 (when (and org-end-time-was-given
16676 (string-match org-plain-time-of-day-regexp txt))
16677 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16678 org-end-time-was-given
16679 (substring txt (match-end 0)))))
16680 (when org-read-date-analyze-futurep
16681 (setq txt (concat txt " (=>F)")))
16682 (setq org-read-date-overlay
16683 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16684 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16686 (defun org-read-date-analyze (ans org-def org-defdecode)
16687 "Analyze the combined answer of the date prompt."
16688 ;; FIXME: cleanup and comment
16689 (let ((nowdecode (decode-time (current-time)))
16690 delta deltan deltaw deltadef year month day
16691 hour minute second wday pm h2 m2 tl wday1
16692 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16693 (setq org-read-date-analyze-futurep nil
16694 org-read-date-analyze-forced-year nil)
16695 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16696 (setq ans "+0"))
16698 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16699 (setq ans (replace-match "" t t ans)
16700 deltan (car delta)
16701 deltaw (nth 1 delta)
16702 deltadef (nth 2 delta)))
16704 ;; Check if there is an iso week date in there. If yes, store the
16705 ;; info and postpone interpreting it until the rest of the parsing
16706 ;; is done.
16707 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16708 (setq iso-year (if (match-end 1)
16709 (org-small-year-to-year
16710 (string-to-number (match-string 1 ans))))
16711 iso-weekday (if (match-end 3)
16712 (string-to-number (match-string 3 ans)))
16713 iso-week (string-to-number (match-string 2 ans)))
16714 (setq ans (replace-match "" t t ans)))
16716 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16717 (when (string-match
16718 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16719 (setq year (if (match-end 2)
16720 (string-to-number (match-string 2 ans))
16721 (progn (setq kill-year t)
16722 (string-to-number (format-time-string "%Y"))))
16723 month (string-to-number (match-string 3 ans))
16724 day (string-to-number (match-string 4 ans)))
16725 (if (< year 100) (setq year (+ 2000 year)))
16726 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16727 t nil ans)))
16729 ;; Help matching dotted european dates
16730 (when (string-match
16731 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16732 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16733 (setq kill-year t)
16734 (string-to-number (format-time-string "%Y")))
16735 day (string-to-number (match-string 1 ans))
16736 month (string-to-number (match-string 2 ans))
16737 ans (replace-match (format "%04d-%02d-%02d" year month day)
16738 t nil ans)))
16740 ;; Help matching american dates, like 5/30 or 5/30/7
16741 (when (string-match
16742 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16743 (setq year (if (match-end 4)
16744 (string-to-number (match-string 4 ans))
16745 (progn (setq kill-year t)
16746 (string-to-number (format-time-string "%Y"))))
16747 month (string-to-number (match-string 1 ans))
16748 day (string-to-number (match-string 2 ans)))
16749 (if (< year 100) (setq year (+ 2000 year)))
16750 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16751 t nil ans)))
16752 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16753 ;; If there is a time with am/pm, and *no* time without it, we convert
16754 ;; so that matching will be successful.
16755 (loop for i from 1 to 2 do ; twice, for end time as well
16756 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16757 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16758 (setq hour (string-to-number (match-string 1 ans))
16759 minute (if (match-end 3)
16760 (string-to-number (match-string 3 ans))
16762 pm (equal ?p
16763 (string-to-char (downcase (match-string 4 ans)))))
16764 (if (and (= hour 12) (not pm))
16765 (setq hour 0)
16766 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16767 (setq ans (replace-match (format "%02d:%02d" hour minute)
16768 t t ans))))
16770 ;; Check if a time range is given as a duration
16771 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16772 (setq hour (string-to-number (match-string 1 ans))
16773 h2 (+ hour (string-to-number (match-string 3 ans)))
16774 minute (string-to-number (match-string 2 ans))
16775 m2 (+ minute (if (match-end 5) (string-to-number
16776 (match-string 5 ans))0)))
16777 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16778 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16779 t t ans)))
16781 ;; Check if there is a time range
16782 (when (boundp 'org-end-time-was-given)
16783 (setq org-time-was-given nil)
16784 (when (and (string-match org-plain-time-of-day-regexp ans)
16785 (match-end 8))
16786 (setq org-end-time-was-given (match-string 8 ans))
16787 (setq ans (concat (substring ans 0 (match-beginning 7))
16788 (substring ans (match-end 7))))))
16790 (setq tl (parse-time-string ans)
16791 day (or (nth 3 tl) (nth 3 org-defdecode))
16792 month (or (nth 4 tl)
16793 (if (and org-read-date-prefer-future
16794 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16795 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16796 (nth 4 org-defdecode)))
16797 year (or (and (not kill-year) (nth 5 tl))
16798 (if (and org-read-date-prefer-future
16799 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16800 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16801 (nth 5 org-defdecode)))
16802 hour (or (nth 2 tl) (nth 2 org-defdecode))
16803 minute (or (nth 1 tl) (nth 1 org-defdecode))
16804 second (or (nth 0 tl) 0)
16805 wday (nth 6 tl))
16807 (when (and (eq org-read-date-prefer-future 'time)
16808 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16809 (equal day (nth 3 nowdecode))
16810 (equal month (nth 4 nowdecode))
16811 (equal year (nth 5 nowdecode))
16812 (nth 2 tl)
16813 (or (< (nth 2 tl) (nth 2 nowdecode))
16814 (and (= (nth 2 tl) (nth 2 nowdecode))
16815 (nth 1 tl)
16816 (< (nth 1 tl) (nth 1 nowdecode)))))
16817 (setq day (1+ day)
16818 futurep t))
16820 ;; Special date definitions below
16821 (cond
16822 (iso-week
16823 ;; There was an iso week
16824 (require 'cal-iso)
16825 (setq futurep nil)
16826 (setq year (or iso-year year)
16827 day (or iso-weekday wday 1)
16828 wday nil ; to make sure that the trigger below does not match
16829 iso-date (calendar-gregorian-from-absolute
16830 (calendar-absolute-from-iso
16831 (list iso-week day year))))
16832 ; FIXME: Should we also push ISO weeks into the future?
16833 ; (when (and org-read-date-prefer-future
16834 ; (not iso-year)
16835 ; (< (calendar-absolute-from-gregorian iso-date)
16836 ; (time-to-days (current-time))))
16837 ; (setq year (1+ year)
16838 ; iso-date (calendar-gregorian-from-absolute
16839 ; (calendar-absolute-from-iso
16840 ; (list iso-week day year)))))
16841 (setq month (car iso-date)
16842 year (nth 2 iso-date)
16843 day (nth 1 iso-date)))
16844 (deltan
16845 (setq futurep nil)
16846 (unless deltadef
16847 (let ((now (decode-time (current-time))))
16848 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16849 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16850 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16851 ((equal deltaw "m") (setq month (+ month deltan)))
16852 ((equal deltaw "y") (setq year (+ year deltan)))))
16853 ((and wday (not (nth 3 tl)))
16854 ;; Weekday was given, but no day, so pick that day in the week
16855 ;; on or after the derived date.
16856 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16857 (unless (equal wday wday1)
16858 (setq day (+ day (% (- wday wday1 -7) 7))))))
16859 (if (and (boundp 'org-time-was-given)
16860 (nth 2 tl))
16861 (setq org-time-was-given t))
16862 (if (< year 100) (setq year (+ 2000 year)))
16863 ;; Check of the date is representable
16864 (if org-read-date-force-compatible-dates
16865 (progn
16866 (if (< year 1970)
16867 (setq year 1970 org-read-date-analyze-forced-year t))
16868 (if (> year 2037)
16869 (setq year 2037 org-read-date-analyze-forced-year t)))
16870 (condition-case nil
16871 (ignore (encode-time second minute hour day month year))
16872 (error
16873 (setq year (nth 5 org-defdecode))
16874 (setq org-read-date-analyze-forced-year t))))
16875 (setq org-read-date-analyze-futurep futurep)
16876 (list second minute hour day month year)))
16878 (defvar parse-time-weekdays)
16879 (defun org-read-date-get-relative (s today default)
16880 "Check string S for special relative date string.
16881 TODAY and DEFAULT are internal times, for today and for a default.
16882 Return shift list (N what def-flag)
16883 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16884 N is the number of WHATs to shift.
16885 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16886 the DEFAULT date rather than TODAY."
16887 (require 'parse-time)
16888 (when (and
16889 (string-match
16890 (concat
16891 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16892 "\\([0-9]+\\)?"
16893 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16894 "\\([ \t]\\|$\\)") s)
16895 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16896 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16897 (string-to-char (substring (match-string 1 s) -1))
16898 ?+))
16899 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16900 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16901 (what (if (match-end 3) (match-string 3 s) "d"))
16902 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16903 (date (if rel default today))
16904 (wday (nth 6 (decode-time date)))
16905 delta)
16906 (if wday1
16907 (progn
16908 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16909 (if (= delta 0) (setq delta 7))
16910 (if (= dir ?-)
16911 (progn
16912 (setq delta (- delta 7))
16913 (if (= delta 0) (setq delta -7))))
16914 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16915 (list delta "d" rel))
16916 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16918 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16919 "Turn a user-specified date into the internal representation.
16920 The internal representation needed by the calendar is (month day year).
16921 This is a wrapper to handle the brain-dead convention in calendar that
16922 user function argument order change dependent on argument order."
16923 (if (boundp 'calendar-date-style)
16924 (cond
16925 ((eq calendar-date-style 'american)
16926 (list arg1 arg2 arg3))
16927 ((eq calendar-date-style 'european)
16928 (list arg2 arg1 arg3))
16929 ((eq calendar-date-style 'iso)
16930 (list arg2 arg3 arg1)))
16931 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16932 (if (org-bound-and-true-p european-calendar-style)
16933 (list arg2 arg1 arg3)
16934 (list arg1 arg2 arg3)))))
16936 (defun org-eval-in-calendar (form &optional keepdate)
16937 "Eval FORM in the calendar window and return to current window.
16938 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16939 otherwise stick to the current value of `org-ans2'."
16940 (let ((sf (selected-frame))
16941 (sw (selected-window)))
16942 (select-window (get-buffer-window "*Calendar*" t))
16943 (eval form)
16944 (when (and (not keepdate) (calendar-cursor-to-date))
16945 (let* ((date (calendar-cursor-to-date))
16946 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16947 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16948 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16949 (select-window sw)
16950 (org-select-frame-set-input-focus sf)))
16952 (defun org-calendar-select ()
16953 "Return to `org-read-date' with the date currently selected.
16954 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16955 (interactive)
16956 (when (calendar-cursor-to-date)
16957 (let* ((date (calendar-cursor-to-date))
16958 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16959 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16960 (if (active-minibuffer-window) (exit-minibuffer))))
16962 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16963 "Insert a date stamp for the date given by the internal TIME.
16964 WITH-HM means use the stamp format that includes the time of the day.
16965 INACTIVE means use square brackets instead of angular ones, so that the
16966 stamp will not contribute to the agenda.
16967 PRE and POST are optional strings to be inserted before and after the
16968 stamp.
16969 The command returns the inserted time stamp."
16970 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16971 stamp)
16972 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16973 (insert-before-markers (or pre ""))
16974 (when (listp extra)
16975 (setq extra (car extra))
16976 (if (and (stringp extra)
16977 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16978 (setq extra (format "-%02d:%02d"
16979 (string-to-number (match-string 1 extra))
16980 (string-to-number (match-string 2 extra))))
16981 (setq extra nil)))
16982 (when extra
16983 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16984 (insert-before-markers (setq stamp (format-time-string fmt time)))
16985 (insert-before-markers (or post ""))
16986 (setq org-last-inserted-timestamp stamp)))
16988 (defun org-toggle-time-stamp-overlays ()
16989 "Toggle the use of custom time stamp formats."
16990 (interactive)
16991 (setq org-display-custom-times (not org-display-custom-times))
16992 (unless org-display-custom-times
16993 (let ((p (point-min)) (bmp (buffer-modified-p)))
16994 (while (setq p (next-single-property-change p 'display))
16995 (if (and (get-text-property p 'display)
16996 (eq (get-text-property p 'face) 'org-date))
16997 (remove-text-properties
16998 p (setq p (next-single-property-change p 'display))
16999 '(display t))))
17000 (set-buffer-modified-p bmp)))
17001 (if (featurep 'xemacs)
17002 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17003 (org-restart-font-lock)
17004 (setq org-table-may-need-update t)
17005 (if org-display-custom-times
17006 (message "Time stamps are overlaid with custom format")
17007 (message "Time stamp overlays removed")))
17009 (defun org-display-custom-time (beg end)
17010 "Overlay modified time stamp format over timestamp between BEG and END."
17011 (let* ((ts (buffer-substring beg end))
17012 t1 w1 with-hm tf time str w2 (off 0))
17013 (save-match-data
17014 (setq t1 (org-parse-time-string ts t))
17015 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17016 (setq off (- (match-end 0) (match-beginning 0)))))
17017 (setq end (- end off))
17018 (setq w1 (- end beg)
17019 with-hm (and (nth 1 t1) (nth 2 t1))
17020 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17021 time (org-fix-decoded-time t1)
17022 str (org-add-props
17023 (format-time-string
17024 (substring tf 1 -1) (apply 'encode-time time))
17025 nil 'mouse-face 'highlight)
17026 w2 (length str))
17027 (if (not (= w2 w1))
17028 (add-text-properties (1+ beg) (+ 2 beg)
17029 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17030 (if (featurep 'xemacs)
17031 (progn
17032 (put-text-property beg end 'invisible t)
17033 (put-text-property beg end 'end-glyph (make-glyph str)))
17034 (put-text-property beg end 'display str))))
17036 (defun org-translate-time (string)
17037 "Translate all timestamps in STRING to custom format.
17038 But do this only if the variable `org-display-custom-times' is set."
17039 (when org-display-custom-times
17040 (save-match-data
17041 (let* ((start 0)
17042 (re org-ts-regexp-both)
17043 t1 with-hm inactive tf time str beg end)
17044 (while (setq start (string-match re string start))
17045 (setq beg (match-beginning 0)
17046 end (match-end 0)
17047 t1 (save-match-data
17048 (org-parse-time-string (substring string beg end) t))
17049 with-hm (and (nth 1 t1) (nth 2 t1))
17050 inactive (equal (substring string beg (1+ beg)) "[")
17051 tf (funcall (if with-hm 'cdr 'car)
17052 org-time-stamp-custom-formats)
17053 time (org-fix-decoded-time t1)
17054 str (format-time-string
17055 (concat
17056 (if inactive "[" "<") (substring tf 1 -1)
17057 (if inactive "]" ">"))
17058 (apply 'encode-time time))
17059 string (replace-match str t t string)
17060 start (+ start (length str)))))))
17061 string)
17063 (defun org-fix-decoded-time (time)
17064 "Set 0 instead of nil for the first 6 elements of time.
17065 Don't touch the rest."
17066 (let ((n 0))
17067 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17069 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17071 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17072 "Difference between TIMESTAMP-STRING and now in days.
17073 If SECONDS is non-nil, return the difference in seconds."
17074 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17075 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17076 (funcall fdiff (current-time)))))
17078 (defun org-deadline-close (timestamp-string &optional ndays)
17079 "Is the time in TIMESTAMP-STRING close to the current date?"
17080 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17081 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17082 (not (org-entry-is-done-p))))
17084 (defun org-get-wdays (ts &optional delay zero-delay)
17085 "Get the deadline lead time appropriate for timestring TS.
17086 When DELAY is non-nil, get the delay time for scheduled items
17087 instead of the deadline lead time. When ZERO-DELAY is non-nil
17088 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17089 don't try to find the delay cookie in the scheduled timestamp."
17090 (let ((tv (if delay org-scheduled-delay-days
17091 org-deadline-warning-days)))
17092 (cond
17093 ((or (and delay (< tv 0))
17094 (and delay zero-delay (<= tv 0))
17095 (and (not delay) (<= tv 0)))
17096 ;; Enforce this value no matter what
17097 (- tv))
17098 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17099 ;; lead time is specified.
17100 (floor (* (string-to-number (match-string 1 ts))
17101 (cdr (assoc (match-string 2 ts)
17102 '(("d" . 1) ("w" . 7)
17103 ("m" . 30.4) ("y" . 365.25)
17104 ("h" . 0.041667)))))))
17105 ;; go for the default.
17106 (t tv))))
17108 (defun org-calendar-select-mouse (ev)
17109 "Return to `org-read-date' with the date currently selected.
17110 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17111 (interactive "e")
17112 (mouse-set-point ev)
17113 (when (calendar-cursor-to-date)
17114 (let* ((date (calendar-cursor-to-date))
17115 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17116 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17117 (if (active-minibuffer-window) (exit-minibuffer))))
17119 (defun org-check-deadlines (ndays)
17120 "Check if there are any deadlines due or past due.
17121 A deadline is considered due if it happens within `org-deadline-warning-days'
17122 days from today's date. If the deadline appears in an entry marked DONE,
17123 it is not shown. The prefix arg NDAYS can be used to test that many
17124 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17125 (interactive "P")
17126 (let* ((org-warn-days
17127 (cond
17128 ((equal ndays '(4)) 100000)
17129 (ndays (prefix-numeric-value ndays))
17130 (t (abs org-deadline-warning-days))))
17131 (case-fold-search nil)
17132 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17133 (callback
17134 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17136 (message "%d deadlines past-due or due within %d days"
17137 (org-occur regexp nil callback)
17138 org-warn-days)))
17140 (defsubst org-re-timestamp (type)
17141 "Return a regexp for timestamp TYPE.
17142 Allowed values for TYPE are:
17144 all: all timestamps
17145 active: only active timestamps (<...>)
17146 inactive: only inactive timestamps ([...])
17147 scheduled: only scheduled timestamps
17148 deadline: only deadline timestamps
17149 closed: only closed time-stamps
17151 When TYPE is nil, fall back on returning a regexp that matches
17152 both scheduled and deadline timestamps."
17153 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17154 ((eq type 'active) org-ts-regexp)
17155 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17156 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17157 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17158 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17159 ((eq type 'scheduled-or-deadline)
17160 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17162 (defun org-check-before-date (date)
17163 "Check if there are deadlines or scheduled entries before DATE."
17164 (interactive (list (org-read-date)))
17165 (let ((case-fold-search nil)
17166 (regexp (org-re-timestamp org-ts-type))
17167 (callback
17168 (lambda () (time-less-p
17169 (org-time-string-to-time (match-string 1))
17170 (org-time-string-to-time date)))))
17171 (message "%d entries before %s"
17172 (org-occur regexp nil callback) date)))
17174 (defun org-check-after-date (date)
17175 "Check if there are deadlines or scheduled entries after DATE."
17176 (interactive (list (org-read-date)))
17177 (let ((case-fold-search nil)
17178 (regexp (org-re-timestamp org-ts-type))
17179 (callback
17180 (lambda () (not
17181 (time-less-p
17182 (org-time-string-to-time (match-string 1))
17183 (org-time-string-to-time date))))))
17184 (message "%d entries after %s"
17185 (org-occur regexp nil callback) date)))
17187 (defun org-check-dates-range (start-date end-date)
17188 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17189 (interactive (list (org-read-date nil nil nil "Range starts")
17190 (org-read-date nil nil nil "Range end")))
17191 (let ((case-fold-search nil)
17192 (regexp (org-re-timestamp org-ts-type))
17193 (callback
17194 (lambda ()
17195 (let ((match (match-string 1)))
17196 (and
17197 (not (time-less-p
17198 (org-time-string-to-time match)
17199 (org-time-string-to-time start-date)))
17200 (time-less-p
17201 (org-time-string-to-time match)
17202 (org-time-string-to-time end-date)))))))
17203 (message "%d entries between %s and %s"
17204 (org-occur regexp nil callback) start-date end-date)))
17206 (defun org-evaluate-time-range (&optional to-buffer)
17207 "Evaluate a time range by computing the difference between start and end.
17208 Normally the result is just printed in the echo area, but with prefix arg
17209 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17210 If the time range is actually in a table, the result is inserted into the
17211 next column.
17212 For time difference computation, a year is assumed to be exactly 365
17213 days in order to avoid rounding problems."
17214 (interactive "P")
17216 (org-clock-update-time-maybe)
17217 (save-excursion
17218 (unless (org-at-date-range-p t)
17219 (goto-char (point-at-bol))
17220 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17221 (if (not (org-at-date-range-p t))
17222 (user-error "Not at a time-stamp range, and none found in current line")))
17223 (let* ((ts1 (match-string 1))
17224 (ts2 (match-string 2))
17225 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17226 (match-end (match-end 0))
17227 (time1 (org-time-string-to-time ts1))
17228 (time2 (org-time-string-to-time ts2))
17229 (t1 (org-float-time time1))
17230 (t2 (org-float-time time2))
17231 (diff (abs (- t2 t1)))
17232 (negative (< (- t2 t1) 0))
17233 ;; (ys (floor (* 365 24 60 60)))
17234 (ds (* 24 60 60))
17235 (hs (* 60 60))
17236 (fy "%dy %dd %02d:%02d")
17237 (fy1 "%dy %dd")
17238 (fd "%dd %02d:%02d")
17239 (fd1 "%dd")
17240 (fh "%02d:%02d")
17241 y d h m align)
17242 (if havetime
17243 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17245 d (floor (/ diff ds)) diff (mod diff ds)
17246 h (floor (/ diff hs)) diff (mod diff hs)
17247 m (floor (/ diff 60)))
17248 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17250 d (floor (+ (/ diff ds) 0.5))
17251 h 0 m 0))
17252 (if (not to-buffer)
17253 (message "%s" (org-make-tdiff-string y d h m))
17254 (if (org-at-table-p)
17255 (progn
17256 (goto-char match-end)
17257 (setq align t)
17258 (and (looking-at " *|") (goto-char (match-end 0))))
17259 (goto-char match-end))
17260 (if (looking-at
17261 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17262 (replace-match ""))
17263 (if negative (insert " -"))
17264 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17265 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17266 (insert " " (format fh h m))))
17267 (if align (org-table-align))
17268 (message "Time difference inserted")))))
17270 (defun org-make-tdiff-string (y d h m)
17271 (let ((fmt "")
17272 (l nil))
17273 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17274 l (push y l)))
17275 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17276 l (push d l)))
17277 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17278 l (push h l)))
17279 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17280 l (push m l)))
17281 (apply 'format fmt (nreverse l))))
17283 (defun org-time-string-to-time (s &optional buffer pos)
17284 "Convert a timestamp string into internal time."
17285 (condition-case errdata
17286 (apply 'encode-time (org-parse-time-string s))
17287 (error (error "Bad timestamp `%s'%s\nError was: %s"
17288 s (if (not (and buffer pos))
17290 (format " at %d in buffer `%s'" pos buffer))
17291 (cdr errdata)))))
17293 (defun org-time-string-to-seconds (s)
17294 "Convert a timestamp string to a number of seconds."
17295 (org-float-time (org-time-string-to-time s)))
17297 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17298 "Convert a time stamp to an absolute day number.
17299 If there is a specifier for a cyclic time stamp, get the closest
17300 date to DAYNR.
17301 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17302 The variable `date' is bound by the calendar when this is called."
17303 (cond
17304 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17305 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17306 daynr
17307 (+ daynr 1000)))
17308 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17309 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17310 (time-to-days (current-time))) (match-string 0 s)
17311 prefer show-all))
17312 (t (time-to-days
17313 (condition-case errdata
17314 (apply 'encode-time (org-parse-time-string s))
17315 (error (error "Bad timestamp `%s'%s\nError was: %s"
17316 s (if (not (and buffer pos))
17318 (format " at %d in buffer `%s'" pos buffer))
17319 (cdr errdata))))))))
17321 (defun org-days-to-iso-week (days)
17322 "Return the iso week number."
17323 (require 'cal-iso)
17324 (car (calendar-iso-from-absolute days)))
17326 (defun org-small-year-to-year (year)
17327 "Convert 2-digit years into 4-digit years.
17328 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17329 The year 2000 cannot be abbreviated. Any year larger than 99
17330 is returned unchanged."
17331 (if (< year 38)
17332 (setq year (+ 2000 year))
17333 (if (< year 100)
17334 (setq year (+ 1900 year))))
17335 year)
17337 (defun org-time-from-absolute (d)
17338 "Return the time corresponding to date D.
17339 D may be an absolute day number, or a calendar-type list (month day year)."
17340 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17341 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17343 (defun org-calendar-holiday ()
17344 "List of holidays, for Diary display in Org-mode."
17345 (require 'holidays)
17346 (let ((hl (funcall
17347 (if (fboundp 'calendar-check-holidays)
17348 'calendar-check-holidays 'check-calendar-holidays) date)))
17349 (if hl (mapconcat 'identity hl "; "))))
17351 (defun org-diary-sexp-entry (sexp entry date)
17352 "Process a SEXP diary ENTRY for DATE."
17353 (require 'diary-lib)
17354 (let ((result (if calendar-debug-sexp
17355 (let ((stack-trace-on-error t))
17356 (eval (car (read-from-string sexp))))
17357 (condition-case nil
17358 (eval (car (read-from-string sexp)))
17359 (error
17360 (beep)
17361 (message "Bad sexp at line %d in %s: %s"
17362 (org-current-line)
17363 (buffer-file-name) sexp)
17364 (sleep-for 2))))))
17365 (cond ((stringp result) (split-string result "; "))
17366 ((and (consp result)
17367 (not (consp (cdr result)))
17368 (stringp (cdr result))) (cdr result))
17369 ((and (consp result)
17370 (stringp (car result))) result)
17371 (result entry))))
17373 (defun org-diary-to-ical-string (frombuf)
17374 "Get iCalendar entries from diary entries in buffer FROMBUF.
17375 This uses the icalendar.el library."
17376 (let* ((tmpdir (if (featurep 'xemacs)
17377 (temp-directory)
17378 temporary-file-directory))
17379 (tmpfile (make-temp-name
17380 (expand-file-name "orgics" tmpdir)))
17381 buf rtn b e)
17382 (with-current-buffer frombuf
17383 (icalendar-export-region (point-min) (point-max) tmpfile)
17384 (setq buf (find-buffer-visiting tmpfile))
17385 (set-buffer buf)
17386 (goto-char (point-min))
17387 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17388 (setq b (match-beginning 0)))
17389 (goto-char (point-max))
17390 (if (re-search-backward "^END:VEVENT" nil t)
17391 (setq e (match-end 0)))
17392 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17393 (kill-buffer buf)
17394 (delete-file tmpfile)
17395 rtn))
17397 (defun org-closest-date (start current change prefer show-all)
17398 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17399 When PREFER is `past', return a date that is either CURRENT or past.
17400 When PREFER is `future', return a date that is either CURRENT or future.
17401 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17402 ;; Make the proper lists from the dates
17403 (catch 'exit
17404 (let ((a1 '(("h" . hour)
17405 ("d" . day)
17406 ("w" . week)
17407 ("m" . month)
17408 ("y" . year)))
17409 (shour (nth 2 (org-parse-time-string start)))
17410 dn dw sday cday n1 n2 n0
17411 d m y y1 y2 date1 date2 nmonths nm ny m2)
17413 (setq start (org-date-to-gregorian start)
17414 current (org-date-to-gregorian
17415 (if show-all
17416 current
17417 (time-to-days (current-time))))
17418 sday (calendar-absolute-from-gregorian start)
17419 cday (calendar-absolute-from-gregorian current))
17421 (if (<= cday sday) (throw 'exit sday))
17423 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17424 (setq dn (string-to-number (match-string 1 change))
17425 dw (cdr (assoc (match-string 2 change) a1)))
17426 (user-error "Invalid change specifier: %s" change))
17427 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17428 (cond
17429 ((eq dw 'hour)
17430 (let ((missing-hours
17431 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17432 dn)))
17433 (setq n1 (if (zerop missing-hours) cday
17434 (- cday (1+ (floor (/ missing-hours 24)))))
17435 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17436 ((eq dw 'day)
17437 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17438 n2 (+ n1 dn)))
17439 ((eq dw 'year)
17440 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17441 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17442 (setq date1 (list m d y1)
17443 n1 (calendar-absolute-from-gregorian date1)
17444 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17445 n2 (calendar-absolute-from-gregorian date2)))
17446 ((eq dw 'month)
17447 ;; approx number of month between the two dates
17448 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17449 ;; How often does dn fit in there?
17450 (setq d (nth 1 start) m (car start) y (nth 2 start)
17451 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17452 m (+ m nm)
17453 ny (floor (/ m 12))
17454 y (+ y ny)
17455 m (- m (* ny 12)))
17456 (while (> m 12) (setq m (- m 12) y (1+ y)))
17457 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17458 (setq m2 (+ m dn) y2 y)
17459 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17460 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17461 (while (<= n2 cday)
17462 (setq n1 n2 m m2 y y2)
17463 (setq m2 (+ m dn) y2 y)
17464 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17465 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17466 ;; Make sure n1 is the earlier date
17467 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17468 (if show-all
17469 (cond
17470 ((eq prefer 'past) (if (= cday n2) n2 n1))
17471 ((eq prefer 'future) (if (= cday n1) n1 n2))
17472 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17473 (cond
17474 ((eq prefer 'past) (if (= cday n2) n2 n1))
17475 ((eq prefer 'future) (if (= cday n1) n1 n2))
17476 (t (if (= cday n1) n1 n2)))))))
17478 (defun org-date-to-gregorian (date)
17479 "Turn any specification of DATE into a Gregorian date for the calendar."
17480 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17481 ((and (listp date) (= (length date) 3)) date)
17482 ((stringp date)
17483 (setq date (org-parse-time-string date))
17484 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17485 ((listp date)
17486 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17488 (defun org-parse-time-string (s &optional nodefault)
17489 "Parse the standard Org-mode time string.
17490 This should be a lot faster than the normal `parse-time-string'.
17491 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17492 hour and minute fields will be nil if not given."
17493 (cond ((string-match org-ts-regexp0 s)
17494 (list 0
17495 (if (or (match-beginning 8) (not nodefault))
17496 (string-to-number (or (match-string 8 s) "0")))
17497 (if (or (match-beginning 7) (not nodefault))
17498 (string-to-number (or (match-string 7 s) "0")))
17499 (string-to-number (match-string 4 s))
17500 (string-to-number (match-string 3 s))
17501 (string-to-number (match-string 2 s))
17502 nil nil nil))
17503 ((string-match "^<[^>]+>$" s)
17504 (decode-time (seconds-to-time (org-matcher-time s))))
17505 (t (error "Not a standard Org-mode time string: %s" s))))
17507 (defun org-timestamp-up (&optional arg)
17508 "Increase the date item at the cursor by one.
17509 If the cursor is on the year, change the year. If it is on the month,
17510 the day or the time, change that.
17511 With prefix ARG, change by that many units."
17512 (interactive "p")
17513 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17515 (defun org-timestamp-down (&optional arg)
17516 "Decrease the date item at the cursor by one.
17517 If the cursor is on the year, change the year. If it is on the month,
17518 the day or the time, change that.
17519 With prefix ARG, change by that many units."
17520 (interactive "p")
17521 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17523 (defun org-timestamp-up-day (&optional arg)
17524 "Increase the date in the time stamp by one day.
17525 With prefix ARG, change that many days."
17526 (interactive "p")
17527 (if (and (not (org-at-timestamp-p t))
17528 (org-at-heading-p))
17529 (org-todo 'up)
17530 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17532 (defun org-timestamp-down-day (&optional arg)
17533 "Decrease the date in the time stamp by one day.
17534 With prefix ARG, change that many days."
17535 (interactive "p")
17536 (if (and (not (org-at-timestamp-p t))
17537 (org-at-heading-p))
17538 (org-todo 'down)
17539 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17541 (defun org-at-timestamp-p (&optional inactive-ok)
17542 "Determine if the cursor is in or at a timestamp."
17543 (interactive)
17544 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17545 (pos (point))
17546 (ans (or (looking-at tsr)
17547 (save-excursion
17548 (skip-chars-backward "^[<\n\r\t")
17549 (if (> (point) (point-min)) (backward-char 1))
17550 (and (looking-at tsr)
17551 (> (- (match-end 0) pos) -1))))))
17552 (and ans
17553 (boundp 'org-ts-what)
17554 (setq org-ts-what
17555 (cond
17556 ((= pos (match-beginning 0)) 'bracket)
17557 ;; Point is considered to be "on the bracket" whether
17558 ;; it's really on it or right after it.
17559 ((= pos (1- (match-end 0))) 'bracket)
17560 ((= pos (match-end 0)) 'after)
17561 ((org-pos-in-match-range pos 2) 'year)
17562 ((org-pos-in-match-range pos 3) 'month)
17563 ((org-pos-in-match-range pos 7) 'hour)
17564 ((org-pos-in-match-range pos 8) 'minute)
17565 ((or (org-pos-in-match-range pos 4)
17566 (org-pos-in-match-range pos 5)) 'day)
17567 ((and (> pos (or (match-end 8) (match-end 5)))
17568 (< pos (match-end 0)))
17569 (- pos (or (match-end 8) (match-end 5))))
17570 (t 'day))))
17571 ans))
17573 (defun org-toggle-timestamp-type ()
17574 "Toggle the type (<active> or [inactive]) of a time stamp."
17575 (interactive)
17576 (when (org-at-timestamp-p t)
17577 (let ((beg (match-beginning 0)) (end (match-end 0))
17578 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17579 (save-excursion
17580 (goto-char beg)
17581 (while (re-search-forward "[][<>]" end t)
17582 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17583 t t)))
17584 (message "Timestamp is now %sactive"
17585 (if (equal (char-after beg) ?<) "" "in")))))
17587 (defun org-at-clock-log-p nil
17588 "Is the cursor on the clock log line?"
17589 (save-excursion
17590 (move-beginning-of-line 1)
17591 (looking-at "^[ \t]*CLOCK:")))
17593 (defvar org-clock-history) ; defined in org-clock.el
17594 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17595 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17596 "Change the date in the time stamp at point.
17597 The date will be changed by N times WHAT. WHAT can be `day', `month',
17598 `year', `minute', `second'. If WHAT is not given, the cursor position
17599 in the timestamp determines what will be changed.
17600 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17601 (let ((origin (point)) origin-cat
17602 with-hm inactive
17603 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17604 org-ts-what
17605 extra rem
17606 ts time time0 fixnext clrgx)
17607 (if (not (org-at-timestamp-p t))
17608 (user-error "Not at a timestamp"))
17609 (if (and (not what) (eq org-ts-what 'bracket))
17610 (org-toggle-timestamp-type)
17611 ;; Point isn't on brackets. Remember the part of the time-stamp
17612 ;; the point was in. Indeed, size of time-stamps may change,
17613 ;; but point must be kept in the same category nonetheless.
17614 (setq origin-cat org-ts-what)
17615 (if (and (not what) (not (eq org-ts-what 'day))
17616 org-display-custom-times
17617 (get-text-property (point) 'display)
17618 (not (get-text-property (1- (point)) 'display)))
17619 (setq org-ts-what 'day))
17620 (setq org-ts-what (or what org-ts-what)
17621 inactive (= (char-after (match-beginning 0)) ?\[)
17622 ts (match-string 0))
17623 (replace-match "")
17624 (when (string-match
17625 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17627 (setq extra (match-string 1 ts))
17628 (if suppress-tmp-delay
17629 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17630 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17631 (setq with-hm t))
17632 (setq time0 (org-parse-time-string ts))
17633 (when (and updown
17634 (eq org-ts-what 'minute)
17635 (not current-prefix-arg))
17636 ;; This looks like s-up and s-down. Change by one rounding step.
17637 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17638 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17639 (setcar (cdr time0) (+ (nth 1 time0)
17640 (if (> n 0) (- rem) (- dm rem))))))
17641 (setq time
17642 (encode-time (or (car time0) 0)
17643 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17644 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17645 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17646 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17647 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17648 (nthcdr 6 time0)))
17649 (when (and (member org-ts-what '(hour minute))
17650 extra
17651 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17652 (setq extra (org-modify-ts-extra
17653 extra
17654 (if (eq org-ts-what 'hour) 2 5)
17655 n dm)))
17656 (when (integerp org-ts-what)
17657 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17658 (if (eq what 'calendar)
17659 (let ((cal-date (org-get-date-from-calendar)))
17660 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17661 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17662 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17663 (setcar time0 (or (car time0) 0))
17664 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17665 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17666 (setq time (apply 'encode-time time0))))
17667 ;; Insert the new time-stamp, and ensure point stays in the same
17668 ;; category as before (i.e. not after the last position in that
17669 ;; category).
17670 (let ((pos (point)))
17671 ;; Stay before inserted string. `save-excursion' is of no use.
17672 (setq org-last-changed-timestamp
17673 (org-insert-time-stamp time with-hm inactive nil nil extra))
17674 (goto-char pos))
17675 (save-match-data
17676 (looking-at org-ts-regexp3)
17677 (goto-char (cond
17678 ;; `day' category ends before `hour' if any, or at
17679 ;; the end of the day name.
17680 ((eq origin-cat 'day)
17681 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17682 ((eq origin-cat 'hour) (min (match-end 7) origin))
17683 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17684 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17685 ;; `year' and `month' have both fixed size: point
17686 ;; couldn't have moved into another part.
17687 (t origin))))
17688 ;; Update clock if on a CLOCK line.
17689 (org-clock-update-time-maybe)
17690 ;; Maybe adjust the closest clock in `org-clock-history'
17691 (when org-clock-adjust-closest
17692 (if (not (and (org-at-clock-log-p)
17693 (< 1 (length (delq nil (mapcar 'marker-position
17694 org-clock-history))))))
17695 (message "No clock to adjust")
17696 (cond ((save-excursion ; fix previous clock?
17697 (re-search-backward org-ts-regexp0 nil t)
17698 (org-looking-back (concat org-clock-string " \\[")))
17699 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17700 ((save-excursion ; fix next clock?
17701 (re-search-backward org-ts-regexp0 nil t)
17702 (looking-at (concat org-ts-regexp0 "\\] =>")))
17703 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17704 (save-window-excursion
17705 ;; Find closest clock to point, adjust the previous/next one in history
17706 (let* ((p (save-excursion (org-back-to-heading t)))
17707 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17708 (clfixnth
17709 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17710 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17711 (if (not clfixpos)
17712 (message "No clock to adjust")
17713 (save-excursion
17714 (org-goto-marker-or-bmk clfixpos)
17715 (org-show-subtree)
17716 (when (re-search-forward clrgx nil t)
17717 (goto-char (match-beginning 1))
17718 (let (org-clock-adjust-closest)
17719 (org-timestamp-change n org-ts-what updown))
17720 (message "Clock adjusted in %s for heading: %s"
17721 (file-name-nondirectory (buffer-file-name))
17722 (org-get-heading t t)))))))))
17723 ;; Try to recenter the calendar window, if any.
17724 (if (and org-calendar-follow-timestamp-change
17725 (get-buffer-window "*Calendar*" t)
17726 (memq org-ts-what '(day month year)))
17727 (org-recenter-calendar (time-to-days time))))))
17729 (defun org-modify-ts-extra (s pos n dm)
17730 "Change the different parts of the lead-time and repeat fields in timestamp."
17731 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17732 ng h m new rem)
17733 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17734 (cond
17735 ((or (org-pos-in-match-range pos 2)
17736 (org-pos-in-match-range pos 3))
17737 (setq m (string-to-number (match-string 3 s))
17738 h (string-to-number (match-string 2 s)))
17739 (if (org-pos-in-match-range pos 2)
17740 (setq h (+ h n))
17741 (setq n (* dm (org-no-warnings (signum n))))
17742 (when (not (= 0 (setq rem (% m dm))))
17743 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17744 (setq m (+ m n)))
17745 (if (< m 0) (setq m (+ m 60) h (1- h)))
17746 (if (> m 59) (setq m (- m 60) h (1+ h)))
17747 (setq h (min 24 (max 0 h)))
17748 (setq ng 1 new (format "-%02d:%02d" h m)))
17749 ((org-pos-in-match-range pos 6)
17750 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17751 ((org-pos-in-match-range pos 5)
17752 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17754 ((org-pos-in-match-range pos 9)
17755 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17756 ((org-pos-in-match-range pos 8)
17757 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17759 (when ng
17760 (setq s (concat
17761 (substring s 0 (match-beginning ng))
17763 (substring s (match-end ng))))))
17766 (defun org-recenter-calendar (date)
17767 "If the calendar is visible, recenter it to DATE."
17768 (let ((cwin (get-buffer-window "*Calendar*" t)))
17769 (when cwin
17770 (let ((calendar-move-hook nil))
17771 (with-selected-window cwin
17772 (calendar-goto-date (if (listp date) date
17773 (calendar-gregorian-from-absolute date))))))))
17775 (defun org-goto-calendar (&optional arg)
17776 "Go to the Emacs calendar at the current date.
17777 If there is a time stamp in the current line, go to that date.
17778 A prefix ARG can be used to force the current date."
17779 (interactive "P")
17780 (let ((tsr org-ts-regexp) diff
17781 (calendar-move-hook nil)
17782 (calendar-view-holidays-initially-flag nil)
17783 (calendar-view-diary-initially-flag nil))
17784 (if (or (org-at-timestamp-p)
17785 (save-excursion
17786 (beginning-of-line 1)
17787 (looking-at (concat ".*" tsr))))
17788 (let ((d1 (time-to-days (current-time)))
17789 (d2 (time-to-days
17790 (org-time-string-to-time (match-string 1)))))
17791 (setq diff (- d2 d1))))
17792 (calendar)
17793 (calendar-goto-today)
17794 (if (and diff (not arg)) (calendar-forward-day diff))))
17796 (defun org-get-date-from-calendar ()
17797 "Return a list (month day year) of date at point in calendar."
17798 (with-current-buffer "*Calendar*"
17799 (save-match-data
17800 (calendar-cursor-to-date))))
17802 (defun org-date-from-calendar ()
17803 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17804 If there is already a time stamp at the cursor position, update it."
17805 (interactive)
17806 (if (org-at-timestamp-p t)
17807 (org-timestamp-change 0 'calendar)
17808 (let ((cal-date (org-get-date-from-calendar)))
17809 (org-insert-time-stamp
17810 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17812 (defcustom org-effort-durations
17813 `(("h" . 60)
17814 ("d" . ,(* 60 8))
17815 ("w" . ,(* 60 8 5))
17816 ("m" . ,(* 60 8 5 4))
17817 ("y" . ,(* 60 8 5 40)))
17818 "Conversion factor to minutes for an effort modifier.
17820 Each entry has the form (MODIFIER . MINUTES).
17822 In an effort string, a number followed by MODIFIER is multiplied
17823 by the specified number of MINUTES to obtain an effort in
17824 minutes.
17826 For example, if the value of this variable is ((\"hours\" . 60)), then an
17827 effort string \"2hours\" is equivalent to 120 minutes."
17828 :group 'org-agenda
17829 :version "24.1"
17830 :type '(alist :key-type (string :tag "Modifier")
17831 :value-type (number :tag "Minutes")))
17833 (defun org-minutes-to-clocksum-string (m)
17834 "Format number of minutes as a clocksum string.
17835 The format is determined by `org-time-clocksum-format',
17836 `org-time-clocksum-use-fractional' and
17837 `org-time-clocksum-fractional-format' and
17838 `org-time-clocksum-use-effort-durations'."
17839 (let ((clocksum "")
17840 (m (round m)) ; Don't allow fractions of minutes
17841 h d w mo y fmt n)
17842 (setq h (if org-time-clocksum-use-effort-durations
17843 (cdr (assoc "h" org-effort-durations)) 60)
17844 d (if org-time-clocksum-use-effort-durations
17845 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17846 w (if org-time-clocksum-use-effort-durations
17847 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17848 mo (if org-time-clocksum-use-effort-durations
17849 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17850 y (if org-time-clocksum-use-effort-durations
17851 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17852 ;; fractional format
17853 (if org-time-clocksum-use-fractional
17854 (cond
17855 ;; single format string
17856 ((stringp org-time-clocksum-fractional-format)
17857 (format org-time-clocksum-fractional-format (/ m (float h))))
17858 ;; choice of fractional formats for different time units
17859 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17860 (> (/ (truncate m) (* y d h)) 0))
17861 (format fmt (/ m (* y d (float h)))))
17862 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17863 (> (/ (truncate m) (* mo d h)) 0))
17864 (format fmt (/ m (* mo d (float h)))))
17865 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17866 (> (/ (truncate m) (* w d h)) 0))
17867 (format fmt (/ m (* w d (float h)))))
17868 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17869 (> (/ (truncate m) (* d h)) 0))
17870 (format fmt (/ m (* d (float h)))))
17871 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17872 (> (/ (truncate m) h) 0))
17873 (format fmt (/ m (float h))))
17874 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17875 (format fmt m))
17876 ;; fall back to smallest time unit with a format
17877 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17878 (format fmt (/ m (float h))))
17879 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17880 (format fmt (/ m (* d (float h)))))
17881 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17882 (format fmt (/ m (* w d (float h)))))
17883 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17884 (format fmt (/ m (* mo d (float h)))))
17885 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17886 (format fmt (/ m (* y d (float h))))))
17887 ;; standard (non-fractional) format, with single format string
17888 (if (stringp org-time-clocksum-format)
17889 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17890 ;; separate formats components
17891 (and (setq fmt (plist-get org-time-clocksum-format :years))
17892 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17893 (plist-get org-time-clocksum-format :require-years))
17894 (setq clocksum (concat clocksum (format fmt n))
17895 m (- m (* n y d h))))
17896 (and (setq fmt (plist-get org-time-clocksum-format :months))
17897 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17898 (plist-get org-time-clocksum-format :require-months))
17899 (setq clocksum (concat clocksum (format fmt n))
17900 m (- m (* n mo d h))))
17901 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17902 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17903 (plist-get org-time-clocksum-format :require-weeks))
17904 (setq clocksum (concat clocksum (format fmt n))
17905 m (- m (* n w d h))))
17906 (and (setq fmt (plist-get org-time-clocksum-format :days))
17907 (or (> (setq n (/ (truncate m) (* d h))) 0)
17908 (plist-get org-time-clocksum-format :require-days))
17909 (setq clocksum (concat clocksum (format fmt n))
17910 m (- m (* n d h))))
17911 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17912 (or (> (setq n (/ (truncate m) h)) 0)
17913 (plist-get org-time-clocksum-format :require-hours))
17914 (setq clocksum (concat clocksum (format fmt n))
17915 m (- m (* n h))))
17916 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17917 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17918 (setq clocksum (concat clocksum (format fmt m))))
17919 ;; return formatted time duration
17920 clocksum))))
17922 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17923 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17924 "Org mode version 8.0")
17926 (defun org-hours-to-clocksum-string (n)
17927 (org-minutes-to-clocksum-string (* n 60)))
17929 (defun org-hh:mm-string-to-minutes (s)
17930 "Convert a string H:MM to a number of minutes.
17931 If the string is just a number, interpret it as minutes.
17932 In fact, the first hh:mm or number in the string will be taken,
17933 there can be extra stuff in the string.
17934 If no number is found, the return value is 0."
17935 (cond
17936 ((integerp s) s)
17937 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17938 (+ (* (string-to-number (match-string 1 s)) 60)
17939 (string-to-number (match-string 2 s))))
17940 ((string-match "\\([0-9]+\\)" s)
17941 (string-to-number (match-string 1 s)))
17942 (t 0)))
17944 (defcustom org-image-actual-width t
17945 "Should we use the actual width of images when inlining them?
17947 When set to `t', always use the image width.
17949 When set to a number, use imagemagick (when available) to set
17950 the image's width to this value.
17952 When set to a number in a list, try to get the width from any
17953 #+ATTR.* keyword if it matches a width specification like
17955 #+ATTR_HTML: :width 300px
17957 and fall back on that number if none is found.
17959 When set to nil, try to get the width from an #+ATTR.* keyword
17960 and fall back on the original width if none is found.
17962 This requires Emacs >= 24.1, build with imagemagick support."
17963 :group 'org-appearance
17964 :version "24.4"
17965 :package-version '(Org . "8.0")
17966 :type '(choice
17967 (const :tag "Use the image width" t)
17968 (integer :tag "Use a number of pixels")
17969 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17970 (const :tag "Use #+ATTR* or don't resize" nil)))
17972 (defcustom org-agenda-inhibit-startup nil
17973 "Inhibit startup when preparing agenda buffers.
17974 When this variable is `t' (the default), the initialization of
17975 the Org agenda buffers is inhibited: e.g. the visibility state
17976 is not set, the tables are not re-aligned, etc."
17977 :type 'boolean
17978 :version "24.3"
17979 :group 'org-agenda)
17981 (define-obsolete-variable-alias
17982 'org-agenda-ignore-drawer-properties
17983 'org-agenda-ignore-properties "24.5")
17985 (defcustom org-agenda-ignore-properties nil
17986 "Avoid updating text properties when building the agenda.
17987 Properties are used to prepare buffers for effort estimates,
17988 appointments, statistics and subtree-local categories.
17989 If you don't use these in the agenda, you can add them to this
17990 list and agenda building will be a bit faster.
17991 The value is a list, with zero or more of the symbols `effort', `appt',
17992 `stats' or `category'."
17993 :type '(set :greedy t
17994 (const effort)
17995 (const appt)
17996 (const stats)
17997 (const category))
17998 :version "24.5"
17999 :package-version '(Org . "8.3")
18000 :group 'org-agenda)
18002 (defun org-duration-string-to-minutes (s &optional output-to-string)
18003 "Convert a duration string S to minutes.
18005 A bare number is interpreted as minutes, modifiers can be set by
18006 customizing `org-effort-durations' (which see).
18008 Entries containing a colon are interpreted as H:MM by
18009 `org-hh:mm-string-to-minutes'."
18010 (let ((result 0)
18011 (re (concat "\\([0-9.]+\\) *\\("
18012 (regexp-opt (mapcar 'car org-effort-durations))
18013 "\\)")))
18014 (while (string-match re s)
18015 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18016 (string-to-number (match-string 1 s))))
18017 (setq s (replace-match "" nil t s)))
18018 (setq result (floor result))
18019 (incf result (org-hh:mm-string-to-minutes s))
18020 (if output-to-string (number-to-string result) result)))
18022 ;;;; Files
18024 (defun org-save-all-org-buffers ()
18025 "Save all Org-mode buffers without user confirmation."
18026 (interactive)
18027 (message "Saving all Org-mode buffers...")
18028 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18029 (when (featurep 'org-id) (org-id-locations-save))
18030 (message "Saving all Org-mode buffers... done"))
18032 (defun org-revert-all-org-buffers ()
18033 "Revert all Org-mode buffers.
18034 Prompt for confirmation when there are unsaved changes.
18035 Be sure you know what you are doing before letting this function
18036 overwrite your changes.
18038 This function is useful in a setup where one tracks org files
18039 with a version control system, to revert on one machine after pulling
18040 changes from another. I believe the procedure must be like this:
18042 1. M-x org-save-all-org-buffers
18043 2. Pull changes from the other machine, resolve conflicts
18044 3. M-x org-revert-all-org-buffers"
18045 (interactive)
18046 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18047 (user-error "Abort"))
18048 (save-excursion
18049 (save-window-excursion
18050 (mapc
18051 (lambda (b)
18052 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18053 (with-current-buffer b buffer-file-name))
18054 (org-pop-to-buffer-same-window b)
18055 (revert-buffer t 'no-confirm)))
18056 (buffer-list))
18057 (when (and (featurep 'org-id) org-id-track-globally)
18058 (org-id-locations-load)))))
18060 ;;;; Agenda files
18062 ;;;###autoload
18063 (defun org-switchb (&optional arg)
18064 "Switch between Org buffers.
18065 With one prefix argument, restrict available buffers to files.
18066 With two prefix arguments, restrict available buffers to agenda files.
18068 Defaults to `iswitchb' for buffer name completion.
18069 Set `org-completion-use-ido' to make it use ido instead."
18070 (interactive "P")
18071 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18072 ((equal arg '(16)) (org-buffer-list 'agenda))
18073 (t (org-buffer-list))))
18074 (org-completion-use-iswitchb org-completion-use-iswitchb)
18075 (org-completion-use-ido org-completion-use-ido))
18076 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18077 (setq org-completion-use-iswitchb t))
18078 (org-pop-to-buffer-same-window
18079 (org-icompleting-read "Org buffer: "
18080 (mapcar 'list (mapcar 'buffer-name blist))
18081 nil t))))
18083 ;;; Define some older names previously used for this functionality
18084 ;;;###autoload
18085 (defalias 'org-ido-switchb 'org-switchb)
18086 ;;;###autoload
18087 (defalias 'org-iswitchb 'org-switchb)
18089 (defun org-buffer-list (&optional predicate exclude-tmp)
18090 "Return a list of Org buffers.
18091 PREDICATE can be `export', `files' or `agenda'.
18093 export restrict the list to Export buffers.
18094 files restrict the list to buffers visiting Org files.
18095 agenda restrict the list to buffers visiting agenda files.
18097 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18098 (let* ((bfn nil)
18099 (agenda-files (and (eq predicate 'agenda)
18100 (mapcar 'file-truename (org-agenda-files t))))
18101 (filter
18102 (cond
18103 ((eq predicate 'files)
18104 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18105 ((eq predicate 'export)
18106 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18107 ((eq predicate 'agenda)
18108 (lambda (b)
18109 (with-current-buffer b
18110 (and (derived-mode-p 'org-mode)
18111 (setq bfn (buffer-file-name b))
18112 (member (file-truename bfn) agenda-files)))))
18113 (t (lambda (b) (with-current-buffer b
18114 (or (derived-mode-p 'org-mode)
18115 (string-match "\*Org .*Export"
18116 (buffer-name b)))))))))
18117 (delq nil
18118 (mapcar
18119 (lambda(b)
18120 (if (and (funcall filter b)
18121 (or (not exclude-tmp)
18122 (not (string-match "tmp" (buffer-name b)))))
18124 nil))
18125 (buffer-list)))))
18127 (defun org-agenda-files (&optional unrestricted archives)
18128 "Get the list of agenda files.
18129 Optional UNRESTRICTED means return the full list even if a restriction
18130 is currently in place.
18131 When ARCHIVES is t, include all archive files that are really being
18132 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18133 `org-agenda-archives-mode' is t."
18134 (let ((files
18135 (cond
18136 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18137 ((stringp org-agenda-files) (org-read-agenda-file-list))
18138 ((listp org-agenda-files) org-agenda-files)
18139 (t (error "Invalid value of `org-agenda-files'")))))
18140 (setq files (apply 'append
18141 (mapcar (lambda (f)
18142 (if (file-directory-p f)
18143 (directory-files
18144 f t org-agenda-file-regexp)
18145 (list f)))
18146 files)))
18147 (when org-agenda-skip-unavailable-files
18148 (setq files (delq nil
18149 (mapcar (function
18150 (lambda (file)
18151 (and (file-readable-p file) file)))
18152 files))))
18153 (when (or (eq archives t)
18154 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18155 (setq files (org-add-archive-files files)))
18156 files))
18158 (defun org-agenda-file-p (&optional file)
18159 "Return non-nil, if FILE is an agenda file.
18160 If FILE is omitted, use the file associated with the current
18161 buffer."
18162 (member (or file (buffer-file-name))
18163 (org-agenda-files t)))
18165 (defun org-edit-agenda-file-list ()
18166 "Edit the list of agenda files.
18167 Depending on setup, this either uses customize to edit the variable
18168 `org-agenda-files', or it visits the file that is holding the list. In the
18169 latter case, the buffer is set up in a way that saving it automatically kills
18170 the buffer and restores the previous window configuration."
18171 (interactive)
18172 (if (stringp org-agenda-files)
18173 (let ((cw (current-window-configuration)))
18174 (find-file org-agenda-files)
18175 (org-set-local 'org-window-configuration cw)
18176 (org-add-hook 'after-save-hook
18177 (lambda ()
18178 (set-window-configuration
18179 (prog1 org-window-configuration
18180 (kill-buffer (current-buffer))))
18181 (org-install-agenda-files-menu)
18182 (message "New agenda file list installed"))
18183 nil 'local)
18184 (message "%s" (substitute-command-keys
18185 "Edit list and finish with \\[save-buffer]")))
18186 (customize-variable 'org-agenda-files)))
18188 (defun org-store-new-agenda-file-list (list)
18189 "Set new value for the agenda file list and save it correctly."
18190 (if (stringp org-agenda-files)
18191 (let ((fe (org-read-agenda-file-list t)) b u)
18192 (while (setq b (find-buffer-visiting org-agenda-files))
18193 (kill-buffer b))
18194 (with-temp-file org-agenda-files
18195 (insert
18196 (mapconcat
18197 (lambda (f) ;; Keep un-expanded entries.
18198 (if (setq u (assoc f fe))
18199 (cdr u)
18201 list "\n")
18202 "\n")))
18203 (let ((org-mode-hook nil) (org-inhibit-startup t)
18204 (org-insert-mode-line-in-empty-file nil))
18205 (setq org-agenda-files list)
18206 (customize-save-variable 'org-agenda-files org-agenda-files))))
18208 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18209 "Read the list of agenda files from a file.
18210 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18211 filenames, used by `org-store-new-agenda-file-list' to write back
18212 un-expanded file names."
18213 (when (file-directory-p org-agenda-files)
18214 (error "`org-agenda-files' cannot be a single directory"))
18215 (when (stringp org-agenda-files)
18216 (with-temp-buffer
18217 (insert-file-contents org-agenda-files)
18218 (mapcar
18219 (lambda (f)
18220 (let ((e (expand-file-name (substitute-in-file-name f)
18221 org-directory)))
18222 (if pair-with-expansion
18223 (cons e f)
18224 e)))
18225 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18227 ;;;###autoload
18228 (defun org-cycle-agenda-files ()
18229 "Cycle through the files in `org-agenda-files'.
18230 If the current buffer visits an agenda file, find the next one in the list.
18231 If the current buffer does not, find the first agenda file."
18232 (interactive)
18233 (let* ((fs (org-agenda-files t))
18234 (files (append fs (list (car fs))))
18235 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18236 file)
18237 (unless files (user-error "No agenda files"))
18238 (catch 'exit
18239 (while (setq file (pop files))
18240 (if (equal (file-truename file) tcf)
18241 (when (car files)
18242 (find-file (car files))
18243 (throw 'exit t))))
18244 (find-file (car fs)))
18245 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18247 (defun org-agenda-file-to-front (&optional to-end)
18248 "Move/add the current file to the top of the agenda file list.
18249 If the file is not present in the list, it is added to the front. If it is
18250 present, it is moved there. With optional argument TO-END, add/move to the
18251 end of the list."
18252 (interactive "P")
18253 (let ((org-agenda-skip-unavailable-files nil)
18254 (file-alist (mapcar (lambda (x)
18255 (cons (file-truename x) x))
18256 (org-agenda-files t)))
18257 (ctf (file-truename
18258 (or buffer-file-name
18259 (user-error "Please save the current buffer to a file"))))
18260 x had)
18261 (setq x (assoc ctf file-alist) had x)
18263 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18264 (if to-end
18265 (setq file-alist (append (delq x file-alist) (list x)))
18266 (setq file-alist (cons x (delq x file-alist))))
18267 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18268 (org-install-agenda-files-menu)
18269 (message "File %s to %s of agenda file list"
18270 (if had "moved" "added") (if to-end "end" "front"))))
18272 (defun org-remove-file (&optional file)
18273 "Remove current file from the list of files in variable `org-agenda-files'.
18274 These are the files which are being checked for agenda entries.
18275 Optional argument FILE means use this file instead of the current."
18276 (interactive)
18277 (let* ((org-agenda-skip-unavailable-files nil)
18278 (file (or file buffer-file-name
18279 (user-error "Current buffer does not visit a file")))
18280 (true-file (file-truename file))
18281 (afile (abbreviate-file-name file))
18282 (files (delq nil (mapcar
18283 (lambda (x)
18284 (if (equal true-file
18285 (file-truename x))
18286 nil x))
18287 (org-agenda-files t)))))
18288 (if (not (= (length files) (length (org-agenda-files t))))
18289 (progn
18290 (org-store-new-agenda-file-list files)
18291 (org-install-agenda-files-menu)
18292 (message "Removed file: %s" afile))
18293 (message "File was not in list: %s (not removed)" afile))))
18295 (defun org-file-menu-entry (file)
18296 (vector file (list 'find-file file) t))
18298 (defun org-check-agenda-file (file)
18299 "Make sure FILE exists. If not, ask user what to do."
18300 (when (not (file-exists-p file))
18301 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18302 (abbreviate-file-name file))
18303 (let ((r (downcase (read-char-exclusive))))
18304 (cond
18305 ((equal r ?r)
18306 (org-remove-file file)
18307 (throw 'nextfile t))
18308 (t (user-error "Abort"))))))
18310 (defun org-get-agenda-file-buffer (file)
18311 "Get an agenda buffer visiting FILE.
18312 If the buffer needs to be created, add it to the list of buffers
18313 which might be released later."
18314 (let ((buf (org-find-base-buffer-visiting file)))
18315 (if buf
18316 buf ; just return it
18317 ;; Make a new buffer and remember it
18318 (setq buf (find-file-noselect file))
18319 (if buf (push buf org-agenda-new-buffers))
18320 buf)))
18322 (defun org-release-buffers (blist)
18323 "Release all buffers in list, asking the user for confirmation when needed.
18324 When a buffer is unmodified, it is just killed. When modified, it is saved
18325 \(if the user agrees) and then killed."
18326 (let (buf file)
18327 (while (setq buf (pop blist))
18328 (setq file (buffer-file-name buf))
18329 (when (and (buffer-modified-p buf)
18330 file
18331 (y-or-n-p (format "Save file %s? " file)))
18332 (with-current-buffer buf (save-buffer)))
18333 (kill-buffer buf))))
18335 (defun org-agenda-prepare-buffers (files)
18336 "Create buffers for all agenda files, protect archived trees and comments."
18337 (interactive)
18338 (let ((pa '(:org-archived t))
18339 (pc '(:org-comment t))
18340 (pall '(:org-archived t :org-comment t))
18341 (inhibit-read-only t)
18342 (org-inhibit-startup org-agenda-inhibit-startup)
18343 (rea (concat ":" org-archive-tag ":"))
18344 file re pos)
18345 (setq org-tag-alist-for-agenda nil
18346 org-tag-groups-alist-for-agenda nil)
18347 (save-excursion
18348 (save-restriction
18349 (while (setq file (pop files))
18350 (catch 'nextfile
18351 (if (bufferp file)
18352 (set-buffer file)
18353 (org-check-agenda-file file)
18354 (set-buffer (org-get-agenda-file-buffer file)))
18355 (widen)
18356 (org-set-regexps-and-options-for-tags)
18357 (setq pos (point))
18358 (goto-char (point-min))
18359 (let ((case-fold-search t))
18360 (when (search-forward "#+setupfile" nil t)
18361 ;; Don't set all regexps and options systematically as
18362 ;; this is only run for setting agenda tags from setup
18363 ;; file
18364 (org-set-regexps-and-options)))
18365 (or (memq 'category org-agenda-ignore-properties)
18366 (org-refresh-category-properties))
18367 (or (memq 'stats org-agenda-ignore-properties)
18368 (org-refresh-stats-properties))
18369 (or (memq 'effort org-agenda-ignore-properties)
18370 (org-refresh-effort-properties))
18371 (or (memq 'appt org-agenda-ignore-properties)
18372 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18373 (setq org-todo-keywords-for-agenda
18374 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18375 (setq org-done-keywords-for-agenda
18376 (append org-done-keywords-for-agenda org-done-keywords))
18377 (setq org-todo-keyword-alist-for-agenda
18378 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18379 (setq org-tag-alist-for-agenda
18380 (org-uniquify
18381 (append org-tag-alist-for-agenda
18382 org-tag-alist
18383 org-tag-persistent-alist)))
18384 (if org-group-tags
18385 (setq org-tag-groups-alist-for-agenda
18386 (org-uniquify-alist
18387 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18388 (org-with-silent-modifications
18389 (save-excursion
18390 (remove-text-properties (point-min) (point-max) pall)
18391 (when org-agenda-skip-archived-trees
18392 (goto-char (point-min))
18393 (while (re-search-forward rea nil t)
18394 (if (org-at-heading-p t)
18395 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18396 (goto-char (point-min))
18397 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18398 (while (re-search-forward re nil t)
18399 (when (save-match-data (org-in-commented-heading-p t))
18400 (add-text-properties
18401 (match-beginning 0) (org-end-of-subtree t) pc)))))
18402 (goto-char pos)))))
18403 (setq org-todo-keywords-for-agenda
18404 (org-uniquify org-todo-keywords-for-agenda))
18405 (setq org-todo-keyword-alist-for-agenda
18406 (org-uniquify org-todo-keyword-alist-for-agenda))))
18409 ;;;; CDLaTeX minor mode
18411 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18412 "Keymap for the minor `org-cdlatex-mode'.")
18414 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18415 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18416 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18417 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18418 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18420 (defvar org-cdlatex-texmathp-advice-is-done nil
18421 "Flag remembering if we have applied the advice to texmathp already.")
18423 (define-minor-mode org-cdlatex-mode
18424 "Toggle the minor `org-cdlatex-mode'.
18425 This mode supports entering LaTeX environment and math in LaTeX fragments
18426 in Org-mode.
18427 \\{org-cdlatex-mode-map}"
18428 nil " OCDL" nil
18429 (when org-cdlatex-mode
18430 (require 'cdlatex)
18431 (run-hooks 'cdlatex-mode-hook)
18432 (cdlatex-compute-tables))
18433 (unless org-cdlatex-texmathp-advice-is-done
18434 (setq org-cdlatex-texmathp-advice-is-done t)
18435 (defadvice texmathp (around org-math-always-on activate)
18436 "Always return t in org-mode buffers.
18437 This is because we want to insert math symbols without dollars even outside
18438 the LaTeX math segments. If Orgmode thinks that point is actually inside
18439 an embedded LaTeX fragment, let texmathp do its job.
18440 \\[org-cdlatex-mode-map]"
18441 (interactive)
18442 (let (p)
18443 (cond
18444 ((not (derived-mode-p 'org-mode)) ad-do-it)
18445 ((eq this-command 'cdlatex-math-symbol)
18446 (setq ad-return-value t
18447 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18449 (let ((p (org-inside-LaTeX-fragment-p)))
18450 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18451 (setq ad-return-value t
18452 texmathp-why '("Org-mode embedded math" . 0))
18453 (if p ad-do-it)))))))))
18455 (defun turn-on-org-cdlatex ()
18456 "Unconditionally turn on `org-cdlatex-mode'."
18457 (org-cdlatex-mode 1))
18459 (defun org-try-cdlatex-tab ()
18460 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18461 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18462 - inside a LaTeX fragment, or
18463 - after the first word in a line, where an abbreviation expansion could
18464 insert a LaTeX environment."
18465 (when org-cdlatex-mode
18466 (cond
18467 ;; Before any word on the line: No expansion possible.
18468 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18469 ;; Just after first word on the line: Expand it. Make sure it
18470 ;; cannot happen on headlines, though.
18471 ((save-excursion
18472 (skip-chars-backward "a-zA-Z0-9*")
18473 (skip-chars-backward " \t")
18474 (and (bolp) (not (org-at-heading-p))))
18475 (cdlatex-tab) t)
18476 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18478 (defun org-cdlatex-underscore-caret (&optional arg)
18479 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18480 Revert to the normal definition outside of these fragments."
18481 (interactive "P")
18482 (if (org-inside-LaTeX-fragment-p)
18483 (call-interactively 'cdlatex-sub-superscript)
18484 (let (org-cdlatex-mode)
18485 (call-interactively (key-binding (vector last-input-event))))))
18487 (defun org-cdlatex-math-modify (&optional arg)
18488 "Execute `cdlatex-math-modify' in LaTeX fragments.
18489 Revert to the normal definition outside of these fragments."
18490 (interactive "P")
18491 (if (org-inside-LaTeX-fragment-p)
18492 (call-interactively 'cdlatex-math-modify)
18493 (let (org-cdlatex-mode)
18494 (call-interactively (key-binding (vector last-input-event))))))
18498 ;;;; LaTeX fragments
18500 (defun org-inside-LaTeX-fragment-p ()
18501 "Test if point is inside a LaTeX fragment.
18502 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18503 sequence appearing also before point.
18504 Even though the matchers for math are configurable, this function assumes
18505 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18506 delimiters are skipped when they have been removed by customization.
18507 The return value is nil, or a cons cell with the delimiter and the
18508 position of this delimiter.
18510 This function does a reasonably good job, but can locally be fooled by
18511 for example currency specifications. For example it will assume being in
18512 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18513 fragments that are properly closed, but during editing, we have to live
18514 with the uncertainty caused by missing closing delimiters. This function
18515 looks only before point, not after."
18516 (catch 'exit
18517 (let ((pos (point))
18518 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18519 (lim (progn
18520 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18521 (point)))
18522 dd-on str (start 0) m re)
18523 (goto-char pos)
18524 (when dodollar
18525 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18526 re (nth 1 (assoc "$" org-latex-regexps)))
18527 (while (string-match re str start)
18528 (cond
18529 ((= (match-end 0) (length str))
18530 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18531 ((= (match-end 0) (- (length str) 5))
18532 (throw 'exit nil))
18533 (t (setq start (match-end 0))))))
18534 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18535 (goto-char pos)
18536 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18537 (and (match-beginning 2) (throw 'exit nil))
18538 ;; count $$
18539 (while (re-search-backward "\\$\\$" lim t)
18540 (setq dd-on (not dd-on)))
18541 (goto-char pos)
18542 (if dd-on (cons "$$" m))))))
18544 (defun org-inside-latex-macro-p ()
18545 "Is point inside a LaTeX macro or its arguments?"
18546 (save-match-data
18547 (org-in-regexp
18548 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18550 (defvar org-latex-fragment-image-overlays nil
18551 "List of overlays carrying the images of latex fragments.")
18552 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18554 (defun org-remove-latex-fragment-image-overlays ()
18555 "Remove all overlays with LaTeX fragment images in current buffer."
18556 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18557 (setq org-latex-fragment-image-overlays nil))
18559 (defun org-preview-latex-fragment (&optional subtree)
18560 "Preview the LaTeX fragment at point, or all locally or globally.
18561 If the cursor is in a LaTeX fragment, create the image and overlay
18562 it over the source code. If there is no fragment at point, display
18563 all fragments in the current text, from one headline to the next. With
18564 prefix SUBTREE, display all fragments in the current subtree. With a
18565 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18566 the cursor is before the first headline,
18567 display all fragments in the buffer.
18568 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18569 (interactive "P")
18570 (unless buffer-file-name
18571 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18572 (when (display-graphic-p)
18573 (org-remove-latex-fragment-image-overlays)
18574 (save-excursion
18575 (save-restriction
18576 (let (beg end at msg)
18577 (cond
18578 ((or (equal subtree '(16))
18579 (not (save-excursion
18580 (re-search-backward org-outline-regexp-bol nil t))))
18581 (setq beg (point-min) end (point-max)
18582 msg "Creating images for buffer...%s"))
18583 ((equal subtree '(4))
18584 (org-back-to-heading)
18585 (setq beg (point) end (org-end-of-subtree t)
18586 msg "Creating images for subtree...%s"))
18588 (if (setq at (org-inside-LaTeX-fragment-p))
18589 (goto-char (max (point-min) (- (cdr at) 2)))
18590 (org-back-to-heading))
18591 (setq beg (point) end (progn (outline-next-heading) (point))
18592 msg (if at "Creating image...%s"
18593 "Creating images for entry...%s"))))
18594 (message msg "")
18595 (narrow-to-region beg end)
18596 (goto-char beg)
18597 (org-format-latex
18598 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18599 (file-name-nondirectory
18600 buffer-file-name)))
18601 default-directory 'overlays msg at 'forbuffer
18602 org-latex-create-formula-image-program)
18603 (message msg "done. Use `C-c C-c' to remove images."))))))
18605 (defun org-format-latex (prefix &optional dir overlays msg at
18606 forbuffer processing-type)
18607 "Replace LaTeX fragments with links to an image, and produce images.
18608 Some of the options can be changed using the variable
18609 `org-format-latex-options'."
18610 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18611 (let* ((prefixnodir (file-name-nondirectory prefix))
18612 (absprefix (expand-file-name prefix dir))
18613 (todir (file-name-directory absprefix))
18614 (opt org-format-latex-options)
18615 (optnew org-format-latex-options)
18616 (matchers (plist-get opt :matchers))
18617 (re-list org-latex-regexps)
18618 (cnt 0) txt hash link beg end re e checkdir
18619 string
18620 m n block-type block linkfile movefile ov)
18621 ;; Check the different regular expressions
18622 (while (setq e (pop re-list))
18623 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18624 block (if block-type "\n\n" ""))
18625 (when (member m matchers)
18626 (goto-char (point-min))
18627 (while (re-search-forward re nil t)
18628 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18629 (or (not overlays)
18630 (not (eq (get-char-property (match-beginning n)
18631 'org-overlay-type)
18632 'org-latex-overlay))))
18633 (cond
18634 ((eq processing-type 'verbatim))
18635 ((eq processing-type 'mathjax)
18636 ;; Prepare for MathJax processing.
18637 (setq string (match-string n))
18638 (when (member m '("$" "$1"))
18639 (save-excursion
18640 (delete-region (match-beginning n) (match-end n))
18641 (goto-char (match-beginning n))
18642 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18643 ((or (eq processing-type 'dvipng)
18644 (eq processing-type 'imagemagick))
18645 ;; Process to an image.
18646 (setq txt (match-string n)
18647 beg (match-beginning n) end (match-end n)
18648 cnt (1+ cnt))
18649 (let ((face (face-at-point))
18650 (fg (plist-get opt :foreground))
18651 (bg (plist-get opt :background))
18652 ;; Ensure full list is printed.
18653 print-length print-level)
18654 (when forbuffer
18655 ;; Get the colors from the face at point.
18656 (goto-char beg)
18657 (when (eq fg 'auto)
18658 (setq fg (face-attribute face :foreground nil 'default)))
18659 (when (eq bg 'auto)
18660 (setq bg (face-attribute face :background nil 'default)))
18661 (setq optnew (copy-sequence opt))
18662 (plist-put optnew :foreground fg)
18663 (plist-put optnew :background bg))
18664 (setq hash (sha1 (prin1-to-string
18665 (list org-format-latex-header
18666 org-latex-default-packages-alist
18667 org-latex-packages-alist
18668 org-format-latex-options
18669 forbuffer txt fg bg)))
18670 linkfile (format "%s_%s.png" prefix hash)
18671 movefile (format "%s_%s.png" absprefix hash)))
18672 (setq link (concat block "[[file:" linkfile "]]" block))
18673 (if msg (message msg cnt))
18674 (goto-char beg)
18675 (unless checkdir ; Ensure the directory exists.
18676 (setq checkdir t)
18677 (or (file-directory-p todir) (make-directory todir t)))
18678 (unless (file-exists-p movefile)
18679 (org-create-formula-image
18680 txt movefile optnew forbuffer processing-type))
18681 (if overlays
18682 (progn
18683 (mapc (lambda (o)
18684 (if (eq (overlay-get o 'org-overlay-type)
18685 'org-latex-overlay)
18686 (delete-overlay o)))
18687 (overlays-in beg end))
18688 (setq ov (make-overlay beg end))
18689 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18690 (if (featurep 'xemacs)
18691 (progn
18692 (overlay-put ov 'invisible t)
18693 (overlay-put
18694 ov 'end-glyph
18695 (make-glyph (vector 'png :file movefile))))
18696 (overlay-put
18697 ov 'display
18698 (list 'image :type 'png :file movefile :ascent 'center)))
18699 (push ov org-latex-fragment-image-overlays)
18700 (goto-char end))
18701 (delete-region beg end)
18702 (insert (org-add-props link
18703 (list 'org-latex-src
18704 (replace-regexp-in-string
18705 "\"" "" txt)
18706 'org-latex-src-embed-type
18707 (if block-type 'paragraph 'character))))))
18708 ((eq processing-type 'mathml)
18709 ;; Process to MathML
18710 (unless (save-match-data (org-format-latex-mathml-available-p))
18711 (user-error "LaTeX to MathML converter not configured"))
18712 (setq txt (match-string n)
18713 beg (match-beginning n) end (match-end n)
18714 cnt (1+ cnt))
18715 (if msg (message msg cnt))
18716 (goto-char beg)
18717 (delete-region beg end)
18718 (insert (org-format-latex-as-mathml
18719 txt block-type prefix dir)))
18721 (error "Unknown conversion type %s for LaTeX fragments"
18722 processing-type)))))))))
18724 (defun org-create-math-formula (latex-frag &optional mathml-file)
18725 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18726 Use `org-latex-to-mathml-convert-command'. If the conversion is
18727 sucessful, return the portion between \"<math...> </math>\"
18728 elements otherwise return nil. When MATHML-FILE is specified,
18729 write the results in to that file. When invoked as an
18730 interactive command, prompt for LATEX-FRAG, with initial value
18731 set to the current active region and echo the results for user
18732 inspection."
18733 (interactive (list (let ((frag (when (org-region-active-p)
18734 (buffer-substring-no-properties
18735 (region-beginning) (region-end)))))
18736 (read-string "LaTeX Fragment: " frag nil frag))))
18737 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18738 (let* ((tmp-in-file (file-relative-name
18739 (make-temp-name (expand-file-name "ltxmathml-in"))))
18740 (ignore (write-region latex-frag nil tmp-in-file))
18741 (tmp-out-file (file-relative-name
18742 (make-temp-name (expand-file-name "ltxmathml-out"))))
18743 (cmd (format-spec
18744 org-latex-to-mathml-convert-command
18745 `((?j . ,(shell-quote-argument
18746 (expand-file-name org-latex-to-mathml-jar-file)))
18747 (?I . ,(shell-quote-argument tmp-in-file))
18748 (?o . ,(shell-quote-argument tmp-out-file)))))
18749 mathml shell-command-output)
18750 (when (org-called-interactively-p 'any)
18751 (unless (org-format-latex-mathml-available-p)
18752 (user-error "LaTeX to MathML converter not configured")))
18753 (message "Running %s" cmd)
18754 (setq shell-command-output (shell-command-to-string cmd))
18755 (setq mathml
18756 (when (file-readable-p tmp-out-file)
18757 (with-current-buffer (find-file-noselect tmp-out-file t)
18758 (goto-char (point-min))
18759 (when (re-search-forward
18760 (concat
18761 (regexp-quote
18762 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18763 "\\(.\\|\n\\)*"
18764 (regexp-quote "</math>")) nil t)
18765 (prog1 (match-string 0) (kill-buffer))))))
18766 (cond
18767 (mathml
18768 (setq mathml
18769 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18770 (when mathml-file
18771 (write-region mathml nil mathml-file))
18772 (when (org-called-interactively-p 'any)
18773 (message mathml)))
18774 ((message "LaTeX to MathML conversion failed")
18775 (message shell-command-output)))
18776 (delete-file tmp-in-file)
18777 (when (file-exists-p tmp-out-file)
18778 (delete-file tmp-out-file))
18779 mathml))
18781 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18782 prefix &optional dir)
18783 "Use `org-create-math-formula' but check local cache first."
18784 (let* ((absprefix (expand-file-name prefix dir))
18785 (print-length nil) (print-level nil)
18786 (formula-id (concat
18787 "formula-"
18788 (sha1
18789 (prin1-to-string
18790 (list latex-frag
18791 org-latex-to-mathml-convert-command)))))
18792 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18793 (formula-cache-dir (file-name-directory formula-cache)))
18795 (unless (file-directory-p formula-cache-dir)
18796 (make-directory formula-cache-dir t))
18798 (unless (file-exists-p formula-cache)
18799 (org-create-math-formula latex-frag formula-cache))
18801 (if (file-exists-p formula-cache)
18802 ;; Successful conversion. Return the link to MathML file.
18803 (org-add-props
18804 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18805 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18806 'org-latex-src-embed-type (if latex-frag-type
18807 'paragraph 'character)))
18808 ;; Failed conversion. Return the LaTeX fragment verbatim
18809 latex-frag)))
18811 (defun org-create-formula-image (string tofile options buffer &optional type)
18812 "Create an image from LaTeX source using dvipng or convert.
18813 This function calls either `org-create-formula-image-with-dvipng'
18814 or `org-create-formula-image-with-imagemagick' depending on the
18815 value of `org-latex-create-formula-image-program' or on the value
18816 of the optional TYPE variable.
18818 Note: ultimately these two function should be combined as they
18819 share a good deal of logic."
18820 (org-check-external-command
18821 "latex" "needed to convert LaTeX fragments to images")
18822 (funcall
18823 (case (or type org-latex-create-formula-image-program)
18824 ('dvipng
18825 (org-check-external-command
18826 "dvipng" "needed to convert LaTeX fragments to images")
18827 'org-create-formula-image-with-dvipng)
18828 ('imagemagick
18829 (org-check-external-command
18830 "convert" "you need to install imagemagick")
18831 'org-create-formula-image-with-imagemagick)
18832 (t (error
18833 "Invalid value of `org-latex-create-formula-image-program'")))
18834 string tofile options buffer))
18836 (declare-function org-export-get-backend "ox" (name))
18837 (declare-function org-export--get-global-options "ox" (&optional backend))
18838 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18839 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18840 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18841 (defun org-create-formula--latex-header ()
18842 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18843 (let ((info (org-combine-plists (org-export--get-global-options
18844 (org-export-get-backend 'latex))
18845 (org-export--get-inbuffer-options
18846 (org-export-get-backend 'latex)))))
18847 (org-latex-guess-babel-language
18848 (org-latex-guess-inputenc
18849 (org-splice-latex-header
18850 org-format-latex-header
18851 org-latex-default-packages-alist
18852 org-latex-packages-alist t
18853 (plist-get info :latex-header)))
18854 info)))
18856 ;; This function borrows from Ganesh Swami's latex2png.el
18857 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18858 "This calls dvipng."
18859 (require 'ox-latex)
18860 (let* ((tmpdir (if (featurep 'xemacs)
18861 (temp-directory)
18862 temporary-file-directory))
18863 (texfilebase (make-temp-name
18864 (expand-file-name "orgtex" tmpdir)))
18865 (texfile (concat texfilebase ".tex"))
18866 (dvifile (concat texfilebase ".dvi"))
18867 (pngfile (concat texfilebase ".png"))
18868 (fnh (if (featurep 'xemacs)
18869 (font-height (face-font 'default))
18870 (face-attribute 'default :height nil)))
18871 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18872 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18873 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18874 "Black"))
18875 (bg (or (plist-get options (if buffer :background :html-background))
18876 "Transparent")))
18877 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18878 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18879 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18880 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18881 (let ((latex-header (org-create-formula--latex-header)))
18882 (with-temp-file texfile
18883 (insert latex-header)
18884 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18885 (let ((dir default-directory))
18886 (ignore-errors
18887 (cd tmpdir)
18888 (call-process "latex" nil nil nil texfile))
18889 (cd dir))
18890 (if (not (file-exists-p dvifile))
18891 (progn (message "Failed to create dvi file from %s" texfile) nil)
18892 (ignore-errors
18893 (if (featurep 'xemacs)
18894 (call-process "dvipng" nil nil nil
18895 "-fg" fg "-bg" bg
18896 "-T" "tight"
18897 "-o" pngfile
18898 dvifile)
18899 (call-process "dvipng" nil nil nil
18900 "-fg" fg "-bg" bg
18901 "-D" dpi
18902 ;;"-x" scale "-y" scale
18903 "-T" "tight"
18904 "-o" pngfile
18905 dvifile)))
18906 (if (not (file-exists-p pngfile))
18907 (if org-format-latex-signal-error
18908 (error "Failed to create png file from %s" texfile)
18909 (message "Failed to create png file from %s" texfile)
18910 nil)
18911 ;; Use the requested file name and clean up
18912 (copy-file pngfile tofile 'replace)
18913 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18914 (if (file-exists-p (concat texfilebase e))
18915 (delete-file (concat texfilebase e))))
18916 pngfile))))
18918 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18919 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18920 "This calls convert, which is included into imagemagick."
18921 (require 'ox-latex)
18922 (let* ((tmpdir (if (featurep 'xemacs)
18923 (temp-directory)
18924 temporary-file-directory))
18925 (texfilebase (make-temp-name
18926 (expand-file-name "orgtex" tmpdir)))
18927 (texfile (concat texfilebase ".tex"))
18928 (pdffile (concat texfilebase ".pdf"))
18929 (pngfile (concat texfilebase ".png"))
18930 (fnh (if (featurep 'xemacs)
18931 (font-height (face-font 'default))
18932 (face-attribute 'default :height nil)))
18933 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18934 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18935 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18936 "black"))
18937 (bg (or (plist-get options (if buffer :background :html-background))
18938 "white")))
18939 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18940 (setq fg (org-latex-color-format fg)))
18941 (if (eq bg 'default) (setq bg (org-latex-color :background))
18942 (setq bg (org-latex-color-format
18943 (if (string= bg "Transparent") "white" bg))))
18944 (let ((latex-header (org-create-formula--latex-header)))
18945 (with-temp-file texfile
18946 (insert latex-header)
18947 (insert "\n\\begin{document}\n"
18948 "\\definecolor{fg}{rgb}{" fg "}\n"
18949 "\\definecolor{bg}{rgb}{" bg "}\n"
18950 "\n\\pagecolor{bg}\n"
18951 "\n{\\color{fg}\n"
18952 string
18953 "\n}\n"
18954 "\n\\end{document}\n")))
18955 (org-latex-compile texfile t)
18956 (if (not (file-exists-p pdffile))
18957 (progn (message "Failed to create pdf file from %s" texfile) nil)
18958 (ignore-errors
18959 (if (featurep 'xemacs)
18960 (call-process "convert" nil nil nil
18961 "-density" "96"
18962 "-trim"
18963 "-antialias"
18964 pdffile
18965 "-quality" "100"
18966 ;; "-sharpen" "0x1.0"
18967 pngfile)
18968 (call-process "convert" nil nil nil
18969 "-density" dpi
18970 "-trim"
18971 "-antialias"
18972 pdffile
18973 "-quality" "100"
18974 ;; "-sharpen" "0x1.0"
18975 pngfile)))
18976 (if (not (file-exists-p pngfile))
18977 (if org-format-latex-signal-error
18978 (error "Failed to create png file from %s" texfile)
18979 (message "Failed to create png file from %s" texfile)
18980 nil)
18981 ;; Use the requested file name and clean up
18982 (copy-file pngfile tofile 'replace)
18983 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18984 (if (file-exists-p (concat texfilebase e))
18985 (delete-file (concat texfilebase e))))
18986 pngfile))))
18988 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18989 "Fill a LaTeX header template TPL.
18990 In the template, the following place holders will be recognized:
18992 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18993 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18994 [PACKAGES] \\usepackage statements for PKG
18995 [NO-PACKAGES] do not include PKG
18996 [EXTRA] the string EXTRA
18997 [NO-EXTRA] do not include EXTRA
18999 For backward compatibility, if both the positive and the negative place
19000 holder is missing, the positive one (without the \"NO-\") will be
19001 assumed to be present at the end of the template.
19002 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19003 EXTRA is a string.
19004 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19005 (let (rpl (end ""))
19006 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19007 (setq rpl (if (or (match-end 1) (not def-pkg))
19008 "" (org-latex-packages-to-string def-pkg snippets-p t))
19009 tpl (replace-match rpl t t tpl))
19010 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19012 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19013 (setq rpl (if (or (match-end 1) (not pkg))
19014 "" (org-latex-packages-to-string pkg snippets-p t))
19015 tpl (replace-match rpl t t tpl))
19016 (if pkg (setq end
19017 (concat end "\n"
19018 (org-latex-packages-to-string pkg snippets-p)))))
19020 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19021 (setq rpl (if (or (match-end 1) (not extra))
19022 "" (concat extra "\n"))
19023 tpl (replace-match rpl t t tpl))
19024 (if (and extra (string-match "\\S-" extra))
19025 (setq end (concat end "\n" extra))))
19027 (if (string-match "\\S-" end)
19028 (concat tpl "\n" end)
19029 tpl)))
19031 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19032 "Turn an alist of packages into a string with the \\usepackage macros."
19033 (setq pkg (mapconcat (lambda(p)
19034 (cond
19035 ((stringp p) p)
19036 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19037 (format "%% Package %s omitted" (cadr p)))
19038 ((equal "" (car p))
19039 (format "\\usepackage{%s}" (cadr p)))
19041 (format "\\usepackage[%s]{%s}"
19042 (car p) (cadr p)))))
19044 "\n"))
19045 (if newline (concat pkg "\n") pkg))
19047 (defun org-dvipng-color (attr)
19048 "Return a RGB color specification for dvipng."
19049 (apply 'format "rgb %s %s %s"
19050 (mapcar 'org-normalize-color
19051 (if (featurep 'xemacs)
19052 (color-rgb-components
19053 (face-property 'default
19054 (cond ((eq attr :foreground) 'foreground)
19055 ((eq attr :background) 'background))))
19056 (color-values (face-attribute 'default attr nil))))))
19058 (defun org-dvipng-color-format (color-name)
19059 "Convert COLOR-NAME to a RGB color value for dvipng."
19060 (apply 'format "rgb %s %s %s"
19061 (mapcar 'org-normalize-color
19062 (color-values color-name))))
19064 (defun org-latex-color (attr)
19065 "Return a RGB color for the LaTeX color package."
19066 (apply 'format "%s,%s,%s"
19067 (mapcar 'org-normalize-color
19068 (if (featurep 'xemacs)
19069 (color-rgb-components
19070 (face-property 'default
19071 (cond ((eq attr :foreground) 'foreground)
19072 ((eq attr :background) 'background))))
19073 (color-values (face-attribute 'default attr nil))))))
19075 (defun org-latex-color-format (color-name)
19076 "Convert COLOR-NAME to a RGB color value."
19077 (apply 'format "%s,%s,%s"
19078 (mapcar 'org-normalize-color
19079 (color-values color-name))))
19081 (defun org-normalize-color (value)
19082 "Return string to be used as color value for an RGB component."
19083 (format "%g" (/ value 65535.0)))
19087 ;; Image display
19089 (defvar org-inline-image-overlays nil)
19090 (make-variable-buffer-local 'org-inline-image-overlays)
19092 (defun org-toggle-inline-images (&optional include-linked)
19093 "Toggle the display of inline images.
19094 INCLUDE-LINKED is passed to `org-display-inline-images'."
19095 (interactive "P")
19096 (if org-inline-image-overlays
19097 (progn
19098 (org-remove-inline-images)
19099 (message "Inline image display turned off"))
19100 (org-display-inline-images include-linked)
19101 (if (and (org-called-interactively-p)
19102 org-inline-image-overlays)
19103 (message "%d images displayed inline"
19104 (length org-inline-image-overlays))
19105 (message "No images to display inline"))))
19107 (defun org-redisplay-inline-images ()
19108 "Refresh the display of inline images."
19109 (interactive)
19110 (if (not org-inline-image-overlays)
19111 (org-toggle-inline-images)
19112 (org-toggle-inline-images)
19113 (org-toggle-inline-images)))
19115 (defun org-display-inline-images (&optional include-linked refresh beg end)
19116 "Display inline images.
19118 An inline image is a link which follows either of these
19119 conventions:
19121 1. Its path is a file with an extension matching return value
19122 from `image-file-name-regexp' and it has no contents.
19124 2. Its description consists in a single link of the previous
19125 type.
19127 When optional argument INCLUDE-LINKED is non-nil, also links with
19128 a text description part will be inlined. This can be nice for
19129 a quick look at those images, but it does not reflect what
19130 exported files will look like.
19132 When optional argument REFRESH is non-nil, refresh existing
19133 images between BEG and END. This will create new image displays
19134 only if necessary. BEG and END default to the buffer
19135 boundaries."
19136 (interactive "P")
19137 (when (display-graphic-p)
19138 (unless refresh
19139 (org-remove-inline-images)
19140 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19141 (org-with-wide-buffer
19142 (goto-char (or beg (point-min)))
19143 (let ((case-fold-search t)
19144 (file-extension-re (org-image-file-name-regexp)))
19145 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19146 (let ((link (save-match-data (org-element-context))))
19147 ;; Check if we're at an inline image.
19148 (when (and (equal (org-element-property :type link) "file")
19149 (or include-linked
19150 (not (org-element-property :contents-begin link)))
19151 (let ((parent (org-element-property :parent link)))
19152 (or (not (eq (org-element-type parent) 'link))
19153 (not (cdr (org-element-contents parent)))))
19154 (org-string-match-p file-extension-re
19155 (org-element-property :path link)))
19156 (let ((file (expand-file-name (org-element-property :path link))))
19157 (when (file-exists-p file)
19158 (let ((width
19159 ;; Apply `org-image-actual-width' specifications.
19160 (cond
19161 ((not (image-type-available-p 'imagemagick)) nil)
19162 ((eq org-image-actual-width t) nil)
19163 ((listp org-image-actual-width)
19165 ;; First try to find a width among
19166 ;; attributes associated to the paragraph
19167 ;; containing link.
19168 (let ((paragraph
19169 (let ((e link))
19170 (while (and (setq e (org-element-property
19171 :parent e))
19172 (not (eq (org-element-type e)
19173 'paragraph))))
19174 e)))
19175 (when paragraph
19176 (save-excursion
19177 (goto-char (org-element-property :begin paragraph))
19178 (when (save-match-data
19179 (re-search-forward
19180 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19181 (org-element-property
19182 :post-affiliated paragraph)
19184 (string-to-number (match-string 1))))))
19185 ;; Otherwise, fall-back to provided number.
19186 (car org-image-actual-width)))
19187 ((numberp org-image-actual-width)
19188 org-image-actual-width)))
19189 (old (get-char-property-and-overlay
19190 (org-element-property :begin link)
19191 'org-image-overlay)))
19192 (if (and (car-safe old) refresh)
19193 (image-refresh (overlay-get (cdr old) 'display))
19194 (let ((image (save-match-data
19195 (create-image file
19196 (and width 'imagemagick)
19198 :width width))))
19199 (when image
19200 (let* ((link
19201 ;; If inline image is the description
19202 ;; of another link, be sure to
19203 ;; consider the latter as the one to
19204 ;; apply the overlay on.
19205 (let ((parent
19206 (org-element-property :parent link)))
19207 (if (eq (org-element-type parent) 'link)
19208 parent
19209 link)))
19210 (ov (make-overlay
19211 (org-element-property :begin link)
19212 (progn
19213 (goto-char
19214 (org-element-property :end link))
19215 (skip-chars-backward " \t")
19216 (point)))))
19217 (overlay-put ov 'display image)
19218 (overlay-put ov 'face 'default)
19219 (overlay-put ov 'org-image-overlay t)
19220 (overlay-put
19221 ov 'modification-hooks
19222 (list 'org-display-inline-remove-overlay))
19223 (push ov org-inline-image-overlays)))))))))))))))
19225 (define-obsolete-function-alias
19226 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19228 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19229 "Remove inline-display overlay if a corresponding region is modified."
19230 (let ((inhibit-modification-hooks t))
19231 (when (and ov after)
19232 (delete ov org-inline-image-overlays)
19233 (delete-overlay ov))))
19235 (defun org-remove-inline-images ()
19236 "Remove inline display of images."
19237 (interactive)
19238 (mapc 'delete-overlay org-inline-image-overlays)
19239 (setq org-inline-image-overlays nil))
19241 ;;;; Key bindings
19243 ;; Outline functions from `outline-mode-prefix-map'
19244 ;; that can be remapped in Org:
19245 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19246 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19247 (define-key org-mode-map [remap outline-forward-same-level]
19248 'org-forward-heading-same-level)
19249 (define-key org-mode-map [remap outline-backward-same-level]
19250 'org-backward-heading-same-level)
19251 (define-key org-mode-map [remap show-branches]
19252 'org-kill-note-or-show-branches)
19253 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19254 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19255 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19257 ;; Outline functions from `outline-mode-prefix-map' that can not
19258 ;; be remapped in Org:
19260 ;; - the column "key binding" shows whether the Outline function is still
19261 ;; available in Org mode on the same key that it has been bound to in
19262 ;; Outline mode:
19263 ;; - "overridden": key used for a different functionality in Org mode
19264 ;; - else: key still bound to the same Outline function in Org mode
19266 ;; | Outline function | key binding | Org replacement |
19267 ;; |------------------------------------+-------------+-----------------------|
19268 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19269 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19270 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19271 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19272 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19273 ;; | `show-entry' | overridden | no replacement |
19274 ;; | `show-children' | `C-c C-i' | visibility cycling |
19275 ;; | `show-branches' | `C-c C-k' | still same function |
19276 ;; | `show-subtree' | overridden | visibility cycling |
19277 ;; | `show-all' | overridden | no replacement |
19278 ;; | `hide-subtree' | overridden | visibility cycling |
19279 ;; | `hide-body' | overridden | no replacement |
19280 ;; | `hide-entry' | overridden | visibility cycling |
19281 ;; | `hide-leaves' | overridden | no replacement |
19282 ;; | `hide-sublevels' | overridden | no replacement |
19283 ;; | `hide-other' | overridden | no replacement |
19285 ;; Make `C-c C-x' a prefix key
19286 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19288 ;; TAB key with modifiers
19289 (org-defkey org-mode-map "\C-i" 'org-cycle)
19290 (org-defkey org-mode-map [(tab)] 'org-cycle)
19291 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19292 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19293 ;; The following line is necessary under Suse GNU/Linux
19294 (unless (featurep 'xemacs)
19295 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19296 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19297 (define-key org-mode-map [backtab] 'org-shifttab)
19299 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19300 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19301 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19303 ;; Cursor keys with modifiers
19304 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19305 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19306 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19307 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19309 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19310 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19311 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19312 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19313 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19314 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19316 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19317 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19318 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19319 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19321 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19322 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19323 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19324 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19326 ;; Babel keys
19327 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19328 (mapc (lambda (pair)
19329 (define-key org-babel-map (car pair) (cdr pair)))
19330 org-babel-key-bindings)
19332 ;;; Extra keys for tty access.
19333 ;; We only set them when really needed because otherwise the
19334 ;; menus don't show the simple keys
19336 (when (or org-use-extra-keys
19337 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19338 (not window-system))
19339 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19340 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19341 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19342 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19343 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19344 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19345 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19346 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19347 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19348 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19349 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19350 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19351 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19352 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19353 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19354 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19355 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19356 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19357 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19358 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19359 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19360 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19361 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19362 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19363 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19364 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19365 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19366 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19368 ;; All the other keys
19370 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19371 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19372 (if (boundp 'narrow-map)
19373 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19374 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19375 (if (boundp 'narrow-map)
19376 (org-defkey narrow-map "b" 'org-narrow-to-block)
19377 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19378 (if (boundp 'narrow-map)
19379 (org-defkey narrow-map "e" 'org-narrow-to-element)
19380 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19381 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19382 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19383 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19384 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19385 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19386 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19387 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19388 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19389 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19390 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19391 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19392 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19393 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19394 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19395 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19396 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19397 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19398 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19399 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19400 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19401 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19402 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19403 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19404 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19405 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19406 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19407 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19408 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19409 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19410 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19411 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19412 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19413 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19414 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19415 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19416 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19417 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19418 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19419 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19420 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19421 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19422 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19423 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19424 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19425 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19426 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19427 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19428 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19429 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19430 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19431 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19432 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19433 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19434 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19435 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19436 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19437 (org-defkey org-mode-map "\C-c^" 'org-sort)
19438 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19439 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19440 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19441 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19442 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19443 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19444 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19445 (org-defkey org-mode-map "\C-m" 'org-return)
19446 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19447 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19448 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19449 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19450 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19451 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19452 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19453 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19454 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19455 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19456 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19457 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19458 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19459 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19460 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19461 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19462 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19463 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19464 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19465 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19466 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19467 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19468 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19470 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19471 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19472 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19474 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19475 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19476 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19477 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19478 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19479 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19480 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19481 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19482 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19483 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19484 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19485 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19486 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19487 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19488 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19489 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19490 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19491 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19492 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19493 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19494 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19495 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19496 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19498 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19499 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19500 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19501 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19502 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19504 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19506 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19508 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19509 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19511 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19514 (when (featurep 'xemacs)
19515 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19518 (defconst org-speed-commands-default
19520 ("Outline Navigation")
19521 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19522 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19523 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19524 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19525 ("F" . org-next-block)
19526 ("B" . org-previous-block)
19527 ("u" . (org-speed-move-safe 'outline-up-heading))
19528 ("j" . org-goto)
19529 ("g" . (org-refile t))
19530 ("Outline Visibility")
19531 ("c" . org-cycle)
19532 ("C" . org-shifttab)
19533 (" " . org-display-outline-path)
19534 ("s" . org-narrow-to-subtree)
19535 ("=" . org-columns)
19536 ("Outline Structure Editing")
19537 ("U" . org-shiftmetaup)
19538 ("D" . org-shiftmetadown)
19539 ("r" . org-metaright)
19540 ("l" . org-metaleft)
19541 ("R" . org-shiftmetaright)
19542 ("L" . org-shiftmetaleft)
19543 ("i" . (progn (forward-char 1) (call-interactively
19544 'org-insert-heading-respect-content)))
19545 ("^" . org-sort)
19546 ("w" . org-refile)
19547 ("a" . org-archive-subtree-default-with-confirmation)
19548 ("@" . org-mark-subtree)
19549 ("#" . org-toggle-comment)
19550 ("Clock Commands")
19551 ("I" . org-clock-in)
19552 ("O" . org-clock-out)
19553 ("Meta Data Editing")
19554 ("t" . org-todo)
19555 ("," . (org-priority))
19556 ("0" . (org-priority ?\ ))
19557 ("1" . (org-priority ?A))
19558 ("2" . (org-priority ?B))
19559 ("3" . (org-priority ?C))
19560 (":" . org-set-tags-command)
19561 ("e" . org-set-effort)
19562 ("E" . org-inc-effort)
19563 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19564 (org-entry-put (point) "APPT_WARNTIME" m)))
19565 ("Agenda Views etc")
19566 ("v" . org-agenda)
19567 ("/" . org-sparse-tree)
19568 ("Misc")
19569 ("o" . org-open-at-point)
19570 ("?" . org-speed-command-help)
19571 ("<" . (org-agenda-set-restriction-lock 'subtree))
19572 (">" . (org-agenda-remove-restriction-lock))
19574 "The default speed commands.")
19576 (defun org-print-speed-command (e)
19577 (if (> (length (car e)) 1)
19578 (progn
19579 (princ "\n")
19580 (princ (car e))
19581 (princ "\n")
19582 (princ (make-string (length (car e)) ?-))
19583 (princ "\n"))
19584 (princ (car e))
19585 (princ " ")
19586 (if (symbolp (cdr e))
19587 (princ (symbol-name (cdr e)))
19588 (prin1 (cdr e)))
19589 (princ "\n")))
19591 (defun org-speed-command-help ()
19592 "Show the available speed commands."
19593 (interactive)
19594 (if (not org-use-speed-commands)
19595 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19596 (with-output-to-temp-buffer "*Help*"
19597 (princ "User-defined Speed commands\n===========================\n")
19598 (mapc 'org-print-speed-command org-speed-commands-user)
19599 (princ "\n")
19600 (princ "Built-in Speed commands\n=======================\n")
19601 (mapc 'org-print-speed-command org-speed-commands-default))
19602 (with-current-buffer "*Help*"
19603 (setq truncate-lines t))))
19605 (defun org-speed-move-safe (cmd)
19606 "Execute CMD, but make sure that the cursor always ends up in a headline.
19607 If not, return to the original position and throw an error."
19608 (interactive)
19609 (let ((pos (point)))
19610 (call-interactively cmd)
19611 (unless (and (bolp) (org-at-heading-p))
19612 (goto-char pos)
19613 (error "Boundary reached while executing %s" cmd))))
19615 (defvar org-self-insert-command-undo-counter 0)
19617 (defvar org-table-auto-blank-field) ; defined in org-table.el
19618 (defvar org-speed-command nil)
19620 (define-obsolete-function-alias
19621 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19623 (defun org-speed-command-activate (keys)
19624 "Hook for activating single-letter speed commands.
19625 `org-speed-commands-default' specifies a minimal command set.
19626 Use `org-speed-commands-user' for further customization."
19627 (when (or (and (bolp) (looking-at org-outline-regexp))
19628 (and (functionp org-use-speed-commands)
19629 (funcall org-use-speed-commands)))
19630 (cdr (assoc keys (append org-speed-commands-user
19631 org-speed-commands-default)))))
19633 (define-obsolete-function-alias
19634 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19636 (defun org-babel-speed-command-activate (keys)
19637 "Hook for activating single-letter code block commands."
19638 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19639 (cdr (assoc keys org-babel-key-bindings))))
19641 (defcustom org-speed-command-hook
19642 '(org-speed-command-default-hook org-babel-speed-command-hook)
19643 "Hook for activating speed commands at strategic locations.
19644 Hook functions are called in sequence until a valid handler is
19645 found.
19647 Each hook takes a single argument, a user-pressed command key
19648 which is also a `self-insert-command' from the global map.
19650 Within the hook, examine the cursor position and the command key
19651 and return nil or a valid handler as appropriate. Handler could
19652 be one of an interactive command, a function, or a form.
19654 Set `org-use-speed-commands' to non-nil value to enable this
19655 hook. The default setting is `org-speed-command-activate'."
19656 :group 'org-structure
19657 :version "24.1"
19658 :type 'hook)
19660 (defun org-self-insert-command (N)
19661 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19662 If the cursor is in a table looking at whitespace, the whitespace is
19663 overwritten, and the table is not marked as requiring realignment."
19664 (interactive "p")
19665 (org-check-before-invisible-edit 'insert)
19666 (cond
19667 ((and org-use-speed-commands
19668 (setq org-speed-command
19669 (run-hook-with-args-until-success
19670 'org-speed-command-hook (this-command-keys))))
19671 (cond
19672 ((commandp org-speed-command)
19673 (setq this-command org-speed-command)
19674 (call-interactively org-speed-command))
19675 ((functionp org-speed-command)
19676 (funcall org-speed-command))
19677 ((and org-speed-command (listp org-speed-command))
19678 (eval org-speed-command))
19679 (t (let (org-use-speed-commands)
19680 (call-interactively 'org-self-insert-command)))))
19681 ((and
19682 (org-table-p)
19683 (progn
19684 ;; check if we blank the field, and if that triggers align
19685 (and (featurep 'org-table) org-table-auto-blank-field
19686 (member last-command
19687 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19688 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19689 ;; got extra space, this field does not determine column width
19690 (let (org-table-may-need-update) (org-table-blank-field))
19691 ;; no extra space, this field may determine column width
19692 (org-table-blank-field)))
19694 (eq N 1)
19695 (looking-at "[^|\n]* |"))
19696 (let (org-table-may-need-update)
19697 (goto-char (1- (match-end 0)))
19698 (backward-delete-char 1)
19699 (goto-char (match-beginning 0))
19700 (self-insert-command N)))
19702 (setq org-table-may-need-update t)
19703 (self-insert-command N)
19704 (org-fix-tags-on-the-fly)
19705 (if org-self-insert-cluster-for-undo
19706 (if (not (eq last-command 'org-self-insert-command))
19707 (setq org-self-insert-command-undo-counter 1)
19708 (if (>= org-self-insert-command-undo-counter 20)
19709 (setq org-self-insert-command-undo-counter 1)
19710 (and (> org-self-insert-command-undo-counter 0)
19711 buffer-undo-list (listp buffer-undo-list)
19712 (not (cadr buffer-undo-list)) ; remove nil entry
19713 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19714 (setq org-self-insert-command-undo-counter
19715 (1+ org-self-insert-command-undo-counter))))))))
19717 (defun org-check-before-invisible-edit (kind)
19718 "Check is editing if kind KIND would be dangerous with invisible text around.
19719 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19720 ;; First, try to get out of here as quickly as possible, to reduce overhead
19721 (if (and org-catch-invisible-edits
19722 (or (not (boundp 'visible-mode)) (not visible-mode))
19723 (or (get-char-property (point) 'invisible)
19724 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19725 ;; OK, we need to take a closer look
19726 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19727 (invisible-before-point (if (bobp) nil (get-char-property
19728 (1- (point)) 'invisible)))
19729 (border-and-ok-direction
19731 ;; Check if we are acting predictably before invisible text
19732 (and invisible-at-point (not invisible-before-point)
19733 (memq kind '(insert delete-backward)))
19734 ;; Check if we are acting predictably after invisible text
19735 ;; This works not well, and I have turned it off. It seems
19736 ;; better to always show and stop after invisible text.
19737 ;; (and (not invisible-at-point) invisible-before-point
19738 ;; (memq kind '(insert delete)))
19740 (when (or (memq invisible-at-point '(outline org-hide-block t))
19741 (memq invisible-before-point '(outline org-hide-block t)))
19742 (if (eq org-catch-invisible-edits 'error)
19743 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19744 (if (and org-custom-properties-overlays
19745 (y-or-n-p "Display invisible properties in this buffer? "))
19746 (org-toggle-custom-properties-visibility)
19747 ;; Make the area visible
19748 (save-excursion
19749 (if invisible-before-point
19750 (goto-char (previous-single-char-property-change
19751 (point) 'invisible)))
19752 (show-subtree))
19753 (cond
19754 ((eq org-catch-invisible-edits 'show)
19755 ;; That's it, we do the edit after showing
19756 (message
19757 "Unfolding invisible region around point before editing")
19758 (sit-for 1))
19759 ((and (eq org-catch-invisible-edits 'smart)
19760 border-and-ok-direction)
19761 (message "Unfolding invisible region around point before editing"))
19763 ;; Don't do the edit, make the user repeat it in full visibility
19764 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19766 (defun org-fix-tags-on-the-fly ()
19767 (when (and (equal (char-after (point-at-bol)) ?*)
19768 (org-at-heading-p))
19769 (org-align-tags-here org-tags-column)))
19771 (defun org-delete-backward-char (N)
19772 "Like `delete-backward-char', insert whitespace at field end in tables.
19773 When deleting backwards, in tables this function will insert whitespace in
19774 front of the next \"|\" separator, to keep the table aligned. The table will
19775 still be marked for re-alignment if the field did fill the entire column,
19776 because, in this case the deletion might narrow the column."
19777 (interactive "p")
19778 (save-match-data
19779 (org-check-before-invisible-edit 'delete-backward)
19780 (if (and (org-table-p)
19781 (eq N 1)
19782 (string-match "|" (buffer-substring (point-at-bol) (point)))
19783 (looking-at ".*?|"))
19784 (let ((pos (point))
19785 (noalign (looking-at "[^|\n\r]* |"))
19786 (c org-table-may-need-update))
19787 (backward-delete-char N)
19788 (if (not overwrite-mode)
19789 (progn
19790 (skip-chars-forward "^|")
19791 (insert " ")
19792 (goto-char (1- pos))))
19793 ;; noalign: if there were two spaces at the end, this field
19794 ;; does not determine the width of the column.
19795 (if noalign (setq org-table-may-need-update c)))
19796 (backward-delete-char N)
19797 (org-fix-tags-on-the-fly))))
19799 (defun org-delete-char (N)
19800 "Like `delete-char', but insert whitespace at field end in tables.
19801 When deleting characters, in tables this function will insert whitespace in
19802 front of the next \"|\" separator, to keep the table aligned. The table will
19803 still be marked for re-alignment if the field did fill the entire column,
19804 because, in this case the deletion might narrow the column."
19805 (interactive "p")
19806 (save-match-data
19807 (org-check-before-invisible-edit 'delete)
19808 (if (and (org-table-p)
19809 (not (bolp))
19810 (not (= (char-after) ?|))
19811 (eq N 1))
19812 (if (looking-at ".*?|")
19813 (let ((pos (point))
19814 (noalign (looking-at "[^|\n\r]* |"))
19815 (c org-table-may-need-update))
19816 (replace-match
19817 (concat (substring (match-string 0) 1 -1) " |") nil t)
19818 (goto-char pos)
19819 ;; noalign: if there were two spaces at the end, this field
19820 ;; does not determine the width of the column.
19821 (if noalign (setq org-table-may-need-update c)))
19822 (delete-char N))
19823 (delete-char N)
19824 (org-fix-tags-on-the-fly))))
19826 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19827 (put 'org-self-insert-command 'delete-selection
19828 (lambda ()
19829 (not (run-hook-with-args-until-success
19830 'self-insert-uses-region-functions))))
19831 (put 'orgtbl-self-insert-command 'delete-selection
19832 (lambda ()
19833 (not (run-hook-with-args-until-success
19834 'self-insert-uses-region-functions))))
19835 (put 'org-delete-char 'delete-selection 'supersede)
19836 (put 'org-delete-backward-char 'delete-selection 'supersede)
19837 (put 'org-yank 'delete-selection 'yank)
19839 ;; Make `flyspell-mode' delay after some commands
19840 (put 'org-self-insert-command 'flyspell-delayed t)
19841 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19842 (put 'org-delete-char 'flyspell-delayed t)
19843 (put 'org-delete-backward-char 'flyspell-delayed t)
19845 ;; Make pabbrev-mode expand after org-mode commands
19846 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19847 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19849 (defun org-remap (map &rest commands)
19850 "In MAP, remap the functions given in COMMANDS.
19851 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19852 (let (new old)
19853 (while commands
19854 (setq old (pop commands) new (pop commands))
19855 (if (fboundp 'command-remapping)
19856 (org-defkey map (vector 'remap old) new)
19857 (substitute-key-definition old new map global-map)))))
19859 (defun org-transpose-words ()
19860 "Transpose words for Org.
19861 This uses the `org-mode-transpose-word-syntax-table' syntax
19862 table, which interprets characters in `org-emphasis-alist' as
19863 word constituents."
19864 (interactive)
19865 (with-syntax-table org-mode-transpose-word-syntax-table
19866 (call-interactively 'transpose-words)))
19867 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19869 (when (eq org-enable-table-editor 'optimized)
19870 ;; If the user wants maximum table support, we need to hijack
19871 ;; some standard editing functions
19872 (org-remap org-mode-map
19873 'self-insert-command 'org-self-insert-command
19874 'delete-char 'org-delete-char
19875 'delete-backward-char 'org-delete-backward-char)
19876 (org-defkey org-mode-map "|" 'org-force-self-insert))
19878 (defvar org-ctrl-c-ctrl-c-hook nil
19879 "Hook for functions attaching themselves to `C-c C-c'.
19881 This can be used to add additional functionality to the C-c C-c
19882 key which executes context-dependent commands. This hook is run
19883 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19884 run after the last test.
19886 Each function will be called with no arguments. The function
19887 must check if the context is appropriate for it to act. If yes,
19888 it should do its thing and then return a non-nil value. If the
19889 context is wrong, just do nothing and return nil.")
19891 (defvar org-ctrl-c-ctrl-c-final-hook nil
19892 "Hook for functions attaching themselves to `C-c C-c'.
19894 This can be used to add additional functionality to the C-c C-c
19895 key which executes context-dependent commands. This hook is run
19896 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19897 before the first test.
19899 Each function will be called with no arguments. The function
19900 must check if the context is appropriate for it to act. If yes,
19901 it should do its thing and then return a non-nil value. If the
19902 context is wrong, just do nothing and return nil.")
19904 (defvar org-tab-first-hook nil
19905 "Hook for functions to attach themselves to TAB.
19906 See `org-ctrl-c-ctrl-c-hook' for more information.
19907 This hook runs as the first action when TAB is pressed, even before
19908 `org-cycle' messes around with the `outline-regexp' to cater for
19909 inline tasks and plain list item folding.
19910 If any function in this hook returns t, any other actions that
19911 would have been caused by TAB (such as table field motion or visibility
19912 cycling) will not occur.")
19914 (defvar org-tab-after-check-for-table-hook nil
19915 "Hook for functions to attach themselves to TAB.
19916 See `org-ctrl-c-ctrl-c-hook' for more information.
19917 This hook runs after it has been established that the cursor is not in a
19918 table, but before checking if the cursor is in a headline or if global cycling
19919 should be done.
19920 If any function in this hook returns t, not other actions like visibility
19921 cycling will be done.")
19923 (defvar org-tab-after-check-for-cycling-hook nil
19924 "Hook for functions to attach themselves to TAB.
19925 See `org-ctrl-c-ctrl-c-hook' for more information.
19926 This hook runs after it has been established that not table field motion and
19927 not visibility should be done because of current context. This is probably
19928 the place where a package like yasnippets can hook in.")
19930 (defvar org-tab-before-tab-emulation-hook nil
19931 "Hook for functions to attach themselves to TAB.
19932 See `org-ctrl-c-ctrl-c-hook' for more information.
19933 This hook runs after every other options for TAB have been exhausted, but
19934 before indentation and \t insertion takes place.")
19936 (defvar org-metaleft-hook nil
19937 "Hook for functions attaching themselves to `M-left'.
19938 See `org-ctrl-c-ctrl-c-hook' for more information.")
19939 (defvar org-metaright-hook nil
19940 "Hook for functions attaching themselves to `M-right'.
19941 See `org-ctrl-c-ctrl-c-hook' for more information.")
19942 (defvar org-metaup-hook nil
19943 "Hook for functions attaching themselves to `M-up'.
19944 See `org-ctrl-c-ctrl-c-hook' for more information.")
19945 (defvar org-metadown-hook nil
19946 "Hook for functions attaching themselves to `M-down'.
19947 See `org-ctrl-c-ctrl-c-hook' for more information.")
19948 (defvar org-shiftmetaleft-hook nil
19949 "Hook for functions attaching themselves to `M-S-left'.
19950 See `org-ctrl-c-ctrl-c-hook' for more information.")
19951 (defvar org-shiftmetaright-hook nil
19952 "Hook for functions attaching themselves to `M-S-right'.
19953 See `org-ctrl-c-ctrl-c-hook' for more information.")
19954 (defvar org-shiftmetaup-hook nil
19955 "Hook for functions attaching themselves to `M-S-up'.
19956 See `org-ctrl-c-ctrl-c-hook' for more information.")
19957 (defvar org-shiftmetadown-hook nil
19958 "Hook for functions attaching themselves to `M-S-down'.
19959 See `org-ctrl-c-ctrl-c-hook' for more information.")
19960 (defvar org-metareturn-hook nil
19961 "Hook for functions attaching themselves to `M-RET'.
19962 See `org-ctrl-c-ctrl-c-hook' for more information.")
19963 (defvar org-shiftup-hook nil
19964 "Hook for functions attaching themselves to `S-up'.
19965 See `org-ctrl-c-ctrl-c-hook' for more information.")
19966 (defvar org-shiftup-final-hook nil
19967 "Hook for functions attaching themselves to `S-up'.
19968 This one runs after all other options except shift-select have been excluded.
19969 See `org-ctrl-c-ctrl-c-hook' for more information.")
19970 (defvar org-shiftdown-hook nil
19971 "Hook for functions attaching themselves to `S-down'.
19972 See `org-ctrl-c-ctrl-c-hook' for more information.")
19973 (defvar org-shiftdown-final-hook nil
19974 "Hook for functions attaching themselves to `S-down'.
19975 This one runs after all other options except shift-select have been excluded.
19976 See `org-ctrl-c-ctrl-c-hook' for more information.")
19977 (defvar org-shiftleft-hook nil
19978 "Hook for functions attaching themselves to `S-left'.
19979 See `org-ctrl-c-ctrl-c-hook' for more information.")
19980 (defvar org-shiftleft-final-hook nil
19981 "Hook for functions attaching themselves to `S-left'.
19982 This one runs after all other options except shift-select have been excluded.
19983 See `org-ctrl-c-ctrl-c-hook' for more information.")
19984 (defvar org-shiftright-hook nil
19985 "Hook for functions attaching themselves to `S-right'.
19986 See `org-ctrl-c-ctrl-c-hook' for more information.")
19987 (defvar org-shiftright-final-hook nil
19988 "Hook for functions attaching themselves to `S-right'.
19989 This one runs after all other options except shift-select have been excluded.
19990 See `org-ctrl-c-ctrl-c-hook' for more information.")
19992 (defun org-modifier-cursor-error ()
19993 "Throw an error, a modified cursor command was applied in wrong context."
19994 (user-error "This command is active in special context like tables, headlines or items"))
19996 (defun org-shiftselect-error ()
19997 "Throw an error because Shift-Cursor command was applied in wrong context."
19998 (if (and (boundp 'shift-select-mode) shift-select-mode)
19999 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20000 (user-error "This command works only in special context like headlines or timestamps")))
20002 (defun org-call-for-shift-select (cmd)
20003 (let ((this-command-keys-shift-translated t))
20004 (call-interactively cmd)))
20006 (defun org-shifttab (&optional arg)
20007 "Global visibility cycling or move to previous table field.
20008 Call `org-table-previous-field' within a table.
20009 When ARG is nil, cycle globally through visibility states.
20010 When ARG is a numeric prefix, show contents of this level."
20011 (interactive "P")
20012 (cond
20013 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20014 ((integerp arg)
20015 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20016 (message "Content view to level: %d" arg)
20017 (org-content (prefix-numeric-value arg2))
20018 (org-cycle-show-empty-lines t)
20019 (setq org-cycle-global-status 'overview)))
20020 (t (call-interactively 'org-global-cycle))))
20022 (defun org-shiftmetaleft ()
20023 "Promote subtree or delete table column.
20024 Calls `org-promote-subtree', `org-outdent-item-tree', or
20025 `org-table-delete-column', depending on context. See the
20026 individual commands for more information."
20027 (interactive)
20028 (cond
20029 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20030 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20031 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20032 ((if (not (org-region-active-p)) (org-at-item-p)
20033 (save-excursion (goto-char (region-beginning))
20034 (org-at-item-p)))
20035 (call-interactively 'org-outdent-item-tree))
20036 (t (org-modifier-cursor-error))))
20038 (defun org-shiftmetaright ()
20039 "Demote subtree or insert table column.
20040 Calls `org-demote-subtree', `org-indent-item-tree', or
20041 `org-table-insert-column', depending on context. See the
20042 individual commands for more information."
20043 (interactive)
20044 (cond
20045 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20046 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20047 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20048 ((if (not (org-region-active-p)) (org-at-item-p)
20049 (save-excursion (goto-char (region-beginning))
20050 (org-at-item-p)))
20051 (call-interactively 'org-indent-item-tree))
20052 (t (org-modifier-cursor-error))))
20054 (defun org-shiftmetaup (&optional arg)
20055 "Drag the line at point up.
20056 In a table, kill the current row.
20057 On a clock timestamp, update the value of the timestamp like `S-<up>'
20058 but also adjust the previous clocked item in the clock history.
20059 Everywhere else, drag the line at point up."
20060 (interactive "P")
20061 (cond
20062 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20063 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20064 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20065 (call-interactively 'org-timestamp-up)))
20066 (t (call-interactively 'org-drag-line-backward))))
20068 (defun org-shiftmetadown (&optional arg)
20069 "Drag the line at point down.
20070 In a table, insert an empty row at the current line.
20071 On a clock timestamp, update the value of the timestamp like `S-<down>'
20072 but also adjust the previous clocked item in the clock history.
20073 Everywhere else, drag the line at point down."
20074 (interactive "P")
20075 (cond
20076 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20077 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20078 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20079 (call-interactively 'org-timestamp-down)))
20080 (t (call-interactively 'org-drag-line-forward))))
20082 (defsubst org-hidden-tree-error ()
20083 (user-error
20084 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20086 (defun org-metaleft (&optional arg)
20087 "Promote heading or move table column to left.
20088 Calls `org-do-promote' or `org-table-move-column', depending on context.
20089 With no specific context, calls the Emacs default `backward-word'.
20090 See the individual commands for more information."
20091 (interactive "P")
20092 (cond
20093 ((run-hook-with-args-until-success 'org-metaleft-hook))
20094 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20095 ((org-with-limited-levels
20096 (or (org-at-heading-p)
20097 (and (org-region-active-p)
20098 (save-excursion
20099 (goto-char (region-beginning))
20100 (org-at-heading-p)))))
20101 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20102 (call-interactively 'org-do-promote))
20103 ;; At an inline task.
20104 ((org-at-heading-p)
20105 (call-interactively 'org-inlinetask-promote))
20106 ((or (org-at-item-p)
20107 (and (org-region-active-p)
20108 (save-excursion
20109 (goto-char (region-beginning))
20110 (org-at-item-p))))
20111 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20112 (call-interactively 'org-outdent-item))
20113 (t (call-interactively 'backward-word))))
20115 (defun org-metaright (&optional arg)
20116 "Demote a subtree, a list item or move table column to right.
20117 In front of a drawer or a block keyword, indent it correctly.
20118 With no specific context, calls the Emacs default `forward-word'.
20119 See the individual commands for more information."
20120 (interactive "P")
20121 (cond
20122 ((run-hook-with-args-until-success 'org-metaright-hook))
20123 ((org-at-table-p) (call-interactively 'org-table-move-column))
20124 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20125 ((org-at-block-p) (call-interactively 'org-indent-block))
20126 ((org-with-limited-levels
20127 (or (org-at-heading-p)
20128 (and (org-region-active-p)
20129 (save-excursion
20130 (goto-char (region-beginning))
20131 (org-at-heading-p)))))
20132 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20133 (call-interactively 'org-do-demote))
20134 ;; At an inline task.
20135 ((org-at-heading-p)
20136 (call-interactively 'org-inlinetask-demote))
20137 ((or (org-at-item-p)
20138 (and (org-region-active-p)
20139 (save-excursion
20140 (goto-char (region-beginning))
20141 (org-at-item-p))))
20142 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20143 (call-interactively 'org-indent-item))
20144 (t (call-interactively 'forward-word))))
20146 (defun org-check-for-hidden (what)
20147 "Check if there are hidden headlines/items in the current visual line.
20148 WHAT can be either `headlines' or `items'. If the current line is
20149 an outline or item heading and it has a folded subtree below it,
20150 this function returns t, nil otherwise."
20151 (let ((re (cond
20152 ((eq what 'headlines) org-outline-regexp-bol)
20153 ((eq what 'items) (org-item-beginning-re))
20154 (t (error "This should not happen"))))
20155 beg end)
20156 (save-excursion
20157 (catch 'exit
20158 (unless (org-region-active-p)
20159 (setq beg (point-at-bol))
20160 (beginning-of-line 2)
20161 (while (and (not (eobp)) ;; this is like `next-line'
20162 (get-char-property (1- (point)) 'invisible))
20163 (beginning-of-line 2))
20164 (setq end (point))
20165 (goto-char beg)
20166 (goto-char (point-at-eol))
20167 (setq end (max end (point)))
20168 (while (re-search-forward re end t)
20169 (if (get-char-property (match-beginning 0) 'invisible)
20170 (throw 'exit t))))
20171 nil))))
20173 (defun org-metaup (&optional arg)
20174 "Move subtree up or move table row up.
20175 Calls `org-move-subtree-up' or `org-table-move-row' or
20176 `org-move-item-up', depending on context. See the individual commands
20177 for more information."
20178 (interactive "P")
20179 (cond
20180 ((run-hook-with-args-until-success 'org-metaup-hook))
20181 ((org-region-active-p)
20182 (let* ((a (min (region-beginning) (region-end)))
20183 (b (1- (max (region-beginning) (region-end))))
20184 (c (save-excursion (goto-char a)
20185 (move-beginning-of-line 0)))
20186 (d (save-excursion (goto-char a)
20187 (move-end-of-line 0) (point))))
20188 (transpose-regions a b c d)
20189 (goto-char c)))
20190 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20191 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20192 ((org-at-item-p) (call-interactively 'org-move-item-up))
20193 (t (org-drag-element-backward))))
20195 (defun org-metadown (&optional arg)
20196 "Move subtree down or move table row down.
20197 Calls `org-move-subtree-down' or `org-table-move-row' or
20198 `org-move-item-down', depending on context. See the individual
20199 commands for more information."
20200 (interactive "P")
20201 (cond
20202 ((run-hook-with-args-until-success 'org-metadown-hook))
20203 ((org-region-active-p)
20204 (let* ((a (min (region-beginning) (region-end)))
20205 (b (max (region-beginning) (region-end)))
20206 (c (save-excursion (goto-char b)
20207 (move-beginning-of-line 1)))
20208 (d (save-excursion (goto-char b)
20209 (move-end-of-line 1) (1+ (point)))))
20210 (transpose-regions a b c d)
20211 (goto-char d)))
20212 ((org-at-table-p) (call-interactively 'org-table-move-row))
20213 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20214 ((org-at-item-p) (call-interactively 'org-move-item-down))
20215 (t (org-drag-element-forward))))
20217 (defun org-shiftup (&optional arg)
20218 "Increase item in timestamp or increase priority of current headline.
20219 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20220 depending on context. See the individual commands for more information."
20221 (interactive "P")
20222 (cond
20223 ((run-hook-with-args-until-success 'org-shiftup-hook))
20224 ((and org-support-shift-select (org-region-active-p))
20225 (org-call-for-shift-select 'previous-line))
20226 ((org-at-timestamp-p t)
20227 (call-interactively (if org-edit-timestamp-down-means-later
20228 'org-timestamp-down 'org-timestamp-up)))
20229 ((and (not (eq org-support-shift-select 'always))
20230 org-enable-priority-commands
20231 (org-at-heading-p))
20232 (call-interactively 'org-priority-up))
20233 ((and (not org-support-shift-select) (org-at-item-p))
20234 (call-interactively 'org-previous-item))
20235 ((org-clocktable-try-shift 'up arg))
20236 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20237 (org-support-shift-select
20238 (org-call-for-shift-select 'previous-line))
20239 (t (org-shiftselect-error))))
20241 (defun org-shiftdown (&optional arg)
20242 "Decrease item in timestamp or decrease priority of current headline.
20243 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20244 depending on context. See the individual commands for more information."
20245 (interactive "P")
20246 (cond
20247 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20248 ((and org-support-shift-select (org-region-active-p))
20249 (org-call-for-shift-select 'next-line))
20250 ((org-at-timestamp-p t)
20251 (call-interactively (if org-edit-timestamp-down-means-later
20252 'org-timestamp-up 'org-timestamp-down)))
20253 ((and (not (eq org-support-shift-select 'always))
20254 org-enable-priority-commands
20255 (org-at-heading-p))
20256 (call-interactively 'org-priority-down))
20257 ((and (not org-support-shift-select) (org-at-item-p))
20258 (call-interactively 'org-next-item))
20259 ((org-clocktable-try-shift 'down arg))
20260 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20261 (org-support-shift-select
20262 (org-call-for-shift-select 'next-line))
20263 (t (org-shiftselect-error))))
20265 (defun org-shiftright (&optional arg)
20266 "Cycle the thing at point or in the current line, depending on context.
20267 Depending on context, this does one of the following:
20269 - switch a timestamp at point one day into the future
20270 - on a headline, switch to the next TODO keyword.
20271 - on an item, switch entire list to the next bullet type
20272 - on a property line, switch to the next allowed value
20273 - on a clocktable definition line, move time block into the future"
20274 (interactive "P")
20275 (cond
20276 ((run-hook-with-args-until-success 'org-shiftright-hook))
20277 ((and org-support-shift-select (org-region-active-p))
20278 (org-call-for-shift-select 'forward-char))
20279 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20280 ((and (not (eq org-support-shift-select 'always))
20281 (org-at-heading-p))
20282 (let ((org-inhibit-logging
20283 (not org-treat-S-cursor-todo-selection-as-state-change))
20284 (org-inhibit-blocking
20285 (not org-treat-S-cursor-todo-selection-as-state-change)))
20286 (org-call-with-arg 'org-todo 'right)))
20287 ((or (and org-support-shift-select
20288 (not (eq org-support-shift-select 'always))
20289 (org-at-item-bullet-p))
20290 (and (not org-support-shift-select) (org-at-item-p)))
20291 (org-call-with-arg 'org-cycle-list-bullet nil))
20292 ((and (not (eq org-support-shift-select 'always))
20293 (org-at-property-p))
20294 (call-interactively 'org-property-next-allowed-value))
20295 ((org-clocktable-try-shift 'right arg))
20296 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20297 (org-support-shift-select
20298 (org-call-for-shift-select 'forward-char))
20299 (t (org-shiftselect-error))))
20301 (defun org-shiftleft (&optional arg)
20302 "Cycle the thing at point or in the current line, depending on context.
20303 Depending on context, this does one of the following:
20305 - switch a timestamp at point one day into the past
20306 - on a headline, switch to the previous TODO keyword.
20307 - on an item, switch entire list to the previous bullet type
20308 - on a property line, switch to the previous allowed value
20309 - on a clocktable definition line, move time block into the past"
20310 (interactive "P")
20311 (cond
20312 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20313 ((and org-support-shift-select (org-region-active-p))
20314 (org-call-for-shift-select 'backward-char))
20315 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20316 ((and (not (eq org-support-shift-select 'always))
20317 (org-at-heading-p))
20318 (let ((org-inhibit-logging
20319 (not org-treat-S-cursor-todo-selection-as-state-change))
20320 (org-inhibit-blocking
20321 (not org-treat-S-cursor-todo-selection-as-state-change)))
20322 (org-call-with-arg 'org-todo 'left)))
20323 ((or (and org-support-shift-select
20324 (not (eq org-support-shift-select 'always))
20325 (org-at-item-bullet-p))
20326 (and (not org-support-shift-select) (org-at-item-p)))
20327 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20328 ((and (not (eq org-support-shift-select 'always))
20329 (org-at-property-p))
20330 (call-interactively 'org-property-previous-allowed-value))
20331 ((org-clocktable-try-shift 'left arg))
20332 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20333 (org-support-shift-select
20334 (org-call-for-shift-select 'backward-char))
20335 (t (org-shiftselect-error))))
20337 (defun org-shiftcontrolright ()
20338 "Switch to next TODO set."
20339 (interactive)
20340 (cond
20341 ((and org-support-shift-select (org-region-active-p))
20342 (org-call-for-shift-select 'forward-word))
20343 ((and (not (eq org-support-shift-select 'always))
20344 (org-at-heading-p))
20345 (org-call-with-arg 'org-todo 'nextset))
20346 (org-support-shift-select
20347 (org-call-for-shift-select 'forward-word))
20348 (t (org-shiftselect-error))))
20350 (defun org-shiftcontrolleft ()
20351 "Switch to previous TODO set."
20352 (interactive)
20353 (cond
20354 ((and org-support-shift-select (org-region-active-p))
20355 (org-call-for-shift-select 'backward-word))
20356 ((and (not (eq org-support-shift-select 'always))
20357 (org-at-heading-p))
20358 (org-call-with-arg 'org-todo 'previousset))
20359 (org-support-shift-select
20360 (org-call-for-shift-select 'backward-word))
20361 (t (org-shiftselect-error))))
20363 (defun org-shiftcontrolup (&optional n)
20364 "Change timestamps synchronously up in CLOCK log lines.
20365 Optional argument N tells to change by that many units."
20366 (interactive "P")
20367 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20368 (let (org-support-shift-select)
20369 (org-clock-timestamps-up n))
20370 (user-error "Not at a clock log")))
20372 (defun org-shiftcontroldown (&optional n)
20373 "Change timestamps synchronously down in CLOCK log lines.
20374 Optional argument N tells to change by that many units."
20375 (interactive "P")
20376 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20377 (let (org-support-shift-select)
20378 (org-clock-timestamps-down n))
20379 (user-error "Not at a clock log")))
20381 (defun org-increase-number-at-point (&optional inc)
20382 "Increment the number at point.
20383 With an optional prefix numeric argument INC, increment using
20384 this numeric value."
20385 (interactive "p")
20386 (if (not (number-at-point))
20387 (user-error "Not on a number")
20388 (unless inc (setq inc 1))
20389 (let ((pos (point))
20390 (beg (skip-chars-backward "-+^/*0-9eE."))
20391 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20392 (setq nap (buffer-substring-no-properties
20393 (+ pos beg) (+ pos beg end)))
20394 (delete-region (+ pos beg) (+ pos beg end))
20395 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20396 (when (org-at-table-p)
20397 (org-table-align)
20398 (org-table-end-of-field 1))))
20400 (defun org-decrease-number-at-point (&optional inc)
20401 "Decrement the number at point.
20402 With an optional prefix numeric argument INC, decrement using
20403 this numeric value."
20404 (interactive "p")
20405 (org-increase-number-at-point (- inc)))
20407 (defun org-ctrl-c-ret ()
20408 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20409 (interactive)
20410 (cond
20411 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20412 (t (call-interactively 'org-insert-heading))))
20414 (defun org-find-visible ()
20415 (let ((s (point)))
20416 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20417 (get-char-property s 'invisible)))
20419 (defun org-find-invisible ()
20420 (let ((s (point)))
20421 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20422 (not (get-char-property s 'invisible))))
20425 (defun org-copy-visible (beg end)
20426 "Copy the visible parts of the region."
20427 (interactive "r")
20428 (let (snippets s)
20429 (save-excursion
20430 (save-restriction
20431 (narrow-to-region beg end)
20432 (setq s (goto-char (point-min)))
20433 (while (not (= (point) (point-max)))
20434 (goto-char (org-find-invisible))
20435 (push (buffer-substring s (point)) snippets)
20436 (setq s (goto-char (org-find-visible))))))
20437 (kill-new (apply 'concat (nreverse snippets)))))
20439 (defun org-copy-special ()
20440 "Copy region in table or copy current subtree.
20441 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20442 See the individual commands for more information."
20443 (interactive)
20444 (call-interactively
20445 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20447 (defun org-cut-special ()
20448 "Cut region in table or cut current subtree.
20449 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20450 See the individual commands for more information."
20451 (interactive)
20452 (call-interactively
20453 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20455 (defun org-paste-special (arg)
20456 "Paste rectangular region into table, or past subtree relative to level.
20457 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20458 See the individual commands for more information."
20459 (interactive "P")
20460 (if (org-at-table-p)
20461 (org-table-paste-rectangle)
20462 (org-paste-subtree arg)))
20464 (defsubst org-in-fixed-width-region-p ()
20465 "Is point in a fixed-width region?"
20466 (save-match-data
20467 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20469 (defun org-edit-special (&optional arg)
20470 "Call a special editor for the element at point.
20471 When at a table, call the formula editor with `org-table-edit-formulas'.
20472 When in a source code block, call `org-edit-src-code'.
20473 When in a fixed-width region, call `org-edit-fixed-width-region'.
20474 When at an #+INCLUDE keyword, visit the included file.
20475 On a link, call `ffap' to visit the link at point.
20476 Otherwise, return a user error."
20477 (interactive "P")
20478 (let ((element (org-element-at-point)))
20479 (assert (not buffer-read-only) nil
20480 "Buffer is read-only: %s" (buffer-name))
20481 (case (org-element-type element)
20482 (src-block
20483 (if (not arg) (org-edit-src-code)
20484 (let* ((info (org-babel-get-src-block-info))
20485 (lang (nth 0 info))
20486 (params (nth 2 info))
20487 (session (cdr (assq :session params))))
20488 (if (not session) (org-edit-src-code)
20489 ;; At a src-block with a session and function called with
20490 ;; an ARG: switch to the buffer related to the inferior
20491 ;; process.
20492 (switch-to-buffer
20493 (funcall (intern (concat "org-babel-prep-session:" lang))
20494 session params))))))
20495 (keyword
20496 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20497 (find-file-other-window
20498 (org-remove-double-quotes
20499 (car (org-split-string (org-element-property :value element)))))
20500 (user-error "No special environment to edit here")))
20501 (table
20502 (if (eq (org-element-property :type element) 'table.el)
20503 (org-edit-src-code)
20504 (call-interactively 'org-table-edit-formulas)))
20505 ;; Only Org tables contain `table-row' type elements.
20506 (table-row (call-interactively 'org-table-edit-formulas))
20507 ((example-block export-block) (org-edit-src-code))
20508 (fixed-width (org-edit-fixed-width-region))
20509 (otherwise
20510 ;; No notable element at point. Though, we may be at a link,
20511 ;; which is an object. Thus, scan deeper.
20512 (if (eq (org-element-type (org-element-context element)) 'link)
20513 (call-interactively 'ffap)
20514 (user-error "No special environment to edit here"))))))
20516 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20517 (defun org-ctrl-c-ctrl-c (&optional arg)
20518 "Set tags in headline, or update according to changed information at point.
20520 This command does many different things, depending on context:
20522 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20523 this is what we do.
20525 - If the cursor is on a statistics cookie, update it.
20527 - If the cursor is in a headline, prompt for tags and insert them
20528 into the current line, aligned to `org-tags-column'. When called
20529 with prefix arg, realign all tags in the current buffer.
20531 - If the cursor is in one of the special #+KEYWORD lines, this
20532 triggers scanning the buffer for these lines and updating the
20533 information.
20535 - If the cursor is inside a table, realign the table. This command
20536 works even if the automatic table editor has been turned off.
20538 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20539 the entire table.
20541 - If the cursor is at a footnote reference or definition, jump to
20542 the corresponding definition or references, respectively.
20544 - If the cursor is a the beginning of a dynamic block, update it.
20546 - If the current buffer is a capture buffer, close note and file it.
20548 - If the cursor is on a <<<target>>>, update radio targets and
20549 corresponding links in this buffer.
20551 - If the cursor is on a numbered item in a plain list, renumber the
20552 ordered list.
20554 - If the cursor is on a checkbox, toggle it.
20556 - If the cursor is on a code block, evaluate it. The variable
20557 `org-confirm-babel-evaluate' can be used to control prompting
20558 before code block evaluation, by default every code block
20559 evaluation requires confirmation. Code block evaluation can be
20560 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20561 (interactive "P")
20562 (cond
20563 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20564 org-occur-highlights
20565 org-latex-fragment-image-overlays)
20566 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20567 (org-remove-occur-highlights)
20568 (org-remove-latex-fragment-image-overlays)
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 (setq ov (overlays-at (point)))
21833 (memq 'org-block-background
21834 (overlay-properties (car ov))))
21835 (and (not inside)
21836 (save-match-data
21837 (save-excursion
21838 (beginning-of-line)
21839 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21841 (defun org-context ()
21842 "Return a list of contexts of the current cursor position.
21843 If several contexts apply, all are returned.
21844 Each context entry is a list with a symbol naming the context, and
21845 two positions indicating start and end of the context. Possible
21846 contexts are:
21848 :headline anywhere in a headline
21849 :headline-stars on the leading stars in a headline
21850 :todo-keyword on a TODO keyword (including DONE) in a headline
21851 :tags on the TAGS in a headline
21852 :priority on the priority cookie in a headline
21853 :item on the first line of a plain list item
21854 :item-bullet on the bullet/number of a plain list item
21855 :checkbox on the checkbox in a plain list item
21856 :table in an org-mode table
21857 :table-special on a special filed in a table
21858 :table-table in a table.el table
21859 :clocktable in a clocktable
21860 :src-block in a source block
21861 :link on a hyperlink
21862 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21863 :target on a <<target>>
21864 :radio-target on a <<<radio-target>>>
21865 :latex-fragment on a LaTeX fragment
21866 :latex-preview on a LaTeX fragment with overlaid preview image
21868 This function expects the position to be visible because it uses font-lock
21869 faces as a help to recognize the following contexts: :table-special, :link,
21870 and :keyword."
21871 (let* ((f (get-text-property (point) 'face))
21872 (faces (if (listp f) f (list f)))
21873 (case-fold-search t)
21874 (p (point)) clist o)
21875 ;; First the large context
21876 (cond
21877 ((org-at-heading-p t)
21878 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21879 (when (progn
21880 (beginning-of-line 1)
21881 (looking-at org-todo-line-tags-regexp))
21882 (push (org-point-in-group p 1 :headline-stars) clist)
21883 (push (org-point-in-group p 2 :todo-keyword) clist)
21884 (push (org-point-in-group p 4 :tags) clist))
21885 (goto-char p)
21886 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21887 (if (looking-at "\\[#[A-Z0-9]\\]")
21888 (push (org-point-in-group p 0 :priority) clist)))
21890 ((org-at-item-p)
21891 (push (org-point-in-group p 2 :item-bullet) clist)
21892 (push (list :item (point-at-bol)
21893 (save-excursion (org-end-of-item) (point)))
21894 clist)
21895 (and (org-at-item-checkbox-p)
21896 (push (org-point-in-group p 0 :checkbox) clist)))
21898 ((org-at-table-p)
21899 (push (list :table (org-table-begin) (org-table-end)) clist)
21900 (if (memq 'org-formula faces)
21901 (push (list :table-special
21902 (previous-single-property-change p 'face)
21903 (next-single-property-change p 'face)) clist)))
21904 ((org-at-table-p 'any)
21905 (push (list :table-table) clist)))
21906 (goto-char p)
21908 (let ((case-fold-search t))
21909 ;; New the "medium" contexts: clocktables, source blocks
21910 (cond ((org-in-clocktable-p)
21911 (push (list :clocktable
21912 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21913 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21914 (match-beginning 1))
21915 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21916 (match-end 0))) clist))
21917 ((org-in-src-block-p)
21918 (push (list :src-block
21919 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21920 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21921 (match-beginning 1))
21922 (and (search-forward "#+END_SRC" nil t)
21923 (match-beginning 0))) clist))))
21924 (goto-char p)
21926 ;; Now the small context
21927 (cond
21928 ((org-at-timestamp-p)
21929 (push (org-point-in-group p 0 :timestamp) clist))
21930 ((memq 'org-link faces)
21931 (push (list :link
21932 (previous-single-property-change p 'face)
21933 (next-single-property-change p 'face)) clist))
21934 ((memq 'org-special-keyword faces)
21935 (push (list :keyword
21936 (previous-single-property-change p 'face)
21937 (next-single-property-change p 'face)) clist))
21938 ((org-at-target-p)
21939 (push (org-point-in-group p 0 :target) clist)
21940 (goto-char (1- (match-beginning 0)))
21941 (if (looking-at org-radio-target-regexp)
21942 (push (org-point-in-group p 0 :radio-target) clist))
21943 (goto-char p))
21944 ((setq o (car (delq nil
21945 (mapcar
21946 (lambda (x)
21947 (if (memq x org-latex-fragment-image-overlays) x))
21948 (overlays-at (point))))))
21949 (push (list :latex-fragment
21950 (overlay-start o) (overlay-end o)) clist)
21951 (push (list :latex-preview
21952 (overlay-start o) (overlay-end o)) clist))
21953 ((org-inside-LaTeX-fragment-p)
21954 ;; FIXME: positions wrong.
21955 (push (list :latex-fragment (point) (point)) clist)))
21957 (setq clist (nreverse (delq nil clist)))
21958 clist))
21960 ;; FIXME: Compare with at-regexp-p Do we need both?
21961 (defun org-in-regexp (re &optional nlines visually)
21962 "Check if point is inside a match of regexp.
21963 Normally only the current line is checked, but you can include NLINES extra
21964 lines both before and after point into the search.
21965 If VISUALLY is set, require that the cursor is not after the match but
21966 really on, so that the block visually is on the match."
21967 (catch 'exit
21968 (let ((pos (point))
21969 (eol (point-at-eol (+ 1 (or nlines 0))))
21970 (inc (if visually 1 0)))
21971 (save-excursion
21972 (beginning-of-line (- 1 (or nlines 0)))
21973 (while (re-search-forward re eol t)
21974 (if (and (<= (match-beginning 0) pos)
21975 (>= (+ inc (match-end 0)) pos))
21976 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21978 (defun org-at-regexp-p (regexp)
21979 "Is point inside a match of REGEXP in the current line?"
21980 (catch 'exit
21981 (save-excursion
21982 (let ((pos (point)) (end (point-at-eol)))
21983 (beginning-of-line 1)
21984 (while (re-search-forward regexp end t)
21985 (if (and (<= (match-beginning 0) pos)
21986 (>= (match-end 0) pos))
21987 (throw 'exit t)))
21988 nil))))
21990 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21991 "Non-nil when point is between matches of START-RE and END-RE.
21993 Also return a non-nil value when point is on one of the matches.
21995 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21996 buffer positions. Default values are the positions of headlines
21997 surrounding the point.
21999 The functions returns a cons cell whose car (resp. cdr) is the
22000 position before START-RE (resp. after END-RE)."
22001 (save-match-data
22002 (let ((pos (point))
22003 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22004 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22005 beg end)
22006 (save-excursion
22007 ;; Point is on a block when on START-RE or if START-RE can be
22008 ;; found before it...
22009 (and (or (org-at-regexp-p start-re)
22010 (re-search-backward start-re limit-up t))
22011 (setq beg (match-beginning 0))
22012 ;; ... and END-RE after it...
22013 (goto-char (match-end 0))
22014 (re-search-forward end-re limit-down t)
22015 (> (setq end (match-end 0)) pos)
22016 ;; ... without another START-RE in-between.
22017 (goto-char (match-beginning 0))
22018 (not (re-search-backward start-re (1+ beg) t))
22019 ;; Return value.
22020 (cons beg end))))))
22022 (defun org-in-block-p (names)
22023 "Non-nil when point belongs to a block whose name belongs to NAMES.
22025 NAMES is a list of strings containing names of blocks.
22027 Return first block name matched, or nil. Beware that in case of
22028 nested blocks, the returned name may not belong to the closest
22029 block from point."
22030 (save-match-data
22031 (catch 'exit
22032 (let ((case-fold-search t)
22033 (lim-up (save-excursion (outline-previous-heading)))
22034 (lim-down (save-excursion (outline-next-heading))))
22035 (mapc (lambda (name)
22036 (let ((n (regexp-quote name)))
22037 (when (org-between-regexps-p
22038 (concat "^[ \t]*#\\+begin_" n)
22039 (concat "^[ \t]*#\\+end_" n)
22040 lim-up lim-down)
22041 (throw 'exit n))))
22042 names))
22043 nil)))
22045 (defun org-in-drawer-p ()
22046 "Non-nil if point is within a drawer.
22047 If point is within a drawer, return it, as parsed data."
22048 (let ((element (save-match-data (org-element-at-point))))
22049 (while (and element (not (memq (org-element-type element)
22050 '(drawer property-drawer))))
22051 (setq element (org-element-property :parent element)))
22052 element))
22054 (defun org-occur-in-agenda-files (regexp &optional nlines)
22055 "Call `multi-occur' with buffers for all agenda files."
22056 (interactive "sOrg-files matching: \np")
22057 (let* ((files (org-agenda-files))
22058 (tnames (mapcar 'file-truename files))
22059 (extra org-agenda-text-search-extra-files)
22061 (when (eq (car extra) 'agenda-archives)
22062 (setq extra (cdr extra))
22063 (setq files (org-add-archive-files files)))
22064 (while (setq f (pop extra))
22065 (unless (member (file-truename f) tnames)
22066 (add-to-list 'files f 'append)
22067 (add-to-list 'tnames (file-truename f) 'append)))
22068 (multi-occur
22069 (mapcar (lambda (x)
22070 (with-current-buffer
22071 (or (get-file-buffer x) (find-file-noselect x))
22072 (widen)
22073 (current-buffer)))
22074 files)
22075 regexp)))
22077 (if (boundp 'occur-mode-find-occurrence-hook)
22078 ;; Emacs 23
22079 (add-hook 'occur-mode-find-occurrence-hook
22080 (lambda ()
22081 (when (derived-mode-p 'org-mode)
22082 (org-reveal))))
22083 ;; Emacs 22
22084 (defadvice occur-mode-goto-occurrence
22085 (after org-occur-reveal activate)
22086 (and (derived-mode-p 'org-mode) (org-reveal)))
22087 (defadvice occur-mode-goto-occurrence-other-window
22088 (after org-occur-reveal activate)
22089 (and (derived-mode-p 'org-mode) (org-reveal)))
22090 (defadvice occur-mode-display-occurrence
22091 (after org-occur-reveal activate)
22092 (when (derived-mode-p 'org-mode)
22093 (let ((pos (occur-mode-find-occurrence)))
22094 (with-current-buffer (marker-buffer pos)
22095 (save-excursion
22096 (goto-char pos)
22097 (org-reveal)))))))
22099 (defun org-occur-link-in-agenda-files ()
22100 "Create a link and search for it in the agendas.
22101 The link is not stored in `org-stored-links', it is just created
22102 for the search purpose."
22103 (interactive)
22104 (let ((link (condition-case nil
22105 (org-store-link nil)
22106 (error "Unable to create a link to here"))))
22107 (org-occur-in-agenda-files (regexp-quote link))))
22109 (defun org-reverse-string (string)
22110 "Return the reverse of STRING."
22111 (apply 'string (reverse (string-to-list string))))
22113 ;; defsubst org-uniquify must be defined before first use
22115 (defun org-uniquify-alist (alist)
22116 "Merge elements of ALIST with the same key.
22118 For example, in this alist:
22120 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22121 => '((a 1 3) (b 2))
22123 merge (a 1) and (a 3) into (a 1 3).
22125 The function returns the new ALIST."
22126 (let (rtn)
22127 (mapc
22128 (lambda (e)
22129 (let (n)
22130 (if (not (assoc (car e) rtn))
22131 (push e rtn)
22132 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22133 (setq rtn (assq-delete-all (car e) rtn))
22134 (push n rtn))))
22135 alist)
22136 rtn))
22138 (defun org-delete-all (elts list)
22139 "Remove all elements in ELTS from LIST."
22140 (while elts
22141 (setq list (delete (pop elts) list)))
22142 list)
22144 (defun org-count (cl-item cl-seq)
22145 "Count the number of occurrences of ITEM in SEQ.
22146 Taken from `count' in cl-seq.el with all keyword arguments removed."
22147 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22148 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22149 (while (< cl-start cl-end)
22150 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22151 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22152 (setq cl-start (1+ cl-start)))
22153 cl-count))
22155 (defun org-remove-if (predicate seq)
22156 "Remove everything from SEQ that fulfills PREDICATE."
22157 (let (res e)
22158 (while seq
22159 (setq e (pop seq))
22160 (if (not (funcall predicate e)) (push e res)))
22161 (nreverse res)))
22163 (defun org-remove-if-not (predicate seq)
22164 "Remove everything from SEQ that does not fulfill PREDICATE."
22165 (let (res e)
22166 (while seq
22167 (setq e (pop seq))
22168 (if (funcall predicate e) (push e res)))
22169 (nreverse res)))
22171 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22172 "Reduce two-argument FUNCTION across SEQ.
22173 Taken from `reduce' in cl-seq.el with all keyword arguments but
22174 \":initial-value\" removed."
22175 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22176 (cadr (memq :initial-value cl-keys)))
22177 (cl-seq (pop cl-seq))
22178 (t (funcall cl-func)))))
22179 (while cl-seq
22180 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22181 cl-accum))
22183 (defun org-every (pred seq)
22184 "Return true if PREDICATE is true of every element of SEQ.
22185 Adapted from `every' in cl.el."
22186 (catch 'org-every
22187 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22190 (defun org-some (pred seq)
22191 "Return true if PREDICATE is true of any element of SEQ.
22192 Adapted from `some' in cl.el."
22193 (catch 'org-some
22194 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22195 nil))
22197 (defun org-back-over-empty-lines ()
22198 "Move backwards over whitespace, to the beginning of the first empty line.
22199 Returns the number of empty lines passed."
22200 (let ((pos (point)))
22201 (if (cdr (assoc 'heading org-blank-before-new-entry))
22202 (skip-chars-backward " \t\n\r")
22203 (unless (eobp)
22204 (forward-line -1)))
22205 (beginning-of-line 2)
22206 (goto-char (min (point) pos))
22207 (count-lines (point) pos)))
22209 (defun org-skip-whitespace ()
22210 (skip-chars-forward " \t\n\r"))
22212 (defun org-point-in-group (point group &optional context)
22213 "Check if POINT is in match-group GROUP.
22214 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22215 match. If the match group does not exist or point is not inside it,
22216 return nil."
22217 (and (match-beginning group)
22218 (>= point (match-beginning group))
22219 (<= point (match-end group))
22220 (if context
22221 (list context (match-beginning group) (match-end group))
22222 t)))
22224 (defun org-switch-to-buffer-other-window (&rest args)
22225 "Switch to buffer in a second window on the current frame.
22226 In particular, do not allow pop-up frames.
22227 Returns the newly created buffer."
22228 (org-no-popups
22229 (apply 'switch-to-buffer-other-window args)))
22231 (defun org-combine-plists (&rest plists)
22232 "Create a single property list from all plists in PLISTS.
22233 The process starts by copying the first list, and then setting properties
22234 from the other lists. Settings in the last list are the most significant
22235 ones and overrule settings in the other lists."
22236 (let ((rtn (copy-sequence (pop plists)))
22237 p v ls)
22238 (while plists
22239 (setq ls (pop plists))
22240 (while ls
22241 (setq p (pop ls) v (pop ls))
22242 (setq rtn (plist-put rtn p v))))
22243 rtn))
22245 (defun org-replace-escapes (string table)
22246 "Replace %-escapes in STRING with values in TABLE.
22247 TABLE is an association list with keys like \"%a\" and string values.
22248 The sequences in STRING may contain normal field width and padding information,
22249 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22250 so values can contain further %-escapes if they are define later in TABLE."
22251 (let ((tbl (copy-alist table))
22252 (case-fold-search nil)
22253 (pchg 0)
22254 e re rpl)
22255 (while (setq e (pop tbl))
22256 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22257 (when (and (cdr e) (string-match re (cdr e)))
22258 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22259 (safe "SREF"))
22260 (add-text-properties 0 3 (list 'sref sref) safe)
22261 (setcdr e (replace-match safe t t (cdr e)))))
22262 (while (string-match re string)
22263 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22264 (cdr e)))
22265 (setq string (replace-match rpl t t string))))
22266 (while (setq pchg (next-property-change pchg string))
22267 (let ((sref (get-text-property pchg 'sref string)))
22268 (when (and sref (string-match "SREF" string pchg))
22269 (setq string (replace-match sref t t string)))))
22270 string))
22272 (defun org-sublist (list start end)
22273 "Return a section of LIST, from START to END.
22274 Counting starts at 1."
22275 (let (rtn (c start))
22276 (setq list (nthcdr (1- start) list))
22277 (while (and list (<= c end))
22278 (push (pop list) rtn)
22279 (setq c (1+ c)))
22280 (nreverse rtn)))
22282 (defun org-find-base-buffer-visiting (file)
22283 "Like `find-buffer-visiting' but always return the base buffer and
22284 not an indirect buffer."
22285 (let ((buf (or (get-file-buffer file)
22286 (find-buffer-visiting file))))
22287 (if buf
22288 (or (buffer-base-buffer buf) buf)
22289 nil)))
22291 (defun org-image-file-name-regexp (&optional extensions)
22292 "Return regexp matching the file names of images.
22293 If EXTENSIONS is given, only match these."
22294 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22295 (image-file-name-regexp)
22296 (let ((image-file-name-extensions
22297 (or extensions
22298 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22299 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22300 (concat "\\."
22301 (regexp-opt (nconc (mapcar 'upcase
22302 image-file-name-extensions)
22303 image-file-name-extensions)
22305 "\\'"))))
22307 (defun org-file-image-p (file &optional extensions)
22308 "Return non-nil if FILE is an image."
22309 (save-match-data
22310 (string-match (org-image-file-name-regexp extensions) file)))
22312 (defun org-get-cursor-date (&optional with-time)
22313 "Return the date at cursor in as a time.
22314 This works in the calendar and in the agenda, anywhere else it just
22315 returns the current time.
22316 If WITH-TIME is non-nil, returns the time of the event at point (in
22317 the agenda) or the current time of the day."
22318 (let (date day defd tp tm hod mod)
22319 (when with-time
22320 (setq tp (get-text-property (point) 'time))
22321 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22322 (setq hod (string-to-number (match-string 1 tp))
22323 mod (string-to-number (match-string 2 tp))))
22324 (or tp (setq hod (nth 2 (decode-time (current-time)))
22325 mod (nth 1 (decode-time (current-time))))))
22326 (cond
22327 ((eq major-mode 'calendar-mode)
22328 (setq date (calendar-cursor-to-date)
22329 defd (encode-time 0 (or mod 0) (or hod 0)
22330 (nth 1 date) (nth 0 date) (nth 2 date))))
22331 ((eq major-mode 'org-agenda-mode)
22332 (setq day (get-text-property (point) 'day))
22333 (if day
22334 (setq date (calendar-gregorian-from-absolute day)
22335 defd (encode-time 0 (or mod 0) (or hod 0)
22336 (nth 1 date) (nth 0 date) (nth 2 date))))))
22337 (or defd (current-time))))
22339 (defun org-mark-subtree (&optional up)
22340 "Mark the current subtree.
22341 This puts point at the start of the current subtree, and mark at
22342 the end. If a numeric prefix UP is given, move up into the
22343 hierarchy of headlines by UP levels before marking the subtree."
22344 (interactive "P")
22345 (org-with-limited-levels
22346 (cond ((org-at-heading-p) (beginning-of-line))
22347 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22348 (t (outline-previous-visible-heading 1))))
22349 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22350 (if (org-called-interactively-p 'any)
22351 (call-interactively 'org-mark-element)
22352 (org-mark-element)))
22355 ;;; Indentation
22357 (defun org--get-expected-indentation (element contentsp)
22358 "Expected indentation column for current line, according to ELEMENT.
22359 ELEMENT is an element containing point. CONTENTSP is non-nil
22360 when indentation is to be computed according to contents of
22361 ELEMENT."
22362 (let ((type (org-element-type element))
22363 (start (org-element-property :begin element)))
22364 (org-with-wide-buffer
22365 (cond
22366 (contentsp
22367 (case type
22368 (footnote-definition 0)
22369 ((headline inlinetask nil)
22370 (if (not org-adapt-indentation) 0
22371 (let ((level (org-current-level)))
22372 (if level (1+ level) 0))))
22373 ((item plain list)
22374 (org-list-item-body-column
22375 (or (org-element-property :post-affiliated element) start)))
22376 (otherwise
22377 (goto-char start)
22378 (org-get-indentation))))
22379 ((memq type '(headline inlinetask nil))
22380 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22381 (org--get-expected-indentation element t)
22383 ((eq type 'footnote-definition) 0)
22384 ;; First paragraph of a footnote definition or an item.
22385 ;; Indent like parent.
22386 ((< (line-beginning-position) start)
22387 (org--get-expected-indentation
22388 (org-element-property :parent element) t))
22389 ;; At first line: indent according to previous sibling, if any,
22390 ;; ignoring footnote definitions and inline tasks, or parent's
22391 ;; contents.
22392 ((= (line-beginning-position) start)
22393 (catch 'exit
22394 (while t
22395 (if (= (point-min) start) (throw 'exit 0)
22396 (goto-char (1- start))
22397 (let ((previous (org-element-at-point)))
22398 (while (let ((parent (org-element-property :parent previous)))
22399 (and parent
22400 (setq previous parent)
22401 (<= (org-element-property :end parent) start))))
22402 (cond ((or (not previous)
22403 (> (org-element-property :end previous) start))
22404 (throw 'exit (org--get-expected-indentation previous t)))
22405 ((memq (org-element-type previous)
22406 '(footnote-definition inlinetask))
22407 (setq start (org-element-property :begin previous)))
22408 (t (goto-char (org-element-property :begin previous))
22409 (throw 'exit (org-get-indentation)))))))))
22410 ;; Otherwise, move to the first non-blank line above.
22412 (beginning-of-line)
22413 (let ((pos (point)))
22414 (skip-chars-backward " \r\t\n")
22415 (cond
22416 ;; Two blank lines end a footnote definition or a plain
22417 ;; list. When we indent an empty line after them, the
22418 ;; containing list or footnote definition is over, so it
22419 ;; qualifies as a previous sibling. Therefore, we indent
22420 ;; like its first line.
22421 ((and (memq type '(footnote-definition plain-list))
22422 (> (count-lines (point) pos) 2))
22423 (goto-char start)
22424 (org-get-indentation))
22425 ;; Line above is the first one of a paragraph at the
22426 ;; beginning of an item or a footnote definition. Indent
22427 ;; like parent.
22428 ((< (line-beginning-position) start)
22429 (org--get-expected-indentation
22430 (org-element-property :parent element) t))
22431 ;; POS is after contents in a greater element. Indent like
22432 ;; the beginning of the element.
22434 ;; As a special case, if point is at the end of a footnote
22435 ;; definition or an item, indent like the very last element
22436 ;; within.
22437 ((let ((cend (org-element-property :contents-end element)))
22438 (and cend (<= cend pos)))
22439 (if (memq type '(footnote-definition item plain-list))
22440 (org--get-expected-indentation (org-element-at-point) nil)
22441 (goto-char start)
22442 (org-get-indentation)))
22443 ;; In any other case, indent like the current line.
22444 (t (org-get-indentation)))))))))
22446 (defun org--align-node-property ()
22447 "Align node property at point.
22448 Alignment is done according to `org-property-format', which see."
22449 (when (save-excursion
22450 (beginning-of-line)
22451 (looking-at org-property-re))
22452 (replace-match
22453 (concat (match-string 4)
22454 (format org-property-format (match-string 1) (match-string 3)))
22455 t t)))
22457 (defun org-indent-line ()
22458 "Indent line depending on context.
22460 Indentation is done according to the following rules:
22462 - Footnote definitions, headlines and inline tasks have to
22463 start at column 0.
22465 - On the very first line of an element, consider, in order, the
22466 next rules until one matches:
22468 1. If there's a sibling element before, ignoring footnote
22469 definitions and inline tasks, indent like its first line.
22471 2. If element has a parent, indent like its contents. More
22472 precisely, if parent is an item, indent after the
22473 description part, if any, or the bullet (see
22474 ``org-list-description-max-indent'). Else, indent like
22475 parent's first line.
22477 3. Otherwise, indent relatively to current level, if
22478 `org-adapt-indentation' is non-nil, or to left margin.
22480 - On a blank line at the end of a plain list, an item, or
22481 a footnote definition, indent like the very last element
22482 within.
22484 - In the code part of a source block, use language major mode
22485 to indent current line if `org-src-tab-acts-natively' is
22486 non-nil. If it is nil, do nothing.
22488 - Otherwise, indent like the first non-blank line above.
22490 The function doesn't indent an item as it could break the whole
22491 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22492 \\[org-shiftmetaright].
22494 Also align node properties according to `org-property-format'."
22495 (interactive)
22496 (cond
22497 (orgstruct-is-++
22498 (let ((indent-line-function
22499 (cadadr (assq 'indent-line-function org-fb-vars))))
22500 (indent-according-to-mode)))
22501 ((org-at-heading-p) 'noindent)
22503 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22504 (type (org-element-type element)))
22505 (cond ((and (memq type '(plain-list item))
22506 (= (line-beginning-position)
22507 (or (org-element-property :post-affiliated element)
22508 (org-element-property :begin element))))
22509 'noindent)
22510 ((and (eq type 'src-block)
22511 org-src-tab-acts-natively
22512 (> (line-beginning-position)
22513 (org-element-property :post-affiliated element))
22514 (< (line-beginning-position)
22515 (org-with-wide-buffer
22516 (goto-char (org-element-property :end element))
22517 (skip-chars-backward " \r\t\n")
22518 (line-beginning-position))))
22519 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22520 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22522 (let ((column (org--get-expected-indentation element nil)))
22523 ;; Preserve current column.
22524 (if (<= (current-column) (current-indentation))
22525 (org-indent-line-to column)
22526 (save-excursion (org-indent-line-to column))))
22527 ;; Align node property. Also preserve current column.
22528 (when (eq type 'node-property)
22529 (let ((column (current-column)))
22530 (org--align-node-property)
22531 (org-move-to-column column)))))))))
22533 (defun org-indent-region (start end)
22534 "Indent each non-blank line in the region.
22535 Called from a program, START and END specify the region to
22536 indent. The function will not indent contents of example blocks,
22537 verse blocks and export blocks as leading white spaces are
22538 assumed to be significant there."
22539 (interactive "r")
22540 (save-excursion
22541 (goto-char start)
22542 (beginning-of-line)
22543 (let ((indent-to
22544 (lambda (ind pos)
22545 ;; Set IND as indentation for all lines between point and
22546 ;; POS or END, whichever comes first. Blank lines are
22547 ;; ignored. Leave point after POS once done.
22548 (let ((limit (copy-marker (min end pos))))
22549 (while (< (point) limit)
22550 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22551 (forward-line))
22552 (set-marker limit nil))))
22553 (end (copy-marker end)))
22554 (while (< (point) end)
22555 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22556 (let* ((element (org-element-at-point))
22557 (type (org-element-type element))
22558 (element-end (copy-marker (org-element-property :end element)))
22559 (ind (org--get-expected-indentation element nil)))
22560 (if (or (memq type '(paragraph table table-row))
22561 (not (or (org-element-property :contents-begin element)
22562 (memq type
22563 '(example-block export-block src-block)))))
22564 ;; Elements here are indented as a single block. Also
22565 ;; align node properties.
22566 (progn
22567 (when (eq type 'node-property)
22568 (org--align-node-property)
22569 (beginning-of-line))
22570 (funcall indent-to ind element-end))
22571 ;; Elements in this category consist of three parts:
22572 ;; before the contents, the contents, and after the
22573 ;; contents. The contents are treated specially,
22574 ;; according to the element type, or not indented at
22575 ;; all. Other parts are indented as a single block.
22576 (let* ((post (copy-marker
22577 (or (org-element-property :post-affiliated element)
22578 (org-element-property :begin element))))
22579 (cbeg
22580 (copy-marker
22581 (cond
22582 ((not (org-element-property :contents-begin element))
22583 ;; Fake contents for source blocks.
22584 (org-with-wide-buffer
22585 (goto-char post)
22586 (forward-line)
22587 (point)))
22588 ((memq type '(footnote-definition item plain-list))
22589 ;; Contents in these elements could start on
22590 ;; the same line as the beginning of the
22591 ;; element. Make sure we start indenting
22592 ;; from the second line.
22593 (org-with-wide-buffer
22594 (goto-char post)
22595 (forward-line)
22596 (point)))
22597 (t (org-element-property :contents-begin element)))))
22598 (cend (copy-marker
22599 (or (org-element-property :contents-end element)
22600 ;; Fake contents for source blocks.
22601 (org-with-wide-buffer
22602 (goto-char element-end)
22603 (skip-chars-backward " \r\t\n")
22604 (line-beginning-position))))))
22605 (funcall indent-to ind cbeg)
22606 (when (< (point) end)
22607 (case type
22608 ((example-block export-block verse-block))
22609 (src-block
22610 ;; In a source block, indent source code according
22611 ;; to language major mode, but only if
22612 ;; `org-src-tab-acts-natively' is non-nil.
22613 (when (and (< (point) end) org-src-tab-acts-natively)
22614 (ignore-errors
22615 (let (org-src-strip-leading-and-trailing-blank-lines
22616 ;; Region boundaries in edit buffer.
22617 (start (1+ (- (point) cbeg)))
22618 (end (- (min cend end) cbeg)))
22619 (org-babel-do-in-edit-buffer
22620 (indent-region start end))))))
22621 (t (org-indent-region (point) (min cend end))))
22622 (goto-char (min cend end))
22623 (when (< (point) end) (funcall indent-to ind element-end)))
22624 (set-marker post nil)
22625 (set-marker cbeg nil)
22626 (set-marker cend nil)))
22627 (set-marker element-end nil))))
22628 (set-marker end nil))))
22630 (defun org-indent-drawer ()
22631 "Indent the drawer at point."
22632 (interactive)
22633 (unless (save-excursion
22634 (beginning-of-line)
22635 (org-looking-at-p org-drawer-regexp))
22636 (user-error "Not at a drawer"))
22637 (let ((element (org-element-at-point)))
22638 (unless (memq (org-element-type element) '(drawer property-drawer))
22639 (user-error "Not at a drawer"))
22640 (org-with-wide-buffer
22641 (org-indent-region (org-element-property :begin element)
22642 (org-element-property :end element))))
22643 (message "Drawer at point indented"))
22645 (defun org-indent-block ()
22646 "Indent the block at point."
22647 (interactive)
22648 (unless (save-excursion
22649 (beginning-of-line)
22650 (let ((case-fold-search t))
22651 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22652 (user-error "Not at a block"))
22653 (let ((element (org-element-at-point)))
22654 (unless (memq (org-element-type element)
22655 '(comment-block center-block example-block export-block
22656 quote-block special-block src-block
22657 verse-block))
22658 (user-error "Not at a block"))
22659 (org-with-wide-buffer
22660 (org-indent-region (org-element-property :begin element)
22661 (org-element-property :end element))))
22662 (message "Block at point indented"))
22665 ;;; Filling
22667 ;; We use our own fill-paragraph and auto-fill functions.
22669 ;; `org-fill-paragraph' relies on adaptive filling and context
22670 ;; checking. Appropriate `fill-prefix' is computed with
22671 ;; `org-adaptive-fill-function'.
22673 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22674 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22675 ;; `org-adaptive-fill-function' value. Internally,
22676 ;; `org-comment-line-break-function' breaks the line.
22678 ;; `org-setup-filling' installs filling and auto-filling related
22679 ;; variables during `org-mode' initialization.
22681 (defvar org-element-paragraph-separate) ; org-element.el
22682 (defun org-setup-filling ()
22683 (require 'org-element)
22684 ;; Prevent auto-fill from inserting unwanted new items.
22685 (when (boundp 'fill-nobreak-predicate)
22686 (org-set-local
22687 'fill-nobreak-predicate
22688 (org-uniquify
22689 (append fill-nobreak-predicate
22690 '(org-fill-line-break-nobreak-p
22691 org-fill-paragraph-with-timestamp-nobreak-p)))))
22692 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22693 (org-set-local 'paragraph-start paragraph-ending)
22694 (org-set-local 'paragraph-separate paragraph-ending))
22695 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22696 (org-set-local 'auto-fill-inhibit-regexp nil)
22697 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22698 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22699 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22701 (defun org-fill-line-break-nobreak-p ()
22702 "Non-nil when a new line at point would create an Org line break."
22703 (save-excursion
22704 (skip-chars-backward "[ \t]")
22705 (skip-chars-backward "\\\\")
22706 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22708 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22709 "Non-nil when a new line at point would split a timestamp."
22710 (and (org-at-timestamp-p t)
22711 (not (looking-at org-ts-regexp-both))))
22713 (declare-function message-in-body-p "message" ())
22714 (defvar orgtbl-line-start-regexp) ; From org-table.el
22715 (defun org-adaptive-fill-function ()
22716 "Compute a fill prefix for the current line.
22717 Return fill prefix, as a string, or nil if current line isn't
22718 meant to be filled. For convenience, if `adaptive-fill-regexp'
22719 matches in paragraphs or comments, use it."
22720 (catch 'exit
22721 (when (derived-mode-p 'message-mode)
22722 (save-excursion
22723 (beginning-of-line)
22724 (cond ((or (not (message-in-body-p))
22725 (looking-at orgtbl-line-start-regexp))
22726 (throw 'exit nil))
22727 ((looking-at message-cite-prefix-regexp)
22728 (throw 'exit (match-string-no-properties 0)))
22729 ((looking-at org-outline-regexp)
22730 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22731 (org-with-wide-buffer
22732 (let* ((p (line-beginning-position))
22733 (element (save-excursion
22734 (beginning-of-line)
22735 (or (ignore-errors (org-element-at-point))
22736 (user-error "An element cannot be parsed line %d"
22737 (line-number-at-pos (point))))))
22738 (type (org-element-type element))
22739 (post-affiliated (org-element-property :post-affiliated element)))
22740 (unless (and post-affiliated (< p post-affiliated))
22741 (case type
22742 (comment
22743 (save-excursion
22744 (beginning-of-line)
22745 (looking-at "[ \t]*")
22746 (concat (match-string 0) "# ")))
22747 (footnote-definition "")
22748 ((item plain-list)
22749 (make-string (org-list-item-body-column
22750 (or post-affiliated
22751 (org-element-property :begin element)))
22752 ? ))
22753 (paragraph
22754 ;; Fill prefix is usually the same as the current line,
22755 ;; unless the paragraph is at the beginning of an item.
22756 (let ((parent (org-element-property :parent element)))
22757 (save-excursion
22758 (beginning-of-line)
22759 (cond ((eq (org-element-type parent) 'item)
22760 (make-string (org-list-item-body-column
22761 (org-element-property :begin parent))
22762 ? ))
22763 ((and adaptive-fill-regexp
22764 ;; Locally disable
22765 ;; `adaptive-fill-function' to let
22766 ;; `fill-context-prefix' handle
22767 ;; `adaptive-fill-regexp' variable.
22768 (let (adaptive-fill-function)
22769 (fill-context-prefix
22770 post-affiliated
22771 (org-element-property :end element)))))
22772 ((looking-at "[ \t]+") (match-string 0))
22773 (t "")))))
22774 (comment-block
22775 ;; Only fill contents if P is within block boundaries.
22776 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22777 (forward-line)
22778 (point)))
22779 (cend (save-excursion
22780 (goto-char (org-element-property :end element))
22781 (skip-chars-backward " \r\t\n")
22782 (line-beginning-position))))
22783 (when (and (>= p cbeg) (< p cend))
22784 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22785 (match-string 0)
22786 ""))))))))))
22788 (declare-function message-goto-body "message" ())
22789 (defvar message-cite-prefix-regexp) ; From message.el
22790 (defun org-fill-paragraph (&optional justify)
22791 "Fill element at point, when applicable.
22793 This function only applies to comment blocks, comments, example
22794 blocks and paragraphs. Also, as a special case, re-align table
22795 when point is at one.
22797 If JUSTIFY is non-nil (interactively, with prefix argument),
22798 justify as well. If `sentence-end-double-space' is non-nil, then
22799 period followed by one space does not end a sentence, so don't
22800 break a line there. The variable `fill-column' controls the
22801 width for filling.
22803 For convenience, when point is at a plain list, an item or
22804 a footnote definition, try to fill the first paragraph within."
22805 (interactive)
22806 (if (and (derived-mode-p 'message-mode)
22807 (or (not (message-in-body-p))
22808 (save-excursion (move-beginning-of-line 1)
22809 (looking-at message-cite-prefix-regexp))))
22810 ;; First ensure filling is correct in message-mode.
22811 (let ((fill-paragraph-function
22812 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22813 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22814 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22815 (paragraph-separate
22816 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22817 (fill-paragraph nil))
22818 (with-syntax-table org-mode-transpose-word-syntax-table
22819 ;; Move to end of line in order to get the first paragraph
22820 ;; within a plain list or a footnote definition.
22821 (let ((element (save-excursion
22822 (end-of-line)
22823 (or (ignore-errors (org-element-at-point))
22824 (user-error "An element cannot be parsed line %d"
22825 (line-number-at-pos (point)))))))
22826 ;; First check if point is in a blank line at the beginning of
22827 ;; the buffer. In that case, ignore filling.
22828 (case (org-element-type element)
22829 ;; Use major mode filling function is src blocks.
22830 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22831 ;; Align Org tables, leave table.el tables as-is.
22832 (table-row (org-table-align) t)
22833 (table
22834 (when (eq (org-element-property :type element) 'org)
22835 (save-excursion
22836 (goto-char (org-element-property :post-affiliated element))
22837 (org-table-align)))
22839 (paragraph
22840 ;; Paragraphs may contain `line-break' type objects.
22841 (let ((beg (max (point-min)
22842 (org-element-property :contents-begin element)))
22843 (end (min (point-max)
22844 (org-element-property :contents-end element))))
22845 ;; Do nothing if point is at an affiliated keyword.
22846 (if (< (line-end-position) beg) t
22847 (when (derived-mode-p 'message-mode)
22848 ;; In `message-mode', do not fill following citation
22849 ;; in current paragraph nor text before message body.
22850 (let ((body-start (save-excursion (message-goto-body))))
22851 (when body-start (setq beg (max body-start beg))))
22852 (when (save-excursion
22853 (re-search-forward
22854 (concat "^" message-cite-prefix-regexp) end t))
22855 (setq end (match-beginning 0))))
22856 ;; Fill paragraph, taking line breaks into account.
22857 ;; For that, slice the paragraph using line breaks as
22858 ;; separators, and fill the parts in reverse order to
22859 ;; avoid messing with markers.
22860 (save-excursion
22861 (goto-char end)
22862 (mapc
22863 (lambda (pos)
22864 (fill-region-as-paragraph pos (point) justify)
22865 (goto-char pos))
22866 ;; Find the list of ending positions for line breaks
22867 ;; in the current paragraph. Add paragraph
22868 ;; beginning to include first slice.
22869 (nreverse
22870 (cons beg
22871 (org-element-map
22872 (org-element--parse-objects
22873 beg end nil (org-element-restriction 'paragraph))
22874 'line-break
22875 (lambda (lb) (org-element-property :end lb)))))))
22876 t)))
22877 ;; Contents of `comment-block' type elements should be
22878 ;; filled as plain text, but only if point is within block
22879 ;; markers.
22880 (comment-block
22881 (let* ((case-fold-search t)
22882 (beg (save-excursion
22883 (goto-char (org-element-property :begin element))
22884 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22885 (forward-line)
22886 (point)))
22887 (end (save-excursion
22888 (goto-char (org-element-property :end element))
22889 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22890 (line-beginning-position))))
22891 (if (or (< (point) beg) (> (point) end)) t
22892 (fill-region-as-paragraph
22893 (save-excursion (end-of-line)
22894 (re-search-backward "^[ \t]*$" beg 'move)
22895 (line-beginning-position))
22896 (save-excursion (beginning-of-line)
22897 (re-search-forward "^[ \t]*$" end 'move)
22898 (line-beginning-position))
22899 justify))))
22900 ;; Fill comments.
22901 (comment
22902 (let ((begin (org-element-property :post-affiliated element))
22903 (end (org-element-property :end element)))
22904 (when (and (>= (point) begin) (<= (point) end))
22905 (let ((begin (save-excursion
22906 (end-of-line)
22907 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22908 (progn (forward-line) (point))
22909 begin)))
22910 (end (save-excursion
22911 (end-of-line)
22912 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22913 (1- (line-beginning-position))
22914 (skip-chars-backward " \r\t\n")
22915 (line-end-position)))))
22916 ;; Do not fill comments when at a blank line.
22917 (when (> end begin)
22918 (let ((fill-prefix
22919 (save-excursion
22920 (beginning-of-line)
22921 (looking-at "[ \t]*#")
22922 (let ((comment-prefix (match-string 0)))
22923 (goto-char (match-end 0))
22924 (if (looking-at adaptive-fill-regexp)
22925 (concat comment-prefix (match-string 0))
22926 (concat comment-prefix " "))))))
22927 (save-excursion
22928 (fill-region-as-paragraph begin end justify))))))
22930 ;; Ignore every other element.
22931 (otherwise t))))))
22933 (defun org-auto-fill-function ()
22934 "Auto-fill function."
22935 ;; Check if auto-filling is meaningful.
22936 (let ((fc (current-fill-column)))
22937 (when (and fc (> (current-column) fc))
22938 (let* ((fill-prefix (org-adaptive-fill-function))
22939 ;; Enforce empty fill prefix, if required. Otherwise, it
22940 ;; will be computed again.
22941 (adaptive-fill-mode (not (equal fill-prefix ""))))
22942 (when fill-prefix (do-auto-fill))))))
22944 (defun org-comment-line-break-function (&optional soft)
22945 "Break line at point and indent, continuing comment if within one.
22946 The inserted newline is marked hard if variable
22947 `use-hard-newlines' is true, unless optional argument SOFT is
22948 non-nil."
22949 (if soft (insert-and-inherit ?\n) (newline 1))
22950 (save-excursion (forward-char -1) (delete-horizontal-space))
22951 (delete-horizontal-space)
22952 (indent-to-left-margin)
22953 (insert-before-markers-and-inherit fill-prefix))
22956 ;;; Fixed Width Areas
22958 (defun org-toggle-fixed-width ()
22959 "Toggle fixed-width markup.
22961 Add or remove fixed-width markup on current line, whenever it
22962 makes sense. Return an error otherwise.
22964 If a region is active and if it contains only fixed-width areas
22965 or blank lines, remove all fixed-width markup in it. If the
22966 region contains anything else, convert all non-fixed-width lines
22967 to fixed-width ones.
22969 Blank lines at the end of the region are ignored unless the
22970 region only contains such lines."
22971 (interactive)
22972 (if (not (org-region-active-p))
22973 ;; No region:
22975 ;; Remove fixed width marker only in a fixed-with element.
22977 ;; Add fixed width maker in paragraphs, in blank lines after
22978 ;; elements or at the beginning of a headline or an inlinetask,
22979 ;; and before any one-line elements (e.g., a clock).
22980 (progn
22981 (beginning-of-line)
22982 (let* ((element (org-element-at-point))
22983 (type (org-element-type element)))
22984 (cond
22985 ((and (eq type 'fixed-width)
22986 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22987 (replace-match
22988 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22989 ((and (memq type '(babel-call clock comment diary-sexp headline
22990 horizontal-rule keyword paragraph
22991 planning))
22992 (or (not (org-element-property :post-affiliated element))
22993 (<= (org-element-property :post-affiliated element)
22994 (point))))
22995 (skip-chars-forward " \t")
22996 (insert ": "))
22997 ((and (org-looking-at-p "[ \t]*$")
22998 (or (eq type 'inlinetask)
22999 (save-excursion
23000 (skip-chars-forward " \r\t\n")
23001 (<= (org-element-property :end element) (point)))))
23002 (delete-region (point) (line-end-position))
23003 (org-indent-line)
23004 (insert ": "))
23005 (t (user-error "Cannot insert a fixed-width line here")))))
23006 ;; Region active.
23007 (let* ((begin (save-excursion
23008 (goto-char (region-beginning))
23009 (line-beginning-position)))
23010 (end (copy-marker
23011 (save-excursion
23012 (goto-char (region-end))
23013 (unless (eolp) (beginning-of-line))
23014 (if (save-excursion (re-search-backward "\\S-" begin t))
23015 (progn (skip-chars-backward " \r\t\n") (point))
23016 (point)))))
23017 (all-fixed-width-p
23018 (catch 'not-all-p
23019 (save-excursion
23020 (goto-char begin)
23021 (skip-chars-forward " \r\t\n")
23022 (when (eobp) (throw 'not-all-p nil))
23023 (while (< (point) end)
23024 (let ((element (org-element-at-point)))
23025 (if (eq (org-element-type element) 'fixed-width)
23026 (goto-char (org-element-property :end element))
23027 (throw 'not-all-p nil))))
23028 t))))
23029 (if all-fixed-width-p
23030 (save-excursion
23031 (goto-char begin)
23032 (while (< (point) end)
23033 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23034 (replace-match
23035 "" nil nil nil
23036 (if (= (line-end-position) (match-end 0)) 0 1)))
23037 (forward-line)))
23038 (let ((min-ind (point-max)))
23039 ;; Find minimum indentation across all lines.
23040 (save-excursion
23041 (goto-char begin)
23042 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23043 (setq min-ind 0)
23044 (catch 'zerop
23045 (while (< (point) end)
23046 (unless (org-looking-at-p "[ \t]*$")
23047 (let ((ind (org-get-indentation)))
23048 (setq min-ind (min min-ind ind))
23049 (when (zerop ind) (throw 'zerop t))))
23050 (forward-line)))))
23051 ;; Loop over all lines and add fixed-width markup everywhere
23052 ;; but in fixed-width lines.
23053 (save-excursion
23054 (goto-char begin)
23055 (while (< (point) end)
23056 (cond
23057 ((org-at-heading-p)
23058 (insert ": ")
23059 (forward-line)
23060 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23061 (insert ":")
23062 (forward-line)))
23063 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23064 (let* ((element (org-element-at-point))
23065 (element-end (org-element-property :end element)))
23066 (if (eq (org-element-type element) 'fixed-width)
23067 (progn (goto-char element-end)
23068 (skip-chars-backward " \r\t\n")
23069 (forward-line))
23070 (let ((limit (min end element-end)))
23071 (while (< (point) limit)
23072 (org-move-to-column min-ind t)
23073 (insert ": ")
23074 (forward-line))))))
23076 (org-move-to-column min-ind t)
23077 (insert ": ")
23078 (forward-line)))))))
23079 (set-marker end nil))))
23082 ;;; Comments
23084 ;; Org comments syntax is quite complex. It requires the entire line
23085 ;; to be just a comment. Also, even with the right syntax at the
23086 ;; beginning of line, some some elements (i.e. verse-block or
23087 ;; example-block) don't accept comments. Usual Emacs comment commands
23088 ;; cannot cope with those requirements. Therefore, Org replaces them.
23090 ;; Org still relies on `comment-dwim', but cannot trust
23091 ;; `comment-only-p'. So, `comment-region-function' and
23092 ;; `uncomment-region-function' both point
23093 ;; to`org-comment-or-uncomment-region'. Eventually,
23094 ;; `org-insert-comment' takes care of insertion of comments at the
23095 ;; beginning of line.
23097 ;; `org-setup-comments-handling' install comments related variables
23098 ;; during `org-mode' initialization.
23100 (defun org-setup-comments-handling ()
23101 (interactive)
23102 (org-set-local 'comment-use-syntax nil)
23103 (org-set-local 'comment-start "# ")
23104 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23105 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23106 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23107 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23109 (defun org-insert-comment ()
23110 "Insert an empty comment above current line.
23111 If the line is empty, insert comment at its beginning. When
23112 point is within a source block, comment according to the related
23113 major mode."
23114 (if (let ((element (org-element-at-point)))
23115 (and (eq (org-element-type element) 'src-block)
23116 (< (save-excursion
23117 (goto-char (org-element-property :post-affiliated element))
23118 (line-end-position))
23119 (point))
23120 (> (save-excursion
23121 (goto-char (org-element-property :end element))
23122 (skip-chars-backward " \r\t\n")
23123 (line-beginning-position))
23124 (point))))
23125 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23126 (beginning-of-line)
23127 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23128 (open-line 1))
23129 (org-indent-line)
23130 (insert "# ")))
23132 (defvar comment-empty-lines) ; From newcomment.el.
23133 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23134 "Comment or uncomment each non-blank line in the region.
23135 Uncomment each non-blank line between BEG and END if it only
23136 contains commented lines. Otherwise, comment them. If region is
23137 strictly within a source block, use appropriate comment syntax."
23138 (if (let ((element (org-element-at-point)))
23139 (and (eq (org-element-type element) 'src-block)
23140 (< (save-excursion
23141 (goto-char (org-element-property :post-affiliated element))
23142 (line-end-position))
23143 beg)
23144 (>= (save-excursion
23145 (goto-char (org-element-property :end element))
23146 (skip-chars-backward " \r\t\n")
23147 (line-beginning-position))
23148 end)))
23149 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23150 (save-restriction
23151 ;; Restrict region
23152 (narrow-to-region (save-excursion (goto-char beg)
23153 (skip-chars-forward " \r\t\n" end)
23154 (line-beginning-position))
23155 (save-excursion (goto-char end)
23156 (skip-chars-backward " \r\t\n" beg)
23157 (line-end-position)))
23158 (let ((uncommentp
23159 ;; UNCOMMENTP is non-nil when every non blank line between
23160 ;; BEG and END is a comment.
23161 (save-excursion
23162 (goto-char (point-min))
23163 (while (and (not (eobp))
23164 (let ((element (org-element-at-point)))
23165 (and (eq (org-element-type element) 'comment)
23166 (goto-char (min (point-max)
23167 (org-element-property
23168 :end element)))))))
23169 (eobp))))
23170 (if uncommentp
23171 ;; Only blank lines and comments in region: uncomment it.
23172 (save-excursion
23173 (goto-char (point-min))
23174 (while (not (eobp))
23175 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23176 (replace-match "" nil nil nil 1))
23177 (forward-line)))
23178 ;; Comment each line in region.
23179 (let ((min-indent (point-max)))
23180 ;; First find the minimum indentation across all lines.
23181 (save-excursion
23182 (goto-char (point-min))
23183 (while (and (not (eobp)) (not (zerop min-indent)))
23184 (unless (looking-at "[ \t]*$")
23185 (setq min-indent (min min-indent (current-indentation))))
23186 (forward-line)))
23187 ;; Then loop over all lines.
23188 (save-excursion
23189 (goto-char (point-min))
23190 (while (not (eobp))
23191 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23192 ;; Don't get fooled by invisible text (e.g. link path)
23193 ;; when moving to column MIN-INDENT.
23194 (let ((buffer-invisibility-spec nil))
23195 (org-move-to-column min-indent t))
23196 (insert comment-start))
23197 (forward-line)))))))))
23199 (defun org-comment-dwim (arg)
23200 (interactive "*P")
23201 "Call `comment-dwim' within a source edit buffer if needed."
23202 (if (org-in-src-block-p)
23203 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23204 (call-interactively 'comment-dwim)))
23207 ;;; Planning
23209 ;; This section contains tools to operate on timestamp objects, as
23210 ;; returned by, e.g. `org-element-context'.
23212 (defun org-timestamp-has-time-p (timestamp)
23213 "Non-nil when TIMESTAMP has a time specified."
23214 (org-element-property :hour-start timestamp))
23216 (defun org-timestamp-format (timestamp format &optional end utc)
23217 "Format a TIMESTAMP element into a string.
23219 FORMAT is a format specifier to be passed to
23220 `format-time-string'.
23222 When optional argument END is non-nil, use end of date-range or
23223 time-range, if possible.
23225 When optional argument UTC is non-nil, time will be expressed as
23226 Universal Time."
23227 (format-time-string
23228 format
23229 (apply 'encode-time
23230 (cons 0
23231 (mapcar
23232 (lambda (prop) (or (org-element-property prop timestamp) 0))
23233 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23234 '(:minute-start :hour-start :day-start :month-start
23235 :year-start)))))
23236 utc))
23238 (defun org-timestamp-split-range (timestamp &optional end)
23239 "Extract a timestamp object from a date or time range.
23241 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23242 the end of the range. Otherwise, extract its start.
23244 Return a new timestamp object sharing the same parent as
23245 TIMESTAMP."
23246 (let ((type (org-element-property :type timestamp)))
23247 (if (memq type '(active inactive diary)) timestamp
23248 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23249 ;; Set new type.
23250 (org-element-put-property
23251 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23252 ;; Copy start properties over end properties if END is
23253 ;; non-nil. Otherwise, copy end properties over `start' ones.
23254 (let ((p-alist '((:minute-start . :minute-end)
23255 (:hour-start . :hour-end)
23256 (:day-start . :day-end)
23257 (:month-start . :month-end)
23258 (:year-start . :year-end))))
23259 (dolist (p-cell p-alist)
23260 (org-element-put-property
23261 split-ts
23262 (funcall (if end 'car 'cdr) p-cell)
23263 (org-element-property
23264 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23265 ;; Eventually refresh `:raw-value'.
23266 (org-element-put-property split-ts :raw-value nil)
23267 (org-element-put-property
23268 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23270 (defun org-timestamp-translate (timestamp &optional boundary)
23271 "Apply `org-translate-time' on a TIMESTAMP object.
23272 When optional argument BOUNDARY is non-nil, it is either the
23273 symbol `start' or `end'. In this case, only translate the
23274 starting or ending part of TIMESTAMP if it is a date or time
23275 range. Otherwise, translate both parts."
23276 (if (and (not boundary)
23277 (memq (org-element-property :type timestamp)
23278 '(active-range inactive-range)))
23279 (concat
23280 (org-translate-time
23281 (org-element-property :raw-value
23282 (org-timestamp-split-range timestamp)))
23283 "--"
23284 (org-translate-time
23285 (org-element-property :raw-value
23286 (org-timestamp-split-range timestamp t))))
23287 (org-translate-time
23288 (org-element-property
23289 :raw-value
23290 (if (not boundary) timestamp
23291 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23295 ;;; Other stuff.
23297 (defun org-reftex-citation ()
23298 "Use reftex-citation to insert a citation into the buffer.
23299 This looks for a line like
23301 #+BIBLIOGRAPHY: foo plain option:-d
23303 and derives from it that foo.bib is the bibliography file relevant
23304 for this document. It then installs the necessary environment for RefTeX
23305 to work in this buffer and calls `reftex-citation' to insert a citation
23306 into the buffer.
23308 Export of such citations to both LaTeX and HTML is handled by the contributed
23309 package ox-bibtex by Taru Karttunen."
23310 (interactive)
23311 (let ((reftex-docstruct-symbol 'rds)
23312 (reftex-cite-format "\\cite{%l}")
23313 rds bib)
23314 (save-excursion
23315 (save-restriction
23316 (widen)
23317 (let ((case-fold-search t)
23318 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23319 (if (not (save-excursion
23320 (or (re-search-forward re nil t)
23321 (re-search-backward re nil t))))
23322 (user-error "No bibliography defined in file")
23323 (setq bib (concat (match-string 1) ".bib")
23324 rds (list (list 'bib bib)))))))
23325 (call-interactively 'reftex-citation)))
23327 ;;;; Functions extending outline functionality
23329 (defun org-beginning-of-line (&optional arg)
23330 "Go to the beginning of the current line. If that is invisible, continue
23331 to a visible line beginning. This makes the function of C-a more intuitive.
23332 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23333 first attempt, and only move to after the tags when the cursor is already
23334 beyond the end of the headline."
23335 (interactive "P")
23336 (let ((pos (point))
23337 (special (if (consp org-special-ctrl-a/e)
23338 (car org-special-ctrl-a/e)
23339 org-special-ctrl-a/e))
23340 deactivate-mark refpos)
23341 (if (org-bound-and-true-p visual-line-mode)
23342 (beginning-of-visual-line 1)
23343 (beginning-of-line 1))
23344 (if (and arg (fboundp 'move-beginning-of-line))
23345 (call-interactively 'move-beginning-of-line)
23346 (if (bobp)
23348 (backward-char 1)
23349 (if (org-truely-invisible-p)
23350 (while (and (not (bobp)) (org-truely-invisible-p))
23351 (backward-char 1)
23352 (beginning-of-line 1))
23353 (forward-char 1))))
23354 (when special
23355 (cond
23356 ((and (looking-at org-complex-heading-regexp)
23357 (= (char-after (match-end 1)) ?\ ))
23358 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23359 (point-at-eol)))
23360 (goto-char
23361 (if (eq special t)
23362 (cond ((> pos refpos) refpos)
23363 ((= pos (point)) refpos)
23364 (t (point)))
23365 (cond ((> pos (point)) (point))
23366 ((not (eq last-command this-command)) (point))
23367 (t refpos)))))
23368 ((org-at-item-p)
23369 ;; Being at an item and not looking at an the item means point
23370 ;; was previously moved to beginning of a visual line, which
23371 ;; doesn't contain the item. Therefore, do nothing special,
23372 ;; just stay here.
23373 (when (looking-at org-list-full-item-re)
23374 ;; Set special position at first white space character after
23375 ;; bullet, and check-box, if any.
23376 (let ((after-bullet
23377 (let ((box (match-end 3)))
23378 (if (not box) (match-end 1)
23379 (let ((after (char-after box)))
23380 (if (and after (= after ? )) (1+ box) box))))))
23381 ;; Special case: Move point to special position when
23382 ;; currently after it or at beginning of line.
23383 (if (eq special t)
23384 (when (or (> pos after-bullet) (= (point) pos))
23385 (goto-char after-bullet))
23386 ;; Reversed case: Move point to special position when
23387 ;; point was already at beginning of line and command is
23388 ;; repeated.
23389 (when (and (= (point) pos) (eq last-command this-command))
23390 (goto-char after-bullet))))))))
23391 (org-no-warnings
23392 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23393 (setq disable-point-adjustment
23394 (or (not (invisible-p (point)))
23395 (not (invisible-p (max (point-min) (1- (point))))))))
23397 (defun org-end-of-line (&optional arg)
23398 "Go to the end of the line.
23399 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23400 tags on the first attempt, and only move to after the tags when
23401 the cursor is already beyond the end of the headline."
23402 (interactive "P")
23403 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23404 org-special-ctrl-a/e))
23405 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23406 'end-of-visual-line)
23407 ((fboundp 'move-end-of-line) 'move-end-of-line)
23408 (t 'end-of-line)))
23409 deactivate-mark)
23410 (if (or (not special) arg) (call-interactively move-fun)
23411 (let* ((element (save-excursion (beginning-of-line)
23412 (org-element-at-point)))
23413 (type (org-element-type element)))
23414 (cond
23415 ((memq type '(headline inlinetask))
23416 (let ((pos (point)))
23417 (beginning-of-line 1)
23418 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23419 (if (eq special t)
23420 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23421 (goto-char (match-beginning 1))
23422 (goto-char (match-end 0)))
23423 (if (or (< pos (match-end 0))
23424 (not (eq this-command last-command)))
23425 (goto-char (match-end 0))
23426 (goto-char (match-beginning 1))))
23427 (call-interactively move-fun))))
23428 ((outline-invisible-p (line-end-position))
23429 ;; If element is hidden, `move-end-of-line' would put point
23430 ;; after it. Use `end-of-line' to stay on current line.
23431 (call-interactively 'end-of-line))
23432 (t (call-interactively move-fun)))))
23433 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23434 (setq disable-point-adjustment
23435 (or (not (invisible-p (point)))
23436 (not (invisible-p (max (point-min) (1- (point))))))))
23438 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23439 (define-key org-mode-map "\C-e" 'org-end-of-line)
23441 (defun org-backward-sentence (&optional arg)
23442 "Go to beginning of sentence, or beginning of table field.
23443 This will call `backward-sentence' or `org-table-beginning-of-field',
23444 depending on context."
23445 (interactive "P")
23446 (cond
23447 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23448 (t (call-interactively 'backward-sentence))))
23450 (defun org-forward-sentence (&optional arg)
23451 "Go to end of sentence, or end of table field.
23452 This will call `forward-sentence' or `org-table-end-of-field',
23453 depending on context."
23454 (interactive "P")
23455 (cond
23456 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23457 (t (call-interactively 'forward-sentence))))
23459 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23460 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23462 (defun org-kill-line (&optional arg)
23463 "Kill line, to tags or end of line."
23464 (interactive "P")
23465 (cond
23466 ((or (not org-special-ctrl-k)
23467 (bolp)
23468 (not (org-at-heading-p)))
23469 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23470 org-ctrl-k-protect-subtree)
23471 (if (or (eq org-ctrl-k-protect-subtree 'error)
23472 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23473 (user-error "C-k aborted as it would kill a hidden subtree")))
23474 (call-interactively
23475 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23476 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23477 (kill-region (point) (match-beginning 1))
23478 (org-set-tags nil t))
23479 (t (kill-region (point) (point-at-eol)))))
23481 (define-key org-mode-map "\C-k" 'org-kill-line)
23483 (defun org-yank (&optional arg)
23484 "Yank. If the kill is a subtree, treat it specially.
23485 This command will look at the current kill and check if is a single
23486 subtree, or a series of subtrees[1]. If it passes the test, and if the
23487 cursor is at the beginning of a line or after the stars of a currently
23488 empty headline, then the yank is handled specially. How exactly depends
23489 on the value of the following variables, both set by default.
23491 org-yank-folded-subtrees
23492 When set, the subtree(s) will be folded after insertion, but only
23493 if doing so would now swallow text after the yanked text.
23495 org-yank-adjusted-subtrees
23496 When set, the subtree will be promoted or demoted in order to
23497 fit into the local outline tree structure, which means that the level
23498 will be adjusted so that it becomes the smaller one of the two
23499 *visible* surrounding headings.
23501 Any prefix to this command will cause `yank' to be called directly with
23502 no special treatment. In particular, a simple \\[universal-argument] prefix \
23503 will just
23504 plainly yank the text as it is.
23506 \[1] The test checks if the first non-white line is a heading
23507 and if there are no other headings with fewer stars."
23508 (interactive "P")
23509 (org-yank-generic 'yank arg))
23511 (defun org-yank-generic (command arg)
23512 "Perform some yank-like command.
23514 This function implements the behavior described in the `org-yank'
23515 documentation. However, it has been generalized to work for any
23516 interactive command with similar behavior."
23518 ;; pretend to be command COMMAND
23519 (setq this-command command)
23521 (if arg
23522 (call-interactively command)
23524 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23525 (and (org-kill-is-subtree-p)
23526 (or (bolp)
23527 (and (looking-at "[ \t]*$")
23528 (string-match
23529 "\\`\\*+\\'"
23530 (buffer-substring (point-at-bol) (point)))))))
23531 swallowp)
23532 (cond
23533 ((and subtreep org-yank-folded-subtrees)
23534 (let ((beg (point))
23535 end)
23536 (if (and subtreep org-yank-adjusted-subtrees)
23537 (org-paste-subtree nil nil 'for-yank)
23538 (call-interactively command))
23540 (setq end (point))
23541 (goto-char beg)
23542 (when (and (bolp) subtreep
23543 (not (setq swallowp
23544 (org-yank-folding-would-swallow-text beg end))))
23545 (org-with-limited-levels
23546 (or (looking-at org-outline-regexp)
23547 (re-search-forward org-outline-regexp-bol end t))
23548 (while (and (< (point) end) (looking-at org-outline-regexp))
23549 (hide-subtree)
23550 (org-cycle-show-empty-lines 'folded)
23551 (condition-case nil
23552 (outline-forward-same-level 1)
23553 (error (goto-char end))))))
23554 (when swallowp
23555 (message
23556 "Inserted text not folded because that would swallow text"))
23558 (goto-char end)
23559 (skip-chars-forward " \t\n\r")
23560 (beginning-of-line 1)
23561 (push-mark beg 'nomsg)))
23562 ((and subtreep org-yank-adjusted-subtrees)
23563 (let ((beg (point-at-bol)))
23564 (org-paste-subtree nil nil 'for-yank)
23565 (push-mark beg 'nomsg)))
23567 (call-interactively command))))))
23569 (defun org-yank-folding-would-swallow-text (beg end)
23570 "Would hide-subtree at BEG swallow any text after END?"
23571 (let (level)
23572 (org-with-limited-levels
23573 (save-excursion
23574 (goto-char beg)
23575 (when (or (looking-at org-outline-regexp)
23576 (re-search-forward org-outline-regexp-bol end t))
23577 (setq level (org-outline-level)))
23578 (goto-char end)
23579 (skip-chars-forward " \t\r\n\v\f")
23580 (if (or (eobp)
23581 (and (bolp) (looking-at org-outline-regexp)
23582 (<= (org-outline-level) level)))
23583 nil ; Nothing would be swallowed
23584 t))))) ; something would swallow
23586 (define-key org-mode-map "\C-y" 'org-yank)
23588 (defun org-truely-invisible-p ()
23589 "Check if point is at a character currently not visible.
23590 This version does not only check the character property, but also
23591 `visible-mode'."
23592 ;; Early versions of noutline don't have `outline-invisible-p'.
23593 (if (org-bound-and-true-p visible-mode)
23595 (outline-invisible-p)))
23597 (defun org-invisible-p2 ()
23598 "Check if point is at a character currently not visible."
23599 (save-excursion
23600 (if (and (eolp) (not (bobp))) (backward-char 1))
23601 ;; Early versions of noutline don't have `outline-invisible-p'.
23602 (outline-invisible-p)))
23604 (defun org-back-to-heading (&optional invisible-ok)
23605 "Call `outline-back-to-heading', but provide a better error message."
23606 (condition-case nil
23607 (outline-back-to-heading invisible-ok)
23608 (error (error "Before first headline at position %d in buffer %s"
23609 (point) (current-buffer)))))
23611 (defun org-before-first-heading-p ()
23612 "Before first heading?"
23613 (save-excursion
23614 (end-of-line)
23615 (null (re-search-backward org-outline-regexp-bol nil t))))
23617 (defun org-at-heading-p (&optional ignored)
23618 (outline-on-heading-p t))
23619 ;; Compatibility alias with Org versions < 7.8.03
23620 (defalias 'org-on-heading-p 'org-at-heading-p)
23622 (defun org-in-commented-heading-p (&optional no-inheritance)
23623 "Non-nil if point is under a commented heading.
23624 This function also checks ancestors of the current headline,
23625 unless optional argument NO-INHERITANCE is non-nil."
23626 (cond
23627 ((org-before-first-heading-p) nil)
23628 ((let ((headline (nth 4 (org-heading-components))))
23629 (and headline
23630 (let ((case-fold-search nil))
23631 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23632 headline)))))
23633 (no-inheritance nil)
23635 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23637 (defun org-at-comment-p nil
23638 "Is cursor in a commented line?"
23639 (save-excursion
23640 (save-match-data
23641 (beginning-of-line)
23642 (looking-at "^[ \t]*# "))))
23644 (defun org-at-drawer-p nil
23645 "Is cursor at a drawer keyword?"
23646 (save-excursion
23647 (move-beginning-of-line 1)
23648 (looking-at org-drawer-regexp)))
23650 (defun org-at-block-p nil
23651 "Is cursor at a block keyword?"
23652 (save-excursion
23653 (move-beginning-of-line 1)
23654 (looking-at org-block-regexp)))
23656 (defun org-point-at-end-of-empty-headline ()
23657 "If point is at the end of an empty headline, return t, else nil.
23658 If the heading only contains a TODO keyword, it is still still considered
23659 empty."
23660 (and (looking-at "[ \t]*$")
23661 (when org-todo-line-regexp
23662 (save-excursion
23663 (beginning-of-line 1)
23664 (let ((case-fold-search nil))
23665 (looking-at org-todo-line-regexp)
23666 (string= (match-string 3) ""))))))
23668 (defun org-at-heading-or-item-p ()
23669 (or (org-at-heading-p) (org-at-item-p)))
23671 (defun org-at-target-p ()
23672 (or (org-in-regexp org-radio-target-regexp)
23673 (org-in-regexp org-target-regexp)))
23674 ;; Compatibility alias with Org versions < 7.8.03
23675 (defalias 'org-on-target-p 'org-at-target-p)
23677 (defun org-up-heading-all (arg)
23678 "Move to the heading line of which the present line is a subheading.
23679 This function considers both visible and invisible heading lines.
23680 With argument, move up ARG levels."
23681 (if (fboundp 'outline-up-heading-all)
23682 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23683 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23685 (defun org-up-heading-safe ()
23686 "Move to the heading line of which the present line is a subheading.
23687 This version will not throw an error. It will return the level of the
23688 headline found, or nil if no higher level is found.
23690 Also, this function will be a lot faster than `outline-up-heading',
23691 because it relies on stars being the outline starters. This can really
23692 make a significant difference in outlines with very many siblings."
23693 (let (start-level re)
23694 (org-back-to-heading t)
23695 (setq start-level (funcall outline-level))
23696 (if (equal start-level 1)
23698 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23699 (if (re-search-backward re nil t)
23700 (funcall outline-level)))))
23702 (defun org-first-sibling-p ()
23703 "Is this heading the first child of its parents?"
23704 (interactive)
23705 (let ((re org-outline-regexp-bol)
23706 level l)
23707 (unless (org-at-heading-p t)
23708 (user-error "Not at a heading"))
23709 (setq level (funcall outline-level))
23710 (save-excursion
23711 (if (not (re-search-backward re nil t))
23713 (setq l (funcall outline-level))
23714 (< l level)))))
23716 (defun org-goto-sibling (&optional previous)
23717 "Goto the next sibling, even if it is invisible.
23718 When PREVIOUS is set, go to the previous sibling instead. Returns t
23719 when a sibling was found. When none is found, return nil and don't
23720 move point."
23721 (let ((fun (if previous 're-search-backward 're-search-forward))
23722 (pos (point))
23723 (re org-outline-regexp-bol)
23724 level l)
23725 (when (ignore-errors (org-back-to-heading t))
23726 (setq level (funcall outline-level))
23727 (catch 'exit
23728 (or previous (forward-char 1))
23729 (while (funcall fun re nil t)
23730 (setq l (funcall outline-level))
23731 (when (< l level) (goto-char pos) (throw 'exit nil))
23732 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23733 (goto-char pos)
23734 nil))))
23736 (defun org-show-siblings ()
23737 "Show all siblings of the current headline."
23738 (save-excursion
23739 (while (org-goto-sibling) (org-flag-heading nil)))
23740 (save-excursion
23741 (while (org-goto-sibling 'previous)
23742 (org-flag-heading nil))))
23744 (defun org-goto-first-child ()
23745 "Goto the first child, even if it is invisible.
23746 Return t when a child was found. Otherwise don't move point and
23747 return nil."
23748 (let (level (pos (point)) (re org-outline-regexp-bol))
23749 (when (ignore-errors (org-back-to-heading t))
23750 (setq level (outline-level))
23751 (forward-char 1)
23752 (if (and (re-search-forward re nil t) (> (outline-level) level))
23753 (progn (goto-char (match-beginning 0)) t)
23754 (goto-char pos) nil))))
23756 (defun org-show-hidden-entry ()
23757 "Show an entry where even the heading is hidden."
23758 (save-excursion
23759 (org-show-entry)))
23761 (defun org-flag-heading (flag &optional entry)
23762 "Flag the current heading. FLAG non-nil means make invisible.
23763 When ENTRY is non-nil, show the entire entry."
23764 (save-excursion
23765 (org-back-to-heading t)
23766 ;; Check if we should show the entire entry
23767 (if entry
23768 (progn
23769 (org-show-entry)
23770 (save-excursion
23771 (and (outline-next-heading)
23772 (org-flag-heading nil))))
23773 (outline-flag-region (max (point-min) (1- (point)))
23774 (save-excursion (outline-end-of-heading) (point))
23775 flag))))
23777 (defun org-get-next-sibling ()
23778 "Move to next heading of the same level, and return point.
23779 If there is no such heading, return nil.
23780 This is like outline-next-sibling, but invisible headings are ok."
23781 (let ((level (funcall outline-level)))
23782 (outline-next-heading)
23783 (while (and (not (eobp)) (> (funcall outline-level) level))
23784 (outline-next-heading))
23785 (if (or (eobp) (< (funcall outline-level) level))
23787 (point))))
23789 (defun org-get-last-sibling ()
23790 "Move to previous heading of the same level, and return point.
23791 If there is no such heading, return nil."
23792 (let ((opoint (point))
23793 (level (funcall outline-level)))
23794 (outline-previous-heading)
23795 (when (and (/= (point) opoint) (outline-on-heading-p t))
23796 (while (and (> (funcall outline-level) level)
23797 (not (bobp)))
23798 (outline-previous-heading))
23799 (if (< (funcall outline-level) level)
23801 (point)))))
23803 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23804 "Goto to the end of a subtree."
23805 ;; This contains an exact copy of the original function, but it uses
23806 ;; `org-back-to-heading', to make it work also in invisible
23807 ;; trees. And is uses an invisible-ok argument.
23808 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23809 ;; Furthermore, when used inside Org, finding the end of a large subtree
23810 ;; with many children and grandchildren etc, this can be much faster
23811 ;; than the outline version.
23812 (org-back-to-heading invisible-ok)
23813 (let ((first t)
23814 (level (funcall outline-level)))
23815 (if (and (derived-mode-p 'org-mode) (< level 1000))
23816 ;; A true heading (not a plain list item), in Org-mode
23817 ;; This means we can easily find the end by looking
23818 ;; only for the right number of stars. Using a regexp to do
23819 ;; this is so much faster than using a Lisp loop.
23820 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23821 (forward-char 1)
23822 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23823 ;; something else, do it the slow way
23824 (while (and (not (eobp))
23825 (or first (> (funcall outline-level) level)))
23826 (setq first nil)
23827 (outline-next-heading)))
23828 (unless to-heading
23829 (if (memq (preceding-char) '(?\n ?\^M))
23830 (progn
23831 ;; Go to end of line before heading
23832 (forward-char -1)
23833 (if (memq (preceding-char) '(?\n ?\^M))
23834 ;; leave blank line before heading
23835 (forward-char -1))))))
23836 (point))
23838 (defun org-end-of-meta-data-and-drawers ()
23839 "Jump to the first text after meta data and drawers in the current entry.
23840 This will move over empty lines, lines with planning time stamps,
23841 clocking lines, and drawers."
23842 (org-back-to-heading t)
23843 (let ((end (save-excursion (outline-next-heading) (point)))
23844 (re (concat "\\(" org-drawer-regexp "\\)"
23845 "\\|" "[ \t]*" org-keyword-time-regexp)))
23846 (forward-line 1)
23847 (while (re-search-forward re end t)
23848 (if (not (match-end 1))
23849 ;; empty or planning line
23850 (forward-line 1)
23851 ;; a drawer, find the end
23852 (re-search-forward "^[ \t]*:END:" end 'move)
23853 (forward-line 1)))
23854 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23855 (point)))
23857 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23858 "Move forward to the ARG'th subheading at same level as this one.
23859 Stop at the first and last subheadings of a superior heading.
23860 Normally this only looks at visible headings, but when INVISIBLE-OK is
23861 non-nil it will also look at invisible ones."
23862 (interactive "p")
23863 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23864 (if (and arg (< arg 0))
23865 (goto-char (point-min))
23866 (outline-next-heading))
23867 (org-at-heading-p)
23868 (let ((level (- (match-end 0) (match-beginning 0) 1))
23869 (f (if (and arg (< arg 0))
23870 're-search-backward
23871 're-search-forward))
23872 (count (if arg (abs arg) 1))
23873 (result (point)))
23874 (while (and (prog1 (> count 0)
23875 (forward-char (if (and arg (< arg 0)) -1 1)))
23876 (funcall f org-outline-regexp-bol nil 'move))
23877 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23878 (cond ((< l level) (setq count 0))
23879 ((and (= l level)
23880 (or invisible-ok
23881 (progn
23882 (goto-char (line-beginning-position))
23883 (not (outline-invisible-p)))))
23884 (setq count (1- count))
23885 (when (eq l level)
23886 (setq result (point)))))))
23887 (goto-char result))
23888 (beginning-of-line 1)))
23890 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23891 "Move backward to the ARG'th subheading at same level as this one.
23892 Stop at the first and last subheadings of a superior heading."
23893 (interactive "p")
23894 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23896 (defun org-next-block (arg &optional backward block-regexp)
23897 "Jump to the next block.
23898 With a prefix argument ARG, jump forward ARG many source blocks.
23899 When BACKWARD is non-nil, jump to the previous block.
23900 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23901 (interactive "p")
23902 (let ((re (or block-regexp org-block-regexp))
23903 (re-search-fn (or (and backward 're-search-backward)
23904 're-search-forward)))
23905 (if (looking-at re) (forward-char 1))
23906 (condition-case nil
23907 (funcall re-search-fn re nil nil arg)
23908 (error (user-error "No %s code blocks"
23909 (if backward "previous" "further" ))))
23910 (goto-char (match-beginning 0)) (org-show-context)))
23912 (defun org-previous-block (arg &optional block-regexp)
23913 "Jump to the previous block.
23914 With a prefix argument ARG, jump backward ARG many source blocks.
23915 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23916 (interactive "p")
23917 (org-next-block arg t block-regexp))
23919 (defun org-forward-paragraph ()
23920 "Move forward to beginning of next paragraph or equivalent.
23922 The function moves point to the beginning of the next visible
23923 structural element, which can be a paragraph, a table, a list
23924 item, etc. It also provides some special moves for convenience:
23926 - On an affiliated keyword, jump to the beginning of the
23927 relative element.
23928 - On an item or a footnote definition, move to the second
23929 element inside, if any.
23930 - On a table or a property drawer, jump after it.
23931 - On a verse or source block, stop after blank lines."
23932 (interactive)
23933 (when (eobp) (user-error "Cannot move further down"))
23934 (let* ((deactivate-mark nil)
23935 (element (org-element-at-point))
23936 (type (org-element-type element))
23937 (post-affiliated (org-element-property :post-affiliated element))
23938 (contents-begin (org-element-property :contents-begin element))
23939 (contents-end (org-element-property :contents-end element))
23940 (end (let ((end (org-element-property :end element)) (parent element))
23941 (while (and (setq parent (org-element-property :parent parent))
23942 (= (org-element-property :contents-end parent) end))
23943 (setq end (org-element-property :end parent)))
23944 end)))
23945 (cond ((not element)
23946 (skip-chars-forward " \r\t\n")
23947 (or (eobp) (beginning-of-line)))
23948 ;; On affiliated keywords, move to element's beginning.
23949 ((and post-affiliated (< (point) post-affiliated))
23950 (goto-char post-affiliated))
23951 ;; At a table row, move to the end of the table. Similarly,
23952 ;; at a node property, move to the end of the property
23953 ;; drawer.
23954 ((memq type '(node-property table-row))
23955 (goto-char (org-element-property
23956 :end (org-element-property :parent element))))
23957 ((memq type '(property-drawer table)) (goto-char end))
23958 ;; Consider blank lines as separators in verse and source
23959 ;; blocks to ease editing.
23960 ((memq type '(src-block verse-block))
23961 (when (eq type 'src-block)
23962 (setq contents-end
23963 (save-excursion (goto-char end)
23964 (skip-chars-backward " \r\t\n")
23965 (line-beginning-position))))
23966 (beginning-of-line)
23967 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23968 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23969 (goto-char end)
23970 (skip-chars-forward " \r\t\n")
23971 (if (= (point) contents-end) (goto-char end)
23972 (beginning-of-line))))
23973 ;; With no contents, just skip element.
23974 ((not contents-begin) (goto-char end))
23975 ;; If contents are invisible, skip the element altogether.
23976 ((outline-invisible-p (line-end-position))
23977 (case type
23978 (headline
23979 (org-with-limited-levels (outline-next-visible-heading 1)))
23980 ;; At a plain list, make sure we move to the next item
23981 ;; instead of skipping the whole list.
23982 (plain-list (forward-char)
23983 (org-forward-paragraph))
23984 (otherwise (goto-char end))))
23985 ((>= (point) contents-end) (goto-char end))
23986 ((>= (point) contents-begin)
23987 ;; This can only happen on paragraphs and plain lists.
23988 (case type
23989 (paragraph (goto-char end))
23990 ;; At a plain list, try to move to second element in
23991 ;; first item, if possible.
23992 (plain-list (end-of-line)
23993 (org-forward-paragraph))))
23994 ;; When contents start on the middle of a line (e.g. in
23995 ;; items and footnote definitions), try to reach first
23996 ;; element starting after current line.
23997 ((> (line-end-position) contents-begin)
23998 (end-of-line)
23999 (org-forward-paragraph))
24000 (t (goto-char contents-begin)))))
24002 (defun org-backward-paragraph ()
24003 "Move backward to start of previous paragraph or equivalent.
24005 The function moves point to the beginning of the current
24006 structural element, which can be a paragraph, a table, a list
24007 item, etc., or to the beginning of the previous visible one if
24008 point is already there. It also provides some special moves for
24009 convenience:
24011 - On an affiliated keyword, jump to the first one.
24012 - On a table or a property drawer, move to its beginning.
24013 - On a verse or source block, stop before blank lines."
24014 (interactive)
24015 (when (bobp) (user-error "Cannot move further up"))
24016 (let* ((deactivate-mark nil)
24017 (element (org-element-at-point))
24018 (type (org-element-type element))
24019 (contents-begin (org-element-property :contents-begin element))
24020 (contents-end (org-element-property :contents-end element))
24021 (post-affiliated (org-element-property :post-affiliated element))
24022 (begin (org-element-property :begin element)))
24023 (cond
24024 ((not element) (goto-char (point-min)))
24025 ((= (point) begin)
24026 (backward-char)
24027 (org-backward-paragraph))
24028 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
24029 ((memq type '(node-property table-row))
24030 (goto-char (org-element-property
24031 :post-affiliated (org-element-property :parent element))))
24032 ((memq type '(property-drawer table)) (goto-char begin))
24033 ((memq type '(src-block verse-block))
24034 (when (eq type 'src-block)
24035 (setq contents-begin
24036 (save-excursion (goto-char begin) (forward-line) (point))))
24037 (if (= (point) contents-begin) (goto-char post-affiliated)
24038 ;; Inside a verse block, see blank lines as paragraph
24039 ;; separators.
24040 (let ((origin (point)))
24041 (skip-chars-backward " \r\t\n" contents-begin)
24042 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24043 (skip-chars-forward " \r\t\n" origin)
24044 (if (= (point) origin) (goto-char contents-begin)
24045 (beginning-of-line))))))
24046 ((not contents-begin) (goto-char (or post-affiliated begin)))
24047 ((eq type 'paragraph)
24048 (goto-char contents-begin)
24049 ;; When at first paragraph in an item or a footnote definition,
24050 ;; move directly to beginning of line.
24051 (let ((parent-contents
24052 (org-element-property
24053 :contents-begin (org-element-property :parent element))))
24054 (when (and parent-contents (= parent-contents contents-begin))
24055 (beginning-of-line))))
24056 ;; At the end of a greater element, move to the beginning of the
24057 ;; last element within.
24058 ((>= (point) contents-end)
24059 (goto-char (1- contents-end))
24060 (org-backward-paragraph))
24061 (t (goto-char (or post-affiliated begin))))
24062 ;; Ensure we never leave point invisible.
24063 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24065 (defun org-forward-element ()
24066 "Move forward by one element.
24067 Move to the next element at the same level, when possible."
24068 (interactive)
24069 (cond ((eobp) (user-error "Cannot move further down"))
24070 ((org-with-limited-levels (org-at-heading-p))
24071 (let ((origin (point)))
24072 (goto-char (org-end-of-subtree nil t))
24073 (unless (org-with-limited-levels (org-at-heading-p))
24074 (goto-char origin)
24075 (user-error "Cannot move further down"))))
24077 (let* ((elem (org-element-at-point))
24078 (end (org-element-property :end elem))
24079 (parent (org-element-property :parent elem)))
24080 (cond ((and parent (= (org-element-property :contents-end parent) end))
24081 (goto-char (org-element-property :end parent)))
24082 ((integer-or-marker-p end) (goto-char end))
24083 (t (message "No element at point")))))))
24085 (defun org-backward-element ()
24086 "Move backward by one element.
24087 Move to the previous element at the same level, when possible."
24088 (interactive)
24089 (cond ((bobp) (user-error "Cannot move further up"))
24090 ((org-with-limited-levels (org-at-heading-p))
24091 ;; At a headline, move to the previous one, if any, or stay
24092 ;; here.
24093 (let ((origin (point)))
24094 (org-with-limited-levels (org-backward-heading-same-level 1))
24095 ;; When current headline has no sibling above, move to its
24096 ;; parent.
24097 (when (= (point) origin)
24098 (or (org-with-limited-levels (org-up-heading-safe))
24099 (progn (goto-char origin)
24100 (user-error "Cannot move further up"))))))
24102 (let* ((elem (org-element-at-point))
24103 (beg (org-element-property :begin elem)))
24104 (cond
24105 ;; Move to beginning of current element if point isn't
24106 ;; there already.
24107 ((null beg) (message "No element at point"))
24108 ((/= (point) beg) (goto-char beg))
24109 (t (goto-char beg)
24110 (skip-chars-backward " \r\t\n")
24111 (unless (bobp)
24112 (let ((prev (org-element-at-point)))
24113 (goto-char (org-element-property :begin prev))
24114 (while (and (setq prev (org-element-property :parent prev))
24115 (<= (org-element-property :end prev) beg))
24116 (goto-char (org-element-property :begin prev)))))))))))
24118 (defun org-up-element ()
24119 "Move to upper element."
24120 (interactive)
24121 (if (org-with-limited-levels (org-at-heading-p))
24122 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24123 (let* ((elem (org-element-at-point))
24124 (parent (org-element-property :parent elem)))
24125 (if parent (goto-char (org-element-property :begin parent))
24126 (if (org-with-limited-levels (org-before-first-heading-p))
24127 (user-error "No surrounding element")
24128 (org-with-limited-levels (org-back-to-heading)))))))
24130 (defvar org-element-greater-elements)
24131 (defun org-down-element ()
24132 "Move to inner element."
24133 (interactive)
24134 (let ((element (org-element-at-point)))
24135 (cond
24136 ((memq (org-element-type element) '(plain-list table))
24137 (goto-char (org-element-property :contents-begin element))
24138 (forward-char))
24139 ((memq (org-element-type element) org-element-greater-elements)
24140 ;; If contents are hidden, first disclose them.
24141 (when (outline-invisible-p (line-end-position)) (org-cycle))
24142 (goto-char (or (org-element-property :contents-begin element)
24143 (user-error "No content for this element"))))
24144 (t (user-error "No inner element")))))
24146 (defun org-drag-element-backward ()
24147 "Move backward element at point."
24148 (interactive)
24149 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24150 (let* ((elem (org-element-at-point))
24151 (prev-elem
24152 (save-excursion
24153 (goto-char (org-element-property :begin elem))
24154 (skip-chars-backward " \r\t\n")
24155 (unless (bobp)
24156 (let* ((beg (org-element-property :begin elem))
24157 (prev (org-element-at-point))
24158 (up prev))
24159 (while (and (setq up (org-element-property :parent up))
24160 (<= (org-element-property :end prev) beg))
24161 (setq prev up))
24162 prev)))))
24163 ;; Error out if no previous element or previous element is
24164 ;; a parent of the current one.
24165 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24166 (user-error "Cannot drag element backward")
24167 (let ((pos (point)))
24168 (org-element-swap-A-B prev-elem elem)
24169 (goto-char (+ (org-element-property :begin prev-elem)
24170 (- pos (org-element-property :begin elem)))))))))
24172 (defun org-drag-element-forward ()
24173 "Move forward element at point."
24174 (interactive)
24175 (let* ((pos (point))
24176 (elem (org-element-at-point)))
24177 (when (= (point-max) (org-element-property :end elem))
24178 (user-error "Cannot drag element forward"))
24179 (goto-char (org-element-property :end elem))
24180 (let ((next-elem (org-element-at-point)))
24181 (when (or (org-element-nested-p elem next-elem)
24182 (and (eq (org-element-type next-elem) 'headline)
24183 (not (eq (org-element-type elem) 'headline))))
24184 (goto-char pos)
24185 (user-error "Cannot drag element forward"))
24186 ;; Compute new position of point: it's shifted by NEXT-ELEM
24187 ;; body's length (without final blanks) and by the length of
24188 ;; blanks between ELEM and NEXT-ELEM.
24189 (let ((size-next (- (save-excursion
24190 (goto-char (org-element-property :end next-elem))
24191 (skip-chars-backward " \r\t\n")
24192 (forward-line)
24193 ;; Small correction if buffer doesn't end
24194 ;; with a newline character.
24195 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24196 (org-element-property :begin next-elem)))
24197 (size-blank (- (org-element-property :end elem)
24198 (save-excursion
24199 (goto-char (org-element-property :end elem))
24200 (skip-chars-backward " \r\t\n")
24201 (forward-line)
24202 (point)))))
24203 (org-element-swap-A-B elem next-elem)
24204 (goto-char (+ pos size-next size-blank))))))
24206 (defun org-drag-line-forward (arg)
24207 "Drag the line at point ARG lines forward."
24208 (interactive "p")
24209 (dotimes (n (abs arg))
24210 (let ((c (current-column)))
24211 (if (< 0 arg)
24212 (progn
24213 (beginning-of-line 2)
24214 (transpose-lines 1)
24215 (beginning-of-line 0))
24216 (transpose-lines 1)
24217 (beginning-of-line -1))
24218 (org-move-to-column c))))
24220 (defun org-drag-line-backward (arg)
24221 "Drag the line at point ARG lines backward."
24222 (interactive "p")
24223 (org-drag-line-forward (- arg)))
24225 (defun org-mark-element ()
24226 "Put point at beginning of this element, mark at end.
24228 Interactively, if this command is repeated or (in Transient Mark
24229 mode) if the mark is active, it marks the next element after the
24230 ones already marked."
24231 (interactive)
24232 (let (deactivate-mark)
24233 (if (and (org-called-interactively-p 'any)
24234 (or (and (eq last-command this-command) (mark t))
24235 (and transient-mark-mode mark-active)))
24236 (set-mark
24237 (save-excursion
24238 (goto-char (mark))
24239 (goto-char (org-element-property :end (org-element-at-point)))))
24240 (let ((element (org-element-at-point)))
24241 (end-of-line)
24242 (push-mark (org-element-property :end element) t t)
24243 (goto-char (org-element-property :begin element))))))
24245 (defun org-narrow-to-element ()
24246 "Narrow buffer to current element."
24247 (interactive)
24248 (let ((elem (org-element-at-point)))
24249 (cond
24250 ((eq (car elem) 'headline)
24251 (narrow-to-region
24252 (org-element-property :begin elem)
24253 (org-element-property :end elem)))
24254 ((memq (car elem) org-element-greater-elements)
24255 (narrow-to-region
24256 (org-element-property :contents-begin elem)
24257 (org-element-property :contents-end elem)))
24259 (narrow-to-region
24260 (org-element-property :begin elem)
24261 (org-element-property :end elem))))))
24263 (defun org-transpose-element ()
24264 "Transpose current and previous elements, keeping blank lines between.
24265 Point is moved after both elements."
24266 (interactive)
24267 (org-skip-whitespace)
24268 (let ((end (org-element-property :end (org-element-at-point))))
24269 (org-drag-element-backward)
24270 (goto-char end)))
24272 (defun org-unindent-buffer ()
24273 "Un-indent the visible part of the buffer.
24274 Relative indentation (between items, inside blocks, etc.) isn't
24275 modified."
24276 (interactive)
24277 (unless (eq major-mode 'org-mode)
24278 (user-error "Cannot un-indent a buffer not in Org mode"))
24279 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24280 unindent-tree ; For byte-compiler.
24281 (unindent-tree
24282 (function
24283 (lambda (contents)
24284 (mapc
24285 (lambda (element)
24286 (if (memq (org-element-type element) '(headline section))
24287 (funcall unindent-tree (org-element-contents element))
24288 (save-excursion
24289 (save-restriction
24290 (narrow-to-region
24291 (org-element-property :begin element)
24292 (org-element-property :end element))
24293 (org-do-remove-indentation)))))
24294 (reverse contents))))))
24295 (funcall unindent-tree (org-element-contents parse-tree))))
24297 (defun org-show-subtree ()
24298 "Show everything after this heading at deeper levels."
24299 (interactive)
24300 (outline-flag-region
24301 (point)
24302 (save-excursion
24303 (org-end-of-subtree t t))
24304 nil))
24306 (defun org-show-entry ()
24307 "Show the body directly following this heading.
24308 Show the heading too, if it is currently invisible."
24309 (interactive)
24310 (save-excursion
24311 (ignore-errors
24312 (org-back-to-heading t)
24313 (outline-flag-region
24314 (max (point-min) (1- (point)))
24315 (save-excursion
24316 (if (re-search-forward
24317 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24318 (match-beginning 1)
24319 (point-max)))
24320 nil)
24321 (org-cycle-hide-drawers 'children))))
24323 (defun org-make-options-regexp (kwds &optional extra)
24324 "Make a regular expression for keyword lines."
24325 (concat
24326 "^[ \t]*#\\+\\("
24327 (mapconcat 'regexp-quote kwds "\\|")
24328 (if extra (concat "\\|" extra))
24329 "\\):[ \t]*\\(.*\\)"))
24331 ;; Make isearch reveal the necessary context
24332 (defun org-isearch-end ()
24333 "Reveal context after isearch exits."
24334 (when isearch-success ; only if search was successful
24335 (if (featurep 'xemacs)
24336 ;; Under XEmacs, the hook is run in the correct place,
24337 ;; we directly show the context.
24338 (org-show-context 'isearch)
24339 ;; In Emacs the hook runs *before* restoring the overlays.
24340 ;; So we have to use a one-time post-command-hook to do this.
24341 ;; (Emacs 22 has a special variable, see function `org-mode')
24342 (unless (and (boundp 'isearch-mode-end-hook-quit)
24343 isearch-mode-end-hook-quit)
24344 ;; Only when the isearch was not quitted.
24345 (org-add-hook 'post-command-hook 'org-isearch-post-command
24346 'append 'local)))
24347 (org-fix-ellipsis-at-bol)))
24349 (defun org-isearch-post-command ()
24350 "Remove self from hook, and show context."
24351 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24352 (org-show-context 'isearch))
24355 ;;;; Integration with and fixes for other packages
24357 ;;; Imenu support
24359 (defvar org-imenu-markers nil
24360 "All markers currently used by Imenu.")
24361 (make-variable-buffer-local 'org-imenu-markers)
24363 (defun org-imenu-new-marker (&optional pos)
24364 "Return a new marker for use by Imenu, and remember the marker."
24365 (let ((m (make-marker)))
24366 (move-marker m (or pos (point)))
24367 (push m org-imenu-markers)
24370 (defun org-imenu-get-tree ()
24371 "Produce the index for Imenu."
24372 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24373 (setq org-imenu-markers nil)
24374 (let* ((n org-imenu-depth)
24375 (re (concat "^" (org-get-limited-outline-regexp)))
24376 (subs (make-vector (1+ n) nil))
24377 (last-level 0)
24378 m level head0 head)
24379 (save-excursion
24380 (save-restriction
24381 (widen)
24382 (goto-char (point-max))
24383 (while (re-search-backward re nil t)
24384 (setq level (org-reduced-level (funcall outline-level)))
24385 (when (and (<= level n)
24386 (looking-at org-complex-heading-regexp)
24387 (setq head0 (org-match-string-no-properties 4)))
24388 (setq head (org-link-display-format head0)
24389 m (org-imenu-new-marker))
24390 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24391 (if (>= level last-level)
24392 (push (cons head m) (aref subs level))
24393 (push (cons head (aref subs (1+ level))) (aref subs level))
24394 (loop for i from (1+ level) to n do (aset subs i nil)))
24395 (setq last-level level)))))
24396 (aref subs 1)))
24398 (eval-after-load "imenu"
24399 '(progn
24400 (add-hook 'imenu-after-jump-hook
24401 (lambda ()
24402 (if (derived-mode-p 'org-mode)
24403 (org-show-context 'org-goto))))))
24405 (defun org-link-display-format (link)
24406 "Replace a link with its the description.
24407 If there is no description, use the link target."
24408 (save-match-data
24409 (if (string-match org-bracket-link-analytic-regexp link)
24410 (replace-match (if (match-end 5)
24411 (match-string 5 link)
24412 (concat (match-string 1 link)
24413 (match-string 3 link)))
24414 nil t link)
24415 link)))
24417 (defun org-toggle-link-display ()
24418 "Toggle the literal or descriptive display of links."
24419 (interactive)
24420 (if org-descriptive-links
24421 (progn (org-remove-from-invisibility-spec '(org-link))
24422 (org-restart-font-lock)
24423 (setq org-descriptive-links nil))
24424 (progn (add-to-invisibility-spec '(org-link))
24425 (org-restart-font-lock)
24426 (setq org-descriptive-links t))))
24428 ;; Speedbar support
24430 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24431 "Overlay marking the agenda restriction line in speedbar.")
24432 (overlay-put org-speedbar-restriction-lock-overlay
24433 'face 'org-agenda-restriction-lock)
24434 (overlay-put org-speedbar-restriction-lock-overlay
24435 'help-echo "Agendas are currently limited to this item.")
24436 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24438 (defun org-speedbar-set-agenda-restriction ()
24439 "Restrict future agenda commands to the location at point in speedbar.
24440 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24441 (interactive)
24442 (require 'org-agenda)
24443 (let (p m tp np dir txt)
24444 (cond
24445 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24446 'org-imenu t))
24447 (setq m (get-text-property p 'org-imenu-marker))
24448 (with-current-buffer (marker-buffer m)
24449 (goto-char m)
24450 (org-agenda-set-restriction-lock 'subtree)))
24451 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24452 'speedbar-function 'speedbar-find-file))
24453 (setq tp (previous-single-property-change
24454 (1+ p) 'speedbar-function)
24455 np (next-single-property-change
24456 tp 'speedbar-function)
24457 dir (speedbar-line-directory)
24458 txt (buffer-substring-no-properties (or tp (point-min))
24459 (or np (point-max))))
24460 (with-current-buffer (find-file-noselect
24461 (let ((default-directory dir))
24462 (expand-file-name txt)))
24463 (unless (derived-mode-p 'org-mode)
24464 (user-error "Cannot restrict to non-Org-mode file"))
24465 (org-agenda-set-restriction-lock 'file)))
24466 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24467 (move-overlay org-speedbar-restriction-lock-overlay
24468 (point-at-bol) (point-at-eol))
24469 (setq current-prefix-arg nil)
24470 (org-agenda-maybe-redo)))
24472 (defvar speedbar-file-key-map)
24473 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24474 (eval-after-load "speedbar"
24475 '(progn
24476 (speedbar-add-supported-extension ".org")
24477 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24478 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24479 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24480 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24481 (add-hook 'speedbar-visiting-tag-hook
24482 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24484 ;;; Fixes and Hacks for problems with other packages
24486 (defun org-mode-flyspell-verify ()
24487 "Function used for `flyspell-generic-check-word-predicate'."
24488 (if (org-at-heading-p)
24489 ;; At a headline or an inlinetask, check title only. This is
24490 ;; faster than relying on `org-element-at-point'.
24491 (and (save-excursion (beginning-of-line)
24492 (and (let ((case-fold-search t))
24493 (not (looking-at "\\*+ END[ \t]*$")))
24494 (looking-at org-complex-heading-regexp)))
24495 (match-beginning 4)
24496 (>= (point) (match-beginning 4))
24497 (or (not (match-beginning 5))
24498 (< (point) (match-beginning 5))))
24499 (let* ((element (org-element-at-point))
24500 (post-affiliated (org-element-property :post-affiliated element))
24501 (object-check
24502 (function
24503 ;; Non-nil if checks can be done for object at point.
24504 (lambda ()
24505 (let ((object (save-excursion
24506 (when (org-looking-at-p "\\>") (backward-char))
24507 (org-element-context element))))
24508 (case (org-element-type object)
24509 ;; Prevent checks in links due to keybinding conflict
24510 ;; with Flyspell.
24511 ((code entity export-snippet inline-babel-call
24512 inline-src-block line-break latex-fragment link macro
24513 statistics-cookie target timestamp verbatim)
24514 nil)
24515 (footnote-reference
24516 ;; Only in inline footnotes, within the definition.
24517 (and (eq (org-element-property :type object) 'inline)
24518 (< (save-excursion
24519 (goto-char (org-element-property :begin object))
24520 (search-forward ":" nil t 2))
24521 (point))))
24522 (otherwise t)))))))
24523 (cond
24524 ;; Ignore checks in all affiliated keywords but captions.
24525 ((and post-affiliated (< (point) post-affiliated))
24526 (and (save-excursion
24527 (beginning-of-line)
24528 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24529 (> (point) (match-end 0))
24530 (funcall object-check)))
24531 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24532 ((and org-log-into-drawer
24533 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24534 (parent element))
24535 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24536 (setq parent (org-element-property :parent parent)))
24537 (and parent
24538 (eq (compare-strings
24539 log nil nil
24540 (org-element-property :drawer-name parent) nil nil t)
24541 t))))
24542 nil)
24544 (case (org-element-type element)
24545 ((comment quote-section) t)
24546 (comment-block
24547 ;; Allow checks between block markers, not on them.
24548 (and (> (line-beginning-position)
24549 (org-element-property :post-affiliated element))
24550 (save-excursion
24551 (end-of-line)
24552 (skip-chars-forward " \r\t\n")
24553 (< (point) (org-element-property :end element)))))
24554 ;; Arbitrary list of keywords where checks are meaningful.
24555 ;; Make sure point is on the value part of the element.
24556 (keyword
24557 (and (member (org-element-property :key element)
24558 '("DESCRIPTION" "TITLE"))
24559 (< (save-excursion
24560 (beginning-of-line) (search-forward ":") (point))
24561 (point))))
24562 ;; Check is globally allowed in paragraphs verse blocks and
24563 ;; table rows (after affiliated keywords) but some objects
24564 ;; must not be affected.
24565 ((paragraph table-row verse-block)
24566 (and (>= (point) (org-element-property :contents-begin element))
24567 (< (point) (org-element-property :contents-end element))
24568 (funcall object-check)))))))))
24569 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24571 (defun org-remove-flyspell-overlays-in (beg end)
24572 "Remove flyspell overlays in region."
24573 (and (org-bound-and-true-p flyspell-mode)
24574 (fboundp 'flyspell-delete-region-overlays)
24575 (flyspell-delete-region-overlays beg end)))
24577 (defvar flyspell-delayed-commands)
24578 (eval-after-load "flyspell"
24579 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24581 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24582 (eval-after-load "bookmark"
24583 '(if (boundp 'bookmark-after-jump-hook)
24584 ;; We can use the hook
24585 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24586 ;; Hook not available, use advice
24587 (defadvice bookmark-jump (after org-make-visible activate)
24588 "Make the position visible."
24589 (org-bookmark-jump-unhide))))
24591 ;; Make sure saveplace shows the location if it was hidden
24592 (eval-after-load "saveplace"
24593 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24594 "Make the position visible."
24595 (org-bookmark-jump-unhide)))
24597 ;; Make sure ecb shows the location if it was hidden
24598 (eval-after-load "ecb"
24599 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24600 "Make hierarchy visible when jumping into location from ECB tree buffer."
24601 (if (derived-mode-p 'org-mode)
24602 (org-show-context))))
24604 (defun org-bookmark-jump-unhide ()
24605 "Unhide the current position, to show the bookmark location."
24606 (and (derived-mode-p 'org-mode)
24607 (or (outline-invisible-p)
24608 (save-excursion (goto-char (max (point-min) (1- (point))))
24609 (outline-invisible-p)))
24610 (org-show-context 'bookmark-jump)))
24612 (defun org-mark-jump-unhide ()
24613 "Make the point visible with `org-show-context' after jumping to the mark."
24614 (when (and (derived-mode-p 'org-mode)
24615 (outline-invisible-p))
24616 (org-show-context 'mark-goto)))
24618 (eval-after-load "simple"
24619 '(defadvice pop-to-mark-command (after org-make-visible activate)
24620 "Make the point visible with `org-show-context'."
24621 (org-mark-jump-unhide)))
24623 (eval-after-load "simple"
24624 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24625 "Make the point visible with `org-show-context'."
24626 (org-mark-jump-unhide)))
24628 (eval-after-load "simple"
24629 '(defadvice pop-global-mark (after org-make-visible activate)
24630 "Make the point visible with `org-show-context'."
24631 (org-mark-jump-unhide)))
24633 ;; Make session.el ignore our circular variable
24634 (defvar session-globals-exclude)
24635 (eval-after-load "session"
24636 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24638 ;;;; Finish up
24640 (provide 'org)
24642 (run-hooks 'org-load-hook)
24644 ;;; org.el ends here