Fix `org-hide-block-toggle' return value
[org-mode.git] / lisp / org.el
blobbcbe1b7ae0ae4c351308eae7cea2f2a7e5e36331
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 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
99 ;; In Org buffers, the value of `outline-regexp' is that of
100 ;; `org-outline-regexp'. The only function still directly relying on
101 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
102 ;; job when `orgstruct-mode' is active.
103 (defvar org-outline-regexp "\\*+ "
104 "Regexp to match Org headlines.")
106 (defvar org-outline-regexp-bol "^\\*+ "
107 "Regexp to match Org headlines.
108 This is similar to `org-outline-regexp' but additionally makes
109 sure that we are at the beginning of the line.")
111 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
112 "Matches a headline, putting stars and text into groups.
113 Stars are put in group 1 and the trimmed body in group 2.")
115 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
116 (unless (boundp 'calendar-view-holidays-initially-flag)
117 (org-defvaralias 'calendar-view-holidays-initially-flag
118 'view-calendar-holidays-initially))
119 (unless (boundp 'calendar-view-diary-initially-flag)
120 (org-defvaralias 'calendar-view-diary-initially-flag
121 'view-diary-entries-initially))
122 (unless (boundp 'diary-fancy-buffer)
123 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
125 (declare-function org-add-archive-files "org-archive" (files))
127 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
128 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
129 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
130 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
133 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
134 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
135 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
136 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
137 (declare-function org-clock-update-time-maybe "org-clock" ())
138 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
141 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
142 (declare-function orgtbl-mode "org-table" (&optional arg))
143 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
144 (declare-function org-beamer-mode "ox-beamer" ())
145 (declare-function org-table-blank-field "org-table" ())
146 (declare-function org-table-edit-field "org-table" (arg))
147 (declare-function org-table-insert-row "org-table" (&optional arg))
148 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
149 (declare-function org-table-set-constants "org-table" ())
150 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-add-archive-files "org-archive" (files))
153 (declare-function org-id-find-id-file "org-id" (id))
154 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
155 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
156 (declare-function org-agenda-redo "org-agenda" (&optional all))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-paste-rectangle "org-table" ())
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
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-nested-p "org-element" (elem-a elem-b))
175 (declare-function org-element-parse-buffer "org-element"
176 (&optional granularity visible-only))
177 (declare-function org-element-property "org-element" (property element))
178 (declare-function org-element-put-property "org-element"
179 (element property value))
180 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
181 (declare-function org-element-parse-buffer "org-element"
182 (&optional granularity visible-only))
183 (declare-function org-element-type "org-element" (element))
185 (defsubst org-uniquify (list)
186 "Non-destructively remove duplicate elements from LIST."
187 (let ((res (copy-sequence list))) (delete-dups res)))
189 (defsubst org-get-at-bol (property)
190 "Get text property PROPERTY at the beginning of line."
191 (get-text-property (point-at-bol) property))
193 (defsubst org-trim (s)
194 "Remove whitespace at the beginning and the end of string S."
195 (replace-regexp-in-string
196 "\\`[ \t\n\r]+" ""
197 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
199 ;; load languages based on value of `org-babel-load-languages'
200 (defvar org-babel-load-languages)
202 ;;;###autoload
203 (defun org-babel-do-load-languages (sym value)
204 "Load the languages defined in `org-babel-load-languages'."
205 (set-default sym value)
206 (mapc (lambda (pair)
207 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
208 (if active
209 (progn
210 (require (intern (concat "ob-" lang))))
211 (progn
212 (funcall 'fmakunbound
213 (intern (concat "org-babel-execute:" lang)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-expand-body:" lang)))))))
216 org-babel-load-languages))
218 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
219 ;;;###autoload
220 (defun org-babel-load-file (file &optional compile)
221 "Load Emacs Lisp source code blocks in the Org-mode FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
228 (float-time
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file))
231 (file-attributes file)))))))
232 (base-name (file-name-sans-extension file))
233 (exported-file (concat base-name ".el")))
234 ;; tangle if the org-mode file is newer than the elisp file
235 (unless (and (file-exists-p exported-file)
236 (> (funcall age file) (funcall age exported-file)))
237 (setq exported-file
238 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
239 (message "%s %s"
240 (if compile
241 (progn (byte-compile-file exported-file 'load)
242 "Compiled and loaded")
243 (progn (load-file exported-file) "Loaded"))
244 exported-file)))
246 (defcustom org-babel-load-languages '((emacs-lisp . t))
247 "Languages which can be evaluated in Org-mode buffers.
248 This list can be used to load support for any of the languages
249 below, note that each language will depend on a different set of
250 system executables and/or Emacs modes. When a language is
251 \"loaded\", then code blocks in that language can be evaluated
252 with `org-babel-execute-src-block' bound by default to C-c
253 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
254 be set to remove code block evaluation from the C-c C-c
255 keybinding. By default only Emacs Lisp (which has no
256 requirements) is loaded."
257 :group 'org-babel
258 :set 'org-babel-do-load-languages
259 :version "24.1"
260 :type '(alist :tag "Babel Languages"
261 :key-type
262 (choice
263 (const :tag "Awk" awk)
264 (const :tag "C" C)
265 (const :tag "R" R)
266 (const :tag "Asymptote" asymptote)
267 (const :tag "Calc" calc)
268 (const :tag "Clojure" clojure)
269 (const :tag "CSS" css)
270 (const :tag "Ditaa" ditaa)
271 (const :tag "Dot" dot)
272 (const :tag "Emacs Lisp" emacs-lisp)
273 (const :tag "Forth" forth)
274 (const :tag "Fortran" fortran)
275 (const :tag "Gnuplot" gnuplot)
276 (const :tag "Haskell" haskell)
277 (const :tag "IO" io)
278 (const :tag "J" J)
279 (const :tag "Java" java)
280 (const :tag "Javascript" js)
281 (const :tag "LaTeX" latex)
282 (const :tag "Ledger" ledger)
283 (const :tag "Lilypond" lilypond)
284 (const :tag "Lisp" lisp)
285 (const :tag "Makefile" makefile)
286 (const :tag "Maxima" maxima)
287 (const :tag "Matlab" matlab)
288 (const :tag "Mscgen" mscgen)
289 (const :tag "Ocaml" ocaml)
290 (const :tag "Octave" octave)
291 (const :tag "Org" org)
292 (const :tag "Perl" perl)
293 (const :tag "Pico Lisp" picolisp)
294 (const :tag "PlantUML" plantuml)
295 (const :tag "Python" python)
296 (const :tag "Ruby" ruby)
297 (const :tag "Sass" sass)
298 (const :tag "Scala" scala)
299 (const :tag "Scheme" scheme)
300 (const :tag "Screen" screen)
301 (const :tag "Shell Script" shell)
302 (const :tag "Shen" shen)
303 (const :tag "Sql" sql)
304 (const :tag "Sqlite" sqlite)
305 (const :tag "ebnf2ps" ebnf2ps))
306 :value-type (boolean :tag "Activate" :value t)))
308 ;;;; Customization variables
309 (defcustom org-clone-delete-id nil
310 "Remove ID property of clones of a subtree.
311 When non-nil, clones of a subtree don't inherit the ID property.
312 Otherwise they inherit the ID property with a new unique
313 identifier."
314 :type 'boolean
315 :version "24.1"
316 :group 'org-id)
318 ;;; Version
319 (org-check-version)
321 ;;;###autoload
322 (defun org-version (&optional here full message)
323 "Show the org-mode version.
324 Interactively, or when MESSAGE is non-nil, show it in echo area.
325 With prefix argument, or when HERE is non-nil, insert it at point.
326 In non-interactive uses, a reduced version string is output unless
327 FULL is given."
328 (interactive (list current-prefix-arg t (not current-prefix-arg)))
329 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
330 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
331 (load-suffixes (list ".el"))
332 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
333 (org-trash (or
334 (and (fboundp 'org-release) (fboundp 'org-git-version))
335 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
336 (load-suffixes save-load-suffixes)
337 (org-version (org-release))
338 (git-version (org-git-version))
339 (version (format "Org-mode version %s (%s @ %s)"
340 org-version
341 git-version
342 (if org-install-dir
343 (if (string= org-dir org-install-dir)
344 org-install-dir
345 (concat "mixed installation! " org-install-dir " and " org-dir))
346 "org-loaddefs.el can not be found!")))
347 (version1 (if full version org-version)))
348 (when here (insert version1))
349 (when message (message "%s" version1))
350 version1))
352 (defconst org-version (org-version))
355 ;;; Syntax Constants
357 ;;;; Block
359 (defconst org-block-regexp
360 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
361 "Regular expression for hiding blocks.")
363 (defconst org-dblock-start-re
364 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
365 "Matches the start line of a dynamic block, with parameters.")
367 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
368 "Matches the end of a dynamic block.")
370 ;;;; Clock and Planning
372 (defconst org-clock-string "CLOCK:"
373 "String used as prefix for timestamps clocking work hours on an item.")
375 (defconst org-closed-string "CLOSED:"
376 "String used as the prefix for timestamps logging closing a TODO entry.")
378 (defconst org-deadline-string "DEADLINE:"
379 "String to mark deadline entries.
380 A deadline is this string, followed by a time stamp. Should be a word,
381 terminated by a colon. You can insert a schedule keyword and
382 a timestamp with \\[org-deadline].")
384 (defconst org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 A schedule is this string, followed by a time stamp. Should be a word,
387 terminated by a colon. You can insert a schedule keyword and
388 a timestamp with \\[org-schedule].")
390 (defconst org-planning-line-re
391 (concat "^[ \t]*"
392 (regexp-opt
393 (list org-closed-string org-deadline-string org-scheduled-string)
395 "Matches a line with planning info.
396 Matched keyword is in group 1.")
398 (defconst org-clock-line-re
399 (concat "^[ \t]*" org-clock-string)
400 "Matches a line with clock info.")
402 ;;;; Drawer
404 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
405 "Matches first or last line of a hidden block.
406 Group 1 contains drawer's name or \"END\".")
408 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
409 "Regular expression matching the first line of a property drawer.")
411 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
412 "Regular expression matching the last line of a property drawer.")
414 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
415 "Regular expression matching the first line of a clock drawer.")
417 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
418 "Regular expression matching the last line of a clock drawer.")
420 (defconst org-property-drawer-re
421 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
422 org-property-end-re "\\)\n?")
423 "Matches an entire property drawer.")
425 (defconst org-clock-drawer-re
426 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
427 org-clock-drawer-end-re "\\)\n?")
428 "Matches an entire clock drawer.")
430 ;;;; Headline
432 (defconst org-heading-keyword-regexp-format
433 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
434 "Printf format for a regexp matching a headline with some keyword.
435 This regexp will match the headline of any node which has the
436 exact keyword that is put into the format. The keyword isn't in
437 any group by default, but the stars and the body are.")
439 (defconst org-heading-keyword-maybe-regexp-format
440 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
441 "Printf format for a regexp matching a headline, possibly with some keyword.
442 This regexp can match any headline with the specified keyword, or
443 without a keyword. The keyword isn't in any group by default,
444 but the stars and the body are.")
446 (defconst org-archive-tag "ARCHIVE"
447 "The tag that marks a subtree as archived.
448 An archived subtree does not open during visibility cycling, and does
449 not contribute to the agenda listings.")
451 (defconst org-comment-string "COMMENT"
452 "Entries starting with this keyword will never be exported.
453 An entry can be toggled between COMMENT and normal with
454 \\[org-toggle-comment].")
457 ;;;; LaTeX Environments and Fragments
459 (defconst org-latex-regexps
460 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
461 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
462 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
463 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
464 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
465 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
466 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
467 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
468 "Regular expressions for matching embedded LaTeX.")
470 ;;;; Node Property
472 (defconst org-effort-property "Effort"
473 "The property that is being used to keep track of effort estimates.
474 Effort estimates given in this property need to have the format H:MM.")
476 ;;;; Table
478 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
479 "Detect an org-type or table-type table.")
481 (defconst org-table-line-regexp "^[ \t]*|"
482 "Detect an org-type table line.")
484 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
485 "Detect an org-type table line.")
487 (defconst org-table-hline-regexp "^[ \t]*|-"
488 "Detect an org-type table hline.")
490 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
491 "Detect a table-type table hline.")
493 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
494 "Detect the first line outside a table when searching from within it.
495 This works for both table types.")
497 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
498 "Detect a #+TBLFM line.")
500 ;;;; Timestamp
502 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
503 "Regular expression for fast time stamp matching.")
505 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
506 "Regular expression for fast time stamp matching.")
508 (defconst org-ts-regexp0
509 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
510 "Regular expression matching time strings for analysis.
511 This one does not require the space after the date, so it can be used
512 on a string that terminates immediately after the date.")
514 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
515 "Regular expression matching time strings for analysis.")
517 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
518 "Regular expression matching time stamps, with groups.")
520 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
521 "Regular expression matching time stamps (also [..]), with groups.")
523 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
524 "Regular expression matching a time stamp range.")
526 (defconst org-tr-regexp-both
527 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
528 "Regular expression matching a time stamp range.")
530 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
531 org-ts-regexp "\\)?")
532 "Regular expression matching a time stamp or time stamp range.")
534 (defconst org-tsr-regexp-both
535 (concat org-ts-regexp-both "\\(--?-?"
536 org-ts-regexp-both "\\)?")
537 "Regular expression matching a time stamp or time stamp range.
538 The time stamps may be either active or inactive.")
540 (defconst org-repeat-re
541 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
542 "Regular expression for specifying repeated events.
543 After a match, group 1 contains the repeat expression.")
545 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
546 "Formats for `format-time-string' which are used for time stamps.")
549 ;;; The custom variables
551 (defgroup org nil
552 "Outline-based notes management and organizer."
553 :tag "Org"
554 :group 'outlines
555 :group 'calendar)
557 (defcustom org-mode-hook nil
558 "Mode hook for Org-mode, run after the mode was turned on."
559 :group 'org
560 :type 'hook)
562 (defcustom org-load-hook nil
563 "Hook that is run after org.el has been loaded."
564 :group 'org
565 :type 'hook)
567 (defcustom org-log-buffer-setup-hook nil
568 "Hook that is run after an Org log buffer is created."
569 :group 'org
570 :version "24.1"
571 :type 'hook)
573 (defvar org-modules) ; defined below
574 (defvar org-modules-loaded nil
575 "Have the modules been loaded already?")
577 (defun org-load-modules-maybe (&optional force)
578 "Load all extensions listed in `org-modules'."
579 (when (or force (not org-modules-loaded))
580 (mapc (lambda (ext)
581 (condition-case nil (require ext)
582 (error (message "Problems while trying to load feature `%s'" ext))))
583 org-modules)
584 (setq org-modules-loaded t)))
586 (defun org-set-modules (var value)
587 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
588 (set var value)
589 (when (featurep 'org)
590 (org-load-modules-maybe 'force)
591 (org-element-cache-reset 'all)))
593 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
594 "Modules that should always be loaded together with org.el.
596 If a description starts with <C>, the file is not part of Emacs
597 and loading it will require that you have downloaded and properly
598 installed the Org mode distribution.
600 You can also use this system to load external packages (i.e. neither Org
601 core modules, nor modules from the CONTRIB directory). Just add symbols
602 to the end of the list. If the package is called org-xyz.el, then you need
603 to add the symbol `xyz', and the package must have a call to:
605 \(provide 'org-xyz)
607 For export specific modules, see also `org-export-backends'."
608 :group 'org
609 :set 'org-set-modules
610 :version "24.4"
611 :package-version '(Org . "8.0")
612 :type
613 '(set :greedy t
614 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
615 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
616 (const :tag " crypt: Encryption of subtrees" org-crypt)
617 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
618 (const :tag " docview: Links to doc-view buffers" org-docview)
619 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
620 (const :tag " habit: Track your consistency with habits" org-habit)
621 (const :tag " id: Global IDs for identifying entries" org-id)
622 (const :tag " info: Links to Info nodes" org-info)
623 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
624 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
625 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
626 (const :tag " mouse: Additional mouse support" org-mouse)
627 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
628 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
629 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
631 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
632 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
633 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
634 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
635 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
636 (const :tag "C collector: Collect properties into tables" org-collector)
637 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
638 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
639 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
640 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
641 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
642 (const :tag "C eval: Include command output as text" org-eval)
643 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
644 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
645 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
646 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
647 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
648 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
649 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
650 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
651 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
652 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
653 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
654 (const :tag "C mew: Links to Mew folders/messages" org-mew)
655 (const :tag "C mtags: Support for muse-like tags" org-mtags)
656 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
657 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
658 (const :tag "C registry: A registry for Org-mode links" org-registry)
659 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
660 (const :tag "C secretary: Team management with org-mode" org-secretary)
661 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
662 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
663 (const :tag "C track: Keep up with Org-mode development" org-track)
664 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
665 (const :tag "C vm: Links to VM folders/messages" org-vm)
666 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
667 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
668 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
670 (defvar org-export--registered-backends) ; From ox.el.
671 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
672 (declare-function org-export-backend-name "ox" (backend))
673 (defcustom org-export-backends '(ascii html icalendar latex)
674 "List of export back-ends that should be always available.
676 If a description starts with <C>, the file is not part of Emacs
677 and loading it will require that you have downloaded and properly
678 installed the Org mode distribution.
680 Unlike to `org-modules', libraries in this list will not be
681 loaded along with Org, but only once the export framework is
682 needed.
684 This variable needs to be set before org.el is loaded. If you
685 need to make a change while Emacs is running, use the customize
686 interface or run the following code, where VAL stands for the new
687 value of the variable, after updating it:
689 \(progn
690 \(setq org-export--registered-backends
691 \(org-remove-if-not
692 \(lambda (backend)
693 \(let ((name (org-export-backend-name backend)))
694 \(or (memq name val)
695 \(catch 'parentp
696 \(dolist (b val)
697 \(and (org-export-derived-backend-p b name)
698 \(throw 'parentp t)))))))
699 org-export--registered-backends))
700 \(let ((new-list (mapcar 'org-export-backend-name
701 org-export--registered-backends)))
702 \(dolist (backend val)
703 \(cond
704 \((not (load (format \"ox-%s\" backend) t t))
705 \(message \"Problems while trying to load export back-end `%s'\"
706 backend))
707 \((not (memq backend new-list)) (push backend new-list))))
708 \(set-default 'org-export-backends new-list)))
710 Adding a back-end to this list will also pull the back-end it
711 depends on, if any."
712 :group 'org
713 :group 'org-export
714 :version "24.4"
715 :package-version '(Org . "8.0")
716 :initialize 'custom-initialize-set
717 :set (lambda (var val)
718 (if (not (featurep 'ox)) (set-default var val)
719 ;; Any back-end not required anymore (not present in VAL and not
720 ;; a parent of any back-end in the new value) is removed from the
721 ;; list of registered back-ends.
722 (setq org-export--registered-backends
723 (org-remove-if-not
724 (lambda (backend)
725 (let ((name (org-export-backend-name backend)))
726 (or (memq name val)
727 (catch 'parentp
728 (dolist (b val)
729 (and (org-export-derived-backend-p b name)
730 (throw 'parentp t)))))))
731 org-export--registered-backends))
732 ;; Now build NEW-LIST of both new back-ends and required
733 ;; parents.
734 (let ((new-list (mapcar 'org-export-backend-name
735 org-export--registered-backends)))
736 (dolist (backend val)
737 (cond
738 ((not (load (format "ox-%s" backend) t t))
739 (message "Problems while trying to load export back-end `%s'"
740 backend))
741 ((not (memq backend new-list)) (push backend new-list))))
742 ;; Set VAR to that list with fixed dependencies.
743 (set-default var new-list))))
744 :type '(set :greedy t
745 (const :tag " ascii Export buffer to ASCII format" ascii)
746 (const :tag " beamer Export buffer to Beamer presentation" beamer)
747 (const :tag " html Export buffer to HTML format" html)
748 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
749 (const :tag " latex Export buffer to LaTeX format" latex)
750 (const :tag " man Export buffer to MAN format" man)
751 (const :tag " md Export buffer to Markdown format" md)
752 (const :tag " odt Export buffer to ODT format" odt)
753 (const :tag " org Export buffer to Org format" org)
754 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
755 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
756 (const :tag "C deck Export buffer to deck.js presentations" deck)
757 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
758 (const :tag "C groff Export buffer to Groff format" groff)
759 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
760 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
761 (const :tag "C s5 Export buffer to s5 presentations" s5)
762 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
764 (eval-after-load 'ox
765 '(mapc
766 (lambda (backend)
767 (condition-case nil (require (intern (format "ox-%s" backend)))
768 (error (message "Problems while trying to load export back-end `%s'"
769 backend))))
770 org-export-backends))
772 (defcustom org-support-shift-select nil
773 "Non-nil means make shift-cursor commands select text when possible.
775 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
776 start selecting a region, or enlarge regions started in this way.
777 In Org-mode, in special contexts, these same keys are used for
778 other purposes, important enough to compete with shift selection.
779 Org tries to balance these needs by supporting `shift-select-mode'
780 outside these special contexts, under control of this variable.
782 The default of this variable is nil, to avoid confusing behavior. Shifted
783 cursor keys will then execute Org commands in the following contexts:
784 - on a headline, changing TODO state (left/right) and priority (up/down)
785 - on a time stamp, changing the time
786 - in a plain list item, changing the bullet type
787 - in a property definition line, switching between allowed values
788 - in the BEGIN line of a clock table (changing the time block).
789 Outside these contexts, the commands will throw an error.
791 When this variable is t and the cursor is not in a special
792 context, Org-mode will support shift-selection for making and
793 enlarging regions. To make this more effective, the bullet
794 cycling will no longer happen anywhere in an item line, but only
795 if the cursor is exactly on the bullet.
797 If you set this variable to the symbol `always', then the keys
798 will not be special in headlines, property lines, and item lines,
799 to make shift selection work there as well. If this is what you
800 want, you can use the following alternative commands: `C-c C-t'
801 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
802 can be used to switch TODO sets, `C-c -' to cycle item bullet
803 types, and properties can be edited by hand or in column view.
805 However, when the cursor is on a timestamp, shift-cursor commands
806 will still edit the time stamp - this is just too good to give up.
808 XEmacs user should have this variable set to nil, because
809 `shift-select-mode' is in Emacs 23 or later only."
810 :group 'org
811 :type '(choice
812 (const :tag "Never" nil)
813 (const :tag "When outside special context" t)
814 (const :tag "Everywhere except timestamps" always)))
816 (defcustom org-loop-over-headlines-in-active-region nil
817 "Shall some commands act upon headlines in the active region?
819 When set to `t', some commands will be performed in all headlines
820 within the active region.
822 When set to `start-level', some commands will be performed in all
823 headlines within the active region, provided that these headlines
824 are of the same level than the first one.
826 When set to a string, those commands will be performed on the
827 matching headlines within the active region. Such string must be
828 a tags/property/todo match as it is used in the agenda tags view.
830 The list of commands is: `org-schedule', `org-deadline',
831 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
832 `org-archive-to-archive-sibling'. The archiving commands skip
833 already archived entries."
834 :type '(choice (const :tag "Don't loop" nil)
835 (const :tag "All headlines in active region" t)
836 (const :tag "In active region, headlines at the same level than the first one" start-level)
837 (string :tag "Tags/Property/Todo matcher"))
838 :version "24.1"
839 :group 'org-todo
840 :group 'org-archive)
842 (defgroup org-startup nil
843 "Options concerning startup of Org-mode."
844 :tag "Org Startup"
845 :group 'org)
847 (defcustom org-startup-folded t
848 "Non-nil means entering Org-mode will switch to OVERVIEW.
849 This can also be configured on a per-file basis by adding one of
850 the following lines anywhere in the buffer:
852 #+STARTUP: fold (or `overview', this is equivalent)
853 #+STARTUP: nofold (or `showall', this is equivalent)
854 #+STARTUP: content
855 #+STARTUP: showeverything
857 By default, this option is ignored when Org opens agenda files
858 for the first time. If you want the agenda to honor the startup
859 option, set `org-agenda-inhibit-startup' to nil."
860 :group 'org-startup
861 :type '(choice
862 (const :tag "nofold: show all" nil)
863 (const :tag "fold: overview" t)
864 (const :tag "content: all headlines" content)
865 (const :tag "show everything, even drawers" showeverything)))
867 (defcustom org-startup-truncated t
868 "Non-nil means entering Org-mode will set `truncate-lines'.
869 This is useful since some lines containing links can be very long and
870 uninteresting. Also tables look terrible when wrapped."
871 :group 'org-startup
872 :type 'boolean)
874 (defcustom org-startup-indented nil
875 "Non-nil means turn on `org-indent-mode' on startup.
876 This can also be configured on a per-file basis by adding one of
877 the following lines anywhere in the buffer:
879 #+STARTUP: indent
880 #+STARTUP: noindent"
881 :group 'org-structure
882 :type '(choice
883 (const :tag "Not" nil)
884 (const :tag "Globally (slow on startup in large files)" t)))
886 (defcustom org-use-sub-superscripts t
887 "Non-nil means interpret \"_\" and \"^\" for display.
889 If you want to control how Org exports those characters, see
890 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
891 used to be an alias for `org-export-with-sub-superscripts' in
892 Org <8.0, it is not anymore.
894 When this option is turned on, you can use TeX-like syntax for
895 sub- and superscripts within the buffer. Several characters after
896 \"_\" or \"^\" will be considered as a single item - so grouping
897 with {} is normally not needed. For example, the following things
898 will be parsed as single sub- or superscripts:
900 10^24 or 10^tau several digits will be considered 1 item.
901 10^-12 or 10^-tau a leading sign with digits or a word
902 x^2-y^3 will be read as x^2 - y^3, because items are
903 terminated by almost any nonword/nondigit char.
904 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
906 Still, ambiguity is possible. So when in doubt, use {} to enclose
907 the sub/superscript. If you set this variable to the symbol `{}',
908 the braces are *required* in order to trigger interpretations as
909 sub/superscript. This can be helpful in documents that need \"_\"
910 frequently in plain text."
911 :group 'org-startup
912 :version "24.4"
913 :package-version '(Org . "8.0")
914 :type '(choice
915 (const :tag "Always interpret" t)
916 (const :tag "Only with braces" {})
917 (const :tag "Never interpret" nil)))
919 (defcustom org-startup-with-beamer-mode nil
920 "Non-nil means turn on `org-beamer-mode' on startup.
921 This can also be configured on a per-file basis by adding one of
922 the following lines anywhere in the buffer:
924 #+STARTUP: beamer"
925 :group 'org-startup
926 :version "24.1"
927 :type 'boolean)
929 (defcustom org-startup-align-all-tables nil
930 "Non-nil means align all tables when visiting a file.
931 This is useful when the column width in tables is forced with <N> cookies
932 in table fields. Such tables will look correct only after the first re-align.
933 This can also be configured on a per-file basis by adding one of
934 the following lines anywhere in the buffer:
935 #+STARTUP: align
936 #+STARTUP: noalign"
937 :group 'org-startup
938 :type 'boolean)
940 (defcustom org-startup-with-inline-images nil
941 "Non-nil means show inline images when loading a new Org file.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
944 #+STARTUP: inlineimages
945 #+STARTUP: noinlineimages"
946 :group 'org-startup
947 :version "24.1"
948 :type 'boolean)
950 (defcustom org-startup-with-latex-preview nil
951 "Non-nil means preview LaTeX fragments when loading a new Org file.
953 This can also be configured on a per-file basis by adding one of
954 the following lines anywhere in the buffer:
955 #+STARTUP: latexpreview
956 #+STARTUP: nolatexpreview"
957 :group 'org-startup
958 :version "24.4"
959 :package-version '(Org . "8.0")
960 :type 'boolean)
962 (defcustom org-insert-mode-line-in-empty-file nil
963 "Non-nil means insert the first line setting Org-mode in empty files.
964 When the function `org-mode' is called interactively in an empty file, this
965 normally means that the file name does not automatically trigger Org-mode.
966 To ensure that the file will always be in Org-mode in the future, a
967 line enforcing Org-mode will be inserted into the buffer, if this option
968 has been set."
969 :group 'org-startup
970 :type 'boolean)
972 (defcustom org-replace-disputed-keys nil
973 "Non-nil means use alternative key bindings for some keys.
974 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
975 These keys are also used by other packages like shift-selection-mode'
976 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
977 If you want to use Org-mode together with one of these other modes,
978 or more generally if you would like to move some Org-mode commands to
979 other keys, set this variable and configure the keys with the variable
980 `org-disputed-keys'.
982 This option is only relevant at load-time of Org-mode, and must be set
983 *before* org.el is loaded. Changing it requires a restart of Emacs to
984 become effective."
985 :group 'org-startup
986 :type 'boolean)
988 (defcustom org-use-extra-keys nil
989 "Non-nil means use extra key sequence definitions for certain commands.
990 This happens automatically if you run XEmacs or if `window-system'
991 is nil. This variable lets you do the same manually. You must
992 set it before loading org.
994 Example: on Carbon Emacs 22 running graphically, with an external
995 keyboard on a Powerbook, the default way of setting M-left might
996 not work for either Alt or ESC. Setting this variable will make
997 it work for ESC."
998 :group 'org-startup
999 :type 'boolean)
1001 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1003 (defcustom org-disputed-keys
1004 '(([(shift up)] . [(meta p)])
1005 ([(shift down)] . [(meta n)])
1006 ([(shift left)] . [(meta -)])
1007 ([(shift right)] . [(meta +)])
1008 ([(control shift right)] . [(meta shift +)])
1009 ([(control shift left)] . [(meta shift -)]))
1010 "Keys for which Org-mode and other modes compete.
1011 This is an alist, cars are the default keys, second element specifies
1012 the alternative to use when `org-replace-disputed-keys' is t.
1014 Keys can be specified in any syntax supported by `define-key'.
1015 The value of this option takes effect only at Org-mode's startup,
1016 therefore you'll have to restart Emacs to apply it after changing."
1017 :group 'org-startup
1018 :type 'alist)
1020 (defun org-key (key)
1021 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1022 Or return the original if not disputed.
1023 Also apply the translations defined in `org-xemacs-key-equivalents'."
1024 (when org-replace-disputed-keys
1025 (let* ((nkey (key-description key))
1026 (x (org-find-if (lambda (x)
1027 (equal (key-description (car x)) nkey))
1028 org-disputed-keys)))
1029 (setq key (if x (cdr x) key))))
1030 (when (featurep 'xemacs)
1031 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1032 key)
1034 (defun org-find-if (predicate seq)
1035 (catch 'exit
1036 (while seq
1037 (if (funcall predicate (car seq))
1038 (throw 'exit (car seq))
1039 (pop seq)))))
1041 (defun org-defkey (keymap key def)
1042 "Define a key, possibly translated, as returned by `org-key'."
1043 (define-key keymap (org-key key) def))
1045 (defcustom org-ellipsis nil
1046 "The ellipsis to use in the Org-mode outline.
1047 When nil, just use the standard three dots.
1048 When a string, use that string instead.
1049 When a face, use the standard 3 dots, but with the specified face.
1050 The change affects only Org-mode (which will then use its own display table).
1051 Changing this requires executing \\[org-mode] in a buffer to become
1052 effective."
1053 :group 'org-startup
1054 :type '(choice (const :tag "Default" nil)
1055 (face :tag "Face" :value org-warning)
1056 (string :tag "String" :value "...#")))
1058 (defvar org-display-table nil
1059 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1061 (defgroup org-keywords nil
1062 "Keywords in Org-mode."
1063 :tag "Org Keywords"
1064 :group 'org)
1066 (defcustom org-closed-keep-when-no-todo nil
1067 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1068 :group 'org-todo
1069 :group 'org-keywords
1070 :version "24.4"
1071 :package-version '(Org . "8.0")
1072 :type 'boolean)
1074 (defgroup org-structure nil
1075 "Options concerning the general structure of Org-mode files."
1076 :tag "Org Structure"
1077 :group 'org)
1079 (defgroup org-reveal-location nil
1080 "Options about how to make context of a location visible."
1081 :tag "Org Reveal Location"
1082 :group 'org-structure)
1084 (defconst org-context-choice
1085 '(choice
1086 (const :tag "Always" t)
1087 (const :tag "Never" nil)
1088 (repeat :greedy t :tag "Individual contexts"
1089 (cons
1090 (choice :tag "Context"
1091 (const agenda)
1092 (const org-goto)
1093 (const occur-tree)
1094 (const tags-tree)
1095 (const link-search)
1096 (const mark-goto)
1097 (const bookmark-jump)
1098 (const isearch)
1099 (const default))
1100 (boolean))))
1101 "Contexts for the reveal options.")
1103 (defcustom org-show-hierarchy-above '((default . t))
1104 "Non-nil means show full hierarchy when revealing a location.
1105 Org-mode often shows locations in an org-mode file which might have
1106 been invisible before. When this is set, the hierarchy of headings
1107 above the exposed location is shown.
1108 Turning this off for example for sparse trees makes them very compact.
1109 Instead of t, this can also be an alist specifying this option for different
1110 contexts. Valid contexts are
1111 agenda when exposing an entry from the agenda
1112 org-goto when using the command `org-goto' on key C-c C-j
1113 occur-tree when using the command `org-occur' on key C-c /
1114 tags-tree when constructing a sparse tree based on tags matches
1115 link-search when exposing search matches associated with a link
1116 mark-goto when exposing the jump goal of a mark
1117 bookmark-jump when exposing a bookmark location
1118 isearch when exiting from an incremental search
1119 default default for all contexts not set explicitly"
1120 :group 'org-reveal-location
1121 :type org-context-choice)
1123 (defcustom org-show-following-heading '((default . nil))
1124 "Non-nil means show following heading when revealing a location.
1125 Org-mode often shows locations in an org-mode file which might have
1126 been invisible before. When this is set, the heading following the
1127 match is shown.
1128 Turning this off for example for sparse trees makes them very compact,
1129 but makes it harder to edit the location of the match. In such a case,
1130 use the command \\[org-reveal] to show more context.
1131 Instead of t, this can also be an alist specifying this option for different
1132 contexts. See `org-show-hierarchy-above' for valid contexts."
1133 :group 'org-reveal-location
1134 :type org-context-choice)
1136 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1137 "Non-nil means show all sibling heading when revealing a location.
1138 Org-mode often shows locations in an org-mode file which might have
1139 been invisible before. When this is set, the sibling of the current entry
1140 heading are all made visible. If `org-show-hierarchy-above' is t,
1141 the same happens on each level of the hierarchy above the current entry.
1143 By default this is on for the isearch context, off for all other contexts.
1144 Turning this off for example for sparse trees makes them very compact,
1145 but makes it harder to edit the location of the match. In such a case,
1146 use the command \\[org-reveal] to show more context.
1147 Instead of t, this can also be an alist specifying this option for different
1148 contexts. See `org-show-hierarchy-above' for valid contexts."
1149 :group 'org-reveal-location
1150 :type org-context-choice
1151 :version "24.4"
1152 :package-version '(Org . "8.0"))
1154 (defcustom org-show-entry-below '((default . nil))
1155 "Non-nil means show the entry below a headline when revealing a location.
1156 Org-mode often shows locations in an org-mode file which might have
1157 been invisible before. When this is set, the text below the headline that is
1158 exposed is also shown.
1160 By default this is off for all contexts.
1161 Instead of t, this can also be an alist specifying this option for different
1162 contexts. See `org-show-hierarchy-above' for valid contexts."
1163 :group 'org-reveal-location
1164 :type org-context-choice)
1166 (defcustom org-indirect-buffer-display 'other-window
1167 "How should indirect tree buffers be displayed?
1168 This applies to indirect buffers created with the commands
1169 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1170 Valid values are:
1171 current-window Display in the current window
1172 other-window Just display in another window.
1173 dedicated-frame Create one new frame, and re-use it each time.
1174 new-frame Make a new frame each time. Note that in this case
1175 previously-made indirect buffers are kept, and you need to
1176 kill these buffers yourself."
1177 :group 'org-structure
1178 :group 'org-agenda-windows
1179 :type '(choice
1180 (const :tag "In current window" current-window)
1181 (const :tag "In current frame, other window" other-window)
1182 (const :tag "Each time a new frame" new-frame)
1183 (const :tag "One dedicated frame" dedicated-frame)))
1185 (defcustom org-use-speed-commands nil
1186 "Non-nil means activate single letter commands at beginning of a headline.
1187 This may also be a function to test for appropriate locations where speed
1188 commands should be active.
1190 For example, to activate speed commands when the point is on any
1191 star at the beginning of the headline, you can do this:
1193 (setq org-use-speed-commands
1194 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1195 :group 'org-structure
1196 :type '(choice
1197 (const :tag "Never" nil)
1198 (const :tag "At beginning of headline stars" t)
1199 (function)))
1201 (defcustom org-speed-commands-user nil
1202 "Alist of additional speed commands.
1203 This list will be checked before `org-speed-commands-default'
1204 when the variable `org-use-speed-commands' is non-nil
1205 and when the cursor is at the beginning of a headline.
1206 The car if each entry is a string with a single letter, which must
1207 be assigned to `self-insert-command' in the global map.
1208 The cdr is either a command to be called interactively, a function
1209 to be called, or a form to be evaluated.
1210 An entry that is just a list with a single string will be interpreted
1211 as a descriptive headline that will be added when listing the speed
1212 commands in the Help buffer using the `?' speed command."
1213 :group 'org-structure
1214 :type '(repeat :value ("k" . ignore)
1215 (choice :value ("k" . ignore)
1216 (list :tag "Descriptive Headline" (string :tag "Headline"))
1217 (cons :tag "Letter and Command"
1218 (string :tag "Command letter")
1219 (choice
1220 (function)
1221 (sexp))))))
1223 (defcustom org-bookmark-names-plist
1224 '(:last-capture "org-capture-last-stored"
1225 :last-refile "org-refile-last-stored"
1226 :last-capture-marker "org-capture-last-stored-marker")
1227 "Names for bookmarks automatically set by some Org commands.
1228 This can provide strings as names for a number of bookmarks Org sets
1229 automatically. The following keys are currently implemented:
1230 :last-capture
1231 :last-capture-marker
1232 :last-refile
1233 When a key does not show up in the property list, the corresponding bookmark
1234 is not set."
1235 :group 'org-structure
1236 :type 'plist)
1238 (defgroup org-cycle nil
1239 "Options concerning visibility cycling in Org-mode."
1240 :tag "Org Cycle"
1241 :group 'org-structure)
1243 (defcustom org-cycle-skip-children-state-if-no-children t
1244 "Non-nil means skip CHILDREN state in entries that don't have any."
1245 :group 'org-cycle
1246 :type 'boolean)
1248 (defcustom org-cycle-max-level nil
1249 "Maximum level which should still be subject to visibility cycling.
1250 Levels higher than this will, for cycling, be treated as text, not a headline.
1251 When `org-odd-levels-only' is set, a value of N in this variable actually
1252 means 2N-1 stars as the limiting headline.
1253 When nil, cycle all levels.
1254 Note that the limiting level of cycling is also influenced by
1255 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1256 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1257 than its value."
1258 :group 'org-cycle
1259 :type '(choice
1260 (const :tag "No limit" nil)
1261 (integer :tag "Maximum level")))
1263 (defcustom org-hide-block-startup nil
1264 "Non-nil means entering Org-mode will fold all blocks.
1265 This can also be set in on a per-file basis with
1267 #+STARTUP: hideblocks
1268 #+STARTUP: showblocks"
1269 :group 'org-startup
1270 :group 'org-cycle
1271 :type 'boolean)
1273 (defcustom org-cycle-global-at-bob nil
1274 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1275 This makes it possible to do global cycling without having to use S-TAB or
1276 \\[universal-argument] TAB. For this special case to work, the first line
1277 of the buffer must not be a headline -- it may be empty or some other text.
1278 When used in this way, `org-cycle-hook' is disabled temporarily to make
1279 sure the cursor stays at the beginning of the buffer. When this option is
1280 nil, don't do anything special at the beginning of the buffer."
1281 :group 'org-cycle
1282 :type 'boolean)
1284 (defcustom org-cycle-level-after-item/entry-creation t
1285 "Non-nil means cycle entry level or item indentation in new empty entries.
1287 When the cursor is at the end of an empty headline, i.e., with only stars
1288 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1289 and then all possible ancestor states, before returning to the original state.
1290 This makes data entry extremely fast: M-RET to create a new headline,
1291 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1293 When the cursor is at the end of an empty plain list item, one TAB will
1294 make it a subitem, two or more tabs will back up to make this an item
1295 higher up in the item hierarchy."
1296 :group 'org-cycle
1297 :type 'boolean)
1299 (defcustom org-cycle-emulate-tab t
1300 "Where should `org-cycle' emulate TAB.
1301 nil Never
1302 white Only in completely white lines
1303 whitestart Only at the beginning of lines, before the first non-white char
1304 t Everywhere except in headlines
1305 exc-hl-bol Everywhere except at the start of a headline
1306 If TAB is used in a place where it does not emulate TAB, the current subtree
1307 visibility is cycled."
1308 :group 'org-cycle
1309 :type '(choice (const :tag "Never" nil)
1310 (const :tag "Only in completely white lines" white)
1311 (const :tag "Before first char in a line" whitestart)
1312 (const :tag "Everywhere except in headlines" t)
1313 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1315 (defcustom org-cycle-separator-lines 2
1316 "Number of empty lines needed to keep an empty line between collapsed trees.
1317 If you leave an empty line between the end of a subtree and the following
1318 headline, this empty line is hidden when the subtree is folded.
1319 Org-mode will leave (exactly) one empty line visible if the number of
1320 empty lines is equal or larger to the number given in this variable.
1321 So the default 2 means at least 2 empty lines after the end of a subtree
1322 are needed to produce free space between a collapsed subtree and the
1323 following headline.
1325 If the number is negative, and the number of empty lines is at least -N,
1326 all empty lines are shown.
1328 Special case: when 0, never leave empty lines in collapsed view."
1329 :group 'org-cycle
1330 :type 'integer)
1331 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1333 (defcustom org-pre-cycle-hook nil
1334 "Hook that is run before visibility cycling is happening.
1335 The function(s) in this hook must accept a single argument which indicates
1336 the new state that will be set right after running this hook. The
1337 argument is a symbol. Before a global state change, it can have the values
1338 `overview', `content', or `all'. Before a local state change, it can have
1339 the values `folded', `children', or `subtree'."
1340 :group 'org-cycle
1341 :type 'hook)
1343 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1344 org-cycle-hide-drawers
1345 org-cycle-hide-inline-tasks
1346 org-cycle-show-empty-lines
1347 org-optimize-window-after-visibility-change)
1348 "Hook that is run after `org-cycle' has changed the buffer visibility.
1349 The function(s) in this hook must accept a single argument which indicates
1350 the new state that was set by the most recent `org-cycle' command. The
1351 argument is a symbol. After a global state change, it can have the values
1352 `overview', `contents', or `all'. After a local state change, it can have
1353 the values `folded', `children', or `subtree'."
1354 :group 'org-cycle
1355 :type 'hook)
1357 (defgroup org-edit-structure nil
1358 "Options concerning structure editing in Org-mode."
1359 :tag "Org Edit Structure"
1360 :group 'org-structure)
1362 (defcustom org-odd-levels-only nil
1363 "Non-nil means skip even levels and only use odd levels for the outline.
1364 This has the effect that two stars are being added/taken away in
1365 promotion/demotion commands. It also influences how levels are
1366 handled by the exporters.
1367 Changing it requires restart of `font-lock-mode' to become effective
1368 for fontification also in regions already fontified.
1369 You may also set this on a per-file basis by adding one of the following
1370 lines to the buffer:
1372 #+STARTUP: odd
1373 #+STARTUP: oddeven"
1374 :group 'org-edit-structure
1375 :group 'org-appearance
1376 :type 'boolean)
1378 (defcustom org-adapt-indentation t
1379 "Non-nil means adapt indentation to outline node level.
1381 When this variable is set, Org assumes that you write outlines by
1382 indenting text in each node to align with the headline (after the stars).
1383 The following issues are influenced by this variable:
1385 - When this is set and the *entire* text in an entry is indented, the
1386 indentation is increased by one space in a demotion command, and
1387 decreased by one in a promotion command. If any line in the entry
1388 body starts with text at column 0, indentation is not changed at all.
1390 - Property drawers and planning information is inserted indented when
1391 this variable s set. When nil, they will not be indented.
1393 - TAB indents a line relative to context. The lines below a headline
1394 will be indented when this variable is set.
1396 Note that this is all about true indentation, by adding and removing
1397 space characters. See also `org-indent.el' which does level-dependent
1398 indentation in a virtual way, i.e. at display time in Emacs."
1399 :group 'org-edit-structure
1400 :type 'boolean)
1402 (defcustom org-special-ctrl-a/e nil
1403 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1405 When t, `C-a' will bring back the cursor to the beginning of the
1406 headline text, i.e. after the stars and after a possible TODO
1407 keyword. In an item, this will be the position after bullet and
1408 check-box, if any. When the cursor is already at that position,
1409 another `C-a' will bring it to the beginning of the line.
1411 `C-e' will jump to the end of the headline, ignoring the presence
1412 of tags in the headline. A second `C-e' will then jump to the
1413 true end of the line, after any tags. This also means that, when
1414 this variable is non-nil, `C-e' also will never jump beyond the
1415 end of the heading of a folded section, i.e. not after the
1416 ellipses.
1418 When set to the symbol `reversed', the first `C-a' or `C-e' works
1419 normally, going to the true line boundary first. Only a directly
1420 following, identical keypress will bring the cursor to the
1421 special positions.
1423 This may also be a cons cell where the behavior for `C-a' and
1424 `C-e' is set separately."
1425 :group 'org-edit-structure
1426 :type '(choice
1427 (const :tag "off" nil)
1428 (const :tag "on: after stars/bullet and before tags first" t)
1429 (const :tag "reversed: true line boundary first" reversed)
1430 (cons :tag "Set C-a and C-e separately"
1431 (choice :tag "Special C-a"
1432 (const :tag "off" nil)
1433 (const :tag "on: after stars/bullet first" t)
1434 (const :tag "reversed: before stars/bullet first" reversed))
1435 (choice :tag "Special C-e"
1436 (const :tag "off" nil)
1437 (const :tag "on: before tags first" t)
1438 (const :tag "reversed: after tags first" reversed)))))
1439 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1441 (defcustom org-special-ctrl-k nil
1442 "Non-nil means `C-k' will behave specially in headlines.
1443 When nil, `C-k' will call the default `kill-line' command.
1444 When t, the following will happen while the cursor is in the headline:
1446 - When the cursor is at the beginning of a headline, kill the entire
1447 line and possible the folded subtree below the line.
1448 - When in the middle of the headline text, kill the headline up to the tags.
1449 - When after the headline text, kill the tags."
1450 :group 'org-edit-structure
1451 :type 'boolean)
1453 (defcustom org-ctrl-k-protect-subtree nil
1454 "Non-nil means, do not delete a hidden subtree with C-k.
1455 When set to the symbol `error', simply throw an error when C-k is
1456 used to kill (part-of) a headline that has hidden text behind it.
1457 Any other non-nil value will result in a query to the user, if it is
1458 OK to kill that hidden subtree. When nil, kill without remorse."
1459 :group 'org-edit-structure
1460 :version "24.1"
1461 :type '(choice
1462 (const :tag "Do not protect hidden subtrees" nil)
1463 (const :tag "Protect hidden subtrees with a security query" t)
1464 (const :tag "Never kill a hidden subtree with C-k" error)))
1466 (defcustom org-special-ctrl-o t
1467 "Non-nil means, make `C-o' insert a row in tables."
1468 :group 'org-edit-structure
1469 :type 'boolean)
1471 (defcustom org-catch-invisible-edits nil
1472 "Check if in invisible region before inserting or deleting a character.
1473 Valid values are:
1475 nil Do not check, so just do invisible edits.
1476 error Throw an error and do nothing.
1477 show Make point visible, and do the requested edit.
1478 show-and-error Make point visible, then throw an error and abort the edit.
1479 smart Make point visible, and do insertion/deletion if it is
1480 adjacent to visible text and the change feels predictable.
1481 Never delete a previously invisible character or add in the
1482 middle or right after an invisible region. Basically, this
1483 allows insertion and backward-delete right before ellipses.
1484 FIXME: maybe in this case we should not even show?"
1485 :group 'org-edit-structure
1486 :version "24.1"
1487 :type '(choice
1488 (const :tag "Do not check" nil)
1489 (const :tag "Throw error when trying to edit" error)
1490 (const :tag "Unhide, but do not do the edit" show-and-error)
1491 (const :tag "Show invisible part and do the edit" show)
1492 (const :tag "Be smart and do the right thing" smart)))
1494 (defcustom org-yank-folded-subtrees t
1495 "Non-nil means when yanking subtrees, fold them.
1496 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1497 it starts with a heading and all other headings in it are either children
1498 or siblings, then fold all the subtrees. However, do this only if no
1499 text after the yank would be swallowed into a folded tree by this action."
1500 :group 'org-edit-structure
1501 :type 'boolean)
1503 (defcustom org-yank-adjusted-subtrees nil
1504 "Non-nil means when yanking subtrees, adjust the level.
1505 With this setting, `org-paste-subtree' is used to insert the subtree, see
1506 this function for details."
1507 :group 'org-edit-structure
1508 :type 'boolean)
1510 (defcustom org-M-RET-may-split-line '((default . t))
1511 "Non-nil means M-RET will split the line at the cursor position.
1512 When nil, it will go to the end of the line before making a
1513 new line.
1514 You may also set this option in a different way for different
1515 contexts. Valid contexts are:
1517 headline when creating a new headline
1518 item when creating a new item
1519 table in a table field
1520 default the value to be used for all contexts not explicitly
1521 customized"
1522 :group 'org-structure
1523 :group 'org-table
1524 :type '(choice
1525 (const :tag "Always" t)
1526 (const :tag "Never" nil)
1527 (repeat :greedy t :tag "Individual contexts"
1528 (cons
1529 (choice :tag "Context"
1530 (const headline)
1531 (const item)
1532 (const table)
1533 (const default))
1534 (boolean)))))
1537 (defcustom org-insert-heading-respect-content nil
1538 "Non-nil means insert new headings after the current subtree.
1539 When nil, the new heading is created directly after the current line.
1540 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1541 this variable on for the duration of the command."
1542 :group 'org-structure
1543 :type 'boolean)
1545 (defcustom org-blank-before-new-entry '((heading . auto)
1546 (plain-list-item . auto))
1547 "Should `org-insert-heading' leave a blank line before new heading/item?
1548 The value is an alist, with `heading' and `plain-list-item' as CAR,
1549 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1550 which case Org will look at the surrounding headings/items and try to
1551 make an intelligent decision whether to insert a blank line or not.
1553 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1554 the setting here is ignored and no empty line is inserted to avoid breaking
1555 the list structure."
1556 :group 'org-edit-structure
1557 :type '(list
1558 (cons (const heading)
1559 (choice (const :tag "Never" nil)
1560 (const :tag "Always" t)
1561 (const :tag "Auto" auto)))
1562 (cons (const plain-list-item)
1563 (choice (const :tag "Never" nil)
1564 (const :tag "Always" t)
1565 (const :tag "Auto" auto)))))
1567 (defcustom org-insert-heading-hook nil
1568 "Hook being run after inserting a new heading."
1569 :group 'org-edit-structure
1570 :type 'hook)
1572 (defcustom org-enable-fixed-width-editor t
1573 "Non-nil means lines starting with \":\" are treated as fixed-width.
1574 This currently only means they are never auto-wrapped.
1575 When nil, such lines will be treated like ordinary lines."
1576 :group 'org-edit-structure
1577 :type 'boolean)
1579 (defcustom org-goto-auto-isearch t
1580 "Non-nil means typing characters in `org-goto' starts incremental search.
1581 When nil, you can use these keybindings to navigate the buffer:
1583 q Quit the org-goto interface
1584 n Go to the next visible heading
1585 p Go to the previous visible heading
1586 f Go one heading forward on same level
1587 b Go one heading backward on same level
1588 u Go one heading up"
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defgroup org-sparse-trees nil
1593 "Options concerning sparse trees in Org-mode."
1594 :tag "Org Sparse Trees"
1595 :group 'org-structure)
1597 (defcustom org-highlight-sparse-tree-matches t
1598 "Non-nil means highlight all matches that define a sparse tree.
1599 The highlights will automatically disappear the next time the buffer is
1600 changed by an edit command."
1601 :group 'org-sparse-trees
1602 :type 'boolean)
1604 (defcustom org-remove-highlights-with-change t
1605 "Non-nil means any change to the buffer will remove temporary highlights.
1606 Such highlights are created by `org-occur' and `org-clock-display'.
1607 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1608 The highlights created by `org-toggle-latex-fragment' always need
1609 `C-c C-x C-l' to be removed."
1610 :group 'org-sparse-trees
1611 :group 'org-time
1612 :type 'boolean)
1615 (defcustom org-occur-hook '(org-first-headline-recenter)
1616 "Hook that is run after `org-occur' has constructed a sparse tree.
1617 This can be used to recenter the window to show as much of the structure
1618 as possible."
1619 :group 'org-sparse-trees
1620 :type 'hook)
1622 (defgroup org-imenu-and-speedbar nil
1623 "Options concerning imenu and speedbar in Org-mode."
1624 :tag "Org Imenu and Speedbar"
1625 :group 'org-structure)
1627 (defcustom org-imenu-depth 2
1628 "The maximum level for Imenu access to Org-mode headlines.
1629 This also applied for speedbar access."
1630 :group 'org-imenu-and-speedbar
1631 :type 'integer)
1633 (defgroup org-table nil
1634 "Options concerning tables in Org-mode."
1635 :tag "Org Table"
1636 :group 'org)
1638 (defcustom org-enable-table-editor 'optimized
1639 "Non-nil means lines starting with \"|\" are handled by the table editor.
1640 When nil, such lines will be treated like ordinary lines.
1642 When equal to the symbol `optimized', the table editor will be optimized to
1643 do the following:
1644 - Automatic overwrite mode in front of whitespace in table fields.
1645 This makes the structure of the table stay in tact as long as the edited
1646 field does not exceed the column width.
1647 - Minimize the number of realigns. Normally, the table is aligned each time
1648 TAB or RET are pressed to move to another field. With optimization this
1649 happens only if changes to a field might have changed the column width.
1650 Optimization requires replacing the functions `self-insert-command',
1651 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1652 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1653 very good at guessing when a re-align will be necessary, but you can always
1654 force one with \\[org-ctrl-c-ctrl-c].
1656 If you would like to use the optimized version in Org-mode, but the
1657 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1659 This variable can be used to turn on and off the table editor during a session,
1660 but in order to toggle optimization, a restart is required.
1662 See also the variable `org-table-auto-blank-field'."
1663 :group 'org-table
1664 :type '(choice
1665 (const :tag "off" nil)
1666 (const :tag "on" t)
1667 (const :tag "on, optimized" optimized)))
1669 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1670 (version<= emacs-version "24.1"))
1671 "Non-nil means cluster self-insert commands for undo when possible.
1672 If this is set, then, like in the Emacs command loop, 20 consecutive
1673 characters will be undone together.
1674 This is configurable, because there is some impact on typing performance."
1675 :group 'org-table
1676 :type 'boolean)
1678 (defcustom org-table-tab-recognizes-table.el t
1679 "Non-nil means TAB will automatically notice a table.el table.
1680 When it sees such a table, it moves point into it and - if necessary -
1681 calls `table-recognize-table'."
1682 :group 'org-table-editing
1683 :type 'boolean)
1685 (defgroup org-link nil
1686 "Options concerning links in Org-mode."
1687 :tag "Org Link"
1688 :group 'org)
1690 (defvar org-link-abbrev-alist-local nil
1691 "Buffer-local version of `org-link-abbrev-alist', which see.
1692 The value of this is taken from the #+LINK lines.")
1693 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1695 (defcustom org-link-abbrev-alist nil
1696 "Alist of link abbreviations.
1697 The car of each element is a string, to be replaced at the start of a link.
1698 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1699 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1701 [[linkkey:tag][description]]
1703 The 'linkkey' must be a word word, starting with a letter, followed
1704 by letters, numbers, '-' or '_'.
1706 If REPLACE is a string, the tag will simply be appended to create the link.
1707 If the string contains \"%s\", the tag will be inserted there. If the string
1708 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1709 at that point (see the function `url-hexify-string'). If the string contains
1710 the specifier \"%(my-function)\", then the custom function `my-function' will
1711 be invoked: this function takes the tag as its only argument and must return
1712 a string.
1714 REPLACE may also be a function that will be called with the tag as the
1715 only argument to create the link, which should be returned as a string.
1717 See the manual for examples."
1718 :group 'org-link
1719 :type '(repeat
1720 (cons
1721 (string :tag "Protocol")
1722 (choice
1723 (string :tag "Format")
1724 (function)))))
1726 (defcustom org-descriptive-links t
1727 "Non-nil means Org will display descriptive links.
1728 E.g. [[http://orgmode.org][Org website]] will be displayed as
1729 \"Org Website\", hiding the link itself and just displaying its
1730 description. When set to `nil', Org will display the full links
1731 literally.
1733 You can interactively set the value of this variable by calling
1734 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1735 :group 'org-link
1736 :type 'boolean)
1738 (defcustom org-link-file-path-type 'adaptive
1739 "How the path name in file links should be stored.
1740 Valid values are:
1742 relative Relative to the current directory, i.e. the directory of the file
1743 into which the link is being inserted.
1744 absolute Absolute path, if possible with ~ for home directory.
1745 noabbrev Absolute path, no abbreviation of home directory.
1746 adaptive Use relative path for files in the current directory and sub-
1747 directories of it. For other files, use an absolute path."
1748 :group 'org-link
1749 :type '(choice
1750 (const relative)
1751 (const absolute)
1752 (const noabbrev)
1753 (const adaptive)))
1755 (defvaralias 'org-activate-links 'org-highlight-links)
1756 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1757 "Types of links that should be highlighted in Org-mode files.
1759 This is a list of symbols, each one of them leading to the
1760 highlighting of a certain link type.
1762 You can still open links that are not highlighted.
1764 In principle, it does not hurt to turn on highlighting for all
1765 link types. There may be a small gain when turning off unused
1766 link types. The types are:
1768 bracket The recommended [[link][description]] or [[link]] links with hiding.
1769 angle Links in angular brackets that may contain whitespace like
1770 <bbdb:Carsten Dominik>.
1771 plain Plain links in normal text, no whitespace, like http://google.com.
1772 radio Text that is matched by a radio target, see manual for details.
1773 tag Tag settings in a headline (link to tag search).
1774 date Time stamps (link to calendar).
1775 footnote Footnote labels.
1777 If you set this variable during an Emacs session, use `org-mode-restart'
1778 in the Org buffer so that the change takes effect."
1779 :group 'org-link
1780 :group 'org-appearance
1781 :type '(set :greedy t
1782 (const :tag "Double bracket links" bracket)
1783 (const :tag "Angular bracket links" angle)
1784 (const :tag "Plain text links" plain)
1785 (const :tag "Radio target matches" radio)
1786 (const :tag "Tags" tag)
1787 (const :tag "Timestamps" date)
1788 (const :tag "Footnotes" footnote)))
1790 (defcustom org-make-link-description-function nil
1791 "Function to use for generating link descriptions from links.
1792 When nil, the link location will be used. This function must take
1793 two parameters: the first one is the link, the second one is the
1794 description generated by `org-insert-link'. The function should
1795 return the description to use."
1796 :group 'org-link
1797 :type '(choice (const nil) (function)))
1799 (defgroup org-link-store nil
1800 "Options concerning storing links in Org-mode."
1801 :tag "Org Store Link"
1802 :group 'org-link)
1804 (defcustom org-url-hexify-p t
1805 "When non-nil, hexify URL when creating a link."
1806 :type 'boolean
1807 :version "24.3"
1808 :group 'org-link-store)
1810 (defcustom org-email-link-description-format "Email %c: %.30s"
1811 "Format of the description part of a link to an email or usenet message.
1812 The following %-escapes will be replaced by corresponding information:
1814 %F full \"From\" field
1815 %f name, taken from \"From\" field, address if no name
1816 %T full \"To\" field
1817 %t first name in \"To\" field, address if no name
1818 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1819 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1820 %s subject
1821 %d date
1822 %m message-id.
1824 You may use normal field width specification between the % and the letter.
1825 This is for example useful to limit the length of the subject.
1827 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1828 :group 'org-link-store
1829 :type 'string)
1831 (defcustom org-from-is-user-regexp
1832 (let (r1 r2)
1833 (when (and user-mail-address (not (string= user-mail-address "")))
1834 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1835 (when (and user-full-name (not (string= user-full-name "")))
1836 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1837 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1838 "Regexp matched against the \"From:\" header of an email or usenet message.
1839 It should match if the message is from the user him/herself."
1840 :group 'org-link-store
1841 :type 'regexp)
1843 (defcustom org-context-in-file-links t
1844 "Non-nil means file links from `org-store-link' contain context.
1845 A search string will be added to the file name with :: as separator and
1846 used to find the context when the link is activated by the command
1847 `org-open-at-point'. When this option is t, the entire active region
1848 will be placed in the search string of the file link. If set to a
1849 positive integer, only the first n lines of context will be stored.
1851 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1852 negates this setting for the duration of the command."
1853 :group 'org-link-store
1854 :type '(choice boolean integer))
1856 (defcustom org-keep-stored-link-after-insertion nil
1857 "Non-nil means keep link in list for entire session.
1859 The command `org-store-link' adds a link pointing to the current
1860 location to an internal list. These links accumulate during a session.
1861 The command `org-insert-link' can be used to insert links into any
1862 Org-mode file (offering completion for all stored links). When this
1863 option is nil, every link which has been inserted once using \\[org-insert-link]
1864 will be removed from the list, to make completing the unused links
1865 more efficient."
1866 :group 'org-link-store
1867 :type 'boolean)
1869 (defgroup org-link-follow nil
1870 "Options concerning following links in Org-mode."
1871 :tag "Org Follow Link"
1872 :group 'org-link)
1874 (defcustom org-link-translation-function nil
1875 "Function to translate links with different syntax to Org syntax.
1876 This can be used to translate links created for example by the Planner
1877 or emacs-wiki packages to Org syntax.
1878 The function must accept two parameters, a TYPE containing the link
1879 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1880 which is everything after the link protocol. It should return a cons
1881 with possibly modified values of type and path.
1882 Org contains a function for this, so if you set this variable to
1883 `org-translate-link-from-planner', you should be able follow many
1884 links created by planner."
1885 :group 'org-link-follow
1886 :type '(choice (const nil) (function)))
1888 (defcustom org-follow-link-hook nil
1889 "Hook that is run after a link has been followed."
1890 :group 'org-link-follow
1891 :type 'hook)
1893 (defcustom org-tab-follows-link nil
1894 "Non-nil means on links TAB will follow the link.
1895 Needs to be set before org.el is loaded.
1896 This really should not be used, it does not make sense, and the
1897 implementation is bad."
1898 :group 'org-link-follow
1899 :type 'boolean)
1901 (defcustom org-return-follows-link nil
1902 "Non-nil means on links RET will follow the link.
1903 In tables, the special behavior of RET has precedence."
1904 :group 'org-link-follow
1905 :type 'boolean)
1907 (defcustom org-mouse-1-follows-link
1908 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1909 "Non-nil means mouse-1 on a link will follow the link.
1910 A longer mouse click will still set point. Does not work on XEmacs.
1911 Needs to be set before org.el is loaded."
1912 :group 'org-link-follow
1913 :version "24.4"
1914 :package-version '(Org . "8.3")
1915 :type '(choice
1916 (const :tag "A double click follows the link" double)
1917 (const :tag "Unconditionally follow the link with mouse-1" t)
1918 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1920 (defcustom org-mark-ring-length 4
1921 "Number of different positions to be recorded in the ring.
1922 Changing this requires a restart of Emacs to work correctly."
1923 :group 'org-link-follow
1924 :type 'integer)
1926 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1927 "Non-nil means internal links in Org files must exactly match a headline.
1928 When nil, the link search tries to match a phrase with all words
1929 in the search text."
1930 :group 'org-link-follow
1931 :version "24.1"
1932 :type '(choice
1933 (const :tag "Use fuzzy text search" nil)
1934 (const :tag "Match only exact headline" t)
1935 (const :tag "Match exact headline or query to create it"
1936 query-to-create)))
1938 (defcustom org-link-frame-setup
1939 '((vm . vm-visit-folder-other-frame)
1940 (vm-imap . vm-visit-imap-folder-other-frame)
1941 (gnus . org-gnus-no-new-news)
1942 (file . find-file-other-window)
1943 (wl . wl-other-frame))
1944 "Setup the frame configuration for following links.
1945 When following a link with Emacs, it may often be useful to display
1946 this link in another window or frame. This variable can be used to
1947 set this up for the different types of links.
1948 For VM, use any of
1949 `vm-visit-folder'
1950 `vm-visit-folder-other-window'
1951 `vm-visit-folder-other-frame'
1952 For Gnus, use any of
1953 `gnus'
1954 `gnus-other-frame'
1955 `org-gnus-no-new-news'
1956 For FILE, use any of
1957 `find-file'
1958 `find-file-other-window'
1959 `find-file-other-frame'
1960 For Wanderlust use any of
1961 `wl'
1962 `wl-other-frame'
1963 For the calendar, use the variable `calendar-setup'.
1964 For BBDB, it is currently only possible to display the matches in
1965 another window."
1966 :group 'org-link-follow
1967 :type '(list
1968 (cons (const vm)
1969 (choice
1970 (const vm-visit-folder)
1971 (const vm-visit-folder-other-window)
1972 (const vm-visit-folder-other-frame)))
1973 (cons (const vm-imap)
1974 (choice
1975 (const vm-visit-imap-folder)
1976 (const vm-visit-imap-folder-other-window)
1977 (const vm-visit-imap-folder-other-frame)))
1978 (cons (const gnus)
1979 (choice
1980 (const gnus)
1981 (const gnus-other-frame)
1982 (const org-gnus-no-new-news)))
1983 (cons (const file)
1984 (choice
1985 (const find-file)
1986 (const find-file-other-window)
1987 (const find-file-other-frame)))
1988 (cons (const wl)
1989 (choice
1990 (const wl)
1991 (const wl-other-frame)))))
1993 (defcustom org-display-internal-link-with-indirect-buffer nil
1994 "Non-nil means use indirect buffer to display infile links.
1995 Activating internal links (from one location in a file to another location
1996 in the same file) normally just jumps to the location. When the link is
1997 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1998 is displayed in
1999 another window. When this option is set, the other window actually displays
2000 an indirect buffer clone of the current buffer, to avoid any visibility
2001 changes to the current buffer."
2002 :group 'org-link-follow
2003 :type 'boolean)
2005 (defcustom org-open-non-existing-files nil
2006 "Non-nil means `org-open-file' will open non-existing files.
2007 When nil, an error will be generated.
2008 This variable applies only to external applications because they
2009 might choke on non-existing files. If the link is to a file that
2010 will be opened in Emacs, the variable is ignored."
2011 :group 'org-link-follow
2012 :type 'boolean)
2014 (defcustom org-open-directory-means-index-dot-org nil
2015 "Non-nil means a link to a directory really means to index.org.
2016 When nil, following a directory link will run dired or open a finder/explorer
2017 window on that directory."
2018 :group 'org-link-follow
2019 :type 'boolean)
2021 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2022 "Non-nil means ask for confirmation before executing shell links.
2023 Shell links can be dangerous: just think about a link
2025 [[shell:rm -rf ~/*][Google Search]]
2027 This link would show up in your Org-mode document as \"Google Search\",
2028 but really it would remove your entire home directory.
2029 Therefore we advise against setting this variable to nil.
2030 Just change it to `y-or-n-p' if you want to confirm with a
2031 single keystroke rather than having to type \"yes\"."
2032 :group 'org-link-follow
2033 :type '(choice
2034 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2035 (const :tag "with y-or-n (faster)" y-or-n-p)
2036 (const :tag "no confirmation (dangerous)" nil)))
2037 (put 'org-confirm-shell-link-function
2038 'safe-local-variable
2039 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2041 (defcustom org-confirm-shell-link-not-regexp ""
2042 "A regexp to skip confirmation for shell links."
2043 :group 'org-link-follow
2044 :version "24.1"
2045 :type 'regexp)
2047 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2048 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2049 Elisp links can be dangerous: just think about a link
2051 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2053 This link would show up in your Org-mode document as \"Google Search\",
2054 but really it would remove your entire home directory.
2055 Therefore we advise against setting this variable to nil.
2056 Just change it to `y-or-n-p' if you want to confirm with a
2057 single keystroke rather than having to type \"yes\"."
2058 :group 'org-link-follow
2059 :type '(choice
2060 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2061 (const :tag "with y-or-n (faster)" y-or-n-p)
2062 (const :tag "no confirmation (dangerous)" nil)))
2063 (put 'org-confirm-shell-link-function
2064 'safe-local-variable
2065 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2067 (defcustom org-confirm-elisp-link-not-regexp ""
2068 "A regexp to skip confirmation for Elisp links."
2069 :group 'org-link-follow
2070 :version "24.1"
2071 :type 'regexp)
2073 (defconst org-file-apps-defaults-gnu
2074 '((remote . emacs)
2075 (system . mailcap)
2076 (t . mailcap))
2077 "Default file applications on a UNIX or GNU/Linux system.
2078 See `org-file-apps'.")
2080 (defconst org-file-apps-defaults-macosx
2081 '((remote . emacs)
2082 (t . "open %s")
2083 (system . "open %s")
2084 ("ps.gz" . "gv %s")
2085 ("eps.gz" . "gv %s")
2086 ("dvi" . "xdvi %s")
2087 ("fig" . "xfig %s"))
2088 "Default file applications on a MacOS X system.
2089 The system \"open\" is known as a default, but we use X11 applications
2090 for some files for which the OS does not have a good default.
2091 See `org-file-apps'.")
2093 (defconst org-file-apps-defaults-windowsnt
2094 (list
2095 '(remote . emacs)
2096 (cons t
2097 (list (if (featurep 'xemacs)
2098 'mswindows-shell-execute
2099 'w32-shell-execute)
2100 "open" 'file))
2101 (cons 'system
2102 (list (if (featurep 'xemacs)
2103 'mswindows-shell-execute
2104 'w32-shell-execute)
2105 "open" 'file)))
2106 "Default file applications on a Windows NT system.
2107 The system \"open\" is used for most files.
2108 See `org-file-apps'.")
2110 (defcustom org-file-apps
2111 '((auto-mode . emacs)
2112 ("\\.mm\\'" . default)
2113 ("\\.x?html?\\'" . default)
2114 ("\\.pdf\\'" . default))
2115 "External applications for opening `file:path' items in a document.
2116 Org-mode uses system defaults for different file types, but
2117 you can use this variable to set the application for a given file
2118 extension. The entries in this list are cons cells where the car identifies
2119 files and the cdr the corresponding command. Possible values for the
2120 file identifier are
2121 \"string\" A string as a file identifier can be interpreted in different
2122 ways, depending on its contents:
2124 - Alphanumeric characters only:
2125 Match links with this file extension.
2126 Example: (\"pdf\" . \"evince %s\")
2127 to open PDFs with evince.
2129 - Regular expression: Match links where the
2130 filename matches the regexp. If you want to
2131 use groups here, use shy groups.
2133 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2134 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2135 to open *.html and *.xhtml with firefox.
2137 - Regular expression which contains (non-shy) groups:
2138 Match links where the whole link, including \"::\", and
2139 anything after that, matches the regexp.
2140 In a custom command string, %1, %2, etc. are replaced with
2141 the parts of the link that were matched by the groups.
2142 For backwards compatibility, if a command string is given
2143 that does not use any of the group matches, this case is
2144 handled identically to the second one (i.e. match against
2145 file name only).
2146 In a custom lisp form, you can access the group matches with
2147 (match-string n link).
2149 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2150 to open [[file:document.pdf::5]] with evince at page 5.
2152 `directory' Matches a directory
2153 `remote' Matches a remote file, accessible through tramp or efs.
2154 Remote files most likely should be visited through Emacs
2155 because external applications cannot handle such paths.
2156 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2157 so all files Emacs knows how to handle. Using this with
2158 command `emacs' will open most files in Emacs. Beware that this
2159 will also open html files inside Emacs, unless you add
2160 (\"html\" . default) to the list as well.
2161 t Default for files not matched by any of the other options.
2162 `system' The system command to open files, like `open' on Windows
2163 and Mac OS X, and mailcap under GNU/Linux. This is the command
2164 that will be selected if you call `C-c C-o' with a double
2165 \\[universal-argument] \\[universal-argument] prefix.
2167 Possible values for the command are:
2168 `emacs' The file will be visited by the current Emacs process.
2169 `default' Use the default application for this file type, which is the
2170 association for t in the list, most likely in the system-specific
2171 part.
2172 This can be used to overrule an unwanted setting in the
2173 system-specific variable.
2174 `system' Use the system command for opening files, like \"open\".
2175 This command is specified by the entry whose car is `system'.
2176 Most likely, the system-specific version of this variable
2177 does define this command, but you can overrule/replace it
2178 here.
2179 string A command to be executed by a shell; %s will be replaced
2180 by the path to the file.
2181 sexp A Lisp form which will be evaluated. The file path will
2182 be available in the Lisp variable `file'.
2183 For more examples, see the system specific constants
2184 `org-file-apps-defaults-macosx'
2185 `org-file-apps-defaults-windowsnt'
2186 `org-file-apps-defaults-gnu'."
2187 :group 'org-link-follow
2188 :type '(repeat
2189 (cons (choice :value ""
2190 (string :tag "Extension")
2191 (const :tag "System command to open files" system)
2192 (const :tag "Default for unrecognized files" t)
2193 (const :tag "Remote file" remote)
2194 (const :tag "Links to a directory" directory)
2195 (const :tag "Any files that have Emacs modes"
2196 auto-mode))
2197 (choice :value ""
2198 (const :tag "Visit with Emacs" emacs)
2199 (const :tag "Use default" default)
2200 (const :tag "Use the system command" system)
2201 (string :tag "Command")
2202 (sexp :tag "Lisp form")))))
2204 (defcustom org-doi-server-url "http://dx.doi.org/"
2205 "The URL of the DOI server."
2206 :type 'string
2207 :version "24.3"
2208 :group 'org-link-follow)
2210 (defgroup org-refile nil
2211 "Options concerning refiling entries in Org-mode."
2212 :tag "Org Refile"
2213 :group 'org)
2215 (defcustom org-directory "~/org"
2216 "Directory with org files.
2217 This is just a default location to look for Org files. There is no need
2218 at all to put your files into this directory. It is only used in the
2219 following situations:
2221 1. When a capture template specifies a target file that is not an
2222 absolute path. The path will then be interpreted relative to
2223 `org-directory'
2224 2. When a capture note is filed away in an interactive way (when exiting the
2225 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2226 with `org-directory' as the default path."
2227 :group 'org-refile
2228 :group 'org-capture
2229 :type 'directory)
2231 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2232 "Default target for storing notes.
2233 Used as a fall back file for org-capture.el, for templates that
2234 do not specify a target file."
2235 :group 'org-refile
2236 :group 'org-capture
2237 :type '(choice
2238 (const :tag "Default from remember-data-file" nil)
2239 file))
2241 (defcustom org-goto-interface 'outline
2242 "The default interface to be used for `org-goto'.
2243 Allowed values are:
2244 outline The interface shows an outline of the relevant file
2245 and the correct heading is found by moving through
2246 the outline or by searching with incremental search.
2247 outline-path-completion Headlines in the current buffer are offered via
2248 completion. This is the interface also used by
2249 the refile command."
2250 :group 'org-refile
2251 :type '(choice
2252 (const :tag "Outline" outline)
2253 (const :tag "Outline-path-completion" outline-path-completion)))
2255 (defcustom org-goto-max-level 5
2256 "Maximum target level when running `org-goto' with refile interface."
2257 :group 'org-refile
2258 :type 'integer)
2260 (defcustom org-reverse-note-order nil
2261 "Non-nil means store new notes at the beginning of a file or entry.
2262 When nil, new notes will be filed to the end of a file or entry.
2263 This can also be a list with cons cells of regular expressions that
2264 are matched against file names, and values."
2265 :group 'org-capture
2266 :group 'org-refile
2267 :type '(choice
2268 (const :tag "Reverse always" t)
2269 (const :tag "Reverse never" nil)
2270 (repeat :tag "By file name regexp"
2271 (cons regexp boolean))))
2273 (defcustom org-log-refile nil
2274 "Information to record when a task is refiled.
2276 Possible values are:
2278 nil Don't add anything
2279 time Add a time stamp to the task
2280 note Prompt for a note and add it with template `org-log-note-headings'
2282 This option can also be set with on a per-file-basis with
2284 #+STARTUP: nologrefile
2285 #+STARTUP: logrefile
2286 #+STARTUP: lognoterefile
2288 You can have local logging settings for a subtree by setting the LOGGING
2289 property to one or more of these keywords.
2291 When bulk-refiling from the agenda, the value `note' is forbidden and
2292 will temporarily be changed to `time'."
2293 :group 'org-refile
2294 :group 'org-progress
2295 :version "24.1"
2296 :type '(choice
2297 (const :tag "No logging" nil)
2298 (const :tag "Record timestamp" time)
2299 (const :tag "Record timestamp with note." note)))
2301 (defcustom org-refile-targets nil
2302 "Targets for refiling entries with \\[org-refile].
2303 This is a list of cons cells. Each cell contains:
2304 - a specification of the files to be considered, either a list of files,
2305 or a symbol whose function or variable value will be used to retrieve
2306 a file name or a list of file names. If you use `org-agenda-files' for
2307 that, all agenda files will be scanned for targets. Nil means consider
2308 headings in the current buffer.
2309 - A specification of how to find candidate refile targets. This may be
2310 any of:
2311 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2312 This tag has to be present in all target headlines, inheritance will
2313 not be considered.
2314 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2315 todo keyword.
2316 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2317 headlines that are refiling targets.
2318 - a cons cell (:level . N). Any headline of level N is considered a target.
2319 Note that, when `org-odd-levels-only' is set, level corresponds to
2320 order in hierarchy, not to the number of stars.
2321 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2322 Note that, when `org-odd-levels-only' is set, level corresponds to
2323 order in hierarchy, not to the number of stars.
2325 Each element of this list generates a set of possible targets.
2326 The union of these sets is presented (with completion) to
2327 the user by `org-refile'.
2329 You can set the variable `org-refile-target-verify-function' to a function
2330 to verify each headline found by the simple criteria above.
2332 When this variable is nil, all top-level headlines in the current buffer
2333 are used, equivalent to the value `((nil . (:level . 1))'."
2334 :group 'org-refile
2335 :type '(repeat
2336 (cons
2337 (choice :value org-agenda-files
2338 (const :tag "All agenda files" org-agenda-files)
2339 (const :tag "Current buffer" nil)
2340 (function) (variable) (file))
2341 (choice :tag "Identify target headline by"
2342 (cons :tag "Specific tag" (const :value :tag) (string))
2343 (cons :tag "TODO keyword" (const :value :todo) (string))
2344 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2345 (cons :tag "Level number" (const :value :level) (integer))
2346 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2348 (defcustom org-refile-target-verify-function nil
2349 "Function to verify if the headline at point should be a refile target.
2350 The function will be called without arguments, with point at the
2351 beginning of the headline. It should return t and leave point
2352 where it is if the headline is a valid target for refiling.
2354 If the target should not be selected, the function must return nil.
2355 In addition to this, it may move point to a place from where the search
2356 should be continued. For example, the function may decide that the entire
2357 subtree of the current entry should be excluded and move point to the end
2358 of the subtree."
2359 :group 'org-refile
2360 :type '(choice
2361 (const nil)
2362 (function)))
2364 (defcustom org-refile-use-cache nil
2365 "Non-nil means cache refile targets to speed up the process.
2366 The cache for a particular file will be updated automatically when
2367 the buffer has been killed, or when any of the marker used for flagging
2368 refile targets no longer points at a live buffer.
2369 If you have added new entries to a buffer that might themselves be targets,
2370 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2371 find that easier, `C-u C-u C-u C-c C-w'."
2372 :group 'org-refile
2373 :version "24.1"
2374 :type 'boolean)
2376 (defcustom org-refile-use-outline-path nil
2377 "Non-nil means provide refile targets as paths.
2378 So a level 3 headline will be available as level1/level2/level3.
2380 When the value is `file', also include the file name (without directory)
2381 into the path. In this case, you can also stop the completion after
2382 the file name, to get entries inserted as top level in the file.
2384 When `full-file-path', include the full file path."
2385 :group 'org-refile
2386 :type '(choice
2387 (const :tag "Not" nil)
2388 (const :tag "Yes" t)
2389 (const :tag "Start with file name" file)
2390 (const :tag "Start with full file path" full-file-path)))
2392 (defcustom org-outline-path-complete-in-steps t
2393 "Non-nil means complete the outline path in hierarchical steps.
2394 When Org-mode uses the refile interface to select an outline path
2395 \(see variable `org-refile-use-outline-path'), the completion of
2396 the path can be done is a single go, or if can be done in steps down
2397 the headline hierarchy. Going in steps is probably the best if you
2398 do not use a special completion package like `ido' or `icicles'.
2399 However, when using these packages, going in one step can be very
2400 fast, while still showing the whole path to the entry."
2401 :group 'org-refile
2402 :type 'boolean)
2404 (defcustom org-refile-allow-creating-parent-nodes nil
2405 "Non-nil means allow to create new nodes as refile targets.
2406 New nodes are then created by adding \"/new node name\" to the completion
2407 of an existing node. When the value of this variable is `confirm',
2408 new node creation must be confirmed by the user (recommended).
2409 When nil, the completion must match an existing entry.
2411 Note that, if the new heading is not seen by the criteria
2412 listed in `org-refile-targets', multiple instances of the same
2413 heading would be created by trying again to file under the new
2414 heading."
2415 :group 'org-refile
2416 :type '(choice
2417 (const :tag "Never" nil)
2418 (const :tag "Always" t)
2419 (const :tag "Prompt for confirmation" confirm)))
2421 (defcustom org-refile-active-region-within-subtree nil
2422 "Non-nil means also refile active region within a subtree.
2424 By default `org-refile' doesn't allow refiling regions if they
2425 don't contain a set of subtrees, but it might be convenient to
2426 do so sometimes: in that case, the first line of the region is
2427 converted to a headline before refiling."
2428 :group 'org-refile
2429 :version "24.1"
2430 :type 'boolean)
2432 (defgroup org-todo nil
2433 "Options concerning TODO items in Org-mode."
2434 :tag "Org TODO"
2435 :group 'org)
2437 (defgroup org-progress nil
2438 "Options concerning Progress logging in Org-mode."
2439 :tag "Org Progress"
2440 :group 'org-time)
2442 (defvar org-todo-interpretation-widgets
2443 '((:tag "Sequence (cycling hits every state)" sequence)
2444 (:tag "Type (cycling directly to DONE)" type))
2445 "The available interpretation symbols for customizing `org-todo-keywords'.
2446 Interested libraries should add to this list.")
2448 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2449 "List of TODO entry keyword sequences and their interpretation.
2450 \\<org-mode-map>This is a list of sequences.
2452 Each sequence starts with a symbol, either `sequence' or `type',
2453 indicating if the keywords should be interpreted as a sequence of
2454 action steps, or as different types of TODO items. The first
2455 keywords are states requiring action - these states will select a headline
2456 for inclusion into the global TODO list Org-mode produces. If one of
2457 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2458 signify that no further action is necessary. If \"|\" is not found,
2459 the last keyword is treated as the only DONE state of the sequence.
2461 The command \\[org-todo] cycles an entry through these states, and one
2462 additional state where no keyword is present. For details about this
2463 cycling, see the manual.
2465 TODO keywords and interpretation can also be set on a per-file basis with
2466 the special #+SEQ_TODO and #+TYP_TODO lines.
2468 Each keyword can optionally specify a character for fast state selection
2469 \(in combination with the variable `org-use-fast-todo-selection')
2470 and specifiers for state change logging, using the same syntax that
2471 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2472 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2473 indicates to record a time stamp each time this state is selected.
2475 Each keyword may also specify if a timestamp or a note should be
2476 recorded when entering or leaving the state, by adding additional
2477 characters in the parenthesis after the keyword. This looks like this:
2478 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2479 record only the time of the state change. With X and Y being either
2480 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2481 Y when leaving the state if and only if the *target* state does not
2482 define X. You may omit any of the fast-selection key or X or /Y,
2483 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2485 For backward compatibility, this variable may also be just a list
2486 of keywords. In this case the interpretation (sequence or type) will be
2487 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2488 :group 'org-todo
2489 :group 'org-keywords
2490 :type '(choice
2491 (repeat :tag "Old syntax, just keywords"
2492 (string :tag "Keyword"))
2493 (repeat :tag "New syntax"
2494 (cons
2495 (choice
2496 :tag "Interpretation"
2497 ;;Quick and dirty way to see
2498 ;;`org-todo-interpretations'. This takes the
2499 ;;place of item arguments
2500 :convert-widget
2501 (lambda (widget)
2502 (widget-put widget
2503 :args (mapcar
2504 (lambda (x)
2505 (widget-convert
2506 (cons 'const x)))
2507 org-todo-interpretation-widgets))
2508 widget))
2509 (repeat
2510 (string :tag "Keyword"))))))
2512 (defvar org-todo-keywords-1 nil
2513 "All TODO and DONE keywords active in a buffer.")
2514 (make-variable-buffer-local 'org-todo-keywords-1)
2515 (defvar org-todo-keywords-for-agenda nil)
2516 (defvar org-done-keywords-for-agenda nil)
2517 (defvar org-todo-keyword-alist-for-agenda nil)
2518 (defvar org-tag-alist-for-agenda nil
2519 "Alist of all tags from all agenda files.")
2520 (defvar org-tag-groups-alist-for-agenda nil
2521 "Alist of all groups tags from all current agenda files.")
2522 (defvar org-tag-groups-alist nil)
2523 (make-variable-buffer-local 'org-tag-groups-alist)
2524 (defvar org-agenda-contributing-files nil)
2525 (defvar org-not-done-keywords nil)
2526 (make-variable-buffer-local 'org-not-done-keywords)
2527 (defvar org-done-keywords nil)
2528 (make-variable-buffer-local 'org-done-keywords)
2529 (defvar org-todo-heads nil)
2530 (make-variable-buffer-local 'org-todo-heads)
2531 (defvar org-todo-sets nil)
2532 (make-variable-buffer-local 'org-todo-sets)
2533 (defvar org-todo-log-states nil)
2534 (make-variable-buffer-local 'org-todo-log-states)
2535 (defvar org-todo-kwd-alist nil)
2536 (make-variable-buffer-local 'org-todo-kwd-alist)
2537 (defvar org-todo-key-alist nil)
2538 (make-variable-buffer-local 'org-todo-key-alist)
2539 (defvar org-todo-key-trigger nil)
2540 (make-variable-buffer-local 'org-todo-key-trigger)
2542 (defcustom org-todo-interpretation 'sequence
2543 "Controls how TODO keywords are interpreted.
2544 This variable is in principle obsolete and is only used for
2545 backward compatibility, if the interpretation of todo keywords is
2546 not given already in `org-todo-keywords'. See that variable for
2547 more information."
2548 :group 'org-todo
2549 :group 'org-keywords
2550 :type '(choice (const sequence)
2551 (const type)))
2553 (defcustom org-use-fast-todo-selection t
2554 "Non-nil means use the fast todo selection scheme with C-c C-t.
2555 This variable describes if and under what circumstances the cycling
2556 mechanism for TODO keywords will be replaced by a single-key, direct
2557 selection scheme.
2559 When nil, fast selection is never used.
2561 When the symbol `prefix', it will be used when `org-todo' is called
2562 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2563 `C-u t' in an agenda buffer.
2565 When t, fast selection is used by default. In this case, the prefix
2566 argument forces cycling instead.
2568 In all cases, the special interface is only used if access keys have
2569 actually been assigned by the user, i.e. if keywords in the configuration
2570 are followed by a letter in parenthesis, like TODO(t)."
2571 :group 'org-todo
2572 :type '(choice
2573 (const :tag "Never" nil)
2574 (const :tag "By default" t)
2575 (const :tag "Only with C-u C-c C-t" prefix)))
2577 (defcustom org-provide-todo-statistics t
2578 "Non-nil means update todo statistics after insert and toggle.
2579 ALL-HEADLINES means update todo statistics by including headlines
2580 with no TODO keyword as well, counting them as not done.
2581 A list of TODO keywords means the same, but skip keywords that are
2582 not in this list.
2583 When set to a list of two lists, the first list contains keywords
2584 to consider as TODO keywords, the second list contains keywords
2585 to consider as DONE keywords.
2587 When this is set, todo statistics is updated in the parent of the
2588 current entry each time a todo state is changed."
2589 :group 'org-todo
2590 :type '(choice
2591 (const :tag "Yes, only for TODO entries" t)
2592 (const :tag "Yes, including all entries" all-headlines)
2593 (repeat :tag "Yes, for TODOs in this list"
2594 (string :tag "TODO keyword"))
2595 (list :tag "Yes, for TODOs and DONEs in these lists"
2596 (repeat (string :tag "TODO keyword"))
2597 (repeat (string :tag "DONE keyword")))
2598 (other :tag "No TODO statistics" nil)))
2600 (defcustom org-hierarchical-todo-statistics t
2601 "Non-nil means TODO statistics covers just direct children.
2602 When nil, all entries in the subtree are considered.
2603 This has only an effect if `org-provide-todo-statistics' is set.
2604 To set this to nil for only a single subtree, use a COOKIE_DATA
2605 property and include the word \"recursive\" into the value."
2606 :group 'org-todo
2607 :type 'boolean)
2609 (defcustom org-after-todo-state-change-hook nil
2610 "Hook which is run after the state of a TODO item was changed.
2611 The new state (a string with a TODO keyword, or nil) is available in the
2612 Lisp variable `org-state'."
2613 :group 'org-todo
2614 :type 'hook)
2616 (defvar org-blocker-hook nil
2617 "Hook for functions that are allowed to block a state change.
2619 Functions in this hook should not modify the buffer.
2620 Each function gets as its single argument a property list,
2621 see `org-trigger-hook' for more information about this list.
2623 If any of the functions in this hook returns nil, the state change
2624 is blocked.")
2626 (defvar org-trigger-hook nil
2627 "Hook for functions that are triggered by a state change.
2629 Each function gets as its single argument a property list with at
2630 least the following elements:
2632 (:type type-of-change :position pos-at-entry-start
2633 :from old-state :to new-state)
2635 Depending on the type, more properties may be present.
2637 This mechanism is currently implemented for:
2639 TODO state changes
2640 ------------------
2641 :type todo-state-change
2642 :from previous state (keyword as a string), or nil, or a symbol
2643 'todo' or 'done', to indicate the general type of state.
2644 :to new state, like in :from")
2646 (defcustom org-enforce-todo-dependencies nil
2647 "Non-nil means undone TODO entries will block switching the parent to DONE.
2648 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2649 be blocked if any prior sibling is not yet done.
2650 Finally, if the parent is blocked because of ordered siblings of its own,
2651 the child will also be blocked."
2652 :set (lambda (var val)
2653 (set var val)
2654 (if val
2655 (add-hook 'org-blocker-hook
2656 'org-block-todo-from-children-or-siblings-or-parent)
2657 (remove-hook 'org-blocker-hook
2658 'org-block-todo-from-children-or-siblings-or-parent)))
2659 :group 'org-todo
2660 :type 'boolean)
2662 (defcustom org-enforce-todo-checkbox-dependencies nil
2663 "Non-nil means unchecked boxes will block switching the parent to DONE.
2664 When this is nil, checkboxes have no influence on switching TODO states.
2665 When non-nil, you first need to check off all check boxes before the TODO
2666 entry can be switched to DONE.
2667 This variable needs to be set before org.el is loaded, and you need to
2668 restart Emacs after a change to make the change effective. The only way
2669 to change is while Emacs is running is through the customize interface."
2670 :set (lambda (var val)
2671 (set var val)
2672 (if val
2673 (add-hook 'org-blocker-hook
2674 'org-block-todo-from-checkboxes)
2675 (remove-hook 'org-blocker-hook
2676 'org-block-todo-from-checkboxes)))
2677 :group 'org-todo
2678 :type 'boolean)
2680 (defcustom org-treat-insert-todo-heading-as-state-change nil
2681 "Non-nil means inserting a TODO heading is treated as state change.
2682 So when the command \\[org-insert-todo-heading] is used, state change
2683 logging will apply if appropriate. When nil, the new TODO item will
2684 be inserted directly, and no logging will take place."
2685 :group 'org-todo
2686 :type 'boolean)
2688 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2689 "Non-nil means switching TODO states with S-cursor counts as state change.
2690 This is the default behavior. However, setting this to nil allows a
2691 convenient way to select a TODO state and bypass any logging associated
2692 with that."
2693 :group 'org-todo
2694 :type 'boolean)
2696 (defcustom org-todo-state-tags-triggers nil
2697 "Tag changes that should be triggered by TODO state changes.
2698 This is a list. Each entry is
2700 (state-change (tag . flag) .......)
2702 State-change can be a string with a state, and empty string to indicate the
2703 state that has no TODO keyword, or it can be one of the symbols `todo'
2704 or `done', meaning any not-done or done state, respectively."
2705 :group 'org-todo
2706 :group 'org-tags
2707 :type '(repeat
2708 (cons (choice :tag "When changing to"
2709 (const :tag "Not-done state" todo)
2710 (const :tag "Done state" done)
2711 (string :tag "State"))
2712 (repeat
2713 (cons :tag "Tag action"
2714 (string :tag "Tag")
2715 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2717 (defcustom org-log-done nil
2718 "Information to record when a task moves to the DONE state.
2720 Possible values are:
2722 nil Don't add anything, just change the keyword
2723 time Add a time stamp to the task
2724 note Prompt for a note and add it with template `org-log-note-headings'
2726 This option can also be set with on a per-file-basis with
2728 #+STARTUP: nologdone
2729 #+STARTUP: logdone
2730 #+STARTUP: lognotedone
2732 You can have local logging settings for a subtree by setting the LOGGING
2733 property to one or more of these keywords."
2734 :group 'org-todo
2735 :group 'org-progress
2736 :type '(choice
2737 (const :tag "No logging" nil)
2738 (const :tag "Record CLOSED timestamp" time)
2739 (const :tag "Record CLOSED timestamp with note." note)))
2741 ;; Normalize old uses of org-log-done.
2742 (cond
2743 ((eq org-log-done t) (setq org-log-done 'time))
2744 ((and (listp org-log-done) (memq 'done org-log-done))
2745 (setq org-log-done 'note)))
2747 (defcustom org-log-reschedule nil
2748 "Information to record when the scheduling date of a tasks is modified.
2750 Possible values are:
2752 nil Don't add anything, just change the date
2753 time Add a time stamp to the task
2754 note Prompt for a note and add it with template `org-log-note-headings'
2756 This option can also be set with on a per-file-basis with
2758 #+STARTUP: nologreschedule
2759 #+STARTUP: logreschedule
2760 #+STARTUP: lognotereschedule"
2761 :group 'org-todo
2762 :group 'org-progress
2763 :type '(choice
2764 (const :tag "No logging" nil)
2765 (const :tag "Record timestamp" time)
2766 (const :tag "Record timestamp with note." note)))
2768 (defcustom org-log-redeadline nil
2769 "Information to record when the deadline date of a tasks is modified.
2771 Possible values are:
2773 nil Don't add anything, just change the date
2774 time Add a time stamp to the task
2775 note Prompt for a note and add it with template `org-log-note-headings'
2777 This option can also be set with on a per-file-basis with
2779 #+STARTUP: nologredeadline
2780 #+STARTUP: logredeadline
2781 #+STARTUP: lognoteredeadline
2783 You can have local logging settings for a subtree by setting the LOGGING
2784 property to one or more of these keywords."
2785 :group 'org-todo
2786 :group 'org-progress
2787 :type '(choice
2788 (const :tag "No logging" nil)
2789 (const :tag "Record timestamp" time)
2790 (const :tag "Record timestamp with note." note)))
2792 (defcustom org-log-note-clock-out nil
2793 "Non-nil means record a note when clocking out of an item.
2794 This can also be configured on a per-file basis by adding one of
2795 the following lines anywhere in the buffer:
2797 #+STARTUP: lognoteclock-out
2798 #+STARTUP: nolognoteclock-out"
2799 :group 'org-todo
2800 :group 'org-progress
2801 :type 'boolean)
2803 (defcustom org-log-done-with-time t
2804 "Non-nil means the CLOSED time stamp will contain date and time.
2805 When nil, only the date will be recorded."
2806 :group 'org-progress
2807 :type 'boolean)
2809 (defcustom org-log-note-headings
2810 '((done . "CLOSING NOTE %t")
2811 (state . "State %-12s from %-12S %t")
2812 (note . "Note taken on %t")
2813 (reschedule . "Rescheduled from %S on %t")
2814 (delschedule . "Not scheduled, was %S on %t")
2815 (redeadline . "New deadline from %S on %t")
2816 (deldeadline . "Removed deadline, was %S on %t")
2817 (refile . "Refiled on %t")
2818 (clock-out . ""))
2819 "Headings for notes added to entries.
2820 The value is an alist, with the car being a symbol indicating the note
2821 context, and the cdr is the heading to be used. The heading may also be the
2822 empty string.
2823 %t in the heading will be replaced by a time stamp.
2824 %T will be an active time stamp instead the default inactive one
2825 %d will be replaced by a short-format time stamp.
2826 %D will be replaced by an active short-format time stamp.
2827 %s will be replaced by the new TODO state, in double quotes.
2828 %S will be replaced by the old TODO state, in double quotes.
2829 %u will be replaced by the user name.
2830 %U will be replaced by the full user name.
2832 In fact, it is not a good idea to change the `state' entry, because
2833 agenda log mode depends on the format of these entries."
2834 :group 'org-todo
2835 :group 'org-progress
2836 :type '(list :greedy t
2837 (cons (const :tag "Heading when closing an item" done) string)
2838 (cons (const :tag
2839 "Heading when changing todo state (todo sequence only)"
2840 state) string)
2841 (cons (const :tag "Heading when just taking a note" note) string)
2842 (cons (const :tag "Heading when rescheduling" reschedule) string)
2843 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2844 (cons (const :tag "Heading when changing deadline" redeadline) string)
2845 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2846 (cons (const :tag "Heading when refiling" refile) string)
2847 (cons (const :tag "Heading when clocking out" clock-out) string)))
2849 (unless (assq 'note org-log-note-headings)
2850 (push '(note . "%t") org-log-note-headings))
2852 (defcustom org-log-into-drawer nil
2853 "Non-nil means insert state change notes and time stamps into a drawer.
2854 When nil, state changes notes will be inserted after the headline and
2855 any scheduling and clock lines, but not inside a drawer.
2857 The value of this variable should be the name of the drawer to use.
2858 LOGBOOK is proposed as the default drawer for this purpose, you can
2859 also set this to a string to define the drawer of your choice.
2861 A value of t is also allowed, representing \"LOGBOOK\".
2863 A value of t or nil can also be set with on a per-file-basis with
2865 #+STARTUP: logdrawer
2866 #+STARTUP: nologdrawer
2868 If this variable is set, `org-log-state-notes-insert-after-drawers'
2869 will be ignored.
2871 You can set the property LOG_INTO_DRAWER to overrule this setting for
2872 a subtree."
2873 :group 'org-todo
2874 :group 'org-progress
2875 :type '(choice
2876 (const :tag "Not into a drawer" nil)
2877 (const :tag "LOGBOOK" t)
2878 (string :tag "Other")))
2880 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2882 (defun org-log-into-drawer ()
2883 "Return the value of `org-log-into-drawer', but let properties overrule.
2884 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2885 used instead of the default value."
2886 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2887 (cond
2888 ((not p) org-log-into-drawer)
2889 ((equal p "nil") nil)
2890 ((equal p "t") "LOGBOOK")
2891 (t p))))
2893 (defcustom org-log-state-notes-insert-after-drawers nil
2894 "Non-nil means insert state change notes after any drawers in entry.
2895 Only the drawers that *immediately* follow the headline and the
2896 deadline/scheduled line are skipped.
2897 When nil, insert notes right after the heading and perhaps the line
2898 with deadline/scheduling if present.
2900 This variable will have no effect if `org-log-into-drawer' is
2901 set."
2902 :group 'org-todo
2903 :group 'org-progress
2904 :type 'boolean)
2906 (defcustom org-log-states-order-reversed t
2907 "Non-nil means the latest state note will be directly after heading.
2908 When nil, the state change notes will be ordered according to time.
2910 This option can also be set with on a per-file-basis with
2912 #+STARTUP: logstatesreversed
2913 #+STARTUP: nologstatesreversed"
2914 :group 'org-todo
2915 :group 'org-progress
2916 :type 'boolean)
2918 (defcustom org-todo-repeat-to-state nil
2919 "The TODO state to which a repeater should return the repeating task.
2920 By default this is the first task in a TODO sequence, or the previous state
2921 in a TODO_TYP set. But you can specify another task here.
2922 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2923 :group 'org-todo
2924 :version "24.1"
2925 :type '(choice (const :tag "Head of sequence" nil)
2926 (string :tag "Specific state")))
2928 (defcustom org-log-repeat 'time
2929 "Non-nil means record moving through the DONE state when triggering repeat.
2930 An auto-repeating task is immediately switched back to TODO when
2931 marked DONE. If you are not logging state changes (by adding \"@\"
2932 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2933 record a closing note, there will be no record of the task moving
2934 through DONE. This variable forces taking a note anyway.
2936 nil Don't force a record
2937 time Record a time stamp
2938 note Prompt for a note and add it with template `org-log-note-headings'
2940 This option can also be set with on a per-file-basis with
2942 #+STARTUP: nologrepeat
2943 #+STARTUP: logrepeat
2944 #+STARTUP: lognoterepeat
2946 You can have local logging settings for a subtree by setting the LOGGING
2947 property to one or more of these keywords."
2948 :group 'org-todo
2949 :group 'org-progress
2950 :type '(choice
2951 (const :tag "Don't force a record" nil)
2952 (const :tag "Force recording the DONE state" time)
2953 (const :tag "Force recording a note with the DONE state" note)))
2956 (defgroup org-priorities nil
2957 "Priorities in Org-mode."
2958 :tag "Org Priorities"
2959 :group 'org-todo)
2961 (defcustom org-enable-priority-commands t
2962 "Non-nil means priority commands are active.
2963 When nil, these commands will be disabled, so that you never accidentally
2964 set a priority."
2965 :group 'org-priorities
2966 :type 'boolean)
2968 (defcustom org-highest-priority ?A
2969 "The highest priority of TODO items. A character like ?A, ?B etc.
2970 Must have a smaller ASCII number than `org-lowest-priority'."
2971 :group 'org-priorities
2972 :type 'character)
2974 (defcustom org-lowest-priority ?C
2975 "The lowest priority of TODO items. A character like ?A, ?B etc.
2976 Must have a larger ASCII number than `org-highest-priority'."
2977 :group 'org-priorities
2978 :type 'character)
2980 (defcustom org-default-priority ?B
2981 "The default priority of TODO items.
2982 This is the priority an item gets if no explicit priority is given.
2983 When starting to cycle on an empty priority the first step in the cycle
2984 depends on `org-priority-start-cycle-with-default'. The resulting first
2985 step priority must not exceed the range from `org-highest-priority' to
2986 `org-lowest-priority' which means that `org-default-priority' has to be
2987 in this range exclusive or inclusive the range boundaries. Else the
2988 first step refuses to set the default and the second will fall back
2989 to (depending on the command used) the highest or lowest priority."
2990 :group 'org-priorities
2991 :type 'character)
2993 (defcustom org-priority-start-cycle-with-default t
2994 "Non-nil means start with default priority when starting to cycle.
2995 When this is nil, the first step in the cycle will be (depending on the
2996 command used) one higher or lower than the default priority.
2997 See also `org-default-priority'."
2998 :group 'org-priorities
2999 :type 'boolean)
3001 (defcustom org-get-priority-function nil
3002 "Function to extract the priority from a string.
3003 The string is normally the headline. If this is nil Org computes the
3004 priority from the priority cookie like [#A] in the headline. It returns
3005 an integer, increasing by 1000 for each priority level.
3006 The user can set a different function here, which should take a string
3007 as an argument and return the numeric priority."
3008 :group 'org-priorities
3009 :version "24.1"
3010 :type '(choice
3011 (const nil)
3012 (function)))
3014 (defgroup org-time nil
3015 "Options concerning time stamps and deadlines in Org-mode."
3016 :tag "Org Time"
3017 :group 'org)
3019 (defcustom org-insert-labeled-timestamps-at-point nil
3020 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3021 When nil, these labeled time stamps are forces into the second line of an
3022 entry, just after the headline. When scheduling from the global TODO list,
3023 the time stamp will always be forced into the second line."
3024 :group 'org-time
3025 :type 'boolean)
3027 (defcustom org-time-stamp-rounding-minutes '(0 5)
3028 "Number of minutes to round time stamps to.
3029 These are two values, the first applies when first creating a time stamp.
3030 The second applies when changing it with the commands `S-up' and `S-down'.
3031 When changing the time stamp, this means that it will change in steps
3032 of N minutes, as given by the second value.
3034 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3035 numbers should be factors of 60, so for example 5, 10, 15.
3037 When this is larger than 1, you can still force an exact time stamp by using
3038 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3039 and by using a prefix arg to `S-up/down' to specify the exact number
3040 of minutes to shift."
3041 :group 'org-time
3042 :get (lambda (var) ; Make sure both elements are there
3043 (if (integerp (default-value var))
3044 (list (default-value var) 5)
3045 (default-value var)))
3046 :type '(list
3047 (integer :tag "when inserting times")
3048 (integer :tag "when modifying times")))
3050 ;; Normalize old customizations of this variable.
3051 (when (integerp org-time-stamp-rounding-minutes)
3052 (setq org-time-stamp-rounding-minutes
3053 (list org-time-stamp-rounding-minutes
3054 org-time-stamp-rounding-minutes)))
3056 (defcustom org-display-custom-times nil
3057 "Non-nil means overlay custom formats over all time stamps.
3058 The formats are defined through the variable `org-time-stamp-custom-formats'.
3059 To turn this on on a per-file basis, insert anywhere in the file:
3060 #+STARTUP: customtime"
3061 :group 'org-time
3062 :set 'set-default
3063 :type 'sexp)
3064 (make-variable-buffer-local 'org-display-custom-times)
3066 (defcustom org-time-stamp-custom-formats
3067 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3068 "Custom formats for time stamps. See `format-time-string' for the syntax.
3069 These are overlaid over the default ISO format if the variable
3070 `org-display-custom-times' is set. Time like %H:%M should be at the
3071 end of the second format. The custom formats are also honored by export
3072 commands, if custom time display is turned on at the time of export."
3073 :group 'org-time
3074 :type 'sexp)
3076 (defun org-time-stamp-format (&optional long inactive)
3077 "Get the right format for a time string."
3078 (let ((f (if long (cdr org-time-stamp-formats)
3079 (car org-time-stamp-formats))))
3080 (if inactive
3081 (concat "[" (substring f 1 -1) "]")
3082 f)))
3084 (defcustom org-time-clocksum-format
3085 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3086 "The format string used when creating CLOCKSUM lines.
3087 This is also used when Org mode generates a time duration.
3089 The value can be a single format string containing two
3090 %-sequences, which will be filled with the number of hours and
3091 minutes in that order.
3093 Alternatively, the value can be a plist associating any of the
3094 keys :years, :months, :weeks, :days, :hours or :minutes with
3095 format strings. The time duration is formatted using only the
3096 time components that are needed and concatenating the results.
3097 If a time unit in absent, it falls back to the next smallest
3098 unit.
3100 The keys :require-years, :require-months, :require-days,
3101 :require-weeks, :require-hours, :require-minutes are also
3102 meaningful. A non-nil value for these keys indicates that the
3103 corresponding time component should always be included, even if
3104 its value is 0.
3107 For example,
3109 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3110 :require-minutes t)
3112 means durations longer than a day will be expressed in days,
3113 hours and minutes, and durations less than a day will always be
3114 expressed in hours and minutes (even for durations less than an
3115 hour).
3117 The value
3119 \(:days \"%dd\" :minutes \"%dm\")
3121 means durations longer than a day will be expressed in days and
3122 minutes, and durations less than a day will be expressed entirely
3123 in minutes (even for durations longer than an hour)."
3124 :group 'org-time
3125 :group 'org-clock
3126 :version "24.4"
3127 :package-version '(Org . "8.0")
3128 :type '(choice (string :tag "Format string")
3129 (set :tag "Plist"
3130 (group :inline t (const :tag "Years" :years)
3131 (string :tag "Format string"))
3132 (group :inline t
3133 (const :tag "Always show years" :require-years)
3134 (const t))
3135 (group :inline t (const :tag "Months" :months)
3136 (string :tag "Format string"))
3137 (group :inline t
3138 (const :tag "Always show months" :require-months)
3139 (const t))
3140 (group :inline t (const :tag "Weeks" :weeks)
3141 (string :tag "Format string"))
3142 (group :inline t
3143 (const :tag "Always show weeks" :require-weeks)
3144 (const t))
3145 (group :inline t (const :tag "Days" :days)
3146 (string :tag "Format string"))
3147 (group :inline t
3148 (const :tag "Always show days" :require-days)
3149 (const t))
3150 (group :inline t (const :tag "Hours" :hours)
3151 (string :tag "Format string"))
3152 (group :inline t
3153 (const :tag "Always show hours" :require-hours)
3154 (const t))
3155 (group :inline t (const :tag "Minutes" :minutes)
3156 (string :tag "Format string"))
3157 (group :inline t
3158 (const :tag "Always show minutes" :require-minutes)
3159 (const t)))))
3161 (defcustom org-time-clocksum-use-fractional nil
3162 "When non-nil, \\[org-clock-display] uses fractional times.
3163 See `org-time-clocksum-format' for more on time clock formats."
3164 :group 'org-time
3165 :group 'org-clock
3166 :version "24.3"
3167 :type 'boolean)
3169 (defcustom org-time-clocksum-use-effort-durations nil
3170 "When non-nil, \\[org-clock-display] uses effort durations.
3171 E.g. by default, one day is considered to be a 8 hours effort,
3172 so a task that has been clocked for 16 hours will be displayed
3173 as during 2 days in the clock display or in the clocktable.
3175 See `org-effort-durations' on how to set effort durations
3176 and `org-time-clocksum-format' for more on time clock formats."
3177 :group 'org-time
3178 :group 'org-clock
3179 :version "24.4"
3180 :package-version '(Org . "8.0")
3181 :type 'boolean)
3183 (defcustom org-time-clocksum-fractional-format "%.2f"
3184 "The format string used when creating CLOCKSUM lines,
3185 or when Org mode generates a time duration, if
3186 `org-time-clocksum-use-fractional' is enabled.
3188 The value can be a single format string containing one
3189 %-sequence, which will be filled with the number of hours as
3190 a float.
3192 Alternatively, the value can be a plist associating any of the
3193 keys :years, :months, :weeks, :days, :hours or :minutes with
3194 a format string. The time duration is formatted using the
3195 largest time unit which gives a non-zero integer part. If all
3196 specified formats have zero integer part, the smallest time unit
3197 is used."
3198 :group 'org-time
3199 :type '(choice (string :tag "Format string")
3200 (set (group :inline t (const :tag "Years" :years)
3201 (string :tag "Format string"))
3202 (group :inline t (const :tag "Months" :months)
3203 (string :tag "Format string"))
3204 (group :inline t (const :tag "Weeks" :weeks)
3205 (string :tag "Format string"))
3206 (group :inline t (const :tag "Days" :days)
3207 (string :tag "Format string"))
3208 (group :inline t (const :tag "Hours" :hours)
3209 (string :tag "Format string"))
3210 (group :inline t (const :tag "Minutes" :minutes)
3211 (string :tag "Format string")))))
3213 (defcustom org-deadline-warning-days 14
3214 "Number of days before expiration during which a deadline becomes active.
3215 This variable governs the display in sparse trees and in the agenda.
3216 When 0 or negative, it means use this number (the absolute value of it)
3217 even if a deadline has a different individual lead time specified.
3219 Custom commands can set this variable in the options section."
3220 :group 'org-time
3221 :group 'org-agenda-daily/weekly
3222 :type 'integer)
3224 (defcustom org-scheduled-delay-days 0
3225 "Number of days before a scheduled item becomes active.
3226 This variable governs the display in sparse trees and in the agenda.
3227 The default value (i.e. 0) means: don't delay scheduled item.
3228 When negative, it means use this number (the absolute value of it)
3229 even if a scheduled item has a different individual delay time
3230 specified.
3232 Custom commands can set this variable in the options section."
3233 :group 'org-time
3234 :group 'org-agenda-daily/weekly
3235 :version "24.4"
3236 :package-version '(Org . "8.0")
3237 :type 'integer)
3239 (defcustom org-read-date-prefer-future t
3240 "Non-nil means assume future for incomplete date input from user.
3241 This affects the following situations:
3242 1. The user gives a month but not a year.
3243 For example, if it is April and you enter \"feb 2\", this will be read
3244 as Feb 2, *next* year. \"May 5\", however, will be this year.
3245 2. The user gives a day, but no month.
3246 For example, if today is the 15th, and you enter \"3\", Org-mode will
3247 read this as the third of *next* month. However, if you enter \"17\",
3248 it will be considered as *this* month.
3250 If you set this variable to the symbol `time', then also the following
3251 will work:
3253 3. If the user gives a time.
3254 If the time is before now, it will be interpreted as tomorrow.
3256 Currently none of this works for ISO week specifications.
3258 When this option is nil, the current day, month and year will always be
3259 used as defaults.
3261 See also `org-agenda-jump-prefer-future'."
3262 :group 'org-time
3263 :type '(choice
3264 (const :tag "Never" nil)
3265 (const :tag "Check month and day" t)
3266 (const :tag "Check month, day, and time" time)))
3268 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3269 "Should the agenda jump command prefer the future for incomplete dates?
3270 The default is to do the same as configured in `org-read-date-prefer-future'.
3271 But you can also set a deviating value here.
3272 This may t or nil, or the symbol `org-read-date-prefer-future'."
3273 :group 'org-agenda
3274 :group 'org-time
3275 :version "24.1"
3276 :type '(choice
3277 (const :tag "Use org-read-date-prefer-future"
3278 org-read-date-prefer-future)
3279 (const :tag "Never" nil)
3280 (const :tag "Always" t)))
3282 (defcustom org-read-date-force-compatible-dates t
3283 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3285 Depending on the system Emacs is running on, certain dates cannot
3286 be represented with the type used internally to represent time.
3287 Dates between 1970-1-1 and 2038-1-1 can always be represented
3288 correctly. Some systems allow for earlier dates, some for later,
3289 some for both. One way to find out it to insert any date into an
3290 Org buffer, putting the cursor on the year and hitting S-up and
3291 S-down to test the range.
3293 When this variable is set to t, the date/time prompt will not let
3294 you specify dates outside the 1970-2037 range, so it is certain that
3295 these dates will work in whatever version of Emacs you are
3296 running, and also that you can move a file from one Emacs implementation
3297 to another. WHenever Org is forcing the year for you, it will display
3298 a message and beep.
3300 When this variable is nil, Org will check if the date is
3301 representable in the specific Emacs implementation you are using.
3302 If not, it will force a year, usually the current year, and beep
3303 to remind you. Currently this setting is not recommended because
3304 the likelihood that you will open your Org files in an Emacs that
3305 has limited date range is not negligible.
3307 A workaround for this problem is to use diary sexp dates for time
3308 stamps outside of this range."
3309 :group 'org-time
3310 :version "24.1"
3311 :type 'boolean)
3313 (defcustom org-read-date-display-live t
3314 "Non-nil means display current interpretation of date prompt live.
3315 This display will be in an overlay, in the minibuffer."
3316 :group 'org-time
3317 :type 'boolean)
3319 (defcustom org-read-date-popup-calendar t
3320 "Non-nil means pop up a calendar when prompting for a date.
3321 In the calendar, the date can be selected with mouse-1. However, the
3322 minibuffer will also be active, and you can simply enter the date as well.
3323 When nil, only the minibuffer will be available."
3324 :group 'org-time
3325 :type 'boolean)
3326 (org-defvaralias 'org-popup-calendar-for-date-prompt
3327 'org-read-date-popup-calendar)
3329 (make-obsolete-variable
3330 'org-read-date-minibuffer-setup-hook
3331 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3332 (defcustom org-read-date-minibuffer-setup-hook nil
3333 "Hook to be used to set up keys for the date/time interface.
3334 Add key definitions to `minibuffer-local-map', which will be a
3335 temporary copy.
3337 WARNING: This option is obsolete, you should use
3338 `org-read-date-minibuffer-local-map' to set up keys."
3339 :group 'org-time
3340 :type 'hook)
3342 (defcustom org-extend-today-until 0
3343 "The hour when your day really ends. Must be an integer.
3344 This has influence for the following applications:
3345 - When switching the agenda to \"today\". It it is still earlier than
3346 the time given here, the day recognized as TODAY is actually yesterday.
3347 - When a date is read from the user and it is still before the time given
3348 here, the current date and time will be assumed to be yesterday, 23:59.
3349 Also, timestamps inserted in capture templates follow this rule.
3351 IMPORTANT: This is a feature whose implementation is and likely will
3352 remain incomplete. Really, it is only here because past midnight seems to
3353 be the favorite working time of John Wiegley :-)"
3354 :group 'org-time
3355 :type 'integer)
3357 (defcustom org-use-effective-time nil
3358 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3359 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3360 \"effective time\" of any timestamps between midnight and 8am will be
3361 23:59 of the previous day."
3362 :group 'org-time
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-use-last-clock-out-time-as-effective-time nil
3367 "When non-nil, use the last clock out time for `org-todo'.
3368 Note that this option has precedence over the combined use of
3369 `org-use-effective-time' and `org-extend-today-until'."
3370 :group 'org-time
3371 :version "24.4"
3372 :package-version '(Org . "8.0")
3373 :type 'boolean)
3375 (defcustom org-edit-timestamp-down-means-later nil
3376 "Non-nil means S-down will increase the time in a time stamp.
3377 When nil, S-up will increase."
3378 :group 'org-time
3379 :type 'boolean)
3381 (defcustom org-calendar-follow-timestamp-change t
3382 "Non-nil means make the calendar window follow timestamp changes.
3383 When a timestamp is modified and the calendar window is visible, it will be
3384 moved to the new date."
3385 :group 'org-time
3386 :type 'boolean)
3388 (defgroup org-tags nil
3389 "Options concerning tags in Org-mode."
3390 :tag "Org Tags"
3391 :group 'org)
3393 (defcustom org-tag-alist nil
3394 "List of tags allowed in Org-mode files.
3395 When this list is nil, Org-mode will base TAG input on what is already in the
3396 buffer.
3397 The value of this variable is an alist, the car of each entry must be a
3398 keyword as a string, the cdr may be a character that is used to select
3399 that tag through the fast-tag-selection interface.
3400 See the manual for details."
3401 :group 'org-tags
3402 :type '(repeat
3403 (choice
3404 (cons (string :tag "Tag name")
3405 (character :tag "Access char"))
3406 (list :tag "Start radio group"
3407 (const :startgroup)
3408 (option (string :tag "Group description")))
3409 (list :tag "Group tags delimiter"
3410 (const :grouptags))
3411 (list :tag "End radio group"
3412 (const :endgroup)
3413 (option (string :tag "Group description")))
3414 (const :tag "New line" (:newline)))))
3416 (defcustom org-tag-persistent-alist nil
3417 "List of tags that will always appear in all Org-mode files.
3418 This is in addition to any in buffer settings or customizations
3419 of `org-tag-alist'.
3420 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3421 The value of this variable is an alist, the car of each entry must be a
3422 keyword as a string, the cdr may be a character that is used to select
3423 that tag through the fast-tag-selection interface.
3424 See the manual for details.
3425 To disable these tags on a per-file basis, insert anywhere in the file:
3426 #+STARTUP: noptag"
3427 :group 'org-tags
3428 :type '(repeat
3429 (choice
3430 (cons (string :tag "Tag name")
3431 (character :tag "Access char"))
3432 (const :tag "Start radio group" (:startgroup))
3433 (const :tag "Group tags delimiter" (:grouptags))
3434 (const :tag "End radio group" (:endgroup))
3435 (const :tag "New line" (:newline)))))
3437 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3438 "If non-nil, always offer completion for all tags of all agenda files.
3439 Instead of customizing this variable directly, you might want to
3440 set it locally for capture buffers, because there no list of
3441 tags in that file can be created dynamically (there are none).
3443 (add-hook 'org-capture-mode-hook
3444 (lambda ()
3445 (set (make-local-variable
3446 'org-complete-tags-always-offer-all-agenda-tags)
3447 t)))"
3448 :group 'org-tags
3449 :version "24.1"
3450 :type 'boolean)
3452 (defvar org-file-tags nil
3453 "List of tags that can be inherited by all entries in the file.
3454 The tags will be inherited if the variable `org-use-tag-inheritance'
3455 says they should be.
3456 This variable is populated from #+FILETAGS lines.")
3458 (defcustom org-use-fast-tag-selection 'auto
3459 "Non-nil means use fast tag selection scheme.
3460 This is a special interface to select and deselect tags with single keys.
3461 When nil, fast selection is never used.
3462 When the symbol `auto', fast selection is used if and only if selection
3463 characters for tags have been configured, either through the variable
3464 `org-tag-alist' or through a #+TAGS line in the buffer.
3465 When t, fast selection is always used and selection keys are assigned
3466 automatically if necessary."
3467 :group 'org-tags
3468 :type '(choice
3469 (const :tag "Always" t)
3470 (const :tag "Never" nil)
3471 (const :tag "When selection characters are configured" auto)))
3473 (defcustom org-fast-tag-selection-single-key nil
3474 "Non-nil means fast tag selection exits after first change.
3475 When nil, you have to press RET to exit it.
3476 During fast tag selection, you can toggle this flag with `C-c'.
3477 This variable can also have the value `expert'. In this case, the window
3478 displaying the tags menu is not even shown, until you press C-c again."
3479 :group 'org-tags
3480 :type '(choice
3481 (const :tag "No" nil)
3482 (const :tag "Yes" t)
3483 (const :tag "Expert" expert)))
3485 (defvar org-fast-tag-selection-include-todo nil
3486 "Non-nil means fast tags selection interface will also offer TODO states.
3487 This is an undocumented feature, you should not rely on it.")
3489 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3490 "The column to which tags should be indented in a headline.
3491 If this number is positive, it specifies the column. If it is negative,
3492 it means that the tags should be flushright to that column. For example,
3493 -80 works well for a normal 80 character screen.
3494 When 0, place tags directly after headline text, with only one space in
3495 between."
3496 :group 'org-tags
3497 :type 'integer)
3499 (defcustom org-auto-align-tags t
3500 "Non-nil keeps tags aligned when modifying headlines.
3501 Some operations (i.e. demoting) change the length of a headline and
3502 therefore shift the tags around. With this option turned on, after
3503 each such operation the tags are again aligned to `org-tags-column'."
3504 :group 'org-tags
3505 :type 'boolean)
3507 (defcustom org-use-tag-inheritance t
3508 "Non-nil means tags in levels apply also for sublevels.
3509 When nil, only the tags directly given in a specific line apply there.
3510 This may also be a list of tags that should be inherited, or a regexp that
3511 matches tags that should be inherited. Additional control is possible
3512 with the variable `org-tags-exclude-from-inheritance' which gives an
3513 explicit list of tags to be excluded from inheritance, even if the value of
3514 `org-use-tag-inheritance' would select it for inheritance.
3516 If this option is t, a match early-on in a tree can lead to a large
3517 number of matches in the subtree when constructing the agenda or creating
3518 a sparse tree. If you only want to see the first match in a tree during
3519 a search, check out the variable `org-tags-match-list-sublevels'."
3520 :group 'org-tags
3521 :type '(choice
3522 (const :tag "Not" nil)
3523 (const :tag "Always" t)
3524 (repeat :tag "Specific tags" (string :tag "Tag"))
3525 (regexp :tag "Tags matched by regexp")))
3527 (defcustom org-tags-exclude-from-inheritance nil
3528 "List of tags that should never be inherited.
3529 This is a way to exclude a few tags from inheritance. For way to do
3530 the opposite, to actively allow inheritance for selected tags,
3531 see the variable `org-use-tag-inheritance'."
3532 :group 'org-tags
3533 :type '(repeat (string :tag "Tag")))
3535 (defun org-tag-inherit-p (tag)
3536 "Check if TAG is one that should be inherited."
3537 (cond
3538 ((member tag org-tags-exclude-from-inheritance) nil)
3539 ((eq org-use-tag-inheritance t) t)
3540 ((not org-use-tag-inheritance) nil)
3541 ((stringp org-use-tag-inheritance)
3542 (string-match org-use-tag-inheritance tag))
3543 ((listp org-use-tag-inheritance)
3544 (member tag org-use-tag-inheritance))
3545 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3547 (defcustom org-tags-match-list-sublevels t
3548 "Non-nil means list also sublevels of headlines matching a search.
3549 This variable applies to tags/property searches, and also to stuck
3550 projects because this search is based on a tags match as well.
3552 When set to the symbol `indented', sublevels are indented with
3553 leading dots.
3555 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3556 the sublevels of a headline matching a tag search often also match
3557 the same search. Listing all of them can create very long lists.
3558 Setting this variable to nil causes subtrees of a match to be skipped.
3560 This variable is semi-obsolete and probably should always be true. It
3561 is better to limit inheritance to certain tags using the variables
3562 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3563 :group 'org-tags
3564 :type '(choice
3565 (const :tag "No, don't list them" nil)
3566 (const :tag "Yes, do list them" t)
3567 (const :tag "List them, indented with leading dots" indented)))
3569 (defcustom org-tags-sort-function nil
3570 "When set, tags are sorted using this function as a comparator."
3571 :group 'org-tags
3572 :type '(choice
3573 (const :tag "No sorting" nil)
3574 (const :tag "Alphabetical" string<)
3575 (const :tag "Reverse alphabetical" string>)
3576 (function :tag "Custom function" nil)))
3578 (defvar org-tags-history nil
3579 "History of minibuffer reads for tags.")
3580 (defvar org-last-tags-completion-table nil
3581 "The last used completion table for tags.")
3582 (defvar org-after-tags-change-hook nil
3583 "Hook that is run after the tags in a line have changed.")
3585 (defgroup org-properties nil
3586 "Options concerning properties in Org-mode."
3587 :tag "Org Properties"
3588 :group 'org)
3590 (defcustom org-property-format "%-10s %s"
3591 "How property key/value pairs should be formatted by `indent-line'.
3592 When `indent-line' hits a property definition, it will format the line
3593 according to this format, mainly to make sure that the values are
3594 lined-up with respect to each other."
3595 :group 'org-properties
3596 :type 'string)
3598 (defcustom org-properties-postprocess-alist nil
3599 "Alist of properties and functions to adjust inserted values.
3600 Elements of this alist must be of the form
3602 ([string] [function])
3604 where [string] must be a property name and [function] must be a
3605 lambda expression: this lambda expression must take one argument,
3606 the value to adjust, and return the new value as a string.
3608 For example, this element will allow the property \"Remaining\"
3609 to be updated wrt the relation between the \"Effort\" property
3610 and the clock summary:
3612 ((\"Remaining\" (lambda(value)
3613 (let ((clocksum (org-clock-sum-current-item))
3614 (effort (org-duration-string-to-minutes
3615 (org-entry-get (point) \"Effort\"))))
3616 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3617 :group 'org-properties
3618 :version "24.1"
3619 :type '(alist :key-type (string :tag "Property")
3620 :value-type (function :tag "Function")))
3622 (defcustom org-use-property-inheritance nil
3623 "Non-nil means properties apply also for sublevels.
3625 This setting is chiefly used during property searches. Turning it on can
3626 cause significant overhead when doing a search, which is why it is not
3627 on by default.
3629 When nil, only the properties directly given in the current entry count.
3630 When t, every property is inherited. The value may also be a list of
3631 properties that should have inheritance, or a regular expression matching
3632 properties that should be inherited.
3634 However, note that some special properties use inheritance under special
3635 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3636 and the properties ending in \"_ALL\" when they are used as descriptor
3637 for valid values of a property.
3639 Note for programmers:
3640 When querying an entry with `org-entry-get', you can control if inheritance
3641 should be used. By default, `org-entry-get' looks only at the local
3642 properties. You can request inheritance by setting the inherit argument
3643 to t (to force inheritance) or to `selective' (to respect the setting
3644 in this variable)."
3645 :group 'org-properties
3646 :type '(choice
3647 (const :tag "Not" nil)
3648 (const :tag "Always" t)
3649 (repeat :tag "Specific properties" (string :tag "Property"))
3650 (regexp :tag "Properties matched by regexp")))
3652 (defun org-property-inherit-p (property)
3653 "Check if PROPERTY is one that should be inherited."
3654 (cond
3655 ((eq org-use-property-inheritance t) t)
3656 ((not org-use-property-inheritance) nil)
3657 ((stringp org-use-property-inheritance)
3658 (string-match org-use-property-inheritance property))
3659 ((listp org-use-property-inheritance)
3660 (member property org-use-property-inheritance))
3661 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3663 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3664 "The default column format, if no other format has been defined.
3665 This variable can be set on the per-file basis by inserting a line
3667 #+COLUMNS: %25ITEM ....."
3668 :group 'org-properties
3669 :type 'string)
3671 (defcustom org-columns-ellipses ".."
3672 "The ellipses to be used when a field in column view is truncated.
3673 When this is the empty string, as many characters as possible are shown,
3674 but then there will be no visual indication that the field has been truncated.
3675 When this is a string of length N, the last N characters of a truncated
3676 field are replaced by this string. If the column is narrower than the
3677 ellipses string, only part of the ellipses string will be shown."
3678 :group 'org-properties
3679 :type 'string)
3681 (defcustom org-columns-modify-value-for-display-function nil
3682 "Function that modifies values for display in column view.
3683 For example, it can be used to cut out a certain part from a time stamp.
3684 The function must take 2 arguments:
3686 column-title The title of the column (*not* the property name)
3687 value The value that should be modified.
3689 The function should return the value that should be displayed,
3690 or nil if the normal value should be used."
3691 :group 'org-properties
3692 :type '(choice (const nil) (function)))
3694 (defconst org-global-properties-fixed
3695 '(("VISIBILITY_ALL" . "folded children content all")
3696 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3697 "List of property/value pairs that can be inherited by any entry.
3699 These are fixed values, for the preset properties. The user variable
3700 that can be used to add to this list is `org-global-properties'.
3702 The entries in this list are cons cells where the car is a property
3703 name and cdr is a string with the value. If the value represents
3704 multiple items like an \"_ALL\" property, separate the items by
3705 spaces.")
3707 (defcustom org-global-properties nil
3708 "List of property/value pairs that can be inherited by any entry.
3710 This list will be combined with the constant `org-global-properties-fixed'.
3712 The entries in this list are cons cells where the car is a property
3713 name and cdr is a string with the value.
3715 You can set buffer-local values for the same purpose in the variable
3716 `org-file-properties' this by adding lines like
3718 #+PROPERTY: NAME VALUE"
3719 :group 'org-properties
3720 :type '(repeat
3721 (cons (string :tag "Property")
3722 (string :tag "Value"))))
3724 (defvar org-file-properties nil
3725 "List of property/value pairs that can be inherited by any entry.
3726 Valid for the current buffer.
3727 This variable is populated from #+PROPERTY lines.")
3728 (make-variable-buffer-local 'org-file-properties)
3730 (defgroup org-agenda nil
3731 "Options concerning agenda views in Org-mode."
3732 :tag "Org Agenda"
3733 :group 'org)
3735 (defvar org-category nil
3736 "Variable used by org files to set a category for agenda display.
3737 Such files should use a file variable to set it, for example
3739 # -*- mode: org; org-category: \"ELisp\"
3741 or contain a special line
3743 #+CATEGORY: ELisp
3745 If the file does not specify a category, then file's base name
3746 is used instead.")
3747 (make-variable-buffer-local 'org-category)
3748 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3750 (defcustom org-agenda-files nil
3751 "The files to be used for agenda display.
3752 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3753 \\[org-remove-file]. You can also use customize to edit the list.
3755 If an entry is a directory, all files in that directory that are matched by
3756 `org-agenda-file-regexp' will be part of the file list.
3758 If the value of the variable is not a list but a single file name, then
3759 the list of agenda files is actually stored and maintained in that file, one
3760 agenda file per line. In this file paths can be given relative to
3761 `org-directory'. Tilde expansion and environment variable substitution
3762 are also made."
3763 :group 'org-agenda
3764 :type '(choice
3765 (repeat :tag "List of files and directories" file)
3766 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3768 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3769 "Regular expression to match files for `org-agenda-files'.
3770 If any element in the list in that variable contains a directory instead
3771 of a normal file, all files in that directory that are matched by this
3772 regular expression will be included."
3773 :group 'org-agenda
3774 :type 'regexp)
3776 (defcustom org-agenda-text-search-extra-files nil
3777 "List of extra files to be searched by text search commands.
3778 These files will be searched in addition to the agenda files by the
3779 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3780 Note that these files will only be searched for text search commands,
3781 not for the other agenda views like todo lists, tag searches or the weekly
3782 agenda. This variable is intended to list notes and possibly archive files
3783 that should also be searched by these two commands.
3784 In fact, if the first element in the list is the symbol `agenda-archives',
3785 then all archive files of all agenda files will be added to the search
3786 scope."
3787 :group 'org-agenda
3788 :type '(set :greedy t
3789 (const :tag "Agenda Archives" agenda-archives)
3790 (repeat :inline t (file))))
3792 (org-defvaralias 'org-agenda-multi-occur-extra-files
3793 'org-agenda-text-search-extra-files)
3795 (defcustom org-agenda-skip-unavailable-files nil
3796 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3797 A nil value means to remove them, after a query, from the list."
3798 :group 'org-agenda
3799 :type 'boolean)
3801 (defcustom org-calendar-to-agenda-key [?c]
3802 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3803 The command `org-calendar-goto-agenda' will be bound to this key. The
3804 default is the character `c' because then `c' can be used to switch back and
3805 forth between agenda and calendar."
3806 :group 'org-agenda
3807 :type 'sexp)
3809 (defcustom org-calendar-insert-diary-entry-key [?i]
3810 "The key to be installed in `calendar-mode-map' for adding diary entries.
3811 This option is irrelevant until `org-agenda-diary-file' has been configured
3812 to point to an Org-mode file. When that is the case, the command
3813 `org-agenda-diary-entry' will be bound to the key given here, by default
3814 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3815 if you want to continue doing this, you need to change this to a different
3816 key."
3817 :group 'org-agenda
3818 :type 'sexp)
3820 (defcustom org-agenda-diary-file 'diary-file
3821 "File to which to add new entries with the `i' key in agenda and calendar.
3822 When this is the symbol `diary-file', the functionality in the Emacs
3823 calendar will be used to add entries to the `diary-file'. But when this
3824 points to a file, `org-agenda-diary-entry' will be used instead."
3825 :group 'org-agenda
3826 :type '(choice
3827 (const :tag "The standard Emacs diary file" diary-file)
3828 (file :tag "Special Org file diary entries")))
3830 (eval-after-load "calendar"
3831 '(progn
3832 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3833 'org-calendar-goto-agenda)
3834 (add-hook 'calendar-mode-hook
3835 (lambda ()
3836 (unless (eq org-agenda-diary-file 'diary-file)
3837 (define-key calendar-mode-map
3838 org-calendar-insert-diary-entry-key
3839 'org-agenda-diary-entry))))))
3841 (defgroup org-latex nil
3842 "Options for embedding LaTeX code into Org-mode."
3843 :tag "Org LaTeX"
3844 :group 'org)
3846 (defcustom org-format-latex-options
3847 '(:foreground default :background default :scale 1.0
3848 :html-foreground "Black" :html-background "Transparent"
3849 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3850 "Options for creating images from LaTeX fragments.
3851 This is a property list with the following properties:
3852 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3853 `default' means use the foreground of the default face.
3854 `auto' means use the foreground from the text face.
3855 :background the background color, or \"Transparent\".
3856 `default' means use the background of the default face.
3857 `auto' means use the background from the text face.
3858 :scale a scaling factor for the size of the images, to get more pixels
3859 :html-foreground, :html-background, :html-scale
3860 the same numbers for HTML export.
3861 :matchers a list indicating which matchers should be used to
3862 find LaTeX fragments. Valid members of this list are:
3863 \"begin\" find environments
3864 \"$1\" find single characters surrounded by $.$
3865 \"$\" find math expressions surrounded by $...$
3866 \"$$\" find math expressions surrounded by $$....$$
3867 \"\\(\" find math expressions surrounded by \\(...\\)
3868 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3869 :group 'org-latex
3870 :type 'plist)
3872 (defcustom org-format-latex-signal-error t
3873 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3874 When nil, just push out a message."
3875 :group 'org-latex
3876 :version "24.1"
3877 :type 'boolean)
3879 (defcustom org-latex-to-mathml-jar-file nil
3880 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3881 Use this to specify additional executable file say a jar file.
3883 When using MathToWeb as the converter, specify the full-path to
3884 your mathtoweb.jar file."
3885 :group 'org-latex
3886 :version "24.1"
3887 :type '(choice
3888 (const :tag "None" nil)
3889 (file :tag "JAR file" :must-match t)))
3891 (defcustom org-latex-to-mathml-convert-command nil
3892 "Command to convert LaTeX fragments to MathML.
3893 Replace format-specifiers in the command as noted below and use
3894 `shell-command' to convert LaTeX to MathML.
3895 %j: Executable file in fully expanded form as specified by
3896 `org-latex-to-mathml-jar-file'.
3897 %I: Input LaTeX file in fully expanded form
3898 %o: Output MathML file
3899 This command is used by `org-create-math-formula'.
3901 When using MathToWeb as the converter, set this to
3902 \"java -jar %j -unicode -force -df %o %I\"."
3903 :group 'org-latex
3904 :version "24.1"
3905 :type '(choice
3906 (const :tag "None" nil)
3907 (string :tag "\nShell command")))
3909 (defcustom org-latex-create-formula-image-program 'dvipng
3910 "Program to convert LaTeX fragments with.
3912 dvipng Process the LaTeX fragments to dvi file, then convert
3913 dvi files to png files using dvipng.
3914 This will also include processing of non-math environments.
3915 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3916 to convert pdf files to png files"
3917 :group 'org-latex
3918 :version "24.1"
3919 :type '(choice
3920 (const :tag "dvipng" dvipng)
3921 (const :tag "imagemagick" imagemagick)))
3923 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3924 "Path to store latex preview images.
3925 A relative path here creates many directories relative to the
3926 processed org files paths. An absolute path puts all preview
3927 images at the same place."
3928 :group 'org-latex
3929 :version "24.3"
3930 :type 'string)
3932 (defun org-format-latex-mathml-available-p ()
3933 "Return t if `org-latex-to-mathml-convert-command' is usable."
3934 (save-match-data
3935 (when (and (boundp 'org-latex-to-mathml-convert-command)
3936 org-latex-to-mathml-convert-command)
3937 (let ((executable (car (split-string
3938 org-latex-to-mathml-convert-command))))
3939 (when (executable-find executable)
3940 (if (string-match
3941 "%j" org-latex-to-mathml-convert-command)
3942 (file-readable-p org-latex-to-mathml-jar-file)
3943 t))))))
3945 (defcustom org-format-latex-header "\\documentclass{article}
3946 \\usepackage[usenames]{color}
3947 \[PACKAGES]
3948 \[DEFAULT-PACKAGES]
3949 \\pagestyle{empty} % do not remove
3950 % The settings below are copied from fullpage.sty
3951 \\setlength{\\textwidth}{\\paperwidth}
3952 \\addtolength{\\textwidth}{-3cm}
3953 \\setlength{\\oddsidemargin}{1.5cm}
3954 \\addtolength{\\oddsidemargin}{-2.54cm}
3955 \\setlength{\\evensidemargin}{\\oddsidemargin}
3956 \\setlength{\\textheight}{\\paperheight}
3957 \\addtolength{\\textheight}{-\\headheight}
3958 \\addtolength{\\textheight}{-\\headsep}
3959 \\addtolength{\\textheight}{-\\footskip}
3960 \\addtolength{\\textheight}{-3cm}
3961 \\setlength{\\topmargin}{1.5cm}
3962 \\addtolength{\\topmargin}{-2.54cm}"
3963 "The document header used for processing LaTeX fragments.
3964 It is imperative that this header make sure that no page number
3965 appears on the page. The package defined in the variables
3966 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3967 will either replace the placeholder \"[PACKAGES]\" in this
3968 header, or they will be appended."
3969 :group 'org-latex
3970 :type 'string)
3972 (defun org-set-packages-alist (var val)
3973 "Set the packages alist and make sure it has 3 elements per entry."
3974 (set var (mapcar (lambda (x)
3975 (if (and (consp x) (= (length x) 2))
3976 (list (car x) (nth 1 x) t)
3978 val)))
3980 (defun org-get-packages-alist (var)
3981 "Get the packages alist and make sure it has 3 elements per entry."
3982 (mapcar (lambda (x)
3983 (if (and (consp x) (= (length x) 2))
3984 (list (car x) (nth 1 x) t)
3986 (default-value var)))
3988 (defcustom org-latex-default-packages-alist
3989 '(("AUTO" "inputenc" t)
3990 ("T1" "fontenc" t)
3991 ("" "fixltx2e" nil)
3992 ("" "graphicx" t)
3993 ("" "longtable" nil)
3994 ("" "float" nil)
3995 ("" "wrapfig" nil)
3996 ("" "rotating" nil)
3997 ("normalem" "ulem" t)
3998 ("" "amsmath" t)
3999 ("" "textcomp" t)
4000 ("" "marvosym" t)
4001 ("" "wasysym" t)
4002 ("" "amssymb" t)
4003 ("" "hyperref" nil)
4004 "\\tolerance=1000")
4005 "Alist of default packages to be inserted in the header.
4007 Change this only if one of the packages here causes an
4008 incompatibility with another package you are using.
4010 The packages in this list are needed by one part or another of
4011 Org mode to function properly:
4013 - inputenc, fontenc: for basic font and character selection
4014 - fixltx2e: Important patches of LaTeX itself
4015 - graphicx: for including images
4016 - longtable: For multipage tables
4017 - float, wrapfig: for figure placement
4018 - rotating: for sideways figures and tables
4019 - ulem: for underline and strike-through
4020 - amsmath: for subscript and superscript and math environments
4021 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4022 for interpreting the entities in `org-entities'. You can skip
4023 some of these packages if you don't use any of their symbols.
4024 - hyperref: for cross references
4026 Therefore you should not modify this variable unless you know
4027 what you are doing. The one reason to change it anyway is that
4028 you might be loading some other package that conflicts with one
4029 of the default packages. Each element is either a cell or
4030 a string.
4032 A cell is of the format:
4034 \( \"options\" \"package\" SNIPPET-FLAG).
4036 If SNIPPET-FLAG is non-nil, the package also needs to be included
4037 when compiling LaTeX snippets into images for inclusion into
4038 non-LaTeX output.
4040 A string will be inserted as-is in the header of the document."
4041 :group 'org-latex
4042 :group 'org-export-latex
4043 :set 'org-set-packages-alist
4044 :get 'org-get-packages-alist
4045 :version "24.1"
4046 :type '(repeat
4047 (choice
4048 (list :tag "options/package pair"
4049 (string :tag "options")
4050 (string :tag "package")
4051 (boolean :tag "Snippet"))
4052 (string :tag "A line of LaTeX"))))
4054 (defcustom org-latex-packages-alist nil
4055 "Alist of packages to be inserted in every LaTeX header.
4057 These will be inserted after `org-latex-default-packages-alist'.
4058 Each element is either a cell or a string.
4060 A cell is of the format:
4062 \(\"options\" \"package\" SNIPPET-FLAG)
4064 SNIPPET-FLAG, when non-nil, indicates that this package is also
4065 needed when turning LaTeX snippets into images for inclusion into
4066 non-LaTeX output.
4068 A string will be inserted as-is in the header of the document.
4070 Make sure that you only list packages here which:
4072 - you want in every file;
4073 - do not conflict with the setup in `org-format-latex-header';
4074 - do not conflict with the default packages in
4075 `org-latex-default-packages-alist'."
4076 :group 'org-latex
4077 :group 'org-export-latex
4078 :set 'org-set-packages-alist
4079 :get 'org-get-packages-alist
4080 :type '(repeat
4081 (choice
4082 (list :tag "options/package pair"
4083 (string :tag "options")
4084 (string :tag "package")
4085 (boolean :tag "Snippet"))
4086 (string :tag "A line of LaTeX"))))
4088 (defgroup org-appearance nil
4089 "Settings for Org-mode appearance."
4090 :tag "Org Appearance"
4091 :group 'org)
4093 (defcustom org-level-color-stars-only nil
4094 "Non-nil means fontify only the stars in each headline.
4095 When nil, the entire headline is fontified.
4096 Changing it requires restart of `font-lock-mode' to become effective
4097 also in regions already fontified."
4098 :group 'org-appearance
4099 :type 'boolean)
4101 (defcustom org-hide-leading-stars nil
4102 "Non-nil means hide the first N-1 stars in a headline.
4103 This works by using the face `org-hide' for these stars. This
4104 face is white for a light background, and black for a dark
4105 background. You may have to customize the face `org-hide' to
4106 make this work.
4107 Changing it requires restart of `font-lock-mode' to become effective
4108 also in regions already fontified.
4109 You may also set this on a per-file basis by adding one of the following
4110 lines to the buffer:
4112 #+STARTUP: hidestars
4113 #+STARTUP: showstars"
4114 :group 'org-appearance
4115 :type 'boolean)
4117 (defcustom org-hidden-keywords nil
4118 "List of symbols corresponding to keywords to be hidden the org buffer.
4119 For example, a value '(title) for this list will make the document's title
4120 appear in the buffer without the initial #+TITLE: keyword."
4121 :group 'org-appearance
4122 :version "24.1"
4123 :type '(set (const :tag "#+AUTHOR" author)
4124 (const :tag "#+DATE" date)
4125 (const :tag "#+EMAIL" email)
4126 (const :tag "#+TITLE" title)))
4128 (defcustom org-custom-properties nil
4129 "List of properties (as strings) with a special meaning.
4130 The default use of these custom properties is to let the user
4131 hide them with `org-toggle-custom-properties-visibility'."
4132 :group 'org-properties
4133 :group 'org-appearance
4134 :version "24.3"
4135 :type '(repeat (string :tag "Property Name")))
4137 (defcustom org-fontify-done-headline nil
4138 "Non-nil means change the face of a headline if it is marked DONE.
4139 Normally, only the TODO/DONE keyword indicates the state of a headline.
4140 When this is non-nil, the headline after the keyword is set to the
4141 `org-headline-done' as an additional indication."
4142 :group 'org-appearance
4143 :type 'boolean)
4145 (defcustom org-fontify-emphasized-text t
4146 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4147 Changing this variable requires a restart of Emacs to take effect."
4148 :group 'org-appearance
4149 :type 'boolean)
4151 (defcustom org-fontify-whole-heading-line nil
4152 "Non-nil means fontify the whole line for headings.
4153 This is useful when setting a background color for the
4154 org-level-* faces."
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-highlight-latex-and-related nil
4159 "Non-nil means highlight LaTeX related syntax in the buffer.
4160 When non nil, the value should be a list containing any of the
4161 following symbols:
4162 `latex' Highlight LaTeX snippets and environments.
4163 `script' Highlight subscript and superscript.
4164 `entities' Highlight entities."
4165 :group 'org-appearance
4166 :version "24.4"
4167 :package-version '(Org . "8.0")
4168 :type '(choice
4169 (const :tag "No highlighting" nil)
4170 (set :greedy t :tag "Highlight"
4171 (const :tag "LaTeX snippets and environments" latex)
4172 (const :tag "Subscript and superscript" script)
4173 (const :tag "Entities" entities))))
4175 (defcustom org-hide-emphasis-markers nil
4176 "Non-nil mean font-lock should hide the emphasis marker characters."
4177 :group 'org-appearance
4178 :type 'boolean)
4180 (defcustom org-hide-macro-markers nil
4181 "Non-nil mean font-lock should hide the brackets marking macro calls."
4182 :group 'org-appearance
4183 :type 'boolean)
4185 (defcustom org-pretty-entities nil
4186 "Non-nil means show entities as UTF8 characters.
4187 When nil, the \\name form remains in the buffer."
4188 :group 'org-appearance
4189 :version "24.1"
4190 :type 'boolean)
4192 (defcustom org-pretty-entities-include-sub-superscripts t
4193 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4194 :group 'org-appearance
4195 :version "24.1"
4196 :type 'boolean)
4198 (defvar org-emph-re nil
4199 "Regular expression for matching emphasis.
4200 After a match, the match groups contain these elements:
4201 0 The match of the full regular expression, including the characters
4202 before and after the proper match
4203 1 The character before the proper match, or empty at beginning of line
4204 2 The proper match, including the leading and trailing markers
4205 3 The leading marker like * or /, indicating the type of highlighting
4206 4 The text between the emphasis markers, not including the markers
4207 5 The character after the match, empty at the end of a line")
4208 (defvar org-verbatim-re nil
4209 "Regular expression for matching verbatim text.")
4210 (defvar org-emphasis-regexp-components) ; defined just below
4211 (defvar org-emphasis-alist) ; defined just below
4212 (defun org-set-emph-re (var val)
4213 "Set variable and compute the emphasis regular expression."
4214 (set var val)
4215 (when (and (boundp 'org-emphasis-alist)
4216 (boundp 'org-emphasis-regexp-components)
4217 org-emphasis-alist org-emphasis-regexp-components)
4218 (let* ((e org-emphasis-regexp-components)
4219 (pre (car e))
4220 (post (nth 1 e))
4221 (border (nth 2 e))
4222 (body (nth 3 e))
4223 (nl (nth 4 e))
4224 (body1 (concat body "*?"))
4225 (markers (mapconcat 'car org-emphasis-alist ""))
4226 (vmarkers (mapconcat
4227 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4228 org-emphasis-alist "")))
4229 ;; make sure special characters appear at the right position in the class
4230 (if (string-match "\\^" markers)
4231 (setq markers (concat (replace-match "" t t markers) "^")))
4232 (if (string-match "-" markers)
4233 (setq markers (concat (replace-match "" t t markers) "-")))
4234 (if (string-match "\\^" vmarkers)
4235 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4236 (if (string-match "-" vmarkers)
4237 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4238 (if (> nl 0)
4239 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4240 (int-to-string nl) "\\}")))
4241 ;; Make the regexp
4242 (setq org-emph-re
4243 (concat "\\([" pre "]\\|^\\)"
4244 "\\("
4245 "\\([" markers "]\\)"
4246 "\\("
4247 "[^" border "]\\|"
4248 "[^" border "]"
4249 body1
4250 "[^" border "]"
4251 "\\)"
4252 "\\3\\)"
4253 "\\([" post "]\\|$\\)"))
4254 (setq org-verbatim-re
4255 (concat "\\([" pre "]\\|^\\)"
4256 "\\("
4257 "\\([" vmarkers "]\\)"
4258 "\\("
4259 "[^" border "]\\|"
4260 "[^" border "]"
4261 body1
4262 "[^" border "]"
4263 "\\)"
4264 "\\3\\)"
4265 "\\([" post "]\\|$\\)")))))
4267 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4268 ;; set this option proved cumbersome. See this message/thread:
4269 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4270 (defvar org-emphasis-regexp-components
4271 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4272 "Components used to build the regular expression for emphasis.
4273 This is a list with five entries. Terminology: In an emphasis string
4274 like \" *strong word* \", we call the initial space PREMATCH, the final
4275 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4276 and \"trong wor\" is the body. The different components in this variable
4277 specify what is allowed/forbidden in each part:
4279 pre Chars allowed as prematch. Beginning of line will be allowed too.
4280 post Chars allowed as postmatch. End of line will be allowed too.
4281 border The chars *forbidden* as border characters.
4282 body-regexp A regexp like \".\" to match a body character. Don't use
4283 non-shy groups here, and don't allow newline here.
4284 newline The maximum number of newlines allowed in an emphasis exp.
4286 You need to reload Org or to restart Emacs after customizing this.")
4288 (defcustom org-emphasis-alist
4289 `(("*" bold)
4290 ("/" italic)
4291 ("_" underline)
4292 ("=" org-verbatim verbatim)
4293 ("~" org-code verbatim)
4294 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4295 "Alist of characters and faces to emphasize text.
4296 Text starting and ending with a special character will be emphasized,
4297 for example *bold*, _underlined_ and /italic/. This variable sets the
4298 marker characters and the face to be used by font-lock for highlighting
4299 in Org-mode Emacs buffers.
4301 You need to reload Org or to restart Emacs after customizing this."
4302 :group 'org-appearance
4303 :set 'org-set-emph-re
4304 :version "24.4"
4305 :package-version '(Org . "8.0")
4306 :type '(repeat
4307 (list
4308 (string :tag "Marker character")
4309 (choice
4310 (face :tag "Font-lock-face")
4311 (plist :tag "Face property list"))
4312 (option (const verbatim)))))
4314 (defvar org-protecting-blocks
4315 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4316 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4317 This is needed for font-lock setup.")
4319 ;;; Miscellaneous options
4321 (defgroup org-completion nil
4322 "Completion in Org-mode."
4323 :tag "Org Completion"
4324 :group 'org)
4326 (defcustom org-completion-use-ido nil
4327 "Non-nil means use ido completion wherever possible.
4328 Note that `ido-mode' must be active for this variable to be relevant.
4329 If you decide to turn this variable on, you might well want to turn off
4330 `org-outline-path-complete-in-steps'.
4331 See also `org-completion-use-iswitchb'."
4332 :group 'org-completion
4333 :type 'boolean)
4335 (defcustom org-completion-use-iswitchb nil
4336 "Non-nil means use iswitchb completion wherever possible.
4337 Note that `iswitchb-mode' must be active for this variable to be relevant.
4338 If you decide to turn this variable on, you might well want to turn off
4339 `org-outline-path-complete-in-steps'.
4340 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4341 :group 'org-completion
4342 :type 'boolean)
4344 (defcustom org-completion-fallback-command 'hippie-expand
4345 "The expansion command called by \\[pcomplete] in normal context.
4346 Normal means, no org-mode-specific context."
4347 :group 'org-completion
4348 :type 'function)
4350 ;;; Functions and variables from their packages
4351 ;; Declared here to avoid compiler warnings
4353 ;; XEmacs only
4354 (defvar outline-mode-menu-heading)
4355 (defvar outline-mode-menu-show)
4356 (defvar outline-mode-menu-hide)
4357 (defvar zmacs-regions) ; XEmacs regions
4359 ;; Emacs only
4360 (defvar mark-active)
4362 ;; Various packages
4363 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4364 (declare-function calendar-forward-day "cal-move" (arg))
4365 (declare-function calendar-goto-date "cal-move" (date))
4366 (declare-function calendar-goto-today "cal-move" ())
4367 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4368 (defvar calc-embedded-close-formula)
4369 (defvar calc-embedded-open-formula)
4370 (declare-function cdlatex-tab "ext:cdlatex" ())
4371 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4372 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4373 (defvar font-lock-unfontify-region-function)
4374 (declare-function iswitchb-read-buffer "iswitchb"
4375 (prompt &optional default require-match start matches-set))
4376 (defvar iswitchb-temp-buflist)
4377 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4378 (defvar org-agenda-tags-todo-honor-ignore-options)
4379 (declare-function org-agenda-skip "org-agenda" ())
4380 (declare-function
4381 org-agenda-format-item "org-agenda"
4382 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4383 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4384 (declare-function org-agenda-change-all-lines "org-agenda"
4385 (newhead hdmarker &optional fixface just-this))
4386 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4387 (declare-function org-agenda-maybe-redo "org-agenda" ())
4388 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4389 (beg end))
4390 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4391 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4392 "org-agenda" (&optional end))
4393 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4394 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4395 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4396 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4397 (declare-function org-indent-mode "org-indent" (&optional arg))
4398 (declare-function parse-time-string "parse-time" (string))
4399 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4400 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4401 (defvar remember-data-file)
4402 (defvar texmathp-why)
4403 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4404 (declare-function table--at-cell-p "table" (position &optional object at-column))
4405 (declare-function calc-eval "calc" (str &optional separator &rest args))
4407 ;;;###autoload
4408 (defun turn-on-orgtbl ()
4409 "Unconditionally turn on `orgtbl-mode'."
4410 (require 'org-table)
4411 (orgtbl-mode 1))
4413 (defun org-at-table-p (&optional table-type)
4414 "Return t if the cursor is inside an org-type table.
4415 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4416 (if org-enable-table-editor
4417 (save-excursion
4418 (beginning-of-line 1)
4419 (looking-at (if table-type org-table-any-line-regexp
4420 org-table-line-regexp)))
4421 nil))
4422 (defsubst org-table-p () (org-at-table-p))
4424 (defun org-at-table.el-p ()
4425 "Return t if and only if we are at a table.el table."
4426 (and (org-at-table-p 'any)
4427 (save-excursion
4428 (goto-char (org-table-begin 'any))
4429 (looking-at org-table1-hline-regexp))))
4431 (defun org-table-recognize-table.el ()
4432 "If there is a table.el table nearby, recognize it and move into it."
4433 (if org-table-tab-recognizes-table.el
4434 (if (org-at-table.el-p)
4435 (progn
4436 (beginning-of-line 1)
4437 (if (looking-at org-table-dataline-regexp)
4439 (if (looking-at org-table1-hline-regexp)
4440 (progn
4441 (beginning-of-line 2)
4442 (if (looking-at org-table-any-border-regexp)
4443 (beginning-of-line -1)))))
4444 (if (re-search-forward "|" (org-table-end t) t)
4445 (progn
4446 (require 'table)
4447 (if (table--at-cell-p (point))
4449 (message "recognizing table.el table...")
4450 (table-recognize-table)
4451 (message "recognizing table.el table...done")))
4452 (error "This should not happen"))
4454 nil)
4455 nil))
4457 (defun org-at-table-hline-p ()
4458 "Return t if the cursor is inside a hline in a table."
4459 (if org-enable-table-editor
4460 (save-excursion
4461 (beginning-of-line 1)
4462 (looking-at org-table-hline-regexp))
4463 nil))
4465 (defun org-table-map-tables (function &optional quietly)
4466 "Apply FUNCTION to the start of all tables in the buffer."
4467 (save-excursion
4468 (save-restriction
4469 (widen)
4470 (goto-char (point-min))
4471 (while (re-search-forward org-table-any-line-regexp nil t)
4472 (unless quietly
4473 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4474 (beginning-of-line 1)
4475 (when (and (looking-at org-table-line-regexp)
4476 ;; Exclude tables in src/example/verbatim/clocktable blocks
4477 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4478 (save-excursion (funcall function))
4479 (or (looking-at org-table-line-regexp)
4480 (forward-char 1)))
4481 (re-search-forward org-table-any-border-regexp nil 1))))
4482 (unless quietly (message "Mapping tables: done")))
4484 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4485 (declare-function org-clock-update-mode-line "org-clock" ())
4486 (declare-function org-resolve-clocks "org-clock"
4487 (&optional also-non-dangling-p prompt last-valid))
4489 (defun org-at-TBLFM-p (&optional pos)
4490 "Return t when point (or POS) is in #+TBLFM line."
4491 (save-excursion
4492 (let ((pos pos)))
4493 (goto-char (or pos (point)))
4494 (beginning-of-line 1)
4495 (looking-at org-TBLFM-regexp)))
4497 (defvar org-clock-start-time)
4498 (defvar org-clock-marker (make-marker)
4499 "Marker recording the last clock-in.")
4500 (defvar org-clock-hd-marker (make-marker)
4501 "Marker recording the last clock-in, but the headline position.")
4502 (defvar org-clock-heading ""
4503 "The heading of the current clock entry.")
4504 (defun org-clock-is-active ()
4505 "Return the buffer where the clock is currently running.
4506 Return nil if no clock is running."
4507 (marker-buffer org-clock-marker))
4509 (defun org-check-running-clock ()
4510 "Check if the current buffer contains the running clock.
4511 If yes, offer to stop it and to save the buffer with the changes."
4512 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4513 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4514 (buffer-name))))
4515 (org-clock-out)
4516 (when (y-or-n-p "Save changed buffer?")
4517 (save-buffer))))
4519 (defun org-clocktable-try-shift (dir n)
4520 "Check if this line starts a clock table, if yes, shift the time block."
4521 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4522 (org-clocktable-shift dir n)))
4524 ;;;###autoload
4525 (defun org-clock-persistence-insinuate ()
4526 "Set up hooks for clock persistence."
4527 (require 'org-clock)
4528 (add-hook 'org-mode-hook 'org-clock-load)
4529 (add-hook 'kill-emacs-hook 'org-clock-save))
4531 (defgroup org-archive nil
4532 "Options concerning archiving in Org-mode."
4533 :tag "Org Archive"
4534 :group 'org-structure)
4536 (defcustom org-archive-location "%s_archive::"
4537 "The location where subtrees should be archived.
4539 The value of this variable is a string, consisting of two parts,
4540 separated by a double-colon. The first part is a filename and
4541 the second part is a headline.
4543 When the filename is omitted, archiving happens in the same file.
4544 %s in the filename will be replaced by the current file
4545 name (without the directory part). Archiving to a different file
4546 is useful to keep archived entries from contributing to the
4547 Org-mode Agenda.
4549 The archived entries will be filed as subtrees of the specified
4550 headline. When the headline is omitted, the subtrees are simply
4551 filed away at the end of the file, as top-level entries. Also in
4552 the heading you can use %s to represent the file name, this can be
4553 useful when using the same archive for a number of different files.
4555 Here are a few examples:
4556 \"%s_archive::\"
4557 If the current file is Projects.org, archive in file
4558 Projects.org_archive, as top-level trees. This is the default.
4560 \"::* Archived Tasks\"
4561 Archive in the current file, under the top-level headline
4562 \"* Archived Tasks\".
4564 \"~/org/archive.org::\"
4565 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4567 \"~/org/archive.org::* From %s\"
4568 Archive in file ~/org/archive.org (absolute path), under headlines
4569 \"From FILENAME\" where file name is the current file name.
4571 \"~/org/datetree.org::datetree/* Finished Tasks\"
4572 The \"datetree/\" string is special, signifying to archive
4573 items to the datetree. Items are placed in either the CLOSED
4574 date of the item, or the current date if there is no CLOSED date.
4575 The heading will be a subentry to the current date. There doesn't
4576 need to be a heading, but there always needs to be a slash after
4577 datetree. For example, to store archived items directly in the
4578 datetree, use \"~/org/datetree.org::datetree/\".
4580 \"basement::** Finished Tasks\"
4581 Archive in file ./basement (relative path), as level 3 trees
4582 below the level 2 heading \"** Finished Tasks\".
4584 You may set this option on a per-file basis by adding to the buffer a
4585 line like
4587 #+ARCHIVE: basement::** Finished Tasks
4589 You may also define it locally for a subtree by setting an ARCHIVE property
4590 in the entry. If such a property is found in an entry, or anywhere up
4591 the hierarchy, it will be used."
4592 :group 'org-archive
4593 :type 'string)
4595 (defcustom org-agenda-skip-archived-trees t
4596 "Non-nil means the agenda will skip any items located in archived trees.
4597 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4598 variable is no longer recommended, you should leave it at the value t.
4599 Instead, use the key `v' to cycle the archives-mode in the agenda."
4600 :group 'org-archive
4601 :group 'org-agenda-skip
4602 :type 'boolean)
4604 (defcustom org-columns-skip-archived-trees t
4605 "Non-nil means ignore archived trees when creating column view."
4606 :group 'org-archive
4607 :group 'org-properties
4608 :type 'boolean)
4610 (defcustom org-cycle-open-archived-trees nil
4611 "Non-nil means `org-cycle' will open archived trees.
4612 An archived tree is a tree marked with the tag ARCHIVE.
4613 When nil, archived trees will stay folded. You can still open them with
4614 normal outline commands like `show-all', but not with the cycling commands."
4615 :group 'org-archive
4616 :group 'org-cycle
4617 :type 'boolean)
4619 (defcustom org-sparse-tree-open-archived-trees nil
4620 "Non-nil means sparse tree construction shows matches in archived trees.
4621 When nil, matches in these trees are highlighted, but the trees are kept in
4622 collapsed state."
4623 :group 'org-archive
4624 :group 'org-sparse-trees
4625 :type 'boolean)
4627 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4628 "The default date type when building a sparse tree.
4629 When this is nil, a date is a scheduled or a deadline timestamp.
4630 Otherwise, these types are allowed:
4632 all: all timestamps
4633 active: only active timestamps (<...>)
4634 inactive: only inactive timestamps (<...)
4635 scheduled: only scheduled timestamps
4636 deadline: only deadline timestamps"
4637 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4638 (const :tag "All timestamps" all)
4639 (const :tag "Only active timestamps" active)
4640 (const :tag "Only inactive timestamps" inactive)
4641 (const :tag "Only scheduled timestamps" scheduled)
4642 (const :tag "Only deadline timestamps" deadline)
4643 (const :tag "Only closed timestamps" closed))
4644 :version "24.3"
4645 :group 'org-sparse-trees)
4647 (defun org-cycle-hide-archived-subtrees (state)
4648 "Re-hide all archived subtrees after a visibility state change."
4649 (when (and (not org-cycle-open-archived-trees)
4650 (not (memq state '(overview folded))))
4651 (save-excursion
4652 (let* ((globalp (memq state '(contents all)))
4653 (beg (if globalp (point-min) (point)))
4654 (end (if globalp (point-max) (org-end-of-subtree t))))
4655 (org-hide-archived-subtrees beg end)
4656 (goto-char beg)
4657 (if (looking-at (concat ".*:" org-archive-tag ":"))
4658 (message "%s" (substitute-command-keys
4659 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4661 (defun org-force-cycle-archived ()
4662 "Cycle subtree even if it is archived."
4663 (interactive)
4664 (setq this-command 'org-cycle)
4665 (let ((org-cycle-open-archived-trees t))
4666 (call-interactively 'org-cycle)))
4668 (defun org-hide-archived-subtrees (beg end)
4669 "Re-hide all archived subtrees after a visibility state change."
4670 (save-excursion
4671 (let* ((re (concat ":" org-archive-tag ":")))
4672 (goto-char beg)
4673 (while (re-search-forward re end t)
4674 (when (org-at-heading-p)
4675 (org-flag-subtree t)
4676 (org-end-of-subtree t))))))
4678 (declare-function outline-end-of-heading "outline" ())
4679 (declare-function outline-flag-region "outline" (from to flag))
4680 (defun org-flag-subtree (flag)
4681 (save-excursion
4682 (org-back-to-heading t)
4683 (outline-end-of-heading)
4684 (outline-flag-region (point)
4685 (progn (org-end-of-subtree t) (point))
4686 flag)))
4688 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4690 ;; Declare Column View Code
4692 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4693 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4694 (declare-function org-columns-compute "org-colview" (property))
4696 ;; Declare ID code
4698 (declare-function org-id-store-link "org-id")
4699 (declare-function org-id-locations-load "org-id")
4700 (declare-function org-id-locations-save "org-id")
4701 (defvar org-id-track-globally)
4703 ;;; Variables for pre-computed regular expressions, all buffer local
4705 (defvar org-todo-regexp nil
4706 "Matches any of the TODO state keywords.")
4707 (make-variable-buffer-local 'org-todo-regexp)
4708 (defvar org-not-done-regexp nil
4709 "Matches any of the TODO state keywords except the last one.")
4710 (make-variable-buffer-local 'org-not-done-regexp)
4711 (defvar org-not-done-heading-regexp nil
4712 "Matches a TODO headline that is not done.")
4713 (make-variable-buffer-local 'org-not-done-regexp)
4714 (defvar org-todo-line-regexp nil
4715 "Matches a headline and puts TODO state into group 2 if present.")
4716 (make-variable-buffer-local 'org-todo-line-regexp)
4717 (defvar org-complex-heading-regexp nil
4718 "Matches a headline and puts everything into groups:
4719 group 1: the stars
4720 group 2: The todo keyword, maybe
4721 group 3: Priority cookie
4722 group 4: True headline
4723 group 5: Tags")
4724 (make-variable-buffer-local 'org-complex-heading-regexp)
4725 (defvar org-complex-heading-regexp-format nil
4726 "Printf format to make regexp to match an exact headline.
4727 This regexp will match the headline of any node which has the
4728 exact headline text that is put into the format, but may have any
4729 TODO state, priority and tags.")
4730 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4731 (defvar org-todo-line-tags-regexp nil
4732 "Matches a headline and puts TODO state into group 2 if present.
4733 Also put tags into group 4 if tags are present.")
4734 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4735 (defvar org-ds-keyword-length 12
4736 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4737 (make-variable-buffer-local 'org-ds-keyword-length)
4738 (defvar org-deadline-regexp nil
4739 "Matches the DEADLINE keyword.")
4740 (make-variable-buffer-local 'org-deadline-regexp)
4741 (defvar org-deadline-time-regexp nil
4742 "Matches the DEADLINE keyword together with a time stamp.")
4743 (make-variable-buffer-local 'org-deadline-time-regexp)
4744 (defvar org-deadline-time-hour-regexp nil
4745 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4746 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4747 (defvar org-deadline-line-regexp nil
4748 "Matches the DEADLINE keyword and the rest of the line.")
4749 (make-variable-buffer-local 'org-deadline-line-regexp)
4750 (defvar org-scheduled-regexp nil
4751 "Matches the SCHEDULED keyword.")
4752 (make-variable-buffer-local 'org-scheduled-regexp)
4753 (defvar org-scheduled-time-regexp nil
4754 "Matches the SCHEDULED keyword together with a time stamp.")
4755 (make-variable-buffer-local 'org-scheduled-time-regexp)
4756 (defvar org-scheduled-time-hour-regexp nil
4757 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4758 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4759 (defvar org-closed-time-regexp nil
4760 "Matches the CLOSED keyword together with a time stamp.")
4761 (make-variable-buffer-local 'org-closed-time-regexp)
4763 (defvar org-keyword-time-regexp nil
4764 "Matches any of the 4 keywords, together with the time stamp.")
4765 (make-variable-buffer-local 'org-keyword-time-regexp)
4766 (defvar org-keyword-time-not-clock-regexp nil
4767 "Matches any of the 3 keywords, together with the time stamp.")
4768 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4769 (defvar org-maybe-keyword-time-regexp nil
4770 "Matches a timestamp, possibly preceded by a keyword.")
4771 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4772 (defvar org-all-time-keywords nil
4773 "List of time keywords.")
4774 (make-variable-buffer-local 'org-all-time-keywords)
4776 (defconst org-plain-time-of-day-regexp
4777 (concat
4778 "\\(\\<[012]?[0-9]"
4779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4780 "\\(--?"
4781 "\\(\\<[012]?[0-9]"
4782 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4783 "\\)?")
4784 "Regular expression to match a plain time or time range.
4785 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4786 groups carry important information:
4787 0 the full match
4788 1 the first time, range or not
4789 8 the second time, if it is a range.")
4791 (defconst org-plain-time-extension-regexp
4792 (concat
4793 "\\(\\<[012]?[0-9]"
4794 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4795 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4796 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4797 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4798 groups carry important information:
4799 0 the full match
4800 7 hours of duration
4801 9 minutes of duration")
4803 (defconst org-stamp-time-of-day-regexp
4804 (concat
4805 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4806 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4807 "\\(--?"
4808 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4809 "Regular expression to match a timestamp time or time range.
4810 After a match, the following groups carry important information:
4811 0 the full match
4812 1 date plus weekday, for back referencing to make sure both times are on the same day
4813 2 the first time, range or not
4814 4 the second time, if it is a range.")
4816 (defconst org-startup-options
4817 '(("fold" org-startup-folded t)
4818 ("overview" org-startup-folded t)
4819 ("nofold" org-startup-folded nil)
4820 ("showall" org-startup-folded nil)
4821 ("showeverything" org-startup-folded showeverything)
4822 ("content" org-startup-folded content)
4823 ("indent" org-startup-indented t)
4824 ("noindent" org-startup-indented nil)
4825 ("hidestars" org-hide-leading-stars t)
4826 ("showstars" org-hide-leading-stars nil)
4827 ("odd" org-odd-levels-only t)
4828 ("oddeven" org-odd-levels-only nil)
4829 ("align" org-startup-align-all-tables t)
4830 ("noalign" org-startup-align-all-tables nil)
4831 ("inlineimages" org-startup-with-inline-images t)
4832 ("noinlineimages" org-startup-with-inline-images nil)
4833 ("latexpreview" org-startup-with-latex-preview t)
4834 ("nolatexpreview" org-startup-with-latex-preview nil)
4835 ("customtime" org-display-custom-times t)
4836 ("logdone" org-log-done time)
4837 ("lognotedone" org-log-done note)
4838 ("nologdone" org-log-done nil)
4839 ("lognoteclock-out" org-log-note-clock-out t)
4840 ("nolognoteclock-out" org-log-note-clock-out nil)
4841 ("logrepeat" org-log-repeat state)
4842 ("lognoterepeat" org-log-repeat note)
4843 ("logdrawer" org-log-into-drawer t)
4844 ("nologdrawer" org-log-into-drawer nil)
4845 ("logstatesreversed" org-log-states-order-reversed t)
4846 ("nologstatesreversed" org-log-states-order-reversed nil)
4847 ("nologrepeat" org-log-repeat nil)
4848 ("logreschedule" org-log-reschedule time)
4849 ("lognotereschedule" org-log-reschedule note)
4850 ("nologreschedule" org-log-reschedule nil)
4851 ("logredeadline" org-log-redeadline time)
4852 ("lognoteredeadline" org-log-redeadline note)
4853 ("nologredeadline" org-log-redeadline nil)
4854 ("logrefile" org-log-refile time)
4855 ("lognoterefile" org-log-refile note)
4856 ("nologrefile" org-log-refile nil)
4857 ("fninline" org-footnote-define-inline t)
4858 ("nofninline" org-footnote-define-inline nil)
4859 ("fnlocal" org-footnote-section nil)
4860 ("fnauto" org-footnote-auto-label t)
4861 ("fnprompt" org-footnote-auto-label nil)
4862 ("fnconfirm" org-footnote-auto-label confirm)
4863 ("fnplain" org-footnote-auto-label plain)
4864 ("fnadjust" org-footnote-auto-adjust t)
4865 ("nofnadjust" org-footnote-auto-adjust nil)
4866 ("constcgs" constants-unit-system cgs)
4867 ("constSI" constants-unit-system SI)
4868 ("noptag" org-tag-persistent-alist nil)
4869 ("hideblocks" org-hide-block-startup t)
4870 ("nohideblocks" org-hide-block-startup nil)
4871 ("beamer" org-startup-with-beamer-mode t)
4872 ("entitiespretty" org-pretty-entities t)
4873 ("entitiesplain" org-pretty-entities nil))
4874 "Variable associated with STARTUP options for org-mode.
4875 Each element is a list of three items: the startup options (as written
4876 in the #+STARTUP line), the corresponding variable, and the value to set
4877 this variable to if the option is found. An optional forth element PUSH
4878 means to push this value onto the list in the variable.")
4880 (defun org-update-property-plist (key val props)
4881 "Update PROPS with KEY and VAL."
4882 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4883 (key (if appending (substring key 0 (- (length key) 1)) key))
4884 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4885 (previous (cdr (assoc key props))))
4886 (if appending
4887 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4888 (cons (cons key val) remainder))))
4890 (defcustom org-group-tags t
4891 "When non-nil (the default), use group tags.
4892 This can be turned on/off through `org-toggle-tags-groups'."
4893 :group 'org-tags
4894 :group 'org-startup
4895 :type 'boolean)
4897 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4899 (defun org-toggle-tags-groups ()
4900 "Toggle support for group tags.
4901 Support for group tags is controlled by the option
4902 `org-group-tags', which is non-nil by default."
4903 (interactive)
4904 (setq org-group-tags (not org-group-tags))
4905 (cond ((and (derived-mode-p 'org-agenda-mode)
4906 org-group-tags)
4907 (org-agenda-redo))
4908 ((derived-mode-p 'org-mode)
4909 (let ((org-inhibit-startup t)) (org-mode))))
4910 (message "Groups tags support has been turned %s"
4911 (if org-group-tags "on" "off")))
4913 (defun org-set-regexps-and-options-for-tags ()
4914 "Precompute variables used for tags."
4915 (when (derived-mode-p 'org-mode)
4916 (org-set-local 'org-file-tags nil)
4917 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4918 (splitre "[ \t]+")
4919 (start 0)
4920 tags ftags key value)
4921 (save-excursion
4922 (save-restriction
4923 (widen)
4924 (goto-char (point-min))
4925 (while (re-search-forward re nil t)
4926 (setq key (upcase (org-match-string-no-properties 1))
4927 value (org-match-string-no-properties 2))
4928 (if (stringp value) (setq value (org-trim value)))
4929 (cond
4930 ((equal key "TAGS")
4931 (setq tags (append tags (if tags '("\\n") nil)
4932 (org-split-string value splitre))))
4933 ((equal key "FILETAGS")
4934 (when (string-match "\\S-" value)
4935 (setq ftags
4936 (append
4937 ftags
4938 (apply 'append
4939 (mapcar (lambda (x) (org-split-string x ":"))
4940 (org-split-string value)))))))))))
4941 ;; Process the file tags.
4942 (and ftags (org-set-local 'org-file-tags
4943 (mapcar 'org-add-prop-inherited ftags)))
4944 (org-set-local 'org-tag-groups-alist nil)
4945 ;; Process the tags.
4946 (when (and (not tags) org-tag-alist)
4947 (setq tags
4948 (mapcar
4949 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4950 ((eq (car tg) :endgroup) "}")
4951 ((eq (car tg) :grouptags) ":")
4952 ((eq (car tg) :newline) "\n")
4953 (t (concat (car tg)
4954 (if (characterp (cdr tg))
4955 (format "(%s)" (char-to-string (cdr tg))) "")))))
4956 org-tag-alist)))
4957 (let (e tgs g)
4958 (while (setq e (pop tags))
4959 (cond
4960 ((equal e "{")
4961 (progn (push '(:startgroup) tgs)
4962 (when (equal (nth 1 tags) ":")
4963 (push (list (replace-regexp-in-string
4964 "(.+)$" "" (nth 0 tags)))
4965 org-tag-groups-alist)
4966 (setq g 0))))
4967 ((equal e ":") (push '(:grouptags) tgs))
4968 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4969 ((equal e "\\n") (push '(:newline) tgs))
4970 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4971 (push (cons (match-string 1 e)
4972 (string-to-char (match-string 2 e))) tgs)
4973 (if (and g (> g 0))
4974 (setcar org-tag-groups-alist
4975 (append (car org-tag-groups-alist)
4976 (list (match-string 1 e)))))
4977 (if g (setq g (1+ g))))
4978 (t (push (list e) tgs)
4979 (if (and g (> g 0))
4980 (setcar org-tag-groups-alist
4981 (append (car org-tag-groups-alist) (list e))))
4982 (if g (setq g (1+ g))))))
4983 (org-set-local 'org-tag-alist nil)
4984 (while (setq e (pop tgs))
4985 (or (and (stringp (car e))
4986 (assoc (car e) org-tag-alist))
4987 (push e org-tag-alist)))
4988 ;; Return a list with tag variables
4989 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4991 (defvar org-ota nil)
4992 (defun org-set-regexps-and-options ()
4993 "Precompute regular expressions used in the current buffer."
4994 (when (derived-mode-p 'org-mode)
4995 (org-set-local 'org-todo-kwd-alist nil)
4996 (org-set-local 'org-todo-key-alist nil)
4997 (org-set-local 'org-todo-key-trigger nil)
4998 (org-set-local 'org-todo-keywords-1 nil)
4999 (org-set-local 'org-done-keywords nil)
5000 (org-set-local 'org-todo-heads nil)
5001 (org-set-local 'org-todo-sets nil)
5002 (org-set-local 'org-todo-log-states nil)
5003 (org-set-local 'org-file-properties nil)
5004 (let ((re (org-make-options-regexp
5005 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5006 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5007 "SETUPFILE" "OPTIONS")
5008 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5009 (splitre "[ \t]+")
5010 (scripts org-use-sub-superscripts)
5011 kwds kws0 kwsa key log value cat arch const links hw dws
5012 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5013 (start 0))
5014 (save-excursion
5015 (save-restriction
5016 (widen)
5017 (goto-char (point-min))
5018 (while
5019 (or (and
5020 ext-setup-or-nil
5021 (not org-ota)
5022 (let (ret)
5023 (with-temp-buffer
5024 (insert ext-setup-or-nil)
5025 (let ((major-mode 'org-mode) org-ota)
5026 (setq ret (save-match-data
5027 (org-set-regexps-and-options-for-tags)))))
5028 ;; Append setupfile tags to existing tags
5029 (setq org-ota t)
5030 (setq org-file-tags
5031 (delq nil (append org-file-tags (nth 0 ret)))
5032 org-tag-alist
5033 (delq nil (append org-tag-alist (nth 1 ret)))
5034 org-tag-groups-alist
5035 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5036 (and ext-setup-or-nil
5037 (string-match re ext-setup-or-nil start)
5038 (setq start (match-end 0)))
5039 (and (setq ext-setup-or-nil nil start 0)
5040 (re-search-forward re nil t)))
5041 (setq key (upcase (match-string 1 ext-setup-or-nil))
5042 value (org-match-string-no-properties 2 ext-setup-or-nil))
5043 (if (stringp value) (setq value (org-trim value)))
5044 (cond
5045 ((equal key "CATEGORY")
5046 (setq cat value))
5047 ((member key '("SEQ_TODO" "TODO"))
5048 (push (cons 'sequence (org-split-string value splitre)) kwds))
5049 ((equal key "TYP_TODO")
5050 (push (cons 'type (org-split-string value splitre)) kwds))
5051 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5052 ;; general TODO-like setup
5053 (push (cons (intern (downcase (match-string 1 key)))
5054 (org-split-string value splitre)) kwds))
5055 ((equal key "COLUMNS")
5056 (org-set-local 'org-columns-default-format value))
5057 ((equal key "LINK")
5058 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5059 (push (cons (match-string 1 value)
5060 (org-trim (match-string 2 value)))
5061 links)))
5062 ((equal key "PRIORITIES")
5063 (setq prio (org-split-string value " +")))
5064 ((equal key "PROPERTY")
5065 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5066 (setq props (org-update-property-plist (match-string 1 value)
5067 (match-string 2 value)
5068 props))))
5069 ((equal key "CONSTANTS")
5070 (org-table-set-constants))
5071 ((equal key "STARTUP")
5072 (let ((opts (org-split-string value splitre))
5073 l var val)
5074 (while (setq l (pop opts))
5075 (when (setq l (assoc l org-startup-options))
5076 (setq var (nth 1 l) val (nth 2 l))
5077 (if (not (nth 3 l))
5078 (set (make-local-variable var) val)
5079 (if (not (listp (symbol-value var)))
5080 (set (make-local-variable var) nil))
5081 (set (make-local-variable var) (symbol-value var))
5082 (add-to-list var val))))))
5083 ((equal key "ARCHIVE")
5084 (setq arch value)
5085 (remove-text-properties 0 (length arch)
5086 '(face t fontified t) arch))
5087 ((equal key "OPTIONS")
5088 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5089 (setq scripts (read (match-string 2 value)))))
5090 ((and (equal key "SETUPFILE")
5091 ;; Prevent checking in Gnus messages
5092 (not buffer-read-only))
5093 (setq setup-contents (org-file-contents
5094 (expand-file-name
5095 (org-remove-double-quotes value))
5096 'noerror))
5097 (if (not ext-setup-or-nil)
5098 (setq ext-setup-or-nil setup-contents start 0)
5099 (setq ext-setup-or-nil
5100 (concat (substring ext-setup-or-nil 0 start)
5101 "\n" setup-contents "\n"
5102 (substring ext-setup-or-nil start)))))))
5103 ;; search for property blocks
5104 (goto-char (point-min))
5105 (while (re-search-forward org-block-regexp nil t)
5106 (when (equal "PROPERTY" (upcase (match-string 1)))
5107 (setq value (replace-regexp-in-string
5108 "[\n\r]" " " (match-string 4)))
5109 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5110 (setq props (org-update-property-plist (match-string 1 value)
5111 (match-string 2 value)
5112 props)))))))
5113 (org-set-local 'org-use-sub-superscripts scripts)
5114 (when cat
5115 (org-set-local 'org-category (intern cat))
5116 (push (cons "CATEGORY" cat) props))
5117 (when prio
5118 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5119 (setq prio (mapcar 'string-to-char prio))
5120 (org-set-local 'org-highest-priority (nth 0 prio))
5121 (org-set-local 'org-lowest-priority (nth 1 prio))
5122 (org-set-local 'org-default-priority (nth 2 prio)))
5123 (and props (org-set-local 'org-file-properties (nreverse props)))
5124 (and arch (org-set-local 'org-archive-location arch))
5125 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5126 ;; Process the TODO keywords
5127 (unless kwds
5128 ;; Use the global values as if they had been given locally.
5129 (setq kwds (default-value 'org-todo-keywords))
5130 (if (stringp (car kwds))
5131 (setq kwds (list (cons org-todo-interpretation
5132 (default-value 'org-todo-keywords)))))
5133 (setq kwds (reverse kwds)))
5134 (setq kwds (nreverse kwds))
5135 (let (inter kws kw)
5136 (while (setq kws (pop kwds))
5137 (let ((kws (or
5138 (run-hook-with-args-until-success
5139 'org-todo-setup-filter-hook kws)
5140 kws)))
5141 (setq inter (pop kws) sep (member "|" kws)
5142 kws0 (delete "|" (copy-sequence kws))
5143 kwsa nil
5144 kws1 (mapcar
5145 (lambda (x)
5146 ;; 1 2
5147 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5148 (progn
5149 (setq kw (match-string 1 x)
5150 key (and (match-end 2) (match-string 2 x))
5151 log (org-extract-log-state-settings x))
5152 (push (cons kw (and key (string-to-char key))) kwsa)
5153 (and log (push log org-todo-log-states))
5155 (error "Invalid TODO keyword %s" x)))
5156 kws0)
5157 kwsa (if kwsa (append '((:startgroup))
5158 (nreverse kwsa)
5159 '((:endgroup))))
5160 hw (car kws1)
5161 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5162 tail (list inter hw (car dws) (org-last dws))))
5163 (add-to-list 'org-todo-heads hw 'append)
5164 (push kws1 org-todo-sets)
5165 (setq org-done-keywords (append org-done-keywords dws nil))
5166 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5167 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5168 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5169 (setq org-todo-sets (nreverse org-todo-sets)
5170 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5171 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5172 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5173 ;; Compute the regular expressions and other local variables.
5174 ;; Using `org-outline-regexp-bol' would complicate them much,
5175 ;; because of the fixed white space at the end of that string.
5176 (if (not org-done-keywords)
5177 (setq org-done-keywords (and org-todo-keywords-1
5178 (list (org-last org-todo-keywords-1)))))
5179 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5180 (length org-scheduled-string)
5181 (length org-clock-string)
5182 (length org-closed-string)))
5183 org-not-done-keywords
5184 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5185 org-todo-regexp
5186 (concat "\\("
5187 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5188 "\\)")
5189 org-not-done-regexp
5190 (concat "\\("
5191 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5192 "\\)")
5193 org-not-done-heading-regexp
5194 (format org-heading-keyword-regexp-format org-not-done-regexp)
5195 org-todo-line-regexp
5196 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5197 org-complex-heading-regexp
5198 (concat "^\\(\\*+\\)"
5199 "\\(?: +" org-todo-regexp "\\)?"
5200 "\\(?: +\\(\\[#.\\]\\)\\)?"
5201 "\\(?: +\\(.*?\\)\\)??"
5202 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5203 "[ \t]*$")
5204 org-complex-heading-regexp-format
5205 (concat "^\\(\\*+\\)"
5206 "\\(?: +" org-todo-regexp "\\)?"
5207 "\\(?: +\\(\\[#.\\]\\)\\)?"
5208 "\\(?: +"
5209 ;; Stats cookies can be stuck to body.
5210 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5211 "\\(%s\\)"
5212 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5213 "\\)"
5214 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5215 "[ \t]*$")
5216 org-todo-line-tags-regexp
5217 (concat "^\\(\\*+\\)"
5218 "\\(?: +" org-todo-regexp "\\)?"
5219 "\\(?: +\\(.*?\\)\\)??"
5220 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5221 "[ \t]*$")
5222 org-deadline-regexp (concat "\\<" org-deadline-string)
5223 org-deadline-time-regexp
5224 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5225 org-deadline-time-hour-regexp
5226 (concat "\\<" org-deadline-string
5227 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5228 org-deadline-line-regexp
5229 (concat "\\<\\(" org-deadline-string "\\).*")
5230 org-scheduled-regexp
5231 (concat "\\<" org-scheduled-string)
5232 org-scheduled-time-regexp
5233 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5234 org-scheduled-time-hour-regexp
5235 (concat "\\<" org-scheduled-string
5236 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5237 org-closed-time-regexp
5238 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5239 org-keyword-time-regexp
5240 (concat "\\<\\(" org-scheduled-string
5241 "\\|" org-deadline-string
5242 "\\|" org-closed-string
5243 "\\|" org-clock-string "\\)"
5244 " *[[<]\\([^]>]+\\)[]>]")
5245 org-keyword-time-not-clock-regexp
5246 (concat "\\<\\(" org-scheduled-string
5247 "\\|" org-deadline-string
5248 "\\|" org-closed-string
5249 "\\)"
5250 " *[[<]\\([^]>]+\\)[]>]")
5251 org-maybe-keyword-time-regexp
5252 (concat "\\(\\<\\(" org-scheduled-string
5253 "\\|" org-deadline-string
5254 "\\|" org-closed-string
5255 "\\|" org-clock-string "\\)\\)?"
5256 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5257 org-all-time-keywords
5258 (mapcar (lambda (w) (substring w 0 -1))
5259 (list org-scheduled-string org-deadline-string
5260 org-clock-string org-closed-string)))
5261 (setq org-ota nil)
5262 (org-compute-latex-and-related-regexp))))
5264 (defun org-file-contents (file &optional noerror)
5265 "Return the contents of FILE, as a string."
5266 (if (and file (file-readable-p file))
5267 (with-temp-buffer
5268 (insert-file-contents file)
5269 (buffer-string))
5270 (funcall (if noerror 'message 'error)
5271 "Cannot read file \"%s\"%s"
5272 file
5273 (let ((from (buffer-file-name (buffer-base-buffer))))
5274 (if from (concat " (referenced in file \"" from "\")") "")))))
5276 (defun org-extract-log-state-settings (x)
5277 "Extract the log state setting from a TODO keyword string.
5278 This will extract info from a string like \"WAIT(w@/!)\"."
5279 (let (kw key log1 log2)
5280 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5281 (setq kw (match-string 1 x)
5282 key (and (match-end 2) (match-string 2 x))
5283 log1 (and (match-end 3) (match-string 3 x))
5284 log2 (and (match-end 4) (match-string 4 x)))
5285 (and (or log1 log2)
5286 (list kw
5287 (and log1 (if (equal log1 "!") 'time 'note))
5288 (and log2 (if (equal log2 "!") 'time 'note)))))))
5290 (defun org-remove-keyword-keys (list)
5291 "Remove a pair of parenthesis at the end of each string in LIST."
5292 (mapcar (lambda (x)
5293 (if (string-match "(.*)$" x)
5294 (substring x 0 (match-beginning 0))
5296 list))
5298 (defun org-assign-fast-keys (alist)
5299 "Assign fast keys to a keyword-key alist.
5300 Respect keys that are already there."
5301 (let (new e (alt ?0))
5302 (while (setq e (pop alist))
5303 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5304 (cdr e)) ;; Key already assigned.
5305 (push e new)
5306 (let ((clist (string-to-list (downcase (car e))))
5307 (used (append new alist)))
5308 (when (= (car clist) ?@)
5309 (pop clist))
5310 (while (and clist (rassoc (car clist) used))
5311 (pop clist))
5312 (unless clist
5313 (while (rassoc alt used)
5314 (incf alt)))
5315 (push (cons (car e) (or (car clist) alt)) new))))
5316 (nreverse new)))
5318 ;;; Some variables used in various places
5320 (defvar org-window-configuration nil
5321 "Used in various places to store a window configuration.")
5322 (defvar org-selected-window nil
5323 "Used in various places to store a window configuration.")
5324 (defvar org-finish-function nil
5325 "Function to be called when `C-c C-c' is used.
5326 This is for getting out of special buffers like capture.")
5329 ;; FIXME: Occasionally check by commenting these, to make sure
5330 ;; no other functions uses these, forgetting to let-bind them.
5331 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5332 (defvar org-last-state)
5333 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5335 ;; Defined somewhere in this file, but used before definition.
5336 (defvar org-entities) ;; defined in org-entities.el
5337 (defvar org-struct-menu)
5338 (defvar org-org-menu)
5339 (defvar org-tbl-menu)
5341 ;;;; Define the Org-mode
5343 ;; We use a before-change function to check if a table might need
5344 ;; an update.
5345 (defvar org-table-may-need-update t
5346 "Indicates that a table might need an update.
5347 This variable is set by `org-before-change-function'.
5348 `org-table-align' sets it back to nil.")
5349 (defun org-before-change-function (beg end)
5350 "Every change indicates that a table might need an update."
5351 (setq org-table-may-need-update t))
5352 (defvar org-mode-map)
5353 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5354 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5355 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5357 (defvar org-table-buffer-is-an nil)
5359 (defvar bidi-paragraph-direction)
5360 (defvar buffer-face-mode-face)
5362 (require 'outline)
5363 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5364 (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"))
5365 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5367 ;; Other stuff we need.
5368 (require 'time-date)
5369 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5370 (require 'easymenu)
5371 (require 'overlay)
5373 ;; (require 'org-macs) moved higher up in the file before it is first used
5374 (require 'org-entities)
5375 ;; (require 'org-compat) moved higher up in the file before it is first used
5376 (require 'org-faces)
5377 (require 'org-list)
5378 (require 'org-pcomplete)
5379 (require 'org-src)
5380 (require 'org-footnote)
5381 (require 'org-macro)
5383 ;; babel
5384 (require 'ob)
5386 ;;;###autoload
5387 (define-derived-mode org-mode outline-mode "Org"
5388 "Outline-based notes management and organizer, alias
5389 \"Carsten's outline-mode for keeping track of everything.\"
5391 Org-mode develops organizational tasks around a NOTES file which
5392 contains information about projects as plain text. Org-mode is
5393 implemented on top of outline-mode, which is ideal to keep the content
5394 of large files well structured. It supports ToDo items, deadlines and
5395 time stamps, which magically appear in the diary listing of the Emacs
5396 calendar. Tables are easily created with a built-in table editor.
5397 Plain text URL-like links connect to websites, emails (VM), Usenet
5398 messages (Gnus), BBDB entries, and any files related to the project.
5399 For printing and sharing of notes, an Org-mode file (or a part of it)
5400 can be exported as a structured ASCII or HTML file.
5402 The following commands are available:
5404 \\{org-mode-map}"
5406 ;; Get rid of Outline menus, they are not needed
5407 ;; Need to do this here because define-derived-mode sets up
5408 ;; the keymap so late. Still, it is a waste to call this each time
5409 ;; we switch another buffer into org-mode.
5410 (if (featurep 'xemacs)
5411 (when (boundp 'outline-mode-menu-heading)
5412 ;; Assume this is Greg's port, it uses easymenu
5413 (easy-menu-remove outline-mode-menu-heading)
5414 (easy-menu-remove outline-mode-menu-show)
5415 (easy-menu-remove outline-mode-menu-hide))
5416 (define-key org-mode-map [menu-bar headings] 'undefined)
5417 (define-key org-mode-map [menu-bar hide] 'undefined)
5418 (define-key org-mode-map [menu-bar show] 'undefined))
5420 (org-load-modules-maybe)
5421 (easy-menu-add org-org-menu)
5422 (easy-menu-add org-tbl-menu)
5423 (org-install-agenda-files-menu)
5424 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5425 (add-to-invisibility-spec '(org-cwidth))
5426 (add-to-invisibility-spec '(org-hide-block . t))
5427 (when (featurep 'xemacs)
5428 (org-set-local 'line-move-ignore-invisible t))
5429 (org-set-local 'outline-regexp org-outline-regexp)
5430 (org-set-local 'outline-level 'org-outline-level)
5431 (setq bidi-paragraph-direction 'left-to-right)
5432 (when (and org-ellipsis
5433 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5434 (fboundp 'make-glyph-code))
5435 (unless org-display-table
5436 (setq org-display-table (make-display-table)))
5437 (set-display-table-slot
5438 org-display-table 4
5439 (vconcat (mapcar
5440 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5441 org-ellipsis)))
5442 (if (stringp org-ellipsis) org-ellipsis "..."))))
5443 (setq buffer-display-table org-display-table))
5444 (org-set-regexps-and-options-for-tags)
5445 (org-set-regexps-and-options)
5446 (org-set-font-lock-defaults)
5447 (when (and org-tag-faces (not org-tags-special-faces-re))
5448 ;; tag faces set outside customize.... force initialization.
5449 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5450 ;; Calc embedded
5451 (org-set-local 'calc-embedded-open-mode "# ")
5452 ;; Modify a few syntax entries
5453 (modify-syntax-entry ?@ "w")
5454 (modify-syntax-entry ?\" "\"")
5455 (modify-syntax-entry ?\\ "_")
5456 (modify-syntax-entry ?~ "_")
5457 (if org-startup-truncated (setq truncate-lines t))
5458 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5459 (org-set-local 'font-lock-unfontify-region-function
5460 'org-unfontify-region)
5461 ;; Activate before-change-function
5462 (org-set-local 'org-table-may-need-update t)
5463 (org-add-hook 'before-change-functions 'org-before-change-function nil
5464 'local)
5465 ;; Check for running clock before killing a buffer
5466 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5467 ;; Initialize macros templates.
5468 (org-macro-initialize-templates)
5469 ;; Initialize radio targets.
5470 (org-update-radio-target-regexp)
5471 ;; Indentation.
5472 (org-set-local 'indent-line-function 'org-indent-line)
5473 (org-set-local 'indent-region-function 'org-indent-region)
5474 ;; Filling and auto-filling.
5475 (org-setup-filling)
5476 ;; Comments.
5477 (org-setup-comments-handling)
5478 ;; Initialize cache.
5479 (org-element-cache-reset)
5480 ;; Beginning/end of defun
5481 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5482 (org-set-local 'end-of-defun-function
5483 (lambda ()
5484 (if (not (org-at-heading-p))
5485 (org-forward-element)
5486 (org-forward-element)
5487 (forward-char -1))))
5488 ;; Next error for sparse trees
5489 (org-set-local 'next-error-function 'org-occur-next-match)
5490 ;; Make sure dependence stuff works reliably, even for users who set it
5491 ;; too late :-(
5492 (if org-enforce-todo-dependencies
5493 (add-hook 'org-blocker-hook
5494 'org-block-todo-from-children-or-siblings-or-parent)
5495 (remove-hook 'org-blocker-hook
5496 'org-block-todo-from-children-or-siblings-or-parent))
5497 (if org-enforce-todo-checkbox-dependencies
5498 (add-hook 'org-blocker-hook
5499 'org-block-todo-from-checkboxes)
5500 (remove-hook 'org-blocker-hook
5501 'org-block-todo-from-checkboxes))
5503 ;; Align options lines
5504 (org-set-local
5505 'align-mode-rules-list
5506 '((org-in-buffer-settings
5507 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5508 (modes . '(org-mode)))))
5510 ;; Imenu
5511 (org-set-local 'imenu-create-index-function
5512 'org-imenu-get-tree)
5514 ;; Make isearch reveal context
5515 (if (or (featurep 'xemacs)
5516 (not (boundp 'outline-isearch-open-invisible-function)))
5517 ;; Emacs 21 and XEmacs make use of the hook
5518 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5519 ;; Emacs 22 deals with this through a special variable
5520 (org-set-local 'outline-isearch-open-invisible-function
5521 (lambda (&rest ignore) (org-show-context 'isearch))))
5523 ;; Setup the pcomplete hooks
5524 (set (make-local-variable 'pcomplete-command-completion-function)
5525 'org-pcomplete-initial)
5526 (set (make-local-variable 'pcomplete-command-name-function)
5527 'org-command-at-point)
5528 (set (make-local-variable 'pcomplete-default-completion-function)
5529 'ignore)
5530 (set (make-local-variable 'pcomplete-parse-arguments-function)
5531 'org-parse-arguments)
5532 (set (make-local-variable 'pcomplete-termination-string) "")
5533 (when (>= emacs-major-version 23)
5534 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5536 ;; If empty file that did not turn on org-mode automatically, make it to.
5537 (if (and org-insert-mode-line-in-empty-file
5538 (org-called-interactively-p 'any)
5539 (= (point-min) (point-max)))
5540 (insert "# -*- mode: org -*-\n\n"))
5541 (unless org-inhibit-startup
5542 (org-unmodified
5543 (and org-startup-with-beamer-mode (org-beamer-mode))
5544 (when org-startup-align-all-tables
5545 (org-table-map-tables 'org-table-align 'quietly))
5546 (when org-startup-with-inline-images
5547 (org-display-inline-images))
5548 (when org-startup-with-latex-preview
5549 (org-toggle-latex-fragment))
5550 (unless org-inhibit-startup-visibility-stuff
5551 (org-set-startup-visibility))
5552 (org-refresh-effort-properties)))
5553 ;; Try to set org-hide correctly
5554 (let ((foreground (org-find-invisible-foreground)))
5555 (if foreground
5556 (set-face-foreground 'org-hide foreground))))
5558 ;; Update `customize-package-emacs-version-alist'
5559 (add-to-list 'customize-package-emacs-version-alist
5560 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5561 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5562 ("8.2.6" . "24.4")))
5564 (defvar org-mode-transpose-word-syntax-table
5565 (let ((st (make-syntax-table)))
5566 (mapc (lambda(c) (modify-syntax-entry
5567 (string-to-char (car c)) "w p" st))
5568 org-emphasis-alist)
5569 st))
5571 (when (fboundp 'abbrev-table-put)
5572 (abbrev-table-put org-mode-abbrev-table
5573 :parents (list text-mode-abbrev-table)))
5575 (defun org-find-invisible-foreground ()
5576 (let ((candidates (remove
5577 "unspecified-bg"
5578 (nconc
5579 (list (face-background 'default)
5580 (face-background 'org-default))
5581 (mapcar
5582 (lambda (alist)
5583 (when (boundp alist)
5584 (cdr (assoc 'background-color (symbol-value alist)))))
5585 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5586 (list (face-foreground 'org-hide))))))
5587 (car (remove nil candidates))))
5589 (defun org-current-time (&optional rounding-minutes past)
5590 "Current time, possibly rounded to ROUNDING-MINUTES.
5591 When ROUNDING-MINUTES is not an integer, fall back on the car of
5592 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5593 the rounding returns a past time."
5594 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5595 (car org-time-stamp-rounding-minutes)))
5596 (time (decode-time)) res)
5597 (if (< r 1)
5598 (current-time)
5599 (setq res
5600 (apply 'encode-time
5601 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5602 (nthcdr 2 time))))
5603 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5604 (seconds-to-time (- (org-float-time res) (* r 60)))
5605 res))))
5607 (defun org-today ()
5608 "Return today date, considering `org-extend-today-until'."
5609 (time-to-days
5610 (time-subtract (current-time)
5611 (list 0 (* 3600 org-extend-today-until) 0))))
5613 ;;;; Font-Lock stuff, including the activators
5615 (defvar org-mouse-map (make-sparse-keymap))
5616 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5617 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5618 (when org-mouse-1-follows-link
5619 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5620 (when org-tab-follows-link
5621 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5622 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5624 (require 'font-lock)
5626 (defconst org-non-link-chars "]\t\n\r<>")
5627 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5628 "file+sys" "news" "shell" "elisp" "doi" "message"
5629 "help"))
5630 (defvar org-link-types-re nil
5631 "Matches a link that has a url-like prefix like \"http:\"")
5632 (defvar org-link-re-with-space nil
5633 "Matches a link with spaces, optional angular brackets around it.")
5634 (defvar org-link-re-with-space2 nil
5635 "Matches a link with spaces, optional angular brackets around it.")
5636 (defvar org-link-re-with-space3 nil
5637 "Matches a link with spaces, only for internal part in bracket links.")
5638 (defvar org-angle-link-re nil
5639 "Matches link with angular brackets, spaces are allowed.")
5640 (defvar org-plain-link-re nil
5641 "Matches plain link, without spaces.")
5642 (defvar org-bracket-link-regexp nil
5643 "Matches a link in double brackets.")
5644 (defvar org-bracket-link-analytic-regexp nil
5645 "Regular expression used to analyze links.
5646 Here is what the match groups contain after a match:
5647 1: http:
5648 2: http
5649 3: path
5650 4: [desc]
5651 5: desc")
5652 (defvar org-bracket-link-analytic-regexp++ nil
5653 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5654 (defvar org-any-link-re nil
5655 "Regular expression matching any link.")
5657 (defconst org-match-sexp-depth 3
5658 "Number of stacked braces for sub/superscript matching.")
5660 (defun org-create-multibrace-regexp (left right n)
5661 "Create a regular expression which will match a balanced sexp.
5662 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5663 as single character strings.
5664 The regexp returned will match the entire expression including the
5665 delimiters. It will also define a single group which contains the
5666 match except for the outermost delimiters. The maximum depth of
5667 stacked delimiters is N. Escaping delimiters is not possible."
5668 (let* ((nothing (concat "[^" left right "]*?"))
5669 (or "\\|")
5670 (re nothing)
5671 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5672 (while (> n 1)
5673 (setq n (1- n)
5674 re (concat re or next)
5675 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5676 (concat left "\\(" re "\\)" right)))
5678 (defconst org-match-substring-regexp
5679 (concat
5680 "\\(\\S-\\)\\([_^]\\)\\("
5681 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5682 "\\|"
5683 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5684 "\\|"
5685 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5686 "The regular expression matching a sub- or superscript.")
5688 (defconst org-match-substring-with-braces-regexp
5689 (concat
5690 "\\(\\S-\\)\\([_^]\\)"
5691 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5692 "The regular expression matching a sub- or superscript, forcing braces.")
5694 (defun org-make-link-regexps ()
5695 "Update the link regular expressions.
5696 This should be called after the variable `org-link-types' has changed."
5697 (let ((types-re (regexp-opt org-link-types t)))
5698 (setq org-link-types-re
5699 (concat "\\`" types-re ":")
5700 org-link-re-with-space
5701 (concat "<?" types-re ":"
5702 "\\([^" org-non-link-chars " ]"
5703 "[^" org-non-link-chars "]*"
5704 "[^" org-non-link-chars " ]\\)>?")
5705 org-link-re-with-space2
5706 (concat "<?" types-re ":"
5707 "\\([^" org-non-link-chars " ]"
5708 "[^\t\n\r]*"
5709 "[^" org-non-link-chars " ]\\)>?")
5710 org-link-re-with-space3
5711 (concat "<?" types-re ":"
5712 "\\([^" org-non-link-chars " ]"
5713 "[^\t\n\r]*\\)")
5714 org-angle-link-re
5715 (concat "<" types-re ":"
5716 "\\([^" org-non-link-chars " ]"
5717 "[^" org-non-link-chars "]*"
5718 "\\)>")
5719 org-plain-link-re
5720 (concat
5721 "\\<" types-re ":"
5722 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5723 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5724 org-bracket-link-regexp
5725 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5726 org-bracket-link-analytic-regexp
5727 (concat
5728 "\\[\\["
5729 "\\(" types-re ":\\)?"
5730 "\\([^]]+\\)"
5731 "\\]"
5732 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5733 "\\]")
5734 org-bracket-link-analytic-regexp++
5735 (concat
5736 "\\[\\["
5737 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5738 "\\([^]]+\\)"
5739 "\\]"
5740 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5741 "\\]")
5742 org-any-link-re
5743 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5744 org-angle-link-re "\\)\\|\\("
5745 org-plain-link-re "\\)"))))
5747 (org-make-link-regexps)
5749 (defvar org-emph-face nil)
5751 (defun org-do-emphasis-faces (limit)
5752 "Run through the buffer and emphasize strings."
5753 (let (rtn a)
5754 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5755 (let* ((border (char-after (match-beginning 3)))
5756 (bre (regexp-quote (char-to-string border))))
5757 (if (and (not (= border (char-after (match-beginning 4))))
5758 (not (save-match-data
5759 (string-match (concat bre ".*" bre)
5760 (replace-regexp-in-string
5761 "\n" " "
5762 (substring (match-string 2) 1 -1))))))
5763 (progn
5764 (setq rtn t)
5765 (setq a (assoc (match-string 3) org-emphasis-alist))
5766 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5767 'face
5768 (nth 1 a))
5769 (and (nth 2 a)
5770 (org-remove-flyspell-overlays-in
5771 (match-beginning 0) (match-end 0)))
5772 (add-text-properties (match-beginning 2) (match-end 2)
5773 '(font-lock-multiline t org-emphasis t))
5774 (when org-hide-emphasis-markers
5775 (add-text-properties (match-end 4) (match-beginning 5)
5776 '(invisible org-link))
5777 (add-text-properties (match-beginning 3) (match-end 3)
5778 '(invisible org-link))))))
5779 (goto-char (1+ (match-beginning 0))))
5780 rtn))
5782 (defun org-emphasize (&optional char)
5783 "Insert or change an emphasis, i.e. a font like bold or italic.
5784 If there is an active region, change that region to a new emphasis.
5785 If there is no region, just insert the marker characters and position
5786 the cursor between them.
5787 CHAR should be the marker character. If it is a space, it means to
5788 remove the emphasis of the selected region.
5789 If CHAR is not given (for example in an interactive call) it will be
5790 prompted for."
5791 (interactive)
5792 (let ((erc org-emphasis-regexp-components)
5793 (prompt "")
5794 (string "") beg end move c s)
5795 (if (org-region-active-p)
5796 (setq beg (region-beginning) end (region-end)
5797 string (buffer-substring beg end))
5798 (setq move t))
5800 (unless char
5801 (message "Emphasis marker or tag: [%s]"
5802 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5803 (setq char (read-char-exclusive)))
5804 (if (equal char ?\ )
5805 (setq s "" move nil)
5806 (unless (assoc (char-to-string char) org-emphasis-alist)
5807 (user-error "No such emphasis marker: \"%c\"" char))
5808 (setq s (char-to-string char)))
5809 (while (and (> (length string) 1)
5810 (equal (substring string 0 1) (substring string -1))
5811 (assoc (substring string 0 1) org-emphasis-alist))
5812 (setq string (substring string 1 -1)))
5813 (setq string (concat s string s))
5814 (if beg (delete-region beg end))
5815 (unless (or (bolp)
5816 (string-match (concat "[" (nth 0 erc) "\n]")
5817 (char-to-string (char-before (point)))))
5818 (insert " "))
5819 (unless (or (eobp)
5820 (string-match (concat "[" (nth 1 erc) "\n]")
5821 (char-to-string (char-after (point)))))
5822 (insert " ") (backward-char 1))
5823 (insert string)
5824 (and move (backward-char 1))))
5826 (defconst org-nonsticky-props
5827 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5829 (defsubst org-rear-nonsticky-at (pos)
5830 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5832 (defun org-activate-plain-links (limit)
5833 "Add link properties for plain links."
5834 (let (f hl)
5835 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5836 (not (member 'org-tag
5837 (get-text-property (1- (match-beginning 0)) 'face)))
5838 (not (org-in-src-block-p)))
5839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5840 (setq f (get-text-property (match-beginning 0) 'face))
5841 (setq hl (org-match-string-no-properties 0))
5842 (if (or (eq f 'org-tag)
5843 (and (listp f) (memq 'org-tag f)))
5845 (add-text-properties (match-beginning 0) (match-end 0)
5846 (list 'mouse-face 'highlight
5847 'face 'org-link
5848 'htmlize-link `(:uri ,hl)
5849 'keymap org-mouse-map))
5850 (org-rear-nonsticky-at (match-end 0)))
5851 t)))
5853 (defun org-activate-code (limit)
5854 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5855 (progn
5856 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5857 (remove-text-properties (match-beginning 0) (match-end 0)
5858 '(display t invisible t intangible t))
5859 t)))
5861 (defcustom org-src-fontify-natively t
5862 "When non-nil, fontify code in code blocks."
5863 :type 'boolean
5864 :version "24.4"
5865 :package-version '(Org . "8.3")
5866 :group 'org-appearance
5867 :group 'org-babel)
5869 (defcustom org-allow-promoting-top-level-subtree nil
5870 "When non-nil, allow promoting a top level subtree.
5871 The leading star of the top level headline will be replaced
5872 by a #."
5873 :type 'boolean
5874 :version "24.1"
5875 :group 'org-appearance)
5877 (defun org-fontify-meta-lines-and-blocks (limit)
5878 (condition-case nil
5879 (org-fontify-meta-lines-and-blocks-1 limit)
5880 (error (message "org-mode fontification error"))))
5882 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5883 "Fontify #+ lines and blocks."
5884 (let ((case-fold-search t))
5885 (if (re-search-forward
5886 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5887 limit t)
5888 (let ((beg (match-beginning 0))
5889 (block-start (match-end 0))
5890 (block-end nil)
5891 (lang (match-string 7))
5892 (beg1 (line-beginning-position 2))
5893 (dc1 (downcase (match-string 2)))
5894 (dc3 (downcase (match-string 3)))
5895 end end1 quoting block-type ovl)
5896 (cond
5897 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5898 ;; a single line of backend-specific content
5899 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5900 (remove-text-properties (match-beginning 0) (match-end 0)
5901 '(display t invisible t intangible t))
5902 (add-text-properties (match-beginning 1) (match-end 3)
5903 '(font-lock-fontified t face org-meta-line))
5904 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5905 '(font-lock-fontified t face org-block))
5906 ; for backend-specific code
5908 ((and (match-end 4) (equal dc3 "+begin"))
5909 ;; Truly a block
5910 (setq block-type (downcase (match-string 5))
5911 quoting (member block-type org-protecting-blocks))
5912 (when (re-search-forward
5913 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5914 nil t) ;; on purpose, we look further than LIMIT
5915 (setq end (min (point-max) (match-end 0))
5916 end1 (min (point-max) (1- (match-beginning 0))))
5917 (setq block-end (match-beginning 0))
5918 (when quoting
5919 (org-remove-flyspell-overlays-in beg1 end1)
5920 (remove-text-properties beg end
5921 '(display t invisible t intangible t)))
5922 (add-text-properties
5923 beg end '(font-lock-fontified t font-lock-multiline t))
5924 (add-text-properties beg beg1 '(face org-meta-line))
5925 (org-remove-flyspell-overlays-in beg beg1)
5926 (add-text-properties ; For end_src
5927 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5928 (org-remove-flyspell-overlays-in end1 end)
5929 (cond
5930 ((and lang (not (string= lang "")) org-src-fontify-natively)
5931 (org-src-font-lock-fontify-block lang block-start block-end)
5932 (add-text-properties beg1 block-end '(src-block t)))
5933 (quoting
5934 (add-text-properties beg1 (min (point-max) (1+ end1))
5935 '(face org-block))) ; end of source block
5936 ((not org-fontify-quote-and-verse-blocks))
5937 ((string= block-type "quote")
5938 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5939 ((string= block-type "verse")
5940 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5941 (add-text-properties beg beg1 '(face org-block-begin-line))
5942 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5943 '(face org-block-end-line))
5945 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5946 (org-remove-flyspell-overlays-in
5947 (match-beginning 0)
5948 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5949 (add-text-properties
5950 beg (match-end 3)
5951 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5952 '(font-lock-fontified t invisible t)
5953 '(font-lock-fontified t face org-document-info-keyword)))
5954 (add-text-properties
5955 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5956 (if (string-equal dc1 "+title:")
5957 '(font-lock-fontified t face org-document-title)
5958 '(font-lock-fontified t face org-document-info))))
5959 ((or (equal dc1 "+results")
5960 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5961 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5962 "+call:" "+header:" "+headers:" "+name:"))
5963 (and (match-end 4) (equal dc3 "+attr")))
5964 (org-remove-flyspell-overlays-in
5965 (match-beginning 0)
5966 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5967 (add-text-properties
5968 beg (match-end 0)
5969 '(font-lock-fontified t face org-meta-line))
5971 ((member dc3 '(" " ""))
5972 (org-remove-flyspell-overlays-in beg (match-end 0))
5973 (add-text-properties
5974 beg (match-end 0)
5975 '(font-lock-fontified t face font-lock-comment-face)))
5976 (t ;; just any other in-buffer setting, but not indented
5977 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5978 (add-text-properties
5979 beg (match-end 0)
5980 '(font-lock-fontified t face org-meta-line))
5981 t))))))
5983 (defun org-fontify-drawers (limit)
5984 "Fontify drawers."
5985 (when (re-search-forward org-drawer-regexp limit t)
5986 (add-text-properties
5987 (match-beginning 0) (match-end 0)
5988 '(font-lock-fontified t face org-special-keyword))
5989 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (defun org-fontify-macros (limit)
5993 "Fontify macros."
5994 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5995 (add-text-properties
5996 (match-beginning 0) (match-end 0)
5997 '(font-lock-fontified t face org-macro))
5998 (when org-hide-macro-markers
5999 (add-text-properties (match-end 2) (match-beginning 2)
6000 '(invisible t))
6001 (add-text-properties (match-beginning 1) (match-end 1)
6002 '(invisible t)))
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6006 (defun org-activate-angle-links (limit)
6007 "Add text properties for angle links."
6008 (if (and (re-search-forward org-angle-link-re limit t)
6009 (not (org-in-src-block-p)))
6010 (progn
6011 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6012 (add-text-properties (match-beginning 0) (match-end 0)
6013 (list 'mouse-face 'highlight
6014 'keymap org-mouse-map))
6015 (org-rear-nonsticky-at (match-end 0))
6016 t)))
6018 (defun org-activate-footnote-links (limit)
6019 "Add text properties for footnotes."
6020 (let ((fn (org-footnote-next-reference-or-definition limit)))
6021 (when fn
6022 (let* ((beg (nth 1 fn))
6023 (end (nth 2 fn))
6024 (label (car fn))
6025 (referencep (/= (line-beginning-position) beg)))
6026 (when (and referencep (nth 3 fn))
6027 (save-excursion
6028 (goto-char beg)
6029 (search-forward (or label "fn:"))
6030 (org-remove-flyspell-overlays-in beg (match-end 0))))
6031 (add-text-properties beg end
6032 (list 'mouse-face 'highlight
6033 'keymap org-mouse-map
6034 'help-echo
6035 (if referencep "Footnote reference"
6036 "Footnote definition")
6037 'font-lock-fontified t
6038 'font-lock-multiline t
6039 'face 'org-footnote))))))
6041 (defun org-activate-bracket-links (limit)
6042 "Add text properties for bracketed links."
6043 (if (and (re-search-forward org-bracket-link-regexp limit t)
6044 (not (org-in-src-block-p)))
6045 (let* ((hl (org-match-string-no-properties 1))
6046 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6047 (ip (org-maybe-intangible
6048 (list 'invisible 'org-link
6049 'keymap org-mouse-map 'mouse-face 'highlight
6050 'font-lock-multiline t 'help-echo help
6051 'htmlize-link `(:uri ,hl))))
6052 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6053 'font-lock-multiline t 'help-echo help
6054 'htmlize-link `(:uri ,hl))))
6055 ;; We need to remove the invisible property here. Table narrowing
6056 ;; may have made some of this invisible.
6057 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6058 (remove-text-properties (match-beginning 0) (match-end 0)
6059 '(invisible nil))
6060 (if (match-end 3)
6061 (progn
6062 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6063 (org-rear-nonsticky-at (match-beginning 3))
6064 (add-text-properties (match-beginning 3) (match-end 3) vp)
6065 (org-rear-nonsticky-at (match-end 3))
6066 (add-text-properties (match-end 3) (match-end 0) ip)
6067 (org-rear-nonsticky-at (match-end 0)))
6068 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6069 (org-rear-nonsticky-at (match-beginning 1))
6070 (add-text-properties (match-beginning 1) (match-end 1) vp)
6071 (org-rear-nonsticky-at (match-end 1))
6072 (add-text-properties (match-end 1) (match-end 0) ip)
6073 (org-rear-nonsticky-at (match-end 0)))
6074 t)))
6076 (defun org-activate-dates (limit)
6077 "Add text properties for dates."
6078 (if (and (re-search-forward org-tsr-regexp-both limit t)
6079 (not (equal (char-before (match-beginning 0)) 91)))
6080 (progn
6081 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6082 (add-text-properties (match-beginning 0) (match-end 0)
6083 (list 'mouse-face 'highlight
6084 'keymap org-mouse-map))
6085 (org-rear-nonsticky-at (match-end 0))
6086 (when org-display-custom-times
6087 (if (match-end 3)
6088 (org-display-custom-time (match-beginning 3) (match-end 3)))
6089 (org-display-custom-time (match-beginning 1) (match-end 1)))
6090 t)))
6092 (defvar org-target-link-regexp nil
6093 "Regular expression matching radio targets in plain text.")
6094 (make-variable-buffer-local 'org-target-link-regexp)
6096 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6097 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6098 border border border))
6099 "Regular expression matching a link target.")
6101 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6102 "Regular expression matching a radio target.")
6104 (defconst org-any-target-regexp
6105 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6106 "Regular expression matching any target.")
6108 (defun org-activate-target-links (limit)
6109 "Add text properties for target matches."
6110 (when org-target-link-regexp
6111 (let ((case-fold-search t))
6112 (if (re-search-forward org-target-link-regexp limit t)
6113 (progn
6114 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map
6118 'help-echo "Radio target link"
6119 'org-linked-text t))
6120 (org-rear-nonsticky-at (match-end 1))
6121 t)))))
6123 (defun org-update-radio-target-regexp ()
6124 "Find all radio targets in this file and update the regular expression.
6125 Also refresh fontification if needed."
6126 (interactive)
6127 (let ((old-regexp org-target-link-regexp)
6128 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6129 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6130 (targets
6131 (org-with-wide-buffer
6132 (goto-char (point-min))
6133 (let (rtn)
6134 (while (re-search-forward org-radio-target-regexp nil t)
6135 ;; Make sure point is really within the object.
6136 (backward-char)
6137 (let ((obj (org-element-context)))
6138 (when (eq (org-element-type obj) 'radio-target)
6139 (add-to-list 'rtn (org-element-property :value obj)))))
6140 rtn))))
6141 (setq org-target-link-regexp
6142 (and targets
6143 (concat before-re
6144 (mapconcat
6145 (lambda (x)
6146 (replace-regexp-in-string
6147 " +" "\\s-+" (regexp-quote x) t t))
6148 targets
6149 "\\|")
6150 after-re)))
6151 (unless (equal old-regexp org-target-link-regexp)
6152 ;; Clean-up cache.
6153 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6154 ((not org-target-link-regexp) old-regexp)
6156 (concat before-re
6157 (mapconcat
6158 (lambda (re)
6159 (substring re (length before-re)
6160 (- (length after-re))))
6161 (list old-regexp org-target-link-regexp)
6162 "\\|")
6163 after-re)))))
6164 (org-with-wide-buffer
6165 (goto-char (point-min))
6166 (while (re-search-forward regexp nil t)
6167 (org-element-cache-refresh (match-beginning 1)))))
6168 ;; Re fontify buffer.
6169 (when (memq 'radio org-highlight-links)
6170 (org-restart-font-lock)))))
6172 (defun org-hide-wide-columns (limit)
6173 (let (s e)
6174 (setq s (text-property-any (point) (or limit (point-max))
6175 'org-cwidth t))
6176 (when s
6177 (setq e (next-single-property-change s 'org-cwidth))
6178 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6179 (goto-char e)
6180 t)))
6182 (defvar org-latex-and-related-regexp nil
6183 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6185 (defun org-compute-latex-and-related-regexp ()
6186 "Compute regular expression for LaTeX, entities and sub/superscript.
6187 Result depends on variable `org-highlight-latex-and-related'."
6188 (org-set-local
6189 'org-latex-and-related-regexp
6190 (let* ((re-sub
6191 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6192 ((eq org-use-sub-superscripts '{})
6193 (list org-match-substring-with-braces-regexp))
6194 (org-use-sub-superscripts (list org-match-substring-regexp))))
6195 (re-latex
6196 (when (memq 'latex org-highlight-latex-and-related)
6197 (let ((matchers (plist-get org-format-latex-options :matchers)))
6198 (delq nil
6199 (mapcar (lambda (x)
6200 (and (member (car x) matchers) (nth 1 x)))
6201 org-latex-regexps)))))
6202 (re-entities
6203 (when (memq 'entities org-highlight-latex-and-related)
6204 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6205 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6207 (defun org-do-latex-and-related (limit)
6208 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6209 LIMIT bounds the search for syntax to highlight. Stop at first
6210 highlighted object, if any. Return t if some highlighting was
6211 done, nil otherwise."
6212 (when (org-string-nw-p org-latex-and-related-regexp)
6213 (catch 'found
6214 (while (re-search-forward org-latex-and-related-regexp limit t)
6215 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6216 'face))
6217 '(org-code org-verbatim underline))
6218 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6219 '(?_ ?^))
6221 0)))
6222 (font-lock-prepend-text-property
6223 (+ offset (match-beginning 0)) (match-end 0)
6224 'face 'org-latex-and-related)
6225 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6226 '(font-lock-multiline t)))
6227 (throw 'found t)))
6228 nil)))
6230 (defun org-restart-font-lock ()
6231 "Restart `font-lock-mode', to force refontification."
6232 (when (and (boundp 'font-lock-mode) font-lock-mode)
6233 (font-lock-mode -1)
6234 (font-lock-mode 1)))
6236 (defun org-activate-tags (limit)
6237 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6238 (progn
6239 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6240 (add-text-properties (match-beginning 1) (match-end 1)
6241 (list 'mouse-face 'highlight
6242 'keymap org-mouse-map))
6243 (org-rear-nonsticky-at (match-end 1))
6244 t)))
6246 (defun org-outline-level ()
6247 "Compute the outline level of the heading at point.
6248 If this is called at a normal headline, the level is the number of stars.
6249 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6250 (save-excursion
6251 (if (not (ignore-errors (org-back-to-heading t)))
6253 (looking-at org-outline-regexp)
6254 (1- (- (match-end 0) (match-beginning 0))))))
6256 (defvar org-font-lock-keywords nil)
6258 (defsubst org-re-property (property &optional literal allow-null)
6259 "Return a regexp matching a PROPERTY line.
6261 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6262 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6263 non-nil, match properties even without a value.
6265 Match group 3 is set to the value when it exists. If there is no
6266 value and ALLOW-NULL is non-nil, it is set to the empty string."
6267 (concat
6268 "^\\(?4:[ \t]*\\)"
6269 (format "\\(?1::\\(?2:%s\\):\\)"
6270 (if literal property (regexp-quote property)))
6271 (if allow-null
6272 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6273 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6275 (defconst org-property-re
6276 (org-re-property ".*?" 'literal t)
6277 "Regular expression matching a property line.
6278 There are four matching groups:
6279 1: :PROPKEY: including the leading and trailing colon,
6280 2: PROPKEY without the leading and trailing colon,
6281 3: PROPVAL without leading or trailing spaces,
6282 4: the indentation of the current line,
6283 5: trailing whitespace.")
6285 (defvar org-font-lock-hook nil
6286 "Functions to be called for special font lock stuff.")
6288 (defvar org-font-lock-set-keywords-hook nil
6289 "Functions that can manipulate `org-font-lock-extra-keywords'.
6290 This is called after `org-font-lock-extra-keywords' is defined, but before
6291 it is installed to be used by font lock. This can be useful if something
6292 needs to be inserted at a specific position in the font-lock sequence.")
6294 (defun org-font-lock-hook (limit)
6295 "Run `org-font-lock-hook' within LIMIT."
6296 (run-hook-with-args 'org-font-lock-hook limit))
6298 (defun org-set-font-lock-defaults ()
6299 "Set font lock defaults for the current buffer."
6300 (let* ((em org-fontify-emphasized-text)
6301 (lk org-highlight-links)
6302 (org-font-lock-extra-keywords
6303 (list
6304 ;; Call the hook
6305 '(org-font-lock-hook)
6306 ;; Headlines
6307 `(,(if org-fontify-whole-heading-line
6308 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6309 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6310 (1 (org-get-level-face 1))
6311 (2 (org-get-level-face 2))
6312 (3 (org-get-level-face 3)))
6313 ;; Table lines
6314 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6315 (1 'org-table t))
6316 ;; Table internals
6317 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6318 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6319 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6320 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6321 ;; Drawers
6322 '(org-fontify-drawers)
6323 ;; Properties
6324 (list org-property-re
6325 '(1 'org-special-keyword t)
6326 '(3 'org-property-value t))
6327 ;; Links
6328 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6329 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6330 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6331 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6332 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6333 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6334 (if (memq 'footnote lk) '(org-activate-footnote-links))
6335 ;; Targets.
6336 (list org-any-target-regexp '(0 'org-target t))
6337 ;; Diary sexps.
6338 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6339 ;; Macro
6340 '(org-fontify-macros)
6341 '(org-hide-wide-columns (0 nil append))
6342 ;; TODO keyword
6343 (list (format org-heading-keyword-regexp-format
6344 org-todo-regexp)
6345 '(2 (org-get-todo-face 2) t))
6346 ;; DONE
6347 (if org-fontify-done-headline
6348 (list (format org-heading-keyword-regexp-format
6349 (concat
6350 "\\(?:"
6351 (mapconcat 'regexp-quote org-done-keywords "\\|")
6352 "\\)"))
6353 '(2 'org-headline-done t))
6354 nil)
6355 ;; Priorities
6356 '(org-font-lock-add-priority-faces)
6357 ;; Tags
6358 '(org-font-lock-add-tag-faces)
6359 ;; Tags groups
6360 (if (and org-group-tags org-tag-groups-alist)
6361 (list (concat org-outline-regexp-bol ".+\\(:"
6362 (regexp-opt (mapcar 'car org-tag-groups-alist))
6363 ":\\).*$")
6364 '(1 'org-tag-group prepend)))
6365 ;; Special keywords
6366 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6367 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6368 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6369 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6370 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6371 ;; Emphasis
6372 (if em
6373 (if (featurep 'xemacs)
6374 '(org-do-emphasis-faces (0 nil append))
6375 '(org-do-emphasis-faces)))
6376 ;; Checkboxes
6377 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6378 1 'org-checkbox prepend)
6379 (if (cdr (assq 'checkbox org-list-automatic-rules))
6380 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6381 (0 (org-get-checkbox-statistics-face) t)))
6382 ;; Description list items
6383 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6384 1 'org-list-dt prepend)
6385 ;; ARCHIVEd headings
6386 (list (concat
6387 org-outline-regexp-bol
6388 "\\(.*:" org-archive-tag ":.*\\)")
6389 '(1 'org-archived prepend))
6390 ;; Specials
6391 '(org-do-latex-and-related)
6392 '(org-fontify-entities)
6393 '(org-raise-scripts)
6394 ;; Code
6395 '(org-activate-code (1 'org-code t))
6396 ;; COMMENT
6397 (list (format
6398 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6399 org-todo-regexp
6400 org-comment-string)
6401 '(9 'org-special-keyword t))
6402 ;; Blocks and meta lines
6403 '(org-fontify-meta-lines-and-blocks))))
6404 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6405 (run-hooks 'org-font-lock-set-keywords-hook)
6406 ;; Now set the full font-lock-keywords
6407 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6408 (org-set-local 'font-lock-defaults
6409 '(org-font-lock-keywords t nil nil backward-paragraph))
6410 (kill-local-variable 'font-lock-keywords) nil))
6412 (defun org-toggle-pretty-entities ()
6413 "Toggle the composition display of entities as UTF8 characters."
6414 (interactive)
6415 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6416 (org-restart-font-lock)
6417 (if org-pretty-entities
6418 (message "Entities are now displayed as UTF8 characters")
6419 (save-restriction
6420 (widen)
6421 (org-decompose-region (point-min) (point-max))
6422 (message "Entities are now displayed as plain text"))))
6424 (defvar org-custom-properties-overlays nil
6425 "List of overlays used for custom properties.")
6426 (make-variable-buffer-local 'org-custom-properties-overlays)
6428 (defun org-toggle-custom-properties-visibility ()
6429 "Display or hide properties in `org-custom-properties'."
6430 (interactive)
6431 (if org-custom-properties-overlays
6432 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6433 (setq org-custom-properties-overlays nil))
6434 (unless (not org-custom-properties)
6435 (save-excursion
6436 (save-restriction
6437 (widen)
6438 (goto-char (point-min))
6439 (while (re-search-forward org-property-re nil t)
6440 (mapc (lambda(p)
6441 (when (equal p (substring (match-string 1) 1 -1))
6442 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6443 (overlay-put o 'invisible t)
6444 (overlay-put o 'org-custom-property t)
6445 (push o org-custom-properties-overlays))))
6446 org-custom-properties)))))))
6448 (defun org-fontify-entities (limit)
6449 "Find an entity to fontify."
6450 (let (ee)
6451 (when org-pretty-entities
6452 (catch 'match
6453 (while (re-search-forward
6454 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6455 limit t)
6456 (if (and (not (org-at-comment-p))
6457 (setq ee (org-entity-get (match-string 1)))
6458 (= (length (nth 6 ee)) 1))
6459 (let*
6460 ((end (if (equal (match-string 2) "{}")
6461 (match-end 2)
6462 (match-end 1))))
6463 (add-text-properties
6464 (match-beginning 0) end
6465 (list 'font-lock-fontified t))
6466 (compose-region (match-beginning 0) end
6467 (nth 6 ee) nil)
6468 (backward-char 1)
6469 (throw 'match t))))
6470 nil))))
6472 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6473 "Fontify string S like in Org-mode."
6474 (with-temp-buffer
6475 (insert s)
6476 (let ((org-odd-levels-only odd-levels))
6477 (org-mode)
6478 (font-lock-ensure)
6479 (buffer-string))))
6481 (defvar org-m nil)
6482 (defvar org-l nil)
6483 (defvar org-f nil)
6484 (defun org-get-level-face (n)
6485 "Get the right face for match N in font-lock matching of headlines."
6486 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6487 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6488 (if org-cycle-level-faces
6489 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6490 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6491 (cond
6492 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6493 ((eq n 2) org-f)
6494 (t (if org-level-color-stars-only nil org-f))))
6497 (defun org-get-todo-face (kwd)
6498 "Get the right face for a TODO keyword KWD.
6499 If KWD is a number, get the corresponding match group."
6500 (if (numberp kwd) (setq kwd (match-string kwd)))
6501 (or (org-face-from-face-or-color
6502 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6503 (and (member kwd org-done-keywords) 'org-done)
6504 'org-todo))
6506 (defun org-face-from-face-or-color (context inherit face-or-color)
6507 "Create a face list that inherits INHERIT, but sets the foreground color.
6508 When FACE-OR-COLOR is not a string, just return it."
6509 (if (stringp face-or-color)
6510 (list :inherit inherit
6511 (cdr (assoc context org-faces-easy-properties))
6512 face-or-color)
6513 face-or-color))
6515 (defun org-font-lock-add-tag-faces (limit)
6516 "Add the special tag faces."
6517 (when (and org-tag-faces org-tags-special-faces-re)
6518 (while (re-search-forward org-tags-special-faces-re limit t)
6519 (add-text-properties (match-beginning 1) (match-end 1)
6520 (list 'face (org-get-tag-face 1)
6521 'font-lock-fontified t))
6522 (backward-char 1))))
6524 (defun org-font-lock-add-priority-faces (limit)
6525 "Add the special priority faces."
6526 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6527 (when (save-match-data (org-at-heading-p))
6528 (add-text-properties
6529 (match-beginning 0) (match-end 0)
6530 (list 'face (or (org-face-from-face-or-color
6531 'priority 'org-priority
6532 (cdr (assoc (char-after (match-beginning 1))
6533 org-priority-faces)))
6534 'org-priority)
6535 'font-lock-fontified t)))))
6537 (defun org-get-tag-face (kwd)
6538 "Get the right face for a TODO keyword KWD.
6539 If KWD is a number, get the corresponding match group."
6540 (if (numberp kwd) (setq kwd (match-string kwd)))
6541 (or (org-face-from-face-or-color
6542 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6543 'org-tag))
6545 (defun org-unfontify-region (beg end &optional maybe_loudly)
6546 "Remove fontification and activation overlays from links."
6547 (font-lock-default-unfontify-region beg end)
6548 (let* ((buffer-undo-list t)
6549 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6550 (inhibit-modification-hooks t)
6551 deactivate-mark buffer-file-name buffer-file-truename)
6552 (org-decompose-region beg end)
6553 (remove-text-properties beg end
6554 '(mouse-face t keymap t org-linked-text t
6555 invisible t intangible t
6556 org-emphasis t))
6557 (org-remove-font-lock-display-properties beg end)))
6559 (defconst org-script-display '(((raise -0.3) (height 0.7))
6560 ((raise 0.3) (height 0.7))
6561 ((raise -0.5))
6562 ((raise 0.5)))
6563 "Display properties for showing superscripts and subscripts.")
6565 (defun org-remove-font-lock-display-properties (beg end)
6566 "Remove specific display properties that have been added by font lock.
6567 The will remove the raise properties that are used to show superscripts
6568 and subscripts."
6569 (let (next prop)
6570 (while (< beg end)
6571 (setq next (next-single-property-change beg 'display nil end)
6572 prop (get-text-property beg 'display))
6573 (if (member prop org-script-display)
6574 (put-text-property beg next 'display nil))
6575 (setq beg next))))
6577 (defun org-raise-scripts (limit)
6578 "Add raise properties to sub/superscripts."
6579 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6580 (if (re-search-forward
6581 (if (eq org-use-sub-superscripts t)
6582 org-match-substring-regexp
6583 org-match-substring-with-braces-regexp)
6584 limit t)
6585 (let* ((pos (point)) table-p comment-p
6586 (mpos (match-beginning 3))
6587 (emph-p (get-text-property mpos 'org-emphasis))
6588 (link-p (get-text-property mpos 'mouse-face))
6589 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6590 (goto-char (point-at-bol))
6591 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6592 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6593 (goto-char pos)
6594 ;; Handle a_b^c
6595 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6596 (if (or comment-p emph-p link-p keyw-p)
6598 (put-text-property (match-beginning 3) (match-end 0)
6599 'display
6600 (if (equal (char-after (match-beginning 2)) ?^)
6601 (nth (if table-p 3 1) org-script-display)
6602 (nth (if table-p 2 0) org-script-display)))
6603 (add-text-properties (match-beginning 2) (match-end 2)
6604 (list 'invisible t
6605 'org-dwidth t 'org-dwidth-n 1))
6606 (if (and (eq (char-after (match-beginning 3)) ?{)
6607 (eq (char-before (match-end 3)) ?}))
6608 (progn
6609 (add-text-properties
6610 (match-beginning 3) (1+ (match-beginning 3))
6611 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6612 (add-text-properties
6613 (1- (match-end 3)) (match-end 3)
6614 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6615 t)))))
6617 ;;;; Visibility cycling, including org-goto and indirect buffer
6619 ;;; Cycling
6621 (defvar org-cycle-global-status nil)
6622 (make-variable-buffer-local 'org-cycle-global-status)
6623 (put 'org-cycle-global-status 'org-state t)
6624 (defvar org-cycle-subtree-status nil)
6625 (make-variable-buffer-local 'org-cycle-subtree-status)
6626 (put 'org-cycle-subtree-status 'org-state t)
6628 (defvar org-inlinetask-min-level)
6630 (defun org-unlogged-message (&rest args)
6631 "Display a message, but avoid logging it in the *Messages* buffer."
6632 (let ((message-log-max nil))
6633 (apply 'message args)))
6635 ;;;###autoload
6636 (defun org-cycle (&optional arg)
6637 "TAB-action and visibility cycling for Org-mode.
6639 This is the command invoked in Org-mode by the TAB key. Its main purpose
6640 is outline visibility cycling, but it also invokes other actions
6641 in special contexts.
6643 - When this function is called with a prefix argument, rotate the entire
6644 buffer through 3 states (global cycling)
6645 1. OVERVIEW: Show only top-level headlines.
6646 2. CONTENTS: Show all headlines of all levels, but no body text.
6647 3. SHOW ALL: Show everything.
6648 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6649 determined by the variable `org-startup-folded', and by any VISIBILITY
6650 properties in the buffer.
6651 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6652 including any drawers.
6654 - When inside a table, re-align the table and move to the next field.
6656 - When point is at the beginning of a headline, rotate the subtree started
6657 by this line through 3 different states (local cycling)
6658 1. FOLDED: Only the main headline is shown.
6659 2. CHILDREN: The main headline and the direct children are shown.
6660 From this state, you can move to one of the children
6661 and zoom in further.
6662 3. SUBTREE: Show the entire subtree, including body text.
6663 If there is no subtree, switch directly from CHILDREN to FOLDED.
6665 - When point is at the beginning of an empty headline and the variable
6666 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6667 of the headline by demoting and promoting it to likely levels. This
6668 speeds up creation document structure by pressing TAB once or several
6669 times right after creating a new headline.
6671 - When there is a numeric prefix, go up to a heading with level ARG, do
6672 a `show-subtree' and return to the previous cursor position. If ARG
6673 is negative, go up that many levels.
6675 - When point is not at the beginning of a headline, execute the global
6676 binding for TAB, which is re-indenting the line. See the option
6677 `org-cycle-emulate-tab' for details.
6679 - Special case: if point is at the beginning of the buffer and there is
6680 no headline in line 1, this function will act as if called with prefix arg
6681 (C-u TAB, same as S-TAB) also when called without prefix arg.
6682 But only if also the variable `org-cycle-global-at-bob' is t."
6683 (interactive "P")
6684 (org-load-modules-maybe)
6685 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6686 (and org-cycle-level-after-item/entry-creation
6687 (or (org-cycle-level)
6688 (org-cycle-item-indentation))))
6689 (let* ((limit-level
6690 (or org-cycle-max-level
6691 (and (boundp 'org-inlinetask-min-level)
6692 org-inlinetask-min-level
6693 (1- org-inlinetask-min-level))))
6694 (nstars (and limit-level
6695 (if org-odd-levels-only
6696 (and limit-level (1- (* limit-level 2)))
6697 limit-level)))
6698 (org-outline-regexp
6699 (if (not (derived-mode-p 'org-mode))
6700 outline-regexp
6701 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6702 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6703 (not (looking-at org-outline-regexp))))
6704 (org-cycle-hook
6705 (if bob-special
6706 (delq 'org-optimize-window-after-visibility-change
6707 (copy-sequence org-cycle-hook))
6708 org-cycle-hook))
6709 (pos (point)))
6711 (if (or bob-special (equal arg '(4)))
6712 ;; special case: use global cycling
6713 (setq arg t))
6715 (cond
6717 ((equal arg '(16))
6718 (setq last-command 'dummy)
6719 (org-set-startup-visibility)
6720 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6722 ((equal arg '(64))
6723 (show-all)
6724 (org-unlogged-message "Entire buffer visible, including drawers"))
6726 ;; Try cdlatex TAB completion
6727 ((org-try-cdlatex-tab))
6729 ;; Table: enter it or move to the next field.
6730 ((org-at-table-p 'any)
6731 (if (org-at-table.el-p)
6732 (message "Use C-c ' to edit table.el tables")
6733 (if arg (org-table-edit-field t)
6734 (org-table-justify-field-maybe)
6735 (call-interactively 'org-table-next-field))))
6737 ((run-hook-with-args-until-success
6738 'org-tab-after-check-for-table-hook))
6740 ;; Global cycling: delegate to `org-cycle-internal-global'.
6741 ((eq arg t) (org-cycle-internal-global))
6743 ;; Drawers: delegate to `org-flag-drawer'.
6744 ((save-excursion
6745 (beginning-of-line 1)
6746 (looking-at org-drawer-regexp))
6747 (org-flag-drawer ; toggle block visibility
6748 (not (get-char-property (match-end 0) 'invisible))))
6750 ;; Show-subtree, ARG levels up from here.
6751 ((integerp arg)
6752 (save-excursion
6753 (org-back-to-heading)
6754 (outline-up-heading (if (< arg 0) (- arg)
6755 (- (funcall outline-level) arg)))
6756 (org-show-subtree)))
6758 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6759 ((and (featurep 'org-inlinetask)
6760 (org-inlinetask-at-task-p)
6761 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6762 (org-inlinetask-toggle-visibility))
6764 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6765 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6766 (save-excursion (beginning-of-line 1)
6767 (looking-at org-outline-regexp)))
6768 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6769 (org-cycle-internal-local))
6771 ;; From there: TAB emulation and template completion.
6772 (buffer-read-only (org-back-to-heading))
6774 ((run-hook-with-args-until-success
6775 'org-tab-after-check-for-cycling-hook))
6777 ((org-try-structure-completion))
6779 ((run-hook-with-args-until-success
6780 'org-tab-before-tab-emulation-hook))
6782 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6783 (or (not (bolp))
6784 (not (looking-at org-outline-regexp))))
6785 (call-interactively (global-key-binding "\t")))
6787 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6788 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6789 (or (and (eq org-cycle-emulate-tab 'white)
6790 (= (match-end 0) (point-at-eol)))
6791 (and (eq org-cycle-emulate-tab 'whitestart)
6792 (>= (match-end 0) pos))))
6794 (eq org-cycle-emulate-tab t))
6795 (call-interactively (global-key-binding "\t")))
6797 (t (save-excursion
6798 (org-back-to-heading)
6799 (org-cycle)))))))
6801 (defun org-cycle-internal-global ()
6802 "Do the global cycling action."
6803 ;; Hack to avoid display of messages for .org attachments in Gnus
6804 (let ((ga (string-match "\\*fontification" (buffer-name))))
6805 (cond
6806 ((and (eq last-command this-command)
6807 (eq org-cycle-global-status 'overview))
6808 ;; We just created the overview - now do table of contents
6809 ;; This can be slow in very large buffers, so indicate action
6810 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6811 (unless ga (org-unlogged-message "CONTENTS..."))
6812 (org-content)
6813 (unless ga (org-unlogged-message "CONTENTS...done"))
6814 (setq org-cycle-global-status 'contents)
6815 (run-hook-with-args 'org-cycle-hook 'contents))
6817 ((and (eq last-command this-command)
6818 (eq org-cycle-global-status 'contents))
6819 ;; We just showed the table of contents - now show everything
6820 (run-hook-with-args 'org-pre-cycle-hook 'all)
6821 (show-all)
6822 (unless ga (org-unlogged-message "SHOW ALL"))
6823 (setq org-cycle-global-status 'all)
6824 (run-hook-with-args 'org-cycle-hook 'all))
6827 ;; Default action: go to overview
6828 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6829 (org-overview)
6830 (unless ga (org-unlogged-message "OVERVIEW"))
6831 (setq org-cycle-global-status 'overview)
6832 (run-hook-with-args 'org-cycle-hook 'overview)))))
6834 (defvar org-called-with-limited-levels nil
6835 "Non-nil when `org-with-limited-levels' is currently active.")
6837 (defun org-cycle-internal-local ()
6838 "Do the local cycling action."
6839 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6840 ;; First, determine end of headline (EOH), end of subtree or item
6841 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6842 (save-excursion
6843 (if (org-at-item-p)
6844 (progn
6845 (beginning-of-line)
6846 (setq struct (org-list-struct))
6847 (setq eoh (point-at-eol))
6848 (setq eos (org-list-get-item-end-before-blank (point) struct))
6849 (setq has-children (org-list-has-child-p (point) struct)))
6850 (org-back-to-heading)
6851 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6852 (setq eos (save-excursion (org-end-of-subtree t t)
6853 (when (bolp) (backward-char)) (point)))
6854 (setq has-children
6855 (or (save-excursion
6856 (let ((level (funcall outline-level)))
6857 (outline-next-heading)
6858 (and (org-at-heading-p t)
6859 (> (funcall outline-level) level))))
6860 (save-excursion
6861 (org-list-search-forward (org-item-beginning-re) eos t)))))
6862 ;; Determine end invisible part of buffer (EOL)
6863 (beginning-of-line 2)
6864 ;; XEmacs doesn't have `next-single-char-property-change'
6865 (if (featurep 'xemacs)
6866 (while (and (not (eobp)) ;; this is like `next-line'
6867 (get-char-property (1- (point)) 'invisible))
6868 (beginning-of-line 2))
6869 (while (and (not (eobp)) ;; this is like `next-line'
6870 (get-char-property (1- (point)) 'invisible))
6871 (goto-char (next-single-char-property-change (point) 'invisible))
6872 (and (eolp) (beginning-of-line 2))))
6873 (setq eol (point)))
6874 ;; Find out what to do next and set `this-command'
6875 (cond
6876 ((= eos eoh)
6877 ;; Nothing is hidden behind this heading
6878 (unless (org-before-first-heading-p)
6879 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6880 (org-unlogged-message "EMPTY ENTRY")
6881 (setq org-cycle-subtree-status nil)
6882 (save-excursion
6883 (goto-char eos)
6884 (outline-next-heading)
6885 (if (outline-invisible-p) (org-flag-heading nil))))
6886 ((and (or (>= eol eos)
6887 (not (string-match "\\S-" (buffer-substring eol eos))))
6888 (or has-children
6889 (not (setq children-skipped
6890 org-cycle-skip-children-state-if-no-children))))
6891 ;; Entire subtree is hidden in one line: children view
6892 (unless (org-before-first-heading-p)
6893 (run-hook-with-args 'org-pre-cycle-hook 'children))
6894 (if (org-at-item-p)
6895 (org-list-set-item-visibility (point-at-bol) struct 'children)
6896 (org-show-entry)
6897 (org-with-limited-levels (show-children))
6898 ;; FIXME: This slows down the func way too much.
6899 ;; How keep drawers hidden in subtree anyway?
6900 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6901 ;; (org-cycle-hide-drawers 'subtree))
6903 ;; Fold every list in subtree to top-level items.
6904 (when (eq org-cycle-include-plain-lists 'integrate)
6905 (save-excursion
6906 (org-back-to-heading)
6907 (while (org-list-search-forward (org-item-beginning-re) eos t)
6908 (beginning-of-line 1)
6909 (let* ((struct (org-list-struct))
6910 (prevs (org-list-prevs-alist struct))
6911 (end (org-list-get-bottom-point struct)))
6912 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6913 (org-list-get-all-items (point) struct prevs))
6914 (goto-char (if (< end eos) end eos)))))))
6915 (org-unlogged-message "CHILDREN")
6916 (save-excursion
6917 (goto-char eos)
6918 (outline-next-heading)
6919 (if (outline-invisible-p) (org-flag-heading nil)))
6920 (setq org-cycle-subtree-status 'children)
6921 (unless (org-before-first-heading-p)
6922 (run-hook-with-args 'org-cycle-hook 'children)))
6923 ((or children-skipped
6924 (and (eq last-command this-command)
6925 (eq org-cycle-subtree-status 'children)))
6926 ;; We just showed the children, or no children are there,
6927 ;; now show everything.
6928 (unless (org-before-first-heading-p)
6929 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6930 (outline-flag-region eoh eos nil)
6931 (org-unlogged-message
6932 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6933 (setq org-cycle-subtree-status 'subtree)
6934 (unless (org-before-first-heading-p)
6935 (run-hook-with-args 'org-cycle-hook 'subtree)))
6937 ;; Default action: hide the subtree.
6938 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6939 (outline-flag-region eoh eos t)
6940 (org-unlogged-message "FOLDED")
6941 (setq org-cycle-subtree-status 'folded)
6942 (unless (org-before-first-heading-p)
6943 (run-hook-with-args 'org-cycle-hook 'folded))))))
6945 ;;;###autoload
6946 (defun org-global-cycle (&optional arg)
6947 "Cycle the global visibility. For details see `org-cycle'.
6948 With \\[universal-argument] prefix arg, switch to startup visibility.
6949 With a numeric prefix, show all headlines up to that level."
6950 (interactive "P")
6951 (let ((org-cycle-include-plain-lists
6952 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6953 (cond
6954 ((integerp arg)
6955 (show-all)
6956 (hide-sublevels arg)
6957 (setq org-cycle-global-status 'contents))
6958 ((equal arg '(4))
6959 (org-set-startup-visibility)
6960 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6962 (org-cycle '(4))))))
6964 (defun org-set-startup-visibility ()
6965 "Set the visibility required by startup options and properties."
6966 (cond
6967 ((eq org-startup-folded t)
6968 (org-overview))
6969 ((eq org-startup-folded 'content)
6970 (org-content))
6971 ((or (eq org-startup-folded 'showeverything)
6972 (eq org-startup-folded nil))
6973 (show-all)))
6974 (unless (eq org-startup-folded 'showeverything)
6975 (if org-hide-block-startup (org-hide-block-all))
6976 (org-set-visibility-according-to-property 'no-cleanup)
6977 (org-cycle-hide-archived-subtrees 'all)
6978 (org-cycle-hide-drawers 'all)
6979 (org-cycle-show-empty-lines t)))
6981 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6982 "Switch subtree visibilities according to :VISIBILITY: property."
6983 (interactive)
6984 (let (org-show-entry-below state)
6985 (save-excursion
6986 (goto-char (point-min))
6987 (while (re-search-forward
6988 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6989 nil t)
6990 (setq state (match-string 1))
6991 (save-excursion
6992 (org-back-to-heading t)
6993 (hide-subtree)
6994 (org-reveal)
6995 (cond
6996 ((equal state '("fold" "folded"))
6997 (hide-subtree))
6998 ((equal state "children")
6999 (org-show-hidden-entry)
7000 (show-children))
7001 ((equal state "content")
7002 (save-excursion
7003 (save-restriction
7004 (org-narrow-to-subtree)
7005 (org-content))))
7006 ((member state '("all" "showall"))
7007 (show-subtree)))))
7008 (unless no-cleanup
7009 (org-cycle-hide-archived-subtrees 'all)
7010 (org-cycle-hide-drawers 'all)
7011 (org-cycle-show-empty-lines 'all)))))
7013 ;; This function uses outline-regexp instead of the more fundamental
7014 ;; org-outline-regexp so that org-cycle-global works outside of Org
7015 ;; buffers, where outline-regexp is needed.
7016 (defun org-overview ()
7017 "Switch to overview mode, showing only top-level headlines.
7018 This shows all headlines with a level equal or greater than the level
7019 of the first headline in the buffer. This is important, because if the
7020 first headline is not level one, then (hide-sublevels 1) gives confusing
7021 results."
7022 (interactive)
7023 (save-excursion
7024 (let ((level
7025 (save-excursion
7026 (goto-char (point-min))
7027 (if (re-search-forward (concat "^" outline-regexp) nil t)
7028 (progn
7029 (goto-char (match-beginning 0))
7030 (funcall outline-level))))))
7031 (and level (hide-sublevels level)))))
7033 (defun org-content (&optional arg)
7034 "Show all headlines in the buffer, like a table of contents.
7035 With numerical argument N, show content up to level N."
7036 (interactive "P")
7037 (org-overview)
7038 (save-excursion
7039 ;; Visit all headings and show their offspring
7040 (and (integerp arg) (org-overview))
7041 (goto-char (point-max))
7042 (catch 'exit
7043 (while (and (progn (condition-case nil
7044 (outline-previous-visible-heading 1)
7045 (error (goto-char (point-min))))
7047 (looking-at org-outline-regexp))
7048 (if (integerp arg)
7049 (show-children (1- arg))
7050 (show-branches))
7051 (if (bobp) (throw 'exit nil))))))
7053 (defun org-optimize-window-after-visibility-change (state)
7054 "Adjust the window after a change in outline visibility.
7055 This function is the default value of the hook `org-cycle-hook'."
7056 (when (get-buffer-window (current-buffer))
7057 (cond
7058 ((eq state 'content) nil)
7059 ((eq state 'all) nil)
7060 ((eq state 'folded) nil)
7061 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7062 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7064 (defun org-remove-empty-overlays-at (pos)
7065 "Remove outline overlays that do not contain non-white stuff."
7066 (mapc
7067 (lambda (o)
7068 (and (eq 'outline (overlay-get o 'invisible))
7069 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7070 (overlay-end o))))
7071 (delete-overlay o)))
7072 (overlays-at pos)))
7074 (defun org-clean-visibility-after-subtree-move ()
7075 "Fix visibility issues after moving a subtree."
7076 ;; First, find a reasonable region to look at:
7077 ;; Start two siblings above, end three below
7078 (let* ((beg (save-excursion
7079 (and (org-get-last-sibling)
7080 (org-get-last-sibling))
7081 (point)))
7082 (end (save-excursion
7083 (and (org-get-next-sibling)
7084 (org-get-next-sibling)
7085 (org-get-next-sibling))
7086 (if (org-at-heading-p)
7087 (point-at-eol)
7088 (point))))
7089 (level (looking-at "\\*+"))
7090 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7091 (save-excursion
7092 (save-restriction
7093 (narrow-to-region beg end)
7094 (when re
7095 ;; Properly fold already folded siblings
7096 (goto-char (point-min))
7097 (while (re-search-forward re nil t)
7098 (if (and (not (outline-invisible-p))
7099 (save-excursion
7100 (goto-char (point-at-eol)) (outline-invisible-p)))
7101 (hide-entry))))
7102 (org-cycle-show-empty-lines 'overview)
7103 (org-cycle-hide-drawers 'overview)))))
7105 (defun org-cycle-show-empty-lines (state)
7106 "Show empty lines above all visible headlines.
7107 The region to be covered depends on STATE when called through
7108 `org-cycle-hook'. Lisp program can use t for STATE to get the
7109 entire buffer covered. Note that an empty line is only shown if there
7110 are at least `org-cycle-separator-lines' empty lines before the headline."
7111 (when (not (= org-cycle-separator-lines 0))
7112 (save-excursion
7113 (let* ((n (abs org-cycle-separator-lines))
7114 (re (cond
7115 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7116 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7117 (t (let ((ns (number-to-string (- n 2))))
7118 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7119 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7120 beg end b e)
7121 (cond
7122 ((memq state '(overview contents t))
7123 (setq beg (point-min) end (point-max)))
7124 ((memq state '(children folded))
7125 (setq beg (point) end (progn (org-end-of-subtree t t)
7126 (beginning-of-line 2)
7127 (point)))))
7128 (when beg
7129 (goto-char beg)
7130 (while (re-search-forward re end t)
7131 (unless (get-char-property (match-end 1) 'invisible)
7132 (setq e (match-end 1))
7133 (if (< org-cycle-separator-lines 0)
7134 (setq b (save-excursion
7135 (goto-char (match-beginning 0))
7136 (org-back-over-empty-lines)
7137 (if (save-excursion
7138 (goto-char (max (point-min) (1- (point))))
7139 (org-at-heading-p))
7140 (1- (point))
7141 (point))))
7142 (setq b (match-beginning 1)))
7143 (outline-flag-region b e nil)))))))
7144 ;; Never hide empty lines at the end of the file.
7145 (save-excursion
7146 (goto-char (point-max))
7147 (outline-previous-heading)
7148 (outline-end-of-heading)
7149 (if (and (looking-at "[ \t\n]+")
7150 (= (match-end 0) (point-max)))
7151 (outline-flag-region (point) (match-end 0) nil))))
7153 (defun org-show-empty-lines-in-parent ()
7154 "Move to the parent and re-show empty lines before visible headlines."
7155 (save-excursion
7156 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7157 (org-cycle-show-empty-lines context))))
7159 (defun org-files-list ()
7160 "Return `org-agenda-files' list, plus all open org-mode files.
7161 This is useful for operations that need to scan all of a user's
7162 open and agenda-wise Org files."
7163 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7164 (dolist (buf (buffer-list))
7165 (with-current-buffer buf
7166 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7167 (let ((file (expand-file-name (buffer-file-name))))
7168 (unless (member file files)
7169 (push file files))))))
7170 files))
7172 (defsubst org-entry-beginning-position ()
7173 "Return the beginning position of the current entry."
7174 (save-excursion (outline-back-to-heading t) (point)))
7176 (defsubst org-entry-end-position ()
7177 "Return the end position of the current entry."
7178 (save-excursion (outline-next-heading) (point)))
7180 (defun org-cycle-hide-drawers (state &optional exceptions)
7181 "Re-hide all drawers after a visibility state change.
7182 When non-nil, optional argument EXCEPTIONS is a list of strings
7183 specifying which drawers should not be hidden."
7184 (when (and (derived-mode-p 'org-mode)
7185 (not (memq state '(overview folded contents))))
7186 (save-excursion
7187 (let* ((globalp (memq state '(contents all)))
7188 (beg (if globalp (point-min) (point)))
7189 (end (if globalp (point-max)
7190 (if (eq state 'children)
7191 (save-excursion (outline-next-heading) (point))
7192 (org-end-of-subtree t)))))
7193 (goto-char beg)
7194 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7195 (unless (member-ignore-case (match-string 1) exceptions)
7196 (let ((drawer (org-element-at-point)))
7197 (when (memq (org-element-type drawer) '(drawer property-drawer))
7198 (org-flag-drawer t drawer)
7199 ;; Make sure to skip drawer entirely or we might flag
7200 ;; it another time when matching its ending line with
7201 ;; `org-drawer-regexp'.
7202 (goto-char (org-element-property :end drawer))))))))))
7204 (defun org-cycle-hide-inline-tasks (state)
7205 "Re-hide inline tasks when switching to 'contents or 'children
7206 visibility state."
7207 (case state
7208 (contents
7209 (when (org-bound-and-true-p org-inlinetask-min-level)
7210 (hide-sublevels (1- org-inlinetask-min-level))))
7211 (children
7212 (when (featurep 'org-inlinetask)
7213 (save-excursion
7214 (while (and (outline-next-heading)
7215 (org-inlinetask-at-task-p))
7216 (org-inlinetask-toggle-visibility)
7217 (org-inlinetask-goto-end)))))))
7219 (defun org-flag-drawer (flag &optional element)
7220 "When FLAG is non-nil, hide the drawer we are at.
7221 Otherwise make it visible. When optional argument ELEMENT is
7222 a parsed drawer, as returned by `org-element-at-point', hide or
7223 show that drawer instead."
7224 (when (save-excursion
7225 (beginning-of-line)
7226 (org-looking-at-p org-drawer-regexp))
7227 (let ((drawer (or element (org-element-at-point))))
7228 (when (memq (org-element-type drawer) '(drawer property-drawer))
7229 (let ((post (org-element-property :post-affiliated drawer)))
7230 (save-excursion
7231 (outline-flag-region
7232 (progn (goto-char post) (line-end-position))
7233 (progn (goto-char (org-element-property :end drawer))
7234 (skip-chars-backward " \r\t\n")
7235 (line-end-position))
7236 flag))
7237 ;; When the drawer is hidden away, make sure point lies in
7238 ;; a visible part of the buffer.
7239 (when (and flag (> (line-beginning-position) post))
7240 (goto-char post)))))))
7242 (defun org-subtree-end-visible-p ()
7243 "Is the end of the current subtree visible?"
7244 (pos-visible-in-window-p
7245 (save-excursion (org-end-of-subtree t) (point))))
7247 (defun org-first-headline-recenter ()
7248 "Move cursor to the first headline and recenter the headline."
7249 (goto-char (point-min))
7250 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7251 (set-window-start (selected-window) (point-at-bol))))
7253 ;;; Saving and restoring visibility
7255 (defun org-outline-overlay-data (&optional use-markers)
7256 "Return a list of the locations of all outline overlays.
7257 These are overlays with the `invisible' property value `outline'.
7258 The return value is a list of cons cells, with start and stop
7259 positions for each overlay.
7260 If USE-MARKERS is set, return the positions as markers."
7261 (let (beg end)
7262 (save-excursion
7263 (save-restriction
7264 (widen)
7265 (delq nil
7266 (mapcar (lambda (o)
7267 (when (eq (overlay-get o 'invisible) 'outline)
7268 (setq beg (overlay-start o)
7269 end (overlay-end o))
7270 (and beg end (> end beg)
7271 (if use-markers
7272 (cons (copy-marker beg)
7273 (copy-marker end t))
7274 (cons beg end)))))
7275 (overlays-in (point-min) (point-max))))))))
7277 (defun org-set-outline-overlay-data (data)
7278 "Create visibility overlays for all positions in DATA.
7279 DATA should have been made by `org-outline-overlay-data'."
7280 (let (o)
7281 (save-excursion
7282 (save-restriction
7283 (widen)
7284 (show-all)
7285 (mapc (lambda (c)
7286 (outline-flag-region (car c) (cdr c) t))
7287 data)))))
7289 ;;; Folding of blocks
7291 (defvar org-hide-block-overlays nil
7292 "Overlays hiding blocks.")
7293 (make-variable-buffer-local 'org-hide-block-overlays)
7295 (defun org-block-map (function &optional start end)
7296 "Call FUNCTION at the head of all source blocks in the current buffer.
7297 Optional arguments START and END can be used to limit the range."
7298 (let ((start (or start (point-min)))
7299 (end (or end (point-max))))
7300 (save-excursion
7301 (goto-char start)
7302 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7303 (save-excursion
7304 (save-match-data
7305 (goto-char (match-beginning 0))
7306 (funcall function)))))))
7308 (defun org-hide-block-toggle-all ()
7309 "Toggle the visibility of all blocks in the current buffer."
7310 (org-block-map 'org-hide-block-toggle))
7312 (defun org-hide-block-all ()
7313 "Fold all blocks in the current buffer."
7314 (interactive)
7315 (org-show-block-all)
7316 (org-block-map 'org-hide-block-toggle-maybe))
7318 (defun org-show-block-all ()
7319 "Unfold all blocks in the current buffer."
7320 (interactive)
7321 (mapc 'delete-overlay org-hide-block-overlays)
7322 (setq org-hide-block-overlays nil))
7324 (defun org-hide-block-toggle-maybe ()
7325 "Toggle visibility of block at point.
7326 Unlike to `org-hide-block-toggle', this function does not throw
7327 an error. Return a non-nil value when toggling is successful."
7328 (interactive)
7329 (and (ignore-errors (org-hide-block-toggle)) t))
7331 (defun org-hide-block-toggle (&optional force)
7332 "Toggle the visibility of the current block.
7333 When optional argument FORCE is `off', make block visible. If it
7334 is non-nil, hide it unconditionally. Throw an error when not at
7335 a block. Return a non-nil value when toggling is successful."
7336 (interactive)
7337 (let ((element (org-element-at-point)))
7338 (unless (memq (org-element-type element)
7339 '(center-block comment-block dynamic-block example-block
7340 export-block quote-block special-block
7341 src-block verse-block))
7342 (user-error "Not at a block"))
7343 (let* ((start (save-excursion
7344 (goto-char (org-element-property :post-affiliated element))
7345 (line-end-position)))
7346 (end (save-excursion
7347 (goto-char (org-element-property :end element))
7348 (skip-chars-backward " \r\t\n")
7349 (line-end-position)))
7350 (overlays (overlays-at start)))
7351 (cond
7352 ;; Do nothing when not before or at the block opening line or
7353 ;; at the block closing line.
7354 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7355 ((and (not (eq force 'off))
7356 (not (memq t (mapcar
7357 (lambda (o)
7358 (eq (overlay-get o 'invisible) 'org-hide-block))
7359 overlays))))
7360 (let ((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 (memq ov org-hide-block-overlays)
7367 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7368 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7369 (delete-overlay ov))))
7370 (push ov org-hide-block-overlays)
7371 ;; When the block is hidden away, make sure point is left in
7372 ;; a visible part of the buffer.
7373 (when (> (line-beginning-position) start)
7374 (goto-char start)
7375 (beginning-of-line))
7376 ;; Signal successful toggling.
7378 ((or (not force) (eq force 'off))
7379 (dolist (ov overlays t)
7380 (when (memq ov org-hide-block-overlays)
7381 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7382 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7383 (delete-overlay ov))))))))
7385 ;; org-tab-after-check-for-cycling-hook
7386 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7387 ;; Remove overlays when changing major mode
7388 (add-hook 'org-mode-hook
7389 (lambda () (org-add-hook 'change-major-mode-hook
7390 'org-show-block-all 'append 'local)))
7392 ;;; Org-goto
7394 (defvar org-goto-window-configuration nil)
7395 (defvar org-goto-marker nil)
7396 (defvar org-goto-map)
7397 (defun org-goto-map ()
7398 "Set the keymap `org-goto'."
7399 (setq org-goto-map
7400 (let ((map (make-sparse-keymap)))
7401 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7402 mouse-drag-region universal-argument org-occur))
7403 cmd)
7404 (while (setq cmd (pop cmds))
7405 (substitute-key-definition cmd cmd map global-map)))
7406 (suppress-keymap map)
7407 (org-defkey map "\C-m" 'org-goto-ret)
7408 (org-defkey map [(return)] 'org-goto-ret)
7409 (org-defkey map [(left)] 'org-goto-left)
7410 (org-defkey map [(right)] 'org-goto-right)
7411 (org-defkey map [(control ?g)] 'org-goto-quit)
7412 (org-defkey map "\C-i" 'org-cycle)
7413 (org-defkey map [(tab)] 'org-cycle)
7414 (org-defkey map [(down)] 'outline-next-visible-heading)
7415 (org-defkey map [(up)] 'outline-previous-visible-heading)
7416 (if org-goto-auto-isearch
7417 (if (fboundp 'define-key-after)
7418 (define-key-after map [t] 'org-goto-local-auto-isearch)
7419 nil)
7420 (org-defkey map "q" 'org-goto-quit)
7421 (org-defkey map "n" 'outline-next-visible-heading)
7422 (org-defkey map "p" 'outline-previous-visible-heading)
7423 (org-defkey map "f" 'outline-forward-same-level)
7424 (org-defkey map "b" 'outline-backward-same-level)
7425 (org-defkey map "u" 'outline-up-heading))
7426 (org-defkey map "/" 'org-occur)
7427 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7428 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7429 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7430 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7431 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7432 map)))
7434 (defconst org-goto-help
7435 "Browse buffer copy, to find location or copy text.%s
7436 RET=jump to location C-g=quit and return to previous location
7437 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7439 (defvar org-goto-start-pos) ; dynamically scoped parameter
7441 (defun org-goto (&optional alternative-interface)
7442 "Look up a different location in the current file, keeping current visibility.
7444 When you want look-up or go to a different location in a
7445 document, the fastest way is often to fold the entire buffer and
7446 then dive into the tree. This method has the disadvantage, that
7447 the previous location will be folded, which may not be what you
7448 want.
7450 This command works around this by showing a copy of the current
7451 buffer in an indirect buffer, in overview mode. You can dive
7452 into the tree in that copy, use org-occur and incremental search
7453 to find a location. When pressing RET or `Q', the command
7454 returns to the original buffer in which the visibility is still
7455 unchanged. After RET it will also jump to the location selected
7456 in the indirect buffer and expose the headline hierarchy above.
7458 With a prefix argument, use the alternative interface: e.g. if
7459 `org-goto-interface' is 'outline use 'outline-path-completion."
7460 (interactive "P")
7461 (org-goto-map)
7462 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7463 (org-refile-use-outline-path t)
7464 (org-refile-target-verify-function nil)
7465 (interface
7466 (if (not alternative-interface)
7467 org-goto-interface
7468 (if (eq org-goto-interface 'outline)
7469 'outline-path-completion
7470 'outline)))
7471 (org-goto-start-pos (point))
7472 (selected-point
7473 (if (eq interface 'outline)
7474 (car (org-get-location (current-buffer) org-goto-help))
7475 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7476 (org-refile-check-position pa)
7477 (nth 3 pa)))))
7478 (if selected-point
7479 (progn
7480 (org-mark-ring-push org-goto-start-pos)
7481 (goto-char selected-point)
7482 (if (or (outline-invisible-p) (org-invisible-p2))
7483 (org-show-context 'org-goto)))
7484 (message "Quit"))))
7486 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7487 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7488 (defvar org-goto-local-auto-isearch-map) ; defined below
7490 (defun org-get-location (buf help)
7491 "Let the user select a location in the Org-mode buffer BUF.
7492 This function uses a recursive edit. It returns the selected position
7493 or nil."
7494 (org-no-popups
7495 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7496 (isearch-hide-immediately nil)
7497 (isearch-search-fun-function
7498 (lambda () 'org-goto-local-search-headings))
7499 (org-goto-selected-point org-goto-exit-command))
7500 (save-excursion
7501 (save-window-excursion
7502 (delete-other-windows)
7503 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7504 (org-pop-to-buffer-same-window
7505 (condition-case nil
7506 (make-indirect-buffer (current-buffer) "*org-goto*")
7507 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7508 (with-output-to-temp-buffer "*Org Help*"
7509 (princ (format help (if org-goto-auto-isearch
7510 " Just type for auto-isearch."
7511 " n/p/f/b/u to navigate, q to quit."))))
7512 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7513 (setq buffer-read-only nil)
7514 (let ((org-startup-truncated t)
7515 (org-startup-folded nil)
7516 (org-startup-align-all-tables nil))
7517 (org-mode)
7518 (org-overview))
7519 (setq buffer-read-only t)
7520 (if (and (boundp 'org-goto-start-pos)
7521 (integer-or-marker-p org-goto-start-pos))
7522 (let ((org-show-hierarchy-above t)
7523 (org-show-siblings t)
7524 (org-show-following-heading t))
7525 (goto-char org-goto-start-pos)
7526 (and (outline-invisible-p) (org-show-context)))
7527 (goto-char (point-min)))
7528 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7529 (message "Select location and press RET")
7530 (use-local-map org-goto-map)
7531 (recursive-edit)))
7532 (kill-buffer "*org-goto*")
7533 (cons org-goto-selected-point org-goto-exit-command))))
7535 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7536 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7537 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7538 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7540 (defun org-goto-local-search-headings (string bound noerror)
7541 "Search and make sure that any matches are in headlines."
7542 (catch 'return
7543 (while (if isearch-forward
7544 (search-forward string bound noerror)
7545 (search-backward string bound noerror))
7546 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7547 (and (member :headline context)
7548 (not (member :tags context))))
7549 (throw 'return (point))))))
7551 (defun org-goto-local-auto-isearch ()
7552 "Start isearch."
7553 (interactive)
7554 (goto-char (point-min))
7555 (let ((keys (this-command-keys)))
7556 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7557 (isearch-mode t)
7558 (isearch-process-search-char (string-to-char keys)))))
7560 (defun org-goto-ret (&optional arg)
7561 "Finish `org-goto' by going to the new location."
7562 (interactive "P")
7563 (setq org-goto-selected-point (point)
7564 org-goto-exit-command 'return)
7565 (throw 'exit nil))
7567 (defun org-goto-left ()
7568 "Finish `org-goto' by going to the new location."
7569 (interactive)
7570 (if (org-at-heading-p)
7571 (progn
7572 (beginning-of-line 1)
7573 (setq org-goto-selected-point (point)
7574 org-goto-exit-command 'left)
7575 (throw 'exit nil))
7576 (user-error "Not on a heading")))
7578 (defun org-goto-right ()
7579 "Finish `org-goto' by going to the new location."
7580 (interactive)
7581 (if (org-at-heading-p)
7582 (progn
7583 (setq org-goto-selected-point (point)
7584 org-goto-exit-command 'right)
7585 (throw 'exit nil))
7586 (user-error "Not on a heading")))
7588 (defun org-goto-quit ()
7589 "Finish `org-goto' without cursor motion."
7590 (interactive)
7591 (setq org-goto-selected-point nil)
7592 (setq org-goto-exit-command 'quit)
7593 (throw 'exit nil))
7595 ;;; Indirect buffer display of subtrees
7597 (defvar org-indirect-dedicated-frame nil
7598 "This is the frame being used for indirect tree display.")
7599 (defvar org-last-indirect-buffer nil)
7601 (defun org-tree-to-indirect-buffer (&optional arg)
7602 "Create indirect buffer and narrow it to current subtree.
7603 With a numerical prefix ARG, go up to this level and then take that tree.
7604 If ARG is negative, go up that many levels.
7606 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7607 indirect buffer previously made with this command, to avoid proliferation of
7608 indirect buffers. However, when you call the command with a \
7609 \\[universal-argument] prefix, or
7610 when `org-indirect-buffer-display' is `new-frame', the last buffer
7611 is kept so that you can work with several indirect buffers at the same time.
7612 If `org-indirect-buffer-display' is `dedicated-frame', the \
7613 \\[universal-argument] prefix also
7614 requests that a new frame be made for the new buffer, so that the dedicated
7615 frame is not changed."
7616 (interactive "P")
7617 (let ((cbuf (current-buffer))
7618 (cwin (selected-window))
7619 (pos (point))
7620 beg end level heading ibuf)
7621 (save-excursion
7622 (org-back-to-heading t)
7623 (when (numberp arg)
7624 (setq level (org-outline-level))
7625 (if (< arg 0) (setq arg (+ level arg)))
7626 (while (> (setq level (org-outline-level)) arg)
7627 (org-up-heading-safe)))
7628 (setq beg (point)
7629 heading (org-get-heading))
7630 (org-end-of-subtree t t)
7631 (if (org-at-heading-p) (backward-char 1))
7632 (setq end (point)))
7633 (if (and (buffer-live-p org-last-indirect-buffer)
7634 (not (eq org-indirect-buffer-display 'new-frame))
7635 (not arg))
7636 (kill-buffer org-last-indirect-buffer))
7637 (setq ibuf (org-get-indirect-buffer cbuf heading)
7638 org-last-indirect-buffer ibuf)
7639 (cond
7640 ((or (eq org-indirect-buffer-display 'new-frame)
7641 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7642 (select-frame (make-frame))
7643 (delete-other-windows)
7644 (org-pop-to-buffer-same-window ibuf)
7645 (org-set-frame-title heading))
7646 ((eq org-indirect-buffer-display 'dedicated-frame)
7647 (raise-frame
7648 (select-frame (or (and org-indirect-dedicated-frame
7649 (frame-live-p org-indirect-dedicated-frame)
7650 org-indirect-dedicated-frame)
7651 (setq org-indirect-dedicated-frame (make-frame)))))
7652 (delete-other-windows)
7653 (org-pop-to-buffer-same-window ibuf)
7654 (org-set-frame-title (concat "Indirect: " heading)))
7655 ((eq org-indirect-buffer-display 'current-window)
7656 (org-pop-to-buffer-same-window ibuf))
7657 ((eq org-indirect-buffer-display 'other-window)
7658 (pop-to-buffer ibuf))
7659 (t (error "Invalid value")))
7660 (if (featurep 'xemacs)
7661 (save-excursion (org-mode) (turn-on-font-lock)))
7662 (narrow-to-region beg end)
7663 (show-all)
7664 (goto-char pos)
7665 (run-hook-with-args 'org-cycle-hook 'all)
7666 (and (window-live-p cwin) (select-window cwin))))
7668 (defun org-get-indirect-buffer (&optional buffer heading)
7669 (setq buffer (or buffer (current-buffer)))
7670 (let ((n 1) (base (buffer-name buffer)) bname)
7671 (while (buffer-live-p
7672 (get-buffer
7673 (setq bname
7674 (concat base "-"
7675 (if heading (concat heading "-" (number-to-string n))
7676 (number-to-string n))))))
7677 (setq n (1+ n)))
7678 (condition-case nil
7679 (make-indirect-buffer buffer bname 'clone)
7680 (error (make-indirect-buffer buffer bname)))))
7682 (defun org-set-frame-title (title)
7683 "Set the title of the current frame to the string TITLE."
7684 ;; FIXME: how to name a single frame in XEmacs???
7685 (unless (featurep 'xemacs)
7686 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7688 ;;;; Structure editing
7690 ;;; Inserting headlines
7692 (defun org-previous-line-empty-p (&optional next)
7693 "Is the previous line a blank line?
7694 When NEXT is non-nil, check the next line instead."
7695 (save-excursion
7696 (and (not (bobp))
7697 (or (beginning-of-line (if next 2 0)) t)
7698 (save-match-data
7699 (looking-at "[ \t]*$")))))
7701 (defun org-insert-heading (&optional arg invisible-ok)
7702 "Insert a new heading or an item with the same depth at point.
7704 If point is at the beginning of a heading or a list item, insert
7705 a new heading or a new item above the current one. If point is
7706 at the beginning of a normal line, turn the line into a heading.
7708 If point is in the middle of a headline or a list item, split the
7709 headline or the item and create a new headline/item with the text
7710 in the current line after point \(see `org-M-RET-may-split-line'
7711 on how to modify this behavior).
7713 With one universal prefix argument, set the user option
7714 `org-insert-heading-respect-content' to t for the duration of
7715 the command. This modifies the behavior described above in this
7716 ways: on list items and at the beginning of normal lines, force
7717 the insertion of a heading after the current subtree.
7719 With two universal prefix arguments, insert the heading at the
7720 end of the grandparent subtree. For example, if point is within
7721 a 2nd-level heading, then it will insert a 2nd-level heading at
7722 the end of the 1st-level parent heading.
7724 If point is at the beginning of a headline, insert a sibling
7725 before the current headline. If point is not at the beginning,
7726 split the line and create a new headline with the text in the
7727 current line after point \(see `org-M-RET-may-split-line' on how
7728 to modify this behavior).
7730 If point is at the beginning of a normal line, turn this line
7731 into a heading.
7733 When INVISIBLE-OK is set, stop at invisible headlines when going
7734 back. This is important for non-interactive uses of the
7735 command."
7736 (interactive "P")
7737 (if (org-called-interactively-p 'any) (org-reveal))
7738 (let ((itemp (org-in-item-p))
7739 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7740 (respect-content (or org-insert-heading-respect-content
7741 (equal arg '(4))))
7742 (initial-content "")
7743 (adjust-empty-lines t))
7745 (cond
7747 ((or (= (buffer-size) 0)
7748 (and (not (save-excursion
7749 (and (ignore-errors (org-back-to-heading invisible-ok))
7750 (org-at-heading-p))))
7751 (or arg (not itemp))))
7752 ;; At beginning of buffer or so high up that only a heading
7753 ;; makes sense.
7754 (cond ((and (bolp) (not respect-content)) (insert "* "))
7755 ((not respect-content)
7756 (unless may-split (end-of-line))
7757 (insert "\n* "))
7758 ((re-search-forward org-outline-regexp-bol nil t)
7759 (beginning-of-line)
7760 (insert "* \n")
7761 (backward-char))
7762 (t (goto-char (point-max))
7763 (insert "\n* ")))
7764 (run-hooks 'org-insert-heading-hook))
7766 ((and itemp (not (member arg '((4) (16)))))
7767 ;; Insert an item
7768 (org-insert-item))
7771 ;; Maybe move at the end of the subtree
7772 (when (equal arg '(16))
7773 (org-up-heading-safe)
7774 (org-end-of-subtree t))
7775 ;; Insert a heading
7776 (save-restriction
7777 (widen)
7778 (let* ((level nil)
7779 (on-heading (org-at-heading-p))
7780 (empty-line-p (if on-heading
7781 (org-previous-line-empty-p)
7782 ;; We will decide later
7783 nil))
7784 ;; Get a level string to fall back on
7785 (fix-level
7786 (if (org-before-first-heading-p) "*"
7787 (save-excursion
7788 (org-back-to-heading t)
7789 (if (org-previous-line-empty-p) (setq empty-line-p t))
7790 (looking-at org-outline-regexp)
7791 (make-string (1- (length (match-string 0))) ?*))))
7792 (stars
7793 (save-excursion
7794 (condition-case nil
7795 (progn
7796 (org-back-to-heading invisible-ok)
7797 (when (and (not on-heading)
7798 (featurep 'org-inlinetask)
7799 (integerp org-inlinetask-min-level)
7800 (>= (length (match-string 0))
7801 org-inlinetask-min-level))
7802 ;; Find a heading level before the inline task
7803 (while (and (setq level (org-up-heading-safe))
7804 (>= level org-inlinetask-min-level)))
7805 (if (org-at-heading-p)
7806 (org-back-to-heading invisible-ok)
7807 (error "This should not happen")))
7808 (unless (and (save-excursion
7809 (save-match-data
7810 (org-backward-heading-same-level
7811 1 invisible-ok))
7812 (= (point) (match-beginning 0)))
7813 (not (org-previous-line-empty-p t)))
7814 (setq empty-line-p (or empty-line-p
7815 (org-previous-line-empty-p))))
7816 (match-string 0))
7817 (error (or fix-level "* ")))))
7818 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7819 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7820 pos hide-previous previous-pos)
7822 ;; If we insert after content, move there and clean up whitespace
7823 (when (and respect-content
7824 (not (org-looking-at-p org-outline-regexp-bol)))
7825 (if (not (org-before-first-heading-p))
7826 (org-end-of-subtree nil t)
7827 (re-search-forward org-outline-regexp-bol)
7828 (beginning-of-line 0))
7829 (skip-chars-backward " \r\n")
7830 (and (not (looking-back "^\\*+"))
7831 (looking-at "[ \t]+") (replace-match ""))
7832 (unless (eobp) (forward-char 1))
7833 (when (looking-at "^\\*")
7834 (unless (bobp) (backward-char 1))
7835 (insert "\n")))
7837 ;; If we are splitting, grab the text that should be moved to the new headline
7838 (when may-split
7839 (if (org-on-heading-p)
7840 ;; This is a heading, we split intelligently (keeping tags)
7841 (let ((pos (point)))
7842 (goto-char (point-at-bol))
7843 (unless (looking-at org-complex-heading-regexp)
7844 (error "This should not happen"))
7845 (when (and (match-beginning 4)
7846 (> pos (match-beginning 4))
7847 (< pos (match-end 4)))
7848 (setq initial-content (buffer-substring pos (match-end 4)))
7849 (goto-char pos)
7850 (delete-region (point) (match-end 4))
7851 (if (looking-at "[ \t]*$")
7852 (replace-match "")
7853 (insert (make-string (length initial-content) ?\ )))
7854 (setq initial-content (org-trim initial-content)))
7855 (goto-char pos))
7856 ;; a normal line
7857 (setq initial-content
7858 (org-trim (buffer-substring (point) (point-at-eol))))
7859 (delete-region (point) (point-at-eol))))
7861 ;; If we are at the beginning of the line, insert before it. Else after
7862 (cond
7863 ((and (bolp) (looking-at "[ \t]*$")))
7864 ((and (bolp) (not (looking-at "[ \t]*$")))
7865 (open-line 1))
7867 (goto-char (point-at-eol))
7868 (insert "\n")))
7870 ;; Insert the new heading
7871 (insert stars)
7872 (just-one-space)
7873 (insert initial-content)
7874 (when adjust-empty-lines
7875 (if (or (not blank)
7876 (and blank (not (org-previous-line-empty-p))))
7877 (org-N-empty-lines-before-current (if blank 1 0))))
7878 (run-hooks 'org-insert-heading-hook)))))))
7880 (defun org-N-empty-lines-before-current (N)
7881 "Make the number of empty lines before current exactly N.
7882 So this will delete or add empty lines."
7883 (save-excursion
7884 (goto-char (point-at-bol))
7885 (if (looking-back "\\s-+" nil 'greedy)
7886 (replace-match ""))
7887 (or (bobp) (insert "\n"))
7888 (while (> N 0)
7889 (insert "\n")
7890 (setq N (1- N)))))
7892 (defun org-get-heading (&optional no-tags no-todo)
7893 "Return the heading of the current entry, without the stars.
7894 When NO-TAGS is non-nil, don't include tags.
7895 When NO-TODO is non-nil, don't include TODO keywords."
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (cond
7899 ((and no-tags no-todo)
7900 (looking-at org-complex-heading-regexp)
7901 (match-string 4))
7902 (no-tags
7903 (looking-at (concat org-outline-regexp
7904 "\\(.*?\\)"
7905 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7906 (match-string 1))
7907 (no-todo
7908 (looking-at org-todo-line-regexp)
7909 (match-string 3))
7910 (t (looking-at org-heading-regexp)
7911 (match-string 2)))))
7913 (defvar orgstruct-mode) ; defined below
7915 (defun org-heading-components ()
7916 "Return the components of the current heading.
7917 This is a list with the following elements:
7918 - the level as an integer
7919 - the reduced level, different if `org-odd-levels-only' is set.
7920 - the TODO keyword, or nil
7921 - the priority character, like ?A, or nil if no priority is given
7922 - the headline text itself, or the tags string if no headline text
7923 - the tags string, or nil."
7924 (save-excursion
7925 (org-back-to-heading t)
7926 (if (let (case-fold-search)
7927 (looking-at
7928 (if orgstruct-mode
7929 org-heading-regexp
7930 org-complex-heading-regexp)))
7931 (if orgstruct-mode
7932 (list (length (match-string 1))
7933 (org-reduced-level (length (match-string 1)))
7936 (match-string 2)
7937 nil)
7938 (list (length (match-string 1))
7939 (org-reduced-level (length (match-string 1)))
7940 (org-match-string-no-properties 2)
7941 (and (match-end 3) (aref (match-string 3) 2))
7942 (org-match-string-no-properties 4)
7943 (org-match-string-no-properties 5))))))
7945 (defun org-get-entry ()
7946 "Get the entry text, after heading, entire subtree."
7947 (save-excursion
7948 (org-back-to-heading t)
7949 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7951 (defun org-insert-heading-after-current ()
7952 "Insert a new heading with same level as current, after current subtree."
7953 (interactive)
7954 (org-back-to-heading)
7955 (org-insert-heading)
7956 (org-move-subtree-down)
7957 (end-of-line 1))
7959 (defun org-insert-heading-respect-content (&optional invisible-ok)
7960 "Insert heading with `org-insert-heading-respect-content' set to t."
7961 (interactive)
7962 (org-insert-heading '(4) invisible-ok))
7964 (defun org-insert-todo-heading-respect-content (&optional force-state)
7965 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7966 (interactive)
7967 (org-insert-todo-heading force-state '(4)))
7969 (defun org-insert-todo-heading (arg &optional force-heading)
7970 "Insert a new heading with the same level and TODO state as current heading.
7971 If the heading has no TODO state, or if the state is DONE, use the first
7972 state (TODO by default). Also with one prefix arg, force first state. With
7973 two prefix args, force inserting at the end of the parent subtree."
7974 (interactive "P")
7975 (when (or force-heading (not (org-insert-item 'checkbox)))
7976 (org-insert-heading (or (and (equal arg '(16)) '(16))
7977 force-heading))
7978 (save-excursion
7979 (org-back-to-heading)
7980 (outline-previous-heading)
7981 (looking-at org-todo-line-regexp))
7982 (let*
7983 ((new-mark-x
7984 (if (or (equal arg '(4))
7985 (not (match-beginning 2))
7986 (member (match-string 2) org-done-keywords))
7987 (car org-todo-keywords-1)
7988 (match-string 2)))
7989 (new-mark
7991 (run-hook-with-args-until-success
7992 'org-todo-get-default-hook new-mark-x nil)
7993 new-mark-x)))
7994 (beginning-of-line 1)
7995 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7996 (if org-treat-insert-todo-heading-as-state-change
7997 (org-todo new-mark)
7998 (insert new-mark " "))))
7999 (when org-provide-todo-statistics
8000 (org-update-parent-todo-statistics))))
8002 (defun org-insert-subheading (arg)
8003 "Insert a new subheading and demote it.
8004 Works for outline headings and for plain lists alike."
8005 (interactive "P")
8006 (org-insert-heading arg)
8007 (cond
8008 ((org-at-heading-p) (org-do-demote))
8009 ((org-at-item-p) (org-indent-item))))
8011 (defun org-insert-todo-subheading (arg)
8012 "Insert a new subheading with TODO keyword or checkbox and demote it.
8013 Works for outline headings and for plain lists alike."
8014 (interactive "P")
8015 (org-insert-todo-heading arg)
8016 (cond
8017 ((org-at-heading-p) (org-do-demote))
8018 ((org-at-item-p) (org-indent-item))))
8020 ;;; Promotion and Demotion
8022 (defvar org-after-demote-entry-hook nil
8023 "Hook run after an entry has been demoted.
8024 The cursor will be at the beginning of the entry.
8025 When a subtree is being demoted, the hook will be called for each node.")
8027 (defvar org-after-promote-entry-hook nil
8028 "Hook run after an entry has been promoted.
8029 The cursor will be at the beginning of the entry.
8030 When a subtree is being promoted, the hook will be called for each node.")
8032 (defun org-promote-subtree ()
8033 "Promote the entire subtree.
8034 See also `org-promote'."
8035 (interactive)
8036 (save-excursion
8037 (org-with-limited-levels (org-map-tree 'org-promote)))
8038 (org-fix-position-after-promote))
8040 (defun org-demote-subtree ()
8041 "Demote the entire subtree. See `org-demote'.
8042 See also `org-promote'."
8043 (interactive)
8044 (save-excursion
8045 (org-with-limited-levels (org-map-tree 'org-demote)))
8046 (org-fix-position-after-promote))
8049 (defun org-do-promote ()
8050 "Promote the current heading higher up the tree.
8051 If the region is active in `transient-mark-mode', promote all headings
8052 in the region."
8053 (interactive)
8054 (save-excursion
8055 (if (org-region-active-p)
8056 (org-map-region 'org-promote (region-beginning) (region-end))
8057 (org-promote)))
8058 (org-fix-position-after-promote))
8060 (defun org-do-demote ()
8061 "Demote the current heading lower down the tree.
8062 If the region is active in `transient-mark-mode', demote all headings
8063 in the region."
8064 (interactive)
8065 (save-excursion
8066 (if (org-region-active-p)
8067 (org-map-region 'org-demote (region-beginning) (region-end))
8068 (org-demote)))
8069 (org-fix-position-after-promote))
8071 (defun org-fix-position-after-promote ()
8072 "Make sure that after pro/demotion cursor position is right."
8073 (let ((pos (point)))
8074 (when (save-excursion
8075 (beginning-of-line 1)
8076 (looking-at org-todo-line-regexp)
8077 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8078 (cond ((eobp) (insert " "))
8079 ((eolp) (insert " "))
8080 ((equal (char-after) ?\ ) (forward-char 1))))))
8082 (defun org-current-level ()
8083 "Return the level of the current entry, or nil if before the first headline.
8084 The level is the number of stars at the beginning of the headline."
8085 (save-excursion
8086 (org-with-limited-levels
8087 (if (ignore-errors (org-back-to-heading t))
8088 (funcall outline-level)))))
8090 (defun org-get-previous-line-level ()
8091 "Return the outline depth of the last headline before the current line.
8092 Returns 0 for the first headline in the buffer, and nil if before the
8093 first headline."
8094 (and (org-current-level)
8095 (or (and (/= (line-beginning-position) (point-min))
8096 (save-excursion (beginning-of-line 0) (org-current-level)))
8097 0)))
8099 (defun org-reduced-level (l)
8100 "Compute the effective level of a heading.
8101 This takes into account the setting of `org-odd-levels-only'."
8102 (cond
8103 ((zerop l) 0)
8104 (org-odd-levels-only (1+ (floor (/ l 2))))
8105 (t l)))
8107 (defun org-level-increment ()
8108 "Return the number of stars that will be added or removed at a
8109 time to headlines when structure editing, based on the value of
8110 `org-odd-levels-only'."
8111 (if org-odd-levels-only 2 1))
8113 (defun org-get-valid-level (level &optional change)
8114 "Rectify a level change under the influence of `org-odd-levels-only'
8115 LEVEL is a current level, CHANGE is by how much the level should be
8116 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8117 even level numbers will become the next higher odd number."
8118 (if org-odd-levels-only
8119 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8120 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8121 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8122 (max 1 (+ level (or change 0)))))
8124 (if (boundp 'define-obsolete-function-alias)
8125 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8126 (define-obsolete-function-alias 'org-get-legal-level
8127 'org-get-valid-level)
8128 (define-obsolete-function-alias 'org-get-legal-level
8129 'org-get-valid-level "23.1")))
8131 (defun org-promote ()
8132 "Promote the current heading higher up the tree.
8133 If the region is active in `transient-mark-mode', promote all headings
8134 in the region."
8135 (org-back-to-heading t)
8136 (let* ((level (save-match-data (funcall outline-level)))
8137 (after-change-functions (remove 'flyspell-after-change-function
8138 after-change-functions))
8139 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8140 (diff (abs (- level (length up-head) -1))))
8141 (cond ((and (= level 1) org-called-with-limited-levels
8142 org-allow-promoting-top-level-subtree)
8143 (replace-match "# " nil t))
8144 ((= level 1)
8145 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8146 (t (replace-match up-head nil t)))
8147 ;; Fixup tag positioning
8148 (unless (= level 1)
8149 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8150 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8151 (run-hooks 'org-after-promote-entry-hook)))
8153 (defun org-demote ()
8154 "Demote the current heading lower down the tree.
8155 If the region is active in `transient-mark-mode', demote all headings
8156 in the region."
8157 (org-back-to-heading t)
8158 (let* ((level (save-match-data (funcall outline-level)))
8159 (after-change-functions (remove 'flyspell-after-change-function
8160 after-change-functions))
8161 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8162 (diff (abs (- level (length down-head) -1))))
8163 (replace-match down-head nil t)
8164 ;; Fixup tag positioning
8165 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8166 (if org-adapt-indentation (org-fixup-indentation diff))
8167 (run-hooks 'org-after-demote-entry-hook)))
8169 (defun org-cycle-level ()
8170 "Cycle the level of an empty headline through possible states.
8171 This goes first to child, then to parent, level, then up the hierarchy.
8172 After top level, it switches back to sibling level."
8173 (interactive)
8174 (let ((org-adapt-indentation nil))
8175 (when (org-point-at-end-of-empty-headline)
8176 (setq this-command 'org-cycle-level) ; Only needed for caching
8177 (let ((cur-level (org-current-level))
8178 (prev-level (org-get-previous-line-level)))
8179 (cond
8180 ;; If first headline in file, promote to top-level.
8181 ((= prev-level 0)
8182 (loop repeat (/ (- cur-level 1) (org-level-increment))
8183 do (org-do-promote)))
8184 ;; If same level as prev, demote one.
8185 ((= prev-level cur-level)
8186 (org-do-demote))
8187 ;; If parent is top-level, promote to top level if not already.
8188 ((= prev-level 1)
8189 (loop repeat (/ (- cur-level 1) (org-level-increment))
8190 do (org-do-promote)))
8191 ;; If top-level, return to prev-level.
8192 ((= cur-level 1)
8193 (loop repeat (/ (- prev-level 1) (org-level-increment))
8194 do (org-do-demote)))
8195 ;; If less than prev-level, promote one.
8196 ((< cur-level prev-level)
8197 (org-do-promote))
8198 ;; If deeper than prev-level, promote until higher than
8199 ;; prev-level.
8200 ((> cur-level prev-level)
8201 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8202 do (org-do-promote))))
8203 t))))
8205 (defun org-map-tree (fun)
8206 "Call FUN for every heading underneath the current one."
8207 (org-back-to-heading)
8208 (let ((level (funcall outline-level)))
8209 (save-excursion
8210 (funcall fun)
8211 (while (and (progn
8212 (outline-next-heading)
8213 (> (funcall outline-level) level))
8214 (not (eobp)))
8215 (funcall fun)))))
8217 (defun org-map-region (fun beg end)
8218 "Call FUN for every heading between BEG and END."
8219 (let ((org-ignore-region t))
8220 (save-excursion
8221 (setq end (copy-marker end))
8222 (goto-char beg)
8223 (if (and (re-search-forward org-outline-regexp-bol nil t)
8224 (< (point) end))
8225 (funcall fun))
8226 (while (and (progn
8227 (outline-next-heading)
8228 (< (point) end))
8229 (not (eobp)))
8230 (funcall fun)))))
8232 (defvar org-property-end-re) ; silence byte-compiler
8233 (defun org-fixup-indentation (diff)
8234 "Change the indentation in the current entry by DIFF.
8235 However, if any line in the current entry has no indentation, or if it
8236 would end up with no indentation after the change, nothing at all is done."
8237 (save-excursion
8238 (let ((end (save-excursion (outline-next-heading)
8239 (point-marker)))
8240 (prohibit (if (> diff 0)
8241 "^\\S-"
8242 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8243 col)
8244 (unless (save-excursion (end-of-line 1)
8245 (re-search-forward prohibit end t))
8246 (while (and (< (point) end)
8247 (re-search-forward "^[ \t]+" end t))
8248 (goto-char (match-end 0))
8249 (setq col (current-column))
8250 (if (< diff 0) (replace-match ""))
8251 (org-indent-to-column (+ diff col))))
8252 (move-marker end nil))))
8254 (defun org-convert-to-odd-levels ()
8255 "Convert an org-mode file with all levels allowed to one with odd levels.
8256 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8257 level 5 etc."
8258 (interactive)
8259 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8260 (let ((outline-level 'org-outline-level)
8261 (org-odd-levels-only nil) n)
8262 (save-excursion
8263 (goto-char (point-min))
8264 (while (re-search-forward "^\\*\\*+ " nil t)
8265 (setq n (- (length (match-string 0)) 2))
8266 (while (>= (setq n (1- n)) 0)
8267 (org-demote))
8268 (end-of-line 1))))))
8270 (defun org-convert-to-oddeven-levels ()
8271 "Convert an org-mode file with only odd levels to one with odd/even levels.
8272 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8273 file contains a section with an even level, conversion would
8274 destroy the structure of the file. An error is signaled in this
8275 case."
8276 (interactive)
8277 (goto-char (point-min))
8278 ;; First check if there are no even levels
8279 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8280 (org-show-context t)
8281 (error "Not all levels are odd in this file. Conversion not possible"))
8282 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8283 (let ((outline-regexp org-outline-regexp)
8284 (outline-level 'org-outline-level)
8285 (org-odd-levels-only nil) n)
8286 (save-excursion
8287 (goto-char (point-min))
8288 (while (re-search-forward "^\\*\\*+ " nil t)
8289 (setq n (/ (1- (length (match-string 0))) 2))
8290 (while (>= (setq n (1- n)) 0)
8291 (org-promote))
8292 (end-of-line 1))))))
8294 (defun org-tr-level (n)
8295 "Make N odd if required."
8296 (if org-odd-levels-only (1+ (/ n 2)) n))
8298 ;;; Vertical tree motion, cutting and pasting of subtrees
8300 (defun org-move-subtree-up (&optional arg)
8301 "Move the current subtree up past ARG headlines of the same level."
8302 (interactive "p")
8303 (org-move-subtree-down (- (prefix-numeric-value arg))))
8305 (defun org-move-subtree-down (&optional arg)
8306 "Move the current subtree down past ARG headlines of the same level."
8307 (interactive "p")
8308 (setq arg (prefix-numeric-value arg))
8309 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8310 'org-get-last-sibling))
8311 (ins-point (make-marker))
8312 (cnt (abs arg))
8313 (col (current-column))
8314 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8315 ;; Select the tree
8316 (org-back-to-heading)
8317 (setq beg0 (point))
8318 (save-excursion
8319 (setq ne-beg (org-back-over-empty-lines))
8320 (setq beg (point)))
8321 (save-match-data
8322 (save-excursion (outline-end-of-heading)
8323 (setq folded (outline-invisible-p)))
8324 (progn (org-end-of-subtree nil t)
8325 (unless (eobp) (backward-char))))
8326 (outline-next-heading)
8327 (setq ne-end (org-back-over-empty-lines))
8328 (setq end (point))
8329 (goto-char beg0)
8330 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8331 ;; include less whitespace
8332 (save-excursion
8333 (goto-char beg)
8334 (forward-line (- ne-beg ne-end))
8335 (setq beg (point))))
8336 ;; Find insertion point, with error handling
8337 (while (> cnt 0)
8338 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8339 (progn (goto-char beg0)
8340 (user-error "Cannot move past superior level or buffer limit")))
8341 (setq cnt (1- cnt)))
8342 (if (> arg 0)
8343 ;; Moving forward - still need to move over subtree
8344 (progn (org-end-of-subtree t t)
8345 (save-excursion
8346 (org-back-over-empty-lines)
8347 (or (bolp) (newline)))))
8348 (setq ne-ins (org-back-over-empty-lines))
8349 (move-marker ins-point (point))
8350 (setq txt (buffer-substring beg end))
8351 (org-save-markers-in-region beg end)
8352 (delete-region beg end)
8353 (org-remove-empty-overlays-at beg)
8354 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8355 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8356 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8357 (let ((bbb (point)))
8358 (insert-before-markers txt)
8359 (org-reinstall-markers-in-region bbb)
8360 (move-marker ins-point bbb))
8361 (or (bolp) (insert "\n"))
8362 (setq ins-end (point))
8363 (goto-char ins-point)
8364 (org-skip-whitespace)
8365 (when (and (< arg 0)
8366 (org-first-sibling-p)
8367 (> ne-ins ne-beg))
8368 ;; Move whitespace back to beginning
8369 (save-excursion
8370 (goto-char ins-end)
8371 (let ((kill-whole-line t))
8372 (kill-line (- ne-ins ne-beg)) (point)))
8373 (insert (make-string (- ne-ins ne-beg) ?\n)))
8374 (move-marker ins-point nil)
8375 (if folded
8376 (hide-subtree)
8377 (org-show-entry)
8378 (show-children)
8379 (org-cycle-hide-drawers 'children))
8380 (org-clean-visibility-after-subtree-move)
8381 ;; move back to the initial column we were at
8382 (move-to-column col)))
8384 (defvar org-subtree-clip ""
8385 "Clipboard for cut and paste of subtrees.
8386 This is actually only a copy of the kill, because we use the normal kill
8387 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8389 (defvar org-subtree-clip-folded nil
8390 "Was the last copied subtree folded?
8391 This is used to fold the tree back after pasting.")
8393 (defun org-cut-subtree (&optional n)
8394 "Cut the current subtree into the clipboard.
8395 With prefix arg N, cut this many sequential subtrees.
8396 This is a short-hand for marking the subtree and then cutting it."
8397 (interactive "p")
8398 (org-copy-subtree n 'cut))
8400 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8401 "Copy the current subtree it in the clipboard.
8402 With prefix arg N, copy this many sequential subtrees.
8403 This is a short-hand for marking the subtree and then copying it.
8404 If CUT is non-nil, actually cut the subtree.
8405 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8406 of some markers in the region, even if CUT is non-nil. This is
8407 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8408 (interactive "p")
8409 (let (beg end folded (beg0 (point)))
8410 (if (org-called-interactively-p 'any)
8411 (org-back-to-heading nil) ; take what looks like a subtree
8412 (org-back-to-heading t)) ; take what is really there
8413 (setq beg (point))
8414 (skip-chars-forward " \t\r\n")
8415 (save-match-data
8416 (if nosubtrees
8417 (outline-next-heading)
8418 (save-excursion (outline-end-of-heading)
8419 (setq folded (outline-invisible-p)))
8420 (ignore-errors (org-forward-heading-same-level (1- n) t))
8421 (org-end-of-subtree t t)))
8422 (setq end (point))
8423 (goto-char beg0)
8424 (when (> end beg)
8425 (setq org-subtree-clip-folded folded)
8426 (when (or cut force-store-markers)
8427 (org-save-markers-in-region beg end))
8428 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8429 (setq org-subtree-clip (current-kill 0))
8430 (message "%s: Subtree(s) with %d characters"
8431 (if cut "Cut" "Copied")
8432 (length org-subtree-clip)))))
8434 (defun org-paste-subtree (&optional level tree for-yank remove)
8435 "Paste the clipboard as a subtree, with modification of headline level.
8436 The entire subtree is promoted or demoted in order to match a new headline
8437 level.
8439 If the cursor is at the beginning of a headline, the same level as
8440 that headline is used to paste the tree.
8442 If not, the new level is derived from the *visible* headings
8443 before and after the insertion point, and taken to be the inferior headline
8444 level of the two. So if the previous visible heading is level 3 and the
8445 next is level 4 (or vice versa), level 4 will be used for insertion.
8446 This makes sure that the subtree remains an independent subtree and does
8447 not swallow low level entries.
8449 You can also force a different level, either by using a numeric prefix
8450 argument, or by inserting the heading marker by hand. For example, if the
8451 cursor is after \"*****\", then the tree will be shifted to level 5.
8453 If optional TREE is given, use this text instead of the kill ring.
8455 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8456 move back over whitespace before inserting, and move point to the end of
8457 the inserted text when done.
8459 When REMOVE is non-nil, remove the subtree from the clipboard."
8460 (interactive "P")
8461 (setq tree (or tree (and kill-ring (current-kill 0))))
8462 (unless (org-kill-is-subtree-p tree)
8463 (user-error "%s"
8464 (substitute-command-keys
8465 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8466 (org-with-limited-levels
8467 (let* ((visp (not (outline-invisible-p)))
8468 (txt tree)
8469 (^re_ "\\(\\*+\\)[ \t]*")
8470 (old-level (if (string-match org-outline-regexp-bol txt)
8471 (- (match-end 0) (match-beginning 0) 1)
8472 -1))
8473 (force-level (cond (level (prefix-numeric-value level))
8474 ((and (looking-at "[ \t]*$")
8475 (string-match
8476 "^\\*+$" (buffer-substring
8477 (point-at-bol) (point))))
8478 (- (match-end 0) (match-beginning 0)))
8479 ((and (bolp)
8480 (looking-at org-outline-regexp))
8481 (- (match-end 0) (point) 1))))
8482 (previous-level (save-excursion
8483 (condition-case nil
8484 (progn
8485 (outline-previous-visible-heading 1)
8486 (if (looking-at ^re_)
8487 (- (match-end 0) (match-beginning 0) 1)
8489 (error 1))))
8490 (next-level (save-excursion
8491 (condition-case nil
8492 (progn
8493 (or (looking-at org-outline-regexp)
8494 (outline-next-visible-heading 1))
8495 (if (looking-at ^re_)
8496 (- (match-end 0) (match-beginning 0) 1)
8498 (error 1))))
8499 (new-level (or force-level (max previous-level next-level)))
8500 (shift (if (or (= old-level -1)
8501 (= new-level -1)
8502 (= old-level new-level))
8504 (- new-level old-level)))
8505 (delta (if (> shift 0) -1 1))
8506 (func (if (> shift 0) 'org-demote 'org-promote))
8507 (org-odd-levels-only nil)
8508 beg end newend)
8509 ;; Remove the forced level indicator
8510 (if force-level
8511 (delete-region (point-at-bol) (point)))
8512 ;; Paste
8513 (beginning-of-line (if (bolp) 1 2))
8514 (setq beg (point))
8515 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8516 (insert-before-markers txt)
8517 (unless (string-match "\n\\'" txt) (insert "\n"))
8518 (setq newend (point))
8519 (org-reinstall-markers-in-region beg)
8520 (setq end (point))
8521 (goto-char beg)
8522 (skip-chars-forward " \t\n\r")
8523 (setq beg (point))
8524 (if (and (outline-invisible-p) visp)
8525 (save-excursion (outline-show-heading)))
8526 ;; Shift if necessary
8527 (unless (= shift 0)
8528 (save-restriction
8529 (narrow-to-region beg end)
8530 (while (not (= shift 0))
8531 (org-map-region func (point-min) (point-max))
8532 (setq shift (+ delta shift)))
8533 (goto-char (point-min))
8534 (setq newend (point-max))))
8535 (when (or (org-called-interactively-p 'interactive) for-yank)
8536 (message "Clipboard pasted as level %d subtree" new-level))
8537 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8538 kill-ring
8539 (eq org-subtree-clip (current-kill 0))
8540 org-subtree-clip-folded)
8541 ;; The tree was folded before it was killed/copied
8542 (hide-subtree))
8543 (and for-yank (goto-char newend))
8544 (and remove (setq kill-ring (cdr kill-ring))))))
8546 (defun org-kill-is-subtree-p (&optional txt)
8547 "Check if the current kill is an outline subtree, or a set of trees.
8548 Returns nil if kill does not start with a headline, or if the first
8549 headline level is not the largest headline level in the tree.
8550 So this will actually accept several entries of equal levels as well,
8551 which is OK for `org-paste-subtree'.
8552 If optional TXT is given, check this string instead of the current kill."
8553 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8554 (re (org-get-limited-outline-regexp))
8555 (^re (concat "^" re))
8556 (start-level (and kill
8557 (string-match
8558 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8559 kill)
8560 (- (match-end 2) (match-beginning 2) 1)))
8561 (start (1+ (or (match-beginning 2) -1))))
8562 (if (not start-level)
8563 (progn
8564 nil) ;; does not even start with a heading
8565 (catch 'exit
8566 (while (setq start (string-match ^re kill (1+ start)))
8567 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8568 (throw 'exit nil)))
8569 t))))
8571 (defvar org-markers-to-move nil
8572 "Markers that should be moved with a cut-and-paste operation.
8573 Those markers are stored together with their positions relative to
8574 the start of the region.")
8576 (defun org-save-markers-in-region (beg end)
8577 "Check markers in region.
8578 If these markers are between BEG and END, record their position relative
8579 to BEG, so that after moving the block of text, we can put the markers back
8580 into place.
8581 This function gets called just before an entry or tree gets cut from the
8582 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8583 called immediately, to move the markers with the entries."
8584 (setq org-markers-to-move nil)
8585 (when (featurep 'org-clock)
8586 (org-clock-save-markers-for-cut-and-paste beg end))
8587 (when (featurep 'org-agenda)
8588 (org-agenda-save-markers-for-cut-and-paste beg end)))
8590 (defun org-check-and-save-marker (marker beg end)
8591 "Check if MARKER is between BEG and END.
8592 If yes, remember the marker and the distance to BEG."
8593 (when (and (marker-buffer marker)
8594 (equal (marker-buffer marker) (current-buffer)))
8595 (if (and (>= marker beg) (< marker end))
8596 (push (cons marker (- marker beg)) org-markers-to-move))))
8598 (defun org-reinstall-markers-in-region (beg)
8599 "Move all remembered markers to their position relative to BEG."
8600 (mapc (lambda (x)
8601 (move-marker (car x) (+ beg (cdr x))))
8602 org-markers-to-move)
8603 (setq org-markers-to-move nil))
8605 (defun org-narrow-to-subtree ()
8606 "Narrow buffer to the current subtree."
8607 (interactive)
8608 (save-excursion
8609 (save-match-data
8610 (org-with-limited-levels
8611 (narrow-to-region
8612 (progn (org-back-to-heading t) (point))
8613 (progn (org-end-of-subtree t t)
8614 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8615 (point)))))))
8617 (defun org-narrow-to-block ()
8618 "Narrow buffer to the current block."
8619 (interactive)
8620 (let* ((case-fold-search t)
8621 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8622 "^[ \t]*#\\+end_.*")))
8623 (if blockp
8624 (narrow-to-region (car blockp) (cdr blockp))
8625 (user-error "Not in a block"))))
8627 (eval-when-compile
8628 (defvar org-property-drawer-re))
8630 (defvar org-property-start-re) ;; defined below
8631 (defun org-clone-subtree-with-time-shift (n &optional shift)
8632 "Clone the task (subtree) at point N times.
8633 The clones will be inserted as siblings.
8635 In interactive use, the user will be prompted for the number of
8636 clones to be produced. If the entry has a timestamp, the user
8637 will also be prompted for a time shift, which may be a repeater
8638 as used in time stamps, for example `+3d'. To disable this,
8639 you can call the function with a universal prefix argument.
8641 When a valid repeater is given and the entry contains any time
8642 stamps, the clones will become a sequence in time, with time
8643 stamps in the subtree shifted for each clone produced. If SHIFT
8644 is nil or the empty string, time stamps will be left alone. The
8645 ID property of the original subtree is removed.
8647 If the original subtree did contain time stamps with a repeater,
8648 the following will happen:
8649 - the repeater will be removed in each clone
8650 - an additional clone will be produced, with the current, unshifted
8651 date(s) in the entry.
8652 - the original entry will be placed *after* all the clones, with
8653 repeater intact.
8654 - the start days in the repeater in the original entry will be shifted
8655 to past the last clone.
8656 In this way you can spell out a number of instances of a repeating task,
8657 and still retain the repeater to cover future instances of the task."
8658 (interactive "nNumber of clones to produce: ")
8659 (let ((shift
8660 (or shift
8661 (if (and (not (equal current-prefix-arg '(4)))
8662 (save-excursion
8663 (re-search-forward org-ts-regexp-both
8664 (save-excursion
8665 (org-end-of-subtree t)
8666 (point)) t)))
8667 (read-from-minibuffer
8668 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8669 ""))) ;; No time shift
8670 (n-no-remove -1)
8671 (drawer-re org-drawer-regexp)
8672 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8673 beg end template task idprop
8674 shift-n shift-what doshift nmin nmax)
8675 (if (not (and (integerp n) (> n 0)))
8676 (user-error "Invalid number of replications %s" n))
8677 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8678 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8679 shift)))
8680 (user-error "Invalid shift specification %s" shift))
8681 (when doshift
8682 (setq shift-n (string-to-number (match-string 1 shift))
8683 shift-what (cdr (assoc (match-string 2 shift)
8684 '(("d" . day) ("w" . week)
8685 ("m" . month) ("y" . year))))))
8686 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8687 (setq nmin 1 nmax n)
8688 (org-back-to-heading t)
8689 (setq beg (point))
8690 (setq idprop (org-entry-get nil "ID"))
8691 (org-end-of-subtree t t)
8692 (or (bolp) (insert "\n"))
8693 (setq end (point))
8694 (setq template (buffer-substring beg end))
8695 (when (and doshift
8696 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8697 (delete-region beg end)
8698 (setq end beg)
8699 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8700 (goto-char end)
8701 (loop for n from nmin to nmax do
8702 ;; prepare clone
8703 (with-temp-buffer
8704 (insert template)
8705 (org-mode)
8706 (goto-char (point-min))
8707 (org-show-subtree)
8708 (and idprop (if org-clone-delete-id
8709 (org-entry-delete nil "ID")
8710 (org-id-get-create t)))
8711 (unless (= n 0)
8712 (while (re-search-forward org-clock-re nil t)
8713 (kill-whole-line))
8714 (goto-char (point-min))
8715 (while (re-search-forward drawer-re nil t)
8716 (org-remove-empty-drawer-at (point))))
8717 (goto-char (point-min))
8718 (when doshift
8719 (while (re-search-forward org-ts-regexp-both nil t)
8720 (org-timestamp-change (* n shift-n) shift-what))
8721 (unless (= n n-no-remove)
8722 (goto-char (point-min))
8723 (while (re-search-forward org-ts-regexp nil t)
8724 (save-excursion
8725 (goto-char (match-beginning 0))
8726 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8727 (delete-region (match-beginning 1) (match-end 1)))))))
8728 (setq task (buffer-string)))
8729 (insert task))
8730 (goto-char beg)))
8732 ;;; Outline Sorting
8734 (defun org-sort (with-case)
8735 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8736 Optional argument WITH-CASE means sort case-sensitively."
8737 (interactive "P")
8738 (cond
8739 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8740 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8742 (org-call-with-arg 'org-sort-entries with-case))))
8744 (defun org-sort-remove-invisible (s)
8745 "Remove invisible links from string S."
8746 (remove-text-properties 0 (length s) org-rm-props s)
8747 (while (string-match org-bracket-link-regexp s)
8748 (setq s (replace-match (if (match-end 2)
8749 (match-string 3 s)
8750 (match-string 1 s)) t t s)))
8751 (let ((st (format " %s " s)))
8752 (while (string-match org-emph-re st)
8753 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8754 (setq s (substring st 1 -1)))
8757 (defvar org-priority-regexp) ; defined later in the file
8759 (defvar org-after-sorting-entries-or-items-hook nil
8760 "Hook that is run after a bunch of entries or items have been sorted.
8761 When children are sorted, the cursor is in the parent line when this
8762 hook gets called. When a region or a plain list is sorted, the cursor
8763 will be in the first entry of the sorted region/list.")
8765 (defun org-sort-entries
8766 (&optional with-case sorting-type getkey-func compare-func property)
8767 "Sort entries on a certain level of an outline tree.
8768 If there is an active region, the entries in the region are sorted.
8769 Else, if the cursor is before the first entry, sort the top-level items.
8770 Else, the children of the entry at point are sorted.
8772 Sorting can be alphabetically, numerically, by date/time as given by
8773 a time stamp, by a property, by priority order, or by a custom function.
8775 The command prompts for the sorting type unless it has been given to the
8776 function through the SORTING-TYPE argument, which needs to be a character,
8777 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8778 the precise meaning of each character:
8780 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8781 c By creation time, which is assumed to be the first inactive time stamp
8782 at the beginning of a line.
8783 d By deadline date/time.
8784 k By clocking time.
8785 n Numerically, by converting the beginning of the entry/item to a number.
8786 o By order of TODO keywords.
8787 p By priority according to the cookie.
8788 r By the value of a property.
8789 s By scheduled date/time.
8790 t By date/time, either the first active time stamp in the entry, or, if
8791 none exist, by the first inactive one.
8793 Capital letters will reverse the sort order.
8795 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8796 called with point at the beginning of the record. It must return either
8797 a string or a number that should serve as the sorting key for that record.
8799 Comparing entries ignores case by default. However, with an optional argument
8800 WITH-CASE, the sorting considers case as well.
8802 Sorting is done against the visible part of the headlines, it ignores hidden
8803 links.
8805 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8806 (interactive "P")
8807 (let ((case-func (if with-case 'identity 'downcase))
8808 (cmstr
8809 ;; The clock marker is lost when using `sort-subr', let's
8810 ;; store the clocking string.
8811 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8812 (save-excursion
8813 (goto-char org-clock-marker)
8814 (looking-back "^.*") (match-string-no-properties 0))))
8815 start beg end stars re re2
8816 txt what tmp)
8817 ;; Find beginning and end of region to sort
8818 (cond
8819 ((org-region-active-p)
8820 ;; we will sort the region
8821 (setq end (region-end)
8822 what "region")
8823 (goto-char (region-beginning))
8824 (if (not (org-at-heading-p)) (outline-next-heading))
8825 (setq start (point)))
8826 ((or (org-at-heading-p)
8827 (ignore-errors (progn (org-back-to-heading) t)))
8828 ;; we will sort the children of the current headline
8829 (org-back-to-heading)
8830 (setq start (point)
8831 end (progn (org-end-of-subtree t t)
8832 (or (bolp) (insert "\n"))
8833 (when (>= (org-back-over-empty-lines) 1)
8834 (forward-line 1))
8835 (point))
8836 what "children")
8837 (goto-char start)
8838 (show-subtree)
8839 (outline-next-heading))
8841 ;; we will sort the top-level entries in this file
8842 (goto-char (point-min))
8843 (or (org-at-heading-p) (outline-next-heading))
8844 (setq start (point))
8845 (goto-char (point-max))
8846 (beginning-of-line 1)
8847 (when (looking-at ".*?\\S-")
8848 ;; File ends in a non-white line
8849 (end-of-line 1)
8850 (insert "\n"))
8851 (setq end (point-max))
8852 (setq what "top-level")
8853 (goto-char start)
8854 (show-all)))
8856 (setq beg (point))
8857 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8859 (looking-at "\\(\\*+\\)")
8860 (setq stars (match-string 1)
8861 re (concat "^" (regexp-quote stars) " +")
8862 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8863 txt (buffer-substring beg end))
8864 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8865 (if (and (not (equal stars "*")) (string-match re2 txt))
8866 (user-error "Region to sort contains a level above the first entry"))
8868 (unless sorting-type
8869 (message
8870 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8871 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8872 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8873 what)
8874 (setq sorting-type (read-char-exclusive))
8876 (unless getkey-func
8877 (and (= (downcase sorting-type) ?f)
8878 (setq getkey-func
8879 (org-icompleting-read "Sort using function: "
8880 obarray 'fboundp t nil nil))
8881 (setq getkey-func (intern getkey-func))))
8883 (and (= (downcase sorting-type) ?r)
8884 (not property)
8885 (setq property
8886 (org-icompleting-read "Property: "
8887 (mapcar 'list (org-buffer-property-keys t))
8888 nil t))))
8890 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8891 (message "Sorting entries...")
8893 (save-restriction
8894 (narrow-to-region start end)
8895 (let ((dcst (downcase sorting-type))
8896 (case-fold-search nil)
8897 (now (current-time)))
8898 (sort-subr
8899 (/= dcst sorting-type)
8900 ;; This function moves to the beginning character of the "record" to
8901 ;; be sorted.
8902 (lambda nil
8903 (if (re-search-forward re nil t)
8904 (goto-char (match-beginning 0))
8905 (goto-char (point-max))))
8906 ;; This function moves to the last character of the "record" being
8907 ;; sorted.
8908 (lambda nil
8909 (save-match-data
8910 (condition-case nil
8911 (outline-forward-same-level 1)
8912 (error
8913 (goto-char (point-max))))))
8914 ;; This function returns the value that gets sorted against.
8915 (lambda nil
8916 (cond
8917 ((= dcst ?n)
8918 (if (looking-at org-complex-heading-regexp)
8919 (string-to-number (org-sort-remove-invisible (match-string 4)))
8920 nil))
8921 ((= dcst ?a)
8922 (if (looking-at org-complex-heading-regexp)
8923 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8924 nil))
8925 ((= dcst ?k)
8926 (or (get-text-property (point) :org-clock-minutes) 0))
8927 ((= dcst ?t)
8928 (let ((end (save-excursion (outline-next-heading) (point))))
8929 (if (or (re-search-forward org-ts-regexp end t)
8930 (re-search-forward org-ts-regexp-both end t))
8931 (org-time-string-to-seconds (match-string 0))
8932 (org-float-time now))))
8933 ((= dcst ?c)
8934 (let ((end (save-excursion (outline-next-heading) (point))))
8935 (if (re-search-forward
8936 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8937 end t)
8938 (org-time-string-to-seconds (match-string 0))
8939 (org-float-time now))))
8940 ((= dcst ?s)
8941 (let ((end (save-excursion (outline-next-heading) (point))))
8942 (if (re-search-forward org-scheduled-time-regexp end t)
8943 (org-time-string-to-seconds (match-string 1))
8944 (org-float-time now))))
8945 ((= dcst ?d)
8946 (let ((end (save-excursion (outline-next-heading) (point))))
8947 (if (re-search-forward org-deadline-time-regexp end t)
8948 (org-time-string-to-seconds (match-string 1))
8949 (org-float-time now))))
8950 ((= dcst ?p)
8951 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8952 (string-to-char (match-string 2))
8953 org-default-priority))
8954 ((= dcst ?r)
8955 (or (org-entry-get nil property) ""))
8956 ((= dcst ?o)
8957 (if (looking-at org-complex-heading-regexp)
8958 (let* ((m (match-string 2))
8959 (s (if (member m org-done-keywords) '- '+)))
8960 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8961 ((= dcst ?f)
8962 (if getkey-func
8963 (progn
8964 (setq tmp (funcall getkey-func))
8965 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8966 tmp)
8967 (error "Invalid key function `%s'" getkey-func)))
8968 (t (error "Invalid sorting type `%c'" sorting-type))))
8970 (cond
8971 ((= dcst ?a) 'string<)
8972 ((= dcst ?f) compare-func)
8973 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8974 (run-hooks 'org-after-sorting-entries-or-items-hook)
8975 ;; Reset the clock marker if needed
8976 (when cmstr
8977 (save-excursion
8978 (goto-char start)
8979 (search-forward cmstr nil t)
8980 (move-marker org-clock-marker (point))))
8981 (message "Sorting entries...done")))
8983 (defun org-do-sort (table what &optional with-case sorting-type)
8984 "Sort TABLE of WHAT according to SORTING-TYPE.
8985 The user will be prompted for the SORTING-TYPE if the call to this
8986 function does not specify it.
8987 WHAT is only for the prompt, to indicate what is being sorted.
8988 The sorting key will be extracted from the car of the elements of
8989 the table.
8990 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8991 (unless sorting-type
8992 (message
8993 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8994 what)
8995 (setq sorting-type (read-char-exclusive)))
8996 (let ((dcst (downcase sorting-type))
8997 extractfun comparefun)
8998 ;; Define the appropriate functions
8999 (cond
9000 ((= dcst ?n)
9001 (setq extractfun 'string-to-number
9002 comparefun (if (= dcst sorting-type) '< '>)))
9003 ((= dcst ?a)
9004 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
9005 (lambda(x) (downcase (org-sort-remove-invisible x))))
9006 comparefun (if (= dcst sorting-type)
9007 'string<
9008 (lambda (a b) (and (not (string< a b))
9009 (not (string= a b)))))))
9010 ((= dcst ?t)
9011 (setq extractfun
9012 (lambda (x)
9013 (cond ((or (string-match org-ts-regexp x)
9014 (string-match org-ts-regexp-both x))
9015 (org-float-time
9016 (org-time-string-to-time (match-string 0 x))))
9017 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9018 (org-hh:mm-string-to-minutes x))
9019 (t 0)))
9020 comparefun (if (= dcst sorting-type) '< '>)))
9021 (t (error "Invalid sorting type `%c'" sorting-type)))
9023 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9024 table)
9025 (lambda (a b) (funcall comparefun (car a) (car b))))))
9028 ;;; The orgstruct minor mode
9030 ;; Define a minor mode which can be used in other modes in order to
9031 ;; integrate the org-mode structure editing commands.
9033 ;; This is really a hack, because the org-mode structure commands use
9034 ;; keys which normally belong to the major mode. Here is how it
9035 ;; works: The minor mode defines all the keys necessary to operate the
9036 ;; structure commands, but wraps the commands into a function which
9037 ;; tests if the cursor is currently at a headline or a plain list
9038 ;; item. If that is the case, the structure command is used,
9039 ;; temporarily setting many Org-mode variables like regular
9040 ;; expressions for filling etc. However, when any of those keys is
9041 ;; used at a different location, function uses `key-binding' to look
9042 ;; up if the key has an associated command in another currently active
9043 ;; keymap (minor modes, major mode, global), and executes that
9044 ;; command. There might be problems if any of the keys is otherwise
9045 ;; used as a prefix key.
9047 (defcustom orgstruct-heading-prefix-regexp ""
9048 "Regexp that matches the custom prefix of Org headlines in
9049 orgstruct(++)-mode."
9050 :group 'org
9051 :version "24.4"
9052 :package-version '(Org . "8.3")
9053 :type 'regexp)
9054 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9056 (defcustom orgstruct-setup-hook nil
9057 "Hook run after orgstruct-mode-map is filled."
9058 :group 'org
9059 :version "24.4"
9060 :package-version '(Org . "8.0")
9061 :type 'hook)
9063 (defvar orgstruct-initialized nil)
9065 (defvar org-local-vars nil
9066 "List of local variables, for use by `orgstruct-mode'.")
9068 ;;;###autoload
9069 (define-minor-mode orgstruct-mode
9070 "Toggle the minor mode `orgstruct-mode'.
9071 This mode is for using Org-mode structure commands in other
9072 modes. The following keys behave as if Org-mode were active, if
9073 the cursor is on a headline, or on a plain list item (both as
9074 defined by Org-mode)."
9075 nil " OrgStruct" (make-sparse-keymap)
9076 (funcall (if orgstruct-mode
9077 'add-to-invisibility-spec
9078 'remove-from-invisibility-spec)
9079 '(outline . t))
9080 (when orgstruct-mode
9081 (org-load-modules-maybe)
9082 (unless orgstruct-initialized
9083 (orgstruct-setup)
9084 (setq orgstruct-initialized t))))
9086 ;;;###autoload
9087 (defun turn-on-orgstruct ()
9088 "Unconditionally turn on `orgstruct-mode'."
9089 (orgstruct-mode 1))
9091 (defvar org-fb-vars nil)
9092 (make-variable-buffer-local 'org-fb-vars)
9093 (defun orgstruct++-mode (&optional arg)
9094 "Toggle `orgstruct-mode', the enhanced version of it.
9095 In addition to setting orgstruct-mode, this also exports all
9096 indentation and autofilling variables from org-mode into the
9097 buffer. It will also recognize item context in multiline items."
9098 (interactive "P")
9099 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9100 (if (< arg 1)
9101 (progn (orgstruct-mode -1)
9102 (mapc (lambda(v)
9103 (org-set-local (car v)
9104 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9105 org-fb-vars))
9106 (orgstruct-mode 1)
9107 (setq org-fb-vars nil)
9108 (unless org-local-vars
9109 (setq org-local-vars (org-get-local-variables)))
9110 (let (var val)
9111 (mapc
9112 (lambda (x)
9113 (when (string-match
9114 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9115 (symbol-name (car x)))
9116 (setq var (car x) val (nth 1 x))
9117 (push (list var `(quote ,(eval var))) org-fb-vars)
9118 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9119 org-local-vars)
9120 (org-set-local 'orgstruct-is-++ t))))
9122 (defvar orgstruct-is-++ nil
9123 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9124 (make-variable-buffer-local 'orgstruct-is-++)
9126 ;;;###autoload
9127 (defun turn-on-orgstruct++ ()
9128 "Unconditionally turn on `orgstruct++-mode'."
9129 (orgstruct++-mode 1))
9131 (defun orgstruct-error ()
9132 "Error when there is no default binding for a structure key."
9133 (interactive)
9134 (funcall (if (fboundp 'user-error)
9135 'user-error
9136 'error)
9137 "This key has no function outside structure elements"))
9139 (defun orgstruct-setup ()
9140 "Setup orgstruct keymap."
9141 (dolist (cell '((org-demote . t)
9142 (org-metaleft . t)
9143 (org-metaright . t)
9144 (org-promote . t)
9145 (org-shiftmetaleft . t)
9146 (org-shiftmetaright . t)
9147 org-backward-element
9148 org-backward-heading-same-level
9149 org-ctrl-c-ret
9150 org-ctrl-c-minus
9151 org-ctrl-c-star
9152 org-cycle
9153 org-forward-heading-same-level
9154 org-insert-heading
9155 org-insert-heading-respect-content
9156 org-kill-note-or-show-branches
9157 org-mark-subtree
9158 org-meta-return
9159 org-metadown
9160 org-metaup
9161 org-narrow-to-subtree
9162 org-promote-subtree
9163 org-reveal
9164 org-shiftdown
9165 org-shiftleft
9166 org-shiftmetadown
9167 org-shiftmetaup
9168 org-shiftright
9169 org-shifttab
9170 org-shifttab
9171 org-shiftup
9172 org-show-subtree
9173 org-sort
9174 org-up-element
9175 outline-demote
9176 outline-next-visible-heading
9177 outline-previous-visible-heading
9178 outline-promote
9179 outline-up-heading
9180 show-children))
9181 (let ((f (or (car-safe cell) cell))
9182 (disable-when-heading-prefix (cdr-safe cell)))
9183 (when (fboundp f)
9184 (let ((new-bindings))
9185 (dolist (binding (nconc (where-is-internal f org-mode-map)
9186 (where-is-internal f outline-mode-map)))
9187 (push binding new-bindings)
9188 ;; TODO use local-function-key-map
9189 (dolist (rep '(("<tab>" . "TAB")
9190 ("<return>" . "RET")
9191 ("<escape>" . "ESC")
9192 ("<delete>" . "DEL")))
9193 (setq binding (read-kbd-macro
9194 (let ((case-fold-search))
9195 (replace-regexp-in-string
9196 (regexp-quote (cdr rep))
9197 (car rep)
9198 (key-description binding)))))
9199 (pushnew binding new-bindings :test 'equal)))
9200 (dolist (binding new-bindings)
9201 (let ((key (lookup-key orgstruct-mode-map binding)))
9202 (when (or (not key) (numberp key))
9203 (ignore-errors
9204 (org-defkey orgstruct-mode-map
9205 binding
9206 (orgstruct-make-binding
9207 f binding disable-when-heading-prefix))))))))))
9208 (run-hooks 'orgstruct-setup-hook))
9210 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9211 "Create a function for binding in the structure minor mode.
9212 FUN is the command to call inside a table. KEY is the key that
9213 should be checked in for a command to execute outside of tables.
9214 Non-nil `disable-when-heading-prefix' means to disable the command
9215 if `orgstruct-heading-prefix-regexp' is not empty."
9216 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9217 (let ((nname name)
9218 (i 0))
9219 (while (fboundp (intern nname))
9220 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9221 (setq name (intern nname)))
9222 (eval
9223 (let ((bindings '((org-heading-regexp
9224 (concat "^"
9225 orgstruct-heading-prefix-regexp
9226 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9227 (org-outline-regexp
9228 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9229 (org-outline-regexp-bol
9230 (concat "^" org-outline-regexp))
9231 (outline-regexp org-outline-regexp)
9232 (outline-heading-end-regexp "\n")
9233 (outline-level 'org-outline-level)
9234 (outline-heading-alist))))
9235 `(defun ,name (arg)
9236 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9237 "Outside of structure, run the binding of `"
9238 (key-description key) "'."
9239 (when disable-when-heading-prefix
9240 (concat
9241 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9242 "back to the default binding due to limitations of Org's implementation of\n"
9243 "`" (symbol-name fun) "'.")))
9244 (interactive "p")
9245 (let* ((disable
9246 ,(and disable-when-heading-prefix
9247 '(not (string= orgstruct-heading-prefix-regexp ""))))
9248 (fallback
9249 (or disable
9250 (not
9251 (let* ,bindings
9252 (org-context-p 'headline 'item
9253 ,(when (memq fun
9254 '(org-insert-heading
9255 org-insert-heading-respect-content
9256 org-meta-return))
9257 '(when orgstruct-is-++
9258 'item-body))))))))
9259 (if fallback
9260 (let* ((orgstruct-mode)
9261 (binding
9262 (loop with key = ,key
9263 for rep in
9264 '(nil
9265 ("<\\([^>]*\\)tab>" . "\\1TAB")
9266 ("<\\([^>]*\\)return>" . "\\1RET")
9267 ("<\\([^>]*\\)escape>" . "\\1ESC")
9268 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9270 (when rep
9271 (setq key (read-kbd-macro
9272 (let ((case-fold-search))
9273 (replace-regexp-in-string
9274 (car rep)
9275 (cdr rep)
9276 (key-description key))))))
9277 thereis (key-binding key))))
9278 (if (keymapp binding)
9279 (org-set-transient-map binding)
9280 (let ((func (or binding
9281 (unless disable
9282 'orgstruct-error))))
9283 (when func
9284 (call-interactively func)))))
9285 (org-run-like-in-org-mode
9286 (lambda ()
9287 (interactive)
9288 (let* ,bindings
9289 (call-interactively ',fun)))))))))
9290 name))
9292 (defun org-contextualize-keys (alist contexts)
9293 "Return valid elements in ALIST depending on CONTEXTS.
9295 `org-agenda-custom-commands' or `org-capture-templates' are the
9296 values used for ALIST, and `org-agenda-custom-commands-contexts'
9297 or `org-capture-templates-contexts' are the associated contexts
9298 definitions."
9299 (let ((contexts
9300 ;; normalize contexts
9301 (mapcar
9302 (lambda(c) (cond ((listp (cadr c))
9303 (list (car c) (car c) (cadr c)))
9304 ((string= "" (cadr c))
9305 (list (car c) (car c) (caddr c)))
9306 (t c))) contexts))
9307 (a alist) c r s)
9308 ;; loop over all commands or templates
9309 (while (setq c (pop a))
9310 (let (vrules repl)
9311 (cond
9312 ((not (assoc (car c) contexts))
9313 (push c r))
9314 ((and (assoc (car c) contexts)
9315 (setq vrules (org-contextualize-validate-key
9316 (car c) contexts)))
9317 (mapc (lambda (vr)
9318 (when (not (equal (car vr) (cadr vr)))
9319 (setq repl vr))) vrules)
9320 (if (not repl) (push c r)
9321 (push (cadr repl) s)
9322 (push
9323 (cons (car c)
9324 (cdr (or (assoc (cadr repl) alist)
9325 (error "Undefined key `%s' as contextual replacement for `%s'"
9326 (cadr repl) (car c)))))
9327 r))))))
9328 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9329 (delq
9331 (delete-dups
9332 (mapcar (lambda (x)
9333 (let ((tpl (car x)))
9334 (when (not (delq
9336 (mapcar (lambda(y)
9337 (equal y tpl)) s))) x)))
9338 (reverse r))))))
9340 (defun org-contextualize-validate-key (key contexts)
9341 "Check CONTEXTS for agenda or capture KEY."
9342 (let (r rr res)
9343 (while (setq r (pop contexts))
9344 (mapc
9345 (lambda (rr)
9346 (when
9347 (and (equal key (car r))
9348 (if (functionp rr) (funcall rr)
9349 (or (and (eq (car rr) 'in-file)
9350 (buffer-file-name)
9351 (string-match (cdr rr) (buffer-file-name)))
9352 (and (eq (car rr) 'in-mode)
9353 (string-match (cdr rr) (symbol-name major-mode)))
9354 (and (eq (car rr) 'in-buffer)
9355 (string-match (cdr rr) (buffer-name)))
9356 (when (and (eq (car rr) 'not-in-file)
9357 (buffer-file-name))
9358 (not (string-match (cdr rr) (buffer-file-name))))
9359 (when (eq (car rr) 'not-in-mode)
9360 (not (string-match (cdr rr) (symbol-name major-mode))))
9361 (when (eq (car rr) 'not-in-buffer)
9362 (not (string-match (cdr rr) (buffer-name)))))))
9363 (push r res)))
9364 (car (last r))))
9365 (delete-dups (delq nil res))))
9367 (defun org-context-p (&rest contexts)
9368 "Check if local context is any of CONTEXTS.
9369 Possible values in the list of contexts are `table', `headline', and `item'."
9370 (let ((pos (point)))
9371 (goto-char (point-at-bol))
9372 (prog1 (or (and (memq 'table contexts)
9373 (looking-at "[ \t]*|"))
9374 (and (memq 'headline contexts)
9375 (looking-at org-outline-regexp))
9376 (and (memq 'item contexts)
9377 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9378 (and (memq 'item-body contexts)
9379 (org-in-item-p)))
9380 (goto-char pos))))
9382 (defun org-get-local-variables ()
9383 "Return a list of all local variables in an Org mode buffer."
9384 (let (varlist)
9385 (with-current-buffer (get-buffer-create "*Org tmp*")
9386 (erase-buffer)
9387 (org-mode)
9388 (setq varlist (buffer-local-variables)))
9389 (kill-buffer "*Org tmp*")
9390 (delq nil
9391 (mapcar
9392 (lambda (x)
9393 (setq x
9394 (if (symbolp x)
9395 (list x)
9396 (list (car x) (cdr x))))
9397 (if (and (not (get (car x) 'org-state))
9398 (string-match
9399 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9400 (symbol-name (car x))))
9401 x nil))
9402 varlist))))
9404 (defun org-clone-local-variables (from-buffer &optional regexp)
9405 "Clone local variables from FROM-BUFFER.
9406 Optional argument REGEXP selects variables to clone."
9407 (mapc
9408 (lambda (pair)
9409 (and (symbolp (car pair))
9410 (or (null regexp)
9411 (string-match regexp (symbol-name (car pair))))
9412 (set (make-local-variable (car pair))
9413 (cdr pair))))
9414 (buffer-local-variables from-buffer)))
9416 ;;;###autoload
9417 (defun org-run-like-in-org-mode (cmd)
9418 "Run a command, pretending that the current buffer is in Org-mode.
9419 This will temporarily bind local variables that are typically bound in
9420 Org-mode to the values they have in Org-mode, and then interactively
9421 call CMD."
9422 (org-load-modules-maybe)
9423 (unless org-local-vars
9424 (setq org-local-vars (org-get-local-variables)))
9425 (let (binds)
9426 (dolist (var org-local-vars)
9427 (when (or (not (boundp (car var)))
9428 (eq (symbol-value (car var))
9429 (default-value (car var))))
9430 (push (list (car var) `(quote ,(cadr var))) binds)))
9431 (eval `(let ,binds
9432 (call-interactively (quote ,cmd))))))
9434 (defun org-get-category (&optional pos force-refresh)
9435 "Get the category applying to position POS."
9436 (save-match-data
9437 (if force-refresh (org-refresh-category-properties))
9438 (let ((pos (or pos (point))))
9439 (or (get-text-property pos 'org-category)
9440 (progn (org-refresh-category-properties)
9441 (get-text-property pos 'org-category))))))
9443 ;;; Refresh properties
9445 (defun org-refresh-properties (dprop tprop)
9446 "Refresh buffer text properties.
9447 DPROP is the drawer property and TPROP is either the
9448 corresponding text property to set, or an alist with each element
9449 being a text property (as a symbol) and a function to apply to
9450 the value of the drawer property."
9451 (let ((case-fold-search t)
9452 (inhibit-read-only t))
9453 (org-with-silent-modifications
9454 (save-excursion
9455 (save-restriction
9456 (widen)
9457 (goto-char (point-min))
9458 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9459 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9461 (defun org-refresh-property (tprop p)
9462 "Refresh the buffer text property TPROP from the drawer property P.
9463 The refresh happens only for the current tree (not subtree)."
9464 (save-excursion
9465 (org-back-to-heading t)
9466 ;; tprop is a text property symbol
9467 (if (symbolp tprop)
9468 (put-text-property
9469 (point) (or (outline-next-heading) (point-max)) tprop p)
9470 ;; tprop is an alist with (properties . function) elements
9471 (mapc (lambda(al)
9472 (save-excursion
9473 (put-text-property
9474 (point-at-bol) (or (outline-next-heading) (point-max))
9475 (car al)
9476 (funcall (cdr al) p))))
9477 tprop))))
9479 (defun org-refresh-category-properties ()
9480 "Refresh category text properties in the buffer."
9481 (let ((case-fold-search t)
9482 (inhibit-read-only t)
9483 (def-cat (cond
9484 ((null org-category)
9485 (if buffer-file-name
9486 (file-name-sans-extension
9487 (file-name-nondirectory buffer-file-name))
9488 "???"))
9489 ((symbolp org-category) (symbol-name org-category))
9490 (t org-category)))
9491 beg end cat pos optionp)
9492 (org-with-silent-modifications
9493 (save-excursion
9494 (save-restriction
9495 (widen)
9496 (goto-char (point-min))
9497 (put-text-property (point) (point-max) 'org-category def-cat)
9498 (while (re-search-forward
9499 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9500 (setq pos (match-end 0)
9501 optionp (equal (char-after (match-beginning 0)) ?#)
9502 cat (org-trim (match-string 2)))
9503 (if optionp
9504 (setq beg (point-at-bol) end (point-max))
9505 (org-back-to-heading t)
9506 (setq beg (point) end (org-end-of-subtree t t)))
9507 (put-text-property beg end 'org-category cat)
9508 (goto-char pos)))))))
9510 (defun org-refresh-stats-properties ()
9511 "Refresh stats text properties in the buffer."
9512 (let (stats)
9513 (org-with-silent-modifications
9514 (save-excursion
9515 (save-restriction
9516 (widen)
9517 (goto-char (point-min))
9518 (while (re-search-forward
9519 (concat org-outline-regexp-bol ".*"
9520 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9521 nil t)
9522 (setq stats (cond ((equal (match-string 3) "0") 0)
9523 ((match-string 2)
9524 (/ (* (string-to-number (match-string 2)) 100)
9525 (string-to-number (match-string 3))))
9526 (t (string-to-number (match-string 1)))))
9527 (org-back-to-heading t)
9528 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9529 'org-stats stats)))))))
9531 (defun org-refresh-effort-properties ()
9532 "Refresh effort properties"
9533 (org-refresh-properties
9534 org-effort-property
9535 '((effort . identity)
9536 (effort-minutes . org-duration-string-to-minutes))))
9538 ;;;; Link Stuff
9540 ;;; Link abbreviations
9542 (defun org-link-expand-abbrev (link)
9543 "Apply replacements as defined in `org-link-abbrev-alist'."
9544 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9545 (let* ((key (match-string 1 link))
9546 (as (or (assoc key org-link-abbrev-alist-local)
9547 (assoc key org-link-abbrev-alist)))
9548 (tag (and (match-end 2) (match-string 3 link)))
9549 rpl)
9550 (if (not as)
9551 link
9552 (setq rpl (cdr as))
9553 (cond
9554 ((symbolp rpl) (funcall rpl tag))
9555 ((string-match "%(\\([^)]+\\))" rpl)
9556 (replace-match
9557 (save-match-data
9558 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9559 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9560 ((string-match "%h" rpl)
9561 (replace-match (url-hexify-string (or tag "")) t t rpl))
9562 (t (concat rpl tag)))))
9563 link))
9565 ;;; Storing and inserting links
9567 (defvar org-insert-link-history nil
9568 "Minibuffer history for links inserted with `org-insert-link'.")
9570 (defvar org-stored-links nil
9571 "Contains the links stored with `org-store-link'.")
9573 (defvar org-store-link-plist nil
9574 "Plist with info about the most recently link created with `org-store-link'.")
9576 (defvar org-link-protocols nil
9577 "Link protocols added to Org-mode using `org-add-link-type'.")
9579 (defvar org-store-link-functions nil
9580 "List of functions that are called to create and store a link.
9581 Each function will be called in turn until one returns a non-nil
9582 value. Each function should check if it is responsible for creating
9583 this link (for example by looking at the major mode).
9584 If not, it must exit and return nil.
9585 If yes, it should return a non-nil value after a calling
9586 `org-store-link-props' with a list of properties and values.
9587 Special properties are:
9589 :type The link prefix, like \"http\". This must be given.
9590 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9591 This is obligatory as well.
9592 :description Optional default description for the second pair
9593 of brackets in an Org-mode link. The user can still change
9594 this when inserting this link into an Org-mode buffer.
9596 In addition to these, any additional properties can be specified
9597 and then used in capture templates.")
9599 (defun org-add-link-type (type &optional follow export)
9600 "Add TYPE to the list of `org-link-types'.
9601 Re-compute all regular expressions depending on `org-link-types'
9603 FOLLOW and EXPORT are two functions.
9605 FOLLOW should take the link path as the single argument and do whatever
9606 is necessary to follow the link, for example find a file or display
9607 a mail message.
9609 EXPORT should format the link path for export to one of the export formats.
9610 It should be a function accepting three arguments:
9612 path the path of the link, the text after the prefix (like \"http:\")
9613 desc the description of the link, if any, or a description added by
9614 org-export-normalize-links if there is none
9615 format the export format, a symbol like `html' or `latex' or `ascii'..
9617 The function may use the FORMAT information to return different values
9618 depending on the format. The return value will be put literally into
9619 the exported file. If the return value is nil, this means Org should
9620 do what it normally does with links which do not have EXPORT defined.
9622 Org-mode has a built-in default for exporting links. If you are happy with
9623 this default, there is no need to define an export function for the link
9624 type. For a simple example of an export function, see `org-bbdb.el'."
9625 (add-to-list 'org-link-types type t)
9626 (org-make-link-regexps)
9627 (if (assoc type org-link-protocols)
9628 (setcdr (assoc type org-link-protocols) (list follow export))
9629 (push (list type follow export) org-link-protocols)))
9631 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9632 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9634 ;;;###autoload
9635 (defun org-store-link (arg)
9636 "\\<org-mode-map>Store an org-link to the current location.
9637 This link is added to `org-stored-links' and can later be inserted
9638 into an org-buffer with \\[org-insert-link].
9640 For some link types, a prefix arg is interpreted.
9641 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9642 For file links, arg negates `org-context-in-file-links'.
9644 A double prefix arg force skipping storing functions that are not
9645 part of Org's core.
9647 A triple prefix arg force storing a link for each line in the
9648 active region."
9649 (interactive "P")
9650 (org-load-modules-maybe)
9651 (if (and (equal arg '(64)) (org-region-active-p))
9652 (save-excursion
9653 (let ((end (region-end)))
9654 (goto-char (region-beginning))
9655 (set-mark (point))
9656 (while (< (point-at-eol) end)
9657 (move-end-of-line 1) (activate-mark)
9658 (let (current-prefix-arg)
9659 (call-interactively 'org-store-link))
9660 (move-beginning-of-line 2)
9661 (set-mark (point)))))
9662 (org-with-limited-levels
9663 (setq org-store-link-plist nil)
9664 (let (link cpltxt desc description search
9665 txt custom-id agenda-link sfuns sfunsn)
9666 (cond
9668 ;; Store a link using an external link type
9669 ((and (not (equal arg '(16)))
9670 (setq sfuns
9671 (delq
9672 nil (mapcar (lambda (f)
9673 (let (fs) (if (funcall f) (push f fs))))
9674 org-store-link-functions))
9675 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9676 (or (and (cdr sfuns)
9677 (funcall (intern
9678 (completing-read
9679 "Which function for creating the link? "
9680 sfunsn nil t (car sfunsn)))))
9681 (funcall (caar sfuns)))
9682 (setq link (plist-get org-store-link-plist :link)
9683 desc (or (plist-get org-store-link-plist
9684 :description) link))))
9686 ;; Store a link from a source code buffer
9687 ((org-src-edit-buffer-p)
9688 (let (label gc)
9689 (while (or (not label)
9690 (save-excursion
9691 (save-restriction
9692 (widen)
9693 (goto-char (point-min))
9694 (re-search-forward
9695 (regexp-quote (format org-coderef-label-format label))
9696 nil t))))
9697 (when label (message "Label exists already") (sit-for 2))
9698 (setq label (read-string "Code line label: " label)))
9699 (end-of-line 1)
9700 (setq link (format org-coderef-label-format label))
9701 (setq gc (- 79 (length link)))
9702 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9703 (insert link)
9704 (setq link (concat "(" label ")") desc nil)))
9706 ;; We are in the agenda, link to referenced location
9707 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9708 (let ((m (or (get-text-property (point) 'org-hd-marker)
9709 (get-text-property (point) 'org-marker))))
9710 (when m
9711 (org-with-point-at m
9712 (setq agenda-link
9713 (if (org-called-interactively-p 'any)
9714 (call-interactively 'org-store-link)
9715 (org-store-link nil)))))))
9717 ((eq major-mode 'calendar-mode)
9718 (let ((cd (calendar-cursor-to-date)))
9719 (setq link
9720 (format-time-string
9721 (car org-time-stamp-formats)
9722 (apply 'encode-time
9723 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9724 nil nil nil))))
9725 (org-store-link-props :type "calendar" :date cd)))
9727 ((eq major-mode 'help-mode)
9728 (setq link (concat "help:" (save-excursion
9729 (goto-char (point-min))
9730 (looking-at "^[^ ]+")
9731 (match-string 0))))
9732 (org-store-link-props :type "help"))
9734 ((eq major-mode 'w3-mode)
9735 (setq cpltxt (if (and (buffer-name)
9736 (not (string-match "Untitled" (buffer-name))))
9737 (buffer-name)
9738 (url-view-url t))
9739 link (url-view-url t))
9740 (org-store-link-props :type "w3" :url (url-view-url t)))
9742 ((eq major-mode 'image-mode)
9743 (setq cpltxt (concat "file:"
9744 (abbreviate-file-name buffer-file-name))
9745 link cpltxt)
9746 (org-store-link-props :type "image" :file buffer-file-name))
9748 ;; In dired, store a link to the file of the current line
9749 ((derived-mode-p 'dired-mode)
9750 (let ((file (dired-get-filename nil t)))
9751 (setq file (if file
9752 (abbreviate-file-name
9753 (expand-file-name (dired-get-filename nil t)))
9754 ;; otherwise, no file so use current directory.
9755 default-directory))
9756 (setq cpltxt (concat "file:" file)
9757 link cpltxt)))
9759 ((setq search (run-hook-with-args-until-success
9760 'org-create-file-search-functions))
9761 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9762 "::" search))
9763 (setq cpltxt (or description link)))
9765 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9766 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9767 (cond
9768 ;; Store a link using the target at point
9769 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9770 (setq cpltxt
9771 (concat "file:"
9772 (abbreviate-file-name
9773 (buffer-file-name (buffer-base-buffer)))
9774 "::" (match-string 1))
9775 link cpltxt))
9776 ((and (featurep 'org-id)
9777 (or (eq org-id-link-to-org-use-id t)
9778 (and (org-called-interactively-p 'any)
9779 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9780 (and (eq org-id-link-to-org-use-id
9781 'create-if-interactive-and-no-custom-id)
9782 (not custom-id))))
9783 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9784 ;; Store a link using the ID at point
9785 (setq link (condition-case nil
9786 (prog1 (org-id-store-link)
9787 (setq desc (or (plist-get org-store-link-plist
9788 :description)
9789 "")))
9790 (error
9791 ;; Probably before first headline, link only to file
9792 (concat "file:"
9793 (abbreviate-file-name
9794 (buffer-file-name (buffer-base-buffer))))))))
9796 ;; Just link to current headline
9797 (setq cpltxt (concat "file:"
9798 (abbreviate-file-name
9799 (buffer-file-name (buffer-base-buffer)))))
9800 ;; Add a context search string
9801 (when (org-xor org-context-in-file-links arg)
9802 (let* ((ee (org-element-at-point))
9803 (et (org-element-type ee))
9804 (ev (plist-get (cadr ee) :value))
9805 (ek (plist-get (cadr ee) :key))
9806 (eok (and (stringp ek) (string-match "name" ek))))
9807 (setq txt (cond
9808 ((org-at-heading-p) nil)
9809 ((and (eq et 'keyword) eok) ev)
9810 ((org-region-active-p)
9811 (buffer-substring (region-beginning) (region-end)))))
9812 (when (or (null txt) (string-match "\\S-" txt))
9813 (setq cpltxt
9814 (concat cpltxt "::"
9815 (condition-case nil
9816 (org-make-org-heading-search-string txt)
9817 (error "")))
9818 desc (or (and (eq et 'keyword) eok ev)
9819 (nth 4 (ignore-errors (org-heading-components)))
9820 "NONE")))))
9821 (if (string-match "::\\'" cpltxt)
9822 (setq cpltxt (substring cpltxt 0 -2)))
9823 (setq link cpltxt))))
9825 ((buffer-file-name (buffer-base-buffer))
9826 ;; Just link to this file here.
9827 (setq cpltxt (concat "file:"
9828 (abbreviate-file-name
9829 (buffer-file-name (buffer-base-buffer)))))
9830 ;; Add a context string.
9831 (when (org-xor org-context-in-file-links arg)
9832 (setq txt (if (org-region-active-p)
9833 (buffer-substring (region-beginning) (region-end))
9834 (buffer-substring (point-at-bol) (point-at-eol))))
9835 ;; Only use search option if there is some text.
9836 (when (string-match "\\S-" txt)
9837 (setq cpltxt
9838 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9839 desc "NONE")))
9840 (setq link cpltxt))
9842 ((org-called-interactively-p 'interactive)
9843 (user-error "No method for storing a link from this buffer"))
9845 (t (setq link nil)))
9847 ;; We're done setting link and desc, clean up
9848 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9849 (setq link (or link cpltxt)
9850 desc (or desc cpltxt))
9851 (cond ((equal desc "NONE") (setq desc nil))
9852 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9853 (let ((d0 (match-string 3 desc))
9854 (p0 (match-string 5 desc)))
9855 (setq desc
9856 (replace-regexp-in-string
9857 org-bracket-link-regexp
9858 (concat (or p0 d0)
9859 (if (equal (length (match-string 0 desc))
9860 (length desc)) "*" "")) desc)))))
9862 ;; Return the link
9863 (if (not (and (or (org-called-interactively-p 'any)
9864 executing-kbd-macro) link))
9865 (or agenda-link (and link (org-make-link-string link desc)))
9866 (push (list link desc) org-stored-links)
9867 (message "Stored: %s" (or desc link))
9868 (when custom-id
9869 (setq link (concat "file:" (abbreviate-file-name
9870 (buffer-file-name)) "::#" custom-id))
9871 (push (list link desc) org-stored-links))
9872 (car org-stored-links))))))
9874 (defun org-store-link-props (&rest plist)
9875 "Store link properties, extract names and addresses."
9876 (let (x adr)
9877 (when (setq x (plist-get plist :from))
9878 (setq adr (mail-extract-address-components x))
9879 (setq plist (plist-put plist :fromname (car adr)))
9880 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9881 (when (setq x (plist-get plist :to))
9882 (setq adr (mail-extract-address-components x))
9883 (setq plist (plist-put plist :toname (car adr)))
9884 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9885 (let ((from (plist-get plist :from))
9886 (to (plist-get plist :to)))
9887 (when (and from to org-from-is-user-regexp)
9888 (setq plist
9889 (plist-put plist :fromto
9890 (if (string-match org-from-is-user-regexp from)
9891 (concat "to %t")
9892 (concat "from %f"))))))
9893 (setq org-store-link-plist plist))
9895 (defun org-add-link-props (&rest plist)
9896 "Add these properties to the link property list."
9897 (let (key value)
9898 (while plist
9899 (setq key (pop plist) value (pop plist))
9900 (setq org-store-link-plist
9901 (plist-put org-store-link-plist key value)))))
9903 (defun org-email-link-description (&optional fmt)
9904 "Return the description part of an email link.
9905 This takes information from `org-store-link-plist' and formats it
9906 according to FMT (default from `org-email-link-description-format')."
9907 (setq fmt (or fmt org-email-link-description-format))
9908 (let* ((p org-store-link-plist)
9909 (to (plist-get p :toaddress))
9910 (from (plist-get p :fromaddress))
9911 (table
9912 (list
9913 (cons "%c" (plist-get p :fromto))
9914 (cons "%F" (plist-get p :from))
9915 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9916 (cons "%T" (plist-get p :to))
9917 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9918 (cons "%s" (plist-get p :subject))
9919 (cons "%d" (plist-get p :date))
9920 (cons "%m" (plist-get p :message-id)))))
9921 (when (string-match "%c" fmt)
9922 ;; Check if the user wrote this message
9923 (if (and org-from-is-user-regexp from to
9924 (save-match-data (string-match org-from-is-user-regexp from)))
9925 (setq fmt (replace-match "to %t" t t fmt))
9926 (setq fmt (replace-match "from %f" t t fmt))))
9927 (org-replace-escapes fmt table)))
9929 (defun org-make-org-heading-search-string (&optional string)
9930 "Make search string for the current headline or STRING."
9931 (let ((s (or string
9932 (and (derived-mode-p 'org-mode)
9933 (save-excursion
9934 (org-back-to-heading t)
9935 (org-element-property :raw-value (org-element-at-point))))))
9936 (lines org-context-in-file-links))
9937 (or string (setq s (concat "*" s))) ; Add * for headlines
9938 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9939 (when (and string (integerp lines) (> lines 0))
9940 (let ((slines (org-split-string s "\n")))
9941 (when (< lines (length slines))
9942 (setq s (mapconcat
9943 'identity
9944 (reverse (nthcdr (- (length slines) lines)
9945 (reverse slines))) "\n")))))
9946 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9948 (defun org-make-link-string (link &optional description)
9949 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9950 (unless (string-match "\\S-" link)
9951 (error "Empty link"))
9952 (when (and description
9953 (stringp description)
9954 (not (string-match "\\S-" description)))
9955 (setq description nil))
9956 (when (stringp description)
9957 ;; Remove brackets from the description, they are fatal.
9958 (while (string-match "\\[" description)
9959 (setq description (replace-match "{" t t description)))
9960 (while (string-match "\\]" description)
9961 (setq description (replace-match "}" t t description))))
9962 (when (equal link description)
9963 ;; No description needed, it is identical
9964 (setq description nil))
9965 (when (and (not description)
9966 (not (string-match (org-image-file-name-regexp) link))
9967 (not (equal link (org-link-escape link))))
9968 (setq description (org-extract-attributes link)))
9969 (setq link
9970 (cond ((string-match (org-image-file-name-regexp) link) link)
9971 ((string-match org-link-types-re link)
9972 (concat (match-string 1 link)
9973 (org-link-escape (substring link (match-end 1)))))
9974 (t (org-link-escape link))))
9975 (concat "[[" link "]"
9976 (if description (concat "[" description "]") "")
9977 "]"))
9979 (defconst org-link-escape-chars
9980 ;;%20 %5B %5D
9981 '(?\ ?\[ ?\])
9982 "List of characters that should be escaped in a link when stored to Org.
9983 This is the list that is used for internal purposes.")
9985 (defconst org-link-escape-chars-browser
9986 ;;%20 %22
9987 '(?\ ?\")
9988 "List of characters to be escaped before handing over to the browser.
9989 If you consider using this constant then you probably want to use
9990 the function `org-link-escape-browser' instead. See there why
9991 this constant is a candidate to be removed once Org drops support
9992 for Emacs 24.1 and 24.2.")
9994 (defun org-link-escape (text &optional table merge)
9995 "Return percent escaped representation of TEXT.
9996 TEXT is a string with the text to escape.
9997 Optional argument TABLE is a list with characters that should be
9998 escaped. When nil, `org-link-escape-chars' is used.
9999 If optional argument MERGE is set, merge TABLE into
10000 `org-link-escape-chars'."
10001 ;; Don't escape chars in internal links
10002 (if (string-match "^\\*[[:alnum:]]+" text)
10003 text
10004 (cond
10005 ((and table merge)
10006 (mapc (lambda (defchr)
10007 (unless (member defchr table)
10008 (setq table (cons defchr table))))
10009 org-link-escape-chars))
10010 ((null table)
10011 (setq table org-link-escape-chars)))
10012 (mapconcat
10013 (lambda (char)
10014 (if (or (member char table)
10015 (and (or (< char 32) (= char ?\%) (> char 126))
10016 org-url-hexify-p))
10017 (mapconcat (lambda (sequence-element)
10018 (format "%%%.2X" sequence-element))
10019 (or (encode-coding-char char 'utf-8)
10020 (error "Unable to percent escape character: %s"
10021 (char-to-string char))) "")
10022 (char-to-string char))) text "")))
10024 (defun org-link-escape-browser (text)
10025 "Escape some characters before handing over to the browser.
10026 This function is a candidate to be removed together with the
10027 constant `org-link-escape-chars-browser' once Org drops support
10028 for Emacs 24.1 and 24.2. All calls to this function will have to
10029 be replaced with `url-encode-url' which is available since Emacs
10030 24.3.1."
10031 ;; Example with the Org link
10032 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10033 ;; to open the browser with +subject:"Release 8.2" filled into the
10034 ;; query field: In this case the variable TEXT contains the
10035 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10036 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10037 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10038 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10039 (if (fboundp 'url-encode-url)
10040 (url-encode-url text)
10041 (if (org-string-match-p
10042 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10043 text)
10044 (org-link-escape text org-link-escape-chars-browser)
10045 text)))
10047 (defun org-link-unescape (str)
10048 "Unhex hexified Unicode strings as returned from the JavaScript function
10049 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10050 (unless (and (null str) (string= "" str))
10051 (let ((pos 0) (case-fold-search t) unhexed)
10052 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10053 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10054 (setq str (replace-match unhexed t t str))
10055 (setq pos (+ pos (length unhexed))))))
10056 str)
10058 (defun org-link-unescape-compound (hex)
10059 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10060 Note: this function also decodes single byte encodings like
10061 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10062 (save-match-data
10063 (let* ((bytes (cdr (split-string hex "%")))
10064 (ret "")
10065 (eat 0)
10066 (sum 0))
10067 (while bytes
10068 (let* ((val (string-to-number (pop bytes) 16))
10069 (shift-xor
10070 (if (= 0 eat)
10071 (cond
10072 ((>= val 252) (cons 6 252))
10073 ((>= val 248) (cons 5 248))
10074 ((>= val 240) (cons 4 240))
10075 ((>= val 224) (cons 3 224))
10076 ((>= val 192) (cons 2 192))
10077 (t (cons 0 0)))
10078 (cons 6 128))))
10079 (if (>= val 192) (setq eat (car shift-xor)))
10080 (setq val (logxor val (cdr shift-xor)))
10081 (setq sum (+ (lsh sum (car shift-xor)) val))
10082 (if (> eat 0) (setq eat (- eat 1)))
10083 (cond
10084 ((= 0 eat) ;multi byte
10085 (setq ret (concat ret (org-char-to-string sum)))
10086 (setq sum 0))
10087 ((not bytes) ; single byte(s)
10088 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10089 ret)))
10091 (defun org-link-unescape-single-byte-sequence (hex)
10092 "Unhexify hex-encoded single byte character sequences."
10093 (mapconcat (lambda (byte)
10094 (char-to-string (string-to-number byte 16)))
10095 (cdr (split-string hex "%")) ""))
10097 (defun org-xor (a b)
10098 "Exclusive or."
10099 (if a (not b) b))
10101 (defun org-fixup-message-id-for-http (s)
10102 "Replace special characters in a message id, so it can be used in an http query."
10103 (when (string-match "%" s)
10104 (setq s (mapconcat (lambda (c)
10105 (if (eq c ?%)
10106 "%25"
10107 (char-to-string c)))
10108 s "")))
10109 (while (string-match "<" s)
10110 (setq s (replace-match "%3C" t t s)))
10111 (while (string-match ">" s)
10112 (setq s (replace-match "%3E" t t s)))
10113 (while (string-match "@" s)
10114 (setq s (replace-match "%40" t t s)))
10117 (defun org-link-prettify (link)
10118 "Return a human-readable representation of LINK.
10119 The car of LINK must be a raw link.
10120 The cdr of LINK must be either a link description or nil."
10121 (let ((desc (or (cadr link) "<no description>")))
10122 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10123 "<" (car link) ">")))
10125 ;;;###autoload
10126 (defun org-insert-link-global ()
10127 "Insert a link like Org-mode does.
10128 This command can be called in any mode to insert a link in Org-mode syntax."
10129 (interactive)
10130 (org-load-modules-maybe)
10131 (org-run-like-in-org-mode 'org-insert-link))
10133 (defun org-insert-all-links (arg &optional pre post)
10134 "Insert all links in `org-stored-links'.
10135 When a universal prefix, do not delete the links from `org-stored-links'.
10136 When `ARG' is a number, insert the last N link(s).
10137 `PRE' and `POST' are optional arguments to define a string to
10138 prepend or to append."
10139 (interactive "P")
10140 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10141 (links (copy-seq org-stored-links))
10142 (pr (or pre "- "))
10143 (po (or post "\n"))
10144 (cnt 1) l)
10145 (if (null org-stored-links)
10146 (message "No link to insert")
10147 (while (and (or (listp arg) (>= arg cnt))
10148 (setq l (if (listp arg)
10149 (pop links)
10150 (pop org-stored-links))))
10151 (setq cnt (1+ cnt))
10152 (insert pr)
10153 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10154 (insert po)))))
10156 (defun org-insert-last-stored-link (arg)
10157 "Insert the last link stored in `org-stored-links'."
10158 (interactive "p")
10159 (org-insert-all-links arg "" "\n"))
10161 (defun org-link-fontify-links-to-this-file ()
10162 "Fontify links to the current file in `org-stored-links'."
10163 (let ((f (buffer-file-name)) a b)
10164 (setq a (mapcar (lambda(l)
10165 (let ((ll (car l)))
10166 (when (and (string-match "^file:\\(.+\\)::" ll)
10167 (equal f (expand-file-name (match-string 1 ll))))
10168 ll)))
10169 org-stored-links))
10170 (when (featurep 'org-id)
10171 (setq b (mapcar (lambda(l)
10172 (let ((ll (car l)))
10173 (when (and (string-match "^id:\\(.+\\)$" ll)
10174 (equal f (expand-file-name
10175 (or (org-id-find-id-file
10176 (match-string 1 ll)) ""))))
10177 ll)))
10178 org-stored-links)))
10179 (mapcar (lambda(l)
10180 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10181 (delq nil (append a b)))))
10183 (defvar org-link-links-in-this-file nil)
10184 (defun org-insert-link (&optional complete-file link-location default-description)
10185 "Insert a link. At the prompt, enter the link.
10187 Completion can be used to insert any of the link protocol prefixes like
10188 http or ftp in use.
10190 The history can be used to select a link previously stored with
10191 `org-store-link'. When the empty string is entered (i.e. if you just
10192 press RET at the prompt), the link defaults to the most recently
10193 stored link. As SPC triggers completion in the minibuffer, you need to
10194 use M-SPC or C-q SPC to force the insertion of a space character.
10196 You will also be prompted for a description, and if one is given, it will
10197 be displayed in the buffer instead of the link.
10199 If there is already a link at point, this command will allow you to edit link
10200 and description parts.
10202 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10203 be selected using completion. The path to the file will be relative to the
10204 current directory if the file is in the current directory or a subdirectory.
10205 Otherwise, the link will be the absolute path as completed in the minibuffer
10206 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10207 option `org-link-file-path-type'.
10209 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10210 the current directory or below.
10212 With three \\[universal-argument] prefixes, negate the meaning of
10213 `org-keep-stored-link-after-insertion'.
10215 If `org-make-link-description-function' is non-nil, this function will be
10216 called with the link target, and the result will be the default
10217 link description.
10219 If the LINK-LOCATION parameter is non-nil, this value will be
10220 used as the link location instead of reading one interactively.
10222 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10223 be used as the default description."
10224 (interactive "P")
10225 (let* ((wcf (current-window-configuration))
10226 (origbuf (current-buffer))
10227 (region (if (org-region-active-p)
10228 (buffer-substring (region-beginning) (region-end))))
10229 (remove (and region (list (region-beginning) (region-end))))
10230 (desc region)
10231 tmphist ; byte-compile incorrectly complains about this
10232 (link link-location)
10233 (abbrevs org-link-abbrev-alist-local)
10234 entry file all-prefixes auto-desc)
10235 (cond
10236 (link-location) ; specified by arg, just use it.
10237 ((org-in-regexp org-bracket-link-regexp 1)
10238 ;; We do have a link at point, and we are going to edit it.
10239 (setq remove (list (match-beginning 0) (match-end 0)))
10240 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10241 (setq link (read-string "Link: "
10242 (org-link-unescape
10243 (org-match-string-no-properties 1)))))
10244 ((or (org-in-regexp org-angle-link-re)
10245 (org-in-regexp org-plain-link-re))
10246 ;; Convert to bracket link
10247 (setq remove (list (match-beginning 0) (match-end 0))
10248 link (read-string "Link: "
10249 (org-remove-angle-brackets (match-string 0)))))
10250 ((member complete-file '((4) (16)))
10251 ;; Completing read for file names.
10252 (setq link (org-file-complete-link complete-file)))
10254 ;; Read link, with completion for stored links.
10255 (org-link-fontify-links-to-this-file)
10256 (org-switch-to-buffer-other-window "*Org Links*")
10257 (with-current-buffer "*Org Links*"
10258 (erase-buffer)
10259 (insert "Insert a link.
10260 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10261 (when org-stored-links
10262 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10263 (insert (mapconcat 'org-link-prettify
10264 (reverse org-stored-links) "\n")))
10265 (goto-char (point-min)))
10266 (let ((cw (selected-window)))
10267 (select-window (get-buffer-window "*Org Links*" 'visible))
10268 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10269 (unless (pos-visible-in-window-p (point-max))
10270 (org-fit-window-to-buffer))
10271 (and (window-live-p cw) (select-window cw)))
10272 ;; Fake a link history, containing the stored links.
10273 (setq tmphist (append (mapcar 'car org-stored-links)
10274 org-insert-link-history))
10275 (setq all-prefixes (append (mapcar 'car abbrevs)
10276 (mapcar 'car org-link-abbrev-alist)
10277 org-link-types))
10278 (unwind-protect
10279 (progn
10280 (setq link
10281 (org-completing-read
10282 "Link: "
10283 (append
10284 (mapcar (lambda (x) (concat x ":"))
10285 all-prefixes)
10286 (mapcar 'car org-stored-links))
10287 nil nil nil
10288 'tmphist
10289 (caar org-stored-links)))
10290 (if (not (string-match "\\S-" link))
10291 (user-error "No link selected"))
10292 (mapc (lambda(l)
10293 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10294 org-stored-links)
10295 (if (or (member link all-prefixes)
10296 (and (equal ":" (substring link -1))
10297 (member (substring link 0 -1) all-prefixes)
10298 (setq link (substring link 0 -1))))
10299 (setq link (with-current-buffer origbuf
10300 (org-link-try-special-completion link)))))
10301 (set-window-configuration wcf)
10302 (kill-buffer "*Org Links*"))
10303 (setq entry (assoc link org-stored-links))
10304 (or entry (push link org-insert-link-history))
10305 (setq desc (or desc (nth 1 entry)))))
10307 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10308 (not org-keep-stored-link-after-insertion))
10309 (setq org-stored-links (delq (assoc link org-stored-links)
10310 org-stored-links)))
10312 (if (and (string-match org-plain-link-re link)
10313 (not (string-match org-ts-regexp link)))
10314 ;; URL-like link, normalize the use of angular brackets.
10315 (setq link (org-remove-angle-brackets link)))
10317 ;; Check if we are linking to the current file with a search
10318 ;; option If yes, simplify the link by using only the search
10319 ;; option.
10320 (when (and buffer-file-name
10321 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10322 (let* ((path (match-string 1 link))
10323 (case-fold-search nil)
10324 (search (match-string 2 link)))
10325 (save-match-data
10326 (if (equal (file-truename buffer-file-name) (file-truename path))
10327 ;; We are linking to this same file, with a search option
10328 (setq link search)))))
10330 ;; Check if we can/should use a relative path. If yes, simplify the link
10331 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10332 (let* ((type (match-string 1 link))
10333 (path (match-string 2 link))
10334 (origpath path)
10335 (case-fold-search nil))
10336 (cond
10337 ((or (eq org-link-file-path-type 'absolute)
10338 (equal complete-file '(16)))
10339 (setq path (abbreviate-file-name (expand-file-name path))))
10340 ((eq org-link-file-path-type 'noabbrev)
10341 (setq path (expand-file-name path)))
10342 ((eq org-link-file-path-type 'relative)
10343 (setq path (file-relative-name path)))
10345 (save-match-data
10346 (if (string-match (concat "^" (regexp-quote
10347 (expand-file-name
10348 (file-name-as-directory
10349 default-directory))))
10350 (expand-file-name path))
10351 ;; We are linking a file with relative path name.
10352 (setq path (substring (expand-file-name path)
10353 (match-end 0)))
10354 (setq path (abbreviate-file-name (expand-file-name path)))))))
10355 (setq link (concat type path))
10356 (if (equal desc origpath)
10357 (setq desc path))))
10359 (if org-make-link-description-function
10360 (setq desc
10361 (or (condition-case nil
10362 (funcall org-make-link-description-function link desc)
10363 (error (progn (message "Can't get link description from `%s'"
10364 (symbol-name org-make-link-description-function))
10365 (sit-for 2) nil)))
10366 (read-string "Description: " default-description)))
10367 (if default-description (setq desc default-description)
10368 (setq desc (or (and auto-desc desc)
10369 (read-string "Description: " desc)))))
10371 (unless (string-match "\\S-" desc) (setq desc nil))
10372 (if remove (apply 'delete-region remove))
10373 (insert (org-make-link-string link desc))))
10375 (defun org-link-try-special-completion (type)
10376 "If there is completion support for link type TYPE, offer it."
10377 (let ((fun (intern (concat "org-" type "-complete-link"))))
10378 (if (functionp fun)
10379 (funcall fun)
10380 (read-string "Link (no completion support): " (concat type ":")))))
10382 (defun org-file-complete-link (&optional arg)
10383 "Create a file link using completion."
10384 (let (file link)
10385 (setq file (org-iread-file-name "File: "))
10386 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10387 (pwd1 (file-name-as-directory (abbreviate-file-name
10388 (expand-file-name ".")))))
10389 (cond
10390 ((equal arg '(16))
10391 (setq link (concat
10392 "file:"
10393 (abbreviate-file-name (expand-file-name file)))))
10394 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10395 (setq link (concat "file:" (match-string 1 file))))
10396 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10397 (expand-file-name file))
10398 (setq link (concat
10399 "file:" (match-string 1 (expand-file-name file)))))
10400 (t (setq link (concat "file:" file)))))
10401 link))
10403 (defun org-iread-file-name (&rest args)
10404 "Read-file-name using `ido-mode' speedup if available.
10405 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10406 See `read-file-name' for a description of parameters."
10407 (org-without-partial-completion
10408 (if (and org-completion-use-ido
10409 (fboundp 'ido-read-file-name)
10410 (boundp 'ido-mode) ido-mode
10411 (listp (second args)))
10412 (let ((ido-enter-matching-directory nil))
10413 (apply 'ido-read-file-name args))
10414 (apply 'read-file-name args))))
10416 (defun org-completing-read (&rest args)
10417 "Completing-read with SPACE being a normal character."
10418 (let ((enable-recursive-minibuffers t)
10419 (minibuffer-local-completion-map
10420 (copy-keymap minibuffer-local-completion-map)))
10421 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10422 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10423 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10424 (apply 'org-icompleting-read args)))
10426 (defun org-completing-read-no-i (&rest args)
10427 (let (org-completion-use-ido org-completion-use-iswitchb)
10428 (apply 'org-completing-read args)))
10430 (defun org-iswitchb-completing-read (prompt choices &rest args)
10431 "Use iswitch as a completing-read replacement to choose from choices.
10432 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10433 from."
10434 (let* ((iswitchb-use-virtual-buffers nil)
10435 (iswitchb-make-buflist-hook
10436 (lambda ()
10437 (setq iswitchb-temp-buflist choices))))
10438 (iswitchb-read-buffer prompt)))
10440 (defun org-icompleting-read (&rest args)
10441 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10442 (org-without-partial-completion
10443 (if (and org-completion-use-ido
10444 (fboundp 'ido-completing-read)
10445 (boundp 'ido-mode) ido-mode
10446 (listp (second args)))
10447 (let ((ido-enter-matching-directory nil))
10448 (apply 'ido-completing-read (concat (car args))
10449 (if (consp (car (nth 1 args)))
10450 (mapcar 'car (nth 1 args))
10451 (nth 1 args))
10452 (cddr args)))
10453 (if (and org-completion-use-iswitchb
10454 (boundp 'iswitchb-mode) iswitchb-mode
10455 (listp (second args)))
10456 (apply 'org-iswitchb-completing-read (concat (car args))
10457 (if (consp (car (nth 1 args)))
10458 (mapcar 'car (nth 1 args))
10459 (nth 1 args))
10460 (cddr args))
10461 (apply 'completing-read args)))))
10463 (defun org-extract-attributes (s)
10464 "Extract the attributes cookie from a string and set as text property."
10465 (let (a attr (start 0) key value)
10466 (save-match-data
10467 (when (string-match "{{\\([^}]+\\)}}$" s)
10468 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10469 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10470 (setq key (match-string 1 a) value (match-string 2 a)
10471 start (match-end 0)
10472 attr (plist-put attr (intern key) value))))
10473 (org-add-props s nil 'org-attr attr))
10476 ;;; Opening/following a link
10478 (defvar org-link-search-failed nil)
10480 (defvar org-open-link-functions nil
10481 "Hook for functions finding a plain text link.
10482 These functions must take a single argument, the link content.
10483 They will be called for links that look like [[link text][description]]
10484 when LINK TEXT does not have a protocol like \"http:\" and does not look
10485 like a filename (e.g. \"./blue.png\").
10487 These functions will be called *before* Org attempts to resolve the
10488 link by doing text searches in the current buffer - so if you want a
10489 link \"[[target]]\" to still find \"<<target>>\", your function should
10490 handle this as a special case.
10492 When the function does handle the link, it must return a non-nil value.
10493 If it decides that it is not responsible for this link, it must return
10494 nil to indicate that that Org-mode can continue with other options
10495 like exact and fuzzy text search.")
10497 (defun org-next-link (&optional search-backward)
10498 "Move forward to the next link.
10499 If the link is in hidden text, expose it."
10500 (interactive "P")
10501 (when (and org-link-search-failed (eq this-command last-command))
10502 (goto-char (point-min))
10503 (message "Link search wrapped back to beginning of buffer"))
10504 (setq org-link-search-failed nil)
10505 (let* ((pos (point))
10506 (ct (org-context))
10507 (a (assoc :link ct))
10508 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10509 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10510 ((looking-at org-any-link-re)
10511 ;; Don't stay stuck at link without an org-link face
10512 (forward-char (if search-backward -1 1))))
10513 (if (funcall srch-fun org-any-link-re nil t)
10514 (progn
10515 (goto-char (match-beginning 0))
10516 (if (outline-invisible-p) (org-show-context)))
10517 (goto-char pos)
10518 (setq org-link-search-failed t)
10519 (message "No further link found"))))
10521 (defun org-previous-link ()
10522 "Move backward to the previous link.
10523 If the link is in hidden text, expose it."
10524 (interactive)
10525 (funcall 'org-next-link t))
10527 (defun org-translate-link (s)
10528 "Translate a link string if a translation function has been defined."
10529 (if (and org-link-translation-function
10530 (fboundp org-link-translation-function)
10531 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10532 (progn
10533 (setq s (funcall org-link-translation-function
10534 (match-string 1 s) (match-string 2 s)))
10535 (concat (car s) ":" (cdr s)))
10538 (defun org-translate-link-from-planner (type path)
10539 "Translate a link from Emacs Planner syntax so that Org can follow it.
10540 This is still an experimental function, your mileage may vary."
10541 (cond
10542 ((member type '("http" "https" "news" "ftp"))
10543 ;; standard Internet links are the same.
10544 nil)
10545 ((and (equal type "irc") (string-match "^//" path))
10546 ;; Planner has two / at the beginning of an irc link, we have 1.
10547 ;; We should have zero, actually....
10548 (setq path (substring path 1)))
10549 ((and (equal type "lisp") (string-match "^/" path))
10550 ;; Planner has a slash, we do not.
10551 (setq type "elisp" path (substring path 1)))
10552 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10553 ;; A typical message link. Planner has the id after the final slash,
10554 ;; we separate it with a hash mark
10555 (setq path (concat (match-string 1 path) "#"
10556 (org-remove-angle-brackets (match-string 2 path))))))
10557 (cons type path))
10559 (defun org-find-file-at-mouse (ev)
10560 "Open file link or URL at mouse."
10561 (interactive "e")
10562 (mouse-set-point ev)
10563 (org-open-at-point 'in-emacs))
10565 (defun org-open-at-mouse (ev)
10566 "Open file link or URL at mouse.
10567 See the docstring of `org-open-file' for details."
10568 (interactive "e")
10569 (mouse-set-point ev)
10570 (if (eq major-mode 'org-agenda-mode)
10571 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10572 (org-open-at-point))
10574 (defvar org-window-config-before-follow-link nil
10575 "The window configuration before following a link.
10576 This is saved in case the need arises to restore it.")
10578 (defvar org-open-link-marker (make-marker)
10579 "Marker pointing to the location where `org-open-at-point' was called.")
10581 ;;;###autoload
10582 (defun org-open-at-point-global ()
10583 "Follow a link like Org-mode does.
10584 This command can be called in any mode to follow a link that has
10585 Org-mode syntax."
10586 (interactive)
10587 (org-run-like-in-org-mode 'org-open-at-point))
10589 ;;;###autoload
10590 (defun org-open-link-from-string (s &optional arg reference-buffer)
10591 "Open a link in the string S, as if it was in Org-mode."
10592 (interactive "sLink: \nP")
10593 (let ((reference-buffer (or reference-buffer (current-buffer))))
10594 (with-temp-buffer
10595 (let ((org-inhibit-startup (not reference-buffer)))
10596 (org-mode)
10597 (insert s)
10598 (goto-char (point-min))
10599 (when reference-buffer
10600 (setq org-link-abbrev-alist-local
10601 (with-current-buffer reference-buffer
10602 org-link-abbrev-alist-local)))
10603 (org-open-at-point arg reference-buffer)))))
10605 (defvar org-open-at-point-functions nil
10606 "Hook that is run when following a link at point.
10608 Functions in this hook must return t if they identify and follow
10609 a link at point. If they don't find anything interesting at point,
10610 they must return nil.")
10612 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10613 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10614 (defun org-open-at-point (&optional arg reference-buffer)
10615 "Open link, timestamp, footnote or tags at point.
10617 When point is on a link, follow it. Normally, files will be
10618 opened by an appropriate application. If the optional prefix
10619 argument ARG is non-nil, Emacs will visit the file. With
10620 a double prefix argument, try to open outside of Emacs, in the
10621 application the system uses for this file type.
10623 When point is on a timestamp, open the agenda at the day
10624 specified.
10626 When point is a footnote definition, move to the first reference
10627 found. If it is on a reference, move to the associated
10628 definition.
10630 When point is on a headline, display a list of every link in the
10631 entry, so it is possible to pick one, or all, of them. If point
10632 is on a tag, call `org-tags-view' instead.
10634 When optional argument REFERENCE-BUFFER is non-nil, it should
10635 specify a buffer from where the link search should happen. This
10636 is used internally by `org-open-link-from-string'.
10638 On top of syntactically correct links, this function will open
10639 the link at point in comments or comment blocks and the first
10640 link in a property drawer line."
10641 (interactive "P")
10642 ;; On a code block, open block's results.
10643 (unless (call-interactively 'org-babel-open-src-block-result)
10644 (org-load-modules-maybe)
10645 (move-marker org-open-link-marker (point))
10646 (setq org-window-config-before-follow-link (current-window-configuration))
10647 (org-remove-occur-highlights nil nil t)
10648 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10649 (let* ((context (org-element-context)) type value)
10650 ;; On an unsupported type, check if point is contained within
10651 ;; a support one.
10652 (while (and (not (memq (setq type (org-element-type context))
10653 '(comment comment-block
10654 headline inlinetask link
10655 footnote-definition footnote-reference
10656 node-property timestamp)))
10657 (setq context (org-element-property :parent context))))
10658 (setq value (org-element-property :value context))
10659 (cond
10660 ;; Blank lines at the beginning of buffer: bail out.
10661 ((not context) (user-error "No link found"))
10662 ;; Exception n°1: links in property drawers
10663 ((eq type 'node-property)
10664 (org-open-link-from-string
10665 (and (string-match org-any-link-re value)
10666 (match-string-no-properties 0 value))))
10667 ;; Exception n°2: links in comments.
10668 ((memq type '(comment comment-block))
10669 (save-excursion
10670 (skip-chars-forward "\\S-" (point-at-eol))
10671 (let ((string-rear (replace-regexp-in-string
10672 "^[ \t]*# [ \t]*" ""
10673 (buffer-substring (point) (line-beginning-position))))
10674 (string-front (buffer-substring (point) (line-end-position))))
10675 (with-temp-buffer
10676 (let ((org-inhibit-startup t)) (org-mode))
10677 (insert value)
10678 (goto-char (point-min))
10679 (when (and (search-forward string-rear nil t)
10680 (search-forward string-front (line-end-position) t))
10681 (goto-char (match-beginning 0))
10682 (org-open-at-point)
10683 (when (string= string-rear "") (forward-char)))))))
10684 ;; On a headline or an inlinetask, but not on a timestamp,
10685 ;; a link, a footnote reference or on tags.
10686 ((and (memq type '(headline inlinetask))
10687 ;; Not on tags.
10688 (progn (save-excursion (beginning-of-line)
10689 (looking-at org-complex-heading-regexp))
10690 (or (not (match-beginning 5))
10691 (< (point) (match-beginning 5)))))
10692 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10693 (links (car data))
10694 (links-end (cdr data)))
10695 (if links
10696 (dolist (link (if (stringp links) (list links) links))
10697 (search-forward link nil links-end)
10698 (goto-char (match-beginning 0))
10699 (org-open-at-point))
10700 (require 'org-attach)
10701 (org-attach-reveal 'if-exists))))
10702 ;; Do nothing on white spaces after an object, unless point
10703 ;; is right after it.
10704 ((> (point)
10705 (save-excursion
10706 (goto-char (org-element-property :end context))
10707 (skip-chars-backward " \t")
10708 (point)))
10709 (user-error "No link found"))
10710 ((eq type 'timestamp) (org-follow-timestamp-link))
10711 ;; On tags within a headline or an inlinetask.
10712 ((and (memq type '(headline inlinetask))
10713 (progn (save-excursion (beginning-of-line)
10714 (looking-at org-complex-heading-regexp))
10715 (and (match-beginning 5)
10716 (>= (point) (match-beginning 5)))))
10717 (org-tags-view arg (substring (match-string 5) 0 -1)))
10718 ((eq type 'link)
10719 (let ((type (org-element-property :type context))
10720 (path (org-link-unescape (org-element-property :path context))))
10721 ;; Switch back to REFERENCE-BUFFER needed when called in
10722 ;; a temporary buffer through `org-open-link-from-string'.
10723 (with-current-buffer (or reference-buffer (current-buffer))
10724 (cond
10725 ((equal type "file")
10726 (if (string-match "[*?{]" (file-name-nondirectory path))
10727 (dired path)
10728 ;; Look into `org-link-protocols' in order to find
10729 ;; a DEDICATED-FUNCTION to open file. The function
10730 ;; will be applied on raw link instead of parsed
10731 ;; link due to the limitation in `org-add-link-type'
10732 ;; ("open" function called with a single argument).
10733 ;; If no such function is found, fallback to
10734 ;; `org-open-file'.
10736 ;; Note : "file+emacs" and "file+sys" types are
10737 ;; hard-coded in order to escape the previous
10738 ;; limitation.
10739 (let* ((option (org-element-property :search-option context))
10740 (app (org-element-property :application context))
10741 (dedicated-function
10742 (nth 1 (assoc app org-link-protocols))))
10743 (if dedicated-function
10744 (funcall dedicated-function
10745 (concat path
10746 (and option (concat "::" option))))
10747 (apply 'org-open-file
10748 path
10749 (cond (arg)
10750 ((equal app "emacs") 'emacs)
10751 ((equal app "sys") 'system))
10752 (cond ((not option) nil)
10753 ((org-string-match-p "\\`[0-9]+\\'" option)
10754 (list (string-to-number option)))
10755 (t (list nil
10756 (org-link-unescape option)))))))))
10757 ((assoc type org-link-protocols)
10758 (funcall (nth 1 (assoc type org-link-protocols)) path))
10759 ((equal type "help")
10760 (let ((f-or-v (intern path)))
10761 (cond ((fboundp f-or-v) (describe-function f-or-v))
10762 ((boundp f-or-v) (describe-variable f-or-v))
10763 (t (error "Not a known function or variable")))))
10764 ((member type '("http" "https" "ftp" "mailto" "news"))
10765 (browse-url (org-link-escape-browser (concat type ":" path))))
10766 ((equal type "doi")
10767 (browse-url
10768 (org-link-escape-browser (concat org-doi-server-url path))))
10769 ((equal type "message") (browse-url (concat type ":" path)))
10770 ((equal type "shell")
10771 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10772 (cmd path))
10773 (if (or (and (org-string-nw-p
10774 org-confirm-shell-link-not-regexp)
10775 (string-match
10776 org-confirm-shell-link-not-regexp cmd))
10777 (not org-confirm-shell-link-function)
10778 (funcall org-confirm-shell-link-function
10779 (format "Execute \"%s\" in shell? "
10780 (org-add-props cmd nil
10781 'face 'org-warning))))
10782 (progn
10783 (message "Executing %s" cmd)
10784 (shell-command cmd buf)
10785 (when (featurep 'midnight)
10786 (setq clean-buffer-list-kill-buffer-names
10787 (cons buf
10788 clean-buffer-list-kill-buffer-names))))
10789 (user-error "Abort"))))
10790 ((equal type "elisp")
10791 (let ((cmd path))
10792 (if (or (and (org-string-nw-p
10793 org-confirm-elisp-link-not-regexp)
10794 (org-string-match-p
10795 org-confirm-elisp-link-not-regexp cmd))
10796 (not org-confirm-elisp-link-function)
10797 (funcall org-confirm-elisp-link-function
10798 (format "Execute \"%s\" as elisp? "
10799 (org-add-props cmd nil
10800 'face 'org-warning))))
10801 (message "%s => %s" cmd
10802 (if (eq (string-to-char cmd) ?\()
10803 (eval (read cmd))
10804 (call-interactively (read cmd))))
10805 (user-error "Abort"))))
10806 ((equal type "id")
10807 (require 'ord-id)
10808 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10809 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10810 (unless (run-hook-with-args-until-success
10811 'org-open-link-functions path)
10812 (if (not arg) (org-mark-ring-push)
10813 (switch-to-buffer-other-window
10814 (org-get-buffer-for-internal-link (current-buffer))))
10815 (let ((cmd `(org-link-search
10816 ,(if (member type '("custom-id" "coderef"))
10817 (org-element-property :raw-link context)
10818 path)
10819 ,(cond ((equal arg '(4)) 'occur)
10820 ((equal arg '(16)) 'org-occur))
10821 ,(org-element-property :begin context))))
10822 (condition-case nil
10823 (let ((org-link-search-inhibit-query t))
10824 (eval cmd))
10825 (error (progn (widen) (eval cmd)))))))
10826 (t (browse-url-at-point))))))
10827 ;; On a footnote reference or at a footnote definition's label.
10828 ((or (eq type 'footnote-reference)
10829 (and (eq type 'footnote-definition)
10830 (save-excursion
10831 ;; Do not validate action when point is on the
10832 ;; spaces right after the footnote label, in
10833 ;; order to be on par with behaviour on links.
10834 (skip-chars-forward " \t")
10835 (let ((begin
10836 (org-element-property :contents-begin context)))
10837 (if begin (< (point) begin)
10838 (= (org-element-property :post-affiliated context)
10839 (line-beginning-position)))))))
10840 (org-footnote-action))
10841 (t (user-error "No link found")))))
10842 (move-marker org-open-link-marker nil)
10843 (run-hook-with-args 'org-follow-link-hook)))
10845 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10846 "Offer links in the current entry and return the selected link.
10847 If there is only one link, return it.
10848 If NTH is an integer, return the NTH link found.
10849 If ZERO is a string, check also this string for a link, and if
10850 there is one, return it."
10851 (with-current-buffer buffer
10852 (save-excursion
10853 (save-restriction
10854 (widen)
10855 (goto-char marker)
10856 (let ((cnt ?0)
10857 (in-emacs (if (integerp nth) nil nth))
10858 have-zero end links link c)
10859 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10860 (push (match-string 0 zero) links)
10861 (setq cnt (1- cnt) have-zero t))
10862 (save-excursion
10863 (org-back-to-heading t)
10864 (setq end (save-excursion (outline-next-heading) (point)))
10865 (while (re-search-forward org-any-link-re end t)
10866 (push (match-string 0) links))
10867 (setq links (org-uniquify (reverse links))))
10868 (cond
10869 ((null links)
10870 (message "No links"))
10871 ((equal (length links) 1)
10872 (setq link (car links)))
10873 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10874 (setq link (nth (if have-zero nth (1- nth)) links)))
10875 (t ; we have to select a link
10876 (save-excursion
10877 (save-window-excursion
10878 (delete-other-windows)
10879 (with-output-to-temp-buffer "*Select Link*"
10880 (mapc (lambda (l)
10881 (if (not (string-match org-bracket-link-regexp l))
10882 (princ (format "[%c] %s\n" (incf cnt)
10883 (org-remove-angle-brackets l)))
10884 (if (match-end 3)
10885 (princ (format "[%c] %s (%s)\n" (incf cnt)
10886 (match-string 3 l) (match-string 1 l)))
10887 (princ (format "[%c] %s\n" (incf cnt)
10888 (match-string 1 l))))))
10889 links))
10890 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10891 (message "Select link to open, RET to open all:")
10892 (setq c (read-char-exclusive))
10893 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10894 (when (equal c ?q) (user-error "Abort"))
10895 (if (equal c ?\C-m)
10896 (setq link links)
10897 (setq nth (- c ?0))
10898 (if have-zero (setq nth (1+ nth)))
10899 (unless (and (integerp nth) (>= (length links) nth))
10900 (user-error "Invalid link selection"))
10901 (setq link (nth (1- nth) links)))))
10902 (cons link end))))))
10904 ;; TODO: These functions are deprecated since `org-open-at-point'
10905 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10906 (defun org-open-file-with-system (path)
10907 "Open file at PATH using the system way of opening it."
10908 (org-open-file path 'system))
10909 (defun org-open-file-with-emacs (path)
10910 "Open file at PATH in Emacs."
10911 (org-open-file path 'emacs))
10914 ;;; File search
10916 (defvar org-create-file-search-functions nil
10917 "List of functions to construct the right search string for a file link.
10918 These functions are called in turn with point at the location to
10919 which the link should point.
10921 A function in the hook should first test if it would like to
10922 handle this file type, for example by checking the `major-mode'
10923 or the file extension. If it decides not to handle this file, it
10924 should just return nil to give other functions a chance. If it
10925 does handle the file, it must return the search string to be used
10926 when following the link. The search string will be part of the
10927 file link, given after a double colon, and `org-open-at-point'
10928 will automatically search for it. If special measures must be
10929 taken to make the search successful, another function should be
10930 added to the companion hook `org-execute-file-search-functions',
10931 which see.
10933 A function in this hook may also use `setq' to set the variable
10934 `description' to provide a suggestion for the descriptive text to
10935 be used for this link when it gets inserted into an Org-mode
10936 buffer with \\[org-insert-link].")
10938 (defvar org-execute-file-search-functions nil
10939 "List of functions to execute a file search triggered by a link.
10941 Functions added to this hook must accept a single argument, the
10942 search string that was part of the file link, the part after the
10943 double colon. The function must first check if it would like to
10944 handle this search, for example by checking the `major-mode' or
10945 the file extension. If it decides not to handle this search, it
10946 should just return nil to give other functions a chance. If it
10947 does handle the search, it must return a non-nil value to keep
10948 other functions from trying.
10950 Each function can access the current prefix argument through the
10951 variable `current-prefix-arg'. Note that a single prefix is used
10952 to force opening a link in Emacs, so it may be good to only use a
10953 numeric or double prefix to guide the search function.
10955 In case this is needed, a function in this hook can also restore
10956 the window configuration before `org-open-at-point' was called using:
10958 (set-window-configuration org-window-config-before-follow-link)")
10960 (defun org-link-search (s &optional type avoid-pos stealth)
10961 "Search for a link search option.
10962 If S is surrounded by forward slashes, it is interpreted as a
10963 regular expression. In org-mode files, this will create an `org-occur'
10964 sparse tree. In ordinary files, `occur' will be used to list matches.
10965 If the current buffer is in `dired-mode', grep will be used to search
10966 in all files. If AVOID-POS is given, ignore matches near that position.
10968 When optional argument STEALTH is non-nil, do not modify
10969 visibility around point, thus ignoring
10970 `org-show-hierarchy-above', `org-show-following-heading' and
10971 `org-show-siblings' variables."
10972 (let ((case-fold-search t)
10973 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10974 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10975 (append '(("") (" ") ("\t") ("\n"))
10976 org-emphasis-alist)
10977 "\\|") "\\)"))
10978 (pos (point))
10979 (pre nil) (post nil)
10980 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10981 (cond
10982 ;; First check if there are any special search functions
10983 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10984 ;; Now try the builtin stuff
10985 ((and (equal (string-to-char s0) ?#)
10986 (> (length s0) 1)
10987 (save-excursion
10988 (goto-char (point-min))
10989 (and
10990 (re-search-forward
10991 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10992 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10993 (setq type 'dedicated
10994 pos (match-beginning 0))))
10995 ;; There is an exact target for this
10996 (goto-char pos)
10997 (org-back-to-heading t)))
10998 ((save-excursion
10999 (goto-char (point-min))
11000 (and
11001 (re-search-forward
11002 (concat "<<" (regexp-quote s0) ">>") nil t)
11003 (setq type 'dedicated
11004 pos (match-beginning 0))))
11005 ;; There is an exact target for this
11006 (goto-char pos))
11007 ((save-excursion
11008 (goto-char (point-min))
11009 (and
11010 (re-search-forward
11011 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11012 (setq type 'dedicated pos (match-beginning 0))))
11013 ;; Found an element with a matching #+name affiliated keyword.
11014 (goto-char pos))
11015 ((and (string-match "^(\\(.*\\))$" s0)
11016 (save-excursion
11017 (goto-char (point-min))
11018 (and
11019 (re-search-forward
11020 (concat "[^[]" (regexp-quote
11021 (format org-coderef-label-format
11022 (match-string 1 s0))))
11023 nil t)
11024 (setq type 'dedicated
11025 pos (1+ (match-beginning 0))))))
11026 ;; There is a coderef target for this
11027 (goto-char pos))
11028 ((string-match "^/\\(.*\\)/$" s)
11029 ;; A regular expression
11030 (cond
11031 ((derived-mode-p 'org-mode)
11032 (org-occur (match-string 1 s)))
11033 (t (org-do-occur (match-string 1 s)))))
11034 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11035 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11036 (goto-char (point-min))
11037 (cond
11038 ((let (case-fold-search)
11039 (re-search-forward (format org-complex-heading-regexp-format
11040 (regexp-quote s))
11041 nil t))
11042 ;; OK, found a match
11043 (setq type 'dedicated)
11044 (goto-char (match-beginning 0)))
11045 ((and (not org-link-search-inhibit-query)
11046 (eq org-link-search-must-match-exact-headline 'query-to-create)
11047 (y-or-n-p "No match - create this as a new heading? "))
11048 (goto-char (point-max))
11049 (or (bolp) (newline))
11050 (insert "* " s "\n")
11051 (beginning-of-line 0))
11053 (goto-char pos)
11054 (error "No match"))))
11056 ;; A normal search string
11057 (when (equal (string-to-char s) ?*)
11058 ;; Anchor on headlines, post may include tags.
11059 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11060 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11061 s (substring s 1)))
11062 (remove-text-properties
11063 0 (length s)
11064 '(face nil mouse-face nil keymap nil fontified nil) s)
11065 ;; Make a series of regular expressions to find a match
11066 (setq words (org-split-string s "[ \n\r\t]+")
11068 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11069 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11070 "\\)" markers)
11071 re2a_ (concat "\\(" (mapconcat 'downcase words
11072 "[ \t\r\n]+") "\\)[ \t\r\n]")
11073 re2a (concat "[ \t\r\n]" re2a_)
11074 re4_ (concat "\\(" (mapconcat 'downcase words
11075 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11076 re4 (concat "[^a-zA-Z_]" re4_)
11078 re1 (concat pre re2 post)
11079 re3 (concat pre (if pre re4_ re4) post)
11080 re5 (concat pre ".*" re4)
11081 re2 (concat pre re2)
11082 re2a (concat pre (if pre re2a_ re2a))
11083 re4 (concat pre (if pre re4_ re4))
11084 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11085 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11086 re5 "\\)"))
11087 (cond
11088 ((eq type 'org-occur) (org-occur reall))
11089 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11090 (t (goto-char (point-min))
11091 (setq type 'fuzzy)
11092 (if (or (and (org-search-not-self 1 re0 nil t)
11093 (setq type 'dedicated))
11094 (org-search-not-self 1 re1 nil t)
11095 (org-search-not-self 1 re2 nil t)
11096 (org-search-not-self 1 re2a nil t)
11097 (org-search-not-self 1 re3 nil t)
11098 (org-search-not-self 1 re4 nil t)
11099 (org-search-not-self 1 re5 nil t))
11100 (goto-char (match-beginning 1))
11101 (goto-char pos)
11102 (error "No match"))))))
11103 (and (derived-mode-p 'org-mode)
11104 (not stealth)
11105 (org-show-context 'link-search))
11106 type))
11108 (defun org-search-not-self (group &rest args)
11109 "Execute `re-search-forward', but only accept matches that do not
11110 enclose the position of `org-open-link-marker'."
11111 (let ((m org-open-link-marker))
11112 (catch 'exit
11113 (while (apply 're-search-forward args)
11114 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11115 (goto-char (match-end group))
11116 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11117 (> (match-beginning 0) (marker-position m))
11118 (< (match-end 0) (marker-position m)))
11119 (save-match-data
11120 (or (not (org-in-regexp
11121 org-bracket-link-analytic-regexp 1))
11122 (not (match-end 4)) ; no description
11123 (and (<= (match-beginning 4) (point))
11124 (>= (match-end 4) (point))))))
11125 (throw 'exit (point))))))))
11127 (defun org-get-buffer-for-internal-link (buffer)
11128 "Return a buffer to be used for displaying the link target of internal links."
11129 (cond
11130 ((not org-display-internal-link-with-indirect-buffer)
11131 buffer)
11132 ((string-match "(Clone)$" (buffer-name buffer))
11133 (message "Buffer is already a clone, not making another one")
11134 ;; we also do not modify visibility in this case
11135 buffer)
11136 (t ; make a new indirect buffer for displaying the link
11137 (let* ((bn (buffer-name buffer))
11138 (ibn (concat bn "(Clone)"))
11139 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11140 (with-current-buffer ib (org-overview))
11141 ib))))
11143 (defun org-do-occur (regexp &optional cleanup)
11144 "Call the Emacs command `occur'.
11145 If CLEANUP is non-nil, remove the printout of the regular expression
11146 in the *Occur* buffer. This is useful if the regex is long and not useful
11147 to read."
11148 (occur regexp)
11149 (when cleanup
11150 (let ((cwin (selected-window)) win beg end)
11151 (when (setq win (get-buffer-window "*Occur*"))
11152 (select-window win))
11153 (goto-char (point-min))
11154 (when (re-search-forward "match[a-z]+" nil t)
11155 (setq beg (match-end 0))
11156 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11157 (setq end (1- (match-beginning 0)))))
11158 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11159 (goto-char (point-min))
11160 (select-window cwin))))
11162 ;;; The mark ring for links jumps
11164 (defvar org-mark-ring nil
11165 "Mark ring for positions before jumps in Org-mode.")
11166 (defvar org-mark-ring-last-goto nil
11167 "Last position in the mark ring used to go back.")
11168 ;; Fill and close the ring
11169 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11170 (loop for i from 1 to org-mark-ring-length do
11171 (push (make-marker) org-mark-ring))
11172 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11173 org-mark-ring)
11175 (defun org-mark-ring-push (&optional pos buffer)
11176 "Put the current position or POS into the mark ring and rotate it."
11177 (interactive)
11178 (setq pos (or pos (point)))
11179 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11180 (move-marker (car org-mark-ring)
11181 (or pos (point))
11182 (or buffer (current-buffer)))
11183 (message "%s"
11184 (substitute-command-keys
11185 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11187 (defun org-mark-ring-goto (&optional n)
11188 "Jump to the previous position in the mark ring.
11189 With prefix arg N, jump back that many stored positions. When
11190 called several times in succession, walk through the entire ring.
11191 Org-mode commands jumping to a different position in the current file,
11192 or to another Org-mode file, automatically push the old position
11193 onto the ring."
11194 (interactive "p")
11195 (let (p m)
11196 (if (eq last-command this-command)
11197 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11198 (setq p org-mark-ring))
11199 (setq org-mark-ring-last-goto p)
11200 (setq m (car p))
11201 (org-pop-to-buffer-same-window (marker-buffer m))
11202 (goto-char m)
11203 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11205 (defun org-remove-angle-brackets (s)
11206 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11207 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11209 (defun org-add-angle-brackets (s)
11210 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11211 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11213 (defun org-remove-double-quotes (s)
11214 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11215 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11218 ;;; Following specific links
11220 (defun org-follow-timestamp-link ()
11221 "Open an agenda view for the time-stamp date/range at point."
11222 (cond
11223 ((org-at-date-range-p t)
11224 (let ((org-agenda-start-on-weekday)
11225 (t1 (match-string 1))
11226 (t2 (match-string 2)) tt1 tt2)
11227 (setq tt1 (time-to-days (org-time-string-to-time t1))
11228 tt2 (time-to-days (org-time-string-to-time t2)))
11229 (let ((org-agenda-buffer-tmp-name
11230 (format "*Org Agenda(a:%s)"
11231 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11232 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11233 ((org-at-timestamp-p t)
11234 (let ((org-agenda-buffer-tmp-name
11235 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11236 (org-agenda-list nil (time-to-days (org-time-string-to-time
11237 (substring (match-string 1) 0 10)))
11238 1)))
11239 (t (error "This should not happen"))))
11242 ;;; Following file links
11243 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11244 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11245 (declare-function mailcap-mime-info
11246 "mailcap" (string &optional request no-decode))
11247 (defvar org-wait nil)
11248 (defun org-open-file (path &optional in-emacs line search)
11249 "Open the file at PATH.
11250 First, this expands any special file name abbreviations. Then the
11251 configuration variable `org-file-apps' is checked if it contains an
11252 entry for this file type, and if yes, the corresponding command is launched.
11254 If no application is found, Emacs simply visits the file.
11256 With optional prefix argument IN-EMACS, Emacs will visit the file.
11257 With a double \\[universal-argument] \\[universal-argument] \
11258 prefix arg, Org tries to avoid opening in Emacs
11259 and to use an external application to visit the file.
11261 Optional LINE specifies a line to go to, optional SEARCH a string
11262 to search for. If LINE or SEARCH is given, the file will be
11263 opened in Emacs, unless an entry from org-file-apps that makes
11264 use of groups in a regexp matches.
11266 If you want to change the way frames are used when following a
11267 link, please customize `org-link-frame-setup'.
11269 If the file does not exist, an error is thrown."
11270 (let* ((file (if (equal path "")
11271 buffer-file-name
11272 (substitute-in-file-name (expand-file-name path))))
11273 (file-apps (append org-file-apps (org-default-apps)))
11274 (apps (org-remove-if
11275 'org-file-apps-entry-match-against-dlink-p file-apps))
11276 (apps-dlink (org-remove-if-not
11277 'org-file-apps-entry-match-against-dlink-p file-apps))
11278 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11279 (dirp (if remp nil (file-directory-p file)))
11280 (file (if (and dirp org-open-directory-means-index-dot-org)
11281 (concat (file-name-as-directory file) "index.org")
11282 file))
11283 (a-m-a-p (assq 'auto-mode apps))
11284 (dfile (downcase file))
11285 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11286 (link (cond ((and (eq line nil)
11287 (eq search nil))
11288 file)
11289 (line
11290 (concat file "::" (number-to-string line)))
11291 (search
11292 (concat file "::" search))))
11293 (dlink (downcase link))
11294 (old-buffer (current-buffer))
11295 (old-pos (point))
11296 (old-mode major-mode)
11297 ext cmd link-match-data)
11298 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11299 (setq ext (match-string 1 dfile))
11300 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11301 (setq ext (match-string 1 dfile))))
11302 (cond
11303 ((member in-emacs '((16) system))
11304 (setq cmd (cdr (assoc 'system apps))))
11305 (in-emacs (setq cmd 'emacs))
11307 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11308 (and dirp (cdr (assoc 'directory apps)))
11309 ; first, try matching against apps-dlink
11310 ; if we get a match here, store the match data for later
11311 (let ((match (assoc-default dlink apps-dlink
11312 'string-match)))
11313 (if match
11314 (progn (setq link-match-data (match-data))
11315 match)
11316 (progn (setq in-emacs (or in-emacs line search))
11317 nil))) ; if we have no match in apps-dlink,
11318 ; always open the file in emacs if line or search
11319 ; is given (for backwards compatibility)
11320 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11321 'string-match)
11322 (cdr (assoc ext apps))
11323 (cdr (assoc t apps))))))
11324 (when (eq cmd 'system)
11325 (setq cmd (cdr (assoc 'system apps))))
11326 (when (eq cmd 'default)
11327 (setq cmd (cdr (assoc t apps))))
11328 (when (eq cmd 'mailcap)
11329 (require 'mailcap)
11330 (mailcap-parse-mailcaps)
11331 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11332 (command (mailcap-mime-info mime-type)))
11333 (if (stringp command)
11334 (setq cmd command)
11335 (setq cmd 'emacs))))
11336 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11337 (not (file-exists-p file))
11338 (not org-open-non-existing-files))
11339 (user-error "No such file: %s" file))
11340 (cond
11341 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11342 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11343 (while (string-match "['\"]%s['\"]" cmd)
11344 (setq cmd (replace-match "%s" t t cmd)))
11345 (while (string-match "%s" cmd)
11346 (setq cmd (replace-match
11347 (save-match-data
11348 (shell-quote-argument
11349 (convert-standard-filename file)))
11350 t t cmd)))
11352 ;; Replace "%1", "%2" etc. in command with group matches from regex
11353 (save-match-data
11354 (let ((match-index 1)
11355 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11356 (set-match-data link-match-data)
11357 (while (<= match-index number-of-groups)
11358 (let ((regex (concat "%" (number-to-string match-index)))
11359 (replace-with (match-string match-index dlink)))
11360 (while (string-match regex cmd)
11361 (setq cmd (replace-match replace-with t t cmd))))
11362 (setq match-index (+ match-index 1)))))
11364 (save-window-excursion
11365 (message "Running %s...done" cmd)
11366 (start-process-shell-command cmd nil cmd)
11367 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11368 ((or (stringp cmd)
11369 (eq cmd 'emacs))
11370 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11371 (widen)
11372 (if line (progn (org-goto-line line)
11373 (if (derived-mode-p 'org-mode)
11374 (org-reveal)))
11375 (if search (org-link-search search))))
11376 ((consp cmd)
11377 (let ((file (convert-standard-filename file)))
11378 (save-match-data
11379 (set-match-data link-match-data)
11380 (eval cmd))))
11381 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11382 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11383 (or (not (equal old-buffer (current-buffer)))
11384 (not (equal old-pos (point))))
11385 (org-mark-ring-push old-pos old-buffer))))
11387 (defun org-file-apps-entry-match-against-dlink-p (entry)
11388 "This function returns non-nil if `entry' uses a regular
11389 expression which should be matched against the whole link by
11390 org-open-file.
11392 It assumes that is the case when the entry uses a regular
11393 expression which has at least one grouping construct and the
11394 action is either a lisp form or a command string containing
11395 '%1', i.e. using at least one subexpression match as a
11396 parameter."
11397 (let ((selector (car entry))
11398 (action (cdr entry)))
11399 (if (stringp selector)
11400 (and (> (regexp-opt-depth selector) 0)
11401 (or (and (stringp action)
11402 (string-match "%[0-9]" action))
11403 (consp action)))
11404 nil)))
11406 (defun org-default-apps ()
11407 "Return the default applications for this operating system."
11408 (cond
11409 ((eq system-type 'darwin)
11410 org-file-apps-defaults-macosx)
11411 ((eq system-type 'windows-nt)
11412 org-file-apps-defaults-windowsnt)
11413 (t org-file-apps-defaults-gnu)))
11415 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11416 "Convert extensions to regular expressions in the cars of LIST.
11417 Also, weed out any non-string entries, because the return value is used
11418 only for regexp matching.
11419 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11420 point to the symbol `emacs', indicating that the file should
11421 be opened in Emacs."
11422 (append
11423 (delq nil
11424 (mapcar (lambda (x)
11425 (if (not (stringp (car x)))
11427 (if (string-match "\\W" (car x))
11429 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11430 list))
11431 (if add-auto-mode
11432 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11434 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11435 (defun org-file-remote-p (file)
11436 "Test whether FILE specifies a location on a remote system.
11437 Return non-nil if the location is indeed remote.
11439 For example, the filename \"/user@host:/foo\" specifies a location
11440 on the system \"/user@host:\"."
11441 (cond ((fboundp 'file-remote-p)
11442 (file-remote-p file))
11443 ((fboundp 'tramp-handle-file-remote-p)
11444 (tramp-handle-file-remote-p file))
11445 ((and (boundp 'ange-ftp-name-format)
11446 (string-match (car ange-ftp-name-format) file))
11447 t)))
11450 ;;;; Refiling
11452 (defun org-get-org-file ()
11453 "Read a filename, with default directory `org-directory'."
11454 (let ((default (or org-default-notes-file remember-data-file)))
11455 (read-file-name (format "File name [%s]: " default)
11456 (file-name-as-directory org-directory)
11457 default)))
11459 (defun org-notes-order-reversed-p ()
11460 "Check if the current file should receive notes in reversed order."
11461 (cond
11462 ((not org-reverse-note-order) nil)
11463 ((eq t org-reverse-note-order) t)
11464 ((not (listp org-reverse-note-order)) nil)
11465 (t (catch 'exit
11466 (let ((all org-reverse-note-order)
11467 entry)
11468 (while (setq entry (pop all))
11469 (if (string-match (car entry) buffer-file-name)
11470 (throw 'exit (cdr entry))))
11471 nil)))))
11473 (defvar org-refile-target-table nil
11474 "The list of refile targets, created by `org-refile'.")
11476 (defvar org-agenda-new-buffers nil
11477 "Buffers created to visit agenda files.")
11479 (defvar org-refile-cache nil
11480 "Cache for refile targets.")
11482 (defvar org-refile-markers nil
11483 "All the markers used for caching refile locations.")
11485 (defun org-refile-marker (pos)
11486 "Get a new refile marker, but only if caching is in use."
11487 (if (not org-refile-use-cache)
11489 (let ((m (make-marker)))
11490 (move-marker m pos)
11491 (push m org-refile-markers)
11492 m)))
11494 (defun org-refile-cache-clear ()
11495 "Clear the refile cache and disable all the markers."
11496 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11497 (setq org-refile-markers nil)
11498 (setq org-refile-cache nil)
11499 (message "Refile cache has been cleared"))
11501 (defun org-refile-cache-check-set (set)
11502 "Check if all the markers in the cache still have live buffers."
11503 (let (marker)
11504 (catch 'exit
11505 (while (and set (setq marker (nth 3 (pop set))))
11506 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11507 (when (and marker (null (marker-buffer marker)))
11508 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11509 (sit-for 3)
11510 (throw 'exit nil)))
11511 t)))
11513 (defun org-refile-cache-put (set &rest identifiers)
11514 "Push the refile targets SET into the cache, under IDENTIFIERS."
11515 (let* ((key (sha1 (prin1-to-string identifiers)))
11516 (entry (assoc key org-refile-cache)))
11517 (if entry
11518 (setcdr entry set)
11519 (push (cons key set) org-refile-cache))))
11521 (defun org-refile-cache-get (&rest identifiers)
11522 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11523 (cond
11524 ((not org-refile-cache) nil)
11525 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11527 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11528 org-refile-cache))))
11529 (and set (org-refile-cache-check-set set) set)))))
11531 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11532 "Produce a table with refile targets."
11533 (let ((case-fold-search nil)
11534 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11535 (entries (or org-refile-targets '((nil . (:level . 1)))))
11536 targets tgs txt re files f desc descre fast-path-p level pos0)
11537 (message "Getting targets...")
11538 (with-current-buffer (or default-buffer (current-buffer))
11539 (while (setq entry (pop entries))
11540 (setq files (car entry) desc (cdr entry))
11541 (setq fast-path-p nil)
11542 (cond
11543 ((null files) (setq files (list (current-buffer))))
11544 ((eq files 'org-agenda-files)
11545 (setq files (org-agenda-files 'unrestricted)))
11546 ((and (symbolp files) (fboundp files))
11547 (setq files (funcall files)))
11548 ((and (symbolp files) (boundp files))
11549 (setq files (symbol-value files))))
11550 (if (stringp files) (setq files (list files)))
11551 (cond
11552 ((eq (car desc) :tag)
11553 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11554 ((eq (car desc) :todo)
11555 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11556 ((eq (car desc) :regexp)
11557 (setq descre (cdr desc)))
11558 ((eq (car desc) :level)
11559 (setq descre (concat "^\\*\\{" (number-to-string
11560 (if org-odd-levels-only
11561 (1- (* 2 (cdr desc)))
11562 (cdr desc)))
11563 "\\}[ \t]")))
11564 ((eq (car desc) :maxlevel)
11565 (setq fast-path-p t)
11566 (setq descre (concat "^\\*\\{1," (number-to-string
11567 (if org-odd-levels-only
11568 (1- (* 2 (cdr desc)))
11569 (cdr desc)))
11570 "\\}[ \t]")))
11571 (t (error "Bad refiling target description %s" desc)))
11572 (while (setq f (pop files))
11573 (with-current-buffer
11574 (if (bufferp f) f (org-get-agenda-file-buffer f))
11576 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11577 (progn
11578 (if (bufferp f) (setq f (buffer-file-name
11579 (buffer-base-buffer f))))
11580 (setq f (and f (expand-file-name f)))
11581 (if (eq org-refile-use-outline-path 'file)
11582 (push (list (file-name-nondirectory f) f nil nil) tgs))
11583 (save-excursion
11584 (save-restriction
11585 (widen)
11586 (goto-char (point-min))
11587 (while (re-search-forward descre nil t)
11588 (goto-char (setq pos0 (point-at-bol)))
11589 (catch 'next
11590 (when org-refile-target-verify-function
11591 (save-match-data
11592 (or (funcall org-refile-target-verify-function)
11593 (throw 'next t))))
11594 (when (and (looking-at org-complex-heading-regexp)
11595 (not (member (match-string 4) excluded-entries))
11596 (match-string 4))
11597 (setq level (org-reduced-level
11598 (- (match-end 1) (match-beginning 1)))
11599 txt (org-link-display-format (match-string 4))
11600 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11601 re (format org-complex-heading-regexp-format
11602 (regexp-quote (match-string 4))))
11603 (when org-refile-use-outline-path
11604 (setq txt (mapconcat
11605 'org-protect-slash
11606 (append
11607 (if (eq org-refile-use-outline-path
11608 'file)
11609 (list (file-name-nondirectory
11610 (buffer-file-name
11611 (buffer-base-buffer))))
11612 (if (eq org-refile-use-outline-path
11613 'full-file-path)
11614 (list (buffer-file-name
11615 (buffer-base-buffer)))))
11616 (org-get-outline-path fast-path-p
11617 level txt)
11618 (list txt))
11619 "/")))
11620 (push (list txt f re (org-refile-marker (point)))
11621 tgs)))
11622 (when (= (point) pos0)
11623 ;; verification function has not moved point
11624 (goto-char (point-at-eol))))))))
11625 (when org-refile-use-cache
11626 (org-refile-cache-put tgs (buffer-file-name) descre))
11627 (setq targets (append tgs targets))))))
11628 (message "Getting targets...done")
11629 (nreverse targets)))
11631 (defun org-protect-slash (s)
11632 (while (string-match "/" s)
11633 (setq s (replace-match "\\" t t s)))
11636 (defvar org-olpa (make-vector 20 nil))
11638 (defun org-get-outline-path (&optional fastp level heading)
11639 "Return the outline path to the current entry, as a list.
11641 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11642 routine which makes outline path derivations for an entire file,
11643 avoiding backtracing. Refile target collection makes use of that."
11644 (if fastp
11645 (progn
11646 (if (> level 19)
11647 (error "Outline path failure, more than 19 levels"))
11648 (loop for i from level upto 19 do
11649 (aset org-olpa i nil))
11650 (prog1
11651 (delq nil (append org-olpa nil))
11652 (aset org-olpa level heading)))
11653 (let (rtn case-fold-search)
11654 (save-excursion
11655 (save-restriction
11656 (widen)
11657 (while (org-up-heading-safe)
11658 (when (looking-at org-complex-heading-regexp)
11659 (push (org-trim
11660 (replace-regexp-in-string
11661 ;; Remove statistical/checkboxes cookies
11662 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11663 (org-match-string-no-properties 4)))
11664 rtn)))
11665 rtn)))))
11667 (defun org-format-outline-path (path &optional width prefix separator)
11668 "Format the outline path PATH for display.
11669 WIDTH is the maximum number of characters that is available.
11670 PREFIX is a prefix to be included in the returned string,
11671 such as the file name.
11672 SEPARATOR is inserted between the different parts of the path,
11673 the default is \"/\"."
11674 (setq width (or width 79))
11675 (if prefix (setq width (- width (length prefix))))
11676 (if (not path)
11677 (or prefix "")
11678 (let* ((nsteps (length path))
11679 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11680 (maxwidth (if (<= total-width width)
11681 10000 ;; everything fits
11682 ;; we need to shorten the level headings
11683 (/ (- width nsteps) nsteps)))
11684 (org-odd-levels-only nil)
11685 (n 0)
11686 (total (1+ (length prefix))))
11687 (setq maxwidth (max maxwidth 10))
11688 (concat prefix
11689 (if prefix (or separator "/"))
11690 (mapconcat
11691 (lambda (h)
11692 (setq n (1+ n))
11693 (if (and (= n nsteps) (< maxwidth 10000))
11694 (setq maxwidth (- total-width total)))
11695 (if (< (length h) maxwidth)
11696 (progn (setq total (+ total (length h) 1)) h)
11697 (setq h (substring h 0 (- maxwidth 2))
11698 total (+ total maxwidth 1))
11699 (if (string-match "[ \t]+\\'" h)
11700 (setq h (substring h 0 (match-beginning 0))))
11701 (setq h (concat h "..")))
11702 (org-add-props h nil 'face
11703 (nth (% (1- n) org-n-level-faces)
11704 org-level-faces))
11706 path (or separator "/"))))))
11708 (defun org-display-outline-path (&optional file current separator just-return-string)
11709 "Display the current outline path in the echo area.
11711 If FILE is non-nil, prepend the output with the file name.
11712 If CURRENT is non-nil, append the current heading to the output.
11713 SEPARATOR is passed through to `org-format-outline-path'. It separates
11714 the different parts of the path and defaults to \"/\".
11715 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11716 (interactive "P")
11717 (let* (case-fold-search
11718 (bfn (buffer-file-name (buffer-base-buffer)))
11719 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11720 res)
11721 (if current (setq path (append path
11722 (save-excursion
11723 (org-back-to-heading t)
11724 (if (looking-at org-complex-heading-regexp)
11725 (list (match-string 4)))))))
11726 (setq res
11727 (org-format-outline-path
11728 path
11729 (1- (frame-width))
11730 (and file bfn (concat (file-name-nondirectory bfn) separator))
11731 separator))
11732 (if just-return-string
11733 (org-no-properties res)
11734 (org-unlogged-message "%s" res))))
11736 (defvar org-refile-history nil
11737 "History for refiling operations.")
11739 (defvar org-after-refile-insert-hook nil
11740 "Hook run after `org-refile' has inserted its stuff at the new location.
11741 Note that this is still *before* the stuff will be removed from
11742 the *old* location.")
11744 (defvar org-capture-last-stored-marker)
11745 (defvar org-refile-keep nil
11746 "Non-nil means `org-refile' will copy instead of refile.")
11748 (defun org-copy ()
11749 "Like `org-refile', but copy."
11750 (interactive)
11751 (let ((org-refile-keep t))
11752 (funcall 'org-refile nil nil nil "Copy")))
11754 (defun org-refile (&optional arg default-buffer rfloc msg)
11755 "Move the entry or entries at point to another heading.
11756 The list of target headings is compiled using the information in
11757 `org-refile-targets', which see.
11759 At the target location, the entry is filed as a subitem of the
11760 target heading. Depending on `org-reverse-note-order', the new
11761 subitem will either be the first or the last subitem.
11763 If there is an active region, all entries in that region will be
11764 refiled. However, the region must fulfill the requirement that
11765 the first heading sets the top-level of the moved text.
11767 With prefix arg ARG, the command will only visit the target
11768 location and not actually move anything.
11770 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11771 refiling operation has put the subtree.
11773 With a numeric prefix argument of `2', refile to the running clock.
11775 With a numeric prefix argument of `3', emulate `org-refile-keep'
11776 being set to `t' and copy to the target location, don't move it.
11777 Beware that keeping refiled entries may result in duplicated ID
11778 properties.
11780 RFLOC can be a refile location obtained in a different way.
11782 MSG is a string to replace \"Refile\" in the default prompt with
11783 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11785 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11787 If you are using target caching (see `org-refile-use-cache'), you
11788 have to clear the target cache in order to find new targets.
11789 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11790 prefix argument (`C-u C-u C-u C-c C-w')."
11791 (interactive "P")
11792 (if (member arg '(0 (64)))
11793 (org-refile-cache-clear)
11794 (let* ((actionmsg (cond (msg msg)
11795 ((equal arg 3) "Refile (and keep)")
11796 (t "Refile")))
11797 (cbuf (current-buffer))
11798 (regionp (org-region-active-p))
11799 (region-start (and regionp (region-beginning)))
11800 (region-end (and regionp (region-end)))
11801 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11802 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11803 pos it nbuf file re level reversed)
11804 (setq last-command nil)
11805 (when regionp
11806 (goto-char region-start)
11807 (or (bolp) (goto-char (point-at-bol)))
11808 (setq region-start (point))
11809 (unless (or (org-kill-is-subtree-p
11810 (buffer-substring region-start region-end))
11811 (prog1 org-refile-active-region-within-subtree
11812 (let ((s (point-at-eol)))
11813 (org-toggle-heading)
11814 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11815 (user-error "The region is not a (sequence of) subtree(s)")))
11816 (if (equal arg '(16))
11817 (org-refile-goto-last-stored)
11818 (when (or
11819 (and (equal arg 2)
11820 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11821 (prog1
11822 (setq it (list (or org-clock-heading "running clock")
11823 (buffer-file-name
11824 (marker-buffer org-clock-hd-marker))
11826 (marker-position org-clock-hd-marker)))
11827 (setq arg nil)))
11828 (setq it (or rfloc
11829 (let (heading-text)
11830 (save-excursion
11831 (unless (and arg (listp arg))
11832 (org-back-to-heading t)
11833 (setq heading-text
11834 (replace-regexp-in-string
11835 org-bracket-link-regexp
11836 "\\3"
11837 (nth 4 (org-heading-components)))))
11838 (org-refile-get-location
11839 (cond ((and arg (listp arg)) "Goto")
11840 (regionp (concat actionmsg " region to"))
11841 (t (concat actionmsg " subtree \""
11842 heading-text "\" to")))
11843 default-buffer
11844 (and (not (equal '(4) arg))
11845 org-refile-allow-creating-parent-nodes)
11846 arg))))))
11847 (setq file (nth 1 it)
11848 re (nth 2 it)
11849 pos (nth 3 it))
11850 (if (and (not arg)
11852 (equal (buffer-file-name) file)
11853 (if regionp
11854 (and (>= pos region-start)
11855 (<= pos region-end))
11856 (and (>= pos (point))
11857 (< pos (save-excursion
11858 (org-end-of-subtree t t))))))
11859 (error "Cannot refile to position inside the tree or region"))
11860 (setq nbuf (or (find-buffer-visiting file)
11861 (find-file-noselect file)))
11862 (if (and arg (not (equal arg 3)))
11863 (progn
11864 (org-pop-to-buffer-same-window nbuf)
11865 (goto-char pos)
11866 (org-show-context 'org-goto))
11867 (if regionp
11868 (progn
11869 (org-kill-new (buffer-substring region-start region-end))
11870 (org-save-markers-in-region region-start region-end))
11871 (org-copy-subtree 1 nil t))
11872 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11873 (find-file-noselect file)))
11874 (setq reversed (org-notes-order-reversed-p))
11875 (save-excursion
11876 (save-restriction
11877 (widen)
11878 (if pos
11879 (progn
11880 (goto-char pos)
11881 (looking-at org-outline-regexp)
11882 (setq level (org-get-valid-level (funcall outline-level) 1))
11883 (goto-char
11884 (if reversed
11885 (or (outline-next-heading) (point-max))
11886 (or (save-excursion (org-get-next-sibling))
11887 (org-end-of-subtree t t)
11888 (point-max)))))
11889 (setq level 1)
11890 (if (not reversed)
11891 (goto-char (point-max))
11892 (goto-char (point-min))
11893 (or (outline-next-heading) (goto-char (point-max)))))
11894 (if (not (bolp)) (newline))
11895 (org-paste-subtree level nil nil t)
11896 (when org-log-refile
11897 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11898 (unless (eq org-log-refile 'note)
11899 (save-excursion (org-add-log-note))))
11900 (and org-auto-align-tags
11901 (let ((org-loop-over-headlines-in-active-region nil))
11902 (org-set-tags nil t)))
11903 (let ((bookmark-name (plist-get org-bookmark-names-plist
11904 :last-refile)))
11905 (when bookmark-name
11906 (with-demoted-errors
11907 (bookmark-set bookmark-name))))
11908 ;; If we are refiling for capture, make sure that the
11909 ;; last-capture pointers point here
11910 (when (org-bound-and-true-p org-refile-for-capture)
11911 (let ((bookmark-name (plist-get org-bookmark-names-plist
11912 :last-capture-marker)))
11913 (when bookmark-name
11914 (with-demoted-errors
11915 (bookmark-set bookmark-name))))
11916 (move-marker org-capture-last-stored-marker (point)))
11917 (if (fboundp 'deactivate-mark) (deactivate-mark))
11918 (run-hooks 'org-after-refile-insert-hook))))
11919 (unless org-refile-keep
11920 (if regionp
11921 (delete-region (point) (+ (point) (- region-end region-start)))
11922 (delete-region
11923 (and (org-back-to-heading t) (point))
11924 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11925 (when (featurep 'org-inlinetask)
11926 (org-inlinetask-remove-END-maybe))
11927 (setq org-markers-to-move nil)
11928 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11930 (defun org-refile-goto-last-stored ()
11931 "Go to the location where the last refile was stored."
11932 (interactive)
11933 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11934 (message "This is the location of the last refile"))
11936 (defun org-refile--get-location (refloc tbl)
11937 "When user refile to REFLOC, find the associated target in TBL.
11938 Also check `org-refile-target-table'."
11939 (car (delq
11941 (mapcar
11942 (lambda (r) (or (assoc r tbl)
11943 (assoc r org-refile-target-table)))
11944 (list (replace-regexp-in-string "/$" "" refloc)
11945 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11947 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11948 no-exclude)
11949 "Prompt the user for a refile location, using PROMPT.
11950 PROMPT should not be suffixed with a colon and a space, because
11951 this function appends the default value from
11952 `org-refile-history' automatically, if that is not empty.
11953 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11954 this is used for the GOTO interface."
11955 (let ((org-refile-targets org-refile-targets)
11956 (org-refile-use-outline-path org-refile-use-outline-path)
11957 excluded-entries)
11958 (when (and (derived-mode-p 'org-mode)
11959 (not org-refile-use-cache)
11960 (not no-exclude))
11961 (org-map-tree
11962 (lambda()
11963 (setq excluded-entries
11964 (append excluded-entries (list (org-get-heading t t)))))))
11965 (setq org-refile-target-table
11966 (org-refile-get-targets default-buffer excluded-entries)))
11967 (unless org-refile-target-table
11968 (user-error "No refile targets"))
11969 (let* ((cbuf (current-buffer))
11970 (partial-completion-mode nil)
11971 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11972 (cfunc (if (and org-refile-use-outline-path
11973 org-outline-path-complete-in-steps)
11974 'org-olpath-completing-read
11975 'org-icompleting-read))
11976 (extra (if org-refile-use-outline-path "/" ""))
11977 (cbnex (concat (buffer-name) extra))
11978 (filename (and cfn (expand-file-name cfn)))
11979 (tbl (mapcar
11980 (lambda (x)
11981 (if (and (not (member org-refile-use-outline-path
11982 '(file full-file-path)))
11983 (not (equal filename (nth 1 x))))
11984 (cons (concat (car x) extra " ("
11985 (file-name-nondirectory (nth 1 x)) ")")
11986 (cdr x))
11987 (cons (concat (car x) extra) (cdr x))))
11988 org-refile-target-table))
11989 (completion-ignore-case t)
11990 cdef
11991 (prompt (concat prompt
11992 (or (and (car org-refile-history)
11993 (concat " (default " (car org-refile-history) ")"))
11994 (and (assoc cbnex tbl) (setq cdef cbnex)
11995 (concat " (default " cbnex ")"))) ": "))
11996 pa answ parent-target child parent old-hist)
11997 (setq old-hist org-refile-history)
11998 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11999 nil 'org-refile-history (or cdef (car org-refile-history))))
12000 (if (setq pa (org-refile--get-location answ tbl))
12001 (progn
12002 (org-refile-check-position pa)
12003 (when (or (not org-refile-history)
12004 (not (eq old-hist org-refile-history))
12005 (not (equal (car pa) (car org-refile-history))))
12006 (setq org-refile-history
12007 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12008 org-refile-history
12009 (cdr org-refile-history))))
12010 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12011 (pop org-refile-history)))
12013 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12014 (progn
12015 (setq parent (match-string 1 answ)
12016 child (match-string 2 answ))
12017 (setq parent-target (org-refile--get-location parent tbl))
12018 (when (and parent-target
12019 (or (eq new-nodes t)
12020 (and (eq new-nodes 'confirm)
12021 (y-or-n-p (format "Create new node \"%s\"? "
12022 child)))))
12023 (org-refile-new-child parent-target child)))
12024 (user-error "Invalid target location")))))
12026 (declare-function org-string-nw-p "org-macs" (s))
12027 (defun org-refile-check-position (refile-pointer)
12028 "Check if the refile pointer matches the headline to which it points."
12029 (let* ((file (nth 1 refile-pointer))
12030 (re (nth 2 refile-pointer))
12031 (pos (nth 3 refile-pointer))
12032 buffer)
12033 (if (and (not (markerp pos)) (not file))
12034 (user-error "Please indicate a target file in the refile path")
12035 (when (org-string-nw-p re)
12036 (setq buffer (if (markerp pos)
12037 (marker-buffer pos)
12038 (or (find-buffer-visiting file)
12039 (find-file-noselect file))))
12040 (with-current-buffer buffer
12041 (save-excursion
12042 (save-restriction
12043 (widen)
12044 (goto-char pos)
12045 (beginning-of-line 1)
12046 (unless (org-looking-at-p re)
12047 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12049 (defun org-refile-new-child (parent-target child)
12050 "Use refile target PARENT-TARGET to add new CHILD below it."
12051 (unless parent-target
12052 (error "Cannot find parent for new node"))
12053 (let ((file (nth 1 parent-target))
12054 (pos (nth 3 parent-target))
12055 level)
12056 (with-current-buffer (or (find-buffer-visiting file)
12057 (find-file-noselect file))
12058 (save-excursion
12059 (save-restriction
12060 (widen)
12061 (if pos
12062 (goto-char pos)
12063 (goto-char (point-max))
12064 (if (not (bolp)) (newline)))
12065 (when (looking-at org-outline-regexp)
12066 (setq level (funcall outline-level))
12067 (org-end-of-subtree t t))
12068 (org-back-over-empty-lines)
12069 (insert "\n" (make-string
12070 (if pos (org-get-valid-level level 1) 1) ?*)
12071 " " child "\n")
12072 (beginning-of-line 0)
12073 (list (concat (car parent-target) "/" child) file "" (point)))))))
12075 (defun org-olpath-completing-read (prompt collection &rest args)
12076 "Read an outline path like a file name."
12077 (let ((thetable collection)
12078 (org-completion-use-ido nil) ; does not work with ido.
12079 (org-completion-use-iswitchb nil)) ; or iswitchb
12080 (apply
12081 'org-icompleting-read prompt
12082 (lambda (string predicate &optional flag)
12083 (let (rtn r f (l (length string)))
12084 (cond
12085 ((eq flag nil)
12086 ;; try completion
12087 (try-completion string thetable))
12088 ((eq flag t)
12089 ;; all-completions
12090 (setq rtn (all-completions string thetable predicate))
12091 (mapcar
12092 (lambda (x)
12093 (setq r (substring x l))
12094 (if (string-match " ([^)]*)$" x)
12095 (setq f (match-string 0 x))
12096 (setq f ""))
12097 (if (string-match "/" r)
12098 (concat string (substring r 0 (match-end 0)) f)
12100 rtn))
12101 ((eq flag 'lambda)
12102 ;; exact match?
12103 (assoc string thetable)))))
12104 args)))
12106 ;;;; Dynamic blocks
12108 (defun org-find-dblock (name)
12109 "Find the first dynamic block with name NAME in the buffer.
12110 If not found, stay at current position and return nil."
12111 (let ((case-fold-search t) pos)
12112 (save-excursion
12113 (goto-char (point-min))
12114 (setq pos (and (re-search-forward
12115 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12116 (match-beginning 0))))
12117 (if pos (goto-char pos))
12118 pos))
12120 (defun org-create-dblock (plist)
12121 "Create a dynamic block section, with parameters taken from PLIST.
12122 PLIST must contain a :name entry which is used as the name of the block."
12123 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12124 (end-of-line 1)
12125 (newline))
12126 (let ((col (current-column))
12127 (name (plist-get plist :name)))
12128 (insert "#+BEGIN: " name)
12129 (while plist
12130 (if (eq (car plist) :name)
12131 (setq plist (cddr plist))
12132 (insert " " (prin1-to-string (pop plist)))))
12133 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12134 (beginning-of-line -2)))
12136 (defun org-prepare-dblock ()
12137 "Prepare dynamic block for refresh.
12138 This empties the block, puts the cursor at the insert position and returns
12139 the property list including an extra property :name with the block name."
12140 (unless (looking-at org-dblock-start-re)
12141 (user-error "Not at a dynamic block"))
12142 (let* ((begdel (1+ (match-end 0)))
12143 (name (org-no-properties (match-string 1)))
12144 (params (append (list :name name)
12145 (read (concat "(" (match-string 3) ")")))))
12146 (save-excursion
12147 (beginning-of-line 1)
12148 (skip-chars-forward " \t")
12149 (setq params (plist-put params :indentation-column (current-column))))
12150 (unless (re-search-forward org-dblock-end-re nil t)
12151 (error "Dynamic block not terminated"))
12152 (setq params
12153 (append params
12154 (list :content (buffer-substring
12155 begdel (match-beginning 0)))))
12156 (delete-region begdel (match-beginning 0))
12157 (goto-char begdel)
12158 (open-line 1)
12159 params))
12161 (defun org-map-dblocks (&optional command)
12162 "Apply COMMAND to all dynamic blocks in the current buffer.
12163 If COMMAND is not given, use `org-update-dblock'."
12164 (let ((cmd (or command 'org-update-dblock)))
12165 (save-excursion
12166 (goto-char (point-min))
12167 (while (re-search-forward org-dblock-start-re nil t)
12168 (goto-char (match-beginning 0))
12169 (save-excursion
12170 (condition-case nil
12171 (funcall cmd)
12172 (error (message "Error during update of dynamic block"))))
12173 (unless (re-search-forward org-dblock-end-re nil t)
12174 (error "Dynamic block not terminated"))))))
12176 (defun org-dblock-update (&optional arg)
12177 "User command for updating dynamic blocks.
12178 Update the dynamic block at point. With prefix ARG, update all dynamic
12179 blocks in the buffer."
12180 (interactive "P")
12181 (if arg
12182 (org-update-all-dblocks)
12183 (or (looking-at org-dblock-start-re)
12184 (org-beginning-of-dblock))
12185 (org-update-dblock)))
12187 (defun org-update-dblock ()
12188 "Update the dynamic block at point.
12189 This means to empty the block, parse for parameters and then call
12190 the correct writing function."
12191 (interactive)
12192 (save-excursion
12193 (let* ((win (selected-window))
12194 (pos (point))
12195 (line (org-current-line))
12196 (params (org-prepare-dblock))
12197 (name (plist-get params :name))
12198 (indent (plist-get params :indentation-column))
12199 (cmd (intern (concat "org-dblock-write:" name))))
12200 (message "Updating dynamic block `%s' at line %d..." name line)
12201 (funcall cmd params)
12202 (message "Updating dynamic block `%s' at line %d...done" name line)
12203 (goto-char pos)
12204 (when (and indent (> indent 0))
12205 (setq indent (make-string indent ?\ ))
12206 (save-excursion
12207 (select-window win)
12208 (org-beginning-of-dblock)
12209 (forward-line 1)
12210 (while (not (looking-at org-dblock-end-re))
12211 (insert indent)
12212 (beginning-of-line 2))
12213 (when (looking-at org-dblock-end-re)
12214 (and (looking-at "[ \t]+")
12215 (replace-match ""))
12216 (insert indent)))))))
12218 (defun org-beginning-of-dblock ()
12219 "Find the beginning of the dynamic block at point.
12220 Error if there is no such block at point."
12221 (let ((pos (point))
12222 beg)
12223 (end-of-line 1)
12224 (if (and (re-search-backward org-dblock-start-re nil t)
12225 (setq beg (match-beginning 0))
12226 (re-search-forward org-dblock-end-re nil t)
12227 (> (match-end 0) pos))
12228 (goto-char beg)
12229 (goto-char pos)
12230 (error "Not in a dynamic block"))))
12232 (defun org-update-all-dblocks ()
12233 "Update all dynamic blocks in the buffer.
12234 This function can be used in a hook."
12235 (interactive)
12236 (when (derived-mode-p 'org-mode)
12237 (org-map-dblocks 'org-update-dblock)))
12240 ;;;; Completion
12242 (declare-function org-export-backend-name "org-export" (cl-x))
12243 (declare-function org-export-backend-options "org-export" (cl-x))
12244 (defun org-get-export-keywords ()
12245 "Return a list of all currently understood export keywords.
12246 Export keywords include options, block names, attributes and
12247 keywords relative to each registered export back-end."
12248 (let (keywords)
12249 (dolist (backend
12250 (org-bound-and-true-p org-export--registered-backends)
12251 (delq nil keywords))
12252 ;; Back-end name (for keywords, like #+LATEX:)
12253 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12254 (dolist (option-entry (org-export-backend-options backend))
12255 ;; Back-end options.
12256 (push (nth 1 option-entry) keywords)))))
12258 (defconst org-options-keywords
12259 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12260 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12261 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12262 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12263 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12265 (defcustom org-structure-template-alist
12266 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12267 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12268 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12269 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12270 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12271 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12272 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12273 ("L" "#+LaTeX: ")
12274 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12275 ("H" "#+HTML: ")
12276 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12277 ("A" "#+ASCII: ")
12278 ("i" "#+INDEX: ?")
12279 ("I" "#+INCLUDE: %file ?"))
12280 "Structure completion elements.
12281 This is a list of abbreviation keys and values. The value gets inserted
12282 if you type `<' followed by the key and then press the completion key,
12283 usually `TAB'. %file will be replaced by a file name after prompting
12284 for the file using completion. The cursor will be placed at the position
12285 of the `?` in the template.
12286 There are two templates for each key, the first uses the original Org syntax,
12287 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12288 the default when the /org-mtags.el/ module has been loaded. See also the
12289 variable `org-mtags-prefer-muse-templates'."
12290 :group 'org-completion
12291 :type '(repeat
12292 (list
12293 (string :tag "Key")
12294 (string :tag "Template")))
12295 :version 24.4
12296 :package-version '(Org . "8.3"))
12298 (defun org-try-structure-completion ()
12299 "Try to complete a structure template before point.
12300 This looks for strings like \"<e\" on an otherwise empty line and
12301 expands them."
12302 (let ((l (buffer-substring (point-at-bol) (point)))
12304 (when (and (looking-at "[ \t]*$")
12305 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12306 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12307 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12308 (match-beginning 1)) a)
12309 t)))
12311 (defun org-complete-expand-structure-template (start cell)
12312 "Expand a structure template."
12313 (let ((rpl (nth 1 cell))
12314 (ind ""))
12315 (delete-region start (point))
12316 (when (string-match "\\`[ \t]*#\\+" rpl)
12317 (cond
12318 ((bolp))
12319 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12320 (setq ind (buffer-substring (point-at-bol) (point))))
12321 (t (newline))))
12322 (setq start (point))
12323 (if (string-match "%file" rpl)
12324 (setq rpl (replace-match
12325 (concat
12326 "\""
12327 (save-match-data
12328 (abbreviate-file-name (read-file-name "Include file: ")))
12329 "\"")
12330 t t rpl)))
12331 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12332 (concat "\n" ind)))
12333 (insert rpl)
12334 (if (re-search-backward "\\?" start t) (delete-char 1))))
12336 ;;;; TODO, DEADLINE, Comments
12338 (defun org-toggle-comment ()
12339 "Change the COMMENT state of an entry."
12340 (interactive)
12341 (save-excursion
12342 (org-back-to-heading)
12343 (looking-at org-complex-heading-regexp)
12344 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12345 (skip-chars-forward " \t")
12346 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12347 (if (org-in-commented-heading-p t)
12348 (delete-region (point)
12349 (progn (search-forward " " (line-end-position) 'move)
12350 (skip-chars-forward " \t")
12351 (point)))
12352 (insert org-comment-string)
12353 (unless (eolp) (insert " ")))))
12355 (defvar org-last-todo-state-is-todo nil
12356 "This is non-nil when the last TODO state change led to a TODO state.
12357 If the last change removed the TODO tag or switched to DONE, then
12358 this is nil.")
12360 (defvar org-setting-tags nil) ; dynamically skipped
12362 (defvar org-todo-setup-filter-hook nil
12363 "Hook for functions that pre-filter todo specs.
12364 Each function takes a todo spec and returns either nil or the spec
12365 transformed into canonical form." )
12367 (defvar org-todo-get-default-hook nil
12368 "Hook for functions that get a default item for todo.
12369 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12370 nil or a string to be used for the todo mark." )
12372 (defvar org-agenda-headline-snapshot-before-repeat)
12374 (defun org-current-effective-time ()
12375 "Return current time adjusted for `org-extend-today-until' variable."
12376 (let* ((ct (org-current-time))
12377 (dct (decode-time ct))
12378 (ct1
12379 (cond
12380 (org-use-last-clock-out-time-as-effective-time
12381 (or (org-clock-get-last-clock-out-time) ct))
12382 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12383 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12384 (t ct))))
12385 ct1))
12387 (defun org-todo-yesterday (&optional arg)
12388 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12389 (interactive "P")
12390 (if (eq major-mode 'org-agenda-mode)
12391 (apply 'org-agenda-todo-yesterday arg)
12392 (let* ((hour (third (decode-time
12393 (org-current-time))))
12394 (org-extend-today-until (1+ hour)))
12395 (org-todo arg))))
12397 (defvar org-block-entry-blocking ""
12398 "First entry preventing the TODO state change.")
12400 (defun org-cancel-repeater ()
12401 "Cancel a repeater by setting its numeric value to zero."
12402 (interactive)
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (let ((bound1 (point))
12406 (bound0 (save-excursion (outline-next-heading) (point))))
12407 (when (re-search-forward
12408 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12409 org-deadline-time-regexp "\\)\\|\\("
12410 org-ts-regexp "\\)")
12411 bound0 t)
12412 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12413 (replace-match "0" t nil nil 1))))))
12415 (defun org-todo (&optional arg)
12416 "Change the TODO state of an item.
12417 The state of an item is given by a keyword at the start of the heading,
12418 like
12419 *** TODO Write paper
12420 *** DONE Call mom
12422 The different keywords are specified in the variable `org-todo-keywords'.
12423 By default the available states are \"TODO\" and \"DONE\".
12424 So for this example: when the item starts with TODO, it is changed to DONE.
12425 When it starts with DONE, the DONE is removed. And when neither TODO nor
12426 DONE are present, add TODO at the beginning of the heading.
12428 With \\[universal-argument] prefix arg, use completion to determine the new \
12429 state.
12430 With numeric prefix arg, switch to that state.
12431 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12432 keywords (nextset).
12433 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12434 With a numeric prefix arg of 0, inhibit note taking for the change.
12435 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12437 When called through ELisp, arg is also interpreted in the following way:
12438 'none -> empty state
12439 \"\"(empty string) -> switch to empty state
12440 'done -> switch to DONE
12441 'nextset -> switch to the next set of keywords
12442 'previousset -> switch to the previous set of keywords
12443 \"WAITING\" -> switch to the specified keyword, but only if it
12444 really is a member of `org-todo-keywords'."
12445 (interactive "P")
12446 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12447 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12448 'region-start-level 'region))
12449 org-loop-over-headlines-in-active-region)
12450 (org-map-entries
12451 `(org-todo ,arg)
12452 org-loop-over-headlines-in-active-region
12453 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12454 (if (equal arg '(16)) (setq arg 'nextset))
12455 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12456 (let ((org-blocker-hook org-blocker-hook)
12457 commentp
12458 case-fold-search)
12459 (when (equal arg '(64))
12460 (setq arg nil org-blocker-hook nil))
12461 (when (and org-blocker-hook
12462 (or org-inhibit-blocking
12463 (org-entry-get nil "NOBLOCKING")))
12464 (setq org-blocker-hook nil))
12465 (save-excursion
12466 (catch 'exit
12467 (org-back-to-heading t)
12468 (when (org-in-commented-heading-p t)
12469 (org-toggle-comment)
12470 (setq commentp t))
12471 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12472 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12473 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12474 (let* ((match-data (match-data))
12475 (startpos (point-at-bol))
12476 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12477 (org-log-done org-log-done)
12478 (org-log-repeat org-log-repeat)
12479 (org-todo-log-states org-todo-log-states)
12480 (org-inhibit-logging
12481 (if (equal arg 0)
12482 (progn (setq arg nil) 'note) org-inhibit-logging))
12483 (this (match-string 1))
12484 (hl-pos (match-beginning 0))
12485 (head (org-get-todo-sequence-head this))
12486 (ass (assoc head org-todo-kwd-alist))
12487 (interpret (nth 1 ass))
12488 (done-word (nth 3 ass))
12489 (final-done-word (nth 4 ass))
12490 (org-last-state (or this ""))
12491 (completion-ignore-case t)
12492 (member (member this org-todo-keywords-1))
12493 (tail (cdr member))
12494 (org-state (cond
12495 ((and org-todo-key-trigger
12496 (or (and (equal arg '(4))
12497 (eq org-use-fast-todo-selection 'prefix))
12498 (and (not arg) org-use-fast-todo-selection
12499 (not (eq org-use-fast-todo-selection
12500 'prefix)))))
12501 ;; Use fast selection
12502 (org-fast-todo-selection))
12503 ((and (equal arg '(4))
12504 (or (not org-use-fast-todo-selection)
12505 (not org-todo-key-trigger)))
12506 ;; Read a state with completion
12507 (org-icompleting-read
12508 "State: " (mapcar 'list org-todo-keywords-1)
12509 nil t))
12510 ((eq arg 'right)
12511 (if this
12512 (if tail (car tail) nil)
12513 (car org-todo-keywords-1)))
12514 ((eq arg 'left)
12515 (if (equal member org-todo-keywords-1)
12517 (if this
12518 (nth (- (length org-todo-keywords-1)
12519 (length tail) 2)
12520 org-todo-keywords-1)
12521 (org-last org-todo-keywords-1))))
12522 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12523 (setq arg nil))) ; hack to fall back to cycling
12524 (arg
12525 ;; user or caller requests a specific state
12526 (cond
12527 ((equal arg "") nil)
12528 ((eq arg 'none) nil)
12529 ((eq arg 'done) (or done-word (car org-done-keywords)))
12530 ((eq arg 'nextset)
12531 (or (car (cdr (member head org-todo-heads)))
12532 (car org-todo-heads)))
12533 ((eq arg 'previousset)
12534 (let ((org-todo-heads (reverse org-todo-heads)))
12535 (or (car (cdr (member head org-todo-heads)))
12536 (car org-todo-heads))))
12537 ((car (member arg org-todo-keywords-1)))
12538 ((stringp arg)
12539 (user-error "State `%s' not valid in this file" arg))
12540 ((nth (1- (prefix-numeric-value arg))
12541 org-todo-keywords-1))))
12542 ((null member) (or head (car org-todo-keywords-1)))
12543 ((equal this final-done-word) nil) ;; -> make empty
12544 ((null tail) nil) ;; -> first entry
12545 ((memq interpret '(type priority))
12546 (if (eq this-command last-command)
12547 (car tail)
12548 (if (> (length tail) 0)
12549 (or done-word (car org-done-keywords))
12550 nil)))
12552 (car tail))))
12553 (org-state (or
12554 (run-hook-with-args-until-success
12555 'org-todo-get-default-hook org-state org-last-state)
12556 org-state))
12557 (next (if org-state (concat " " org-state " ") " "))
12558 (change-plist (list :type 'todo-state-change :from this :to org-state
12559 :position startpos))
12560 dolog now-done-p)
12561 (when org-blocker-hook
12562 (setq org-last-todo-state-is-todo
12563 (not (member this org-done-keywords)))
12564 (unless (save-excursion
12565 (save-match-data
12566 (org-with-wide-buffer
12567 (run-hook-with-args-until-failure
12568 'org-blocker-hook change-plist))))
12569 (if (org-called-interactively-p 'interactive)
12570 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12571 this org-state org-block-entry-blocking)
12572 ;; fail silently
12573 (message "TODO state change from %s to %s blocked (by \"%s\")"
12574 this org-state org-block-entry-blocking)
12575 (throw 'exit nil))))
12576 (store-match-data match-data)
12577 (replace-match next t t)
12578 (cond ((equal this org-state)
12579 (message "TODO state was already %s" (org-trim next)))
12580 ((pos-visible-in-window-p hl-pos)
12581 (message "TODO state changed to %s" (org-trim next))))
12582 (unless head
12583 (setq head (org-get-todo-sequence-head org-state)
12584 ass (assoc head org-todo-kwd-alist)
12585 interpret (nth 1 ass)
12586 done-word (nth 3 ass)
12587 final-done-word (nth 4 ass)))
12588 (when (memq arg '(nextset previousset))
12589 (message "Keyword-Set %d/%d: %s"
12590 (- (length org-todo-sets) -1
12591 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12592 (length org-todo-sets)
12593 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12594 (setq org-last-todo-state-is-todo
12595 (not (member org-state org-done-keywords)))
12596 (setq now-done-p (and (member org-state org-done-keywords)
12597 (not (member this org-done-keywords))))
12598 (and logging (org-local-logging logging))
12599 (when (and (or org-todo-log-states org-log-done)
12600 (not (eq org-inhibit-logging t))
12601 (not (memq arg '(nextset previousset))))
12602 ;; we need to look at recording a time and note
12603 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12604 (nth 2 (assoc this org-todo-log-states))))
12605 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12606 (setq dolog 'time))
12607 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12608 (and org-state
12609 (member org-state org-not-done-keywords)
12610 (not (member this org-not-done-keywords))))
12611 ;; This is now a todo state and was not one before
12612 ;; If there was a CLOSED time stamp, get rid of it.
12613 (org-add-planning-info nil nil 'closed))
12614 (when (and now-done-p org-log-done)
12615 ;; It is now done, and it was not done before
12616 (org-add-planning-info 'closed (org-current-effective-time))
12617 (if (and (not dolog) (eq 'note org-log-done))
12618 (org-add-log-setup 'done org-state this 'findpos 'note)))
12619 (when (and org-state dolog)
12620 ;; This is a non-nil state, and we need to log it
12621 (org-add-log-setup 'state org-state this 'findpos dolog)))
12622 ;; Fixup tag positioning
12623 (org-todo-trigger-tag-changes org-state)
12624 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12625 (when org-provide-todo-statistics
12626 (org-update-parent-todo-statistics))
12627 (run-hooks 'org-after-todo-state-change-hook)
12628 (if (and arg (not (member org-state org-done-keywords)))
12629 (setq head (org-get-todo-sequence-head org-state)))
12630 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12631 ;; Do we need to trigger a repeat?
12632 (when now-done-p
12633 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12634 ;; This is for the agenda, take a snapshot of the headline.
12635 (save-match-data
12636 (setq org-agenda-headline-snapshot-before-repeat
12637 (org-get-heading))))
12638 (org-auto-repeat-maybe org-state))
12639 ;; Fixup cursor location if close to the keyword
12640 (if (and (outline-on-heading-p)
12641 (not (bolp))
12642 (save-excursion (beginning-of-line 1)
12643 (looking-at org-todo-line-regexp))
12644 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12645 (progn
12646 (goto-char (or (match-end 2) (match-end 1)))
12647 (and (looking-at " ") (just-one-space))))
12648 (when org-trigger-hook
12649 (save-excursion
12650 (run-hook-with-args 'org-trigger-hook change-plist)))
12651 (when commentp (org-toggle-comment))))))))
12653 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12654 "Block turning an entry into a TODO, using the hierarchy.
12655 This checks whether the current task should be blocked from state
12656 changes. Such blocking occurs when:
12658 1. The task has children which are not all in a completed state.
12660 2. A task has a parent with the property :ORDERED:, and there
12661 are siblings prior to the current task with incomplete
12662 status.
12664 3. The parent of the task is blocked because it has siblings that should
12665 be done first, or is child of a block grandparent TODO entry."
12667 (if (not org-enforce-todo-dependencies)
12668 t ; if locally turned off don't block
12669 (catch 'dont-block
12670 ;; If this is not a todo state change, or if this entry is already DONE,
12671 ;; do not block
12672 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12673 (member (plist-get change-plist :from)
12674 (cons 'done org-done-keywords))
12675 (member (plist-get change-plist :to)
12676 (cons 'todo org-not-done-keywords))
12677 (not (plist-get change-plist :to)))
12678 (throw 'dont-block t))
12679 ;; If this task has children, and any are undone, it's blocked
12680 (save-excursion
12681 (org-back-to-heading t)
12682 (let ((this-level (funcall outline-level)))
12683 (outline-next-heading)
12684 (let ((child-level (funcall outline-level)))
12685 (while (and (not (eobp))
12686 (> child-level this-level))
12687 ;; this todo has children, check whether they are all
12688 ;; completed
12689 (if (and (not (org-entry-is-done-p))
12690 (org-entry-is-todo-p))
12691 (progn (setq org-block-entry-blocking (org-get-heading))
12692 (throw 'dont-block nil)))
12693 (outline-next-heading)
12694 (setq child-level (funcall outline-level))))))
12695 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12696 ;; any previous siblings are undone, it's blocked
12697 (save-excursion
12698 (org-back-to-heading t)
12699 (let* ((pos (point))
12700 (parent-pos (and (org-up-heading-safe) (point))))
12701 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12702 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12703 (forward-line 1)
12704 (re-search-forward org-not-done-heading-regexp pos t))
12705 (setq org-block-entry-blocking (match-string 0))
12706 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12707 ;; Search further up the hierarchy, to see if an ancestor is blocked
12708 (while t
12709 (goto-char parent-pos)
12710 (if (not (looking-at org-not-done-heading-regexp))
12711 (throw 'dont-block t)) ; do not block, parent is not a TODO
12712 (setq pos (point))
12713 (setq parent-pos (and (org-up-heading-safe) (point)))
12714 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12715 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12716 (forward-line 1)
12717 (re-search-forward org-not-done-heading-regexp pos t)
12718 (setq org-block-entry-blocking (org-get-heading)))
12719 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12721 (defcustom org-track-ordered-property-with-tag nil
12722 "Should the ORDERED property also be shown as a tag?
12723 The ORDERED property decides if an entry should require subtasks to be
12724 completed in sequence. Since a property is not very visible, setting
12725 this option means that toggling the ORDERED property with the command
12726 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12727 not relevant for the behavior, but it makes things more visible.
12729 Note that toggling the tag with tags commands will not change the property
12730 and therefore not influence behavior!
12732 This can be t, meaning the tag ORDERED should be used, It can also be a
12733 string to select a different tag for this task."
12734 :group 'org-todo
12735 :type '(choice
12736 (const :tag "No tracking" nil)
12737 (const :tag "Track with ORDERED tag" t)
12738 (string :tag "Use other tag")))
12740 (defun org-toggle-ordered-property ()
12741 "Toggle the ORDERED property of the current entry.
12742 For better visibility, you can track the value of this property with a tag.
12743 See variable `org-track-ordered-property-with-tag'."
12744 (interactive)
12745 (let* ((t1 org-track-ordered-property-with-tag)
12746 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12747 (save-excursion
12748 (org-back-to-heading)
12749 (if (org-entry-get nil "ORDERED")
12750 (progn
12751 (org-delete-property "ORDERED")
12752 (and tag (org-toggle-tag tag 'off))
12753 (message "Subtasks can be completed in arbitrary order"))
12754 (org-entry-put nil "ORDERED" "t")
12755 (and tag (org-toggle-tag tag 'on))
12756 (message "Subtasks must be completed in sequence")))))
12758 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12759 (defun org-block-todo-from-checkboxes (change-plist)
12760 "Block turning an entry into a TODO, using checkboxes.
12761 This checks whether the current task should be blocked from state
12762 changes because there are unchecked boxes in this entry."
12763 (if (not org-enforce-todo-checkbox-dependencies)
12764 t ; if locally turned off don't block
12765 (catch 'dont-block
12766 ;; If this is not a todo state change, or if this entry is already DONE,
12767 ;; do not block
12768 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12769 (member (plist-get change-plist :from)
12770 (cons 'done org-done-keywords))
12771 (member (plist-get change-plist :to)
12772 (cons 'todo org-not-done-keywords))
12773 (not (plist-get change-plist :to)))
12774 (throw 'dont-block t))
12775 ;; If this task has checkboxes that are not checked, it's blocked
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (let ((beg (point)) end)
12779 (outline-next-heading)
12780 (setq end (point))
12781 (goto-char beg)
12782 (if (org-list-search-forward
12783 (concat (org-item-beginning-re)
12784 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12785 "\\[[- ]\\]")
12786 end t)
12787 (progn
12788 (if (boundp 'org-blocked-by-checkboxes)
12789 (setq org-blocked-by-checkboxes t))
12790 (throw 'dont-block nil)))))
12791 t))) ; do not block
12793 (defun org-entry-blocked-p ()
12794 "Is the current entry blocked?"
12795 (org-with-silent-modifications
12796 (if (org-entry-get nil "NOBLOCKING")
12797 nil ;; Never block this entry
12798 (not (run-hook-with-args-until-failure
12799 'org-blocker-hook
12800 (list :type 'todo-state-change
12801 :position (point)
12802 :from 'todo
12803 :to 'done))))))
12805 (defun org-update-statistics-cookies (all)
12806 "Update the statistics cookie, either from TODO or from checkboxes.
12807 This should be called with the cursor in a line with a statistics cookie."
12808 (interactive "P")
12809 (if all
12810 (progn
12811 (org-update-checkbox-count 'all)
12812 (org-map-entries 'org-update-parent-todo-statistics))
12813 (if (not (org-at-heading-p))
12814 (org-update-checkbox-count)
12815 (let ((pos (point-marker))
12816 end l1 l2)
12817 (ignore-errors (org-back-to-heading t))
12818 (if (not (org-at-heading-p))
12819 (org-update-checkbox-count)
12820 (setq l1 (org-outline-level))
12821 (setq end (save-excursion
12822 (outline-next-heading)
12823 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12824 (point)))
12825 (if (and (save-excursion
12826 (re-search-forward
12827 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12828 (not (save-excursion (re-search-forward
12829 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12830 (org-update-checkbox-count)
12831 (if (and l2 (> l2 l1))
12832 (progn
12833 (goto-char end)
12834 (org-update-parent-todo-statistics))
12835 (goto-char pos)
12836 (beginning-of-line 1)
12837 (while (re-search-forward
12838 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12839 (point-at-eol) t)
12840 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12841 (goto-char pos)
12842 (move-marker pos nil)))))
12844 (defvar org-entry-property-inherited-from) ;; defined below
12845 (defun org-update-parent-todo-statistics ()
12846 "Update any statistics cookie in the parent of the current headline.
12847 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12848 the entire subtree and this will travel up the hierarchy and update
12849 statistics everywhere."
12850 (let* ((prop (save-excursion (org-up-heading-safe)
12851 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12852 (recursive (or (not org-hierarchical-todo-statistics)
12853 (and prop (string-match "\\<recursive\\>" prop))))
12854 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12856 (first t)
12857 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12858 level ltoggle l1 new ndel
12859 (cnt-all 0) (cnt-done 0) is-percent kwd
12860 checkbox-beg ov ovs ove cookie-present)
12861 (catch 'exit
12862 (save-excursion
12863 (beginning-of-line 1)
12864 (setq ltoggle (funcall outline-level))
12865 ;; Three situations are to consider:
12867 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12868 ;; to the top-level ancestor on the headline;
12870 ;; 2. If parent has "recursive" property, repeat up to the
12871 ;; headline setting that property, taking inheritance into
12872 ;; account;
12874 ;; 3. Else, move up to direct parent and proceed only once.
12875 (while (and (setq level (org-up-heading-safe))
12876 (or recursive first)
12877 (>= (point) lim))
12878 (setq first nil cookie-present nil)
12879 (unless (and level
12880 (not (string-match
12881 "\\<checkbox\\>"
12882 (downcase (or (org-entry-get nil "COOKIE_DATA")
12883 "")))))
12884 (throw 'exit nil))
12885 (while (re-search-forward box-re (point-at-eol) t)
12886 (setq cnt-all 0 cnt-done 0 cookie-present t)
12887 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12888 (save-match-data
12889 (unless (outline-next-heading) (throw 'exit nil))
12890 (while (and (looking-at org-complex-heading-regexp)
12891 (> (setq l1 (length (match-string 1))) level))
12892 (setq kwd (and (or recursive (= l1 ltoggle))
12893 (match-string 2)))
12894 (if (or (eq org-provide-todo-statistics 'all-headlines)
12895 (and (eq org-provide-todo-statistics t)
12896 (or (member kwd org-done-keywords)))
12897 (and (listp org-provide-todo-statistics)
12898 (stringp (car org-provide-todo-statistics))
12899 (or (member kwd org-provide-todo-statistics)
12900 (member kwd org-done-keywords)))
12901 (and (listp org-provide-todo-statistics)
12902 (listp (car org-provide-todo-statistics))
12903 (or (member kwd (car org-provide-todo-statistics))
12904 (and (member kwd org-done-keywords)
12905 (member kwd (cadr org-provide-todo-statistics))))))
12906 (setq cnt-all (1+ cnt-all))
12907 (if (eq org-provide-todo-statistics t)
12908 (and kwd (setq cnt-all (1+ cnt-all)))))
12909 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12910 (member kwd org-done-keywords))
12911 (and (listp org-provide-todo-statistics)
12912 (listp (car org-provide-todo-statistics))
12913 (member kwd org-done-keywords)
12914 (member kwd (cadr org-provide-todo-statistics)))
12915 (and (listp org-provide-todo-statistics)
12916 (stringp (car org-provide-todo-statistics))
12917 (member kwd org-done-keywords)))
12918 (setq cnt-done (1+ cnt-done)))
12919 (outline-next-heading)))
12920 (setq new
12921 (if is-percent
12922 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12923 (format "[%d/%d]" cnt-done cnt-all))
12924 ndel (- (match-end 0) checkbox-beg))
12925 ;; handle overlays when updating cookie from column view
12926 (when (setq ov (car (overlays-at checkbox-beg)))
12927 (setq ovs (overlay-start ov) ove (overlay-end ov))
12928 (delete-overlay ov))
12929 (goto-char checkbox-beg)
12930 (insert new)
12931 (delete-region (point) (+ (point) ndel))
12932 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12933 (when ov (move-overlay ov ovs ove)))
12934 (when cookie-present
12935 (run-hook-with-args 'org-after-todo-statistics-hook
12936 cnt-done (- cnt-all cnt-done))))))
12937 (run-hooks 'org-todo-statistics-hook)))
12939 (defvar org-after-todo-statistics-hook nil
12940 "Hook that is called after a TODO statistics cookie has been updated.
12941 Each function is called with two arguments: the number of not-done entries
12942 and the number of done entries.
12944 For example, the following function, when added to this hook, will switch
12945 an entry to DONE when all children are done, and back to TODO when new
12946 entries are set to a TODO status. Note that this hook is only called
12947 when there is a statistics cookie in the headline!
12949 (defun org-summary-todo (n-done n-not-done)
12950 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12951 (let (org-log-done org-log-states) ; turn off logging
12952 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12955 (defvar org-todo-statistics-hook nil
12956 "Hook that is run whenever Org thinks TODO statistics should be updated.
12957 This hook runs even if there is no statistics cookie present, in which case
12958 `org-after-todo-statistics-hook' would not run.")
12960 (defun org-todo-trigger-tag-changes (state)
12961 "Apply the changes defined in `org-todo-state-tags-triggers'."
12962 (let ((l org-todo-state-tags-triggers)
12963 changes)
12964 (when (or (not state) (equal state ""))
12965 (setq changes (append changes (cdr (assoc "" l)))))
12966 (when (and (stringp state) (> (length state) 0))
12967 (setq changes (append changes (cdr (assoc state l)))))
12968 (when (member state org-not-done-keywords)
12969 (setq changes (append changes (cdr (assoc 'todo l)))))
12970 (when (member state org-done-keywords)
12971 (setq changes (append changes (cdr (assoc 'done l)))))
12972 (dolist (c changes)
12973 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12975 (defun org-local-logging (value)
12976 "Get logging settings from a property VALUE."
12977 (let* (words w a)
12978 ;; directly set the variables, they are already local.
12979 (setq org-log-done nil
12980 org-log-repeat nil
12981 org-todo-log-states nil)
12982 (setq words (org-split-string value))
12983 (while (setq w (pop words))
12984 (cond
12985 ((setq a (assoc w org-startup-options))
12986 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12987 (set (nth 1 a) (nth 2 a))))
12988 ((setq a (org-extract-log-state-settings w))
12989 (and (member (car a) org-todo-keywords-1)
12990 (push a org-todo-log-states)))))))
12992 (defun org-get-todo-sequence-head (kwd)
12993 "Return the head of the TODO sequence to which KWD belongs.
12994 If KWD is not set, check if there is a text property remembering the
12995 right sequence."
12996 (let (p)
12997 (cond
12998 ((not kwd)
12999 (or (get-text-property (point-at-bol) 'org-todo-head)
13000 (progn
13001 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13002 nil (point-at-eol)))
13003 (get-text-property p 'org-todo-head))))
13004 ((not (member kwd org-todo-keywords-1))
13005 (car org-todo-keywords-1))
13006 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13008 (defun org-fast-todo-selection ()
13009 "Fast TODO keyword selection with single keys.
13010 Returns the new TODO keyword, or nil if no state change should occur."
13011 (let* ((fulltable org-todo-key-alist)
13012 (done-keywords org-done-keywords) ;; needed for the faces.
13013 (maxlen (apply 'max (mapcar
13014 (lambda (x)
13015 (if (stringp (car x)) (string-width (car x)) 0))
13016 fulltable)))
13017 (expert nil)
13018 (fwidth (+ maxlen 3 1 3))
13019 (ncol (/ (- (window-width) 4) fwidth))
13020 tg cnt e c tbl
13021 groups ingroup)
13022 (save-excursion
13023 (save-window-excursion
13024 (if expert
13025 (set-buffer (get-buffer-create " *Org todo*"))
13026 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13027 (erase-buffer)
13028 (org-set-local 'org-done-keywords done-keywords)
13029 (setq tbl fulltable cnt 0)
13030 (while (setq e (pop tbl))
13031 (cond
13032 ((equal e '(:startgroup))
13033 (push '() groups) (setq ingroup t)
13034 (when (not (= cnt 0))
13035 (setq cnt 0)
13036 (insert "\n"))
13037 (insert "{ "))
13038 ((equal e '(:endgroup))
13039 (setq ingroup nil cnt 0)
13040 (insert "}\n"))
13041 ((equal e '(:newline))
13042 (when (not (= cnt 0))
13043 (setq cnt 0)
13044 (insert "\n")
13045 (setq e (car tbl))
13046 (while (equal (car tbl) '(:newline))
13047 (insert "\n")
13048 (setq tbl (cdr tbl)))))
13050 (setq tg (car e) c (cdr e))
13051 (if ingroup (push tg (car groups)))
13052 (setq tg (org-add-props tg nil 'face
13053 (org-get-todo-face tg)))
13054 (if (and (= cnt 0) (not ingroup)) (insert " "))
13055 (insert "[" c "] " tg (make-string
13056 (- fwidth 4 (length tg)) ?\ ))
13057 (when (= (setq cnt (1+ cnt)) ncol)
13058 (insert "\n")
13059 (if ingroup (insert " "))
13060 (setq cnt 0)))))
13061 (insert "\n")
13062 (goto-char (point-min))
13063 (if (not expert) (org-fit-window-to-buffer))
13064 (message "[a-z..]:Set [SPC]:clear")
13065 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13066 (cond
13067 ((or (= c ?\C-g)
13068 (and (= c ?q) (not (rassoc c fulltable))))
13069 (setq quit-flag t))
13070 ((= c ?\ ) nil)
13071 ((setq e (rassoc c fulltable) tg (car e))
13073 (t (setq quit-flag t)))))))
13075 (defun org-entry-is-todo-p ()
13076 (member (org-get-todo-state) org-not-done-keywords))
13078 (defun org-entry-is-done-p ()
13079 (member (org-get-todo-state) org-done-keywords))
13081 (defun org-get-todo-state ()
13082 "Return the TODO keyword of the current subtree."
13083 (save-excursion
13084 (org-back-to-heading t)
13085 (and (looking-at org-todo-line-regexp)
13086 (match-end 2)
13087 (match-string 2))))
13089 (defun org-at-date-range-p (&optional inactive-ok)
13090 "Is the cursor inside a date range?"
13091 (interactive)
13092 (save-excursion
13093 (catch 'exit
13094 (let ((pos (point)))
13095 (skip-chars-backward "^[<\r\n")
13096 (skip-chars-backward "<[")
13097 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13098 (>= (match-end 0) pos)
13099 (throw 'exit t))
13100 (skip-chars-backward "^<[\r\n")
13101 (skip-chars-backward "<[")
13102 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13103 (>= (match-end 0) pos)
13104 (throw 'exit t)))
13105 nil)))
13107 (defun org-get-repeat (&optional tagline)
13108 "Check if there is a deadline/schedule with repeater in this entry."
13109 (save-match-data
13110 (save-excursion
13111 (org-back-to-heading t)
13112 (and (re-search-forward (if tagline
13113 (concat tagline "\\s-*" org-repeat-re)
13114 org-repeat-re)
13115 (org-entry-end-position) t)
13116 (match-string-no-properties 1)))))
13118 (defvar org-last-changed-timestamp)
13119 (defvar org-last-inserted-timestamp)
13120 (defvar org-log-post-message)
13121 (defvar org-log-note-purpose)
13122 (defvar org-log-note-how nil)
13123 (defvar org-log-note-extra)
13124 (defun org-auto-repeat-maybe (done-word)
13125 "Check if the current headline contains a repeated deadline/schedule.
13126 If yes, set TODO state back to what it was and change the base date
13127 of repeating deadline/scheduled time stamps to new date.
13128 This function is run automatically after each state change to a DONE state."
13129 ;; last-state is dynamically scoped into this function
13130 (let* ((repeat (org-get-repeat))
13131 (aa (assoc org-last-state org-todo-kwd-alist))
13132 (interpret (nth 1 aa))
13133 (head (nth 2 aa))
13134 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13135 (msg "Entry repeats: ")
13136 (org-log-done nil)
13137 (org-todo-log-states nil)
13138 re type n what ts time to-state)
13139 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13140 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13141 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13142 org-todo-repeat-to-state))
13143 (unless (and to-state (member to-state org-todo-keywords-1))
13144 (setq to-state (if (eq interpret 'type) org-last-state head)))
13145 (org-todo to-state)
13146 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13147 (org-entry-put nil "LAST_REPEAT" (format-time-string
13148 (org-time-stamp-format t t))))
13149 (when org-log-repeat
13150 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13151 (memq 'org-add-log-note post-command-hook))
13152 ;; OK, we are already setup for some record
13153 (if (eq org-log-repeat 'note)
13154 ;; make sure we take a note, not only a time stamp
13155 (setq org-log-note-how 'note))
13156 ;; Set up for taking a record
13157 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13158 org-last-state
13159 'findpos org-log-repeat)))
13160 (org-back-to-heading t)
13161 (org-add-planning-info nil nil 'closed)
13162 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13163 org-deadline-time-regexp "\\)\\|\\("
13164 org-ts-regexp "\\)"))
13165 (while (re-search-forward
13166 re (save-excursion (outline-next-heading) (point)) t)
13167 (setq type (if (match-end 1) org-scheduled-string
13168 (if (match-end 3) org-deadline-string "Plain:"))
13169 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13170 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13171 (setq n (string-to-number (match-string 2 ts))
13172 what (match-string 3 ts))
13173 (if (equal what "w") (setq n (* n 7) what "d"))
13174 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13175 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13176 ;; Preparation, see if we need to modify the start date for the change
13177 (when (match-end 1)
13178 (setq time (save-match-data (org-time-string-to-time ts)))
13179 (cond
13180 ((equal (match-string 1 ts) ".")
13181 ;; Shift starting date to today
13182 (org-timestamp-change
13183 (- (org-today) (time-to-days time))
13184 'day))
13185 ((equal (match-string 1 ts) "+")
13186 (let ((nshiftmax 10) (nshift 0))
13187 (while (or (= nshift 0)
13188 (<= (time-to-days time)
13189 (time-to-days (current-time))))
13190 (when (= (incf nshift) nshiftmax)
13191 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13192 (user-error "Abort")))
13193 (org-timestamp-change n (cdr (assoc what whata)))
13194 (org-at-timestamp-p t)
13195 (setq ts (match-string 1))
13196 (setq time (save-match-data (org-time-string-to-time ts)))))
13197 (org-timestamp-change (- n) (cdr (assoc what whata)))
13198 ;; rematch, so that we have everything in place for the real shift
13199 (org-at-timestamp-p t)
13200 (setq ts (match-string 1))
13201 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13202 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13203 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13204 (setq org-log-post-message msg)
13205 (message "%s" msg))))
13207 (defun org-show-todo-tree (arg)
13208 "Make a compact tree which shows all headlines marked with TODO.
13209 The tree will show the lines where the regexp matches, and all higher
13210 headlines above the match.
13211 With a \\[universal-argument] prefix, prompt for a regexp to match.
13212 With a numeric prefix N, construct a sparse tree for the Nth element
13213 of `org-todo-keywords-1'."
13214 (interactive "P")
13215 (let ((case-fold-search nil)
13216 (kwd-re
13217 (cond ((null arg) org-not-done-regexp)
13218 ((equal arg '(4))
13219 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13220 (mapcar 'list org-todo-keywords-1))))
13221 (concat "\\("
13222 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13223 "\\)\\>")))
13224 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13225 (regexp-quote (nth (1- (prefix-numeric-value arg))
13226 org-todo-keywords-1)))
13227 (t (user-error "Invalid prefix argument: %s" arg)))))
13228 (message "%d TODO entries found"
13229 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13231 (defun org-deadline (arg &optional time)
13232 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13233 With one universal prefix argument, remove any deadline from the item.
13234 With two universal prefix arguments, prompt for a warning delay.
13235 With argument TIME, set the deadline at the corresponding date. TIME
13236 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13237 (interactive "P")
13238 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13239 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13240 'region-start-level 'region))
13241 org-loop-over-headlines-in-active-region)
13242 (org-map-entries
13243 `(org-deadline ',arg ,time)
13244 org-loop-over-headlines-in-active-region
13245 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13246 (let* ((old-date (org-entry-get nil "DEADLINE"))
13247 (old-date-time (if old-date (org-time-string-to-time old-date)))
13248 (repeater (and old-date
13249 (string-match
13250 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13251 old-date)
13252 (match-string 1 old-date))))
13253 (cond
13254 ((equal arg '(4))
13255 (when (and old-date org-log-redeadline)
13256 (org-add-log-setup 'deldeadline nil old-date 'findpos
13257 org-log-redeadline))
13258 (org-remove-timestamp-with-keyword org-deadline-string)
13259 (message "Item no longer has a deadline."))
13260 ((equal arg '(16))
13261 (save-excursion
13262 (org-back-to-heading t)
13263 (if (re-search-forward
13264 org-deadline-time-regexp
13265 (save-excursion (outline-next-heading) (point)) t)
13266 (let* ((rpl0 (match-string 1))
13267 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13268 (replace-match
13269 (concat org-deadline-string
13270 " <" rpl
13271 (format " -%dd"
13272 (abs
13273 (- (time-to-days
13274 (save-match-data
13275 (org-read-date nil t nil "Warn starting from" old-date-time)))
13276 (time-to-days old-date-time))))
13277 ">") t t))
13278 (user-error "No deadline information to update"))))
13280 (org-add-planning-info 'deadline time 'closed)
13281 (when (and old-date org-log-redeadline
13282 (not (equal old-date
13283 (substring org-last-inserted-timestamp 1 -1))))
13284 (org-add-log-setup 'redeadline nil old-date 'findpos
13285 org-log-redeadline))
13286 (when repeater
13287 (save-excursion
13288 (org-back-to-heading t)
13289 (when (re-search-forward (concat org-deadline-string " "
13290 org-last-inserted-timestamp)
13291 (save-excursion
13292 (outline-next-heading) (point)) t)
13293 (goto-char (1- (match-end 0)))
13294 (insert " " repeater)
13295 (setq org-last-inserted-timestamp
13296 (concat (substring org-last-inserted-timestamp 0 -1)
13297 " " repeater
13298 (substring org-last-inserted-timestamp -1))))))
13299 (message "Deadline on %s" org-last-inserted-timestamp))))))
13301 (defun org-schedule (arg &optional time)
13302 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13303 With one universal prefix argument, remove any scheduling date from the item.
13304 With two universal prefix arguments, prompt for a delay cookie.
13305 With argument TIME, scheduled at the corresponding date. TIME can
13306 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13307 (interactive "P")
13308 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13309 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13310 'region-start-level 'region))
13311 org-loop-over-headlines-in-active-region)
13312 (org-map-entries
13313 `(org-schedule ',arg ,time)
13314 org-loop-over-headlines-in-active-region
13315 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13316 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13317 (old-date-time (if old-date (org-time-string-to-time old-date)))
13318 (repeater (and old-date
13319 (string-match
13320 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13321 old-date)
13322 (match-string 1 old-date))))
13323 (cond
13324 ((equal arg '(4))
13325 (progn
13326 (when (and old-date org-log-reschedule)
13327 (org-add-log-setup 'delschedule nil old-date 'findpos
13328 org-log-reschedule))
13329 (org-remove-timestamp-with-keyword org-scheduled-string)
13330 (message "Item is no longer scheduled.")))
13331 ((equal arg '(16))
13332 (save-excursion
13333 (org-back-to-heading t)
13334 (if (re-search-forward
13335 org-scheduled-time-regexp
13336 (save-excursion (outline-next-heading) (point)) t)
13337 (let* ((rpl0 (match-string 1))
13338 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13339 (replace-match
13340 (concat org-scheduled-string
13341 " <" rpl
13342 (format " -%dd"
13343 (abs
13344 (- (time-to-days
13345 (save-match-data
13346 (org-read-date nil t nil "Delay until" old-date-time)))
13347 (time-to-days old-date-time))))
13348 ">") t t))
13349 (user-error "No scheduled information to update"))))
13351 (org-add-planning-info 'scheduled time 'closed)
13352 (when (and old-date org-log-reschedule
13353 (not (equal old-date
13354 (substring org-last-inserted-timestamp 1 -1))))
13355 (org-add-log-setup 'reschedule nil old-date 'findpos
13356 org-log-reschedule))
13357 (when repeater
13358 (save-excursion
13359 (org-back-to-heading t)
13360 (when (re-search-forward (concat org-scheduled-string " "
13361 org-last-inserted-timestamp)
13362 (save-excursion
13363 (outline-next-heading) (point)) t)
13364 (goto-char (1- (match-end 0)))
13365 (insert " " repeater)
13366 (setq org-last-inserted-timestamp
13367 (concat (substring org-last-inserted-timestamp 0 -1)
13368 " " repeater
13369 (substring org-last-inserted-timestamp -1))))))
13370 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13372 (defun org-get-scheduled-time (pom &optional inherit)
13373 "Get the scheduled time as a time tuple, of a format suitable
13374 for calling org-schedule with, or if there is no scheduling,
13375 returns nil."
13376 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13377 (when time
13378 (apply 'encode-time (org-parse-time-string time)))))
13380 (defun org-get-deadline-time (pom &optional inherit)
13381 "Get the deadline as a time tuple, of a format suitable for
13382 calling org-deadline with, or if there is no scheduling, returns
13383 nil."
13384 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13385 (when time
13386 (apply 'encode-time (org-parse-time-string time)))))
13388 (defun org-remove-timestamp-with-keyword (keyword)
13389 "Remove all time stamps with KEYWORD in the current entry."
13390 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13391 beg)
13392 (save-excursion
13393 (org-back-to-heading t)
13394 (setq beg (point))
13395 (outline-next-heading)
13396 (while (re-search-backward re beg t)
13397 (replace-match "")
13398 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13399 (equal (char-before) ?\ ))
13400 (backward-delete-char 1)
13401 (if (string-match "^[ \t]*$" (buffer-substring
13402 (point-at-bol) (point-at-eol)))
13403 (delete-region (point-at-bol)
13404 (min (point-max) (1+ (point-at-eol))))))))))
13406 (defvar org-time-was-given) ; dynamically scoped parameter
13407 (defvar org-end-time-was-given) ; dynamically scoped parameter
13409 (defun org-add-planning-info (what &optional time &rest remove)
13410 "Insert new timestamp with keyword in the line directly after the headline.
13411 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13412 If non is given, the user is prompted for a date.
13413 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13414 be removed."
13415 (interactive)
13416 (let (org-time-was-given org-end-time-was-given ts
13417 end default-time default-input)
13419 (catch 'exit
13420 (when (and (memq what '(scheduled deadline))
13421 (or (not time)
13422 (and (stringp time)
13423 (string-match "^[-+]+[0-9]" time))))
13424 ;; Try to get a default date/time from existing timestamp
13425 (save-excursion
13426 (org-back-to-heading t)
13427 (setq end (save-excursion (outline-next-heading) (point)))
13428 (when (re-search-forward (if (eq what 'scheduled)
13429 org-scheduled-time-regexp
13430 org-deadline-time-regexp)
13431 end t)
13432 (setq ts (match-string 1)
13433 default-time
13434 (apply 'encode-time (org-parse-time-string ts))
13435 default-input (and ts (org-get-compact-tod ts))))))
13436 (when what
13437 (setq time
13438 (if (stringp time)
13439 ;; This is a string (relative or absolute), set proper date
13440 (apply 'encode-time
13441 (org-read-date-analyze
13442 time default-time (decode-time default-time)))
13443 ;; If necessary, get the time from the user
13444 (or time (org-read-date nil 'to-time nil nil
13445 default-time default-input)))))
13447 (when (and org-insert-labeled-timestamps-at-point
13448 (member what '(scheduled deadline)))
13449 (insert
13450 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13451 (org-insert-time-stamp time org-time-was-given
13452 nil nil nil (list org-end-time-was-given))
13453 (setq what nil))
13454 (save-excursion
13455 (save-restriction
13456 (let (col list elt ts buffer-invisibility-spec)
13457 (org-back-to-heading t)
13458 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13459 (goto-char (match-end 1))
13460 (setq col (current-column))
13461 (goto-char (match-end 0))
13462 (if (eobp) (insert "\n") (forward-char 1))
13463 (when (and (not what)
13464 (not (looking-at
13465 (concat "[ \t]*"
13466 org-keyword-time-not-clock-regexp))))
13467 ;; Nothing to add, nothing to remove...... :-)
13468 (throw 'exit nil))
13469 (if (and (not (looking-at org-outline-regexp))
13470 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13471 "[^\r\n]*"))
13472 (not (equal (match-string 1) org-clock-string)))
13473 (narrow-to-region (match-beginning 0) (match-end 0))
13474 (insert-before-markers "\n")
13475 (backward-char 1)
13476 (narrow-to-region (point) (point))
13477 (and org-adapt-indentation (org-indent-to-column col)))
13478 ;; Check if we have to remove something.
13479 (setq list (cons what remove))
13480 (while list
13481 (setq elt (pop list))
13482 (when (or (and (eq elt 'scheduled)
13483 (re-search-forward org-scheduled-time-regexp nil t))
13484 (and (eq elt 'deadline)
13485 (re-search-forward org-deadline-time-regexp nil t))
13486 (and (eq elt 'closed)
13487 (re-search-forward org-closed-time-regexp nil t)))
13488 (replace-match "")
13489 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13490 (and (looking-at "[ \t]+") (replace-match ""))
13491 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13492 (when what
13493 (insert
13494 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13495 (cond ((eq what 'scheduled) org-scheduled-string)
13496 ((eq what 'deadline) org-deadline-string)
13497 ((eq what 'closed) org-closed-string))
13498 " ")
13499 (setq ts (org-insert-time-stamp
13500 time
13501 (or org-time-was-given
13502 (and (eq what 'closed) org-log-done-with-time))
13503 (eq what 'closed)
13504 nil nil (list org-end-time-was-given)))
13505 (insert
13506 (if (not (or (bolp) (eq (char-before) ?\ )
13507 (memq (char-after) '(32 10))
13508 (eobp))) " " ""))
13509 (end-of-line 1))
13510 (goto-char (point-min))
13511 (widen)
13512 (if (and (looking-at "[ \t]*\n")
13513 (equal (char-before) ?\n))
13514 (delete-region (1- (point)) (point-at-eol)))
13515 ts))))))
13517 (defvar org-log-note-marker (make-marker))
13518 (defvar org-log-note-purpose nil)
13519 (defvar org-log-note-state nil)
13520 (defvar org-log-note-previous-state nil)
13521 (defvar org-log-note-extra nil)
13522 (defvar org-log-note-window-configuration nil)
13523 (defvar org-log-note-return-to (make-marker))
13524 (defvar org-log-note-effective-time nil
13525 "Remembered current time so that dynamically scoped
13526 `org-extend-today-until' affects tha timestamps in state change
13527 log")
13529 (defvar org-log-post-message nil
13530 "Message to be displayed after a log note has been stored.
13531 The auto-repeater uses this.")
13533 (defun org-add-note ()
13534 "Add a note to the current entry.
13535 This is done in the same way as adding a state change note."
13536 (interactive)
13537 (org-add-log-setup 'note nil nil 'findpos nil))
13539 (defvar org-property-end-re)
13540 (defun org-add-log-setup (&optional purpose state prev-state
13541 findpos how extra)
13542 "Set up the post command hook to take a note.
13543 If this is about to TODO state change, the new state is expected in STATE.
13544 When FINDPOS is non-nil, find the correct position for the note in
13545 the current entry. If not, assume that it can be inserted at point.
13546 HOW is an indicator what kind of note should be created.
13547 EXTRA is additional text that will be inserted into the notes buffer."
13548 (let* ((org-log-into-drawer (org-log-into-drawer))
13549 (drawer (cond ((stringp org-log-into-drawer)
13550 org-log-into-drawer)
13551 (org-log-into-drawer "LOGBOOK"))))
13552 (save-restriction
13553 (save-excursion
13554 (when findpos
13555 (org-back-to-heading t)
13556 (narrow-to-region (point) (save-excursion
13557 (outline-next-heading) (point)))
13558 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13559 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13560 "[^\r\n]*\\)?"))
13561 (goto-char (match-end 0))
13562 (cond
13563 (drawer
13564 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13565 nil t)
13566 (progn
13567 (goto-char (match-end 0))
13568 (or org-log-states-order-reversed
13569 (and (re-search-forward org-property-end-re nil t)
13570 (goto-char (1- (match-beginning 0))))))
13571 (insert "\n:" drawer ":\n:END:")
13572 (beginning-of-line 0)
13573 (org-indent-line)
13574 (beginning-of-line 2)
13575 (org-indent-line)
13576 (end-of-line 0)))
13577 ((and org-log-state-notes-insert-after-drawers
13578 (save-excursion
13579 (forward-line) (looking-at org-drawer-regexp)))
13580 (forward-line)
13581 (while (looking-at org-drawer-regexp)
13582 (goto-char (match-end 0))
13583 (re-search-forward org-property-end-re (point-max) t)
13584 (forward-line))
13585 (forward-line -1)))
13586 (unless org-log-states-order-reversed
13587 (and (= (char-after) ?\n) (forward-char 1))
13588 (org-skip-over-state-notes)
13589 (skip-chars-backward " \t\n\r")))
13590 (move-marker org-log-note-marker (point))
13591 (setq org-log-note-purpose purpose
13592 org-log-note-state state
13593 org-log-note-previous-state prev-state
13594 org-log-note-how how
13595 org-log-note-extra extra
13596 org-log-note-effective-time (org-current-effective-time))
13597 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13599 (defun org-skip-over-state-notes ()
13600 "Skip past the list of State notes in an entry."
13601 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13602 (when (ignore-errors (goto-char (org-in-item-p)))
13603 (let* ((struct (org-list-struct))
13604 (prevs (org-list-prevs-alist struct)))
13605 (while (looking-at "[ \t]*- State")
13606 (goto-char (or (org-list-get-next-item (point) struct prevs)
13607 (org-list-get-item-end (point) struct)))))))
13609 (defun org-add-log-note (&optional purpose)
13610 "Pop up a window for taking a note, and add this note later at point."
13611 (remove-hook 'post-command-hook 'org-add-log-note)
13612 (setq org-log-note-window-configuration (current-window-configuration))
13613 (delete-other-windows)
13614 (move-marker org-log-note-return-to (point))
13615 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13616 (goto-char org-log-note-marker)
13617 (org-switch-to-buffer-other-window "*Org Note*")
13618 (erase-buffer)
13619 (if (memq org-log-note-how '(time state))
13620 (let (current-prefix-arg) (org-store-log-note))
13621 (let ((org-inhibit-startup t)) (org-mode))
13622 (insert (format "# Insert note for %s.
13623 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13624 (cond
13625 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13626 ((eq org-log-note-purpose 'done) "closed todo item")
13627 ((eq org-log-note-purpose 'state)
13628 (format "state change from \"%s\" to \"%s\""
13629 (or org-log-note-previous-state "")
13630 (or org-log-note-state "")))
13631 ((eq org-log-note-purpose 'reschedule)
13632 "rescheduling")
13633 ((eq org-log-note-purpose 'delschedule)
13634 "no longer scheduled")
13635 ((eq org-log-note-purpose 'redeadline)
13636 "changing deadline")
13637 ((eq org-log-note-purpose 'deldeadline)
13638 "removing deadline")
13639 ((eq org-log-note-purpose 'refile)
13640 "refiling")
13641 ((eq org-log-note-purpose 'note)
13642 "this entry")
13643 (t (error "This should not happen")))))
13644 (if org-log-note-extra (insert org-log-note-extra))
13645 (org-set-local 'org-finish-function 'org-store-log-note)
13646 (run-hooks 'org-log-buffer-setup-hook)))
13648 (defvar org-note-abort nil) ; dynamically scoped
13649 (defun org-store-log-note ()
13650 "Finish taking a log note, and insert it to where it belongs."
13651 (let ((txt (buffer-string)))
13652 (kill-buffer (current-buffer))
13653 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13654 lines ind bul)
13655 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13656 (setq txt (replace-match "" t t txt)))
13657 (if (string-match "\\s-+\\'" txt)
13658 (setq txt (replace-match "" t t txt)))
13659 (setq lines (org-split-string txt "\n"))
13660 (when (and note (string-match "\\S-" note))
13661 (setq note
13662 (org-replace-escapes
13663 note
13664 (list (cons "%u" (user-login-name))
13665 (cons "%U" user-full-name)
13666 (cons "%t" (format-time-string
13667 (org-time-stamp-format 'long 'inactive)
13668 org-log-note-effective-time))
13669 (cons "%T" (format-time-string
13670 (org-time-stamp-format 'long nil)
13671 org-log-note-effective-time))
13672 (cons "%d" (format-time-string
13673 (org-time-stamp-format nil 'inactive)
13674 org-log-note-effective-time))
13675 (cons "%D" (format-time-string
13676 (org-time-stamp-format nil nil)
13677 org-log-note-effective-time))
13678 (cons "%s" (if org-log-note-state
13679 (concat "\"" org-log-note-state "\"")
13680 ""))
13681 (cons "%S" (if org-log-note-previous-state
13682 (concat "\"" org-log-note-previous-state "\"")
13683 "\"\"")))))
13684 (if lines (setq note (concat note " \\\\")))
13685 (push note lines))
13686 (when (or current-prefix-arg org-note-abort)
13687 (when org-log-into-drawer
13688 (org-remove-empty-drawer-at org-log-note-marker))
13689 (setq lines nil))
13690 (when lines
13691 (with-current-buffer (marker-buffer org-log-note-marker)
13692 (save-excursion
13693 (goto-char org-log-note-marker)
13694 (move-marker org-log-note-marker nil)
13695 (end-of-line 1)
13696 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13697 (setq ind (save-excursion
13698 (if (ignore-errors (goto-char (org-in-item-p)))
13699 (let ((struct (org-list-struct)))
13700 (org-list-get-ind
13701 (org-list-get-top-point struct) struct))
13702 (skip-chars-backward " \r\t\n")
13703 (cond
13704 ((and (org-at-heading-p)
13705 org-adapt-indentation)
13706 (1+ (org-current-level)))
13707 ((org-at-heading-p) 0)
13708 (t (org-get-indentation))))))
13709 (setq bul (org-list-bullet-string "-"))
13710 (org-indent-line-to ind)
13711 (insert bul (pop lines))
13712 (let ((ind-body (+ (length bul) ind)))
13713 (while lines
13714 (insert "\n")
13715 (org-indent-line-to ind-body)
13716 (insert (pop lines))))
13717 (message "Note stored")
13718 (org-back-to-heading t)
13719 (org-cycle-hide-drawers 'children))
13720 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13721 ;; from within `org-add-log-note' because `buffer-undo-list'
13722 ;; is then modified outside of `org-with-remote-undo'.
13723 (when (eq this-command 'org-agenda-todo)
13724 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13725 ;; Don't add undo information when called from `org-agenda-todo'
13726 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13727 (set-window-configuration org-log-note-window-configuration)
13728 (with-current-buffer (marker-buffer org-log-note-return-to)
13729 (goto-char org-log-note-return-to))
13730 (move-marker org-log-note-return-to nil)
13731 (and org-log-post-message (message "%s" org-log-post-message))))
13733 (defun org-remove-empty-drawer-at (pos)
13734 "Remove an empty drawer at position POS.
13735 POS may also be a marker."
13736 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13737 (org-with-wide-buffer
13738 (goto-char pos)
13739 (let ((drawer (org-element-at-point)))
13740 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13741 (not (org-element-property :contents-begin drawer)))
13742 (delete-region (org-element-property :begin drawer)
13743 (progn (goto-char (org-element-property :end drawer))
13744 (skip-chars-backward " \r\t\n")
13745 (forward-line)
13746 (point))))))))
13748 (defvar org-ts-type nil)
13749 (defun org-sparse-tree (&optional arg type)
13750 "Create a sparse tree, prompt for the details.
13751 This command can create sparse trees. You first need to select the type
13752 of match used to create the tree:
13754 t Show all TODO entries.
13755 T Show entries with a specific TODO keyword.
13756 m Show entries selected by a tags/property match.
13757 p Enter a property name and its value (both with completion on existing
13758 names/values) and show entries with that property.
13759 r Show entries matching a regular expression (`/' can be used as well).
13760 b Show deadlines and scheduled items before a date.
13761 a Show deadlines and scheduled items after a date.
13762 d Show deadlines due within `org-deadline-warning-days'.
13763 D Show deadlines and scheduled items between a date range."
13764 (interactive "P")
13765 (setq type (or type org-sparse-tree-default-date-type))
13766 (setq org-ts-type type)
13767 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13768 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13769 [c]ycle through date types: %s"
13770 (case type
13771 (all "all timestamps")
13772 (scheduled "only scheduled")
13773 (deadline "only deadline")
13774 (active "only active timestamps")
13775 (inactive "only inactive timestamps")
13776 (scheduled-or-deadline "scheduled/deadline")
13777 (closed "with a closed time-stamp")
13778 (otherwise "scheduled/deadline")))
13779 (let ((answer (read-char-exclusive)))
13780 (case answer
13782 (org-sparse-tree
13784 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13785 inactive closed)))))
13786 (?d (call-interactively 'org-check-deadlines))
13787 (?b (call-interactively 'org-check-before-date))
13788 (?a (call-interactively 'org-check-after-date))
13789 (?D (call-interactively 'org-check-dates-range))
13790 (?t (call-interactively 'org-show-todo-tree))
13791 (?T (org-show-todo-tree '(4)))
13792 (?m (call-interactively 'org-match-sparse-tree))
13793 ((?p ?P)
13794 (let* ((kwd (org-icompleting-read
13795 "Property: " (mapcar 'list (org-buffer-property-keys))))
13796 (value (org-icompleting-read
13797 "Value: " (mapcar 'list (org-property-values kwd)))))
13798 (unless (string-match "\\`{.*}\\'" value)
13799 (setq value (concat "\"" value "\"")))
13800 (org-match-sparse-tree arg (concat kwd "=" value))))
13801 ((?r ?R ?/) (call-interactively 'org-occur))
13802 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13804 (defvar org-occur-highlights nil
13805 "List of overlays used for occur matches.")
13806 (make-variable-buffer-local 'org-occur-highlights)
13807 (defvar org-occur-parameters nil
13808 "Parameters of the active org-occur calls.
13809 This is a list, each call to org-occur pushes as cons cell,
13810 containing the regular expression and the callback, onto the list.
13811 The list can contain several entries if `org-occur' has been called
13812 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13813 will only contain one set of parameters. When the highlights are
13814 removed (for example with `C-c C-c', or with the next edit (depending
13815 on `org-remove-highlights-with-change'), this variable is emptied
13816 as well.")
13817 (make-variable-buffer-local 'org-occur-parameters)
13819 (defun org-occur (regexp &optional keep-previous callback)
13820 "Make a compact tree which shows all matches of REGEXP.
13821 The tree will show the lines where the regexp matches, and all higher
13822 headlines above the match. It will also show the heading after the match,
13823 to make sure editing the matching entry is easy.
13824 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13825 call to `org-occur' will be kept, to allow stacking of calls to this
13826 command.
13827 If CALLBACK is non-nil, it is a function which is called to confirm
13828 that the match should indeed be shown."
13829 (interactive "sRegexp: \nP")
13830 (when (equal regexp "")
13831 (user-error "Regexp cannot be empty"))
13832 (unless keep-previous
13833 (org-remove-occur-highlights nil nil t))
13834 (push (cons regexp callback) org-occur-parameters)
13835 (let ((cnt 0))
13836 (save-excursion
13837 (goto-char (point-min))
13838 (if (or (not keep-previous) ; do not want to keep
13839 (not org-occur-highlights)) ; no previous matches
13840 ;; hide everything
13841 (org-overview))
13842 (while (re-search-forward regexp nil t)
13843 (when (or (not callback)
13844 (save-match-data (funcall callback)))
13845 (setq cnt (1+ cnt))
13846 (when org-highlight-sparse-tree-matches
13847 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13848 (org-show-context 'occur-tree))))
13849 (when org-remove-highlights-with-change
13850 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13851 nil 'local))
13852 (unless org-sparse-tree-open-archived-trees
13853 (org-hide-archived-subtrees (point-min) (point-max)))
13854 (run-hooks 'org-occur-hook)
13855 (if (org-called-interactively-p 'interactive)
13856 (message "%d match(es) for regexp %s" cnt regexp))
13857 cnt))
13859 (defun org-occur-next-match (&optional n reset)
13860 "Function for `next-error-function' to find sparse tree matches.
13861 N is the number of matches to move, when negative move backwards.
13862 RESET is entirely ignored - this function always goes back to the
13863 starting point when no match is found."
13864 (let* ((limit (if (< n 0) (point-min) (point-max)))
13865 (search-func (if (< n 0)
13866 'previous-single-char-property-change
13867 'next-single-char-property-change))
13868 (n (abs n))
13869 (pos (point))
13871 (catch 'exit
13872 (while (setq p1 (funcall search-func (point) 'org-type))
13873 (when (equal p1 limit)
13874 (goto-char pos)
13875 (user-error "No more matches"))
13876 (when (equal (get-char-property p1 'org-type) 'org-occur)
13877 (setq n (1- n))
13878 (when (= n 0)
13879 (goto-char p1)
13880 (throw 'exit (point))))
13881 (goto-char p1))
13882 (goto-char p1)
13883 (user-error "No more matches"))))
13885 (defun org-show-context (&optional key)
13886 "Make sure point and context are visible.
13887 How much context is shown depends upon the variables
13888 `org-show-hierarchy-above', `org-show-following-heading',
13889 `org-show-entry-below' and `org-show-siblings'."
13890 (let ((heading-p (org-at-heading-p t))
13891 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13892 (following-p (org-get-alist-option org-show-following-heading key))
13893 (entry-p (org-get-alist-option org-show-entry-below key))
13894 (siblings-p (org-get-alist-option org-show-siblings key)))
13895 ;; Show heading or entry text
13896 (if (and heading-p (not entry-p))
13897 (org-flag-heading nil) ; only show the heading
13898 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13899 (org-show-hidden-entry))) ; show entire entry
13900 (when following-p
13901 ;; Show next sibling, or heading below text
13902 (save-excursion
13903 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13904 (org-flag-heading nil))))
13905 (when siblings-p (org-show-siblings))
13906 (when hierarchy-p
13907 ;; show all higher headings, possibly with siblings
13908 (save-excursion
13909 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13910 (not (bobp)))
13911 (org-flag-heading nil)
13912 (when siblings-p (org-show-siblings)))))))
13914 (defvar org-reveal-start-hook nil
13915 "Hook run before revealing a location.")
13917 (defun org-reveal (&optional siblings)
13918 "Show current entry, hierarchy above it, and the following headline.
13919 This can be used to show a consistent set of context around locations
13920 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13921 not t for the search context.
13923 With optional argument SIBLINGS, on each level of the hierarchy all
13924 siblings are shown. This repairs the tree structure to what it would
13925 look like when opened with hierarchical calls to `org-cycle'.
13926 With double optional argument \\[universal-argument] \\[universal-argument], \
13927 go to the parent and show the
13928 entire tree."
13929 (interactive "P")
13930 (run-hooks 'org-reveal-start-hook)
13931 (let ((org-show-hierarchy-above t)
13932 (org-show-following-heading t)
13933 (org-show-siblings (if siblings t org-show-siblings)))
13934 (org-show-context nil))
13935 (when (equal siblings '(16))
13936 (save-excursion
13937 (when (org-up-heading-safe)
13938 (org-show-subtree)
13939 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13941 (defun org-highlight-new-match (beg end)
13942 "Highlight from BEG to END and mark the highlight is an occur headline."
13943 (let ((ov (make-overlay beg end)))
13944 (overlay-put ov 'face 'secondary-selection)
13945 (overlay-put ov 'org-type 'org-occur)
13946 (push ov org-occur-highlights)))
13948 (defun org-remove-occur-highlights (&optional beg end noremove)
13949 "Remove the occur highlights from the buffer.
13950 BEG and END are ignored. If NOREMOVE is nil, remove this function
13951 from the `before-change-functions' in the current buffer."
13952 (interactive)
13953 (unless org-inhibit-highlight-removal
13954 (mapc 'delete-overlay org-occur-highlights)
13955 (setq org-occur-highlights nil)
13956 (setq org-occur-parameters nil)
13957 (unless noremove
13958 (remove-hook 'before-change-functions
13959 'org-remove-occur-highlights 'local))))
13961 ;;;; Priorities
13963 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13964 "Regular expression matching the priority indicator.")
13966 (defvar org-remove-priority-next-time nil)
13968 (defun org-priority-up ()
13969 "Increase the priority of the current item."
13970 (interactive)
13971 (org-priority 'up))
13973 (defun org-priority-down ()
13974 "Decrease the priority of the current item."
13975 (interactive)
13976 (org-priority 'down))
13978 (defun org-priority (&optional action show)
13979 "Change the priority of an item.
13980 ACTION can be `set', `up', `down', or a character."
13981 (interactive "P")
13982 (if (equal action '(4))
13983 (org-show-priority)
13984 (unless org-enable-priority-commands
13985 (user-error "Priority commands are disabled"))
13986 (setq action (or action 'set))
13987 (let (current new news have remove)
13988 (save-excursion
13989 (org-back-to-heading t)
13990 (if (looking-at org-priority-regexp)
13991 (setq current (string-to-char (match-string 2))
13992 have t))
13993 (cond
13994 ((eq action 'remove)
13995 (setq remove t new ?\ ))
13996 ((or (eq action 'set)
13997 (if (featurep 'xemacs) (characterp action) (integerp action)))
13998 (if (not (eq action 'set))
13999 (setq new action)
14000 (message "Priority %c-%c, SPC to remove: "
14001 org-highest-priority org-lowest-priority)
14002 (save-match-data
14003 (setq new (read-char-exclusive))))
14004 (if (and (= (upcase org-highest-priority) org-highest-priority)
14005 (= (upcase org-lowest-priority) org-lowest-priority))
14006 (setq new (upcase new)))
14007 (cond ((equal new ?\ ) (setq remove t))
14008 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14009 (user-error "Priority must be between `%c' and `%c'"
14010 org-highest-priority org-lowest-priority))))
14011 ((eq action 'up)
14012 (setq new (if have
14013 (1- current) ; normal cycling
14014 ;; last priority was empty
14015 (if (eq last-command this-command)
14016 org-lowest-priority ; wrap around empty to lowest
14017 ;; default
14018 (if org-priority-start-cycle-with-default
14019 org-default-priority
14020 (1- org-default-priority))))))
14021 ((eq action 'down)
14022 (setq new (if have
14023 (1+ current) ; normal cycling
14024 ;; last priority was empty
14025 (if (eq last-command this-command)
14026 org-highest-priority ; wrap around empty to highest
14027 ;; default
14028 (if org-priority-start-cycle-with-default
14029 org-default-priority
14030 (1+ org-default-priority))))))
14031 (t (user-error "Invalid action")))
14032 (if (or (< (upcase new) org-highest-priority)
14033 (> (upcase new) org-lowest-priority))
14034 (if (and (memq action '(up down))
14035 (not have) (not (eq last-command this-command)))
14036 ;; `new' is from default priority
14037 (error
14038 "The default can not be set, see `org-default-priority' why")
14039 ;; normal cycling: `new' is beyond highest/lowest priority
14040 ;; and is wrapped around to the empty priority
14041 (setq remove t)))
14042 (setq news (format "%c" new))
14043 (if have
14044 (if remove
14045 (replace-match "" t t nil 1)
14046 (replace-match news t t nil 2))
14047 (if remove
14048 (user-error "No priority cookie found in line")
14049 (let ((case-fold-search nil))
14050 (looking-at org-todo-line-regexp))
14051 (if (match-end 2)
14052 (progn
14053 (goto-char (match-end 2))
14054 (insert " [#" news "]"))
14055 (goto-char (match-beginning 3))
14056 (insert "[#" news "] "))))
14057 (org-set-tags nil 'align))
14058 (if remove
14059 (message "Priority removed")
14060 (message "Priority of current item set to %s" news)))))
14062 (defun org-show-priority ()
14063 "Show the priority of the current item.
14064 This priority is composed of the main priority given with the [#A] cookies,
14065 and by additional input from the age of a schedules or deadline entry."
14066 (interactive)
14067 (let ((pri (if (eq major-mode 'org-agenda-mode)
14068 (org-get-at-bol 'priority)
14069 (save-excursion
14070 (save-match-data
14071 (beginning-of-line)
14072 (and (looking-at org-heading-regexp)
14073 (org-get-priority (match-string 0))))))))
14074 (message "Priority is %d" (if pri pri -1000))))
14076 (defun org-get-priority (s)
14077 "Find priority cookie and return priority."
14078 (save-match-data
14079 (if (functionp org-get-priority-function)
14080 (funcall org-get-priority-function)
14081 (if (not (string-match org-priority-regexp s))
14082 (* 1000 (- org-lowest-priority org-default-priority))
14083 (* 1000 (- org-lowest-priority
14084 (string-to-char (match-string 2 s))))))))
14086 ;;;; Tags
14088 (defvar org-agenda-archives-mode)
14089 (defvar org-map-continue-from nil
14090 "Position from where mapping should continue.
14091 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14093 (defvar org-scanner-tags nil
14094 "The current tag list while the tags scanner is running.")
14095 (defvar org-trust-scanner-tags nil
14096 "Should `org-get-tags-at' use the tags for the scanner.
14097 This is for internal dynamical scoping only.
14098 When this is non-nil, the function `org-get-tags-at' will return the value
14099 of `org-scanner-tags' instead of building the list by itself. This
14100 can lead to large speed-ups when the tags scanner is used in a file with
14101 many entries, and when the list of tags is retrieved, for example to
14102 obtain a list of properties. Building the tags list for each entry in such
14103 a file becomes an N^2 operation - but with this variable set, it scales
14104 as N.")
14106 (defun org-scan-tags (action matcher todo-only &optional start-level)
14107 "Scan headline tags with inheritance and produce output ACTION.
14109 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14110 or `agenda' to produce an entry list for an agenda view. It can also be
14111 a Lisp form or a function that should be called at each matched headline, in
14112 this case the return value is a list of all return values from these calls.
14114 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14115 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14116 only lines with a not-done TODO keyword are included in the output.
14117 This should be the same variable that was scoped into
14118 and set by `org-make-tags-matcher' when it constructed MATCHER.
14120 START-LEVEL can be a string with asterisks, reducing the scope to
14121 headlines matching this string."
14122 (require 'org-agenda)
14123 (let* ((re (concat "^"
14124 (if start-level
14125 ;; Get the correct level to match
14126 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14127 org-outline-regexp)
14128 " *\\(\\<\\("
14129 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14130 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14131 (props (list 'face 'default
14132 'done-face 'org-agenda-done
14133 'undone-face 'default
14134 'mouse-face 'highlight
14135 'org-not-done-regexp org-not-done-regexp
14136 'org-todo-regexp org-todo-regexp
14137 'org-complex-heading-regexp org-complex-heading-regexp
14138 'help-echo
14139 (format "mouse-2 or RET jump to org file %s"
14140 (abbreviate-file-name
14141 (or (buffer-file-name (buffer-base-buffer))
14142 (buffer-name (buffer-base-buffer)))))))
14143 (org-map-continue-from nil)
14144 lspos tags tags-list
14145 (tags-alist (list (cons 0 org-file-tags)))
14146 (llast 0) rtn rtn1 level category i txt
14147 todo marker entry priority)
14148 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14149 (setq action (list 'lambda nil action)))
14150 (save-excursion
14151 (goto-char (point-min))
14152 (when (eq action 'sparse-tree)
14153 (org-overview)
14154 (org-remove-occur-highlights))
14155 (while (let (case-fold-search)
14156 (re-search-forward re nil t))
14157 (setq org-map-continue-from nil)
14158 (catch :skip
14159 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14160 tags (if (match-end 4) (org-match-string-no-properties 4)))
14161 (goto-char (setq lspos (match-beginning 0)))
14162 (setq level (org-reduced-level (org-outline-level))
14163 category (org-get-category))
14164 (setq i llast llast level)
14165 ;; remove tag lists from same and sublevels
14166 (while (>= i level)
14167 (when (setq entry (assoc i tags-alist))
14168 (setq tags-alist (delete entry tags-alist)))
14169 (setq i (1- i)))
14170 ;; add the next tags
14171 (when tags
14172 (setq tags (org-split-string tags ":")
14173 tags-alist
14174 (cons (cons level tags) tags-alist)))
14175 ;; compile tags for current headline
14176 (setq tags-list
14177 (if org-use-tag-inheritance
14178 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14179 tags)
14180 org-scanner-tags tags-list)
14181 (when org-use-tag-inheritance
14182 (setcdr (car tags-alist)
14183 (mapcar (lambda (x)
14184 (setq x (copy-sequence x))
14185 (org-add-prop-inherited x))
14186 (cdar tags-alist))))
14187 (when (and tags org-use-tag-inheritance
14188 (or (not (eq t org-use-tag-inheritance))
14189 org-tags-exclude-from-inheritance))
14190 ;; selective inheritance, remove uninherited ones
14191 (setcdr (car tags-alist)
14192 (org-remove-uninherited-tags (cdar tags-alist))))
14193 (when (and
14195 ;; eval matcher only when the todo condition is OK
14196 (and (or (not todo-only) (member todo org-not-done-keywords))
14197 (let ((case-fold-search t) (org-trust-scanner-tags t))
14198 (eval matcher)))
14200 ;; Call the skipper, but return t if it does not skip,
14201 ;; so that the `and' form continues evaluating
14202 (progn
14203 (unless (eq action 'sparse-tree) (org-agenda-skip))
14206 ;; Check if timestamps are deselecting this entry
14207 (or (not todo-only)
14208 (and (member todo org-not-done-keywords)
14209 (or (not org-agenda-tags-todo-honor-ignore-options)
14210 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14212 ;; select this headline
14213 (cond
14214 ((eq action 'sparse-tree)
14215 (and org-highlight-sparse-tree-matches
14216 (org-get-heading) (match-end 0)
14217 (org-highlight-new-match
14218 (match-beginning 1) (match-end 1)))
14219 (org-show-context 'tags-tree))
14220 ((eq action 'agenda)
14221 (setq txt (org-agenda-format-item
14223 (concat
14224 (if (eq org-tags-match-list-sublevels 'indented)
14225 (make-string (1- level) ?.) "")
14226 (org-get-heading))
14227 level category
14228 tags-list)
14229 priority (org-get-priority txt))
14230 (goto-char lspos)
14231 (setq marker (org-agenda-new-marker))
14232 (org-add-props txt props
14233 'org-marker marker 'org-hd-marker marker 'org-category category
14234 'todo-state todo
14235 'priority priority 'type "tagsmatch")
14236 (push txt rtn))
14237 ((functionp action)
14238 (setq org-map-continue-from nil)
14239 (save-excursion
14240 (setq rtn1 (funcall action))
14241 (push rtn1 rtn)))
14242 (t (user-error "Invalid action")))
14244 ;; if we are to skip sublevels, jump to end of subtree
14245 (unless org-tags-match-list-sublevels
14246 (org-end-of-subtree t)
14247 (backward-char 1))))
14248 ;; Get the correct position from where to continue
14249 (if org-map-continue-from
14250 (goto-char org-map-continue-from)
14251 (and (= (point) lspos) (end-of-line 1)))))
14252 (when (and (eq action 'sparse-tree)
14253 (not org-sparse-tree-open-archived-trees))
14254 (org-hide-archived-subtrees (point-min) (point-max)))
14255 (nreverse rtn)))
14257 (defun org-remove-uninherited-tags (tags)
14258 "Remove all tags that are not inherited from the list TAGS."
14259 (cond
14260 ((eq org-use-tag-inheritance t)
14261 (if org-tags-exclude-from-inheritance
14262 (org-delete-all org-tags-exclude-from-inheritance tags)
14263 tags))
14264 ((not org-use-tag-inheritance) nil)
14265 ((stringp org-use-tag-inheritance)
14266 (delq nil (mapcar
14267 (lambda (x)
14268 (if (and (string-match org-use-tag-inheritance x)
14269 (not (member x org-tags-exclude-from-inheritance)))
14270 x nil))
14271 tags)))
14272 ((listp org-use-tag-inheritance)
14273 (delq nil (mapcar
14274 (lambda (x)
14275 (if (member x org-use-tag-inheritance) x nil))
14276 tags)))))
14278 (defun org-match-sparse-tree (&optional todo-only match)
14279 "Create a sparse tree according to tags string MATCH.
14280 MATCH can contain positive and negative selection of tags, like
14281 \"+WORK+URGENT-WITHBOSS\".
14282 If optional argument TODO-ONLY is non-nil, only select lines that are
14283 also TODO lines."
14284 (interactive "P")
14285 (org-agenda-prepare-buffers (list (current-buffer)))
14286 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14288 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14290 (defvar org-cached-props nil)
14291 (defun org-cached-entry-get (pom property)
14292 (if (or (eq t org-use-property-inheritance)
14293 (and (stringp org-use-property-inheritance)
14294 (string-match org-use-property-inheritance property))
14295 (and (listp org-use-property-inheritance)
14296 (member property org-use-property-inheritance)))
14297 ;; Caching is not possible, check it directly
14298 (org-entry-get pom property 'inherit)
14299 ;; Get all properties, so that we can do complicated checks easily
14300 (cdr (assoc property (or org-cached-props
14301 (setq org-cached-props
14302 (org-entry-properties pom)))))))
14304 (defun org-global-tags-completion-table (&optional files)
14305 "Return the list of all tags in all agenda buffer/files.
14306 Optional FILES argument is a list of files which can be used
14307 instead of the agenda files."
14308 (save-excursion
14309 (org-uniquify
14310 (delq nil
14311 (apply 'append
14312 (mapcar
14313 (lambda (file)
14314 (set-buffer (find-file-noselect file))
14315 (append (org-get-buffer-tags)
14316 (mapcar (lambda (x) (if (stringp (car-safe x))
14317 (list (car-safe x)) nil))
14318 org-tag-alist)))
14319 (if (and files (car files))
14320 files
14321 (org-agenda-files))))))))
14323 (defun org-make-tags-matcher (match)
14324 "Create the TAGS/TODO matcher form for the selection string MATCH.
14326 The variable `todo-only' is scoped dynamically into this function.
14327 It will be set to t if the matcher restricts matching to TODO entries,
14328 otherwise will not be touched.
14330 Returns a cons of the selection string MATCH and the constructed
14331 lisp form implementing the matcher. The matcher is to be evaluated
14332 at an Org entry, with point on the headline, and returns t if the
14333 entry matches the selection string MATCH. The returned lisp form
14334 references two variables with information about the entry, which
14335 must be bound around the form's evaluation: todo, the TODO keyword
14336 at the entry (or nil of none); and tags-list, the list of all tags
14337 at the entry including inherited ones. Additionally, the category
14338 of the entry (if any) must be specified as the text property
14339 'org-category on the headline.
14341 See also `org-scan-tags'.
14343 (declare (special todo-only))
14344 (unless (boundp 'todo-only)
14345 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14346 (unless match
14347 ;; Get a new match request, with completion against the global
14348 ;; tags table and the local tags in current buffer
14349 (let ((org-last-tags-completion-table
14350 (org-uniquify
14351 (delq nil (append (org-get-buffer-tags)
14352 (org-global-tags-completion-table))))))
14353 (setq match (org-completing-read-no-i
14354 "Match: " 'org-tags-completion-function nil nil nil
14355 'org-tags-history))))
14357 ;; Parse the string and create a lisp form
14358 (let ((match0 match)
14359 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14360 minus tag mm
14361 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14362 orterms term orlist re-p str-p level-p level-op time-p
14363 prop-p pn pv po gv rest (start 0) (ss 0))
14364 ;; Expand group tags
14365 (setq match (org-tags-expand match))
14367 ;; Check if there is a TODO part of this match, which would be the
14368 ;; part after a "/". TO make sure that this slash is not part of
14369 ;; a property value to be matched against, we also check that there
14370 ;; is no " after that slash.
14371 ;; First, find the last slash
14372 (while (string-match "/+" match ss)
14373 (setq start (match-beginning 0) ss (match-end 0)))
14374 (if (and (string-match "/+" match start)
14375 (not (save-match-data (string-match "\"" match start))))
14376 ;; match contains also a todo-matching request
14377 (progn
14378 (setq tagsmatch (substring match 0 (match-beginning 0))
14379 todomatch (substring match (match-end 0)))
14380 (if (string-match "^!" todomatch)
14381 (setq todo-only t todomatch (substring todomatch 1)))
14382 (if (string-match "^\\s-*$" todomatch)
14383 (setq todomatch nil)))
14384 ;; only matching tags
14385 (setq tagsmatch match todomatch nil))
14387 ;; Make the tags matcher
14388 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14389 (setq tagsmatcher t)
14390 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14391 (while (setq term (pop orterms))
14392 (while (and (equal (substring term -1) "\\") orterms)
14393 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14394 (while (string-match re term)
14395 (setq rest (substring term (match-end 0))
14396 minus (and (match-end 1)
14397 (equal (match-string 1 term) "-"))
14398 tag (save-match-data (replace-regexp-in-string
14399 "\\\\-" "-"
14400 (match-string 2 term)))
14401 re-p (equal (string-to-char tag) ?{)
14402 level-p (match-end 4)
14403 prop-p (match-end 5)
14404 mm (cond
14405 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14406 (level-p
14407 (setq level-op (org-op-to-function (match-string 3 term)))
14408 `(,level-op level ,(string-to-number
14409 (match-string 4 term))))
14410 (prop-p
14411 (setq pn (match-string 5 term)
14412 po (match-string 6 term)
14413 pv (match-string 7 term)
14414 re-p (equal (string-to-char pv) ?{)
14415 str-p (equal (string-to-char pv) ?\")
14416 time-p (save-match-data
14417 (string-match "^\"[[<].*[]>]\"$" pv))
14418 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14419 (if time-p (setq pv (org-matcher-time pv)))
14420 (setq po (org-op-to-function po (if time-p 'time str-p)))
14421 (cond
14422 ((equal pn "CATEGORY")
14423 (setq gv '(get-text-property (point) 'org-category)))
14424 ((equal pn "TODO")
14425 (setq gv 'todo))
14427 (setq gv `(org-cached-entry-get nil ,pn))))
14428 (if re-p
14429 (if (eq po 'org<>)
14430 `(not (string-match ,pv (or ,gv "")))
14431 `(string-match ,pv (or ,gv "")))
14432 (if str-p
14433 `(,po (or ,gv "") ,pv)
14434 `(,po (string-to-number (or ,gv ""))
14435 ,(string-to-number pv) ))))
14436 (t `(member ,tag tags-list)))
14437 mm (if minus (list 'not mm) mm)
14438 term rest)
14439 (push mm tagsmatcher))
14440 (push (if (> (length tagsmatcher) 1)
14441 (cons 'and tagsmatcher)
14442 (car tagsmatcher))
14443 orlist)
14444 (setq tagsmatcher nil))
14445 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14446 (setq tagsmatcher
14447 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14448 ;; Make the todo matcher
14449 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14450 (setq todomatcher t)
14451 (setq orterms (org-split-string todomatch "|") orlist nil)
14452 (while (setq term (pop orterms))
14453 (while (string-match re term)
14454 (setq minus (and (match-end 1)
14455 (equal (match-string 1 term) "-"))
14456 kwd (match-string 2 term)
14457 re-p (equal (string-to-char kwd) ?{)
14458 term (substring term (match-end 0))
14459 mm (if re-p
14460 `(string-match ,(substring kwd 1 -1) todo)
14461 (list 'equal 'todo kwd))
14462 mm (if minus (list 'not mm) mm))
14463 (push mm todomatcher))
14464 (push (if (> (length todomatcher) 1)
14465 (cons 'and todomatcher)
14466 (car todomatcher))
14467 orlist)
14468 (setq todomatcher nil))
14469 (setq todomatcher (if (> (length orlist) 1)
14470 (cons 'or orlist) (car orlist))))
14472 ;; Return the string and lisp forms of the matcher
14473 (setq matcher (if todomatcher
14474 (list 'and tagsmatcher todomatcher)
14475 tagsmatcher))
14476 (when todo-only
14477 (setq matcher (list 'and '(member todo org-not-done-keywords)
14478 matcher)))
14479 (cons match0 matcher)))
14481 (defun org-tags-expand (match &optional single-as-list downcased)
14482 "Expand group tags in MATCH.
14484 This replaces every group tag in MATCH with a regexp tag search.
14485 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14486 will be replaced like this:
14488 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14489 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14490 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14492 Replacing by a regexp preserves the structure of the match.
14493 E.g., this expansion
14495 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14497 will match anything tagged with \"Lab\" and \"Home\", or tagged
14498 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14500 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14501 assumed to be a single group tag, and the function will return
14502 the list of tags in this group.
14504 When DOWNCASE is non-nil, expand downcased TAGS."
14505 (if org-group-tags
14506 (let* ((case-fold-search t)
14507 (stable org-mode-syntax-table)
14508 (tal (or org-tag-groups-alist-for-agenda
14509 org-tag-groups-alist))
14510 (tal (if downcased
14511 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14512 (tml (mapcar 'car tal))
14513 (rtnmatch match) rpl)
14514 ;; @ and _ are allowed as word-components in tags
14515 (modify-syntax-entry ?@ "w" stable)
14516 (modify-syntax-entry ?_ "w" stable)
14517 (while (and tml
14518 (with-syntax-table stable
14519 (string-match
14520 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14521 (regexp-opt tml) "\\>\\)") rtnmatch)))
14522 (let* ((dir (match-string 1 rtnmatch))
14523 (tag (match-string 2 rtnmatch))
14524 (tag (if downcased (downcase tag) tag)))
14525 (setq tml (delete tag tml))
14526 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14527 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14528 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14529 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14530 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14531 (if single-as-list
14532 (or (reverse rpl) (list rtnmatch))
14533 rtnmatch))
14534 (if single-as-list (list (if downcased (downcase match) match))
14535 match)))
14537 (defun org-op-to-function (op &optional stringp)
14538 "Turn an operator into the appropriate function."
14539 (setq op
14540 (cond
14541 ((equal op "<" ) '(< string< org-time<))
14542 ((equal op ">" ) '(> org-string> org-time>))
14543 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14544 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14545 ((member op '("=" "==")) '(= string= org-time=))
14546 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14547 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14549 (defun org<> (a b) (not (= a b)))
14550 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14551 (defun org-string>= (a b) (not (string< a b)))
14552 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14553 (defun org-string<> (a b) (not (string= a b)))
14554 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14555 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14556 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14557 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14558 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14559 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14560 (defun org-2ft (s)
14561 "Convert S to a floating point time.
14562 If S is already a number, just return it. If it is a string, parse
14563 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14564 (cond
14565 ((numberp s) s)
14566 ((stringp s)
14567 (condition-case nil
14568 (float-time (apply 'encode-time (org-parse-time-string s)))
14569 (error 0.)))
14570 (t 0.)))
14572 (defun org-time-today ()
14573 "Time in seconds today at 0:00.
14574 Returns the float number of seconds since the beginning of the
14575 epoch to the beginning of today (00:00)."
14576 (float-time (apply 'encode-time
14577 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14579 (defun org-matcher-time (s)
14580 "Interpret a time comparison value."
14581 (save-match-data
14582 (cond
14583 ((string= s "<now>") (float-time))
14584 ((string= s "<today>") (org-time-today))
14585 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14586 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14587 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14588 (+ (org-time-today)
14589 (* (string-to-number (match-string 1 s))
14590 (cdr (assoc (match-string 2 s)
14591 '(("d" . 86400.0) ("w" . 604800.0)
14592 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14593 (t (org-2ft s)))))
14595 (defun org-match-any-p (re list)
14596 "Does re match any element of list?"
14597 (setq list (mapcar (lambda (x) (string-match re x)) list))
14598 (delq nil list))
14600 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14601 (defvar org-tags-overlay (make-overlay 1 1))
14602 (org-detach-overlay org-tags-overlay)
14604 (defun org-get-local-tags-at (&optional pos)
14605 "Get a list of tags defined in the current headline."
14606 (org-get-tags-at pos 'local))
14608 (defun org-get-local-tags ()
14609 "Get a list of tags defined in the current headline."
14610 (org-get-tags-at nil 'local))
14612 (defun org-get-tags-at (&optional pos local)
14613 "Get a list of all headline tags applicable at POS.
14614 POS defaults to point. If tags are inherited, the list contains
14615 the targets in the same sequence as the headlines appear, i.e.
14616 the tags of the current headline come last.
14617 When LOCAL is non-nil, only return tags from the current headline,
14618 ignore inherited ones."
14619 (interactive)
14620 (if (and org-trust-scanner-tags
14621 (or (not pos) (equal pos (point)))
14622 (not local))
14623 org-scanner-tags
14624 (let (tags ltags lastpos parent)
14625 (save-excursion
14626 (save-restriction
14627 (widen)
14628 (goto-char (or pos (point)))
14629 (save-match-data
14630 (catch 'done
14631 (condition-case nil
14632 (progn
14633 (org-back-to-heading t)
14634 (while (not (equal lastpos (point)))
14635 (setq lastpos (point))
14636 (when (looking-at
14637 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14638 (setq ltags (org-split-string
14639 (org-match-string-no-properties 1) ":"))
14640 (when parent
14641 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14642 (setq tags (append
14643 (if parent
14644 (org-remove-uninherited-tags ltags)
14645 ltags)
14646 tags)))
14647 (or org-use-tag-inheritance (throw 'done t))
14648 (if local (throw 'done t))
14649 (or (org-up-heading-safe) (error nil))
14650 (setq parent t)))
14651 (error nil)))))
14652 (if local
14653 tags
14654 (reverse (delete-dups
14655 (reverse (append
14656 (org-remove-uninherited-tags
14657 org-file-tags) tags)))))))))
14659 (defun org-add-prop-inherited (s)
14660 (add-text-properties 0 (length s) '(inherited t) s)
14663 (defun org-toggle-tag (tag &optional onoff)
14664 "Toggle the tag TAG for the current line.
14665 If ONOFF is `on' or `off', don't toggle but set to this state."
14666 (let (res current)
14667 (save-excursion
14668 (org-back-to-heading t)
14669 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14670 (point-at-eol) t)
14671 (progn
14672 (setq current (match-string 1))
14673 (replace-match ""))
14674 (setq current ""))
14675 (setq current (nreverse (org-split-string current ":")))
14676 (cond
14677 ((eq onoff 'on)
14678 (setq res t)
14679 (or (member tag current) (push tag current)))
14680 ((eq onoff 'off)
14681 (or (not (member tag current)) (setq current (delete tag current))))
14682 (t (if (member tag current)
14683 (setq current (delete tag current))
14684 (setq res t)
14685 (push tag current))))
14686 (end-of-line 1)
14687 (if current
14688 (progn
14689 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14690 (org-set-tags nil t))
14691 (delete-horizontal-space))
14692 (run-hooks 'org-after-tags-change-hook))
14693 res))
14695 (defun org-align-tags-here (to-col)
14696 ;; Assumes that this is a headline
14697 "Align tags on the current headline to TO-COL."
14698 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14699 (beginning-of-line 1)
14700 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14701 (< pos (match-beginning 2)))
14702 (progn
14703 (setq tags-l (- (match-end 2) (match-beginning 2)))
14704 (goto-char (match-beginning 1))
14705 (insert " ")
14706 (delete-region (point) (1+ (match-beginning 2)))
14707 (setq ncol (max (current-column)
14708 (1+ col)
14709 (if (> to-col 0)
14710 to-col
14711 (- (abs to-col) tags-l))))
14712 (setq p (point))
14713 (insert (make-string (- ncol (current-column)) ?\ ))
14714 (setq ncol (current-column))
14715 (when indent-tabs-mode (tabify p (point-at-eol)))
14716 (org-move-to-column (min ncol col)))
14717 (goto-char pos))))
14719 (defun org-set-tags-command (&optional arg just-align)
14720 "Call the set-tags command for the current entry."
14721 (interactive "P")
14722 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14723 (org-set-tags arg just-align)
14724 (save-excursion
14725 (unless (and (org-region-active-p)
14726 org-loop-over-headlines-in-active-region)
14727 (org-back-to-heading t))
14728 (org-set-tags arg just-align))))
14730 (defun org-set-tags-to (data)
14731 "Set the tags of the current entry to DATA, replacing the current tags.
14732 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14733 If DATA is nil or the empty string, any tags will be removed."
14734 (interactive "sTags: ")
14735 (setq data
14736 (cond
14737 ((eq data nil) "")
14738 ((equal data "") "")
14739 ((stringp data)
14740 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14741 ":"))
14742 ((listp data)
14743 (concat ":" (mapconcat 'identity data ":") ":"))))
14744 (when data
14745 (save-excursion
14746 (org-back-to-heading t)
14747 (when (looking-at org-complex-heading-regexp)
14748 (if (match-end 5)
14749 (progn
14750 (goto-char (match-beginning 5))
14751 (insert data)
14752 (delete-region (point) (point-at-eol))
14753 (org-set-tags nil 'align))
14754 (goto-char (point-at-eol))
14755 (insert " " data)
14756 (org-set-tags nil 'align)))
14757 (beginning-of-line 1)
14758 (if (looking-at ".*?\\([ \t]+\\)$")
14759 (delete-region (match-beginning 1) (match-end 1))))))
14761 (defun org-align-all-tags ()
14762 "Align the tags i all headings."
14763 (interactive)
14764 (save-excursion
14765 (or (ignore-errors (org-back-to-heading t))
14766 (outline-next-heading))
14767 (if (org-at-heading-p)
14768 (org-set-tags t)
14769 (message "No headings"))))
14771 (defvar org-indent-indentation-per-level)
14772 (defun org-set-tags (&optional arg just-align)
14773 "Set the tags for the current headline.
14774 With prefix ARG, realign all tags in headings in the current buffer.
14775 When JUST-ALIGN is non-nil, only align tags."
14776 (interactive "P")
14777 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14778 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14779 'region-start-level 'region))
14780 org-loop-over-headlines-in-active-region)
14781 (org-map-entries
14782 ;; We don't use ARG and JUST-ALIGN here because these args
14783 ;; are not useful when looping over headlines.
14784 `(org-set-tags)
14785 org-loop-over-headlines-in-active-region
14786 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14787 (let* ((re org-outline-regexp-bol)
14788 (current (unless arg (org-get-tags-string)))
14789 (col (current-column))
14790 (org-setting-tags t)
14791 table current-tags inherited-tags ; computed below when needed
14792 tags p0 c0 c1 rpl di tc level)
14793 (if arg
14794 (save-excursion
14795 (goto-char (point-min))
14796 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14797 (while (re-search-forward re nil t)
14798 (org-set-tags nil t)
14799 (end-of-line 1)))
14800 (message "All tags realigned to column %d" org-tags-column))
14801 (if just-align
14802 (setq tags current)
14803 ;; Get a new set of tags from the user
14804 (save-excursion
14805 (setq table (append org-tag-persistent-alist
14806 (or org-tag-alist (org-get-buffer-tags))
14807 (and
14808 org-complete-tags-always-offer-all-agenda-tags
14809 (org-global-tags-completion-table
14810 (org-agenda-files))))
14811 org-last-tags-completion-table table
14812 current-tags (org-split-string current ":")
14813 inherited-tags (nreverse
14814 (nthcdr (length current-tags)
14815 (nreverse (org-get-tags-at))))
14816 tags
14817 (if (or (eq t org-use-fast-tag-selection)
14818 (and org-use-fast-tag-selection
14819 (delq nil (mapcar 'cdr table))))
14820 (org-fast-tag-selection
14821 current-tags inherited-tags table
14822 (if org-fast-tag-selection-include-todo
14823 org-todo-key-alist))
14824 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14825 (org-trim
14826 (org-icompleting-read "Tags: "
14827 'org-tags-completion-function
14828 nil nil current 'org-tags-history))))))
14829 (while (string-match "[-+&]+" tags)
14830 ;; No boolean logic, just a list
14831 (setq tags (replace-match ":" t t tags))))
14833 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14835 (if org-tags-sort-function
14836 (setq tags (mapconcat 'identity
14837 (sort (org-split-string
14838 tags (org-re "[^[:alnum:]_@#%]+"))
14839 org-tags-sort-function) ":")))
14841 (if (string-match "\\`[\t ]*\\'" tags)
14842 (setq tags "")
14843 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14844 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14846 ;; Insert new tags at the correct column
14847 (beginning-of-line 1)
14848 (setq level (or (and (looking-at org-outline-regexp)
14849 (- (match-end 0) (point) 1))
14851 (cond
14852 ((and (equal current "") (equal tags "")))
14853 ((re-search-forward
14854 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14855 (point-at-eol) t)
14856 (if (equal tags "")
14857 (setq rpl "")
14858 (goto-char (match-beginning 0))
14859 (setq c0 (current-column)
14860 ;; compute offset for the case of org-indent-mode active
14861 di (if (org-bound-and-true-p org-indent-mode)
14862 (* (1- org-indent-indentation-per-level) (1- level))
14864 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14865 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14866 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14867 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14868 (replace-match rpl t t)
14869 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14870 tags)
14871 (t (error "Tags alignment failed")))
14872 (org-move-to-column col)
14873 (unless just-align
14874 (run-hooks 'org-after-tags-change-hook))))))
14876 (defun org-change-tag-in-region (beg end tag off)
14877 "Add or remove TAG for each entry in the region.
14878 This works in the agenda, and also in an org-mode buffer."
14879 (interactive
14880 (list (region-beginning) (region-end)
14881 (let ((org-last-tags-completion-table
14882 (if (derived-mode-p 'org-mode)
14883 (org-uniquify
14884 (delq nil (append (org-get-buffer-tags)
14885 (org-global-tags-completion-table))))
14886 (org-global-tags-completion-table))))
14887 (org-icompleting-read
14888 "Tag: " 'org-tags-completion-function nil nil nil
14889 'org-tags-history))
14890 (progn
14891 (message "[s]et or [r]emove? ")
14892 (equal (read-char-exclusive) ?r))))
14893 (if (fboundp 'deactivate-mark) (deactivate-mark))
14894 (let ((agendap (equal major-mode 'org-agenda-mode))
14895 l1 l2 m buf pos newhead (cnt 0))
14896 (goto-char end)
14897 (setq l2 (1- (org-current-line)))
14898 (goto-char beg)
14899 (setq l1 (org-current-line))
14900 (loop for l from l1 to l2 do
14901 (org-goto-line l)
14902 (setq m (get-text-property (point) 'org-hd-marker))
14903 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14904 (and agendap m))
14905 (setq buf (if agendap (marker-buffer m) (current-buffer))
14906 pos (if agendap m (point)))
14907 (with-current-buffer buf
14908 (save-excursion
14909 (save-restriction
14910 (goto-char pos)
14911 (setq cnt (1+ cnt))
14912 (org-toggle-tag tag (if off 'off 'on))
14913 (setq newhead (org-get-heading)))))
14914 (and agendap (org-agenda-change-all-lines newhead m))))
14915 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14917 (defun org-tags-completion-function (string predicate &optional flag)
14918 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14919 (confirm (lambda (x) (stringp (car x)))))
14920 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14921 (setq s1 (match-string 1 string)
14922 s2 (match-string 2 string))
14923 (setq s1 "" s2 string))
14924 (cond
14925 ((eq flag nil)
14926 ;; try completion
14927 (setq rtn (try-completion s2 ctable confirm))
14928 (if (stringp rtn)
14929 (setq rtn
14930 (concat s1 s2 (substring rtn (length s2))
14931 (if (and org-add-colon-after-tag-completion
14932 (assoc rtn ctable))
14933 ":" ""))))
14934 rtn)
14935 ((eq flag t)
14936 ;; all-completions
14937 (all-completions s2 ctable confirm))
14938 ((eq flag 'lambda)
14939 ;; exact match?
14940 (assoc s2 ctable)))))
14942 (defun org-fast-tag-insert (kwd tags face &optional end)
14943 "Insert KDW, and the TAGS, the latter with face FACE.
14944 Also insert END."
14945 (insert (format "%-12s" (concat kwd ":"))
14946 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14947 (or end "")))
14949 (defun org-fast-tag-show-exit (flag)
14950 (save-excursion
14951 (org-goto-line 3)
14952 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14953 (replace-match ""))
14954 (when flag
14955 (end-of-line 1)
14956 (org-move-to-column (- (window-width) 19) t)
14957 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14959 (defun org-set-current-tags-overlay (current prefix)
14960 "Add an overlay to CURRENT tag with PREFIX."
14961 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14962 (if (featurep 'xemacs)
14963 (org-overlay-display org-tags-overlay (concat prefix s)
14964 'secondary-selection)
14965 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14966 (org-overlay-display org-tags-overlay (concat prefix s)))))
14968 (defvar org-last-tag-selection-key nil)
14969 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14970 "Fast tag selection with single keys.
14971 CURRENT is the current list of tags in the headline, INHERITED is the
14972 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14973 possibly with grouping information. TODO-TABLE is a similar table with
14974 TODO keywords, should these have keys assigned to them.
14975 If the keys are nil, a-z are automatically assigned.
14976 Returns the new tags string, or nil to not change the current settings."
14977 (let* ((fulltable (append table todo-table))
14978 (maxlen (apply 'max (mapcar
14979 (lambda (x)
14980 (if (stringp (car x)) (string-width (car x)) 0))
14981 fulltable)))
14982 (buf (current-buffer))
14983 (expert (eq org-fast-tag-selection-single-key 'expert))
14984 (buffer-tags nil)
14985 (fwidth (+ maxlen 3 1 3))
14986 (ncol (/ (- (window-width) 4) fwidth))
14987 (i-face 'org-done)
14988 (c-face 'org-todo)
14989 tg cnt e c char c1 c2 ntable tbl rtn
14990 ov-start ov-end ov-prefix
14991 (exit-after-next org-fast-tag-selection-single-key)
14992 (done-keywords org-done-keywords)
14993 groups ingroup)
14994 (save-excursion
14995 (beginning-of-line 1)
14996 (if (looking-at
14997 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14998 (setq ov-start (match-beginning 1)
14999 ov-end (match-end 1)
15000 ov-prefix "")
15001 (setq ov-start (1- (point-at-eol))
15002 ov-end (1+ ov-start))
15003 (skip-chars-forward "^\n\r")
15004 (setq ov-prefix
15005 (concat
15006 (buffer-substring (1- (point)) (point))
15007 (if (> (current-column) org-tags-column)
15009 (make-string (- org-tags-column (current-column)) ?\ ))))))
15010 (move-overlay org-tags-overlay ov-start ov-end)
15011 (save-window-excursion
15012 (if expert
15013 (set-buffer (get-buffer-create " *Org tags*"))
15014 (delete-other-windows)
15015 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15016 (org-switch-to-buffer-other-window " *Org tags*"))
15017 (erase-buffer)
15018 (org-set-local 'org-done-keywords done-keywords)
15019 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15020 (org-fast-tag-insert "Current" current c-face "\n\n")
15021 (org-fast-tag-show-exit exit-after-next)
15022 (org-set-current-tags-overlay current ov-prefix)
15023 (setq tbl fulltable char ?a cnt 0)
15024 (while (setq e (pop tbl))
15025 (cond
15026 ((equal (car e) :startgroup)
15027 (push '() groups) (setq ingroup t)
15028 (when (not (= cnt 0))
15029 (setq cnt 0)
15030 (insert "\n"))
15031 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15032 ((equal (car e) :endgroup)
15033 (setq ingroup nil cnt 0)
15034 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15035 ((equal e '(:newline))
15036 (when (not (= cnt 0))
15037 (setq cnt 0)
15038 (insert "\n")
15039 (setq e (car tbl))
15040 (while (equal (car tbl) '(:newline))
15041 (insert "\n")
15042 (setq tbl (cdr tbl)))))
15043 ((equal e '(:grouptags)) nil)
15045 (setq tg (copy-sequence (car e)) c2 nil)
15046 (if (cdr e)
15047 (setq c (cdr e))
15048 ;; automatically assign a character.
15049 (setq c1 (string-to-char
15050 (downcase (substring
15051 tg (if (= (string-to-char tg) ?@) 1 0)))))
15052 (if (or (rassoc c1 ntable) (rassoc c1 table))
15053 (while (or (rassoc char ntable) (rassoc char table))
15054 (setq char (1+ char)))
15055 (setq c2 c1))
15056 (setq c (or c2 char)))
15057 (if ingroup (push tg (car groups)))
15058 (setq tg (org-add-props tg nil 'face
15059 (cond
15060 ((not (assoc tg table))
15061 (org-get-todo-face tg))
15062 ((member tg current) c-face)
15063 ((member tg inherited) i-face))))
15064 (if (equal (caar tbl) :grouptags)
15065 (org-add-props tg nil 'face 'org-tag-group))
15066 (if (and (= cnt 0) (not ingroup)) (insert " "))
15067 (insert "[" c "] " tg (make-string
15068 (- fwidth 4 (length tg)) ?\ ))
15069 (push (cons tg c) ntable)
15070 (when (= (setq cnt (1+ cnt)) ncol)
15071 (insert "\n")
15072 (if ingroup (insert " "))
15073 (setq cnt 0)))))
15074 (setq ntable (nreverse ntable))
15075 (insert "\n")
15076 (goto-char (point-min))
15077 (if (not expert) (org-fit-window-to-buffer))
15078 (setq rtn
15079 (catch 'exit
15080 (while t
15081 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15082 (if (not groups) "no " "")
15083 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15084 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15085 (setq org-last-tag-selection-key c)
15086 (cond
15087 ((= c ?\r) (throw 'exit t))
15088 ((= c ?!)
15089 (setq groups (not groups))
15090 (goto-char (point-min))
15091 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15092 ((= c ?\C-c)
15093 (if (not expert)
15094 (org-fast-tag-show-exit
15095 (setq exit-after-next (not exit-after-next)))
15096 (setq expert nil)
15097 (delete-other-windows)
15098 (set-window-buffer (split-window-vertically) " *Org tags*")
15099 (org-switch-to-buffer-other-window " *Org tags*")
15100 (org-fit-window-to-buffer)))
15101 ((or (= c ?\C-g)
15102 (and (= c ?q) (not (rassoc c ntable))))
15103 (org-detach-overlay org-tags-overlay)
15104 (setq quit-flag t))
15105 ((= c ?\ )
15106 (setq current nil)
15107 (if exit-after-next (setq exit-after-next 'now)))
15108 ((= c ?\t)
15109 (condition-case nil
15110 (setq tg (org-icompleting-read
15111 "Tag: "
15112 (or buffer-tags
15113 (with-current-buffer buf
15114 (org-get-buffer-tags)))))
15115 (quit (setq tg "")))
15116 (when (string-match "\\S-" tg)
15117 (add-to-list 'buffer-tags (list tg))
15118 (if (member tg current)
15119 (setq current (delete tg current))
15120 (push tg current)))
15121 (if exit-after-next (setq exit-after-next 'now)))
15122 ((setq e (rassoc c todo-table) tg (car e))
15123 (with-current-buffer buf
15124 (save-excursion (org-todo tg)))
15125 (if exit-after-next (setq exit-after-next 'now)))
15126 ((setq e (rassoc c ntable) tg (car e))
15127 (if (member tg current)
15128 (setq current (delete tg current))
15129 (loop for g in groups do
15130 (if (member tg g)
15131 (mapc (lambda (x)
15132 (setq current (delete x current)))
15133 g)))
15134 (push tg current))
15135 (if exit-after-next (setq exit-after-next 'now))))
15137 ;; Create a sorted list
15138 (setq current
15139 (sort current
15140 (lambda (a b)
15141 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15142 (if (eq exit-after-next 'now) (throw 'exit t))
15143 (goto-char (point-min))
15144 (beginning-of-line 2)
15145 (delete-region (point) (point-at-eol))
15146 (org-fast-tag-insert "Current" current c-face)
15147 (org-set-current-tags-overlay current ov-prefix)
15148 (while (re-search-forward
15149 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15150 (setq tg (match-string 1))
15151 (add-text-properties
15152 (match-beginning 1) (match-end 1)
15153 (list 'face
15154 (cond
15155 ((member tg current) c-face)
15156 ((member tg inherited) i-face)
15157 (t (get-text-property (match-beginning 1) 'face))))))
15158 (goto-char (point-min)))))
15159 (org-detach-overlay org-tags-overlay)
15160 (if rtn
15161 (mapconcat 'identity current ":")
15162 nil))))
15164 (defun org-get-tags-string ()
15165 "Get the TAGS string in the current headline."
15166 (unless (org-at-heading-p t)
15167 (user-error "Not on a heading"))
15168 (save-excursion
15169 (beginning-of-line 1)
15170 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15171 (org-match-string-no-properties 1)
15172 "")))
15174 (defun org-get-tags ()
15175 "Get the list of tags specified in the current headline."
15176 (org-split-string (org-get-tags-string) ":"))
15178 (defun org-get-buffer-tags ()
15179 "Get a table of all tags used in the buffer, for completion."
15180 (let (tags)
15181 (save-excursion
15182 (goto-char (point-min))
15183 (while (re-search-forward
15184 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15185 (when (equal (char-after (point-at-bol 0)) ?*)
15186 (mapc (lambda (x) (add-to-list 'tags x))
15187 (org-split-string (org-match-string-no-properties 1) ":")))))
15188 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15189 (mapcar 'list tags)))
15191 ;;;; The mapping API
15193 (defun org-map-entries (func &optional match scope &rest skip)
15194 "Call FUNC at each headline selected by MATCH in SCOPE.
15196 FUNC is a function or a lisp form. The function will be called without
15197 arguments, with the cursor positioned at the beginning of the headline.
15198 The return values of all calls to the function will be collected and
15199 returned as a list.
15201 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15202 does not need to preserve point. After evaluation, the cursor will be
15203 moved to the end of the line (presumably of the headline of the
15204 processed entry) and search continues from there. Under some
15205 circumstances, this may not produce the wanted results. For example,
15206 if you have removed (e.g. archived) the current (sub)tree it could
15207 mean that the next entry will be skipped entirely. In such cases, you
15208 can specify the position from where search should continue by making
15209 FUNC set the variable `org-map-continue-from' to the desired buffer
15210 position.
15212 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15213 Only headlines that are matched by this query will be considered during
15214 the iteration. When MATCH is nil or t, all headlines will be
15215 visited by the iteration.
15217 SCOPE determines the scope of this command. It can be any of:
15219 nil The current buffer, respecting the restriction if any
15220 tree The subtree started with the entry at point
15221 region The entries within the active region, if any
15222 region-start-level
15223 The entries within the active region, but only those at
15224 the same level than the first one.
15225 file The current buffer, without restriction
15226 file-with-archives
15227 The current buffer, and any archives associated with it
15228 agenda All agenda files
15229 agenda-with-archives
15230 All agenda files with any archive files associated with them
15231 \(file1 file2 ...)
15232 If this is a list, all files in the list will be scanned
15234 The remaining args are treated as settings for the skipping facilities of
15235 the scanner. The following items can be given here:
15237 archive skip trees with the archive tag
15238 comment skip trees with the COMMENT keyword
15239 function or Emacs Lisp form:
15240 will be used as value for `org-agenda-skip-function', so
15241 whenever the function returns a position, FUNC will not be
15242 called for that entry and search will continue from the
15243 position returned
15245 If your function needs to retrieve the tags including inherited tags
15246 at the *current* entry, you can use the value of the variable
15247 `org-scanner-tags' which will be much faster than getting the value
15248 with `org-get-tags-at'. If your function gets properties with
15249 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15250 to t around the call to `org-entry-properties' to get the same speedup.
15251 Note that if your function moves around to retrieve tags and properties at
15252 a *different* entry, you cannot use these techniques."
15253 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15254 (not (org-region-active-p)))
15255 (let* ((org-agenda-archives-mode nil) ; just to make sure
15256 (org-agenda-skip-archived-trees (memq 'archive skip))
15257 (org-agenda-skip-comment-trees (memq 'comment skip))
15258 (org-agenda-skip-function
15259 (car (org-delete-all '(comment archive) skip)))
15260 (org-tags-match-list-sublevels t)
15261 (start-level (eq scope 'region-start-level))
15262 matcher file res
15263 org-todo-keywords-for-agenda
15264 org-done-keywords-for-agenda
15265 org-todo-keyword-alist-for-agenda
15266 org-tag-alist-for-agenda
15267 todo-only)
15269 (cond
15270 ((eq match t) (setq matcher t))
15271 ((eq match nil) (setq matcher t))
15272 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15274 (save-excursion
15275 (save-restriction
15276 (cond ((eq scope 'tree)
15277 (org-back-to-heading t)
15278 (org-narrow-to-subtree)
15279 (setq scope nil))
15280 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15281 (org-region-active-p))
15282 ;; If needed, set start-level to a string like "2"
15283 (when start-level
15284 (save-excursion
15285 (goto-char (region-beginning))
15286 (unless (org-at-heading-p) (outline-next-heading))
15287 (setq start-level (org-current-level))))
15288 (narrow-to-region (region-beginning)
15289 (save-excursion
15290 (goto-char (region-end))
15291 (unless (and (bolp) (org-at-heading-p))
15292 (outline-next-heading))
15293 (point)))
15294 (setq scope nil)))
15296 (if (not scope)
15297 (progn
15298 (org-agenda-prepare-buffers
15299 (list (buffer-file-name (current-buffer))))
15300 (setq res (org-scan-tags func matcher todo-only start-level)))
15301 ;; Get the right scope
15302 (cond
15303 ((and scope (listp scope) (symbolp (car scope)))
15304 (setq scope (eval scope)))
15305 ((eq scope 'agenda)
15306 (setq scope (org-agenda-files t)))
15307 ((eq scope 'agenda-with-archives)
15308 (setq scope (org-agenda-files t))
15309 (setq scope (org-add-archive-files scope)))
15310 ((eq scope 'file)
15311 (setq scope (list (buffer-file-name))))
15312 ((eq scope 'file-with-archives)
15313 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15314 (org-agenda-prepare-buffers scope)
15315 (while (setq file (pop scope))
15316 (with-current-buffer (org-find-base-buffer-visiting file)
15317 (save-excursion
15318 (save-restriction
15319 (widen)
15320 (goto-char (point-min))
15321 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15322 res)))
15324 ;;;; Properties
15326 ;;; Setting and retrieving properties
15328 (defconst org-special-properties
15329 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15330 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15331 "The special properties valid in Org-mode.
15333 These are properties that are not defined in the property drawer,
15334 but in some other way.")
15336 (defconst org-default-properties
15337 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15338 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15339 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15340 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15341 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15342 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15343 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15344 "Some properties that are used by Org-mode for various purposes.
15345 Being in this list makes sure that they are offered for completion.")
15347 (defun org-property-action ()
15348 "Do an action on properties."
15349 (interactive)
15350 (let (c)
15351 (org-at-property-p)
15352 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15353 (setq c (read-char-exclusive))
15354 (cond
15355 ((equal c ?s)
15356 (call-interactively 'org-set-property))
15357 ((equal c ?d)
15358 (call-interactively 'org-delete-property))
15359 ((equal c ?D)
15360 (call-interactively 'org-delete-property-globally))
15361 ((equal c ?c)
15362 (call-interactively 'org-compute-property-at-point))
15363 (t (user-error "No such property action %c" c)))))
15365 (defun org-inc-effort ()
15366 "Increment the value of the effort property in the current entry."
15367 (interactive)
15368 (org-set-effort nil t))
15370 (defvar org-clock-effort) ;; Defined in org-clock.el
15371 (defvar org-clock-current-task) ;; Defined in org-clock.el
15372 (defun org-set-effort (&optional value increment)
15373 "Set the effort property of the current entry.
15374 With numerical prefix arg, use the nth allowed value, 0 stands for the
15375 10th allowed value.
15377 When INCREMENT is non-nil, set the property to the next allowed value."
15378 (interactive "P")
15379 (if (equal value 0) (setq value 10))
15380 (let* ((completion-ignore-case t)
15381 (prop org-effort-property)
15382 (cur (org-entry-get nil prop))
15383 (allowed (org-property-get-allowed-values nil prop 'table))
15384 (existing (mapcar 'list (org-property-values prop)))
15385 (heading (nth 4 (org-heading-components)))
15387 (val (cond
15388 ((stringp value) value)
15389 ((and allowed (integerp value))
15390 (or (car (nth (1- value) allowed))
15391 (car (org-last allowed))))
15392 ((and allowed increment)
15393 (or (caadr (member (list cur) allowed))
15394 (user-error "Allowed effort values are not set")))
15395 (allowed
15396 (message "Select 1-9,0, [RET%s]: %s"
15397 (if cur (concat "=" cur) "")
15398 (mapconcat 'car allowed " "))
15399 (setq rpl (read-char-exclusive))
15400 (if (equal rpl ?\r)
15402 (setq rpl (- rpl ?0))
15403 (if (equal rpl 0) (setq rpl 10))
15404 (if (and (> rpl 0) (<= rpl (length allowed)))
15405 (car (nth (1- rpl) allowed))
15406 (org-completing-read "Effort: " allowed nil))))
15408 (let (org-completion-use-ido org-completion-use-iswitchb)
15409 (org-completing-read
15410 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15411 (concat "[" cur "]") "")
15412 ": ")
15413 existing nil nil "" nil cur))))))
15414 (unless (equal (org-entry-get nil prop) val)
15415 (org-entry-put nil prop val))
15416 (org-refresh-property
15417 '((effort . identity)
15418 (effort-minutes . org-duration-string-to-minutes))
15419 val)
15420 (when (string= heading org-clock-current-task)
15421 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15422 (org-clock-update-mode-line))
15423 (message "%s is now %s" prop val)))
15425 (defun org-at-property-p ()
15426 "Non-nil when point is inside a property drawer.
15427 See `org-property-re' for match data, if applicable."
15428 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15429 (save-excursion
15430 (beginning-of-line)
15431 (looking-at org-property-re))))
15433 (defun org-get-property-block (&optional beg end force)
15434 "Return the (beg . end) range of the body of the property drawer.
15435 BEG and END are the beginning and end of the current subtree, or of
15436 the part before the first headline. If they are not given, they will
15437 be found. If the drawer does not exist and FORCE is non-nil, create
15438 the drawer."
15439 (catch 'exit
15440 (save-excursion
15441 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15442 (progn (org-back-to-heading t) (point))))
15443 (end (or end (and (not (outline-next-heading)) (point-max))
15444 (point))))
15445 (goto-char beg)
15446 (if (re-search-forward org-property-start-re end t)
15447 (setq beg (1+ (match-end 0)))
15448 (if force
15449 (save-excursion
15450 (org-insert-property-drawer)
15451 (setq end (progn (outline-next-heading) (point))))
15452 (throw 'exit nil))
15453 (goto-char beg)
15454 (if (re-search-forward org-property-start-re end t)
15455 (setq beg (1+ (match-end 0)))))
15456 (if (re-search-forward org-property-end-re end t)
15457 (setq end (match-beginning 0))
15458 (or force (throw 'exit nil))
15459 (goto-char beg)
15460 (setq end beg)
15461 (org-indent-line)
15462 (insert ":END:\n"))
15463 (cons beg end)))))
15465 (defun org-entry-properties (&optional pom which specific)
15466 "Get all properties of the entry at point-or-marker POM.
15467 This includes the TODO keyword, the tags, time strings for deadline,
15468 scheduled, and clocking, and any additional properties defined in the
15469 entry. The return value is an alist, keys may occur multiple times
15470 if the property key was used several times.
15471 POM may also be nil, in which case the current entry is used.
15472 If WHICH is nil or `all', get all properties. If WHICH is
15473 `special' or `standard', only get that subclass. If WHICH
15474 is a string only get exactly this property. SPECIFIC can be a string, the
15475 specific property we are interested in. Specifying it can speed
15476 things up because then unnecessary parsing is avoided."
15477 (setq which (or which 'all))
15478 (org-with-wide-buffer
15479 (org-with-point-at pom
15480 (let ((clockstr (substring org-clock-string 0 -1))
15481 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15482 (case-fold-search nil)
15483 beg end range props sum-props key key1 value string clocksum clocksumt)
15484 (when (and (derived-mode-p 'org-mode)
15485 (ignore-errors (org-back-to-heading t)))
15486 (setq beg (point))
15487 (setq sum-props (get-text-property (point) 'org-summaries))
15488 (setq clocksum (get-text-property (point) :org-clock-minutes)
15489 clocksumt (get-text-property (point) :org-clock-minutes-today))
15490 (outline-next-heading)
15491 (setq end (point))
15492 (when (memq which '(all special))
15493 ;; Get the special properties, like TODO and tags
15494 (goto-char beg)
15495 (when (and (or (not specific) (string= specific "TODO"))
15496 (looking-at org-todo-line-regexp) (match-end 2))
15497 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15498 (when (and (or (not specific) (string= specific "PRIORITY"))
15499 (looking-at org-priority-regexp))
15500 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15501 (when (or (not specific) (string= specific "FILE"))
15502 (push (cons "FILE" buffer-file-name) props))
15503 (when (and (or (not specific) (string= specific "TAGS"))
15504 (setq value (org-get-tags-string))
15505 (string-match "\\S-" value))
15506 (push (cons "TAGS" value) props))
15507 (when (and (or (not specific) (string= specific "ALLTAGS"))
15508 (setq value (org-get-tags-at)))
15509 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15510 ":"))
15511 props))
15512 (when (or (not specific) (string= specific "BLOCKED"))
15513 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15514 (when (or (not specific)
15515 (member specific
15516 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15517 "TIMESTAMP" "TIMESTAMP_IA")))
15518 (catch 'match
15519 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15520 (not (text-property-any 0 (length (match-string 0))
15521 'face 'font-lock-comment-face
15522 (match-string 0))))
15523 (setq key (if (match-end 1)
15524 (substring (org-match-string-no-properties 1)
15525 0 -1))
15526 string (if (equal key clockstr)
15527 (org-trim
15528 (buffer-substring-no-properties
15529 (match-beginning 3) (goto-char
15530 (point-at-eol))))
15531 (substring (org-match-string-no-properties 3)
15532 1 -1)))
15533 ;; Get the correct property name from the key. This is
15534 ;; necessary if the user has configured time keywords.
15535 (setq key1 (concat key ":"))
15536 (cond
15537 ((not key)
15538 (setq key
15539 (if (= (char-after (match-beginning 3)) ?\[)
15540 "TIMESTAMP_IA" "TIMESTAMP")))
15541 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15542 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15543 ((equal key1 org-closed-string) (setq key "CLOSED"))
15544 ((equal key1 org-clock-string) (setq key "CLOCK")))
15545 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15546 (progn
15547 (push (cons key string) props)
15548 ;; no need to search further if match is found
15549 (throw 'match t))
15550 (when (or (equal key "CLOCK") (not (assoc key props)))
15551 (push (cons key string) props)))))))
15553 (when (memq which '(all standard))
15554 ;; Get the standard properties, like :PROP: ...
15555 (setq range (org-get-property-block beg end))
15556 (when range
15557 (goto-char (car range))
15558 (while (re-search-forward org-property-re
15559 (cdr range) t)
15560 (setq key (org-match-string-no-properties 2)
15561 value (org-trim (or (org-match-string-no-properties 3) "")))
15562 (unless (member key excluded)
15563 (push (cons key (or value "")) props)))))
15564 (if clocksum
15565 (push (cons "CLOCKSUM"
15566 (org-columns-number-to-string (/ (float clocksum) 60.)
15567 'add_times))
15568 props))
15569 (if clocksumt
15570 (push (cons "CLOCKSUM_T"
15571 (org-columns-number-to-string (/ (float clocksumt) 60.)
15572 'add_times))
15573 props))
15574 (unless (assoc "CATEGORY" props)
15575 (push (cons "CATEGORY" (org-get-category)) props))
15576 (append sum-props (nreverse props)))))))
15578 (defun org-entry-get (pom property &optional inherit literal-nil)
15579 "Get value of PROPERTY for entry or content at point-or-marker POM.
15580 If INHERIT is non-nil and the entry does not have the property,
15581 then also check higher levels of the hierarchy.
15582 If INHERIT is the symbol `selective', use inheritance only if the setting
15583 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15584 If the property is present but empty, the return value is the empty string.
15585 If the property is not present at all, nil is returned.
15587 Return the value as a string.
15589 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15590 do not interpret it as the list atom nil. This is used for inheritance
15591 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15592 (org-with-point-at pom
15593 (if (and inherit (if (eq inherit 'selective)
15594 (org-property-inherit-p property)
15596 (org-entry-get-with-inheritance property literal-nil)
15597 (if (member property org-special-properties)
15598 ;; We need a special property. Use `org-entry-properties'
15599 ;; to retrieve it, but specify the wanted property
15600 (cdr (assoc property (org-entry-properties nil 'special property)))
15601 (org-with-wide-buffer
15602 (let ((range (org-get-property-block)))
15603 (when (and range (not (eq (car range) (cdr range)))
15604 (save-excursion
15605 (goto-char (car range))
15606 (re-search-forward
15607 (concat (org-re-property property) "\\|"
15608 (org-re-property (concat property "+")))
15609 (cdr range) t)))
15610 (let* ((props
15611 (list (or (assoc property org-file-properties)
15612 (assoc property org-global-properties)
15613 (assoc property org-global-properties-fixed))))
15614 (ap (lambda (key)
15615 (when (re-search-forward
15616 (org-re-property key) (cdr range) t)
15617 (setq props
15618 (org-update-property-plist
15620 (if (match-end 3)
15621 (org-match-string-no-properties 3) "")
15622 props)))))
15623 val)
15624 (goto-char (car range))
15625 (funcall ap property)
15626 (goto-char (car range))
15627 (while (funcall ap (concat property "+")))
15628 (setq val (cdr (assoc property props)))
15629 (when val (if literal-nil val (org-not-nil val)))))))))))
15631 (defun org-property-or-variable-value (var &optional inherit)
15632 "Check if there is a property fixing the value of VAR.
15633 If yes, return this value. If not, return the current value of the variable."
15634 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15635 (if (and prop (stringp prop) (string-match "\\S-" prop))
15636 (read prop)
15637 (symbol-value var))))
15639 (defun org-entry-delete (pom property)
15640 "Delete the property PROPERTY from entry at point-or-marker POM."
15641 (unless (member property org-special-properties)
15642 (org-with-point-at pom
15643 (let ((range (org-get-property-block)))
15644 (if (and range
15645 (goto-char (car range))
15646 (re-search-forward
15647 (org-re-property property nil t)
15648 (cdr range) t))
15649 (progn
15650 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15651 (org-remove-empty-drawer-at (car range))
15653 nil)))))
15655 ;; Multi-values properties are properties that contain multiple values
15656 ;; These values are assumed to be single words, separated by whitespace.
15657 (defun org-entry-add-to-multivalued-property (pom property value)
15658 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15659 (let* ((old (org-entry-get pom property))
15660 (values (and old (org-split-string old "[ \t]"))))
15661 (setq value (org-entry-protect-space value))
15662 (unless (member value values)
15663 (setq values (append values (list value)))
15664 (org-entry-put pom property
15665 (mapconcat 'identity values " ")))))
15667 (defun org-entry-remove-from-multivalued-property (pom property value)
15668 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15669 (let* ((old (org-entry-get pom property))
15670 (values (and old (org-split-string old "[ \t]"))))
15671 (setq value (org-entry-protect-space value))
15672 (when (member value values)
15673 (setq values (delete value values))
15674 (org-entry-put pom property
15675 (mapconcat 'identity values " ")))))
15677 (defun org-entry-member-in-multivalued-property (pom property value)
15678 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15679 (let* ((old (org-entry-get pom property))
15680 (values (and old (org-split-string old "[ \t]"))))
15681 (setq value (org-entry-protect-space value))
15682 (member value values)))
15684 (defun org-entry-get-multivalued-property (pom property)
15685 "Return a list of values in a multivalued property."
15686 (let* ((value (org-entry-get pom property))
15687 (values (and value (org-split-string value "[ \t]"))))
15688 (mapcar 'org-entry-restore-space values)))
15690 (defun org-entry-put-multivalued-property (pom property &rest values)
15691 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15692 VALUES should be a list of strings. Spaces will be protected."
15693 (org-entry-put pom property
15694 (mapconcat 'org-entry-protect-space values " "))
15695 (let* ((value (org-entry-get pom property))
15696 (values (and value (org-split-string value "[ \t]"))))
15697 (mapcar 'org-entry-restore-space values)))
15699 (defun org-entry-protect-space (s)
15700 "Protect spaces and newline in string S."
15701 (while (string-match " " s)
15702 (setq s (replace-match "%20" t t s)))
15703 (while (string-match "\n" s)
15704 (setq s (replace-match "%0A" t t s)))
15707 (defun org-entry-restore-space (s)
15708 "Restore spaces and newline in string S."
15709 (while (string-match "%20" s)
15710 (setq s (replace-match " " t t s)))
15711 (while (string-match "%0A" s)
15712 (setq s (replace-match "\n" t t s)))
15715 (defvar org-entry-property-inherited-from (make-marker)
15716 "Marker pointing to the entry from where a property was inherited.
15717 Each call to `org-entry-get-with-inheritance' will set this marker to the
15718 location of the entry where the inheritance search matched. If there was
15719 no match, the marker will point nowhere.
15720 Note that also `org-entry-get' calls this function, if the INHERIT flag
15721 is set.")
15723 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15724 "Get PROPERTY of entry or content at point, search higher levels if needed.
15725 The search will stop at the first ancestor which has the property defined.
15726 If the value found is \"nil\", return nil to show that the property
15727 should be considered as undefined (this is the meaning of nil here).
15728 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15729 (move-marker org-entry-property-inherited-from nil)
15730 (let (tmp)
15731 (save-excursion
15732 (save-restriction
15733 (widen)
15734 (catch 'ex
15735 (while t
15736 (when (setq tmp (org-entry-get nil property nil literal-nil))
15737 (or (ignore-errors (org-back-to-heading t))
15738 (goto-char (point-min)))
15739 (move-marker org-entry-property-inherited-from (point))
15740 (throw 'ex tmp))
15741 (or (ignore-errors (org-up-heading-safe))
15742 (throw 'ex nil))))))
15743 (setq tmp (or tmp
15744 (cdr (assoc property org-file-properties))
15745 (cdr (assoc property org-global-properties))
15746 (cdr (assoc property org-global-properties-fixed))))
15747 (if literal-nil tmp (org-not-nil tmp))))
15749 (defvar org-property-changed-functions nil
15750 "Hook called when the value of a property has changed.
15751 Each hook function should accept two arguments, the name of the property
15752 and the new value.")
15754 (defun org-entry-put (pom property value)
15755 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15756 If the value is `nil', it is converted to the empty string.
15757 If it is not a string, an error is raised."
15758 (cond ((null value) (setq value ""))
15759 ((not (stringp value))
15760 (error "Properties values should be strings.")))
15761 (org-with-point-at pom
15762 (org-back-to-heading t)
15763 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15764 range)
15765 (cond
15766 ((equal property "TODO")
15767 (when (and (string-match "\\S-" value)
15768 (not (member value org-todo-keywords-1)))
15769 (user-error "\"%s\" is not a valid TODO state" value))
15770 (if (or (not value)
15771 (not (string-match "\\S-" value)))
15772 (setq value 'none))
15773 (org-todo value)
15774 (org-set-tags nil 'align))
15775 ((equal property "PRIORITY")
15776 (org-priority (if (and value (string-match "\\S-" value))
15777 (string-to-char value) ?\ ))
15778 (org-set-tags nil 'align))
15779 ((equal property "CLOCKSUM")
15780 (if (not (re-search-forward
15781 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15782 (error "Cannot find a clock log")
15783 (goto-char (- (match-end 1) 2))
15784 (cond
15785 ((eq value 'earlier) (org-timestamp-down))
15786 ((eq value 'later) (org-timestamp-up)))
15787 (org-clock-sum-current-item)))
15788 ((equal property "SCHEDULED")
15789 (if (re-search-forward org-scheduled-time-regexp end t)
15790 (cond
15791 ((eq value 'earlier) (org-timestamp-change -1 'day))
15792 ((eq value 'later) (org-timestamp-change 1 'day))
15793 (t (call-interactively 'org-schedule)))
15794 (call-interactively 'org-schedule)))
15795 ((equal property "DEADLINE")
15796 (if (re-search-forward org-deadline-time-regexp end t)
15797 (cond
15798 ((eq value 'earlier) (org-timestamp-change -1 'day))
15799 ((eq value 'later) (org-timestamp-change 1 'day))
15800 (t (call-interactively 'org-deadline)))
15801 (call-interactively 'org-deadline)))
15802 ((member property org-special-properties)
15803 (error "The %s property can not yet be set with `org-entry-put'"
15804 property))
15805 (t ; a non-special property
15806 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15807 (setq range (org-get-property-block beg end 'force))
15808 (goto-char (car range))
15809 (if (re-search-forward
15810 (org-re-property property nil t) (cdr range) t)
15811 (progn
15812 (delete-region (match-beginning 0) (match-end 0))
15813 (goto-char (match-beginning 0)))
15814 (goto-char (cdr range))
15815 (insert "\n")
15816 (backward-char 1)
15817 (org-indent-line))
15818 (insert ":" property ":")
15819 (and value (insert " " value))
15820 (org-indent-line)))))
15821 (run-hook-with-args 'org-property-changed-functions property value)))
15823 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15824 "Get all property keys in the current buffer.
15825 With INCLUDE-SPECIALS, also list the special properties that reflect things
15826 like tags and TODO state.
15827 With INCLUDE-DEFAULTS, also include properties that has special meaning
15828 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15829 and others.
15830 With INCLUDE-COLUMNS, also include property names given in COLUMN
15831 formats in the current buffer."
15832 (let (rtn range cfmt s p)
15833 (save-excursion
15834 (save-restriction
15835 (widen)
15836 (goto-char (point-min))
15837 (while (re-search-forward org-property-start-re nil t)
15838 (catch 'cont
15839 (setq range (or (org-get-property-block)
15840 (if (y-or-n-p
15841 (format "Malformed drawer at %d, repair?" (point)))
15842 (org-get-property-block nil nil t)
15843 (throw 'cont nil))))
15844 (goto-char (car range))
15845 (while (re-search-forward org-property-re
15846 (cdr range) t)
15847 (add-to-list 'rtn (org-match-string-no-properties 2)))
15848 (outline-next-heading)))))
15850 (when include-specials
15851 (setq rtn (append org-special-properties rtn)))
15853 (when include-defaults
15854 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15855 (add-to-list 'rtn org-effort-property))
15857 (when include-columns
15858 (save-excursion
15859 (save-restriction
15860 (widen)
15861 (goto-char (point-min))
15862 (while (re-search-forward
15863 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15864 nil t)
15865 (setq cfmt (match-string 2) s 0)
15866 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15867 cfmt s)
15868 (setq s (match-end 0)
15869 p (match-string 1 cfmt))
15870 (unless (or (equal p "ITEM")
15871 (member p org-special-properties))
15872 (add-to-list 'rtn (match-string 1 cfmt))))))))
15874 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15876 (defun org-property-values (key)
15877 "Return a list of all values of property KEY in the current buffer."
15878 (save-excursion
15879 (save-restriction
15880 (widen)
15881 (goto-char (point-min))
15882 (let ((re (org-re-property key))
15883 values)
15884 (while (re-search-forward re nil t)
15885 (add-to-list 'values (org-trim (match-string 3))))
15886 (delete "" values)))))
15888 (defun org-insert-property-drawer ()
15889 "Insert a property drawer into the current entry."
15890 (org-back-to-heading t)
15891 (looking-at org-outline-regexp)
15892 (let ((indent (if org-adapt-indentation
15893 (- (match-end 0) (match-beginning 0))
15895 (beg (point))
15896 (re (concat "^[ \t]*" org-keyword-time-regexp))
15897 (org-clock-re (format "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|%s\\|:END:\\)"
15898 org-clock-string))
15899 (org-skip-line-list (list org-clock-string ":END:"))
15900 end hiddenp)
15901 (outline-next-heading)
15902 (setq end (point))
15903 (goto-char beg)
15904 (while (re-search-forward re end t))
15905 (setq hiddenp (outline-invisible-p))
15906 (end-of-line 1)
15907 (and (equal (char-after) ?\n) (forward-char 1))
15908 (while (looking-at org-clock-re)
15909 (if (member (match-string 1) org-skip-line-list)
15910 ;; just skip this line
15911 (beginning-of-line 2)
15912 ;; Drawer start, find the end
15913 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15914 (beginning-of-line 1)))
15915 (org-skip-over-state-notes)
15916 (skip-chars-backward " \t\n\r")
15917 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15918 (forward-char 1))
15919 (goto-char (point-at-eol))
15920 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15921 (beginning-of-line 0)
15922 (org-indent-to-column indent)
15923 (beginning-of-line 2)
15924 (org-indent-to-column indent)
15925 (beginning-of-line 0)
15926 (if hiddenp
15927 (save-excursion
15928 (org-back-to-heading t)
15929 (hide-entry))
15930 (org-flag-drawer t))))
15932 (defun org-insert-drawer (&optional arg drawer)
15933 "Insert a drawer at point.
15935 Optional argument DRAWER, when non-nil, is a string representing
15936 drawer's name. Otherwise, the user is prompted for a name.
15938 If a region is active, insert the drawer around that region
15939 instead.
15941 Point is left between drawer's boundaries."
15942 (interactive "P")
15943 (let* ((drawer (if arg "PROPERTIES"
15944 (or drawer (read-from-minibuffer "Drawer: ")))))
15945 (cond
15946 ;; With C-u, fall back on `org-insert-property-drawer'
15947 (arg (org-insert-property-drawer))
15949 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15950 (user-error "Invalid drawer name"))
15951 ;; With an active region, insert a drawer at point.
15952 ((not (org-region-active-p))
15953 (progn
15954 (unless (bolp) (insert "\n"))
15955 (insert (format ":%s:\n\n:END:\n" drawer))
15956 (forward-line -2)))
15957 ;; Otherwise, insert the drawer at point
15959 (let ((rbeg (region-beginning))
15960 (rend (copy-marker (region-end))))
15961 (unwind-protect
15962 (progn
15963 (goto-char rbeg)
15964 (beginning-of-line)
15965 (when (save-excursion
15966 (re-search-forward org-outline-regexp-bol rend t))
15967 (user-error "Drawers cannot contain headlines"))
15968 ;; Position point at the beginning of the first
15969 ;; non-blank line in region. Insert drawer's opening
15970 ;; there, then indent it.
15971 (org-skip-whitespace)
15972 (beginning-of-line)
15973 (insert ":" drawer ":\n")
15974 (forward-line -1)
15975 (indent-for-tab-command)
15976 ;; Move point to the beginning of the first blank line
15977 ;; after the last non-blank line in region. Insert
15978 ;; drawer's closing, then indent it.
15979 (goto-char rend)
15980 (skip-chars-backward " \r\t\n")
15981 (insert "\n:END:")
15982 (deactivate-mark t)
15983 (indent-for-tab-command)
15984 (unless (eolp) (insert "\n")))
15985 ;; Clear marker, whatever the outcome of insertion is.
15986 (set-marker rend nil)))))))
15988 (defvar org-property-set-functions-alist nil
15989 "Property set function alist.
15990 Each entry should have the following format:
15992 (PROPERTY . READ-FUNCTION)
15994 The read function will be called with the same argument as
15995 `org-completing-read'.")
15997 (defun org-set-property-function (property)
15998 "Get the function that should be used to set PROPERTY.
15999 This is computed according to `org-property-set-functions-alist'."
16000 (or (cdr (assoc property org-property-set-functions-alist))
16001 'org-completing-read))
16003 (defun org-read-property-value (property)
16004 "Read PROPERTY value from user."
16005 (let* ((completion-ignore-case t)
16006 (allowed (org-property-get-allowed-values nil property 'table))
16007 (cur (org-entry-get nil property))
16008 (prompt (concat property " value"
16009 (if (and cur (string-match "\\S-" cur))
16010 (concat " [" cur "]") "") ": "))
16011 (set-function (org-set-property-function property))
16012 (val (if allowed
16013 (funcall set-function prompt allowed nil
16014 (not (get-text-property 0 'org-unrestricted
16015 (caar allowed))))
16016 (let (org-completion-use-ido org-completion-use-iswitchb)
16017 (funcall set-function prompt
16018 (mapcar 'list (org-property-values property))
16019 nil nil "" nil cur)))))
16020 (org-trim val)))
16022 (defvar org-last-set-property nil)
16023 (defvar org-last-set-property-value nil)
16024 (defun org-read-property-name ()
16025 "Read a property name."
16026 (let* ((completion-ignore-case t)
16027 (keys (org-buffer-property-keys nil t t))
16028 (default-prop (or (save-excursion
16029 (save-match-data
16030 (beginning-of-line)
16031 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16032 (null (string= (match-string 1) "END"))
16033 (match-string 1))))
16034 org-last-set-property))
16035 (property (org-icompleting-read
16036 (concat "Property"
16037 (if default-prop (concat " [" default-prop "]") "")
16038 ": ")
16039 (mapcar 'list keys)
16040 nil nil nil nil
16041 default-prop)))
16042 (if (member property keys)
16043 property
16044 (or (cdr (assoc (downcase property)
16045 (mapcar (lambda (x) (cons (downcase x) x))
16046 keys)))
16047 property))))
16049 (defun org-set-property-and-value (use-last)
16050 "Allow to set [PROPERTY]: [value] direction from prompt.
16051 When use-default, don't even ask, just use the last
16052 \"[PROPERTY]: [value]\" string from the history."
16053 (interactive "P")
16054 (let* ((completion-ignore-case t)
16055 (pv (or (and use-last org-last-set-property-value)
16056 (org-completing-read
16057 "Enter a \"[Property]: [value]\" pair: "
16058 nil nil nil nil nil
16059 org-last-set-property-value)))
16060 prop val)
16061 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16062 (setq prop (match-string 1 pv)
16063 val (match-string 2 pv))
16064 (org-set-property prop val))))
16066 (defun org-set-property (property value)
16067 "In the current entry, set PROPERTY to VALUE.
16068 When called interactively, this will prompt for a property name, offering
16069 completion on existing and default properties. And then it will prompt
16070 for a value, offering completion either on allowed values (via an inherited
16071 xxx_ALL property) or on existing values in other instances of this property
16072 in the current file."
16073 (interactive (list nil nil))
16074 (let* ((property (or property (org-read-property-name)))
16075 (value (or value (org-read-property-value property)))
16076 (fn (cdr (assoc property org-properties-postprocess-alist))))
16077 (setq org-last-set-property property)
16078 (setq org-last-set-property-value (concat property ": " value))
16079 ;; Possibly postprocess the inserted value:
16080 (when fn (setq value (funcall fn value)))
16081 (unless (equal (org-entry-get nil property) value)
16082 (org-entry-put nil property value))))
16084 (defun org-delete-property (property)
16085 "In the current entry, delete PROPERTY."
16086 (interactive
16087 (let* ((completion-ignore-case t)
16088 (cat (org-entry-get (point) "CATEGORY"))
16089 (props0 (org-entry-properties nil 'standard))
16090 (props (if cat props0
16091 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16092 (prop (if (< 1 (length props))
16093 (org-icompleting-read "Property: " props nil t)
16094 (caar props))))
16095 (list prop)))
16096 (if (not property)
16097 (message "No property to delete in this entry")
16098 (org-entry-delete nil property)
16099 (message "Property \"%s\" deleted" property)))
16101 (defun org-delete-property-globally (property)
16102 "Remove PROPERTY globally, from all entries."
16103 (interactive
16104 (let* ((completion-ignore-case t)
16105 (prop (org-icompleting-read
16106 "Globally remove property: "
16107 (mapcar 'list (org-buffer-property-keys)))))
16108 (list prop)))
16109 (save-excursion
16110 (save-restriction
16111 (widen)
16112 (goto-char (point-min))
16113 (let ((cnt 0))
16114 (while (re-search-forward
16115 (org-re-property property)
16116 nil t)
16117 (setq cnt (1+ cnt))
16118 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16119 (message "Property \"%s\" removed from %d entries" property cnt)))))
16121 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16123 (defun org-compute-property-at-point ()
16124 "Compute the property at point.
16125 This looks for an enclosing column format, extracts the operator and
16126 then applies it to the property in the column format's scope."
16127 (interactive)
16128 (unless (org-at-property-p)
16129 (user-error "Not at a property"))
16130 (let ((prop (org-match-string-no-properties 2)))
16131 (org-columns-get-format-and-top-level)
16132 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16133 (user-error "No operator defined for property %s" prop))
16134 (org-columns-compute prop)))
16136 (defvar org-property-allowed-value-functions nil
16137 "Hook for functions supplying allowed values for a specific property.
16138 The functions must take a single argument, the name of the property, and
16139 return a flat list of allowed values. If \":ETC\" is one of
16140 the values, this means that these values are intended as defaults for
16141 completion, but that other values should be allowed too.
16142 The functions must return nil if they are not responsible for this
16143 property.")
16145 (defun org-property-get-allowed-values (pom property &optional table)
16146 "Get allowed values for the property PROPERTY.
16147 When TABLE is non-nil, return an alist that can directly be used for
16148 completion."
16149 (let (vals)
16150 (cond
16151 ((equal property "TODO")
16152 (setq vals (org-with-point-at pom
16153 (append org-todo-keywords-1 '("")))))
16154 ((equal property "PRIORITY")
16155 (let ((n org-lowest-priority))
16156 (while (>= n org-highest-priority)
16157 (push (char-to-string n) vals)
16158 (setq n (1- n)))))
16159 ((member property org-special-properties))
16160 ((setq vals (run-hook-with-args-until-success
16161 'org-property-allowed-value-functions property)))
16163 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16164 (when (and vals (string-match "\\S-" vals))
16165 (setq vals (car (read-from-string (concat "(" vals ")"))))
16166 (setq vals (mapcar (lambda (x)
16167 (cond ((stringp x) x)
16168 ((numberp x) (number-to-string x))
16169 ((symbolp x) (symbol-name x))
16170 (t "???")))
16171 vals)))))
16172 (when (member ":ETC" vals)
16173 (setq vals (remove ":ETC" vals))
16174 (org-add-props (car vals) '(org-unrestricted t)))
16175 (if table (mapcar 'list vals) vals)))
16177 (defun org-property-previous-allowed-value (&optional previous)
16178 "Switch to the next allowed value for this property."
16179 (interactive)
16180 (org-property-next-allowed-value t))
16182 (defun org-property-next-allowed-value (&optional previous)
16183 "Switch to the next allowed value for this property."
16184 (interactive)
16185 (unless (org-at-property-p)
16186 (user-error "Not at a property"))
16187 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16188 (key (match-string 2))
16189 (value (match-string 3))
16190 (allowed (or (org-property-get-allowed-values (point) key)
16191 (and (member value '("[ ]" "[-]" "[X]"))
16192 '("[ ]" "[X]"))))
16193 (heading (save-match-data (nth 4 (org-heading-components))))
16194 nval)
16195 (unless allowed
16196 (user-error "Allowed values for this property have not been defined"))
16197 (if previous (setq allowed (reverse allowed)))
16198 (if (member value allowed)
16199 (setq nval (car (cdr (member value allowed)))))
16200 (setq nval (or nval (car allowed)))
16201 (if (equal nval value)
16202 (user-error "Only one allowed value for this property"))
16203 (org-at-property-p)
16204 (replace-match (concat " :" key ": " nval) t t)
16205 (org-indent-line)
16206 (beginning-of-line 1)
16207 (skip-chars-forward " \t")
16208 (when (equal prop org-effort-property)
16209 (org-refresh-property
16210 '((effort . identity)
16211 (effort-minutes . org-duration-string-to-minutes))
16212 nval)
16213 (when (string= org-clock-current-task heading)
16214 (setq org-clock-effort nval)
16215 (org-clock-update-mode-line)))
16216 (run-hook-with-args 'org-property-changed-functions key nval)))
16218 (defun org-find-olp (path &optional this-buffer)
16219 "Return a marker pointing to the entry at outline path OLP.
16220 If anything goes wrong, throw an error.
16221 You can wrap this call to catch the error like this:
16223 (condition-case msg
16224 (org-mobile-locate-entry (match-string 4))
16225 (error (nth 1 msg)))
16227 The return value will then be either a string with the error message,
16228 or a marker if everything is OK.
16230 If THIS-BUFFER is set, the outline path does not contain a file,
16231 only headings."
16232 (let* ((file (if this-buffer buffer-file-name (pop path)))
16233 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16234 (level 1)
16235 (lmin 1)
16236 (lmax 1)
16237 limit re end found pos heading cnt flevel)
16238 (unless buffer (error "File not found :%s" file))
16239 (with-current-buffer buffer
16240 (save-excursion
16241 (save-restriction
16242 (widen)
16243 (setq limit (point-max))
16244 (goto-char (point-min))
16245 (while (setq heading (pop path))
16246 (setq re (format org-complex-heading-regexp-format
16247 (regexp-quote heading)))
16248 (setq cnt 0 pos (point))
16249 (while (re-search-forward re end t)
16250 (setq level (- (match-end 1) (match-beginning 1)))
16251 (if (and (>= level lmin) (<= level lmax))
16252 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16253 (when (= cnt 0) (error "Heading not found on level %d: %s"
16254 lmax heading))
16255 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16256 lmax heading))
16257 (goto-char found)
16258 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16259 (setq end (save-excursion (org-end-of-subtree t t))))
16260 (when (org-at-heading-p)
16261 (point-marker)))))))
16263 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16264 "Find node HEADING in BUFFER.
16265 Return a marker to the heading if it was found, or nil if not.
16266 If POS-ONLY is set, return just the position instead of a marker.
16268 The heading text must match exact, but it may have a TODO keyword,
16269 a priority cookie and tags in the standard locations."
16270 (with-current-buffer (or buffer (current-buffer))
16271 (save-excursion
16272 (save-restriction
16273 (widen)
16274 (goto-char (point-min))
16275 (let (case-fold-search)
16276 (if (re-search-forward
16277 (format org-complex-heading-regexp-format
16278 (regexp-quote heading)) nil t)
16279 (if pos-only
16280 (match-beginning 0)
16281 (move-marker (make-marker) (match-beginning 0)))))))))
16283 (defun org-find-exact-heading-in-directory (heading &optional dir)
16284 "Find Org node headline HEADING in all .org files in directory DIR.
16285 When the target headline is found, return a marker to this location."
16286 (let ((files (directory-files (or dir default-directory)
16287 t "\\`[^.#].*\\.org\\'"))
16288 file visiting m buffer)
16289 (catch 'found
16290 (while (setq file (pop files))
16291 (message "trying %s" file)
16292 (setq visiting (org-find-base-buffer-visiting file))
16293 (setq buffer (or visiting (find-file-noselect file)))
16294 (setq m (org-find-exact-headline-in-buffer
16295 heading buffer))
16296 (when (and (not m) (not visiting)) (kill-buffer buffer))
16297 (and m (throw 'found m))))))
16299 (defun org-find-entry-with-id (ident)
16300 "Locate the entry that contains the ID property with exact value IDENT.
16301 IDENT can be a string, a symbol or a number, this function will search for
16302 the string representation of it.
16303 Return the position where this entry starts, or nil if there is no such entry."
16304 (interactive "sID: ")
16305 (let ((id (cond
16306 ((stringp ident) ident)
16307 ((symbol-name ident) (symbol-name ident))
16308 ((numberp ident) (number-to-string ident))
16309 (t (error "IDENT %s must be a string, symbol or number" ident))))
16310 (case-fold-search nil))
16311 (save-excursion
16312 (save-restriction
16313 (widen)
16314 (goto-char (point-min))
16315 (when (re-search-forward
16316 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16317 nil t)
16318 (org-back-to-heading t)
16319 (point))))))
16321 ;;;; Timestamps
16323 (defvar org-last-changed-timestamp nil)
16324 (defvar org-last-inserted-timestamp nil
16325 "The last time stamp inserted with `org-insert-time-stamp'.")
16326 (defvar org-ts-what) ; dynamically scoped parameter
16328 (defun org-time-stamp (arg &optional inactive)
16329 "Prompt for a date/time and insert a time stamp.
16330 If the user specifies a time like HH:MM or if this command is
16331 called with at least one prefix argument, the time stamp contains
16332 the date and the time. Otherwise, only the date is be included.
16334 All parts of a date not specified by the user is filled in from
16335 the current date/time. So if you just press return without
16336 typing anything, the time stamp will represent the current
16337 date/time.
16339 If there is already a timestamp at the cursor, it will be
16340 modified.
16342 With two universal prefix arguments, insert an active timestamp
16343 with the current time without prompting the user.
16345 When called from lisp, the timestamp is inactive if INACTIVE is
16346 non-nil."
16347 (interactive "P")
16348 (let* ((ts nil)
16349 (default-time
16350 ;; Default time is either today, or, when entering a range,
16351 ;; the range start.
16352 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16353 (save-excursion
16354 (re-search-backward
16355 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16356 (- (point) 20) t)))
16357 (apply 'encode-time (org-parse-time-string (match-string 1)))
16358 (current-time)))
16359 (default-input (and ts (org-get-compact-tod ts)))
16360 (repeater (save-excursion
16361 (save-match-data
16362 (beginning-of-line)
16363 (when (re-search-forward
16364 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16365 (save-excursion (progn (end-of-line) (point))) t)
16366 (match-string 0)))))
16367 org-time-was-given org-end-time-was-given time)
16368 (cond
16369 ((and (org-at-timestamp-p t)
16370 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16371 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16372 (insert "--")
16373 (setq time (let ((this-command this-command))
16374 (org-read-date arg 'totime nil nil
16375 default-time default-input inactive)))
16376 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16377 ((org-at-timestamp-p t)
16378 (setq time (let ((this-command this-command))
16379 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16380 (when (org-at-timestamp-p t) ; just to get the match data
16381 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16382 (replace-match "")
16383 (setq org-last-changed-timestamp
16384 (org-insert-time-stamp
16385 time (or org-time-was-given arg)
16386 inactive nil nil (list org-end-time-was-given)))
16387 (when repeater (goto-char (1- (point))) (insert " " repeater)
16388 (setq org-last-changed-timestamp
16389 (concat (substring org-last-inserted-timestamp 0 -1)
16390 " " repeater ">"))))
16391 (message "Timestamp updated"))
16392 ((equal arg '(16))
16393 (org-insert-time-stamp (current-time) t inactive))
16395 (setq time (let ((this-command this-command))
16396 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16397 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16398 nil nil (list org-end-time-was-given))))))
16400 ;; FIXME: can we use this for something else, like computing time differences?
16401 (defun org-get-compact-tod (s)
16402 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16403 (let* ((t1 (match-string 1 s))
16404 (h1 (string-to-number (match-string 2 s)))
16405 (m1 (string-to-number (match-string 3 s)))
16406 (t2 (and (match-end 4) (match-string 5 s)))
16407 (h2 (and t2 (string-to-number (match-string 6 s))))
16408 (m2 (and t2 (string-to-number (match-string 7 s))))
16409 dh dm)
16410 (if (not t2)
16412 (setq dh (- h2 h1) dm (- m2 m1))
16413 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16414 (concat t1 "+" (number-to-string dh)
16415 (and (/= 0 dm) (format ":%02d" dm)))))))
16417 (defun org-time-stamp-inactive (&optional arg)
16418 "Insert an inactive time stamp.
16419 An inactive time stamp is enclosed in square brackets instead of angle
16420 brackets. It is inactive in the sense that it does not trigger agenda entries,
16421 does not link to the calendar and cannot be changed with the S-cursor keys.
16422 So these are more for recording a certain time/date."
16423 (interactive "P")
16424 (org-time-stamp arg 'inactive))
16426 (defvar org-date-ovl (make-overlay 1 1))
16427 (overlay-put org-date-ovl 'face 'org-date-selected)
16428 (org-detach-overlay org-date-ovl)
16430 (defvar org-ans1) ; dynamically scoped parameter
16431 (defvar org-ans2) ; dynamically scoped parameter
16433 (defvar org-plain-time-of-day-regexp) ; defined below
16435 (defvar org-overriding-default-time nil) ; dynamically scoped
16436 (defvar org-read-date-overlay nil)
16437 (defvar org-dcst nil) ; dynamically scoped
16438 (defvar org-read-date-history nil)
16439 (defvar org-read-date-final-answer nil)
16440 (defvar org-read-date-analyze-futurep nil)
16441 (defvar org-read-date-analyze-forced-year nil)
16442 (defvar org-read-date-inactive)
16444 (defvar org-read-date-minibuffer-local-map
16445 (let* ((org-replace-disputed-keys nil)
16446 (map (make-sparse-keymap)))
16447 (set-keymap-parent map minibuffer-local-map)
16448 (org-defkey map (kbd ".")
16449 (lambda () (interactive)
16450 ;; Are we at the beginning of the prompt?
16451 (if (looking-back "^[^:]+: ")
16452 (org-eval-in-calendar '(calendar-goto-today))
16453 (insert "."))))
16454 (org-defkey map (kbd "C-.")
16455 (lambda () (interactive)
16456 (org-eval-in-calendar '(calendar-goto-today))))
16457 (org-defkey map [(meta shift left)]
16458 (lambda () (interactive)
16459 (org-eval-in-calendar '(calendar-backward-month 1))))
16460 (org-defkey map [(meta shift right)]
16461 (lambda () (interactive)
16462 (org-eval-in-calendar '(calendar-forward-month 1))))
16463 (org-defkey map [(meta shift up)]
16464 (lambda () (interactive)
16465 (org-eval-in-calendar '(calendar-backward-year 1))))
16466 (org-defkey map [(meta shift down)]
16467 (lambda () (interactive)
16468 (org-eval-in-calendar '(calendar-forward-year 1))))
16469 (org-defkey map [?\e (shift left)]
16470 (lambda () (interactive)
16471 (org-eval-in-calendar '(calendar-backward-month 1))))
16472 (org-defkey map [?\e (shift right)]
16473 (lambda () (interactive)
16474 (org-eval-in-calendar '(calendar-forward-month 1))))
16475 (org-defkey map [?\e (shift up)]
16476 (lambda () (interactive)
16477 (org-eval-in-calendar '(calendar-backward-year 1))))
16478 (org-defkey map [?\e (shift down)]
16479 (lambda () (interactive)
16480 (org-eval-in-calendar '(calendar-forward-year 1))))
16481 (org-defkey map [(shift up)]
16482 (lambda () (interactive)
16483 (org-eval-in-calendar '(calendar-backward-week 1))))
16484 (org-defkey map [(shift down)]
16485 (lambda () (interactive)
16486 (org-eval-in-calendar '(calendar-forward-week 1))))
16487 (org-defkey map [(shift left)]
16488 (lambda () (interactive)
16489 (org-eval-in-calendar '(calendar-backward-day 1))))
16490 (org-defkey map [(shift right)]
16491 (lambda () (interactive)
16492 (org-eval-in-calendar '(calendar-forward-day 1))))
16493 (org-defkey map "!"
16494 (lambda () (interactive)
16495 (org-eval-in-calendar '(diary-view-entries))
16496 (message "")))
16497 (org-defkey map ">"
16498 (lambda () (interactive)
16499 (org-eval-in-calendar '(scroll-calendar-left 1))))
16500 (org-defkey map "<"
16501 (lambda () (interactive)
16502 (org-eval-in-calendar '(scroll-calendar-right 1))))
16503 (org-defkey map "\C-v"
16504 (lambda () (interactive)
16505 (org-eval-in-calendar
16506 '(calendar-scroll-left-three-months 1))))
16507 (org-defkey map "\M-v"
16508 (lambda () (interactive)
16509 (org-eval-in-calendar
16510 '(calendar-scroll-right-three-months 1))))
16511 map)
16512 "Keymap for minibuffer commands when using `org-read-date'.")
16514 (defvar org-def)
16515 (defvar org-defdecode)
16516 (defvar org-with-time)
16518 (defun org-read-date (&optional org-with-time to-time from-string prompt
16519 default-time default-input inactive)
16520 "Read a date, possibly a time, and make things smooth for the user.
16521 The prompt will suggest to enter an ISO date, but you can also enter anything
16522 which will at least partially be understood by `parse-time-string'.
16523 Unrecognized parts of the date will default to the current day, month, year,
16524 hour and minute. If this command is called to replace a timestamp at point,
16525 or to enter the second timestamp of a range, the default time is taken
16526 from the existing stamp. Furthermore, the command prefers the future,
16527 so if you are giving a date where the year is not given, and the day-month
16528 combination is already past in the current year, it will assume you
16529 mean next year. For details, see the manual. A few examples:
16531 3-2-5 --> 2003-02-05
16532 feb 15 --> currentyear-02-15
16533 2/15 --> currentyear-02-15
16534 sep 12 9 --> 2009-09-12
16535 12:45 --> today 12:45
16536 22 sept 0:34 --> currentyear-09-22 0:34
16537 12 --> currentyear-currentmonth-12
16538 Fri --> nearest Friday after today
16539 -Tue --> last Tuesday
16540 etc.
16542 Furthermore you can specify a relative date by giving, as the *first* thing
16543 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16544 change in days weeks, months, years.
16545 With a single plus or minus, the date is relative to today. With a double
16546 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16547 +4d --> four days from today
16548 +4 --> same as above
16549 +2w --> two weeks from today
16550 ++5 --> five days from default date
16552 The function understands only English month and weekday abbreviations.
16554 While prompting, a calendar is popped up - you can also select the
16555 date with the mouse (button 1). The calendar shows a period of three
16556 months. To scroll it to other months, use the keys `>' and `<'.
16557 If you don't like the calendar, turn it off with
16558 \(setq org-read-date-popup-calendar nil)
16560 With optional argument TO-TIME, the date will immediately be converted
16561 to an internal time.
16562 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16563 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16564 still enter a time, and this function will inform the calling routine
16565 about this change. The calling routine may then choose to change the
16566 format used to insert the time stamp into the buffer to include the time.
16567 With optional argument FROM-STRING, read from this string instead from
16568 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16569 the time/date that is used for everything that is not specified by the
16570 user."
16571 (require 'parse-time)
16572 (let* ((org-time-stamp-rounding-minutes
16573 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16574 (org-dcst org-display-custom-times)
16575 (ct (org-current-time))
16576 (org-def (or org-overriding-default-time default-time ct))
16577 (org-defdecode (decode-time org-def))
16578 (dummy (progn
16579 (when (< (nth 2 org-defdecode) org-extend-today-until)
16580 (setcar (nthcdr 2 org-defdecode) -1)
16581 (setcar (nthcdr 1 org-defdecode) 59)
16582 (setq org-def (apply 'encode-time org-defdecode)
16583 org-defdecode (decode-time org-def)))))
16584 (mouse-autoselect-window nil) ; Don't let the mouse jump
16585 (calendar-frame-setup nil)
16586 (calendar-setup nil)
16587 (calendar-move-hook nil)
16588 (calendar-view-diary-initially-flag nil)
16589 (calendar-view-holidays-initially-flag nil)
16590 (timestr (format-time-string
16591 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16592 (prompt (concat (if prompt (concat prompt " ") "")
16593 (format "Date+time [%s]: " timestr)))
16594 ans (org-ans0 "") org-ans1 org-ans2 final)
16596 (cond
16597 (from-string (setq ans from-string))
16598 (org-read-date-popup-calendar
16599 (save-excursion
16600 (save-window-excursion
16601 (calendar)
16602 (org-eval-in-calendar '(setq cursor-type nil) t)
16603 (unwind-protect
16604 (progn
16605 (calendar-forward-day (- (time-to-days org-def)
16606 (calendar-absolute-from-gregorian
16607 (calendar-current-date))))
16608 (org-eval-in-calendar nil t)
16609 (let* ((old-map (current-local-map))
16610 (map (copy-keymap calendar-mode-map))
16611 (minibuffer-local-map
16612 (copy-keymap org-read-date-minibuffer-local-map)))
16613 (org-defkey map (kbd "RET") 'org-calendar-select)
16614 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16615 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16616 (unwind-protect
16617 (progn
16618 (use-local-map map)
16619 (setq org-read-date-inactive inactive)
16620 (add-hook 'post-command-hook 'org-read-date-display)
16621 (setq org-ans0 (read-string prompt default-input
16622 'org-read-date-history nil))
16623 ;; org-ans0: from prompt
16624 ;; org-ans1: from mouse click
16625 ;; org-ans2: from calendar motion
16626 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16627 (remove-hook 'post-command-hook 'org-read-date-display)
16628 (use-local-map old-map)
16629 (when org-read-date-overlay
16630 (delete-overlay org-read-date-overlay)
16631 (setq org-read-date-overlay nil)))))
16632 (bury-buffer "*Calendar*")))))
16634 (t ; Naked prompt only
16635 (unwind-protect
16636 (setq ans (read-string prompt default-input
16637 'org-read-date-history timestr))
16638 (when org-read-date-overlay
16639 (delete-overlay org-read-date-overlay)
16640 (setq org-read-date-overlay nil)))))
16642 (setq final (org-read-date-analyze ans org-def org-defdecode))
16644 (when org-read-date-analyze-forced-year
16645 (message "Year was forced into %s"
16646 (if org-read-date-force-compatible-dates
16647 "compatible range (1970-2037)"
16648 "range representable on this machine"))
16649 (ding))
16651 ;; One round trip to get rid of 34th of August and stuff like that....
16652 (setq final (decode-time (apply 'encode-time final)))
16654 (setq org-read-date-final-answer ans)
16656 (if to-time
16657 (apply 'encode-time final)
16658 (if (and (boundp 'org-time-was-given) org-time-was-given)
16659 (format "%04d-%02d-%02d %02d:%02d"
16660 (nth 5 final) (nth 4 final) (nth 3 final)
16661 (nth 2 final) (nth 1 final))
16662 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16664 (defun org-read-date-display ()
16665 "Display the current date prompt interpretation in the minibuffer."
16666 (when org-read-date-display-live
16667 (when org-read-date-overlay
16668 (delete-overlay org-read-date-overlay))
16669 (when (minibufferp (current-buffer))
16670 (save-excursion
16671 (end-of-line 1)
16672 (while (not (equal (buffer-substring
16673 (max (point-min) (- (point) 4)) (point))
16674 " "))
16675 (insert " ")))
16676 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16677 " " (or org-ans1 org-ans2)))
16678 (org-end-time-was-given nil)
16679 (f (org-read-date-analyze ans org-def org-defdecode))
16680 (fmts (if org-dcst
16681 org-time-stamp-custom-formats
16682 org-time-stamp-formats))
16683 (fmt (if (or org-with-time
16684 (and (boundp 'org-time-was-given) org-time-was-given))
16685 (cdr fmts)
16686 (car fmts)))
16687 (txt (format-time-string fmt (apply 'encode-time f)))
16688 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16689 (txt (concat "=> " txt)))
16690 (when (and org-end-time-was-given
16691 (string-match org-plain-time-of-day-regexp txt))
16692 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16693 org-end-time-was-given
16694 (substring txt (match-end 0)))))
16695 (when org-read-date-analyze-futurep
16696 (setq txt (concat txt " (=>F)")))
16697 (setq org-read-date-overlay
16698 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16699 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16701 (defun org-read-date-analyze (ans org-def org-defdecode)
16702 "Analyze the combined answer of the date prompt."
16703 ;; FIXME: cleanup and comment
16704 (let ((nowdecode (decode-time (current-time)))
16705 delta deltan deltaw deltadef year month day
16706 hour minute second wday pm h2 m2 tl wday1
16707 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16708 (setq org-read-date-analyze-futurep nil
16709 org-read-date-analyze-forced-year nil)
16710 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16711 (setq ans "+0"))
16713 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16714 (setq ans (replace-match "" t t ans)
16715 deltan (car delta)
16716 deltaw (nth 1 delta)
16717 deltadef (nth 2 delta)))
16719 ;; Check if there is an iso week date in there. If yes, store the
16720 ;; info and postpone interpreting it until the rest of the parsing
16721 ;; is done.
16722 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16723 (setq iso-year (if (match-end 1)
16724 (org-small-year-to-year
16725 (string-to-number (match-string 1 ans))))
16726 iso-weekday (if (match-end 3)
16727 (string-to-number (match-string 3 ans)))
16728 iso-week (string-to-number (match-string 2 ans)))
16729 (setq ans (replace-match "" t t ans)))
16731 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16732 (when (string-match
16733 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16734 (setq year (if (match-end 2)
16735 (string-to-number (match-string 2 ans))
16736 (progn (setq kill-year t)
16737 (string-to-number (format-time-string "%Y"))))
16738 month (string-to-number (match-string 3 ans))
16739 day (string-to-number (match-string 4 ans)))
16740 (if (< year 100) (setq year (+ 2000 year)))
16741 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16742 t nil ans)))
16744 ;; Help matching dotted european dates
16745 (when (string-match
16746 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16747 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16748 (setq kill-year t)
16749 (string-to-number (format-time-string "%Y")))
16750 day (string-to-number (match-string 1 ans))
16751 month (string-to-number (match-string 2 ans))
16752 ans (replace-match (format "%04d-%02d-%02d" year month day)
16753 t nil ans)))
16755 ;; Help matching american dates, like 5/30 or 5/30/7
16756 (when (string-match
16757 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16758 (setq year (if (match-end 4)
16759 (string-to-number (match-string 4 ans))
16760 (progn (setq kill-year t)
16761 (string-to-number (format-time-string "%Y"))))
16762 month (string-to-number (match-string 1 ans))
16763 day (string-to-number (match-string 2 ans)))
16764 (if (< year 100) (setq year (+ 2000 year)))
16765 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16766 t nil ans)))
16767 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16768 ;; If there is a time with am/pm, and *no* time without it, we convert
16769 ;; so that matching will be successful.
16770 (loop for i from 1 to 2 do ; twice, for end time as well
16771 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16772 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16773 (setq hour (string-to-number (match-string 1 ans))
16774 minute (if (match-end 3)
16775 (string-to-number (match-string 3 ans))
16777 pm (equal ?p
16778 (string-to-char (downcase (match-string 4 ans)))))
16779 (if (and (= hour 12) (not pm))
16780 (setq hour 0)
16781 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16782 (setq ans (replace-match (format "%02d:%02d" hour minute)
16783 t t ans))))
16785 ;; Check if a time range is given as a duration
16786 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16787 (setq hour (string-to-number (match-string 1 ans))
16788 h2 (+ hour (string-to-number (match-string 3 ans)))
16789 minute (string-to-number (match-string 2 ans))
16790 m2 (+ minute (if (match-end 5) (string-to-number
16791 (match-string 5 ans))0)))
16792 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16793 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16794 t t ans)))
16796 ;; Check if there is a time range
16797 (when (boundp 'org-end-time-was-given)
16798 (setq org-time-was-given nil)
16799 (when (and (string-match org-plain-time-of-day-regexp ans)
16800 (match-end 8))
16801 (setq org-end-time-was-given (match-string 8 ans))
16802 (setq ans (concat (substring ans 0 (match-beginning 7))
16803 (substring ans (match-end 7))))))
16805 (setq tl (parse-time-string ans)
16806 day (or (nth 3 tl) (nth 3 org-defdecode))
16807 month (or (nth 4 tl)
16808 (if (and org-read-date-prefer-future
16809 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16810 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16811 (nth 4 org-defdecode)))
16812 year (or (and (not kill-year) (nth 5 tl))
16813 (if (and org-read-date-prefer-future
16814 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16815 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16816 (nth 5 org-defdecode)))
16817 hour (or (nth 2 tl) (nth 2 org-defdecode))
16818 minute (or (nth 1 tl) (nth 1 org-defdecode))
16819 second (or (nth 0 tl) 0)
16820 wday (nth 6 tl))
16822 (when (and (eq org-read-date-prefer-future 'time)
16823 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16824 (equal day (nth 3 nowdecode))
16825 (equal month (nth 4 nowdecode))
16826 (equal year (nth 5 nowdecode))
16827 (nth 2 tl)
16828 (or (< (nth 2 tl) (nth 2 nowdecode))
16829 (and (= (nth 2 tl) (nth 2 nowdecode))
16830 (nth 1 tl)
16831 (< (nth 1 tl) (nth 1 nowdecode)))))
16832 (setq day (1+ day)
16833 futurep t))
16835 ;; Special date definitions below
16836 (cond
16837 (iso-week
16838 ;; There was an iso week
16839 (require 'cal-iso)
16840 (setq futurep nil)
16841 (setq year (or iso-year year)
16842 day (or iso-weekday wday 1)
16843 wday nil ; to make sure that the trigger below does not match
16844 iso-date (calendar-gregorian-from-absolute
16845 (calendar-absolute-from-iso
16846 (list iso-week day year))))
16847 ; FIXME: Should we also push ISO weeks into the future?
16848 ; (when (and org-read-date-prefer-future
16849 ; (not iso-year)
16850 ; (< (calendar-absolute-from-gregorian iso-date)
16851 ; (time-to-days (current-time))))
16852 ; (setq year (1+ year)
16853 ; iso-date (calendar-gregorian-from-absolute
16854 ; (calendar-absolute-from-iso
16855 ; (list iso-week day year)))))
16856 (setq month (car iso-date)
16857 year (nth 2 iso-date)
16858 day (nth 1 iso-date)))
16859 (deltan
16860 (setq futurep nil)
16861 (unless deltadef
16862 (let ((now (decode-time (current-time))))
16863 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16864 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16865 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16866 ((equal deltaw "m") (setq month (+ month deltan)))
16867 ((equal deltaw "y") (setq year (+ year deltan)))))
16868 ((and wday (not (nth 3 tl)))
16869 ;; Weekday was given, but no day, so pick that day in the week
16870 ;; on or after the derived date.
16871 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16872 (unless (equal wday wday1)
16873 (setq day (+ day (% (- wday wday1 -7) 7))))))
16874 (if (and (boundp 'org-time-was-given)
16875 (nth 2 tl))
16876 (setq org-time-was-given t))
16877 (if (< year 100) (setq year (+ 2000 year)))
16878 ;; Check of the date is representable
16879 (if org-read-date-force-compatible-dates
16880 (progn
16881 (if (< year 1970)
16882 (setq year 1970 org-read-date-analyze-forced-year t))
16883 (if (> year 2037)
16884 (setq year 2037 org-read-date-analyze-forced-year t)))
16885 (condition-case nil
16886 (ignore (encode-time second minute hour day month year))
16887 (error
16888 (setq year (nth 5 org-defdecode))
16889 (setq org-read-date-analyze-forced-year t))))
16890 (setq org-read-date-analyze-futurep futurep)
16891 (list second minute hour day month year)))
16893 (defvar parse-time-weekdays)
16894 (defun org-read-date-get-relative (s today default)
16895 "Check string S for special relative date string.
16896 TODAY and DEFAULT are internal times, for today and for a default.
16897 Return shift list (N what def-flag)
16898 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16899 N is the number of WHATs to shift.
16900 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16901 the DEFAULT date rather than TODAY."
16902 (require 'parse-time)
16903 (when (and
16904 (string-match
16905 (concat
16906 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16907 "\\([0-9]+\\)?"
16908 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16909 "\\([ \t]\\|$\\)") s)
16910 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16911 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16912 (string-to-char (substring (match-string 1 s) -1))
16913 ?+))
16914 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16915 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16916 (what (if (match-end 3) (match-string 3 s) "d"))
16917 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16918 (date (if rel default today))
16919 (wday (nth 6 (decode-time date)))
16920 delta)
16921 (if wday1
16922 (progn
16923 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16924 (if (= delta 0) (setq delta 7))
16925 (if (= dir ?-)
16926 (progn
16927 (setq delta (- delta 7))
16928 (if (= delta 0) (setq delta -7))))
16929 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16930 (list delta "d" rel))
16931 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16933 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16934 "Turn a user-specified date into the internal representation.
16935 The internal representation needed by the calendar is (month day year).
16936 This is a wrapper to handle the brain-dead convention in calendar that
16937 user function argument order change dependent on argument order."
16938 (if (boundp 'calendar-date-style)
16939 (cond
16940 ((eq calendar-date-style 'american)
16941 (list arg1 arg2 arg3))
16942 ((eq calendar-date-style 'european)
16943 (list arg2 arg1 arg3))
16944 ((eq calendar-date-style 'iso)
16945 (list arg2 arg3 arg1)))
16946 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16947 (if (org-bound-and-true-p european-calendar-style)
16948 (list arg2 arg1 arg3)
16949 (list arg1 arg2 arg3)))))
16951 (defun org-eval-in-calendar (form &optional keepdate)
16952 "Eval FORM in the calendar window and return to current window.
16953 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16954 otherwise stick to the current value of `org-ans2'."
16955 (let ((sf (selected-frame))
16956 (sw (selected-window)))
16957 (select-window (get-buffer-window "*Calendar*" t))
16958 (eval form)
16959 (when (and (not keepdate) (calendar-cursor-to-date))
16960 (let* ((date (calendar-cursor-to-date))
16961 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16962 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16963 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16964 (select-window sw)
16965 (org-select-frame-set-input-focus sf)))
16967 (defun org-calendar-select ()
16968 "Return to `org-read-date' with the date currently selected.
16969 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16970 (interactive)
16971 (when (calendar-cursor-to-date)
16972 (let* ((date (calendar-cursor-to-date))
16973 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16974 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16975 (if (active-minibuffer-window) (exit-minibuffer))))
16977 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16978 "Insert a date stamp for the date given by the internal TIME.
16979 WITH-HM means use the stamp format that includes the time of the day.
16980 INACTIVE means use square brackets instead of angular ones, so that the
16981 stamp will not contribute to the agenda.
16982 PRE and POST are optional strings to be inserted before and after the
16983 stamp.
16984 The command returns the inserted time stamp."
16985 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16986 stamp)
16987 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16988 (insert-before-markers (or pre ""))
16989 (when (listp extra)
16990 (setq extra (car extra))
16991 (if (and (stringp extra)
16992 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16993 (setq extra (format "-%02d:%02d"
16994 (string-to-number (match-string 1 extra))
16995 (string-to-number (match-string 2 extra))))
16996 (setq extra nil)))
16997 (when extra
16998 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16999 (insert-before-markers (setq stamp (format-time-string fmt time)))
17000 (insert-before-markers (or post ""))
17001 (setq org-last-inserted-timestamp stamp)))
17003 (defun org-toggle-time-stamp-overlays ()
17004 "Toggle the use of custom time stamp formats."
17005 (interactive)
17006 (setq org-display-custom-times (not org-display-custom-times))
17007 (unless org-display-custom-times
17008 (let ((p (point-min)) (bmp (buffer-modified-p)))
17009 (while (setq p (next-single-property-change p 'display))
17010 (if (and (get-text-property p 'display)
17011 (eq (get-text-property p 'face) 'org-date))
17012 (remove-text-properties
17013 p (setq p (next-single-property-change p 'display))
17014 '(display t))))
17015 (set-buffer-modified-p bmp)))
17016 (if (featurep 'xemacs)
17017 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17018 (org-restart-font-lock)
17019 (setq org-table-may-need-update t)
17020 (if org-display-custom-times
17021 (message "Time stamps are overlaid with custom format")
17022 (message "Time stamp overlays removed")))
17024 (defun org-display-custom-time (beg end)
17025 "Overlay modified time stamp format over timestamp between BEG and END."
17026 (let* ((ts (buffer-substring beg end))
17027 t1 w1 with-hm tf time str w2 (off 0))
17028 (save-match-data
17029 (setq t1 (org-parse-time-string ts t))
17030 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17031 (setq off (- (match-end 0) (match-beginning 0)))))
17032 (setq end (- end off))
17033 (setq w1 (- end beg)
17034 with-hm (and (nth 1 t1) (nth 2 t1))
17035 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17036 time (org-fix-decoded-time t1)
17037 str (org-add-props
17038 (format-time-string
17039 (substring tf 1 -1) (apply 'encode-time time))
17040 nil 'mouse-face 'highlight)
17041 w2 (length str))
17042 (if (not (= w2 w1))
17043 (add-text-properties (1+ beg) (+ 2 beg)
17044 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17045 (if (featurep 'xemacs)
17046 (progn
17047 (put-text-property beg end 'invisible t)
17048 (put-text-property beg end 'end-glyph (make-glyph str)))
17049 (put-text-property beg end 'display str))))
17051 (defun org-translate-time (string)
17052 "Translate all timestamps in STRING to custom format.
17053 But do this only if the variable `org-display-custom-times' is set."
17054 (when org-display-custom-times
17055 (save-match-data
17056 (let* ((start 0)
17057 (re org-ts-regexp-both)
17058 t1 with-hm inactive tf time str beg end)
17059 (while (setq start (string-match re string start))
17060 (setq beg (match-beginning 0)
17061 end (match-end 0)
17062 t1 (save-match-data
17063 (org-parse-time-string (substring string beg end) t))
17064 with-hm (and (nth 1 t1) (nth 2 t1))
17065 inactive (equal (substring string beg (1+ beg)) "[")
17066 tf (funcall (if with-hm 'cdr 'car)
17067 org-time-stamp-custom-formats)
17068 time (org-fix-decoded-time t1)
17069 str (format-time-string
17070 (concat
17071 (if inactive "[" "<") (substring tf 1 -1)
17072 (if inactive "]" ">"))
17073 (apply 'encode-time time))
17074 string (replace-match str t t string)
17075 start (+ start (length str)))))))
17076 string)
17078 (defun org-fix-decoded-time (time)
17079 "Set 0 instead of nil for the first 6 elements of time.
17080 Don't touch the rest."
17081 (let ((n 0))
17082 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17084 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17086 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17087 "Difference between TIMESTAMP-STRING and now in days.
17088 If SECONDS is non-nil, return the difference in seconds."
17089 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17090 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17091 (funcall fdiff (current-time)))))
17093 (defun org-deadline-close (timestamp-string &optional ndays)
17094 "Is the time in TIMESTAMP-STRING close to the current date?"
17095 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17096 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17097 (not (org-entry-is-done-p))))
17099 (defun org-get-wdays (ts &optional delay zero-delay)
17100 "Get the deadline lead time appropriate for timestring TS.
17101 When DELAY is non-nil, get the delay time for scheduled items
17102 instead of the deadline lead time. When ZERO-DELAY is non-nil
17103 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17104 don't try to find the delay cookie in the scheduled timestamp."
17105 (let ((tv (if delay org-scheduled-delay-days
17106 org-deadline-warning-days)))
17107 (cond
17108 ((or (and delay (< tv 0))
17109 (and delay zero-delay (<= tv 0))
17110 (and (not delay) (<= tv 0)))
17111 ;; Enforce this value no matter what
17112 (- tv))
17113 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17114 ;; lead time is specified.
17115 (floor (* (string-to-number (match-string 1 ts))
17116 (cdr (assoc (match-string 2 ts)
17117 '(("d" . 1) ("w" . 7)
17118 ("m" . 30.4) ("y" . 365.25)
17119 ("h" . 0.041667)))))))
17120 ;; go for the default.
17121 (t tv))))
17123 (defun org-calendar-select-mouse (ev)
17124 "Return to `org-read-date' with the date currently selected.
17125 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17126 (interactive "e")
17127 (mouse-set-point ev)
17128 (when (calendar-cursor-to-date)
17129 (let* ((date (calendar-cursor-to-date))
17130 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17131 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17132 (if (active-minibuffer-window) (exit-minibuffer))))
17134 (defun org-check-deadlines (ndays)
17135 "Check if there are any deadlines due or past due.
17136 A deadline is considered due if it happens within `org-deadline-warning-days'
17137 days from today's date. If the deadline appears in an entry marked DONE,
17138 it is not shown. The prefix arg NDAYS can be used to test that many
17139 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17140 (interactive "P")
17141 (let* ((org-warn-days
17142 (cond
17143 ((equal ndays '(4)) 100000)
17144 (ndays (prefix-numeric-value ndays))
17145 (t (abs org-deadline-warning-days))))
17146 (case-fold-search nil)
17147 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17148 (callback
17149 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17151 (message "%d deadlines past-due or due within %d days"
17152 (org-occur regexp nil callback)
17153 org-warn-days)))
17155 (defsubst org-re-timestamp (type)
17156 "Return a regexp for timestamp TYPE.
17157 Allowed values for TYPE are:
17159 all: all timestamps
17160 active: only active timestamps (<...>)
17161 inactive: only inactive timestamps ([...])
17162 scheduled: only scheduled timestamps
17163 deadline: only deadline timestamps
17164 closed: only closed time-stamps
17166 When TYPE is nil, fall back on returning a regexp that matches
17167 both scheduled and deadline timestamps."
17168 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17169 ((eq type 'active) org-ts-regexp)
17170 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17171 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17172 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17173 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17174 ((eq type 'scheduled-or-deadline)
17175 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17177 (defun org-check-before-date (date)
17178 "Check if there are deadlines or scheduled entries before DATE."
17179 (interactive (list (org-read-date)))
17180 (let ((case-fold-search nil)
17181 (regexp (org-re-timestamp org-ts-type))
17182 (callback
17183 (lambda () (time-less-p
17184 (org-time-string-to-time (match-string 1))
17185 (org-time-string-to-time date)))))
17186 (message "%d entries before %s"
17187 (org-occur regexp nil callback) date)))
17189 (defun org-check-after-date (date)
17190 "Check if there are deadlines or scheduled entries after DATE."
17191 (interactive (list (org-read-date)))
17192 (let ((case-fold-search nil)
17193 (regexp (org-re-timestamp org-ts-type))
17194 (callback
17195 (lambda () (not
17196 (time-less-p
17197 (org-time-string-to-time (match-string 1))
17198 (org-time-string-to-time date))))))
17199 (message "%d entries after %s"
17200 (org-occur regexp nil callback) date)))
17202 (defun org-check-dates-range (start-date end-date)
17203 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17204 (interactive (list (org-read-date nil nil nil "Range starts")
17205 (org-read-date nil nil nil "Range end")))
17206 (let ((case-fold-search nil)
17207 (regexp (org-re-timestamp org-ts-type))
17208 (callback
17209 (lambda ()
17210 (let ((match (match-string 1)))
17211 (and
17212 (not (time-less-p
17213 (org-time-string-to-time match)
17214 (org-time-string-to-time start-date)))
17215 (time-less-p
17216 (org-time-string-to-time match)
17217 (org-time-string-to-time end-date)))))))
17218 (message "%d entries between %s and %s"
17219 (org-occur regexp nil callback) start-date end-date)))
17221 (defun org-evaluate-time-range (&optional to-buffer)
17222 "Evaluate a time range by computing the difference between start and end.
17223 Normally the result is just printed in the echo area, but with prefix arg
17224 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17225 If the time range is actually in a table, the result is inserted into the
17226 next column.
17227 For time difference computation, a year is assumed to be exactly 365
17228 days in order to avoid rounding problems."
17229 (interactive "P")
17231 (org-clock-update-time-maybe)
17232 (save-excursion
17233 (unless (org-at-date-range-p t)
17234 (goto-char (point-at-bol))
17235 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17236 (if (not (org-at-date-range-p t))
17237 (user-error "Not at a time-stamp range, and none found in current line")))
17238 (let* ((ts1 (match-string 1))
17239 (ts2 (match-string 2))
17240 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17241 (match-end (match-end 0))
17242 (time1 (org-time-string-to-time ts1))
17243 (time2 (org-time-string-to-time ts2))
17244 (t1 (org-float-time time1))
17245 (t2 (org-float-time time2))
17246 (diff (abs (- t2 t1)))
17247 (negative (< (- t2 t1) 0))
17248 ;; (ys (floor (* 365 24 60 60)))
17249 (ds (* 24 60 60))
17250 (hs (* 60 60))
17251 (fy "%dy %dd %02d:%02d")
17252 (fy1 "%dy %dd")
17253 (fd "%dd %02d:%02d")
17254 (fd1 "%dd")
17255 (fh "%02d:%02d")
17256 y d h m align)
17257 (if havetime
17258 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17260 d (floor (/ diff ds)) diff (mod diff ds)
17261 h (floor (/ diff hs)) diff (mod diff hs)
17262 m (floor (/ diff 60)))
17263 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17265 d (floor (+ (/ diff ds) 0.5))
17266 h 0 m 0))
17267 (if (not to-buffer)
17268 (message "%s" (org-make-tdiff-string y d h m))
17269 (if (org-at-table-p)
17270 (progn
17271 (goto-char match-end)
17272 (setq align t)
17273 (and (looking-at " *|") (goto-char (match-end 0))))
17274 (goto-char match-end))
17275 (if (looking-at
17276 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17277 (replace-match ""))
17278 (if negative (insert " -"))
17279 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17280 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17281 (insert " " (format fh h m))))
17282 (if align (org-table-align))
17283 (message "Time difference inserted")))))
17285 (defun org-make-tdiff-string (y d h m)
17286 (let ((fmt "")
17287 (l nil))
17288 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17289 l (push y l)))
17290 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17291 l (push d l)))
17292 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17293 l (push h l)))
17294 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17295 l (push m l)))
17296 (apply 'format fmt (nreverse l))))
17298 (defun org-time-string-to-time (s &optional buffer pos)
17299 "Convert a timestamp string into internal time."
17300 (condition-case errdata
17301 (apply 'encode-time (org-parse-time-string s))
17302 (error (error "Bad timestamp `%s'%s\nError was: %s"
17303 s (if (not (and buffer pos))
17305 (format " at %d in buffer `%s'" pos buffer))
17306 (cdr errdata)))))
17308 (defun org-time-string-to-seconds (s)
17309 "Convert a timestamp string to a number of seconds."
17310 (org-float-time (org-time-string-to-time s)))
17312 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17313 "Convert a time stamp to an absolute day number.
17314 If there is a specifier for a cyclic time stamp, get the closest
17315 date to DAYNR.
17316 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17317 The variable `date' is bound by the calendar when this is called."
17318 (cond
17319 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17320 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17321 daynr
17322 (+ daynr 1000)))
17323 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17324 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17325 (time-to-days (current-time))) (match-string 0 s)
17326 prefer show-all))
17327 (t (time-to-days
17328 (condition-case errdata
17329 (apply 'encode-time (org-parse-time-string s))
17330 (error (error "Bad timestamp `%s'%s\nError was: %s"
17331 s (if (not (and buffer pos))
17333 (format " at %d in buffer `%s'" pos buffer))
17334 (cdr errdata))))))))
17336 (defun org-days-to-iso-week (days)
17337 "Return the iso week number."
17338 (require 'cal-iso)
17339 (car (calendar-iso-from-absolute days)))
17341 (defun org-small-year-to-year (year)
17342 "Convert 2-digit years into 4-digit years.
17343 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17344 The year 2000 cannot be abbreviated. Any year larger than 99
17345 is returned unchanged."
17346 (if (< year 38)
17347 (setq year (+ 2000 year))
17348 (if (< year 100)
17349 (setq year (+ 1900 year))))
17350 year)
17352 (defun org-time-from-absolute (d)
17353 "Return the time corresponding to date D.
17354 D may be an absolute day number, or a calendar-type list (month day year)."
17355 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17356 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17358 (defun org-calendar-holiday ()
17359 "List of holidays, for Diary display in Org-mode."
17360 (require 'holidays)
17361 (let ((hl (funcall
17362 (if (fboundp 'calendar-check-holidays)
17363 'calendar-check-holidays 'check-calendar-holidays) date)))
17364 (if hl (mapconcat 'identity hl "; "))))
17366 (defun org-diary-sexp-entry (sexp entry date)
17367 "Process a SEXP diary ENTRY for DATE."
17368 (require 'diary-lib)
17369 (let ((result (if calendar-debug-sexp
17370 (let ((stack-trace-on-error t))
17371 (eval (car (read-from-string sexp))))
17372 (condition-case nil
17373 (eval (car (read-from-string sexp)))
17374 (error
17375 (beep)
17376 (message "Bad sexp at line %d in %s: %s"
17377 (org-current-line)
17378 (buffer-file-name) sexp)
17379 (sleep-for 2))))))
17380 (cond ((stringp result) (split-string result "; "))
17381 ((and (consp result)
17382 (not (consp (cdr result)))
17383 (stringp (cdr result))) (cdr result))
17384 ((and (consp result)
17385 (stringp (car result))) result)
17386 (result entry))))
17388 (defun org-diary-to-ical-string (frombuf)
17389 "Get iCalendar entries from diary entries in buffer FROMBUF.
17390 This uses the icalendar.el library."
17391 (let* ((tmpdir (if (featurep 'xemacs)
17392 (temp-directory)
17393 temporary-file-directory))
17394 (tmpfile (make-temp-name
17395 (expand-file-name "orgics" tmpdir)))
17396 buf rtn b e)
17397 (with-current-buffer frombuf
17398 (icalendar-export-region (point-min) (point-max) tmpfile)
17399 (setq buf (find-buffer-visiting tmpfile))
17400 (set-buffer buf)
17401 (goto-char (point-min))
17402 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17403 (setq b (match-beginning 0)))
17404 (goto-char (point-max))
17405 (if (re-search-backward "^END:VEVENT" nil t)
17406 (setq e (match-end 0)))
17407 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17408 (kill-buffer buf)
17409 (delete-file tmpfile)
17410 rtn))
17412 (defun org-closest-date (start current change prefer show-all)
17413 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17414 When PREFER is `past', return a date that is either CURRENT or past.
17415 When PREFER is `future', return a date that is either CURRENT or future.
17416 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17417 ;; Make the proper lists from the dates
17418 (catch 'exit
17419 (let ((a1 '(("h" . hour)
17420 ("d" . day)
17421 ("w" . week)
17422 ("m" . month)
17423 ("y" . year)))
17424 (shour (nth 2 (org-parse-time-string start)))
17425 dn dw sday cday n1 n2 n0
17426 d m y y1 y2 date1 date2 nmonths nm ny m2)
17428 (setq start (org-date-to-gregorian start)
17429 current (org-date-to-gregorian
17430 (if show-all
17431 current
17432 (time-to-days (current-time))))
17433 sday (calendar-absolute-from-gregorian start)
17434 cday (calendar-absolute-from-gregorian current))
17436 (if (<= cday sday) (throw 'exit sday))
17438 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17439 (setq dn (string-to-number (match-string 1 change))
17440 dw (cdr (assoc (match-string 2 change) a1)))
17441 (user-error "Invalid change specifier: %s" change))
17442 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17443 (cond
17444 ((eq dw 'hour)
17445 (let ((missing-hours
17446 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17447 dn)))
17448 (setq n1 (if (zerop missing-hours) cday
17449 (- cday (1+ (floor (/ missing-hours 24)))))
17450 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17451 ((eq dw 'day)
17452 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17453 n2 (+ n1 dn)))
17454 ((eq dw 'year)
17455 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17456 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17457 (setq date1 (list m d y1)
17458 n1 (calendar-absolute-from-gregorian date1)
17459 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17460 n2 (calendar-absolute-from-gregorian date2)))
17461 ((eq dw 'month)
17462 ;; approx number of month between the two dates
17463 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17464 ;; How often does dn fit in there?
17465 (setq d (nth 1 start) m (car start) y (nth 2 start)
17466 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17467 m (+ m nm)
17468 ny (floor (/ m 12))
17469 y (+ y ny)
17470 m (- m (* ny 12)))
17471 (while (> m 12) (setq m (- m 12) y (1+ y)))
17472 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17473 (setq m2 (+ m dn) y2 y)
17474 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17475 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17476 (while (<= n2 cday)
17477 (setq n1 n2 m m2 y y2)
17478 (setq m2 (+ m dn) y2 y)
17479 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17480 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17481 ;; Make sure n1 is the earlier date
17482 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17483 (if show-all
17484 (cond
17485 ((eq prefer 'past) (if (= cday n2) n2 n1))
17486 ((eq prefer 'future) (if (= cday n1) n1 n2))
17487 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17488 (cond
17489 ((eq prefer 'past) (if (= cday n2) n2 n1))
17490 ((eq prefer 'future) (if (= cday n1) n1 n2))
17491 (t (if (= cday n1) n1 n2)))))))
17493 (defun org-date-to-gregorian (date)
17494 "Turn any specification of DATE into a Gregorian date for the calendar."
17495 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17496 ((and (listp date) (= (length date) 3)) date)
17497 ((stringp date)
17498 (setq date (org-parse-time-string date))
17499 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17500 ((listp date)
17501 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17503 (defun org-parse-time-string (s &optional nodefault)
17504 "Parse the standard Org-mode time string.
17505 This should be a lot faster than the normal `parse-time-string'.
17506 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17507 hour and minute fields will be nil if not given."
17508 (cond ((string-match org-ts-regexp0 s)
17509 (list 0
17510 (if (or (match-beginning 8) (not nodefault))
17511 (string-to-number (or (match-string 8 s) "0")))
17512 (if (or (match-beginning 7) (not nodefault))
17513 (string-to-number (or (match-string 7 s) "0")))
17514 (string-to-number (match-string 4 s))
17515 (string-to-number (match-string 3 s))
17516 (string-to-number (match-string 2 s))
17517 nil nil nil))
17518 ((string-match "^<[^>]+>$" s)
17519 (decode-time (seconds-to-time (org-matcher-time s))))
17520 (t (error "Not a standard Org-mode time string: %s" s))))
17522 (defun org-timestamp-up (&optional arg)
17523 "Increase the date item at the cursor by one.
17524 If the cursor is on the year, change the year. If it is on the month,
17525 the day or the time, change that.
17526 With prefix ARG, change by that many units."
17527 (interactive "p")
17528 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17530 (defun org-timestamp-down (&optional arg)
17531 "Decrease the date item at the cursor by one.
17532 If the cursor is on the year, change the year. If it is on the month,
17533 the day or the time, change that.
17534 With prefix ARG, change by that many units."
17535 (interactive "p")
17536 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17538 (defun org-timestamp-up-day (&optional arg)
17539 "Increase the date in the time stamp by one day.
17540 With prefix ARG, change that many days."
17541 (interactive "p")
17542 (if (and (not (org-at-timestamp-p t))
17543 (org-at-heading-p))
17544 (org-todo 'up)
17545 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17547 (defun org-timestamp-down-day (&optional arg)
17548 "Decrease the date in the time stamp by one day.
17549 With prefix ARG, change that many days."
17550 (interactive "p")
17551 (if (and (not (org-at-timestamp-p t))
17552 (org-at-heading-p))
17553 (org-todo 'down)
17554 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17556 (defun org-at-timestamp-p (&optional inactive-ok)
17557 "Determine if the cursor is in or at a timestamp."
17558 (interactive)
17559 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17560 (pos (point))
17561 (ans (or (looking-at tsr)
17562 (save-excursion
17563 (skip-chars-backward "^[<\n\r\t")
17564 (if (> (point) (point-min)) (backward-char 1))
17565 (and (looking-at tsr)
17566 (> (- (match-end 0) pos) -1))))))
17567 (and ans
17568 (boundp 'org-ts-what)
17569 (setq org-ts-what
17570 (cond
17571 ((= pos (match-beginning 0)) 'bracket)
17572 ;; Point is considered to be "on the bracket" whether
17573 ;; it's really on it or right after it.
17574 ((= pos (1- (match-end 0))) 'bracket)
17575 ((= pos (match-end 0)) 'after)
17576 ((org-pos-in-match-range pos 2) 'year)
17577 ((org-pos-in-match-range pos 3) 'month)
17578 ((org-pos-in-match-range pos 7) 'hour)
17579 ((org-pos-in-match-range pos 8) 'minute)
17580 ((or (org-pos-in-match-range pos 4)
17581 (org-pos-in-match-range pos 5)) 'day)
17582 ((and (> pos (or (match-end 8) (match-end 5)))
17583 (< pos (match-end 0)))
17584 (- pos (or (match-end 8) (match-end 5))))
17585 (t 'day))))
17586 ans))
17588 (defun org-toggle-timestamp-type ()
17589 "Toggle the type (<active> or [inactive]) of a time stamp."
17590 (interactive)
17591 (when (org-at-timestamp-p t)
17592 (let ((beg (match-beginning 0)) (end (match-end 0))
17593 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17594 (save-excursion
17595 (goto-char beg)
17596 (while (re-search-forward "[][<>]" end t)
17597 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17598 t t)))
17599 (message "Timestamp is now %sactive"
17600 (if (equal (char-after beg) ?<) "" "in")))))
17602 (defun org-at-clock-log-p nil
17603 "Is the cursor on the clock log line?"
17604 (save-excursion
17605 (move-beginning-of-line 1)
17606 (looking-at org-clock-line-re)))
17608 (defvar org-clock-history) ; defined in org-clock.el
17609 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17610 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17611 "Change the date in the time stamp at point.
17612 The date will be changed by N times WHAT. WHAT can be `day', `month',
17613 `year', `minute', `second'. If WHAT is not given, the cursor position
17614 in the timestamp determines what will be changed.
17615 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17616 (let ((origin (point)) origin-cat
17617 with-hm inactive
17618 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17619 org-ts-what
17620 extra rem
17621 ts time time0 fixnext clrgx)
17622 (if (not (org-at-timestamp-p t))
17623 (user-error "Not at a timestamp"))
17624 (if (and (not what) (eq org-ts-what 'bracket))
17625 (org-toggle-timestamp-type)
17626 ;; Point isn't on brackets. Remember the part of the time-stamp
17627 ;; the point was in. Indeed, size of time-stamps may change,
17628 ;; but point must be kept in the same category nonetheless.
17629 (setq origin-cat org-ts-what)
17630 (if (and (not what) (not (eq org-ts-what 'day))
17631 org-display-custom-times
17632 (get-text-property (point) 'display)
17633 (not (get-text-property (1- (point)) 'display)))
17634 (setq org-ts-what 'day))
17635 (setq org-ts-what (or what org-ts-what)
17636 inactive (= (char-after (match-beginning 0)) ?\[)
17637 ts (match-string 0))
17638 (replace-match "")
17639 (when (string-match
17640 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17642 (setq extra (match-string 1 ts))
17643 (if suppress-tmp-delay
17644 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17645 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17646 (setq with-hm t))
17647 (setq time0 (org-parse-time-string ts))
17648 (when (and updown
17649 (eq org-ts-what 'minute)
17650 (not current-prefix-arg))
17651 ;; This looks like s-up and s-down. Change by one rounding step.
17652 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17653 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17654 (setcar (cdr time0) (+ (nth 1 time0)
17655 (if (> n 0) (- rem) (- dm rem))))))
17656 (setq time
17657 (encode-time (or (car time0) 0)
17658 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17659 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17660 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17661 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17662 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17663 (nthcdr 6 time0)))
17664 (when (and (member org-ts-what '(hour minute))
17665 extra
17666 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17667 (setq extra (org-modify-ts-extra
17668 extra
17669 (if (eq org-ts-what 'hour) 2 5)
17670 n dm)))
17671 (when (integerp org-ts-what)
17672 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17673 (if (eq what 'calendar)
17674 (let ((cal-date (org-get-date-from-calendar)))
17675 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17676 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17677 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17678 (setcar time0 (or (car time0) 0))
17679 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17680 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17681 (setq time (apply 'encode-time time0))))
17682 ;; Insert the new time-stamp, and ensure point stays in the same
17683 ;; category as before (i.e. not after the last position in that
17684 ;; category).
17685 (let ((pos (point)))
17686 ;; Stay before inserted string. `save-excursion' is of no use.
17687 (setq org-last-changed-timestamp
17688 (org-insert-time-stamp time with-hm inactive nil nil extra))
17689 (goto-char pos))
17690 (save-match-data
17691 (looking-at org-ts-regexp3)
17692 (goto-char (cond
17693 ;; `day' category ends before `hour' if any, or at
17694 ;; the end of the day name.
17695 ((eq origin-cat 'day)
17696 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17697 ((eq origin-cat 'hour) (min (match-end 7) origin))
17698 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17699 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17700 ;; `year' and `month' have both fixed size: point
17701 ;; couldn't have moved into another part.
17702 (t origin))))
17703 ;; Update clock if on a CLOCK line.
17704 (org-clock-update-time-maybe)
17705 ;; Maybe adjust the closest clock in `org-clock-history'
17706 (when org-clock-adjust-closest
17707 (if (not (and (org-at-clock-log-p)
17708 (< 1 (length (delq nil (mapcar 'marker-position
17709 org-clock-history))))))
17710 (message "No clock to adjust")
17711 (cond ((save-excursion ; fix previous clock?
17712 (re-search-backward org-ts-regexp0 nil t)
17713 (org-looking-back (concat org-clock-string " \\[")))
17714 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17715 ((save-excursion ; fix next clock?
17716 (re-search-backward org-ts-regexp0 nil t)
17717 (looking-at (concat org-ts-regexp0 "\\] =>")))
17718 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17719 (save-window-excursion
17720 ;; Find closest clock to point, adjust the previous/next one in history
17721 (let* ((p (save-excursion (org-back-to-heading t)))
17722 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17723 (clfixnth
17724 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17725 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17726 (if (not clfixpos)
17727 (message "No clock to adjust")
17728 (save-excursion
17729 (org-goto-marker-or-bmk clfixpos)
17730 (org-show-subtree)
17731 (when (re-search-forward clrgx nil t)
17732 (goto-char (match-beginning 1))
17733 (let (org-clock-adjust-closest)
17734 (org-timestamp-change n org-ts-what updown))
17735 (message "Clock adjusted in %s for heading: %s"
17736 (file-name-nondirectory (buffer-file-name))
17737 (org-get-heading t t)))))))))
17738 ;; Try to recenter the calendar window, if any.
17739 (if (and org-calendar-follow-timestamp-change
17740 (get-buffer-window "*Calendar*" t)
17741 (memq org-ts-what '(day month year)))
17742 (org-recenter-calendar (time-to-days time))))))
17744 (defun org-modify-ts-extra (s pos n dm)
17745 "Change the different parts of the lead-time and repeat fields in timestamp."
17746 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17747 ng h m new rem)
17748 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17749 (cond
17750 ((or (org-pos-in-match-range pos 2)
17751 (org-pos-in-match-range pos 3))
17752 (setq m (string-to-number (match-string 3 s))
17753 h (string-to-number (match-string 2 s)))
17754 (if (org-pos-in-match-range pos 2)
17755 (setq h (+ h n))
17756 (setq n (* dm (org-no-warnings (signum n))))
17757 (when (not (= 0 (setq rem (% m dm))))
17758 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17759 (setq m (+ m n)))
17760 (if (< m 0) (setq m (+ m 60) h (1- h)))
17761 (if (> m 59) (setq m (- m 60) h (1+ h)))
17762 (setq h (min 24 (max 0 h)))
17763 (setq ng 1 new (format "-%02d:%02d" h m)))
17764 ((org-pos-in-match-range pos 6)
17765 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17766 ((org-pos-in-match-range pos 5)
17767 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17769 ((org-pos-in-match-range pos 9)
17770 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17771 ((org-pos-in-match-range pos 8)
17772 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17774 (when ng
17775 (setq s (concat
17776 (substring s 0 (match-beginning ng))
17778 (substring s (match-end ng))))))
17781 (defun org-recenter-calendar (date)
17782 "If the calendar is visible, recenter it to DATE."
17783 (let ((cwin (get-buffer-window "*Calendar*" t)))
17784 (when cwin
17785 (let ((calendar-move-hook nil))
17786 (with-selected-window cwin
17787 (calendar-goto-date (if (listp date) date
17788 (calendar-gregorian-from-absolute date))))))))
17790 (defun org-goto-calendar (&optional arg)
17791 "Go to the Emacs calendar at the current date.
17792 If there is a time stamp in the current line, go to that date.
17793 A prefix ARG can be used to force the current date."
17794 (interactive "P")
17795 (let ((tsr org-ts-regexp) diff
17796 (calendar-move-hook nil)
17797 (calendar-view-holidays-initially-flag nil)
17798 (calendar-view-diary-initially-flag nil))
17799 (if (or (org-at-timestamp-p)
17800 (save-excursion
17801 (beginning-of-line 1)
17802 (looking-at (concat ".*" tsr))))
17803 (let ((d1 (time-to-days (current-time)))
17804 (d2 (time-to-days
17805 (org-time-string-to-time (match-string 1)))))
17806 (setq diff (- d2 d1))))
17807 (calendar)
17808 (calendar-goto-today)
17809 (if (and diff (not arg)) (calendar-forward-day diff))))
17811 (defun org-get-date-from-calendar ()
17812 "Return a list (month day year) of date at point in calendar."
17813 (with-current-buffer "*Calendar*"
17814 (save-match-data
17815 (calendar-cursor-to-date))))
17817 (defun org-date-from-calendar ()
17818 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17819 If there is already a time stamp at the cursor position, update it."
17820 (interactive)
17821 (if (org-at-timestamp-p t)
17822 (org-timestamp-change 0 'calendar)
17823 (let ((cal-date (org-get-date-from-calendar)))
17824 (org-insert-time-stamp
17825 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17827 (defcustom org-effort-durations
17828 `(("h" . 60)
17829 ("d" . ,(* 60 8))
17830 ("w" . ,(* 60 8 5))
17831 ("m" . ,(* 60 8 5 4))
17832 ("y" . ,(* 60 8 5 40)))
17833 "Conversion factor to minutes for an effort modifier.
17835 Each entry has the form (MODIFIER . MINUTES).
17837 In an effort string, a number followed by MODIFIER is multiplied
17838 by the specified number of MINUTES to obtain an effort in
17839 minutes.
17841 For example, if the value of this variable is ((\"hours\" . 60)), then an
17842 effort string \"2hours\" is equivalent to 120 minutes."
17843 :group 'org-agenda
17844 :version "24.1"
17845 :type '(alist :key-type (string :tag "Modifier")
17846 :value-type (number :tag "Minutes")))
17848 (defun org-minutes-to-clocksum-string (m)
17849 "Format number of minutes as a clocksum string.
17850 The format is determined by `org-time-clocksum-format',
17851 `org-time-clocksum-use-fractional' and
17852 `org-time-clocksum-fractional-format' and
17853 `org-time-clocksum-use-effort-durations'."
17854 (let ((clocksum "")
17855 (m (round m)) ; Don't allow fractions of minutes
17856 h d w mo y fmt n)
17857 (setq h (if org-time-clocksum-use-effort-durations
17858 (cdr (assoc "h" org-effort-durations)) 60)
17859 d (if org-time-clocksum-use-effort-durations
17860 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17861 w (if org-time-clocksum-use-effort-durations
17862 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17863 mo (if org-time-clocksum-use-effort-durations
17864 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17865 y (if org-time-clocksum-use-effort-durations
17866 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17867 ;; fractional format
17868 (if org-time-clocksum-use-fractional
17869 (cond
17870 ;; single format string
17871 ((stringp org-time-clocksum-fractional-format)
17872 (format org-time-clocksum-fractional-format (/ m (float h))))
17873 ;; choice of fractional formats for different time units
17874 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17875 (> (/ (truncate m) (* y d h)) 0))
17876 (format fmt (/ m (* y d (float h)))))
17877 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17878 (> (/ (truncate m) (* mo d h)) 0))
17879 (format fmt (/ m (* mo d (float h)))))
17880 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17881 (> (/ (truncate m) (* w d h)) 0))
17882 (format fmt (/ m (* w d (float h)))))
17883 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17884 (> (/ (truncate m) (* d h)) 0))
17885 (format fmt (/ m (* d (float h)))))
17886 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17887 (> (/ (truncate m) h) 0))
17888 (format fmt (/ m (float h))))
17889 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17890 (format fmt m))
17891 ;; fall back to smallest time unit with a format
17892 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17893 (format fmt (/ m (float h))))
17894 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17895 (format fmt (/ m (* d (float h)))))
17896 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17897 (format fmt (/ m (* w d (float h)))))
17898 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17899 (format fmt (/ m (* mo d (float h)))))
17900 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17901 (format fmt (/ m (* y d (float h))))))
17902 ;; standard (non-fractional) format, with single format string
17903 (if (stringp org-time-clocksum-format)
17904 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17905 ;; separate formats components
17906 (and (setq fmt (plist-get org-time-clocksum-format :years))
17907 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17908 (plist-get org-time-clocksum-format :require-years))
17909 (setq clocksum (concat clocksum (format fmt n))
17910 m (- m (* n y d h))))
17911 (and (setq fmt (plist-get org-time-clocksum-format :months))
17912 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17913 (plist-get org-time-clocksum-format :require-months))
17914 (setq clocksum (concat clocksum (format fmt n))
17915 m (- m (* n mo d h))))
17916 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17917 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17918 (plist-get org-time-clocksum-format :require-weeks))
17919 (setq clocksum (concat clocksum (format fmt n))
17920 m (- m (* n w d h))))
17921 (and (setq fmt (plist-get org-time-clocksum-format :days))
17922 (or (> (setq n (/ (truncate m) (* d h))) 0)
17923 (plist-get org-time-clocksum-format :require-days))
17924 (setq clocksum (concat clocksum (format fmt n))
17925 m (- m (* n d h))))
17926 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17927 (or (> (setq n (/ (truncate m) h)) 0)
17928 (plist-get org-time-clocksum-format :require-hours))
17929 (setq clocksum (concat clocksum (format fmt n))
17930 m (- m (* n h))))
17931 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17932 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17933 (setq clocksum (concat clocksum (format fmt m))))
17934 ;; return formatted time duration
17935 clocksum))))
17937 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17938 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17939 "Org mode version 8.0")
17941 (defun org-hours-to-clocksum-string (n)
17942 (org-minutes-to-clocksum-string (* n 60)))
17944 (defun org-hh:mm-string-to-minutes (s)
17945 "Convert a string H:MM to a number of minutes.
17946 If the string is just a number, interpret it as minutes.
17947 In fact, the first hh:mm or number in the string will be taken,
17948 there can be extra stuff in the string.
17949 If no number is found, the return value is 0."
17950 (cond
17951 ((integerp s) s)
17952 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17953 (+ (* (string-to-number (match-string 1 s)) 60)
17954 (string-to-number (match-string 2 s))))
17955 ((string-match "\\([0-9]+\\)" s)
17956 (string-to-number (match-string 1 s)))
17957 (t 0)))
17959 (defcustom org-image-actual-width t
17960 "Should we use the actual width of images when inlining them?
17962 When set to `t', always use the image width.
17964 When set to a number, use imagemagick (when available) to set
17965 the image's width to this value.
17967 When set to a number in a list, try to get the width from any
17968 #+ATTR.* keyword if it matches a width specification like
17970 #+ATTR_HTML: :width 300px
17972 and fall back on that number if none is found.
17974 When set to nil, try to get the width from an #+ATTR.* keyword
17975 and fall back on the original width if none is found.
17977 This requires Emacs >= 24.1, build with imagemagick support."
17978 :group 'org-appearance
17979 :version "24.4"
17980 :package-version '(Org . "8.0")
17981 :type '(choice
17982 (const :tag "Use the image width" t)
17983 (integer :tag "Use a number of pixels")
17984 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17985 (const :tag "Use #+ATTR* or don't resize" nil)))
17987 (defcustom org-agenda-inhibit-startup nil
17988 "Inhibit startup when preparing agenda buffers.
17989 When this variable is `t', the initialization of the Org agenda
17990 buffers is inhibited: e.g. the visibility state is not set, the
17991 tables are not re-aligned, etc."
17992 :type 'boolean
17993 :version "24.3"
17994 :group 'org-agenda)
17996 (define-obsolete-variable-alias
17997 'org-agenda-ignore-drawer-properties
17998 'org-agenda-ignore-properties "24.5")
18000 (defcustom org-agenda-ignore-properties nil
18001 "Avoid updating text properties when building the agenda.
18002 Properties are used to prepare buffers for effort estimates,
18003 appointments, statistics and subtree-local categories.
18004 If you don't use these in the agenda, you can add them to this
18005 list and agenda building will be a bit faster.
18006 The value is a list, with zero or more of the symbols `effort', `appt',
18007 `stats' or `category'."
18008 :type '(set :greedy t
18009 (const effort)
18010 (const appt)
18011 (const stats)
18012 (const category))
18013 :version "24.5"
18014 :package-version '(Org . "8.3")
18015 :group 'org-agenda)
18017 (defun org-duration-string-to-minutes (s &optional output-to-string)
18018 "Convert a duration string S to minutes.
18020 A bare number is interpreted as minutes, modifiers can be set by
18021 customizing `org-effort-durations' (which see).
18023 Entries containing a colon are interpreted as H:MM by
18024 `org-hh:mm-string-to-minutes'."
18025 (let ((result 0)
18026 (re (concat "\\([0-9.]+\\) *\\("
18027 (regexp-opt (mapcar 'car org-effort-durations))
18028 "\\)")))
18029 (while (string-match re s)
18030 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18031 (string-to-number (match-string 1 s))))
18032 (setq s (replace-match "" nil t s)))
18033 (setq result (floor result))
18034 (incf result (org-hh:mm-string-to-minutes s))
18035 (if output-to-string (number-to-string result) result)))
18037 ;;;; Files
18039 (defun org-save-all-org-buffers ()
18040 "Save all Org-mode buffers without user confirmation."
18041 (interactive)
18042 (message "Saving all Org-mode buffers...")
18043 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18044 (when (featurep 'org-id) (org-id-locations-save))
18045 (message "Saving all Org-mode buffers... done"))
18047 (defun org-revert-all-org-buffers ()
18048 "Revert all Org-mode buffers.
18049 Prompt for confirmation when there are unsaved changes.
18050 Be sure you know what you are doing before letting this function
18051 overwrite your changes.
18053 This function is useful in a setup where one tracks org files
18054 with a version control system, to revert on one machine after pulling
18055 changes from another. I believe the procedure must be like this:
18057 1. M-x org-save-all-org-buffers
18058 2. Pull changes from the other machine, resolve conflicts
18059 3. M-x org-revert-all-org-buffers"
18060 (interactive)
18061 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18062 (user-error "Abort"))
18063 (save-excursion
18064 (save-window-excursion
18065 (mapc
18066 (lambda (b)
18067 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18068 (with-current-buffer b buffer-file-name))
18069 (org-pop-to-buffer-same-window b)
18070 (revert-buffer t 'no-confirm)))
18071 (buffer-list))
18072 (when (and (featurep 'org-id) org-id-track-globally)
18073 (org-id-locations-load)))))
18075 ;;;; Agenda files
18077 ;;;###autoload
18078 (defun org-switchb (&optional arg)
18079 "Switch between Org buffers.
18080 With one prefix argument, restrict available buffers to files.
18081 With two prefix arguments, restrict available buffers to agenda files.
18083 Defaults to `iswitchb' for buffer name completion.
18084 Set `org-completion-use-ido' to make it use ido instead."
18085 (interactive "P")
18086 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18087 ((equal arg '(16)) (org-buffer-list 'agenda))
18088 (t (org-buffer-list))))
18089 (org-completion-use-iswitchb org-completion-use-iswitchb)
18090 (org-completion-use-ido org-completion-use-ido))
18091 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18092 (setq org-completion-use-iswitchb t))
18093 (org-pop-to-buffer-same-window
18094 (org-icompleting-read "Org buffer: "
18095 (mapcar 'list (mapcar 'buffer-name blist))
18096 nil t))))
18098 ;;; Define some older names previously used for this functionality
18099 ;;;###autoload
18100 (defalias 'org-ido-switchb 'org-switchb)
18101 ;;;###autoload
18102 (defalias 'org-iswitchb 'org-switchb)
18104 (defun org-buffer-list (&optional predicate exclude-tmp)
18105 "Return a list of Org buffers.
18106 PREDICATE can be `export', `files' or `agenda'.
18108 export restrict the list to Export buffers.
18109 files restrict the list to buffers visiting Org files.
18110 agenda restrict the list to buffers visiting agenda files.
18112 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18113 (let* ((bfn nil)
18114 (agenda-files (and (eq predicate 'agenda)
18115 (mapcar 'file-truename (org-agenda-files t))))
18116 (filter
18117 (cond
18118 ((eq predicate 'files)
18119 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18120 ((eq predicate 'export)
18121 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18122 ((eq predicate 'agenda)
18123 (lambda (b)
18124 (with-current-buffer b
18125 (and (derived-mode-p 'org-mode)
18126 (setq bfn (buffer-file-name b))
18127 (member (file-truename bfn) agenda-files)))))
18128 (t (lambda (b) (with-current-buffer b
18129 (or (derived-mode-p 'org-mode)
18130 (string-match "\*Org .*Export"
18131 (buffer-name b)))))))))
18132 (delq nil
18133 (mapcar
18134 (lambda(b)
18135 (if (and (funcall filter b)
18136 (or (not exclude-tmp)
18137 (not (string-match "tmp" (buffer-name b)))))
18139 nil))
18140 (buffer-list)))))
18142 (defun org-agenda-files (&optional unrestricted archives)
18143 "Get the list of agenda files.
18144 Optional UNRESTRICTED means return the full list even if a restriction
18145 is currently in place.
18146 When ARCHIVES is t, include all archive files that are really being
18147 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18148 `org-agenda-archives-mode' is t."
18149 (let ((files
18150 (cond
18151 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18152 ((stringp org-agenda-files) (org-read-agenda-file-list))
18153 ((listp org-agenda-files) org-agenda-files)
18154 (t (error "Invalid value of `org-agenda-files'")))))
18155 (setq files (apply 'append
18156 (mapcar (lambda (f)
18157 (if (file-directory-p f)
18158 (directory-files
18159 f t org-agenda-file-regexp)
18160 (list f)))
18161 files)))
18162 (when org-agenda-skip-unavailable-files
18163 (setq files (delq nil
18164 (mapcar (function
18165 (lambda (file)
18166 (and (file-readable-p file) file)))
18167 files))))
18168 (when (or (eq archives t)
18169 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18170 (setq files (org-add-archive-files files)))
18171 files))
18173 (defun org-agenda-file-p (&optional file)
18174 "Return non-nil, if FILE is an agenda file.
18175 If FILE is omitted, use the file associated with the current
18176 buffer."
18177 (member (or file (buffer-file-name))
18178 (org-agenda-files t)))
18180 (defun org-edit-agenda-file-list ()
18181 "Edit the list of agenda files.
18182 Depending on setup, this either uses customize to edit the variable
18183 `org-agenda-files', or it visits the file that is holding the list. In the
18184 latter case, the buffer is set up in a way that saving it automatically kills
18185 the buffer and restores the previous window configuration."
18186 (interactive)
18187 (if (stringp org-agenda-files)
18188 (let ((cw (current-window-configuration)))
18189 (find-file org-agenda-files)
18190 (org-set-local 'org-window-configuration cw)
18191 (org-add-hook 'after-save-hook
18192 (lambda ()
18193 (set-window-configuration
18194 (prog1 org-window-configuration
18195 (kill-buffer (current-buffer))))
18196 (org-install-agenda-files-menu)
18197 (message "New agenda file list installed"))
18198 nil 'local)
18199 (message "%s" (substitute-command-keys
18200 "Edit list and finish with \\[save-buffer]")))
18201 (customize-variable 'org-agenda-files)))
18203 (defun org-store-new-agenda-file-list (list)
18204 "Set new value for the agenda file list and save it correctly."
18205 (if (stringp org-agenda-files)
18206 (let ((fe (org-read-agenda-file-list t)) b u)
18207 (while (setq b (find-buffer-visiting org-agenda-files))
18208 (kill-buffer b))
18209 (with-temp-file org-agenda-files
18210 (insert
18211 (mapconcat
18212 (lambda (f) ;; Keep un-expanded entries.
18213 (if (setq u (assoc f fe))
18214 (cdr u)
18216 list "\n")
18217 "\n")))
18218 (let ((org-mode-hook nil) (org-inhibit-startup t)
18219 (org-insert-mode-line-in-empty-file nil))
18220 (setq org-agenda-files list)
18221 (customize-save-variable 'org-agenda-files org-agenda-files))))
18223 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18224 "Read the list of agenda files from a file.
18225 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18226 filenames, used by `org-store-new-agenda-file-list' to write back
18227 un-expanded file names."
18228 (when (file-directory-p org-agenda-files)
18229 (error "`org-agenda-files' cannot be a single directory"))
18230 (when (stringp org-agenda-files)
18231 (with-temp-buffer
18232 (insert-file-contents org-agenda-files)
18233 (mapcar
18234 (lambda (f)
18235 (let ((e (expand-file-name (substitute-in-file-name f)
18236 org-directory)))
18237 (if pair-with-expansion
18238 (cons e f)
18239 e)))
18240 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18242 ;;;###autoload
18243 (defun org-cycle-agenda-files ()
18244 "Cycle through the files in `org-agenda-files'.
18245 If the current buffer visits an agenda file, find the next one in the list.
18246 If the current buffer does not, find the first agenda file."
18247 (interactive)
18248 (let* ((fs (org-agenda-files t))
18249 (files (append fs (list (car fs))))
18250 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18251 file)
18252 (unless files (user-error "No agenda files"))
18253 (catch 'exit
18254 (while (setq file (pop files))
18255 (if (equal (file-truename file) tcf)
18256 (when (car files)
18257 (find-file (car files))
18258 (throw 'exit t))))
18259 (find-file (car fs)))
18260 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18262 (defun org-agenda-file-to-front (&optional to-end)
18263 "Move/add the current file to the top of the agenda file list.
18264 If the file is not present in the list, it is added to the front. If it is
18265 present, it is moved there. With optional argument TO-END, add/move to the
18266 end of the list."
18267 (interactive "P")
18268 (let ((org-agenda-skip-unavailable-files nil)
18269 (file-alist (mapcar (lambda (x)
18270 (cons (file-truename x) x))
18271 (org-agenda-files t)))
18272 (ctf (file-truename
18273 (or buffer-file-name
18274 (user-error "Please save the current buffer to a file"))))
18275 x had)
18276 (setq x (assoc ctf file-alist) had x)
18278 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18279 (if to-end
18280 (setq file-alist (append (delq x file-alist) (list x)))
18281 (setq file-alist (cons x (delq x file-alist))))
18282 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18283 (org-install-agenda-files-menu)
18284 (message "File %s to %s of agenda file list"
18285 (if had "moved" "added") (if to-end "end" "front"))))
18287 (defun org-remove-file (&optional file)
18288 "Remove current file from the list of files in variable `org-agenda-files'.
18289 These are the files which are being checked for agenda entries.
18290 Optional argument FILE means use this file instead of the current."
18291 (interactive)
18292 (let* ((org-agenda-skip-unavailable-files nil)
18293 (file (or file buffer-file-name
18294 (user-error "Current buffer does not visit a file")))
18295 (true-file (file-truename file))
18296 (afile (abbreviate-file-name file))
18297 (files (delq nil (mapcar
18298 (lambda (x)
18299 (if (equal true-file
18300 (file-truename x))
18301 nil x))
18302 (org-agenda-files t)))))
18303 (if (not (= (length files) (length (org-agenda-files t))))
18304 (progn
18305 (org-store-new-agenda-file-list files)
18306 (org-install-agenda-files-menu)
18307 (message "Removed file: %s" afile))
18308 (message "File was not in list: %s (not removed)" afile))))
18310 (defun org-file-menu-entry (file)
18311 (vector file (list 'find-file file) t))
18313 (defun org-check-agenda-file (file)
18314 "Make sure FILE exists. If not, ask user what to do."
18315 (when (not (file-exists-p file))
18316 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18317 (abbreviate-file-name file))
18318 (let ((r (downcase (read-char-exclusive))))
18319 (cond
18320 ((equal r ?r)
18321 (org-remove-file file)
18322 (throw 'nextfile t))
18323 (t (user-error "Abort"))))))
18325 (defun org-get-agenda-file-buffer (file)
18326 "Get an agenda buffer visiting FILE.
18327 If the buffer needs to be created, add it to the list of buffers
18328 which might be released later."
18329 (let ((buf (org-find-base-buffer-visiting file)))
18330 (if buf
18331 buf ; just return it
18332 ;; Make a new buffer and remember it
18333 (setq buf (find-file-noselect file))
18334 (if buf (push buf org-agenda-new-buffers))
18335 buf)))
18337 (defun org-release-buffers (blist)
18338 "Release all buffers in list, asking the user for confirmation when needed.
18339 When a buffer is unmodified, it is just killed. When modified, it is saved
18340 \(if the user agrees) and then killed."
18341 (let (buf file)
18342 (while (setq buf (pop blist))
18343 (setq file (buffer-file-name buf))
18344 (when (and (buffer-modified-p buf)
18345 file
18346 (y-or-n-p (format "Save file %s? " file)))
18347 (with-current-buffer buf (save-buffer)))
18348 (kill-buffer buf))))
18350 (defun org-agenda-prepare-buffers (files)
18351 "Create buffers for all agenda files, protect archived trees and comments."
18352 (interactive)
18353 (let ((pa '(:org-archived t))
18354 (pc '(:org-comment t))
18355 (pall '(:org-archived t :org-comment t))
18356 (inhibit-read-only t)
18357 (org-inhibit-startup org-agenda-inhibit-startup)
18358 (rea (concat ":" org-archive-tag ":"))
18359 file re pos)
18360 (setq org-tag-alist-for-agenda nil
18361 org-tag-groups-alist-for-agenda nil)
18362 (save-excursion
18363 (save-restriction
18364 (while (setq file (pop files))
18365 (catch 'nextfile
18366 (if (bufferp file)
18367 (set-buffer file)
18368 (org-check-agenda-file file)
18369 (set-buffer (org-get-agenda-file-buffer file)))
18370 (widen)
18371 (org-set-regexps-and-options-for-tags)
18372 (setq pos (point))
18373 (goto-char (point-min))
18374 (let ((case-fold-search t))
18375 (when (search-forward "#+setupfile" nil t)
18376 ;; Don't set all regexps and options systematically as
18377 ;; this is only run for setting agenda tags from setup
18378 ;; file
18379 (org-set-regexps-and-options)))
18380 (or (memq 'category org-agenda-ignore-properties)
18381 (org-refresh-category-properties))
18382 (or (memq 'stats org-agenda-ignore-properties)
18383 (org-refresh-stats-properties))
18384 (or (memq 'effort org-agenda-ignore-properties)
18385 (org-refresh-effort-properties))
18386 (or (memq 'appt org-agenda-ignore-properties)
18387 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18388 (setq org-todo-keywords-for-agenda
18389 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18390 (setq org-done-keywords-for-agenda
18391 (append org-done-keywords-for-agenda org-done-keywords))
18392 (setq org-todo-keyword-alist-for-agenda
18393 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18394 (setq org-tag-alist-for-agenda
18395 (org-uniquify
18396 (append org-tag-alist-for-agenda
18397 org-tag-alist
18398 org-tag-persistent-alist)))
18399 (if org-group-tags
18400 (setq org-tag-groups-alist-for-agenda
18401 (org-uniquify-alist
18402 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18403 (org-with-silent-modifications
18404 (save-excursion
18405 (remove-text-properties (point-min) (point-max) pall)
18406 (when org-agenda-skip-archived-trees
18407 (goto-char (point-min))
18408 (while (re-search-forward rea nil t)
18409 (if (org-at-heading-p t)
18410 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18411 (goto-char (point-min))
18412 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18413 (while (re-search-forward re nil t)
18414 (when (save-match-data (org-in-commented-heading-p t))
18415 (add-text-properties
18416 (match-beginning 0) (org-end-of-subtree t) pc)))))
18417 (goto-char pos)))))
18418 (setq org-todo-keywords-for-agenda
18419 (org-uniquify org-todo-keywords-for-agenda))
18420 (setq org-todo-keyword-alist-for-agenda
18421 (org-uniquify org-todo-keyword-alist-for-agenda))))
18424 ;;;; CDLaTeX minor mode
18426 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18427 "Keymap for the minor `org-cdlatex-mode'.")
18429 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18430 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18431 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18432 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18433 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18435 (defvar org-cdlatex-texmathp-advice-is-done nil
18436 "Flag remembering if we have applied the advice to texmathp already.")
18438 (define-minor-mode org-cdlatex-mode
18439 "Toggle the minor `org-cdlatex-mode'.
18440 This mode supports entering LaTeX environment and math in LaTeX fragments
18441 in Org-mode.
18442 \\{org-cdlatex-mode-map}"
18443 nil " OCDL" nil
18444 (when org-cdlatex-mode
18445 (require 'cdlatex)
18446 (run-hooks 'cdlatex-mode-hook)
18447 (cdlatex-compute-tables))
18448 (unless org-cdlatex-texmathp-advice-is-done
18449 (setq org-cdlatex-texmathp-advice-is-done t)
18450 (defadvice texmathp (around org-math-always-on activate)
18451 "Always return t in org-mode buffers.
18452 This is because we want to insert math symbols without dollars even outside
18453 the LaTeX math segments. If Orgmode thinks that point is actually inside
18454 an embedded LaTeX fragment, let texmathp do its job.
18455 \\[org-cdlatex-mode-map]"
18456 (interactive)
18457 (let (p)
18458 (cond
18459 ((not (derived-mode-p 'org-mode)) ad-do-it)
18460 ((eq this-command 'cdlatex-math-symbol)
18461 (setq ad-return-value t
18462 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18464 (let ((p (org-inside-LaTeX-fragment-p)))
18465 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18466 (setq ad-return-value t
18467 texmathp-why '("Org-mode embedded math" . 0))
18468 (if p ad-do-it)))))))))
18470 (defun turn-on-org-cdlatex ()
18471 "Unconditionally turn on `org-cdlatex-mode'."
18472 (org-cdlatex-mode 1))
18474 (defun org-try-cdlatex-tab ()
18475 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18476 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18477 - inside a LaTeX fragment, or
18478 - after the first word in a line, where an abbreviation expansion could
18479 insert a LaTeX environment."
18480 (when org-cdlatex-mode
18481 (cond
18482 ;; Before any word on the line: No expansion possible.
18483 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18484 ;; Just after first word on the line: Expand it. Make sure it
18485 ;; cannot happen on headlines, though.
18486 ((save-excursion
18487 (skip-chars-backward "a-zA-Z0-9*")
18488 (skip-chars-backward " \t")
18489 (and (bolp) (not (org-at-heading-p))))
18490 (cdlatex-tab) t)
18491 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18493 (defun org-cdlatex-underscore-caret (&optional arg)
18494 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18495 Revert to the normal definition outside of these fragments."
18496 (interactive "P")
18497 (if (org-inside-LaTeX-fragment-p)
18498 (call-interactively 'cdlatex-sub-superscript)
18499 (let (org-cdlatex-mode)
18500 (call-interactively (key-binding (vector last-input-event))))))
18502 (defun org-cdlatex-math-modify (&optional arg)
18503 "Execute `cdlatex-math-modify' in LaTeX fragments.
18504 Revert to the normal definition outside of these fragments."
18505 (interactive "P")
18506 (if (org-inside-LaTeX-fragment-p)
18507 (call-interactively 'cdlatex-math-modify)
18508 (let (org-cdlatex-mode)
18509 (call-interactively (key-binding (vector last-input-event))))))
18511 (defun org-cdlatex-environment-indent (&optional environment item)
18512 "Execute `cdlatex-environment' and indent the inserted environment."
18513 (interactive)
18514 (cdlatex-environment environment item)
18515 (let ((element (org-element-at-point)))
18516 (org-indent-region (org-element-property :begin element)
18517 (org-element-property :end element))))
18520 ;;;; LaTeX fragments
18522 (defun org-inside-LaTeX-fragment-p ()
18523 "Test if point is inside a LaTeX fragment.
18524 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18525 sequence appearing also before point.
18526 Even though the matchers for math are configurable, this function assumes
18527 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18528 delimiters are skipped when they have been removed by customization.
18529 The return value is nil, or a cons cell with the delimiter and the
18530 position of this delimiter.
18532 This function does a reasonably good job, but can locally be fooled by
18533 for example currency specifications. For example it will assume being in
18534 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18535 fragments that are properly closed, but during editing, we have to live
18536 with the uncertainty caused by missing closing delimiters. This function
18537 looks only before point, not after."
18538 (catch 'exit
18539 (let ((pos (point))
18540 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18541 (lim (progn
18542 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18543 (point)))
18544 dd-on str (start 0) m re)
18545 (goto-char pos)
18546 (when dodollar
18547 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18548 re (nth 1 (assoc "$" org-latex-regexps)))
18549 (while (string-match re str start)
18550 (cond
18551 ((= (match-end 0) (length str))
18552 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18553 ((= (match-end 0) (- (length str) 5))
18554 (throw 'exit nil))
18555 (t (setq start (match-end 0))))))
18556 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18557 (goto-char pos)
18558 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18559 (and (match-beginning 2) (throw 'exit nil))
18560 ;; count $$
18561 (while (re-search-backward "\\$\\$" lim t)
18562 (setq dd-on (not dd-on)))
18563 (goto-char pos)
18564 (if dd-on (cons "$$" m))))))
18566 (defun org-inside-latex-macro-p ()
18567 "Is point inside a LaTeX macro or its arguments?"
18568 (save-match-data
18569 (org-in-regexp
18570 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18572 (defvar org-latex-fragment-image-overlays nil
18573 "List of overlays carrying the images of latex fragments.")
18574 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18576 (defun org-remove-latex-fragment-image-overlays ()
18577 "Remove all overlays with LaTeX fragment images in current buffer."
18578 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18579 (setq org-latex-fragment-image-overlays nil))
18581 (define-obsolete-function-alias
18582 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18583 (defun org-toggle-latex-fragment (&optional subtree)
18584 "Preview the LaTeX fragment at point, or all locally or globally.
18585 If the cursor is in a LaTeX fragment, create the image and overlay
18586 it over the source code. If there is no fragment at point, display
18587 all fragments in the current text, from one headline to the next. With
18588 prefix SUBTREE, display all fragments in the current subtree. With a
18589 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18590 the cursor is before the first headline,
18591 display all fragments in the buffer.
18592 The images can be removed again with \\[org-toggle-latex-fragment]."
18593 (interactive "P")
18594 (unless buffer-file-name
18595 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18596 (if org-latex-fragment-image-overlays
18597 (progn (org-remove-latex-fragment-image-overlays)
18598 (message "LaTeX fragments images removed"))
18599 (when (display-graphic-p)
18600 (org-remove-latex-fragment-image-overlays)
18601 (save-excursion
18602 (save-restriction
18603 (let (beg end at msg)
18604 (cond
18605 ((or (equal subtree '(16))
18606 (not (save-excursion
18607 (re-search-backward org-outline-regexp-bol nil t))))
18608 (setq beg (point-min) end (point-max)
18609 msg "Creating images for buffer...%s"))
18610 ((equal subtree '(4))
18611 (org-back-to-heading)
18612 (setq beg (point) end (org-end-of-subtree t)
18613 msg "Creating images for subtree...%s"))
18615 (if (setq at (org-inside-LaTeX-fragment-p))
18616 (goto-char (max (point-min) (- (cdr at) 2)))
18617 (org-back-to-heading))
18618 (setq beg (point) end (progn (outline-next-heading) (point))
18619 msg (if at "Creating image...%s"
18620 "Creating images for entry...%s"))))
18621 (message msg "")
18622 (narrow-to-region beg end)
18623 (goto-char beg)
18624 (org-format-latex
18625 (concat org-latex-preview-ltxpng-directory
18626 (file-name-sans-extension
18627 (file-name-nondirectory buffer-file-name)))
18628 default-directory 'overlays msg at 'forbuffer
18629 org-latex-create-formula-image-program)
18630 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18632 (defun org-format-latex (prefix &optional dir overlays msg at
18633 forbuffer processing-type)
18634 "Replace LaTeX fragments with links to an image, and produce images.
18635 Some of the options can be changed using the variable
18636 `org-format-latex-options'."
18637 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18638 (let* ((prefixnodir (file-name-nondirectory prefix))
18639 (absprefix (expand-file-name prefix dir))
18640 (todir (file-name-directory absprefix))
18641 (opt org-format-latex-options)
18642 (optnew org-format-latex-options)
18643 (matchers (plist-get opt :matchers))
18644 (re-list org-latex-regexps)
18645 (cnt 0) txt hash link beg end re e checkdir
18646 string
18647 m n block-type block linkfile movefile ov)
18648 ;; Check the different regular expressions
18649 (while (setq e (pop re-list))
18650 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18651 block (if block-type "\n\n" ""))
18652 (when (member m matchers)
18653 (goto-char (point-min))
18654 (while (re-search-forward re nil t)
18655 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18656 (or (not overlays)
18657 (not (eq (get-char-property (match-beginning n)
18658 'org-overlay-type)
18659 'org-latex-overlay))))
18660 (cond
18661 ((eq processing-type 'verbatim))
18662 ((eq processing-type 'mathjax)
18663 ;; Prepare for MathJax processing.
18664 (setq string (match-string n))
18665 (when (member m '("$" "$1"))
18666 (save-excursion
18667 (delete-region (match-beginning n) (match-end n))
18668 (goto-char (match-beginning n))
18669 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18670 ((or (eq processing-type 'dvipng)
18671 (eq processing-type 'imagemagick))
18672 ;; Process to an image.
18673 (setq txt (match-string n)
18674 beg (match-beginning n) end (match-end n)
18675 cnt (1+ cnt))
18676 (let ((face (face-at-point))
18677 (fg (plist-get opt :foreground))
18678 (bg (plist-get opt :background))
18679 ;; Ensure full list is printed.
18680 print-length print-level)
18681 (when forbuffer
18682 ;; Get the colors from the face at point.
18683 (goto-char beg)
18684 (when (eq fg 'auto)
18685 (setq fg (face-attribute face :foreground nil 'default)))
18686 (when (eq bg 'auto)
18687 (setq bg (face-attribute face :background nil 'default)))
18688 (setq optnew (copy-sequence opt))
18689 (plist-put optnew :foreground fg)
18690 (plist-put optnew :background bg))
18691 (setq hash (sha1 (prin1-to-string
18692 (list org-format-latex-header
18693 org-latex-default-packages-alist
18694 org-latex-packages-alist
18695 org-format-latex-options
18696 forbuffer txt fg bg)))
18697 linkfile (format "%s_%s.png" prefix hash)
18698 movefile (format "%s_%s.png" absprefix hash)))
18699 (setq link (concat block "[[file:" linkfile "]]" block))
18700 (if msg (message msg cnt))
18701 (goto-char beg)
18702 (unless checkdir ; Ensure the directory exists.
18703 (setq checkdir t)
18704 (or (file-directory-p todir) (make-directory todir t)))
18705 (unless (file-exists-p movefile)
18706 (org-create-formula-image
18707 txt movefile optnew forbuffer processing-type))
18708 (if overlays
18709 (progn
18710 (mapc (lambda (o)
18711 (if (eq (overlay-get o 'org-overlay-type)
18712 'org-latex-overlay)
18713 (delete-overlay o)))
18714 (overlays-in beg end))
18715 (setq ov (make-overlay beg end))
18716 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18717 (if (featurep 'xemacs)
18718 (progn
18719 (overlay-put ov 'invisible t)
18720 (overlay-put
18721 ov 'end-glyph
18722 (make-glyph (vector 'png :file movefile))))
18723 (overlay-put
18724 ov 'display
18725 (list 'image :type 'png :file movefile :ascent 'center)))
18726 (push ov org-latex-fragment-image-overlays)
18727 (goto-char end))
18728 (delete-region beg end)
18729 (insert (org-add-props link
18730 (list 'org-latex-src
18731 (replace-regexp-in-string
18732 "\"" "" txt)
18733 'org-latex-src-embed-type
18734 (if block-type 'paragraph 'character))))))
18735 ((eq processing-type 'mathml)
18736 ;; Process to MathML
18737 (unless (save-match-data (org-format-latex-mathml-available-p))
18738 (user-error "LaTeX to MathML converter not configured"))
18739 (setq txt (match-string n)
18740 beg (match-beginning n) end (match-end n)
18741 cnt (1+ cnt))
18742 (if msg (message msg cnt))
18743 (goto-char beg)
18744 (delete-region beg end)
18745 (insert (org-format-latex-as-mathml
18746 txt block-type prefix dir)))
18748 (error "Unknown conversion type %s for LaTeX fragments"
18749 processing-type)))))))))
18751 (defun org-create-math-formula (latex-frag &optional mathml-file)
18752 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18753 Use `org-latex-to-mathml-convert-command'. If the conversion is
18754 sucessful, return the portion between \"<math...> </math>\"
18755 elements otherwise return nil. When MATHML-FILE is specified,
18756 write the results in to that file. When invoked as an
18757 interactive command, prompt for LATEX-FRAG, with initial value
18758 set to the current active region and echo the results for user
18759 inspection."
18760 (interactive (list (let ((frag (when (org-region-active-p)
18761 (buffer-substring-no-properties
18762 (region-beginning) (region-end)))))
18763 (read-string "LaTeX Fragment: " frag nil frag))))
18764 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18765 (let* ((tmp-in-file (file-relative-name
18766 (make-temp-name (expand-file-name "ltxmathml-in"))))
18767 (ignore (write-region latex-frag nil tmp-in-file))
18768 (tmp-out-file (file-relative-name
18769 (make-temp-name (expand-file-name "ltxmathml-out"))))
18770 (cmd (format-spec
18771 org-latex-to-mathml-convert-command
18772 `((?j . ,(shell-quote-argument
18773 (expand-file-name org-latex-to-mathml-jar-file)))
18774 (?I . ,(shell-quote-argument tmp-in-file))
18775 (?o . ,(shell-quote-argument tmp-out-file)))))
18776 mathml shell-command-output)
18777 (when (org-called-interactively-p 'any)
18778 (unless (org-format-latex-mathml-available-p)
18779 (user-error "LaTeX to MathML converter not configured")))
18780 (message "Running %s" cmd)
18781 (setq shell-command-output (shell-command-to-string cmd))
18782 (setq mathml
18783 (when (file-readable-p tmp-out-file)
18784 (with-current-buffer (find-file-noselect tmp-out-file t)
18785 (goto-char (point-min))
18786 (when (re-search-forward
18787 (concat
18788 (regexp-quote
18789 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18790 "\\(.\\|\n\\)*"
18791 (regexp-quote "</math>")) nil t)
18792 (prog1 (match-string 0) (kill-buffer))))))
18793 (cond
18794 (mathml
18795 (setq mathml
18796 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18797 (when mathml-file
18798 (write-region mathml nil mathml-file))
18799 (when (org-called-interactively-p 'any)
18800 (message mathml)))
18801 ((message "LaTeX to MathML conversion failed")
18802 (message shell-command-output)))
18803 (delete-file tmp-in-file)
18804 (when (file-exists-p tmp-out-file)
18805 (delete-file tmp-out-file))
18806 mathml))
18808 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18809 prefix &optional dir)
18810 "Use `org-create-math-formula' but check local cache first."
18811 (let* ((absprefix (expand-file-name prefix dir))
18812 (print-length nil) (print-level nil)
18813 (formula-id (concat
18814 "formula-"
18815 (sha1
18816 (prin1-to-string
18817 (list latex-frag
18818 org-latex-to-mathml-convert-command)))))
18819 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18820 (formula-cache-dir (file-name-directory formula-cache)))
18822 (unless (file-directory-p formula-cache-dir)
18823 (make-directory formula-cache-dir t))
18825 (unless (file-exists-p formula-cache)
18826 (org-create-math-formula latex-frag formula-cache))
18828 (if (file-exists-p formula-cache)
18829 ;; Successful conversion. Return the link to MathML file.
18830 (org-add-props
18831 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18832 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18833 'org-latex-src-embed-type (if latex-frag-type
18834 'paragraph 'character)))
18835 ;; Failed conversion. Return the LaTeX fragment verbatim
18836 latex-frag)))
18838 (defun org-create-formula-image (string tofile options buffer &optional type)
18839 "Create an image from LaTeX source using dvipng or convert.
18840 This function calls either `org-create-formula-image-with-dvipng'
18841 or `org-create-formula-image-with-imagemagick' depending on the
18842 value of `org-latex-create-formula-image-program' or on the value
18843 of the optional TYPE variable.
18845 Note: ultimately these two function should be combined as they
18846 share a good deal of logic."
18847 (org-check-external-command
18848 "latex" "needed to convert LaTeX fragments to images")
18849 (funcall
18850 (case (or type org-latex-create-formula-image-program)
18851 ('dvipng
18852 (org-check-external-command
18853 "dvipng" "needed to convert LaTeX fragments to images")
18854 'org-create-formula-image-with-dvipng)
18855 ('imagemagick
18856 (org-check-external-command
18857 "convert" "you need to install imagemagick")
18858 'org-create-formula-image-with-imagemagick)
18859 (t (error
18860 "Invalid value of `org-latex-create-formula-image-program'")))
18861 string tofile options buffer))
18863 (declare-function org-export-get-backend "ox" (name))
18864 (declare-function org-export--get-global-options "ox" (&optional backend))
18865 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18866 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18867 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18868 (defun org-create-formula--latex-header ()
18869 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18870 (let ((info (org-combine-plists (org-export--get-global-options
18871 (org-export-get-backend 'latex))
18872 (org-export--get-inbuffer-options
18873 (org-export-get-backend 'latex)))))
18874 (org-latex-guess-babel-language
18875 (org-latex-guess-inputenc
18876 (org-splice-latex-header
18877 org-format-latex-header
18878 org-latex-default-packages-alist
18879 org-latex-packages-alist t
18880 (plist-get info :latex-header)))
18881 info)))
18883 ;; This function borrows from Ganesh Swami's latex2png.el
18884 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18885 "This calls dvipng."
18886 (require 'ox-latex)
18887 (let* ((tmpdir (if (featurep 'xemacs)
18888 (temp-directory)
18889 temporary-file-directory))
18890 (texfilebase (make-temp-name
18891 (expand-file-name "orgtex" tmpdir)))
18892 (texfile (concat texfilebase ".tex"))
18893 (dvifile (concat texfilebase ".dvi"))
18894 (pngfile (concat texfilebase ".png"))
18895 (fnh (if (featurep 'xemacs)
18896 (font-height (face-font 'default))
18897 (face-attribute 'default :height nil)))
18898 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18899 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18900 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18901 "Black"))
18902 (bg (or (plist-get options (if buffer :background :html-background))
18903 "Transparent")))
18904 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18905 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18906 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18907 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18908 (let ((latex-header (org-create-formula--latex-header)))
18909 (with-temp-file texfile
18910 (insert latex-header)
18911 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18912 (let ((dir default-directory))
18913 (ignore-errors
18914 (cd tmpdir)
18915 (call-process "latex" nil nil nil texfile))
18916 (cd dir))
18917 (if (not (file-exists-p dvifile))
18918 (progn (message "Failed to create dvi file from %s" texfile) nil)
18919 (ignore-errors
18920 (if (featurep 'xemacs)
18921 (call-process "dvipng" nil nil nil
18922 "-fg" fg "-bg" bg
18923 "-T" "tight"
18924 "-o" pngfile
18925 dvifile)
18926 (call-process "dvipng" nil nil nil
18927 "-fg" fg "-bg" bg
18928 "-D" dpi
18929 ;;"-x" scale "-y" scale
18930 "-T" "tight"
18931 "-o" pngfile
18932 dvifile)))
18933 (if (not (file-exists-p pngfile))
18934 (if org-format-latex-signal-error
18935 (error "Failed to create png file from %s" texfile)
18936 (message "Failed to create png file from %s" texfile)
18937 nil)
18938 ;; Use the requested file name and clean up
18939 (copy-file pngfile tofile 'replace)
18940 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18941 (if (file-exists-p (concat texfilebase e))
18942 (delete-file (concat texfilebase e))))
18943 pngfile))))
18945 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18946 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18947 "This calls convert, which is included into imagemagick."
18948 (require 'ox-latex)
18949 (let* ((tmpdir (if (featurep 'xemacs)
18950 (temp-directory)
18951 temporary-file-directory))
18952 (texfilebase (make-temp-name
18953 (expand-file-name "orgtex" tmpdir)))
18954 (texfile (concat texfilebase ".tex"))
18955 (pdffile (concat texfilebase ".pdf"))
18956 (pngfile (concat texfilebase ".png"))
18957 (fnh (if (featurep 'xemacs)
18958 (font-height (face-font 'default))
18959 (face-attribute 'default :height nil)))
18960 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18961 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18962 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18963 "black"))
18964 (bg (or (plist-get options (if buffer :background :html-background))
18965 "white")))
18966 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18967 (setq fg (org-latex-color-format fg)))
18968 (if (eq bg 'default) (setq bg (org-latex-color :background))
18969 (setq bg (org-latex-color-format
18970 (if (string= bg "Transparent") "white" bg))))
18971 (let ((latex-header (org-create-formula--latex-header)))
18972 (with-temp-file texfile
18973 (insert latex-header)
18974 (insert "\n\\begin{document}\n"
18975 "\\definecolor{fg}{rgb}{" fg "}\n"
18976 "\\definecolor{bg}{rgb}{" bg "}\n"
18977 "\n\\pagecolor{bg}\n"
18978 "\n{\\color{fg}\n"
18979 string
18980 "\n}\n"
18981 "\n\\end{document}\n")))
18982 (org-latex-compile texfile t)
18983 (if (not (file-exists-p pdffile))
18984 (progn (message "Failed to create pdf file from %s" texfile) nil)
18985 (ignore-errors
18986 (if (featurep 'xemacs)
18987 (call-process "convert" nil nil nil
18988 "-density" "96"
18989 "-trim"
18990 "-antialias"
18991 pdffile
18992 "-quality" "100"
18993 ;; "-sharpen" "0x1.0"
18994 pngfile)
18995 (call-process "convert" nil nil nil
18996 "-density" dpi
18997 "-trim"
18998 "-antialias"
18999 pdffile
19000 "-quality" "100"
19001 ;; "-sharpen" "0x1.0"
19002 pngfile)))
19003 (if (not (file-exists-p pngfile))
19004 (if org-format-latex-signal-error
19005 (error "Failed to create png file from %s" texfile)
19006 (message "Failed to create png file from %s" texfile)
19007 nil)
19008 ;; Use the requested file name and clean up
19009 (copy-file pngfile tofile 'replace)
19010 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19011 (if (file-exists-p (concat texfilebase e))
19012 (delete-file (concat texfilebase e))))
19013 pngfile))))
19015 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19016 "Fill a LaTeX header template TPL.
19017 In the template, the following place holders will be recognized:
19019 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19020 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19021 [PACKAGES] \\usepackage statements for PKG
19022 [NO-PACKAGES] do not include PKG
19023 [EXTRA] the string EXTRA
19024 [NO-EXTRA] do not include EXTRA
19026 For backward compatibility, if both the positive and the negative place
19027 holder is missing, the positive one (without the \"NO-\") will be
19028 assumed to be present at the end of the template.
19029 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19030 EXTRA is a string.
19031 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19032 (let (rpl (end ""))
19033 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19034 (setq rpl (if (or (match-end 1) (not def-pkg))
19035 "" (org-latex-packages-to-string def-pkg snippets-p t))
19036 tpl (replace-match rpl t t tpl))
19037 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19039 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19040 (setq rpl (if (or (match-end 1) (not pkg))
19041 "" (org-latex-packages-to-string pkg snippets-p t))
19042 tpl (replace-match rpl t t tpl))
19043 (if pkg (setq end
19044 (concat end "\n"
19045 (org-latex-packages-to-string pkg snippets-p)))))
19047 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19048 (setq rpl (if (or (match-end 1) (not extra))
19049 "" (concat extra "\n"))
19050 tpl (replace-match rpl t t tpl))
19051 (if (and extra (string-match "\\S-" extra))
19052 (setq end (concat end "\n" extra))))
19054 (if (string-match "\\S-" end)
19055 (concat tpl "\n" end)
19056 tpl)))
19058 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19059 "Turn an alist of packages into a string with the \\usepackage macros."
19060 (setq pkg (mapconcat (lambda(p)
19061 (cond
19062 ((stringp p) p)
19063 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19064 (format "%% Package %s omitted" (cadr p)))
19065 ((equal "" (car p))
19066 (format "\\usepackage{%s}" (cadr p)))
19068 (format "\\usepackage[%s]{%s}"
19069 (car p) (cadr p)))))
19071 "\n"))
19072 (if newline (concat pkg "\n") pkg))
19074 (defun org-dvipng-color (attr)
19075 "Return a RGB color specification for dvipng."
19076 (apply 'format "rgb %s %s %s"
19077 (mapcar 'org-normalize-color
19078 (if (featurep 'xemacs)
19079 (color-rgb-components
19080 (face-property 'default
19081 (cond ((eq attr :foreground) 'foreground)
19082 ((eq attr :background) 'background))))
19083 (color-values (face-attribute 'default attr nil))))))
19085 (defun org-dvipng-color-format (color-name)
19086 "Convert COLOR-NAME to a RGB color value for dvipng."
19087 (apply 'format "rgb %s %s %s"
19088 (mapcar 'org-normalize-color
19089 (color-values color-name))))
19091 (defun org-latex-color (attr)
19092 "Return a RGB color for the LaTeX color package."
19093 (apply 'format "%s,%s,%s"
19094 (mapcar 'org-normalize-color
19095 (if (featurep 'xemacs)
19096 (color-rgb-components
19097 (face-property 'default
19098 (cond ((eq attr :foreground) 'foreground)
19099 ((eq attr :background) 'background))))
19100 (color-values (face-attribute 'default attr nil))))))
19102 (defun org-latex-color-format (color-name)
19103 "Convert COLOR-NAME to a RGB color value."
19104 (apply 'format "%s,%s,%s"
19105 (mapcar 'org-normalize-color
19106 (color-values color-name))))
19108 (defun org-normalize-color (value)
19109 "Return string to be used as color value for an RGB component."
19110 (format "%g" (/ value 65535.0)))
19114 ;; Image display
19116 (defvar org-inline-image-overlays nil)
19117 (make-variable-buffer-local 'org-inline-image-overlays)
19119 (defun org-toggle-inline-images (&optional include-linked)
19120 "Toggle the display of inline images.
19121 INCLUDE-LINKED is passed to `org-display-inline-images'."
19122 (interactive "P")
19123 (if org-inline-image-overlays
19124 (progn
19125 (org-remove-inline-images)
19126 (message "Inline image display turned off"))
19127 (org-display-inline-images include-linked)
19128 (if (and (org-called-interactively-p)
19129 org-inline-image-overlays)
19130 (message "%d images displayed inline"
19131 (length org-inline-image-overlays))
19132 (message "No images to display inline"))))
19134 (defun org-redisplay-inline-images ()
19135 "Refresh the display of inline images."
19136 (interactive)
19137 (if (not org-inline-image-overlays)
19138 (org-toggle-inline-images)
19139 (org-toggle-inline-images)
19140 (org-toggle-inline-images)))
19142 (defun org-display-inline-images (&optional include-linked refresh beg end)
19143 "Display inline images.
19145 An inline image is a link which follows either of these
19146 conventions:
19148 1. Its path is a file with an extension matching return value
19149 from `image-file-name-regexp' and it has no contents.
19151 2. Its description consists in a single link of the previous
19152 type.
19154 When optional argument INCLUDE-LINKED is non-nil, also links with
19155 a text description part will be inlined. This can be nice for
19156 a quick look at those images, but it does not reflect what
19157 exported files will look like.
19159 When optional argument REFRESH is non-nil, refresh existing
19160 images between BEG and END. This will create new image displays
19161 only if necessary. BEG and END default to the buffer
19162 boundaries."
19163 (interactive "P")
19164 (when (display-graphic-p)
19165 (unless refresh
19166 (org-remove-inline-images)
19167 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19168 (org-with-wide-buffer
19169 (goto-char (or beg (point-min)))
19170 (let ((case-fold-search t)
19171 (file-extension-re (org-image-file-name-regexp)))
19172 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19173 (let ((link (save-match-data (org-element-context))))
19174 ;; Check if we're at an inline image.
19175 (when (and (equal (org-element-property :type link) "file")
19176 (or include-linked
19177 (not (org-element-property :contents-begin link)))
19178 (let ((parent (org-element-property :parent link)))
19179 (or (not (eq (org-element-type parent) 'link))
19180 (not (cdr (org-element-contents parent)))))
19181 (org-string-match-p file-extension-re
19182 (org-element-property :path link)))
19183 (let ((file (expand-file-name (org-element-property :path link))))
19184 (when (file-exists-p file)
19185 (let ((width
19186 ;; Apply `org-image-actual-width' specifications.
19187 (cond
19188 ((not (image-type-available-p 'imagemagick)) nil)
19189 ((eq org-image-actual-width t) nil)
19190 ((listp org-image-actual-width)
19192 ;; First try to find a width among
19193 ;; attributes associated to the paragraph
19194 ;; containing link.
19195 (let ((paragraph
19196 (let ((e link))
19197 (while (and (setq e (org-element-property
19198 :parent e))
19199 (not (eq (org-element-type e)
19200 'paragraph))))
19201 e)))
19202 (when paragraph
19203 (save-excursion
19204 (goto-char (org-element-property :begin paragraph))
19205 (when
19206 (re-search-forward
19207 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19208 (org-element-property
19209 :post-affiliated paragraph)
19211 (string-to-number (match-string 1))))))
19212 ;; Otherwise, fall-back to provided number.
19213 (car org-image-actual-width)))
19214 ((numberp org-image-actual-width)
19215 org-image-actual-width)))
19216 (old (get-char-property-and-overlay
19217 (org-element-property :begin link)
19218 'org-image-overlay)))
19219 (if (and (car-safe old) refresh)
19220 (image-refresh (overlay-get (cdr old) 'display))
19221 (let ((image (create-image file
19222 (and width 'imagemagick)
19224 :width width)))
19225 (when image
19226 (let* ((link
19227 ;; If inline image is the description
19228 ;; of another link, be sure to
19229 ;; consider the latter as the one to
19230 ;; apply the overlay on.
19231 (let ((parent
19232 (org-element-property :parent link)))
19233 (if (eq (org-element-type parent) 'link)
19234 parent
19235 link)))
19236 (ov (make-overlay
19237 (org-element-property :begin link)
19238 (progn
19239 (goto-char
19240 (org-element-property :end link))
19241 (skip-chars-backward " \t")
19242 (point)))))
19243 (overlay-put ov 'display image)
19244 (overlay-put ov 'face 'default)
19245 (overlay-put ov 'org-image-overlay t)
19246 (overlay-put
19247 ov 'modification-hooks
19248 (list 'org-display-inline-remove-overlay))
19249 (push ov org-inline-image-overlays)))))))))))))))
19251 (define-obsolete-function-alias
19252 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19254 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19255 "Remove inline-display overlay if a corresponding region is modified."
19256 (let ((inhibit-modification-hooks t))
19257 (when (and ov after)
19258 (delete ov org-inline-image-overlays)
19259 (delete-overlay ov))))
19261 (defun org-remove-inline-images ()
19262 "Remove inline display of images."
19263 (interactive)
19264 (mapc 'delete-overlay org-inline-image-overlays)
19265 (setq org-inline-image-overlays nil))
19267 ;;;; Key bindings
19269 ;; Outline functions from `outline-mode-prefix-map'
19270 ;; that can be remapped in Org:
19271 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19272 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19273 (define-key org-mode-map [remap outline-forward-same-level]
19274 'org-forward-heading-same-level)
19275 (define-key org-mode-map [remap outline-backward-same-level]
19276 'org-backward-heading-same-level)
19277 (define-key org-mode-map [remap show-branches]
19278 'org-kill-note-or-show-branches)
19279 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19280 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19281 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19283 ;; Outline functions from `outline-mode-prefix-map' that can not
19284 ;; be remapped in Org:
19286 ;; - the column "key binding" shows whether the Outline function is still
19287 ;; available in Org mode on the same key that it has been bound to in
19288 ;; Outline mode:
19289 ;; - "overridden": key used for a different functionality in Org mode
19290 ;; - else: key still bound to the same Outline function in Org mode
19292 ;; | Outline function | key binding | Org replacement |
19293 ;; |------------------------------------+-------------+-----------------------|
19294 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19295 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19296 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19297 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19298 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19299 ;; | `show-entry' | overridden | no replacement |
19300 ;; | `show-children' | `C-c C-i' | visibility cycling |
19301 ;; | `show-branches' | `C-c C-k' | still same function |
19302 ;; | `show-subtree' | overridden | visibility cycling |
19303 ;; | `show-all' | overridden | no replacement |
19304 ;; | `hide-subtree' | overridden | visibility cycling |
19305 ;; | `hide-body' | overridden | no replacement |
19306 ;; | `hide-entry' | overridden | visibility cycling |
19307 ;; | `hide-leaves' | overridden | no replacement |
19308 ;; | `hide-sublevels' | overridden | no replacement |
19309 ;; | `hide-other' | overridden | no replacement |
19311 ;; Make `C-c C-x' a prefix key
19312 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19314 ;; TAB key with modifiers
19315 (org-defkey org-mode-map "\C-i" 'org-cycle)
19316 (org-defkey org-mode-map [(tab)] 'org-cycle)
19317 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19318 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19319 ;; The following line is necessary under Suse GNU/Linux
19320 (unless (featurep 'xemacs)
19321 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19322 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19323 (define-key org-mode-map [backtab] 'org-shifttab)
19325 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19326 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19327 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19329 ;; Cursor keys with modifiers
19330 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19331 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19332 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19333 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19335 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19336 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19337 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19338 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19339 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19340 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19342 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19343 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19344 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19345 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19347 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19348 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19349 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19350 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19352 ;; Babel keys
19353 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19354 (mapc (lambda (pair)
19355 (define-key org-babel-map (car pair) (cdr pair)))
19356 org-babel-key-bindings)
19358 ;;; Extra keys for tty access.
19359 ;; We only set them when really needed because otherwise the
19360 ;; menus don't show the simple keys
19362 (when (or org-use-extra-keys
19363 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19364 (not window-system))
19365 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19366 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19367 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19368 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19369 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19370 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19371 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19372 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19373 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19374 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19375 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19376 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19377 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19378 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19379 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19380 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19381 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19382 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19383 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19384 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19385 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19386 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19387 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19388 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19389 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19390 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19391 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19392 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19394 ;; All the other keys
19396 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19397 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19398 (if (boundp 'narrow-map)
19399 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19400 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19401 (if (boundp 'narrow-map)
19402 (org-defkey narrow-map "b" 'org-narrow-to-block)
19403 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19404 (if (boundp 'narrow-map)
19405 (org-defkey narrow-map "e" 'org-narrow-to-element)
19406 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19407 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19408 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19409 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19410 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19411 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19412 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19413 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19414 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19415 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19416 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19417 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19418 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19419 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19420 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19421 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19422 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19423 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19424 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19425 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19426 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19427 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19428 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19429 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19430 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19431 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19432 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19433 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19434 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19435 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19436 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19437 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19438 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19439 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19440 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19441 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19442 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19443 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19444 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19445 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19446 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19447 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19448 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19449 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19450 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19451 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19452 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19453 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19454 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19455 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19456 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19457 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19458 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19459 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19460 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19461 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19462 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19463 (org-defkey org-mode-map "\C-c^" 'org-sort)
19464 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19465 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19466 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19467 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19468 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19469 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19470 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19471 (org-defkey org-mode-map "\C-m" 'org-return)
19472 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19473 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19474 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19475 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19476 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19477 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19478 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19479 (org-defkey org-mode-map "\C-cp" 'orgtbl-ascii-plot)
19480 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19481 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19482 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19483 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19484 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19485 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19486 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19487 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19488 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19489 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19490 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19491 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19492 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19493 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19494 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19495 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19497 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19498 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19499 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19501 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19502 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19503 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19504 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19505 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19506 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19507 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19508 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19509 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19510 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19511 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19512 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19513 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19514 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19515 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19516 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19517 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19518 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19519 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19520 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19521 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19522 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19523 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19525 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19526 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19527 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19528 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19529 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19531 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19533 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19535 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19536 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19538 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19541 (when (featurep 'xemacs)
19542 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19545 (defconst org-speed-commands-default
19547 ("Outline Navigation")
19548 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19549 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19550 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19551 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19552 ("F" . org-next-block)
19553 ("B" . org-previous-block)
19554 ("u" . (org-speed-move-safe 'outline-up-heading))
19555 ("j" . org-goto)
19556 ("g" . (org-refile t))
19557 ("Outline Visibility")
19558 ("c" . org-cycle)
19559 ("C" . org-shifttab)
19560 (" " . org-display-outline-path)
19561 ("s" . org-narrow-to-subtree)
19562 ("=" . org-columns)
19563 ("Outline Structure Editing")
19564 ("U" . org-metaup)
19565 ("D" . org-metadown)
19566 ("r" . org-metaright)
19567 ("l" . org-metaleft)
19568 ("R" . org-shiftmetaright)
19569 ("L" . org-shiftmetaleft)
19570 ("i" . (progn (forward-char 1) (call-interactively
19571 'org-insert-heading-respect-content)))
19572 ("^" . org-sort)
19573 ("w" . org-refile)
19574 ("a" . org-archive-subtree-default-with-confirmation)
19575 ("@" . org-mark-subtree)
19576 ("#" . org-toggle-comment)
19577 ("Clock Commands")
19578 ("I" . org-clock-in)
19579 ("O" . org-clock-out)
19580 ("Meta Data Editing")
19581 ("t" . org-todo)
19582 ("," . (org-priority))
19583 ("0" . (org-priority ?\ ))
19584 ("1" . (org-priority ?A))
19585 ("2" . (org-priority ?B))
19586 ("3" . (org-priority ?C))
19587 (":" . org-set-tags-command)
19588 ("e" . org-set-effort)
19589 ("E" . org-inc-effort)
19590 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19591 (org-entry-put (point) "APPT_WARNTIME" m)))
19592 ("Agenda Views etc")
19593 ("v" . org-agenda)
19594 ("/" . org-sparse-tree)
19595 ("Misc")
19596 ("o" . org-open-at-point)
19597 ("?" . org-speed-command-help)
19598 ("<" . (org-agenda-set-restriction-lock 'subtree))
19599 (">" . (org-agenda-remove-restriction-lock))
19601 "The default speed commands.")
19603 (defun org-print-speed-command (e)
19604 (if (> (length (car e)) 1)
19605 (progn
19606 (princ "\n")
19607 (princ (car e))
19608 (princ "\n")
19609 (princ (make-string (length (car e)) ?-))
19610 (princ "\n"))
19611 (princ (car e))
19612 (princ " ")
19613 (if (symbolp (cdr e))
19614 (princ (symbol-name (cdr e)))
19615 (prin1 (cdr e)))
19616 (princ "\n")))
19618 (defun org-speed-command-help ()
19619 "Show the available speed commands."
19620 (interactive)
19621 (if (not org-use-speed-commands)
19622 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19623 (with-output-to-temp-buffer "*Help*"
19624 (princ "User-defined Speed commands\n===========================\n")
19625 (mapc 'org-print-speed-command org-speed-commands-user)
19626 (princ "\n")
19627 (princ "Built-in Speed commands\n=======================\n")
19628 (mapc 'org-print-speed-command org-speed-commands-default))
19629 (with-current-buffer "*Help*"
19630 (setq truncate-lines t))))
19632 (defun org-speed-move-safe (cmd)
19633 "Execute CMD, but make sure that the cursor always ends up in a headline.
19634 If not, return to the original position and throw an error."
19635 (interactive)
19636 (let ((pos (point)))
19637 (call-interactively cmd)
19638 (unless (and (bolp) (org-at-heading-p))
19639 (goto-char pos)
19640 (error "Boundary reached while executing %s" cmd))))
19642 (defvar org-self-insert-command-undo-counter 0)
19644 (defvar org-table-auto-blank-field) ; defined in org-table.el
19645 (defvar org-speed-command nil)
19647 (define-obsolete-function-alias
19648 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19650 (defun org-speed-command-activate (keys)
19651 "Hook for activating single-letter speed commands.
19652 `org-speed-commands-default' specifies a minimal command set.
19653 Use `org-speed-commands-user' for further customization."
19654 (when (or (and (bolp) (looking-at org-outline-regexp))
19655 (and (functionp org-use-speed-commands)
19656 (funcall org-use-speed-commands)))
19657 (cdr (assoc keys (append org-speed-commands-user
19658 org-speed-commands-default)))))
19660 (define-obsolete-function-alias
19661 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19663 (defun org-babel-speed-command-activate (keys)
19664 "Hook for activating single-letter code block commands."
19665 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19666 (cdr (assoc keys org-babel-key-bindings))))
19668 (defcustom org-speed-command-hook
19669 '(org-speed-command-default-hook org-babel-speed-command-hook)
19670 "Hook for activating speed commands at strategic locations.
19671 Hook functions are called in sequence until a valid handler is
19672 found.
19674 Each hook takes a single argument, a user-pressed command key
19675 which is also a `self-insert-command' from the global map.
19677 Within the hook, examine the cursor position and the command key
19678 and return nil or a valid handler as appropriate. Handler could
19679 be one of an interactive command, a function, or a form.
19681 Set `org-use-speed-commands' to non-nil value to enable this
19682 hook. The default setting is `org-speed-command-activate'."
19683 :group 'org-structure
19684 :version "24.1"
19685 :type 'hook)
19687 (defun org-self-insert-command (N)
19688 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19689 If the cursor is in a table looking at whitespace, the whitespace is
19690 overwritten, and the table is not marked as requiring realignment."
19691 (interactive "p")
19692 (org-check-before-invisible-edit 'insert)
19693 (cond
19694 ((and org-use-speed-commands
19695 (setq org-speed-command
19696 (run-hook-with-args-until-success
19697 'org-speed-command-hook (this-command-keys))))
19698 (cond
19699 ((commandp org-speed-command)
19700 (setq this-command org-speed-command)
19701 (call-interactively org-speed-command))
19702 ((functionp org-speed-command)
19703 (funcall org-speed-command))
19704 ((and org-speed-command (listp org-speed-command))
19705 (eval org-speed-command))
19706 (t (let (org-use-speed-commands)
19707 (call-interactively 'org-self-insert-command)))))
19708 ((and
19709 (org-table-p)
19710 (progn
19711 ;; check if we blank the field, and if that triggers align
19712 (and (featurep 'org-table) org-table-auto-blank-field
19713 (member last-command
19714 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19715 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19716 ;; got extra space, this field does not determine column width
19717 (let (org-table-may-need-update) (org-table-blank-field))
19718 ;; no extra space, this field may determine column width
19719 (org-table-blank-field)))
19721 (eq N 1)
19722 (looking-at "[^|\n]* |"))
19723 (let (org-table-may-need-update)
19724 (goto-char (1- (match-end 0)))
19725 (backward-delete-char 1)
19726 (goto-char (match-beginning 0))
19727 (self-insert-command N)))
19729 (setq org-table-may-need-update t)
19730 (self-insert-command N)
19731 (org-fix-tags-on-the-fly)
19732 (if org-self-insert-cluster-for-undo
19733 (if (not (eq last-command 'org-self-insert-command))
19734 (setq org-self-insert-command-undo-counter 1)
19735 (if (>= org-self-insert-command-undo-counter 20)
19736 (setq org-self-insert-command-undo-counter 1)
19737 (and (> org-self-insert-command-undo-counter 0)
19738 buffer-undo-list (listp buffer-undo-list)
19739 (not (cadr buffer-undo-list)) ; remove nil entry
19740 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19741 (setq org-self-insert-command-undo-counter
19742 (1+ org-self-insert-command-undo-counter))))))))
19744 (defun org-check-before-invisible-edit (kind)
19745 "Check is editing if kind KIND would be dangerous with invisible text around.
19746 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19747 ;; First, try to get out of here as quickly as possible, to reduce overhead
19748 (if (and org-catch-invisible-edits
19749 (or (not (boundp 'visible-mode)) (not visible-mode))
19750 (or (get-char-property (point) 'invisible)
19751 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19752 ;; OK, we need to take a closer look
19753 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19754 (invisible-before-point (if (bobp) nil (get-char-property
19755 (1- (point)) 'invisible)))
19756 (border-and-ok-direction
19758 ;; Check if we are acting predictably before invisible text
19759 (and invisible-at-point (not invisible-before-point)
19760 (memq kind '(insert delete-backward)))
19761 ;; Check if we are acting predictably after invisible text
19762 ;; This works not well, and I have turned it off. It seems
19763 ;; better to always show and stop after invisible text.
19764 ;; (and (not invisible-at-point) invisible-before-point
19765 ;; (memq kind '(insert delete)))
19767 (when (or (memq invisible-at-point '(outline org-hide-block t))
19768 (memq invisible-before-point '(outline org-hide-block t)))
19769 (if (eq org-catch-invisible-edits 'error)
19770 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19771 (if (and org-custom-properties-overlays
19772 (y-or-n-p "Display invisible properties in this buffer? "))
19773 (org-toggle-custom-properties-visibility)
19774 ;; Make the area visible
19775 (save-excursion
19776 (if invisible-before-point
19777 (goto-char (previous-single-char-property-change
19778 (point) 'invisible)))
19779 (show-subtree))
19780 (cond
19781 ((eq org-catch-invisible-edits 'show)
19782 ;; That's it, we do the edit after showing
19783 (message
19784 "Unfolding invisible region around point before editing")
19785 (sit-for 1))
19786 ((and (eq org-catch-invisible-edits 'smart)
19787 border-and-ok-direction)
19788 (message "Unfolding invisible region around point before editing"))
19790 ;; Don't do the edit, make the user repeat it in full visibility
19791 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19793 (defun org-fix-tags-on-the-fly ()
19794 (when (and (equal (char-after (point-at-bol)) ?*)
19795 (org-at-heading-p))
19796 (org-align-tags-here org-tags-column)))
19798 (defun org-delete-backward-char (N)
19799 "Like `delete-backward-char', insert whitespace at field end in tables.
19800 When deleting backwards, in tables this function will insert whitespace in
19801 front of the next \"|\" separator, to keep the table aligned. The table will
19802 still be marked for re-alignment if the field did fill the entire column,
19803 because, in this case the deletion might narrow the column."
19804 (interactive "p")
19805 (save-match-data
19806 (org-check-before-invisible-edit 'delete-backward)
19807 (if (and (org-table-p)
19808 (eq N 1)
19809 (string-match "|" (buffer-substring (point-at-bol) (point)))
19810 (looking-at ".*?|"))
19811 (let ((pos (point))
19812 (noalign (looking-at "[^|\n\r]* |"))
19813 (c org-table-may-need-update))
19814 (backward-delete-char N)
19815 (if (not overwrite-mode)
19816 (progn
19817 (skip-chars-forward "^|")
19818 (insert " ")
19819 (goto-char (1- pos))))
19820 ;; noalign: if there were two spaces at the end, this field
19821 ;; does not determine the width of the column.
19822 (if noalign (setq org-table-may-need-update c)))
19823 (backward-delete-char N)
19824 (org-fix-tags-on-the-fly))))
19826 (defun org-delete-char (N)
19827 "Like `delete-char', but insert whitespace at field end in tables.
19828 When deleting characters, in tables this function will insert whitespace in
19829 front of the next \"|\" separator, to keep the table aligned. The table will
19830 still be marked for re-alignment if the field did fill the entire column,
19831 because, in this case the deletion might narrow the column."
19832 (interactive "p")
19833 (save-match-data
19834 (org-check-before-invisible-edit 'delete)
19835 (if (and (org-table-p)
19836 (not (bolp))
19837 (not (= (char-after) ?|))
19838 (eq N 1))
19839 (if (looking-at ".*?|")
19840 (let ((pos (point))
19841 (noalign (looking-at "[^|\n\r]* |"))
19842 (c org-table-may-need-update))
19843 (replace-match
19844 (concat (substring (match-string 0) 1 -1) " |") nil t)
19845 (goto-char pos)
19846 ;; noalign: if there were two spaces at the end, this field
19847 ;; does not determine the width of the column.
19848 (if noalign (setq org-table-may-need-update c)))
19849 (delete-char N))
19850 (delete-char N)
19851 (org-fix-tags-on-the-fly))))
19853 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19854 (put 'org-self-insert-command 'delete-selection
19855 (lambda ()
19856 (not (run-hook-with-args-until-success
19857 'self-insert-uses-region-functions))))
19858 (put 'orgtbl-self-insert-command 'delete-selection
19859 (lambda ()
19860 (not (run-hook-with-args-until-success
19861 'self-insert-uses-region-functions))))
19862 (put 'org-delete-char 'delete-selection 'supersede)
19863 (put 'org-delete-backward-char 'delete-selection 'supersede)
19864 (put 'org-yank 'delete-selection 'yank)
19866 ;; Make `flyspell-mode' delay after some commands
19867 (put 'org-self-insert-command 'flyspell-delayed t)
19868 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19869 (put 'org-delete-char 'flyspell-delayed t)
19870 (put 'org-delete-backward-char 'flyspell-delayed t)
19872 ;; Make pabbrev-mode expand after org-mode commands
19873 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19874 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19876 (defun org-remap (map &rest commands)
19877 "In MAP, remap the functions given in COMMANDS.
19878 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19879 (let (new old)
19880 (while commands
19881 (setq old (pop commands) new (pop commands))
19882 (if (fboundp 'command-remapping)
19883 (org-defkey map (vector 'remap old) new)
19884 (substitute-key-definition old new map global-map)))))
19886 (defun org-transpose-words ()
19887 "Transpose words for Org.
19888 This uses the `org-mode-transpose-word-syntax-table' syntax
19889 table, which interprets characters in `org-emphasis-alist' as
19890 word constituents."
19891 (interactive)
19892 (with-syntax-table org-mode-transpose-word-syntax-table
19893 (call-interactively 'transpose-words)))
19894 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19896 (when (eq org-enable-table-editor 'optimized)
19897 ;; If the user wants maximum table support, we need to hijack
19898 ;; some standard editing functions
19899 (org-remap org-mode-map
19900 'self-insert-command 'org-self-insert-command
19901 'delete-char 'org-delete-char
19902 'delete-backward-char 'org-delete-backward-char)
19903 (org-defkey org-mode-map "|" 'org-force-self-insert))
19905 (defvar org-ctrl-c-ctrl-c-hook nil
19906 "Hook for functions attaching themselves to `C-c C-c'.
19908 This can be used to add additional functionality to the C-c C-c
19909 key which executes context-dependent commands. This hook is run
19910 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19911 run after the last test.
19913 Each function will be called with no arguments. The function
19914 must check if the context is appropriate for it to act. If yes,
19915 it should do its thing and then return a non-nil value. If the
19916 context is wrong, just do nothing and return nil.")
19918 (defvar org-ctrl-c-ctrl-c-final-hook nil
19919 "Hook for functions attaching themselves to `C-c C-c'.
19921 This can be used to add additional functionality to the C-c C-c
19922 key which executes context-dependent commands. This hook is run
19923 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19924 before the first test.
19926 Each function will be called with no arguments. The function
19927 must check if the context is appropriate for it to act. If yes,
19928 it should do its thing and then return a non-nil value. If the
19929 context is wrong, just do nothing and return nil.")
19931 (defvar org-tab-first-hook nil
19932 "Hook for functions to attach themselves to TAB.
19933 See `org-ctrl-c-ctrl-c-hook' for more information.
19934 This hook runs as the first action when TAB is pressed, even before
19935 `org-cycle' messes around with the `outline-regexp' to cater for
19936 inline tasks and plain list item folding.
19937 If any function in this hook returns t, any other actions that
19938 would have been caused by TAB (such as table field motion or visibility
19939 cycling) will not occur.")
19941 (defvar org-tab-after-check-for-table-hook nil
19942 "Hook for functions to attach themselves to TAB.
19943 See `org-ctrl-c-ctrl-c-hook' for more information.
19944 This hook runs after it has been established that the cursor is not in a
19945 table, but before checking if the cursor is in a headline or if global cycling
19946 should be done.
19947 If any function in this hook returns t, not other actions like visibility
19948 cycling will be done.")
19950 (defvar org-tab-after-check-for-cycling-hook nil
19951 "Hook for functions to attach themselves to TAB.
19952 See `org-ctrl-c-ctrl-c-hook' for more information.
19953 This hook runs after it has been established that not table field motion and
19954 not visibility should be done because of current context. This is probably
19955 the place where a package like yasnippets can hook in.")
19957 (defvar org-tab-before-tab-emulation-hook nil
19958 "Hook for functions to attach themselves to TAB.
19959 See `org-ctrl-c-ctrl-c-hook' for more information.
19960 This hook runs after every other options for TAB have been exhausted, but
19961 before indentation and \t insertion takes place.")
19963 (defvar org-metaleft-hook nil
19964 "Hook for functions attaching themselves to `M-left'.
19965 See `org-ctrl-c-ctrl-c-hook' for more information.")
19966 (defvar org-metaright-hook nil
19967 "Hook for functions attaching themselves to `M-right'.
19968 See `org-ctrl-c-ctrl-c-hook' for more information.")
19969 (defvar org-metaup-hook nil
19970 "Hook for functions attaching themselves to `M-up'.
19971 See `org-ctrl-c-ctrl-c-hook' for more information.")
19972 (defvar org-metadown-hook nil
19973 "Hook for functions attaching themselves to `M-down'.
19974 See `org-ctrl-c-ctrl-c-hook' for more information.")
19975 (defvar org-shiftmetaleft-hook nil
19976 "Hook for functions attaching themselves to `M-S-left'.
19977 See `org-ctrl-c-ctrl-c-hook' for more information.")
19978 (defvar org-shiftmetaright-hook nil
19979 "Hook for functions attaching themselves to `M-S-right'.
19980 See `org-ctrl-c-ctrl-c-hook' for more information.")
19981 (defvar org-shiftmetaup-hook nil
19982 "Hook for functions attaching themselves to `M-S-up'.
19983 See `org-ctrl-c-ctrl-c-hook' for more information.")
19984 (defvar org-shiftmetadown-hook nil
19985 "Hook for functions attaching themselves to `M-S-down'.
19986 See `org-ctrl-c-ctrl-c-hook' for more information.")
19987 (defvar org-metareturn-hook nil
19988 "Hook for functions attaching themselves to `M-RET'.
19989 See `org-ctrl-c-ctrl-c-hook' for more information.")
19990 (defvar org-shiftup-hook nil
19991 "Hook for functions attaching themselves to `S-up'.
19992 See `org-ctrl-c-ctrl-c-hook' for more information.")
19993 (defvar org-shiftup-final-hook nil
19994 "Hook for functions attaching themselves to `S-up'.
19995 This one runs after all other options except shift-select have been excluded.
19996 See `org-ctrl-c-ctrl-c-hook' for more information.")
19997 (defvar org-shiftdown-hook nil
19998 "Hook for functions attaching themselves to `S-down'.
19999 See `org-ctrl-c-ctrl-c-hook' for more information.")
20000 (defvar org-shiftdown-final-hook nil
20001 "Hook for functions attaching themselves to `S-down'.
20002 This one runs after all other options except shift-select have been excluded.
20003 See `org-ctrl-c-ctrl-c-hook' for more information.")
20004 (defvar org-shiftleft-hook nil
20005 "Hook for functions attaching themselves to `S-left'.
20006 See `org-ctrl-c-ctrl-c-hook' for more information.")
20007 (defvar org-shiftleft-final-hook nil
20008 "Hook for functions attaching themselves to `S-left'.
20009 This one runs after all other options except shift-select have been excluded.
20010 See `org-ctrl-c-ctrl-c-hook' for more information.")
20011 (defvar org-shiftright-hook nil
20012 "Hook for functions attaching themselves to `S-right'.
20013 See `org-ctrl-c-ctrl-c-hook' for more information.")
20014 (defvar org-shiftright-final-hook nil
20015 "Hook for functions attaching themselves to `S-right'.
20016 This one runs after all other options except shift-select have been excluded.
20017 See `org-ctrl-c-ctrl-c-hook' for more information.")
20019 (defun org-modifier-cursor-error ()
20020 "Throw an error, a modified cursor command was applied in wrong context."
20021 (user-error "This command is active in special context like tables, headlines or items"))
20023 (defun org-shiftselect-error ()
20024 "Throw an error because Shift-Cursor command was applied in wrong context."
20025 (if (and (boundp 'shift-select-mode) shift-select-mode)
20026 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20027 (user-error "This command works only in special context like headlines or timestamps")))
20029 (defun org-call-for-shift-select (cmd)
20030 (let ((this-command-keys-shift-translated t))
20031 (call-interactively cmd)))
20033 (defun org-shifttab (&optional arg)
20034 "Global visibility cycling or move to previous table field.
20035 Call `org-table-previous-field' within a table.
20036 When ARG is nil, cycle globally through visibility states.
20037 When ARG is a numeric prefix, show contents of this level."
20038 (interactive "P")
20039 (cond
20040 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20041 ((integerp arg)
20042 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20043 (message "Content view to level: %d" arg)
20044 (org-content (prefix-numeric-value arg2))
20045 (org-cycle-show-empty-lines t)
20046 (setq org-cycle-global-status 'overview)))
20047 (t (call-interactively 'org-global-cycle))))
20049 (defun org-shiftmetaleft ()
20050 "Promote subtree or delete table column.
20051 Calls `org-promote-subtree', `org-outdent-item-tree', or
20052 `org-table-delete-column', depending on context. See the
20053 individual commands for more information."
20054 (interactive)
20055 (cond
20056 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20057 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20058 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20059 ((if (not (org-region-active-p)) (org-at-item-p)
20060 (save-excursion (goto-char (region-beginning))
20061 (org-at-item-p)))
20062 (call-interactively 'org-outdent-item-tree))
20063 (t (org-modifier-cursor-error))))
20065 (defun org-shiftmetaright ()
20066 "Demote subtree or insert table column.
20067 Calls `org-demote-subtree', `org-indent-item-tree', or
20068 `org-table-insert-column', depending on context. See the
20069 individual commands for more information."
20070 (interactive)
20071 (cond
20072 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20073 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20074 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20075 ((if (not (org-region-active-p)) (org-at-item-p)
20076 (save-excursion (goto-char (region-beginning))
20077 (org-at-item-p)))
20078 (call-interactively 'org-indent-item-tree))
20079 (t (org-modifier-cursor-error))))
20081 (defun org-shiftmetaup (&optional arg)
20082 "Drag the line at point up.
20083 In a table, kill the current row.
20084 On a clock timestamp, update the value of the timestamp like `S-<up>'
20085 but also adjust the previous clocked item in the clock history.
20086 Everywhere else, drag the line at point up."
20087 (interactive "P")
20088 (cond
20089 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20090 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20091 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20092 (call-interactively 'org-timestamp-up)))
20093 (t (call-interactively 'org-drag-line-backward))))
20095 (defun org-shiftmetadown (&optional arg)
20096 "Drag the line at point down.
20097 In a table, insert an empty row at the current line.
20098 On a clock timestamp, update the value of the timestamp like `S-<down>'
20099 but also adjust the previous clocked item in the clock history.
20100 Everywhere else, drag the line at point down."
20101 (interactive "P")
20102 (cond
20103 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20104 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20105 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20106 (call-interactively 'org-timestamp-down)))
20107 (t (call-interactively 'org-drag-line-forward))))
20109 (defsubst org-hidden-tree-error ()
20110 (user-error
20111 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20113 (defun org-metaleft (&optional arg)
20114 "Promote heading or move table column to left.
20115 Calls `org-do-promote' or `org-table-move-column', depending on context.
20116 With no specific context, calls the Emacs default `backward-word'.
20117 See the individual commands for more information."
20118 (interactive "P")
20119 (cond
20120 ((run-hook-with-args-until-success 'org-metaleft-hook))
20121 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20122 ((org-with-limited-levels
20123 (or (org-at-heading-p)
20124 (and (org-region-active-p)
20125 (save-excursion
20126 (goto-char (region-beginning))
20127 (org-at-heading-p)))))
20128 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20129 (call-interactively 'org-do-promote))
20130 ;; At an inline task.
20131 ((org-at-heading-p)
20132 (call-interactively 'org-inlinetask-promote))
20133 ((or (org-at-item-p)
20134 (and (org-region-active-p)
20135 (save-excursion
20136 (goto-char (region-beginning))
20137 (org-at-item-p))))
20138 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20139 (call-interactively 'org-outdent-item))
20140 (t (call-interactively 'backward-word))))
20142 (defun org-metaright (&optional arg)
20143 "Demote a subtree, a list item or move table column to right.
20144 In front of a drawer or a block keyword, indent it correctly.
20145 With no specific context, calls the Emacs default `forward-word'.
20146 See the individual commands for more information."
20147 (interactive "P")
20148 (cond
20149 ((run-hook-with-args-until-success 'org-metaright-hook))
20150 ((org-at-table-p) (call-interactively 'org-table-move-column))
20151 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20152 ((org-at-block-p) (call-interactively 'org-indent-block))
20153 ((org-with-limited-levels
20154 (or (org-at-heading-p)
20155 (and (org-region-active-p)
20156 (save-excursion
20157 (goto-char (region-beginning))
20158 (org-at-heading-p)))))
20159 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20160 (call-interactively 'org-do-demote))
20161 ;; At an inline task.
20162 ((org-at-heading-p)
20163 (call-interactively 'org-inlinetask-demote))
20164 ((or (org-at-item-p)
20165 (and (org-region-active-p)
20166 (save-excursion
20167 (goto-char (region-beginning))
20168 (org-at-item-p))))
20169 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20170 (call-interactively 'org-indent-item))
20171 (t (call-interactively 'forward-word))))
20173 (defun org-check-for-hidden (what)
20174 "Check if there are hidden headlines/items in the current visual line.
20175 WHAT can be either `headlines' or `items'. If the current line is
20176 an outline or item heading and it has a folded subtree below it,
20177 this function returns t, nil otherwise."
20178 (let ((re (cond
20179 ((eq what 'headlines) org-outline-regexp-bol)
20180 ((eq what 'items) (org-item-beginning-re))
20181 (t (error "This should not happen"))))
20182 beg end)
20183 (save-excursion
20184 (catch 'exit
20185 (unless (org-region-active-p)
20186 (setq beg (point-at-bol))
20187 (beginning-of-line 2)
20188 (while (and (not (eobp)) ;; this is like `next-line'
20189 (get-char-property (1- (point)) 'invisible))
20190 (beginning-of-line 2))
20191 (setq end (point))
20192 (goto-char beg)
20193 (goto-char (point-at-eol))
20194 (setq end (max end (point)))
20195 (while (re-search-forward re end t)
20196 (if (get-char-property (match-beginning 0) 'invisible)
20197 (throw 'exit t))))
20198 nil))))
20200 (defun org-metaup (&optional arg)
20201 "Move subtree up or move table row up.
20202 Calls `org-move-subtree-up' or `org-table-move-row' or
20203 `org-move-item-up', depending on context. See the individual commands
20204 for more information."
20205 (interactive "P")
20206 (cond
20207 ((run-hook-with-args-until-success 'org-metaup-hook))
20208 ((org-region-active-p)
20209 (let* ((a (min (region-beginning) (region-end)))
20210 (b (1- (max (region-beginning) (region-end))))
20211 (c (save-excursion (goto-char a)
20212 (move-beginning-of-line 0)))
20213 (d (save-excursion (goto-char a)
20214 (move-end-of-line 0) (point))))
20215 (transpose-regions a b c d)
20216 (goto-char c)))
20217 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20218 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20219 ((org-at-item-p) (call-interactively 'org-move-item-up))
20220 (t (org-drag-element-backward))))
20222 (defun org-metadown (&optional arg)
20223 "Move subtree down or move table row down.
20224 Calls `org-move-subtree-down' or `org-table-move-row' or
20225 `org-move-item-down', depending on context. See the individual
20226 commands for more information."
20227 (interactive "P")
20228 (cond
20229 ((run-hook-with-args-until-success 'org-metadown-hook))
20230 ((org-region-active-p)
20231 (let* ((a (min (region-beginning) (region-end)))
20232 (b (max (region-beginning) (region-end)))
20233 (c (save-excursion (goto-char b)
20234 (move-beginning-of-line 1)))
20235 (d (save-excursion (goto-char b)
20236 (move-end-of-line 1) (1+ (point)))))
20237 (transpose-regions a b c d)
20238 (goto-char d)))
20239 ((org-at-table-p) (call-interactively 'org-table-move-row))
20240 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20241 ((org-at-item-p) (call-interactively 'org-move-item-down))
20242 (t (org-drag-element-forward))))
20244 (defun org-shiftup (&optional arg)
20245 "Increase item in timestamp or increase priority of current headline.
20246 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20247 depending on context. See the individual commands for more information."
20248 (interactive "P")
20249 (cond
20250 ((run-hook-with-args-until-success 'org-shiftup-hook))
20251 ((and org-support-shift-select (org-region-active-p))
20252 (org-call-for-shift-select 'previous-line))
20253 ((org-at-timestamp-p t)
20254 (call-interactively (if org-edit-timestamp-down-means-later
20255 'org-timestamp-down 'org-timestamp-up)))
20256 ((and (not (eq org-support-shift-select 'always))
20257 org-enable-priority-commands
20258 (org-at-heading-p))
20259 (call-interactively 'org-priority-up))
20260 ((and (not org-support-shift-select) (org-at-item-p))
20261 (call-interactively 'org-previous-item))
20262 ((org-clocktable-try-shift 'up arg))
20263 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20264 (org-support-shift-select
20265 (org-call-for-shift-select 'previous-line))
20266 (t (org-shiftselect-error))))
20268 (defun org-shiftdown (&optional arg)
20269 "Decrease item in timestamp or decrease priority of current headline.
20270 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20271 depending on context. See the individual commands for more information."
20272 (interactive "P")
20273 (cond
20274 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20275 ((and org-support-shift-select (org-region-active-p))
20276 (org-call-for-shift-select 'next-line))
20277 ((org-at-timestamp-p t)
20278 (call-interactively (if org-edit-timestamp-down-means-later
20279 'org-timestamp-up 'org-timestamp-down)))
20280 ((and (not (eq org-support-shift-select 'always))
20281 org-enable-priority-commands
20282 (org-at-heading-p))
20283 (call-interactively 'org-priority-down))
20284 ((and (not org-support-shift-select) (org-at-item-p))
20285 (call-interactively 'org-next-item))
20286 ((org-clocktable-try-shift 'down arg))
20287 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20288 (org-support-shift-select
20289 (org-call-for-shift-select 'next-line))
20290 (t (org-shiftselect-error))))
20292 (defun org-shiftright (&optional arg)
20293 "Cycle the thing at point or in the current line, depending on context.
20294 Depending on context, this does one of the following:
20296 - switch a timestamp at point one day into the future
20297 - on a headline, switch to the next TODO keyword.
20298 - on an item, switch entire list to the next bullet type
20299 - on a property line, switch to the next allowed value
20300 - on a clocktable definition line, move time block into the future"
20301 (interactive "P")
20302 (cond
20303 ((run-hook-with-args-until-success 'org-shiftright-hook))
20304 ((and org-support-shift-select (org-region-active-p))
20305 (org-call-for-shift-select 'forward-char))
20306 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20307 ((and (not (eq org-support-shift-select 'always))
20308 (org-at-heading-p))
20309 (let ((org-inhibit-logging
20310 (not org-treat-S-cursor-todo-selection-as-state-change))
20311 (org-inhibit-blocking
20312 (not org-treat-S-cursor-todo-selection-as-state-change)))
20313 (org-call-with-arg 'org-todo 'right)))
20314 ((or (and org-support-shift-select
20315 (not (eq org-support-shift-select 'always))
20316 (org-at-item-bullet-p))
20317 (and (not org-support-shift-select) (org-at-item-p)))
20318 (org-call-with-arg 'org-cycle-list-bullet nil))
20319 ((and (not (eq org-support-shift-select 'always))
20320 (org-at-property-p))
20321 (call-interactively 'org-property-next-allowed-value))
20322 ((org-clocktable-try-shift 'right arg))
20323 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20324 (org-support-shift-select
20325 (org-call-for-shift-select 'forward-char))
20326 (t (org-shiftselect-error))))
20328 (defun org-shiftleft (&optional arg)
20329 "Cycle the thing at point or in the current line, depending on context.
20330 Depending on context, this does one of the following:
20332 - switch a timestamp at point one day into the past
20333 - on a headline, switch to the previous TODO keyword.
20334 - on an item, switch entire list to the previous bullet type
20335 - on a property line, switch to the previous allowed value
20336 - on a clocktable definition line, move time block into the past"
20337 (interactive "P")
20338 (cond
20339 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20340 ((and org-support-shift-select (org-region-active-p))
20341 (org-call-for-shift-select 'backward-char))
20342 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20343 ((and (not (eq org-support-shift-select 'always))
20344 (org-at-heading-p))
20345 (let ((org-inhibit-logging
20346 (not org-treat-S-cursor-todo-selection-as-state-change))
20347 (org-inhibit-blocking
20348 (not org-treat-S-cursor-todo-selection-as-state-change)))
20349 (org-call-with-arg 'org-todo 'left)))
20350 ((or (and org-support-shift-select
20351 (not (eq org-support-shift-select 'always))
20352 (org-at-item-bullet-p))
20353 (and (not org-support-shift-select) (org-at-item-p)))
20354 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20355 ((and (not (eq org-support-shift-select 'always))
20356 (org-at-property-p))
20357 (call-interactively 'org-property-previous-allowed-value))
20358 ((org-clocktable-try-shift 'left arg))
20359 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20360 (org-support-shift-select
20361 (org-call-for-shift-select 'backward-char))
20362 (t (org-shiftselect-error))))
20364 (defun org-shiftcontrolright ()
20365 "Switch to next TODO set."
20366 (interactive)
20367 (cond
20368 ((and org-support-shift-select (org-region-active-p))
20369 (org-call-for-shift-select 'forward-word))
20370 ((and (not (eq org-support-shift-select 'always))
20371 (org-at-heading-p))
20372 (org-call-with-arg 'org-todo 'nextset))
20373 (org-support-shift-select
20374 (org-call-for-shift-select 'forward-word))
20375 (t (org-shiftselect-error))))
20377 (defun org-shiftcontrolleft ()
20378 "Switch to previous TODO set."
20379 (interactive)
20380 (cond
20381 ((and org-support-shift-select (org-region-active-p))
20382 (org-call-for-shift-select 'backward-word))
20383 ((and (not (eq org-support-shift-select 'always))
20384 (org-at-heading-p))
20385 (org-call-with-arg 'org-todo 'previousset))
20386 (org-support-shift-select
20387 (org-call-for-shift-select 'backward-word))
20388 (t (org-shiftselect-error))))
20390 (defun org-shiftcontrolup (&optional n)
20391 "Change timestamps synchronously up in CLOCK log lines.
20392 Optional argument N tells to change by that many units."
20393 (interactive "P")
20394 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20395 (let (org-support-shift-select)
20396 (org-clock-timestamps-up n))
20397 (user-error "Not at a clock log")))
20399 (defun org-shiftcontroldown (&optional n)
20400 "Change timestamps synchronously down in CLOCK log lines.
20401 Optional argument N tells to change by that many units."
20402 (interactive "P")
20403 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20404 (let (org-support-shift-select)
20405 (org-clock-timestamps-down n))
20406 (user-error "Not at a clock log")))
20408 (defun org-increase-number-at-point (&optional inc)
20409 "Increment the number at point.
20410 With an optional prefix numeric argument INC, increment using
20411 this numeric value."
20412 (interactive "p")
20413 (if (not (number-at-point))
20414 (user-error "Not on a number")
20415 (unless inc (setq inc 1))
20416 (let ((pos (point))
20417 (beg (skip-chars-backward "-+^/*0-9eE."))
20418 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20419 (setq nap (buffer-substring-no-properties
20420 (+ pos beg) (+ pos beg end)))
20421 (delete-region (+ pos beg) (+ pos beg end))
20422 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20423 (when (org-at-table-p)
20424 (org-table-align)
20425 (org-table-end-of-field 1))))
20427 (defun org-decrease-number-at-point (&optional inc)
20428 "Decrement the number at point.
20429 With an optional prefix numeric argument INC, decrement using
20430 this numeric value."
20431 (interactive "p")
20432 (org-increase-number-at-point (- inc)))
20434 (defun org-ctrl-c-ret ()
20435 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20436 (interactive)
20437 (cond
20438 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20439 (t (call-interactively 'org-insert-heading))))
20441 (defun org-find-visible ()
20442 (let ((s (point)))
20443 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20444 (get-char-property s 'invisible)))
20446 (defun org-find-invisible ()
20447 (let ((s (point)))
20448 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20449 (not (get-char-property s 'invisible))))
20452 (defun org-copy-visible (beg end)
20453 "Copy the visible parts of the region."
20454 (interactive "r")
20455 (let (snippets s)
20456 (save-excursion
20457 (save-restriction
20458 (narrow-to-region beg end)
20459 (setq s (goto-char (point-min)))
20460 (while (not (= (point) (point-max)))
20461 (goto-char (org-find-invisible))
20462 (push (buffer-substring s (point)) snippets)
20463 (setq s (goto-char (org-find-visible))))))
20464 (kill-new (apply 'concat (nreverse snippets)))))
20466 (defun org-copy-special ()
20467 "Copy region in table or copy current subtree.
20468 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20469 See the individual commands for more information."
20470 (interactive)
20471 (call-interactively
20472 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20474 (defun org-cut-special ()
20475 "Cut region in table or cut current subtree.
20476 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20477 See the individual commands for more information."
20478 (interactive)
20479 (call-interactively
20480 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20482 (defun org-paste-special (arg)
20483 "Paste rectangular region into table, or past subtree relative to level.
20484 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20485 See the individual commands for more information."
20486 (interactive "P")
20487 (if (org-at-table-p)
20488 (org-table-paste-rectangle)
20489 (org-paste-subtree arg)))
20491 (defsubst org-in-fixed-width-region-p ()
20492 "Is point in a fixed-width region?"
20493 (save-match-data
20494 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20496 (defun org-edit-special (&optional arg)
20497 "Call a special editor for the element at point.
20498 When at a table, call the formula editor with `org-table-edit-formulas'.
20499 When in a source code block, call `org-edit-src-code'.
20500 When in a fixed-width region, call `org-edit-fixed-width-region'.
20501 When at an #+INCLUDE keyword, visit the included file.
20502 On a link, call `ffap' to visit the link at point.
20503 Otherwise, return a user error."
20504 (interactive "P")
20505 (let ((element (org-element-at-point)))
20506 (assert (not buffer-read-only) nil
20507 "Buffer is read-only: %s" (buffer-name))
20508 (case (org-element-type element)
20509 (src-block
20510 (if (not arg) (org-edit-src-code)
20511 (let* ((info (org-babel-get-src-block-info))
20512 (lang (nth 0 info))
20513 (params (nth 2 info))
20514 (session (cdr (assq :session params))))
20515 (if (not session) (org-edit-src-code)
20516 ;; At a src-block with a session and function called with
20517 ;; an ARG: switch to the buffer related to the inferior
20518 ;; process.
20519 (switch-to-buffer
20520 (funcall (intern (concat "org-babel-prep-session:" lang))
20521 session params))))))
20522 (keyword
20523 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20524 (find-file-other-window
20525 (org-remove-double-quotes
20526 (car (org-split-string (org-element-property :value element)))))
20527 (user-error "No special environment to edit here")))
20528 (table
20529 (if (eq (org-element-property :type element) 'table.el)
20530 (org-edit-src-code)
20531 (call-interactively 'org-table-edit-formulas)))
20532 ;; Only Org tables contain `table-row' type elements.
20533 (table-row (call-interactively 'org-table-edit-formulas))
20534 ((example-block export-block) (org-edit-src-code))
20535 (fixed-width (org-edit-fixed-width-region))
20536 (otherwise
20537 ;; No notable element at point. Though, we may be at a link,
20538 ;; which is an object. Thus, scan deeper.
20539 (if (eq (org-element-type (org-element-context element)) 'link)
20540 (call-interactively 'ffap)
20541 (user-error "No special environment to edit here"))))))
20543 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20544 (defun org-ctrl-c-ctrl-c (&optional arg)
20545 "Set tags in headline, or update according to changed information at point.
20547 This command does many different things, depending on context:
20549 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20550 this is what we do.
20552 - If the cursor is on a statistics cookie, update it.
20554 - If the cursor is in a headline, prompt for tags and insert them
20555 into the current line, aligned to `org-tags-column'. When called
20556 with prefix arg, realign all tags in the current buffer.
20558 - If the cursor is in one of the special #+KEYWORD lines, this
20559 triggers scanning the buffer for these lines and updating the
20560 information.
20562 - If the cursor is inside a table, realign the table. This command
20563 works even if the automatic table editor has been turned off.
20565 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20566 the entire table.
20568 - If the cursor is at a footnote reference or definition, jump to
20569 the corresponding definition or references, respectively.
20571 - If the cursor is a the beginning of a dynamic block, update it.
20573 - If the current buffer is a capture buffer, close note and file it.
20575 - If the cursor is on a <<<target>>>, update radio targets and
20576 corresponding links in this buffer.
20578 - If the cursor is on a numbered item in a plain list, renumber the
20579 ordered list.
20581 - If the cursor is on a checkbox, toggle it.
20583 - If the cursor is on a code block, evaluate it. The variable
20584 `org-confirm-babel-evaluate' can be used to control prompting
20585 before code block evaluation, by default every code block
20586 evaluation requires confirmation. Code block evaluation can be
20587 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20588 (interactive "P")
20589 (cond
20590 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20591 org-occur-highlights)
20592 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20593 (org-remove-occur-highlights)
20594 (message "Temporary highlights/overlays removed from current buffer"))
20595 ((and (local-variable-p 'org-finish-function (current-buffer))
20596 (fboundp org-finish-function))
20597 (funcall org-finish-function))
20598 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20600 (let* ((context (org-element-context)) (type (org-element-type context)))
20601 ;; Test if point is within a blank line.
20602 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20603 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20604 (user-error "C-c C-c can do nothing useful at this location"))
20605 (case type
20606 ;; When at a link, act according to the parent instead.
20607 (link (setq context (org-element-property :parent context))
20608 (setq type (org-element-type context)))
20609 ;; Unsupported object types: refer to the first supported
20610 ;; element or object containing it.
20611 ((bold code entity export-snippet inline-babel-call inline-src-block
20612 italic latex-fragment line-break macro strike-through subscript
20613 superscript underline verbatim)
20614 (while (and (setq context (org-element-property :parent context))
20615 (not (memq (setq type (org-element-type context))
20616 '(radio-target paragraph verse-block
20617 table-cell)))))))
20618 ;; For convenience: at the first line of a paragraph on the
20619 ;; same line as an item, apply function on that item instead.
20620 (when (eq type 'paragraph)
20621 (let ((parent (org-element-property :parent context)))
20622 (when (and (eq (org-element-type parent) 'item)
20623 (= (point-at-bol) (org-element-property :begin parent)))
20624 (setq context parent type 'item))))
20625 ;; Act according to type of element or object at point.
20626 (case type
20627 (clock (org-clock-update-time-maybe))
20628 (dynamic-block
20629 (save-excursion
20630 (goto-char (org-element-property :post-affiliated context))
20631 (org-update-dblock)))
20632 (footnote-definition
20633 (goto-char (org-element-property :post-affiliated context))
20634 (call-interactively 'org-footnote-action))
20635 (footnote-reference (call-interactively 'org-footnote-action))
20636 ((headline inlinetask)
20637 (save-excursion (goto-char (org-element-property :begin context))
20638 (call-interactively 'org-set-tags)))
20639 (item
20640 ;; At an item: a double C-u set checkbox to "[-]"
20641 ;; unconditionally, whereas a single one will toggle its
20642 ;; presence. Without an universal argument, if the item
20643 ;; has a checkbox, toggle it. Otherwise repair the list.
20644 (let* ((box (org-element-property :checkbox context))
20645 (struct (org-element-property :structure context))
20646 (old-struct (copy-tree struct))
20647 (parents (org-list-parents-alist struct))
20648 (prevs (org-list-prevs-alist struct))
20649 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20650 (org-list-set-checkbox
20651 (org-element-property :begin context) struct
20652 (cond ((equal arg '(16)) "[-]")
20653 ((and (not box) (equal arg '(4))) "[ ]")
20654 ((or (not box) (equal arg '(4))) nil)
20655 ((eq box 'on) "[ ]")
20656 (t "[X]")))
20657 ;; Mimic `org-list-write-struct' but with grabbing
20658 ;; a return value from `org-list-struct-fix-box'.
20659 (org-list-struct-fix-ind struct parents 2)
20660 (org-list-struct-fix-item-end struct)
20661 (org-list-struct-fix-bul struct prevs)
20662 (org-list-struct-fix-ind struct parents)
20663 (let ((block-item
20664 (org-list-struct-fix-box struct parents prevs orderedp)))
20665 (if (and box (equal struct old-struct))
20666 (if (equal arg '(16))
20667 (message "Checkboxes already reset")
20668 (user-error "Cannot toggle this checkbox: %s"
20669 (if (eq box 'on)
20670 "all subitems checked"
20671 "unchecked subitems")))
20672 (org-list-struct-apply-struct struct old-struct)
20673 (org-update-checkbox-count-maybe))
20674 (when block-item
20675 (message "Checkboxes were removed due to empty box at line %d"
20676 (org-current-line block-item))))))
20677 (keyword
20678 (let ((org-inhibit-startup-visibility-stuff t)
20679 (org-startup-align-all-tables nil))
20680 (when (boundp 'org-table-coordinate-overlays)
20681 (mapc 'delete-overlay org-table-coordinate-overlays)
20682 (setq org-table-coordinate-overlays nil))
20683 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20684 (message "Local setup has been refreshed"))
20685 (plain-list
20686 ;; At a plain list, with a double C-u argument, set
20687 ;; checkboxes of each item to "[-]", whereas a single one
20688 ;; will toggle their presence according to the state of the
20689 ;; first item in the list. Without an argument, repair the
20690 ;; list.
20691 (let* ((begin (org-element-property :contents-begin context))
20692 (beginm (move-marker (make-marker) begin))
20693 (struct (org-element-property :structure context))
20694 (old-struct (copy-tree struct))
20695 (first-box (save-excursion
20696 (goto-char begin)
20697 (looking-at org-list-full-item-re)
20698 (match-string-no-properties 3)))
20699 (new-box (cond ((equal arg '(16)) "[-]")
20700 ((equal arg '(4)) (unless first-box "[ ]"))
20701 ((equal first-box "[X]") "[ ]")
20702 (t "[X]"))))
20703 (cond
20704 (arg
20705 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20706 (org-list-get-all-items
20707 begin struct (org-list-prevs-alist struct))))
20708 ((and first-box (eq (point) begin))
20709 ;; For convenience, when point is at bol on the first
20710 ;; item of the list and no argument is provided, simply
20711 ;; toggle checkbox of that item, if any.
20712 (org-list-set-checkbox begin struct new-box)))
20713 (org-list-write-struct
20714 struct (org-list-parents-alist struct) old-struct)
20715 (org-update-checkbox-count-maybe)
20716 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20717 ((property-drawer node-property)
20718 (call-interactively 'org-property-action))
20719 ((radio-target target)
20720 (call-interactively 'org-update-radio-target-regexp))
20721 (statistics-cookie
20722 (call-interactively 'org-update-statistics-cookies))
20723 ((table table-cell table-row)
20724 ;; At a table, recalculate every field and align it. Also
20725 ;; send the table if necessary. If the table has
20726 ;; a `table.el' type, just give up. At a table row or
20727 ;; cell, maybe recalculate line but always align table.
20728 (if (eq (org-element-property :type context) 'table.el)
20729 (message "Use C-c ' to edit table.el tables")
20730 (let ((org-enable-table-editor t))
20731 (if (or (eq type 'table)
20732 ;; Check if point is at a TBLFM line.
20733 (and (eq type 'table-row)
20734 (= (point) (org-element-property :end context))))
20735 (save-excursion
20736 (if (org-at-TBLFM-p)
20737 (progn (require 'org-table)
20738 (org-table-calc-current-TBLFM))
20739 (goto-char (org-element-property :contents-begin context))
20740 (org-call-with-arg 'org-table-recalculate (or arg t))
20741 (orgtbl-send-table 'maybe)))
20742 (org-table-maybe-eval-formula)
20743 (cond (arg (call-interactively 'org-table-recalculate))
20744 ((org-table-maybe-recalculate-line))
20745 (t (org-table-align)))))))
20746 (timestamp (org-timestamp-change 0 'day))
20747 (otherwise
20748 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20749 (user-error
20750 "C-c C-c can do nothing useful at this location")))))))))
20752 (defun org-mode-restart ()
20753 (interactive)
20754 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20755 (funcall major-mode)
20756 (hack-local-variables)
20757 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20758 (org-indent-mode -1)))
20759 (message "%s restarted" major-mode))
20761 (defun org-kill-note-or-show-branches ()
20762 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20763 (interactive)
20764 (if (not org-finish-function)
20765 (progn
20766 (hide-subtree)
20767 (call-interactively 'show-branches))
20768 (let ((org-note-abort t))
20769 (funcall org-finish-function))))
20771 (defun org-open-line (n)
20772 "Insert a new row in tables, call `open-line' elsewhere.
20773 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20774 (interactive "*p")
20775 (cond
20776 ((not org-special-ctrl-o)
20777 (open-line n))
20778 ((org-at-table-p)
20779 (org-table-insert-row))
20781 (open-line n))))
20783 (defun org-return (&optional indent)
20784 "Goto next table row or insert a newline.
20785 Calls `org-table-next-row' or `newline', depending on context.
20786 See the individual commands for more information."
20787 (interactive)
20788 (let (org-ts-what)
20789 (cond
20790 ((or (bobp) (org-in-src-block-p))
20791 (if indent (newline-and-indent) (newline)))
20792 ((org-at-table-p)
20793 (org-table-justify-field-maybe)
20794 (call-interactively 'org-table-next-row))
20795 ;; when `newline-and-indent' is called within a list, make sure
20796 ;; text moved stays inside the item.
20797 ((and (org-in-item-p) indent)
20798 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20799 (progn
20800 (save-match-data (newline))
20801 (org-indent-line-to (length (match-string 0))))
20802 (let ((ind (org-get-indentation)))
20803 (newline)
20804 (if (org-looking-back org-list-end-re)
20805 (org-indent-line)
20806 (org-indent-line-to ind)))))
20807 ((and org-return-follows-link
20808 (org-at-timestamp-p t)
20809 (not (eq org-ts-what 'after)))
20810 (org-follow-timestamp-link))
20811 ((and org-return-follows-link
20812 (let ((tprop (get-text-property (point) 'face)))
20813 (or (eq tprop 'org-link)
20814 (and (listp tprop) (memq 'org-link tprop)))))
20815 (call-interactively 'org-open-at-point))
20816 ((and (org-at-heading-p)
20817 (looking-at
20818 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20819 (org-show-entry)
20820 (end-of-line 1)
20821 (newline))
20822 (t (if indent (newline-and-indent) (newline))))))
20824 (defun org-return-indent ()
20825 "Goto next table row or insert a newline and indent.
20826 Calls `org-table-next-row' or `newline-and-indent', depending on
20827 context. See the individual commands for more information."
20828 (interactive)
20829 (org-return t))
20831 (defun org-ctrl-c-star ()
20832 "Compute table, or change heading status of lines.
20833 Calls `org-table-recalculate' or `org-toggle-heading',
20834 depending on context."
20835 (interactive)
20836 (cond
20837 ((org-at-table-p)
20838 (call-interactively 'org-table-recalculate))
20840 ;; Convert all lines in region to list items
20841 (call-interactively 'org-toggle-heading))))
20843 (defun org-ctrl-c-minus ()
20844 "Insert separator line in table or modify bullet status of line.
20845 Also turns a plain line or a region of lines into list items.
20846 Calls `org-table-insert-hline', `org-toggle-item', or
20847 `org-cycle-list-bullet', depending on context."
20848 (interactive)
20849 (cond
20850 ((org-at-table-p)
20851 (call-interactively 'org-table-insert-hline))
20852 ((org-region-active-p)
20853 (call-interactively 'org-toggle-item))
20854 ((org-in-item-p)
20855 (call-interactively 'org-cycle-list-bullet))
20857 (call-interactively 'org-toggle-item))))
20859 (defun org-toggle-item (arg)
20860 "Convert headings or normal lines to items, items to normal lines.
20861 If there is no active region, only the current line is considered.
20863 If the first non blank line in the region is a headline, convert
20864 all headlines to items, shifting text accordingly.
20866 If it is an item, convert all items to normal lines.
20868 If it is normal text, change region into a list of items.
20869 With a prefix argument ARG, change the region in a single item."
20870 (interactive "P")
20871 (let ((shift-text
20872 (function
20873 ;; Shift text in current section to IND, from point to END.
20874 ;; The function leaves point to END line.
20875 (lambda (ind end)
20876 (let ((min-i 1000) (end (copy-marker end)))
20877 ;; First determine the minimum indentation (MIN-I) of
20878 ;; the text.
20879 (save-excursion
20880 (catch 'exit
20881 (while (< (point) end)
20882 (let ((i (org-get-indentation)))
20883 (cond
20884 ;; Skip blank lines and inline tasks.
20885 ((looking-at "^[ \t]*$"))
20886 ((looking-at org-outline-regexp-bol))
20887 ;; We can't find less than 0 indentation.
20888 ((zerop i) (throw 'exit (setq min-i 0)))
20889 ((< i min-i) (setq min-i i))))
20890 (forward-line))))
20891 ;; Then indent each line so that a line indented to
20892 ;; MIN-I becomes indented to IND. Ignore blank lines
20893 ;; and inline tasks in the process.
20894 (let ((delta (- ind min-i)))
20895 (while (< (point) end)
20896 (unless (or (looking-at "^[ \t]*$")
20897 (looking-at org-outline-regexp-bol))
20898 (org-indent-line-to (+ (org-get-indentation) delta)))
20899 (forward-line)))))))
20900 (skip-blanks
20901 (function
20902 ;; Return beginning of first non-blank line, starting from
20903 ;; line at POS.
20904 (lambda (pos)
20905 (save-excursion
20906 (goto-char pos)
20907 (skip-chars-forward " \r\t\n")
20908 (point-at-bol)))))
20909 beg end)
20910 ;; Determine boundaries of changes.
20911 (if (org-region-active-p)
20912 (setq beg (funcall skip-blanks (region-beginning))
20913 end (copy-marker (region-end)))
20914 (setq beg (funcall skip-blanks (point-at-bol))
20915 end (copy-marker (point-at-eol))))
20916 ;; Depending on the starting line, choose an action on the text
20917 ;; between BEG and END.
20918 (org-with-limited-levels
20919 (save-excursion
20920 (goto-char beg)
20921 (cond
20922 ;; Case 1. Start at an item: de-itemize. Note that it only
20923 ;; happens when a region is active: `org-ctrl-c-minus'
20924 ;; would call `org-cycle-list-bullet' otherwise.
20925 ((org-at-item-p)
20926 (while (< (point) end)
20927 (when (org-at-item-p)
20928 (skip-chars-forward " \t")
20929 (delete-region (point) (match-end 0)))
20930 (forward-line)))
20931 ;; Case 2. Start at an heading: convert to items.
20932 ((org-at-heading-p)
20933 (let* ((bul (org-list-bullet-string "-"))
20934 (bul-len (length bul))
20935 (done (org-entry-is-done-p))
20936 (todo (org-entry-is-todo-p))
20937 ;; Indentation of the first heading. It should be
20938 ;; relative to the indentation of its parent, if any.
20939 (start-ind (save-excursion
20940 (cond
20941 ((not org-adapt-indentation) 0)
20942 ((not (outline-previous-heading)) 0)
20943 (t (length (match-string 0))))))
20944 ;; Level of first heading. Further headings will be
20945 ;; compared to it to determine hierarchy in the list.
20946 (ref-level (org-reduced-level (org-outline-level))))
20947 (when (or done todo) (org-todo ""))
20948 (while (< (point) end)
20949 (let* ((level (org-reduced-level (org-outline-level)))
20950 (delta (max 0 (- level ref-level))))
20951 ;; If current headline is less indented than the first
20952 ;; one, set it as reference, in order to preserve
20953 ;; subtrees.
20954 (when (< level ref-level) (setq ref-level level))
20955 (replace-match bul t t)
20956 (org-indent-line-to (+ start-ind (* delta bul-len)))
20957 (when (or done todo)
20958 (let* ((struct (org-list-struct))
20959 (old (copy-tree struct)))
20960 (org-list-set-checkbox (line-beginning-position)
20961 struct
20962 (if done "[X]" "[ ]"))
20963 (org-list-write-struct struct
20964 (org-list-parents-alist struct)
20965 old)))
20966 ;; Ensure all text down to END (or SECTION-END) belongs
20967 ;; to the newly created item.
20968 (let ((section-end (save-excursion
20969 (or (outline-next-heading) (point)))))
20970 (forward-line)
20971 (funcall shift-text
20972 (+ start-ind (* (1+ delta) bul-len))
20973 (min end section-end)))))))
20974 ;; Case 3. Normal line with ARG: make the first line of region
20975 ;; an item, and shift indentation of others lines to
20976 ;; set them as item's body.
20977 (arg (let* ((bul (org-list-bullet-string "-"))
20978 (bul-len (length bul))
20979 (ref-ind (org-get-indentation)))
20980 (skip-chars-forward " \t")
20981 (insert bul)
20982 (forward-line)
20983 (while (< (point) end)
20984 ;; Ensure that lines less indented than first one
20985 ;; still get included in item body.
20986 (funcall shift-text
20987 (+ ref-ind bul-len)
20988 (min end (save-excursion (or (outline-next-heading)
20989 (point)))))
20990 (forward-line))))
20991 ;; Case 4. Normal line without ARG: turn each non-item line
20992 ;; into an item.
20994 (while (< (point) end)
20995 (unless (or (org-at-heading-p) (org-at-item-p))
20996 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20997 (replace-match
20998 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20999 (forward-line))))))))
21001 (defun org-toggle-heading (&optional nstars)
21002 "Convert headings to normal text, or items or text to headings.
21003 If there is no active region, only convert the current line.
21005 With a \\[universal-argument] prefix, convert the whole list at
21006 point into heading.
21008 In a region:
21010 - If the first non blank line is a headline, remove the stars
21011 from all headlines in the region.
21013 - If it is a normal line, turn each and every normal line (i.e.,
21014 not an heading or an item) in the region into headings. If you
21015 want to convert only the first line of this region, use one
21016 universal prefix argument.
21018 - If it is a plain list item, turn all plain list items into headings.
21020 When converting a line into a heading, the number of stars is chosen
21021 such that the lines become children of the current entry. However,
21022 when a numeric prefix argument is given, its value determines the
21023 number of stars to add."
21024 (interactive "P")
21025 (let ((skip-blanks
21026 (function
21027 ;; Return beginning of first non-blank line, starting from
21028 ;; line at POS.
21029 (lambda (pos)
21030 (save-excursion
21031 (goto-char pos)
21032 (while (org-at-comment-p) (forward-line))
21033 (skip-chars-forward " \r\t\n")
21034 (point-at-bol)))))
21035 beg end toggled)
21036 ;; Determine boundaries of changes. If a universal prefix has
21037 ;; been given, put the list in a region. If region ends at a bol,
21038 ;; do not consider the last line to be in the region.
21040 (when (and current-prefix-arg (org-at-item-p))
21041 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21042 (org-mark-element))
21044 (if (org-region-active-p)
21045 (setq beg (funcall skip-blanks (region-beginning))
21046 end (copy-marker (save-excursion
21047 (goto-char (region-end))
21048 (if (bolp) (point) (point-at-eol)))))
21049 (setq beg (funcall skip-blanks (point-at-bol))
21050 end (copy-marker (point-at-eol))))
21051 ;; Ensure inline tasks don't count as headings.
21052 (org-with-limited-levels
21053 (save-excursion
21054 (goto-char beg)
21055 (cond
21056 ;; Case 1. Started at an heading: de-star headings.
21057 ((org-at-heading-p)
21058 (while (< (point) end)
21059 (when (org-at-heading-p t)
21060 (looking-at org-outline-regexp) (replace-match "")
21061 (setq toggled t))
21062 (forward-line)))
21063 ;; Case 2. Started at an item: change items into headlines.
21064 ;; One star will be added by `org-list-to-subtree'.
21065 ((org-at-item-p)
21066 (let* ((stars (make-string
21067 ;; subtract the star that will be added again by
21068 ;; `org-list-to-subtree'
21069 (if (numberp nstars) (1- nstars)
21070 (or (org-current-level) 0))
21071 ?*))
21072 (add-stars
21073 (cond (nstars "") ; stars from prefix only
21074 ((equal stars "") "") ; before first heading
21075 (org-odd-levels-only "*") ; inside heading, odd
21076 (t "")))) ; inside heading, oddeven
21077 (while (< (point) end)
21078 (when (org-at-item-p)
21079 ;; Pay attention to cases when region ends before list.
21080 (let* ((struct (org-list-struct))
21081 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21082 (save-restriction
21083 (narrow-to-region (point) list-end)
21084 (insert
21085 (org-list-to-subtree
21086 (org-list-parse-list t)
21087 '(:istart (concat stars add-stars (funcall get-stars depth))
21088 :icount (concat stars add-stars (funcall get-stars depth)))))))
21089 (setq toggled t))
21090 (forward-line))))
21091 ;; Case 3. Started at normal text: make every line an heading,
21092 ;; skipping headlines and items.
21093 (t (let* ((stars
21094 (make-string
21095 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21096 (add-stars
21097 (cond (nstars "") ; stars from prefix only
21098 ((equal stars "") "*") ; before first heading
21099 (org-odd-levels-only "**") ; inside heading, odd
21100 (t "*"))) ; inside heading, oddeven
21101 (rpl (concat stars add-stars " "))
21102 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21103 (while (< (point) (if (equal nstars '(4)) lend end))
21104 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21105 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21106 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21107 (forward-line)))))))
21108 (unless toggled (message "Cannot toggle heading from here"))))
21110 (defun org-meta-return (&optional arg)
21111 "Insert a new heading or wrap a region in a table.
21112 Calls `org-insert-heading' or `org-table-wrap-region', depending
21113 on context. See the individual commands for more information."
21114 (interactive "P")
21115 (org-check-before-invisible-edit 'insert)
21116 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21117 (let* ((element (org-element-at-point))
21118 (type (org-element-type element)))
21119 (when (eq type 'table-row)
21120 (setq element (org-element-property :parent element))
21121 (setq type 'table))
21122 (if (and (eq type 'table)
21123 (eq (org-element-property :type element) 'org)
21124 (>= (point) (org-element-property :contents-begin element))
21125 (< (point) (org-element-property :contents-end element)))
21126 (call-interactively 'org-table-wrap-region)
21127 (call-interactively 'org-insert-heading)))))
21129 ;;; Menu entries
21131 (defsubst org-in-subtree-not-table-p ()
21132 "Are we in a subtree and not in a table?"
21133 (and (not (org-before-first-heading-p))
21134 (not (org-at-table-p))))
21136 ;; Define the Org-mode menus
21137 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21138 '("Tbl"
21139 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21140 ["Next Field" org-cycle (org-at-table-p)]
21141 ["Previous Field" org-shifttab (org-at-table-p)]
21142 ["Next Row" org-return (org-at-table-p)]
21143 "--"
21144 ["Blank Field" org-table-blank-field (org-at-table-p)]
21145 ["Edit Field" org-table-edit-field (org-at-table-p)]
21146 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21147 "--"
21148 ("Column"
21149 ["Move Column Left" org-metaleft (org-at-table-p)]
21150 ["Move Column Right" org-metaright (org-at-table-p)]
21151 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21152 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21153 ["Ascii plot" orgtbl-ascii-plot (org-at-table-p)])
21154 ("Row"
21155 ["Move Row Up" org-metaup (org-at-table-p)]
21156 ["Move Row Down" org-metadown (org-at-table-p)]
21157 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21158 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21159 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21160 "--"
21161 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21162 ("Rectangle"
21163 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21164 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21165 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21166 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21167 "--"
21168 ("Calculate"
21169 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21170 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21171 ["Edit Formulas" org-edit-special (org-at-table-p)]
21172 "--"
21173 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21174 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21175 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21176 "--"
21177 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21178 "--"
21179 ["Sum Column/Rectangle" org-table-sum
21180 (or (org-at-table-p) (org-region-active-p))]
21181 ["Which Column?" org-table-current-column (org-at-table-p)])
21182 ["Debug Formulas"
21183 org-table-toggle-formula-debugger
21184 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21185 ["Show Col/Row Numbers"
21186 org-table-toggle-coordinate-overlays
21187 :style toggle
21188 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21189 "--"
21190 ["Create" org-table-create (and (not (org-at-table-p))
21191 org-enable-table-editor)]
21192 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21193 ["Import from File" org-table-import (not (org-at-table-p))]
21194 ["Export to File" org-table-export (org-at-table-p)]
21195 "--"
21196 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21198 (easy-menu-define org-org-menu org-mode-map "Org menu"
21199 '("Org"
21200 ("Show/Hide"
21201 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21202 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21203 ["Sparse Tree..." org-sparse-tree t]
21204 ["Reveal Context" org-reveal t]
21205 ["Show All" show-all t]
21206 "--"
21207 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21208 "--"
21209 ["New Heading" org-insert-heading t]
21210 ("Navigate Headings"
21211 ["Up" outline-up-heading t]
21212 ["Next" outline-next-visible-heading t]
21213 ["Previous" outline-previous-visible-heading t]
21214 ["Next Same Level" outline-forward-same-level t]
21215 ["Previous Same Level" outline-backward-same-level t]
21216 "--"
21217 ["Jump" org-goto t])
21218 ("Edit Structure"
21219 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21220 "--"
21221 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21222 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21223 "--"
21224 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21225 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21226 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21227 "--"
21228 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21229 "--"
21230 ["Copy visible text" org-copy-visible t]
21231 "--"
21232 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21233 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21234 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21235 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21236 "--"
21237 ["Sort Region/Children" org-sort t]
21238 "--"
21239 ["Convert to odd levels" org-convert-to-odd-levels t]
21240 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21241 ("Editing"
21242 ["Emphasis..." org-emphasize t]
21243 ["Edit Source Example" org-edit-special t]
21244 "--"
21245 ["Footnote new/jump" org-footnote-action t]
21246 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21247 ("Archive"
21248 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21249 "--"
21250 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21251 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21252 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21254 "--"
21255 ("Hyperlinks"
21256 ["Store Link (Global)" org-store-link t]
21257 ["Find existing link to here" org-occur-link-in-agenda-files t]
21258 ["Insert Link" org-insert-link t]
21259 ["Follow Link" org-open-at-point t]
21260 "--"
21261 ["Next link" org-next-link t]
21262 ["Previous link" org-previous-link t]
21263 "--"
21264 ["Descriptive Links"
21265 org-toggle-link-display
21266 :style radio
21267 :selected org-descriptive-links
21269 ["Literal Links"
21270 org-toggle-link-display
21271 :style radio
21272 :selected (not org-descriptive-links)])
21273 "--"
21274 ("TODO Lists"
21275 ["TODO/DONE/-" org-todo t]
21276 ("Select keyword"
21277 ["Next keyword" org-shiftright (org-at-heading-p)]
21278 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21279 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21280 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21281 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21282 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21283 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21284 "--"
21285 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21286 :selected org-enforce-todo-dependencies :style toggle :active t]
21287 "Settings for tree at point"
21288 ["Do Children sequentially" org-toggle-ordered-property :style radio
21289 :selected (org-entry-get nil "ORDERED")
21290 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21291 ["Do Children parallel" org-toggle-ordered-property :style radio
21292 :selected (not (org-entry-get nil "ORDERED"))
21293 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21294 "--"
21295 ["Set Priority" org-priority t]
21296 ["Priority Up" org-shiftup t]
21297 ["Priority Down" org-shiftdown t]
21298 "--"
21299 ["Get news from all feeds" org-feed-update-all t]
21300 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21301 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21302 ("TAGS and Properties"
21303 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21304 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21305 "--"
21306 ["Set property" org-set-property (not (org-before-first-heading-p))]
21307 ["Column view of properties" org-columns t]
21308 ["Insert Column View DBlock" org-insert-columns-dblock t])
21309 ("Dates and Scheduling"
21310 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21311 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21312 ("Change Date"
21313 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21314 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21315 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21316 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21317 ["Compute Time Range" org-evaluate-time-range t]
21318 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21319 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21320 "--"
21321 ["Custom time format" org-toggle-time-stamp-overlays
21322 :style radio :selected org-display-custom-times]
21323 "--"
21324 ["Goto Calendar" org-goto-calendar t]
21325 ["Date from Calendar" org-date-from-calendar t]
21326 "--"
21327 ["Start/Restart Timer" org-timer-start t]
21328 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21329 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21330 ["Insert Timer String" org-timer t]
21331 ["Insert Timer Item" org-timer-item t])
21332 ("Logging work"
21333 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21334 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21335 ["Clock out" org-clock-out t]
21336 ["Clock cancel" org-clock-cancel t]
21337 "--"
21338 ["Mark as default task" org-clock-mark-default-task t]
21339 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21340 ["Goto running clock" org-clock-goto t]
21341 "--"
21342 ["Display times" org-clock-display t]
21343 ["Create clock table" org-clock-report t]
21344 "--"
21345 ["Record DONE time"
21346 (progn (setq org-log-done (not org-log-done))
21347 (message "Switching to %s will %s record a timestamp"
21348 (car org-done-keywords)
21349 (if org-log-done "automatically" "not")))
21350 :style toggle :selected org-log-done])
21351 "--"
21352 ["Agenda Command..." org-agenda t]
21353 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21354 ("File List for Agenda")
21355 ("Special views current file"
21356 ["TODO Tree" org-show-todo-tree t]
21357 ["Check Deadlines" org-check-deadlines t]
21358 ["Timeline" org-timeline t]
21359 ["Tags/Property tree" org-match-sparse-tree t])
21360 "--"
21361 ["Export/Publish..." org-export-dispatch t]
21362 ("LaTeX"
21363 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21364 :selected org-cdlatex-mode]
21365 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21366 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21367 ["Modify math symbol" org-cdlatex-math-modify
21368 (org-inside-LaTeX-fragment-p)]
21369 ["Insert citation" org-reftex-citation t]
21370 "--"
21371 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21372 "--"
21373 ("MobileOrg"
21374 ["Push Files and Views" org-mobile-push t]
21375 ["Get Captured and Flagged" org-mobile-pull t]
21376 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21377 "--"
21378 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21379 "--"
21380 ("Documentation"
21381 ["Show Version" org-version t]
21382 ["Info Documentation" org-info t])
21383 ("Customize"
21384 ["Browse Org Group" org-customize t]
21385 "--"
21386 ["Expand This Menu" org-create-customize-menu
21387 (fboundp 'customize-menu-create)])
21388 ["Send bug report" org-submit-bug-report t]
21389 "--"
21390 ("Refresh/Reload"
21391 ["Refresh setup current buffer" org-mode-restart t]
21392 ["Reload Org (after update)" org-reload t]
21393 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21396 (defun org-info (&optional node)
21397 "Read documentation for Org-mode in the info system.
21398 With optional NODE, go directly to that node."
21399 (interactive)
21400 (info (format "(org)%s" (or node ""))))
21402 ;;;###autoload
21403 (defun org-submit-bug-report ()
21404 "Submit a bug report on Org-mode via mail.
21406 Don't hesitate to report any problems or inaccurate documentation.
21408 If you don't have setup sending mail from (X)Emacs, please copy the
21409 output buffer into your mail program, as it gives us important
21410 information about your Org-mode version and configuration."
21411 (interactive)
21412 (require 'reporter)
21413 (org-load-modules-maybe)
21414 (org-require-autoloaded-modules)
21415 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21416 (reporter-submit-bug-report
21417 "emacs-orgmode@gnu.org"
21418 (org-version nil 'full)
21419 (let (list)
21420 (save-window-excursion
21421 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21422 (delete-other-windows)
21423 (erase-buffer)
21424 (insert "You are about to submit a bug report to the Org-mode mailing list.
21426 We would like to add your full Org-mode and Outline configuration to the
21427 bug report. This greatly simplifies the work of the maintainer and
21428 other experts on the mailing list.
21430 HOWEVER, some variables you have customized may contain private
21431 information. The names of customers, colleagues, or friends, might
21432 appear in the form of file names, tags, todo states, or search strings.
21433 If you answer yes to the prompt, you might want to check and remove
21434 such private information before sending the email.")
21435 (add-text-properties (point-min) (point-max) '(face org-warning))
21436 (when (yes-or-no-p "Include your Org-mode configuration ")
21437 (mapatoms
21438 (lambda (v)
21439 (and (boundp v)
21440 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21441 (or (and (symbol-value v)
21442 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21443 (and
21444 (get v 'custom-type) (get v 'standard-value)
21445 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21446 (push v list)))))
21447 (kill-buffer (get-buffer "*Warn about privacy*"))
21448 list))
21449 nil nil
21450 "Remember to cover the basics, that is, what you expected to happen and
21451 what in fact did happen. You don't know how to make a good report? See
21453 http://orgmode.org/manual/Feedback.html#Feedback
21455 Your bug report will be posted to the Org-mode mailing list.
21456 ------------------------------------------------------------------------")
21457 (save-excursion
21458 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21459 (replace-match "\\1Bug: \\3 [\\2]")))))
21462 (defun org-install-agenda-files-menu ()
21463 (let ((bl (buffer-list)))
21464 (save-excursion
21465 (while bl
21466 (set-buffer (pop bl))
21467 (if (derived-mode-p 'org-mode) (setq bl nil)))
21468 (when (derived-mode-p 'org-mode)
21469 (easy-menu-change
21470 '("Org") "File List for Agenda"
21471 (append
21472 (list
21473 ["Edit File List" (org-edit-agenda-file-list) t]
21474 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21475 ["Remove Current File from List" org-remove-file t]
21476 ["Cycle through agenda files" org-cycle-agenda-files t]
21477 ["Occur in all agenda files" org-occur-in-agenda-files t]
21478 "--")
21479 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21481 ;;;; Documentation
21483 (defun org-require-autoloaded-modules ()
21484 (interactive)
21485 (mapc 'require
21486 '(org-agenda org-archive org-attach org-clock org-colview org-id
21487 org-table org-timer)))
21489 ;;;###autoload
21490 (defun org-reload (&optional uncompiled)
21491 "Reload all org lisp files.
21492 With prefix arg UNCOMPILED, load the uncompiled versions."
21493 (interactive "P")
21494 (require 'loadhist)
21495 (let* ((org-dir (org-find-library-dir "org"))
21496 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21497 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21498 (remove-re (mapconcat 'identity
21499 (mapcar (lambda (f) (concat "^" f "$"))
21500 (list (if (featurep 'xemacs)
21501 "org-colview"
21502 "org-colview-xemacs")
21503 "org" "org-loaddefs" "org-version"))
21504 "\\|"))
21505 (feats (delete-dups
21506 (mapcar 'file-name-sans-extension
21507 (mapcar 'file-name-nondirectory
21508 (delq nil
21509 (mapcar 'feature-file
21510 features))))))
21511 (lfeat (append
21512 (sort
21513 (setq feats
21514 (delq nil (mapcar
21515 (lambda (f)
21516 (if (and (string-match feature-re f)
21517 (not (string-match remove-re f)))
21518 f nil))
21519 feats)))
21520 'string-lessp)
21521 (list "org-version" "org")))
21522 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21523 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21524 load-uncore load-misses)
21525 (setq load-misses
21526 (delq 't
21527 (mapcar (lambda (f)
21528 (or (org-load-noerror-mustsuffix (concat org-dir f))
21529 (and (string= org-dir contrib-dir)
21530 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21531 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21532 (add-to-list 'load-uncore f 'append)
21535 lfeat)))
21536 (if load-uncore
21537 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21538 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21539 (if load-misses
21540 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21541 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21542 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21544 ;;;###autoload
21545 (defun org-customize ()
21546 "Call the customize function with org as argument."
21547 (interactive)
21548 (org-load-modules-maybe)
21549 (org-require-autoloaded-modules)
21550 (customize-browse 'org))
21552 (defun org-create-customize-menu ()
21553 "Create a full customization menu for Org-mode, insert it into the menu."
21554 (interactive)
21555 (org-load-modules-maybe)
21556 (org-require-autoloaded-modules)
21557 (if (fboundp 'customize-menu-create)
21558 (progn
21559 (easy-menu-change
21560 '("Org") "Customize"
21561 `(["Browse Org group" org-customize t]
21562 "--"
21563 ,(customize-menu-create 'org)
21564 ["Set" Custom-set t]
21565 ["Save" Custom-save t]
21566 ["Reset to Current" Custom-reset-current t]
21567 ["Reset to Saved" Custom-reset-saved t]
21568 ["Reset to Standard Settings" Custom-reset-standard t]))
21569 (message "\"Org\"-menu now contains full customization menu"))
21570 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21572 ;;;; Miscellaneous stuff
21574 ;;; Generally useful functions
21576 (defsubst org-get-at-eol (property n)
21577 "Get text property PROPERTY at the end of line less N characters."
21578 (get-text-property (- (point-at-eol) n) property))
21580 (defun org-find-text-property-in-string (prop s)
21581 "Return the first non-nil value of property PROP in string S."
21582 (or (get-text-property 0 prop s)
21583 (get-text-property (or (next-single-property-change 0 prop s) 0)
21584 prop s)))
21586 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21587 "Display the given MESSAGE as a warning."
21588 (if (fboundp 'display-warning)
21589 (display-warning 'org message
21590 (if (featurep 'xemacs) 'warning :warning))
21591 (let ((buf (get-buffer-create "*Org warnings*")))
21592 (with-current-buffer buf
21593 (goto-char (point-max))
21594 (insert "Warning (Org): " message)
21595 (unless (bolp)
21596 (newline)))
21597 (display-buffer buf)
21598 (sit-for 0))))
21600 (defun org-eval (form)
21601 "Eval FORM and return result."
21602 (condition-case error
21603 (eval form)
21604 (error (format "%%![Error: %s]" error))))
21606 (defun org-in-clocktable-p ()
21607 "Check if the cursor is in a clocktable."
21608 (let ((pos (point)) start)
21609 (save-excursion
21610 (end-of-line 1)
21611 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21612 (setq start (match-beginning 0))
21613 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21614 (>= (match-end 0) pos)
21615 start))))
21617 (defun org-in-verbatim-emphasis ()
21618 (save-match-data
21619 (and (org-in-regexp org-emph-re 2)
21620 (>= (point) (match-beginning 3))
21621 (<= (point) (match-end 4))
21622 (member (match-string 3) '("=" "~")))))
21624 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21625 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21626 (if (and marker (marker-buffer marker)
21627 (buffer-live-p (marker-buffer marker)))
21628 (progn
21629 (org-pop-to-buffer-same-window (marker-buffer marker))
21630 (if (or (> marker (point-max)) (< marker (point-min)))
21631 (widen))
21632 (goto-char marker)
21633 (org-show-context 'org-goto))
21634 (if bookmark
21635 (bookmark-jump bookmark)
21636 (error "Cannot find location"))))
21638 (defun org-quote-csv-field (s)
21639 "Quote field for inclusion in CSV material."
21640 (if (string-match "[\",]" s)
21641 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21644 (defun org-force-self-insert (N)
21645 "Needed to enforce self-insert under remapping."
21646 (interactive "p")
21647 (self-insert-command N))
21649 (defun org-string-width (s)
21650 "Compute width of string, ignoring invisible characters.
21651 This ignores character with invisibility property `org-link', and also
21652 characters with property `org-cwidth', because these will become invisible
21653 upon the next fontification round."
21654 (let (b l)
21655 (when (or (eq t buffer-invisibility-spec)
21656 (assq 'org-link buffer-invisibility-spec))
21657 (while (setq b (text-property-any 0 (length s)
21658 'invisible 'org-link s))
21659 (setq s (concat (substring s 0 b)
21660 (substring s (or (next-single-property-change
21661 b 'invisible s) (length s)))))))
21662 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21663 (setq s (concat (substring s 0 b)
21664 (substring s (or (next-single-property-change
21665 b 'org-cwidth s) (length s))))))
21666 (setq l (string-width s) b -1)
21667 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21668 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21671 (defun org-shorten-string (s maxlength)
21672 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21673 If the string is shorter or has length MAXLENGTH, just return the
21674 original string. If it is longer, the functions finds a space in the
21675 string, breaks this string off at that locations and adds three dots
21676 as ellipsis. Including the ellipsis, the string will not be longer
21677 than MAXLENGTH. If finding a good breaking point in the string does
21678 not work, the string is just chopped off in the middle of a word
21679 if necessary."
21680 (if (<= (length s) maxlength)
21682 (let* ((n (max (- maxlength 4) 1))
21683 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21684 (if (string-match re s)
21685 (concat (match-string 1 s) "...")
21686 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21688 (defun org-get-indentation (&optional line)
21689 "Get the indentation of the current line, interpreting tabs.
21690 When LINE is given, assume it represents a line and compute its indentation."
21691 (if line
21692 (if (string-match "^ *" (org-remove-tabs line))
21693 (match-end 0))
21694 (save-excursion
21695 (beginning-of-line 1)
21696 (skip-chars-forward " \t")
21697 (current-column))))
21699 (defun org-get-string-indentation (s)
21700 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21701 (let ((n -1) (i 0) (w tab-width) c)
21702 (catch 'exit
21703 (while (< (setq n (1+ n)) (length s))
21704 (setq c (aref s n))
21705 (cond ((= c ?\ ) (setq i (1+ i)))
21706 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21707 (t (throw 'exit t)))))
21710 (defun org-remove-tabs (s &optional width)
21711 "Replace tabulators in S with spaces.
21712 Assumes that s is a single line, starting in column 0."
21713 (setq width (or width tab-width))
21714 (while (string-match "\t" s)
21715 (setq s (replace-match
21716 (make-string
21717 (- (* width (/ (+ (match-beginning 0) width) width))
21718 (match-beginning 0)) ?\ )
21719 t t s)))
21722 (defun org-fix-indentation (line ind)
21723 "Fix indentation in LINE.
21724 IND is a cons cell with target and minimum indentation.
21725 If the current indentation in LINE is smaller than the minimum,
21726 leave it alone. If it is larger than ind, set it to the target."
21727 (let* ((l (org-remove-tabs line))
21728 (i (org-get-indentation l))
21729 (i1 (car ind)) (i2 (cdr ind)))
21730 (if (>= i i2) (setq l (substring line i2)))
21731 (if (> i1 0)
21732 (concat (make-string i1 ?\ ) l)
21733 l)))
21735 (defun org-remove-indentation (code &optional n)
21736 "Remove the maximum common indentation from the lines in CODE.
21737 N may optionally be the number of spaces to remove."
21738 (with-temp-buffer
21739 (insert code)
21740 (org-do-remove-indentation n)
21741 (buffer-string)))
21743 (defun org-do-remove-indentation (&optional n)
21744 "Remove the maximum common indentation from the buffer."
21745 (untabify (point-min) (point-max))
21746 (let ((min 10000) re)
21747 (if n
21748 (setq min n)
21749 (goto-char (point-min))
21750 (while (re-search-forward "^ *[^ \n]" nil t)
21751 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21752 (unless (or (= min 0) (= min 10000))
21753 (setq re (format "^ \\{%d\\}" min))
21754 (goto-char (point-min))
21755 (while (re-search-forward re nil t)
21756 (replace-match "")
21757 (end-of-line 1))
21758 min)))
21760 (defun org-fill-template (template alist)
21761 "Find each %key of ALIST in TEMPLATE and replace it."
21762 (let ((case-fold-search nil)
21763 entry key value)
21764 (setq alist (sort (copy-sequence alist)
21765 (lambda (a b) (< (length (car a)) (length (car b))))))
21766 (while (setq entry (pop alist))
21767 (setq template
21768 (replace-regexp-in-string
21769 (concat "%" (regexp-quote (car entry)))
21770 (or (cdr entry) "") template t t)))
21771 template))
21773 (defun org-base-buffer (buffer)
21774 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21775 (if (not buffer)
21776 buffer
21777 (or (buffer-base-buffer buffer)
21778 buffer)))
21780 (defun org-wrap (string &optional width lines)
21781 "Wrap string to either a number of lines, or a width in characters.
21782 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21783 that costs. If there is a word longer than WIDTH, the text is actually
21784 wrapped to the length of that word.
21785 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21786 many lines, whatever width that takes.
21787 The return value is a list of lines, without newlines at the end."
21788 (let* ((words (org-split-string string "[ \t\n]+"))
21789 (maxword (apply 'max (mapcar 'org-string-width words)))
21790 w ll)
21791 (cond (width
21792 (org-do-wrap words (max maxword width)))
21793 (lines
21794 (setq w maxword)
21795 (setq ll (org-do-wrap words maxword))
21796 (if (<= (length ll) lines)
21798 (setq ll words)
21799 (while (> (length ll) lines)
21800 (setq w (1+ w))
21801 (setq ll (org-do-wrap words w)))
21802 ll))
21803 (t (error "Cannot wrap this")))))
21805 (defun org-do-wrap (words width)
21806 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21807 (let (lines line)
21808 (while words
21809 (setq line (pop words))
21810 (while (and words (< (+ (length line) (length (car words))) width))
21811 (setq line (concat line " " (pop words))))
21812 (setq lines (push line lines)))
21813 (nreverse lines)))
21815 (defun org-split-string (string &optional separators)
21816 "Splits STRING into substrings at SEPARATORS.
21817 No empty strings are returned if there are matches at the beginning
21818 and end of string."
21819 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21820 (start 0)
21821 notfirst
21822 (list nil))
21823 (while (and (string-match rexp string
21824 (if (and notfirst
21825 (= start (match-beginning 0))
21826 (< start (length string)))
21827 (1+ start) start))
21828 (< (match-beginning 0) (length string)))
21829 (setq notfirst t)
21830 (or (eq (match-beginning 0) 0)
21831 (and (eq (match-beginning 0) (match-end 0))
21832 (eq (match-beginning 0) start))
21833 (setq list
21834 (cons (substring string start (match-beginning 0))
21835 list)))
21836 (setq start (match-end 0)))
21837 (or (eq start (length string))
21838 (setq list
21839 (cons (substring string start)
21840 list)))
21841 (nreverse list)))
21843 (defun org-quote-vert (s)
21844 "Replace \"|\" with \"\\vert\"."
21845 (while (string-match "|" s)
21846 (setq s (replace-match "\\vert" t t s)))
21849 (defun org-uuidgen-p (s)
21850 "Is S an ID created by UUIDGEN?"
21851 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21853 (defun org-in-src-block-p (&optional inside)
21854 "Whether point is in a code source block.
21855 When INSIDE is non-nil, don't consider we are within a src block
21856 when point is at #+BEGIN_SRC or #+END_SRC."
21857 (let ((case-fold-search t) ov)
21858 (or (and (eq (get-char-property (point) 'src-block) t))
21859 (and (not inside)
21860 (save-match-data
21861 (save-excursion
21862 (beginning-of-line)
21863 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21865 (defun org-context ()
21866 "Return a list of contexts of the current cursor position.
21867 If several contexts apply, all are returned.
21868 Each context entry is a list with a symbol naming the context, and
21869 two positions indicating start and end of the context. Possible
21870 contexts are:
21872 :headline anywhere in a headline
21873 :headline-stars on the leading stars in a headline
21874 :todo-keyword on a TODO keyword (including DONE) in a headline
21875 :tags on the TAGS in a headline
21876 :priority on the priority cookie in a headline
21877 :item on the first line of a plain list item
21878 :item-bullet on the bullet/number of a plain list item
21879 :checkbox on the checkbox in a plain list item
21880 :table in an org-mode table
21881 :table-special on a special filed in a table
21882 :table-table in a table.el table
21883 :clocktable in a clocktable
21884 :src-block in a source block
21885 :link on a hyperlink
21886 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21887 :target on a <<target>>
21888 :radio-target on a <<<radio-target>>>
21889 :latex-fragment on a LaTeX fragment
21890 :latex-preview on a LaTeX fragment with overlaid preview image
21892 This function expects the position to be visible because it uses font-lock
21893 faces as a help to recognize the following contexts: :table-special, :link,
21894 and :keyword."
21895 (let* ((f (get-text-property (point) 'face))
21896 (faces (if (listp f) f (list f)))
21897 (case-fold-search t)
21898 (p (point)) clist o)
21899 ;; First the large context
21900 (cond
21901 ((org-at-heading-p t)
21902 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21903 (when (progn
21904 (beginning-of-line 1)
21905 (looking-at org-todo-line-tags-regexp))
21906 (push (org-point-in-group p 1 :headline-stars) clist)
21907 (push (org-point-in-group p 2 :todo-keyword) clist)
21908 (push (org-point-in-group p 4 :tags) clist))
21909 (goto-char p)
21910 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21911 (if (looking-at "\\[#[A-Z0-9]\\]")
21912 (push (org-point-in-group p 0 :priority) clist)))
21914 ((org-at-item-p)
21915 (push (org-point-in-group p 2 :item-bullet) clist)
21916 (push (list :item (point-at-bol)
21917 (save-excursion (org-end-of-item) (point)))
21918 clist)
21919 (and (org-at-item-checkbox-p)
21920 (push (org-point-in-group p 0 :checkbox) clist)))
21922 ((org-at-table-p)
21923 (push (list :table (org-table-begin) (org-table-end)) clist)
21924 (if (memq 'org-formula faces)
21925 (push (list :table-special
21926 (previous-single-property-change p 'face)
21927 (next-single-property-change p 'face)) clist)))
21928 ((org-at-table-p 'any)
21929 (push (list :table-table) clist)))
21930 (goto-char p)
21932 (let ((case-fold-search t))
21933 ;; New the "medium" contexts: clocktables, source blocks
21934 (cond ((org-in-clocktable-p)
21935 (push (list :clocktable
21936 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21937 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21938 (match-beginning 1))
21939 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21940 (match-end 0))) clist))
21941 ((org-in-src-block-p)
21942 (push (list :src-block
21943 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21944 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21945 (match-beginning 1))
21946 (and (search-forward "#+END_SRC" nil t)
21947 (match-beginning 0))) clist))))
21948 (goto-char p)
21950 ;; Now the small context
21951 (cond
21952 ((org-at-timestamp-p)
21953 (push (org-point-in-group p 0 :timestamp) clist))
21954 ((memq 'org-link faces)
21955 (push (list :link
21956 (previous-single-property-change p 'face)
21957 (next-single-property-change p 'face)) clist))
21958 ((memq 'org-special-keyword faces)
21959 (push (list :keyword
21960 (previous-single-property-change p 'face)
21961 (next-single-property-change p 'face)) clist))
21962 ((org-at-target-p)
21963 (push (org-point-in-group p 0 :target) clist)
21964 (goto-char (1- (match-beginning 0)))
21965 (if (looking-at org-radio-target-regexp)
21966 (push (org-point-in-group p 0 :radio-target) clist))
21967 (goto-char p))
21968 ((setq o (car (delq nil
21969 (mapcar
21970 (lambda (x)
21971 (if (memq x org-latex-fragment-image-overlays) x))
21972 (overlays-at (point))))))
21973 (push (list :latex-fragment
21974 (overlay-start o) (overlay-end o)) clist)
21975 (push (list :latex-preview
21976 (overlay-start o) (overlay-end o)) clist))
21977 ((org-inside-LaTeX-fragment-p)
21978 ;; FIXME: positions wrong.
21979 (push (list :latex-fragment (point) (point)) clist)))
21981 (setq clist (nreverse (delq nil clist)))
21982 clist))
21984 ;; FIXME: Compare with at-regexp-p Do we need both?
21985 (defun org-in-regexp (re &optional nlines visually)
21986 "Check if point is inside a match of regexp.
21987 Normally only the current line is checked, but you can include NLINES extra
21988 lines both before and after point into the search.
21989 If VISUALLY is set, require that the cursor is not after the match but
21990 really on, so that the block visually is on the match."
21991 (catch 'exit
21992 (let ((pos (point))
21993 (eol (point-at-eol (+ 1 (or nlines 0))))
21994 (inc (if visually 1 0)))
21995 (save-excursion
21996 (beginning-of-line (- 1 (or nlines 0)))
21997 (while (re-search-forward re eol t)
21998 (if (and (<= (match-beginning 0) pos)
21999 (>= (+ inc (match-end 0)) pos))
22000 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22002 (defun org-at-regexp-p (regexp)
22003 "Is point inside a match of REGEXP in the current line?"
22004 (catch 'exit
22005 (save-excursion
22006 (let ((pos (point)) (end (point-at-eol)))
22007 (beginning-of-line 1)
22008 (while (re-search-forward regexp end t)
22009 (if (and (<= (match-beginning 0) pos)
22010 (>= (match-end 0) pos))
22011 (throw 'exit t)))
22012 nil))))
22014 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22015 "Non-nil when point is between matches of START-RE and END-RE.
22017 Also return a non-nil value when point is on one of the matches.
22019 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22020 buffer positions. Default values are the positions of headlines
22021 surrounding the point.
22023 The functions returns a cons cell whose car (resp. cdr) is the
22024 position before START-RE (resp. after END-RE)."
22025 (save-match-data
22026 (let ((pos (point))
22027 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22028 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22029 beg end)
22030 (save-excursion
22031 ;; Point is on a block when on START-RE or if START-RE can be
22032 ;; found before it...
22033 (and (or (org-at-regexp-p start-re)
22034 (re-search-backward start-re limit-up t))
22035 (setq beg (match-beginning 0))
22036 ;; ... and END-RE after it...
22037 (goto-char (match-end 0))
22038 (re-search-forward end-re limit-down t)
22039 (> (setq end (match-end 0)) pos)
22040 ;; ... without another START-RE in-between.
22041 (goto-char (match-beginning 0))
22042 (not (re-search-backward start-re (1+ beg) t))
22043 ;; Return value.
22044 (cons beg end))))))
22046 (defun org-in-block-p (names)
22047 "Non-nil when point belongs to a block whose name belongs to NAMES.
22049 NAMES is a list of strings containing names of blocks.
22051 Return first block name matched, or nil. Beware that in case of
22052 nested blocks, the returned name may not belong to the closest
22053 block from point."
22054 (save-match-data
22055 (catch 'exit
22056 (let ((case-fold-search t)
22057 (lim-up (save-excursion (outline-previous-heading)))
22058 (lim-down (save-excursion (outline-next-heading))))
22059 (mapc (lambda (name)
22060 (let ((n (regexp-quote name)))
22061 (when (org-between-regexps-p
22062 (concat "^[ \t]*#\\+begin_" n)
22063 (concat "^[ \t]*#\\+end_" n)
22064 lim-up lim-down)
22065 (throw 'exit n))))
22066 names))
22067 nil)))
22069 (defun org-in-drawer-p ()
22070 "Non-nil if point is within a drawer.
22071 If point is within a drawer, return it, as parsed data."
22072 (let ((element (save-match-data (org-element-at-point))))
22073 (while (and element (not (memq (org-element-type element)
22074 '(drawer property-drawer))))
22075 (setq element (org-element-property :parent element)))
22076 element))
22078 (defun org-occur-in-agenda-files (regexp &optional nlines)
22079 "Call `multi-occur' with buffers for all agenda files."
22080 (interactive "sOrg-files matching: \np")
22081 (let* ((files (org-agenda-files))
22082 (tnames (mapcar 'file-truename files))
22083 (extra org-agenda-text-search-extra-files)
22085 (when (eq (car extra) 'agenda-archives)
22086 (setq extra (cdr extra))
22087 (setq files (org-add-archive-files files)))
22088 (while (setq f (pop extra))
22089 (unless (member (file-truename f) tnames)
22090 (add-to-list 'files f 'append)
22091 (add-to-list 'tnames (file-truename f) 'append)))
22092 (multi-occur
22093 (mapcar (lambda (x)
22094 (with-current-buffer
22095 (or (get-file-buffer x) (find-file-noselect x))
22096 (widen)
22097 (current-buffer)))
22098 files)
22099 regexp)))
22101 (if (boundp 'occur-mode-find-occurrence-hook)
22102 ;; Emacs 23
22103 (add-hook 'occur-mode-find-occurrence-hook
22104 (lambda ()
22105 (when (derived-mode-p 'org-mode)
22106 (org-reveal))))
22107 ;; Emacs 22
22108 (defadvice occur-mode-goto-occurrence
22109 (after org-occur-reveal activate)
22110 (and (derived-mode-p 'org-mode) (org-reveal)))
22111 (defadvice occur-mode-goto-occurrence-other-window
22112 (after org-occur-reveal activate)
22113 (and (derived-mode-p 'org-mode) (org-reveal)))
22114 (defadvice occur-mode-display-occurrence
22115 (after org-occur-reveal activate)
22116 (when (derived-mode-p 'org-mode)
22117 (let ((pos (occur-mode-find-occurrence)))
22118 (with-current-buffer (marker-buffer pos)
22119 (save-excursion
22120 (goto-char pos)
22121 (org-reveal)))))))
22123 (defun org-occur-link-in-agenda-files ()
22124 "Create a link and search for it in the agendas.
22125 The link is not stored in `org-stored-links', it is just created
22126 for the search purpose."
22127 (interactive)
22128 (let ((link (condition-case nil
22129 (org-store-link nil)
22130 (error "Unable to create a link to here"))))
22131 (org-occur-in-agenda-files (regexp-quote link))))
22133 (defun org-reverse-string (string)
22134 "Return the reverse of STRING."
22135 (apply 'string (reverse (string-to-list string))))
22137 ;; defsubst org-uniquify must be defined before first use
22139 (defun org-uniquify-alist (alist)
22140 "Merge elements of ALIST with the same key.
22142 For example, in this alist:
22144 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22145 => '((a 1 3) (b 2))
22147 merge (a 1) and (a 3) into (a 1 3).
22149 The function returns the new ALIST."
22150 (let (rtn)
22151 (mapc
22152 (lambda (e)
22153 (let (n)
22154 (if (not (assoc (car e) rtn))
22155 (push e rtn)
22156 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22157 (setq rtn (assq-delete-all (car e) rtn))
22158 (push n rtn))))
22159 alist)
22160 rtn))
22162 (defun org-delete-all (elts list)
22163 "Remove all elements in ELTS from LIST."
22164 (while elts
22165 (setq list (delete (pop elts) list)))
22166 list)
22168 (defun org-count (cl-item cl-seq)
22169 "Count the number of occurrences of ITEM in SEQ.
22170 Taken from `count' in cl-seq.el with all keyword arguments removed."
22171 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22172 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22173 (while (< cl-start cl-end)
22174 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22175 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22176 (setq cl-start (1+ cl-start)))
22177 cl-count))
22179 (defun org-remove-if (predicate seq)
22180 "Remove everything from SEQ that fulfills PREDICATE."
22181 (let (res e)
22182 (while seq
22183 (setq e (pop seq))
22184 (if (not (funcall predicate e)) (push e res)))
22185 (nreverse res)))
22187 (defun org-remove-if-not (predicate seq)
22188 "Remove everything from SEQ that does not fulfill PREDICATE."
22189 (let (res e)
22190 (while seq
22191 (setq e (pop seq))
22192 (if (funcall predicate e) (push e res)))
22193 (nreverse res)))
22195 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22196 "Reduce two-argument FUNCTION across SEQ.
22197 Taken from `reduce' in cl-seq.el with all keyword arguments but
22198 \":initial-value\" removed."
22199 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22200 (cadr (memq :initial-value cl-keys)))
22201 (cl-seq (pop cl-seq))
22202 (t (funcall cl-func)))))
22203 (while cl-seq
22204 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22205 cl-accum))
22207 (defun org-every (pred seq)
22208 "Return true if PREDICATE is true of every element of SEQ.
22209 Adapted from `every' in cl.el."
22210 (catch 'org-every
22211 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22214 (defun org-some (pred seq)
22215 "Return true if PREDICATE is true of any element of SEQ.
22216 Adapted from `some' in cl.el."
22217 (catch 'org-some
22218 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22219 nil))
22221 (defun org-back-over-empty-lines ()
22222 "Move backwards over whitespace, to the beginning of the first empty line.
22223 Returns the number of empty lines passed."
22224 (let ((pos (point)))
22225 (if (cdr (assoc 'heading org-blank-before-new-entry))
22226 (skip-chars-backward " \t\n\r")
22227 (unless (eobp)
22228 (forward-line -1)))
22229 (beginning-of-line 2)
22230 (goto-char (min (point) pos))
22231 (count-lines (point) pos)))
22233 (defun org-skip-whitespace ()
22234 (skip-chars-forward " \t\n\r"))
22236 (defun org-point-in-group (point group &optional context)
22237 "Check if POINT is in match-group GROUP.
22238 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22239 match. If the match group does not exist or point is not inside it,
22240 return nil."
22241 (and (match-beginning group)
22242 (>= point (match-beginning group))
22243 (<= point (match-end group))
22244 (if context
22245 (list context (match-beginning group) (match-end group))
22246 t)))
22248 (defun org-switch-to-buffer-other-window (&rest args)
22249 "Switch to buffer in a second window on the current frame.
22250 In particular, do not allow pop-up frames.
22251 Returns the newly created buffer."
22252 (org-no-popups
22253 (apply 'switch-to-buffer-other-window args)))
22255 (defun org-combine-plists (&rest plists)
22256 "Create a single property list from all plists in PLISTS.
22257 The process starts by copying the first list, and then setting properties
22258 from the other lists. Settings in the last list are the most significant
22259 ones and overrule settings in the other lists."
22260 (let ((rtn (copy-sequence (pop plists)))
22261 p v ls)
22262 (while plists
22263 (setq ls (pop plists))
22264 (while ls
22265 (setq p (pop ls) v (pop ls))
22266 (setq rtn (plist-put rtn p v))))
22267 rtn))
22269 (defun org-replace-escapes (string table)
22270 "Replace %-escapes in STRING with values in TABLE.
22271 TABLE is an association list with keys like \"%a\" and string values.
22272 The sequences in STRING may contain normal field width and padding information,
22273 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22274 so values can contain further %-escapes if they are define later in TABLE."
22275 (let ((tbl (copy-alist table))
22276 (case-fold-search nil)
22277 (pchg 0)
22278 e re rpl)
22279 (while (setq e (pop tbl))
22280 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22281 (when (and (cdr e) (string-match re (cdr e)))
22282 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22283 (safe "SREF"))
22284 (add-text-properties 0 3 (list 'sref sref) safe)
22285 (setcdr e (replace-match safe t t (cdr e)))))
22286 (while (string-match re string)
22287 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22288 (cdr e)))
22289 (setq string (replace-match rpl t t string))))
22290 (while (setq pchg (next-property-change pchg string))
22291 (let ((sref (get-text-property pchg 'sref string)))
22292 (when (and sref (string-match "SREF" string pchg))
22293 (setq string (replace-match sref t t string)))))
22294 string))
22296 (defun org-sublist (list start end)
22297 "Return a section of LIST, from START to END.
22298 Counting starts at 1."
22299 (let (rtn (c start))
22300 (setq list (nthcdr (1- start) list))
22301 (while (and list (<= c end))
22302 (push (pop list) rtn)
22303 (setq c (1+ c)))
22304 (nreverse rtn)))
22306 (defun org-find-base-buffer-visiting (file)
22307 "Like `find-buffer-visiting' but always return the base buffer and
22308 not an indirect buffer."
22309 (let ((buf (or (get-file-buffer file)
22310 (find-buffer-visiting file))))
22311 (if buf
22312 (or (buffer-base-buffer buf) buf)
22313 nil)))
22315 (defun org-image-file-name-regexp (&optional extensions)
22316 "Return regexp matching the file names of images.
22317 If EXTENSIONS is given, only match these."
22318 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22319 (image-file-name-regexp)
22320 (let ((image-file-name-extensions
22321 (or extensions
22322 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22323 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22324 (concat "\\."
22325 (regexp-opt (nconc (mapcar 'upcase
22326 image-file-name-extensions)
22327 image-file-name-extensions)
22329 "\\'"))))
22331 (defun org-file-image-p (file &optional extensions)
22332 "Return non-nil if FILE is an image."
22333 (save-match-data
22334 (string-match (org-image-file-name-regexp extensions) file)))
22336 (defun org-get-cursor-date (&optional with-time)
22337 "Return the date at cursor in as a time.
22338 This works in the calendar and in the agenda, anywhere else it just
22339 returns the current time.
22340 If WITH-TIME is non-nil, returns the time of the event at point (in
22341 the agenda) or the current time of the day."
22342 (let (date day defd tp tm hod mod)
22343 (when with-time
22344 (setq tp (get-text-property (point) 'time))
22345 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22346 (setq hod (string-to-number (match-string 1 tp))
22347 mod (string-to-number (match-string 2 tp))))
22348 (or tp (setq hod (nth 2 (decode-time (current-time)))
22349 mod (nth 1 (decode-time (current-time))))))
22350 (cond
22351 ((eq major-mode 'calendar-mode)
22352 (setq date (calendar-cursor-to-date)
22353 defd (encode-time 0 (or mod 0) (or hod 0)
22354 (nth 1 date) (nth 0 date) (nth 2 date))))
22355 ((eq major-mode 'org-agenda-mode)
22356 (setq day (get-text-property (point) 'day))
22357 (if day
22358 (setq date (calendar-gregorian-from-absolute day)
22359 defd (encode-time 0 (or mod 0) (or hod 0)
22360 (nth 1 date) (nth 0 date) (nth 2 date))))))
22361 (or defd (current-time))))
22363 (defun org-mark-subtree (&optional up)
22364 "Mark the current subtree.
22365 This puts point at the start of the current subtree, and mark at
22366 the end. If a numeric prefix UP is given, move up into the
22367 hierarchy of headlines by UP levels before marking the subtree."
22368 (interactive "P")
22369 (org-with-limited-levels
22370 (cond ((org-at-heading-p) (beginning-of-line))
22371 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22372 (t (outline-previous-visible-heading 1))))
22373 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22374 (if (org-called-interactively-p 'any)
22375 (call-interactively 'org-mark-element)
22376 (org-mark-element)))
22379 ;;; Indentation
22381 (defun org--get-expected-indentation (element contentsp)
22382 "Expected indentation column for current line, according to ELEMENT.
22383 ELEMENT is an element containing point. CONTENTSP is non-nil
22384 when indentation is to be computed according to contents of
22385 ELEMENT."
22386 (let ((type (org-element-type element))
22387 (start (org-element-property :begin element)))
22388 (org-with-wide-buffer
22389 (cond
22390 (contentsp
22391 (case type
22392 (footnote-definition 0)
22393 ((headline inlinetask nil)
22394 (if (not org-adapt-indentation) 0
22395 (let ((level (org-current-level)))
22396 (if level (1+ level) 0))))
22397 ((item plain list)
22398 (org-list-item-body-column
22399 (org-element-property :post-affiliated element)))
22400 (otherwise
22401 (goto-char start)
22402 (org-get-indentation))))
22403 ((memq type '(headline inlinetask nil))
22404 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22405 (org--get-expected-indentation element t)
22407 ((eq type 'footnote-definition) 0)
22408 ;; First paragraph of a footnote definition or an item.
22409 ;; Indent like parent.
22410 ((< (line-beginning-position) start)
22411 (org--get-expected-indentation
22412 (org-element-property :parent element) t))
22413 ;; At first line: indent according to previous sibling, if any,
22414 ;; ignoring footnote definitions and inline tasks, or parent's
22415 ;; contents.
22416 ((= (line-beginning-position) start)
22417 (catch 'exit
22418 (while t
22419 (if (= (point-min) start) (throw 'exit 0)
22420 (goto-char (1- start))
22421 (let ((previous (org-element-at-point)))
22422 (while (let ((parent (org-element-property :parent previous)))
22423 (and parent
22424 (setq previous parent)
22425 (<= (org-element-property :end parent) start))))
22426 (cond ((or (not previous)
22427 (> (org-element-property :end previous) start))
22428 (throw 'exit (org--get-expected-indentation previous t)))
22429 ((memq (org-element-type previous)
22430 '(footnote-definition inlinetask))
22431 (setq start (org-element-property :begin previous)))
22432 (t (goto-char (org-element-property :begin previous))
22433 (throw 'exit (org-get-indentation)))))))))
22434 ;; Otherwise, move to the first non-blank line above.
22436 (beginning-of-line)
22437 (let ((pos (point)))
22438 (skip-chars-backward " \r\t\n")
22439 (cond
22440 ;; Two blank lines end a footnote definition or a plain
22441 ;; list. When we indent an empty line after them, the
22442 ;; containing list or footnote definition is over, so it
22443 ;; qualifies as a previous sibling. Therefore, we indent
22444 ;; like its first line.
22445 ((and (memq type '(footnote-definition plain-list))
22446 (> (count-lines (point) pos) 2))
22447 (goto-char start)
22448 (org-get-indentation))
22449 ;; Line above is the first one of a paragraph at the
22450 ;; beginning of an item or a footnote definition. Indent
22451 ;; like parent.
22452 ((< (line-beginning-position) start)
22453 (org--get-expected-indentation
22454 (org-element-property :parent element) t))
22455 ;; POS is after contents in a greater element. Indent like
22456 ;; the beginning of the element.
22458 ;; As a special case, if point is at the end of a footnote
22459 ;; definition or an item, indent like the very last element
22460 ;; within.
22461 ((let ((cend (org-element-property :contents-end element)))
22462 (and cend (<= cend pos)))
22463 (if (memq type '(footnote-definition item plain-list))
22464 (org--get-expected-indentation (org-element-at-point) nil)
22465 (goto-char start)
22466 (org-get-indentation)))
22467 ;; In any other case, indent like the current line.
22468 (t (org-get-indentation)))))))))
22470 (defun org--align-node-property ()
22471 "Align node property at point.
22472 Alignment is done according to `org-property-format', which see."
22473 (when (save-excursion
22474 (beginning-of-line)
22475 (looking-at org-property-re))
22476 (replace-match
22477 (concat (match-string 4)
22478 (org-trim
22479 (format org-property-format (match-string 1) (match-string 3))))
22480 t t)))
22482 (defun org-indent-line ()
22483 "Indent line depending on context.
22485 Indentation is done according to the following rules:
22487 - Footnote definitions, headlines and inline tasks have to
22488 start at column 0.
22490 - On the very first line of an element, consider, in order, the
22491 next rules until one matches:
22493 1. If there's a sibling element before, ignoring footnote
22494 definitions and inline tasks, indent like its first line.
22496 2. If element has a parent, indent like its contents. More
22497 precisely, if parent is an item, indent after the
22498 description part, if any, or the bullet (see
22499 ``org-list-description-max-indent'). Else, indent like
22500 parent's first line.
22502 3. Otherwise, indent relatively to current level, if
22503 `org-adapt-indentation' is non-nil, or to left margin.
22505 - On a blank line at the end of a plain list, an item, or
22506 a footnote definition, indent like the very last element
22507 within.
22509 - In the code part of a source block, use language major mode
22510 to indent current line if `org-src-tab-acts-natively' is
22511 non-nil. If it is nil, do nothing.
22513 - Otherwise, indent like the first non-blank line above.
22515 The function doesn't indent an item as it could break the whole
22516 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22517 \\[org-shiftmetaright].
22519 Also align node properties according to `org-property-format'."
22520 (interactive)
22521 (cond
22522 (orgstruct-is-++
22523 (let ((indent-line-function
22524 (cadadr (assq 'indent-line-function org-fb-vars))))
22525 (indent-according-to-mode)))
22526 ((org-at-heading-p) 'noindent)
22528 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22529 (type (org-element-type element)))
22530 (cond ((and (memq type '(plain-list item))
22531 (= (line-beginning-position)
22532 (org-element-property :post-affiliated element)))
22533 'noindent)
22534 ((and (eq type 'src-block)
22535 org-src-tab-acts-natively
22536 (> (line-beginning-position)
22537 (org-element-property :post-affiliated element))
22538 (< (line-beginning-position)
22539 (org-with-wide-buffer
22540 (goto-char (org-element-property :end element))
22541 (skip-chars-backward " \r\t\n")
22542 (line-beginning-position))))
22543 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22544 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22546 (let ((column (org--get-expected-indentation element nil)))
22547 ;; Preserve current column.
22548 (if (<= (current-column) (current-indentation))
22549 (org-indent-line-to column)
22550 (save-excursion (org-indent-line-to column))))
22551 ;; Align node property. Also preserve current column.
22552 (when (eq type 'node-property)
22553 (let ((column (current-column)))
22554 (org--align-node-property)
22555 (org-move-to-column column)))))))))
22557 (defun org-indent-region (start end)
22558 "Indent each non-blank line in the region.
22559 Called from a program, START and END specify the region to
22560 indent. The function will not indent contents of example blocks,
22561 verse blocks and export blocks as leading white spaces are
22562 assumed to be significant there."
22563 (interactive "r")
22564 (save-excursion
22565 (goto-char start)
22566 (beginning-of-line)
22567 (let ((indent-to
22568 (lambda (ind pos)
22569 ;; Set IND as indentation for all lines between point and
22570 ;; POS or END, whichever comes first. Blank lines are
22571 ;; ignored. Leave point after POS once done.
22572 (let ((limit (copy-marker (min end pos))))
22573 (while (< (point) limit)
22574 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22575 (forward-line))
22576 (set-marker limit nil))))
22577 (end (copy-marker end)))
22578 (while (< (point) end)
22579 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22580 (let* ((element (org-element-at-point))
22581 (type (org-element-type element))
22582 (element-end (copy-marker (org-element-property :end element)))
22583 (ind (org--get-expected-indentation element nil)))
22584 (if (or (memq type '(paragraph table table-row))
22585 (not (or (org-element-property :contents-begin element)
22586 (memq type
22587 '(example-block export-block src-block)))))
22588 ;; Elements here are indented as a single block. Also
22589 ;; align node properties.
22590 (progn
22591 (when (eq type 'node-property)
22592 (org--align-node-property)
22593 (beginning-of-line))
22594 (funcall indent-to ind element-end))
22595 ;; Elements in this category consist of three parts:
22596 ;; before the contents, the contents, and after the
22597 ;; contents. The contents are treated specially,
22598 ;; according to the element type, or not indented at
22599 ;; all. Other parts are indented as a single block.
22600 (let* ((post (copy-marker
22601 (org-element-property :post-affiliated element)))
22602 (cbeg
22603 (copy-marker
22604 (cond
22605 ((not (org-element-property :contents-begin element))
22606 ;; Fake contents for source blocks.
22607 (org-with-wide-buffer
22608 (goto-char post)
22609 (forward-line)
22610 (point)))
22611 ((memq type '(footnote-definition item plain-list))
22612 ;; Contents in these elements could start on
22613 ;; the same line as the beginning of the
22614 ;; element. Make sure we start indenting
22615 ;; from the second line.
22616 (org-with-wide-buffer
22617 (goto-char post)
22618 (forward-line)
22619 (point)))
22620 (t (org-element-property :contents-begin element)))))
22621 (cend (copy-marker
22622 (or (org-element-property :contents-end element)
22623 ;; Fake contents for source blocks.
22624 (org-with-wide-buffer
22625 (goto-char element-end)
22626 (skip-chars-backward " \r\t\n")
22627 (line-beginning-position))))))
22628 (funcall indent-to ind cbeg)
22629 (when (< (point) end)
22630 (case type
22631 ((example-block export-block verse-block))
22632 (src-block
22633 ;; In a source block, indent source code according
22634 ;; to language major mode, but only if
22635 ;; `org-src-tab-acts-natively' is non-nil.
22636 (when (and (< (point) end) org-src-tab-acts-natively)
22637 (ignore-errors
22638 (let (org-src-strip-leading-and-trailing-blank-lines
22639 ;; Region boundaries in edit buffer.
22640 (start (1+ (- (point) cbeg)))
22641 (end (- (min cend end) cbeg)))
22642 (org-babel-do-in-edit-buffer
22643 (indent-region start end))))))
22644 (t (org-indent-region (point) (min cend end))))
22645 (goto-char (min cend end))
22646 (when (< (point) end) (funcall indent-to ind element-end)))
22647 (set-marker post nil)
22648 (set-marker cbeg nil)
22649 (set-marker cend nil)))
22650 (set-marker element-end nil))))
22651 (set-marker end nil))))
22653 (defun org-indent-drawer ()
22654 "Indent the drawer at point."
22655 (interactive)
22656 (unless (save-excursion
22657 (beginning-of-line)
22658 (org-looking-at-p org-drawer-regexp))
22659 (user-error "Not at a drawer"))
22660 (let ((element (org-element-at-point)))
22661 (unless (memq (org-element-type element) '(drawer property-drawer))
22662 (user-error "Not at a drawer"))
22663 (org-with-wide-buffer
22664 (org-indent-region (org-element-property :begin element)
22665 (org-element-property :end element))))
22666 (message "Drawer at point indented"))
22668 (defun org-indent-block ()
22669 "Indent the block at point."
22670 (interactive)
22671 (unless (save-excursion
22672 (beginning-of-line)
22673 (let ((case-fold-search t))
22674 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22675 (user-error "Not at a block"))
22676 (let ((element (org-element-at-point)))
22677 (unless (memq (org-element-type element)
22678 '(comment-block center-block dynamic-block example-block
22679 export-block quote-block special-block
22680 src-block verse-block))
22681 (user-error "Not at a block"))
22682 (org-with-wide-buffer
22683 (org-indent-region (org-element-property :begin element)
22684 (org-element-property :end element))))
22685 (message "Block at point indented"))
22688 ;;; Filling
22690 ;; We use our own fill-paragraph and auto-fill functions.
22692 ;; `org-fill-paragraph' relies on adaptive filling and context
22693 ;; checking. Appropriate `fill-prefix' is computed with
22694 ;; `org-adaptive-fill-function'.
22696 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22697 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22698 ;; `org-adaptive-fill-function' value. Internally,
22699 ;; `org-comment-line-break-function' breaks the line.
22701 ;; `org-setup-filling' installs filling and auto-filling related
22702 ;; variables during `org-mode' initialization.
22704 (defvar org-element-paragraph-separate) ; org-element.el
22705 (defun org-setup-filling ()
22706 (require 'org-element)
22707 ;; Prevent auto-fill from inserting unwanted new items.
22708 (when (boundp 'fill-nobreak-predicate)
22709 (org-set-local
22710 'fill-nobreak-predicate
22711 (org-uniquify
22712 (append fill-nobreak-predicate
22713 '(org-fill-line-break-nobreak-p
22714 org-fill-paragraph-with-timestamp-nobreak-p)))))
22715 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22716 (org-set-local 'paragraph-start paragraph-ending)
22717 (org-set-local 'paragraph-separate paragraph-ending))
22718 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22719 (org-set-local 'auto-fill-inhibit-regexp nil)
22720 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22721 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22722 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22724 (defun org-fill-line-break-nobreak-p ()
22725 "Non-nil when a new line at point would create an Org line break."
22726 (save-excursion
22727 (skip-chars-backward "[ \t]")
22728 (skip-chars-backward "\\\\")
22729 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22731 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22732 "Non-nil when a new line at point would split a timestamp."
22733 (and (org-at-timestamp-p t)
22734 (not (looking-at org-ts-regexp-both))))
22736 (declare-function message-in-body-p "message" ())
22737 (defvar orgtbl-line-start-regexp) ; From org-table.el
22738 (defun org-adaptive-fill-function ()
22739 "Compute a fill prefix for the current line.
22740 Return fill prefix, as a string, or nil if current line isn't
22741 meant to be filled. For convenience, if `adaptive-fill-regexp'
22742 matches in paragraphs or comments, use it."
22743 (catch 'exit
22744 (when (derived-mode-p 'message-mode)
22745 (save-excursion
22746 (beginning-of-line)
22747 (cond ((or (not (message-in-body-p))
22748 (looking-at orgtbl-line-start-regexp))
22749 (throw 'exit nil))
22750 ((looking-at message-cite-prefix-regexp)
22751 (throw 'exit (match-string-no-properties 0)))
22752 ((looking-at org-outline-regexp)
22753 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22754 (org-with-wide-buffer
22755 (unless (org-at-heading-p)
22756 (let* ((p (line-beginning-position))
22757 (element (save-excursion
22758 (beginning-of-line)
22759 (org-element-at-point)))
22760 (type (org-element-type element))
22761 (post-affiliated (org-element-property :post-affiliated element)))
22762 (unless (< p post-affiliated)
22763 (case type
22764 (comment
22765 (save-excursion
22766 (beginning-of-line)
22767 (looking-at "[ \t]*")
22768 (concat (match-string 0) "# ")))
22769 (footnote-definition "")
22770 ((item plain-list)
22771 (make-string (org-list-item-body-column post-affiliated) ?\s))
22772 (paragraph
22773 ;; Fill prefix is usually the same as the current line,
22774 ;; unless the paragraph is at the beginning of an item.
22775 (let ((parent (org-element-property :parent element)))
22776 (save-excursion
22777 (beginning-of-line)
22778 (cond ((eq (org-element-type parent) 'item)
22779 (make-string (org-list-item-body-column
22780 (org-element-property :begin parent))
22781 ?\s))
22782 ((and adaptive-fill-regexp
22783 ;; Locally disable
22784 ;; `adaptive-fill-function' to let
22785 ;; `fill-context-prefix' handle
22786 ;; `adaptive-fill-regexp' variable.
22787 (let (adaptive-fill-function)
22788 (fill-context-prefix
22789 post-affiliated
22790 (org-element-property :end element)))))
22791 ((looking-at "[ \t]+") (match-string 0))
22792 (t "")))))
22793 (comment-block
22794 ;; Only fill contents if P is within block boundaries.
22795 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22796 (forward-line)
22797 (point)))
22798 (cend (save-excursion
22799 (goto-char (org-element-property :end element))
22800 (skip-chars-backward " \r\t\n")
22801 (line-beginning-position))))
22802 (when (and (>= p cbeg) (< p cend))
22803 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22804 (match-string 0)
22805 "")))))))))))
22807 (declare-function message-goto-body "message" ())
22808 (defvar message-cite-prefix-regexp) ; From message.el
22809 (defun org-fill-paragraph (&optional justify)
22810 "Fill element at point, when applicable.
22812 This function only applies to comment blocks, comments, example
22813 blocks and paragraphs. Also, as a special case, re-align table
22814 when point is at one.
22816 If JUSTIFY is non-nil (interactively, with prefix argument),
22817 justify as well. If `sentence-end-double-space' is non-nil, then
22818 period followed by one space does not end a sentence, so don't
22819 break a line there. The variable `fill-column' controls the
22820 width for filling.
22822 For convenience, when point is at a plain list, an item or
22823 a footnote definition, try to fill the first paragraph within."
22824 (interactive)
22825 (if (and (derived-mode-p 'message-mode)
22826 (or (not (message-in-body-p))
22827 (save-excursion (move-beginning-of-line 1)
22828 (looking-at message-cite-prefix-regexp))))
22829 ;; First ensure filling is correct in message-mode.
22830 (let ((fill-paragraph-function
22831 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22832 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22833 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22834 (paragraph-separate
22835 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22836 (fill-paragraph nil))
22837 (with-syntax-table org-mode-transpose-word-syntax-table
22838 ;; Move to end of line in order to get the first paragraph
22839 ;; within a plain list or a footnote definition.
22840 (let ((element (save-excursion
22841 (end-of-line)
22842 (or (ignore-errors (org-element-at-point))
22843 (user-error "An element cannot be parsed line %d"
22844 (line-number-at-pos (point)))))))
22845 ;; First check if point is in a blank line at the beginning of
22846 ;; the buffer. In that case, ignore filling.
22847 (case (org-element-type element)
22848 ;; Use major mode filling function is src blocks.
22849 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22850 ;; Align Org tables, leave table.el tables as-is.
22851 (table-row (org-table-align) t)
22852 (table
22853 (when (eq (org-element-property :type element) 'org)
22854 (save-excursion
22855 (goto-char (org-element-property :post-affiliated element))
22856 (org-table-align)))
22858 (paragraph
22859 ;; Paragraphs may contain `line-break' type objects.
22860 (let ((beg (max (point-min)
22861 (org-element-property :contents-begin element)))
22862 (end (min (point-max)
22863 (org-element-property :contents-end element))))
22864 ;; Do nothing if point is at an affiliated keyword.
22865 (if (< (line-end-position) beg) t
22866 (when (derived-mode-p 'message-mode)
22867 ;; In `message-mode', do not fill following citation
22868 ;; in current paragraph nor text before message body.
22869 (let ((body-start (save-excursion (message-goto-body))))
22870 (when body-start (setq beg (max body-start beg))))
22871 (when (save-excursion
22872 (re-search-forward
22873 (concat "^" message-cite-prefix-regexp) end t))
22874 (setq end (match-beginning 0))))
22875 ;; Fill paragraph, taking line breaks into account.
22876 (save-excursion
22877 (goto-char beg)
22878 (let ((cuts (list beg)))
22879 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22880 (when (eq 'line-break
22881 (org-element-type
22882 (save-excursion (backward-char)
22883 (org-element-context))))
22884 (push (point) cuts)))
22885 (dolist (c (delq end cuts))
22886 (fill-region-as-paragraph c end justify)
22887 (setq end c))))
22888 t)))
22889 ;; Contents of `comment-block' type elements should be
22890 ;; filled as plain text, but only if point is within block
22891 ;; markers.
22892 (comment-block
22893 (let* ((case-fold-search t)
22894 (beg (save-excursion
22895 (goto-char (org-element-property :begin element))
22896 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22897 (forward-line)
22898 (point)))
22899 (end (save-excursion
22900 (goto-char (org-element-property :end element))
22901 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22902 (line-beginning-position))))
22903 (if (or (< (point) beg) (> (point) end)) t
22904 (fill-region-as-paragraph
22905 (save-excursion (end-of-line)
22906 (re-search-backward "^[ \t]*$" beg 'move)
22907 (line-beginning-position))
22908 (save-excursion (beginning-of-line)
22909 (re-search-forward "^[ \t]*$" end 'move)
22910 (line-beginning-position))
22911 justify))))
22912 ;; Fill comments.
22913 (comment
22914 (let ((begin (org-element-property :post-affiliated element))
22915 (end (org-element-property :end element)))
22916 (when (and (>= (point) begin) (<= (point) end))
22917 (let ((begin (save-excursion
22918 (end-of-line)
22919 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22920 (progn (forward-line) (point))
22921 begin)))
22922 (end (save-excursion
22923 (end-of-line)
22924 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22925 (1- (line-beginning-position))
22926 (skip-chars-backward " \r\t\n")
22927 (line-end-position)))))
22928 ;; Do not fill comments when at a blank line.
22929 (when (> end begin)
22930 (let ((fill-prefix
22931 (save-excursion
22932 (beginning-of-line)
22933 (looking-at "[ \t]*#")
22934 (let ((comment-prefix (match-string 0)))
22935 (goto-char (match-end 0))
22936 (if (looking-at adaptive-fill-regexp)
22937 (concat comment-prefix (match-string 0))
22938 (concat comment-prefix " "))))))
22939 (save-excursion
22940 (fill-region-as-paragraph begin end justify))))))
22942 ;; Ignore every other element.
22943 (otherwise t))))))
22945 (defun org-auto-fill-function ()
22946 "Auto-fill function."
22947 ;; Check if auto-filling is meaningful.
22948 (let ((fc (current-fill-column)))
22949 (when (and fc (> (current-column) fc))
22950 (let* ((fill-prefix (org-adaptive-fill-function))
22951 ;; Enforce empty fill prefix, if required. Otherwise, it
22952 ;; will be computed again.
22953 (adaptive-fill-mode (not (equal fill-prefix ""))))
22954 (when fill-prefix (do-auto-fill))))))
22956 (defun org-comment-line-break-function (&optional soft)
22957 "Break line at point and indent, continuing comment if within one.
22958 The inserted newline is marked hard if variable
22959 `use-hard-newlines' is true, unless optional argument SOFT is
22960 non-nil."
22961 (if soft (insert-and-inherit ?\n) (newline 1))
22962 (save-excursion (forward-char -1) (delete-horizontal-space))
22963 (delete-horizontal-space)
22964 (indent-to-left-margin)
22965 (insert-before-markers-and-inherit fill-prefix))
22968 ;;; Fixed Width Areas
22970 (defun org-toggle-fixed-width ()
22971 "Toggle fixed-width markup.
22973 Add or remove fixed-width markup on current line, whenever it
22974 makes sense. Return an error otherwise.
22976 If a region is active and if it contains only fixed-width areas
22977 or blank lines, remove all fixed-width markup in it. If the
22978 region contains anything else, convert all non-fixed-width lines
22979 to fixed-width ones.
22981 Blank lines at the end of the region are ignored unless the
22982 region only contains such lines."
22983 (interactive)
22984 (if (not (org-region-active-p))
22985 ;; No region:
22987 ;; Remove fixed width marker only in a fixed-with element.
22989 ;; Add fixed width maker in paragraphs, in blank lines after
22990 ;; elements or at the beginning of a headline or an inlinetask,
22991 ;; and before any one-line elements (e.g., a clock).
22992 (progn
22993 (beginning-of-line)
22994 (let* ((element (org-element-at-point))
22995 (type (org-element-type element)))
22996 (cond
22997 ((and (eq type 'fixed-width)
22998 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22999 (replace-match
23000 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23001 ((and (memq type '(babel-call clock comment diary-sexp headline
23002 horizontal-rule keyword paragraph
23003 planning))
23004 (<= (org-element-property :post-affiliated element) (point)))
23005 (skip-chars-forward " \t")
23006 (insert ": "))
23007 ((and (org-looking-at-p "[ \t]*$")
23008 (or (eq type 'inlinetask)
23009 (save-excursion
23010 (skip-chars-forward " \r\t\n")
23011 (<= (org-element-property :end element) (point)))))
23012 (delete-region (point) (line-end-position))
23013 (org-indent-line)
23014 (insert ": "))
23015 (t (user-error "Cannot insert a fixed-width line here")))))
23016 ;; Region active.
23017 (let* ((begin (save-excursion
23018 (goto-char (region-beginning))
23019 (line-beginning-position)))
23020 (end (copy-marker
23021 (save-excursion
23022 (goto-char (region-end))
23023 (unless (eolp) (beginning-of-line))
23024 (if (save-excursion (re-search-backward "\\S-" begin t))
23025 (progn (skip-chars-backward " \r\t\n") (point))
23026 (point)))))
23027 (all-fixed-width-p
23028 (catch 'not-all-p
23029 (save-excursion
23030 (goto-char begin)
23031 (skip-chars-forward " \r\t\n")
23032 (when (eobp) (throw 'not-all-p nil))
23033 (while (< (point) end)
23034 (let ((element (org-element-at-point)))
23035 (if (eq (org-element-type element) 'fixed-width)
23036 (goto-char (org-element-property :end element))
23037 (throw 'not-all-p nil))))
23038 t))))
23039 (if all-fixed-width-p
23040 (save-excursion
23041 (goto-char begin)
23042 (while (< (point) end)
23043 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23044 (replace-match
23045 "" nil nil nil
23046 (if (= (line-end-position) (match-end 0)) 0 1)))
23047 (forward-line)))
23048 (let ((min-ind (point-max)))
23049 ;; Find minimum indentation across all lines.
23050 (save-excursion
23051 (goto-char begin)
23052 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23053 (setq min-ind 0)
23054 (catch 'zerop
23055 (while (< (point) end)
23056 (unless (org-looking-at-p "[ \t]*$")
23057 (let ((ind (org-get-indentation)))
23058 (setq min-ind (min min-ind ind))
23059 (when (zerop ind) (throw 'zerop t))))
23060 (forward-line)))))
23061 ;; Loop over all lines and add fixed-width markup everywhere
23062 ;; but in fixed-width lines.
23063 (save-excursion
23064 (goto-char begin)
23065 (while (< (point) end)
23066 (cond
23067 ((org-at-heading-p)
23068 (insert ": ")
23069 (forward-line)
23070 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23071 (insert ":")
23072 (forward-line)))
23073 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23074 (let* ((element (org-element-at-point))
23075 (element-end (org-element-property :end element)))
23076 (if (eq (org-element-type element) 'fixed-width)
23077 (progn (goto-char element-end)
23078 (skip-chars-backward " \r\t\n")
23079 (forward-line))
23080 (let ((limit (min end element-end)))
23081 (while (< (point) limit)
23082 (org-move-to-column min-ind t)
23083 (insert ": ")
23084 (forward-line))))))
23086 (org-move-to-column min-ind t)
23087 (insert ": ")
23088 (forward-line)))))))
23089 (set-marker end nil))))
23092 ;;; Comments
23094 ;; Org comments syntax is quite complex. It requires the entire line
23095 ;; to be just a comment. Also, even with the right syntax at the
23096 ;; beginning of line, some some elements (i.e. verse-block or
23097 ;; example-block) don't accept comments. Usual Emacs comment commands
23098 ;; cannot cope with those requirements. Therefore, Org replaces them.
23100 ;; Org still relies on `comment-dwim', but cannot trust
23101 ;; `comment-only-p'. So, `comment-region-function' and
23102 ;; `uncomment-region-function' both point
23103 ;; to`org-comment-or-uncomment-region'. Eventually,
23104 ;; `org-insert-comment' takes care of insertion of comments at the
23105 ;; beginning of line.
23107 ;; `org-setup-comments-handling' install comments related variables
23108 ;; during `org-mode' initialization.
23110 (defun org-setup-comments-handling ()
23111 (interactive)
23112 (org-set-local 'comment-use-syntax nil)
23113 (org-set-local 'comment-start "# ")
23114 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23115 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23116 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23117 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23119 (defun org-insert-comment ()
23120 "Insert an empty comment above current line.
23121 If the line is empty, insert comment at its beginning. When
23122 point is within a source block, comment according to the related
23123 major mode."
23124 (if (let ((element (org-element-at-point)))
23125 (and (eq (org-element-type element) 'src-block)
23126 (< (save-excursion
23127 (goto-char (org-element-property :post-affiliated element))
23128 (line-end-position))
23129 (point))
23130 (> (save-excursion
23131 (goto-char (org-element-property :end element))
23132 (skip-chars-backward " \r\t\n")
23133 (line-beginning-position))
23134 (point))))
23135 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23136 (beginning-of-line)
23137 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23138 (open-line 1))
23139 (org-indent-line)
23140 (insert "# ")))
23142 (defvar comment-empty-lines) ; From newcomment.el.
23143 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23144 "Comment or uncomment each non-blank line in the region.
23145 Uncomment each non-blank line between BEG and END if it only
23146 contains commented lines. Otherwise, comment them. If region is
23147 strictly within a source block, use appropriate comment syntax."
23148 (if (let ((element (org-element-at-point)))
23149 (and (eq (org-element-type element) 'src-block)
23150 (< (save-excursion
23151 (goto-char (org-element-property :post-affiliated element))
23152 (line-end-position))
23153 beg)
23154 (>= (save-excursion
23155 (goto-char (org-element-property :end element))
23156 (skip-chars-backward " \r\t\n")
23157 (line-beginning-position))
23158 end)))
23159 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23160 (save-restriction
23161 ;; Restrict region
23162 (narrow-to-region (save-excursion (goto-char beg)
23163 (skip-chars-forward " \r\t\n" end)
23164 (line-beginning-position))
23165 (save-excursion (goto-char end)
23166 (skip-chars-backward " \r\t\n" beg)
23167 (line-end-position)))
23168 (let ((uncommentp
23169 ;; UNCOMMENTP is non-nil when every non blank line between
23170 ;; BEG and END is a comment.
23171 (save-excursion
23172 (goto-char (point-min))
23173 (while (and (not (eobp))
23174 (let ((element (org-element-at-point)))
23175 (and (eq (org-element-type element) 'comment)
23176 (goto-char (min (point-max)
23177 (org-element-property
23178 :end element)))))))
23179 (eobp))))
23180 (if uncommentp
23181 ;; Only blank lines and comments in region: uncomment it.
23182 (save-excursion
23183 (goto-char (point-min))
23184 (while (not (eobp))
23185 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23186 (replace-match "" nil nil nil 1))
23187 (forward-line)))
23188 ;; Comment each line in region.
23189 (let ((min-indent (point-max)))
23190 ;; First find the minimum indentation across all lines.
23191 (save-excursion
23192 (goto-char (point-min))
23193 (while (and (not (eobp)) (not (zerop min-indent)))
23194 (unless (looking-at "[ \t]*$")
23195 (setq min-indent (min min-indent (current-indentation))))
23196 (forward-line)))
23197 ;; Then loop over all lines.
23198 (save-excursion
23199 (goto-char (point-min))
23200 (while (not (eobp))
23201 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23202 ;; Don't get fooled by invisible text (e.g. link path)
23203 ;; when moving to column MIN-INDENT.
23204 (let ((buffer-invisibility-spec nil))
23205 (org-move-to-column min-indent t))
23206 (insert comment-start))
23207 (forward-line)))))))))
23209 (defun org-comment-dwim (arg)
23210 "Call `comment-dwim' within a source edit buffer if needed."
23211 (interactive "*P")
23212 (if (org-in-src-block-p)
23213 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23214 (call-interactively 'comment-dwim)))
23217 ;;; Planning
23219 ;; This section contains tools to operate on timestamp objects, as
23220 ;; returned by, e.g. `org-element-context'.
23222 (defun org-timestamp-has-time-p (timestamp)
23223 "Non-nil when TIMESTAMP has a time specified."
23224 (org-element-property :hour-start timestamp))
23226 (defun org-timestamp-format (timestamp format &optional end utc)
23227 "Format a TIMESTAMP element into a string.
23229 FORMAT is a format specifier to be passed to
23230 `format-time-string'.
23232 When optional argument END is non-nil, use end of date-range or
23233 time-range, if possible.
23235 When optional argument UTC is non-nil, time will be expressed as
23236 Universal Time."
23237 (format-time-string
23238 format
23239 (apply 'encode-time
23240 (cons 0
23241 (mapcar
23242 (lambda (prop) (or (org-element-property prop timestamp) 0))
23243 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23244 '(:minute-start :hour-start :day-start :month-start
23245 :year-start)))))
23246 utc))
23248 (defun org-timestamp-split-range (timestamp &optional end)
23249 "Extract a timestamp object from a date or time range.
23251 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23252 the end of the range. Otherwise, extract its start.
23254 Return a new timestamp object sharing the same parent as
23255 TIMESTAMP."
23256 (let ((type (org-element-property :type timestamp)))
23257 (if (memq type '(active inactive diary)) timestamp
23258 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23259 ;; Set new type.
23260 (org-element-put-property
23261 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23262 ;; Copy start properties over end properties if END is
23263 ;; non-nil. Otherwise, copy end properties over `start' ones.
23264 (let ((p-alist '((:minute-start . :minute-end)
23265 (:hour-start . :hour-end)
23266 (:day-start . :day-end)
23267 (:month-start . :month-end)
23268 (:year-start . :year-end))))
23269 (dolist (p-cell p-alist)
23270 (org-element-put-property
23271 split-ts
23272 (funcall (if end 'car 'cdr) p-cell)
23273 (org-element-property
23274 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23275 ;; Eventually refresh `:raw-value'.
23276 (org-element-put-property split-ts :raw-value nil)
23277 (org-element-put-property
23278 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23280 (defun org-timestamp-translate (timestamp &optional boundary)
23281 "Apply `org-translate-time' on a TIMESTAMP object.
23282 When optional argument BOUNDARY is non-nil, it is either the
23283 symbol `start' or `end'. In this case, only translate the
23284 starting or ending part of TIMESTAMP if it is a date or time
23285 range. Otherwise, translate both parts."
23286 (if (and (not boundary)
23287 (memq (org-element-property :type timestamp)
23288 '(active-range inactive-range)))
23289 (concat
23290 (org-translate-time
23291 (org-element-property :raw-value
23292 (org-timestamp-split-range timestamp)))
23293 "--"
23294 (org-translate-time
23295 (org-element-property :raw-value
23296 (org-timestamp-split-range timestamp t))))
23297 (org-translate-time
23298 (org-element-property
23299 :raw-value
23300 (if (not boundary) timestamp
23301 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23305 ;;; Other stuff.
23307 (defun org-reftex-citation ()
23308 "Use reftex-citation to insert a citation into the buffer.
23309 This looks for a line like
23311 #+BIBLIOGRAPHY: foo plain option:-d
23313 and derives from it that foo.bib is the bibliography file relevant
23314 for this document. It then installs the necessary environment for RefTeX
23315 to work in this buffer and calls `reftex-citation' to insert a citation
23316 into the buffer.
23318 Export of such citations to both LaTeX and HTML is handled by the contributed
23319 package ox-bibtex by Taru Karttunen."
23320 (interactive)
23321 (let ((reftex-docstruct-symbol 'rds)
23322 (reftex-cite-format "\\cite{%l}")
23323 rds bib)
23324 (save-excursion
23325 (save-restriction
23326 (widen)
23327 (let ((case-fold-search t)
23328 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23329 (if (not (save-excursion
23330 (or (re-search-forward re nil t)
23331 (re-search-backward re nil t))))
23332 (user-error "No bibliography defined in file")
23333 (setq bib (concat (match-string 1) ".bib")
23334 rds (list (list 'bib bib)))))))
23335 (call-interactively 'reftex-citation)))
23337 ;;;; Functions extending outline functionality
23339 (defun org-beginning-of-line (&optional arg)
23340 "Go to the beginning of the current line. If that is invisible, continue
23341 to a visible line beginning. This makes the function of C-a more intuitive.
23342 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23343 first attempt, and only move to after the tags when the cursor is already
23344 beyond the end of the headline."
23345 (interactive "P")
23346 (let ((pos (point))
23347 (special (if (consp org-special-ctrl-a/e)
23348 (car org-special-ctrl-a/e)
23349 org-special-ctrl-a/e))
23350 deactivate-mark refpos)
23351 (if (org-bound-and-true-p visual-line-mode)
23352 (beginning-of-visual-line 1)
23353 (beginning-of-line 1))
23354 (if (and arg (fboundp 'move-beginning-of-line))
23355 (call-interactively 'move-beginning-of-line)
23356 (if (bobp)
23358 (backward-char 1)
23359 (if (org-truely-invisible-p)
23360 (while (and (not (bobp)) (org-truely-invisible-p))
23361 (backward-char 1)
23362 (beginning-of-line 1))
23363 (forward-char 1))))
23364 (when special
23365 (cond
23366 ((and (looking-at org-complex-heading-regexp)
23367 (= (char-after (match-end 1)) ?\ ))
23368 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23369 (point-at-eol)))
23370 (goto-char
23371 (if (eq special t)
23372 (cond ((> pos refpos) refpos)
23373 ((= pos (point)) refpos)
23374 (t (point)))
23375 (cond ((> pos (point)) (point))
23376 ((not (eq last-command this-command)) (point))
23377 (t refpos)))))
23378 ((org-at-item-p)
23379 ;; Being at an item and not looking at an the item means point
23380 ;; was previously moved to beginning of a visual line, which
23381 ;; doesn't contain the item. Therefore, do nothing special,
23382 ;; just stay here.
23383 (when (looking-at org-list-full-item-re)
23384 ;; Set special position at first white space character after
23385 ;; bullet, and check-box, if any.
23386 (let ((after-bullet
23387 (let ((box (match-end 3)))
23388 (if (not box) (match-end 1)
23389 (let ((after (char-after box)))
23390 (if (and after (= after ? )) (1+ box) box))))))
23391 ;; Special case: Move point to special position when
23392 ;; currently after it or at beginning of line.
23393 (if (eq special t)
23394 (when (or (> pos after-bullet) (= (point) pos))
23395 (goto-char after-bullet))
23396 ;; Reversed case: Move point to special position when
23397 ;; point was already at beginning of line and command is
23398 ;; repeated.
23399 (when (and (= (point) pos) (eq last-command this-command))
23400 (goto-char after-bullet))))))))
23401 (org-no-warnings
23402 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23403 (setq disable-point-adjustment
23404 (or (not (invisible-p (point)))
23405 (not (invisible-p (max (point-min) (1- (point))))))))
23407 (defun org-end-of-line (&optional arg)
23408 "Go to the end of the line.
23409 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23410 tags on the first attempt, and only move to after the tags when
23411 the cursor is already beyond the end of the headline."
23412 (interactive "P")
23413 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23414 org-special-ctrl-a/e))
23415 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23416 'end-of-visual-line)
23417 ((fboundp 'move-end-of-line) 'move-end-of-line)
23418 (t 'end-of-line)))
23419 deactivate-mark)
23420 (if (or (not special) arg) (call-interactively move-fun)
23421 (let* ((element (save-excursion (beginning-of-line)
23422 (org-element-at-point)))
23423 (type (org-element-type element)))
23424 (cond
23425 ((memq type '(headline inlinetask))
23426 (let ((pos (point)))
23427 (beginning-of-line 1)
23428 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23429 (if (eq special t)
23430 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23431 (goto-char (match-beginning 1))
23432 (goto-char (match-end 0)))
23433 (if (or (< pos (match-end 0))
23434 (not (eq this-command last-command)))
23435 (goto-char (match-end 0))
23436 (goto-char (match-beginning 1))))
23437 (call-interactively move-fun))))
23438 ((outline-invisible-p (line-end-position))
23439 ;; If element is hidden, `move-end-of-line' would put point
23440 ;; after it. Use `end-of-line' to stay on current line.
23441 (call-interactively 'end-of-line))
23442 (t (call-interactively move-fun)))))
23443 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23444 (setq disable-point-adjustment
23445 (or (not (invisible-p (point)))
23446 (not (invisible-p (max (point-min) (1- (point))))))))
23448 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23449 (define-key org-mode-map "\C-e" 'org-end-of-line)
23451 (defun org-backward-sentence (&optional arg)
23452 "Go to beginning of sentence, or beginning of table field.
23453 This will call `backward-sentence' or `org-table-beginning-of-field',
23454 depending on context."
23455 (interactive "P")
23456 (cond
23457 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23458 (t (call-interactively 'backward-sentence))))
23460 (defun org-forward-sentence (&optional arg)
23461 "Go to end of sentence, or end of table field.
23462 This will call `forward-sentence' or `org-table-end-of-field',
23463 depending on context."
23464 (interactive "P")
23465 (cond
23466 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23467 (t (call-interactively 'forward-sentence))))
23469 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23470 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23472 (defun org-kill-line (&optional arg)
23473 "Kill line, to tags or end of line."
23474 (interactive "P")
23475 (cond
23476 ((or (not org-special-ctrl-k)
23477 (bolp)
23478 (not (org-at-heading-p)))
23479 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23480 org-ctrl-k-protect-subtree)
23481 (if (or (eq org-ctrl-k-protect-subtree 'error)
23482 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23483 (user-error "C-k aborted as it would kill a hidden subtree")))
23484 (call-interactively
23485 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23486 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23487 (kill-region (point) (match-beginning 1))
23488 (org-set-tags nil t))
23489 (t (kill-region (point) (point-at-eol)))))
23491 (define-key org-mode-map "\C-k" 'org-kill-line)
23493 (defun org-yank (&optional arg)
23494 "Yank. If the kill is a subtree, treat it specially.
23495 This command will look at the current kill and check if is a single
23496 subtree, or a series of subtrees[1]. If it passes the test, and if the
23497 cursor is at the beginning of a line or after the stars of a currently
23498 empty headline, then the yank is handled specially. How exactly depends
23499 on the value of the following variables, both set by default.
23501 `org-yank-folded-subtrees'
23502 When set, the subtree(s) will be folded after insertion, but only
23503 if doing so would now swallow text after the yanked text.
23505 `org-yank-adjusted-subtrees'
23506 When set, the subtree will be promoted or demoted in order to
23507 fit into the local outline tree structure, which means that the
23508 level will be adjusted so that it becomes the smaller one of the
23509 two *visible* surrounding headings.
23511 Any prefix to this command will cause `yank' to be called directly with
23512 no special treatment. In particular, a simple \\[universal-argument] prefix \
23513 will just
23514 plainly yank the text as it is.
23516 \[1] The test checks if the first non-white line is a heading
23517 and if there are no other headings with fewer stars."
23518 (interactive "P")
23519 (org-yank-generic 'yank arg))
23521 (defun org-yank-generic (command arg)
23522 "Perform some yank-like command.
23524 This function implements the behavior described in the `org-yank'
23525 documentation. However, it has been generalized to work for any
23526 interactive command with similar behavior."
23528 ;; pretend to be command COMMAND
23529 (setq this-command command)
23531 (if arg
23532 (call-interactively command)
23534 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23535 (and (org-kill-is-subtree-p)
23536 (or (bolp)
23537 (and (looking-at "[ \t]*$")
23538 (string-match
23539 "\\`\\*+\\'"
23540 (buffer-substring (point-at-bol) (point)))))))
23541 swallowp)
23542 (cond
23543 ((and subtreep org-yank-folded-subtrees)
23544 (let ((beg (point))
23545 end)
23546 (if (and subtreep org-yank-adjusted-subtrees)
23547 (org-paste-subtree nil nil 'for-yank)
23548 (call-interactively command))
23550 (setq end (point))
23551 (goto-char beg)
23552 (when (and (bolp) subtreep
23553 (not (setq swallowp
23554 (org-yank-folding-would-swallow-text beg end))))
23555 (org-with-limited-levels
23556 (or (looking-at org-outline-regexp)
23557 (re-search-forward org-outline-regexp-bol end t))
23558 (while (and (< (point) end) (looking-at org-outline-regexp))
23559 (hide-subtree)
23560 (org-cycle-show-empty-lines 'folded)
23561 (condition-case nil
23562 (outline-forward-same-level 1)
23563 (error (goto-char end))))))
23564 (when swallowp
23565 (message
23566 "Inserted text not folded because that would swallow text"))
23568 (goto-char end)
23569 (skip-chars-forward " \t\n\r")
23570 (beginning-of-line 1)
23571 (push-mark beg 'nomsg)))
23572 ((and subtreep org-yank-adjusted-subtrees)
23573 (let ((beg (point-at-bol)))
23574 (org-paste-subtree nil nil 'for-yank)
23575 (push-mark beg 'nomsg)))
23577 (call-interactively command))))))
23579 (defun org-yank-folding-would-swallow-text (beg end)
23580 "Would hide-subtree at BEG swallow any text after END?"
23581 (let (level)
23582 (org-with-limited-levels
23583 (save-excursion
23584 (goto-char beg)
23585 (when (or (looking-at org-outline-regexp)
23586 (re-search-forward org-outline-regexp-bol end t))
23587 (setq level (org-outline-level)))
23588 (goto-char end)
23589 (skip-chars-forward " \t\r\n\v\f")
23590 (if (or (eobp)
23591 (and (bolp) (looking-at org-outline-regexp)
23592 (<= (org-outline-level) level)))
23593 nil ; Nothing would be swallowed
23594 t))))) ; something would swallow
23596 (define-key org-mode-map "\C-y" 'org-yank)
23598 (defun org-truely-invisible-p ()
23599 "Check if point is at a character currently not visible.
23600 This version does not only check the character property, but also
23601 `visible-mode'."
23602 ;; Early versions of noutline don't have `outline-invisible-p'.
23603 (if (org-bound-and-true-p visible-mode)
23605 (outline-invisible-p)))
23607 (defun org-invisible-p2 ()
23608 "Check if point is at a character currently not visible."
23609 (save-excursion
23610 (if (and (eolp) (not (bobp))) (backward-char 1))
23611 ;; Early versions of noutline don't have `outline-invisible-p'.
23612 (outline-invisible-p)))
23614 (defun org-back-to-heading (&optional invisible-ok)
23615 "Call `outline-back-to-heading', but provide a better error message."
23616 (condition-case nil
23617 (outline-back-to-heading invisible-ok)
23618 (error (error "Before first headline at position %d in buffer %s"
23619 (point) (current-buffer)))))
23621 (defun org-before-first-heading-p ()
23622 "Before first heading?"
23623 (save-excursion
23624 (end-of-line)
23625 (null (re-search-backward org-outline-regexp-bol nil t))))
23627 (defun org-at-heading-p (&optional ignored)
23628 (outline-on-heading-p t))
23629 ;; Compatibility alias with Org versions < 7.8.03
23630 (defalias 'org-on-heading-p 'org-at-heading-p)
23632 (defun org-in-commented-heading-p (&optional no-inheritance)
23633 "Non-nil if point is under a commented heading.
23634 This function also checks ancestors of the current headline,
23635 unless optional argument NO-INHERITANCE is non-nil."
23636 (cond
23637 ((org-before-first-heading-p) nil)
23638 ((let ((headline (nth 4 (org-heading-components))))
23639 (and headline
23640 (let ((case-fold-search nil))
23641 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23642 headline)))))
23643 (no-inheritance nil)
23645 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23647 (defun org-at-comment-p nil
23648 "Is cursor in a commented line?"
23649 (save-excursion
23650 (save-match-data
23651 (beginning-of-line)
23652 (looking-at "^[ \t]*# "))))
23654 (defun org-at-drawer-p nil
23655 "Is cursor at a drawer keyword?"
23656 (save-excursion
23657 (move-beginning-of-line 1)
23658 (looking-at org-drawer-regexp)))
23660 (defun org-at-block-p nil
23661 "Is cursor at a block keyword?"
23662 (save-excursion
23663 (move-beginning-of-line 1)
23664 (looking-at org-block-regexp)))
23666 (defun org-point-at-end-of-empty-headline ()
23667 "If point is at the end of an empty headline, return t, else nil.
23668 If the heading only contains a TODO keyword, it is still still considered
23669 empty."
23670 (and (looking-at "[ \t]*$")
23671 (when org-todo-line-regexp
23672 (save-excursion
23673 (beginning-of-line 1)
23674 (let ((case-fold-search nil))
23675 (looking-at org-todo-line-regexp)
23676 (string= (match-string 3) ""))))))
23678 (defun org-at-heading-or-item-p ()
23679 (or (org-at-heading-p) (org-at-item-p)))
23681 (defun org-at-target-p ()
23682 (or (org-in-regexp org-radio-target-regexp)
23683 (org-in-regexp org-target-regexp)))
23684 ;; Compatibility alias with Org versions < 7.8.03
23685 (defalias 'org-on-target-p 'org-at-target-p)
23687 (defun org-up-heading-all (arg)
23688 "Move to the heading line of which the present line is a subheading.
23689 This function considers both visible and invisible heading lines.
23690 With argument, move up ARG levels."
23691 (if (fboundp 'outline-up-heading-all)
23692 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23693 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23695 (defun org-up-heading-safe ()
23696 "Move to the heading line of which the present line is a subheading.
23697 This version will not throw an error. It will return the level of the
23698 headline found, or nil if no higher level is found.
23700 Also, this function will be a lot faster than `outline-up-heading',
23701 because it relies on stars being the outline starters. This can really
23702 make a significant difference in outlines with very many siblings."
23703 (when (ignore-errors (org-back-to-heading t))
23704 (let ((level-up (1- (funcall outline-level))))
23705 (and (> level-up 0)
23706 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23707 (funcall outline-level)))))
23709 (defun org-first-sibling-p ()
23710 "Is this heading the first child of its parents?"
23711 (interactive)
23712 (let ((re org-outline-regexp-bol)
23713 level l)
23714 (unless (org-at-heading-p t)
23715 (user-error "Not at a heading"))
23716 (setq level (funcall outline-level))
23717 (save-excursion
23718 (if (not (re-search-backward re nil t))
23720 (setq l (funcall outline-level))
23721 (< l level)))))
23723 (defun org-goto-sibling (&optional previous)
23724 "Goto the next sibling, even if it is invisible.
23725 When PREVIOUS is set, go to the previous sibling instead. Returns t
23726 when a sibling was found. When none is found, return nil and don't
23727 move point."
23728 (let ((fun (if previous 're-search-backward 're-search-forward))
23729 (pos (point))
23730 (re org-outline-regexp-bol)
23731 level l)
23732 (when (ignore-errors (org-back-to-heading t))
23733 (setq level (funcall outline-level))
23734 (catch 'exit
23735 (or previous (forward-char 1))
23736 (while (funcall fun re nil t)
23737 (setq l (funcall outline-level))
23738 (when (< l level) (goto-char pos) (throw 'exit nil))
23739 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23740 (goto-char pos)
23741 nil))))
23743 (defun org-show-siblings ()
23744 "Show all siblings of the current headline."
23745 (save-excursion
23746 (while (org-goto-sibling) (org-flag-heading nil)))
23747 (save-excursion
23748 (while (org-goto-sibling 'previous)
23749 (org-flag-heading nil))))
23751 (defun org-goto-first-child ()
23752 "Goto the first child, even if it is invisible.
23753 Return t when a child was found. Otherwise don't move point and
23754 return nil."
23755 (let (level (pos (point)) (re org-outline-regexp-bol))
23756 (when (ignore-errors (org-back-to-heading t))
23757 (setq level (outline-level))
23758 (forward-char 1)
23759 (if (and (re-search-forward re nil t) (> (outline-level) level))
23760 (progn (goto-char (match-beginning 0)) t)
23761 (goto-char pos) nil))))
23763 (defun org-show-hidden-entry ()
23764 "Show an entry where even the heading is hidden."
23765 (save-excursion
23766 (org-show-entry)))
23768 (defun org-flag-heading (flag &optional entry)
23769 "Flag the current heading. FLAG non-nil means make invisible.
23770 When ENTRY is non-nil, show the entire entry."
23771 (save-excursion
23772 (org-back-to-heading t)
23773 ;; Check if we should show the entire entry
23774 (if entry
23775 (progn
23776 (org-show-entry)
23777 (save-excursion
23778 (and (outline-next-heading)
23779 (org-flag-heading nil))))
23780 (outline-flag-region (max (point-min) (1- (point)))
23781 (save-excursion (outline-end-of-heading) (point))
23782 flag))))
23784 (defun org-get-next-sibling ()
23785 "Move to next heading of the same level, and return point.
23786 If there is no such heading, return nil.
23787 This is like outline-next-sibling, but invisible headings are ok."
23788 (let ((level (funcall outline-level)))
23789 (outline-next-heading)
23790 (while (and (not (eobp)) (> (funcall outline-level) level))
23791 (outline-next-heading))
23792 (if (or (eobp) (< (funcall outline-level) level))
23794 (point))))
23796 (defun org-get-last-sibling ()
23797 "Move to previous heading of the same level, and return point.
23798 If there is no such heading, return nil."
23799 (let ((opoint (point))
23800 (level (funcall outline-level)))
23801 (outline-previous-heading)
23802 (when (and (/= (point) opoint) (outline-on-heading-p t))
23803 (while (and (> (funcall outline-level) level)
23804 (not (bobp)))
23805 (outline-previous-heading))
23806 (if (< (funcall outline-level) level)
23808 (point)))))
23810 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23811 "Goto to the end of a subtree."
23812 ;; This contains an exact copy of the original function, but it uses
23813 ;; `org-back-to-heading', to make it work also in invisible
23814 ;; trees. And is uses an invisible-ok argument.
23815 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23816 ;; Furthermore, when used inside Org, finding the end of a large subtree
23817 ;; with many children and grandchildren etc, this can be much faster
23818 ;; than the outline version.
23819 (org-back-to-heading invisible-ok)
23820 (let ((first t)
23821 (level (funcall outline-level)))
23822 (if (and (derived-mode-p 'org-mode) (< level 1000))
23823 ;; A true heading (not a plain list item), in Org-mode
23824 ;; This means we can easily find the end by looking
23825 ;; only for the right number of stars. Using a regexp to do
23826 ;; this is so much faster than using a Lisp loop.
23827 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23828 (forward-char 1)
23829 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23830 ;; something else, do it the slow way
23831 (while (and (not (eobp))
23832 (or first (> (funcall outline-level) level)))
23833 (setq first nil)
23834 (outline-next-heading)))
23835 (unless to-heading
23836 (if (memq (preceding-char) '(?\n ?\^M))
23837 (progn
23838 ;; Go to end of line before heading
23839 (forward-char -1)
23840 (if (memq (preceding-char) '(?\n ?\^M))
23841 ;; leave blank line before heading
23842 (forward-char -1))))))
23843 (point))
23845 (defun org-end-of-meta-data-and-drawers ()
23846 "Jump to the first text after meta data and drawers in the current entry.
23847 This will move over empty lines, lines with planning time stamps,
23848 clocking lines, and drawers."
23849 (org-back-to-heading t)
23850 (let ((end (save-excursion (outline-next-heading) (point)))
23851 (re (concat "\\(" org-drawer-regexp "\\)"
23852 "\\|" "[ \t]*" org-keyword-time-regexp)))
23853 (forward-line 1)
23854 (while (re-search-forward re end t)
23855 (if (not (match-end 1))
23856 ;; empty or planning line
23857 (forward-line 1)
23858 ;; a drawer, find the end
23859 (re-search-forward "^[ \t]*:END:" end 'move)
23860 (forward-line 1)))
23861 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23862 (point)))
23864 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23865 "Move forward to the ARG'th subheading at same level as this one.
23866 Stop at the first and last subheadings of a superior heading.
23867 Normally this only looks at visible headings, but when INVISIBLE-OK is
23868 non-nil it will also look at invisible ones."
23869 (interactive "p")
23870 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23871 (if (and arg (< arg 0))
23872 (goto-char (point-min))
23873 (outline-next-heading))
23874 (org-at-heading-p)
23875 (let ((level (- (match-end 0) (match-beginning 0) 1))
23876 (f (if (and arg (< arg 0))
23877 're-search-backward
23878 're-search-forward))
23879 (count (if arg (abs arg) 1))
23880 (result (point)))
23881 (while (and (prog1 (> count 0)
23882 (forward-char (if (and arg (< arg 0)) -1 1)))
23883 (funcall f org-outline-regexp-bol nil 'move))
23884 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23885 (cond ((< l level) (setq count 0))
23886 ((and (= l level)
23887 (or invisible-ok
23888 (progn
23889 (goto-char (line-beginning-position))
23890 (not (outline-invisible-p)))))
23891 (setq count (1- count))
23892 (when (eq l level)
23893 (setq result (point)))))))
23894 (goto-char result))
23895 (beginning-of-line 1)))
23897 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23898 "Move backward to the ARG'th subheading at same level as this one.
23899 Stop at the first and last subheadings of a superior heading."
23900 (interactive "p")
23901 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23903 (defun org-next-block (arg &optional backward block-regexp)
23904 "Jump to the next block.
23905 With a prefix argument ARG, jump forward ARG many source blocks.
23906 When BACKWARD is non-nil, jump to the previous block.
23907 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23908 (interactive "p")
23909 (let ((re (or block-regexp org-block-regexp))
23910 (re-search-fn (or (and backward 're-search-backward)
23911 're-search-forward)))
23912 (if (looking-at re) (forward-char 1))
23913 (condition-case nil
23914 (funcall re-search-fn re nil nil arg)
23915 (error (user-error "No %s code blocks"
23916 (if backward "previous" "further" ))))
23917 (goto-char (match-beginning 0)) (org-show-context)))
23919 (defun org-previous-block (arg &optional block-regexp)
23920 "Jump to the previous block.
23921 With a prefix argument ARG, jump backward ARG many source blocks.
23922 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23923 (interactive "p")
23924 (org-next-block arg t block-regexp))
23926 (defun org-forward-paragraph ()
23927 "Move forward to beginning of next paragraph or equivalent.
23929 The function moves point to the beginning of the next visible
23930 structural element, which can be a paragraph, a table, a list
23931 item, etc. It also provides some special moves for convenience:
23933 - On an affiliated keyword, jump to the beginning of the
23934 relative element.
23935 - On an item or a footnote definition, move to the second
23936 element inside, if any.
23937 - On a table or a property drawer, jump after it.
23938 - On a verse or source block, stop after blank lines."
23939 (interactive)
23940 (when (eobp) (user-error "Cannot move further down"))
23941 (let* ((deactivate-mark nil)
23942 (element (org-element-at-point))
23943 (type (org-element-type element))
23944 (post-affiliated (org-element-property :post-affiliated element))
23945 (contents-begin (org-element-property :contents-begin element))
23946 (contents-end (org-element-property :contents-end element))
23947 (end (let ((end (org-element-property :end element)) (parent element))
23948 (while (and (setq parent (org-element-property :parent parent))
23949 (= (org-element-property :contents-end parent) end))
23950 (setq end (org-element-property :end parent)))
23951 end)))
23952 (cond ((not element)
23953 (skip-chars-forward " \r\t\n")
23954 (or (eobp) (beginning-of-line)))
23955 ;; On affiliated keywords, move to element's beginning.
23956 ((< (point) post-affiliated)
23957 (goto-char post-affiliated))
23958 ;; At a table row, move to the end of the table. Similarly,
23959 ;; at a node property, move to the end of the property
23960 ;; drawer.
23961 ((memq type '(node-property table-row))
23962 (goto-char (org-element-property
23963 :end (org-element-property :parent element))))
23964 ((memq type '(property-drawer table)) (goto-char end))
23965 ;; Consider blank lines as separators in verse and source
23966 ;; blocks to ease editing.
23967 ((memq type '(src-block verse-block))
23968 (when (eq type 'src-block)
23969 (setq contents-end
23970 (save-excursion (goto-char end)
23971 (skip-chars-backward " \r\t\n")
23972 (line-beginning-position))))
23973 (beginning-of-line)
23974 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23975 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23976 (goto-char end)
23977 (skip-chars-forward " \r\t\n")
23978 (if (= (point) contents-end) (goto-char end)
23979 (beginning-of-line))))
23980 ;; With no contents, just skip element.
23981 ((not contents-begin) (goto-char end))
23982 ;; If contents are invisible, skip the element altogether.
23983 ((outline-invisible-p (line-end-position))
23984 (case type
23985 (headline
23986 (org-with-limited-levels (outline-next-visible-heading 1)))
23987 ;; At a plain list, make sure we move to the next item
23988 ;; instead of skipping the whole list.
23989 (plain-list (forward-char)
23990 (org-forward-paragraph))
23991 (otherwise (goto-char end))))
23992 ((>= (point) contents-end) (goto-char end))
23993 ((>= (point) contents-begin)
23994 ;; This can only happen on paragraphs and plain lists.
23995 (case type
23996 (paragraph (goto-char end))
23997 ;; At a plain list, try to move to second element in
23998 ;; first item, if possible.
23999 (plain-list (end-of-line)
24000 (org-forward-paragraph))))
24001 ;; When contents start on the middle of a line (e.g. in
24002 ;; items and footnote definitions), try to reach first
24003 ;; element starting after current line.
24004 ((> (line-end-position) contents-begin)
24005 (end-of-line)
24006 (org-forward-paragraph))
24007 (t (goto-char contents-begin)))))
24009 (defun org-backward-paragraph ()
24010 "Move backward to start of previous paragraph or equivalent.
24012 The function moves point to the beginning of the current
24013 structural element, which can be a paragraph, a table, a list
24014 item, etc., or to the beginning of the previous visible one if
24015 point is already there. It also provides some special moves for
24016 convenience:
24018 - On an affiliated keyword, jump to the first one.
24019 - On a table or a property drawer, move to its beginning.
24020 - On a verse or source block, stop before blank lines."
24021 (interactive)
24022 (when (bobp) (user-error "Cannot move further up"))
24023 (let* ((deactivate-mark nil)
24024 (element (org-element-at-point))
24025 (type (org-element-type element))
24026 (contents-begin (org-element-property :contents-begin element))
24027 (contents-end (org-element-property :contents-end element))
24028 (post-affiliated (org-element-property :post-affiliated element))
24029 (begin (org-element-property :begin element)))
24030 (cond
24031 ((not element) (goto-char (point-min)))
24032 ((= (point) begin)
24033 (backward-char)
24034 (org-backward-paragraph))
24035 ((<= (point) post-affiliated) (goto-char begin))
24036 ((memq type '(node-property table-row))
24037 (goto-char (org-element-property
24038 :post-affiliated (org-element-property :parent element))))
24039 ((memq type '(property-drawer table)) (goto-char begin))
24040 ((memq type '(src-block verse-block))
24041 (when (eq type 'src-block)
24042 (setq contents-begin
24043 (save-excursion (goto-char begin) (forward-line) (point))))
24044 (if (= (point) contents-begin) (goto-char post-affiliated)
24045 ;; Inside a verse block, see blank lines as paragraph
24046 ;; separators.
24047 (let ((origin (point)))
24048 (skip-chars-backward " \r\t\n" contents-begin)
24049 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24050 (skip-chars-forward " \r\t\n" origin)
24051 (if (= (point) origin) (goto-char contents-begin)
24052 (beginning-of-line))))))
24053 ((not contents-begin) (goto-char (or post-affiliated begin)))
24054 ((eq type 'paragraph)
24055 (goto-char contents-begin)
24056 ;; When at first paragraph in an item or a footnote definition,
24057 ;; move directly to beginning of line.
24058 (let ((parent-contents
24059 (org-element-property
24060 :contents-begin (org-element-property :parent element))))
24061 (when (and parent-contents (= parent-contents contents-begin))
24062 (beginning-of-line))))
24063 ;; At the end of a greater element, move to the beginning of the
24064 ;; last element within.
24065 ((>= (point) contents-end)
24066 (goto-char (1- contents-end))
24067 (org-backward-paragraph))
24068 (t (goto-char (or post-affiliated begin))))
24069 ;; Ensure we never leave point invisible.
24070 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24072 (defun org-forward-element ()
24073 "Move forward by one element.
24074 Move to the next element at the same level, when possible."
24075 (interactive)
24076 (cond ((eobp) (user-error "Cannot move further down"))
24077 ((org-with-limited-levels (org-at-heading-p))
24078 (let ((origin (point)))
24079 (goto-char (org-end-of-subtree nil t))
24080 (unless (org-with-limited-levels (org-at-heading-p))
24081 (goto-char origin)
24082 (user-error "Cannot move further down"))))
24084 (let* ((elem (org-element-at-point))
24085 (end (org-element-property :end elem))
24086 (parent (org-element-property :parent elem)))
24087 (cond ((and parent (= (org-element-property :contents-end parent) end))
24088 (goto-char (org-element-property :end parent)))
24089 ((integer-or-marker-p end) (goto-char end))
24090 (t (message "No element at point")))))))
24092 (defun org-backward-element ()
24093 "Move backward by one element.
24094 Move to the previous element at the same level, when possible."
24095 (interactive)
24096 (cond ((bobp) (user-error "Cannot move further up"))
24097 ((org-with-limited-levels (org-at-heading-p))
24098 ;; At a headline, move to the previous one, if any, or stay
24099 ;; here.
24100 (let ((origin (point)))
24101 (org-with-limited-levels (org-backward-heading-same-level 1))
24102 ;; When current headline has no sibling above, move to its
24103 ;; parent.
24104 (when (= (point) origin)
24105 (or (org-with-limited-levels (org-up-heading-safe))
24106 (progn (goto-char origin)
24107 (user-error "Cannot move further up"))))))
24109 (let* ((elem (org-element-at-point))
24110 (beg (org-element-property :begin elem)))
24111 (cond
24112 ;; Move to beginning of current element if point isn't
24113 ;; there already.
24114 ((null beg) (message "No element at point"))
24115 ((/= (point) beg) (goto-char beg))
24116 (t (goto-char beg)
24117 (skip-chars-backward " \r\t\n")
24118 (unless (bobp)
24119 (let ((prev (org-element-at-point)))
24120 (goto-char (org-element-property :begin prev))
24121 (while (and (setq prev (org-element-property :parent prev))
24122 (<= (org-element-property :end prev) beg))
24123 (goto-char (org-element-property :begin prev)))))))))))
24125 (defun org-up-element ()
24126 "Move to upper element."
24127 (interactive)
24128 (if (org-with-limited-levels (org-at-heading-p))
24129 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24130 (let* ((elem (org-element-at-point))
24131 (parent (org-element-property :parent elem)))
24132 (if parent (goto-char (org-element-property :begin parent))
24133 (if (org-with-limited-levels (org-before-first-heading-p))
24134 (user-error "No surrounding element")
24135 (org-with-limited-levels (org-back-to-heading)))))))
24137 (defvar org-element-greater-elements)
24138 (defun org-down-element ()
24139 "Move to inner element."
24140 (interactive)
24141 (let ((element (org-element-at-point)))
24142 (cond
24143 ((memq (org-element-type element) '(plain-list table))
24144 (goto-char (org-element-property :contents-begin element))
24145 (forward-char))
24146 ((memq (org-element-type element) org-element-greater-elements)
24147 ;; If contents are hidden, first disclose them.
24148 (when (outline-invisible-p (line-end-position)) (org-cycle))
24149 (goto-char (or (org-element-property :contents-begin element)
24150 (user-error "No content for this element"))))
24151 (t (user-error "No inner element")))))
24153 (defun org-drag-element-backward ()
24154 "Move backward element at point."
24155 (interactive)
24156 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24157 (let* ((elem (org-element-at-point))
24158 (prev-elem
24159 (save-excursion
24160 (goto-char (org-element-property :begin elem))
24161 (skip-chars-backward " \r\t\n")
24162 (unless (bobp)
24163 (let* ((beg (org-element-property :begin elem))
24164 (prev (org-element-at-point))
24165 (up prev))
24166 (while (and (setq up (org-element-property :parent up))
24167 (<= (org-element-property :end up) beg))
24168 (setq prev up))
24169 prev)))))
24170 ;; Error out if no previous element or previous element is
24171 ;; a parent of the current one.
24172 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24173 (user-error "Cannot drag element backward")
24174 (let ((pos (point)))
24175 (org-element-swap-A-B prev-elem elem)
24176 (goto-char (+ (org-element-property :begin prev-elem)
24177 (- pos (org-element-property :begin elem)))))))))
24179 (defun org-drag-element-forward ()
24180 "Move forward element at point."
24181 (interactive)
24182 (let* ((pos (point))
24183 (elem (org-element-at-point)))
24184 (when (= (point-max) (org-element-property :end elem))
24185 (user-error "Cannot drag element forward"))
24186 (goto-char (org-element-property :end elem))
24187 (let ((next-elem (org-element-at-point)))
24188 (when (or (org-element-nested-p elem next-elem)
24189 (and (eq (org-element-type next-elem) 'headline)
24190 (not (eq (org-element-type elem) 'headline))))
24191 (goto-char pos)
24192 (user-error "Cannot drag element forward"))
24193 ;; Compute new position of point: it's shifted by NEXT-ELEM
24194 ;; body's length (without final blanks) and by the length of
24195 ;; blanks between ELEM and NEXT-ELEM.
24196 (let ((size-next (- (save-excursion
24197 (goto-char (org-element-property :end next-elem))
24198 (skip-chars-backward " \r\t\n")
24199 (forward-line)
24200 ;; Small correction if buffer doesn't end
24201 ;; with a newline character.
24202 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24203 (org-element-property :begin next-elem)))
24204 (size-blank (- (org-element-property :end elem)
24205 (save-excursion
24206 (goto-char (org-element-property :end elem))
24207 (skip-chars-backward " \r\t\n")
24208 (forward-line)
24209 (point)))))
24210 (org-element-swap-A-B elem next-elem)
24211 (goto-char (+ pos size-next size-blank))))))
24213 (defun org-drag-line-forward (arg)
24214 "Drag the line at point ARG lines forward."
24215 (interactive "p")
24216 (dotimes (n (abs arg))
24217 (let ((c (current-column)))
24218 (if (< 0 arg)
24219 (progn
24220 (beginning-of-line 2)
24221 (transpose-lines 1)
24222 (beginning-of-line 0))
24223 (transpose-lines 1)
24224 (beginning-of-line -1))
24225 (org-move-to-column c))))
24227 (defun org-drag-line-backward (arg)
24228 "Drag the line at point ARG lines backward."
24229 (interactive "p")
24230 (org-drag-line-forward (- arg)))
24232 (defun org-mark-element ()
24233 "Put point at beginning of this element, mark at end.
24235 Interactively, if this command is repeated or (in Transient Mark
24236 mode) if the mark is active, it marks the next element after the
24237 ones already marked."
24238 (interactive)
24239 (let (deactivate-mark)
24240 (if (and (org-called-interactively-p 'any)
24241 (or (and (eq last-command this-command) (mark t))
24242 (and transient-mark-mode mark-active)))
24243 (set-mark
24244 (save-excursion
24245 (goto-char (mark))
24246 (goto-char (org-element-property :end (org-element-at-point)))))
24247 (let ((element (org-element-at-point)))
24248 (end-of-line)
24249 (push-mark (org-element-property :end element) t t)
24250 (goto-char (org-element-property :begin element))))))
24252 (defun org-narrow-to-element ()
24253 "Narrow buffer to current element."
24254 (interactive)
24255 (let ((elem (org-element-at-point)))
24256 (cond
24257 ((eq (car elem) 'headline)
24258 (narrow-to-region
24259 (org-element-property :begin elem)
24260 (org-element-property :end elem)))
24261 ((memq (car elem) org-element-greater-elements)
24262 (narrow-to-region
24263 (org-element-property :contents-begin elem)
24264 (org-element-property :contents-end elem)))
24266 (narrow-to-region
24267 (org-element-property :begin elem)
24268 (org-element-property :end elem))))))
24270 (defun org-transpose-element ()
24271 "Transpose current and previous elements, keeping blank lines between.
24272 Point is moved after both elements."
24273 (interactive)
24274 (org-skip-whitespace)
24275 (let ((end (org-element-property :end (org-element-at-point))))
24276 (org-drag-element-backward)
24277 (goto-char end)))
24279 (defun org-unindent-buffer ()
24280 "Un-indent the visible part of the buffer.
24281 Relative indentation (between items, inside blocks, etc.) isn't
24282 modified."
24283 (interactive)
24284 (unless (eq major-mode 'org-mode)
24285 (user-error "Cannot un-indent a buffer not in Org mode"))
24286 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24287 unindent-tree ; For byte-compiler.
24288 (unindent-tree
24289 (function
24290 (lambda (contents)
24291 (mapc
24292 (lambda (element)
24293 (if (memq (org-element-type element) '(headline section))
24294 (funcall unindent-tree (org-element-contents element))
24295 (save-excursion
24296 (save-restriction
24297 (narrow-to-region
24298 (org-element-property :begin element)
24299 (org-element-property :end element))
24300 (org-do-remove-indentation)))))
24301 (reverse contents))))))
24302 (funcall unindent-tree (org-element-contents parse-tree))))
24304 (defun org-show-subtree ()
24305 "Show everything after this heading at deeper levels."
24306 (interactive)
24307 (outline-flag-region
24308 (point)
24309 (save-excursion
24310 (org-end-of-subtree t t))
24311 nil))
24313 (defun org-show-entry ()
24314 "Show the body directly following this heading.
24315 Show the heading too, if it is currently invisible."
24316 (interactive)
24317 (save-excursion
24318 (ignore-errors
24319 (org-back-to-heading t)
24320 (outline-flag-region
24321 (max (point-min) (1- (point)))
24322 (save-excursion
24323 (if (re-search-forward
24324 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24325 (match-beginning 1)
24326 (point-max)))
24327 nil)
24328 (org-cycle-hide-drawers 'children))))
24330 (defun org-make-options-regexp (kwds &optional extra)
24331 "Make a regular expression for keyword lines."
24332 (concat
24333 "^[ \t]*#\\+\\("
24334 (mapconcat 'regexp-quote kwds "\\|")
24335 (if extra (concat "\\|" extra))
24336 "\\):[ \t]*\\(.*\\)"))
24338 ;; Make isearch reveal the necessary context
24339 (defun org-isearch-end ()
24340 "Reveal context after isearch exits."
24341 (when isearch-success ; only if search was successful
24342 (if (featurep 'xemacs)
24343 ;; Under XEmacs, the hook is run in the correct place,
24344 ;; we directly show the context.
24345 (org-show-context 'isearch)
24346 ;; In Emacs the hook runs *before* restoring the overlays.
24347 ;; So we have to use a one-time post-command-hook to do this.
24348 ;; (Emacs 22 has a special variable, see function `org-mode')
24349 (unless (and (boundp 'isearch-mode-end-hook-quit)
24350 isearch-mode-end-hook-quit)
24351 ;; Only when the isearch was not quitted.
24352 (org-add-hook 'post-command-hook 'org-isearch-post-command
24353 'append 'local)))))
24355 (defun org-isearch-post-command ()
24356 "Remove self from hook, and show context."
24357 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24358 (org-show-context 'isearch))
24361 ;;;; Integration with and fixes for other packages
24363 ;;; Imenu support
24365 (defvar org-imenu-markers nil
24366 "All markers currently used by Imenu.")
24367 (make-variable-buffer-local 'org-imenu-markers)
24369 (defun org-imenu-new-marker (&optional pos)
24370 "Return a new marker for use by Imenu, and remember the marker."
24371 (let ((m (make-marker)))
24372 (move-marker m (or pos (point)))
24373 (push m org-imenu-markers)
24376 (defun org-imenu-get-tree ()
24377 "Produce the index for Imenu."
24378 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24379 (setq org-imenu-markers nil)
24380 (let* ((n org-imenu-depth)
24381 (re (concat "^" (org-get-limited-outline-regexp)))
24382 (subs (make-vector (1+ n) nil))
24383 (last-level 0)
24384 m level head0 head)
24385 (save-excursion
24386 (save-restriction
24387 (widen)
24388 (goto-char (point-max))
24389 (while (re-search-backward re nil t)
24390 (setq level (org-reduced-level (funcall outline-level)))
24391 (when (and (<= level n)
24392 (looking-at org-complex-heading-regexp)
24393 (setq head0 (org-match-string-no-properties 4)))
24394 (setq head (org-link-display-format head0)
24395 m (org-imenu-new-marker))
24396 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24397 (if (>= level last-level)
24398 (push (cons head m) (aref subs level))
24399 (push (cons head (aref subs (1+ level))) (aref subs level))
24400 (loop for i from (1+ level) to n do (aset subs i nil)))
24401 (setq last-level level)))))
24402 (aref subs 1)))
24404 (eval-after-load "imenu"
24405 '(progn
24406 (add-hook 'imenu-after-jump-hook
24407 (lambda ()
24408 (if (derived-mode-p 'org-mode)
24409 (org-show-context 'org-goto))))))
24411 (defun org-link-display-format (link)
24412 "Replace a link with its the description.
24413 If there is no description, use the link target."
24414 (save-match-data
24415 (if (string-match org-bracket-link-analytic-regexp link)
24416 (replace-match (if (match-end 5)
24417 (match-string 5 link)
24418 (concat (match-string 1 link)
24419 (match-string 3 link)))
24420 nil t link)
24421 link)))
24423 (defun org-toggle-link-display ()
24424 "Toggle the literal or descriptive display of links."
24425 (interactive)
24426 (if org-descriptive-links
24427 (progn (org-remove-from-invisibility-spec '(org-link))
24428 (org-restart-font-lock)
24429 (setq org-descriptive-links nil))
24430 (progn (add-to-invisibility-spec '(org-link))
24431 (org-restart-font-lock)
24432 (setq org-descriptive-links t))))
24434 ;; Speedbar support
24436 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24437 "Overlay marking the agenda restriction line in speedbar.")
24438 (overlay-put org-speedbar-restriction-lock-overlay
24439 'face 'org-agenda-restriction-lock)
24440 (overlay-put org-speedbar-restriction-lock-overlay
24441 'help-echo "Agendas are currently limited to this item.")
24442 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24444 (defun org-speedbar-set-agenda-restriction ()
24445 "Restrict future agenda commands to the location at point in speedbar.
24446 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24447 (interactive)
24448 (require 'org-agenda)
24449 (let (p m tp np dir txt)
24450 (cond
24451 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24452 'org-imenu t))
24453 (setq m (get-text-property p 'org-imenu-marker))
24454 (with-current-buffer (marker-buffer m)
24455 (goto-char m)
24456 (org-agenda-set-restriction-lock 'subtree)))
24457 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24458 'speedbar-function 'speedbar-find-file))
24459 (setq tp (previous-single-property-change
24460 (1+ p) 'speedbar-function)
24461 np (next-single-property-change
24462 tp 'speedbar-function)
24463 dir (speedbar-line-directory)
24464 txt (buffer-substring-no-properties (or tp (point-min))
24465 (or np (point-max))))
24466 (with-current-buffer (find-file-noselect
24467 (let ((default-directory dir))
24468 (expand-file-name txt)))
24469 (unless (derived-mode-p 'org-mode)
24470 (user-error "Cannot restrict to non-Org-mode file"))
24471 (org-agenda-set-restriction-lock 'file)))
24472 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24473 (move-overlay org-speedbar-restriction-lock-overlay
24474 (point-at-bol) (point-at-eol))
24475 (setq current-prefix-arg nil)
24476 (org-agenda-maybe-redo)))
24478 (defvar speedbar-file-key-map)
24479 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24480 (eval-after-load "speedbar"
24481 '(progn
24482 (speedbar-add-supported-extension ".org")
24483 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24484 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24485 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24486 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24487 (add-hook 'speedbar-visiting-tag-hook
24488 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24490 ;;; Fixes and Hacks for problems with other packages
24492 (defun org-mode-flyspell-verify ()
24493 "Function used for `flyspell-generic-check-word-predicate'."
24494 (if (org-at-heading-p)
24495 ;; At a headline or an inlinetask, check title only. This is
24496 ;; faster than relying on `org-element-at-point'.
24497 (and (save-excursion (beginning-of-line)
24498 (and (let ((case-fold-search t))
24499 (not (looking-at "\\*+ END[ \t]*$")))
24500 (looking-at org-complex-heading-regexp)))
24501 (match-beginning 4)
24502 (>= (point) (match-beginning 4))
24503 (or (not (match-beginning 5))
24504 (< (point) (match-beginning 5))))
24505 (let* ((element (org-element-at-point))
24506 (post-affiliated (org-element-property :post-affiliated element))
24507 (object-check
24508 (function
24509 ;; Non-nil if checks can be done for object at point.
24510 (lambda ()
24511 (let ((object (save-excursion
24512 (when (org-looking-at-p "\\>") (backward-char))
24513 (org-element-context element))))
24514 (case (org-element-type object)
24515 ;; Prevent checks in links due to keybinding conflict
24516 ;; with Flyspell.
24517 ((code entity export-snippet inline-babel-call
24518 inline-src-block line-break latex-fragment link macro
24519 statistics-cookie target timestamp verbatim)
24520 nil)
24521 (footnote-reference
24522 ;; Only in inline footnotes, within the definition.
24523 (and (eq (org-element-property :type object) 'inline)
24524 (< (save-excursion
24525 (goto-char (org-element-property :begin object))
24526 (search-forward ":" nil t 2))
24527 (point))))
24528 (otherwise t)))))))
24529 (cond
24530 ;; Ignore checks in all affiliated keywords but captions.
24531 ((< (point) post-affiliated)
24532 (and (save-excursion
24533 (beginning-of-line)
24534 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24535 (> (point) (match-end 0))
24536 (funcall object-check)))
24537 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24538 ((and org-log-into-drawer
24539 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24540 (parent element))
24541 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24542 (setq parent (org-element-property :parent parent)))
24543 (and parent
24544 (eq (compare-strings
24545 log nil nil
24546 (org-element-property :drawer-name parent) nil nil t)
24547 t))))
24548 nil)
24550 (case (org-element-type element)
24551 ((comment quote-section) t)
24552 (comment-block
24553 ;; Allow checks between block markers, not on them.
24554 (and (> (line-beginning-position) post-affiliated)
24555 (save-excursion
24556 (end-of-line)
24557 (skip-chars-forward " \r\t\n")
24558 (< (point) (org-element-property :end element)))))
24559 ;; Arbitrary list of keywords where checks are meaningful.
24560 ;; Make sure point is on the value part of the element.
24561 (keyword
24562 (and (member (org-element-property :key element)
24563 '("DESCRIPTION" "TITLE"))
24564 (< (save-excursion
24565 (beginning-of-line) (search-forward ":") (point))
24566 (point))))
24567 ;; Check is globally allowed in paragraphs verse blocks and
24568 ;; table rows (after affiliated keywords) but some objects
24569 ;; must not be affected.
24570 ((paragraph table-row verse-block)
24571 (and (>= (point) (org-element-property :contents-begin element))
24572 (< (point) (org-element-property :contents-end element))
24573 (funcall object-check)))))))))
24574 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24576 (defun org-remove-flyspell-overlays-in (beg end)
24577 "Remove flyspell overlays in region."
24578 (and (org-bound-and-true-p flyspell-mode)
24579 (fboundp 'flyspell-delete-region-overlays)
24580 (flyspell-delete-region-overlays beg end)))
24582 (defvar flyspell-delayed-commands)
24583 (eval-after-load "flyspell"
24584 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24586 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24587 (eval-after-load "bookmark"
24588 '(if (boundp 'bookmark-after-jump-hook)
24589 ;; We can use the hook
24590 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24591 ;; Hook not available, use advice
24592 (defadvice bookmark-jump (after org-make-visible activate)
24593 "Make the position visible."
24594 (org-bookmark-jump-unhide))))
24596 ;; Make sure saveplace shows the location if it was hidden
24597 (eval-after-load "saveplace"
24598 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24599 "Make the position visible."
24600 (org-bookmark-jump-unhide)))
24602 ;; Make sure ecb shows the location if it was hidden
24603 (eval-after-load "ecb"
24604 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24605 "Make hierarchy visible when jumping into location from ECB tree buffer."
24606 (if (derived-mode-p 'org-mode)
24607 (org-show-context))))
24609 (defun org-bookmark-jump-unhide ()
24610 "Unhide the current position, to show the bookmark location."
24611 (and (derived-mode-p 'org-mode)
24612 (or (outline-invisible-p)
24613 (save-excursion (goto-char (max (point-min) (1- (point))))
24614 (outline-invisible-p)))
24615 (org-show-context 'bookmark-jump)))
24617 (defun org-mark-jump-unhide ()
24618 "Make the point visible with `org-show-context' after jumping to the mark."
24619 (when (and (derived-mode-p 'org-mode)
24620 (outline-invisible-p))
24621 (org-show-context 'mark-goto)))
24623 (eval-after-load "simple"
24624 '(defadvice pop-to-mark-command (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 exchange-point-and-mark (after org-make-visible activate)
24630 "Make the point visible with `org-show-context'."
24631 (org-mark-jump-unhide)))
24633 (eval-after-load "simple"
24634 '(defadvice pop-global-mark (after org-make-visible activate)
24635 "Make the point visible with `org-show-context'."
24636 (org-mark-jump-unhide)))
24638 ;; Make session.el ignore our circular variable
24639 (defvar session-globals-exclude)
24640 (eval-after-load "session"
24641 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24643 ;;;; Finish up
24645 (provide 'org)
24647 (run-hooks 'org-load-hook)
24649 ;;; org.el ends here